@camstack/core 0.1.38 → 0.1.40
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/auth/auth-manager.d.ts +12 -1
- package/dist/auth/auth-manager.d.ts.map +1 -1
- package/dist/auth/scope-matcher.d.ts +8 -0
- package/dist/auth/scope-matcher.d.ts.map +1 -0
- package/dist/auth/totp-manager.d.ts +0 -1
- package/dist/auth/totp-manager.d.ts.map +1 -1
- package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.d.ts +15 -0
- package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.d.ts.map +1 -1
- package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +27 -6
- package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js.map +1 -1
- package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +27 -6
- package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs.map +1 -1
- package/dist/builtins/device-manager/device-config-contribution.d.ts +33 -0
- package/dist/builtins/device-manager/device-config-contribution.d.ts.map +1 -0
- package/dist/builtins/device-manager/device-manager.addon.d.ts +52 -17
- package/dist/builtins/device-manager/device-manager.addon.d.ts.map +1 -1
- package/dist/builtins/device-manager/device-manager.addon.js +285 -161
- package/dist/builtins/device-manager/device-manager.addon.js.map +1 -1
- package/dist/builtins/device-manager/device-manager.addon.mjs +286 -162
- package/dist/builtins/device-manager/device-manager.addon.mjs.map +1 -1
- package/dist/builtins/local-auth/auth-schema.d.ts +1 -0
- package/dist/builtins/local-auth/auth-schema.d.ts.map +1 -1
- package/dist/builtins/local-auth/local-auth.addon.d.ts +1 -0
- package/dist/builtins/local-auth/local-auth.addon.d.ts.map +1 -1
- package/dist/builtins/local-auth/local-auth.addon.js +354 -3
- package/dist/builtins/local-auth/local-auth.addon.js.map +1 -1
- package/dist/builtins/local-auth/local-auth.addon.mjs +355 -3
- package/dist/builtins/local-auth/local-auth.addon.mjs.map +1 -1
- package/dist/builtins/local-auth/oauth-grants.d.ts +46 -0
- package/dist/builtins/local-auth/oauth-grants.d.ts.map +1 -0
- package/dist/builtins/local-auth/oauth-session-manager.d.ts +51 -0
- package/dist/builtins/local-auth/oauth-session-manager.d.ts.map +1 -0
- package/dist/builtins/remote-access-orchestrator/enabled-providers-reconcile.d.ts +97 -0
- package/dist/builtins/remote-access-orchestrator/enabled-providers-reconcile.d.ts.map +1 -0
- package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.d.ts +17 -0
- package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.d.ts.map +1 -1
- package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +95 -5
- package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js.map +1 -1
- package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +95 -5
- package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs.map +1 -1
- package/dist/builtins/snapshot/index.js +1 -3
- package/dist/builtins/snapshot/index.js.map +1 -1
- package/dist/builtins/snapshot/index.mjs +1 -3
- package/dist/builtins/snapshot/index.mjs.map +1 -1
- package/dist/builtins/snapshot/snapshot.addon.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +419 -97
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +419 -98
- package/dist/index.mjs.map +1 -1
- package/package.json +19 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["WELL_KNOWN_TAB_MAP","StorageLocationTypeSchema","errMsg","DeviceType","DeviceFeature","AlertSchema","alertsCapability","storageCapability","storageProviderCapability","backupCapability","settingsStoreCapability","logDestinationCapability","addonPagesCapability","addonWidgetsCapability","deviceManagerCapability","deviceStateCapability","authProviderCapability","snapshotCapability","metricsProviderCapability","platformProbeCapability","localNetworkCapability","UserRecordSchema","ApiKeyRecordSchema","ScopedTokenSchema","userManagementCapability","errMsg"],"sources":["../../types/dist/index-CWhQOnm9.mjs","../../types/dist/node.mjs","../src/events/event-bus.ts","../src/download/model-downloader.ts","../src/download/model-download-service.ts","../src/python/python-env-manager.ts","../src/pipeline/pipeline-validator.ts","../src/pipeline/pipeline-runner.ts","../src/pipeline/engine-manager-resolver.ts","../src/network/network-quality.ts","../src/repl/repl-engine.ts","../src/lifecycle/lifecycle-state-machine.ts","../src/feature/feature-manager.ts","../src/events/system-event-bus.ts","../src/logging/log-ring-buffer.ts","../src/logging/scoped-logger.ts","../src/logging/log-manager.ts","../src/storage/fs-storage-backend.ts","../src/storage/storage-location-manager.ts","../src/storage/storage-manager.ts","../src/notification/notification-service.ts","../src/notification/toast-service.ts","../src/addon-routes/addon-route-registry.ts","../src/tls/cert-manager.ts","../src/addon/addon-api-factory.ts","../src/builtins/sqlite-storage/integration-registry.ts"],"sourcesContent":["import { z } from \"zod\";\nconst MODEL_FORMATS = [\"onnx\", \"coreml\", \"openvino\", \"tflite\", \"pt\"];\nconst WELL_KNOWN_TABS = [\n { id: \"overview\", label: \"Overview\", icon: \"layout-dashboard\", order: -10 },\n { id: \"general\", label: \"General\", icon: \"settings\", order: 0 },\n { id: \"image\", label: \"Image\", icon: \"image\", order: 5 },\n { id: \"light\", label: \"Light\", icon: \"lightbulb\", order: 7 },\n { id: \"motion\", label: \"Motion\", icon: \"activity\", order: 10 },\n { id: \"audio\", label: \"Audio\", icon: \"mic\", order: 12 },\n { id: \"alarms\", label: \"Alarms\", icon: \"bell-ring\", order: 13 },\n { id: \"snapshot\", label: \"Snapshot\", icon: \"camera\", order: 15 },\n { id: \"osd\", label: \"OSD\", icon: \"type\", order: 18 },\n { id: \"stream-broker\", label: \"Stream Broker\", icon: \"radio\", order: 20 },\n { id: \"streaming\", label: \"Streaming\", icon: \"video\", order: 35 },\n { id: \"pipeline\", label: \"Detection Pipeline\", icon: \"cpu\", order: 39 },\n { id: \"zones\", label: \"Detection\", icon: \"shapes\", order: 38 },\n { id: \"live-stats\", label: \"Live Stats\", icon: \"activity\", order: 39 },\n { id: \"recording\", label: \"Recording\", icon: \"circle-dot\", order: 40 },\n // Pipeline-page tabs — `engine` co-locates `detection-pipeline`'s\n // vision-engine section + `audio-analyzer`'s audio-engine section\n // (same modality of choice, different pipelines). `scheduler` and\n // `decoder` group the runner / decoder addon settings under their\n // own tabs so the pipeline page bar stays manageable.\n { id: \"engine\", label: \"Inference Engine\", icon: \"zap\", order: 41 },\n { id: \"scheduler\", label: \"Scheduler\", icon: \"list-checks\", order: 42 },\n { id: \"decoder\", label: \"Decoder\", icon: \"film\", order: 43 },\n { id: \"notifications\", label: \"Notifications\", icon: \"bell\", order: 50 },\n { id: \"network\", label: \"Network\", icon: \"globe\", order: 60 },\n { id: \"storage\", label: \"Storage\", icon: \"hard-drive\", order: 70 },\n { id: \"advanced\", label: \"Advanced\", icon: \"wrench\", order: 100 }\n];\nconst WELL_KNOWN_TAB_MAP = Object.fromEntries(WELL_KNOWN_TABS.map((t) => [t.id, t]));\nfunction isValuelessField(field) {\n return field.type === \"separator\" || field.type === \"info\" || field.type === \"button\" || field.type === \"object-array\" || field.type === \"widget\" || field.type === \"addon-action-button\";\n}\nfunction hydrateSchema(schema, values) {\n return {\n ...schema.tabs ? { tabs: [...schema.tabs] } : {},\n sections: schema.sections.map((section) => ({\n ...section,\n fields: section.fields.map((field) => hydrateField(field, values))\n }))\n };\n}\nfunction hydrateField(field, values) {\n if (isValuelessField(field)) {\n return field;\n }\n if (field.type === \"group\") {\n const hydratedChildren = field.fields.map((child) => hydrateField(child, values));\n const out = {\n ...field,\n fields: hydratedChildren\n };\n return out;\n }\n if (field.type === \"sub-tabs\") {\n const hydratedTabs = field.tabs.map((tab) => ({\n ...tab,\n fields: tab.fields.map((child) => hydrateField(child, values))\n }));\n const out = {\n ...field,\n tabs: hydratedTabs\n };\n return out;\n }\n const key = field.key;\n const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;\n const defaultValue = field.default;\n if (field.multiple) {\n const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];\n const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === \"string\" ? \"\" : null;\n const minCount = Math.max(field.multiple.min, stored.length);\n const items = [];\n for (let i = 0; i < minCount; i++) {\n items.push(i < stored.length ? stored[i] : itemFallback);\n }\n return { ...field, value: items };\n }\n const rawValue = storedValue !== void 0 ? storedValue : defaultValue !== void 0 ? defaultValue : null;\n const value = field.type === \"textarea\" && field.isJson && rawValue !== null && typeof rawValue === \"object\" ? JSON.stringify(rawValue, null, 2) : rawValue;\n const hydrated = { ...field, value };\n return hydrated;\n}\nfunction typeOf(field) {\n switch (field.type) {\n case \"text\":\n case \"textarea\":\n case \"password\":\n case \"color\":\n case \"probe\":\n return \"string\";\n case \"number\":\n case \"slider\":\n return \"number\";\n case \"boolean\":\n return \"boolean\";\n default:\n return \"other\";\n }\n}\nconst StorageLocationTypeSchema = z.enum([\n \"data\",\n \"media\",\n \"recordings\",\n // Recording-stream slots — addons pick high/low/clips per use case.\n // The legacy `IStorageProvider` interface enumerated these; keeping\n // them in the Zod enum means the `storage` cap can route per-slot\n // location refs (e.g. `'recordings-high:nas-01'`) without losing\n // type safety.\n \"recordings-high\",\n \"recordings-low\",\n \"recordings-clips\",\n // Detection snapshots / thumbnails / crops.\n \"event-images\",\n \"models\",\n \"cache\",\n \"logs\",\n \"addons-data\",\n // `backups` — owned by the backup-orchestrator builtin. Default\n // root: `<dataDir>/backups`. Operators can repoint via the same\n // override mechanism every other location uses (storage settings).\n \"backups\"\n]);\nconst STORAGE_LOCATION_CARDINALITY = {\n // Singletons — system-internal or split-state-incoherent\n data: \"singleton\",\n media: \"singleton\",\n cache: \"singleton\",\n logs: \"singleton\",\n \"addons-data\": \"singleton\",\n models: \"singleton\",\n \"event-images\": \"singleton\",\n // Multi — operator-driven storage tiering\n recordings: \"multi\",\n \"recordings-high\": \"multi\",\n \"recordings-low\": \"multi\",\n \"recordings-clips\": \"multi\",\n backups: \"multi\"\n};\nconst StorageLocationSchema = z.object({\n id: z.string().regex(/^[a-z][a-z0-9-]*:[a-z0-9-]+$/),\n type: StorageLocationTypeSchema,\n displayName: z.string().min(1),\n providerId: z.string().min(1),\n config: z.record(z.string(), z.unknown()),\n isDefault: z.boolean().default(false),\n isSystem: z.boolean().default(false),\n createdAt: z.number(),\n updatedAt: z.number()\n});\nconst StorageLocationRefSchema = z.union([\n StorageLocationTypeSchema,\n z.string().regex(/^[a-z][a-z0-9-]*:[a-z0-9-]+$/)\n]);\nconst DecoderStatsSchema = z.object({\n inputFps: z.number(),\n outputFps: z.number(),\n avgDecodeTimeMs: z.number(),\n droppedFrames: z.number()\n});\nconst DecoderSessionConfigSchema = z.object({\n codec: z.string(),\n maxFps: z.number().default(0),\n outputFormat: z.enum([\"jpeg\", \"rgb\", \"bgr\", \"yuv420\", \"gray\"]).default(\"jpeg\"),\n scale: z.number().default(1),\n width: z.number().optional(),\n height: z.number().optional(),\n /**\n * Identifier of the camera this decoder session serves. Optional\n * because the cap is generic (any caller could request decode), but\n * stream-broker passes it so decoder logs include `deviceId` for\n * per-camera filtering when diagnosing failures (e.g. node-av\n * sendPacket errors on a single hung camera).\n */\n deviceId: z.number().int().nonnegative().optional(),\n /**\n * Free-form tag for log scoping. Stream-broker uses\n * `broker:<deviceId>/<profile>`. Decoder session logger surfaces it\n * on every line so `grep tag=broker:5/high` filters one camera\n * profile cleanly.\n */\n tag: z.string().optional()\n});\nfunction errMsg(err) {\n if (err instanceof Error) return err.message;\n if (typeof err === \"string\") return err;\n return String(err);\n}\nconst AUDIO_MACRO_LABELS = [\n { id: \"speech\", name: \"Speech\", icon: \"🗣️\" },\n { id: \"scream\", name: \"Scream / Shout\", icon: \"😱\" },\n { id: \"crying\", name: \"Crying / Baby\", icon: \"😢\" },\n { id: \"laughter\", name: \"Laughter\", icon: \"😂\" },\n { id: \"music\", name: \"Music\", icon: \"🎵\" },\n { id: \"dog\", name: \"Dog\", icon: \"🐕\" },\n { id: \"cat\", name: \"Cat\", icon: \"🐈\" },\n { id: \"bird\", name: \"Bird\", icon: \"🐦\" },\n { id: \"animal\", name: \"Animal (other)\", icon: \"🐾\" },\n { id: \"alarm\", name: \"Alarm / Siren\", icon: \"🚨\" },\n { id: \"doorbell\", name: \"Doorbell / Knock\", icon: \"🔔\" },\n { id: \"glass_breaking\", name: \"Glass Breaking\", icon: \"💥\" },\n { id: \"gunshot\", name: \"Gunshot / Explosion\", icon: \"💣\" },\n { id: \"vehicle\", name: \"Vehicle\", icon: \"🚗\" },\n { id: \"siren\", name: \"Emergency Siren\", icon: \"🚑\" },\n { id: \"fire\", name: \"Fire / Smoke\", icon: \"🔥\" },\n { id: \"water\", name: \"Water\", icon: \"💧\" },\n { id: \"wind\", name: \"Wind / Weather\", icon: \"🌬️\" },\n { id: \"door\", name: \"Door\", icon: \"🚪\" },\n { id: \"footsteps\", name: \"Footsteps\", icon: \"👣\" },\n { id: \"crowd\", name: \"Crowd / Chatter\", icon: \"👥\" },\n { id: \"telephone\", name: \"Telephone\", icon: \"📞\" },\n { id: \"engine\", name: \"Engine / Motor\", icon: \"⚙️\" },\n { id: \"tools\", name: \"Tools / Construction\", icon: \"🔨\" },\n { id: \"silence\", name: \"Silence\", icon: \"🤫\" }\n];\nconst YAMNET_TO_MACRO = {\n mapping: {\n // Speech\n \"Speech\": \"speech\",\n \"Child speech, kid speaking\": \"speech\",\n \"Conversation\": \"speech\",\n \"Narration, monologue\": \"speech\",\n \"Babbling\": \"speech\",\n \"Whispering\": \"speech\",\n \"Speech synthesizer\": \"speech\",\n \"Humming\": \"speech\",\n \"Rapping\": \"speech\",\n \"Singing\": \"speech\",\n \"Choir\": \"speech\",\n \"Child singing\": \"speech\",\n // Scream / Shout\n \"Shout\": \"scream\",\n \"Bellow\": \"scream\",\n \"Yell\": \"scream\",\n \"Screaming\": \"scream\",\n \"Children shouting\": \"scream\",\n \"Whoop\": \"scream\",\n // Crying\n \"Crying, sobbing\": \"crying\",\n \"Baby cry, infant cry\": \"crying\",\n \"Whimper\": \"crying\",\n \"Wail, moan\": \"crying\",\n \"Groan\": \"crying\",\n // Laughter\n \"Laughter\": \"laughter\",\n \"Baby laughter\": \"laughter\",\n \"Giggle\": \"laughter\",\n \"Snicker\": \"laughter\",\n \"Belly laugh\": \"laughter\",\n \"Chuckle, chortle\": \"laughter\",\n // Music\n \"Music\": \"music\",\n \"Musical instrument\": \"music\",\n \"Guitar\": \"music\",\n \"Piano\": \"music\",\n \"Drum\": \"music\",\n \"Drum kit\": \"music\",\n \"Violin, fiddle\": \"music\",\n \"Flute\": \"music\",\n \"Saxophone\": \"music\",\n \"Trumpet\": \"music\",\n \"Synthesizer\": \"music\",\n \"Pop music\": \"music\",\n \"Rock music\": \"music\",\n \"Hip hop music\": \"music\",\n \"Classical music\": \"music\",\n \"Jazz\": \"music\",\n \"Electronic music\": \"music\",\n \"Background music\": \"music\",\n // Dog\n \"Dog\": \"dog\",\n \"Bark\": \"dog\",\n \"Yip\": \"dog\",\n \"Howl\": \"dog\",\n \"Bow-wow\": \"dog\",\n \"Growling\": \"dog\",\n \"Whimper (dog)\": \"dog\",\n // Cat\n \"Cat\": \"cat\",\n \"Purr\": \"cat\",\n \"Meow\": \"cat\",\n \"Hiss\": \"cat\",\n \"Caterwaul\": \"cat\",\n // Bird\n \"Bird\": \"bird\",\n \"Bird vocalization, bird call, bird song\": \"bird\",\n \"Chirp, tweet\": \"bird\",\n \"Squawk\": \"bird\",\n \"Crow\": \"bird\",\n \"Owl\": \"bird\",\n \"Pigeon, dove\": \"bird\",\n // Animal (other)\n \"Animal\": \"animal\",\n \"Domestic animals, pets\": \"animal\",\n \"Livestock, farm animals, working animals\": \"animal\",\n \"Horse\": \"animal\",\n \"Cattle, bovinae\": \"animal\",\n \"Pig\": \"animal\",\n \"Sheep\": \"animal\",\n \"Goat\": \"animal\",\n \"Frog\": \"animal\",\n \"Insect\": \"animal\",\n \"Cricket\": \"animal\",\n // Alarm / Siren\n \"Alarm\": \"alarm\",\n \"Alarm clock\": \"alarm\",\n \"Smoke detector, smoke alarm\": \"alarm\",\n \"Fire alarm\": \"alarm\",\n \"Buzzer\": \"alarm\",\n \"Civil defense siren\": \"alarm\",\n \"Car alarm\": \"alarm\",\n // Emergency Siren\n \"Siren\": \"siren\",\n \"Police car (siren)\": \"siren\",\n \"Ambulance (siren)\": \"siren\",\n \"Fire engine, fire truck (siren)\": \"siren\",\n \"Emergency vehicle\": \"siren\",\n \"Foghorn\": \"siren\",\n // Doorbell / Knock\n \"Doorbell\": \"doorbell\",\n \"Ding-dong\": \"doorbell\",\n \"Knock\": \"doorbell\",\n \"Tap\": \"doorbell\",\n // Glass Breaking\n \"Glass\": \"glass_breaking\",\n \"Shatter\": \"glass_breaking\",\n \"Chink, clink\": \"glass_breaking\",\n // Gunshot / Explosion\n \"Gunshot, gunfire\": \"gunshot\",\n \"Machine gun\": \"gunshot\",\n \"Explosion\": \"gunshot\",\n \"Fireworks\": \"gunshot\",\n \"Firecracker\": \"gunshot\",\n \"Artillery fire\": \"gunshot\",\n \"Cap gun\": \"gunshot\",\n \"Boom\": \"gunshot\",\n // Vehicle\n \"Vehicle\": \"vehicle\",\n \"Car\": \"vehicle\",\n \"Truck\": \"vehicle\",\n \"Bus\": \"vehicle\",\n \"Motorcycle\": \"vehicle\",\n \"Car passing by\": \"vehicle\",\n \"Vehicle horn, car horn, honking\": \"vehicle\",\n \"Traffic noise, roadway noise\": \"vehicle\",\n \"Train\": \"vehicle\",\n \"Aircraft\": \"vehicle\",\n \"Helicopter\": \"vehicle\",\n \"Bicycle\": \"vehicle\",\n \"Skateboard\": \"vehicle\",\n // Fire / Smoke\n \"Fire\": \"fire\",\n \"Crackle\": \"fire\",\n // Water\n \"Water\": \"water\",\n \"Rain\": \"water\",\n \"Raindrop\": \"water\",\n \"Rain on surface\": \"water\",\n \"Stream\": \"water\",\n \"Waterfall\": \"water\",\n \"Ocean\": \"water\",\n \"Waves, surf\": \"water\",\n \"Splash, splatter\": \"water\",\n // Wind / Weather\n \"Wind\": \"wind\",\n \"Thunderstorm\": \"wind\",\n \"Thunder\": \"wind\",\n \"Wind noise (microphone)\": \"wind\",\n \"Rustling leaves\": \"wind\",\n // Door\n \"Door\": \"door\",\n \"Sliding door\": \"door\",\n \"Slam\": \"door\",\n \"Cupboard open or close\": \"door\",\n // Footsteps\n \"Walk, footsteps\": \"footsteps\",\n \"Run\": \"footsteps\",\n \"Shuffle\": \"footsteps\",\n // Crowd\n \"Crowd\": \"crowd\",\n \"Chatter\": \"crowd\",\n \"Cheering\": \"crowd\",\n \"Applause\": \"crowd\",\n \"Children playing\": \"crowd\",\n \"Hubbub, speech noise, speech babble\": \"crowd\",\n // Telephone\n \"Telephone\": \"telephone\",\n \"Telephone bell ringing\": \"telephone\",\n \"Ringtone\": \"telephone\",\n \"Telephone dialing, DTMF\": \"telephone\",\n \"Busy signal\": \"telephone\",\n // Engine / Motor\n \"Engine\": \"engine\",\n \"Engine starting\": \"engine\",\n \"Idling\": \"engine\",\n \"Accelerating, revving, vroom\": \"engine\",\n \"Light engine (high frequency)\": \"engine\",\n \"Medium engine (mid frequency)\": \"engine\",\n \"Heavy engine (low frequency)\": \"engine\",\n \"Lawn mower\": \"engine\",\n \"Chainsaw\": \"engine\",\n // Tools / Construction\n \"Hammer\": \"tools\",\n \"Jackhammer\": \"tools\",\n \"Sawing\": \"tools\",\n \"Power tool\": \"tools\",\n \"Drill\": \"tools\",\n \"Sanding\": \"tools\",\n // Silence\n \"Silence\": \"silence\"\n },\n preserveOriginal: false\n};\nconst APPLE_SA_TO_MACRO = {\n mapping: {\n \"speech\": \"speech\",\n \"child_speech\": \"speech\",\n \"conversation\": \"speech\",\n \"whispering\": \"speech\",\n \"singing\": \"speech\",\n \"humming\": \"speech\",\n \"shout\": \"scream\",\n \"yell\": \"scream\",\n \"screaming\": \"scream\",\n \"crying\": \"crying\",\n \"baby_crying\": \"crying\",\n \"sobbing\": \"crying\",\n \"laughter\": \"laughter\",\n \"baby_laughter\": \"laughter\",\n \"giggling\": \"laughter\",\n \"music\": \"music\",\n \"guitar\": \"music\",\n \"piano\": \"music\",\n \"drums\": \"music\",\n \"dog_bark\": \"dog\",\n \"dog_bow_wow\": \"dog\",\n \"dog_growling\": \"dog\",\n \"dog_howl\": \"dog\",\n \"cat_meow\": \"cat\",\n \"cat_purr\": \"cat\",\n \"cat_hiss\": \"cat\",\n \"bird\": \"bird\",\n \"bird_chirp\": \"bird\",\n \"bird_squawk\": \"bird\",\n \"animal\": \"animal\",\n \"horse\": \"animal\",\n \"cow_moo\": \"animal\",\n \"insect\": \"animal\",\n \"alarm\": \"alarm\",\n \"smoke_alarm\": \"alarm\",\n \"fire_alarm\": \"alarm\",\n \"car_alarm\": \"alarm\",\n \"siren\": \"siren\",\n \"police_siren\": \"siren\",\n \"ambulance_siren\": \"siren\",\n \"doorbell\": \"doorbell\",\n \"door_knock\": \"doorbell\",\n \"knocking\": \"doorbell\",\n \"glass_breaking\": \"glass_breaking\",\n \"glass_shatter\": \"glass_breaking\",\n \"gunshot\": \"gunshot\",\n \"explosion\": \"gunshot\",\n \"fireworks\": \"gunshot\",\n \"car\": \"vehicle\",\n \"truck\": \"vehicle\",\n \"motorcycle\": \"vehicle\",\n \"car_horn\": \"vehicle\",\n \"vehicle_horn\": \"vehicle\",\n \"traffic\": \"vehicle\",\n \"fire\": \"fire\",\n \"fire_crackle\": \"fire\",\n \"water\": \"water\",\n \"rain\": \"water\",\n \"ocean\": \"water\",\n \"splash\": \"water\",\n \"wind\": \"wind\",\n \"thunder\": \"wind\",\n \"thunderstorm\": \"wind\",\n \"door\": \"door\",\n \"door_slam\": \"door\",\n \"sliding_door\": \"door\",\n \"footsteps\": \"footsteps\",\n \"walking\": \"footsteps\",\n \"running\": \"footsteps\",\n \"crowd\": \"crowd\",\n \"chatter\": \"crowd\",\n \"cheering\": \"crowd\",\n \"applause\": \"crowd\",\n \"telephone_ring\": \"telephone\",\n \"ringtone\": \"telephone\",\n \"engine\": \"engine\",\n \"engine_starting\": \"engine\",\n \"lawn_mower\": \"engine\",\n \"chainsaw\": \"engine\",\n \"hammer\": \"tools\",\n \"jackhammer\": \"tools\",\n \"drill\": \"tools\",\n \"power_tool\": \"tools\",\n \"silence\": \"silence\"\n },\n preserveOriginal: false\n};\nconst _macroLookup = /* @__PURE__ */ new Map();\nfor (const [k, v] of Object.entries(YAMNET_TO_MACRO.mapping)) {\n _macroLookup.set(k.toLowerCase(), v);\n}\nfor (const [k, v] of Object.entries(APPLE_SA_TO_MACRO.mapping)) {\n _macroLookup.set(k.toLowerCase(), v);\n}\nfunction mapAudioLabelToMacro(label) {\n return _macroLookup.get(label.toLowerCase()) ?? null;\n}\nfunction getAudioMacroClassIds() {\n return AUDIO_MACRO_LABELS.map((l) => l.id);\n}\nvar DeviceType = /* @__PURE__ */ ((DeviceType2) => {\n DeviceType2[\"Camera\"] = \"camera\";\n DeviceType2[\"Hub\"] = \"hub\";\n DeviceType2[\"Light\"] = \"light\";\n DeviceType2[\"Siren\"] = \"siren\";\n DeviceType2[\"Switch\"] = \"switch\";\n DeviceType2[\"Sensor\"] = \"sensor\";\n DeviceType2[\"Thermostat\"] = \"thermostat\";\n DeviceType2[\"Button\"] = \"button\";\n DeviceType2[\"Generic\"] = \"generic\";\n return DeviceType2;\n})(DeviceType || {});\nvar DeviceFeature = /* @__PURE__ */ ((DeviceFeature2) => {\n DeviceFeature2[\"BatteryOperated\"] = \"battery-operated\";\n DeviceFeature2[\"Rebootable\"] = \"rebootable\";\n DeviceFeature2[\"NativeSnapshot\"] = \"native-snapshot\";\n DeviceFeature2[\"DoorbellButton\"] = \"doorbell-button\";\n DeviceFeature2[\"TwoWayAudio\"] = \"two-way-audio\";\n DeviceFeature2[\"PanTiltZoom\"] = \"pan-tilt-zoom\";\n DeviceFeature2[\"PtzAutotrack\"] = \"ptz-autotrack\";\n DeviceFeature2[\"MotionTrigger\"] = \"motion-trigger\";\n return DeviceFeature2;\n})(DeviceFeature || {});\nvar ChargingStatus = /* @__PURE__ */ ((ChargingStatus2) => {\n ChargingStatus2[\"ChargingDC\"] = \"charging-dc\";\n ChargingStatus2[\"ChargingSolar\"] = \"charging-solar\";\n ChargingStatus2[\"NotCharging\"] = \"not-charging\";\n return ChargingStatus2;\n})(ChargingStatus || {});\nvar DeviceRole = /* @__PURE__ */ ((DeviceRole2) => {\n DeviceRole2[\"Siren\"] = \"siren\";\n DeviceRole2[\"Floodlight\"] = \"floodlight\";\n DeviceRole2[\"Spotlight\"] = \"spotlight\";\n DeviceRole2[\"PirSensor\"] = \"pir-sensor\";\n DeviceRole2[\"Chime\"] = \"chime\";\n DeviceRole2[\"Autotrack\"] = \"autotrack\";\n DeviceRole2[\"Nightvision\"] = \"nightvision\";\n DeviceRole2[\"PrivacyMask\"] = \"privacy-mask\";\n DeviceRole2[\"Doorbell\"] = \"doorbell\";\n return DeviceRole2;\n})(DeviceRole || {});\nconst AccessoryKind = {\n Siren: DeviceRole.Siren,\n Floodlight: DeviceRole.Floodlight,\n Spotlight: DeviceRole.Spotlight,\n PirSensor: DeviceRole.PirSensor,\n Chime: DeviceRole.Chime,\n Autotrack: DeviceRole.Autotrack,\n Nightvision: DeviceRole.Nightvision,\n PrivacyMask: DeviceRole.PrivacyMask\n};\nconst ACCESSORY_LABEL = {\n [AccessoryKind.Siren]: \"Siren\",\n [AccessoryKind.Floodlight]: \"Floodlight\",\n [AccessoryKind.Spotlight]: \"Spotlight\",\n [AccessoryKind.PirSensor]: \"PIR\",\n [AccessoryKind.Chime]: \"Chime\",\n [AccessoryKind.Autotrack]: \"Autotracking\",\n [AccessoryKind.Nightvision]: \"Night Vision\",\n [AccessoryKind.PrivacyMask]: \"Privacy Mask\"\n};\nfunction accessoryStableId(parentStableId, kind, index) {\n const base = `${parentStableId}:${kind}`;\n return typeof index === \"number\" ? `${base}:${index}` : base;\n}\nfunction deviceMatchesProfile(features, profile) {\n if (!features || features.length === 0) return false;\n return features.includes(profile.when.hasFeature);\n}\nconst BATTERY_DEVICE_PROFILE = {\n id: \"battery\",\n label: \"Battery-operated camera\",\n when: { hasFeature: DeviceFeature.BatteryOperated },\n defaults: {\n audioMode: \"disabled\",\n detectionMode: \"on-motion\"\n },\n settings: {\n \"snapshot.minRefreshIntervalSec\": 3600,\n \"streamBroker.preBufferEnabled\": false\n }\n};\nconst DEVICE_PROFILES = [\n BATTERY_DEVICE_PROFILE\n];\nfunction resolveDeviceProfile(features) {\n for (const profile of DEVICE_PROFILES) {\n if (deviceMatchesProfile(features, profile)) return profile;\n }\n return null;\n}\nconst DeviceStatusSchema = z.object({\n /**\n * Device-level liveness. Drivers flip via `markOnline(boolean)` on\n * `BaseDevice`. Provider semantics vary — RTSP aggregates broker\n * stream-health, Reolink reads firmware push events, ONVIF tracks\n * ping responses. This cap intentionally does NOT prescribe which\n * signal drives the flag.\n */\n online: z.boolean(),\n /** Ms epoch of the last `online` transition. Lets consumers tell\n * apart \"just came online\" from \"still online\". */\n lastChangedAt: z.number()\n});\nconst deviceStatusCapability = {\n name: \"device-status\",\n scope: \"device\",\n mode: \"singleton\",\n methods: {},\n events: {\n /** Emitted when `online` transitions. Mirrors the semantics of\n * `battery.onStatusChanged`. */\n onStatusChanged: { data: z.object({\n deviceId: z.number(),\n status: DeviceStatusSchema\n }) }\n },\n status: {\n schema: DeviceStatusSchema,\n kind: \"push\"\n },\n runtimeState: DeviceStatusSchema\n};\nconst FeatureProbeStatusSchema = z.object({\n /**\n * Driver-specific flag bag. Each driver picks its own key names — the\n * cap deliberately does NOT enforce a closed enum here. Reolink keys:\n * `hasPtz`, `hasIntercom`, `hasDoorbell`, `hasFloodlight`, `hasSiren`,\n * `hasPirSensor`, `hasAutotrack`, `hasBattery`. Hikvision keys:\n * `hasSupplementalLight`, `lightHasWhiteLight`, `hasAlarmIo`, `hasPtz`.\n */\n flags: z.record(z.string(), z.unknown()),\n /**\n * Coarse driver-classification — lets cross-process consumers tell apart\n * cameras / battery-cams / NVRs without re-running the probe. `null`\n * before the first probe completes.\n */\n deviceType: z.string().nullable(),\n /** Camera/firmware model string. `null` when the firmware doesn't expose it. */\n model: z.string().nullable(),\n /** Channel count for NVR/Hub devices; `1` for standalone cameras; `null` pre-probe. */\n channelCount: z.number().nullable(),\n /**\n * Ms epoch of the last SUCCESSFUL probe. `0` before the first probe\n * completes — drivers' `getAccessoryChildren()` should treat zero as\n * \"probe not done yet, return empty\" so accessories aren't spawned\n * before the firmware is queried.\n */\n lastProbedAt: z.number(),\n /**\n * Framework convention: every runtime-state slice carries this for the\n * createRuntimeStateBridge stale-check helper. We keep it in sync with\n * `lastProbedAt` on every write.\n */\n lastFetchedAt: z.number()\n});\nconst featureProbeCapability = {\n name: \"feature-probe\",\n scope: \"device\",\n mode: \"singleton\",\n methods: {},\n events: {\n /** Fires whenever a fresh probe completes (kernel-driven `reprobe()`\n * or driver-initiated re-detect after a state change). */\n onProbeChanged: { data: z.object({\n deviceId: z.number(),\n status: FeatureProbeStatusSchema\n }) }\n },\n status: {\n schema: FeatureProbeStatusSchema,\n kind: \"push\"\n },\n runtimeState: FeatureProbeStatusSchema\n};\nconst ContributionSectionSchema = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string().optional(),\n style: z.enum([\"card\", \"accordion\"]).optional(),\n defaultCollapsed: z.boolean().optional(),\n columns: z.union([z.literal(1), z.literal(2), z.literal(3), z.literal(4)]).optional(),\n tab: z.string().optional(),\n // Hoist the section into a top-level device tab (DeviceDetail\n // discovers these and renders one tab per unique `tab` id). Default\n // 'settings' keeps the section under the Config tab.\n location: z.enum([\"settings\", \"top-tab\"]).optional(),\n order: z.number().optional(),\n fields: z.array(z.any())\n});\nconst ContributionTabSchema = z.object({\n id: z.string(),\n label: z.string(),\n icon: z.string(),\n order: z.number().optional()\n});\nconst ContributionSchema = z.object({\n tabs: z.array(ContributionTabSchema).optional(),\n sections: z.array(ContributionSectionSchema)\n});\nconst ContributionOutputSchema = ContributionSchema.nullable();\nconst DEVICE_SETTINGS_CONTRIBUTION_METHODS = {\n getDeviceSettingsContribution: {\n input: z.object({ deviceId: z.number() }),\n output: ContributionOutputSchema,\n kind: \"query\",\n auth: \"protected\"\n },\n getDeviceLiveContribution: {\n input: z.object({ deviceId: z.number() }),\n output: ContributionOutputSchema,\n kind: \"query\",\n auth: \"protected\"\n },\n applyDeviceSettingsPatch: {\n input: z.object({ deviceId: z.number(), patch: z.record(z.string(), z.unknown()) }),\n output: z.object({ success: z.literal(true) }),\n kind: \"mutation\",\n auth: \"admin\"\n }\n};\nconst DEVICE_STATUS_METHOD = {\n getStatus: {\n input: z.object({ deviceId: z.number() }),\n output: z.unknown().nullable(),\n kind: \"query\",\n auth: \"protected\"\n }\n};\nfunction expandCapMethods(def) {\n let out = def.methods;\n if (def.exposesDeviceSettings) {\n out = { ...DEVICE_SETTINGS_CONTRIBUTION_METHODS, ...out };\n }\n if (def.status) {\n out = { ...DEVICE_STATUS_METHOD, ...out };\n }\n return out;\n}\nfunction method(input, output, options) {\n return {\n input,\n output,\n kind: options?.kind ?? \"query\",\n auth: options?.auth ?? \"protected\",\n ...options?.access !== void 0 ? { access: options.access } : {},\n timeoutMs: options?.timeoutMs\n };\n}\nfunction event(data) {\n return { data };\n}\nconst AudioClassSummarySchema = z.object({\n className: z.string(),\n /** Number of windows (chunks) where this class was the top hit. */\n hits: z.number().int().nonnegative(),\n /** Mean score across those hits, clamped to [0,1]. */\n avgScore: z.number().min(0).max(1),\n /** Peak score in the window. */\n peakScore: z.number().min(0).max(1)\n});\nconst AudioMetricsSnapshotSchema = z.object({\n /** Wall-clock timestamp (ms) of the most recent audio window. */\n ts: z.number().int(),\n /** Sliding-window length (seconds) used for aggregation. */\n windowSec: z.number().int().positive(),\n /** Latest level reading from the most recent window. */\n level: z.object({\n rms: z.number(),\n dbfs: z.number()\n }),\n /** Peak dBFS observed across the rolling window. */\n peakDbfs: z.number(),\n /** Mean dBFS across the rolling window. */\n avgDbfs: z.number(),\n /** Most recent above-threshold classification, or null on silence. */\n current: z.object({\n className: z.string(),\n score: z.number().min(0).max(1),\n timestamp: z.number().int()\n }).nullable(),\n /** Per-class summary across the rolling window — keys are\n * `macroClass` strings (e.g. `dog_bark`, `speech`, `glass_break`). */\n byClass: z.array(AudioClassSummarySchema).readonly()\n});\nconst AudioMetricsHistoryPointSchema = z.object({\n /** Wall-clock ms when this sample was recorded. */\n ts: z.number().int(),\n /** Instantaneous dBFS level at sample time. `null` for windows where\n * the source had no level reading (rare; happens at decode startup). */\n dbfs: z.number().nullable(),\n /** Rolling-window peak dBFS at sample time. Same window the live\n * snapshot reports. */\n peakDbfs: z.number(),\n /** Rolling-window mean dBFS at sample time. */\n avgDbfs: z.number(),\n /** Dominant above-threshold class at sample time, or null on silence. */\n topClass: z.string().nullable(),\n /** Score of the dominant class (`null` whenever `topClass` is null). */\n topScore: z.number().min(0).max(1).nullable()\n});\nconst AudioMetricsHistorySchema = z.object({\n points: z.array(AudioMetricsHistoryPointSchema).readonly(),\n /** Actual ms between adjacent samples after any subsampling. */\n effectiveSampleEveryMs: z.number().int().positive(),\n /** Wall-clock window covered by `points` (`points[N-1].ts - points[0].ts`),\n * or `0` when there's fewer than 2 samples. */\n windowMsActual: z.number().int().nonnegative()\n});\nconst audioMetricsCapability = {\n name: \"audio-metrics\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n /** Latest snapshot for this device. Null until the analytics\n * pipeline has processed at least one audio window. */\n getCurrentSnapshot: method(\n z.object({ deviceId: z.number() }),\n AudioMetricsSnapshotSchema.nullable()\n ),\n /**\n * Time-series view of recent audio-metrics samples. The provider\n * keeps an in-memory ring of ~1Hz samples (matching the slice-\n * write rate) capped at `MAX_HISTORY_POINTS_KEPT` (provider-side).\n * `windowSec` selects how far back to read; `sampleEveryMs`\n * downsamples by bucketed averaging when finer than the kept\n * granularity. Empty `points` array on freshly-booted providers\n * with no audio yet — same convention as `getCurrentSnapshot`.\n */\n getHistory: method(\n z.object({\n deviceId: z.number(),\n /** History window in seconds. Default 300 (5 minutes).\n * Provider clamps to its retention cap if larger. */\n windowSec: z.number().int().positive().optional(),\n /** Target sample interval in ms. Default 1000 (1 sample/second).\n * Provider clamps to natural sample rate if smaller, and\n * bucket-averages when bigger than the requested window\n * would produce more than `maxPoints` samples. */\n sampleEveryMs: z.number().int().positive().optional()\n }),\n AudioMetricsHistorySchema\n )\n },\n /** Reactive runtime-state mirror — live `device.state.audioMetrics.value`. */\n runtimeState: AudioMetricsSnapshotSchema\n};\nconst BatteryStatusSchema = z.object({\n /** 0..100 inclusive. Firmware-reported. */\n percentage: z.number().min(0).max(100),\n /**\n * Charging source. `'dc'` covers wall/USB adapters; `'solar'` is\n * Reolink-specific for the Solar Panel 2 accessory (will become\n * common on other battery cams). `'none'` means running on battery\n * alone.\n */\n charging: z.enum([\"dc\", \"solar\", \"none\"]),\n /**\n * True when the camera firmware has gone into low-power mode. Battery\n * providers MUST avoid polling during sleep — reading the battery\n * wakes the camera up and drains charge.\n */\n sleeping: z.boolean(),\n /** Ms epoch of the last observation. Lets consumers reason about freshness. */\n lastUpdated: z.number()\n});\nconst batteryCapability = {\n name: \"battery\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera, DeviceType.Sensor, DeviceType.Button, DeviceType.Switch],\n methods: {},\n events: {\n /**\n * Emitted whenever the cached status changes (firmware push OR\n * poll observes a delta). The DeviceEventPropagator mirrors this\n * event on the parent chain — subscribing to a camera's source\n * receives battery events from child accessories automatically.\n */\n onStatusChanged: { data: z.object({\n deviceId: z.number(),\n status: BatteryStatusSchema\n }) }\n },\n status: {\n schema: BatteryStatusSchema,\n kind: \"push\"\n },\n /**\n * Runtime-state slice — every provider that registers this cap\n * stores the same shape under `device.runtimeState[battery]`.\n * Cross-provider uniformity: a Reolink Argus, a Frigate sensor\n * proxy, an ONVIF battery cam all read/write the same keys.\n * Consumers (BatteryBadge, snapshot wrapper sleep gate) read once\n * via `device.runtimeState.getCapState('battery')` regardless of\n * the underlying driver.\n */\n runtimeState: BatteryStatusSchema\n};\nconst BrightnessStatusSchema = z.object({\n /** Current level as 0..100 inclusive. Firmware-reported. */\n percentage: z.number().min(0).max(100),\n /** Ms epoch of the last operator-driven change. Useful for UI freshness. */\n lastChangedAt: z.number()\n});\nconst brightnessCapability = {\n name: \"brightness\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Light],\n methods: {\n setBrightness: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n percentage: z.number().min(0).max(100)\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n },\n events: {\n /**\n * Emitted whenever the brightness changes — operator action OR\n * firmware push. Subscribers (UI sliders, automation engines) react\n * without polling.\n */\n onBrightnessChanged: { data: z.object({\n deviceId: z.number(),\n percentage: z.number().min(0).max(100),\n lastChangedAt: z.number()\n }) }\n },\n status: {\n schema: BrightnessStatusSchema,\n kind: \"command-driven\"\n },\n /**\n * Runtime-state slice — the last applied brightness level, mirrored\n * by the kernel. Read via `device.state.brightness.value` so UI\n * sliders surface the current level without polling the provider.\n */\n runtimeState: BrightnessStatusSchema\n};\nconst CamProfileSchema = z.enum([\"high\", \"mid\", \"low\"]);\nconst CAM_PROFILE_ORDER = [\"high\", \"mid\", \"low\"];\nconst CamStreamKindSchema = z.enum([\n \"pull-rtsp\",\n \"pull-rtmp\",\n \"pull-http\",\n \"pull-rfc4571\",\n \"push-annexb\"\n]);\nconst CamStreamResolutionSchema = z.object({\n width: z.number().int().positive(),\n height: z.number().int().positive()\n});\nconst CameraStreamSchema = z.object({\n /** Stable, provider-assigned id unique within the (deviceId) scope. */\n camStreamId: z.string().min(1),\n deviceId: z.number().int().nonnegative(),\n kind: CamStreamKindSchema,\n /** Required for pull-* kinds. Ignored for push-annexb. */\n url: z.string().optional(),\n codec: z.string().optional(),\n resolution: CamStreamResolutionSchema.optional(),\n fps: z.number().positive().optional(),\n /** Human label surfaced in the Admin UI \"Camera Stream\" dropdown. */\n label: z.string().optional(),\n /**\n * Device-level features the publisher advertised (e.g. `battery-operated`).\n * The broker, snapshot orchestrator, and prebuffer manager all consult\n * this list to derive policy — relaxed stall watchdog for battery\n * cams, prebuffer off by default, longer snapshot rate-limit, etc.\n *\n * Single source of truth replacing per-stream flags like the\n * historical `allowStall`: if the publisher knows the camera is\n * battery-powered, every downstream service derives the right policy\n * from this list.\n */\n deviceFeatures: z.array(z.string()).optional(),\n /**\n * Whether this stream participates in the broker's automatic profile\n * assignment (`computeInitialAssignment`). Defaults to `true`. Publishers\n * use `false` when they want a stream to be SELECTABLE in the UI but not\n * picked by default — e.g. Reolink publishes its native Baichuan streams\n * as `autoEligible: true` (the recommended path) and its RTSP / RTMP\n * mirrors as `autoEligible: false` (still pickable per slot, just not\n * the auto choice). Manual `assignProfile` calls remain valid for\n * non-eligible streams.\n */\n autoEligible: z.boolean().optional(),\n /**\n * Transport-specific opaque metadata. The broker passes it through to\n * the source reader without inspecting it. Currently used by\n * `pull-rfc4571` streams to carry the upstream SDP (so the reader can\n * route RTP packets to the right depacketizer without an in-band\n * DESCRIBE phase). Other kinds typically leave it undefined.\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n});\nconst ProfileSlotStatusSchema = z.enum([\n \"unassigned\",\n \"idle\",\n \"connecting\",\n \"streaming\",\n \"error\"\n]);\nconst ProfileSlotSchema = z.object({\n deviceId: z.number().int().nonnegative(),\n profile: CamProfileSchema,\n /** Broker id the rest of the system addresses: `${deviceId}/${profile}`. */\n brokerId: z.string(),\n /** `null` when the profile is unassigned. */\n sourceCamStreamId: z.string().nullable(),\n status: ProfileSlotStatusSchema,\n resolution: CamStreamResolutionSchema.optional(),\n codec: z.string().optional(),\n preBufferSec: z.number().nonnegative().optional(),\n errorMessage: z.string().optional()\n});\nconst StreamSourceEntrySchema$1 = z.object({\n id: z.string(),\n label: z.string(),\n protocol: z.enum([\"rtsp\", \"rtmp\", \"annexb\", \"http-mjpeg\", \"webrtc\", \"custom\"]),\n url: z.string().optional(),\n resolution: z.object({ width: z.number(), height: z.number() }).readonly().optional(),\n fps: z.number().optional(),\n bitrate: z.number().optional(),\n codec: z.string().optional(),\n profileHint: z.enum([\"high\", \"mid\", \"low\"]).optional()\n});\nconst StreamSourceSchema = z.object({\n type: z.string(),\n url: z.string(),\n videoCodec: z.string().optional(),\n audioCodec: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).readonly().optional()\n});\nconst EncodedPacketSchema = z.object({\n type: z.enum([\"video\", \"audio\"]),\n data: z.instanceof(Uint8Array),\n pts: z.number(),\n dts: z.number(),\n keyframe: z.boolean(),\n codec: z.string()\n});\nconst DecodedFrameSchema = z.object({\n data: z.instanceof(Uint8Array),\n width: z.number(),\n height: z.number(),\n format: z.enum([\"jpeg\", \"rgb\", \"bgr\", \"yuv420\", \"gray\"]),\n timestamp: z.number()\n});\nconst BrokerStatusSchema$1 = z.enum([\"idle\", \"connecting\", \"streaming\", \"error\", \"stopped\"]);\nconst BrokerStatsSchema = z.object({\n status: BrokerStatusSchema$1,\n inputFps: z.number(),\n decodeFps: z.number(),\n encodedSubscribers: z.number(),\n decodedSubscribers: z.number(),\n uptimeMs: z.number(),\n bitrateKbps: z.number(),\n idrIntervalMs: z.number(),\n codec: z.string().optional(),\n totalBytes: z.number(),\n packetCount: z.number(),\n rtspClients: z.number(),\n pipeClients: z.number(),\n preBufferSec: z.number(),\n preBufferMs: z.number(),\n preBufferPackets: z.number(),\n /**\n * Moleculer node id of the decoder provider currently servicing this\n * stream's decoded subscribers. `null` until the deferred decoder is\n * created (no decoded clients yet, or codec not detected). Surfaces the\n * runtime decoder placement so the UI can show \"Decoder: <agent>\" without\n * a separate cap call per broker.\n */\n decoderNodeId: z.string().nullable(),\n /**\n * Detected audio track parameters from the RTSP DESCRIBE / SDP. `null`\n * when the stream has no audio track or the broker is in cold start.\n * `supported = false` means the codec was detected but the local\n * decoder pipeline cannot produce PCM chunks (e.g. AAC without the\n * AAC pipeline wired). Surfaced in the UI device-overview so operators\n * can pre-pick the audio-analysis model that matches the codec.\n */\n audio: z.object({\n codec: z.string(),\n sampleRate: z.number(),\n channels: z.number(),\n supported: z.boolean()\n }).nullable().optional()\n});\nconst StreamFormatSchema = z.enum([\"webrtc\", \"hls\", \"mjpeg\", \"rtsp\"]);\nconst StreamInfoSchema = z.object({\n streamId: z.string(),\n format: StreamFormatSchema,\n url: z.string().nullable(),\n active: z.boolean()\n});\nconst streamingEngineCapability = {\n name: \"streaming-engine\",\n scope: \"system\",\n mode: \"singleton\",\n internal: true,\n methods: {\n registerStream: method(\n z.object({ streamId: z.string(), sourceUrl: z.string(), codec: z.string().optional() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n unregisterStream: method(z.object({ streamId: z.string() }), z.void(), { kind: \"mutation\" }),\n getStreamUrl: method(\n z.object({ streamId: z.string(), format: StreamFormatSchema }),\n z.string().nullable()\n ),\n listStreams: method(z.void(), z.array(StreamInfoSchema))\n }\n};\nconst RtspRestreamEntrySchema = z.object({\n brokerId: z.string(),\n url: z.string(),\n mutedUrl: z.string(),\n enabled: z.boolean()\n});\nconst BrokerRtspClientSchema = z.object({\n sessionId: z.string(),\n remoteAddr: z.string(),\n playing: z.boolean(),\n muted: z.boolean(),\n connectedAt: z.number(),\n lastRtpAt: z.number(),\n bytesSent: z.number()\n});\nconst BrokerDecodedClientSchema = z.object({\n tag: z.string(),\n subscribedAt: z.number(),\n maxFps: z.number(),\n framesDelivered: z.number(),\n framesDropped: z.number()\n});\nconst BrokerAudioClientSchema = z.object({\n tag: z.string(),\n subscribedAt: z.number(),\n chunksDelivered: z.number()\n});\nconst BrokerClientsSchema = z.object({\n rtsp: z.array(BrokerRtspClientSchema).readonly(),\n decoded: z.array(BrokerDecodedClientSchema).readonly(),\n audio: z.array(BrokerAudioClientSchema).readonly(),\n pipeClients: z.number(),\n encodedSubscribers: z.number()\n});\nconst PlaceholderReasonSchema = z.enum([\n \"reconnecting\",\n \"sleeping\",\n \"offline\",\n \"disabled\",\n \"waking\"\n]);\nconst VideoCodecTargetSchema = z.enum([\"H264\", \"H265\", \"auto\"]);\nconst AudioCodecTargetSchema = z.enum([\"AAC\", \"Opus\", \"PCMU\", \"none\"]);\nconst MaxResolutionSchema = z.object({\n width: z.number().int().positive(),\n height: z.number().int().positive()\n});\nconst GetStreamWithCodecInputSchema = z.object({\n deviceId: z.number().int().nonnegative(),\n videoCodec: VideoCodecTargetSchema,\n audioCodec: AudioCodecTargetSchema.optional(),\n maxResolution: MaxResolutionSchema.optional(),\n tag: z.string().optional()\n});\nconst RtpSourceSchema = z.object({\n url: z.string(),\n videoCodec: z.enum([\"H264\", \"H265\"]),\n audioCodec: z.string(),\n resolution: MaxResolutionSchema,\n transcoded: z.boolean(),\n encoder: z.string(),\n pipelineKey: z.string()\n});\nconst streamBrokerCapability = {\n name: \"stream-broker\",\n scope: \"system\",\n mode: \"singleton\",\n exposesDeviceSettings: true,\n methods: {\n publishCameraStream: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n camStreamId: z.string().min(1),\n kind: CamStreamKindSchema,\n url: z.string().optional(),\n codec: z.string().optional(),\n resolution: CamStreamResolutionSchema.optional(),\n fps: z.number().positive().optional(),\n label: z.string().optional(),\n deviceFeatures: z.array(z.string()).optional(),\n autoEligible: z.boolean().optional(),\n metadata: z.record(z.string(), z.unknown()).optional()\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n retractCameraStream: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n camStreamId: z.string().min(1)\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n assignProfile: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n profile: CamProfileSchema,\n camStreamId: z.string().min(1)\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n unassignProfile: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n profile: CamProfileSchema\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n listAllCameraStreams: method(\n z.void(),\n z.array(CameraStreamSchema).readonly()\n ),\n listAllProfileSlots: method(\n z.void(),\n z.array(ProfileSlotSchema).readonly()\n ),\n getBrokerStats: method(\n z.object({ brokerId: z.string() }),\n BrokerStatsSchema\n ),\n listClients: method(\n z.object({ brokerId: z.string() }),\n BrokerClientsSchema\n ),\n killClient: method(\n z.object({\n brokerId: z.string(),\n channel: z.enum([\"rtsp\", \"decoded\", \"audio\"]),\n handle: z.string()\n }),\n z.object({ killed: z.boolean() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n restartProfile: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n profile: CamProfileSchema\n }),\n z.object({ success: z.boolean() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n getStreamUrl: method(\n z.object({ streamId: z.string(), format: StreamFormatSchema }),\n z.object({ url: z.string() })\n ),\n /**\n * Shared codec-targeted stream API — see Task #184.\n * Resolution order: source-select → HW transcode → libx264/libx265.\n */\n getStreamWithCodec: method(\n GetStreamWithCodecInputSchema,\n RtpSourceSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n releaseStreamWithCodec: method(\n z.object({ pipelineKey: z.string() }),\n z.object({ released: z.boolean(), refcount: z.number().int().nonnegative() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n getBroker: method(\n z.object({ brokerId: z.string() }),\n z.custom()\n ),\n setPreBufferDuration: method(\n z.object({ brokerId: z.string(), seconds: z.number().min(0).max(30) }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n getPreBufferInfo: method(\n z.object({ brokerId: z.string() }),\n z.object({ configuredSec: z.number(), bufferedMs: z.number(), packetCount: z.number() })\n ),\n getRtspPort: method(z.void(), z.number()),\n getAllRtspEntries: method(\n z.object({ hostname: z.string().optional() }),\n z.array(RtspRestreamEntrySchema).readonly()\n ),\n getRtspEntry: method(\n z.object({ brokerId: z.string(), hostname: z.string().optional() }),\n RtspRestreamEntrySchema.nullable()\n ),\n regenerateRtspToken: method(\n z.object({ brokerId: z.string() }),\n z.string().nullable(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n setRtspEnabled: method(\n z.object({ brokerId: z.string(), enabled: z.boolean() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n isRtspEnabled: method(\n z.object({ brokerId: z.string() }),\n z.boolean()\n )\n },\n events: {\n onCamStreamDemand: event(z.object({\n deviceId: z.number().int().nonnegative(),\n camStreamId: z.string(),\n profile: CamProfileSchema\n })),\n onCamStreamIdle: event(z.object({\n deviceId: z.number().int().nonnegative(),\n camStreamId: z.string()\n })),\n onRequestStreamSourceRefresh: event(z.object({\n deviceId: z.number().int().nonnegative(),\n camStreamId: z.string(),\n brokerId: z.string()\n }))\n }\n};\nconst cameraStreamsCapability = {\n name: \"camera-streams\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n getCameraStreams: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.array(CameraStreamSchema).readonly()\n ),\n getBrokerStreams: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.array(ProfileSlotSchema).readonly()\n ),\n /**\n * Per-device RTSP restream entries. Returns the broker's published\n * RTSP URLs (one per `${deviceId}/${profile}`) for THIS device only,\n * including the rendered `url` field with the RTSP token applied.\n * Consumers (snapshot wrapper, recording, external probes) use this\n * to pick a stream URL without scanning the whole cluster.\n *\n * The system `stream-broker.getAllRtspEntries({hostname?})` still\n * exists for whole-cluster use cases (admin dashboard, settings\n * exports). This device-scoped accessor is the supported handle for\n * code that already has a `deviceId` in hand — keeps device-keyed\n * filtering server-side and rides the DeviceProxy auto-injection.\n */\n getRtspEntries: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n /** Override hostname embedded in returned URLs. Defaults to the broker's bound address. */\n hostname: z.string().optional()\n }),\n z.array(RtspRestreamEntrySchema).readonly()\n )\n },\n events: {\n /** Fires on publishCameraStream / retractCameraStream. */\n onCamStreamsChanged: event(z.object({\n deviceId: z.number().int().nonnegative(),\n camStreams: z.array(CameraStreamSchema).readonly()\n })),\n /** Fires on assignProfile / unassignProfile / runtime status change. */\n onProfileSlotsChanged: event(z.object({\n deviceId: z.number().int().nonnegative(),\n profileSlots: z.array(ProfileSlotSchema).readonly()\n }))\n },\n /**\n * Per-device live stream-broker state. Persistent settings (RTSP\n * tokens, profile assignments, pre-buffer config, RTSP-enabled toggles,\n * streamingDebug) stay in the broker's addon store — they survive\n * restarts. The slice below carries ONLY what's truly runtime:\n *\n * - `online` — at least one profile slot is currently `'streaming'`.\n * Drivers without a firmware liveness signal (RTSP, ONVIF…) can\n * subscribe and mirror this into `state.deviceStatus.online`.\n * - `slotStatuses` — current `ProfileSlotStatus` per profile,\n * mirroring the runtime-mutable subset of `ProfileSlot`.\n * - `slotErrors` — last error message per profile (only set when the\n * corresponding slot is in `'error'`).\n * - `lastChangedAt` — freshness signal for consumers that want to\n * reason about how stale the slice is.\n *\n * Written by the stream-broker manager on every transition that\n * affects these aggregates. Read via `device.state.cameraStreams.<field>`\n * (BaseDevice proxy) or, cross-process, via\n * `device-state.getCapSlice({deviceId, capName: 'camera-streams'})`.\n * The cap's `onChanged` event fires automatically on each write so\n * subscribers get push semantics for free.\n */\n runtimeState: z.object({\n online: z.boolean(),\n slotStatuses: z.object({\n high: ProfileSlotStatusSchema.optional(),\n mid: ProfileSlotStatusSchema.optional(),\n low: ProfileSlotStatusSchema.optional()\n }),\n slotErrors: z.object({\n high: z.string().optional(),\n mid: z.string().optional(),\n low: z.string().optional()\n }),\n lastChangedAt: z.number()\n })\n};\nconst DiscoveredChildStatusSchema = z.enum([\"online\", \"sleeping\", \"offline\", \"unknown\"]);\nconst DiscoveredChildDeviceSchema = z.object({\n /** Stable, integration-defined identifier. Mirrors Scrypted's `nativeId`. */\n childNativeId: z.string(),\n /** Friendly name as reported by the source (Reolink camera name, ONVIF profile, ...). */\n name: z.string(),\n /** DeviceType the child should be created with on adopt. */\n type: z.enum(DeviceType),\n status: DiscoveredChildStatusSchema,\n /** Free-form integration-specific metadata surfaced in the panel. */\n metadata: z.object({\n model: z.string().optional(),\n serialNumber: z.string().optional(),\n uid: z.string().optional(),\n /** Reolink: 0-based channel index inside the parent NVR/Hub. */\n rtspChannel: z.number().int().nonnegative().optional(),\n isBattery: z.boolean().optional(),\n isDoorbell: z.boolean().optional(),\n isMultifocal: z.boolean().optional()\n }).default({}),\n /**\n * `true` when the framework already created a child device for this\n * `childNativeId` under the current parent. The panel uses it to\n * gate the Add/Remove button and surface the existing `deviceId`.\n */\n alreadyAdopted: z.boolean(),\n /** When `alreadyAdopted=true`, the framework-assigned child device id. */\n adoptedDeviceId: z.number().int().nonnegative().nullable()\n});\nconst DeviceDiscoveryStatusSchema = z.object({\n discovered: z.array(DiscoveredChildDeviceSchema),\n /** Wall-clock ms of the last successful enumeration. */\n lastDiscoveryAt: z.number().int().nonnegative().nullable(),\n /** Last error surfaced from the source (rendered as a banner). */\n lastError: z.string().nullable()\n});\nconst deviceDiscoveryCapability = {\n name: \"device-discovery\",\n scope: \"device\",\n mode: \"singleton\",\n // Hub is the canonical parent. Other integrations (gateway-style)\n // can register against the cap by also targeting their root type.\n deviceTypes: [DeviceType.Hub],\n status: {\n schema: DeviceDiscoveryStatusSchema,\n kind: \"poll\"\n },\n // Mirror status into the per-device runtime-state slice so the panel\n // hydrates from the kernel cache without a round-trip on every open.\n runtimeState: DeviceDiscoveryStatusSchema.extend({\n lastFetchedAt: z.number().int().nonnegative()\n }),\n methods: {\n /**\n * Snapshot of the current `discovered` list. Returns the\n * runtime-state cache — call `refreshDiscovery` first if a\n * fresh round-trip to the source is required.\n */\n listDiscovered: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.array(DiscoveredChildDeviceSchema).readonly()\n ),\n /**\n * Force the integration to re-enumerate and update the\n * runtime-state slice. Returns the freshly-enumerated list (also\n * available via `listDiscovered` post-call).\n */\n refreshDiscovery: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.array(DiscoveredChildDeviceSchema).readonly(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Promote a discovered entry to a real child device. The framework\n * creates the child via `kernel.devices.create()` with\n * `parentDeviceId = parent.id` and seeds the child's config from\n * `childInitialConfig` (driver-defined; usually carries channel +\n * uid + parent reference). Returns the kernel-assigned numeric id.\n */\n adoptDevice: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n childNativeId: z.string(),\n /** Optional override for the child's display name. */\n name: z.string().optional()\n }),\n z.object({\n deviceId: z.number().int().nonnegative(),\n stableId: z.string()\n }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Inverse of `adoptDevice`: removes the child device from the\n * kernel registry. The discovered entry remains in the\n * enumeration (status updates resume) so the operator can re-adopt\n * it later without a fresh refresh.\n */\n releaseDevice: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n childDeviceId: z.number().int().nonnegative()\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst DoorbellStatusSchema = z.object({\n /** Ms epoch of the last press. null = never observed since this provider started. */\n lastPressedAt: z.number().nullable(),\n /** Counter since provider start. Resets on reboot. Useful for metrics/debug. */\n pressCountSinceStart: z.number()\n});\nconst DoorbellPressEventSchema = z.object({\n deviceId: z.number(),\n timestamp: z.number()\n});\nconst doorbellCapability = {\n name: \"doorbell\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Button],\n methods: {},\n events: {\n /**\n * Fires once per physical press. Reolink delivers via Baichuan\n * push (`ReolinkSimpleEvent.type === 'doorbell'`). There is no\n * release/duration — it's a pulse.\n */\n onPressed: { data: DoorbellPressEventSchema }\n },\n status: {\n schema: DoorbellStatusSchema,\n kind: \"push\"\n },\n /**\n * Runtime-state slice — last press timestamp + lifetime press count.\n * Mirrored by the kernel and readable via\n * `device.state.doorbell.value`. UIs can show \"last ring 5m ago\"\n * without subscribing.\n */\n runtimeState: DoorbellStatusSchema\n};\nconst FrameFormatSchema = z.enum([\"jpeg\", \"rgb\", \"bgr\", \"yuv420\", \"gray\"]);\nconst FrameInputSchema = z.object({\n data: z.custom(),\n format: FrameFormatSchema,\n width: z.number(),\n height: z.number(),\n timestamp: z.number()\n});\nconst BoundingBoxSchema = z.object({\n x: z.number(),\n y: z.number(),\n w: z.number(),\n h: z.number()\n});\nconst SpatialDetectionSchema = z.object({\n class: z.string(),\n originalClass: z.string(),\n score: z.number(),\n bbox: BoundingBoxSchema\n});\nconst AudioChunkInputSchema = z.object({\n data: z.instanceof(Float32Array),\n sampleRate: z.number(),\n channels: z.number(),\n timestamp: z.number(),\n /** Originating device id — used by the classifier for per-camera concurrency tracking. */\n deviceId: z.number().optional()\n});\nconst AudioLevelSchema = z.object({\n rms: z.number(),\n dbfs: z.number()\n});\nconst AudioClassificationLabelSchema = z.object({\n /**\n * Primary display class. Depending on how the label was produced\n * this is either the macro category (e.g. `dog`) or the raw\n * backend label (e.g. `Dog bark`). Mirrors `class` on\n * `SpatialDetection`.\n */\n className: z.string(),\n /**\n * Raw backend-native label the classifier actually emitted (e.g.\n * `Dog bark` for YAMNet, `dog_bark` for Apple SoundAnalysis). For\n * macro-aggregated entries this is the top raw contributor. Mirrors\n * `originalClass` on `SpatialDetection`.\n */\n originalClass: z.string().optional(),\n score: z.number()\n});\nconst MotionRegionSchema = z.object({\n bbox: BoundingBoxSchema,\n pixelCount: z.number(),\n intensity: z.number()\n});\nconst MotionAnalysisResultSchema = z.object({\n detected: z.boolean(),\n regionCount: z.number(),\n /** Regions passing minArea filter — used for pipeline triggering. */\n regions: z.array(MotionRegionSchema).readonly(),\n /** All raw regions from CCL before minArea filter — used for UI debug overlay. */\n rawRegions: z.array(MotionRegionSchema).readonly(),\n frameWidth: z.number(),\n frameHeight: z.number(),\n analysisMs: z.number()\n});\nconst motionDetectionCapability = {\n name: \"motion-detection\",\n scope: \"device\",\n mode: \"singleton\",\n exposesDeviceSettings: true,\n methods: {\n analyze: method(\n z.object({ deviceId: z.number(), frame: FrameInputSchema }),\n MotionAnalysisResultSchema,\n { kind: \"mutation\" }\n ),\n removeCamera: method(z.object({ deviceId: z.number() }), z.void(), { kind: \"mutation\" }),\n reset: method(z.void(), z.void(), { kind: \"mutation\" })\n },\n events: {\n onMotion: { data: z.object({\n deviceId: z.number(),\n detected: z.boolean(),\n regionCount: z.number()\n }) }\n }\n};\nconst OrchestratorMetricsSchema = z.object({\n activeCameras: z.number(),\n throttledCameras: z.number(),\n avgInferenceTimeMs: z.number(),\n queueDepth: z.number()\n});\nconst CameraMetricsSchema = z.object({\n detectionMode: z.enum([\"disabled\", \"always-on\", \"on-motion\"]),\n configuredFps: z.number(),\n actualFps: z.number(),\n queueDepth: z.number(),\n avgInferenceTimeMs: z.number(),\n droppedFrames: z.number(),\n phase: z.enum([\"idle\", \"watching\", \"active\"])\n});\nconst CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({\n deviceId: z.number()\n});\nconst ModelFormatSchema$1 = z.enum([\"onnx\", \"coreml\", \"openvino\", \"tflite\", \"pt\"]);\nconst PipelineSlotSchema = z.enum([\"detector\", \"cropper\", \"classifier\", \"refiner\", \"audio-classifier\"]);\nconst PipelineEngineChoiceSchema = z.object({\n runtime: z.enum([\"node\", \"python\"]),\n backend: z.string(),\n format: ModelFormatSchema$1,\n device: z.string().optional()\n});\nconst EngineDeviceInfoSchema = z.object({\n id: z.string(),\n label: z.string(),\n description: z.string().optional()\n});\nconst AvailableEngineSchema = z.object({\n engine: PipelineEngineChoiceSchema,\n devices: z.array(EngineDeviceInfoSchema).readonly(),\n defaultDevice: z.string()\n});\nconst PipelineDefaultStepSchema = z.lazy(\n () => z.object({\n addonId: z.string(),\n addonName: z.string(),\n slot: PipelineSlotSchema,\n inputClasses: z.array(z.string()).readonly(),\n outputClasses: z.array(z.string()).readonly(),\n enabled: z.boolean(),\n modelId: z.string(),\n children: z.array(PipelineDefaultStepSchema).readonly(),\n engine: PipelineEngineChoiceSchema.optional(),\n group: z.string().optional(),\n settings: z.record(z.string(), z.unknown()).optional()\n })\n);\nconst PipelineTemplateStepSchema = z.lazy(\n () => z.object({\n addonId: z.string(),\n enabled: z.boolean(),\n modelId: z.string(),\n children: z.array(PipelineTemplateStepSchema).readonly(),\n settings: z.record(z.string(), z.unknown()).optional()\n })\n);\nconst PipelineTemplateSchema$1 = z.object({\n id: z.string(),\n name: z.string(),\n createdAt: z.string(),\n updatedAt: z.string(),\n engine: PipelineEngineChoiceSchema,\n steps: z.array(PipelineTemplateStepSchema).readonly()\n});\nconst PipelineModelOptionSchema = z.object({\n id: z.string(),\n name: z.string(),\n formats: z.record(\n z.string(),\n z.object({ downloaded: z.boolean(), sizeMB: z.number() })\n )\n});\nconst ConfigFieldBridge = z.custom();\nconst PipelineAddonSchemaSchema = z.object({\n id: z.string(),\n name: z.string(),\n slot: PipelineSlotSchema,\n inputClasses: z.array(z.string()).readonly(),\n outputClasses: z.array(z.string()).readonly(),\n childSlots: z.array(PipelineSlotSchema).readonly(),\n models: z.array(PipelineModelOptionSchema).readonly(),\n defaultModelId: z.string(),\n // Per-format model override. Lets an addon declare \"on `coreml` prefer\n // apple-soundanalysis, on `onnx` prefer yamnet-onnx\". The orchestrator's\n // agent-seed routine uses this to pick a modelId that matches the\n // agent's active engine format.\n defaultModelIdByFormat: z.record(z.string(), z.string()).optional(),\n // Whether a freshly-seeded agent starts with this addon `enabled: true`.\n // Absent = true. Operator-controlled after first seed.\n enabledByDefault: z.boolean().optional(),\n defaultConfidence: z.number(),\n group: z.string().optional(),\n configSchema: z.array(ConfigFieldBridge).readonly().optional()\n});\nconst PipelineSlotSchemaSchema = z.object({\n id: PipelineSlotSchema,\n label: z.string(),\n priority: z.number(),\n parentSlot: PipelineSlotSchema.nullable(),\n addons: z.array(PipelineAddonSchemaSchema).readonly()\n});\nconst PipelineSchemaSchema = z.object({\n availableEngines: z.array(AvailableEngineSchema).readonly(),\n selectedEngine: PipelineEngineChoiceSchema,\n slots: z.array(PipelineSlotSchemaSchema).readonly()\n});\nconst DetectorOutputSchema = z.object({\n detections: z.array(SpatialDetectionSchema).readonly(),\n inferenceMs: z.number(),\n modelId: z.string()\n});\nconst PipelineStepInputSchema = z.lazy(\n () => z.object({\n addonId: z.string(),\n modelId: z.string(),\n enabled: z.boolean().default(true),\n children: z.array(PipelineStepInputSchema).optional(),\n settings: z.record(z.string(), z.unknown()).optional()\n })\n);\nconst ReferenceImageEntrySchema = z.object({\n filename: z.string(),\n stepIds: z.array(z.string()).readonly().optional()\n});\nconst ReferenceImageBodySchema = z.object({\n base64: z.string(),\n filename: z.string()\n});\nconst ReferenceAudioEntrySchema = z.object({\n filename: z.string(),\n sizeKb: z.number()\n});\nconst ReferenceAudioBodySchema = z.object({\n base64: z.string()\n});\nconst AudioBackendSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n available: z.boolean(),\n /**\n * Raw classifier labels this backend can emit (e.g. YAMNet's\n * 521-class set or Apple SoundAnalysis's 303-class set). Used by\n * the benchmark UI to populate the `enabledMicroClasses` filter\n * specific to the selected backend without a separate fetch.\n */\n rawLabels: z.array(z.string()).readonly().optional()\n});\nconst AudioCapabilitiesSchema = z.object({\n activeBackend: z.string(),\n availableBackends: z.array(AudioBackendSchema).readonly(),\n sampleRate: z.number(),\n chunkDurationMs: z.number()\n});\nconst DownloadModelResultSchema = z.object({\n filePath: z.string(),\n sizeMB: z.number(),\n durationMs: z.number()\n});\nconst AudioTestResultSchema = z.object({\n success: z.boolean(),\n error: z.string().optional(),\n frame: z.custom().optional()\n});\nconst PipelineConfigBridge = z.custom();\nconst ConfigUISchemaBridge = z.custom();\nconst ConfigUISchemaNullableBridge = z.custom();\nconst InferenceCapabilitiesBridge = z.custom();\nconst ModelAvailabilityListBridge = z.custom();\nconst PipelineRunResultBridge = z.custom();\nconst pipelineExecutorCapability = {\n name: \"pipeline-executor\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n // ── Engine selection ─────────────────────────────────────────────\n // `setEngine` removed in Phase 6c — the stateless-pipeline model\n // picks engine per-camera, not per-node. `getSelectedEngine` is\n // kept read-only so the benchmark + models-page can still show the\n // executor's bootstrap engine; its semantics degrade to \"what the\n // executor would pick by default\" in the stateless world.\n getAvailableEngines: method(z.void(), z.array(PipelineEngineChoiceSchema)),\n getSelectedEngine: method(z.void(), PipelineEngineChoiceSchema),\n getDefaultSteps: method(PipelineEngineChoiceSchema, z.array(PipelineDefaultStepSchema)),\n /**\n * Re-run the platform probe for the inference engine and write the\n * detected runtime / backend / device back into the addon's own\n * global settings store. Returns the engine that was picked so the\n * UI can confirm without a second round-trip. Triggers the standard\n * `requiresRestart` auto-restart flow because all three fields are\n * marked restart-required. Replaces the legacy per-agent\n * `pipeline-orchestrator.reprobeAgentHwAccel` surface for the\n * engine dimension — each addon now owns its own probe.\n */\n reprobeEngine: method(z.void(), PipelineEngineChoiceSchema, { kind: \"mutation\", auth: \"admin\" }),\n // ── Video pipeline step configuration (phase 2c) ─────────────────\n // Per-addonId config the operator tunes on the Pipeline → agent\n // page. Replaces the orchestrator's per-agent\n // `setAgentAddonDefaults` mutation. No `enabled` flag — the cap\n // binding system (wrapper caps + setWrapperActive) decides whether\n // a step runs.\n getVideoPipelineSteps: method(\n z.void(),\n z.record(z.string(), z.object({\n modelId: z.string(),\n settings: z.record(z.string(), z.unknown()).readonly()\n }))\n ),\n setVideoPipelineSteps: method(\n z.object({\n steps: z.record(z.string(), z.object({\n modelId: z.string(),\n settings: z.record(z.string(), z.unknown()).readonly()\n }))\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Global pipeline configuration ────────────────────────────────\n // `setGlobalSteps` removed in Phase 6c — there is no \"global\n // pipeline\" in the stateless model (each camera carries its own\n // steps via the orchestrator's `pipelines/<deviceId>`).\n // `getGlobalSteps` is kept read-only as a benchmark fallback;\n // it returns null in fresh stateless deploys.\n getSchema: method(z.void(), PipelineSchemaSchema),\n getGlobalSteps: method(z.void(), z.array(PipelineDefaultStepSchema).readonly().nullable()),\n getGlobalPipelineConfig: method(z.void(), PipelineConfigBridge),\n getOrchestratorConfigSchema: method(z.void(), ConfigUISchemaBridge),\n // ── Templates ────────────────────────────────────────────────────\n listTemplates: method(z.void(), z.array(PipelineTemplateSchema$1).readonly()),\n saveTemplate: method(\n z.object({\n name: z.string(),\n steps: z.array(PipelineTemplateStepSchema).readonly(),\n engine: PipelineEngineChoiceSchema\n }),\n PipelineTemplateSchema$1,\n { kind: \"mutation\" }\n ),\n updateTemplate: method(\n z.object({\n id: z.string(),\n name: z.string().optional(),\n steps: z.array(PipelineTemplateStepSchema).readonly().optional()\n }),\n PipelineTemplateSchema$1,\n { kind: \"mutation\" }\n ),\n deleteTemplate: method(z.object({ id: z.string() }), z.void(), { kind: \"mutation\" }),\n // ── Inference / detection ────────────────────────────────────────\n getCapabilities: method(z.void(), InferenceCapabilitiesBridge),\n getAddonModels: method(z.object({ addonId: z.string() }), ModelAvailabilityListBridge),\n downloadModel: method(\n z.object({ addonId: z.string(), modelId: z.string(), format: ModelFormatSchema$1 }),\n DownloadModelResultSchema,\n { kind: \"mutation\" }\n ),\n deleteModel: method(\n z.object({ addonId: z.string(), modelId: z.string(), format: ModelFormatSchema$1 }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\" }\n ),\n // NOTE: onDownloadProgress / onPipelineProgress removed in Fase H.4.\n // Consumers subscribe via the generic `live.onEvent` core router with\n // `{category: 'model.download.progress'}` or `{category: 'pipeline.progress'}`\n // — the event bus already handles category filtering, no dedicated\n // pipeline-executor method needed.\n detect: method(\n z.object({ addonId: z.string(), frame: FrameInputSchema, config: z.record(z.string(), z.unknown()).optional() }),\n DetectorOutputSchema\n ),\n // `runFrame` removed in Phase 4 — runtime dispatch now goes through\n // the stateless `runPipeline({engine, steps, frame, deviceId})` path.\n // The runner hydrates `steps` from the orchestrator's attach payload\n // (`pipelines[deviceId]`), so there is no longer an executor-side\n // global \"current pipeline\" for a legacy `runFrame` call to target.\n /**\n * Stateless single-frame execution. Callers (runner, benchmark) pass\n * the complete `engine` + `steps` tree; the executor holds no state\n * about cameras or saved pipelines.\n *\n * `engine` is optional during the migration window to preserve the\n * legacy call shape used by existing benchmark code; once all\n * callers pass it explicitly we make it required.\n *\n * Exactly one of `frame`, `imageBase64`, `referenceImage` must be\n * provided:\n * - `frame`: runtime dispatch path (runner → decoded broker frame).\n * Carries the raw buffer, dimensions, and format; the executor\n * uses it directly without base64 round-tripping.\n * - `imageBase64`: one-shot test path (benchmark ImageTab).\n * - `referenceImage`: named file from the reference-image store.\n */\n runPipeline: method(\n z.object({\n engine: PipelineEngineChoiceSchema.optional(),\n steps: z.array(PipelineStepInputSchema).min(1),\n frame: FrameInputSchema.optional(),\n imageBase64: z.string().optional(),\n /**\n * Binary JPEG bytes — preferred over `imageBase64` on internal\n * hops (hub → forked worker via Moleculer MsgPack) because it\n * skips the 33% base64 overhead + the per-call base64 decode on\n * the detection-pipeline worker. Callers can pass either; exactly\n * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.\n */\n image: z.instanceof(Uint8Array).optional(),\n referenceImage: z.string().optional(),\n deviceId: z.number().optional(),\n sessionId: z.string().optional()\n }),\n PipelineRunResultBridge,\n { kind: \"mutation\" }\n ),\n /**\n * Batched run — N raw frames packed into one cap call. The provider\n * routes the batch through `SharedInferencePool.inferBatch`\n * (`MSG_INFER_BATCH = 0x03`) so the IPC framing and JSON response\n * envelope cost is amortised N:1 vs N concurrent `runPipeline`\n * calls. Single root step + uniform model assumed; trees with crop\n * children fall back to sequential execution.\n *\n * Used by `scripts/bench-scrypted-style.mts` to mirror Scrypted's\n * `detectObjects(media, {batch})` semantics for fair comparison.\n */\n runPipelineBatch: method(\n z.object({\n engine: PipelineEngineChoiceSchema.optional(),\n steps: z.array(PipelineStepInputSchema).min(1),\n frames: z.array(FrameInputSchema).min(1).max(255),\n deviceId: z.number().optional(),\n sessionId: z.string().optional()\n }),\n z.object({\n results: z.array(PipelineRunResultBridge).readonly()\n }),\n { kind: \"mutation\" }\n ),\n // ── Bench frame cache (Python pool-side) ──────────────────────────\n /**\n * Cache a raw frame inside the Python inference pool's memory.\n * Returns a numeric `frameId` that `inferCached` references —\n * subsequent calls send only 5 bytes through the pipe instead of\n * 1.2MB raw data, eliminating the pipe transfer bottleneck.\n */\n cacheFrameInPool: method(\n z.object({\n data: z.instanceof(Uint8Array),\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n format: z.enum([\"rgb\", \"bgr\", \"gray\"])\n }),\n z.object({\n frameId: z.number(),\n width: z.number(),\n height: z.number()\n }),\n { kind: \"mutation\" }\n ),\n /**\n * Run inference on a previously cached frame. Sends only 5 bytes\n * (model_idx + frameId) through the IPC pipe — eliminates the\n * ~35ms per-call overhead of transferring 1.2MB raw data.\n */\n inferCached: method(\n z.object({\n stepId: z.string(),\n frameId: z.number().int()\n }),\n z.record(z.string(), z.unknown()),\n { kind: \"mutation\" }\n ),\n /**\n * Release a cached frame from the Python pool's memory.\n */\n uncacheFrame: method(\n z.object({ frameId: z.number().int() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /** Returns the effective pool tuning (resolved from user overrides + backend defaults). */\n getEffectiveTuning: method(\n z.void(),\n z.object({\n batchMode: z.string(),\n windowMs: z.number(),\n maxBatchSize: z.number(),\n concurrency: z.number()\n })\n ),\n // ── Engine registry / management (stateless-pipeline spec) ────────\n /**\n * List every EngineFactory currently loaded in this executor's RAM,\n * with the models resident and a coarse \"in use\" marker derived from\n * ongoing inference activity. Used by the Pipeline page Engines tab.\n */\n listLoadedEngines: method(\n z.void(),\n z.array(z.object({\n engineKey: z.string(),\n engine: PipelineEngineChoiceSchema,\n modelsLoaded: z.array(z.string()).readonly(),\n inUseByCameras: z.array(z.number()).readonly(),\n /**\n * Origin of this resident factory.\n * - `runtime` — main camera-serving engine (no idle TTL).\n * - `warm-override` — benchmark/test override held in the warm\n * cache; auto-disposed after the idle TTL.\n */\n kind: z.enum([\"runtime\", \"warm-override\"]),\n /** Native pid of the underlying Python pool (null when no pool). */\n poolPid: z.number().nullable(),\n /** ms since this factory was last used (null when not warm-tracked). */\n idleMs: z.number().nullable(),\n /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */\n idleTtlMs: z.number().nullable()\n })).readonly()\n ),\n /** Warm up an engine without running a frame. No-op if already loaded. */\n spinEngine: method(\n z.object({ engine: PipelineEngineChoiceSchema }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Unload an engine from RAM. `force:true` unloads even when cameras\n * are actively using it (they re-spin on next frame). Default is\n * gated — returns `{success:false, reason}` when in use.\n */\n killEngine: method(\n z.object({\n engine: PipelineEngineChoiceSchema,\n force: z.boolean().optional()\n }),\n z.object({ success: z.boolean(), reason: z.string().optional() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Benchmarks & testing ─────────────────────────────────────────\n // Moved to `@camstack/addon-benchmark` as customActions (2026-04-14).\n // The addon exposes runBenchmark / runPipelineTest / listBenchmarkHistory /\n // saveBenchmarkResult / deleteBenchmarkResult / clearBenchmarkHistory via\n // `api.addons.custom.mutate({addonId: 'benchmark', action, input})` and\n // delegates the actual pipeline execution back to this cap's runPipeline.\n // ── Reference media ──────────────────────────────────────────────\n listReferenceImages: method(z.void(), z.array(ReferenceImageEntrySchema).readonly()),\n getReferenceImage: method(z.object({ filename: z.string() }), ReferenceImageBodySchema.nullable()),\n getReferenceAudioFiles: method(z.void(), z.array(ReferenceAudioEntrySchema).readonly()),\n getReferenceAudio: method(z.object({ filename: z.string() }), ReferenceAudioBodySchema.nullable()),\n getAudioCapabilities: method(z.void(), AudioCapabilitiesSchema),\n runAudioTest: method(\n z.object({\n addonId: z.string(),\n modelId: z.string(),\n filename: z.string().optional(),\n // Per-step settings (e.g. `enabledClasses`) sourced from the\n // audio-classifier step's `getConfigSchema()`. The provider\n // applies them to the classification result before returning.\n settings: z.record(z.string(), z.unknown()).optional()\n }),\n AudioTestResultSchema,\n { kind: \"mutation\" }\n ),\n // ── Detection wiring / metrics (from detection-config) ───────────\n getDetectionConfigSchema: method(z.void(), ConfigUISchemaNullableBridge)\n // NOTE: orchestratorStatus / cameraDetectionStatus removed in the\n // pipeline page redesign — UI reads runner metrics directly via\n // perNodePipeline.getLocalMetrics / getCameraMetrics, which forward\n // to the pipeline-runner cap on the target node.\n //\n // NOTE: listBrokers / brokerStatus used to live here too — removed in\n // Fase H.3. Frontends now call `streamBroker.listBrokers` directly and\n // filter by deviceId client-side (brokerId prefix match). The broker\n // collection lives in the stream-broker capability and there is no\n // reason for pipeline-executor to mirror it.\n //\n // NOTE: subscribeLive / subscribeAudioLive removed in Fase H.4.\n // Consumers use the generic `live.onEvent` / `live.onDeviceEvent`\n // with `{category: 'pipeline.progress' | 'pipeline.inference-result'\n // | 'pipeline.audio-inference-result'}`.\n // Per-device pipeline step CRUD (`getDevicePipelineSteps` /\n // `setDevicePipelineSteps` / `clearDevicePipelineSteps`) removed in\n // Phase 4b. The orchestrator owns per-camera pipeline content now\n // (`pipelineOrchestrator.{get,set}CameraPipeline` +\n // `pipelines/<deviceId>` in its addon store). The executor is\n // stateless w.r.t. cameras — it receives `steps` inline on every\n // `runPipeline` call.\n }\n};\nconst ZoneKindEnum = z.enum([\"polygon\", \"tripwire\"]);\nconst PolygonPointSchema = z.object({\n x: z.number(),\n y: z.number()\n});\nconst ZoneSchema = z.object({\n id: z.string(),\n name: z.string(),\n kind: ZoneKindEnum.default(\"polygon\"),\n /** Polygon vertices, fraction of frame (0–1). */\n polygon: z.array(PolygonPointSchema).readonly(),\n /** Visual color for UI rendering. */\n color: z.string().default(\"#3b82f6\")\n});\nconst zonesCapability = {\n name: \"zones\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n listZones: method(\n z.object({ deviceId: z.number() }),\n z.array(ZoneSchema).readonly()\n ),\n addZone: method(\n z.object({ deviceId: z.number(), zone: ZoneSchema }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n removeZone: method(\n z.object({ deviceId: z.number(), zoneId: z.string() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n updateZone: method(\n z.object({ deviceId: z.number(), zone: ZoneSchema }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n },\n /**\n * Runtime-state slice — the live zone catalogue mirrored by the\n * orchestrator on every CRUD mutation. Consumers read via\n * `device.state.zones.value` / `.watch(...)` without round-tripping\n * the cap, and the codegen DeviceProxy auto-wires the reactive\n * handle. Slice shape is `{ zones: Zone[] }` so future extensions\n * (e.g. zone groupings) can sit alongside the polygon list.\n */\n runtimeState: z.object({\n zones: z.array(ZoneSchema).readonly()\n })\n};\nconst motionCooldownMsField = { min: 0, max: 6e4, default: 3e4, step: 500 };\nconst motionFpsField = { min: 1, max: 30, default: 4, step: 1 };\nconst detectionFpsField = { min: 1, max: 30, default: 10, step: 1 };\nconst MotionSourceEnum = z.enum([\"onboard\", \"analyzer\"]);\nconst MotionSourcesSchema = z.array(MotionSourceEnum);\nconst ReportMotionInputSchema = z.object({\n deviceId: z.number(),\n detected: z.boolean(),\n source: MotionSourceEnum.default(\"analyzer\"),\n regions: z.array(MotionRegionSchema).readonly().optional()\n});\nconst RunnerCameraConfigSchema = z.object({\n deviceId: z.number(),\n /**\n * Operator-facing scheduling mode for the SW object detection\n * pipeline. Replaces the legacy 2-state `priority` toggle.\n *\n * - `'disabled'` — runner never subscribes to the substream for\n * detection; phase stays idle. Bindings stay\n * bound; this is the runtime-level off switch.\n * - `'always-on'` — phase starts in `'active'` and never falls\n * back to `'watching'`.\n * - `'on-motion'` — phase starts in `'watching'`; transitions to\n * `'active'` when a motion source fires; falls\n * back to `'watching'` after `motionCooldownMs`.\n */\n detectionMode: z.enum([\"disabled\", \"always-on\", \"on-motion\"]).default(\"on-motion\"),\n /** Audio scheduling mode — same values as `detectionMode`. The\n * audio-analyzer addon reads this to decide whether to subscribe\n * to the audio decoded stream. */\n audioMode: z.enum([\"disabled\", \"always-on\", \"on-motion\"]).default(\"always-on\"),\n motionCooldownMs: z.number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),\n motionFps: z.number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),\n detectionFps: z.number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),\n motionStreamId: z.string(),\n detectionStreamId: z.string(),\n /**\n * Motion sources that can activate the pipeline. At least one must\n * be present. Multiple sources OR-ed: any one firing arms the\n * cooldown timer and transitions watching → active. The same\n * `motionCooldownMs` applies to whichever source(s) fire — the\n * timer rearms on every `reportMotion(true)` and expires after the\n * window, returning the runner to `watching`.\n *\n * - `analyzer`: ML/frame-diff motion detection (motion-wasm or other\n * analyzer providers) running on decoded frames in this runner.\n * - `onboard`: camera-native motion pushes (Reolink Baichuan, ONVIF\n * analytics, Frigate motion). The provider emits ProviderMotion\n * events; the orchestrator forwards to `reportMotion`.\n */\n motionSources: MotionSourcesSchema.default([\"analyzer\"]),\n pipelineEnabled: z.boolean().default(true),\n // ── Stateless-pipeline: content carried with the attach ───────────\n /** Engine choice for video steps (runtime+backend+format). */\n engine: PipelineEngineChoiceSchema.optional(),\n /** Ordered tree of video steps. Absent → runner skips video detection. */\n steps: z.array(PipelineStepInputSchema).readonly().optional(),\n /** Audio classification branch. `enabled:false` disables, null skips. */\n audio: z.object({\n engine: PipelineEngineChoiceSchema,\n modelId: z.string(),\n enabled: z.boolean()\n }).nullable().optional(),\n /**\n * Per-camera detection zones (user + onboard) snapshot at dispatch\n * time. Forwarded so motion-wasm + pipeline-executor running on the\n * runner can apply include/exclude/monitor logic without an extra\n * round-trip to the hub. The orchestrator re-dispatches the camera\n * whenever its `zones` device-state slice changes, so the runner's\n * copy stays in sync. Empty array → no zone filtering.\n */\n zones: z.array(ZoneSchema).readonly().default([])\n});\nconst RunnerCameraDeviceUIFields = [\n {\n key: \"motionSources\",\n type: \"multiselect\",\n label: \"Motion Sources\",\n default: [\"analyzer\"],\n options: [\n { value: \"analyzer\", label: \"Frame-diff Analyzer (motion addon)\" },\n { value: \"onboard\", label: \"Camera Onboard Sensor\" }\n ]\n },\n // Analyzer-only knobs — gated on `motionSources` containing the\n // `analyzer` (frame-diff) source. When the operator picks\n // `onboard`-only (camera-native VMD), running an analyzer pipeline\n // would burn CPU for no signal, so we hide the FPS / cooldown /\n // stream-profile tuning entirely. The dependent section header in\n // the orchestrator reads \"Frame-diff Analyzer\" → these fields\n // disappear together when the source isn't selected.\n {\n key: \"motionFps\",\n type: \"slider\",\n label: \"Motion FPS (analyzer)\",\n min: motionFpsField.min,\n max: motionFpsField.max,\n step: motionFpsField.step,\n default: motionFpsField.default,\n showValue: true,\n unit: \"fps\",\n showWhen: { field: \"motionSources\", includes: \"analyzer\" }\n },\n {\n key: \"detectionFps\",\n type: \"slider\",\n label: \"Detection FPS\",\n min: detectionFpsField.min,\n max: detectionFpsField.max,\n step: detectionFpsField.step,\n default: detectionFpsField.default,\n showValue: true,\n unit: \"fps\"\n },\n // Motion cooldown applies to BOTH analyzer and onboard sources —\n // every reportMotion(true) re-arms the cooldown regardless of the\n // emitting source, so the operator must be able to tune it for\n // onboard-only cameras too. Without this the field silently\n // disappeared when the user picked \"Camera Onboard Sensor\" only.\n {\n key: \"motionCooldownMs\",\n type: \"slider\",\n label: \"Motion Cooldown\",\n description: \"Time without a fresh motion event before the active phase ends. Applies to all motion sources — every motion event re-arms the timer.\",\n min: motionCooldownMsField.min,\n max: motionCooldownMsField.max,\n step: motionCooldownMsField.step,\n default: motionCooldownMsField.default,\n showValue: true,\n unit: \"s\",\n displayScale: 1e3\n }\n];\nconst RunnerLocalLoadSchema = z.object({\n /** Moleculer node id of this runner instance. */\n nodeId: z.string(),\n /** Total cameras currently attached (regardless of phase). */\n attachedCameras: z.number(),\n /** Cameras currently in `active` phase (running detection inference). */\n activeCameras: z.number(),\n /** Average inference FPS across all attached cameras. */\n avgInferenceFps: z.number(),\n /** Average inference latency in ms across all attached cameras. */\n avgInferenceTimeMs: z.number(),\n /** Total queue depth across motion + detection queues. */\n queueDepthTotal: z.number(),\n /** Hardware capability flags reported by this node. */\n hardware: z.object({\n hasGpu: z.boolean(),\n inferenceBackend: z.string().optional(),\n cpuCores: z.number().optional()\n })\n});\nconst RunnerLocalMetricsSchema = z.object({\n nodeId: z.string(),\n activeCameras: z.number(),\n throttledCameras: z.number(),\n avgInferenceTimeMs: z.number(),\n queueDepth: z.number()\n});\nconst pipelineRunnerCapability = {\n name: \"pipeline-runner\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n // ── Camera lifecycle (called by orchestrator) ────────────────────\n /** Attach a camera to this runner. Subscribes to local broker. */\n attachCamera: method(RunnerCameraConfigSchema, z.object({ success: z.literal(true) }), { kind: \"mutation\" }),\n /** Detach a camera. Unsubscribes from local broker, clears queues. */\n detachCamera: method(z.object({ deviceId: z.number() }), z.object({ success: z.literal(true) }), { kind: \"mutation\" }),\n /**\n * Report an external motion event for a camera. Drives the runner's\n * phase machine: every `detected: true` clears + rearms the\n * cooldown timer (`motionCooldownMs`); when the timer expires the\n * camera returns to `watching`. `detected: false` is a no-op —\n * onboard sources never send an explicit clear, the timer is the\n * single closure path.\n *\n * `source` discriminates which motion path triggered the event so\n * the runner can attach the right metadata to the cap-state event\n * (analyzer carries `regions[]`, onboard does not). `regions` is\n * populated only for `source: 'analyzer'` — the analyzer's\n * frame-diff result. Always-on cameras silently ignore\n * reportMotion calls.\n */\n reportMotion: method(\n ReportMotionInputSchema,\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\" }\n ),\n // ── Observability (called by orchestrator + dashboards) ──────────\n /** Return load summary used by the orchestrator's load balancer. */\n getLocalLoad: method(z.void(), RunnerLocalLoadSchema),\n /** Return aggregate runtime metrics for this runner instance. */\n getLocalMetrics: method(z.void(), RunnerLocalMetricsSchema),\n /** Per-camera metrics for cameras attached to this runner. */\n getCameraMetrics: method(z.object({ deviceId: z.number() }), CameraMetricsSchema.nullable()),\n /** All per-camera metrics in one round-trip. */\n getAllCameraMetrics: method(z.void(), z.array(CameraMetricsWithDeviceIdSchema).readonly()),\n /** List the deviceIds currently attached to this runner. */\n getLocalCameras: method(z.void(), z.array(z.number()).readonly())\n // NOTE: Phase 6 (settings redesign) removed `getTuning` / `setTuning`.\n // The four tuning fields are now exposed via the addon-level settings\n // API (`pipeline-runner.getAddonSettings / updateAddonSettings`) and\n // rendered in the admin UI via `NodeAddonsSettingsPanel` instead of\n // the dedicated `NodeTuningTab` that used to call these cap methods.\n }\n};\nconst MotionStatusSchema = z.object({\n detected: z.boolean(),\n /** Ms epoch of the last detected-true observation. Null if never detected. */\n lastDetectedAt: z.number().nullable(),\n /**\n * Ms after which `detected` auto-reverts to false if no fresh push\n * arrives. Mirrors the scrypted-reolink-native default. Null means\n * the provider leaves detected state until a native \"clear\" event.\n */\n autoClearAfterMs: z.number().nullable()\n});\nconst MotionOnMotionChangedDataSchema = z.object({\n deviceId: z.number(),\n detected: z.boolean(),\n timestamp: z.number(),\n source: MotionSourceEnum,\n regions: z.array(MotionRegionSchema).readonly().optional()\n});\nconst motionCapability = {\n name: \"motion\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera, DeviceType.Sensor],\n methods: {\n /**\n * Pull the current motion state synchronously. Convenience shortcut\n * for consumers that don't need the full status object; equivalent\n * to `getStatus()?.detected ?? false`. Will likely be folded into\n * `getStatus` once the auto-injected status surface lands in every\n * consumer.\n */\n isDetected: method(\n z.object({ deviceId: z.number() }),\n z.boolean()\n )\n },\n events: {\n /**\n * Fires every time the runner transitions a camera between\n * `watching` and `active` phases. `source` carries which motion\n * path drove the transition; `regions` is populated only for\n * `source: 'analyzer'` (frame-diff regions from the ML motion\n * detector) — onboard sources don't carry per-frame regions\n * here (camera-provided zones / AI metadata live in dedicated\n * channels: `detection.camera-native`, future zone capability).\n *\n * Consumers that want all motion pushes (even with `detected`\n * unchanged) should subscribe to the status subscription via\n * `device-manager.subscribeDeviceStatusAggregate` instead.\n */\n onMotionChanged: { data: MotionOnMotionChangedDataSchema }\n },\n status: {\n schema: MotionStatusSchema,\n kind: \"push\"\n },\n /**\n * Runtime-state slice — the last observed motion snapshot, mirrored\n * by the kernel and readable cross-process via\n * `device.state.motion.value`. Reads never invoke the provider, so\n * UIs and other addons can poll the cached state safely.\n */\n runtimeState: MotionStatusSchema\n};\nconst MotionTriggerStatusSchema = z.object({\n enabled: z.boolean(),\n /** Ms epoch of the last operator-driven change. */\n lastChangedAt: z.number()\n});\nconst MotionTriggerRuntimeStateSchema = MotionTriggerStatusSchema.extend({\n /** Ms epoch of the last successful camera fetch (0 = never). */\n lastFetchedAt: z.number()\n});\nconst motionTriggerCapability = {\n name: \"motion-trigger\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Light, DeviceType.Siren, DeviceType.Switch],\n methods: {\n setMotionTrigger: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n enabled: z.boolean()\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n },\n events: {\n onMotionTriggerChanged: { data: z.object({\n deviceId: z.number(),\n enabled: z.boolean(),\n lastChangedAt: z.number()\n }) }\n },\n status: {\n schema: MotionTriggerStatusSchema,\n kind: \"command-driven\"\n },\n runtimeState: MotionTriggerRuntimeStateSchema\n};\nconst AutotrackTargetTypeSchema = z.string().describe(\"Vendor target string (people/vehicle/pet); empty = camera default\");\nconst PtzAutotrackSettingsSchema = z.object({\n targetType: AutotrackTargetTypeSchema,\n stopDelaySeconds: z.number().int().min(0).max(300),\n disappearDelaySeconds: z.number().int().min(0).max(300)\n});\nconst PtzAutotrackTargetOptionSchema = z.object({\n value: z.string(),\n label: z.string()\n});\nconst PtzAutotrackStatusSchema = z.object({\n /** True when autotrack is currently armed on the camera. */\n enabled: z.boolean(),\n /** Ms epoch of the last on/off transition (0 if never observed). */\n lastChangedAt: z.number(),\n /** Currently-applied settings the camera reports. Drivers fill\n * this from the firmware GET so the UI can echo what's *really*\n * active vs the operator-typed values in the settings form. */\n currentSettings: PtzAutotrackSettingsSchema.nullable(),\n /**\n * Target types the camera advertises. Driver-supplied — Reolink\n * exposes `people` / `vehicle` / `pet`, Hikvision exposes\n * `auto` / `human` / `vehicle` when the `<smartTrackingType>` knob\n * is supported. Empty array = vendor doesn't expose a selector\n * (treat as auto-only). The UI renders these as the `targetType`\n * field options without hardcoding a vendor-specific list.\n */\n supportedTargetTypes: z.array(PtzAutotrackTargetOptionSchema)\n});\nconst PtzAutotrackRuntimeStateSchema = PtzAutotrackStatusSchema.extend({\n /** Ms epoch of the last successful camera fetch (0 = never). */\n lastFetchedAt: z.number()\n});\nconst ptzAutotrackCapability = {\n name: \"ptz-autotrack\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n /**\n * Read the current on/off state + last-applied settings.\n * Drivers may serve from a cache + refresh on a schedule —\n * callers should NOT poll faster than ~5s.\n */\n getStatus: method(\n z.object({ deviceId: z.number() }),\n PtzAutotrackStatusSchema\n ),\n /**\n * Arm or disarm autotrack. Resolves once the camera has\n * acknowledged the transition; the `onStatusChanged` event\n * fires shortly after with the live state.\n */\n setEnabled: method(\n z.object({ deviceId: z.number(), enabled: z.boolean() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /**\n * Read settings (target type + delays). Mirrors the\n * `getStatus().currentSettings` payload but exposes it as a\n * standalone read for callers that want settings without the\n * status surface around them. `null` until the driver has\n * harvested the firmware state at least once.\n */\n getSettings: method(\n z.object({ deviceId: z.number() }),\n PtzAutotrackSettingsSchema.nullable()\n ),\n /**\n * Update one or more settings. Partial — keys that aren't\n * supplied keep their last persisted value. The driver is\n * responsible for clamping vendor-specific ranges if narrower\n * than the cross-vendor max declared on the schema.\n */\n setSettings: method(\n z.object({\n deviceId: z.number(),\n settings: PtzAutotrackSettingsSchema.partial()\n }),\n z.void(),\n { kind: \"mutation\" }\n )\n },\n events: {\n onStatusChanged: { data: z.object({\n deviceId: z.number(),\n status: PtzAutotrackStatusSchema\n }) }\n },\n status: {\n schema: PtzAutotrackStatusSchema,\n kind: \"command-driven\"\n },\n /**\n * Persistent slice mirrored across restarts. The provider writes\n * here on every successful firmware fetch / settings push;\n * `getStatus` and `getSettings` then read this snapshot synchronously\n * with a stale-driven async refresh in the background. Keeps the\n * fetch / cache / fallback logic out of the four cap methods —\n * they become trampolines over `runtimeState`.\n */\n runtimeState: PtzAutotrackRuntimeStateSchema\n};\nconst SwitchStatusSchema = z.object({\n on: z.boolean(),\n /** Ms epoch of the last state change. Useful for UI \"X minutes ago\". */\n lastChangedAt: z.number()\n});\nconst switchCapability = {\n name: \"switch\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Switch, DeviceType.Siren, DeviceType.Light],\n methods: {\n setState: method(\n z.object({ deviceId: z.number(), on: z.boolean() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n },\n events: {\n onStateChanged: { data: z.object({\n deviceId: z.number(),\n on: z.boolean(),\n lastChangedAt: z.number()\n }) }\n },\n status: {\n schema: SwitchStatusSchema,\n kind: \"command-driven\"\n },\n /**\n * Runtime-state slice — the last applied on/off state, mirrored by\n * the kernel. Read via `device.state.switch.value`; UI toggles do\n * not need to re-query the provider after a setState mutation.\n */\n runtimeState: SwitchStatusSchema,\n settings: {\n bindings: [{\n kind: \"scalar\",\n statusPath: \"on\",\n method: \"setState\",\n valueArg: \"on\",\n field: { label: \"On\", kind: \"boolean\" }\n }]\n }\n};\nconst PerScopeBreakdownSchema = z.object({\n /** Total tracked objects in this scope (frame / zone / unzoned). */\n totalObjects: z.number().int().nonnegative(),\n /** Per-class count. Keys are macro class names (e.g. `person`, `car`). */\n byClass: z.record(z.string(), z.number().int().nonnegative())\n});\nconst ZoneScopeBreakdownSchema = PerScopeBreakdownSchema.extend({\n zoneId: z.string(),\n zoneName: z.string(),\n /** TrackIds of objects currently inside this zone — for cross-reference\n * with the per-track detail panel and live overlay. */\n trackIds: z.array(z.string()).readonly()\n});\nconst CameraOccupancySnapshotSchema = z.object({\n /** Frame timestamp of the inference result that produced this snapshot. */\n ts: z.number().int(),\n /** Frame width/height in pixels — let the UI normalize bbox coords. */\n frameWidth: z.number().int().nonnegative(),\n frameHeight: z.number().int().nonnegative(),\n /** Per-zone breakdown — one entry per defined zone (user + onboard). */\n zones: z.array(ZoneScopeBreakdownSchema).readonly(),\n /** Frame-wide aggregate (everywhere, regardless of zone membership). */\n frame: PerScopeBreakdownSchema,\n /** Detections that landed outside every zone. Empty when no zones defined. */\n unzoned: PerScopeBreakdownSchema\n});\nconst HistoryResolutionEnum = z.enum([\"minute\", \"5min\", \"hour\"]);\nconst HistoryRangeSchema = z.object({\n /** Range start (epoch ms, inclusive). */\n from: z.number().int(),\n /** Range end (epoch ms, inclusive). Defaults to \"now\" at query time. */\n to: z.number().int(),\n resolution: HistoryResolutionEnum\n});\nconst HistoryPointSchema = z.object({\n /** Bucket midpoint (epoch ms). */\n ts: z.number().int(),\n /** Object count averaged over the bucket (rounded to nearest integer). */\n count: z.number().int().nonnegative()\n});\nconst zoneAnalyticsCapability = {\n name: \"zone-analytics\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n /** Latest computed occupancy snapshot for this camera. Null when\n * the analytics pipeline hasn't seen a frame for this device yet\n * (no inference result emitted since boot or since binding was\n * activated). */\n getCurrentSnapshot: method(\n z.object({ deviceId: z.number() }),\n CameraOccupancySnapshotSchema.nullable()\n ),\n /** Time-series object count inside one zone. `className` optional —\n * omit to count every class in the zone. */\n getZoneHistory: method(\n z.object({\n deviceId: z.number(),\n zoneId: z.string(),\n className: z.string().optional()\n }).extend(HistoryRangeSchema.shape),\n z.array(HistoryPointSchema).readonly()\n ),\n /** Time-series frame-wide object count (everywhere). */\n getCameraHistory: method(\n z.object({\n deviceId: z.number(),\n className: z.string().optional()\n }).extend(HistoryRangeSchema.shape),\n z.array(HistoryPointSchema).readonly()\n ),\n /** Time-series count of objects outside every zone. */\n getUnzonedHistory: method(\n z.object({\n deviceId: z.number(),\n className: z.string().optional()\n }).extend(HistoryRangeSchema.shape),\n z.array(HistoryPointSchema).readonly()\n )\n },\n /**\n * Runtime-state slice — the latest occupancy snapshot mirrored by\n * the analytics frame processor on every inference result. Consumers\n * read via `device.state.zoneAnalytics.value` and stay in sync\n * automatically; the explicit `getCurrentSnapshot` cap method is\n * still useful for one-off polls without a subscription.\n */\n runtimeState: CameraOccupancySnapshotSchema\n};\nconst ZoneRuleModeEnum = z.enum([\"include\", \"exclude\"]);\nconst ZoneRuleSchema = z.object({\n /** Stable rule id — survives edits, used by the UI for diffing. */\n id: z.string(),\n /** Optional human-readable label rendered in the rule editor. */\n name: z.string().optional(),\n /** Zones this rule targets. The rule's `mode` applies to ALL\n * listed zones (OR-set: a detection in any one of them counts).\n * At least one zone id required — a rule with no targets is a\n * configuration mistake and the form validator rejects it. */\n zoneIds: z.array(z.string()).min(1).readonly(),\n mode: ZoneRuleModeEnum,\n /**\n * Class names this rule applies to. Empty / undefined ⇒ rule\n * applies to every class. Class strings match the `macroClass`\n * field on detections (e.g. `person`, `car`, `dog`).\n */\n classFilter: z.array(z.string()).readonly().optional(),\n /**\n * Minimum bbox/mask overlap (0–1) with any of the rule's zones\n * required to consider an entity \"in the zone\". Defaults to the\n * consumer's stage default when omitted. Kept for back-compat with\n * existing per-rule overrides; new operators pick the value via\n * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is\n * set, the lower-level engine reads it as a 0–1 fraction.\n */\n overlapThreshold: z.number().min(0).max(1).optional(),\n /**\n * Operator-friendly version of `overlapThreshold` — the percentage\n * of the detection's bbox that must lie inside the zone for the\n * rule to match. Documented default is 85%; the engine substitutes\n * that when the field is omitted (kept optional so existing rules\n * stored without it stay valid).\n *\n * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a\n * rule, the engine prefers `bboxInclusionPct` because it's the\n * field exposed in the UI. Internally both feed the same gate.\n */\n bboxInclusionPct: z.number().min(0).max(100).optional(),\n /**\n * When `true` and a detection has a segmentation mask, use the\n * mask for overlap instead of the bbox. Detection-stage only;\n * motion rules ignore this field.\n */\n preferMask: z.boolean().optional(),\n /**\n * Soft-toggle: `false` disables the rule without deleting it.\n * Defaults to `true` so operators creating a rule via the UI\n * see it active immediately.\n */\n enabled: z.boolean().default(true)\n});\nconst ZoneRulesArraySchema = z.array(ZoneRuleSchema).readonly();\nconst ZoneRuleStageEnum = z.enum([\"motion\", \"detection\"]);\nconst zoneRulesCapability = {\n name: \"zone-rules\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n /** Read the full rule list for a given stage (empty when no rules\n * are defined yet). */\n listRules: method(\n z.object({ deviceId: z.number(), stage: ZoneRuleStageEnum }),\n z.array(ZoneRuleSchema).readonly()\n ),\n /** Bulk-replace the rule list for one stage. The provider validates\n * each entry against {@link ZoneRuleSchema} (zoneIds non-empty,\n * thresholds in range) and rejects the whole patch if any entry\n * is invalid — partial writes are a configuration footgun. */\n setRules: method(\n z.object({\n deviceId: z.number(),\n stage: ZoneRuleStageEnum,\n rules: z.array(ZoneRuleSchema).readonly()\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n },\n /**\n * Runtime-state slice — both stages mirrored together so consumers\n * see one reactive handle (`device.state.zoneRules.value`) instead\n * of two. Bulk-replace mutations on either stage write the full\n * `{motion, detection}` shape, so subscribers always get the\n * complete current set. Consumers that only care about one stage\n * just read the matching property.\n */\n runtimeState: z.object({\n motion: z.array(ZoneRuleSchema).readonly(),\n detection: z.array(ZoneRuleSchema).readonly()\n })\n};\nconst ProviderStatusSchema = z.object({\n connected: z.boolean(),\n deviceCount: z.number(),\n error: z.string().optional()\n});\nconst DiscoveredDeviceSchema = z.object({\n externalId: z.string(),\n name: z.string(),\n type: z.string(),\n metadata: z.record(z.string(), z.unknown()).optional()\n});\nconst DiscoveryCandidateSchema = z.object({\n stableId: z.string(),\n type: z.enum(DeviceType),\n suggestedName: z.string(),\n prefilledConfig: z.record(z.string(), z.unknown())\n});\nconst DeviceSummarySchema = z.object({\n id: z.number(),\n stableId: z.string(),\n addonId: z.string(),\n type: z.string(),\n name: z.string(),\n parentDeviceId: z.number().nullable(),\n online: z.boolean(),\n features: z.array(z.string()),\n config: z.record(z.string(), z.unknown())\n});\nconst FieldProbeResultSchema = z.object({\n status: z.enum([\"ok\", \"error\"]),\n labels: z.array(z.string()).optional(),\n error: z.string().optional()\n});\nconst CreationSchemaOutputSchema = z.unknown();\nconst deviceProviderCapability = {\n name: \"device-provider\",\n scope: \"system\",\n mode: \"collection\",\n methods: {\n // ── Lifecycle + introspection ─────────────────────────────────────\n start: method(z.void(), z.void(), { kind: \"mutation\" }),\n stop: method(z.void(), z.void(), { kind: \"mutation\" }),\n getStatus: method(z.void(), ProviderStatusSchema),\n getDevices: method(z.void(), z.array(z.object({\n id: z.string(),\n name: z.string(),\n type: z.string()\n }))),\n // ── Discovery + adoption (optional — see supportsDiscovery) ──────\n supportsDiscovery: method(z.object({}), z.boolean()),\n discoverDevices: method(\n z.object({}),\n z.array(DiscoveryCandidateSchema),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n adoptDiscoveredDevice: method(\n z.object({ candidate: DiscoveryCandidateSchema }),\n DeviceSummarySchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Manual creation (optional — see supportsManualCreation) ──────\n supportsManualCreation: method(z.object({}), z.boolean()),\n /**\n * Fetch the creation form schema for a given DeviceType. Returns\n * `null` when the provider does not support manually creating\n * devices of that type. The output is a `ConfigUISchema` — the\n * router type-asserts it at the boundary.\n */\n getChildCreationSchema: method(\n z.object({ type: z.enum(DeviceType) }),\n CreationSchemaOutputSchema\n ),\n createDevice: method(\n z.object({\n type: z.enum(DeviceType),\n config: z.record(z.string(), z.unknown())\n }),\n DeviceSummarySchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Test a single field in the creation form before the device has\n * been persisted. Typical use: probing an RTSP URL entered by the\n * user. Providers that don't support field probing return\n * `{ success: true, message: 'Field test not supported' }`.\n *\n * `formValues` is the live snapshot of every field in the form at\n * the moment the user clicked Test — useful for probes that depend\n * on multiple fields together (e.g. Reolink autodetect needs host\n * + credentials + UID + transport mode in a single call). Optional\n * for backwards compatibility; providers free to ignore it.\n */\n testCreationField: method(\n z.object({\n type: z.enum(DeviceType),\n key: z.string(),\n value: z.unknown(),\n formValues: z.record(z.string(), z.unknown()).optional()\n }),\n FieldProbeResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst ConfigTabDeclarationSchema = z.object({\n id: z.string(),\n label: z.string(),\n icon: z.string(),\n order: z.number().optional()\n});\nconst ConfigSectionWithValuesSchema = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string().optional(),\n style: z.enum([\"card\", \"accordion\"]).optional(),\n defaultCollapsed: z.boolean().optional(),\n columns: z.union([z.literal(1), z.literal(2), z.literal(3), z.literal(4)]).optional(),\n tab: z.string().optional(),\n // Hoist the section into a top-level device tab. DeviceDetail\n // discovers these from the aggregate and renders one tab per unique\n // `tab` id; the default `'settings'` keeps the section under Config.\n location: z.enum([\"settings\", \"top-tab\"]).optional(),\n order: z.number().optional(),\n fields: z.array(z.any())\n});\nconst SettingsSchemaWithValuesSchema = z.object({\n tabs: z.array(ConfigTabDeclarationSchema).optional(),\n sections: z.array(ConfigSectionWithValuesSchema)\n});\nconst SettingsPatchSchema = z.record(z.string(), z.unknown());\nconst SettingsUpdateResultSchema = z.object({\n success: z.literal(true)\n});\nconst addonSettingsCapability = {\n name: \"addon-settings\",\n scope: \"system\",\n mode: \"singleton\",\n nodeIdMode: \"data\",\n methods: {\n // ── Global-level settings ─────────────────────────────────────────\n //\n // `overlay` — optional preview overlay. When present, the provider\n // hydrates the schema as if the overlay were merged on top of the\n // persisted store (without writing anything). Used by override-mode\n // UIs (benchmark tabs) to get cascade-aware option lists when the\n // operator tweaks an upstream field — e.g. changing engineRuntime\n // from 'python' to 'node' refetches with `overlay: {engineRuntime:\n // 'node'}` so the backend/device dropdowns re-derive.\n getGlobalSettings: method(\n z.object({\n addonId: z.string(),\n nodeId: z.string().optional(),\n overlay: z.record(z.string(), z.unknown()).optional()\n }),\n SettingsSchemaWithValuesSchema.nullable()\n ),\n updateGlobalSettings: method(\n z.object({ addonId: z.string(), nodeId: z.string().optional(), patch: SettingsPatchSchema }),\n SettingsUpdateResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Device-level settings ─────────────────────────────────────────\n getDeviceSettings: method(\n z.object({ addonId: z.string(), deviceId: z.number(), nodeId: z.string().optional() }),\n SettingsSchemaWithValuesSchema.nullable()\n ),\n updateDeviceSettings: method(\n z.object({ addonId: z.string(), deviceId: z.number(), nodeId: z.string().optional(), patch: SettingsPatchSchema }),\n SettingsUpdateResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst AlertSeveritySchema = z.enum([\"info\", \"success\", \"warning\", \"error\"]);\nconst AlertStatusSchema = z.enum([\"active\", \"in-progress\", \"completed\", \"failed\", \"dismissed\"]);\nconst AlertSourceSchema = z.object({\n type: z.string(),\n id: z.string()\n});\nconst AlertSchema = z.object({\n id: z.string(),\n category: z.string(),\n severity: AlertSeveritySchema,\n title: z.string(),\n message: z.string(),\n status: AlertStatusSchema,\n progress: z.number().optional(),\n read: z.boolean(),\n createdAt: z.number(),\n updatedAt: z.number(),\n source: AlertSourceSchema.optional(),\n metadata: z.record(z.string(), z.unknown()).optional()\n});\nconst alertsCapability = {\n name: \"alerts\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n emit: method(AlertSchema, z.void(), { kind: \"mutation\" }),\n update: method(\n z.object({ alertId: z.string(), patch: AlertSchema.partial() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n list: method(\n z.object({ unreadOnly: z.boolean().optional(), limit: z.number().optional() }).optional(),\n z.array(AlertSchema).readonly()\n ),\n getUnreadCount: method(z.void(), z.number()),\n markRead: method(z.object({ alertId: z.string() }), z.void(), { kind: \"mutation\" }),\n markAllRead: method(z.void(), z.void(), { kind: \"mutation\" }),\n dismiss: method(z.object({ alertId: z.string() }), z.void(), { kind: \"mutation\" })\n }\n};\nconst storageCapability = {\n name: \"storage\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n // ── Small-file primitives ────────────────────────────────────────\n // `location` is a ref (type or fully-qualified id). The orchestrator\n // resolves the ref to a concrete `StorageLocation` and dispatches.\n resolve: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string() }),\n z.string()\n ),\n write: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string(), data: z.instanceof(Uint8Array) }),\n z.void(),\n { kind: \"mutation\" }\n ),\n read: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string() }),\n z.instanceof(Uint8Array)\n ),\n exists: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string() }),\n z.boolean()\n ),\n list: method(\n z.object({ location: StorageLocationRefSchema, prefix: z.string().optional() }),\n z.array(z.string()).readonly()\n ),\n delete: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n getAvailableSpace: method(\n z.object({ location: StorageLocationRefSchema }),\n z.number().nullable()\n ),\n // ── Chunked I/O ──────────────────────────────────────────────────\n // Same protocol as `storage-provider` but on the consumer side.\n // Sessions are owned by the orchestrator: it forwards each chunk\n // to the provider that backs the resolved location.\n beginUpload: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string(), sizeBytes: z.number().optional() }),\n z.object({ uploadId: z.string() }),\n { kind: \"mutation\" }\n ),\n writeChunk: method(\n z.object({ uploadId: z.string(), offset: z.number(), data: z.instanceof(Uint8Array) }),\n z.void(),\n { kind: \"mutation\" }\n ),\n finalizeUpload: method(z.object({ uploadId: z.string() }), z.void(), { kind: \"mutation\" }),\n abortUpload: method(z.object({ uploadId: z.string() }), z.void(), { kind: \"mutation\" }),\n beginDownload: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string() }),\n z.object({ downloadId: z.string(), sizeBytes: z.number() }),\n { kind: \"mutation\" }\n ),\n readChunk: method(\n z.object({ downloadId: z.string(), offset: z.number(), length: z.number() }),\n z.instanceof(Uint8Array)\n ),\n endDownload: method(z.object({ downloadId: z.string() }), z.void(), { kind: \"mutation\" }),\n // ── Location management ─────────────────────────────────────────\n // The orchestrator's authoritative surface for the admin-UI's\n // storage-locations page. Operators add/edit/test/remove location\n // instances here; `upsertLocation` and `deleteLocation` require\n // superAdmin auth.\n listLocations: method(\n z.object({ type: StorageLocationTypeSchema.optional() }),\n z.array(StorageLocationSchema).readonly()\n ),\n getDefaultLocation: method(\n z.object({ type: StorageLocationTypeSchema }),\n StorageLocationSchema.nullable()\n ),\n upsertLocation: method(\n StorageLocationSchema.omit({ createdAt: true, updatedAt: true }),\n StorageLocationSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n deleteLocation: method(\n z.object({ id: z.string() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n testLocation: method(\n z.object({ id: z.string() }),\n z.object({ ok: z.boolean(), error: z.string().optional() }),\n { auth: \"admin\" }\n ),\n // ── Provider discovery ──────────────────────────────────────────\n // The admin-UI's \"Add location\" wizard shows one entry per\n // registered `storage-provider` collection cap. Each entry is the\n // provider's `getProviderInfo()` blob — stable, addon-driven, no\n // hard-coded list in the UI. The orchestrator gathers them by\n // walking the registry on every call (cheap; the list almost\n // never changes after boot).\n listProviders: method(\n z.void(),\n z.array(z.object({\n providerId: z.string(),\n displayName: z.string(),\n supportedLocationTypes: z.array(StorageLocationTypeSchema).readonly(),\n configSchema: z.unknown()\n })).readonly()\n ),\n // Validate a candidate config against a provider BEFORE persisting.\n // Used by the wizard so operators can preflight a connection\n // (e.g. SFTP credentials, S3 bucket access) without leaving an\n // orphan record behind on failure.\n testConfig: method(\n z.object({\n providerId: z.string(),\n config: z.record(z.string(), z.unknown())\n }),\n z.object({ ok: z.boolean(), error: z.string().optional() }),\n { auth: \"admin\" }\n )\n }\n};\nconst ProviderInfoSchema = z.object({\n providerId: z.string().min(1),\n displayName: z.string().min(1),\n supportedLocationTypes: z.array(StorageLocationTypeSchema).readonly(),\n configSchema: z.unknown()\n});\nconst TestLocationResultSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional()\n});\nconst BeginUploadInputSchema = z.object({\n location: StorageLocationSchema,\n relativePath: z.string(),\n sizeBytes: z.number().optional()\n});\nconst BeginUploadResultSchema = z.object({ uploadId: z.string() });\nconst WriteChunkInputSchema = z.object({\n uploadId: z.string(),\n offset: z.number(),\n data: z.instanceof(Uint8Array)\n});\nconst FinalizeUploadInputSchema = z.object({ uploadId: z.string() });\nconst AbortUploadInputSchema = z.object({ uploadId: z.string() });\nconst BeginDownloadInputSchema = z.object({\n location: StorageLocationSchema,\n relativePath: z.string()\n});\nconst BeginDownloadResultSchema = z.object({\n downloadId: z.string(),\n sizeBytes: z.number()\n});\nconst ReadChunkInputSchema = z.object({\n downloadId: z.string(),\n offset: z.number(),\n length: z.number()\n});\nconst EndDownloadInputSchema = z.object({ downloadId: z.string() });\nconst storageProviderCapability = {\n name: \"storage-provider\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n /** Self-description for the \"Add location\" wizard. */\n getProviderInfo: method(z.void(), ProviderInfoSchema),\n /** Validate config + probe connectivity. Called on add and on edit. */\n testLocation: method(\n z.object({ config: z.record(z.string(), z.unknown()) }),\n TestLocationResultSchema,\n { auth: \"admin\" }\n ),\n // ── Small-file primitives ────────────────────────────────────────\n // The location is passed inline so the orchestrator dispatches\n // without provider-side location state.\n resolve: method(\n z.object({ location: StorageLocationSchema, relativePath: z.string() }),\n z.string()\n ),\n write: method(\n z.object({ location: StorageLocationSchema, relativePath: z.string(), data: z.instanceof(Uint8Array) }),\n z.void(),\n { kind: \"mutation\" }\n ),\n read: method(\n z.object({ location: StorageLocationSchema, relativePath: z.string() }),\n z.instanceof(Uint8Array)\n ),\n exists: method(\n z.object({ location: StorageLocationSchema, relativePath: z.string() }),\n z.boolean()\n ),\n list: method(\n z.object({ location: StorageLocationSchema, prefix: z.string().optional() }),\n z.array(z.string()).readonly()\n ),\n delete: method(\n z.object({ location: StorageLocationSchema, relativePath: z.string() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n getAvailableSpace: method(\n z.object({ location: StorageLocationSchema }),\n z.number().nullable()\n ),\n // ── Chunked upload ──────────────────────────────────────────────\n beginUpload: method(BeginUploadInputSchema, BeginUploadResultSchema, { kind: \"mutation\" }),\n writeChunk: method(WriteChunkInputSchema, z.void(), { kind: \"mutation\" }),\n finalizeUpload: method(FinalizeUploadInputSchema, z.void(), { kind: \"mutation\" }),\n abortUpload: method(AbortUploadInputSchema, z.void(), { kind: \"mutation\" }),\n // ── Chunked download ────────────────────────────────────────────\n beginDownload: method(BeginDownloadInputSchema, BeginDownloadResultSchema, { kind: \"mutation\" }),\n readChunk: method(ReadChunkInputSchema, z.instanceof(Uint8Array)),\n endDownload: method(EndDownloadInputSchema, z.void(), { kind: \"mutation\" })\n }\n};\nconst BackupSubDestinationInfoSchema = z.object({\n /**\n * Sub-id within this addon. Convention `default` for single-\n * destination addons; addons that host many (S3 with N buckets)\n * pick stable per-bucket strings. The orchestrator stitches\n * `<manifestId>:<subId>` for the wire format.\n */\n subId: z.string(),\n displayName: z.string(),\n description: z.string().optional(),\n kind: z.string(),\n triggerSupported: z.boolean(),\n restoreSupported: z.boolean()\n});\nconst BackupDestinationInfoSchema = BackupSubDestinationInfoSchema.extend({\n /** `<addonId>:<subId>` — globally-unique dispatch key. */\n id: z.string(),\n /**\n * Manifest id of the owning addon. The Settings button on the\n * destination card opens that addon's `globalSettingsSchema` panel.\n */\n addonId: z.string(),\n /** Operator-toggled enable flag from the destination-policy table. */\n enabled: z.boolean(),\n /** Operator-defined retention count (archives kept per destination). */\n retentionCount: z.number(),\n /** Operator-defined display label (overrides storage location displayName). */\n label: z.string().optional(),\n /** Newest-archive timestamp from `manifests.json`, or undefined. */\n lastSuccessAt: z.number().optional(),\n /** Newest-archive size from `manifests.json`, or undefined. */\n lastSuccessSizeBytes: z.number().optional(),\n /** Per-destination cron expression. Empty = manual-only (no schedule). */\n cron: z.string().optional(),\n /** ms-epoch of next computed firing for this destination's cron, if any. */\n nextRunAt: z.number().optional(),\n /** ms-epoch of last successful scheduled run (mirrors policy.lastRunAt). */\n lastRunAt: z.number().optional()\n});\nconst BackupArchiveEntrySchema = z.object({\n id: z.string(),\n filename: z.string(),\n createdAt: z.number(),\n sizeBytes: z.number(),\n label: z.string().optional(),\n /** Top-level locations included in the archive (db, addons, tls, …). */\n locations: z.array(z.string()).readonly()\n});\nconst BackupEntrySchema = z.object({\n id: z.string(),\n /** Addon id of the destination that owns this backup (e.g. `local-backup`, `s3-backup`). */\n destinationId: z.string().optional(),\n label: z.string().optional(),\n createdAt: z.number(),\n sizeBytes: z.number(),\n locations: z.array(z.string()).optional()\n});\nconst ArchiveEntrySchema = z.object({\n path: z.string(),\n kind: z.enum([\"file\", \"dir\", \"symlink\"]),\n sizeBytes: z.number(),\n mtime: z.number()\n});\nconst ArchiveManifestSchema = z.object({\n archiveVersion: z.literal(1),\n createdAt: z.number(),\n dataDir: z.string(),\n locations: z.array(z.string()),\n entries: z.array(ArchiveEntrySchema),\n totalBytes: z.number(),\n totalFiles: z.number()\n});\nconst LocationStatSchema = z.object({\n name: z.string(),\n sizeBytes: z.number(),\n fileCount: z.number(),\n present: z.boolean()\n});\nconst backupCapability = {\n name: \"backup\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n /**\n * Flat aggregate of every destination across every registered\n * `backup-destination` provider. This is the orchestrator-side\n * surface; it expands per-addon `listDestinations()` results into\n * one list the UI can render directly.\n */\n listDestinations: method(\n z.void(),\n z.array(BackupDestinationInfoSchema).readonly(),\n { auth: \"admin\" }\n ),\n /**\n * Trigger a backup. Without `destinations` the orchestrator fans\n * out to every destination flagged as enabled in the routing\n * config; with it, only the listed addons receive the archive.\n */\n trigger: method(\n z.object({\n /** Subset of registered `backup-destination` addon ids to write to. */\n destinations: z.array(z.string()).optional(),\n locations: z.array(z.string()).optional(),\n label: z.string().optional()\n }).optional(),\n z.array(BackupEntrySchema).readonly(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Union of every destination's archives, each tagged with `destinationId`. */\n list: method(z.void(), z.array(BackupEntrySchema).readonly(), { auth: \"admin\" }),\n /**\n * Pre-backup snapshot of the well-known locations on disk — sizes\n * + file counts. Powers the opt-in checklist that lets the\n * operator pick which subsections of state get archived.\n */\n listLocations: method(z.void(), z.array(LocationStatSchema).readonly(), { auth: \"admin\" }),\n /**\n * Read the embedded `.camstack-backup-manifest.json` from a\n * previously-created archive. The manifest carries the full\n * file/dir listing with sizes + mtimes — the readdir snapshot\n * the UI shows in the \"Contents\" panel. Returns `null` when the\n * archive predates manifests (created before this feature\n * shipped).\n */\n getEntries: method(\n z.object({ destinationId: z.string(), backupId: z.string() }),\n ArchiveManifestSchema.nullable(),\n { auth: \"admin\" }\n ),\n restore: method(\n z.object({\n destinationId: z.string(),\n backupId: z.string(),\n /**\n * Optional whitelist — only restore these top-level locations\n * from the archive. Default = every location the archive\n * carries (full restore). The boot-time apply hook reads\n * this list and skips entries whose path doesn't start with\n * any of them.\n */\n locations: z.array(z.string()).optional()\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n delete: method(\n z.object({ destinationId: z.string(), backupId: z.string() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * List archives at a single destination. Reads the per-location\n * `manifests.json` and returns one entry per archive (newest\n * first). Powers the destinations-table drill-in in admin UI.\n */\n listArchives: method(\n z.object({ destinationId: z.string() }),\n z.array(BackupArchiveEntrySchema).readonly(),\n { auth: \"admin\" }\n ),\n /**\n * Upsert a per-destination policy row. The `locationId` MUST be\n * the id of an existing `backups`-typed `StorageLocation`. Used\n * by the admin-UI destinations table (enable toggle + retention\n * input + optional label).\n */\n upsertDestinationPolicy: method(\n z.object({\n locationId: z.string(),\n enabled: z.boolean(),\n retentionCount: z.number().int().min(1).max(1e3),\n label: z.string().optional(),\n /**\n * Per-destination cron expression. Empty string clears the\n * schedule (manual-only). Validated server-side via croner;\n * malformed expressions reject the upsert with an actionable\n * message.\n */\n cron: z.string().optional()\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Validate a cron expression and peek the next N firing times.\n * Used by the admin-UI CronEditor to render a live \"next-run\"\n * preview as the operator edits the pattern.\n */\n previewSchedule: method(\n z.object({\n cron: z.string(),\n count: z.number().int().min(1).max(20).optional()\n }),\n z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n nextRuns: z.array(z.number()).readonly()\n })\n )\n }\n};\nconst QueryFilterSchema = z.object({\n where: z.record(z.string(), z.unknown()).optional(),\n whereIn: z.record(z.string(), z.array(z.unknown())).optional(),\n whereBetween: z.record(z.string(), z.tuple([z.unknown(), z.unknown()])).optional(),\n orderBy: z.object({\n field: z.string(),\n direction: z.enum([\"asc\", \"desc\"])\n }).optional(),\n limit: z.number().optional(),\n offset: z.number().optional()\n});\nconst SettingsRecordSchema = z.object({\n id: z.string(),\n data: z.record(z.string(), z.unknown())\n});\nconst CollectionColumnSchema = z.object({\n name: z.string(),\n type: z.enum([\"TEXT\", \"INTEGER\", \"REAL\", \"JSON\", \"BOOLEAN\"]),\n primaryKey: z.boolean().optional(),\n notNull: z.boolean().optional(),\n unique: z.boolean().optional()\n});\nconst CollectionIndexSchema = z.object({\n name: z.string(),\n columns: z.array(z.string()).readonly(),\n unique: z.boolean().optional()\n});\nconst settingsStoreCapability = {\n name: \"settings-store\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n /** Get a single value by key from a collection. */\n get: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), key: z.string() }),\n z.unknown()\n ),\n /** Set a value by key in a collection (upsert). */\n set: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), key: z.string(), value: z.unknown() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /** Get all entries matching an optional filter. */\n query: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), filter: QueryFilterSchema.optional() }),\n z.array(SettingsRecordSchema).readonly()\n ),\n /** Insert a new record. */\n insert: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), record: SettingsRecordSchema }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /** Update an existing record by ID. */\n update: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), id: z.string(), data: z.record(z.string(), z.unknown()) }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /** Delete a record by key/ID. */\n delete: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), key: z.string() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /** Count entries in a collection, optionally filtered. */\n count: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), filter: QueryFilterSchema.optional() }),\n z.number()\n ),\n /** Check if a collection is empty. */\n isEmpty: method(\n z.object({ namespace: z.string().optional(), collection: z.string() }),\n z.boolean()\n ),\n /**\n * Declare a typed (SQL-backed) collection with explicit columns +\n * indexes. Idempotent: re-declaring an existing collection with the\n * same shape is a no-op; shape changes (new columns, new indexes)\n * are applied additively. Subsequent `insert` / `update` / `delete`\n * / `query` calls on this collection use typed columns instead of\n * JSON-blob storage — `record.data` fields are spread across\n * columns, `query.filter.where` matches real columns (no\n * `json_extract` overhead), `orderBy` uses column indexes.\n *\n * Addons call this in `onInitialize` before their first read/write.\n * Collection names should be namespaced by addon (e.g.\n * `pipeline-analytics:object-events`) to avoid cross-addon\n * clashes — no automatic prefix is added.\n */\n declareCollection: method(\n z.object({\n namespace: z.string().optional(),\n collection: z.string(),\n columns: z.array(CollectionColumnSchema).readonly(),\n indexes: z.array(CollectionIndexSchema).readonly().optional()\n }),\n z.void(),\n { kind: \"mutation\" }\n )\n }\n};\nconst LogLevelSchema$1 = z.enum([\"debug\", \"info\", \"warn\", \"error\"]);\nconst LogEntrySchema = z.object({\n timestamp: z.date(),\n level: LogLevelSchema$1,\n scope: z.array(z.string()),\n message: z.string(),\n meta: z.record(z.string(), z.unknown()).optional(),\n tags: z.record(z.string(), z.string()).optional()\n});\nconst logDestinationCapability = {\n name: \"log-destination\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n write: method(LogEntrySchema, z.void(), { kind: \"mutation\" }),\n query: method(\n z.object({\n scope: z.array(z.string()).optional(),\n level: LogLevelSchema$1.optional(),\n since: z.date().optional(),\n until: z.date().optional(),\n limit: z.number().optional(),\n tags: z.record(z.string(), z.string()).optional()\n }),\n z.array(LogEntrySchema).readonly()\n )\n }\n};\nconst StaticDirOutputSchema = z.object({ staticDir: z.string() });\nconst VersionOutputSchema = z.object({ version: z.string() });\nconst adminUiCapability = {\n name: \"admin-ui\",\n scope: \"system\",\n mode: \"singleton\",\n internal: true,\n methods: {\n getStaticDir: method(z.void(), StaticDirOutputSchema),\n getVersion: method(z.void(), VersionOutputSchema)\n }\n};\nconst SsoBridgeClaimsSchema = z.object({\n userId: z.string(),\n username: z.string(),\n isAdmin: z.boolean(),\n provider: z.string(),\n email: z.string().optional(),\n displayName: z.string().optional(),\n /**\n * Public HTTPS URL of the hub that issued this token. Used by\n * cloud-mode OAuth proxies (Alexa Smart Home Lambda, future Google\n * Home Lambda) to route a request back to the originating hub\n * without holding routing state of their own. The Lambda decodes the\n * JWT WITHOUT verifying the signature — the hub re-verifies on every\n * inbound call so trust still rests with the signing hub.\n */\n hubUrl: z.string().optional()\n});\nconst ssoBridgeCapability = {\n name: \"sso-bridge\",\n scope: \"system\",\n mode: \"singleton\",\n internal: true,\n methods: {\n signBridgeToken: method(\n z.object({\n claims: SsoBridgeClaimsSchema,\n ttlSec: z.number().int().positive().optional()\n }),\n z.object({ token: z.string() })\n ),\n verifyBridgeToken: method(\n z.object({ token: z.string() }),\n SsoBridgeClaimsSchema.nullable()\n )\n }\n};\nconst PasskeySummarySchema = z.object({\n credentialId: z.string(),\n label: z.string(),\n createdAt: z.number(),\n lastUsedAt: z.number().nullable(),\n transports: z.array(z.string()).default([])\n});\nconst userPasskeysCapability = {\n name: \"user-passkeys\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n beginRegistration: method(\n z.object({ userId: z.string(), username: z.string() }),\n // PublicKeyCredentialCreationOptionsJSON — opaque JSON shape from\n // @simplewebauthn. The browser passes it straight to credentials.create().\n z.object({ optionsJSON: z.record(z.string(), z.unknown()) }),\n { kind: \"mutation\", auth: \"admin\", access: \"create\" }\n ),\n finishRegistration: method(\n z.object({\n userId: z.string(),\n /** RegistrationResponseJSON from the browser. */\n response: z.record(z.string(), z.unknown()),\n /** Operator-visible label (e.g. \"MacBook Touch ID\"). */\n label: z.string()\n }),\n z.object({ success: z.literal(true), credentialId: z.string() }),\n { kind: \"mutation\", auth: \"admin\", access: \"create\" }\n ),\n beginAuthentication: method(\n // userId optional — when absent, the addon emits a \"passkey discovery\"\n // (`allowCredentials: []`) so the browser shows every available\n // credential. When present, only the user's credentials are allowed.\n z.object({ userId: z.string().optional() }),\n z.object({ optionsJSON: z.record(z.string(), z.unknown()) }),\n { kind: \"mutation\", access: \"view\" }\n ),\n finishAuthentication: method(\n z.object({\n /** Required — the user the assertion belongs to (verified). */\n userId: z.string(),\n /** AuthenticationResponseJSON from the browser. */\n response: z.record(z.string(), z.unknown())\n }),\n z.object({ verified: z.boolean() }),\n { kind: \"mutation\", access: \"view\" }\n ),\n listPasskeys: method(\n z.object({ userId: z.string() }),\n z.array(PasskeySummarySchema),\n { auth: \"admin\" }\n ),\n removePasskey: method(\n z.object({ userId: z.string(), credentialId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\", access: \"delete\" }\n )\n }\n};\nconst EmailAddressSchema = z.email();\nconst SendEmailInputSchema = z.object({\n to: z.union([EmailAddressSchema, z.array(EmailAddressSchema).min(1)]),\n cc: z.array(EmailAddressSchema).optional(),\n bcc: z.array(EmailAddressSchema).optional(),\n /** RFC 5322 `From` field. Most relays will reject if the domain\n * isn't authorised — the addon is responsible for substituting a\n * sane default when omitted. */\n from: z.string().optional(),\n /** Optional `Reply-To` override. */\n replyTo: z.string().optional(),\n subject: z.string(),\n /** Plain-text body. Required even when `html` is present (fallback\n * for clients that strip HTML — including most spam filters). */\n text: z.string(),\n /** Optional HTML body. Renders alongside `text` as multi-part. */\n html: z.string().optional()\n});\nconst SendEmailResultSchema = z.object({\n messageId: z.string(),\n accepted: z.array(EmailAddressSchema).default([]),\n rejected: z.array(EmailAddressSchema).default([])\n});\nconst SmtpStatusSchema = z.object({\n /** True iff the addon has successfully verified the relay. */\n ready: z.boolean(),\n /** Operator-visible host string (no credentials). */\n host: z.string(),\n /** Last error message reported by the relay, when not ready. */\n error: z.string().optional(),\n /** Last successful verify timestamp (unix ms). */\n lastVerifiedAt: z.number().optional()\n});\nconst smtpProviderCapability = {\n name: \"smtp-provider\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n providerKind: \"email\",\n methods: {\n sendEmail: method(\n SendEmailInputSchema,\n SendEmailResultSchema,\n { kind: \"mutation\", auth: \"admin\", access: \"create\" }\n ),\n /** Round-trip ping against the SMTP relay (EHLO + AUTH if configured).\n * Used by the operator's \"Test connection\" button. */\n verify: method(\n z.void(),\n SmtpStatusSchema,\n { kind: \"mutation\", auth: \"admin\", access: \"view\" }\n ),\n getStatus: method(\n z.void(),\n SmtpStatusSchema,\n { auth: \"admin\" }\n )\n }\n};\nconst BrokerKindSchema = z.enum([\"external\", \"embedded\"]);\nconst BrokerStatusSchema = z.enum([\n \"connected\",\n \"disconnected\",\n \"auth-failed\",\n \"unreachable\",\n \"tls-error\"\n]);\nconst BrokerInfoSchema = z.object({\n id: z.string(),\n name: z.string(),\n url: z.string(),\n kind: BrokerKindSchema,\n status: BrokerStatusSchema,\n latencyMs: z.number().nullable(),\n error: z.string().optional(),\n /** Embedded brokers only: number of MQTT clients currently connected. */\n connectedClients: z.number().int().nonnegative().optional(),\n /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */\n lastCheckedAt: z.number().optional()\n});\nconst BrokerConnectionDetailsSchema = z.object({\n url: z.string(),\n username: z.string().optional(),\n password: z.string().optional(),\n /**\n * Suggested prefix for `clientId`. Each consumer should suffix this\n * with its own discriminator (addon id, instance id) so reconnects\n * don't kick each other off (MQTT spec: clientId must be unique per\n * broker).\n */\n clientIdPrefix: z.string().optional()\n});\nconst AddBrokerInputSchema = z.object({\n name: z.string().min(1),\n url: z.string().regex(/^(mqtt|mqtts|ws|wss):\\/\\//, \"URL must start with mqtt(s):// or ws(s)://\"),\n username: z.string().optional(),\n password: z.string().optional(),\n clientIdPrefix: z.string().optional()\n});\nconst AddBrokerResultSchema = z.object({\n id: z.string()\n});\nconst IdInputSchema = z.object({ id: z.string() });\nconst TestResultSchema = z.discriminatedUnion(\"ok\", [\n z.object({ ok: z.literal(true), latencyMs: z.number() }),\n z.object({ ok: z.literal(false), error: z.string() })\n]);\nconst StartEmbeddedInputSchema = z.object({\n port: z.number().int().min(1).max(65535).default(1883),\n /** Allow anonymous connect (no username/password). Default: false. */\n allowAnonymous: z.boolean().default(false),\n /** Optional shared username/password for clients. */\n username: z.string().optional(),\n password: z.string().optional()\n});\nconst StartEmbeddedResultSchema = z.object({\n id: z.string(),\n url: z.string()\n});\nconst StatusSchema = z.object({\n brokerCount: z.number(),\n embeddedRunning: z.boolean()\n});\nconst mqttBrokerCapability = {\n name: \"mqtt-broker\",\n scope: \"system\",\n mode: \"collection\",\n providerKind: \"broker\",\n status: { schema: StatusSchema, kind: \"poll\" },\n methods: {\n listBrokers: method(z.void(), z.array(BrokerInfoSchema)),\n getBrokerConfig: method(IdInputSchema, BrokerConnectionDetailsSchema),\n addBroker: method(AddBrokerInputSchema, AddBrokerResultSchema, { kind: \"mutation\" }),\n removeBroker: method(IdInputSchema, z.void(), { kind: \"mutation\" }),\n testConnection: method(IdInputSchema, TestResultSchema, { kind: \"mutation\" }),\n startEmbeddedBroker: method(StartEmbeddedInputSchema, StartEmbeddedResultSchema, { kind: \"mutation\" }),\n stopEmbeddedBroker: method(IdInputSchema, z.void(), { kind: \"mutation\" }),\n getStatus: method(z.void(), StatusSchema)\n }\n};\nconst LinkStateSchema = z.enum([\"unlinked\", \"linked\", \"error\"]);\nconst ExportSetupFieldSchema = z.object({\n label: z.string(),\n value: z.string(),\n /** Mask the value by default + render a reveal toggle (client id, secrets). */\n secret: z.boolean().optional()\n});\nconst ExportSetupSchema = z.object({\n /** A string to render as a scannable QR — HAP `X-HM://…` URI, a pairing URL, etc. Omitted when there's nothing to scan. */\n qr: z.string().optional(),\n /** Label/value rows shown with a copy button (HAP setup code, OAuth URLs, client id, linked-account count, …). */\n fields: z.array(ExportSetupFieldSchema).readonly().optional(),\n /** Free-form operator instructions rendered above the fields. */\n note: z.string().optional()\n});\nconst DeviceExportStatusSchema = z.object({\n linkState: LinkStateSchema,\n exposedDeviceCount: z.number(),\n error: z.string().optional(),\n /**\n * Optional pairing/account info the panel renders in a generic\n * \"Setup\" section. Addon-agnostic — the addon id identifies the\n * export target, never an `ecosystem` key here.\n */\n setup: ExportSetupSchema.optional()\n});\nconst DeviceKindSchema = z.string();\nconst ExposedDeviceSchema = z.object({\n deviceId: z.string(),\n exposedAs: z.string().optional(),\n capabilities: z.array(z.string()).optional()\n});\nconst ExposeInputSchema = z.object({\n deviceId: z.string(),\n capabilities: z.array(z.string()).optional()\n});\nconst UnexposeInputSchema = z.object({ deviceId: z.string() });\nconst deviceExportCapability = {\n name: \"device-export\",\n scope: \"system\",\n mode: \"collection\",\n providerKind: \"device-export\",\n status: { schema: DeviceExportStatusSchema, kind: \"poll\" },\n /**\n * Each export provider contributes its own per-device \"Export\" panel\n * (enabled toggle, preferred stream, addon-specific knobs like the\n * HA-MQTT discovery prefix). The three framework methods\n * `getDeviceSettingsContribution` / `getDeviceLiveContribution` /\n * `applyDeviceSettingsPatch` are auto-injected on the provider\n * interface and routed to the device-details aggregator.\n */\n exposesDeviceSettings: true,\n methods: {\n getStatus: method(z.void(), DeviceExportStatusSchema),\n listSupportedDeviceKinds: method(z.void(), z.array(DeviceKindSchema)),\n listExposedDevices: method(z.void(), z.array(ExposedDeviceSchema)),\n exposeDevice: method(ExposeInputSchema, z.void(), { kind: \"mutation\" }),\n unexposeDevice: method(UnexposeInputSchema, z.void(), { kind: \"mutation\" })\n }\n};\nconst AddonPageDeclarationSchema$1 = z.object({\n id: z.string(),\n label: z.string(),\n icon: z.string(),\n path: z.string(),\n remoteName: z.string(),\n bundle: z.string()\n});\nconst AddonPageInfoSchema = z.object({\n addonId: z.string(),\n page: AddonPageDeclarationSchema$1,\n bundleUrl: z.string()\n});\nconst addonPagesCapability = {\n name: \"addon-pages\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n listPages: method(z.void(), z.array(AddonPageInfoSchema).readonly())\n }\n};\nconst AddonPageDeclarationSchema = z.object({\n id: z.string(),\n label: z.string(),\n icon: z.string(),\n path: z.string(),\n /**\n * Module Federation remote name — must match the `name` field on the\n * page addon's `federation()` plugin config. Used by admin-ui's\n * `<AddonPageLoader>` to call `loadRemote('<remoteName>/page')`.\n * Conventionally `addon_<id>_page` (snake_case; MF names cannot\n * contain hyphens).\n */\n remoteName: z.string(),\n /**\n * Bundle filename inside the addon's `dist/` dir served at\n * `/api/addon-pages/<addonId>/<bundle>`. With Module Federation this\n * is always `'remoteEntry.js'`; the value is kept on the metadata so\n * the static-file route can compute an mtime-based cache-buster URL\n * without a separate filesystem stat.\n */\n bundle: z.string()\n});\nconst addonPagesSourceCapability = {\n name: \"addon-pages-source\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n listPages: method(z.void(), z.array(AddonPageDeclarationSchema).readonly())\n }\n};\nconst WidgetHostEnum = z.enum([\"device-tab\", \"dashboard\", \"integration-detail\"]);\nconst WidgetSizeEnum = z.enum([\"xs\", \"sm\", \"md\", \"lg\", \"xl\"]);\nconst WidgetMetadataSchema = z.object({\n /** Stable id within the addon — kebab-case. */\n stableId: z.string(),\n /** Operator-facing label. */\n label: z.string(),\n description: z.string().optional(),\n icon: z.string().optional(),\n /**\n * Module Federation remote name — must match the `name` field on the\n * widget addon's `federation()` plugin config. Used by the host's\n * `<WidgetRegistryProvider>` to call `loadRemote('<remoteName>/widgets')`.\n * Conventionally `addon_<addonid>_widgets` (snake_case; MF names\n * cannot contain hyphens).\n */\n remoteName: z.string(),\n /**\n * Bundle filename inside the addon's `dist/` dir served at\n * `/api/addon-widgets/<addonId>/<bundle>`. With Module Federation\n * this is always `'remoteEntry.js'` — the value is kept on the\n * metadata so the static-file route can compute an mtime-based\n * cache-buster URL without a separate filesystem stat.\n */\n bundle: z.string(),\n /** Where the widget makes sense to render. */\n hosts: z.array(WidgetHostEnum).readonly(),\n /** Required props the host must supply. Validated at <WidgetSlot> mount. */\n requires: z.object({\n deviceContext: z.boolean().default(false),\n integrationContext: z.boolean().default(false)\n }),\n /** Dashboard placement HINTS (operator can override per instance). */\n defaultSize: WidgetSizeEnum.default(\"md\"),\n allowedSizes: z.array(WidgetSizeEnum).readonly().default([\"sm\", \"md\", \"lg\"]),\n defaultColumns: z.number().int().min(1).max(12).default(6),\n defaultRows: z.number().int().min(1).max(12).default(1)\n});\nconst addonWidgetsSourceCapability = {\n name: \"addon-widgets-source\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n listWidgets: method(z.void(), z.array(WidgetMetadataSchema).readonly())\n }\n};\nconst EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({\n addonId: z.string(),\n bundleUrl: z.string()\n});\nconst addonWidgetsCapability = {\n name: \"addon-widgets\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n listWidgets: method(z.void(), z.array(EnrichedWidgetMetadataSchema).readonly())\n }\n};\nconst AddonHttpRouteSchema = z.object({\n method: z.enum([\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\"]),\n path: z.string(),\n access: z.enum([\"public\", \"authenticated\", \"admin\"]).optional(),\n description: z.string().optional()\n});\nconst InvokeRequestSchema = z.object({\n method: z.string(),\n path: z.string(),\n params: z.record(z.string(), z.string()),\n query: z.record(z.string(), z.string()),\n body: z.unknown(),\n headers: z.record(z.string(), z.string()),\n user: z.object({\n id: z.string(),\n username: z.string(),\n isAdmin: z.boolean()\n }).optional(),\n scopedToken: z.unknown().optional()\n});\nconst InvokeReplyEnvelopeSchema = z.object({\n status: z.number().int(),\n headers: z.record(z.string(), z.string()),\n /** When set, the hub MUST `reply.redirect(redirectUrl)` instead of\n * sending `body`. Status defaults to 302 when this is set unless\n * the handler called `reply.code(...)` explicitly. */\n redirectUrl: z.string().nullable(),\n /** JSON-serializable body. `undefined` is treated as \"no body\". */\n body: z.unknown().optional(),\n /** Set when the handler called `reply.type(mime)`. */\n contentType: z.string().optional()\n});\nconst addonRoutesCapability = {\n name: \"addon-routes\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n getRoutes: method(z.void(), z.array(AddonHttpRouteSchema)),\n /**\n * Cross-process dispatch entry point. Forked addons implement this\n * (via `buildAddonRouteProvider`) so the hub's Fastify catch-all\n * can route through Moleculer when the handler lives in a worker.\n *\n * Local addons can implement it for free with the same helper;\n * the hub bypasses the wire on co-located addons.\n */\n invoke: method(InvokeRequestSchema, InvokeReplyEnvelopeSchema, { kind: \"mutation\" })\n }\n};\nconst HWACCEL_OPTIONS = [\n { value: \"auto\", label: \"Auto (defer to probed best)\" },\n { value: \"none\", label: \"Off (software)\" },\n { value: \"videotoolbox\", label: \"VideoToolbox (macOS)\" },\n { value: \"cuda\", label: \"CUDA (NVIDIA)\" },\n { value: \"nvdec\", label: \"NVDEC (NVIDIA legacy)\" },\n { value: \"vaapi\", label: \"VAAPI (Linux Intel/AMD)\" },\n { value: \"qsv\", label: \"QuickSync (Intel)\" },\n { value: \"d3d11va\", label: \"D3D11VA (Windows)\" },\n { value: \"dxva2\", label: \"DXVA2 (Windows legacy)\" },\n { value: \"amf\", label: \"AMF (AMD)\" },\n { value: \"vdpau\", label: \"VDPAU (Linux NVIDIA legacy)\" },\n { value: \"drm\", label: \"DRM (Linux generic)\" }\n];\nconst DEFAULT_DECODER_HWACCEL_CONFIG = {\n hwaccel: \"auto\",\n probedBestHwaccel: \"\"\n};\nconst decoderCapability = {\n name: \"decoder\",\n scope: \"system\",\n // Singleton — one decoder per node. `decoder-nodeav` is the default\n // install; operators can swap to a different provider via the\n // binding system's active-addon selection. The old collection shape\n // existed to let node-av + ffmpeg coexist and priority-sort at\n // stream-start; that fallback was dropped once node-av covered the\n // full codec matrix.\n mode: \"singleton\",\n methods: {\n // ── Discovery ─────────────────────────────────────────────────\n supportsCodec: method(z.object({ codec: z.string() }), z.boolean()),\n getInfo: method(z.void(), z.object({\n id: z.string(),\n name: z.string(),\n isPullMode: z.boolean().optional(),\n priority: z.number().optional()\n })),\n // ── Session lifecycle ─────────────────────────────────────────\n // `nodeId` carries the Moleculer nodeID of the decoder provider that\n // owns the session. Brokers store it so they can react to per-agent\n // events (e.g. `pipeline.agent-hwaccel-changed`) and rotate only the\n // sessions that actually live on the affected node.\n createSession: method(DecoderSessionConfigSchema, z.object({ sessionId: z.string(), nodeId: z.string() })),\n destroySession: method(z.object({ sessionId: z.string() }), z.void()),\n // ── Data plane ────────────────────────────────────────────────\n pushPacket: method(z.object({\n sessionId: z.string(),\n packet: EncodedPacketSchema\n }), z.void()),\n openStream: method(z.object({\n sessionId: z.string(),\n url: z.string()\n }), z.void()),\n // ── Output — polling-based frame retrieval ────────────────────\n pullFrames: method(z.object({\n sessionId: z.string(),\n maxCount: z.number().default(1)\n }), z.array(DecodedFrameSchema)),\n // ── Control ───────────────────────────────────────────────────\n updateConfig: method(z.object({\n sessionId: z.string(),\n config: DecoderSessionConfigSchema.partial()\n }), z.void()),\n getStats: method(z.object({ sessionId: z.string() }), DecoderStatsSchema),\n // ── Inventory — session-level state ONLY ─────────────────────\n // Sessions are a decoder concept, so `listActiveSessions` lives\n // here. Process-level measurements (memory/cpu) go through the\n // generic `metrics-provider` cap — decoder stays free of\n // observability concerns that aren't specific to decoding.\n listActiveSessions: method(z.void(), z.array(z.object({\n sessionId: z.string(),\n codec: z.string(),\n outputFormat: z.string(),\n createdAtMs: z.number()\n })).readonly()),\n /**\n * Re-run the host platform-probe for the decoder's hwaccel backend\n * and write the detected value into the addon's own global\n * settings (`probedBestHwaccel`). Replaces the legacy per-agent\n * `pipeline-orchestrator.reprobeAgentHwAccel` — each decoder addon\n * now owns its own probe.\n *\n * Returns the backend the probe picked (`'none'` = software-only\n * host, otherwise one of `HwAccelBackend`). The operator's\n * `hwaccel` setting (auto / none / backend) is not touched; only\n * the `probedBestHwaccel` hint.\n */\n reprobeHwaccel: method(\n z.void(),\n z.object({ backend: z.string() }),\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst RegisteredStreamSchema = z.object({\n streamId: z.string(),\n label: z.string().optional(),\n codec: z.string(),\n type: z.enum([\"video\", \"audio\"]),\n sourceUrl: z.string()\n});\nconst ExposedResourceSchema = z.object({\n streamId: z.string(),\n format: z.string(),\n value: z.string()\n});\nconst restreamerCapability = {\n name: \"restreamer\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n registerDevice: method(\n z.object({ deviceId: z.number(), streams: z.array(RegisteredStreamSchema).readonly() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n unregisterDevice: method(z.object({ deviceId: z.number() }), z.void(), { kind: \"mutation\" }),\n getExposedResources: method(\n z.object({ deviceId: z.number() }),\n z.array(ExposedResourceSchema).readonly()\n )\n }\n};\nconst webrtcClientHintsSchema = z.object({\n viewportWidth: z.number().int().positive().optional(),\n viewportHeight: z.number().int().positive().optional(),\n devicePixelRatio: z.number().positive().optional(),\n /** navigator.connection.downlink — Mbps the browser estimates. */\n downlinkMbps: z.number().nonnegative().optional(),\n /** Hard tier override; takes precedence over scoring when registered. */\n prefersTier: z.string().optional()\n}).partial();\nconst webrtcCapability = {\n name: \"webrtc\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n handleOffer: method(\n z.object({ streamId: z.string(), sdpOffer: z.string() }),\n z.string(),\n { kind: \"mutation\" }\n ),\n supportsStream: method(z.object({ streamId: z.string() }), z.boolean()),\n registerStream: method(\n z.object({ streamId: z.string(), codec: z.string() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n unregisterStream: method(z.object({ streamId: z.string() }), z.void(), { kind: \"mutation\" }),\n /**\n * Two-step server-offer signaling. `hints` is optional — providers\n * that don't care about adaptive source selection ignore it.\n */\n createSession: method(\n z.object({\n streamId: z.string(),\n hints: webrtcClientHintsSchema.optional()\n }),\n z.object({ sessionId: z.string(), sdpOffer: z.string() }),\n { kind: \"mutation\" }\n ),\n handleAnswer: method(\n z.object({ sessionId: z.string(), sdpAnswer: z.string() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n closeSession: method(z.object({ sessionId: z.string() }), z.void(), { kind: \"mutation\" }),\n /**\n * Whether this provider supports adaptive bitrate for the given stream.\n * Currently always false — adaptive selection is one-shot at session\n * start, not in-session encoder switching. Phase 5 plans to layer\n * encoder-driven adaptation on top.\n */\n hasAdaptiveBitrate: method(\n z.object({ streamId: z.string() }),\n z.boolean()\n )\n }\n};\nconst WebrtcStreamTargetSchema = z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"adaptive\") }),\n z.object({ kind: z.literal(\"profile\"), profile: CamProfileSchema }),\n z.object({ kind: z.literal(\"cam-stream\"), camStreamId: z.string().min(1) })\n]);\nconst WebrtcStreamChoiceSchema = z.object({\n /** Stable id for React keys / dropdowns (e.g. `'adaptive'`, `'profile:high'`, `'stream:native:main'`). */\n id: z.string(),\n /** Display label. */\n label: z.string(),\n /** Discriminated target — pass straight to `createSession`. */\n target: WebrtcStreamTargetSchema,\n /** Codec of the underlying broker stream (null for adaptive). */\n codec: z.string().nullable(),\n /** Resolution of the underlying stream (null for adaptive). */\n resolution: z.object({ width: z.number(), height: z.number() }).nullable(),\n /** Broker status (null for adaptive). */\n status: z.enum([\"idle\", \"connecting\", \"streaming\", \"error\", \"stopped\"]).nullable(),\n /** Input FPS from the camera (null for adaptive). */\n inputFps: z.number().nullable(),\n /** Decoded FPS (null for adaptive). */\n decodeFps: z.number().nullable(),\n /** Bitrate in kbps (null for adaptive). */\n bitrateKbps: z.number().nullable()\n});\nconst webrtcSessionCapability = {\n name: \"webrtc-session\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n /**\n * List available WebRTC streams for a device.\n * Returns adaptive (if any profile is assigned) + each assigned profile\n * with codec/resolution info. UI renders this directly — no hardcoded\n * profile names needed.\n */\n listStreams: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.array(WebrtcStreamChoiceSchema)\n ),\n /**\n * Open a WebRTC session against a specific target on the device.\n * `target.kind` discriminates between adaptive selection, a profile\n * slot, or a specific cam stream source — see `WebrtcStreamTarget`.\n * The server resolves the target to a live broker; clients never\n * build or parse brokerId strings.\n */\n createSession: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n target: WebrtcStreamTargetSchema,\n hints: webrtcClientHintsSchema.optional()\n }),\n z.object({ sessionId: z.string(), sdpOffer: z.string() }),\n { kind: \"mutation\" }\n ),\n /**\n * Accept a CLIENT-generated SDP offer and return the server's\n * SDP answer. Mirrors the WHEP / Alexa\n * `Alexa.RTCSessionController.InitiateSessionWithOffer` direction\n * (client offers, server answers) — the dual of `createSession`,\n * which has the server offer first.\n *\n * `target` defaults to the device's adaptive selection when\n * omitted; an optional `sessionId` lets the client provide its\n * own correlation id (Alexa supplies one in the directive\n * payload). The returned `sessionId` is whatever the server uses\n * to track the session and accepts via `closeSession`.\n */\n handleOffer: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n target: WebrtcStreamTargetSchema.optional(),\n sdpOffer: z.string(),\n sessionId: z.string().optional()\n }),\n z.object({ sessionId: z.string(), sdpAnswer: z.string() }),\n { kind: \"mutation\" }\n ),\n handleAnswer: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n sessionId: z.string(),\n sdpAnswer: z.string()\n }),\n z.void(),\n { kind: \"mutation\" }\n ),\n closeSession: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n sessionId: z.string()\n }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /** Whether the underlying provider supports adaptive bitrate for this profile. */\n hasAdaptiveBitrate: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n profile: CamProfileSchema\n }),\n z.boolean()\n )\n }\n};\nconst CameraPipelineConfigSchema = z.object({\n engine: PipelineEngineChoiceSchema,\n steps: z.array(PipelineStepInputSchema).readonly(),\n audio: z.object({\n engine: PipelineEngineChoiceSchema,\n modelId: z.string(),\n enabled: z.boolean(),\n settings: z.record(z.string(), z.unknown()).readonly().optional()\n }).nullable().optional()\n});\nconst PipelineTemplateSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string().optional(),\n config: CameraPipelineConfigSchema,\n createdAt: z.string(),\n updatedAt: z.string()\n});\nconst AgentAddonConfigSchema = z.object({\n enabled: z.boolean(),\n modelId: z.string(),\n settings: z.record(z.string(), z.unknown()).readonly()\n});\nconst AgentPipelineSettingsSchema = z.object({\n addonDefaults: z.record(z.string(), AgentAddonConfigSchema).readonly()\n});\nconst CameraPipelineForAgentSchema = z.object({\n steps: z.array(PipelineStepInputSchema).readonly(),\n audio: z.object({\n modelId: z.string(),\n enabled: z.boolean()\n }).nullable()\n});\nconst CameraStepOverridePatchSchema = z.object({\n enabled: z.boolean().optional(),\n modelId: z.string().optional(),\n settings: z.record(z.string(), z.unknown()).readonly().optional()\n});\nconst CameraPipelineSettingsSchema = z.object({\n pinnedAgentNodeId: z.string().optional(),\n stepToggles: z.record(z.string(), z.boolean()).optional(),\n stepOverridesByAgent: z.record(\n z.string(),\n z.record(z.string(), CameraStepOverridePatchSchema)\n ).optional(),\n pipelineByAgent: z.record(z.string(), CameraPipelineForAgentSchema).optional()\n});\nconst PipelineAssignmentSchema = z.object({\n deviceId: z.number(),\n /** Moleculer node id of the runner currently responsible for this camera. */\n agentNodeId: z.string(),\n /** True when the assignment was set manually, false when chosen by the balancer. */\n pinned: z.boolean(),\n /** Why this assignment was made — useful for debugging the load balancer. */\n reason: z.enum([\"manual\", \"capacity\", \"hardware-affinity\", \"failover\", \"rebalance\"]),\n /** Unix timestamp (ms) when the assignment was last updated. */\n assignedAt: z.number()\n});\nconst DecoderAssignmentSchema = z.object({\n deviceId: z.number(),\n /** Moleculer node id of the decoder provider currently responsible for this camera. */\n decoderNodeId: z.string(),\n /** True when the assignment was set manually via `assignDecoder`, false when chosen by the balancer. */\n pinned: z.boolean(),\n /** Why this assignment was made — useful for debugging the decoder balancer. */\n reason: z.enum([\"manual\", \"co-located\", \"capacity\", \"hardware-affinity\"])\n});\nconst AgentLoadSummarySchema = z.object({\n nodeId: z.string(),\n online: z.boolean(),\n load: RunnerLocalLoadSchema,\n /** Computed score used by the L2 capacity balancer (lower = less loaded). */\n score: z.number()\n});\nconst GlobalMetricsSchema = z.object({\n totalAgents: z.number(),\n onlineAgents: z.number(),\n totalCameras: z.number(),\n attachedCameras: z.number(),\n activeCameras: z.number(),\n /** Average inference time across all agents weighted by their camera count. */\n avgInferenceTimeMs: z.number(),\n /** Total queue depth across all agents. */\n queueDepth: z.number()\n});\nconst CapabilityBindingsSchema = z.record(z.string(), z.string());\nconst pipelineOrchestratorCapability = {\n name: \"pipeline-orchestrator\",\n scope: \"system\",\n mode: \"singleton\",\n exposesDeviceSettings: true,\n methods: {\n // ── Pipeline placement overrides ────────────────────────────────────\n /**\n * Pin a camera's pipeline to a specific agent (L1 affinity).\n * The orchestrator re-evaluates the assignment immediately.\n */\n assignPipeline: method(\n z.object({ deviceId: z.number(), agentNodeId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Clear a camera's pipeline pin and let the auto-balancer re-pick\n * the optimal agent. The orchestrator persists `preferredAgent=null`\n * (and `pipelineNodeId='auto'`), then re-runs the balancer with the\n * cached `RunnerCameraConfig` and migrates only when the chosen\n * node differs. The camera stays in `getPipelineAssignments()` —\n * just with `pinned=false`. If no runner is currently available\n * (cluster-wide), the camera is left unassigned but the cached\n * config is kept so the next dispatch event re-attaches it.\n */\n unassignPipeline: method(\n z.object({ deviceId: z.number() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Trigger a full rebalance pass. Iterates over all assigned cameras,\n * recomputes the optimal agent for each one based on current load +\n * hardware affinity, and migrates cameras whose current agent is no\n * longer optimal. Pinned cameras are never migrated.\n */\n rebalance: method(z.void(), z.object({ migrated: z.number() }), { kind: \"mutation\", auth: \"admin\" }),\n // ── Observability ────────────────────────────────────────────────\n /** Get the full camera-to-agent assignment map. */\n getPipelineAssignments: method(z.void(), z.array(PipelineAssignmentSchema).readonly()),\n /** Get one camera's assignment, or null if unassigned. */\n getPipelineAssignment: method(z.object({ deviceId: z.number() }), PipelineAssignmentSchema.nullable()),\n /** Get per-agent load summaries used by the load balancer + dashboards. */\n getAgentLoad: method(z.void(), z.array(AgentLoadSummarySchema).readonly()),\n /** Aggregate global metrics across the whole detection cluster. */\n getGlobalMetrics: method(z.void(), GlobalMetricsSchema),\n /**\n * Per-camera live metrics (phase, fps, inference, queue, drops).\n * The orchestrator owns the device→agent assignment map and is the\n * canonical place to ask \"give me the metrics for this camera\". It\n * resolves the agent that holds the camera and delegates to that\n * runner's `getCameraMetrics`. Returns null if the device is not\n * assigned or the runner has no record for it (e.g. the camera was\n * just dispatched and the runner hasn't received the first frame).\n */\n getCameraMetrics: method(z.object({ deviceId: z.number() }), CameraMetricsSchema.nullable()),\n // ── Capability bindings (which addon implements each cap on each node) ──\n /** Read the capability binding map for one node. Empty record = no overrides (first-registered wins). */\n getCapabilityBindings: method(z.object({ nodeId: z.string() }), CapabilityBindingsSchema),\n /** Set the addon that implements `capName` on `nodeId`. Emits `capability.binding-changed`. */\n setCapabilityBinding: method(\n z.object({ nodeId: z.string(), capName: z.string(), addonId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Decoder scheduling ─────────────────────────────────────────────\n /** Pin a device's decoder to a specific node. */\n assignDecoder: method(\n z.object({ deviceId: z.number(), nodeId: z.string() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Clear a device's decoder pin (revert to auto). */\n unassignDecoder: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Get every camera's decoder placement. */\n getDecoderAssignments: method(z.void(), z.array(DecoderAssignmentSchema).readonly()),\n // ── Audio scheduling ───────────────────────────────────────────────\n /** Pin a device's audio analysis to a specific cluster node. */\n assignAudio: method(\n z.object({ deviceId: z.number(), nodeId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Clear a device's audio node pin (revert to auto load-balanced). */\n unassignAudio: method(\n z.object({ deviceId: z.number() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Get the current audio assignment for one device, or null if not yet assigned. */\n getAudioAssignment: method(\n z.object({ deviceId: z.number() }),\n z.object({\n nodeId: z.string(),\n pinned: z.boolean(),\n assignedAt: z.number()\n }).nullable()\n ),\n /** Get per-node audio load (device counts) for all known audio-analyzer nodes. */\n getAudioNodeLoad: method(\n z.void(),\n z.array(z.object({ nodeId: z.string(), deviceCount: z.number() }))\n ),\n /** Get all current audio assignments across all devices. */\n getAudioAssignments: method(\n z.void(),\n z.array(z.object({\n deviceId: z.number(),\n nodeId: z.string(),\n pinned: z.boolean(),\n assignedAt: z.number()\n }))\n ),\n /**\n * Get one camera's decoder placement (computed if not yet pinned).\n * Consumed by `stream-broker.createBroker` so decoder provider\n * selection is deterministic — fixes the 2026-04-18 race where\n * `capProviders[0]` silently picked ffmpeg-on-agent-0 for a\n * hub-assigned camera.\n *\n * `pipelineNodeId` is the node already chosen to run inference for\n * this camera. When provided, the balancer prefers co-location with\n * it; omitted → falls back to the last known assignment in the\n * `assignments` map and finally to 'hub'.\n */\n getDecoderAssignment: method(\n z.object({\n deviceId: z.number(),\n pipelineNodeId: z.string().optional()\n }),\n DecoderAssignmentSchema\n ),\n // NOTE: the `getDeviceOrchestrationSettings`,\n // `getDeviceOrchestrationOverrides` and `getGlobalOrchestrationSettings`\n // methods were removed in Phase 6. Consumers now read settings via\n // the standard 3-level resolver (`resolveAddonSettings`) over the\n // addon config store — see the top of this file for details.\n // ── 3-level pipeline settings (new model) ──────────────────────────\n //\n // Replaces the per-camera full-config + cluster-default model with:\n // `agent.addonDefaults` (flat per-addon config; auto-seeded from catalog),\n // `camera.stepToggles` (bool overlay; absent = inherit agent),\n // `camera.pipelineByAgent` (wholesale override escape hatch).\n //\n // The orchestrator's `resolvePipeline` collapses these into the\n // `CameraPipelineConfig` the runner consumes at dispatch.\n // `agentNodeId` (not `nodeId`) is intentional: the generated cap router\n // auto-routes any input field literally named `nodeId` to that node's\n // provider. `pipeline-orchestrator` is a HUB-SINGLETON cap — the\n // agent-node identifier here is DATA (\"which agent to read/write\"),\n // not routing. Using `agentNodeId` keeps the call on the hub as\n // intended.\n /** Read one agent's settings. Null when not yet seeded. */\n getAgentSettings: method(\n z.object({ agentNodeId: z.string() }),\n AgentPipelineSettingsSchema.nullable()\n ),\n /** Enumerate every agent's settings (hub + remote runners). */\n listAgentSettings: method(\n z.void(),\n z.array(z.object({\n nodeId: z.string(),\n settings: AgentPipelineSettingsSchema\n })).readonly()\n ),\n /** Bulk-replace ALL addon configs on one agent. Used by the agent-level PipelineEditor which emits the full map per edit. Merges on top of existing entries — omitted addonIds are left alone. */\n setAgentAddonDefaults: method(\n z.object({\n agentNodeId: z.string(),\n defaults: z.record(z.string(), AgentAddonConfigSchema)\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Drop a single agent's persisted settings. Used by the cluster\n * \"Offline agents\" panel to evict stale entries left behind when an\n * agent's data dir was rebuilt (new random nodeId) or older code wrote\n * the env name as the nodeId. The orchestrator otherwise never deletes\n * agentSettings — entries accumulate until a hub reset.\n *\n * `success: false` indicates the nodeId wasn't in the store (no-op).\n * Refuses to remove `hub` (the orchestrator always co-resides with it).\n */\n removeAgentSettings: method(\n z.object({ agentNodeId: z.string() }),\n z.object({ success: z.boolean(), removed: z.boolean() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // Phase 2f: `setAgentEngineChoice`, `setAgentHwAccel`,\n // `reprobeAgentHwAccel` removed. Engine ownership moved to the\n // `detection-pipeline` addon (`engineRuntime/engineBackend/engineDevice`\n // + `pipelineExecutor.reprobeEngine`). Hwaccel ownership moved to\n // each decoder addon (`decoder-nodeav`/`decoder-ffmpeg` global\n // settings + `decoder.reprobeHwaccel`). UI + decoder sessions read\n // via `api.addonSettings.getGlobalSettings({addonId, nodeId})`.\n /** Read one camera's settings. Null when never touched (inherits agent defaults fully). */\n getCameraSettings: method(\n z.object({ deviceId: z.number() }),\n CameraPipelineSettingsSchema.nullable()\n ),\n /** Set or clear the 3-state toggle for one (camera, addonId). Pass `enabled: null` to clear and revert to agent default. */\n setCameraStepToggle: method(\n z.object({\n deviceId: z.number(),\n addonId: z.string(),\n enabled: z.boolean().nullable()\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Read every L2.5 override map for a device. Null when device has no overrides. */\n getCameraStepOverrides: method(\n z.object({ deviceId: z.number() }),\n z.record(\n z.string(),\n // agentNodeId\n z.record(z.string(), CameraStepOverridePatchSchema)\n ).nullable()\n ),\n /**\n * Write or clear the L2.5 per-agent override for one addonId on a device.\n * `patch: null` clears the entry entirely for that (agent, addon) pair.\n */\n setCameraStepOverride: method(\n z.object({\n deviceId: z.number(),\n agentNodeId: z.string(),\n addonId: z.string(),\n patch: CameraStepOverridePatchSchema.nullable()\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Write or clear the wholesale per-agent pipeline override. Pass `pipeline: null` to drop the override. */\n setCameraPipelineForAgent: method(\n z.object({\n deviceId: z.number(),\n agentNodeId: z.string(),\n pipeline: CameraPipelineForAgentSchema.nullable()\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Resolve the effective pipeline for `(deviceId, agentNodeId?)` — walks the full precedence chain. Read-only preview used by the UI to show what will run. */\n resolvePipeline: method(\n z.object({ deviceId: z.number(), agentNodeId: z.string().optional() }),\n CameraPipelineConfigSchema\n ),\n // ── Template library (hub-only, read by any device-details UI) ─────\n /** List every template the operator has saved. */\n listTemplates: method(z.void(), z.array(PipelineTemplateSchema).readonly()),\n /** Create a new named preset from a given CameraPipelineConfig. */\n saveTemplate: method(\n z.object({\n name: z.string(),\n description: z.string().optional(),\n config: CameraPipelineConfigSchema\n }),\n PipelineTemplateSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Partial update of a template. Any omitted field is preserved. */\n updateTemplate: method(\n z.object({\n id: z.string(),\n name: z.string().optional(),\n description: z.string().optional(),\n config: CameraPipelineConfigSchema.optional()\n }),\n PipelineTemplateSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Remove a template. Camera configs that were seeded from it keep a copy. */\n deleteTemplate: method(\n z.object({ id: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst AudioAnalysisResultSchema = z.object({\n level: AudioLevelSchema,\n classification: z.object({\n labels: z.array(AudioClassificationLabelSchema).readonly(),\n inferenceMs: z.number()\n }).optional(),\n timestamp: z.number()\n});\nconst AudioAnalysisSettingsSchema = z.object({\n minConfidence: z.number().min(0).max(1).default(0.3),\n allowedClasses: z.array(z.string()).default([])\n});\nconst AudioClassificationResultSchema = z.object({\n // Macro-aggregated labels (25-class taxonomy from `AUDIO_MACRO_LABELS`).\n // Primary surface — used by the live audio analyzer and notifications.\n labels: z.array(AudioClassificationLabelSchema).readonly(),\n // Raw backend-native labels (e.g. YAMNet's 521 classes or Apple\n // SoundAnalysis's 303 classes), unaggregated. Optional so existing\n // consumers continue to work; populated by the analyzer provider\n // for callers that want fine-grained output — the benchmark UI uses\n // this in `micro` mode.\n rawLabels: z.array(AudioClassificationLabelSchema).readonly().optional(),\n inferenceMs: z.number()\n});\nconst AUDIO_BACKEND_CHOICES = [\n { value: \"auto\", label: \"Auto (platform default)\" },\n { value: \"apple-soundanalysis\", label: \"Apple SoundAnalysis (macOS 12+)\" },\n { value: \"yamnet-onnx\", label: \"YAMNet ONNX (cross-platform)\" }\n];\nconst DEFAULT_AUDIO_ANALYZER_CONFIG = {\n audioBackend: \"auto\",\n probedBestAudioBackend: \"\",\n selectedAudioModel: \"\"\n};\nconst audioAnalyzerCapability = {\n name: \"audio-analyzer\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n analyseChunk: method(\n z.object({ chunk: AudioChunkInputSchema, settings: AudioAnalysisSettingsSchema }),\n AudioAnalysisResultSchema.nullable(),\n { kind: \"mutation\" }\n ),\n // ONNX / Apple SoundAnalysis inference can exceed the broker's default\n // 5s requestTimeout on first load or under CPU pressure. 30s covers\n // even the worst-case cold-start without hanging indefinitely.\n classify: method(AudioChunkInputSchema, AudioClassificationResultSchema, { timeoutMs: 3e4 }),\n isReady: method(z.void(), z.boolean()),\n dispose: method(z.void(), z.void(), { kind: \"mutation\" }),\n /**\n * Re-run the host platform-probe for the audio backend and persist\n * the detected value into `probedBestAudioBackend`. Replaces the\n * orchestrator's legacy `AgentPipelineSettings.audio.engine` —\n * audio-analyzer now owns the choice. Operator `audioBackend` is\n * not touched; only the probed-best hint.\n */\n reprobeAudioEngine: method(\n z.void(),\n z.object({ backend: z.string() }),\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst audioAnalysisCapability = {\n name: \"audio-analysis\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n exposesDeviceSettings: true,\n methods: {\n /**\n * Resolve per-device audio analysis settings (minConfidence,\n * allowedClasses) from the addon settings store for a given camera.\n * Orchestrator callers use this before handing chunks to\n * `audio-analyzer.processChunk`.\n */\n resolveDeviceSettings: method(\n z.object({ deviceId: z.number() }),\n z.custom()\n )\n },\n events: {\n onAudioLevel: event(z.object({\n deviceId: z.number(),\n rms: z.number(),\n dbfs: z.number()\n }))\n }\n};\nconst PcmSampleFormatSchema = z.enum([\"f32le\", \"s16le\"]);\nconst AudioCodecInfoSchema = z.object({\n codec: z.string(),\n canDecode: z.boolean(),\n canEncode: z.boolean(),\n label: z.string().optional()\n});\nconst AudioDecodeSessionConfigSchema = z.object({\n codec: z.string(),\n sourceSampleRate: z.number().int().positive(),\n sourceChannels: z.number().int().positive(),\n extraData: z.instanceof(Uint8Array).optional(),\n targetSampleRate: z.number().int().positive(),\n targetChannels: z.number().int().positive(),\n targetFormat: PcmSampleFormatSchema.optional(),\n idleMs: z.number().int().positive().optional(),\n tag: z.string().optional()\n});\nconst AudioEncodeSessionConfigSchema = z.object({\n codec: z.string(),\n sourceSampleRate: z.number().int().positive(),\n sourceChannels: z.number().int().positive(),\n sourceFormat: PcmSampleFormatSchema.optional(),\n targetSampleRate: z.number().int().positive(),\n targetChannels: z.number().int().positive(),\n bitrateKbps: z.number().int().positive().optional(),\n idleMs: z.number().int().positive().optional(),\n tag: z.string().optional()\n});\nconst AudioPcmChunkSchema = z.object({\n data: z.instanceof(Uint8Array),\n sampleRate: z.number().int().positive(),\n channels: z.number().int().positive(),\n format: PcmSampleFormatSchema,\n pts: z.number()\n});\nconst AudioEncodedChunkSchema = z.object({\n data: z.instanceof(Uint8Array),\n codec: z.string(),\n pts: z.number(),\n frameComplete: z.boolean()\n});\nconst SessionInventoryEntrySchema = z.object({\n sessionId: z.string(),\n kind: z.enum([\"decode\", \"encode\"]),\n codec: z.string(),\n sourceSampleRate: z.number(),\n sourceChannels: z.number(),\n targetSampleRate: z.number(),\n targetChannels: z.number(),\n format: PcmSampleFormatSchema,\n tag: z.string().optional(),\n createdAtMs: z.number(),\n lastActivityMs: z.number(),\n framesIn: z.number(),\n framesOut: z.number()\n});\nconst audioCodecCapability = {\n name: \"audio-codec\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n // ── Discovery ─────────────────────────────────────────────────────────\n /** Probe the local runtime and return the supported codec matrix. */\n listSupportedCodecs: method(z.void(), z.array(AudioCodecInfoSchema).readonly()),\n /** Cheap predicate — does the runtime support `(codec, kind)`? */\n canHandle: method(\n z.object({ codec: z.string(), kind: z.enum([\"decode\", \"encode\"]) }),\n z.boolean()\n ),\n // ── Session lifecycle ─────────────────────────────────────────────────\n createDecodeSession: method(\n AudioDecodeSessionConfigSchema,\n z.object({ sessionId: z.string(), nodeId: z.string() }),\n { kind: \"mutation\" }\n ),\n createEncodeSession: method(\n AudioEncodeSessionConfigSchema,\n z.object({ sessionId: z.string(), nodeId: z.string() }),\n { kind: \"mutation\" }\n ),\n closeSession: method(\n z.object({ sessionId: z.string(), nodeId: z.string().optional() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n // ── Decode data plane ─────────────────────────────────────────────────\n // Session-bound methods include an optional `nodeId` field so the\n // generated cap router auto-routes calls to the same node that owns\n // the session. Audio-codec sessions are process-local — without sticky\n // routing the round-robin across nodes serves \"session not found\" on\n // every other call.\n /** Push one encoded audio frame into a decode session. */\n pushEncodedFrame: method(\n z.object({\n sessionId: z.string(),\n nodeId: z.string().optional(),\n data: z.instanceof(Uint8Array),\n /** Source PTS in milliseconds. Synthesised when omitted. */\n pts: z.number().optional()\n }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /** Pull up to `maxCount` PCM chunks from a decode session. */\n pullPcm: method(\n z.object({\n sessionId: z.string(),\n nodeId: z.string().optional(),\n maxCount: z.number().int().positive().default(8)\n }),\n z.array(AudioPcmChunkSchema)\n ),\n // ── Encode data plane ─────────────────────────────────────────────────\n /** Push one PCM chunk into an encode session. */\n pushPcm: method(\n z.object({\n sessionId: z.string(),\n nodeId: z.string().optional(),\n data: z.instanceof(Uint8Array),\n /** Source PTS in milliseconds. */\n pts: z.number().optional()\n }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /** Pull up to `maxCount` encoded chunks from an encode session. */\n pullEncoded: method(\n z.object({\n sessionId: z.string(),\n nodeId: z.string().optional(),\n maxCount: z.number().int().positive().default(8)\n }),\n z.array(AudioEncodedChunkSchema)\n ),\n /** Flush any pending encoded output (call before close on graceful tear). */\n flushEncode: method(\n z.object({ sessionId: z.string(), nodeId: z.string().optional() }),\n z.array(AudioEncodedChunkSchema),\n { kind: \"mutation\" }\n ),\n // ── Inventory ─────────────────────────────────────────────────────────\n listActiveSessions: method(\n z.void(),\n z.array(SessionInventoryEntrySchema).readonly()\n )\n }\n};\nconst EmbeddingResultSchema = z.object({\n embedding: z.array(z.number()),\n inferenceMs: z.number()\n});\nconst EmbeddingInfoSchema = z.object({\n modelId: z.string(),\n embeddingDim: z.number(),\n ready: z.boolean()\n});\nconst embeddingEncoderCapability = {\n name: \"embedding-encoder\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n encode: method(\n z.object({ crop: z.instanceof(Uint8Array), width: z.number(), height: z.number() }),\n EmbeddingResultSchema\n ),\n encodeText: method(z.object({ text: z.string() }), EmbeddingResultSchema),\n getInfo: method(z.void(), EmbeddingInfoSchema)\n }\n};\nconst DeviceInfoSchema = z.object({\n /** Progressive, system-wide unique number. Allocated synchronously by\n * `device-manager.allocateDeviceId` BEFORE the owning `IDevice` is\n * constructed, so every live device exposes an `id` — no transient\n * null window. Distinct from `stableId`, which is unique per\n * integration. Ids are monotonic and never reissued on removal. */\n id: z.number(),\n stableId: z.string(),\n addonId: z.string(),\n type: z.enum(DeviceType),\n name: z.string(),\n /** Operator-organisational location label. `null` when unset. */\n location: z.string().nullable(),\n /** Soft-disabled flag. */\n disabled: z.boolean(),\n parentDeviceId: z.number().nullable(),\n /** Optional semantic role — `DeviceRole` string. null for top-level devices. */\n role: z.string().nullable().optional(),\n online: z.boolean(),\n features: z.array(z.string()),\n /** true when the device has a getStreamSources() method (ICameraDevice) */\n isCamera: z.boolean(),\n /** Current config values — serializable snapshot */\n config: z.record(z.string(), z.unknown()),\n /** Hardware + identity blob (manufacturer / model / firmware / sn /\n * uid / mac / …). Populated by drivers; editable via setMetadata. */\n metadata: z.record(z.string(), z.unknown()).nullable().optional()\n});\nconst ConfigEntrySchema$1 = z.object({\n key: z.string(),\n value: z.unknown(),\n description: z.string().optional()\n});\nconst SavedDeviceRowSchema = z.object({\n /** Numeric id reserved at allocateDeviceId time. */\n id: z.number(),\n /** External-system identifier — required for the worker's `kernel.devices.create()` call. */\n stableId: z.string(),\n type: z.string(),\n name: z.string(),\n /** Operator-organisational location label. `null` when unset. */\n location: z.string().nullable(),\n /** Soft-disabled flag. */\n disabled: z.boolean(),\n parentDeviceId: z.number().nullable(),\n /** Optional semantic role — stringified `DeviceRole` enum value. null for top-level devices. */\n role: z.string().nullable().optional()\n});\nconst DeviceMetaSchema = z.object({\n id: z.number(),\n stableId: z.string(),\n addonId: z.string(),\n type: z.string(),\n name: z.string(),\n location: z.string().nullable(),\n disabled: z.boolean(),\n parentDeviceId: z.number().nullable(),\n metadata: z.record(z.string(), z.unknown()).nullable().optional()\n});\nconst ConfigUISchemaOutput = z.unknown().nullable();\nconst StreamProbeResultSchema = z.object({\n streamId: z.string(),\n width: z.number().optional(),\n height: z.number().optional(),\n codec: z.string().optional(),\n fps: z.number().optional(),\n bitrateKbps: z.number().optional()\n});\nconst DeviceRegisterPayloadSchema = z.object({\n addonId: z.string(),\n stableId: z.string(),\n /** Pre-allocated numeric id from `allocateDeviceId`. The hub persists\n * it alongside the meta record; callers never invent this value. */\n id: z.number(),\n type: z.string(),\n name: z.string(),\n /** Operator-organisational location label. Optional on register —\n * the hub seeds `null` when omitted. */\n location: z.string().nullable().optional(),\n /** Soft-disabled flag. Optional on register — the hub seeds `false`. */\n disabled: z.boolean().optional(),\n parentDeviceId: z.number().nullable(),\n /** Optional semantic role — see `DeviceRole`. Driver authors pass this\n * at register time when the device is an accessory with a known role. */\n role: z.string().nullable().optional(),\n /** Snapshot of `device.features` at registration time. Persisted in\n * `DeviceMeta` so the hub can answer `getDevice` for forked-worker\n * devices with the right `DeviceFeature[]` even when the live\n * instance lives on a remote node. Re-published on every register\n * call (workers re-register on init), so probe-driven updates\n * (e.g. PTZ flag flipping after the abilities probe) propagate. */\n features: z.array(z.string()).optional(),\n config: z.record(z.string(), z.unknown())\n});\nconst DeviceRemovePayloadSchema = z.object({\n deviceId: z.number()\n});\nconst DevicePersistConfigPayloadSchema = z.object({\n deviceId: z.number(),\n data: z.record(z.string(), z.unknown())\n});\nconst deviceManagerCapability = {\n name: \"device-manager\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n // ── Persistence (migrated from device-persistence) ────────────────────────\n /** Reserve (or re-resolve) a progressive numeric id for `(addonId, stableId)`.\n * Idempotent: returns the existing id if one is already persisted for the\n * pair. Callers invoke this before `registerDevice` so the live IDevice\n * can bind `id` at construction time through `DeviceContext.id`. */\n allocateDeviceId: method(\n z.object({ addonId: z.string(), stableId: z.string() }),\n z.object({ id: z.number() }),\n { kind: \"mutation\" }\n ),\n /** Register a device in the DB + in-memory registry. Called by DeviceManagerApi.register(). */\n registerDevice: method(DeviceRegisterPayloadSchema, z.void(), { kind: \"mutation\" }),\n /** Remove a device from the DB + in-memory registry. Called by DeviceManagerApi.remove(). */\n removeDevice: method(DeviceRemovePayloadSchema, z.void(), { kind: \"mutation\" }),\n /** Persist device config blob. Called by DeviceConfig.set/setAll(). */\n persistConfig: method(DevicePersistConfigPayloadSchema, z.void(), { kind: \"mutation\" }),\n /** Load persisted config for a device. Called at restore time. */\n loadConfig: method(\n z.object({ deviceId: z.number() }),\n z.record(z.string(), z.unknown())\n ),\n /** Load persisted runtime state. Called at device adopt time. */\n loadRuntimeState: method(\n z.object({ deviceId: z.number() }),\n z.record(z.string(), z.unknown())\n ),\n /** Load operator-organisational meta surface for a device. Called by\n * the kernel proxy to populate `DeviceContext.deviceMeta` before\n * the device class constructor runs. Returns `null` when the id\n * doesn't resolve to a persisted row. */\n loadMeta: method(\n z.object({ deviceId: z.number() }),\n DeviceMetaSchema.nullable()\n ),\n /** Update the operator-edited display name. Persists to the meta\n * row + emits `EventCategory.DeviceMetaChanged`. */\n setName: method(\n z.object({ deviceId: z.number(), name: z.string() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Update the operator-organisational location label. `null`\n * clears it. */\n setLocation: method(\n z.object({ deviceId: z.number(), location: z.string().nullable() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Patch the device's hardware-identity metadata blob. Merges\n * `patch` over the current blob (shallow). Value `null` for a\n * given key removes that key. Drivers populate factual fields\n * on first probe (model / firmware / mac / sn / uid); operators\n * can override or augment via the Device Info tab. */\n setMetadata: method(\n z.object({\n deviceId: z.number(),\n patch: z.record(z.string(), z.unknown())\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Operator-curated location registry. Returns the union of:\n * (1) labels persisted in the registry via `addLocation`, and\n * (2) labels currently in use on at least one device's\n * `meta.location` field.\n * Sorted case-insensitively + deduped + trimmed of empty strings.\n * Drives the autocomplete in the Device Info location editor. */\n listLocations: method(\n z.void(),\n z.array(z.string())\n ),\n /** Add a label to the curated location registry. No-op when the\n * label (case-insensitive, trimmed) is already present. Empty\n * / whitespace-only inputs throw. */\n addLocation: method(\n z.object({ name: z.string() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Remove a label from the curated registry. Devices that still\n * reference this label keep their `meta.location` value — the\n * registry is purely a suggestion list. To purge from devices,\n * iterate them and call `setLocation(deviceId, null)`\n * separately (or pass `cascade: true` to do it in one shot). */\n removeLocation: method(\n z.object({ name: z.string(), cascade: z.boolean().optional() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Soft-disable / re-enable the device. Drivers consult\n * `BaseDevice.disabled` to gate lifecycle hooks. */\n setDisabled: method(\n z.object({ deviceId: z.number(), disabled: z.boolean() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** List persisted devices for an addon (DB, for restore). */\n listPersistedByAddon: method(\n z.object({ addonId: z.string() }),\n z.array(SavedDeviceRowSchema)\n ),\n // ── Query — live registry ─────────────────────────────────────────────────\n /** List all devices (live registry), optionally filtered by addonId. */\n listAll: method(\n z.object({ addonId: z.string().optional() }),\n z.array(DeviceInfoSchema)\n ),\n /** Get a single device by numeric deviceId. */\n getDevice: method(\n z.object({ deviceId: z.number() }),\n DeviceInfoSchema.nullable()\n ),\n /** List children of a parent device (by parent numeric id). */\n getChildren: method(\n z.object({ parentDeviceId: z.number() }),\n z.array(DeviceInfoSchema)\n ),\n // ── Runtime — live device operations ─────────────────────────────────────\n /** Get stream sources for a camera device. */\n getStreamSources: method(\n z.object({ deviceId: z.number() }),\n z.array(StreamSourceEntrySchema$1)\n ),\n /** Get config entries (key + value + description) for a device. */\n getConfigSchema: method(\n z.object({ deviceId: z.number() }),\n z.array(ConfigEntrySchema$1)\n ),\n /** Get the ConfigUISchema for a device's settings (for admin UI rendering). */\n getSettingsSchema: method(\n z.object({ deviceId: z.number() }),\n ConfigUISchemaOutput\n ),\n // ── Mutations — config changes, enable/disable, remove ────────────────────\n /** Update device config values (partial merge). */\n updateConfig: method(\n z.object({\n deviceId: z.number(),\n values: z.record(z.string(), z.unknown())\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Enable a device (writes enabled=true to device config). */\n enable: method(\n z.object({ deviceId: z.number() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Disable a device (writes enabled=false to device config). */\n disable: method(\n z.object({ deviceId: z.number() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Remove a device and all children: calls device.removeDevice() then removes from registry + DB. */\n remove: method(\n z.object({ deviceId: z.number() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Stream profile map ────────────────────────────────────────────────────\n /** Get quality→streamId mapping for a camera. Derived from profileHint if not explicitly set. */\n getStreamProfileMap: method(\n z.object({ deviceId: z.number() }),\n z.record(z.string(), z.string().nullable())\n ),\n /** Persist quality→streamId mapping in device config under reserved key _profileMap. */\n setStreamProfileMap: method(\n z.object({\n deviceId: z.number(),\n profileMap: z.record(z.string(), z.string().nullable())\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Run ffprobe on each stream source URL and return metadata. No-op if stream probe unavailable. */\n probeStreams: method(\n z.object({ deviceId: z.number() }),\n z.array(StreamProbeResultSchema),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Bindings — per-device capability provider map ────────────────────────\n /**\n * Return the per-capability binding map for a device. Each entry lists the\n * currently-active provider (native or wrapper) + the underlying native\n * addon id, so consumers can decide routing without re-running discovery.\n */\n getBindings: method(\n z.object({ deviceId: z.number() }),\n z.object({\n deviceId: z.number(),\n entries: z.array(z.object({\n capName: z.string(),\n kind: z.enum([\"native\", \"wrapped\"]),\n providerAddonId: z.string(),\n providerNodeId: z.string(),\n nativeAddonId: z.string()\n }))\n })\n ),\n /**\n * Return the binding map for every device known to the hub. Used by\n * `SystemManager` warm-boot: a single round-trip resolves the\n * routing for the entire fleet so subsequent `sm.getDeviceById(id)`\n * calls are sync. Bindings change rarely (only on wrapper toggle or\n * device add/remove) — clients invalidate via the\n * `capability.binding-changed` event.\n */\n getAllBindings: method(\n z.object({}),\n z.array(z.object({\n deviceId: z.number(),\n entries: z.array(z.object({\n capName: z.string(),\n kind: z.enum([\"native\", \"wrapped\"]),\n providerAddonId: z.string(),\n providerNodeId: z.string(),\n nativeAddonId: z.string()\n }))\n }))\n ),\n /**\n * Activate (or deactivate) a wrapper addon for a (device, cap) pair.\n * Persists the binding via ctx.settings. active=false clears the wrapper\n * (falls back to native if registered).\n */\n setWrapperActive: method(\n z.object({\n deviceId: z.number(),\n capName: z.string(),\n wrapperAddonId: z.string(),\n active: z.boolean()\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Return the addon ids that declared a wrapper provider for `capName`.\n * Backs the device-bindings UI's wrapper-picker dropdown. Entries are\n * sourced from `CapabilityRegistry.wrapperProviders`, populated at\n * `ProviderRegistration.kind === 'wrapper'` time.\n */\n listWrappersForCap: method(\n z.object({ capName: z.string() }),\n z.array(z.string())\n ),\n /**\n * Return every device-scoped capability name that applies to a\n * deviceType (scope:'device' + deviceTypes includes the given type),\n * paired with the wrappers that can provide it. Backs the device\n * bindings UI so it can show rows for bindable caps even when no\n * native is registered yet — the user can still activate a wrapper\n * to light the cap up (e.g. snapshot via ffmpeg fallback for a camera\n * without `snapshotUrl`).\n */\n listBindableCapsForDeviceType: method(\n z.object({ deviceType: z.string() }),\n z.array(z.object({\n capName: z.string(),\n wrappers: z.array(z.string())\n }))\n ),\n // ── Device-details aggregators ───────────────────────────────────────────\n //\n // Single entry point the admin UI calls to render the device-details page.\n // The hub enumerates every provider of `device-settings-contributor` (a\n // `collection` cap) plus its own base section and returns a single\n // `ConfigUISchemaWithValues` with merged tabs/sections.\n //\n // Two endpoints, two cadences:\n // - `getDeviceSettingsAggregate` — editable fields + static readonly.\n // Cached on the UI side, invalidated on successful `updateDeviceField`.\n // - `getDeviceLiveInfoAggregate` — readonly, dynamic. UI polls at a\n // short interval (~2-3 s). Fields carry `source: 'live'` so the\n // renderer knows which query owns the value.\n //\n // Save flow goes through `updateDeviceField` — the aggregator routes the\n // write to `addon-settings.updateDeviceSettings` for the declared\n // `writerAddonId` (or to its own device config store when `writerAddonId`\n // equals the device-manager addon id).\n getDeviceSettingsAggregate: method(\n z.object({ deviceId: z.number() }),\n SettingsSchemaWithValuesSchema.nullable()\n ),\n getDeviceLiveInfoAggregate: method(\n z.object({ deviceId: z.number() }),\n SettingsSchemaWithValuesSchema.nullable()\n ),\n /**\n * Unified entry point — returns both settings + live in a single call\n * so the admin UI pulls the whole device-details panel with one round-\n * trip instead of firing two parallel queries. The `live` field is the\n * polled portion; the UI re-fetches the whole aggregate at the live\n * cadence and uses the `settings` slice verbatim until the user\n * writes through `updateDeviceFieldsBatch`.\n */\n getDeviceAggregate: method(\n z.object({ deviceId: z.number() }),\n z.object({\n settings: SettingsSchemaWithValuesSchema.nullable(),\n live: SettingsSchemaWithValuesSchema.nullable()\n })\n ),\n updateDeviceField: method(\n z.object({\n deviceId: z.number(),\n writerCapName: z.string(),\n writerAddonId: z.string(),\n key: z.string(),\n value: z.unknown()\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Batched counterpart of `updateDeviceField` — the admin UI groups\n * per-provider changes so a single round-trip triggers at most one\n * `applyDeviceSettingsPatch` per `(capName, addonId)` tuple. Per-patch\n * failures are reported in `failures[]` without aborting the others;\n * consumers inspect the list and surface targeted errors.\n */\n updateDeviceFieldsBatch: method(\n z.object({\n deviceId: z.number(),\n changes: z.array(z.object({\n writerCapName: z.string(),\n writerAddonId: z.string(),\n key: z.string(),\n value: z.unknown()\n }))\n }),\n z.object({\n success: z.literal(true),\n failures: z.array(z.object({\n writerCapName: z.string(),\n writerAddonId: z.string(),\n error: z.string()\n }))\n }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Device-provider operations (routed via CapabilityRegistry) ────────────\n //\n // These methods proxy to the `device-provider` capability collection,\n // routing by addonId. Moving them here from the compat router\n // (`device-ops.router.ts`) allows addon ctx.api callers to reach them\n // through the standard Moleculer-registered cap surface.\n /** Trigger device discovery on a device-provider addon. */\n discoverDevices: method(\n z.object({ addonId: z.string() }),\n z.array(DiscoveryCandidateSchema),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Adopt a discovered device via the device-provider capability. */\n adoptDevice: method(\n z.object({\n addonId: z.string(),\n candidate: DiscoveryCandidateSchema\n }),\n DeviceSummarySchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Get the creation form schema (ConfigUISchema) for a device type from a provider.\n * Returns null when the provider does not support manual creation.\n */\n getCreationSchema: method(\n z.object({\n addonId: z.string(),\n type: z.enum(DeviceType)\n }),\n z.unknown().nullable()\n ),\n /** Create a new device via the device-provider capability. */\n createDevice: method(\n z.object({\n addonId: z.string(),\n type: z.enum(DeviceType),\n config: z.record(z.string(), z.unknown())\n }),\n DeviceSummarySchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Test a single form field value during device creation (no device\n * exists yet). `formValues` carries the live snapshot of every\n * field in the form so probes that depend on multiple fields (e.g.\n * Reolink autodetect needs host + credentials + UID together) can\n * run without a separate round-trip per field. Optional for\n * backwards compatibility.\n */\n testCreationField: method(\n z.object({\n addonId: z.string(),\n type: z.enum(DeviceType),\n key: z.string(),\n value: z.unknown(),\n formValues: z.record(z.string(), z.unknown()).optional()\n }),\n FieldProbeResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Test a field value on an existing device (e.g. probe an RTSP URL).\n * Routes through the device-provider for the owning addon.\n */\n testField: method(\n z.object({\n deviceId: z.number(),\n key: z.string(),\n value: z.unknown()\n }),\n FieldProbeResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Aggregate status snapshot across every cap registered for a\n * device. Returns a flat map `{ capName: status | null }` where\n * `status` is whatever `capDef.status.schema` validates to — or\n * `null` when no provider for that cap is registered on the\n * device, or the provider returned null, or the returned value\n * failed validation.\n *\n * `caps` is a positional tuple of cap names. The runtime only\n * returns entries for caps that are KNOWN to the system (validated\n * against `CAP_NAMES_WITH_STATUS` at call time); unknown names are\n * silently skipped. The client-side hook narrows the return type\n * using `CapStatusTypeMap` so the TS-inferred shape matches the\n * runtime shape.\n *\n * When `caps` is omitted, the server returns status for EVERY\n * registered cap on the device. Use this only for debug / overview\n * pages — it's O(N caps) per call.\n */\n getDeviceStatusAggregate: method(\n z.object({\n deviceId: z.number(),\n caps: z.array(z.string()).readonly().optional()\n }),\n z.record(z.string(), z.unknown().nullable())\n )\n }\n};\nconst deviceStateCapability = {\n name: \"device-state\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n /** Full state snapshot for one device. Empty object if no\n * cap-keyed slice has been written yet. */\n getSnapshot: method(\n z.object({ deviceId: z.number() }),\n z.record(z.string(), z.record(z.string(), z.unknown()))\n ),\n /** Single cap slice. Returns null when the slice hasn't been\n * written or the device isn't registered. */\n getCapSlice: method(\n z.object({ deviceId: z.number(), capName: z.string() }),\n z.record(z.string(), z.unknown()).nullable()\n ),\n /**\n * Whole-system snapshot — every device's full state in one\n * payload. Used by `SystemManager` for warm-boot: a single\n * round-trip populates the client mirror so every subsequent\n * `sm.getDeviceById(id).state.<cap>.value` is sync. Empty inner\n * record for devices that haven't emitted any slice yet.\n */\n getAllSnapshots: method(\n z.object({}),\n z.record(z.string(), z.record(z.string(), z.record(z.string(), z.unknown())))\n ),\n /**\n * Canonical cross-layer WRITE for one cap-keyed slice. Used by\n * everyone who needs to publish runtime state for a device:\n * device providers (via `BaseDevice.runtimeState.setCapState`\n * which delegates here), system-scope addons (e.g. the pipeline\n * runner writing the `motion` slice on phase transitions), and\n * direct cap-router callers in tests.\n *\n * Behavior on the hub:\n * 1. Resolve the device — throws if unknown.\n * 2. Diff the slice against the current mirror (no-op on\n * identical writes — saves disk and event churn).\n * 3. Update the mirror in place.\n * 4. Persist the full per-device blob to disk (debounced).\n * 5. Emit `onChanged` for this cap so subscribers (UI mirror,\n * SystemManager, per-cap typed listeners) refresh.\n *\n * Schema validation is the caller's responsibility — callers\n * going through `BaseDevice.runtimeState.setCapState` get the\n * cap's `runtimeState` schema enforced in-process before the\n * write reaches here. Direct callers should validate against\n * the cap's schema themselves.\n *\n * No `patch` variant — for shallow merges read the slice via\n * `getCapSlice` first, merge, and write. The single-writer\n * conventions on each cap make atomic-merge semantics\n * unnecessary in practice.\n */\n setCapSlice: method(\n z.object({\n deviceId: z.number(),\n capName: z.string(),\n slice: z.record(z.string(), z.unknown())\n }),\n z.void(),\n { kind: \"mutation\" }\n )\n },\n events: {\n /**\n * Fires whenever a cap-keyed slice changes. Per-event payload\n * carries the slice that changed — subscribers can render off\n * the payload alone without re-querying. Filterable by `deviceId`\n * via the standard `EventFilter` helpers.\n */\n onChanged: event(z.object({\n deviceId: z.number(),\n capName: z.string(),\n slice: z.record(z.string(), z.unknown())\n }))\n }\n};\nconst AuthResultSchema = z.object({\n userId: z.string(),\n username: z.string(),\n email: z.string().optional(),\n displayName: z.string().optional(),\n /**\n * Whether the authenticating user is an admin. The auth-provider\n * surface returns this so the server's login flow can mint a JWT\n * with the correct bypass flag. Non-admin users authenticated via\n * an external IdP still need their scopes assigned by an admin via\n * `setUserScopes` — the SSO flow doesn't carry permissions.\n */\n isAdmin: z.boolean().default(false)\n});\nconst authProviderCapability = {\n name: \"auth-provider\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n validateCredentials: method(\n z.object({ username: z.string(), password: z.string() }),\n AuthResultSchema.nullable(),\n { kind: \"mutation\" }\n ),\n getLoginUrl: method(z.object({ state: z.string() }), z.string()),\n handleCallback: method(z.record(z.string(), z.string()), AuthResultSchema, { kind: \"mutation\" }),\n validateToken: method(z.object({ token: z.string() }), AuthResultSchema.nullable())\n }\n};\nconst NetworkEndpointSchema = z.object({\n url: z.string(),\n hostname: z.string(),\n port: z.number(),\n protocol: z.enum([\"http\", \"https\"])\n});\nconst NetworkAccessStatusSchema = z.object({\n connected: z.boolean(),\n endpoint: NetworkEndpointSchema.nullable(),\n error: z.string().optional()\n});\nconst NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({\n /**\n * Stable id within the provider — typically `<mode>-<sourcePort>` so\n * the orchestrator can dedupe across `listEndpoints` polls.\n */\n id: z.string(),\n /** Operator-facing label (mirrors `MeshEndpoint.label`). */\n label: z.string(),\n /** Optional provider-specific mode tag, used for icon/colour in admin UI. */\n mode: z.string().optional(),\n /** Originating local port the ingress fronts (informational). */\n sourcePort: z.number().optional()\n});\nconst networkAccessCapability = {\n name: \"network-access\",\n scope: \"system\",\n mode: \"collection\",\n providerKind: \"ingress\",\n methods: {\n start: method(z.void(), NetworkEndpointSchema, { kind: \"mutation\" }),\n stop: method(z.void(), z.void(), { kind: \"mutation\" }),\n getEndpoint: method(z.void(), NetworkEndpointSchema.nullable()),\n getStatus: method(z.void(), NetworkAccessStatusSchema),\n /**\n * Enumerate every active ingress entry. Providers that expose only a\n * single endpoint may omit this method; callers fall back to\n * `getEndpoint()` in that case.\n */\n listEndpoints: method(z.void(), z.array(NetworkEndpointEntrySchema).readonly())\n }\n};\nconst TurnServerSchema = z.object({\n /** Single URL or list of URLs (e.g. \"turn:turn.example.com:3478?transport=udp\"). */\n urls: z.union([z.string(), z.array(z.string())]),\n username: z.string().optional(),\n credential: z.string().optional()\n});\nconst turnProviderCapability = {\n name: \"turn-provider\",\n scope: \"system\",\n mode: \"collection\",\n methods: {\n /**\n * Return the current list of TURN/STUN servers with credentials.\n * Implementations may fetch fresh short-lived credentials on each call\n * (e.g. Cloudflare API) — consumers SHOULD call this per-session.\n */\n getTurnServers: method(\n z.void(),\n z.array(TurnServerSchema).readonly()\n )\n }\n};\nconst SnapshotImageSchema = z.object({\n base64: z.string(),\n contentType: z.string()\n});\nconst SnapshotStatusSchema = z.object({\n /** Ms epoch of the last successful capture. Null if none yet. */\n lastCapturedAt: z.number().nullable(),\n /** Age of the cached image in ms. Null if no cache. */\n cacheAgeMs: z.number().nullable(),\n /** Size in bytes of the last captured image. Null if no capture. */\n lastBytes: z.number().nullable(),\n /** Stream id used for the last capture ('high'|'mid'|'low' or custom). Null if via HTTP endpoint. */\n lastStreamId: z.string().nullable()\n});\nconst snapshotCapability = {\n name: \"snapshot\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n // Owns per-device snapshot settings (preferred stream, debug logging).\n // The three DeviceSettingsContribution methods are auto-added to the\n // provider interface via `InferProvider` — `SnapshotAddon` implements\n // them and persists per-device state through `ctx.settings.writeDeviceStore`.\n exposesDeviceSettings: true,\n methods: {\n getSnapshot: method(\n z.object({\n deviceId: z.number(),\n streamId: z.string().optional(),\n /**\n * Bypass the cache freshness check and fetch directly from the\n * native (or stream-broker fallback). Triggered by the UI's\n * \"refresh\" button so an operator can force a fresh frame\n * even when the cache is well within `snapshotMaxAgeMs`.\n * On battery cams this WILL wake the camera — accept the\n * cost only when the user explicitly asks for it.\n */\n force: z.boolean().optional()\n }),\n SnapshotImageSchema.nullable()\n ),\n invalidateCache: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n },\n status: {\n schema: SnapshotStatusSchema,\n kind: \"poll\"\n }\n};\nconst snapshotProviderCapability = {\n name: \"snapshot-provider\",\n scope: \"system\",\n mode: \"collection\",\n methods: {\n supportsDevice: method(\n z.object({ deviceId: z.number() }),\n z.boolean()\n ),\n getSnapshot: method(\n z.object({\n deviceId: z.number(),\n streamId: z.string().optional()\n }),\n SnapshotImageSchema.nullable()\n )\n }\n};\nconst NotificationSchema = z.object({\n title: z.string(),\n body: z.string(),\n imageUrl: z.string().optional(),\n deviceId: z.number().optional(),\n eventId: z.string().optional(),\n priority: z.enum([\"low\", \"normal\", \"high\", \"critical\"]).default(\"normal\"),\n metadata: z.record(z.string(), z.unknown()).optional()\n});\nconst notificationOutputCapability = {\n name: \"notification-output\",\n scope: \"system\",\n mode: \"collection\",\n methods: {\n send: method(NotificationSchema, z.void(), { kind: \"mutation\" }),\n sendTest: method(\n z.void(),\n z.object({ success: z.boolean(), error: z.string().optional() }),\n { kind: \"mutation\" }\n )\n }\n};\nconst NotificationRuleConditionsSchema = z.object({\n deviceIds: z.array(z.number()).readonly().optional(),\n classNames: z.array(z.string()).readonly().optional(),\n zoneIds: z.array(z.string()).readonly().optional(),\n minConfidence: z.number().optional(),\n source: z.enum([\"pipeline\", \"onboard\", \"any\"]).optional(),\n schedule: z.object({\n days: z.array(z.number()).readonly(),\n startHour: z.number(),\n endHour: z.number()\n }).optional(),\n cooldownSeconds: z.number().optional(),\n minDwellSeconds: z.number().optional()\n});\nconst NotificationRuleTemplateSchema = z.object({\n title: z.string(),\n body: z.string(),\n imageMode: z.enum([\"crop\", \"annotated\", \"full\", \"none\"])\n});\nconst NotificationRuleSchema = z.object({\n id: z.string(),\n name: z.string(),\n enabled: z.boolean(),\n eventTypes: z.array(z.string()).readonly(),\n conditions: NotificationRuleConditionsSchema,\n outputs: z.array(z.string()).readonly(),\n template: NotificationRuleTemplateSchema.optional(),\n priority: z.enum([\"low\", \"normal\", \"high\", \"critical\"])\n});\nconst NotificationTestResultSchema = z.object({\n ruleId: z.string(),\n eventId: z.string(),\n timestamp: z.number(),\n wouldFire: z.boolean(),\n reason: z.string().optional()\n});\nconst NotificationHistoryEntrySchema = z.object({\n id: z.string(),\n ruleId: z.string(),\n ruleName: z.string(),\n eventId: z.string(),\n timestamp: z.number(),\n outputs: z.array(z.string()).readonly(),\n success: z.boolean(),\n error: z.string().optional(),\n deviceId: z.number().optional()\n});\nconst NotificationHistoryFilterSchema = z.object({\n ruleId: z.string().optional(),\n deviceId: z.number().optional(),\n from: z.number().optional(),\n to: z.number().optional(),\n limit: z.number().optional()\n});\nconst advancedNotifierCapability = {\n name: \"advanced-notifier\",\n scope: \"system\",\n mode: \"singleton\",\n internal: true,\n methods: {\n getRules: method(\n z.void(),\n z.object({ rules: z.array(NotificationRuleSchema).readonly() })\n ),\n upsertRule: method(\n z.object({ rule: NotificationRuleSchema }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\" }\n ),\n deleteRule: method(\n z.object({ ruleId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\" }\n ),\n testRule: method(\n z.object({ ruleId: z.string(), lookbackMinutes: z.number() }),\n z.object({ results: z.array(NotificationTestResultSchema).readonly() }),\n { kind: \"mutation\" }\n ),\n getHistory: method(\n z.object({ filter: NotificationHistoryFilterSchema.optional() }),\n z.object({ entries: z.array(NotificationHistoryEntrySchema).readonly() })\n )\n }\n};\nconst RecordingModeSchema = z.enum([\"continuous\", \"motion\", \"scheduled\", \"composite\"]);\nconst StreamPolicySchema = z.object({\n streamId: z.string(),\n mode: z.enum([\"always\", \"inherit\"])\n});\nconst ScheduleRuleSchema = z.object({\n days: z.array(z.number()).readonly(),\n startTime: z.string(),\n endTime: z.string(),\n mode: z.enum([\"continuous\", \"motion\"])\n});\nconst RecordingPolicySchema = z.object({\n deviceId: z.number(),\n mode: RecordingModeSchema,\n streams: z.array(StreamPolicySchema).readonly(),\n enabled: z.boolean(),\n preBufferSec: z.number(),\n postBufferSec: z.number(),\n scheduleRules: z.array(ScheduleRuleSchema).readonly().optional()\n});\nconst DataCategorySchema = z.enum([\n \"recording:main\",\n \"recording:mid\",\n \"recording:sub\",\n \"thumbnail:scrub\",\n \"thumbnail:event\"\n]);\nconst RecordingStorageConfigSchema = z.object({\n deviceId: z.number(),\n dataCategory: DataCategorySchema,\n storageName: z.string(),\n subDirectory: z.string(),\n retentionDays: z.number().nullable(),\n retentionGb: z.number().nullable()\n});\nconst RecordingSegmentSchema = z.object({\n id: z.string(),\n deviceId: z.number(),\n streamId: z.string(),\n startTime: z.number(),\n endTime: z.number(),\n duration: z.number(),\n path: z.string(),\n storageName: z.string(),\n subDirectory: z.string(),\n sizeBytes: z.number(),\n codec: z.enum([\"h264\", \"h265\"]),\n hasAudio: z.boolean()\n});\nconst RecordingThumbnailSchema = z.object({\n deviceId: z.number(),\n timestamp: z.number(),\n path: z.string(),\n storageName: z.string(),\n subDirectory: z.string(),\n sizeBytes: z.number(),\n category: z.enum([\"scrub\", \"event\"])\n});\nconst AvailabilityRangeSchema = z.object({\n startTime: z.number(),\n endTime: z.number(),\n streams: z.array(z.string()).readonly()\n});\nconst StorageUsageSchema = z.object({\n totalBytes: z.number(),\n segmentCount: z.number()\n});\nconst StreamEstimateSchema = z.object({\n bitrateKbps: z.number(),\n retentionDays: z.number().nullable(),\n retentionGb: z.number().nullable(),\n estimatedGb: z.number(),\n estimatedDaysAtCapacity: z.number().nullable()\n});\nconst StorageEstimateSchema = z.object({\n perStream: z.record(z.string(), StreamEstimateSchema),\n thumbnails: z.object({ estimatedGb: z.number() }),\n totalEstimatedGb: z.number(),\n motionEstimate: z.object({\n avgEventsPerDay: z.number(),\n avgDurationSec: z.number(),\n dutyCyclePercent: z.number()\n }).optional()\n});\nconst MotionStatsSchema = z.object({\n totalEvents: z.number(),\n avgDurationSec: z.number(),\n avgEventsPerDay: z.number(),\n dutyCyclePercent: z.number()\n});\nconst DeviceIdInput = z.object({ deviceId: z.number() });\nconst EnableInput = z.object({\n deviceId: z.number(),\n policy: RecordingPolicySchema.omit({ deviceId: true }),\n storageOverrides: z.array(RecordingStorageConfigSchema.omit({ deviceId: true })).readonly().optional(),\n ffmpegOverrides: z.record(z.string(), z.unknown()).optional()\n});\nconst TimeRangeInput = z.object({\n deviceId: z.number(),\n startTime: z.number(),\n endTime: z.number()\n});\nconst StreamTimeRangeInput = z.object({\n deviceId: z.number(),\n streamId: z.string(),\n startTime: z.number(),\n endTime: z.number()\n});\nconst PlaylistInput = z.object({\n deviceId: z.number(),\n streamId: z.string(),\n startTime: z.number(),\n endTime: z.number(),\n live: z.boolean().optional()\n});\nconst ThumbnailInput = z.object({\n deviceId: z.number(),\n timestamp: z.number(),\n category: z.string().optional()\n});\nconst DeviceStreamInput = z.object({\n deviceId: z.number(),\n streamId: z.string()\n});\nconst StorageEstimateInput = z.object({\n deviceId: z.number(),\n motionInput: z.object({\n avgEventsPerDay: z.number(),\n avgDurationSec: z.number()\n }).optional()\n});\nconst RetentionConfigInput = z.object({\n deviceId: z.number(),\n dataCategory: DataCategorySchema\n});\nconst SetPolicyInput = z.object({\n deviceId: z.number(),\n policy: RecordingPolicySchema.omit({ deviceId: true })\n});\nconst UpdateConfigInput = z.object({\n deviceId: z.number(),\n policy: RecordingPolicySchema.omit({ deviceId: true }),\n ffmpegOverrides: z.record(z.string(), z.unknown()).optional()\n});\nconst recordingEngineCapability = {\n name: \"recording-engine\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n // ── Status ────────────────────────────────────────────────────────\n getStatus: method(z.void(), z.object({\n activeRecordings: z.number(),\n totalSegments: z.number(),\n totalSizeMB: z.number()\n })),\n // ── Lifecycle ─────────────────────────────────────────────────────\n enable: method(EnableInput, z.void(), { kind: \"mutation\", auth: \"admin\" }),\n disable: method(DeviceIdInput, z.void(), { kind: \"mutation\", auth: \"admin\" }),\n // ── Config ────────────────────────────────────────────────────────\n getConfig: method(DeviceIdInput, RecordingPolicySchema.nullable()),\n updateConfig: method(UpdateConfigInput, z.void(), { kind: \"mutation\", auth: \"admin\" }),\n // ── Playback ──────────────────────────────────────────────────────\n getPlaylist: method(PlaylistInput, z.string()),\n getThumbnail: method(ThumbnailInput, RecordingThumbnailSchema.nullable()),\n getSegments: method(StreamTimeRangeInput, z.array(RecordingSegmentSchema).readonly()),\n getAvailability: method(TimeRangeInput, z.array(AvailabilityRangeSchema).readonly()),\n // ── Storage ───────────────────────────────────────────────────────\n estimateStorage: method(StorageEstimateInput, StorageEstimateSchema),\n estimateGlobalStorage: method(z.void(), StorageEstimateSchema),\n getStorageUsage: method(DeviceStreamInput, StorageUsageSchema),\n // ── Policy ────────────────────────────────────────────────────────\n setPolicy: method(SetPolicyInput, z.void(), { kind: \"mutation\", auth: \"admin\" }),\n getPolicy: method(DeviceIdInput, RecordingPolicySchema.nullable()),\n getPolicyStatus: method(DeviceIdInput, z.object({\n deviceId: z.number(),\n enabled: z.boolean(),\n mode: RecordingModeSchema,\n activeStreams: z.number()\n }).nullable()),\n // ── Retention ─────────────────────────────────────────────────────\n getRetentionConfig: method(RetentionConfigInput, RecordingStorageConfigSchema.nullable()),\n updateRetentionConfig: method(RecordingStorageConfigSchema, z.void(), { kind: \"mutation\", auth: \"admin\" }),\n // ── Motion ────────────────────────────────────────────────────────\n getMotionStats: method(TimeRangeInput, MotionStatsSchema)\n }\n};\nconst detectionPipelineCapability = {\n name: \"detection-pipeline\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n exposesDeviceSettings: true,\n methods: {}\n};\nconst TrackStateSchema = z.enum([\"new\", \"entered\", \"left\", \"moving\", \"idle\"]);\nconst EventKindSchema = z.enum([\"motion\", \"object\", \"audio\"]);\nconst TrackPositionSchema = z.object({\n x: z.number(),\n y: z.number(),\n timestamp: z.number(),\n bbox: BoundingBoxSchema\n});\nconst TrackSnapshotSchema = z.object({\n timestamp: z.number(),\n position: TrackPositionSchema,\n /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */\n mediaKey: z.string()\n});\nconst TrackSchema = z.object({\n trackId: z.string(),\n deviceId: z.number(),\n className: z.string(),\n label: z.string().optional(),\n firstSeen: z.number(),\n lastSeen: z.number(),\n /** Frame-rate position history (subject to maxPositionHistory cap). */\n positions: z.array(TrackPositionSchema).readonly(),\n /** Periodic snapshots at snapshotIntervalMs cadence (subject to\n * saveThumbnails policy). */\n snapshots: z.array(TrackSnapshotSchema).readonly(),\n /** Deduplicated zones the track has entered at least once. */\n zonesVisited: z.array(z.string()).readonly(),\n /** Cumulative normalized distance travelled (0..1 units = full frame width). */\n totalDistance: z.number(),\n state: TrackStateSchema,\n active: z.boolean()\n});\nconst BaseEventFields = {\n id: z.string(),\n deviceId: z.number(),\n timestamp: z.number()\n};\nconst MotionEventSchema = z.object({\n ...BaseEventFields,\n kind: z.literal(\"motion\"),\n regionCount: z.number(),\n regions: z.array(z.object({\n bbox: BoundingBoxSchema,\n pixelCount: z.number(),\n intensity: z.number()\n })).readonly(),\n frameWidth: z.number(),\n frameHeight: z.number()\n});\nconst ObjectEventSchema = z.object({\n ...BaseEventFields,\n kind: z.literal(\"object\"),\n trackId: z.string(),\n className: z.string(),\n label: z.string().optional(),\n confidence: z.number(),\n bbox: BoundingBoxSchema,\n zones: z.array(z.string()).readonly(),\n state: TrackStateSchema,\n /** MediaStore key for the crop attached to this event (if any). */\n mediaKey: z.string().optional()\n});\nconst AudioEventSchema = z.object({\n ...BaseEventFields,\n kind: z.literal(\"audio\"),\n rms: z.number(),\n dbfs: z.number(),\n classification: z.object({\n className: z.string(),\n originalClass: z.string().optional(),\n score: z.number()\n }).optional()\n});\nconst MediaFileSchema = z.object({\n key: z.string(),\n kind: z.enum([\"crop\", \"thumbnail\", \"snapshot\"]),\n base64: z.string(),\n sizeBytes: z.number(),\n timestamp: z.number()\n});\nconst DEFAULT_EVENT_QUERY_LIMIT = 1e3;\nconst MAX_EVENT_QUERY_LIMIT = 5e3;\nconst DeviceEventQueryInput = z.object({\n deviceId: z.number(),\n since: z.number().optional(),\n until: z.number().optional(),\n limit: z.number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)\n});\nconst ObjectEventQueryInput = DeviceEventQueryInput.extend({\n classFilter: z.string().optional()\n});\nconst TrackedDetectionSchema = z.object({\n trackId: z.string(),\n className: z.string(),\n confidence: z.number(),\n bbox: BoundingBoxSchema,\n zones: z.array(z.string()).readonly(),\n state: TrackStateSchema\n});\nconst pipelineAnalyticsCapability = {\n name: \"pipeline-analytics\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n exposesDeviceSettings: true,\n methods: {\n // ── Tracks ────────────────────────────────────────────────\n getActiveTracks: method(\n z.object({ deviceId: z.number() }),\n z.array(TrackSchema).readonly()\n ),\n getTrack: method(\n z.object({ deviceId: z.number(), trackId: z.string() }),\n TrackSchema.nullable()\n ),\n /** Historical completed tracks for a device. Queried from the\n * persisted `pipeline-analytics:tracks` collection; active tracks\n * still in RAM are not included. */\n listTracks: method(\n z.object({\n deviceId: z.number(),\n since: z.number().optional(),\n until: z.number().optional(),\n limit: z.number().optional()\n }),\n z.array(TrackSchema).readonly()\n ),\n clearTracks: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Events (per-kind, parallel-queryable) ─────────────────\n getMotionEvents: method(\n DeviceEventQueryInput,\n z.array(MotionEventSchema).readonly()\n ),\n getObjectEvents: method(\n ObjectEventQueryInput,\n z.array(ObjectEventSchema).readonly()\n ),\n getAudioEvents: method(\n DeviceEventQueryInput,\n z.array(AudioEventSchema).readonly()\n ),\n // ── Media ─────────────────────────────────────────────────\n getEventMedia: method(\n z.object({ eventId: z.string() }),\n z.array(MediaFileSchema).readonly()\n ),\n getTrackMedia: method(\n z.object({ trackId: z.string() }),\n z.array(MediaFileSchema).readonly()\n )\n },\n events: {\n /**\n * Enriched frame emitted after refinement. Carries lightweight\n * tracked-detection metadata (track id, class, zones, state) so\n * downstream consumers (stream overlays, notifications) can\n * annotate without querying full Track state.\n */\n onFrameTracked: {\n data: z.object({\n deviceId: z.number(),\n timestamp: z.number(),\n frameWidth: z.number(),\n frameHeight: z.number(),\n detections: z.array(TrackedDetectionSchema).readonly()\n })\n },\n /** Track entered active state (first-seen). */\n onTrackStarted: {\n data: z.object({\n deviceId: z.number(),\n trackId: z.string(),\n className: z.string()\n })\n },\n /** Track expired (TTL reached after last detection). */\n onTrackEnded: {\n data: z.object({\n deviceId: z.number(),\n trackId: z.string(),\n className: z.string(),\n durationMs: z.number()\n })\n },\n /** Canonical \"something happened at device X\" event, per-kind. */\n onDetectionEvent: {\n data: z.object({\n deviceId: z.number(),\n kind: EventKindSchema,\n eventId: z.string(),\n timestamp: z.number()\n })\n }\n }\n};\nconst CpuBreakdownSchema = z.object({\n total: z.number(),\n user: z.number(),\n system: z.number(),\n irq: z.number(),\n nice: z.number(),\n loadAvg: z.tuple([z.number(), z.number(), z.number()]),\n cores: z.number()\n});\nconst MemoryInfoSchema = z.object({\n percent: z.number(),\n totalBytes: z.number(),\n usedBytes: z.number(),\n availableBytes: z.number(),\n swapUsedBytes: z.number(),\n swapTotalBytes: z.number()\n});\nconst DiskIoSnapshotSchema = z.object({\n readBytes: z.number(),\n writeBytes: z.number(),\n readOps: z.number(),\n writeOps: z.number(),\n timestampMs: z.number()\n});\nconst NetworkIoSnapshotSchema = z.object({\n rxBytes: z.number(),\n txBytes: z.number(),\n rxPackets: z.number(),\n txPackets: z.number(),\n rxErrors: z.number(),\n txErrors: z.number(),\n timestampMs: z.number()\n});\nconst MetricsGpuInfoSchema = z.object({\n utilization: z.number(),\n model: z.string(),\n memoryUsedBytes: z.number(),\n memoryTotalBytes: z.number(),\n temperature: z.number().nullable()\n});\nconst ProcessResourceInfoSchema = z.object({\n openFds: z.number(),\n threadCount: z.number(),\n activeHandles: z.number(),\n activeRequests: z.number()\n});\nconst PressureAvgsSchema = z.object({\n avg10: z.number(),\n avg60: z.number(),\n avg300: z.number()\n});\nconst PressureInfoSchema = z.object({\n some: PressureAvgsSchema,\n full: PressureAvgsSchema.nullable()\n});\nconst SystemResourceSnapshotSchema = z.object({\n cpu: CpuBreakdownSchema,\n memory: MemoryInfoSchema,\n gpu: MetricsGpuInfoSchema.nullable(),\n network: NetworkIoSnapshotSchema,\n disk: DiskIoSnapshotSchema,\n pressure: z.object({\n cpu: PressureInfoSchema.nullable(),\n memory: PressureInfoSchema.nullable(),\n io: PressureInfoSchema.nullable()\n }),\n process: ProcessResourceInfoSchema,\n cpuTemperature: z.number().nullable(),\n timestampMs: z.number()\n});\nconst DiskSpaceInfoSchema = z.object({\n path: z.string(),\n totalBytes: z.number(),\n usedBytes: z.number(),\n availableBytes: z.number(),\n percent: z.number()\n});\nconst PidResourceStatsSchema = z.object({\n pid: z.number(),\n cpu: z.number(),\n memory: z.number()\n});\nconst AddonInstanceSchema = z.object({\n addonId: z.string(),\n nodeId: z.string(),\n role: z.enum([\"hub\", \"worker\"]),\n pid: z.number(),\n state: z.enum([\"starting\", \"running\", \"stopping\", \"stopped\", \"crashed\"]),\n uptimeSec: z.number()\n});\nconst NodeProcessSchema = z.object({\n pid: z.number(),\n ppid: z.number(),\n pgid: z.number(),\n classification: z.enum([\"root\", \"managed\", \"system\", \"ghost\"]),\n /** `$process` addon binding when `managed`, else null. */\n addonId: z.string().nullable(),\n /** Kernel-reported nodeId when the process is a known agent/worker. */\n nodeId: z.string().nullable(),\n /** Truncated command line. */\n command: z.string(),\n cpuPercent: z.number(),\n memoryRssBytes: z.number(),\n /** Wall-clock uptime (seconds). Parsed from `ps etime`. */\n uptimeSec: z.number(),\n /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */\n orphaned: z.boolean()\n});\nconst KillProcessInputSchema = z.object({\n pid: z.number(),\n /** Force = SIGKILL. Default is SIGTERM. */\n force: z.boolean().optional()\n});\nconst KillProcessResultSchema = z.object({\n success: z.boolean(),\n reason: z.string().optional(),\n signal: z.enum([\"SIGTERM\", \"SIGKILL\"]).optional()\n});\nconst SystemMetricsSchema = z.object({\n cpuPercent: z.number(),\n memoryPercent: z.number(),\n memoryUsedMB: z.number(),\n memoryTotalMB: z.number(),\n diskPercent: z.number().optional(),\n temperature: z.number().optional(),\n gpuPercent: z.number().optional(),\n gpuMemoryPercent: z.number().optional()\n});\nconst metricsProviderCapability = {\n name: \"metrics-provider\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n /** Fresh, full system snapshot (triggers OS-level collection). */\n collectSnapshot: method(z.void(), SystemResourceSnapshotSchema),\n /** Most recent cached snapshot from the background sampler, or null pre-first-sample. */\n getCached: method(z.void(), SystemResourceSnapshotSchema.nullable()),\n /** Light-weight cached summary for heartbeats and list views. */\n getCurrent: method(z.void(), SystemMetricsSchema),\n /** Disk space for the given mount/path. */\n getDiskSpace: method(z.object({ dirPath: z.string() }), DiskSpaceInfoSchema),\n /** GPU info (null if unavailable). */\n getGpuInfo: method(z.void(), MetricsGpuInfoSchema.nullable()),\n /** CPU temperature in °C (null if unavailable). */\n getCpuTemperature: method(z.void(), z.number().nullable()),\n /** Per-PID resource stats. Missing/dead PIDs are omitted from the result. */\n getProcessStats: method(\n z.object({ pids: z.array(z.number()) }),\n z.array(PidResourceStatsSchema)\n ),\n /**\n * List addon instances known to this node — one entry per forked worker\n * plus a synthetic 'hub' entry representing the local hub process.\n * Used by benchmarks/observability to detect whether a given addon runs\n * in its own process (measurable independently) or inline with the hub.\n */\n listAddonInstances: method(z.void(), z.array(AddonInstanceSchema).readonly()),\n /**\n * Resource stats for the process hosting the given addon.\n * Returns null when the addon runs in-process on the hub (can't measure\n * independently — caller should detect via listAddonInstances). Returns\n * hub process stats for addonId '$hub'.\n */\n getAddonStats: method(z.object({ addonId: z.string() }), PidResourceStatsSchema.nullable()),\n /**\n * Snapshot of every camstack-related process on this node with a\n * ghost/managed/root classification. Powers the Cluster → Agent →\n * Processes tab: cross-references `$process.list` against a `ps` scan\n * so orphaned trees (PPID=1) or unknown children show up as `ghost`\n * and can be killed from the UI.\n */\n listNodeProcesses: method(z.void(), z.array(NodeProcessSchema).readonly()),\n /**\n * Send SIGTERM (or SIGKILL when `force`) to a pid inside this node's\n * process tree. The provider refuses pids that aren't in the live\n * `listNodeProcesses()` snapshot — callers can't use this endpoint\n * to kill arbitrary system processes.\n */\n killProcess: method(\n KillProcessInputSchema,\n KillProcessResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst PtzPresetSchema = z.object({ id: z.string(), name: z.string() });\nconst PtzPositionSchema = z.object({ pan: z.number(), tilt: z.number(), zoom: z.number() });\nconst PtzMoveCommandSchema = z.object({\n pan: z.number().optional(),\n tilt: z.number().optional(),\n zoom: z.number().optional(),\n speed: z.number().optional()\n});\nconst ptzCapability = {\n name: \"ptz\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n move: method(\n PtzMoveCommandSchema.extend({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n continuousMove: method(\n PtzMoveCommandSchema.extend({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n stop: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n getPresets: method(\n z.object({ deviceId: z.number() }),\n z.array(PtzPresetSchema)\n ),\n goToPreset: method(\n z.object({ deviceId: z.number(), presetId: z.string() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n goHome: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /**\n * Pull the current PTZ position. Redundant with the auto-injected\n * `getStatus` method (see `status` below); kept for callers that\n * haven't migrated. Will be folded into `getStatus` in a future\n * cleanup pass once all consumers use the typed status surface.\n */\n getPosition: method(\n z.object({ deviceId: z.number() }),\n PtzPositionSchema\n )\n },\n status: {\n schema: PtzPositionSchema,\n kind: \"command-driven\"\n }\n};\nconst EventItemSchema = z.object({\n id: z.string(),\n type: z.string(),\n timestamp: z.number(),\n // unix ms\n label: z.string().optional(),\n thumbnailUrl: z.string().optional(),\n clipUrl: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional()\n});\nconst eventsCapability = {\n name: \"events\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n getEvents: method(\n z.object({\n deviceId: z.number(),\n from: z.number().optional(),\n to: z.number().optional(),\n limit: z.number().optional()\n }),\n z.array(EventItemSchema)\n ),\n getEventThumbnail: method(\n z.object({ deviceId: z.number(), eventId: z.string() }),\n z.object({ base64: z.string(), contentType: z.string() }).nullable()\n ),\n getEventClipUrl: method(\n z.object({ deviceId: z.number(), eventId: z.string() }),\n z.string().nullable()\n )\n }\n};\nconst SegmentSchema = z.object({\n id: z.string(),\n startTs: z.number(),\n // unix ms\n endTs: z.number(),\n durationSec: z.number(),\n sizeBytes: z.number().optional()\n});\nconst recordingCapability = {\n name: \"recording\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n getSegments: method(\n z.object({\n deviceId: z.number(),\n from: z.number().optional(),\n to: z.number().optional()\n }),\n z.array(SegmentSchema)\n ),\n getPlaybackUrl: method(\n z.object({ deviceId: z.number(), segmentId: z.string() }),\n z.string().nullable()\n ),\n getThumbnailAt: method(\n z.object({ deviceId: z.number(), timestamp: z.number() }),\n z.object({ base64: z.string(), contentType: z.string() }).nullable()\n )\n }\n};\nconst StreamSourceEntrySchema = z.object({\n id: z.string(),\n label: z.string(),\n protocol: z.enum([\"rtsp\", \"rtmp\", \"annexb\", \"http-mjpeg\", \"webrtc\", \"custom\"]),\n url: z.string().optional(),\n resolution: z.object({ width: z.number(), height: z.number() }).optional(),\n fps: z.number().optional(),\n bitrate: z.number().optional(),\n codec: z.string().optional(),\n profileHint: z.enum([\"high\", \"mid\", \"low\"]).optional(),\n sdp: z.string().optional()\n});\nconst ConfigEntrySchema = z.object({\n key: z.string(),\n value: z.unknown()\n});\nconst deviceOpsCapability = {\n name: \"device-ops\",\n scope: \"device\",\n mode: \"singleton\",\n methods: {\n /**\n * Return stream sources for camera-like devices. Non-camera devices\n * return an empty array (the bridge did the same; preserved for compat).\n */\n getStreamSources: method(\n z.object({ deviceId: z.number() }),\n z.array(StreamSourceEntrySchema)\n ),\n /**\n * Return the device's config entries (key + current value). Used by\n * the device-manager aggregator when reading the driver's schema+values.\n */\n getConfigEntries: method(\n z.object({ deviceId: z.number() }),\n z.array(ConfigEntrySchema)\n ),\n /**\n * Bulk-apply a config patch via `IDevice.config.setAll`. Covers the\n * updateConfig / setStreamProfileMap / enable-as-config paths from\n * the old bridge.\n */\n setConfig: method(\n z.object({\n deviceId: z.number(),\n values: z.record(z.string(), z.unknown())\n }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /**\n * Invoke `IDevice.removeDevice()` so the driver can release resources\n * (close sockets, stop background tasks, …). The device-manager still\n * performs its own persistence cleanup before/after this call.\n */\n removeDevice: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /**\n * Build the ConfigUISchema (FormBuilder input shape) from the device's\n * Zod config schema. Runs on the worker that owns the IDevice so the\n * Zod types stay local (they're function references, not\n * serializable). Returns a fully JSON-serializable schema with\n * sections/fields the admin UI renders directly.\n *\n * Needed because the hub-side `device-manager.getSettingsSchema`\n * couldn't reach forked-worker devices — it had no registry entry\n * and no cross-process lookup, so the UI silently rendered an empty\n * settings panel for every worker-owned device.\n *\n * Returns `null` when the device isn't found on this worker.\n */\n getSettingsSchema: method(\n z.object({ deviceId: z.number() }),\n z.unknown().nullable()\n )\n }\n};\nconst CameraCredentialsSchema = z.object({\n /** Camera IP or hostname (no scheme). */\n host: z.string(),\n /** Primary protocol port (varies per vendor: Baichuan 9000, ISAPI 80/443, RTSP 554). */\n port: z.number().int().positive().optional(),\n /** ONVIF service port if known by the provider. */\n onvifPort: z.number().int().positive().optional(),\n /** RTSP service port if known. */\n rtspPort: z.number().int().positive().optional(),\n /** HTTP(S) flag for the primary protocol port. */\n https: z.boolean().optional(),\n /** Login username. */\n username: z.string().optional(),\n /** Login password. CONSUMERS MUST NOT log or event-bus this value. */\n password: z.string().optional(),\n /** ONVIF profile hint advertised by the camera (`T`, `Q`, `G`, `S`). */\n onvifProfile: z.string().optional()\n});\nconst CameraCredentialsStatusSchema = z.object({\n host: z.string(),\n port: z.number().int().positive().nullable(),\n onvifPort: z.number().int().positive().nullable(),\n rtspPort: z.number().int().positive().nullable(),\n https: z.boolean().nullable(),\n hasUsername: z.boolean(),\n hasPassword: z.boolean(),\n onvifProfile: z.string().nullable()\n});\nconst cameraCredentialsCapability = {\n name: \"camera-credentials\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n /**\n * Return the camera's full credential bundle for admin consumers.\n * Each provider implementation returns a snapshot of its persisted\n * config — no I/O to the camera. Returns null when the device is\n * not owned by this addon (deviceId mismatch).\n */\n getCredentials: method(\n z.object({ deviceId: z.number() }),\n CameraCredentialsSchema.nullable(),\n { kind: \"query\", auth: \"admin\" }\n )\n },\n status: {\n schema: CameraCredentialsStatusSchema,\n kind: \"command-driven\"\n }\n};\nconst rebootCapability = {\n name: \"reboot\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera, DeviceType.Sensor, DeviceType.Switch],\n methods: {\n reboot: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst OsdOverlayKindEnum = z.enum([\"text\", \"timestamp\", \"watermark\"]);\nconst OsdPositionEnum = z.enum([\n \"top-left\",\n \"top-center\",\n \"top-right\",\n \"bottom-left\",\n \"bottom-center\",\n \"bottom-right\",\n \"custom\"\n]);\nconst OsdOverlaySchema = z.object({\n /** Stable driver-assigned id. Reolink uses `'channel'`, `'time'`, `'watermark'`. */\n id: z.string(),\n kind: OsdOverlayKindEnum,\n enabled: z.boolean(),\n /** Active text (text/watermark). Undefined for 'timestamp' (firmware-generated). */\n text: z.string().optional(),\n position: OsdPositionEnum.optional(),\n /**\n * Positions the firmware accepts for this specific overlay. Populated\n * by the driver at register time. Empty array → positioning not\n * configurable; the UI hides the position field.\n */\n availablePositions: z.array(OsdPositionEnum).readonly(),\n /** Firmware does not allow editing the `text` field (e.g. timestamp). */\n readOnly: z.boolean().optional()\n});\nconst OsdStatusSchema = z.object({\n overlays: z.array(OsdOverlaySchema).readonly()\n});\nconst OsdOverlayPatchSchema = z.object({\n enabled: z.boolean().optional(),\n text: z.string().optional(),\n position: OsdPositionEnum.optional()\n}).partial();\nconst osdCapability = {\n name: \"osd\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n /**\n * Patch a single overlay by id. Provider handles read-modify-write\n * against firmware APIs that require the full object (Reolink\n * `SetOsd`). Omitted patch keys are preserved. Successful\n * completion triggers `onStatusChanged`.\n */\n setOverlay: method(\n z.object({\n deviceId: z.number(),\n overlayId: z.string(),\n patch: OsdOverlayPatchSchema\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n },\n events: {\n onStatusChanged: { data: z.object({\n deviceId: z.number(),\n status: OsdStatusSchema\n }) }\n },\n status: {\n schema: OsdStatusSchema,\n kind: \"command-driven\"\n },\n settings: {\n bindings: [{\n kind: \"array\",\n statusPath: \"overlays\",\n idField: \"id\",\n method: \"setOverlay\",\n idArg: \"overlayId\",\n patchArg: \"patch\",\n sectionId: \"osd\",\n sectionTitle: \"Video overlays\",\n itemFields: {\n enabled: {\n label: (o) => `${String(o.id)} enabled`,\n kind: \"boolean\"\n },\n text: {\n label: (o) => `${String(o.id)} text`,\n kind: \"text\",\n when: (o) => o.kind !== \"timestamp\" && !o.readOnly\n },\n position: {\n label: (o) => `${String(o.id)} position`,\n kind: \"select\",\n options: (o) => o.availablePositions ?? [],\n when: (o) => Array.isArray(o.availablePositions) && o.availablePositions.length > 0\n }\n }\n }]\n }\n};\nconst AccessoriesStatusSchema = z.object({\n childDeviceIds: z.array(z.number()).readonly()\n});\nconst accessoriesCapability = {\n name: \"accessories\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera, DeviceType.Hub],\n methods: {},\n events: {\n /**\n * Emitted when a child device is created, removed, or its parent\n * assignment changes. Payload carries the fresh list.\n */\n onAccessoriesChanged: { data: z.object({\n deviceId: z.number(),\n childDeviceIds: z.array(z.number()).readonly()\n }) }\n },\n status: {\n schema: AccessoriesStatusSchema,\n kind: \"command-driven\"\n }\n};\nconst IntercomAbilitySchema = z.object({\n /** Codecs accepted by firmware, in preference order. Driver-authored strings. */\n codecs: z.array(z.string()),\n /** Sample rate (Hz) the firmware expects. Reolink typical: 16000. */\n sampleRate: z.number(),\n duplex: z.enum([\"half\", \"full\"]),\n /** Max in-flight audio backlog before drop (ms). Server uses this to bound latency. */\n maxBacklogMs: z.number()\n});\nconst IntercomStatusSchema = z.object({\n /** True while a talk session is open. */\n talking: z.boolean(),\n /** Ms epoch of the most recent session start. Null if never opened. */\n lastSessionAt: z.number().nullable(),\n /** Firmware ability cached at first session creation. Null until probed. */\n ability: IntercomAbilitySchema.nullable()\n});\nconst intercomCapability = {\n name: \"intercom\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n /**\n * Open a server-side WebRTC audio-only session. Returns an SDP\n * offer with a single sendonly audio m-line the client answers\n * (client → server direction). The server wakes battery cams\n * transparently before opening the upstream talk channel.\n */\n startSession: method(\n z.object({ deviceId: z.number() }),\n z.object({ sessionId: z.string(), sdpOffer: z.string() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n handleAnswer: method(\n z.object({\n deviceId: z.number(),\n sessionId: z.string(),\n sdpAnswer: z.string()\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Close explicitly. Server also auto-closes on 30s idle. */\n stopSession: method(\n z.object({ deviceId: z.number(), sessionId: z.string() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Open a raw-PCM talk session (no WebRTC SDP plumbing). Used by\n * non-WebRTC consumers (HomeKit export, Alexa raw audio, test\n * harnesses) that already have decoded PCM frames and just need a\n * direct path onto the camera's talk channel. Mutually exclusive\n * with `startSession` (an active WebRTC session must be stopped\n * before a raw-PCM session can be opened on the same device, and\n * vice versa).\n */\n startTalkSession: method(\n z.object({ deviceId: z.number() }),\n z.object({ sessionId: z.string() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Push a chunk of PCM s16le mono onto the active raw-PCM talk\n * session. Frames are encoded to the firmware's expected codec\n * (Reolink: IMA ADPCM @ camera sample rate; Hikvision: G.711 @\n * 8 kHz) inside the provider — callers must resample upstream to\n * the rate the camera negotiated (typical: 16 kHz Reolink,\n * 8 kHz Hikvision). PCM is shipped base64-encoded so the payload\n * survives JSON serialization across tRPC.\n */\n pushTalkPcm: method(\n z.object({\n deviceId: z.number(),\n /** PCM frames as little-endian s16, mono. Base64-encoded so\n * the payload survives tRPC JSON serialization. */\n pcmBase64: z.string(),\n /** Sequence number for ordering / dropping out-of-order frames. */\n sequenceNumber: z.number().int()\n }),\n z.object({ accepted: z.boolean() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Close the raw-PCM talk session. Idempotent. */\n endTalkSession: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n },\n events: {\n onStatusChanged: { data: z.object({\n deviceId: z.number(),\n status: IntercomStatusSchema\n }) }\n },\n status: {\n schema: IntercomStatusSchema,\n kind: \"command-driven\"\n }\n};\nconst NativeObjectClassEnum = z.enum([\n \"person\",\n \"vehicle\",\n \"animal\",\n \"face\",\n \"package\",\n \"other\"\n]);\nconst NativeDetectionSchema = z.object({\n class: NativeObjectClassEnum,\n timestamp: z.number(),\n /** Firmware-provided confidence [0..1]. Reolink pushes don't carry it → undefined. */\n confidence: z.number().min(0).max(1).optional()\n});\nconst NativeObjectDetectionStatusSchema = z.object({\n /**\n * Last observed instance per class. Undefined entries mean the class\n * is supported but nothing has been seen since the provider started.\n */\n lastByClass: z.record(NativeObjectClassEnum, NativeDetectionSchema.nullable()),\n /** Classes the firmware is capable of detecting — enumerated at device register. */\n supportedClasses: z.array(NativeObjectClassEnum).readonly()\n});\nconst nativeObjectDetectionCapability = {\n name: \"native-object-detection\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {},\n events: {\n onDetected: { data: z.object({\n deviceId: z.number(),\n detection: NativeDetectionSchema\n }) }\n },\n status: {\n schema: NativeObjectDetectionStatusSchema,\n kind: \"push\"\n }\n};\nconst ModelFormatSchema = z.enum(MODEL_FORMATS);\nconst HwAccelBackendInputSchema = z.enum([\n \"videotoolbox\",\n \"cuda\",\n \"nvdec\",\n \"vaapi\",\n \"qsv\",\n \"d3d11va\",\n \"dxva2\",\n \"amf\",\n \"vdpau\",\n \"drm\",\n \"coreml\",\n \"tensorrt\",\n \"openvino\",\n \"directml\",\n \"webgpu\",\n \"none\"\n]).nullable().optional();\nconst HwAccelResolutionSchema = z.object({\n preferred: z.array(z.string()).readonly()\n});\nconst HardwareEncoderIdSchema = z.enum([\n \"h264_videotoolbox\",\n \"hevc_videotoolbox\",\n \"h264_vaapi\",\n \"hevc_vaapi\",\n \"h264_nvenc\",\n \"hevc_nvenc\",\n \"h264_qsv\",\n \"hevc_qsv\",\n \"h264_amf\",\n \"hevc_amf\",\n \"libx264\",\n \"libx265\"\n]);\nconst HardwareEncoderProbeSchema = z.object({\n encoder: HardwareEncoderIdSchema,\n codec: z.enum([\"H264\", \"H265\"]),\n family: z.enum([\"videotoolbox\", \"vaapi\", \"nvenc\", \"qsv\", \"amf\", \"software\"]),\n available: z.boolean(),\n reason: z.string().optional()\n});\nconst HardwareEncodersSchema = z.object({\n encoders: z.array(HardwareEncoderProbeSchema).readonly(),\n defaultH264: HardwareEncoderIdSchema,\n defaultH265: HardwareEncoderIdSchema,\n probedAt: z.number()\n});\nconst HardwarePlatformSchema = z.enum([\"darwin\", \"linux\", \"win32\"]);\nconst HardwareArchSchema = z.enum([\"arm64\", \"x64\"]);\nconst GpuInfoSchema = z.object({\n type: z.enum([\"nvidia\", \"amd\", \"intel\", \"apple\"]),\n name: z.string(),\n memoryMB: z.number().optional()\n});\nconst NpuInfoSchema = z.object({\n type: z.enum([\"apple-ane\", \"intel-npu\"])\n});\nconst HardwareInfoSchema = z.object({\n platform: HardwarePlatformSchema,\n arch: HardwareArchSchema,\n cpuModel: z.string(),\n cpuCores: z.number(),\n totalRAM_MB: z.number(),\n availableRAM_MB: z.number(),\n gpu: GpuInfoSchema.nullable(),\n npu: NpuInfoSchema.nullable()\n});\nconst PlatformScoreSchema = z.object({\n runtime: z.enum([\"node\", \"python\"]),\n backend: z.string(),\n format: z.enum([\"onnx\", \"coreml\", \"openvino\"]),\n score: z.number(),\n reason: z.string(),\n available: z.boolean()\n});\nconst PlatformCapabilitiesSchema = z.object({\n hardware: HardwareInfoSchema,\n scores: z.array(PlatformScoreSchema).readonly(),\n bestScore: PlatformScoreSchema,\n pythonPath: z.string().nullable()\n});\nconst ModelRequirementSchema = z.object({\n modelId: z.string(),\n name: z.string(),\n minRAM_MB: z.number(),\n accuracyScore: z.number(),\n formats: z.array(z.string()).readonly()\n});\nconst ResolvedInferenceConfigSchema = z.object({\n modelId: z.string(),\n runtime: z.enum([\"node\", \"python\"]),\n backend: z.string(),\n format: ModelFormatSchema,\n reason: z.string()\n});\nconst platformProbeCapability = {\n name: \"platform-probe\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n getCapabilities: method(z.void(), PlatformCapabilitiesSchema),\n getHardware: method(z.void(), HardwareInfoSchema),\n resolveInferenceConfig: method(\n z.object({ requirements: z.array(ModelRequirementSchema).readonly() }),\n ResolvedInferenceConfigSchema\n ),\n resolveHwAccel: method(\n z.object({ prefer: HwAccelBackendInputSchema, nodeId: z.string().optional() }),\n HwAccelResolutionSchema\n ),\n /**\n * Hardware-encoder probe — see Task #185. Cached after first call.\n */\n getHardwareEncoders: method(z.void(), HardwareEncodersSchema),\n refreshHardwareEncoders: method(\n z.void(),\n HardwareEncodersSchema,\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst InterfaceKindEnum = z.enum([\n \"lan\",\n // wired ethernet (en0, eth0, ...)\n \"wifi\",\n // wireless (en1, wlan*, ...)\n \"docker\",\n // docker0 / br-* / veth*\n \"vpn\",\n // tun*, utun*, wg*, tap*\n \"loopback\",\n // lo, lo0\n \"other\"\n // anything we can't classify confidently\n]);\nconst LocalInterfaceSchema = z.object({\n /** Interface name as reported by the OS (e.g. `en0`, `eth0`, `lo0`). */\n name: z.string(),\n family: z.enum([\"IPv4\", \"IPv6\"]),\n address: z.string(),\n /** CIDR shorthand (e.g. `192.168.1.10/24`). Empty when OS doesn't expose. */\n cidr: z.string(),\n /** OS netmask. Stable across calls so the SDK can hash on it. */\n netmask: z.string(),\n /** True for `127.0.0.1`/`::1`. Returned for completeness but never preferred. */\n internal: z.boolean(),\n /** Hardware MAC (empty for loopback / virtual interfaces). */\n mac: z.string(),\n /** Derived classification — see `InterfaceKindEnum`. */\n kind: InterfaceKindEnum,\n /**\n * `true` for the auto-selected outbound interface. Exactly zero or\n * one entry has this set per call; the SDK picks this one for the\n * first connection attempt.\n */\n preferred: z.boolean(),\n /**\n * Heuristic flag: `true` when the address looks usable for clients\n * (RFC 1918 / public IPv4, IPv6 ULA / GUA), `false` for link-local\n * / loopback / multicast / docker / vpn / unknown ranges. Same\n * heuristic that drives `autoSeedAllowlist`.\n */\n plausible: z.boolean(),\n /**\n * Human-readable rationale for non-plausible entries (e.g. \"IPv6\n * link-local — only reachable on the same link\"). Empty string for\n * plausible entries. The UI surfaces this verbatim as the tooltip\n * on the \"Unlikely usable\" badge so the backend stays the single\n * source of truth — front-end consumers don't re-derive the reason.\n */\n plausibleReason: z.string()\n});\nconst ListResultSchema = z.object({\n interfaces: z.array(LocalInterfaceSchema).readonly(),\n /** Wall-clock timestamp at which the snapshot was probed. */\n probedAt: z.number()\n});\nconst PreferredSchema = LocalInterfaceSchema.nullable();\nconst ConnectionEndpointSchema = z.object({\n /** Operator-facing label (e.g. \"LAN — en0\", \"Public tunnel\"). */\n label: z.string(),\n /** Fully-formed base URL with scheme + host + port. */\n baseUrl: z.string(),\n /** Network-level hint for the SDK — picks a small icon, sorts within\n * a tier. Coarse categorisation (LAN vs public vs loopback). */\n kind: z.enum([\n \"lan-ipv4\",\n // private RFC1918 / link-local IPv4\n \"lan-ipv6\",\n // private IPv6\n \"public\",\n // tunnel / external FQDN\n \"loopback\"\n // 127.0.0.1 — last-resort fallback\n ]),\n /**\n * Originating-interface kind — `lan`/`wifi`/`docker`/`vpn`/`other`/\n * `loopback`/`public`. Lets the UI render an accurate badge (e.g. a\n * VPN address gets a \"VPN\" tag instead of being lumped under\n * \"lan-ipv4\"). `'public'` for the tunnel hostname.\n */\n interfaceKind: z.enum([\"lan\", \"wifi\", \"docker\", \"vpn\", \"other\", \"loopback\", \"public\"]),\n /**\n * Mirrors `LocalInterface.plausible` — false for endpoints derived\n * from non-plausible interfaces (VPN, docker, link-local, …). The\n * UI uses it to mark \"Unlikely usable\" without re-deriving from\n * the address shape.\n */\n plausible: z.boolean(),\n /** Same as `LocalInterface.plausibleReason` — empty when plausible. */\n plausibleReason: z.string(),\n /**\n * Suggested priority for racing — lower = try first. Stable across\n * calls so the client can sort even if the cap returns a new\n * ordering between polls.\n */\n priority: z.number()\n});\nconst GetConnectionEndpointsResultSchema = z.object({\n endpoints: z.array(ConnectionEndpointSchema).readonly()\n});\nconst AllowedAddressesSchema = z.object({\n /**\n * Allowlist of interface addresses operators have explicitly opted\n * into for the connection-endpoint race. Empty array = \"auto\" — every\n * non-loopback / non-link-local interface participates. Set by the\n * Network Addresses admin page and persisted by the addon.\n */\n addresses: z.array(z.string()).readonly()\n});\nconst localNetworkCapability = {\n name: \"local-network\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n /** Return the current interface snapshot. */\n list: method(z.void(), ListResultSchema),\n /**\n * Auto-selected outbound interface. Heuristic:\n * 1. Skip internal / link-local / 169.254.*.\n * 2. Prefer LAN/wifi (real Ethernet) over docker/vpn.\n * 3. IPv4 wins over IPv6 (compat with legacy consumers).\n * 4. Tie-break on lowest CIDR mask (most-specific subnet).\n * Returns `null` only when the host has zero non-loopback addresses.\n * Honours `getAllowedAddresses()` — if the operator pinned an\n * allowlist, only those addresses are candidates.\n */\n getPreferred: method(z.void(), PreferredSchema),\n /**\n * Ordered candidate base URLs the SDK should try on connect.\n * Includes LAN IPs (one per non-internal interface), the public\n * tunnel hostname (when active), and loopback as a last-resort\n * fallback. Filterable by `includeLoopback` / `ipv4Only`.\n * Honours `getAllowedAddresses()` when set — addresses outside\n * the allowlist are dropped (the public tunnel + loopback are\n * always included as escape hatches).\n */\n getConnectionEndpoints: method(\n z.object({\n /** Local hub HTTP port to use in base URLs. */\n port: z.number().int().min(1).max(65535),\n /** Include `http(s)://127.0.0.1:<port>` as the lowest-priority\n * candidate. Default `true`. */\n includeLoopback: z.boolean().optional(),\n /** Skip IPv6 entries. Some legacy clients can't parse them.\n * Default `false`. */\n ipv4Only: z.boolean().optional(),\n /** Scheme to emit for LAN/loopback URLs. Default `'http'`.\n * Pass `'https'` when the caller is itself loaded over HTTPS\n * to avoid mixed-content blocks in the browser. The public\n * tunnel always emits `https://` regardless. */\n scheme: z.enum([\"http\", \"https\"]).optional()\n }),\n GetConnectionEndpointsResultSchema\n ),\n /**\n * Read the operator's allowlist. Empty = \"auto\" (no filter). Used\n * by the admin UI's address selector to seed its checkbox state.\n */\n getAllowedAddresses: method(z.void(), AllowedAddressesSchema),\n /**\n * Replace the allowlist atomically. Persisted via the addon store\n * (kernel-managed) so it survives restarts. Pass `[]` to revert to\n * auto mode.\n */\n setAllowedAddresses: method(\n AllowedAddressesSchema,\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\" }\n ),\n /**\n * Re-run the boot heuristic over the current interface snapshot\n * and atomically replace the allowlist with the result. Useful\n * after a major network change (new dock, new VPN, IP rebound)\n * when the operator wants to wipe their manual edits and start\n * over from the auto-detected best matches.\n */\n resetAllowlistToBestMatch: method(\n z.void(),\n AllowedAddressesSchema,\n { kind: \"mutation\" }\n )\n }\n};\nconst MeshEndpointSchema = z.object({\n /** Stable identifier within the provider (e.g. `mesh-ipv4`, `magicdns`, `funnel`). */\n id: z.string(),\n /** Operator-facing label (e.g. \"Mesh IPv4\", \"MagicDNS\"). */\n label: z.string(),\n /**\n * Where the endpoint is reachable from:\n * - `mesh`: only peers on the same mesh (Tailscale tailnet, …)\n * - `public`: open internet (Funnel, public-tunnel pass-through)\n */\n scope: z.enum([\"mesh\", \"public\"]),\n /** Full base URL (e.g. `https://camstack.tail-abc.ts.net`). */\n url: z.string(),\n /** Hostname portion (for SAN cert checks + display). */\n hostname: z.string(),\n /** Port (`443` for Funnel/Serve, anything for raw mesh IP). */\n port: z.number(),\n /** Always `http` or `https`. */\n protocol: z.enum([\"http\", \"https\"])\n});\nconst MeshPeerSchema = z.object({\n /** Stable peer id assigned by the mesh control plane. */\n id: z.string(),\n /** Hostname / device name as shown in the mesh dashboard. */\n hostname: z.string(),\n /** MagicDNS / mesh DNS name (e.g. `peer-foo.tail-abc.ts.net`). Empty when the provider doesn't support DNS or peer-side resolution is disabled. */\n magicDns: z.string(),\n /** Mesh IPv4 / IPv6 addresses combined. Multiple when dual-stacked. */\n addresses: z.array(z.string()).readonly(),\n /** Operating system reported by the peer (informational). */\n os: z.string().optional(),\n /** Whether this peer is currently reachable. */\n online: z.boolean(),\n /** Last-seen timestamp (epoch ms). 0 when never seen. */\n lastSeenMs: z.number(),\n /** True for the row representing the current host. */\n isSelf: z.boolean(),\n /**\n * Connection mode to this peer:\n * - `direct`: NAT-traversed P2P (UDP punched)\n * - `relay`: traffic relayed through provider edge (Tailscale DERP)\n * - `idle`: peer reachable but no recent traffic / handshake\n */\n connection: z.enum([\"direct\", \"relay\", \"idle\"]),\n /** DERP region / relay node identifier when `connection: relay`. Null otherwise. */\n relay: z.string().nullable(),\n /** Last successful handshake timestamp (epoch ms). 0 when never. */\n lastHandshakeMs: z.number(),\n /** Bytes received from this peer since the daemon started. */\n rxBytes: z.number(),\n /** Bytes transmitted to this peer since the daemon started. */\n txBytes: z.number(),\n /** ACL tags this peer carries (e.g. `[\"tag:server\"]`). Empty when human-owned. */\n tags: z.array(z.string()).readonly(),\n /** True when the peer advertises itself as an exit-node candidate. */\n exitNodeOption: z.boolean(),\n /** Subnet routes the peer advertises (e.g. `[\"192.168.1.0/24\"]`). */\n advertisedRoutes: z.array(z.string()).readonly(),\n /** Owner account login (e.g. `foo@example.com`). Null for tagged peers. */\n userLogin: z.string().nullable(),\n /** Pre-auth key / machine-key expiry (epoch ms). Null when keys don't expire. */\n keyExpiry: z.number().nullable()\n});\nconst MeshStatusSchema = z.object({\n /** True when the host is joined and the daemon reports healthy. */\n joined: z.boolean(),\n /** Local mesh IPv4 (e.g. `100.x.x.x` for Tailscale). Empty when not joined. */\n meshIp: z.string(),\n /** MagicDNS / mesh hostname (e.g. `camstack.tail-abc.ts.net`). Empty if not configured. */\n magicDnsHostname: z.string(),\n /** Number of peers visible to this host (excluding self). */\n peerCount: z.number(),\n /** Every endpoint this provider exposes for the current host. */\n endpoints: z.array(MeshEndpointSchema).readonly(),\n /** Last error from the daemon, when not joined. */\n error: z.string().optional(),\n // ── Account / tenant identity (generic across providers) ────────\n /**\n * Tenant / tailnet / network display name (Tailscale = tailnet\n * domain, Headscale = namespace, ZeroTier = network name). Empty\n * pre-join. Per-provider semantics, common slot.\n */\n tenantName: z.string(),\n /**\n * Mesh DNS suffix when the provider exposes peer-resolvable DNS\n * (Tailscale MagicDNS, Headscale MagicDNS, …). Empty when the\n * provider doesn't ship DNS (e.g. ZeroTier).\n */\n magicDnsSuffix: z.string(),\n /**\n * Authenticated user / account login bound to this host. Null when\n * the provider authenticates with a long-lived network token rather\n * than a user account (e.g. ZeroTier API token).\n */\n userLogin: z.string().nullable(),\n /**\n * Provider control-plane URL (Tailscale SaaS `https://login.tailscale.com`,\n * self-hosted Headscale, ZeroTier Central, …). Empty when not\n * applicable (rare).\n */\n controlPlaneUrl: z.string(),\n /**\n * Machine-key / node-key expiry (epoch ms). Null when the provider\n * doesn't rotate keys for the bound host. Operator-facing surface\n * for \"your access expires on …\" banners.\n */\n keyExpiry: z.number().nullable(),\n // ── Onboard-daemon handoff (Tailscale, generic slot) ────────────\n /**\n * When the provider runs its OWN mesh daemon (e.g. the Tailscale\n * client addon in `onboard` mode spawns a private `tailscaled`),\n * this carries the local control-socket path. Companion addons that\n * must drive the SAME daemon — chiefly `tailscale-ingress` for\n * Serve/Funnel — read it to point their CLI at the right socket\n * instead of the system default. Empty when the provider uses the\n * host's system daemon (or doesn't have the concept).\n */\n daemonSocket: z.string().optional(),\n /**\n * Path to the mesh CLI binary the provider downloaded for onboard\n * mode. Companion addons reuse it so they don't need a system\n * install when the operator chose a fully self-contained mesh.\n * Empty in host mode.\n */\n daemonCliPath: z.string().optional()\n});\nconst meshNetworkCapability = {\n name: \"mesh-network\",\n scope: \"system\",\n mode: \"collection\",\n providerKind: \"mesh\",\n methods: {\n /** Return the current join state + endpoints + peer count. Cheap\n * poll-target — admin UI hits this every few seconds. */\n getStatus: method(z.void(), MeshStatusSchema),\n /**\n * Join the host to the provider's mesh using a one-time auth key\n * (generated by the operator in the provider's admin dashboard).\n * Implementations should be idempotent — re-calling with the same\n * key while already joined is a no-op + success.\n */\n join: method(\n z.object({\n /** Provider-specific auth key. For Tailscale this is the\n * `tskey-auth-*` token from admin.tailscale.com. */\n authKey: z.string().min(8),\n /** Optional hostname override the host should advertise. */\n hostname: z.string().optional()\n }),\n z.object({ joined: z.literal(true) }),\n { kind: \"mutation\" }\n ),\n /**\n * Start an interactive browser-redirect login flow.\n *\n * The provider spawns its daemon's join command without a pre-auth\n * key, captures the verification URL the daemon prints, and returns\n * it. The admin UI opens the URL in a new tab; the user completes\n * authentication in the provider's web console and the background\n * process self-terminates. The caller then polls `getStatus()` until\n * `joined: true`.\n *\n * Mirrors the `tailscale up` (no `--auth-key`) flow.\n */\n startLogin: method(\n z.object({\n /** Optional hostname override the host should advertise once joined. */\n hostname: z.string().optional()\n }),\n z.object({\n /** Authentication URL the operator should open in a browser. */\n loginUrl: z.string()\n }),\n { kind: \"mutation\" }\n ),\n /** Leave the mesh. After this the meshIp/magicDnsHostname/etc.\n * vanish until the next `join`. The bound account stays — a\n * subsequent `join` reuses it without prompting for a new login. */\n leave: method(\n z.void(),\n z.object({ left: z.literal(true) }),\n { kind: \"mutation\" }\n ),\n /**\n * Sign out of the mesh account entirely. Distinct from `leave`:\n * `leave` only takes the host off-mesh (`tailscale down`) while the\n * account binding survives, so the next `join` reconnects silently.\n * `logout` (`tailscale logout`) wipes the daemon's stored\n * credentials — the next `startLogin` MUST go through a fresh\n * browser-redirect flow to bind a new account.\n */\n logout: method(\n z.void(),\n z.object({ loggedOut: z.literal(true) }),\n { kind: \"mutation\" }\n ),\n /** Enumerate every peer the daemon currently knows about. */\n listPeers: method(z.void(), z.object({\n peers: z.array(MeshPeerSchema).readonly()\n })),\n /**\n * Probe the mesh daemon / API for a sanity check WITHOUT joining.\n * Operator-facing \"test connection\" button: validates the auth key\n * + reaches the control plane and reports back what would happen\n * on join.\n *\n * Tailscale: dry-runs `tailscale up --auth-key=… --reset` against\n * an idempotency probe; for an already-joined node it just returns\n * the current status.\n */\n testConnection: method(\n z.object({\n /** Optional auth key — when provided, probes the key validity\n * against the provider's API. Omit when already joined to\n * just ping the daemon. */\n authKey: z.string().optional()\n }),\n z.object({\n ok: z.boolean(),\n /** Provider-side identifier resolved by the probe (tailnet\n * name for Tailscale, network id for ZeroTier, etc.). */\n tenant: z.string().optional(),\n /** Daemon binary version, when reachable. */\n daemonVersion: z.string().optional(),\n /** Human-readable error when `ok: false`. */\n error: z.string().optional()\n }),\n { kind: \"mutation\" }\n )\n // Provider-specific runtime knobs (accept-routes / advertise-routes /\n // shields-up / ssh / exit-node, …) live on the addon's own\n // `getSettingsUISchema` (form-builder), NOT here. Different mesh\n // providers (Tailscale, Headscale, ZeroTier, Nebula) have very\n // different config surfaces — picking one shape and forcing all\n // implementations to honour it would either lose options or\n // misrepresent them. The Mesh page renders the addon's settings\n // schema as a \"Settings\" tab next to the generic Status / Peers\n // tabs driven by this cap.\n }\n};\nconst MethodAccessSchema = z.enum([\"view\", \"create\", \"delete\"]);\nconst AllowedProviderSchema = z.union([z.literal(\"*\"), z.array(z.string())]);\nconst AllowedDevicesSchema = z.record(z.string(), z.union([z.literal(\"*\"), z.array(z.string())]));\nconst CapScopeSchema = z.enum([\"device\", \"system\"]);\nconst TokenScopeSchema = z.discriminatedUnion(\"type\", [\n z.object({\n type: z.literal(\"category\"),\n target: CapScopeSchema,\n access: z.array(MethodAccessSchema).min(1)\n }),\n z.object({\n type: z.literal(\"capability\"),\n target: z.string(),\n access: z.array(MethodAccessSchema).min(1)\n }),\n z.object({\n type: z.literal(\"addon\"),\n target: z.string(),\n access: z.array(MethodAccessSchema).min(1)\n }),\n z.object({\n type: z.literal(\"device\"),\n /**\n * One or more deviceIds (serialised as strings for wire-format\n * consistency with the rest of the union). Matcher accepts if\n * `input.deviceId` ∈ `targets`. Array shape avoids the row-explosion\n * of one scope-per-device when granting access to a set of cameras.\n */\n targets: z.array(z.string()).min(1),\n access: z.array(MethodAccessSchema).min(1)\n })\n]);\nconst UserRecordSchema = z.object({\n id: z.string(),\n username: z.string(),\n passwordHash: z.string(),\n /**\n * Admin bypass. When true, the middleware skips the scope-access\n * check entirely. There is no other axis of privilege; the legacy\n * role enum collapsed onto this boolean in v2.\n */\n isAdmin: z.boolean().default(false),\n allowedProviders: AllowedProviderSchema,\n allowedDevices: AllowedDevicesSchema,\n /**\n * Scopes granted to this user. Admins bypass; their `scopes` is\n * ignored. Non-admins without scopes are locked out of every\n * protected call.\n */\n scopes: z.array(TokenScopeSchema).default([]),\n createdAt: z.number(),\n updatedAt: z.number()\n});\nconst ApiKeyRecordSchema = z.object({\n id: z.string(),\n label: z.string(),\n isAdmin: z.boolean().default(false),\n allowedProviders: AllowedProviderSchema,\n allowedDevices: AllowedDevicesSchema,\n tokenHash: z.string(),\n tokenPrefix: z.string(),\n createdAt: z.number(),\n lastUsedAt: z.number().optional()\n});\nconst ScopedTokenSchema = z.object({\n id: z.string(),\n userId: z.string(),\n name: z.string(),\n tokenHash: z.string(),\n tokenPrefix: z.string(),\n scopes: z.array(TokenScopeSchema),\n // SQLite/JSON storage round-trips undefined → null. Use `nullish` so the\n // schema accepts both `null` (read from disk) and `undefined` (in-memory).\n expiresAt: z.number().nullish(),\n lastUsedAt: z.number().nullish(),\n createdAt: z.number()\n});\nconst UserSummarySchema = z.object({\n id: z.string(),\n username: z.string(),\n isAdmin: z.boolean().default(false),\n allowedProviders: z.union([z.array(z.string()), z.literal(\"*\")]),\n allowedDevices: z.record(z.string(), z.union([z.array(z.string()), z.literal(\"*\")])),\n scopes: z.array(TokenScopeSchema).default([]),\n /**\n * True iff this user has a CONFIRMED TOTP enrollment. Surfaced on\n * `listUsers` so the admin Users page can render the \"Remove 2FA\"\n * action conditionally without firing one `getTotpStatus` query per\n * row. Self-service enrollment lives on the user's profile page.\n */\n totpEnabled: z.boolean().default(false),\n createdAt: z.number(),\n updatedAt: z.number()\n});\nconst CreateUserInputSchema = z.object({\n username: z.string(),\n password: z.string().min(6),\n isAdmin: z.boolean().default(false),\n allowedProviders: z.union([z.array(z.string()), z.literal(\"*\")]).optional(),\n allowedDevices: z.record(z.string(), z.union([z.array(z.string()), z.literal(\"*\")])).optional(),\n scopes: z.array(TokenScopeSchema).optional()\n});\nconst UpdateUserInputSchema = z.object({\n id: z.string(),\n isAdmin: z.boolean().optional(),\n allowedProviders: z.union([z.array(z.string()), z.literal(\"*\")]).optional(),\n allowedDevices: z.record(z.string(), z.union([z.array(z.string()), z.literal(\"*\")])).optional(),\n scopes: z.array(TokenScopeSchema).optional()\n});\nconst ApiKeySummarySchema = z.object({\n id: z.string(),\n label: z.string(),\n isAdmin: z.boolean().default(false),\n allowedProviders: z.union([z.array(z.string()), z.literal(\"*\")]).optional(),\n allowedDevices: z.record(z.string(), z.union([z.array(z.string()), z.literal(\"*\")])).optional(),\n tokenPrefix: z.string(),\n createdAt: z.number(),\n lastUsedAt: z.number().optional()\n});\nconst CreateApiKeyInputSchema = z.object({\n label: z.string(),\n isAdmin: z.boolean().default(false),\n allowedProviders: z.union([z.array(z.string()), z.literal(\"*\")]).optional(),\n allowedDevices: z.record(z.string(), z.union([z.array(z.string()), z.literal(\"*\")])).optional()\n});\nconst CreateApiKeyResultSchema = z.object({\n token: z.string(),\n record: ApiKeySummarySchema\n});\nconst ScopedTokenSummarySchema = z.object({\n id: z.string(),\n userId: z.string(),\n name: z.string(),\n tokenPrefix: z.string(),\n scopes: z.array(TokenScopeSchema),\n expiresAt: z.number().nullish(),\n lastUsedAt: z.number().nullish(),\n createdAt: z.number()\n});\nconst CreateScopedTokenInputSchema = z.object({\n userId: z.string(),\n name: z.string(),\n scopes: z.array(TokenScopeSchema),\n expiresAt: z.number().optional()\n});\nconst CreateScopedTokenResultSchema = z.object({\n token: z.string(),\n record: ScopedTokenSummarySchema\n});\nconst TotpSetupResultSchema = z.object({\n secret: z.string(),\n otpauthUrl: z.string()\n});\nconst TotpStatusSchema = z.object({\n /** True iff `confirmedAt != null` — a pending half-enrollment is reported as `enabled: false`. */\n enabled: z.boolean(),\n /** Null when no row exists OR the row is still pending confirmation. */\n confirmedAt: z.number().nullable()\n});\nconst userManagementCapability = {\n name: \"user-management\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n listUsers: method(z.void(), z.array(UserSummarySchema), { auth: \"admin\" }),\n createUser: method(CreateUserInputSchema, UserSummarySchema, { kind: \"mutation\", auth: \"admin\", access: \"create\" }),\n updateUser: method(UpdateUserInputSchema, z.object({ success: z.literal(true) }), { kind: \"mutation\", auth: \"admin\", access: \"create\" }),\n deleteUser: method(z.object({ id: z.string() }), z.object({ success: z.literal(true) }), { kind: \"mutation\", auth: \"admin\", access: \"delete\" }),\n resetPassword: method(\n z.object({ id: z.string(), newPassword: z.string().min(6) }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\", access: \"create\" }\n ),\n setUserScopes: method(\n z.object({ userId: z.string(), scopes: z.array(TokenScopeSchema) }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\", access: \"create\" }\n ),\n validateCredentials: method(\n z.object({ username: z.string(), password: z.string() }),\n UserSummarySchema.extend({ passwordHash: z.string() }).nullable(),\n { kind: \"mutation\", access: \"view\" }\n ),\n listApiKeys: method(z.void(), z.array(ApiKeySummarySchema), { auth: \"admin\" }),\n createApiKey: method(CreateApiKeyInputSchema, CreateApiKeyResultSchema, { kind: \"mutation\", auth: \"admin\", access: \"create\" }),\n revokeApiKey: method(z.object({ id: z.string() }), z.object({ success: z.literal(true) }), { kind: \"mutation\", auth: \"admin\", access: \"delete\" }),\n validateApiKey: method(z.object({ token: z.string() }), ApiKeySummarySchema.nullable(), { kind: \"mutation\", access: \"view\" }),\n createScopedToken: method(CreateScopedTokenInputSchema, CreateScopedTokenResultSchema, { kind: \"mutation\", auth: \"admin\", access: \"create\" }),\n revokeScopedToken: method(z.object({ id: z.string() }), z.object({ success: z.literal(true) }), { kind: \"mutation\", auth: \"admin\", access: \"delete\" }),\n validateScopedToken: method(z.object({ token: z.string() }), ScopedTokenSummarySchema.nullable(), { access: \"view\" }),\n listScopedTokens: method(z.object({ userId: z.string() }), z.array(ScopedTokenSummarySchema), { auth: \"admin\" }),\n // ── TOTP / 2FA ─────────────────────────────────────────────────\n //\n // Setup → Confirm → (Verify on login) → Disable.\n //\n // Admin-only for now: operator enrolls TOTP on a user's behalf by\n // pairing their authenticator with the returned QR. Self-service\n // enrollment is a follow-up (needs the cap framework to expose the\n // caller's identity to the provider so the provider can enforce\n // self-or-admin).\n setupTotp: method(\n z.object({ userId: z.string() }),\n TotpSetupResultSchema,\n { kind: \"mutation\", auth: \"admin\", access: \"create\" }\n ),\n confirmTotp: method(\n z.object({ userId: z.string(), code: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\", access: \"create\" }\n ),\n disableTotp: method(\n z.object({ userId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\", access: \"delete\" }\n ),\n getTotpStatus: method(\n z.object({ userId: z.string() }),\n TotpStatusSchema,\n { auth: \"admin\" }\n ),\n // Public (no `auth`) — used by the login flow's second-step\n // challenge endpoint. The userId comes from the password-validation\n // step (signed bridge token), so this method is not a free oracle.\n verifyTotp: method(\n z.object({ userId: z.string(), code: z.string() }),\n z.object({ valid: z.boolean() }),\n { kind: \"mutation\", access: \"view\" }\n )\n }\n};\nconst FeatureManifestSchema = z.object({\n streaming: z.boolean(),\n notifications: z.boolean(),\n objectDetection: z.boolean(),\n remoteAccess: z.boolean(),\n agentCluster: z.boolean(),\n smartHome: z.boolean(),\n recordings: z.boolean(),\n backup: z.boolean(),\n repl: z.boolean()\n});\nconst HealthStatusSchema = z.object({\n status: z.literal(\"ok\"),\n uptime: z.number()\n});\nconst NetworkAddressSchema = z.object({\n name: z.string(),\n address: z.string(),\n family: z.string(),\n internal: z.boolean()\n});\nconst systemCapability = {\n name: \"system\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n info: method(z.void(), FeatureManifestSchema),\n health: method(z.void(), HealthStatusSchema),\n featureFlags: method(z.void(), FeatureManifestSchema),\n networkAddresses: method(z.void(), z.array(NetworkAddressSchema).readonly()),\n // Retention config is opaque on the wire — the analytics-suite owns the\n // schema. `getRetentionConfig` returns null when the analytics addon\n // is not loaded; `setRetentionConfig` accepts a partial patch.\n getRetentionConfig: method(z.void(), z.unknown().nullable(), { auth: \"admin\" }),\n setRetentionConfig: method(\n z.record(z.string(), z.unknown()),\n z.null(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n forceRetentionCleanup: method(z.void(), z.void(), { kind: \"mutation\", auth: \"admin\" })\n }\n};\nconst StreamNetworkStatsSchema = z.object({\n nominalBitrateKbps: z.number(),\n observedBitrateKbps: z.number(),\n peakBitrateKbps: z.number(),\n packetLossPercent: z.number(),\n lastUpdated: z.number()\n});\nconst ClientNetworkStatsSchema = z.object({\n rttMs: z.number(),\n jitterMs: z.number(),\n estimatedBandwidthKbps: z.number(),\n lastUpdated: z.number()\n});\nconst DeviceNetworkStatsSchema = z.object({\n deviceId: z.number(),\n streams: z.record(z.string(), StreamNetworkStatsSchema),\n client: ClientNetworkStatsSchema.optional()\n});\nconst networkQualityCapability = {\n name: \"network-quality\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n getDeviceStats: method(\n z.object({ deviceId: z.number() }),\n DeviceNetworkStatsSchema.nullable()\n ),\n getAllStats: method(\n z.void(),\n z.array(DeviceNetworkStatsSchema).readonly()\n ),\n reportClientStats: method(\n z.object({\n deviceId: z.number(),\n rttMs: z.number().min(0).max(6e4),\n jitterMs: z.number().min(0).max(1e4),\n estimatedBandwidthKbps: z.number().min(0).max(1e6)\n }),\n z.void(),\n { kind: \"mutation\" }\n )\n }\n};\nconst ToastSchema = z.object({\n title: z.string(),\n message: z.string(),\n severity: z.enum([\"info\", \"warning\", \"critical\"]),\n duration: z.number().optional(),\n action: z.object({\n label: z.string(),\n url: z.string()\n }).optional()\n});\nconst toastCapability = {\n name: \"toast\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n onToast: method(z.void(), ToastSchema, { kind: \"subscription\" })\n }\n};\nconst TopologyServiceSchema = z.object({\n addonId: z.string(),\n capabilities: z.array(z.string()).readonly(),\n status: z.string()\n});\nconst TopologyProcessSchema = z.object({\n pid: z.number(),\n name: z.string(),\n state: z.string(),\n cpuPercent: z.number(),\n memoryRss: z.number(),\n uptimeSeconds: z.number(),\n services: z.array(TopologyServiceSchema).readonly(),\n groupId: z.string().optional()\n});\nconst TopologyNodeSchema = z.object({\n id: z.string(),\n name: z.string(),\n hostname: z.string(),\n platform: z.string(),\n arch: z.string(),\n cpuModel: z.string().nullable(),\n cpuCores: z.number(),\n memoryMB: z.number(),\n engines: z.array(z.string()).readonly(),\n isHub: z.boolean(),\n isOnline: z.boolean(),\n cpuPercent: z.number(),\n memoryPercent: z.number(),\n uptime: z.number(),\n lastSeen: z.string(),\n localIps: z.array(z.string()).readonly(),\n addons: z.array(\n z.object({\n id: z.string(),\n capabilities: z.array(z.string()).readonly(),\n status: z.string()\n })\n ).readonly(),\n processes: z.array(TopologyProcessSchema).readonly()\n});\nconst ClusterAddonNodeDeploymentSchema = z.object({\n nodeId: z.string(),\n name: z.string(),\n version: z.string(),\n status: z.string(),\n synced: z.boolean()\n});\nconst ClusterAddonStatusEntrySchema = z.object({\n hubVersion: z.string(),\n nodes: z.array(ClusterAddonNodeDeploymentSchema)\n});\nconst NodeAddonInputSchema = z.object({\n nodeId: z.string(),\n addonId: z.string()\n});\nconst NodeAddonEntrySchema = z.object({\n id: z.string(),\n status: z.string(),\n version: z.string().optional(),\n packageName: z.string().optional()\n});\nconst SuccessSchema = z.object({ success: z.boolean() });\nconst RestartProcessResultSchema = z.object({\n success: z.boolean(),\n reason: z.string().optional()\n});\nconst RestartNodeResultSchema = z.object({\n restarted: z.array(z.string()).readonly(),\n failed: z.array(z.string()).readonly()\n});\nconst RenameNodeResultSchema = z.object({\n nodeId: z.string(),\n name: z.string()\n});\nconst nodesCapability = {\n name: \"nodes\",\n scope: \"system\",\n mode: \"singleton\",\n nodeIdMode: \"data\",\n methods: {\n topology: method(\n z.void(),\n z.array(TopologyNodeSchema).readonly(),\n { auth: \"admin\" }\n ),\n deployAddon: method(NodeAddonInputSchema, SuccessSchema, {\n kind: \"mutation\",\n auth: \"admin\"\n }),\n undeployAddon: method(NodeAddonInputSchema, SuccessSchema, {\n kind: \"mutation\",\n auth: \"admin\"\n }),\n restartAddon: method(NodeAddonInputSchema, SuccessSchema, {\n kind: \"mutation\",\n auth: \"admin\"\n }),\n restartProcess: method(\n z.object({ nodeId: z.string(), processName: z.string() }),\n RestartProcessResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n restartNode: method(\n z.object({ nodeId: z.string() }),\n RestartNodeResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n shutdownNode: method(\n z.object({ nodeId: z.string() }),\n SuccessSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n renameNode: method(\n z.object({ nodeId: z.string(), name: z.string().min(1).max(64) }),\n RenameNodeResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n clusterAddonStatus: method(\n z.void(),\n z.record(z.string(), ClusterAddonStatusEntrySchema),\n { auth: \"admin\" }\n ),\n /**\n * Direct per-node addon listing — calls `$agent.status` on the target\n * node (or returns the hub registry for `nodeId === 'hub'`) and surfaces\n * the full addon roster including `version` + `packageName`. The\n * `topology` cap also includes addons but strips them down to\n * `{id, capabilities, status}` for the cluster diagram; this method\n * is the one the per-node \"Addons\" tab should call.\n */\n getNodeAddons: method(\n z.object({ nodeId: z.string() }),\n z.array(NodeAddonEntrySchema).readonly(),\n { auth: \"admin\" }\n ),\n setProcessLogLevel: method(\n z.object({ nodeId: z.string(), level: z.string() }),\n SuccessSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n executeQuery: method(\n z.object({\n nodeId: z.string(),\n addonId: z.string(),\n queryName: z.string(),\n params: z.record(z.string(), z.unknown()).optional()\n }),\n z.unknown(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst IntegrationWithStateSchema = z.object({\n id: z.string(),\n addonId: z.string(),\n name: z.string(),\n enabled: z.boolean(),\n info: z.record(z.string(), z.unknown()).readonly(),\n createdAt: z.number(),\n updatedAt: z.number(),\n processState: z.string()\n});\nconst IntegrationLiteSchema = z.object({\n id: z.string(),\n addonId: z.string(),\n name: z.string(),\n enabled: z.boolean(),\n info: z.record(z.string(), z.unknown()).readonly(),\n createdAt: z.number(),\n updatedAt: z.number()\n});\nconst AvailableIntegrationTypeSchema = z.object({\n addonId: z.string(),\n name: z.string(),\n description: z.string(),\n iconUrl: z.string().nullable(),\n color: z.string(),\n instanceMode: z.string(),\n discoveryMode: z.string(),\n existingInstances: z.array(z.object({ id: z.string(), name: z.string() })),\n canAdd: z.boolean()\n});\nconst TestConnectionResultSchema = z.object({\n success: z.boolean(),\n error: z.string().optional()\n});\nconst CreateIntegrationInputSchema = z.object({\n addonId: z.string(),\n name: z.string(),\n enabled: z.boolean().optional(),\n info: z.record(z.string(), z.unknown()).optional(),\n settings: z.record(z.string(), z.unknown()).optional(),\n skipRestart: z.boolean().optional()\n});\nconst UpdateIntegrationInputSchema = z.object({\n id: z.string(),\n name: z.string().optional(),\n enabled: z.boolean().optional(),\n info: z.record(z.string(), z.unknown()).optional()\n});\nconst DeleteIntegrationResultSchema = z.object({\n success: z.boolean(),\n deletedId: z.string()\n});\nconst integrationsCapability = {\n name: \"integrations\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n list: method(z.void(), z.array(IntegrationWithStateSchema)),\n get: method(z.object({ id: z.string() }), IntegrationWithStateSchema),\n getByAddonId: method(\n z.object({ addonId: z.string() }),\n IntegrationLiteSchema.nullable()\n ),\n create: method(\n CreateIntegrationInputSchema,\n IntegrationLiteSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n update: method(\n UpdateIntegrationInputSchema,\n IntegrationLiteSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n delete: method(\n z.object({ id: z.string() }),\n DeleteIntegrationResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n getSettings: method(\n z.object({ id: z.string() }),\n z.record(z.string(), z.unknown()),\n { auth: \"admin\" }\n ),\n setSettings: method(\n z.object({\n id: z.string(),\n settings: z.record(z.string(), z.unknown())\n }),\n z.object({ success: z.boolean() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n getAvailableTypes: method(\n z.void(),\n z.array(AvailableIntegrationTypeSchema),\n { auth: \"admin\" }\n ),\n testConnection: method(\n z.object({\n addonId: z.string(),\n settings: z.record(z.string(), z.unknown())\n }),\n TestConnectionResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst LogLevelSchema = z.enum([\"debug\", \"info\", \"warn\", \"error\"]);\nconst ChannelSchema = z.enum([\"off\", \"latest\", \"beta\"]);\nconst ChannelWithInheritSchema = z.enum([\"off\", \"latest\", \"beta\", \"inherit\"]);\nconst ManifestShapeSchema = z.object({\n id: z.string(),\n name: z.string().optional(),\n version: z.string().optional(),\n description: z.string().optional(),\n icon: z.string().optional(),\n color: z.string().optional(),\n // Loose schema for `manifest.capabilities` — runtime entries are\n // either kebab-case strings (legacy form) or `CapabilityDeclaration`\n // objects. The cap output schema deliberately keeps it as\n // `readonly unknown[]` so admin-ui consumers cast to the canonical\n // `AddonListItem` (from `@camstack/types`) before reading fields.\n capabilities: z.array(z.unknown()).readonly().optional(),\n packageName: z.string(),\n packageVersion: z.string(),\n packageDisplayName: z.string().optional(),\n /**\n * Bundle metadata when the npm package ships multiple addon entries\n * (mirror of `AddonPackageManifest.bundle` in @camstack/types). When\n * present, the admin UI groups all entries with the same packageName\n * under a collapsible bundle card. Single-entry packages omit this.\n */\n bundle: z.object({\n displayName: z.string(),\n description: z.string().optional(),\n icon: z.string().optional()\n }).optional(),\n protected: z.boolean().optional(),\n removable: z.boolean().optional()\n});\nconst AddonProcessSchema = z.object({\n pid: z.number().optional(),\n mode: z.string(),\n state: z.string()\n});\nconst AddonHealthSchema = z.object({\n phase: z.enum([\"pending\", \"healthy\", \"failed\"]),\n retryCount: z.number(),\n firstFailureAt: z.number().nullable(),\n lastAttemptAt: z.number().nullable(),\n lastError: z.object({ message: z.string(), stack: z.string().optional() }).nullable(),\n nextRetryAt: z.number().nullable(),\n alertEmitted: z.boolean(),\n retrying: z.boolean(),\n inGracePeriod: z.boolean()\n});\nconst AddonListItemSchema = z.object({\n manifest: ManifestShapeSchema,\n declaration: z.unknown().optional(),\n source: z.string(),\n installSource: z.string().optional(),\n process: AddonProcessSchema.optional(),\n /**\n * True when `applyUpdate` last ran for this package and a pre-update\n * backup is still on disk (post-update health-check hasn't cleared\n * it yet, or the user hasn't called `clearBackup`). Drives the\n * Rollback button visibility in admin-ui's AddonCard.\n */\n hasBackup: z.boolean().optional(),\n /** Kernel health snapshot — null when monitor doesn't track this package. */\n health: AddonHealthSchema.nullable().optional()\n});\nconst InstalledPackageSchema = z.object({\n name: z.string(),\n version: z.string(),\n dir: z.string(),\n installSource: z.string().optional()\n});\nconst PackageUpdateSchema = z.object({\n name: z.string(),\n currentVersion: z.string(),\n latestVersion: z.string(),\n category: z.enum([\"addon\", \"core\"]),\n requiresRestart: z.boolean()\n});\nconst PackageVersionInfoSchema = z.object({\n version: z.string(),\n publishedAt: z.string(),\n deprecated: z.string().optional(),\n distTags: z.array(z.string()).readonly()\n});\nconst SearchResultSchema = z.object({\n name: z.string(),\n version: z.string(),\n description: z.string(),\n keywords: z.array(z.string()).readonly(),\n publishedAt: z.string(),\n author: z.string(),\n installed: z.boolean(),\n installedVersion: z.string().optional()\n});\nconst AutoUpdateSettingsSchema = z.object({\n channel: ChannelSchema,\n intervalSeconds: z.number()\n});\nconst AddonAutoUpdateSchema = ChannelWithInheritSchema;\nconst RestartAddonResultSchema = z.unknown();\nconst InstallPackageResultSchema = z.unknown();\nconst ReloadPackagesResultSchema = z.unknown();\nconst UpdateFrameworkPackageResultSchema = z.object({\n packageName: z.string(),\n fromVersion: z.string(),\n toVersion: z.string(),\n /** Ms-epoch the server scheduled its self-restart. */\n restartingAt: z.number()\n});\nconst FrameworkPackageStatusSchema = z.object({\n packageName: z.string(),\n currentVersion: z.string(),\n latestVersion: z.string().nullable(),\n hasUpdate: z.boolean(),\n /** Optional manifest description for the row tooltip. */\n description: z.string().optional()\n});\nconst LogStreamEntrySchema = z.object({\n timestamp: z.string(),\n level: z.string(),\n message: z.string(),\n scope: z.string().optional()\n});\nconst LogQueryEntrySchema = z.unknown();\nconst CustomActionInputSchema = z.object({\n addonId: z.string().min(1),\n action: z.string().min(1),\n input: z.unknown()\n});\nconst addonsCapability = {\n name: \"addons\",\n scope: \"system\",\n mode: \"singleton\",\n nodeIdMode: \"data\",\n methods: {\n // ── Listing ──────────────────────────────────────────────────────\n list: method(z.void(), z.array(AddonListItemSchema).readonly()),\n // ── Logs (query) ────────────────────────────────────────────────\n // Default auth (`protected`): authenticated users — including scoped\n // tokens with the right route-prefix scope. Reading logs isn't an\n // administrative action; install/restart/uninstall stay admin-only.\n getLogs: method(\n z.object({\n addonId: z.string(),\n limit: z.number().min(1).max(500).default(100),\n level: LogLevelSchema.optional()\n }),\n z.array(LogQueryEntrySchema)\n ),\n // ── Packages ────────────────────────────────────────────────────\n listPackages: method(z.void(), z.array(InstalledPackageSchema).readonly()),\n installPackage: method(\n z.object({ packageName: z.string(), version: z.string().optional() }),\n InstallPackageResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n installFromWorkspace: method(\n z.object({ packageName: z.string() }),\n InstallPackageResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n isWorkspaceAvailable: method(z.void(), z.boolean()),\n listWorkspacePackages: method(z.void(), z.array(z.unknown()).readonly()),\n uninstallPackage: method(\n z.object({ packageName: z.string() }),\n z.unknown(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n reloadPackages: method(z.void(), ReloadPackagesResultSchema, {\n kind: \"mutation\",\n auth: \"admin\"\n }),\n // Note: original router declared `searchAvailable` input as optional\n // outer object. The cap codegen requires a stable input shape — we\n // make `query` optional inside a required object to preserve client\n // call shape (`{ query?: string }`).\n searchAvailable: method(\n z.object({ query: z.string().optional() }),\n z.array(SearchResultSchema)\n ),\n /**\n * Available package updates for a node. `nodeId` omitted (or\n * `'hub'`) checks the hub's own installed packages; an agent\n * `nodeId` checks that agent's installed roster against npm\n * (the hub does the npm lookups + diff — agents stay npm-free).\n */\n listUpdates: method(\n z.object({ nodeId: z.string().optional() }),\n z.array(PackageUpdateSchema).readonly(),\n { auth: \"admin\" }\n ),\n /**\n * Update one package on a node. `nodeId` omitted (or `'hub'`)\n * installs on the hub via npm; an agent `nodeId` makes the hub\n * pack the resolved version and push the tarball to that agent\n * (`$agent.deploy` + `$agent.reload`) — agents need no npm runtime.\n */\n updatePackage: method(\n z.object({\n name: z.string().min(1),\n version: z.string().optional(),\n nodeId: z.string().optional()\n }),\n z.unknown(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Roll back an addon to the version it had before the most recent\n * `updatePackage` call. The backup directory pointer is kept in the\n * central addon manifest until the post-update health-check\n * confirms the new install works (then it's cleared automatically),\n * so this only succeeds when the most recent update either failed\n * its restart or the user explicitly wants to revert.\n *\n * Returns `{ rolledBackTo: <version> }` on success, or\n * `{ rolledBackTo: null }` when there's no backup to roll back to\n * (caller can show a \"no backup available\" UI).\n */\n rollbackPackage: method(\n z.object({ name: z.string().min(1) }),\n z.object({ rolledBackTo: z.string().nullable() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Re-check updates for a node, bypassing any cache. `nodeId`\n * omitted (or `'hub'`) refreshes the hub; an agent `nodeId`\n * re-checks that agent's roster. */\n forceRefresh: method(\n z.object({ nodeId: z.string().optional() }),\n z.unknown(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n restartServer: method(\n z.object({ confirm: z.literal(true) }),\n z.unknown(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Most-recent restart marker (kind / packageName / from→to versions\n * / requestedBy / requestedAt). Returns `null` when this process\n * didn't boot from a tracked restart, or when the\n * post-boot retention window (5 min) has elapsed.\n *\n * Drives the admin-UI reconnect overlay's success toast — the\n * `system.restart-completed` event itself is fired before the\n * client has time to re-subscribe, so the client queries this on\n * first reconnect instead.\n */\n getLastRestart: method(\n z.void(),\n z.object({\n kind: z.enum([\"framework-update\", \"manual\", \"system\"]),\n packageName: z.string().optional(),\n fromVersion: z.string().optional(),\n toVersion: z.string().optional(),\n requestedBy: z.string().optional(),\n requestedAt: z.number()\n }).nullable(),\n { auth: \"admin\" }\n ),\n /**\n * Snapshot of the framework packages installed under the hub's\n * `<appRoot>/node_modules/`. Each row carries the currently\n * installed version and (best-effort) the latest version\n * available on npm. Drives the admin-UI \"System packages\" panel.\n *\n * Spec: docs/superpowers/specs/2026-05-14-framework-live-update-design.md\n */\n listFrameworkPackages: method(\n z.void(),\n z.array(FrameworkPackageStatusSchema).readonly(),\n { auth: \"admin\" }\n ),\n /**\n * Cluster-wide capability-provider discovery. Returns the list of\n * `{ addonId, mode, isActive }` tuples for whatever addon(s)\n * currently provide the requested capability across the cluster.\n *\n * Why this lives on `addons` (and not on a `capabilities` cap of\n * its own): the hub's main-process `CapabilityRegistry` already\n * aggregates registrations from every forked group-runner and\n * remote agent via Moleculer event propagation — there's no\n * cross-process registry mirror to build, just an introspection\n * shim.\n *\n * Use this from addon code when you need to know whether another\n * addon has registered a specific cap (e.g. `tailscale-ingress`\n * checking `tailscale-client` is up before calling `tailscale\n * serve`). Don't reach for `ctx.capabilities.getCollectionEntries`\n * — that reads the LOCAL registry of the calling addon's group\n * runner and never sees providers in other processes. See\n * `CLAUDE.md` → Critical rules → ctx.api vs ctx.capabilities.\n */\n listCapabilityProviders: method(\n z.object({ capName: z.string().min(1) }),\n z.array(z.object({\n addonId: z.string(),\n mode: z.enum([\"singleton\", \"collection\"]),\n isActive: z.boolean()\n })).readonly()\n ),\n /**\n * Toggle a single collection-cap provider on/off. Generic write-side\n * counterpart of `listCapabilityProviders` — drives the per-provider\n * Enable/Disable affordance in admin pages (TURN servers, etc.)\n * without needing a bespoke orchestrator cap.\n *\n * Reaches the hub's `CapabilityRegistry` directly:\n * `enableCollectionProvider` / `disableCollectionProvider` flip the\n * registry-level `disabledProviders` set. `getCollectionEntries`\n * already filters disabled providers out, so a disabled provider\n * drops out of every collection aggregate immediately. Only valid\n * for `mode: 'collection'` caps — the registry no-ops + warns for\n * singletons.\n */\n setCapabilityProviderEnabled: method(\n z.object({\n capName: z.string().min(1),\n addonId: z.string().min(1),\n enabled: z.boolean()\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Live-update one of the framework packages marked\n * `camstack.system: true` (`@camstack/types|kernel|core|sdk|ui-library`).\n * Runs `npm install --prefix <appRoot> <name>@<version> --no-save`,\n * writes a `.restart-pending` marker, emits `system.restarting`\n * and schedules a graceful process exit. The supervisor (Docker /\n * Electron / systemd) brings the hub back up; on first boot after\n * the restart the marker fires `system.restart-completed`.\n *\n * `version` defaults to `'latest'`. The allow-list of valid\n * `packageName` values is enforced server-side.\n *\n * Spec: docs/superpowers/specs/2026-05-14-framework-live-update-design.md\n */\n updateFrameworkPackage: method(\n z.object({\n packageName: z.string().min(1),\n version: z.string().optional()\n }),\n UpdateFrameworkPackageResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n getVersions: method(\n z.object({ name: z.string() }),\n z.array(PackageVersionInfoSchema).readonly()\n ),\n restartAddon: method(\n z.object({ addonId: z.string() }),\n RestartAddonResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Force-retry a failed addon NOW. Resets the retry counter so the\n * next failure starts from the 60s interval again. Used by the\n * \"Retry now\" button in the Addons admin page row + AlertCenter\n * alert action. Idempotent on healthy addons (no-op).\n */\n retryLoad: method(\n z.object({ packageName: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Auto-update ─────────────────────────────────────────────────\n getAutoUpdateSettings: method(\n z.void(),\n AutoUpdateSettingsSchema,\n { auth: \"admin\" }\n ),\n setAutoUpdateSettings: method(\n z.object({\n channel: ChannelSchema,\n intervalSeconds: z.number().min(300).max(86400).optional()\n }),\n z.unknown(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n getAddonAutoUpdate: method(\n z.object({ addonId: z.string() }),\n AddonAutoUpdateSchema,\n { auth: \"admin\" }\n ),\n setAddonAutoUpdate: method(\n z.object({ addonId: z.string(), channel: ChannelWithInheritSchema }),\n z.unknown(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n applyAutoUpdateToAll: method(\n z.object({ channel: ChannelSchema }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Custom action dispatcher ────────────────────────────────────\n // Generic dispatcher used by `bindAddonActions`. Per-action auth\n // is enforced inside the provider; the outer cap auth is\n // `protected` (any authenticated user) so individual addons can\n // gate their own actions to public/protected/admin/superAdmin.\n custom: method(CustomActionInputSchema, z.unknown(), { kind: \"mutation\" }),\n // ── Log streaming ───────────────────────────────────────────────\n onAddonLogs: method(\n z.object({\n addonId: z.string(),\n level: LogLevelSchema.optional()\n }),\n LogStreamEntrySchema,\n { kind: \"subscription\" }\n )\n }\n};\nconst PIPELINE_FLOW_CAPABILITY_NAMES = [\n \"decoder\",\n \"motion-detection\",\n \"pipeline-executor\",\n \"audio-analyzer\",\n \"pipeline-analytics\",\n \"notification-output\"\n];\nconst PIPELINE_OWNER_CAPABILITY_NAMES = [\n ...PIPELINE_FLOW_CAPABILITY_NAMES,\n \"pipeline-orchestrator\",\n \"pipeline-runner\"\n];\nexport {\n networkQualityCapability as $,\n adminUiCapability as A,\n advancedNotifierCapability as B,\n alertsCapability as C,\n audioAnalysisCapability as D,\n audioAnalyzerCapability as E,\n audioCodecCapability as F,\n authProviderCapability as G,\n backupCapability as H,\n cameraCredentialsCapability as I,\n decoderCapability as J,\n detectionPipelineCapability as K,\n deviceExportCapability as L,\n deviceManagerCapability as M,\n deviceOpsCapability as N,\n deviceStateCapability as O,\n embeddingEncoderCapability as P,\n eventsCapability as Q,\n integrationsCapability as R,\n intercomCapability as S,\n localNetworkCapability as T,\n logDestinationCapability as U,\n meshNetworkCapability as V,\n metricsProviderCapability as W,\n motionDetectionCapability as X,\n mqttBrokerCapability as Y,\n nativeObjectDetectionCapability as Z,\n networkAccessCapability as _,\n zoneRulesCapability as a,\n AudioMetricsSnapshotSchema as a$,\n nodesCapability as a0,\n notificationOutputCapability as a1,\n osdCapability as a2,\n pipelineAnalyticsCapability as a3,\n pipelineExecutorCapability as a4,\n pipelineOrchestratorCapability as a5,\n pipelineRunnerCapability as a6,\n platformProbeCapability as a7,\n ptzCapability as a8,\n rebootCapability as a9,\n AddonAutoUpdateSchema as aA,\n AddonListItemSchema as aB,\n AddonPageDeclarationSchema as aC,\n AddonPageInfoSchema as aD,\n AgentLoadSummarySchema as aE,\n AlertSchema as aF,\n AlertSeveritySchema as aG,\n AlertSourceSchema as aH,\n AlertStatusSchema as aI,\n ApiKeyRecordSchema as aJ,\n ApiKeySummarySchema as aK,\n ArchiveEntrySchema as aL,\n ArchiveManifestSchema as aM,\n AudioAnalysisResultSchema as aN,\n AudioAnalysisSettingsSchema as aO,\n AudioChunkInputSchema as aP,\n AudioClassSummarySchema as aQ,\n AudioClassificationLabelSchema as aR,\n AudioClassificationResultSchema as aS,\n AudioCodecInfoSchema as aT,\n AudioDecodeSessionConfigSchema as aU,\n AudioEncodeSessionConfigSchema as aV,\n AudioEncodedChunkSchema as aW,\n AudioEventSchema as aX,\n AudioLevelSchema as aY,\n AudioMetricsHistoryPointSchema as aZ,\n AudioMetricsHistorySchema as a_,\n recordingCapability as aa,\n recordingEngineCapability as ab,\n restreamerCapability as ac,\n settingsStoreCapability as ad,\n smtpProviderCapability as ae,\n snapshotCapability as af,\n snapshotProviderCapability as ag,\n ssoBridgeCapability as ah,\n storageCapability as ai,\n storageProviderCapability as aj,\n streamBrokerCapability as ak,\n streamingEngineCapability as al,\n systemCapability as am,\n toastCapability as an,\n turnProviderCapability as ao,\n userManagementCapability as ap,\n userPasskeysCapability as aq,\n webrtcCapability as ar,\n webrtcSessionCapability as as,\n ACCESSORY_LABEL as at,\n APPLE_SA_TO_MACRO as au,\n AUDIO_BACKEND_CHOICES as av,\n AUDIO_MACRO_LABELS as aw,\n AccessoriesStatusSchema as ax,\n AccessoryKind as ay,\n AddBrokerInputSchema as az,\n zoneAnalyticsCapability as b,\n DeviceRole as b$,\n AudioPcmChunkSchema as b0,\n AuthResultSchema as b1,\n AutoUpdateSettingsSchema as b2,\n AvailableIntegrationTypeSchema as b3,\n BATTERY_DEVICE_PROFILE as b4,\n BackupDestinationInfoSchema as b5,\n BackupEntrySchema as b6,\n BatteryStatusSchema as b7,\n BoundingBoxSchema as b8,\n BrightnessStatusSchema as b9,\n ConfigSectionWithValuesSchema as bA,\n ConfigTabDeclarationSchema as bB,\n CreateApiKeyInputSchema as bC,\n CreateApiKeyResultSchema as bD,\n CreateIntegrationInputSchema as bE,\n CreateScopedTokenInputSchema as bF,\n CreateScopedTokenResultSchema as bG,\n CreateUserInputSchema as bH,\n CustomActionInputSchema as bI,\n DEFAULT_AUDIO_ANALYZER_CONFIG as bJ,\n DEFAULT_DECODER_HWACCEL_CONFIG as bK,\n DEVICE_PROFILES as bL,\n DEVICE_SETTINGS_CONTRIBUTION_METHODS as bM,\n DEVICE_STATUS_METHOD as bN,\n DecodedFrameSchema as bO,\n DecoderAssignmentSchema as bP,\n DecoderSessionConfigSchema as bQ,\n DecoderStatsSchema as bR,\n DeleteIntegrationResultSchema as bS,\n DetectorOutputSchema as bT,\n DeviceDiscoveryStatusSchema as bU,\n ExposeInputSchema as bV,\n DeviceExportStatusSchema as bW,\n UnexposeInputSchema as bX,\n DeviceFeature as bY,\n DeviceInfoSchema as bZ,\n DeviceNetworkStatsSchema as b_,\n BrokerAudioClientSchema as ba,\n BrokerClientsSchema as bb,\n BrokerConnectionDetailsSchema as bc,\n BrokerDecodedClientSchema as bd,\n BrokerInfoSchema as be,\n BrokerRtspClientSchema as bf,\n BrokerStatsSchema as bg,\n BrokerStatusSchema$1 as bh,\n CAM_PROFILE_ORDER as bi,\n CamProfileSchema as bj,\n CamStreamKindSchema as bk,\n CamStreamResolutionSchema as bl,\n CameraCredentialsSchema as bm,\n CameraCredentialsStatusSchema as bn,\n CameraMetricsSchema as bo,\n CameraMetricsWithDeviceIdSchema as bp,\n CameraStreamSchema as bq,\n CapScopeSchema as br,\n CapabilityBindingsSchema as bs,\n ChargingStatus as bt,\n ClientNetworkStatsSchema as bu,\n ClusterAddonNodeDeploymentSchema as bv,\n ClusterAddonStatusEntrySchema as bw,\n CollectionColumnSchema as bx,\n CollectionIndexSchema as by,\n ConfigEntrySchema$1 as bz,\n motionCapability as c,\n OsdOverlaySchema as c$,\n DeviceStatusSchema as c0,\n DeviceType as c1,\n DiscoveredChildDeviceSchema as c2,\n DiscoveredChildStatusSchema as c3,\n DiscoveredDeviceSchema as c4,\n DoorbellPressEventSchema as c5,\n DoorbellStatusSchema as c6,\n EmbeddingInfoSchema as c7,\n EmbeddingResultSchema as c8,\n EncodedPacketSchema as c9,\n MediaFileSchema as cA,\n MeshPeerSchema as cB,\n MeshStatusSchema as cC,\n MethodAccessSchema as cD,\n MotionAnalysisResultSchema as cE,\n MotionEventSchema as cF,\n MotionOnMotionChangedDataSchema as cG,\n MotionRegionSchema as cH,\n MotionSourceEnum as cI,\n MotionSourcesSchema as cJ,\n MotionStatusSchema as cK,\n MotionTriggerRuntimeStateSchema as cL,\n MotionTriggerStatusSchema as cM,\n StatusSchema as cN,\n NativeDetectionSchema as cO,\n NativeObjectClassEnum as cP,\n NativeObjectDetectionStatusSchema as cQ,\n NetworkAccessStatusSchema as cR,\n NetworkAddressSchema as cS,\n NetworkEndpointSchema as cT,\n NotificationHistoryEntrySchema as cU,\n NotificationRuleSchema as cV,\n NotificationSchema as cW,\n ObjectEventSchema as cX,\n OrchestratorMetricsSchema as cY,\n OsdOverlayKindEnum as cZ,\n OsdOverlayPatchSchema as c_,\n EnrichedWidgetMetadataSchema as ca,\n EventItemSchema as cb,\n EventKindSchema as cc,\n ExportSetupFieldSchema as cd,\n ExportSetupSchema as ce,\n ExposedDeviceSchema as cf,\n ExposedResourceSchema as cg,\n FeatureManifestSchema as ch,\n FeatureProbeStatusSchema as ci,\n FrameInputSchema as cj,\n GetStreamWithCodecInputSchema as ck,\n GlobalMetricsSchema as cl,\n HWACCEL_OPTIONS as cm,\n HealthStatusSchema as cn,\n HistoryPointSchema as co,\n HistoryResolutionEnum as cp,\n InstalledPackageSchema as cq,\n IntegrationLiteSchema as cr,\n IntegrationWithStateSchema as cs,\n IntercomAbilitySchema as ct,\n IntercomStatusSchema as cu,\n LocationStatSchema as cv,\n LogEntrySchema as cw,\n LogLevelSchema$1 as cx,\n LogStreamEntrySchema as cy,\n MODEL_FORMATS as cz,\n doorbellCapability as d,\n ReadChunkInputSchema as d$,\n OsdPositionEnum as d0,\n OsdStatusSchema as d1,\n PIPELINE_FLOW_CAPABILITY_NAMES as d2,\n PIPELINE_OWNER_CAPABILITY_NAMES as d3,\n PackageUpdateSchema as d4,\n PackageVersionInfoSchema as d5,\n PasskeySummarySchema as d6,\n PcmSampleFormatSchema as d7,\n PerScopeBreakdownSchema as d8,\n PipelineAssignmentSchema as d9,\n STORAGE_LOCATION_CARDINALITY as dA,\n ScopedTokenSchema as dB,\n ScopedTokenSummarySchema as dC,\n SearchResultSchema as dD,\n SegmentSchema as dE,\n SendEmailInputSchema as dF,\n SendEmailResultSchema as dG,\n SettingsPatchSchema as dH,\n SettingsRecordSchema as dI,\n SettingsSchemaWithValuesSchema as dJ,\n SettingsUpdateResultSchema as dK,\n SmtpStatusSchema as dL,\n SnapshotImageSchema as dM,\n SpatialDetectionSchema as dN,\n SsoBridgeClaimsSchema as dO,\n StartEmbeddedInputSchema as dP,\n AbortUploadInputSchema as dQ,\n BeginDownloadInputSchema as dR,\n BeginDownloadResultSchema as dS,\n BeginUploadInputSchema as dT,\n BeginUploadResultSchema as dU,\n EndDownloadInputSchema as dV,\n FinalizeUploadInputSchema as dW,\n StorageLocationRefSchema as dX,\n StorageLocationSchema as dY,\n StorageLocationTypeSchema as dZ,\n ProviderInfoSchema as d_,\n PipelineDefaultStepSchema as da,\n PipelineEngineChoiceSchema as db,\n PipelineRunResultBridge as dc,\n PipelineStepInputSchema as dd,\n PlaceholderReasonSchema as de,\n PolygonPointSchema as df,\n ProfileSlotSchema as dg,\n ProfileSlotStatusSchema as dh,\n ProviderStatusSchema as di,\n PtzAutotrackRuntimeStateSchema as dj,\n PtzAutotrackSettingsSchema as dk,\n PtzAutotrackStatusSchema as dl,\n PtzAutotrackTargetOptionSchema as dm,\n PtzMoveCommandSchema as dn,\n PtzPositionSchema as dp,\n PtzPresetSchema as dq,\n QueryFilterSchema as dr,\n RegisteredStreamSchema as ds,\n ReportMotionInputSchema as dt,\n RtpSourceSchema as du,\n RtspRestreamEntrySchema as dv,\n RunnerCameraConfigSchema as dw,\n RunnerCameraDeviceUIFields as dx,\n RunnerLocalLoadSchema as dy,\n RunnerLocalMetricsSchema as dz,\n errMsg as e,\n TestLocationResultSchema as e0,\n WriteChunkInputSchema as e1,\n StreamFormatSchema as e2,\n StreamInfoSchema as e3,\n StreamNetworkStatsSchema as e4,\n StreamSourceEntrySchema$1 as e5,\n StreamSourceSchema as e6,\n SwitchStatusSchema as e7,\n SystemMetricsSchema as e8,\n TestConnectionResultSchema as e9,\n ZoneSchema as eA,\n ZoneScopeBreakdownSchema as eB,\n accessoryStableId as eC,\n deviceMatchesProfile as eD,\n event as eE,\n expandCapMethods as eF,\n getAudioMacroClassIds as eG,\n mapAudioLabelToMacro as eH,\n method as eI,\n resolveDeviceProfile as eJ,\n webrtcClientHintsSchema as eK,\n ToastSchema as ea,\n TokenScopeSchema as eb,\n TopologyNodeSchema as ec,\n TopologyProcessSchema as ed,\n TopologyServiceSchema as ee,\n TrackSchema as ef,\n TrackStateSchema as eg,\n TrackedDetectionSchema as eh,\n TurnServerSchema as ei,\n UpdateIntegrationInputSchema as ej,\n UpdateUserInputSchema as ek,\n UserRecordSchema as el,\n UserSummarySchema as em,\n WELL_KNOWN_TABS as en,\n WELL_KNOWN_TAB_MAP as eo,\n WebrtcStreamChoiceSchema as ep,\n WebrtcStreamTargetSchema as eq,\n WidgetHostEnum as er,\n WidgetMetadataSchema as es,\n WidgetSizeEnum as et,\n YAMNET_TO_MACRO as eu,\n ZoneKindEnum as ev,\n ZoneRuleModeEnum as ew,\n ZoneRuleSchema as ex,\n ZoneRuleStageEnum as ey,\n ZoneRulesArraySchema as ez,\n featureProbeCapability as f,\n deviceStatusCapability as g,\n hydrateSchema as h,\n deviceDiscoveryCapability as i,\n cameraStreamsCapability as j,\n brightnessCapability as k,\n batteryCapability as l,\n motionTriggerCapability as m,\n audioMetricsCapability as n,\n deviceProviderCapability as o,\n ptzAutotrackCapability as p,\n accessoriesCapability as q,\n addonPagesCapability as r,\n switchCapability as s,\n addonPagesSourceCapability as t,\n addonRoutesCapability as u,\n addonSettingsCapability as v,\n addonWidgetsCapability as w,\n addonWidgetsSourceCapability as x,\n addonsCapability as y,\n zonesCapability as z\n};\n//# sourceMappingURL=index-CWhQOnm9.mjs.map\n","import * as fs from \"node:fs\";\nimport { existsSync, mkdirSync, createWriteStream, unlinkSync, chmodSync, readdirSync, rmSync, renameSync, writeFileSync, readFileSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport { join, basename } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { Readable } from \"node:stream\";\nimport { execFileSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { e as errMsg } from \"./index-CWhQOnm9.mjs\";\nimport \"zod\";\nfunction getPlatformInfo() {\n return {\n platform: process.platform,\n arch: process.arch\n };\n}\nfunction buildBinaryPath(dataDir, name, platform) {\n const ext = (platform ?? process.platform) === \"win32\" ? \".exe\" : \"\";\n return join(dataDir, \"deps\", `${name}${ext}`);\n}\nfunction findInPath(name) {\n try {\n execFileSync(name, [\"--version\"], { stdio: \"pipe\", timeout: 5e3 });\n return name;\n } catch {\n return null;\n }\n}\nasync function downloadBinary(opts) {\n const { name, url, targetDir, targetName, logger, isArchive, archiveFormat, archiveInnerPath } = opts;\n const targetPath = join(targetDir, targetName);\n if (existsSync(targetPath)) {\n logger.debug(\"Binary already exists\", { meta: { name, targetPath } });\n return targetPath;\n }\n mkdirSync(targetDir, { recursive: true });\n logger.info(\"Downloading binary\", { meta: { name, url } });\n const response = await fetch(url, { redirect: \"follow\" });\n if (!response.ok || !response.body) {\n throw new Error(`Failed to download ${name}: ${response.status} ${response.statusText}`);\n }\n if (isArchive) {\n const ext = archiveFormat ?? \"tar.gz\";\n const tmpArchive = join(targetDir, `${name}-download.${ext}`);\n const nodeStream = Readable.fromWeb(response.body);\n await pipeline(nodeStream, createWriteStream(tmpArchive));\n const tmpExtractDir = join(targetDir, `${name}-extract`);\n mkdirSync(tmpExtractDir, { recursive: true });\n if (ext === \"zip\") {\n try {\n execFileSync(\"unzip\", [\"-o\", \"-q\", tmpArchive, \"-d\", tmpExtractDir], { stdio: \"pipe\" });\n } catch {\n execFileSync(\"tar\", [\"-xf\", tmpArchive, \"-C\", tmpExtractDir], { stdio: \"pipe\" });\n }\n } else if (ext === \"tar.xz\") {\n execFileSync(\"tar\", [\"-xJf\", tmpArchive, \"-C\", tmpExtractDir], { stdio: \"pipe\" });\n } else {\n execFileSync(\"tar\", [\"-xzf\", tmpArchive, \"-C\", tmpExtractDir], { stdio: \"pipe\" });\n }\n if (archiveInnerPath) {\n const { copyFileSync } = await import(\"node:fs\");\n const sourcePath = join(tmpExtractDir, archiveInnerPath);\n if (!existsSync(sourcePath)) {\n throw new Error(`Binary not found in archive at ${archiveInnerPath}`);\n }\n copyFileSync(sourcePath, targetPath);\n }\n unlinkSync(tmpArchive);\n const { rmSync: rmSync2 } = await import(\"node:fs\");\n rmSync2(tmpExtractDir, { recursive: true, force: true });\n } else {\n const nodeStream = Readable.fromWeb(response.body);\n await pipeline(nodeStream, createWriteStream(targetPath));\n }\n chmodSync(targetPath, 493);\n logger.info(\"Binary downloaded\", { meta: { name, targetPath } });\n return targetPath;\n}\nasync function ensureBinary(opts) {\n const ext = process.platform === \"win32\" ? \".exe\" : \"\";\n const targetName = `${opts.name}${ext}`;\n const targetPath = join(opts.targetDir, targetName);\n if (existsSync(targetPath)) {\n opts.logger.debug(\"Binary found at target path\", { meta: { name: opts.name, targetPath } });\n return targetPath;\n }\n const inPath = findInPath(opts.name);\n if (inPath) {\n opts.logger.info(\"Binary found in system PATH\", { meta: { name: opts.name } });\n return inPath;\n }\n return downloadBinary({\n name: opts.name,\n url: opts.downloadUrl,\n targetDir: opts.targetDir,\n targetName,\n logger: opts.logger,\n isArchive: opts.isArchive,\n archiveFormat: opts.archiveFormat,\n archiveInnerPath: opts.archiveInnerPath\n });\n}\nconst FFMPEG_VERSION = \"7.1\";\nfunction getFfmpegDownloadUrl(platform, arch) {\n switch (platform) {\n case \"linux\": {\n const archMap = { x64: \"amd64\", arm64: \"arm64\" };\n const a = archMap[arch];\n if (!a) throw new Error(`Unsupported Linux architecture: ${arch}`);\n return `https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-${a}-static.tar.xz`;\n }\n case \"darwin\": {\n const archMap = { arm64: \"arm64\", x64: \"amd64\" };\n const a = archMap[arch];\n if (!a) throw new Error(`Unsupported macOS architecture: ${arch}`);\n return `https://www.osxexperts.net/ffmpeg${FFMPEG_VERSION.replace(\".\", \"\")}arm.zip`;\n }\n default:\n throw new Error(`Unsupported platform: ${platform}`);\n }\n}\nfunction getFfmpegArchiveInfo(platform) {\n switch (platform) {\n case \"linux\":\n return {\n isArchive: true,\n archiveFormat: \"tar.xz\",\n archiveInnerPath: `ffmpeg-${FFMPEG_VERSION}-amd64-static/ffmpeg`\n };\n case \"darwin\":\n return {\n isArchive: true,\n archiveFormat: \"zip\",\n archiveInnerPath: \"ffmpeg\"\n };\n default:\n throw new Error(`Unsupported platform: ${platform}`);\n }\n}\nasync function ensureFfmpeg(dataDir, logger) {\n const depsDir = join(dataDir, \"deps\");\n const platform = process.platform;\n const arch = process.arch;\n const archiveInfo = getFfmpegArchiveInfo(platform);\n return ensureBinary({\n name: \"ffmpeg\",\n targetDir: depsDir,\n downloadUrl: getFfmpegDownloadUrl(platform, arch),\n logger,\n ...archiveInfo\n });\n}\nconst PYTHON_VERSION = \"3.12.12\";\nconst PP_BASE = `https://github.com/bjia56/portable-python/releases/download/cpython-v${PYTHON_VERSION}-build.0`;\nfunction getPythonDownloadUrl(platform, arch) {\n switch (platform) {\n case \"linux\": {\n const archMap = { x64: \"x86_64\", arm64: \"aarch64\" };\n const a = archMap[arch];\n if (!a) throw new Error(`Unsupported Linux architecture for Python: ${arch}`);\n return `${PP_BASE}/python-headless-${PYTHON_VERSION}-linux-${a}.zip`;\n }\n case \"darwin\": {\n return `${PP_BASE}/python-headless-${PYTHON_VERSION}-darwin-universal2.zip`;\n }\n default:\n throw new Error(`Unsupported platform for portable Python: ${platform}`);\n }\n}\nasync function ensurePython(dataDir, logger) {\n const pythonDir = join(dataDir, \"deps\", \"python\");\n const pythonBin = join(pythonDir, \"bin\", \"python3\");\n if (existsSync(pythonBin)) {\n logger.debug(\"Portable Python found\", { meta: { pythonBin } });\n return pythonBin;\n }\n logger.info(\"Downloading portable Python (headless)\", { meta: { version: PYTHON_VERSION } });\n const depsDir = join(dataDir, \"deps\");\n mkdirSync(depsDir, { recursive: true });\n const url = getPythonDownloadUrl(process.platform, process.arch);\n const tmpArchive = join(depsDir, \"python-download.zip\");\n logger.info(\"Python download source\", { meta: { url } });\n const response = await fetch(url, { redirect: \"follow\" });\n if (!response.ok || !response.body) {\n logger.warn(\"Failed to download Python — ML detection will not be available\", { meta: { status: response.status } });\n return null;\n }\n const nodeStream = Readable.fromWeb(response.body);\n await pipeline(nodeStream, createWriteStream(tmpArchive));\n try {\n execFileSync(\"unzip\", [\"-o\", \"-q\", tmpArchive, \"-d\", depsDir], { stdio: \"pipe\" });\n } catch {\n execFileSync(\"python3\", [\"-m\", \"zipfile\", \"-e\", tmpArchive, depsDir], { stdio: \"pipe\" });\n }\n const { unlinkSync: unlinkSync2 } = await import(\"node:fs\");\n unlinkSync2(tmpArchive);\n if (!existsSync(pythonBin)) {\n const candidates = readdirSync(depsDir).filter(\n (name) => name.startsWith(\"python-\") && existsSync(join(depsDir, name, \"bin\", \"python3\"))\n );\n if (candidates.length === 0) {\n logger.warn(\"Python extraction succeeded but no python3 binary found in any subdir\", {\n meta: { depsDir }\n });\n return null;\n }\n const extractedRoot = join(depsDir, candidates[0]);\n if (existsSync(pythonDir)) {\n rmSync(pythonDir, { recursive: true, force: true });\n }\n renameSync(extractedRoot, pythonDir);\n }\n if (!existsSync(pythonBin)) {\n logger.warn(\"Python extraction succeeded but binary not found at expected path\", {\n meta: { pythonBin }\n });\n return null;\n }\n chmodSync(pythonBin, 493);\n if (process.platform === \"darwin\") {\n const realBin = join(pythonDir, \"bin\", \"python3.real\");\n if (!existsSync(realBin)) {\n renameSync(pythonBin, realBin);\n const archFlag = process.arch === \"arm64\" ? \"-arm64\" : \"-x86_64\";\n writeFileSync(\n pythonBin,\n `#!/bin/sh\nexec /usr/bin/arch ${archFlag} \"${realBin}\" \"$@\"\n`\n );\n chmodSync(pythonBin, 493);\n const pyAlt = join(pythonDir, \"bin\", \"python\");\n if (existsSync(pyAlt)) {\n try {\n rmSync(pyAlt, { force: true });\n } catch {\n }\n writeFileSync(\n pyAlt,\n `#!/bin/sh\nexec /usr/bin/arch ${archFlag} \"${realBin}\" \"$@\"\n`\n );\n chmodSync(pyAlt, 493);\n }\n logger.info(\"Locked python3 to host arch via shell stub\", {\n meta: { archFlag, realBin }\n });\n }\n }\n logger.info(\"Portable Python installed\", { meta: { version: PYTHON_VERSION, pythonBin } });\n return pythonBin;\n}\nasync function installPythonPackages(pythonPath, packages, logger) {\n if (packages.length === 0) return;\n logger.info(\"Installing Python packages\", { meta: { packages } });\n try {\n execFileSync(pythonPath, [\"-m\", \"pip\", \"install\", \"--quiet\", ...packages], {\n stdio: \"pipe\",\n timeout: 3e5\n // 5 minutes for large packages like torch\n });\n logger.info(\"Python packages installed successfully\");\n } catch (err) {\n logger.error(\"Failed to install Python packages\", { meta: { error: errMsg(err) } });\n throw err;\n }\n}\nasync function installPythonRequirements(pythonPath, requirementsFile, logger) {\n if (!existsSync(requirementsFile)) {\n throw new Error(`Requirements file not found: ${requirementsFile}`);\n }\n const contents = readFileSync(requirementsFile);\n const hash = createHash(\"sha256\").update(contents).digest(\"hex\").slice(0, 16);\n const fileBase = basename(requirementsFile).replace(/\\.txt$/i, \"\");\n const pythonRoot = join(pythonPath, \"..\", \"..\");\n const markerDir = join(pythonRoot, \".requirements-installed\");\n const markerPath = join(markerDir, `${fileBase}-${hash}.marker`);\n if (existsSync(markerPath)) {\n logger.debug(\"Python requirements already installed\", { meta: { requirementsFile, hash } });\n return;\n }\n logger.info(\"Installing Python requirements\", { meta: { requirementsFile, hash } });\n try {\n execFileSync(\n pythonPath,\n [\"-m\", \"pip\", \"install\", \"--quiet\", \"--disable-pip-version-check\", \"-r\", requirementsFile],\n {\n stdio: \"pipe\",\n timeout: 6e5\n // 10 minutes — coremltools + tensorflow can be slow\n }\n );\n } catch (err) {\n logger.error(\"Failed to install Python requirements\", {\n meta: { requirementsFile, error: errMsg(err) }\n });\n throw err;\n }\n mkdirSync(markerDir, { recursive: true });\n writeFileSync(markerPath, `${requirementsFile}\n${(/* @__PURE__ */ new Date()).toISOString()}\n`);\n logger.info(\"Python requirements installed\", { meta: { requirementsFile, hash } });\n}\nconst STORAGE_LOCATION_TYPES = [\n \"data\",\n \"media\",\n \"recordings\",\n \"recordings-high\",\n \"recordings-low\",\n \"recordings-clips\",\n \"event-images\",\n \"models\",\n \"addons-data\",\n \"cache\",\n \"logs\",\n \"backups\"\n];\nconst DEFAULT_LOCATION_SUBDIRS = {\n \"data\": \"db\",\n \"media\": \"media\",\n \"recordings\": \"recordings\",\n \"recordings-high\": \"recordings-high\",\n \"recordings-low\": \"recordings-low\",\n \"recordings-clips\": \"recordings-clips\",\n \"event-images\": \"event-images\",\n \"models\": \"models\",\n \"addons-data\": \"addons-data\",\n \"cache\": \"/tmp/camstack-cache\",\n \"logs\": \"logs\",\n \"backups\": \"backups\"\n};\nclass FilesystemStorageProvider {\n id = \"local\";\n name = \"Local Filesystem\";\n supportedLocations = [...STORAGE_LOCATION_TYPES];\n rootPath;\n locationPaths;\n constructor(rootPath, overrides) {\n this.rootPath = path.resolve(rootPath);\n this.locationPaths = /* @__PURE__ */ new Map();\n for (const loc of STORAGE_LOCATION_TYPES) {\n const override = overrides?.[loc];\n if (override) {\n this.locationPaths.set(loc, path.resolve(override));\n } else {\n const subdir = DEFAULT_LOCATION_SUBDIRS[loc];\n this.locationPaths.set(\n loc,\n path.isAbsolute(subdir) ? subdir : path.join(this.rootPath, subdir)\n );\n }\n }\n }\n async resolve({ location, relativePath }) {\n const base = this.locationPaths.get(location);\n if (!base) throw new Error(`Unknown storage location: ${location}`);\n return path.join(base, relativePath);\n }\n async write({ location, relativePath, data }) {\n const filePath = await this.resolve({ location, relativePath });\n await fs.promises.mkdir(path.dirname(filePath), { recursive: true });\n if (Buffer.isBuffer(data)) {\n await fs.promises.writeFile(filePath, data);\n } else {\n const writeStream = fs.createWriteStream(filePath);\n await new Promise((resolve, reject) => {\n data.pipe(writeStream);\n writeStream.on(\"finish\", resolve);\n writeStream.on(\"error\", reject);\n });\n }\n }\n async read({ location, relativePath }) {\n return fs.promises.readFile(await this.resolve({ location, relativePath }));\n }\n async exists({ location, relativePath }) {\n try {\n await fs.promises.access(await this.resolve({ location, relativePath }));\n return true;\n } catch {\n return false;\n }\n }\n async list({ location, prefix }) {\n const base = this.locationPaths.get(location);\n if (!base) return [];\n const dir = prefix ? path.join(base, prefix) : base;\n try {\n const entries = await fs.promises.readdir(dir, { withFileTypes: true });\n return entries.map((e) => prefix ? `${prefix}/${e.name}` : e.name);\n } catch {\n return [];\n }\n }\n async delete({ location, relativePath }) {\n const filePath = await this.resolve({ location, relativePath });\n await fs.promises.rm(filePath, { force: true });\n }\n async getAvailableSpace({ location }) {\n const base = this.locationPaths.get(location);\n if (!base) return null;\n try {\n let target = base;\n while (!fs.existsSync(target)) {\n const parent = path.dirname(target);\n if (!parent || parent === target) return null;\n target = parent;\n }\n const stats = await fs.promises.statfs(target);\n return stats.bavail * stats.bsize;\n } catch {\n return null;\n }\n }\n /** Get the resolved path for a location type */\n getLocationPath(location) {\n const p = this.locationPaths.get(location);\n if (!p) throw new Error(`Unknown storage location: ${location}`);\n return p;\n }\n /** Get the root path */\n getRootPath() {\n return this.rootPath;\n }\n}\nexport {\n FilesystemStorageProvider,\n PYTHON_VERSION,\n buildBinaryPath,\n downloadBinary,\n ensureBinary,\n ensureFfmpeg,\n ensurePython,\n findInPath,\n getFfmpegDownloadUrl,\n getPlatformInfo,\n getPythonDownloadUrl,\n installPythonPackages,\n installPythonRequirements\n};\n//# sourceMappingURL=node.mjs.map\n","type EventCallback<T = unknown> = (data: T) => void\n\nexport class EventBus {\n private listeners = new Map<string, Set<EventCallback>>()\n\n on<T = unknown>(event: string, callback: EventCallback<T>): () => void {\n if (!this.listeners.has(event)) this.listeners.set(event, new Set())\n const set = this.listeners.get(event)!\n set.add(callback as EventCallback)\n return () => set.delete(callback as EventCallback)\n }\n\n emit<T = unknown>(event: string, data: T): void {\n const set = this.listeners.get(event)\n if (!set) return\n for (const cb of set) {\n try { cb(data) } catch { /* don't let one listener break others */ }\n }\n }\n\n once<T = unknown>(event: string, callback: EventCallback<T>): () => void {\n const unsub = this.on<T>(event, (data) => {\n unsub()\n callback(data)\n })\n return unsub\n }\n\n removeAllListeners(event?: string): void {\n if (event) this.listeners.delete(event)\n else this.listeners.clear()\n }\n\n listenerCount(event: string): number {\n return this.listeners.get(event)?.size ?? 0\n }\n}\n","import type { ModelCatalogEntry, ModelDownloadOptions, ModelDownloadResult, ModelFormat } from '@camstack/types'\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport { createHash } from 'node:crypto'\n\n/** Build fetch headers, including HF auth token for huggingface.co URLs */\nfunction buildHeaders(url: string): Record<string, string> {\n const headers: Record<string, string> = { 'User-Agent': 'CamStack/1.0' }\n const hfToken = process.env['HF_TOKEN'] ?? process.env['HUGGING_FACE_HUB_TOKEN']\n if (hfToken && url.includes('huggingface.co')) {\n headers['Authorization'] = `Bearer ${hfToken}`\n }\n return headers\n}\n\n/**\n * Download a single file from a URL to a destination path.\n * Uses native fetch() (Node 22+) which handles redirects natively.\n * Streams to disk with optional progress callback.\n * Returns the destination path. Skips download if file already exists.\n */\nexport async function downloadFile(\n url: string,\n destPath: string,\n onProgress?: (downloaded: number, total: number) => void,\n): Promise<string> {\n if (fs.existsSync(destPath)) return destPath\n\n fs.mkdirSync(path.dirname(destPath), { recursive: true })\n\n // Atomic download: write to .downloading tmp, rename on success\n const tmpPath = destPath + '.downloading'\n\n try {\n const response = await fetch(url, {\n redirect: 'follow',\n headers: buildHeaders(url),\n })\n if (!response.ok) {\n throw new Error(`HTTP ${response.status} downloading ${url}`)\n }\n if (!response.body) {\n throw new Error(`No response body from ${url}`)\n }\n\n const total = parseInt(response.headers.get('content-length') ?? '0', 10)\n let downloaded = 0\n\n const fileStream = fs.createWriteStream(tmpPath)\n const reader = response.body.getReader()\n\n try {\n for (;;) {\n const { done, value } = await reader.read() as { done: boolean; value?: Uint8Array }\n if (done || !value) break\n fileStream.write(value)\n downloaded += value.length\n onProgress?.(downloaded, total)\n }\n } finally {\n fileStream.end()\n await new Promise<void>((resolve, reject) => {\n fileStream.on('finish', resolve)\n fileStream.on('error', reject)\n })\n }\n\n fs.renameSync(tmpPath, destPath)\n return destPath\n } catch (err) {\n // Clean up partial download\n try { fs.unlinkSync(tmpPath) } catch { /* ignore */ }\n throw err\n }\n}\n\n/**\n * Fetch JSON from a URL using native fetch().\n */\nexport async function fetchJson(url: string): Promise<unknown> {\n const response = await fetch(url, {\n redirect: 'follow',\n headers: buildHeaders(url),\n })\n if (!response.ok) {\n throw new Error(`HTTP ${response.status} fetching ${url}`)\n }\n return response.json()\n}\n\n/**\n * Download a model with fallback URLs and optional SHA256 verification.\n * Legacy API preserved for backward compatibility -- delegates to downloadFile().\n */\nexport async function downloadModel(options: ModelDownloadOptions): Promise<ModelDownloadResult> {\n const { url, fallbackUrls = [], destDir, filename, expectedSha256, onProgress } = options\n\n const fname = filename ?? url.split('/').pop() ?? 'model.bin'\n const destPath = path.join(destDir, fname)\n\n // Check cache\n if (fs.existsSync(destPath)) {\n return { filePath: destPath, downloadedBytes: 0, fromCache: true }\n }\n\n fs.mkdirSync(destDir, { recursive: true })\n\n const urls = [url, ...fallbackUrls]\n let lastError: Error | null = null\n\n for (const tryUrl of urls) {\n try {\n await downloadFile(tryUrl, destPath, onProgress)\n\n // Verify SHA256 if provided\n if (expectedSha256) {\n const hash = await computeSha256(destPath)\n if (hash !== expectedSha256) {\n fs.unlinkSync(destPath)\n throw new Error(`SHA256 mismatch: expected ${expectedSha256}, got ${hash}`)\n }\n }\n\n const stat = fs.statSync(destPath)\n return { filePath: destPath, downloadedBytes: stat.size, fromCache: false }\n } catch (e) {\n lastError = e as Error\n if (fs.existsSync(destPath)) fs.unlinkSync(destPath)\n }\n }\n\n throw lastError ?? new Error(`Failed to download model from ${url}`)\n}\n\nasync function computeSha256(filePath: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const hash = createHash('sha256')\n const stream = fs.createReadStream(filePath)\n stream.on('data', (chunk) => hash.update(chunk))\n stream.on('end', () => resolve(hash.digest('hex')))\n stream.on('error', reject)\n })\n}\n\n// ---------------------------------------------------------------------------\n// ModelCatalogEntry-based helpers\n// ---------------------------------------------------------------------------\n//\n// These are the standalone counterparts to `ModelDownloadService.ensure()`\n// for callers that don't need a class-based catalog and just want to\n// resolve a single `ModelCatalogEntry` against `modelsDir`. Detection\n// pipeline previously kept its own copy of this logic\n// (`addon-detection-pipeline/src/engine/model-downloader.ts`); merging\n// them here lets every addon (detection, audio-analyzer, embedding-\n// encoder, …) share one source of truth.\n\n/** Progress callback: (downloadedBytes, totalBytes | undefined) */\nexport type DownloadProgressCallback = (downloaded: number, total: number | undefined) => void\n\n/**\n * Download every file in a HuggingFace directory bundle (e.g.,\n * `.mlpackage` / OpenVINO IR pair) atomically. `knownFiles` lists the\n * relative paths inside the directory; the function fetches each from\n * `${url}/${file}` and renames the staging directory only on full\n * success. Mirrors `ModelDownloadService.downloadDirectory` but\n * exposed as a standalone for catalog-less callers.\n */\nasync function downloadDirectory(\n url: string,\n destDir: string,\n knownFiles: readonly string[] | undefined,\n onProgress?: DownloadProgressCallback,\n): Promise<void> {\n const match = url.match(/huggingface\\.co\\/([^/]+\\/[^/]+)\\/resolve\\/main\\/(.+)/)\n if (!match) throw new Error(`Cannot parse HuggingFace URL: ${url}`)\n const [, repo, dirPath] = match\n\n const files = (knownFiles ?? []).map(f => ({\n relativePath: f,\n fileUrl: `https://huggingface.co/${repo}/resolve/main/${dirPath}/${f}`,\n }))\n if (files.length === 0) {\n throw new Error(`Directory bundle requires explicit \\`files\\` list (got none for ${url})`)\n }\n\n const tmpDir = destDir + '.downloading'\n fs.rmSync(tmpDir, { recursive: true, force: true })\n fs.mkdirSync(tmpDir, { recursive: true })\n\n let totalDownloaded = 0\n try {\n for (const file of files) {\n const destPath = path.join(tmpDir, file.relativePath)\n fs.mkdirSync(path.dirname(destPath), { recursive: true })\n await downloadFile(file.fileUrl, destPath, (downloaded, _total) => {\n onProgress?.(totalDownloaded + downloaded, undefined)\n })\n totalDownloaded += fs.statSync(destPath).size\n }\n fs.rmSync(destDir, { recursive: true, force: true })\n fs.renameSync(tmpDir, destDir)\n } catch (err) {\n fs.rmSync(tmpDir, { recursive: true, force: true })\n throw err\n }\n}\n\n/**\n * Resolve a `ModelCatalogEntry` against `modelsDir`: download model file\n * (or directory bundle) + extra files (labels JSON, charset dict, …),\n * skip if already on disk. Returns the local model path.\n */\nexport async function ensureModel(\n modelsDir: string,\n entry: ModelCatalogEntry,\n format: ModelFormat,\n onProgress?: DownloadProgressCallback,\n): Promise<string> {\n const formatEntry = entry.formats[format]\n if (!formatEntry) {\n throw new Error(\n `Model \"${entry.id}\" has no ${format} format. Available: ${Object.keys(entry.formats).join(', ')}`,\n )\n }\n\n // Extras (labels, dicts) — independent of format.\n if (entry.extraFiles) {\n for (const extra of entry.extraFiles) {\n await downloadFile(extra.url, path.join(modelsDir, extra.filename))\n }\n }\n\n const filename = formatEntry.url.split('/').pop() ?? `${entry.id}.${format}`\n const modelPath = path.join(modelsDir, filename)\n\n if (fs.existsSync(modelPath)) {\n if (formatEntry.isDirectory && !fs.existsSync(path.join(modelPath, 'Manifest.json'))) {\n // Stale half-downloaded mlpackage — wipe and re-fetch.\n fs.rmSync(modelPath, { recursive: true, force: true })\n } else {\n return modelPath\n }\n }\n\n fs.mkdirSync(modelsDir, { recursive: true })\n\n if (formatEntry.isDirectory) {\n await downloadDirectory(formatEntry.url, modelPath, formatEntry.files, onProgress)\n } else {\n await downloadFile(formatEntry.url, modelPath, (downloaded, total) =>\n onProgress?.(downloaded, total === 0 ? undefined : total),\n )\n }\n\n return modelPath\n}\n\n/** Compute the on-disk path for a given model + format, even when not yet downloaded. */\nexport function getModelFilePath(\n modelsDir: string,\n entry: ModelCatalogEntry,\n format: ModelFormat,\n): string | null {\n const formatEntry = entry.formats[format]\n if (!formatEntry) return null\n const filename = formatEntry.url.split('/').pop() ?? `${entry.id}.${format}`\n return path.join(modelsDir, filename)\n}\n\n/** True iff the model file (or `Manifest.json` for directory bundles) exists and is non-empty. */\nexport function isModelDownloaded(\n modelsDir: string,\n entry: ModelCatalogEntry,\n format: ModelFormat,\n): boolean {\n const formatEntry = entry.formats[format]\n if (!formatEntry) return false\n const modelPath = getModelFilePath(modelsDir, entry, format)\n if (!modelPath || !fs.existsSync(modelPath)) return false\n if (formatEntry.isDirectory) return fs.existsSync(path.join(modelPath, 'Manifest.json'))\n return fs.statSync(modelPath).size > 0\n}\n\n/** Remove the on-disk model file/directory. Returns true if something was deleted. */\nexport function deleteModelFromDisk(\n modelsDir: string,\n entry: ModelCatalogEntry,\n format: ModelFormat,\n): boolean {\n const modelPath = getModelFilePath(modelsDir, entry, format)\n if (!modelPath || !fs.existsSync(modelPath)) return false\n const formatEntry = entry.formats[format]\n if (formatEntry?.isDirectory) {\n fs.rmSync(modelPath, { recursive: true, force: true })\n } else {\n fs.unlinkSync(modelPath)\n }\n return true\n}\n","import type { ModelCatalogEntry, ModelFormat, IAddonModelManager } from '@camstack/types'\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport { downloadFile, fetchJson } from './model-downloader.js'\n\n/**\n * Unified model download service.\n *\n * Handles downloading model files and extra files (labels, dicts) from a\n * catalog of ModelCatalogEntry items. Supports single-file models and\n * directory bundles (e.g., .mlpackage for CoreML).\n *\n * Addons use this via `context.models.ensure(modelId, format)`.\n */\nexport class ModelDownloadService implements IAddonModelManager {\n private readonly catalog: ReadonlyMap<string, ModelCatalogEntry>\n\n constructor(\n private readonly modelsDir: string,\n catalog: readonly ModelCatalogEntry[],\n private readonly onProgress?: (modelId: string, downloaded: number, total: number) => void,\n ) {\n const map = new Map<string, ModelCatalogEntry>()\n for (const entry of catalog) {\n map.set(entry.id, entry)\n }\n this.catalog = map\n }\n\n /**\n * Ensure a model (and its extra files) is downloaded.\n * Returns the local filesystem path to the model file/directory.\n */\n async ensure(modelId: string, format?: ModelFormat): Promise<string> {\n const entry = this.catalog.get(modelId)\n if (!entry) {\n throw new Error(`ModelDownloadService: unknown model \"${modelId}\"`)\n }\n\n // Resolve format: use provided or pick first available\n const selectedFormat = format ?? this.pickDefaultFormat(entry)\n const formatEntry = entry.formats[selectedFormat]\n if (!formatEntry) {\n throw new Error(\n `ModelDownloadService: model \"${modelId}\" has no ${selectedFormat} format`,\n )\n }\n\n // Download extra files first (labels JSON, dict.txt, etc.)\n await this.ensureExtraFiles(modelId)\n\n // Derive local path from URL\n const modelPath = this.modelFilePath(entry, selectedFormat)\n\n if (fs.existsSync(modelPath)) {\n // Validate directory bundles have required Manifest.json\n if (formatEntry.isDirectory) {\n if (!fs.existsSync(path.join(modelPath, 'Manifest.json'))) {\n fs.rmSync(modelPath, { recursive: true, force: true })\n } else {\n return modelPath\n }\n } else {\n return modelPath\n }\n }\n\n fs.mkdirSync(this.modelsDir, { recursive: true })\n\n if (formatEntry.isDirectory) {\n await this.downloadDirectory(\n formatEntry.url,\n modelPath,\n formatEntry.files,\n modelId,\n )\n } else {\n await downloadFile(\n formatEntry.url,\n modelPath,\n this.onProgress\n ? (downloaded, total) => this.onProgress!(modelId, downloaded, total)\n : undefined,\n )\n }\n\n return modelPath\n }\n\n /**\n * Ensure extra files for a model are downloaded.\n * Returns the local paths of all extra files.\n */\n async ensureExtraFiles(modelId: string): Promise<readonly string[]> {\n const entry = this.catalog.get(modelId)\n if (!entry) {\n throw new Error(`ModelDownloadService: unknown model \"${modelId}\"`)\n }\n\n const extras = entry.extraFiles\n if (!extras || extras.length === 0) return []\n\n const paths: string[] = []\n for (const extra of extras) {\n const destPath = path.join(this.modelsDir, extra.filename)\n await downloadFile(extra.url, destPath)\n paths.push(destPath)\n }\n return paths\n }\n\n /** Absolute path to the shared models directory. */\n getModelsDir(): string {\n return this.modelsDir\n }\n\n /** Check if a model file is already present on disk. */\n isDownloaded(modelId: string, format?: ModelFormat): boolean {\n const entry = this.catalog.get(modelId)\n if (!entry) return false\n\n const selectedFormat = format ?? this.pickDefaultFormat(entry)\n const formatEntry = entry.formats[selectedFormat]\n if (!formatEntry) return false\n\n const modelPath = this.modelFilePath(entry, selectedFormat)\n if (!fs.existsSync(modelPath)) return false\n\n // Validate directory bundles\n if (formatEntry.isDirectory) {\n return fs.existsSync(path.join(modelPath, 'Manifest.json'))\n }\n\n return fs.statSync(modelPath).size > 0\n }\n\n /** Get the catalog entry for a model by ID. */\n getEntry(modelId: string): ModelCatalogEntry | undefined {\n return this.catalog.get(modelId)\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private pickDefaultFormat(entry: ModelCatalogEntry): ModelFormat {\n // Prefer onnx, then others in order\n const priority: ModelFormat[] = ['onnx', 'coreml', 'openvino', 'tflite', 'pt']\n for (const fmt of priority) {\n if (entry.formats[fmt]) return fmt\n }\n // Fallback: first available format\n const first = Object.keys(entry.formats)[0] as ModelFormat | undefined\n if (first) return first\n throw new Error(`ModelDownloadService: model \"${entry.id}\" has no formats`)\n }\n\n private modelFilePath(entry: ModelCatalogEntry, format: ModelFormat): string {\n const formatEntry = entry.formats[format]\n if (!formatEntry) {\n throw new Error(`Model ${entry.id} has no ${format} format`)\n }\n const urlParts = formatEntry.url.split('/')\n const filename = urlParts[urlParts.length - 1] ?? `${entry.id}.${format}`\n return path.join(this.modelsDir, filename)\n }\n\n /**\n * Download a directory bundle (e.g., .mlpackage) from HuggingFace.\n * ATOMIC: downloads to temp dir, renames only on complete success.\n */\n private async downloadDirectory(\n url: string,\n destDir: string,\n knownFiles?: readonly string[],\n _modelId?: string,\n ): Promise<void> {\n const match = url.match(/huggingface\\.co\\/([^/]+\\/[^/]+)\\/resolve\\/main\\/(.+)/)\n if (!match) throw new Error(`Cannot parse HuggingFace URL: ${url}`)\n\n const [, repo, dirPath] = match\n\n let filesToDownload: Array<{ relativePath: string; fileUrl: string }>\n\n if (knownFiles && knownFiles.length > 0) {\n filesToDownload = knownFiles.map(f => ({\n relativePath: f,\n fileUrl: `https://huggingface.co/${repo}/resolve/main/${dirPath}/${f}`,\n }))\n } else {\n const hfFiles = await this.listHfFiles(repo!, dirPath!)\n if (hfFiles.length === 0) {\n throw new Error(`No files found in HuggingFace directory: ${dirPath}`)\n }\n filesToDownload = hfFiles.map(f => ({\n relativePath: f.path.substring(dirPath!.length + 1),\n fileUrl: `https://huggingface.co/${repo}/resolve/main/${f.path}`,\n }))\n }\n\n const tmpDir = destDir + '.downloading'\n fs.rmSync(tmpDir, { recursive: true, force: true })\n fs.mkdirSync(tmpDir, { recursive: true })\n\n try {\n for (const file of filesToDownload) {\n const destPath = path.join(tmpDir, file.relativePath)\n fs.mkdirSync(path.dirname(destPath), { recursive: true })\n await downloadFile(file.fileUrl, destPath)\n }\n\n fs.rmSync(destDir, { recursive: true, force: true })\n fs.renameSync(tmpDir, destDir)\n } catch (err) {\n fs.rmSync(tmpDir, { recursive: true, force: true })\n throw err\n }\n }\n\n /** Recursively list all files in a HuggingFace directory via API. */\n private async listHfFiles(\n repo: string,\n dirPath: string,\n ): Promise<Array<{ path: string; size: number }>> {\n const apiUrl = `https://huggingface.co/api/models/${repo}/tree/main/${dirPath}`\n const entries = (await fetchJson(apiUrl)) as ReadonlyArray<{\n readonly type: string\n readonly path: string\n readonly size?: number\n readonly lfs?: { readonly size: number }\n }>\n const files: Array<{ path: string; size: number }> = []\n\n for (const entry of entries) {\n if (entry.type === 'file') {\n files.push({ path: entry.path, size: entry.size ?? entry.lfs?.size ?? 0 })\n } else if (entry.type === 'directory') {\n const subFiles = await this.listHfFiles(repo, entry.path)\n files.push(...subFiles)\n }\n }\n\n return files\n }\n}\n","import type { IPythonEnvironment, PythonProbeResult, PythonEnvReady } from '@camstack/types'\nimport { execFile, spawn } from 'node:child_process'\nimport type { ChildProcess } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\nconst execFileAsync = promisify(execFile)\n\nexport class PythonEnvManager implements IPythonEnvironment {\n private venvPath: string\n private cachedProbe: PythonProbeResult | null = null\n\n constructor(dataDir: string) {\n this.venvPath = path.join(dataDir, '.venv')\n }\n\n async probe(): Promise<PythonProbeResult> {\n if (this.cachedProbe) return this.cachedProbe\n\n // Try python3, then python\n for (const cmd of ['python3', 'python']) {\n try {\n const { stdout } = await execFileAsync(cmd, ['--version'])\n const version = stdout.trim().replace('Python ', '')\n const major = parseInt(version.split('.')[0] ?? '0', 10)\n const minor = parseInt(version.split('.')[1] ?? '0', 10)\n\n if (major < 3 || (major === 3 && minor < 10)) continue\n\n // Get path\n const { stdout: pathOut } = await execFileAsync(cmd, ['-c', 'import sys; print(sys.executable)'])\n\n this.cachedProbe = {\n available: true,\n version,\n path: pathOut.trim(),\n }\n return this.cachedProbe\n } catch { continue }\n }\n\n this.cachedProbe = { available: false }\n return this.cachedProbe\n }\n\n async ensure(options: { packages: readonly string[] }): Promise<PythonEnvReady> {\n const probe = await this.probe()\n if (!probe.available || !probe.path) {\n throw new Error('Python 3.10+ is required but not found on this system')\n }\n\n // Create venv if needed\n if (!fs.existsSync(path.join(this.venvPath, 'bin', 'python'))) {\n await execFileAsync(probe.path, ['-m', 'venv', this.venvPath])\n }\n\n const venvPython = path.join(this.venvPath, 'bin', 'python')\n\n // Install packages\n if (options.packages.length > 0) {\n await execFileAsync(venvPython, ['-m', 'pip', 'install', '-q', ...options.packages])\n }\n\n return {\n pythonPath: venvPython,\n venvPath: this.venvPath,\n spawn: (script: string, args: readonly string[]) => {\n return spawn(venvPython, [script, ...args])\n },\n }\n }\n\n spawn(script: string, args: readonly string[]): ChildProcess {\n const venvPython = path.join(this.venvPath, 'bin', 'python')\n if (!fs.existsSync(venvPython)) {\n throw new Error('Python venv not initialized. Call ensure() first.')\n }\n return spawn(venvPython, [script, ...args])\n }\n}\n","import type { PipelineConfig, PipelineNode, ValidationIssue, ValidationResult } from '@camstack/types'\n\nexport type { ValidationIssue, ValidationResult }\n\n/**\n * Check if a pipeline step is available in the system.\n * Implementations should check the capability registry for `pipeline-step:{stepId}`.\n */\nexport type StepExistsFn = (stepId: string) => boolean\n\nexport class PipelineValidator {\n constructor(private readonly stepExists: StepExistsFn) {}\n\n validate(config: PipelineConfig): ValidationResult {\n const errors: ValidationIssue[] = []\n const warnings: ValidationIssue[] = []\n\n for (const node of config.video) {\n this.validateNode(node, errors, warnings)\n }\n\n if (config.audio) {\n this.validateNode(config.audio, errors, warnings)\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n }\n }\n\n private validateNode(\n node: PipelineNode,\n errors: ValidationIssue[],\n warnings: ValidationIssue[],\n ): void {\n if (!this.stepExists(node.addon)) {\n errors.push({\n step: node.step,\n addon: node.addon,\n message: `Step \"${node.addon}\" has no provider — the addon that provided it may have been removed`,\n severity: 'error',\n })\n return\n }\n\n if (node.children) {\n for (const child of node.children) {\n this.validateNode(child, errors, warnings)\n }\n }\n }\n}\n","import type {\n FrameInput,\n CropInput,\n PipelineConfig,\n PipelineNode,\n PipelineResult,\n StepResult,\n SpatialDetection,\n PipelineSlot,\n IAddonResolver,\n InferenceOutput,\n} from '@camstack/types'\nimport { randomUUID } from 'node:crypto'\nimport { errMsg } from '@camstack/types'\n\nexport class PipelineRunner {\n constructor(\n private readonly addonResolver: IAddonResolver,\n ) {}\n\n async run(frame: FrameInput, config: PipelineConfig): Promise<PipelineResult> {\n const startTime = performance.now()\n const results: StepResult[] = []\n const timings: Record<string, number> = {}\n\n // Execute video pipeline root nodes\n for (const rootNode of config.video) {\n await this.executeNode(rootNode, frame, null, results, timings)\n }\n\n // Execute audio node if present (independent)\n if (config.audio) {\n await this.executeNode(config.audio, frame, null, results, timings)\n }\n\n return {\n results,\n totalMs: performance.now() - startTime,\n timings,\n frameTimestamp: frame.timestamp,\n }\n }\n private async executeNode(\n node: PipelineNode,\n frame: FrameInput,\n parentDetection: { det: SpatialDetection; resultId: string } | null,\n results: StepResult[],\n timings: Record<string, number>,\n ): Promise<void> {\n const resultId = randomUUID()\n const stepStart = performance.now()\n\n try {\n // Resolve addon caller via the resolver\n const effectiveConfig = { ...node.configOverride }\n const caller = await this.addonResolver.resolve(node.addon, effectiveConfig)\n\n // Unified interface: always call process() with the appropriate input.\n // - Root nodes: FrameInput (full frame)\n // - Child nodes: CropInput (region from parent detection)\n // The addon determines output type (detections/crops/classifications/mask)\n // based on its slot — the runner doesn't need to know.\n let output: InferenceOutput\n\n if (parentDetection) {\n const cropInput: CropInput = {\n frame,\n roi: parentDetection.det.bbox,\n parentDetection: parentDetection.det,\n }\n output = await caller.process(cropInput)\n } else {\n output = await caller.process(frame)\n }\n\n const stepMs = performance.now() - stepStart\n\n // Determine slot type from output shape\n const slot: PipelineSlot =\n 'detections' in output ? 'detector' :\n 'crops' in output ? 'cropper' :\n 'classifier'\n\n const stepResult: StepResult = {\n addon: node.addon,\n slot,\n output,\n parentResultId: parentDetection?.resultId,\n resultId,\n inferenceMs: output.inferenceMs,\n preprocessMs: 0,\n totalMs: stepMs,\n }\n results.push(stepResult)\n timings[node.step] = stepMs\n\n // Process children\n if (node.children?.length) {\n const detections: readonly SpatialDetection[] =\n 'detections' in output ? output.detections :\n 'crops' in output ? output.crops :\n []\n\n // For each detection, find children with matching inputClasses and execute\n await this.executeChildren(node.children, frame, detections, resultId, results, timings)\n }\n } catch (error: unknown) {\n const stepMs = performance.now() - stepStart\n const message = errMsg(error)\n results.push({\n addon: node.addon,\n slot: 'detector',\n output: { detections: [], inferenceMs: 0, modelId: '' },\n parentResultId: parentDetection?.resultId,\n resultId,\n inferenceMs: 0,\n preprocessMs: 0,\n totalMs: stepMs,\n error: {\n code: 'ADDON_ERROR',\n message,\n childrenSkipped: true,\n },\n })\n }\n }\n\n private async executeChildren(\n children: readonly PipelineNode[],\n frame: FrameInput,\n parentDetections: readonly SpatialDetection[],\n parentResultId: string,\n results: StepResult[],\n timings: Record<string, number>,\n ): Promise<void> {\n // For each parent detection, run all matching children in parallel\n const promises: Promise<void>[] = []\n\n for (const detection of parentDetections) {\n // Skip detections with degenerate bounding boxes\n if (detection.bbox.w < 1 || detection.bbox.h < 1) continue\n\n for (const child of children) {\n // TODO: Check inputClasses matching from addon manifest\n // For now, run all children on all detections (caller configures tree correctly)\n promises.push(\n this.executeNode(child, frame, { det: detection, resultId: parentResultId }, results, timings),\n )\n }\n }\n\n await Promise.allSettled(promises)\n }\n}\n","import type {\n IAddonResolver,\n IAddonCaller,\n IEngineManager,\n InferenceOutput,\n FrameInput,\n CropInput,\n} from '@camstack/types'\n\n/**\n * Adapter that wraps an IEngineManager + addonConfigs as an IAddonResolver.\n *\n * Used for backwards compatibility — the in-process AddonEngineManager\n * still uses the old getOrCreateEngine(addonId, globalConfig, override) API.\n * This adapter bridges it to the new resolve(addonId, config) interface.\n */\nexport class EngineManagerResolver implements IAddonResolver {\n constructor(\n private readonly engineManager: IEngineManager,\n private readonly addonConfigs: Map<string, Record<string, unknown>>,\n ) {}\n\n async resolve(addonId: string, config: Record<string, unknown>): Promise<IAddonCaller> {\n const globalConfig = this.addonConfigs.get(addonId) ?? {}\n const engine = await this.engineManager.getOrCreateEngine(addonId, globalConfig, config)\n\n return {\n process: async (input: FrameInput | CropInput): Promise<InferenceOutput> => {\n return engine.process(input as FrameInput)\n },\n }\n }\n\n async shutdownAll(): Promise<void> {\n await this.engineManager.shutdownAll()\n }\n}\n","import type {\n StreamNetworkStats,\n ClientNetworkStats,\n DeviceNetworkStats,\n INetworkQualityTracker,\n} from '@camstack/types'\n\nexport type {\n StreamNetworkStats,\n ClientNetworkStats,\n DeviceNetworkStats,\n INetworkQualityTracker,\n}\n\ninterface MutableStreamStats {\n nominalBitrateKbps: number\n samples: number[]\n peakBitrateKbps: number\n packetLossSamples: number[]\n lastUpdated: number\n}\n\nexport class NetworkQualityTracker implements INetworkQualityTracker {\n private readonly devices = new Map<number, {\n streams: Map<string, MutableStreamStats>\n client: (ClientNetworkStats & { lastUpdated: number }) | null\n }>()\n\n private static readonly MAX_SAMPLES = 30 // ~5 min at 10s reporting interval\n\n reportStreamStats(deviceId: number, streamId: string, bitrateKbps: number, packetLoss?: number): void {\n const device = this.getOrCreateDevice(deviceId)\n let stream = device.streams.get(streamId)\n if (!stream) {\n stream = { nominalBitrateKbps: bitrateKbps, samples: [], peakBitrateKbps: 0, packetLossSamples: [], lastUpdated: 0 }\n device.streams.set(streamId, stream)\n }\n\n stream.samples.push(bitrateKbps)\n if (stream.samples.length > NetworkQualityTracker.MAX_SAMPLES) stream.samples.shift()\n\n stream.peakBitrateKbps = Math.max(stream.peakBitrateKbps, bitrateKbps)\n\n if (packetLoss !== undefined) {\n stream.packetLossSamples.push(packetLoss)\n if (stream.packetLossSamples.length > NetworkQualityTracker.MAX_SAMPLES) stream.packetLossSamples.shift()\n }\n\n stream.lastUpdated = Date.now()\n }\n\n reportClientStats(deviceId: number, stats: Omit<ClientNetworkStats, 'lastUpdated'>): void {\n const device = this.getOrCreateDevice(deviceId)\n device.client = { ...stats, lastUpdated: Date.now() }\n }\n\n getDeviceStats(deviceId: number): DeviceNetworkStats | null {\n const device = this.devices.get(deviceId)\n if (!device) return null\n\n const streams: Record<string, StreamNetworkStats> = {}\n for (const [streamId, s] of device.streams) {\n const avg = (arr: number[]) => arr.length === 0 ? 0 : arr.reduce((a, b) => a + b, 0) / arr.length\n streams[streamId] = {\n nominalBitrateKbps: s.nominalBitrateKbps,\n observedBitrateKbps: Math.round(avg(s.samples)),\n peakBitrateKbps: s.peakBitrateKbps,\n packetLossPercent: Math.round(avg(s.packetLossSamples) * 10) / 10,\n lastUpdated: s.lastUpdated,\n }\n }\n\n return { deviceId, streams, client: device.client ?? undefined }\n }\n\n getAllStats(): readonly DeviceNetworkStats[] {\n const results: DeviceNetworkStats[] = []\n for (const deviceId of this.devices.keys()) {\n const stats = this.getDeviceStats(deviceId)\n if (stats) results.push(stats)\n }\n return results\n }\n\n private getOrCreateDevice(deviceId: number) {\n let device = this.devices.get(deviceId)\n if (!device) {\n device = { streams: new Map(), client: null }\n this.devices.set(deviceId, device)\n }\n return device\n }\n}\n","import * as vm from 'node:vm'\nimport * as util from 'node:util'\nimport type {\n IReplEngine,\n IReplContextProvider,\n ReplSessionContext,\n ReplResult,\n} from './interfaces.js'\n\nconst EXECUTION_TIMEOUT_MS = 5000\nconst COMPLETION_TIMEOUT_MS = 1000\n\nexport class ReplEngine implements IReplEngine {\n constructor(\n private readonly contextProvider: IReplContextProvider,\n ) {}\n\n async execute(code: string, context: ReplSessionContext): Promise<ReplResult> {\n const start = Date.now()\n const sandbox = await this.buildSandbox(context)\n\n try {\n const vmContext = vm.createContext(sandbox)\n const script = new vm.Script(code)\n let result: unknown = script.runInContext(vmContext, { timeout: EXECUTION_TIMEOUT_MS })\n\n // If result is a Promise, await it with timeout\n if (result && typeof result === 'object' && 'then' in result && typeof (result as { then: unknown }).then === 'function') {\n result = await Promise.race([\n result as Promise<unknown>,\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error('Async timeout (5s)')), EXECUTION_TIMEOUT_MS),\n ),\n ])\n }\n\n const duration = Date.now() - start\n\n if (result === undefined) {\n return { output: 'undefined', type: 'void', duration }\n }\n\n return {\n output: util.inspect(result, {\n depth: 4,\n colors: false,\n maxArrayLength: 50,\n maxStringLength: 1000,\n }),\n type: 'value',\n duration,\n }\n } catch (err: unknown) {\n // Errors thrown inside vm contexts may not be instanceof Error\n // because they use a different Error constructor from the sandbox\n const message =\n err instanceof Error\n ? err.message\n : typeof err === 'object' && err !== null && 'message' in err\n ? String((err as { message: unknown }).message)\n : String(err)\n return {\n output: message,\n type: 'error',\n duration: Date.now() - start,\n }\n }\n }\n\n async getCompletions(partial: string, context: ReplSessionContext): Promise<string[]> {\n const sandbox = await this.buildSandbox(context)\n const keys = Object.keys(sandbox)\n\n if (!partial) return keys\n\n const lastDot = partial.lastIndexOf('.')\n if (lastDot === -1) {\n return keys.filter(k => k.startsWith(partial))\n }\n\n // Object property completion: \"device.get\" -> look up device, return matching keys\n const objPath = partial.substring(0, lastDot)\n const propPrefix = partial.substring(lastDot + 1)\n\n try {\n const vmContext = vm.createContext(sandbox)\n const obj: unknown = vm.runInContext(objPath, vmContext, { timeout: COMPLETION_TIMEOUT_MS })\n if (obj && typeof obj === 'object') {\n const proto: unknown = Object.getPrototypeOf(obj)\n const objKeys = Object.getOwnPropertyNames(obj)\n .concat(Object.getOwnPropertyNames(proto ?? {}))\n .filter(k => k.startsWith(propPrefix))\n return [...new Set(objKeys)].map(k => `${objPath}.${k}`)\n }\n } catch {\n // Ignore errors during completion\n }\n\n return []\n }\n\n private async buildSandbox(context: ReplSessionContext): Promise<Record<string, unknown>> {\n const base: Record<string, unknown> = {\n console: {\n log: (...args: unknown[]) => util.inspect(args),\n warn: (...args: unknown[]) => util.inspect(args),\n },\n JSON,\n Math,\n Date,\n Array,\n Object,\n String,\n Number,\n Boolean,\n Map,\n Set,\n Promise,\n Buffer,\n // Blocked globals\n setTimeout: undefined,\n setInterval: undefined,\n fetch: undefined,\n require: undefined,\n process: undefined,\n // Merge user-provided variables\n ...context.variables,\n }\n\n switch (context.scope.type) {\n case 'system':\n return { ...base, ...(await this.contextProvider.getSystemSandbox()) }\n\n case 'device':\n return { ...base, ...(await this.contextProvider.getDeviceSandbox(context.scope.deviceId!)) }\n\n case 'provider':\n return { ...base, ...(await this.contextProvider.getProviderSandbox(context.scope.providerId!)) }\n\n case 'addon':\n return { ...base, ...(await this.contextProvider.getAddonSandbox(context.scope.addonId!)) }\n\n default:\n return base\n }\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport type { IScopedLogger, IEventBus } from '@camstack/types'\n\nexport type ElementState = 'stopped' | 'starting' | 'running' | 'stopping' | 'error' | 'disabled'\n\nexport interface ElementStatus {\n state: ElementState\n error?: string\n startedAt?: number\n stoppedAt?: number\n restartCount: number\n uptime: number\n}\n\nconst VALID_TRANSITIONS: Readonly<Record<ElementState, readonly ElementState[]>> = {\n stopped: ['starting', 'disabled'],\n starting: ['running', 'error', 'stopping'],\n running: ['stopping', 'error'],\n stopping: ['stopped', 'error'],\n error: ['starting', 'stopped', 'disabled'],\n disabled: ['stopped'],\n}\n\nexport class LifecycleStateMachine {\n private _state: ElementState = 'stopped'\n private _error?: string\n private _startedAt?: number\n private _stoppedAt?: number\n private _restartCount = 0\n private _hasStartedOnce = false\n\n constructor(\n private readonly elementId: string,\n private readonly elementType: 'provider' | 'device' | 'addon' | 'process',\n private readonly eventBus: IEventBus,\n private readonly logger: IScopedLogger,\n ) {}\n\n get state(): ElementState {\n return this._state\n }\n\n getStatus(): ElementStatus {\n return {\n state: this._state,\n error: this._error,\n startedAt: this._startedAt,\n stoppedAt: this._stoppedAt,\n restartCount: this._restartCount,\n uptime:\n this._state === 'running' && this._startedAt\n ? Date.now() - this._startedAt\n : 0,\n }\n }\n\n transition(to: ElementState, error?: string): boolean {\n const from = this._state\n\n if (!this.isValidTransition(from, to)) {\n this.logger.warn('Invalid state transition', { meta: { from, to } })\n return false\n }\n\n this._state = to\n this._error = error\n\n if (to === 'running') {\n if (this._hasStartedOnce) {\n this._restartCount++\n }\n this._hasStartedOnce = true\n this._startedAt = Date.now()\n this._stoppedAt = undefined\n }\n\n if (to === 'stopped' || to === 'error' || to === 'disabled') {\n this._stoppedAt = Date.now()\n }\n\n this.logger.info('State transition', { meta: { from, to, error } })\n\n this.eventBus.emit({\n id: randomUUID(),\n timestamp: new Date(),\n source: { type: this.elementType, id: this.elementId },\n category: `${this.elementType}.state.${to}`,\n data: { from, to, error, elementId: this.elementId },\n })\n\n return true\n }\n\n incrementRestartCount(): void {\n this._restartCount++\n }\n\n private isValidTransition(from: ElementState, to: ElementState): boolean {\n return VALID_TRANSITIONS[from]?.includes(to) ?? false\n }\n}\n","import type { FeatureManifest, FeatureFlag } from '@camstack/types'\n\nexport type { FeatureManifest, FeatureFlag }\n\nexport type FeatureConfigReader = {\n readonly features: FeatureManifest\n}\n\nexport class FeatureManager {\n constructor(private readonly configReader: FeatureConfigReader) {}\n\n isEnabled(flag: FeatureFlag): boolean {\n return this.configReader.features[flag]\n }\n\n getManifest(): FeatureManifest {\n return { ...this.configReader.features }\n }\n}\n","import type {\n EventSource,\n SystemEvent,\n EventFilter,\n IEventBus,\n} from '@camstack/types'\n\nexport type { EventSource, SystemEvent, EventFilter }\n\ninterface Subscriber {\n readonly filter: EventFilter\n readonly callback: (event: SystemEvent) => void\n}\n\nclass EventRingBuffer {\n private readonly buffer: Array<SystemEvent | undefined>\n private head = 0\n private count = 0\n\n constructor(private readonly capacity: number) {\n this.buffer = Array.from<SystemEvent | undefined>({ length: capacity })\n }\n\n push(event: SystemEvent): void {\n this.buffer[this.head] = event\n this.head = (this.head + 1) % this.capacity\n if (this.count < this.capacity) {\n this.count++\n }\n }\n\n getAll(): readonly SystemEvent[] {\n const result: SystemEvent[] = []\n for (let i = 0; i < this.count; i++) {\n const index = (this.head - 1 - i + this.capacity) % this.capacity\n result.push(this.buffer[index]!)\n }\n return result\n }\n\n query(filter?: EventFilter, limit?: number): readonly SystemEvent[] {\n let result = [...this.getAll()]\n\n if (filter) {\n result = result.filter((event) => matchesFilter(event, filter))\n }\n\n if (limit !== undefined && limit > 0) {\n return result.slice(0, limit)\n }\n\n return result\n }\n}\n\nfunction matchesCategory(eventCategory: string, filterCategory: string): boolean {\n if (filterCategory.endsWith('.*')) {\n const prefix = filterCategory.slice(0, -2)\n return eventCategory.startsWith(prefix + '.') || eventCategory === prefix\n }\n return eventCategory === filterCategory\n}\n\nfunction matchesFilter(event: SystemEvent, filter: EventFilter): boolean {\n if (filter.category) {\n const raw = filter.category\n const categories: string[] = Array.isArray(raw) ? raw.map(String) : [String(raw)]\n if (!categories.some((cat) => matchesCategory(event.category, cat))) {\n return false\n }\n }\n\n if (filter.source) {\n if (event.source.type !== filter.source.type || event.source.id !== filter.source.id) {\n return false\n }\n }\n\n if (filter.agentId) {\n const eventNodeId = event.source.nodeId\n // Prefix match: 'hub' matches 'hub', 'hub/pipeline', etc.\n if (!eventNodeId || !eventNodeId.startsWith(filter.agentId)) {\n return false\n }\n }\n\n if (filter.addonId) {\n const eventAddonId = event.source.addonId\n ?? (event.source.type === 'addon' ? String(event.source.id) : undefined)\n if (eventAddonId !== filter.addonId) {\n return false\n }\n }\n\n if (filter.deviceId !== undefined) {\n const eventDeviceId = event.source.deviceId\n ?? (event.source.type === 'device' ? Number(event.source.id) : undefined)\n if (eventDeviceId !== filter.deviceId) {\n return false\n }\n }\n\n if (filter.since && event.timestamp < filter.since) {\n return false\n }\n\n return true\n}\n\nexport class SystemEventBus implements IEventBus {\n private readonly ringBuffer: EventRingBuffer\n private readonly subscribers: Subscriber[] = []\n\n constructor(bufferSize: number = 10000) {\n this.ringBuffer = new EventRingBuffer(bufferSize)\n }\n\n emit(event: SystemEvent): void {\n this.ringBuffer.push(event)\n\n for (const subscriber of this.subscribers) {\n if (matchesFilter(event, subscriber.filter)) {\n queueMicrotask(() => {\n try {\n subscriber.callback(event)\n } catch (err) {\n console.error(`[EventBus] Subscriber error for ${event.category}:`, err)\n }\n })\n }\n }\n }\n\n /**\n * Subscribe to events matching a filter.\n * When called with a typed category filter, the handler receives typed event data.\n */\n subscribe(filter: EventFilter, handler: (event: SystemEvent) => void): () => void {\n const subscriber: Subscriber = { filter, callback: handler }\n this.subscribers.push(subscriber)\n\n return () => {\n const index = this.subscribers.indexOf(subscriber)\n if (index !== -1) {\n this.subscribers.splice(index, 1)\n }\n }\n }\n\n getRecent(filter?: EventFilter, limit?: number): readonly SystemEvent[] {\n return this.ringBuffer.query(filter, limit)\n }\n}\n","import type { LogLevel, LogEntry, LogFilter, LogTags } from '@camstack/types'\n\nexport type { LogLevel, LogEntry, LogFilter }\n\n/**\n * Per-tag filter matcher with semantic-aware comparisons:\n *\n * `addonId` — matches the entry's bare addon id (strips any `@<workerId>`\n * qualifier added by the cap-router for remote providers).\n * So a UI filter for `audio-classifier` matches both the\n * addon's own log lines and bridge management lines whose\n * addonId is logged as `audio-classifier@dev-agent-0/audio-classifier`.\n *\n * `agentId` — matches when ANY of these hold:\n * * the entry was emitted by that agent (`agentId` exact)\n * * the entry's `nodeId` IS that agent (single-node case)\n * * the entry's `nodeId` starts with `<agent>/` (worker\n * inside that agent — e.g. `dev-agent-0/audio-classifier`)\n * Captures all the log emission paths for an addon hosted\n * on the agent regardless of who actually emitted the line.\n *\n * any other key — exact match (legacy semantics).\n *\n * Returns `true` when ALL filter keys match (AND), `false` otherwise.\n * `undefined` filter values are skipped.\n */\nexport function matchesLogTags(\n entryTags: LogTags | undefined,\n filterTags: Partial<LogTags>,\n): boolean {\n if (!entryTags) return false\n for (const [key, value] of Object.entries(filterTags)) {\n if (value === undefined) continue\n const entryValue = entryTags[key as keyof LogTags]\n if (key === 'addonId') {\n // Normalize away both suffix conventions so a filter on the\n // addon's manifest id matches every log line emitted by it:\n // - `<addonId>@<version>` — bridge-injected when relaying\n // logs from forked workers (kernel/capability-registry).\n // - `<addonId>::<sub-service>` — sub-component scope used by\n // addons that mount native-device-ops shims (e.g.\n // `audio-codec-nodeav::native-device-ops`). Operators\n // filtering by the addon's id expect to see those rows.\n let bare = entryValue\n if (typeof bare === 'string') {\n bare = bare.split('@')[0]\n if (typeof bare === 'string') {\n const colonIdx = bare.indexOf('::')\n if (colonIdx >= 0) bare = bare.slice(0, colonIdx)\n }\n }\n if (bare !== value) return false\n } else if (key === 'agentId') {\n const nodeId = entryTags['nodeId']\n const matchEmitter = entryValue === value\n const matchExactNode = nodeId === value\n const matchWorker = typeof nodeId === 'string' && nodeId.startsWith(`${value}/`)\n if (!matchEmitter && !matchExactNode && !matchWorker) return false\n } else {\n if (entryValue !== value) return false\n }\n }\n return true\n}\n\nexport class LogRingBuffer {\n private readonly buffer: Array<LogEntry | undefined>\n private head = 0\n private count = 0\n\n constructor(private readonly capacity: number = 10000) {\n this.buffer = Array.from<LogEntry | undefined>({ length: capacity })\n }\n\n push(entry: LogEntry): void {\n this.buffer[this.head] = entry\n this.head = (this.head + 1) % this.capacity\n if (this.count < this.capacity) {\n this.count++\n }\n }\n\n getAll(): LogEntry[] {\n const result: LogEntry[] = []\n\n for (let i = 0; i < this.count; i++) {\n const index = (this.head - 1 - i + this.capacity) % this.capacity\n result.push(this.buffer[index]!)\n }\n\n return result\n }\n\n query(filter: LogFilter): LogEntry[] {\n const all = this.getAll()\n let result = all\n\n if (filter.level) {\n result = result.filter((entry) => entry.level === filter.level)\n }\n\n if (filter.since) {\n result = result.filter((entry) => entry.timestamp >= filter.since!)\n }\n\n if (filter.until) {\n result = result.filter((entry) => entry.timestamp <= filter.until!)\n }\n\n if (filter.tags) {\n const filterTags = filter.tags\n result = result.filter((entry) => matchesLogTags(entry.tags, filterTags))\n }\n\n if (filter.limit !== undefined && filter.limit > 0) {\n result = result.slice(0, filter.limit)\n }\n\n return result\n }\n\n /**\n * Drop entries that match `filter`. Returns the number of entries\n * removed. Triggered by the UI's \"Clear logs\" button so the operator\n * can wipe the historical buffer for a specific scope (per-device,\n * per-addon, per-agent) — without it, closing and reopening the\n * panel re-populates the cleared rows from the server's ring buffer.\n *\n * Filter semantics mirror `query` (same level / since / until / tags\n * handling) — whatever you'd see listed by `query(filter)` is what\n * gets removed.\n */\n clear(filter: LogFilter = {}): number {\n if (this.count === 0) return 0\n const survivors: LogEntry[] = []\n for (let i = 0; i < this.count; i++) {\n // Same iteration order as getAll (newest first), but we'll\n // re-insert oldest-first to preserve push semantics.\n const index = (this.head - 1 - i + this.capacity) % this.capacity\n const entry = this.buffer[index]!\n let matches = true\n if (filter.level !== undefined && entry.level !== filter.level) matches = false\n if (matches && filter.since !== undefined && entry.timestamp < filter.since) matches = false\n if (matches && filter.until !== undefined && entry.timestamp > filter.until) matches = false\n if (matches && filter.tags !== undefined && !matchesLogTags(entry.tags, filter.tags)) matches = false\n if (!matches) survivors.push(entry)\n }\n const removed = this.count - survivors.length\n if (removed === 0) return 0\n // Re-seed the buffer in original push order (oldest first → newest last).\n this.buffer.fill(undefined)\n this.head = 0\n this.count = 0\n for (let i = survivors.length - 1; i >= 0; i--) {\n this.push(survivors[i]!)\n }\n return removed\n }\n}\n","import type { IScopedLogger, LogExtras, LogTags } from '@camstack/types'\nimport type { LogEntry, LogLevel } from './log-ring-buffer.js'\n\nexport type { IScopedLogger }\n\nexport class ScopedLogger implements IScopedLogger {\n constructor(\n private readonly scope: string | undefined,\n private readonly writeFn: (entry: LogEntry) => void,\n private readonly tags?: LogTags,\n ) {}\n\n debug(message: string, extras?: LogExtras): void {\n this.write('debug', message, extras)\n }\n\n info(message: string, extras?: LogExtras): void {\n this.write('info', message, extras)\n }\n\n warn(message: string, extras?: LogExtras): void {\n this.write('warn', message, extras)\n }\n\n error(message: string, extras?: LogExtras): void {\n this.write('error', message, extras)\n }\n\n child(childScope: string): IScopedLogger {\n return new ScopedLogger(childScope, this.writeFn, this.tags)\n }\n\n withTags(tags: LogTags): IScopedLogger {\n const merged = this.tags ? { ...this.tags, ...tags } : tags\n return new ScopedLogger(this.scope, this.writeFn, merged)\n }\n\n private write(level: LogLevel, message: string, extras?: LogExtras): void {\n const mergedTags = this.mergeTags(extras?.tags)\n const entry: LogEntry = {\n timestamp: new Date(),\n level,\n message,\n ...(this.scope !== undefined ? { scope: this.scope } : {}),\n ...(extras?.meta !== undefined ? { meta: extras.meta } : {}),\n ...(mergedTags ? { tags: mergedTags } : {}),\n }\n this.writeFn(entry)\n }\n\n private mergeTags(extraTags?: LogTags): LogTags | undefined {\n if (!this.tags && !extraTags) return undefined\n if (!this.tags) return extraTags\n if (!extraTags) return this.tags\n return { ...this.tags, ...extraTags }\n }\n}\n","import { LogRingBuffer, matchesLogTags, type LogEntry, type LogFilter } from './log-ring-buffer.js'\nimport { ScopedLogger, type IScopedLogger } from './scoped-logger.js'\n\nexport interface ILogDestination {\n initialize(): Promise<void>\n shutdown(): Promise<void>\n write(entry: LogEntry): void\n query?(filter: LogFilter): Promise<readonly LogEntry[]>\n}\n\nexport class LogManager {\n private readonly ringBuffer: LogRingBuffer\n private readonly destinations: ILogDestination[] = []\n private readonly subscribers = new Map<string, { filter: Partial<LogFilter>; callback: (entry: LogEntry) => void }>()\n private deviceNameLookup: ((deviceId: number) => string | null) | null = null\n\n constructor(bufferSize: number = 10000) {\n this.ringBuffer = new LogRingBuffer(bufferSize)\n }\n\n /**\n * Register a callback that resolves `deviceId → deviceName`. Called\n * for every emitted entry that carries `tags.deviceId` but no\n * explicit `tags.deviceName` — the LogManager injects the resolved\n * name directly into the entry's tags BEFORE ring-buffer / destination\n * write, so every destination (local console, file, remote forwarder,\n * addon-bundled copies of core) sees the enriched shape regardless of\n * which module instance the destination was built from.\n */\n setDeviceNameLookup(lookup: ((deviceId: number) => string | null) | null): void {\n this.deviceNameLookup = lookup\n }\n\n createLogger(scope?: string): IScopedLogger {\n return new ScopedLogger(scope, (entry: LogEntry) => {\n const enriched = this.enrichDeviceName(entry)\n this.ringBuffer.push(enriched)\n for (const dest of this.destinations) {\n dest.write(enriched)\n }\n // Notify real-time subscribers\n for (const [, sub] of this.subscribers) {\n if (this.matchesFilter(enriched, sub.filter)) {\n try { sub.callback(enriched) } catch { /* subscriber error — ignore */ }\n }\n }\n })\n }\n\n private enrichDeviceName(entry: LogEntry): LogEntry {\n if (!this.deviceNameLookup) return entry\n const tags = entry.tags\n if (!tags) return entry\n const deviceId = (tags as { deviceId?: unknown }).deviceId\n if (typeof deviceId !== 'number' || !Number.isFinite(deviceId)) return entry\n if (typeof (tags as { deviceName?: unknown }).deviceName === 'string') return entry\n const name = this.deviceNameLookup(deviceId)\n if (!name) return entry\n return { ...entry, tags: { ...tags, deviceName: name } }\n }\n\n /** Subscribe to live logs matching a filter. Returns an unsubscribe function. */\n subscribe(filter: Partial<LogFilter>, callback: (entry: LogEntry) => void): () => void {\n const id = Math.random().toString(36).slice(2)\n this.subscribers.set(id, { filter, callback })\n return () => { this.subscribers.delete(id) }\n }\n\n private matchesFilter(entry: LogEntry, filter: Partial<LogFilter>): boolean {\n if (filter.level) {\n const levels: string[] = ['debug', 'info', 'warn', 'error']\n const minIdx = levels.indexOf(filter.level)\n const entryIdx = levels.indexOf(entry.level)\n if (entryIdx < minIdx) return false\n }\n if (filter.tags) {\n if (!matchesLogTags(entry.tags, filter.tags)) return false\n }\n return true\n }\n\n /**\n * Register a log destination.\n *\n * @param opts.replay If true (default), replay every entry currently in\n * the ring buffer to the new destination before live\n * traffic starts. Lets a destination added mid-boot\n * still receive boot-time log entries.\n */\n addDestination(dest: ILogDestination, opts: { replay?: boolean } = {}): void {\n const replay = opts.replay ?? true\n this.destinations.push(dest)\n if (replay) {\n for (const entry of this.ringBuffer.query({})) {\n try { dest.write(entry) } catch { /* destination replay error — ignore */ }\n }\n }\n }\n\n removeDestination(dest: ILogDestination): void {\n const index = this.destinations.indexOf(dest)\n if (index !== -1) {\n this.destinations.splice(index, 1)\n }\n }\n\n query(filter: LogFilter): LogEntry[] {\n return this.ringBuffer.query(filter)\n }\n\n /**\n * Drop ring-buffer entries matching `filter`. Returns the count\n * removed. Backs the UI's \"Clear logs\" admin action so an operator\n * can wipe the historical window for a scope (per-device, per-addon,\n * agent-level) without restarting the server. External destinations\n * (file, forwarder) are NOT touched — only the in-memory ring.\n */\n clear(filter: LogFilter = {}): number {\n return this.ringBuffer.clear(filter)\n }\n}\n","import { existsSync, accessSync, constants } from 'node:fs'\nimport { join, resolve, dirname, isAbsolute } from 'node:path'\n\nexport interface IStorageBackend {\n /** Backend type identifier */\n readonly type: string\n /** Base path of this backend */\n readonly basePath: string\n /** Resolve a subpath to an absolute path */\n resolve(subpath: string): string\n /**\n * Check whether the backend is usable: either the base directory\n * already exists and is writable, OR we can create it on first\n * write (i.e. the nearest existing ancestor is writable).\n */\n isAvailable(): boolean\n /** No-op for lazy backends. Kept for API compatibility. */\n initialize(): Promise<void>\n}\n\n/**\n * Filesystem storage backend — lazy by design.\n *\n * `initialize()` does NOT create the base directory eagerly. Instead,\n * consumers that write via `FilesystemStorageProvider` (and other write\n * helpers in storage-manager.ts) run `fs.mkdir(dirname(filePath), { recursive: true })`\n * right before every `writeFile`, so the directory tree appears on demand.\n *\n * The previous behaviour eagerly mkdir'd every location declared in\n * `StorageLocationManager.initializeDefaults()` — six directories (`db`,\n * `media`, `recordings`, `models`, `cache`, `logs`) got created at boot\n * even if the installation had no cameras, no recording addon, no\n * analytics addon, etc. That meant every fresh install looked like it\n * was producing data when it had nothing to write. Laziness fixes that:\n * a directory only exists once an addon decides to put a file there.\n */\nexport class FsStorageBackend implements IStorageBackend {\n readonly type = 'local'\n readonly basePath: string\n\n constructor(basePath: string) {\n this.basePath = resolve(basePath)\n }\n\n resolve(subpath: string): string {\n if (isAbsolute(subpath)) return subpath\n return join(this.basePath, subpath)\n }\n\n isAvailable(): boolean {\n // If the base dir already exists, check write permission directly.\n // Otherwise walk up to the first existing ancestor (guaranteed to\n // terminate at the filesystem root) and check it is writable — we\n // can then mkdir the missing segments on first write.\n try {\n if (existsSync(this.basePath)) {\n accessSync(this.basePath, constants.W_OK)\n return true\n }\n let parent = dirname(this.basePath)\n while (parent && parent !== dirname(parent)) {\n if (existsSync(parent)) {\n accessSync(parent, constants.W_OK)\n return true\n }\n parent = dirname(parent)\n }\n return false\n } catch {\n return false\n }\n }\n\n async initialize(): Promise<void> {\n // No-op: base directory is created lazily on first write. See the\n // class docstring for the rationale.\n }\n}\n","import { join, isAbsolute } from 'node:path'\nimport { FsStorageBackend, type IStorageBackend } from './fs-storage-backend.js'\n\nexport type StorageLocationName = 'data' | 'media' | 'recordings' | 'models' | 'cache' | 'logs'\n\nexport class StorageLocationManager {\n private readonly backends: Map<StorageLocationName, IStorageBackend> = new Map()\n private readonly dataPath: string\n\n constructor(dataPath: string) {\n this.dataPath = dataPath\n }\n\n /** Initialize all locations with default paths */\n async initializeDefaults(): Promise<void> {\n const defaults: Record<StorageLocationName, string> = {\n data: join(this.dataPath, 'db'),\n media: join(this.dataPath, 'media'),\n recordings: join(this.dataPath, 'recordings'),\n models: join(this.dataPath, 'models'),\n cache: '/tmp/camstack-cache',\n logs: join(this.dataPath, 'logs'),\n }\n\n for (const [name, path] of Object.entries(defaults)) {\n const backend = new FsStorageBackend(path)\n await backend.initialize()\n this.backends.set(name as StorageLocationName, backend)\n }\n }\n\n /** Override a specific location's backend path */\n async setLocationPath(name: StorageLocationName, basePath: string): Promise<void> {\n const resolved = isAbsolute(basePath) ? basePath : join(this.dataPath, basePath)\n const backend = new FsStorageBackend(resolved)\n await backend.initialize()\n this.backends.set(name, backend)\n }\n\n /** Get the backend for a location */\n getBackend(name: StorageLocationName): IStorageBackend {\n const backend = this.backends.get(name)\n if (!backend) throw new Error(`Storage location \"${name}\" not initialized`)\n return backend\n }\n\n /** Resolve a path within a location */\n resolve(location: StorageLocationName, subpath: string): string {\n return this.getBackend(location).resolve(subpath)\n }\n\n /** Check if all locations are available */\n getStatus(): Array<{ name: StorageLocationName; available: boolean; path: string }> {\n return Array.from(this.backends.entries()).map(([name, backend]) => ({\n name,\n available: backend.isAvailable(),\n path: backend.basePath,\n }))\n }\n\n /** All location names */\n getLocationNames(): StorageLocationName[] {\n return Array.from(this.backends.keys())\n }\n}\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport { StorageLocationManager, type StorageLocationName } from './storage-location-manager.js'\nimport type {\n IStorageProvider as INewStorageProvider,\n ISettingsBackend,\n} from '@camstack/types'\n\n// Legacy interfaces — still used by consumers during migration\nexport interface IStorageProvider {\n initialize(): Promise<void>\n shutdown(): Promise<void>\n getLocation(name: StorageLocationName): IStorageLocation\n export?(locationName: StorageLocationName): Promise<Buffer>\n import?(locationName: StorageLocationName, data: Buffer): Promise<void>\n}\n\nexport interface QueryFilter {\n where?: Record<string, unknown>\n whereIn?: Record<string, unknown[]>\n whereBetween?: Record<string, [unknown, unknown]>\n orderBy?: { field: string; direction: 'asc' | 'desc' }\n limit?: number\n offset?: number\n}\n\nexport interface StorageRecord {\n collection: string\n id: string\n data: Record<string, unknown>\n}\n\nexport interface IStructuredStorage {\n query(collection: string, filter?: QueryFilter): Promise<readonly StorageRecord[]>\n insert(record: StorageRecord): Promise<StorageRecord>\n update(collection: string, id: string, data: Record<string, unknown>): Promise<StorageRecord>\n delete(collection: string, id: string): Promise<void>\n count(collection: string, filter?: QueryFilter): Promise<number>\n}\n\nexport interface IFileStorage {\n readFile(path: string): Promise<Buffer>\n writeFile(path: string, data: Buffer): Promise<void>\n deleteFile(path: string): Promise<void>\n listFiles(prefix?: string): Promise<readonly string[]>\n getFileUrl(path: string): Promise<string>\n exists(path: string): Promise<boolean>\n}\n\nexport interface IStorageLocation {\n structured?: IStructuredStorage\n files?: IFileStorage\n}\n\n/**\n * StorageManager — bridge between legacy code (getLocation/getLocationPath)\n * and the new capability-based storage system.\n *\n * Legacy consumers call getLocation('addon', namespace) to get structured + file storage.\n * This manager builds the response from:\n * - SettingsBackend (for structured queries) — provided by sqlite-settings addon\n * - LocationManager (for file paths) — set during Phase 2 boot\n */\nexport class StorageManager {\n private legacyProvider: IStorageProvider | null = null\n private locationManager: StorageLocationManager | null = null\n private newStorageProvider: INewStorageProvider | null = null\n private settingsBackend: ISettingsBackend | null = null\n\n /** @deprecated Set by legacy capability consumer — use setNewStorageProvider instead */\n setProvider(provider: IStorageProvider | INewStorageProvider): void {\n // Check if it's the new provider (has 'supportedLocations') or legacy (has 'getLocation')\n if ('getLocation' in provider) {\n this.legacyProvider = provider\n } else {\n this.newStorageProvider = provider\n }\n }\n\n setNewStorageProvider(provider: INewStorageProvider): void {\n this.newStorageProvider = provider\n }\n\n setSettingsBackend(backend: ISettingsBackend): void {\n this.settingsBackend = backend\n }\n\n getSettingsBackend(): ISettingsBackend {\n if (!this.settingsBackend) {\n throw new Error('SettingsBackend not initialized — storage addon not yet loaded')\n }\n return this.settingsBackend\n }\n\n getProvider(): IStorageProvider {\n if (this.legacyProvider) return this.legacyProvider\n if (!this.newStorageProvider && !this.settingsBackend && !this.locationManager) {\n throw new Error('No storage provider configured')\n }\n // Return a shim that wraps new providers\n return this.createLegacyShim()\n }\n\n setLocationManager(manager: StorageLocationManager): void {\n this.locationManager = manager\n }\n\n getLocationManager(): StorageLocationManager {\n if (!this.locationManager) {\n throw new Error('StorageLocationManager not initialized')\n }\n return this.locationManager\n }\n\n async initializeLocations(dataPath: string): Promise<void> {\n // Was previously a dynamic `await import(...)` for code-split, but the\n // module is also re-exported statically by core/src/index.ts so the\n // dynamic split never materialized (Rolldown reported it as\n // INEFFECTIVE_DYNAMIC_IMPORT). Switched to a top-of-file named\n // import — same shape, no chunk-graph confusion.\n const manager = new StorageLocationManager(dataPath)\n await manager.initializeDefaults()\n this.locationManager = manager\n }\n\n getLocationPath(name: StorageLocationName): string {\n return this.getLocationManager().getBackend(name).basePath\n }\n\n /**\n * Get a storage location with optional namespace scoping.\n * Builds IStorageLocation from settingsBackend (structured) + locationManager (files).\n */\n getLocation(name: StorageLocationName | string, namespace?: string): IStorageLocation {\n if (!this.legacyProvider && !this.newStorageProvider && !this.settingsBackend && !this.locationManager) {\n throw new Error('No storage provider configured')\n }\n // Try legacy provider first\n if (this.legacyProvider) {\n try {\n // Legacy alias → new location name mapping. `name` may be any string\n // coming from addon code; the final narrowing cast is the single\n // boundary between the public API (string) and the internal union.\n const LEGACY_MAP = { config: 'data', events: 'data', addon: 'data' } as const satisfies Record<string, StorageLocationName>\n const mapped = name in LEGACY_MAP ? LEGACY_MAP[name as keyof typeof LEGACY_MAP] : (name as StorageLocationName)\n const mappedName: StorageLocationName = mapped\n const location = this.legacyProvider.getLocation(mappedName)\n return namespace ? this.createNamespacedLocation(location, namespace) : location\n } catch {\n // Fall through to new approach\n }\n }\n\n // Build from new providers\n const location: IStorageLocation = {}\n\n // Structured storage from settingsBackend\n if (this.settingsBackend) {\n const backend = this.settingsBackend\n location.structured = {\n async query(collection: string, filter?: QueryFilter) {\n const results = await backend.query({ collection, filter })\n return results.map(r => ({ collection, id: r.id, data: r.data }))\n },\n async insert(record: StorageRecord) {\n const id = record.id || (await import('node:crypto')).randomUUID()\n await backend.insert({ collection: record.collection, record: { id, data: record.data } })\n return { ...record, id }\n },\n async update(collection: string, id: string, data: Record<string, unknown>) {\n await backend.update({ collection, id, data })\n return { collection, id, data }\n },\n async delete(collection: string, id: string) {\n await backend.delete({ collection, key: id })\n },\n async count(collection: string, filter?: QueryFilter) {\n return backend.count({ collection, filter })\n },\n }\n }\n\n // File storage from locationManager\n if (this.locationManager) {\n const LEGACY_MAP = { config: 'data', events: 'data', addon: 'data' } as const satisfies Record<string, StorageLocationName>\n const mappedName: StorageLocationName = name in LEGACY_MAP\n ? LEGACY_MAP[name as keyof typeof LEGACY_MAP]\n : (name as StorageLocationName)\n try {\n const basePath = this.locationManager.getBackend(mappedName).basePath\n location.files = {\n async readFile(p: string) { return fs.promises.readFile(path.join(basePath, p)) },\n async writeFile(p: string, data: Buffer) {\n const full = path.join(basePath, p)\n await fs.promises.mkdir(path.dirname(full), { recursive: true })\n await fs.promises.writeFile(full, data)\n },\n async deleteFile(p: string) { await fs.promises.rm(path.join(basePath, p), { force: true }) },\n async listFiles(prefix?: string) {\n const dir = prefix ? path.join(basePath, prefix) : basePath\n try { return (await fs.promises.readdir(dir)).map(f => prefix ? `${prefix}/${f}` : f) } catch { return [] }\n },\n async getFileUrl(p: string) { return path.join(basePath, p) },\n async exists(p: string) { try { await fs.promises.access(path.join(basePath, p)); return true } catch { return false } },\n }\n } catch {\n // Location not available\n }\n }\n\n return namespace ? this.createNamespacedLocation(location, namespace) : location\n }\n\n private createLegacyShim(): IStorageProvider {\n const self = this\n return {\n async initialize() {},\n async shutdown() {},\n getLocation(name: StorageLocationName) { return self.getLocation(name) },\n }\n }\n\n private createNamespacedLocation(location: IStorageLocation, namespace: string): IStorageLocation {\n const prefix = namespace.endsWith('/') ? namespace : `${namespace}/`\n\n return {\n structured: location.structured ? {\n async query(collection: string, filter?: QueryFilter) {\n return location.structured!.query(`${prefix}${collection}`, filter)\n },\n async insert(record: StorageRecord) {\n return location.structured!.insert({ ...record, collection: `${prefix}${record.collection}` })\n },\n async update(collection: string, id: string, data: Record<string, unknown>) {\n return location.structured!.update(`${prefix}${collection}`, id, data)\n },\n async delete(collection: string, id: string) {\n return location.structured!.delete(`${prefix}${collection}`, id)\n },\n async count(collection: string, filter?: QueryFilter) {\n return location.structured!.count(`${prefix}${collection}`, filter)\n },\n } : undefined,\n\n files: location.files ? {\n async readFile(p: string) { return location.files!.readFile(`${prefix}${p}`) },\n async writeFile(p: string, data: Buffer) { return location.files!.writeFile(`${prefix}${p}`, data) },\n async deleteFile(p: string) { return location.files!.deleteFile(`${prefix}${p}`) },\n async listFiles(filePrefix?: string) { return location.files!.listFiles(`${prefix}${filePrefix ?? ''}`) },\n async getFileUrl(p: string) { return location.files!.getFileUrl(`${prefix}${p}`) },\n async exists(p: string) { return location.files!.exists(`${prefix}${p}`) },\n } : undefined,\n }\n }\n}\n","import type { INotificationOutput, Notification, ICapabilityRegistry } from '@camstack/types'\nimport type { IScopedLogger } from '../logging/scoped-logger.js'\nimport { errMsg } from '@camstack/types'\n\n/**\n * Central notification service that routes notifications to configured outputs.\n * Framework-agnostic — dependencies injected via constructor.\n *\n * Outputs are resolved from the ICapabilityRegistry's 'notification-output'\n * collection on each call (proxy pattern). Falls back to a local map\n * when no registry is provided (backward compat).\n */\nexport class NotificationService {\n private readonly localOutputs = new Map<string, INotificationOutput>()\n private readonly routing = new Map<string, string[]>()\n private readonly rateLimits = new Map<string, number>()\n private readonly lastSent = new Map<string, number>()\n private registry: ICapabilityRegistry | null = null\n\n constructor(private readonly logger: IScopedLogger) {}\n\n /** Set the registry for live output lookup. Called once during boot. */\n setRegistry(registry: ICapabilityRegistry): void {\n this.registry = registry\n }\n\n /** Resolve all outputs — prefers registry, falls back to local map */\n private get outputs(): ReadonlyMap<string, INotificationOutput> {\n if (this.registry) {\n const collection = this.registry.getCollection<INotificationOutput>('notification-output')\n const map = new Map<string, INotificationOutput>()\n for (const output of collection) {\n map.set(output.id, output)\n }\n return map\n }\n return this.localOutputs\n }\n\n /** Register an output in the local fallback map (used when no registry is set). */\n registerLocalOutput(output: INotificationOutput): void {\n this.localOutputs.set(output.id, output)\n this.logger.info('Notification output added', { meta: { name: output.name, outputId: output.id } })\n }\n\n /** Remove an output from the local fallback map. */\n unregisterLocalOutput(id: string): void {\n this.localOutputs.delete(id)\n this.logger.info('Notification output removed', { meta: { outputId: id } })\n }\n\n setRouting(category: string, outputIds: string[]): void {\n this.routing.set(category, [...outputIds])\n }\n\n setRateLimit(category: string, minIntervalMs: number): void {\n this.rateLimits.set(category, minIntervalMs)\n }\n\n async notify(notification: Notification): Promise<void> {\n const { category, deviceId } = notification\n\n // Rate limit check\n const rateLimitKey = deviceId ? `${category}:${deviceId}` : category\n const minInterval = this.rateLimits.get(category) ?? 0\n if (minInterval > 0) {\n const last = this.lastSent.get(rateLimitKey) ?? 0\n if (notification.timestamp - last < minInterval) {\n this.logger.debug('Rate limited', { meta: { rateLimitKey } })\n return\n }\n }\n\n // Determine target outputs\n const targetIds = this.routing.get(category) ?? this.routing.get('*') ?? []\n if (targetIds.length === 0) {\n this.logger.debug('No routing configured for category', { meta: { category } })\n return\n }\n\n const currentOutputs = this.outputs\n\n // Update last-sent timestamp\n this.lastSent.set(rateLimitKey, notification.timestamp)\n\n // Send to all targets in parallel with error isolation\n await Promise.allSettled(\n targetIds\n .map((id) => currentOutputs.get(id))\n .filter((output): output is INotificationOutput => output !== undefined)\n .map(async (output) => {\n try {\n await output.send(notification)\n } catch (err) {\n const msg = errMsg(err)\n this.logger.error('Notification output failed', { meta: { outputId: output.id, error: msg } })\n }\n }),\n )\n\n return undefined\n }\n\n getOutputs(): ReadonlyArray<{ id: string; name: string; icon: string }> {\n return Array.from(this.outputs.values()).map(({ id, name, icon }) => ({ id, name, icon }))\n }\n\n getRouting(): ReadonlyMap<string, string[]> {\n return this.routing\n }\n\n getOutput(id: string): INotificationOutput | undefined {\n return this.outputs.get(id)\n }\n}\n","import type { Toast } from '@camstack/types'\n\nexport type Unsubscribe = () => void\n\ninterface ListenerEntry {\n readonly userId: string\n readonly callback: (toast: Toast) => void\n}\n\n/**\n * Service for broadcasting toast notifications to connected UI clients.\n * Framework-agnostic — integrates with tRPC subscriptions via subscribe().\n */\nexport class ToastService {\n private readonly listeners = new Map<string, ListenerEntry>()\n\n /**\n * Subscribe to toast events for a specific user.\n * Returns an unsubscribe function.\n */\n subscribe(connectionId: string, userId: string, callback: (toast: Toast) => void): Unsubscribe {\n this.listeners.set(connectionId, { userId, callback })\n return () => {\n this.listeners.delete(connectionId)\n }\n }\n\n /**\n * Broadcast a toast to all connected clients.\n */\n broadcast(toast: Toast): void {\n for (const entry of this.listeners.values()) {\n entry.callback(toast)\n }\n }\n\n /**\n * Send a toast to a specific user's connections only.\n */\n sendToUser(userId: string, toast: Toast): void {\n for (const entry of this.listeners.values()) {\n if (entry.userId === userId) {\n entry.callback(toast)\n }\n }\n }\n}\n","import type { IAddonHttpRoute, IAddonRouteProvider } from '@camstack/types'\n\ninterface RouteMatch {\n readonly route: IAddonHttpRoute\n readonly addonId: string\n readonly params: Record<string, string>\n}\n\ninterface RegisteredRoute {\n readonly addonId: string\n readonly route: IAddonHttpRoute\n /** Full path including /addon/{addonId}/ prefix */\n readonly fullPath: string\n}\n\n/**\n * Registry for dynamic HTTP routes registered by addons.\n * Framework-agnostic — the server HTTP layer queries this registry to dispatch requests.\n */\nexport class AddonRouteRegistry {\n private readonly routes = new Map<string, RegisteredRoute[]>()\n\n /**\n * Register all routes from an addon's route provider.\n */\n registerRoutes(addonId: string, provider: IAddonRouteProvider): void {\n const addonRoutes = provider.getRoutes()\n const registered: RegisteredRoute[] = addonRoutes.map((route) => {\n const normalizedPath = route.path.startsWith('/') ? route.path : `/${route.path}`\n return {\n addonId,\n route,\n fullPath: `/addon/${addonId}${normalizedPath}`,\n }\n })\n this.routes.set(addonId, registered)\n }\n\n /**\n * Unregister all routes for an addon.\n */\n unregisterRoutes(addonId: string): void {\n this.routes.delete(addonId)\n }\n\n /**\n * Match an incoming request method + path to a registered route.\n * Supports simple path parameters (e.g., /items/:id).\n */\n matchRoute(method: string, path: string): RouteMatch | null {\n const normalizedMethod = method.toUpperCase()\n\n for (const registeredRoutes of this.routes.values()) {\n for (const entry of registeredRoutes) {\n if (entry.route.method !== normalizedMethod) continue\n\n const params = matchPath(entry.fullPath, path)\n if (params !== null) {\n return {\n route: entry.route,\n addonId: entry.addonId,\n params,\n }\n }\n }\n }\n\n return null\n }\n\n /**\n * List all registered routes across all addons.\n */\n listRoutes(): ReadonlyArray<{ addonId: string; method: string; path: string; access: string; description?: string }> {\n const result: Array<{ addonId: string; method: string; path: string; access: string; description?: string }> = []\n for (const registeredRoutes of this.routes.values()) {\n for (const entry of registeredRoutes) {\n result.push({\n addonId: entry.addonId,\n method: entry.route.method,\n path: entry.fullPath,\n access: entry.route.access,\n description: entry.route.description,\n })\n }\n }\n return result\n }\n}\n\n/**\n * Match a route pattern against an actual path.\n * Supports :param segments (e.g., /addon/:addonId/items/:id).\n * Returns extracted params or null if no match.\n */\nfunction matchPath(pattern: string, path: string): Record<string, string> | null {\n const patternParts = pattern.split('/').filter(Boolean)\n const pathParts = path.split('/').filter(Boolean)\n\n if (patternParts.length !== pathParts.length) {\n return null\n }\n\n const params: Record<string, string> = {}\n\n for (let i = 0; i < patternParts.length; i++) {\n const patternPart = patternParts[i]!\n const pathPart = pathParts[i]!\n\n if (patternPart.startsWith(':')) {\n params[patternPart.slice(1)] = pathPart\n } else if (patternPart !== pathPart) {\n return null\n }\n }\n\n return params\n}\n","import { X509Certificate } from 'node:crypto'\nimport { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport { existsSync, mkdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport * as os from 'node:os'\n\nconst execFileAsync = promisify(execFile)\n\nexport interface TlsCertPair {\n readonly cert: Buffer\n readonly key: Buffer\n}\n\nexport interface EnsureTlsResult {\n readonly certPath: string\n readonly keyPath: string\n readonly generated: boolean\n}\n\nexport interface CertOptions {\n /** Common Name for the cert (default: 'camstack.local') */\n readonly commonName?: string\n /** Validity in days (default: 825 — max for browsers) */\n readonly validDays?: number\n /** Additional SANs (DNS names or IPs) */\n readonly extraSans?: readonly string[]\n}\n\n/**\n * Ensure a self-signed TLS certificate exists in the given directory.\n * Generates one if missing. Returns paths to cert and key files.\n */\nexport async function ensureTlsCert(\n dataDir: string,\n options?: CertOptions,\n): Promise<EnsureTlsResult> {\n const tlsDir = join(dataDir, 'tls')\n const certPath = join(tlsDir, 'camstack.crt')\n const keyPath = join(tlsDir, 'camstack.key')\n\n // Already exists — reuse\n if (existsSync(certPath) && existsSync(keyPath)) {\n try {\n const certPem = readFileSync(certPath)\n const x509 = new X509Certificate(certPem)\n const validTo = new Date(x509.validTo)\n if (validTo > new Date()) {\n return { certPath, keyPath, generated: false }\n }\n // Expired — regenerate below\n } catch {\n // Corrupted — regenerate below\n }\n }\n\n mkdirSync(tlsDir, { recursive: true })\n\n const cn = options?.commonName ?? 'camstack.local'\n const validDays = options?.validDays ?? 825\n\n // Collect SANs: localhost, 127.0.0.1, all local IPs, hostname\n const sanDns = new Set<string>(['localhost', cn, os.hostname()])\n const sanIps = new Set<string>(['127.0.0.1', '::1'])\n\n // Add all local network IPs\n const interfaces = os.networkInterfaces()\n for (const addrs of Object.values(interfaces)) {\n if (!addrs) continue\n for (const addr of addrs) {\n if (!addr.internal) {\n sanIps.add(addr.address)\n }\n }\n }\n\n // Add extra SANs\n for (const san of options?.extraSans ?? []) {\n if (san.match(/^\\d+\\.\\d+\\.\\d+\\.\\d+$/) || san.includes(':')) {\n sanIps.add(san)\n } else {\n sanDns.add(san)\n }\n }\n\n // Build SAN string for openssl\n const sanParts: string[] = []\n for (const dns of sanDns) {\n sanParts.push(`DNS:${dns}`)\n }\n for (const ip of sanIps) {\n sanParts.push(`IP:${ip}`)\n }\n const sanString = sanParts.join(',')\n\n // Generate self-signed certificate using openssl CLI\n await execFileAsync('openssl', [\n 'req', '-x509',\n '-newkey', 'rsa:2048',\n '-keyout', keyPath,\n '-out', certPath,\n '-days', String(validDays),\n '-nodes',\n '-subj', `/CN=${cn}`,\n '-addext', `subjectAltName=${sanString}`,\n ])\n\n // Set restrictive permissions on the key file\n const { chmod } = await import('node:fs/promises')\n await chmod(keyPath, 0o600)\n\n return { certPath, keyPath, generated: true }\n}\n\n/**\n * Load TLS cert+key from files. Returns Buffers suitable for Node.js TLS options.\n */\nexport function loadTlsCert(certPath: string, keyPath: string): TlsCertPair {\n return {\n cert: readFileSync(certPath),\n key: readFileSync(keyPath),\n }\n}\n","/**\n * Factory for creating tRPC clients for addons.\n *\n * In-process only: `createDirectCaller()` uses tRPC's `createCallerFactory`\n * to call procedures directly (zero network overhead) and wraps the raw\n * caller in a proxy so it matches `CreateTRPCClient<AppRouter>` shape —\n * addons use `context.api.namespace.method.query(input)` identically to\n * the cross-process path.\n *\n * Cross-process calls (forked workers, remote agents) ride the Moleculer\n * broker via `brokerTransportLink` in the kernel — not this factory.\n */\n\nexport interface DirectCallerOptions {\n /** The tRPC router instance (from buildAppRouter) */\n readonly router: unknown\n /** Context for the caller (user identity, etc.) */\n readonly context: { readonly user: { readonly id: string; readonly username: string; readonly role: string } }\n}\n\n/**\n * Wrap a raw tRPC caller (from `createCallerFactory`) in a proxy that\n * exposes each leaf procedure as `{ query, mutate, subscribe }`, matching\n * the shape of `CreateTRPCClient<AppRouter>`.\n *\n * The tricky part: tRPC v11 callers expose nested routers as callable\n * no-op functions (e.g. `caller.greet` is `typeof === 'function'`), so\n * we can't use `typeof` to tell namespace from leaf. Instead, we return\n * a unified proxy that handles BOTH behaviours:\n *\n * - Accessing `.query` / `.mutate` treats the current node as a leaf\n * procedure and invokes `caller(input)` when called.\n * - Accessing `.subscribe` throws (not supported on direct caller).\n * - Accessing any other property descends into `caller[prop]` and\n * returns a nested proxy.\n */\nfunction wrapCallerAsClient<T>(caller: unknown): T {\n return new Proxy(Object.create(null) as Record<string, unknown>, {\n get(_target, prop) {\n if (typeof prop !== 'string') return undefined\n\n if (prop === 'query' || prop === 'mutate') {\n // Leaf-mode: the current `caller` is expected to be a procedure\n // function. The tRPC caller accepts the raw input as its first\n // argument and returns `Promise<output>`.\n if (typeof caller !== 'function') {\n throw new Error(\n `Cannot call .${prop}() — this tRPC node is not a procedure`,\n )\n }\n const fn = caller as (input?: unknown) => Promise<unknown>\n return (input?: unknown) => fn(input)\n }\n\n if (prop === 'subscribe') {\n return () => {\n throw new Error(\n `subscribe() is not supported on direct caller — use the WSS client for subscriptions`,\n )\n }\n }\n\n // Namespace descent — keep walking the caller tree.\n const child = (caller as Record<string, unknown> | null | undefined)?.[prop]\n if (child === undefined || child === null) return undefined\n return wrapCallerAsClient<unknown>(child)\n },\n }) as T\n}\n\nexport class AddonApiFactory {\n /**\n * Create a direct caller -- calls tRPC procedures directly in-process.\n * Zero network overhead. Used for in-process addons and dev mode.\n *\n * Returns `AddonApi` — the same tRPC client surface that broker-routed\n * callers get. Callers treat it uniformly as `context.api` regardless\n * of the underlying transport.\n */\n async createDirectCaller(options: DirectCallerOptions): Promise<import('@camstack/types').AddonApi> {\n const { initTRPC } = await import('@trpc/server')\n const t = initTRPC.create()\n type RouterLike = Parameters<typeof t.createCallerFactory>[0]\n const callerFactory = t.createCallerFactory(options.router as RouterLike)\n type CallerContext = Parameters<ReturnType<typeof t.createCallerFactory>>[0]\n const caller = callerFactory(options.context as CallerContext)\n return wrapCallerAsClient<import('@camstack/types').AddonApi>(caller)\n }\n}\n","import type {\n Integration, PersistedDevice,\n CreateIntegrationInput, CreateDeviceInput,\n IIntegrationRegistry,\n ISettingsBackend,\n TableSchema,\n} from '@camstack/types'\nimport { parseJsonObject } from '@camstack/types'\n\nfunction serializeSetting(value: unknown): { value: string; valueType: string } {\n if (typeof value === 'number') return { value: String(value), valueType: 'number' }\n if (typeof value === 'boolean') return { value: String(value), valueType: 'boolean' }\n if (typeof value === 'string') return { value, valueType: 'string' }\n return { value: JSON.stringify(value), valueType: 'json' }\n}\n\nfunction deserializeSetting(value: string, valueType: string): unknown {\n switch (valueType) {\n case 'number': return Number(value)\n case 'boolean': return value === 'true'\n case 'json': try { return JSON.parse(value) } catch { return value }\n default: return value\n }\n}\n\nlet integrationCounter = 0\nlet deviceCounter = 0\n\nfunction nextIntegrationId(): string {\n return `int_${String(++integrationCounter).padStart(4, '0')}`\n}\n\nfunction nextDeviceId(): string {\n return `dev_${String(++deviceCounter).padStart(4, '0')}`\n}\n\nconst INTEGRATIONS_SCHEMA: TableSchema = {\n columns: [\n { name: 'id', type: 'TEXT', primaryKey: true },\n { name: 'addon_id', type: 'TEXT', notNull: true },\n { name: 'name', type: 'TEXT', notNull: true },\n { name: 'enabled', type: 'INTEGER', notNull: true, defaultValue: 1 },\n { name: 'info', type: 'TEXT', notNull: true, defaultValue: '{}' },\n { name: 'created_at', type: 'INTEGER', notNull: true },\n { name: 'updated_at', type: 'INTEGER', notNull: true },\n ],\n indexes: [\n { name: 'idx_integrations_addon', columns: ['addon_id'] },\n ],\n}\n\nconst INTEGRATION_SETTINGS_SCHEMA: TableSchema = {\n columns: [\n { name: 'integration_id', type: 'TEXT', notNull: true },\n { name: 'key', type: 'TEXT', notNull: true },\n { name: 'value', type: 'TEXT', notNull: true },\n { name: 'value_type', type: 'TEXT', notNull: true, defaultValue: 'string' },\n ],\n}\n\nconst DEVICES_SCHEMA: TableSchema = {\n columns: [\n { name: 'id', type: 'TEXT', primaryKey: true },\n { name: 'integration_id', type: 'TEXT', notNull: true },\n { name: 'stable_id', type: 'TEXT', notNull: true, unique: true },\n { name: 'type', type: 'TEXT', notNull: true, defaultValue: 'camera' },\n { name: 'name', type: 'TEXT', notNull: true },\n { name: 'enabled', type: 'INTEGER', notNull: true, defaultValue: 1 },\n { name: 'info', type: 'TEXT', notNull: true, defaultValue: '{}' },\n { name: 'created_at', type: 'INTEGER', notNull: true },\n { name: 'updated_at', type: 'INTEGER', notNull: true },\n ],\n indexes: [\n { name: 'idx_devices_integration', columns: ['integration_id'] },\n { name: 'idx_devices_stable', columns: ['stable_id'], unique: true },\n { name: 'idx_devices_type', columns: ['type'] },\n ],\n}\n\nconst DEVICE_SETTINGS_SCHEMA: TableSchema = {\n columns: [\n { name: 'device_id', type: 'TEXT', notNull: true },\n { name: 'key', type: 'TEXT', notNull: true },\n { name: 'value', type: 'TEXT', notNull: true },\n { name: 'value_type', type: 'TEXT', notNull: true, defaultValue: 'string' },\n ],\n}\n\nexport class IntegrationRegistry implements IIntegrationRegistry {\n private readonly backend: ISettingsBackend\n\n constructor(backend: ISettingsBackend) {\n this.backend = backend\n }\n\n async initialize(): Promise<void> {\n await this.backend.ensureTable?.('integrations', INTEGRATIONS_SCHEMA)\n await this.backend.ensureTable?.('integration_settings', INTEGRATION_SETTINGS_SCHEMA)\n await this.backend.ensureTable?.('devices', DEVICES_SCHEMA)\n await this.backend.ensureTable?.('device_settings_kv', DEVICE_SETTINGS_SCHEMA)\n\n // Resume counters from max existing IDs\n const ints = await this.backend.tableQuery?.('integrations', { orderBy: { field: 'id', direction: 'desc' }, limit: 1 }) ?? []\n if (ints[0]) {\n const num = parseInt(String(ints[0]['id']).replace('int_', ''), 10)\n if (!isNaN(num)) integrationCounter = num\n }\n const devs = await this.backend.tableQuery?.('devices', { orderBy: { field: 'id', direction: 'desc' }, limit: 1 }) ?? []\n if (devs[0]) {\n const num = parseInt(String(devs[0]['id']).replace('dev_', ''), 10)\n if (!isNaN(num)) deviceCounter = num\n }\n }\n\n // --- Integrations ---\n\n async createIntegration(input: CreateIntegrationInput): Promise<Integration> {\n const id = nextIntegrationId()\n const now = Math.floor(Date.now() / 1000)\n\n await this.backend.tableInsert?.('integrations', {\n id,\n addon_id: input.addonId,\n name: input.name,\n enabled: input.enabled !== false ? 1 : 0,\n info: JSON.stringify(input.info ?? {}),\n created_at: now,\n updated_at: now,\n })\n\n if (input.settings) {\n await this.setIntegrationSettings(id, input.settings)\n }\n\n return {\n id,\n addonId: input.addonId,\n name: input.name,\n enabled: input.enabled !== false,\n info: input.info ?? {},\n createdAt: now,\n updatedAt: now,\n }\n }\n\n async getIntegration(id: string): Promise<Integration | null> {\n const row = await this.backend.tableGet?.('integrations', { id })\n return row ? this.mapIntegration(row) : null\n }\n\n async getIntegrationByAddonId(addonId: string): Promise<Integration | null> {\n const row = await this.backend.tableGet?.('integrations', { addon_id: addonId })\n return row ? this.mapIntegration(row) : null\n }\n\n async listIntegrations(): Promise<readonly Integration[]> {\n const rows = await this.backend.tableQuery?.('integrations', { orderBy: { field: 'created_at', direction: 'asc' } }) ?? []\n return rows.map(r => this.mapIntegration(r))\n }\n\n async updateIntegration(id: string, updates: Partial<Pick<Integration, 'name' | 'enabled' | 'info'>>): Promise<Integration | null> {\n const updateRow: Record<string, unknown> = { updated_at: Math.floor(Date.now() / 1000) }\n if (updates.name !== undefined) updateRow['name'] = updates.name\n if (updates.enabled !== undefined) updateRow['enabled'] = updates.enabled ? 1 : 0\n if (updates.info !== undefined) updateRow['info'] = JSON.stringify(updates.info)\n\n await this.backend.tableUpdate?.('integrations', { id }, updateRow)\n return this.getIntegration(id)\n }\n\n async deleteIntegration(id: string): Promise<boolean> {\n const devices = await this.listDevices(id)\n for (const d of devices) {\n await this.backend.tableDelete?.('device_settings_kv', { device_id: d.id })\n }\n await this.backend.tableDelete?.('devices', { integration_id: id })\n await this.backend.tableDelete?.('integration_settings', { integration_id: id })\n await this.backend.tableDelete?.('integrations', { id })\n return true\n }\n\n // --- Integration Settings ---\n\n async getIntegrationSettings(integrationId: string): Promise<Record<string, unknown>> {\n const result: Record<string, unknown> = {}\n const rows = await this.backend.tableQuery?.('integration_settings', { where: { integration_id: integrationId } }) ?? []\n for (const row of rows) {\n result[String(row['key'])] = deserializeSetting(String(row['value']), String(row['value_type']))\n }\n return result\n }\n\n async setIntegrationSetting(integrationId: string, key: string, value: unknown): Promise<void> {\n const s = serializeSetting(value)\n await this.backend.tableDelete?.('integration_settings', { integration_id: integrationId, key })\n await this.backend.tableInsert?.('integration_settings', {\n integration_id: integrationId,\n key,\n value: s.value,\n value_type: s.valueType,\n })\n }\n\n async setIntegrationSettings(integrationId: string, settings: Record<string, unknown>): Promise<void> {\n for (const [key, value] of Object.entries(settings)) {\n await this.setIntegrationSetting(integrationId, key, value)\n }\n }\n\n // --- Devices ---\n\n async createDevice(input: CreateDeviceInput): Promise<PersistedDevice> {\n const id = nextDeviceId()\n const now = Math.floor(Date.now() / 1000)\n\n await this.backend.tableInsert?.('devices', {\n id,\n integration_id: input.integrationId,\n stable_id: input.stableId,\n type: input.type,\n name: input.name,\n enabled: input.enabled !== false ? 1 : 0,\n info: JSON.stringify(input.info ?? {}),\n created_at: now,\n updated_at: now,\n })\n\n if (input.settings) {\n await this.setDeviceSettings(id, input.settings)\n }\n\n return {\n id,\n integrationId: input.integrationId,\n stableId: input.stableId,\n type: input.type,\n name: input.name,\n enabled: input.enabled !== false,\n info: input.info ?? {},\n createdAt: now,\n updatedAt: now,\n }\n }\n\n async getDevice(id: string): Promise<PersistedDevice | null> {\n const row = await this.backend.tableGet?.('devices', { id })\n return row ? this.mapDevice(row) : null\n }\n\n async getDeviceByStableId(stableId: string): Promise<PersistedDevice | null> {\n const row = await this.backend.tableGet?.('devices', { stable_id: stableId })\n return row ? this.mapDevice(row) : null\n }\n\n async listDevices(integrationId?: string): Promise<readonly PersistedDevice[]> {\n const options = integrationId\n ? { where: { integration_id: integrationId }, orderBy: { field: 'created_at' as const, direction: 'asc' as const } }\n : { orderBy: { field: 'created_at' as const, direction: 'asc' as const } }\n const rows = await this.backend.tableQuery?.('devices', options) ?? []\n return rows.map(r => this.mapDevice(r))\n }\n\n async listCameras(): Promise<readonly PersistedDevice[]> {\n const rows = await this.backend.tableQuery?.('devices', { where: { type: 'camera' }, orderBy: { field: 'created_at', direction: 'asc' } }) ?? []\n return rows.map(r => this.mapDevice(r))\n }\n\n async updateDevice(id: string, updates: Partial<Pick<PersistedDevice, 'name' | 'enabled' | 'info'>>): Promise<PersistedDevice | null> {\n const updateRow: Record<string, unknown> = { updated_at: Math.floor(Date.now() / 1000) }\n if (updates.name !== undefined) updateRow['name'] = updates.name\n if (updates.enabled !== undefined) updateRow['enabled'] = updates.enabled ? 1 : 0\n if (updates.info !== undefined) updateRow['info'] = JSON.stringify(updates.info)\n\n await this.backend.tableUpdate?.('devices', { id }, updateRow)\n return this.getDevice(id)\n }\n\n async deleteDevice(id: string): Promise<boolean> {\n await this.backend.tableDelete?.('device_settings_kv', { device_id: id })\n await this.backend.tableDelete?.('devices', { id })\n return true\n }\n\n // --- Device Settings ---\n\n async getDeviceSettings(deviceId: string): Promise<Record<string, unknown>> {\n const result: Record<string, unknown> = {}\n const rows = await this.backend.tableQuery?.('device_settings_kv', { where: { device_id: deviceId } }) ?? []\n for (const row of rows) {\n result[String(row['key'])] = deserializeSetting(String(row['value']), String(row['value_type']))\n }\n return result\n }\n\n async setDeviceSetting(deviceId: string, key: string, value: unknown): Promise<void> {\n const s = serializeSetting(value)\n await this.backend.tableDelete?.('device_settings_kv', { device_id: deviceId, key })\n await this.backend.tableInsert?.('device_settings_kv', {\n device_id: deviceId,\n key,\n value: s.value,\n value_type: s.valueType,\n })\n }\n\n async setDeviceSettings(deviceId: string, settings: Record<string, unknown>): Promise<void> {\n for (const [key, value] of Object.entries(settings)) {\n await this.setDeviceSetting(deviceId, key, value)\n }\n }\n\n // --- Mappers ---\n\n private mapIntegration(row: Record<string, unknown>): Integration {\n return {\n id: String(row['id']),\n addonId: String(row['addon_id']),\n name: String(row['name']),\n enabled: row['enabled'] === 1,\n info: typeof row['info'] === 'string' ? (parseJsonObject(row['info']) ?? {}) : {},\n createdAt: Number(row['created_at']),\n updatedAt: Number(row['updated_at']),\n }\n }\n\n private mapDevice(row: Record<string, unknown>): PersistedDevice {\n return {\n id: String(row['id']),\n integrationId: String(row['integration_id']),\n stableId: String(row['stable_id']),\n type: String(row['type']),\n name: String(row['name']),\n enabled: row['enabled'] === 1,\n info: typeof row['info'] === 'string' ? (parseJsonObject(row['info']) ?? {}) : {},\n createdAt: Number(row['created_at']),\n updatedAt: Number(row['updated_at']),\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,IAAM,gBAAgB;CAAC;CAAQ;CAAU;CAAY;CAAU;CAAK;AA8BzC,OAAO,YAAY;CA5B5C;EAAE,IAAI;EAAY,OAAO;EAAY,MAAM;EAAoB,OAAO;EAAK;CAC3E;EAAE,IAAI;EAAW,OAAO;EAAW,MAAM;EAAY,OAAO;EAAG;CAC/D;EAAE,IAAI;EAAS,OAAO;EAAS,MAAM;EAAS,OAAO;EAAG;CACxD;EAAE,IAAI;EA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IAAI,cAAc,CAAC;EAElG,OAAO;;CAGT,MAAM,iBAAiB,UAAkB,KAAa,OAA+B;EACnF,MAAM,IAAI,iBAAiB,MAAM;EACjC,MAAM,KAAK,QAAQ,cAAc,sBAAsB;GAAE,WAAW;GAAU;GAAK,CAAC;EACpF,MAAM,KAAK,QAAQ,cAAc,sBAAsB;GACrD,WAAW;GACX;GACA,OAAO,EAAE;GACT,YAAY,EAAE;GACf,CAAC;;CAGJ,MAAM,kBAAkB,UAAkB,UAAkD;EAC1F,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,SAAS,EACjD,MAAM,KAAK,iBAAiB,UAAU,KAAK,MAAM;;CAMrD,eAAuB,KAA2C;EAChE,OAAO;GACL,IAAI,OAAO,IAAI,MAAM;GACrB,SAAS,OAAO,IAAI,YAAY;GAChC,MAAM,OAAO,IAAI,QAAQ;GACzB,SAAS,IAAI,eAAe;GAC5B,MAAM,OAAO,IAAI,YAAY,WAAY,gBAAgB,IAAI,QAAQ,IAAI,EAAE,GAAI,EAAE;GACjF,WAAW,OAAO,IAAI,cAAc;GACpC,WAAW,OAAO,IAAI,cAAc;GACrC;;CAGH,UAAkB,KAA+C;EAC/D,OAAO;GACL,IAAI,OAAO,IAAI,MAAM;GACrB,eAAe,OAAO,IAAI,kBAAkB;GAC5C,UAAU,OAAO,IAAI,aAAa;GAClC,MAAM,OAAO,IAAI,QAAQ;GACzB,MAAM,OAAO,IAAI,QAAQ;GACzB,SAAS,IAAI,eAAe;GAC5B,MAAM,OAAO,IAAI,YAAY,WAAY,gBAAgB,IAAI,QAAQ,IAAI,EAAE,GAAI,EAAE;GACjF,WAAW,OAAO,IAAI,cAAc;GACpC,WAAW,OAAO,IAAI,cAAc;GACrC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["WELL_KNOWN_TAB_MAP","StorageLocationTypeSchema","errMsg","DeviceType","DeviceFeature","AlertSchema","alertsCapability","storageCapability","storageProviderCapability","backupCapability","settingsStoreCapability","logDestinationCapability","UserRecordSchema","ApiKeyRecordSchema","ScopedTokenSchema","addonPagesCapability","addonWidgetsCapability","deviceManagerCapability","deviceStateCapability","authProviderCapability","snapshotCapability","metricsProviderCapability","platformProbeCapability","localNetworkCapability","userManagementCapability","errMsg"],"sources":["../../types/dist/index-CgPd35k5.mjs","../../types/dist/node.mjs","../src/events/event-bus.ts","../src/download/model-downloader.ts","../src/download/model-download-service.ts","../src/python/python-env-manager.ts","../src/pipeline/pipeline-validator.ts","../src/pipeline/pipeline-runner.ts","../src/pipeline/engine-manager-resolver.ts","../src/network/network-quality.ts","../src/repl/repl-engine.ts","../src/lifecycle/lifecycle-state-machine.ts","../src/feature/feature-manager.ts","../src/events/system-event-bus.ts","../src/logging/log-ring-buffer.ts","../src/logging/scoped-logger.ts","../src/logging/log-manager.ts","../src/storage/fs-storage-backend.ts","../src/storage/storage-location-manager.ts","../src/storage/storage-manager.ts","../src/auth/scope-matcher.ts","../src/notification/notification-service.ts","../src/notification/toast-service.ts","../src/addon-routes/addon-route-registry.ts","../src/tls/cert-manager.ts","../src/addon/addon-api-factory.ts","../src/builtins/sqlite-storage/integration-registry.ts"],"sourcesContent":["import { z } from \"zod\";\nconst MODEL_FORMATS = [\"onnx\", \"coreml\", \"openvino\", \"tflite\", \"pt\"];\nconst WELL_KNOWN_TABS = [\n { id: \"overview\", label: \"Overview\", icon: \"layout-dashboard\", order: -10 },\n { id: \"general\", label: \"General\", icon: \"settings\", order: 0 },\n { id: \"image\", label: \"Image\", icon: \"image\", order: 5 },\n { id: \"light\", label: \"Light\", icon: \"lightbulb\", order: 7 },\n { id: \"motion\", label: \"Motion\", icon: \"activity\", order: 10 },\n { id: \"audio\", label: \"Audio\", icon: \"mic\", order: 12 },\n { id: \"alarms\", label: \"Alarms\", icon: \"bell-ring\", order: 13 },\n { id: \"snapshot\", label: \"Snapshot\", icon: \"camera\", order: 15 },\n { id: \"osd\", label: \"OSD\", icon: \"type\", order: 18 },\n { id: \"stream-broker\", label: \"Stream Broker\", icon: \"radio\", order: 20 },\n { id: \"streaming\", label: \"Streaming\", icon: \"video\", order: 35 },\n { id: \"ptz\", label: \"PTZ\", icon: \"move\", order: 40 },\n { id: \"pipeline\", label: \"Detection Pipeline\", icon: \"cpu\", order: 39 },\n { id: \"zones\", label: \"Detection\", icon: \"shapes\", order: 38 },\n { id: \"live-stats\", label: \"Live Stats\", icon: \"activity\", order: 39 },\n { id: \"recording\", label: \"Recording\", icon: \"circle-dot\", order: 40 },\n // Pipeline-page tabs — `engine` co-locates `detection-pipeline`'s\n // vision-engine section + `audio-analyzer`'s audio-engine section\n // (same modality of choice, different pipelines). `scheduler` and\n // `decoder` group the runner / decoder addon settings under their\n // own tabs so the pipeline page bar stays manageable.\n { id: \"engine\", label: \"Inference Engine\", icon: \"zap\", order: 41 },\n { id: \"scheduler\", label: \"Scheduler\", icon: \"list-checks\", order: 42 },\n { id: \"decoder\", label: \"Decoder\", icon: \"film\", order: 43 },\n { id: \"notifications\", label: \"Notifications\", icon: \"bell\", order: 50 },\n { id: \"network\", label: \"Network\", icon: \"globe\", order: 60 },\n { id: \"storage\", label: \"Storage\", icon: \"hard-drive\", order: 70 },\n { id: \"advanced\", label: \"Advanced\", icon: \"wrench\", order: 100 }\n];\nconst WELL_KNOWN_TAB_MAP = Object.fromEntries(WELL_KNOWN_TABS.map((t) => [t.id, t]));\nfunction isValuelessField(field) {\n return field.type === \"separator\" || field.type === \"info\" || field.type === \"button\" || field.type === \"object-array\" || field.type === \"widget\" || field.type === \"addon-action-button\";\n}\nfunction hydrateSchema(schema, values) {\n return {\n ...schema.tabs ? { tabs: [...schema.tabs] } : {},\n sections: schema.sections.map((section) => ({\n ...section,\n fields: section.fields.map((field) => hydrateField(field, values))\n }))\n };\n}\nfunction hydrateField(field, values) {\n if (isValuelessField(field)) {\n return field;\n }\n if (field.type === \"group\") {\n const hydratedChildren = field.fields.map((child) => hydrateField(child, values));\n const out = {\n ...field,\n fields: hydratedChildren\n };\n return out;\n }\n if (field.type === \"sub-tabs\") {\n const hydratedTabs = field.tabs.map((tab) => ({\n ...tab,\n fields: tab.fields.map((child) => hydrateField(child, values))\n }));\n const out = {\n ...field,\n tabs: hydratedTabs\n };\n return out;\n }\n const key = field.key;\n const storedValue = Object.prototype.hasOwnProperty.call(values, key) ? values[key] : void 0;\n const defaultValue = field.default;\n if (field.multiple) {\n const stored = Array.isArray(storedValue) ? storedValue : storedValue !== void 0 && storedValue !== null ? [storedValue] : [];\n const itemFallback = field.multiple.itemDefault !== void 0 ? field.multiple.itemDefault : defaultValue !== void 0 ? defaultValue : typeOf(field) === \"string\" ? \"\" : null;\n const minCount = Math.max(field.multiple.min, stored.length);\n const items = [];\n for (let i = 0; i < minCount; i++) {\n items.push(i < stored.length ? stored[i] : itemFallback);\n }\n return { ...field, value: items };\n }\n const rawValue = storedValue !== void 0 ? storedValue : defaultValue !== void 0 ? defaultValue : null;\n if (field.type === \"password\") {\n return { ...field, value: \"\" };\n }\n const value = field.type === \"textarea\" && field.isJson && rawValue !== null && typeof rawValue === \"object\" ? JSON.stringify(rawValue, null, 2) : rawValue;\n const hydrated = { ...field, value };\n return hydrated;\n}\nfunction typeOf(field) {\n switch (field.type) {\n case \"text\":\n case \"textarea\":\n case \"password\":\n case \"color\":\n case \"probe\":\n return \"string\";\n case \"number\":\n case \"slider\":\n return \"number\";\n case \"boolean\":\n return \"boolean\";\n default:\n return \"other\";\n }\n}\nconst StorageLocationTypeSchema = z.enum([\n \"data\",\n \"media\",\n \"recordings\",\n // Recording-stream slots — addons pick high/low/clips per use case.\n // The legacy `IStorageProvider` interface enumerated these; keeping\n // them in the Zod enum means the `storage` cap can route per-slot\n // location refs (e.g. `'recordings-high:nas-01'`) without losing\n // type safety.\n \"recordings-high\",\n \"recordings-low\",\n \"recordings-clips\",\n // Detection snapshots / thumbnails / crops.\n \"event-images\",\n \"models\",\n \"cache\",\n \"logs\",\n \"addons-data\",\n // `backups` — owned by the backup-orchestrator builtin. Default\n // root: `<dataDir>/backups`. Operators can repoint via the same\n // override mechanism every other location uses (storage settings).\n \"backups\"\n]);\nconst STORAGE_LOCATION_CARDINALITY = {\n // Singletons — system-internal or split-state-incoherent\n data: \"singleton\",\n media: \"singleton\",\n cache: \"singleton\",\n logs: \"singleton\",\n \"addons-data\": \"singleton\",\n models: \"singleton\",\n \"event-images\": \"singleton\",\n // Multi — operator-driven storage tiering\n recordings: \"multi\",\n \"recordings-high\": \"multi\",\n \"recordings-low\": \"multi\",\n \"recordings-clips\": \"multi\",\n backups: \"multi\"\n};\nconst StorageLocationSchema = z.object({\n id: z.string().regex(/^[a-z][a-z0-9-]*:[a-z0-9-]+$/),\n type: StorageLocationTypeSchema,\n displayName: z.string().min(1),\n providerId: z.string().min(1),\n config: z.record(z.string(), z.unknown()),\n isDefault: z.boolean().default(false),\n isSystem: z.boolean().default(false),\n createdAt: z.number(),\n updatedAt: z.number()\n});\nconst StorageLocationRefSchema = z.union([\n StorageLocationTypeSchema,\n z.string().regex(/^[a-z][a-z0-9-]*:[a-z0-9-]+$/)\n]);\nconst DecoderStatsSchema = z.object({\n inputFps: z.number(),\n outputFps: z.number(),\n avgDecodeTimeMs: z.number(),\n droppedFrames: z.number()\n});\nconst DecoderSessionConfigSchema = z.object({\n codec: z.string(),\n maxFps: z.number().default(0),\n outputFormat: z.enum([\"jpeg\", \"rgb\", \"bgr\", \"yuv420\", \"gray\"]).default(\"jpeg\"),\n scale: z.number().default(1),\n width: z.number().optional(),\n height: z.number().optional(),\n /**\n * Identifier of the camera this decoder session serves. Optional\n * because the cap is generic (any caller could request decode), but\n * stream-broker passes it so decoder logs include `deviceId` for\n * per-camera filtering when diagnosing failures (e.g. node-av\n * sendPacket errors on a single hung camera).\n */\n deviceId: z.number().int().nonnegative().optional(),\n /**\n * Free-form tag for log scoping. Stream-broker uses\n * `broker:<deviceId>/<profile>`. Decoder session logger surfaces it\n * on every line so `grep tag=broker:5/high` filters one camera\n * profile cleanly.\n */\n tag: z.string().optional(),\n /**\n * Where the session delivers decoded frames (Phase 5 / D9):\n *\n * - `'callback'` (default) — the legacy pixel path: decoded frames are\n * buffered as `DecodedFrame`s and drained via `pullFrames`.\n * - `'shm'` — the shared-memory frame plane: decoded frames are written\n * into an OS shared-memory ring and drained as zero-pixel\n * `FrameHandle`s via `pullHandles`. A session is one mode or the\n * other — `pullFrames` returns nothing for an `'shm'` session and\n * `pullHandles` returns nothing for a `'callback'` session.\n */\n frameSink: z.enum([\"callback\", \"shm\"]).default(\"callback\")\n});\nfunction errMsg(err) {\n if (err instanceof Error) return err.message;\n if (typeof err === \"string\") return err;\n return String(err);\n}\nconst AUDIO_MACRO_LABELS = [\n { id: \"speech\", name: \"Speech\", icon: \"🗣️\" },\n { id: \"scream\", name: \"Scream / Shout\", icon: \"😱\" },\n { id: \"crying\", name: \"Crying / Baby\", icon: \"😢\" },\n { id: \"laughter\", name: \"Laughter\", icon: \"😂\" },\n { id: \"music\", name: \"Music\", icon: \"🎵\" },\n { id: \"dog\", name: \"Dog\", icon: \"🐕\" },\n { id: \"cat\", name: \"Cat\", icon: \"🐈\" },\n { id: \"bird\", name: \"Bird\", icon: \"🐦\" },\n { id: \"animal\", name: \"Animal (other)\", icon: \"🐾\" },\n { id: \"alarm\", name: \"Alarm / Siren\", icon: \"🚨\" },\n { id: \"doorbell\", name: \"Doorbell / Knock\", icon: \"🔔\" },\n { id: \"glass_breaking\", name: \"Glass Breaking\", icon: \"💥\" },\n { id: \"gunshot\", name: \"Gunshot / Explosion\", icon: \"💣\" },\n { id: \"vehicle\", name: \"Vehicle\", icon: \"🚗\" },\n { id: \"siren\", name: \"Emergency Siren\", icon: \"🚑\" },\n { id: \"fire\", name: \"Fire / Smoke\", icon: \"🔥\" },\n { id: \"water\", name: \"Water\", icon: \"💧\" },\n { id: \"wind\", name: \"Wind / Weather\", icon: \"🌬️\" },\n { id: \"door\", name: \"Door\", icon: \"🚪\" },\n { id: \"footsteps\", name: \"Footsteps\", icon: \"👣\" },\n { id: \"crowd\", name: \"Crowd / Chatter\", icon: \"👥\" },\n { id: \"telephone\", name: \"Telephone\", icon: \"📞\" },\n { id: \"engine\", name: \"Engine / Motor\", icon: \"⚙️\" },\n { id: \"tools\", name: \"Tools / Construction\", icon: \"🔨\" },\n { id: \"silence\", name: \"Silence\", icon: \"🤫\" }\n];\nconst YAMNET_TO_MACRO = {\n mapping: {\n // Speech\n \"Speech\": \"speech\",\n \"Child speech, kid speaking\": \"speech\",\n \"Conversation\": \"speech\",\n \"Narration, monologue\": \"speech\",\n \"Babbling\": \"speech\",\n \"Whispering\": \"speech\",\n \"Speech synthesizer\": \"speech\",\n \"Humming\": \"speech\",\n \"Rapping\": \"speech\",\n \"Singing\": \"speech\",\n \"Choir\": \"speech\",\n \"Child singing\": \"speech\",\n // Scream / Shout\n \"Shout\": \"scream\",\n \"Bellow\": \"scream\",\n \"Yell\": \"scream\",\n \"Screaming\": \"scream\",\n \"Children shouting\": \"scream\",\n \"Whoop\": \"scream\",\n // Crying\n \"Crying, sobbing\": \"crying\",\n \"Baby cry, infant cry\": \"crying\",\n \"Whimper\": \"crying\",\n \"Wail, moan\": \"crying\",\n \"Groan\": \"crying\",\n // Laughter\n \"Laughter\": \"laughter\",\n \"Baby laughter\": \"laughter\",\n \"Giggle\": \"laughter\",\n \"Snicker\": \"laughter\",\n \"Belly laugh\": \"laughter\",\n \"Chuckle, chortle\": \"laughter\",\n // Music\n \"Music\": \"music\",\n \"Musical instrument\": \"music\",\n \"Guitar\": \"music\",\n \"Piano\": \"music\",\n \"Drum\": \"music\",\n \"Drum kit\": \"music\",\n \"Violin, fiddle\": \"music\",\n \"Flute\": \"music\",\n \"Saxophone\": \"music\",\n \"Trumpet\": \"music\",\n \"Synthesizer\": \"music\",\n \"Pop music\": \"music\",\n \"Rock music\": \"music\",\n \"Hip hop music\": \"music\",\n \"Classical music\": \"music\",\n \"Jazz\": \"music\",\n \"Electronic music\": \"music\",\n \"Background music\": \"music\",\n // Dog\n \"Dog\": \"dog\",\n \"Bark\": \"dog\",\n \"Yip\": \"dog\",\n \"Howl\": \"dog\",\n \"Bow-wow\": \"dog\",\n \"Growling\": \"dog\",\n \"Whimper (dog)\": \"dog\",\n // Cat\n \"Cat\": \"cat\",\n \"Purr\": \"cat\",\n \"Meow\": \"cat\",\n \"Hiss\": \"cat\",\n \"Caterwaul\": \"cat\",\n // Bird\n \"Bird\": \"bird\",\n \"Bird vocalization, bird call, bird song\": \"bird\",\n \"Chirp, tweet\": \"bird\",\n \"Squawk\": \"bird\",\n \"Crow\": \"bird\",\n \"Owl\": \"bird\",\n \"Pigeon, dove\": \"bird\",\n // Animal (other)\n \"Animal\": \"animal\",\n \"Domestic animals, pets\": \"animal\",\n \"Livestock, farm animals, working animals\": \"animal\",\n \"Horse\": \"animal\",\n \"Cattle, bovinae\": \"animal\",\n \"Pig\": \"animal\",\n \"Sheep\": \"animal\",\n \"Goat\": \"animal\",\n \"Frog\": \"animal\",\n \"Insect\": \"animal\",\n \"Cricket\": \"animal\",\n // Alarm / Siren\n \"Alarm\": \"alarm\",\n \"Alarm clock\": \"alarm\",\n \"Smoke detector, smoke alarm\": \"alarm\",\n \"Fire alarm\": \"alarm\",\n \"Buzzer\": \"alarm\",\n \"Civil defense siren\": \"alarm\",\n \"Car alarm\": \"alarm\",\n // Emergency Siren\n \"Siren\": \"siren\",\n \"Police car (siren)\": \"siren\",\n \"Ambulance (siren)\": \"siren\",\n \"Fire engine, fire truck (siren)\": \"siren\",\n \"Emergency vehicle\": \"siren\",\n \"Foghorn\": \"siren\",\n // Doorbell / Knock\n \"Doorbell\": \"doorbell\",\n \"Ding-dong\": \"doorbell\",\n \"Knock\": \"doorbell\",\n \"Tap\": \"doorbell\",\n // Glass Breaking\n \"Glass\": \"glass_breaking\",\n \"Shatter\": \"glass_breaking\",\n \"Chink, clink\": \"glass_breaking\",\n // Gunshot / Explosion\n \"Gunshot, gunfire\": \"gunshot\",\n \"Machine gun\": \"gunshot\",\n \"Explosion\": \"gunshot\",\n \"Fireworks\": \"gunshot\",\n \"Firecracker\": \"gunshot\",\n \"Artillery fire\": \"gunshot\",\n \"Cap gun\": \"gunshot\",\n \"Boom\": \"gunshot\",\n // Vehicle\n \"Vehicle\": \"vehicle\",\n \"Car\": \"vehicle\",\n \"Truck\": \"vehicle\",\n \"Bus\": \"vehicle\",\n \"Motorcycle\": \"vehicle\",\n \"Car passing by\": \"vehicle\",\n \"Vehicle horn, car horn, honking\": \"vehicle\",\n \"Traffic noise, roadway noise\": \"vehicle\",\n \"Train\": \"vehicle\",\n \"Aircraft\": \"vehicle\",\n \"Helicopter\": \"vehicle\",\n \"Bicycle\": \"vehicle\",\n \"Skateboard\": \"vehicle\",\n // Fire / Smoke\n \"Fire\": \"fire\",\n \"Crackle\": \"fire\",\n // Water\n \"Water\": \"water\",\n \"Rain\": \"water\",\n \"Raindrop\": \"water\",\n \"Rain on surface\": \"water\",\n \"Stream\": \"water\",\n \"Waterfall\": \"water\",\n \"Ocean\": \"water\",\n \"Waves, surf\": \"water\",\n \"Splash, splatter\": \"water\",\n // Wind / Weather\n \"Wind\": \"wind\",\n \"Thunderstorm\": \"wind\",\n \"Thunder\": \"wind\",\n \"Wind noise (microphone)\": \"wind\",\n \"Rustling leaves\": \"wind\",\n // Door\n \"Door\": \"door\",\n \"Sliding door\": \"door\",\n \"Slam\": \"door\",\n \"Cupboard open or close\": \"door\",\n // Footsteps\n \"Walk, footsteps\": \"footsteps\",\n \"Run\": \"footsteps\",\n \"Shuffle\": \"footsteps\",\n // Crowd\n \"Crowd\": \"crowd\",\n \"Chatter\": \"crowd\",\n \"Cheering\": \"crowd\",\n \"Applause\": \"crowd\",\n \"Children playing\": \"crowd\",\n \"Hubbub, speech noise, speech babble\": \"crowd\",\n // Telephone\n \"Telephone\": \"telephone\",\n \"Telephone bell ringing\": \"telephone\",\n \"Ringtone\": \"telephone\",\n \"Telephone dialing, DTMF\": \"telephone\",\n \"Busy signal\": \"telephone\",\n // Engine / Motor\n \"Engine\": \"engine\",\n \"Engine starting\": \"engine\",\n \"Idling\": \"engine\",\n \"Accelerating, revving, vroom\": \"engine\",\n \"Light engine (high frequency)\": \"engine\",\n \"Medium engine (mid frequency)\": \"engine\",\n \"Heavy engine (low frequency)\": \"engine\",\n \"Lawn mower\": \"engine\",\n \"Chainsaw\": \"engine\",\n // Tools / Construction\n \"Hammer\": \"tools\",\n \"Jackhammer\": \"tools\",\n \"Sawing\": \"tools\",\n \"Power tool\": \"tools\",\n \"Drill\": \"tools\",\n \"Sanding\": \"tools\",\n // Silence\n \"Silence\": \"silence\"\n },\n preserveOriginal: false\n};\nconst APPLE_SA_TO_MACRO = {\n mapping: {\n \"speech\": \"speech\",\n \"child_speech\": \"speech\",\n \"conversation\": \"speech\",\n \"whispering\": \"speech\",\n \"singing\": \"speech\",\n \"humming\": \"speech\",\n \"shout\": \"scream\",\n \"yell\": \"scream\",\n \"screaming\": \"scream\",\n \"crying\": \"crying\",\n \"baby_crying\": \"crying\",\n \"sobbing\": \"crying\",\n \"laughter\": \"laughter\",\n \"baby_laughter\": \"laughter\",\n \"giggling\": \"laughter\",\n \"music\": \"music\",\n \"guitar\": \"music\",\n \"piano\": \"music\",\n \"drums\": \"music\",\n \"dog_bark\": \"dog\",\n \"dog_bow_wow\": \"dog\",\n \"dog_growling\": \"dog\",\n \"dog_howl\": \"dog\",\n \"cat_meow\": \"cat\",\n \"cat_purr\": \"cat\",\n \"cat_hiss\": \"cat\",\n \"bird\": \"bird\",\n \"bird_chirp\": \"bird\",\n \"bird_squawk\": \"bird\",\n \"animal\": \"animal\",\n \"horse\": \"animal\",\n \"cow_moo\": \"animal\",\n \"insect\": \"animal\",\n \"alarm\": \"alarm\",\n \"smoke_alarm\": \"alarm\",\n \"fire_alarm\": \"alarm\",\n \"car_alarm\": \"alarm\",\n \"siren\": \"siren\",\n \"police_siren\": \"siren\",\n \"ambulance_siren\": \"siren\",\n \"doorbell\": \"doorbell\",\n \"door_knock\": \"doorbell\",\n \"knocking\": \"doorbell\",\n \"glass_breaking\": \"glass_breaking\",\n \"glass_shatter\": \"glass_breaking\",\n \"gunshot\": \"gunshot\",\n \"explosion\": \"gunshot\",\n \"fireworks\": \"gunshot\",\n \"car\": \"vehicle\",\n \"truck\": \"vehicle\",\n \"motorcycle\": \"vehicle\",\n \"car_horn\": \"vehicle\",\n \"vehicle_horn\": \"vehicle\",\n \"traffic\": \"vehicle\",\n \"fire\": \"fire\",\n \"fire_crackle\": \"fire\",\n \"water\": \"water\",\n \"rain\": \"water\",\n \"ocean\": \"water\",\n \"splash\": \"water\",\n \"wind\": \"wind\",\n \"thunder\": \"wind\",\n \"thunderstorm\": \"wind\",\n \"door\": \"door\",\n \"door_slam\": \"door\",\n \"sliding_door\": \"door\",\n \"footsteps\": \"footsteps\",\n \"walking\": \"footsteps\",\n \"running\": \"footsteps\",\n \"crowd\": \"crowd\",\n \"chatter\": \"crowd\",\n \"cheering\": \"crowd\",\n \"applause\": \"crowd\",\n \"telephone_ring\": \"telephone\",\n \"ringtone\": \"telephone\",\n \"engine\": \"engine\",\n \"engine_starting\": \"engine\",\n \"lawn_mower\": \"engine\",\n \"chainsaw\": \"engine\",\n \"hammer\": \"tools\",\n \"jackhammer\": \"tools\",\n \"drill\": \"tools\",\n \"power_tool\": \"tools\",\n \"silence\": \"silence\"\n },\n preserveOriginal: false\n};\nconst _macroLookup = /* @__PURE__ */ new Map();\nfor (const [k, v] of Object.entries(YAMNET_TO_MACRO.mapping)) {\n _macroLookup.set(k.toLowerCase(), v);\n}\nfor (const [k, v] of Object.entries(APPLE_SA_TO_MACRO.mapping)) {\n _macroLookup.set(k.toLowerCase(), v);\n}\nfunction mapAudioLabelToMacro(label) {\n return _macroLookup.get(label.toLowerCase()) ?? null;\n}\nfunction getAudioMacroClassIds() {\n return AUDIO_MACRO_LABELS.map((l) => l.id);\n}\nvar DeviceType = /* @__PURE__ */ ((DeviceType2) => {\n DeviceType2[\"Camera\"] = \"camera\";\n DeviceType2[\"Hub\"] = \"hub\";\n DeviceType2[\"Light\"] = \"light\";\n DeviceType2[\"Siren\"] = \"siren\";\n DeviceType2[\"Switch\"] = \"switch\";\n DeviceType2[\"Sensor\"] = \"sensor\";\n DeviceType2[\"Thermostat\"] = \"thermostat\";\n DeviceType2[\"Button\"] = \"button\";\n DeviceType2[\"Generic\"] = \"generic\";\n return DeviceType2;\n})(DeviceType || {});\nvar DeviceFeature = /* @__PURE__ */ ((DeviceFeature2) => {\n DeviceFeature2[\"BatteryOperated\"] = \"battery-operated\";\n DeviceFeature2[\"Rebootable\"] = \"rebootable\";\n DeviceFeature2[\"NativeSnapshot\"] = \"native-snapshot\";\n DeviceFeature2[\"DoorbellButton\"] = \"doorbell-button\";\n DeviceFeature2[\"TwoWayAudio\"] = \"two-way-audio\";\n DeviceFeature2[\"PanTiltZoom\"] = \"pan-tilt-zoom\";\n DeviceFeature2[\"PtzAutotrack\"] = \"ptz-autotrack\";\n DeviceFeature2[\"MotionTrigger\"] = \"motion-trigger\";\n return DeviceFeature2;\n})(DeviceFeature || {});\nvar ChargingStatus = /* @__PURE__ */ ((ChargingStatus2) => {\n ChargingStatus2[\"ChargingDC\"] = \"charging-dc\";\n ChargingStatus2[\"ChargingSolar\"] = \"charging-solar\";\n ChargingStatus2[\"NotCharging\"] = \"not-charging\";\n return ChargingStatus2;\n})(ChargingStatus || {});\nvar DeviceRole = /* @__PURE__ */ ((DeviceRole2) => {\n DeviceRole2[\"Siren\"] = \"siren\";\n DeviceRole2[\"Floodlight\"] = \"floodlight\";\n DeviceRole2[\"Spotlight\"] = \"spotlight\";\n DeviceRole2[\"PirSensor\"] = \"pir-sensor\";\n DeviceRole2[\"Chime\"] = \"chime\";\n DeviceRole2[\"Autotrack\"] = \"autotrack\";\n DeviceRole2[\"Nightvision\"] = \"nightvision\";\n DeviceRole2[\"PrivacyMask\"] = \"privacy-mask\";\n DeviceRole2[\"Doorbell\"] = \"doorbell\";\n return DeviceRole2;\n})(DeviceRole || {});\nconst AccessoryKind = {\n Siren: DeviceRole.Siren,\n Floodlight: DeviceRole.Floodlight,\n Spotlight: DeviceRole.Spotlight,\n PirSensor: DeviceRole.PirSensor,\n Chime: DeviceRole.Chime,\n Autotrack: DeviceRole.Autotrack,\n Nightvision: DeviceRole.Nightvision,\n PrivacyMask: DeviceRole.PrivacyMask\n};\nconst ACCESSORY_LABEL = {\n [AccessoryKind.Siren]: \"Siren\",\n [AccessoryKind.Floodlight]: \"Floodlight\",\n [AccessoryKind.Spotlight]: \"Spotlight\",\n [AccessoryKind.PirSensor]: \"PIR\",\n [AccessoryKind.Chime]: \"Chime\",\n [AccessoryKind.Autotrack]: \"Autotracking\",\n [AccessoryKind.Nightvision]: \"Night Vision\",\n [AccessoryKind.PrivacyMask]: \"Privacy Mask\"\n};\nfunction accessoryStableId(parentStableId, kind, index) {\n const base = `${parentStableId}:${kind}`;\n return typeof index === \"number\" ? `${base}:${index}` : base;\n}\nfunction deviceMatchesProfile(features, profile) {\n if (!features || features.length === 0) return false;\n return features.includes(profile.when.hasFeature);\n}\nconst BATTERY_DEVICE_PROFILE = {\n id: \"battery\",\n label: \"Battery-operated camera\",\n when: { hasFeature: DeviceFeature.BatteryOperated },\n defaults: {\n audioMode: \"disabled\",\n detectionMode: \"on-motion\"\n },\n settings: {\n \"snapshot.minRefreshIntervalSec\": 3600,\n \"streamBroker.preBufferEnabled\": false\n }\n};\nconst DEVICE_PROFILES = [\n BATTERY_DEVICE_PROFILE\n];\nfunction resolveDeviceProfile(features) {\n for (const profile of DEVICE_PROFILES) {\n if (deviceMatchesProfile(features, profile)) return profile;\n }\n return null;\n}\nconst DeviceStatusSchema = z.object({\n /**\n * Device-level liveness. Drivers flip via `markOnline(boolean)` on\n * `BaseDevice`. Provider semantics vary — RTSP aggregates broker\n * stream-health, Reolink reads firmware push events, ONVIF tracks\n * ping responses. This cap intentionally does NOT prescribe which\n * signal drives the flag.\n */\n online: z.boolean(),\n /** Ms epoch of the last `online` transition. Lets consumers tell\n * apart \"just came online\" from \"still online\". */\n lastChangedAt: z.number()\n});\nconst deviceStatusCapability = {\n name: \"device-status\",\n scope: \"device\",\n mode: \"singleton\",\n methods: {},\n events: {\n /** Emitted when `online` transitions. Mirrors the semantics of\n * `battery.onStatusChanged`. */\n onStatusChanged: { data: z.object({\n deviceId: z.number(),\n status: DeviceStatusSchema\n }) }\n },\n status: {\n schema: DeviceStatusSchema,\n kind: \"push\"\n },\n runtimeState: DeviceStatusSchema\n};\nconst FeatureProbeStatusSchema = z.object({\n /**\n * Driver-specific flag bag. Each driver picks its own key names — the\n * cap deliberately does NOT enforce a closed enum here. Reolink keys:\n * `hasPtz`, `hasIntercom`, `hasDoorbell`, `hasFloodlight`, `hasSiren`,\n * `hasPirSensor`, `hasAutotrack`, `hasBattery`. Hikvision keys:\n * `hasSupplementalLight`, `lightHasWhiteLight`, `hasAlarmIo`, `hasPtz`.\n */\n flags: z.record(z.string(), z.unknown()),\n /**\n * Coarse driver-classification — lets cross-process consumers tell apart\n * cameras / battery-cams / NVRs without re-running the probe. `null`\n * before the first probe completes.\n */\n deviceType: z.string().nullable(),\n /** Camera/firmware model string. `null` when the firmware doesn't expose it. */\n model: z.string().nullable(),\n /** Channel count for NVR/Hub devices; `1` for standalone cameras; `null` pre-probe. */\n channelCount: z.number().nullable(),\n /**\n * Ms epoch of the last SUCCESSFUL probe. `0` before the first probe\n * completes — drivers' `getAccessoryChildren()` should treat zero as\n * \"probe not done yet, return empty\" so accessories aren't spawned\n * before the firmware is queried.\n */\n lastProbedAt: z.number(),\n /**\n * Framework convention: every runtime-state slice carries this for the\n * createRuntimeStateBridge stale-check helper. We keep it in sync with\n * `lastProbedAt` on every write.\n */\n lastFetchedAt: z.number()\n});\nconst featureProbeCapability = {\n name: \"feature-probe\",\n scope: \"device\",\n mode: \"singleton\",\n methods: {},\n events: {\n /** Fires whenever a fresh probe completes (kernel-driven `reprobe()`\n * or driver-initiated re-detect after a state change). */\n onProbeChanged: { data: z.object({\n deviceId: z.number(),\n status: FeatureProbeStatusSchema\n }) }\n },\n status: {\n schema: FeatureProbeStatusSchema,\n kind: \"push\"\n },\n runtimeState: FeatureProbeStatusSchema\n};\nconst ContributionSectionSchema = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string().optional(),\n style: z.enum([\"card\", \"accordion\"]).optional(),\n defaultCollapsed: z.boolean().optional(),\n columns: z.union([z.literal(1), z.literal(2), z.literal(3), z.literal(4)]).optional(),\n tab: z.string().optional(),\n // Hoist the section into a top-level device tab (DeviceDetail\n // discovers these and renders one tab per unique `tab` id). Default\n // 'settings' keeps the section under the Config tab.\n location: z.enum([\"settings\", \"top-tab\"]).optional(),\n order: z.number().optional(),\n fields: z.array(z.any())\n});\nconst ContributionTabSchema = z.object({\n id: z.string(),\n label: z.string(),\n icon: z.string(),\n order: z.number().optional()\n});\nconst ContributionSchema = z.object({\n tabs: z.array(ContributionTabSchema).optional(),\n sections: z.array(ContributionSectionSchema)\n});\nconst ContributionOutputSchema = ContributionSchema.nullable();\nconst DEVICE_SETTINGS_CONTRIBUTION_METHODS = {\n getDeviceSettingsContribution: {\n input: z.object({ deviceId: z.number() }),\n output: ContributionOutputSchema,\n kind: \"query\",\n auth: \"protected\"\n },\n getDeviceLiveContribution: {\n input: z.object({ deviceId: z.number() }),\n output: ContributionOutputSchema,\n kind: \"query\",\n auth: \"protected\"\n },\n applyDeviceSettingsPatch: {\n input: z.object({ deviceId: z.number(), patch: z.record(z.string(), z.unknown()) }),\n output: z.object({ success: z.literal(true) }),\n kind: \"mutation\",\n auth: \"admin\"\n }\n};\nconst DEVICE_STATUS_METHOD = {\n getStatus: {\n input: z.object({ deviceId: z.number() }),\n output: z.unknown().nullable(),\n kind: \"query\",\n auth: \"protected\"\n }\n};\nfunction expandCapMethods(def) {\n let out = def.methods;\n if (def.exposesDeviceSettings) {\n out = { ...DEVICE_SETTINGS_CONTRIBUTION_METHODS, ...out };\n }\n if (def.status) {\n out = { ...DEVICE_STATUS_METHOD, ...out };\n }\n return out;\n}\nfunction method(input, output, options) {\n return {\n input,\n output,\n kind: options?.kind ?? \"query\",\n auth: options?.auth ?? \"protected\",\n ...options?.access !== void 0 ? { access: options.access } : {},\n timeoutMs: options?.timeoutMs\n };\n}\nfunction event(data) {\n return { data };\n}\nfunction isDeviceConfigCap(def) {\n return def?.deviceConfig !== void 0;\n}\nconst AudioClassSummarySchema = z.object({\n className: z.string(),\n /** Number of windows (chunks) where this class was the top hit. */\n hits: z.number().int().nonnegative(),\n /** Mean score across those hits, clamped to [0,1]. */\n avgScore: z.number().min(0).max(1),\n /** Peak score in the window. */\n peakScore: z.number().min(0).max(1)\n});\nconst AudioMetricsSnapshotSchema = z.object({\n /** Wall-clock timestamp (ms) of the most recent audio window. */\n ts: z.number().int(),\n /** Sliding-window length (seconds) used for aggregation. */\n windowSec: z.number().int().positive(),\n /** Latest level reading from the most recent window. */\n level: z.object({\n rms: z.number(),\n dbfs: z.number()\n }),\n /** Peak dBFS observed across the rolling window. */\n peakDbfs: z.number(),\n /** Mean dBFS across the rolling window. */\n avgDbfs: z.number(),\n /** Most recent above-threshold classification, or null on silence. */\n current: z.object({\n className: z.string(),\n score: z.number().min(0).max(1),\n timestamp: z.number().int()\n }).nullable(),\n /** Per-class summary across the rolling window — keys are\n * `macroClass` strings (e.g. `dog_bark`, `speech`, `glass_break`). */\n byClass: z.array(AudioClassSummarySchema).readonly()\n});\nconst AudioMetricsHistoryPointSchema = z.object({\n /** Wall-clock ms when this sample was recorded. */\n ts: z.number().int(),\n /** Instantaneous dBFS level at sample time. `null` for windows where\n * the source had no level reading (rare; happens at decode startup). */\n dbfs: z.number().nullable(),\n /** Rolling-window peak dBFS at sample time. Same window the live\n * snapshot reports. */\n peakDbfs: z.number(),\n /** Rolling-window mean dBFS at sample time. */\n avgDbfs: z.number(),\n /** Dominant above-threshold class at sample time, or null on silence. */\n topClass: z.string().nullable(),\n /** Score of the dominant class (`null` whenever `topClass` is null). */\n topScore: z.number().min(0).max(1).nullable()\n});\nconst AudioMetricsHistorySchema = z.object({\n points: z.array(AudioMetricsHistoryPointSchema).readonly(),\n /** Actual ms between adjacent samples after any subsampling. */\n effectiveSampleEveryMs: z.number().int().positive(),\n /** Wall-clock window covered by `points` (`points[N-1].ts - points[0].ts`),\n * or `0` when there's fewer than 2 samples. */\n windowMsActual: z.number().int().nonnegative()\n});\nconst audioMetricsCapability = {\n name: \"audio-metrics\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n /** Latest snapshot for this device. Null until the analytics\n * pipeline has processed at least one audio window. */\n getCurrentSnapshot: method(\n z.object({ deviceId: z.number() }),\n AudioMetricsSnapshotSchema.nullable()\n ),\n /**\n * Time-series view of recent audio-metrics samples. The provider\n * keeps an in-memory ring of ~1Hz samples (matching the slice-\n * write rate) capped at `MAX_HISTORY_POINTS_KEPT` (provider-side).\n * `windowSec` selects how far back to read; `sampleEveryMs`\n * downsamples by bucketed averaging when finer than the kept\n * granularity. Empty `points` array on freshly-booted providers\n * with no audio yet — same convention as `getCurrentSnapshot`.\n */\n getHistory: method(\n z.object({\n deviceId: z.number(),\n /** History window in seconds. Default 300 (5 minutes).\n * Provider clamps to its retention cap if larger. */\n windowSec: z.number().int().positive().optional(),\n /** Target sample interval in ms. Default 1000 (1 sample/second).\n * Provider clamps to natural sample rate if smaller, and\n * bucket-averages when bigger than the requested window\n * would produce more than `maxPoints` samples. */\n sampleEveryMs: z.number().int().positive().optional()\n }),\n AudioMetricsHistorySchema\n )\n },\n /** Reactive runtime-state mirror — live `device.state.audioMetrics.value`. */\n runtimeState: AudioMetricsSnapshotSchema\n};\nconst BatteryStatusSchema = z.object({\n /** 0..100 inclusive. Firmware-reported. */\n percentage: z.number().min(0).max(100),\n /**\n * Charging source. `'dc'` covers wall/USB adapters; `'solar'` is\n * Reolink-specific for the Solar Panel 2 accessory (will become\n * common on other battery cams). `'none'` means running on battery\n * alone.\n */\n charging: z.enum([\"dc\", \"solar\", \"none\"]),\n /**\n * True when the camera firmware has gone into low-power mode. Battery\n * providers MUST avoid polling during sleep — reading the battery\n * wakes the camera up and drains charge.\n */\n sleeping: z.boolean(),\n /** Ms epoch of the last observation. Lets consumers reason about freshness. */\n lastUpdated: z.number()\n});\nconst batteryCapability = {\n name: \"battery\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera, DeviceType.Sensor, DeviceType.Button, DeviceType.Switch],\n methods: {},\n events: {\n /**\n * Emitted whenever the cached status changes (firmware push OR\n * poll observes a delta). The DeviceEventPropagator mirrors this\n * event on the parent chain — subscribing to a camera's source\n * receives battery events from child accessories automatically.\n */\n onStatusChanged: { data: z.object({\n deviceId: z.number(),\n status: BatteryStatusSchema\n }) }\n },\n status: {\n schema: BatteryStatusSchema,\n kind: \"push\"\n },\n /**\n * Runtime-state slice — every provider that registers this cap\n * stores the same shape under `device.runtimeState[battery]`.\n * Cross-provider uniformity: a Reolink Argus, a Frigate sensor\n * proxy, an ONVIF battery cam all read/write the same keys.\n * Consumers (BatteryBadge, snapshot wrapper sleep gate) read once\n * via `device.runtimeState.getCapState('battery')` regardless of\n * the underlying driver.\n */\n runtimeState: BatteryStatusSchema\n};\nconst BrightnessStatusSchema = z.object({\n /** Current level as 0..100 inclusive. Firmware-reported. */\n percentage: z.number().min(0).max(100),\n /** Ms epoch of the last operator-driven change. Useful for UI freshness. */\n lastChangedAt: z.number()\n});\nconst brightnessCapability = {\n name: \"brightness\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Light],\n methods: {\n setBrightness: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n percentage: z.number().min(0).max(100)\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n },\n events: {\n /**\n * Emitted whenever the brightness changes — operator action OR\n * firmware push. Subscribers (UI sliders, automation engines) react\n * without polling.\n */\n onBrightnessChanged: { data: z.object({\n deviceId: z.number(),\n percentage: z.number().min(0).max(100),\n lastChangedAt: z.number()\n }) }\n },\n status: {\n schema: BrightnessStatusSchema,\n kind: \"command-driven\"\n },\n /**\n * Runtime-state slice — the last applied brightness level, mirrored\n * by the kernel. Read via `device.state.brightness.value` so UI\n * sliders surface the current level without polling the provider.\n */\n runtimeState: BrightnessStatusSchema\n};\nconst CamProfileSchema = z.enum([\"high\", \"mid\", \"low\"]);\nconst CAM_PROFILE_ORDER = [\"high\", \"mid\", \"low\"];\nconst CamStreamKindSchema = z.enum([\n \"pull-rtsp\",\n \"pull-rtmp\",\n \"pull-http\",\n \"pull-rfc4571\",\n \"push-annexb\"\n]);\nconst CamStreamResolutionSchema = z.object({\n width: z.number().int().positive(),\n height: z.number().int().positive()\n});\nconst CameraStreamSchema = z.object({\n /** Stable, provider-assigned id unique within the (deviceId) scope. */\n camStreamId: z.string().min(1),\n deviceId: z.number().int().nonnegative(),\n kind: CamStreamKindSchema,\n /** Required for pull-* kinds. Ignored for push-annexb. */\n url: z.string().optional(),\n codec: z.string().optional(),\n resolution: CamStreamResolutionSchema.optional(),\n fps: z.number().positive().optional(),\n /** Human label surfaced in the Admin UI \"Camera Stream\" dropdown. */\n label: z.string().optional(),\n /**\n * Device-level features the publisher advertised (e.g. `battery-operated`).\n * The broker, snapshot orchestrator, and prebuffer manager all consult\n * this list to derive policy — relaxed stall watchdog for battery\n * cams, prebuffer off by default, longer snapshot rate-limit, etc.\n *\n * Single source of truth replacing per-stream flags like the\n * historical `allowStall`: if the publisher knows the camera is\n * battery-powered, every downstream service derives the right policy\n * from this list.\n */\n deviceFeatures: z.array(z.string()).optional(),\n /**\n * Whether this stream participates in the broker's automatic profile\n * assignment (`computeInitialAssignment`). Defaults to `true`. Publishers\n * use `false` when they want a stream to be SELECTABLE in the UI but not\n * picked by default — e.g. Reolink publishes its native Baichuan streams\n * as `autoEligible: true` (the recommended path) and its RTSP / RTMP\n * mirrors as `autoEligible: false` (still pickable per slot, just not\n * the auto choice). Manual `assignProfile` calls remain valid for\n * non-eligible streams.\n */\n autoEligible: z.boolean().optional(),\n /**\n * Transport-specific opaque metadata. The broker passes it through to\n * the source reader without inspecting it. Currently used by\n * `pull-rfc4571` streams to carry the upstream SDP (so the reader can\n * route RTP packets to the right depacketizer without an in-band\n * DESCRIBE phase). Other kinds typically leave it undefined.\n */\n metadata: z.record(z.string(), z.unknown()).optional()\n});\nconst ProfileSlotStatusSchema = z.enum([\n \"unassigned\",\n \"idle\",\n \"connecting\",\n \"streaming\",\n \"error\"\n]);\nconst ProfileSlotSchema = z.object({\n deviceId: z.number().int().nonnegative(),\n profile: CamProfileSchema,\n /** Broker id the rest of the system addresses: `${deviceId}/${profile}`. */\n brokerId: z.string(),\n /** `null` when the profile is unassigned. */\n sourceCamStreamId: z.string().nullable(),\n status: ProfileSlotStatusSchema,\n resolution: CamStreamResolutionSchema.optional(),\n codec: z.string().optional(),\n preBufferSec: z.number().nonnegative().optional(),\n errorMessage: z.string().optional()\n});\nconst StreamSourceEntrySchema$1 = z.object({\n id: z.string(),\n label: z.string(),\n protocol: z.enum([\"rtsp\", \"rtmp\", \"annexb\", \"http-mjpeg\", \"webrtc\", \"custom\"]),\n url: z.string().optional(),\n resolution: z.object({ width: z.number(), height: z.number() }).readonly().optional(),\n fps: z.number().optional(),\n bitrate: z.number().optional(),\n codec: z.string().optional(),\n profileHint: z.enum([\"high\", \"mid\", \"low\"]).optional()\n});\nconst StreamSourceSchema = z.object({\n type: z.string(),\n url: z.string(),\n videoCodec: z.string().optional(),\n audioCodec: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).readonly().optional()\n});\nconst EncodedPacketSchema = z.object({\n type: z.enum([\"video\", \"audio\"]),\n data: z.instanceof(Uint8Array),\n pts: z.number(),\n dts: z.number(),\n keyframe: z.boolean(),\n codec: z.string()\n});\nconst DecodedFrameSchema = z.object({\n data: z.instanceof(Uint8Array),\n width: z.number(),\n height: z.number(),\n format: z.enum([\"jpeg\", \"rgb\", \"bgr\", \"yuv420\", \"gray\"]),\n timestamp: z.number()\n});\nconst FrameHandleSchema = z.object({\n shmId: z.string(),\n slot: z.number().int().nonnegative(),\n seq: z.number().int().nonnegative(),\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n format: z.enum([\"jpeg\", \"rgb\", \"bgr\", \"yuv420\", \"gray\"]),\n pts: z.number(),\n byteLength: z.number().int().nonnegative(),\n nodeId: z.string(),\n slotCount: z.number().int().positive()\n});\nconst FrameHandleFormatSchema = z.enum([\"rgb\", \"bgr\", \"yuv420\", \"gray\"]);\nconst SubscribeFramesInputSchema = z.object({\n brokerId: z.string(),\n format: FrameHandleFormatSchema,\n /**\n * Optional reader-side cadence hint in frames per second. The broker does\n * NOT throttle — latest-wins ring reads drop frames implicitly for a slow\n * consumer. The value is echoed back in `SubscribeFramesResult.maxFps` so\n * the consumer can pace its own `pullFrameHandles` polling.\n */\n maxFps: z.number().positive().optional(),\n /** Short caller-identity tag (`motion`, `detection`, …) for diagnostics. */\n tag: z.string().optional()\n});\nconst SubscribeFramesResultSchema = z.object({\n /** Opaque id the consumer passes to `pullFrameHandles` / `unsubscribeFrames`. */\n subscriptionId: z.string(),\n /** Reader-side cadence hint (frames/s) — echoes `SubscribeFramesInput.maxFps`. */\n maxFps: z.number().nonnegative()\n});\nconst DecodedAudioChunkSchema = z.object({\n data: z.instanceof(Uint8Array),\n sampleRate: z.number().int().positive(),\n channels: z.number().int().positive(),\n timestamp: z.number()\n});\nconst SubscribeAudioChunksInputSchema = z.object({\n brokerId: z.string(),\n /** Short caller-identity tag (`audio-analyzer`, …) for `listClients`. */\n tag: z.string().optional()\n});\nconst SubscribeAudioChunksResultSchema = z.object({\n /** Opaque id passed to `pullAudioChunks` / `unsubscribeAudioChunks`. */\n subscriptionId: z.string()\n});\nconst BrokerStatusSchema$1 = z.enum([\"idle\", \"connecting\", \"streaming\", \"error\", \"stopped\"]);\nconst BrokerStatsSchema = z.object({\n status: BrokerStatusSchema$1,\n inputFps: z.number(),\n decodeFps: z.number(),\n encodedSubscribers: z.number(),\n decodedSubscribers: z.number(),\n uptimeMs: z.number(),\n bitrateKbps: z.number(),\n idrIntervalMs: z.number(),\n codec: z.string().optional(),\n totalBytes: z.number(),\n packetCount: z.number(),\n rtspClients: z.number(),\n pipeClients: z.number(),\n preBufferSec: z.number(),\n preBufferMs: z.number(),\n preBufferPackets: z.number(),\n /**\n * Moleculer node id of the decoder provider currently servicing this\n * stream's decoded subscribers. `null` until the deferred decoder is\n * created (no decoded clients yet, or codec not detected). Surfaces the\n * runtime decoder placement so the UI can show \"Decoder: <agent>\" without\n * a separate cap call per broker.\n */\n decoderNodeId: z.string().nullable(),\n /**\n * Detected audio track parameters from the RTSP DESCRIBE / SDP. `null`\n * when the stream has no audio track or the broker is in cold start.\n * `supported = false` means the codec was detected but the local\n * decoder pipeline cannot produce PCM chunks (e.g. AAC without the\n * AAC pipeline wired). Surfaced in the UI device-overview so operators\n * can pre-pick the audio-analysis model that matches the codec.\n */\n audio: z.object({\n codec: z.string(),\n sampleRate: z.number(),\n channels: z.number(),\n supported: z.boolean()\n }).nullable().optional()\n});\nconst StreamFormatSchema = z.enum([\"webrtc\", \"hls\", \"mjpeg\", \"rtsp\"]);\nconst StreamInfoSchema = z.object({\n streamId: z.string(),\n format: StreamFormatSchema,\n url: z.string().nullable(),\n active: z.boolean()\n});\nconst streamingEngineCapability = {\n name: \"streaming-engine\",\n scope: \"system\",\n mode: \"singleton\",\n internal: true,\n methods: {\n registerStream: method(\n z.object({ streamId: z.string(), sourceUrl: z.string(), codec: z.string().optional() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n unregisterStream: method(z.object({ streamId: z.string() }), z.void(), { kind: \"mutation\" }),\n getStreamUrl: method(\n z.object({ streamId: z.string(), format: StreamFormatSchema }),\n z.string().nullable()\n ),\n listStreams: method(z.void(), z.array(StreamInfoSchema))\n }\n};\nconst RtspRestreamEntrySchema = z.object({\n brokerId: z.string(),\n url: z.string(),\n mutedUrl: z.string(),\n enabled: z.boolean()\n});\nconst BrokerRtspClientSchema = z.object({\n sessionId: z.string(),\n remoteAddr: z.string(),\n playing: z.boolean(),\n muted: z.boolean(),\n connectedAt: z.number(),\n lastRtpAt: z.number(),\n bytesSent: z.number()\n});\nconst BrokerDecodedClientSchema = z.object({\n tag: z.string(),\n subscribedAt: z.number(),\n maxFps: z.number(),\n framesDelivered: z.number(),\n framesDropped: z.number()\n});\nconst BrokerAudioClientSchema = z.object({\n tag: z.string(),\n subscribedAt: z.number(),\n chunksDelivered: z.number()\n});\nconst BrokerClientsSchema = z.object({\n rtsp: z.array(BrokerRtspClientSchema).readonly(),\n decoded: z.array(BrokerDecodedClientSchema).readonly(),\n audio: z.array(BrokerAudioClientSchema).readonly(),\n pipeClients: z.number(),\n encodedSubscribers: z.number()\n});\nconst PlaceholderReasonSchema = z.enum([\n \"reconnecting\",\n \"sleeping\",\n \"offline\",\n \"disabled\",\n \"waking\"\n]);\nconst VideoCodecTargetSchema = z.enum([\"H264\", \"H265\", \"auto\"]);\nconst AudioCodecTargetSchema = z.enum([\"AAC\", \"Opus\", \"PCMU\", \"none\"]);\nconst MaxResolutionSchema = z.object({\n width: z.number().int().positive(),\n height: z.number().int().positive()\n});\nconst GetStreamWithCodecInputSchema = z.object({\n deviceId: z.number().int().nonnegative(),\n videoCodec: VideoCodecTargetSchema,\n audioCodec: AudioCodecTargetSchema.optional(),\n maxResolution: MaxResolutionSchema.optional(),\n tag: z.string().optional()\n});\nconst RtpSourceSchema = z.object({\n url: z.string(),\n videoCodec: z.enum([\"H264\", \"H265\"]),\n audioCodec: z.string(),\n resolution: MaxResolutionSchema,\n transcoded: z.boolean(),\n encoder: z.string(),\n pipelineKey: z.string()\n});\nconst streamBrokerCapability = {\n name: \"stream-broker\",\n scope: \"system\",\n mode: \"singleton\",\n exposesDeviceSettings: true,\n methods: {\n publishCameraStream: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n camStreamId: z.string().min(1),\n kind: CamStreamKindSchema,\n url: z.string().optional(),\n codec: z.string().optional(),\n resolution: CamStreamResolutionSchema.optional(),\n fps: z.number().positive().optional(),\n label: z.string().optional(),\n deviceFeatures: z.array(z.string()).optional(),\n autoEligible: z.boolean().optional(),\n metadata: z.record(z.string(), z.unknown()).optional()\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n retractCameraStream: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n camStreamId: z.string().min(1)\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n assignProfile: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n profile: CamProfileSchema,\n camStreamId: z.string().min(1)\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n unassignProfile: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n profile: CamProfileSchema\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n listAllCameraStreams: method(\n z.void(),\n z.array(CameraStreamSchema).readonly()\n ),\n listAllProfileSlots: method(\n z.void(),\n z.array(ProfileSlotSchema).readonly()\n ),\n getBrokerStats: method(\n z.object({ brokerId: z.string() }),\n BrokerStatsSchema\n ),\n listClients: method(\n z.object({ brokerId: z.string() }),\n BrokerClientsSchema\n ),\n killClient: method(\n z.object({\n brokerId: z.string(),\n channel: z.enum([\"rtsp\", \"decoded\", \"audio\"]),\n handle: z.string()\n }),\n z.object({ killed: z.boolean() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n restartProfile: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n profile: CamProfileSchema\n }),\n z.object({ success: z.boolean() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n getStreamUrl: method(\n z.object({ streamId: z.string(), format: StreamFormatSchema }),\n z.object({ url: z.string() })\n ),\n /**\n * Shared codec-targeted stream API — see Task #184.\n * Resolution order: source-select → HW transcode → libx264/libx265.\n */\n getStreamWithCodec: method(\n GetStreamWithCodecInputSchema,\n RtpSourceSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n releaseStreamWithCodec: method(\n z.object({ pipelineKey: z.string() }),\n z.object({ released: z.boolean(), refcount: z.number().int().nonnegative() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * ── Decoded audio-chunk plane (Phase 5 / D9) ──────────────────────\n *\n * The serialisable replacement for the live-object `IStreamBroker.\n * onDecodedAudioChunk` callback path. Unlike the video frame plane,\n * audio chunks are tiny (a ~500ms PCM window is a few KB) so they ship\n * their bytes INLINE over tRPC — no shared-memory ring. A consumer:\n *\n * 1. `subscribeAudioChunks({ brokerId, tag })` — the broker registers\n * a per-subscription bounded FIFO queue and returns a\n * `subscriptionId`.\n * 2. polls `pullAudioChunks({ subscriptionId, maxCount })` — drains\n * `DecodedAudioChunk[]` in arrival order (FIFO, no latest-wins\n * drop: an audio gap is audible / breaks an analysis window). The\n * queue is generously sized; it only drops its oldest chunk if a\n * truly stalled consumer lets it overflow.\n * 3. `unsubscribeAudioChunks({ subscriptionId })` on teardown.\n */\n subscribeAudioChunks: method(\n SubscribeAudioChunksInputSchema,\n SubscribeAudioChunksResultSchema,\n { kind: \"mutation\" }\n ),\n pullAudioChunks: method(\n z.object({\n subscriptionId: z.string(),\n maxCount: z.number().int().positive().default(8)\n }),\n z.array(DecodedAudioChunkSchema).readonly()\n ),\n unsubscribeAudioChunks: method(\n z.object({ subscriptionId: z.string() }),\n z.object({ released: z.boolean() }),\n { kind: \"mutation\" }\n ),\n /**\n * ── Shared-memory frame plane (Phase 5 / D9) ──────────────────────\n *\n * The handle-based replacement for the live-object `IStreamBroker.\n * onDecodedFrame` callback path. A consumer:\n *\n * 1. `subscribeFrames({ brokerId, format })` — the broker spins up\n * (or reuses) a `frameSink: 'shm'` decoder session producing that\n * `format` and returns a `subscriptionId`.\n * 2. polls `pullFrameHandles({ subscriptionId, maxCount })` — drains\n * zero-pixel `FrameHandle[]`; each handle is fed to a\n * `FrameRingReader` that opens the named shm segment and reads the\n * pixels back zero-copy.\n * 3. `unsubscribeFrames({ subscriptionId })` on teardown.\n *\n * The broker keeps one shm ring per `(brokerId, format)` actually\n * requested — no broker-side `sharp` conversion. fps throttling is\n * implicit (latest-wins ring reads drop frames for a slow consumer).\n */\n subscribeFrames: method(\n SubscribeFramesInputSchema,\n SubscribeFramesResultSchema,\n { kind: \"mutation\" }\n ),\n pullFrameHandles: method(\n z.object({\n subscriptionId: z.string(),\n maxCount: z.number().int().positive().default(4)\n }),\n z.array(FrameHandleSchema).readonly()\n ),\n unsubscribeFrames: method(\n z.object({ subscriptionId: z.string() }),\n z.object({ released: z.boolean() }),\n { kind: \"mutation\" }\n ),\n setPreBufferDuration: method(\n z.object({ brokerId: z.string(), seconds: z.number().min(0).max(30) }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n getPreBufferInfo: method(\n z.object({ brokerId: z.string() }),\n z.object({ configuredSec: z.number(), bufferedMs: z.number(), packetCount: z.number() })\n ),\n getRtspPort: method(z.void(), z.number()),\n getAllRtspEntries: method(\n z.object({ hostname: z.string().optional() }),\n z.array(RtspRestreamEntrySchema).readonly()\n ),\n getRtspEntry: method(\n z.object({ brokerId: z.string(), hostname: z.string().optional() }),\n RtspRestreamEntrySchema.nullable()\n ),\n regenerateRtspToken: method(\n z.object({ brokerId: z.string() }),\n z.string().nullable(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n setRtspEnabled: method(\n z.object({ brokerId: z.string(), enabled: z.boolean() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n isRtspEnabled: method(\n z.object({ brokerId: z.string() }),\n z.boolean()\n )\n },\n events: {\n onCamStreamDemand: event(z.object({\n deviceId: z.number().int().nonnegative(),\n camStreamId: z.string(),\n profile: CamProfileSchema\n })),\n onCamStreamIdle: event(z.object({\n deviceId: z.number().int().nonnegative(),\n camStreamId: z.string()\n })),\n onRequestStreamSourceRefresh: event(z.object({\n deviceId: z.number().int().nonnegative(),\n camStreamId: z.string(),\n brokerId: z.string()\n }))\n }\n};\nconst cameraStreamsCapability = {\n name: \"camera-streams\",\n scope: \"device\",\n mode: \"singleton\",\n kind: \"wrapper\",\n defaultActive: true,\n deviceTypes: [DeviceType.Camera],\n methods: {\n getCameraStreams: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.array(CameraStreamSchema).readonly()\n ),\n getBrokerStreams: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.array(ProfileSlotSchema).readonly()\n ),\n /**\n * Per-device RTSP restream entries. Returns the broker's published\n * RTSP URLs (one per `${deviceId}/${profile}`) for THIS device only,\n * including the rendered `url` field with the RTSP token applied.\n * Consumers (snapshot wrapper, recording, external probes) use this\n * to pick a stream URL without scanning the whole cluster.\n *\n * The system `stream-broker.getAllRtspEntries({hostname?})` still\n * exists for whole-cluster use cases (admin dashboard, settings\n * exports). This device-scoped accessor is the supported handle for\n * code that already has a `deviceId` in hand — keeps device-keyed\n * filtering server-side and rides the DeviceProxy auto-injection.\n */\n getRtspEntries: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n /** Override hostname embedded in returned URLs. Defaults to the broker's bound address. */\n hostname: z.string().optional()\n }),\n z.array(RtspRestreamEntrySchema).readonly()\n )\n },\n events: {\n /** Fires on publishCameraStream / retractCameraStream. */\n onCamStreamsChanged: event(z.object({\n deviceId: z.number().int().nonnegative(),\n camStreams: z.array(CameraStreamSchema).readonly()\n })),\n /** Fires on assignProfile / unassignProfile / runtime status change. */\n onProfileSlotsChanged: event(z.object({\n deviceId: z.number().int().nonnegative(),\n profileSlots: z.array(ProfileSlotSchema).readonly()\n }))\n },\n /**\n * Per-device live stream-broker state. Persistent settings (RTSP\n * tokens, profile assignments, pre-buffer config, RTSP-enabled toggles,\n * streamingDebug) stay in the broker's addon store — they survive\n * restarts. The slice below carries ONLY what's truly runtime:\n *\n * - `online` — at least one profile slot is currently `'streaming'`.\n * Drivers without a firmware liveness signal (RTSP, ONVIF…) can\n * subscribe and mirror this into `state.deviceStatus.online`.\n * - `slotStatuses` — current `ProfileSlotStatus` per profile,\n * mirroring the runtime-mutable subset of `ProfileSlot`.\n * - `slotErrors` — last error message per profile (only set when the\n * corresponding slot is in `'error'`).\n * - `lastChangedAt` — freshness signal for consumers that want to\n * reason about how stale the slice is.\n *\n * Written by the stream-broker manager on every transition that\n * affects these aggregates. Read via `device.state.cameraStreams.<field>`\n * (BaseDevice proxy) or, cross-process, via\n * `device-state.getCapSlice({deviceId, capName: 'camera-streams'})`.\n * The cap's `onChanged` event fires automatically on each write so\n * subscribers get push semantics for free.\n */\n runtimeState: z.object({\n online: z.boolean(),\n slotStatuses: z.object({\n high: ProfileSlotStatusSchema.optional(),\n mid: ProfileSlotStatusSchema.optional(),\n low: ProfileSlotStatusSchema.optional()\n }),\n slotErrors: z.object({\n high: z.string().optional(),\n mid: z.string().optional(),\n low: z.string().optional()\n }),\n lastChangedAt: z.number()\n })\n};\nconst DiscoveredChildStatusSchema = z.enum([\"online\", \"sleeping\", \"offline\", \"unknown\"]);\nconst DiscoveredChildDeviceSchema = z.object({\n /** Stable, integration-defined identifier. Mirrors Scrypted's `nativeId`. */\n childNativeId: z.string(),\n /** Friendly name as reported by the source (Reolink camera name, ONVIF profile, ...). */\n name: z.string(),\n /** DeviceType the child should be created with on adopt. */\n type: z.enum(DeviceType),\n status: DiscoveredChildStatusSchema,\n /** Free-form integration-specific metadata surfaced in the panel. */\n metadata: z.object({\n model: z.string().optional(),\n serialNumber: z.string().optional(),\n uid: z.string().optional(),\n /** Reolink: 0-based channel index inside the parent NVR/Hub. */\n rtspChannel: z.number().int().nonnegative().optional(),\n isBattery: z.boolean().optional(),\n isDoorbell: z.boolean().optional(),\n isMultifocal: z.boolean().optional()\n }).default({}),\n /**\n * `true` when the framework already created a child device for this\n * `childNativeId` under the current parent. The panel uses it to\n * gate the Add/Remove button and surface the existing `deviceId`.\n */\n alreadyAdopted: z.boolean(),\n /** When `alreadyAdopted=true`, the framework-assigned child device id. */\n adoptedDeviceId: z.number().int().nonnegative().nullable()\n});\nconst DeviceDiscoveryStatusSchema = z.object({\n discovered: z.array(DiscoveredChildDeviceSchema),\n /** Wall-clock ms of the last successful enumeration. */\n lastDiscoveryAt: z.number().int().nonnegative().nullable(),\n /** Last error surfaced from the source (rendered as a banner). */\n lastError: z.string().nullable()\n});\nconst deviceDiscoveryCapability = {\n name: \"device-discovery\",\n scope: \"device\",\n mode: \"singleton\",\n // Hub is the canonical parent. Other integrations (gateway-style)\n // can register against the cap by also targeting their root type.\n deviceTypes: [DeviceType.Hub],\n status: {\n schema: DeviceDiscoveryStatusSchema,\n kind: \"poll\"\n },\n // Mirror status into the per-device runtime-state slice so the panel\n // hydrates from the kernel cache without a round-trip on every open.\n runtimeState: DeviceDiscoveryStatusSchema.extend({\n lastFetchedAt: z.number().int().nonnegative()\n }),\n methods: {\n /**\n * Snapshot of the current `discovered` list. Returns the\n * runtime-state cache — call `refreshDiscovery` first if a\n * fresh round-trip to the source is required.\n */\n listDiscovered: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.array(DiscoveredChildDeviceSchema).readonly()\n ),\n /**\n * Force the integration to re-enumerate and update the\n * runtime-state slice. Returns the freshly-enumerated list (also\n * available via `listDiscovered` post-call).\n */\n refreshDiscovery: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.array(DiscoveredChildDeviceSchema).readonly(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Promote a discovered entry to a real child device. The framework\n * creates the child via `kernel.devices.create()` with\n * `parentDeviceId = parent.id` and seeds the child's config from\n * `childInitialConfig` (driver-defined; usually carries channel +\n * uid + parent reference). Returns the kernel-assigned numeric id.\n */\n adoptDevice: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n childNativeId: z.string(),\n /** Optional override for the child's display name. */\n name: z.string().optional()\n }),\n z.object({\n deviceId: z.number().int().nonnegative(),\n stableId: z.string()\n }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Inverse of `adoptDevice`: removes the child device from the\n * kernel registry. The discovered entry remains in the\n * enumeration (status updates resume) so the operator can re-adopt\n * it later without a fresh refresh.\n */\n releaseDevice: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n childDeviceId: z.number().int().nonnegative()\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst DoorbellStatusSchema = z.object({\n /** Ms epoch of the last press. null = never observed since this provider started. */\n lastPressedAt: z.number().nullable(),\n /** Counter since provider start. Resets on reboot. Useful for metrics/debug. */\n pressCountSinceStart: z.number()\n});\nconst DoorbellPressEventSchema = z.object({\n deviceId: z.number(),\n timestamp: z.number()\n});\nconst doorbellCapability = {\n name: \"doorbell\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Button],\n methods: {},\n events: {\n /**\n * Fires once per physical press. Reolink delivers via Baichuan\n * push (`ReolinkSimpleEvent.type === 'doorbell'`). There is no\n * release/duration — it's a pulse.\n */\n onPressed: { data: DoorbellPressEventSchema }\n },\n status: {\n schema: DoorbellStatusSchema,\n kind: \"push\"\n },\n /**\n * Runtime-state slice — last press timestamp + lifetime press count.\n * Mirrored by the kernel and readable via\n * `device.state.doorbell.value`. UIs can show \"last ring 5m ago\"\n * without subscribing.\n */\n runtimeState: DoorbellStatusSchema\n};\nconst FrameFormatSchema = z.enum([\"jpeg\", \"rgb\", \"bgr\", \"yuv420\", \"gray\"]);\nconst FrameInputSchema = z.object({\n data: z.custom(),\n format: FrameFormatSchema,\n width: z.number(),\n height: z.number(),\n timestamp: z.number()\n});\nconst BoundingBoxSchema = z.object({\n x: z.number(),\n y: z.number(),\n w: z.number(),\n h: z.number()\n});\nconst SpatialDetectionSchema = z.object({\n class: z.string(),\n originalClass: z.string(),\n score: z.number(),\n bbox: BoundingBoxSchema\n});\nconst AudioChunkInputSchema = z.object({\n data: z.instanceof(Float32Array),\n sampleRate: z.number(),\n channels: z.number(),\n timestamp: z.number(),\n /** Originating device id — used by the classifier for per-camera concurrency tracking. */\n deviceId: z.number().optional()\n});\nconst AudioLevelSchema = z.object({\n rms: z.number(),\n dbfs: z.number()\n});\nconst AudioClassificationLabelSchema = z.object({\n /**\n * Primary display class. Depending on how the label was produced\n * this is either the macro category (e.g. `dog`) or the raw\n * backend label (e.g. `Dog bark`). Mirrors `class` on\n * `SpatialDetection`.\n */\n className: z.string(),\n /**\n * Raw backend-native label the classifier actually emitted (e.g.\n * `Dog bark` for YAMNet, `dog_bark` for Apple SoundAnalysis). For\n * macro-aggregated entries this is the top raw contributor. Mirrors\n * `originalClass` on `SpatialDetection`.\n */\n originalClass: z.string().optional(),\n score: z.number()\n});\nconst MotionRegionSchema = z.object({\n bbox: BoundingBoxSchema,\n pixelCount: z.number(),\n intensity: z.number()\n});\nconst MotionAnalysisResultSchema = z.object({\n detected: z.boolean(),\n regionCount: z.number(),\n /** Regions passing minArea filter — used for pipeline triggering. */\n regions: z.array(MotionRegionSchema).readonly(),\n /** All raw regions from CCL before minArea filter — used for UI debug overlay. */\n rawRegions: z.array(MotionRegionSchema).readonly(),\n frameWidth: z.number(),\n frameHeight: z.number(),\n analysisMs: z.number()\n});\nconst motionDetectionCapability = {\n name: \"motion-detection\",\n scope: \"device\",\n mode: \"singleton\",\n kind: \"wrapper\",\n defaultActive: true,\n exposesDeviceSettings: true,\n methods: {\n analyze: method(\n z.object({ deviceId: z.number(), frame: FrameInputSchema }),\n MotionAnalysisResultSchema,\n { kind: \"mutation\" }\n ),\n removeCamera: method(z.object({ deviceId: z.number() }), z.void(), { kind: \"mutation\" }),\n reset: method(z.void(), z.void(), { kind: \"mutation\" })\n },\n events: {\n onMotion: { data: z.object({\n deviceId: z.number(),\n detected: z.boolean(),\n regionCount: z.number()\n }) }\n }\n};\nconst OrchestratorMetricsSchema = z.object({\n activeCameras: z.number(),\n throttledCameras: z.number(),\n avgInferenceTimeMs: z.number(),\n queueDepth: z.number()\n});\nconst CameraMetricsSchema = z.object({\n detectionMode: z.enum([\"disabled\", \"always-on\", \"on-motion\"]),\n configuredFps: z.number(),\n actualFps: z.number(),\n queueDepth: z.number(),\n avgInferenceTimeMs: z.number(),\n droppedFrames: z.number(),\n phase: z.enum([\"idle\", \"watching\", \"active\"])\n});\nconst CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({\n deviceId: z.number()\n});\nconst ModelFormatSchema$1 = z.enum([\"onnx\", \"coreml\", \"openvino\", \"tflite\", \"pt\"]);\nconst PipelineSlotSchema = z.enum([\"detector\", \"cropper\", \"classifier\", \"refiner\", \"audio-classifier\"]);\nconst PipelineEngineChoiceSchema = z.object({\n runtime: z.enum([\"node\", \"python\"]),\n backend: z.string(),\n format: ModelFormatSchema$1,\n device: z.string().optional()\n});\nconst EngineDeviceInfoSchema = z.object({\n id: z.string(),\n label: z.string(),\n description: z.string().optional()\n});\nconst AvailableEngineSchema = z.object({\n engine: PipelineEngineChoiceSchema,\n devices: z.array(EngineDeviceInfoSchema).readonly(),\n defaultDevice: z.string()\n});\nconst PipelineDefaultStepSchema = z.lazy(\n () => z.object({\n addonId: z.string(),\n addonName: z.string(),\n slot: PipelineSlotSchema,\n inputClasses: z.array(z.string()).readonly(),\n outputClasses: z.array(z.string()).readonly(),\n enabled: z.boolean(),\n modelId: z.string(),\n children: z.array(PipelineDefaultStepSchema).readonly(),\n engine: PipelineEngineChoiceSchema.optional(),\n group: z.string().optional(),\n settings: z.record(z.string(), z.unknown()).optional()\n })\n);\nconst PipelineTemplateStepSchema = z.lazy(\n () => z.object({\n addonId: z.string(),\n enabled: z.boolean(),\n modelId: z.string(),\n children: z.array(PipelineTemplateStepSchema).readonly(),\n settings: z.record(z.string(), z.unknown()).optional()\n })\n);\nconst PipelineTemplateSchema$1 = z.object({\n id: z.string(),\n name: z.string(),\n createdAt: z.string(),\n updatedAt: z.string(),\n engine: PipelineEngineChoiceSchema,\n steps: z.array(PipelineTemplateStepSchema).readonly()\n});\nconst PipelineModelOptionSchema = z.object({\n id: z.string(),\n name: z.string(),\n formats: z.record(\n z.string(),\n z.object({ downloaded: z.boolean(), sizeMB: z.number() })\n )\n});\nconst ConfigFieldBridge = z.custom();\nconst PipelineAddonSchemaSchema = z.object({\n id: z.string(),\n name: z.string(),\n slot: PipelineSlotSchema,\n inputClasses: z.array(z.string()).readonly(),\n outputClasses: z.array(z.string()).readonly(),\n childSlots: z.array(PipelineSlotSchema).readonly(),\n models: z.array(PipelineModelOptionSchema).readonly(),\n defaultModelId: z.string(),\n // Per-format model override. Lets an addon declare \"on `coreml` prefer\n // apple-soundanalysis, on `onnx` prefer yamnet-onnx\". The orchestrator's\n // agent-seed routine uses this to pick a modelId that matches the\n // agent's active engine format.\n defaultModelIdByFormat: z.record(z.string(), z.string()).optional(),\n // Whether a freshly-seeded agent starts with this addon `enabled: true`.\n // Absent = true. Operator-controlled after first seed.\n enabledByDefault: z.boolean().optional(),\n defaultConfidence: z.number(),\n group: z.string().optional(),\n configSchema: z.array(ConfigFieldBridge).readonly().optional()\n});\nconst PipelineSlotSchemaSchema = z.object({\n id: PipelineSlotSchema,\n label: z.string(),\n priority: z.number(),\n parentSlot: PipelineSlotSchema.nullable(),\n addons: z.array(PipelineAddonSchemaSchema).readonly()\n});\nconst PipelineSchemaSchema = z.object({\n availableEngines: z.array(AvailableEngineSchema).readonly(),\n selectedEngine: PipelineEngineChoiceSchema,\n slots: z.array(PipelineSlotSchemaSchema).readonly()\n});\nconst DetectorOutputSchema = z.object({\n detections: z.array(SpatialDetectionSchema).readonly(),\n inferenceMs: z.number(),\n modelId: z.string()\n});\nconst PipelineStepInputSchema = z.lazy(\n () => z.object({\n addonId: z.string(),\n modelId: z.string(),\n enabled: z.boolean().default(true),\n children: z.array(PipelineStepInputSchema).optional(),\n settings: z.record(z.string(), z.unknown()).optional()\n })\n);\nconst ReferenceImageEntrySchema = z.object({\n filename: z.string(),\n stepIds: z.array(z.string()).readonly().optional()\n});\nconst ReferenceImageBodySchema = z.object({\n base64: z.string(),\n filename: z.string()\n});\nconst ReferenceAudioEntrySchema = z.object({\n filename: z.string(),\n sizeKb: z.number()\n});\nconst ReferenceAudioBodySchema = z.object({\n base64: z.string()\n});\nconst AudioBackendSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n available: z.boolean(),\n /**\n * Raw classifier labels this backend can emit (e.g. YAMNet's\n * 521-class set or Apple SoundAnalysis's 303-class set). Used by\n * the benchmark UI to populate the `enabledMicroClasses` filter\n * specific to the selected backend without a separate fetch.\n */\n rawLabels: z.array(z.string()).readonly().optional()\n});\nconst AudioCapabilitiesSchema = z.object({\n activeBackend: z.string(),\n availableBackends: z.array(AudioBackendSchema).readonly(),\n sampleRate: z.number(),\n chunkDurationMs: z.number()\n});\nconst DownloadModelResultSchema = z.object({\n filePath: z.string(),\n sizeMB: z.number(),\n durationMs: z.number()\n});\nconst AudioTestResultSchema = z.object({\n success: z.boolean(),\n error: z.string().optional(),\n frame: z.custom().optional()\n});\nconst PipelineConfigBridge = z.custom();\nconst ConfigUISchemaBridge = z.custom();\nconst ConfigUISchemaNullableBridge = z.custom();\nconst InferenceCapabilitiesBridge = z.custom();\nconst ModelAvailabilityListBridge = z.custom();\nconst PipelineRunResultBridge = z.custom();\nconst pipelineExecutorCapability = {\n name: \"pipeline-executor\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n // ── Engine selection ─────────────────────────────────────────────\n // `setEngine` removed in Phase 6c — the stateless-pipeline model\n // picks engine per-camera, not per-node. `getSelectedEngine` is\n // kept read-only so the benchmark + models-page can still show the\n // executor's bootstrap engine; its semantics degrade to \"what the\n // executor would pick by default\" in the stateless world.\n getAvailableEngines: method(z.void(), z.array(PipelineEngineChoiceSchema)),\n getSelectedEngine: method(z.void(), PipelineEngineChoiceSchema),\n getDefaultSteps: method(PipelineEngineChoiceSchema, z.array(PipelineDefaultStepSchema)),\n /**\n * Re-run the platform probe for the inference engine and write the\n * detected runtime / backend / device back into the addon's own\n * global settings store. Returns the engine that was picked so the\n * UI can confirm without a second round-trip. Triggers the standard\n * `requiresRestart` auto-restart flow because all three fields are\n * marked restart-required. Replaces the legacy per-agent\n * `pipeline-orchestrator.reprobeAgentHwAccel` surface for the\n * engine dimension — each addon now owns its own probe.\n */\n reprobeEngine: method(z.void(), PipelineEngineChoiceSchema, { kind: \"mutation\", auth: \"admin\" }),\n // ── Video pipeline step configuration (phase 2c) ─────────────────\n // Per-addonId config the operator tunes on the Pipeline → agent\n // page. Replaces the orchestrator's per-agent\n // `setAgentAddonDefaults` mutation. No `enabled` flag — the cap\n // binding system (wrapper caps + setWrapperActive) decides whether\n // a step runs.\n getVideoPipelineSteps: method(\n z.void(),\n z.record(z.string(), z.object({\n modelId: z.string(),\n settings: z.record(z.string(), z.unknown()).readonly()\n }))\n ),\n setVideoPipelineSteps: method(\n z.object({\n steps: z.record(z.string(), z.object({\n modelId: z.string(),\n settings: z.record(z.string(), z.unknown()).readonly()\n }))\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Global pipeline configuration ────────────────────────────────\n // `setGlobalSteps` removed in Phase 6c — there is no \"global\n // pipeline\" in the stateless model (each camera carries its own\n // steps via the orchestrator's `pipelines/<deviceId>`).\n // `getGlobalSteps` is kept read-only as a benchmark fallback;\n // it returns null in fresh stateless deploys.\n getSchema: method(z.void(), PipelineSchemaSchema),\n getGlobalSteps: method(z.void(), z.array(PipelineDefaultStepSchema).readonly().nullable()),\n getGlobalPipelineConfig: method(z.void(), PipelineConfigBridge),\n getOrchestratorConfigSchema: method(z.void(), ConfigUISchemaBridge),\n // ── Templates ────────────────────────────────────────────────────\n listTemplates: method(z.void(), z.array(PipelineTemplateSchema$1).readonly()),\n saveTemplate: method(\n z.object({\n name: z.string(),\n steps: z.array(PipelineTemplateStepSchema).readonly(),\n engine: PipelineEngineChoiceSchema\n }),\n PipelineTemplateSchema$1,\n { kind: \"mutation\" }\n ),\n updateTemplate: method(\n z.object({\n id: z.string(),\n name: z.string().optional(),\n steps: z.array(PipelineTemplateStepSchema).readonly().optional()\n }),\n PipelineTemplateSchema$1,\n { kind: \"mutation\" }\n ),\n deleteTemplate: method(z.object({ id: z.string() }), z.void(), { kind: \"mutation\" }),\n // ── Inference / detection ────────────────────────────────────────\n getCapabilities: method(z.void(), InferenceCapabilitiesBridge),\n getAddonModels: method(z.object({ addonId: z.string() }), ModelAvailabilityListBridge),\n downloadModel: method(\n z.object({ addonId: z.string(), modelId: z.string(), format: ModelFormatSchema$1 }),\n DownloadModelResultSchema,\n { kind: \"mutation\" }\n ),\n deleteModel: method(\n z.object({ addonId: z.string(), modelId: z.string(), format: ModelFormatSchema$1 }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\" }\n ),\n // NOTE: onDownloadProgress / onPipelineProgress removed in Fase H.4.\n // Consumers subscribe via the generic `live.onEvent` core router with\n // `{category: 'model.download.progress'}` or `{category: 'pipeline.progress'}`\n // — the event bus already handles category filtering, no dedicated\n // pipeline-executor method needed.\n detect: method(\n z.object({ addonId: z.string(), frame: FrameInputSchema, config: z.record(z.string(), z.unknown()).optional() }),\n DetectorOutputSchema\n ),\n // `runFrame` removed in Phase 4 — runtime dispatch now goes through\n // the stateless `runPipeline({engine, steps, frame, deviceId})` path.\n // The runner hydrates `steps` from the orchestrator's attach payload\n // (`pipelines[deviceId]`), so there is no longer an executor-side\n // global \"current pipeline\" for a legacy `runFrame` call to target.\n /**\n * Stateless single-frame execution. Callers (runner, benchmark) pass\n * the complete `engine` + `steps` tree; the executor holds no state\n * about cameras or saved pipelines.\n *\n * `engine` is optional during the migration window to preserve the\n * legacy call shape used by existing benchmark code; once all\n * callers pass it explicitly we make it required.\n *\n * Exactly one of `frame`, `imageBase64`, `referenceImage` must be\n * provided:\n * - `frame`: runtime dispatch path (runner → decoded broker frame).\n * Carries the raw buffer, dimensions, and format; the executor\n * uses it directly without base64 round-tripping.\n * - `imageBase64`: one-shot test path (benchmark ImageTab).\n * - `referenceImage`: named file from the reference-image store.\n */\n runPipeline: method(\n z.object({\n engine: PipelineEngineChoiceSchema.optional(),\n steps: z.array(PipelineStepInputSchema).min(1),\n frame: FrameInputSchema.optional(),\n imageBase64: z.string().optional(),\n /**\n * Binary JPEG bytes — preferred over `imageBase64` on internal\n * hops (hub → forked worker via Moleculer MsgPack) because it\n * skips the 33% base64 overhead + the per-call base64 decode on\n * the detection-pipeline worker. Callers can pass either; exactly\n * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.\n */\n image: z.instanceof(Uint8Array).optional(),\n referenceImage: z.string().optional(),\n deviceId: z.number().optional(),\n sessionId: z.string().optional()\n }),\n PipelineRunResultBridge,\n { kind: \"mutation\" }\n ),\n /**\n * Batched run — N raw frames packed into one cap call. The provider\n * routes the batch through `SharedInferencePool.inferBatch`\n * (`MSG_INFER_BATCH = 0x03`) so the IPC framing and JSON response\n * envelope cost is amortised N:1 vs N concurrent `runPipeline`\n * calls. Single root step + uniform model assumed; trees with crop\n * children fall back to sequential execution.\n *\n * Used by `scripts/bench-scrypted-style.mts` to mirror Scrypted's\n * `detectObjects(media, {batch})` semantics for fair comparison.\n */\n runPipelineBatch: method(\n z.object({\n engine: PipelineEngineChoiceSchema.optional(),\n steps: z.array(PipelineStepInputSchema).min(1),\n frames: z.array(FrameInputSchema).min(1).max(255),\n deviceId: z.number().optional(),\n sessionId: z.string().optional()\n }),\n z.object({\n results: z.array(PipelineRunResultBridge).readonly()\n }),\n { kind: \"mutation\" }\n ),\n // ── Bench frame cache (Python pool-side) ──────────────────────────\n /**\n * Cache a raw frame inside the Python inference pool's memory.\n * Returns a numeric `frameId` that `inferCached` references —\n * subsequent calls send only 5 bytes through the pipe instead of\n * 1.2MB raw data, eliminating the pipe transfer bottleneck.\n */\n cacheFrameInPool: method(\n z.object({\n data: z.instanceof(Uint8Array),\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n format: z.enum([\"rgb\", \"bgr\", \"gray\"])\n }),\n z.object({\n frameId: z.number(),\n width: z.number(),\n height: z.number()\n }),\n { kind: \"mutation\" }\n ),\n /**\n * Run inference on a previously cached frame. Sends only 5 bytes\n * (model_idx + frameId) through the IPC pipe — eliminates the\n * ~35ms per-call overhead of transferring 1.2MB raw data.\n */\n inferCached: method(\n z.object({\n stepId: z.string(),\n frameId: z.number().int()\n }),\n z.record(z.string(), z.unknown()),\n { kind: \"mutation\" }\n ),\n /**\n * Release a cached frame from the Python pool's memory.\n */\n uncacheFrame: method(\n z.object({ frameId: z.number().int() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /** Returns the effective pool tuning (resolved from user overrides + backend defaults). */\n getEffectiveTuning: method(\n z.void(),\n z.object({\n batchMode: z.string(),\n windowMs: z.number(),\n maxBatchSize: z.number(),\n concurrency: z.number()\n })\n ),\n // ── Engine registry / management (stateless-pipeline spec) ────────\n /**\n * List every EngineFactory currently loaded in this executor's RAM,\n * with the models resident and a coarse \"in use\" marker derived from\n * ongoing inference activity. Used by the Pipeline page Engines tab.\n */\n listLoadedEngines: method(\n z.void(),\n z.array(z.object({\n engineKey: z.string(),\n engine: PipelineEngineChoiceSchema,\n modelsLoaded: z.array(z.string()).readonly(),\n inUseByCameras: z.array(z.number()).readonly(),\n /**\n * Origin of this resident factory.\n * - `runtime` — main camera-serving engine (no idle TTL).\n * - `warm-override` — benchmark/test override held in the warm\n * cache; auto-disposed after the idle TTL.\n */\n kind: z.enum([\"runtime\", \"warm-override\"]),\n /** Native pid of the underlying Python pool (null when no pool). */\n poolPid: z.number().nullable(),\n /** ms since this factory was last used (null when not warm-tracked). */\n idleMs: z.number().nullable(),\n /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */\n idleTtlMs: z.number().nullable()\n })).readonly()\n ),\n /** Warm up an engine without running a frame. No-op if already loaded. */\n spinEngine: method(\n z.object({ engine: PipelineEngineChoiceSchema }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Unload an engine from RAM. `force:true` unloads even when cameras\n * are actively using it (they re-spin on next frame). Default is\n * gated — returns `{success:false, reason}` when in use.\n */\n killEngine: method(\n z.object({\n engine: PipelineEngineChoiceSchema,\n force: z.boolean().optional()\n }),\n z.object({ success: z.boolean(), reason: z.string().optional() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Benchmarks & testing ─────────────────────────────────────────\n // Moved to `@camstack/addon-benchmark` as customActions (2026-04-14).\n // The addon exposes runBenchmark / runPipelineTest / listBenchmarkHistory /\n // saveBenchmarkResult / deleteBenchmarkResult / clearBenchmarkHistory via\n // `api.addons.custom.mutate({addonId: 'benchmark', action, input})` and\n // delegates the actual pipeline execution back to this cap's runPipeline.\n // ── Reference media ──────────────────────────────────────────────\n listReferenceImages: method(z.void(), z.array(ReferenceImageEntrySchema).readonly()),\n getReferenceImage: method(z.object({ filename: z.string() }), ReferenceImageBodySchema.nullable()),\n getReferenceAudioFiles: method(z.void(), z.array(ReferenceAudioEntrySchema).readonly()),\n getReferenceAudio: method(z.object({ filename: z.string() }), ReferenceAudioBodySchema.nullable()),\n getAudioCapabilities: method(z.void(), AudioCapabilitiesSchema),\n runAudioTest: method(\n z.object({\n addonId: z.string(),\n modelId: z.string(),\n filename: z.string().optional(),\n // Per-step settings (e.g. `enabledClasses`) sourced from the\n // audio-classifier step's `getConfigSchema()`. The provider\n // applies them to the classification result before returning.\n settings: z.record(z.string(), z.unknown()).optional()\n }),\n AudioTestResultSchema,\n { kind: \"mutation\" }\n ),\n // ── Detection wiring / metrics (from detection-config) ───────────\n getDetectionConfigSchema: method(z.void(), ConfigUISchemaNullableBridge)\n // NOTE: orchestratorStatus / cameraDetectionStatus removed in the\n // pipeline page redesign — UI reads runner metrics directly via\n // perNodePipeline.getLocalMetrics / getCameraMetrics, which forward\n // to the pipeline-runner cap on the target node.\n //\n // NOTE: listBrokers / brokerStatus used to live here too — removed in\n // Fase H.3. Frontends now call `streamBroker.listBrokers` directly and\n // filter by deviceId client-side (brokerId prefix match). The broker\n // collection lives in the stream-broker capability and there is no\n // reason for pipeline-executor to mirror it.\n //\n // NOTE: subscribeLive / subscribeAudioLive removed in Fase H.4.\n // Consumers use the generic `live.onEvent` / `live.onDeviceEvent`\n // with `{category: 'pipeline.progress' | 'pipeline.inference-result'\n // | 'pipeline.audio-inference-result'}`.\n // Per-device pipeline step CRUD (`getDevicePipelineSteps` /\n // `setDevicePipelineSteps` / `clearDevicePipelineSteps`) removed in\n // Phase 4b. The orchestrator owns per-camera pipeline content now\n // (`pipelineOrchestrator.{get,set}CameraPipeline` +\n // `pipelines/<deviceId>` in its addon store). The executor is\n // stateless w.r.t. cameras — it receives `steps` inline on every\n // `runPipeline` call.\n }\n};\nconst ZoneKindEnum = z.enum([\"polygon\", \"tripwire\"]);\nconst PolygonPointSchema = z.object({\n x: z.number(),\n y: z.number()\n});\nconst ZoneSchema = z.object({\n id: z.string(),\n name: z.string(),\n kind: ZoneKindEnum.default(\"polygon\"),\n /** Polygon vertices, fraction of frame (0–1). */\n polygon: z.array(PolygonPointSchema).readonly(),\n /** Visual color for UI rendering. */\n color: z.string().default(\"#3b82f6\")\n});\nconst zonesCapability = {\n name: \"zones\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n listZones: method(\n z.object({ deviceId: z.number() }),\n z.array(ZoneSchema).readonly()\n ),\n addZone: method(\n z.object({ deviceId: z.number(), zone: ZoneSchema }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n removeZone: method(\n z.object({ deviceId: z.number(), zoneId: z.string() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n updateZone: method(\n z.object({ deviceId: z.number(), zone: ZoneSchema }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n },\n /**\n * Runtime-state slice — the live zone catalogue mirrored by the\n * orchestrator on every CRUD mutation. Consumers read via\n * `device.state.zones.value` / `.watch(...)` without round-tripping\n * the cap, and the codegen DeviceProxy auto-wires the reactive\n * handle. Slice shape is `{ zones: Zone[] }` so future extensions\n * (e.g. zone groupings) can sit alongside the polygon list.\n */\n runtimeState: z.object({\n zones: z.array(ZoneSchema).readonly()\n })\n};\nconst motionCooldownMsField = { min: 0, max: 6e4, default: 3e4, step: 500 };\nconst motionFpsField = { min: 1, max: 30, default: 4, step: 1 };\nconst detectionFpsField = { min: 1, max: 30, default: 10, step: 1 };\nconst MotionSourceEnum = z.enum([\"onboard\", \"analyzer\"]);\nconst MotionSourcesSchema = z.array(MotionSourceEnum);\nconst ReportMotionInputSchema = z.object({\n deviceId: z.number(),\n detected: z.boolean(),\n source: MotionSourceEnum.default(\"analyzer\"),\n regions: z.array(MotionRegionSchema).readonly().optional()\n});\nconst RunnerCameraConfigSchema = z.object({\n deviceId: z.number(),\n /**\n * Operator-facing scheduling mode for the SW object detection\n * pipeline. Replaces the legacy 2-state `priority` toggle.\n *\n * - `'disabled'` — runner never subscribes to the substream for\n * detection; phase stays idle. Bindings stay\n * bound; this is the runtime-level off switch.\n * - `'always-on'` — phase starts in `'active'` and never falls\n * back to `'watching'`.\n * - `'on-motion'` — phase starts in `'watching'`; transitions to\n * `'active'` when a motion source fires; falls\n * back to `'watching'` after `motionCooldownMs`.\n */\n detectionMode: z.enum([\"disabled\", \"always-on\", \"on-motion\"]).default(\"on-motion\"),\n /** Audio scheduling mode — same values as `detectionMode`. The\n * audio-analyzer addon reads this to decide whether to subscribe\n * to the audio decoded stream. */\n audioMode: z.enum([\"disabled\", \"always-on\", \"on-motion\"]).default(\"always-on\"),\n motionCooldownMs: z.number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),\n motionFps: z.number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),\n detectionFps: z.number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),\n motionStreamId: z.string(),\n detectionStreamId: z.string(),\n /**\n * Motion sources that can activate the pipeline. At least one must\n * be present. Multiple sources OR-ed: any one firing arms the\n * cooldown timer and transitions watching → active. The same\n * `motionCooldownMs` applies to whichever source(s) fire — the\n * timer rearms on every `reportMotion(true)` and expires after the\n * window, returning the runner to `watching`.\n *\n * - `analyzer`: ML/frame-diff motion detection (motion-wasm or other\n * analyzer providers) running on decoded frames in this runner.\n * - `onboard`: camera-native motion pushes (Reolink Baichuan, ONVIF\n * analytics, Frigate motion). The provider emits ProviderMotion\n * events; the orchestrator forwards to `reportMotion`.\n */\n motionSources: MotionSourcesSchema.default([\"analyzer\"]),\n pipelineEnabled: z.boolean().default(true),\n // ── Stateless-pipeline: content carried with the attach ───────────\n /** Engine choice for video steps (runtime+backend+format). */\n engine: PipelineEngineChoiceSchema.optional(),\n /** Ordered tree of video steps. Absent → runner skips video detection. */\n steps: z.array(PipelineStepInputSchema).readonly().optional(),\n /** Audio classification branch. `enabled:false` disables, null skips. */\n audio: z.object({\n engine: PipelineEngineChoiceSchema,\n modelId: z.string(),\n enabled: z.boolean()\n }).nullable().optional(),\n /**\n * Per-camera detection zones (user + onboard) snapshot at dispatch\n * time. Forwarded so motion-wasm + pipeline-executor running on the\n * runner can apply include/exclude/monitor logic without an extra\n * round-trip to the hub. The orchestrator re-dispatches the camera\n * whenever its `zones` device-state slice changes, so the runner's\n * copy stays in sync. Empty array → no zone filtering.\n */\n zones: z.array(ZoneSchema).readonly().default([])\n});\nconst RunnerCameraDeviceUIFields = [\n {\n key: \"motionSources\",\n type: \"multiselect\",\n label: \"Motion Sources\",\n default: [\"analyzer\"],\n options: [\n { value: \"analyzer\", label: \"Frame-diff Analyzer (motion addon)\" },\n { value: \"onboard\", label: \"Camera Onboard Sensor\" }\n ]\n },\n // Analyzer-only knobs — gated on `motionSources` containing the\n // `analyzer` (frame-diff) source. When the operator picks\n // `onboard`-only (camera-native VMD), running an analyzer pipeline\n // would burn CPU for no signal, so we hide the FPS / cooldown /\n // stream-profile tuning entirely. The dependent section header in\n // the orchestrator reads \"Frame-diff Analyzer\" → these fields\n // disappear together when the source isn't selected.\n {\n key: \"motionFps\",\n type: \"slider\",\n label: \"Motion FPS (analyzer)\",\n min: motionFpsField.min,\n max: motionFpsField.max,\n step: motionFpsField.step,\n default: motionFpsField.default,\n showValue: true,\n unit: \"fps\",\n showWhen: { field: \"motionSources\", includes: \"analyzer\" }\n },\n {\n key: \"detectionFps\",\n type: \"slider\",\n label: \"Detection FPS\",\n min: detectionFpsField.min,\n max: detectionFpsField.max,\n step: detectionFpsField.step,\n default: detectionFpsField.default,\n showValue: true,\n unit: \"fps\"\n },\n // Motion cooldown applies to BOTH analyzer and onboard sources —\n // every reportMotion(true) re-arms the cooldown regardless of the\n // emitting source, so the operator must be able to tune it for\n // onboard-only cameras too. Without this the field silently\n // disappeared when the user picked \"Camera Onboard Sensor\" only.\n {\n key: \"motionCooldownMs\",\n type: \"slider\",\n label: \"Motion Cooldown\",\n description: \"Time without a fresh motion event before the active phase ends. Applies to all motion sources — every motion event re-arms the timer.\",\n min: motionCooldownMsField.min,\n max: motionCooldownMsField.max,\n step: motionCooldownMsField.step,\n default: motionCooldownMsField.default,\n showValue: true,\n unit: \"s\",\n displayScale: 1e3\n }\n];\nconst RunnerLocalLoadSchema = z.object({\n /** Moleculer node id of this runner instance. */\n nodeId: z.string(),\n /** Total cameras currently attached (regardless of phase). */\n attachedCameras: z.number(),\n /** Cameras currently in `active` phase (running detection inference). */\n activeCameras: z.number(),\n /** Average inference FPS across all attached cameras. */\n avgInferenceFps: z.number(),\n /** Average inference latency in ms across all attached cameras. */\n avgInferenceTimeMs: z.number(),\n /** Total queue depth across motion + detection queues. */\n queueDepthTotal: z.number(),\n /** Hardware capability flags reported by this node. */\n hardware: z.object({\n hasGpu: z.boolean(),\n inferenceBackend: z.string().optional(),\n cpuCores: z.number().optional()\n })\n});\nconst RunnerLocalMetricsSchema = z.object({\n nodeId: z.string(),\n activeCameras: z.number(),\n throttledCameras: z.number(),\n avgInferenceTimeMs: z.number(),\n queueDepth: z.number()\n});\nconst pipelineRunnerCapability = {\n name: \"pipeline-runner\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n // ── Camera lifecycle (called by orchestrator) ────────────────────\n /** Attach a camera to this runner. Subscribes to local broker. */\n attachCamera: method(RunnerCameraConfigSchema, z.object({ success: z.literal(true) }), { kind: \"mutation\" }),\n /** Detach a camera. Unsubscribes from local broker, clears queues. */\n detachCamera: method(z.object({ deviceId: z.number() }), z.object({ success: z.literal(true) }), { kind: \"mutation\" }),\n /**\n * Report an external motion event for a camera. Drives the runner's\n * phase machine: every `detected: true` clears + rearms the\n * cooldown timer (`motionCooldownMs`); when the timer expires the\n * camera returns to `watching`. `detected: false` is a no-op —\n * onboard sources never send an explicit clear, the timer is the\n * single closure path.\n *\n * `source` discriminates which motion path triggered the event so\n * the runner can attach the right metadata to the cap-state event\n * (analyzer carries `regions[]`, onboard does not). `regions` is\n * populated only for `source: 'analyzer'` — the analyzer's\n * frame-diff result. Always-on cameras silently ignore\n * reportMotion calls.\n */\n reportMotion: method(\n ReportMotionInputSchema,\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\" }\n ),\n // ── Observability (called by orchestrator + dashboards) ──────────\n /** Return load summary used by the orchestrator's load balancer. */\n getLocalLoad: method(z.void(), RunnerLocalLoadSchema),\n /** Return aggregate runtime metrics for this runner instance. */\n getLocalMetrics: method(z.void(), RunnerLocalMetricsSchema),\n /** Per-camera metrics for cameras attached to this runner. */\n getCameraMetrics: method(z.object({ deviceId: z.number() }), CameraMetricsSchema.nullable()),\n /** All per-camera metrics in one round-trip. */\n getAllCameraMetrics: method(z.void(), z.array(CameraMetricsWithDeviceIdSchema).readonly()),\n /** List the deviceIds currently attached to this runner. */\n getLocalCameras: method(z.void(), z.array(z.number()).readonly())\n // NOTE: Phase 6 (settings redesign) removed `getTuning` / `setTuning`.\n // The four tuning fields are now exposed via the addon-level settings\n // API (`pipeline-runner.getAddonSettings / updateAddonSettings`) and\n // rendered in the admin UI via `NodeAddonsSettingsPanel` instead of\n // the dedicated `NodeTuningTab` that used to call these cap methods.\n }\n};\nconst MotionStatusSchema = z.object({\n detected: z.boolean(),\n /** Ms epoch of the last detected-true observation. Null if never detected. */\n lastDetectedAt: z.number().nullable(),\n /**\n * Ms after which `detected` auto-reverts to false if no fresh push\n * arrives. Mirrors the scrypted-reolink-native default. Null means\n * the provider leaves detected state until a native \"clear\" event.\n */\n autoClearAfterMs: z.number().nullable()\n});\nconst MotionOnMotionChangedDataSchema = z.object({\n deviceId: z.number(),\n detected: z.boolean(),\n timestamp: z.number(),\n source: MotionSourceEnum,\n regions: z.array(MotionRegionSchema).readonly().optional()\n});\nconst motionCapability = {\n name: \"motion\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera, DeviceType.Sensor],\n methods: {\n /**\n * Pull the current motion state synchronously. Convenience shortcut\n * for consumers that don't need the full status object; equivalent\n * to `getStatus()?.detected ?? false`. Will likely be folded into\n * `getStatus` once the auto-injected status surface lands in every\n * consumer.\n */\n isDetected: method(\n z.object({ deviceId: z.number() }),\n z.boolean()\n )\n },\n events: {\n /**\n * Fires every time the runner transitions a camera between\n * `watching` and `active` phases. `source` carries which motion\n * path drove the transition; `regions` is populated only for\n * `source: 'analyzer'` (frame-diff regions from the ML motion\n * detector) — onboard sources don't carry per-frame regions\n * here (camera-provided zones / AI metadata live in dedicated\n * channels: `detection.camera-native`, future zone capability).\n *\n * Consumers that want all motion pushes (even with `detected`\n * unchanged) should subscribe to the status subscription via\n * `device-manager.subscribeDeviceStatusAggregate` instead.\n */\n onMotionChanged: { data: MotionOnMotionChangedDataSchema }\n },\n status: {\n schema: MotionStatusSchema,\n kind: \"push\"\n },\n /**\n * Runtime-state slice — the last observed motion snapshot, mirrored\n * by the kernel and readable cross-process via\n * `device.state.motion.value`. Reads never invoke the provider, so\n * UIs and other addons can poll the cached state safely.\n */\n runtimeState: MotionStatusSchema\n};\nconst MotionTriggerStatusSchema = z.object({\n enabled: z.boolean(),\n /** Ms epoch of the last operator-driven change. */\n lastChangedAt: z.number()\n});\nconst MotionTriggerRuntimeStateSchema = MotionTriggerStatusSchema.extend({\n /** Ms epoch of the last successful camera fetch (0 = never). */\n lastFetchedAt: z.number()\n});\nconst motionTriggerCapability = {\n name: \"motion-trigger\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Light, DeviceType.Siren, DeviceType.Switch],\n methods: {\n setMotionTrigger: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n enabled: z.boolean()\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n },\n events: {\n onMotionTriggerChanged: { data: z.object({\n deviceId: z.number(),\n enabled: z.boolean(),\n lastChangedAt: z.number()\n }) }\n },\n status: {\n schema: MotionTriggerStatusSchema,\n kind: \"command-driven\"\n },\n runtimeState: MotionTriggerRuntimeStateSchema\n};\nconst MotionZoneStatusSchema = z.object({\n enabled: z.boolean(),\n sensitivity: z.number(),\n /** Row-major active-cell grid. Length = gridWidth*gridHeight (see getOptions). */\n cells: z.array(z.boolean()),\n lastFetchedAt: z.number()\n});\nconst MotionZoneOptionsSchema = z.object({\n gridWidth: z.number(),\n gridHeight: z.number(),\n sensitivity: z.object({ min: z.number(), max: z.number(), step: z.number() })\n});\nconst MotionZonePatchSchema = z.object({\n enabled: z.boolean().optional(),\n sensitivity: z.number().optional(),\n cells: z.array(z.boolean()).optional()\n});\nconst motionZonesCapability = {\n name: \"motion-zones\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n deviceConfig: {\n ui: { kind: \"widget\", widgetId: \"host/motion-zones-grid\", tab: \"motion\", label: \"Motion Zones\" }\n },\n methods: {\n getOptions: method(z.object({ deviceId: z.number() }), MotionZoneOptionsSchema),\n setZone: method(\n z.object({ deviceId: z.number(), patch: MotionZonePatchSchema }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n },\n status: { schema: MotionZoneStatusSchema, kind: \"poll\" },\n runtimeState: MotionZoneStatusSchema\n};\nconst AutotrackTargetTypeSchema = z.string().describe(\"Vendor target string (people/vehicle/pet); empty = camera default\");\nconst PtzAutotrackSettingsSchema = z.object({\n targetType: AutotrackTargetTypeSchema,\n stopDelaySeconds: z.number().int().min(0).max(300),\n disappearDelaySeconds: z.number().int().min(0).max(300)\n});\nconst PtzAutotrackTargetOptionSchema = z.object({\n value: z.string(),\n label: z.string()\n});\nconst PtzAutotrackStatusSchema = z.object({\n /** True when autotrack is currently armed on the camera. */\n enabled: z.boolean(),\n /** Ms epoch of the last on/off transition (0 if never observed). */\n lastChangedAt: z.number(),\n /** Currently-applied settings the camera reports. Drivers fill\n * this from the firmware GET so the UI can echo what's *really*\n * active vs the operator-typed values in the settings form. */\n currentSettings: PtzAutotrackSettingsSchema.nullable(),\n /**\n * Target types the camera advertises. Driver-supplied — Reolink\n * exposes `people` / `vehicle` / `pet`, Hikvision exposes\n * `auto` / `human` / `vehicle` when the `<smartTrackingType>` knob\n * is supported. Empty array = vendor doesn't expose a selector\n * (treat as auto-only). The UI renders these as the `targetType`\n * field options without hardcoding a vendor-specific list.\n */\n supportedTargetTypes: z.array(PtzAutotrackTargetOptionSchema)\n});\nconst PtzAutotrackRuntimeStateSchema = PtzAutotrackStatusSchema.extend({\n /** Ms epoch of the last successful camera fetch (0 = never). */\n lastFetchedAt: z.number()\n});\nconst ptzAutotrackCapability = {\n name: \"ptz-autotrack\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n deviceConfig: {\n ui: { kind: \"widget\", widgetId: \"host/ptz-autotrack\", tab: \"ptz\", topTab: true, label: \"Auto-Tracking\", order: 5 }\n },\n methods: {\n /**\n * Read the current on/off state + last-applied settings.\n * Drivers may serve from a cache + refresh on a schedule —\n * callers should NOT poll faster than ~5s.\n */\n getStatus: method(\n z.object({ deviceId: z.number() }),\n PtzAutotrackStatusSchema\n ),\n /**\n * Arm or disarm autotrack. Resolves once the camera has\n * acknowledged the transition; the `onStatusChanged` event\n * fires shortly after with the live state.\n */\n setEnabled: method(\n z.object({ deviceId: z.number(), enabled: z.boolean() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /**\n * Read settings (target type + delays). Mirrors the\n * `getStatus().currentSettings` payload but exposes it as a\n * standalone read for callers that want settings without the\n * status surface around them. `null` until the driver has\n * harvested the firmware state at least once.\n */\n getSettings: method(\n z.object({ deviceId: z.number() }),\n PtzAutotrackSettingsSchema.nullable()\n ),\n /**\n * Update one or more settings. Partial — keys that aren't\n * supplied keep their last persisted value. The driver is\n * responsible for clamping vendor-specific ranges if narrower\n * than the cross-vendor max declared on the schema.\n */\n setSettings: method(\n z.object({\n deviceId: z.number(),\n settings: PtzAutotrackSettingsSchema.partial()\n }),\n z.void(),\n { kind: \"mutation\" }\n )\n },\n events: {\n onStatusChanged: { data: z.object({\n deviceId: z.number(),\n status: PtzAutotrackStatusSchema\n }) }\n },\n status: {\n schema: PtzAutotrackStatusSchema,\n kind: \"command-driven\"\n },\n /**\n * Persistent slice mirrored across restarts. The provider writes\n * here on every successful firmware fetch / settings push;\n * `getStatus` and `getSettings` then read this snapshot synchronously\n * with a stale-driven async refresh in the background. Keeps the\n * fetch / cache / fallback logic out of the four cap methods —\n * they become trampolines over `runtimeState`.\n */\n runtimeState: PtzAutotrackRuntimeStateSchema\n};\nconst StreamProfileSchema = z.enum([\"main\", \"sub\", \"ext\"]);\nconst StreamProfileConfigSchema = z.object({\n width: z.number(),\n height: z.number(),\n codec: z.enum([\"h264\", \"h265\"]),\n framerate: z.number(),\n bitrate: z.number(),\n // kbps\n bitrateMode: z.enum([\"vbr\", \"cbr\"]).optional(),\n encoderProfile: z.enum([\"high\", \"main\", \"baseline\"]).optional(),\n gop: z.number().optional(),\n audio: z.boolean().optional()\n});\nconst StreamParamsStatusSchema = z.object({\n /** Per-profile current config. A profile absent = the camera doesn't have it. */\n main: StreamProfileConfigSchema.optional(),\n sub: StreamProfileConfigSchema.optional(),\n ext: StreamProfileConfigSchema.optional(),\n lastFetchedAt: z.number()\n});\nconst StreamProfileOptionsSchema = z.object({\n resolutions: z.array(z.object({ width: z.number(), height: z.number() })),\n codecs: z.array(z.enum([\"h264\", \"h265\"])),\n framerates: z.array(z.number()),\n /** Allowed bitrate values (kbps). Empty if the camera takes a free range. */\n bitrates: z.array(z.number()),\n /** Optional [min,max] kbps when the camera accepts a continuous range. */\n bitrateRange: z.tuple([z.number(), z.number()]).optional(),\n supportsBitrateMode: z.boolean(),\n supportsEncoderProfile: z.boolean(),\n supportsGop: z.boolean(),\n /** Allowed GOP / keyframe-interval range, in seconds — drives the\n * I-frame-interval selector. Absent when the camera advertises GOP\n * support but no concrete range (callers then fall back to a free\n * numeric input). `{ min, max, step }` per the getOptions convention. */\n gop: z.object({ min: z.number(), max: z.number(), step: z.number() }).optional()\n});\nconst StreamParamsOptionsSchema = z.object({\n main: StreamProfileOptionsSchema.optional(),\n sub: StreamProfileOptionsSchema.optional(),\n ext: StreamProfileOptionsSchema.optional()\n});\nconst StreamProfilePatchSchema = z.object({\n width: z.number().optional(),\n height: z.number().optional(),\n codec: z.enum([\"h264\", \"h265\"]).optional(),\n framerate: z.number().optional(),\n bitrate: z.number().optional(),\n bitrateMode: z.enum([\"vbr\", \"cbr\"]).optional(),\n encoderProfile: z.enum([\"high\", \"main\", \"baseline\"]).optional(),\n gop: z.number().optional(),\n audio: z.boolean().optional()\n});\nconst streamParamsCapability = {\n name: \"stream-params\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n deviceConfig: {\n ui: { kind: \"derived-form\", builderId: \"stream-params\", tab: \"streaming\" }\n },\n methods: {\n getOptions: method(\n z.object({ deviceId: z.number() }),\n StreamParamsOptionsSchema\n ),\n setProfile: method(\n z.object({\n deviceId: z.number(),\n profile: StreamProfileSchema,\n patch: StreamProfilePatchSchema\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Build the `ConfigUISchema` (admin-ui `ConfigFormBuilder` input\n * shape) for this camera's stream-encoder settings — one section per\n * profile (main / sub / ext) with the resolution / codec / framerate\n * / bitrate / bitrate-mode / encoder-profile / GOP controls the\n * firmware actually exposes.\n *\n * Driven by `getOptions` (camera-probed availability) + `getStatus`\n * (current per-profile config); each field's `default` is seeded\n * from the live config so the form renders the camera state in one\n * pass. Returns `null` when the camera exposes no configurable\n * stream property — the renderer then shows the unsupported message.\n *\n * Output is `z.unknown().nullable()` — the same convention every\n * other `ConfigUISchema`-returning cap method uses (`device-ops`,\n * `device-manager`); `ConfigUISchema` is a TS-only type with no\n * companion Zod schema, and a concrete object would collapse\n * unrelated AppRouter branches to `unknown` during codegen.\n */\n getConfigSchema: method(\n z.object({ deviceId: z.number() }),\n z.unknown().nullable()\n )\n },\n status: {\n schema: StreamParamsStatusSchema,\n kind: \"poll\"\n },\n runtimeState: StreamParamsStatusSchema\n};\nconst SwitchStatusSchema = z.object({\n on: z.boolean(),\n /** Ms epoch of the last state change. Useful for UI \"X minutes ago\". */\n lastChangedAt: z.number()\n});\nconst switchCapability = {\n name: \"switch\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Switch, DeviceType.Siren, DeviceType.Light],\n methods: {\n setState: method(\n z.object({ deviceId: z.number(), on: z.boolean() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n },\n events: {\n onStateChanged: { data: z.object({\n deviceId: z.number(),\n on: z.boolean(),\n lastChangedAt: z.number()\n }) }\n },\n status: {\n schema: SwitchStatusSchema,\n kind: \"command-driven\"\n },\n /**\n * Runtime-state slice — the last applied on/off state, mirrored by\n * the kernel. Read via `device.state.switch.value`; UI toggles do\n * not need to re-query the provider after a setState mutation.\n */\n runtimeState: SwitchStatusSchema,\n settings: {\n bindings: [{\n kind: \"scalar\",\n statusPath: \"on\",\n method: \"setState\",\n valueArg: \"on\",\n field: { label: \"On\", kind: \"boolean\" }\n }]\n }\n};\nconst PerScopeBreakdownSchema = z.object({\n /** Total tracked objects in this scope (frame / zone / unzoned). */\n totalObjects: z.number().int().nonnegative(),\n /** Per-class count. Keys are macro class names (e.g. `person`, `car`). */\n byClass: z.record(z.string(), z.number().int().nonnegative())\n});\nconst ZoneScopeBreakdownSchema = PerScopeBreakdownSchema.extend({\n zoneId: z.string(),\n zoneName: z.string(),\n /** TrackIds of objects currently inside this zone — for cross-reference\n * with the per-track detail panel and live overlay. */\n trackIds: z.array(z.string()).readonly()\n});\nconst CameraOccupancySnapshotSchema = z.object({\n /** Frame timestamp of the inference result that produced this snapshot. */\n ts: z.number().int(),\n /** Frame width/height in pixels — let the UI normalize bbox coords. */\n frameWidth: z.number().int().nonnegative(),\n frameHeight: z.number().int().nonnegative(),\n /** Per-zone breakdown — one entry per defined zone (user + onboard). */\n zones: z.array(ZoneScopeBreakdownSchema).readonly(),\n /** Frame-wide aggregate (everywhere, regardless of zone membership). */\n frame: PerScopeBreakdownSchema,\n /** Detections that landed outside every zone. Empty when no zones defined. */\n unzoned: PerScopeBreakdownSchema\n});\nconst HistoryResolutionEnum = z.enum([\"minute\", \"5min\", \"hour\"]);\nconst HistoryRangeSchema = z.object({\n /** Range start (epoch ms, inclusive). */\n from: z.number().int(),\n /** Range end (epoch ms, inclusive). Defaults to \"now\" at query time. */\n to: z.number().int(),\n resolution: HistoryResolutionEnum\n});\nconst HistoryPointSchema = z.object({\n /** Bucket midpoint (epoch ms). */\n ts: z.number().int(),\n /** Object count averaged over the bucket (rounded to nearest integer). */\n count: z.number().int().nonnegative()\n});\nconst zoneAnalyticsCapability = {\n name: \"zone-analytics\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n /** Latest computed occupancy snapshot for this camera. Null when\n * the analytics pipeline hasn't seen a frame for this device yet\n * (no inference result emitted since boot or since binding was\n * activated). */\n getCurrentSnapshot: method(\n z.object({ deviceId: z.number() }),\n CameraOccupancySnapshotSchema.nullable()\n ),\n /** Time-series object count inside one zone. `className` optional —\n * omit to count every class in the zone. */\n getZoneHistory: method(\n z.object({\n deviceId: z.number(),\n zoneId: z.string(),\n className: z.string().optional()\n }).extend(HistoryRangeSchema.shape),\n z.array(HistoryPointSchema).readonly()\n ),\n /** Time-series frame-wide object count (everywhere). */\n getCameraHistory: method(\n z.object({\n deviceId: z.number(),\n className: z.string().optional()\n }).extend(HistoryRangeSchema.shape),\n z.array(HistoryPointSchema).readonly()\n ),\n /** Time-series count of objects outside every zone. */\n getUnzonedHistory: method(\n z.object({\n deviceId: z.number(),\n className: z.string().optional()\n }).extend(HistoryRangeSchema.shape),\n z.array(HistoryPointSchema).readonly()\n )\n },\n /**\n * Runtime-state slice — the latest occupancy snapshot mirrored by\n * the analytics frame processor on every inference result. Consumers\n * read via `device.state.zoneAnalytics.value` and stay in sync\n * automatically; the explicit `getCurrentSnapshot` cap method is\n * still useful for one-off polls without a subscription.\n */\n runtimeState: CameraOccupancySnapshotSchema\n};\nconst ZoneRuleModeEnum = z.enum([\"include\", \"exclude\"]);\nconst ZoneRuleSchema = z.object({\n /** Stable rule id — survives edits, used by the UI for diffing. */\n id: z.string(),\n /** Optional human-readable label rendered in the rule editor. */\n name: z.string().optional(),\n /** Zones this rule targets. The rule's `mode` applies to ALL\n * listed zones (OR-set: a detection in any one of them counts).\n * At least one zone id required — a rule with no targets is a\n * configuration mistake and the form validator rejects it. */\n zoneIds: z.array(z.string()).min(1).readonly(),\n mode: ZoneRuleModeEnum,\n /**\n * Class names this rule applies to. Empty / undefined ⇒ rule\n * applies to every class. Class strings match the `macroClass`\n * field on detections (e.g. `person`, `car`, `dog`).\n */\n classFilter: z.array(z.string()).readonly().optional(),\n /**\n * Minimum bbox/mask overlap (0–1) with any of the rule's zones\n * required to consider an entity \"in the zone\". Defaults to the\n * consumer's stage default when omitted. Kept for back-compat with\n * existing per-rule overrides; new operators pick the value via\n * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is\n * set, the lower-level engine reads it as a 0–1 fraction.\n */\n overlapThreshold: z.number().min(0).max(1).optional(),\n /**\n * Operator-friendly version of `overlapThreshold` — the percentage\n * of the detection's bbox that must lie inside the zone for the\n * rule to match. Documented default is 85%; the engine substitutes\n * that when the field is omitted (kept optional so existing rules\n * stored without it stay valid).\n *\n * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a\n * rule, the engine prefers `bboxInclusionPct` because it's the\n * field exposed in the UI. Internally both feed the same gate.\n */\n bboxInclusionPct: z.number().min(0).max(100).optional(),\n /**\n * When `true` and a detection has a segmentation mask, use the\n * mask for overlap instead of the bbox. Detection-stage only;\n * motion rules ignore this field.\n */\n preferMask: z.boolean().optional(),\n /**\n * Soft-toggle: `false` disables the rule without deleting it.\n * Defaults to `true` so operators creating a rule via the UI\n * see it active immediately.\n */\n enabled: z.boolean().default(true)\n});\nconst ZoneRulesArraySchema = z.array(ZoneRuleSchema).readonly();\nconst ZoneRuleStageEnum = z.enum([\"motion\", \"detection\"]);\nconst zoneRulesCapability = {\n name: \"zone-rules\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n /** Read the full rule list for a given stage (empty when no rules\n * are defined yet). */\n listRules: method(\n z.object({ deviceId: z.number(), stage: ZoneRuleStageEnum }),\n z.array(ZoneRuleSchema).readonly()\n ),\n /** Bulk-replace the rule list for one stage. The provider validates\n * each entry against {@link ZoneRuleSchema} (zoneIds non-empty,\n * thresholds in range) and rejects the whole patch if any entry\n * is invalid — partial writes are a configuration footgun. */\n setRules: method(\n z.object({\n deviceId: z.number(),\n stage: ZoneRuleStageEnum,\n rules: z.array(ZoneRuleSchema).readonly()\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n },\n /**\n * Runtime-state slice — both stages mirrored together so consumers\n * see one reactive handle (`device.state.zoneRules.value`) instead\n * of two. Bulk-replace mutations on either stage write the full\n * `{motion, detection}` shape, so subscribers always get the\n * complete current set. Consumers that only care about one stage\n * just read the matching property.\n */\n runtimeState: z.object({\n motion: z.array(ZoneRuleSchema).readonly(),\n detection: z.array(ZoneRuleSchema).readonly()\n })\n};\nconst ProviderStatusSchema = z.object({\n connected: z.boolean(),\n deviceCount: z.number(),\n error: z.string().optional()\n});\nconst DiscoveredDeviceSchema = z.object({\n externalId: z.string(),\n name: z.string(),\n type: z.string(),\n metadata: z.record(z.string(), z.unknown()).optional()\n});\nconst DiscoveryCandidateSchema = z.object({\n stableId: z.string(),\n type: z.enum(DeviceType),\n suggestedName: z.string(),\n prefilledConfig: z.record(z.string(), z.unknown())\n});\nconst DeviceSummarySchema = z.object({\n id: z.number(),\n stableId: z.string(),\n addonId: z.string(),\n type: z.string(),\n name: z.string(),\n parentDeviceId: z.number().nullable(),\n online: z.boolean(),\n features: z.array(z.string()),\n config: z.record(z.string(), z.unknown())\n});\nconst FieldProbeResultSchema = z.object({\n status: z.enum([\"ok\", \"error\"]),\n labels: z.array(z.string()).optional(),\n error: z.string().optional()\n});\nconst CreationSchemaOutputSchema = z.unknown();\nconst deviceProviderCapability = {\n name: \"device-provider\",\n scope: \"system\",\n mode: \"collection\",\n methods: {\n // ── Lifecycle + introspection ─────────────────────────────────────\n start: method(z.void(), z.void(), { kind: \"mutation\" }),\n stop: method(z.void(), z.void(), { kind: \"mutation\" }),\n getStatus: method(z.void(), ProviderStatusSchema),\n getDevices: method(z.void(), z.array(z.object({\n id: z.string(),\n name: z.string(),\n type: z.string()\n }))),\n // ── Discovery + adoption (optional — see supportsDiscovery) ──────\n supportsDiscovery: method(z.object({}), z.boolean()),\n discoverDevices: method(\n z.object({}),\n z.array(DiscoveryCandidateSchema),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n adoptDiscoveredDevice: method(\n z.object({ candidate: DiscoveryCandidateSchema }),\n DeviceSummarySchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Manual creation (optional — see supportsManualCreation) ──────\n supportsManualCreation: method(z.object({}), z.boolean()),\n /**\n * Fetch the creation form schema for a given DeviceType. Returns\n * `null` when the provider does not support manually creating\n * devices of that type. The output is a `ConfigUISchema` — the\n * router type-asserts it at the boundary.\n */\n getChildCreationSchema: method(\n z.object({ type: z.enum(DeviceType) }),\n CreationSchemaOutputSchema\n ),\n createDevice: method(\n z.object({\n type: z.enum(DeviceType),\n config: z.record(z.string(), z.unknown())\n }),\n DeviceSummarySchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Test a single field in the creation form before the device has\n * been persisted. Typical use: probing an RTSP URL entered by the\n * user. Providers that don't support field probing return\n * `{ success: true, message: 'Field test not supported' }`.\n *\n * `formValues` is the live snapshot of every field in the form at\n * the moment the user clicked Test — useful for probes that depend\n * on multiple fields together (e.g. Reolink autodetect needs host\n * + credentials + UID + transport mode in a single call). Optional\n * for backwards compatibility; providers free to ignore it.\n */\n testCreationField: method(\n z.object({\n type: z.enum(DeviceType),\n key: z.string(),\n value: z.unknown(),\n formValues: z.record(z.string(), z.unknown()).optional()\n }),\n FieldProbeResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst ConfigTabDeclarationSchema = z.object({\n id: z.string(),\n label: z.string(),\n icon: z.string(),\n order: z.number().optional()\n});\nconst ConfigSectionWithValuesSchema = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string().optional(),\n style: z.enum([\"card\", \"accordion\"]).optional(),\n defaultCollapsed: z.boolean().optional(),\n columns: z.union([z.literal(1), z.literal(2), z.literal(3), z.literal(4)]).optional(),\n tab: z.string().optional(),\n // Hoist the section into a top-level device tab. DeviceDetail\n // discovers these from the aggregate and renders one tab per unique\n // `tab` id; the default `'settings'` keeps the section under Config.\n location: z.enum([\"settings\", \"top-tab\"]).optional(),\n order: z.number().optional(),\n fields: z.array(z.any())\n});\nconst SettingsSchemaWithValuesSchema = z.object({\n tabs: z.array(ConfigTabDeclarationSchema).optional(),\n sections: z.array(ConfigSectionWithValuesSchema)\n});\nconst SettingsPatchSchema = z.record(z.string(), z.unknown());\nconst SettingsUpdateResultSchema = z.object({\n success: z.literal(true)\n});\nconst addonSettingsCapability = {\n name: \"addon-settings\",\n scope: \"system\",\n mode: \"singleton\",\n nodeIdMode: \"data\",\n methods: {\n // ── Global-level settings ─────────────────────────────────────────\n //\n // `overlay` — optional preview overlay. When present, the provider\n // hydrates the schema as if the overlay were merged on top of the\n // persisted store (without writing anything). Used by override-mode\n // UIs (benchmark tabs) to get cascade-aware option lists when the\n // operator tweaks an upstream field — e.g. changing engineRuntime\n // from 'python' to 'node' refetches with `overlay: {engineRuntime:\n // 'node'}` so the backend/device dropdowns re-derive.\n getGlobalSettings: method(\n z.object({\n addonId: z.string(),\n nodeId: z.string().optional(),\n overlay: z.record(z.string(), z.unknown()).optional()\n }),\n SettingsSchemaWithValuesSchema.nullable()\n ),\n updateGlobalSettings: method(\n z.object({ addonId: z.string(), nodeId: z.string().optional(), patch: SettingsPatchSchema }),\n SettingsUpdateResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Device-level settings ─────────────────────────────────────────\n getDeviceSettings: method(\n z.object({ addonId: z.string(), deviceId: z.number(), nodeId: z.string().optional() }),\n SettingsSchemaWithValuesSchema.nullable()\n ),\n updateDeviceSettings: method(\n z.object({ addonId: z.string(), deviceId: z.number(), nodeId: z.string().optional(), patch: SettingsPatchSchema }),\n SettingsUpdateResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst AlertSeveritySchema = z.enum([\"info\", \"success\", \"warning\", \"error\"]);\nconst AlertStatusSchema = z.enum([\"active\", \"in-progress\", \"completed\", \"failed\", \"dismissed\"]);\nconst AlertSourceSchema = z.object({\n type: z.string(),\n id: z.string()\n});\nconst AlertSchema = z.object({\n id: z.string(),\n category: z.string(),\n severity: AlertSeveritySchema,\n title: z.string(),\n message: z.string(),\n status: AlertStatusSchema,\n progress: z.number().optional(),\n read: z.boolean(),\n createdAt: z.number(),\n updatedAt: z.number(),\n source: AlertSourceSchema.optional(),\n metadata: z.record(z.string(), z.unknown()).optional()\n});\nconst alertsCapability = {\n name: \"alerts\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n emit: method(AlertSchema, z.void(), { kind: \"mutation\" }),\n update: method(\n z.object({ alertId: z.string(), patch: AlertSchema.partial() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n list: method(\n z.object({ unreadOnly: z.boolean().optional(), limit: z.number().optional() }).optional(),\n z.array(AlertSchema).readonly()\n ),\n getUnreadCount: method(z.void(), z.number()),\n markRead: method(z.object({ alertId: z.string() }), z.void(), { kind: \"mutation\" }),\n markAllRead: method(z.void(), z.void(), { kind: \"mutation\" }),\n dismiss: method(z.object({ alertId: z.string() }), z.void(), { kind: \"mutation\" })\n }\n};\nconst storageCapability = {\n name: \"storage\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n // ── Small-file primitives ────────────────────────────────────────\n // `location` is a ref (type or fully-qualified id). The orchestrator\n // resolves the ref to a concrete `StorageLocation` and dispatches.\n resolve: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string() }),\n z.string()\n ),\n write: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string(), data: z.instanceof(Uint8Array) }),\n z.void(),\n { kind: \"mutation\" }\n ),\n read: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string() }),\n z.instanceof(Uint8Array)\n ),\n exists: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string() }),\n z.boolean()\n ),\n list: method(\n z.object({ location: StorageLocationRefSchema, prefix: z.string().optional() }),\n z.array(z.string()).readonly()\n ),\n delete: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n getAvailableSpace: method(\n z.object({ location: StorageLocationRefSchema }),\n z.number().nullable()\n ),\n // ── Chunked I/O ──────────────────────────────────────────────────\n // Same protocol as `storage-provider` but on the consumer side.\n // Sessions are owned by the orchestrator: it forwards each chunk\n // to the provider that backs the resolved location.\n beginUpload: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string(), sizeBytes: z.number().optional() }),\n z.object({ uploadId: z.string() }),\n { kind: \"mutation\" }\n ),\n writeChunk: method(\n z.object({ uploadId: z.string(), offset: z.number(), data: z.instanceof(Uint8Array) }),\n z.void(),\n { kind: \"mutation\" }\n ),\n finalizeUpload: method(z.object({ uploadId: z.string() }), z.void(), { kind: \"mutation\" }),\n abortUpload: method(z.object({ uploadId: z.string() }), z.void(), { kind: \"mutation\" }),\n beginDownload: method(\n z.object({ location: StorageLocationRefSchema, relativePath: z.string() }),\n z.object({ downloadId: z.string(), sizeBytes: z.number() }),\n { kind: \"mutation\" }\n ),\n readChunk: method(\n z.object({ downloadId: z.string(), offset: z.number(), length: z.number() }),\n z.instanceof(Uint8Array)\n ),\n endDownload: method(z.object({ downloadId: z.string() }), z.void(), { kind: \"mutation\" }),\n // ── Location management ─────────────────────────────────────────\n // The orchestrator's authoritative surface for the admin-UI's\n // storage-locations page. Operators add/edit/test/remove location\n // instances here; `upsertLocation` and `deleteLocation` require\n // superAdmin auth.\n listLocations: method(\n z.object({ type: StorageLocationTypeSchema.optional() }),\n z.array(StorageLocationSchema).readonly()\n ),\n getDefaultLocation: method(\n z.object({ type: StorageLocationTypeSchema }),\n StorageLocationSchema.nullable()\n ),\n upsertLocation: method(\n StorageLocationSchema.omit({ createdAt: true, updatedAt: true }),\n StorageLocationSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n deleteLocation: method(\n z.object({ id: z.string() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n testLocation: method(\n z.object({ id: z.string() }),\n z.object({ ok: z.boolean(), error: z.string().optional() }),\n { auth: \"admin\" }\n ),\n // ── Provider discovery ──────────────────────────────────────────\n // The admin-UI's \"Add location\" wizard shows one entry per\n // registered `storage-provider` collection cap. Each entry is the\n // provider's `getProviderInfo()` blob — stable, addon-driven, no\n // hard-coded list in the UI. The orchestrator gathers them by\n // walking the registry on every call (cheap; the list almost\n // never changes after boot).\n listProviders: method(\n z.void(),\n z.array(z.object({\n providerId: z.string(),\n displayName: z.string(),\n supportedLocationTypes: z.array(StorageLocationTypeSchema).readonly(),\n configSchema: z.unknown()\n })).readonly()\n ),\n // Validate a candidate config against a provider BEFORE persisting.\n // Used by the wizard so operators can preflight a connection\n // (e.g. SFTP credentials, S3 bucket access) without leaving an\n // orphan record behind on failure.\n testConfig: method(\n z.object({\n providerId: z.string(),\n config: z.record(z.string(), z.unknown())\n }),\n z.object({ ok: z.boolean(), error: z.string().optional() }),\n { auth: \"admin\" }\n )\n }\n};\nconst ProviderInfoSchema = z.object({\n providerId: z.string().min(1),\n displayName: z.string().min(1),\n supportedLocationTypes: z.array(StorageLocationTypeSchema).readonly(),\n configSchema: z.unknown()\n});\nconst TestLocationResultSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional()\n});\nconst BeginUploadInputSchema = z.object({\n location: StorageLocationSchema,\n relativePath: z.string(),\n sizeBytes: z.number().optional()\n});\nconst BeginUploadResultSchema = z.object({ uploadId: z.string() });\nconst WriteChunkInputSchema = z.object({\n uploadId: z.string(),\n offset: z.number(),\n data: z.instanceof(Uint8Array)\n});\nconst FinalizeUploadInputSchema = z.object({ uploadId: z.string() });\nconst AbortUploadInputSchema = z.object({ uploadId: z.string() });\nconst BeginDownloadInputSchema = z.object({\n location: StorageLocationSchema,\n relativePath: z.string()\n});\nconst BeginDownloadResultSchema = z.object({\n downloadId: z.string(),\n sizeBytes: z.number()\n});\nconst ReadChunkInputSchema = z.object({\n downloadId: z.string(),\n offset: z.number(),\n length: z.number()\n});\nconst EndDownloadInputSchema = z.object({ downloadId: z.string() });\nconst storageProviderCapability = {\n name: \"storage-provider\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n /** Self-description for the \"Add location\" wizard. */\n getProviderInfo: method(z.void(), ProviderInfoSchema),\n /** Validate config + probe connectivity. Called on add and on edit. */\n testLocation: method(\n z.object({ config: z.record(z.string(), z.unknown()) }),\n TestLocationResultSchema,\n { auth: \"admin\" }\n ),\n // ── Small-file primitives ────────────────────────────────────────\n // The location is passed inline so the orchestrator dispatches\n // without provider-side location state.\n resolve: method(\n z.object({ location: StorageLocationSchema, relativePath: z.string() }),\n z.string()\n ),\n write: method(\n z.object({ location: StorageLocationSchema, relativePath: z.string(), data: z.instanceof(Uint8Array) }),\n z.void(),\n { kind: \"mutation\" }\n ),\n read: method(\n z.object({ location: StorageLocationSchema, relativePath: z.string() }),\n z.instanceof(Uint8Array)\n ),\n exists: method(\n z.object({ location: StorageLocationSchema, relativePath: z.string() }),\n z.boolean()\n ),\n list: method(\n z.object({ location: StorageLocationSchema, prefix: z.string().optional() }),\n z.array(z.string()).readonly()\n ),\n delete: method(\n z.object({ location: StorageLocationSchema, relativePath: z.string() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n getAvailableSpace: method(\n z.object({ location: StorageLocationSchema }),\n z.number().nullable()\n ),\n // ── Chunked upload ──────────────────────────────────────────────\n beginUpload: method(BeginUploadInputSchema, BeginUploadResultSchema, { kind: \"mutation\" }),\n writeChunk: method(WriteChunkInputSchema, z.void(), { kind: \"mutation\" }),\n finalizeUpload: method(FinalizeUploadInputSchema, z.void(), { kind: \"mutation\" }),\n abortUpload: method(AbortUploadInputSchema, z.void(), { kind: \"mutation\" }),\n // ── Chunked download ────────────────────────────────────────────\n beginDownload: method(BeginDownloadInputSchema, BeginDownloadResultSchema, { kind: \"mutation\" }),\n readChunk: method(ReadChunkInputSchema, z.instanceof(Uint8Array)),\n endDownload: method(EndDownloadInputSchema, z.void(), { kind: \"mutation\" })\n }\n};\nconst BackupSubDestinationInfoSchema = z.object({\n /**\n * Sub-id within this addon. Convention `default` for single-\n * destination addons; addons that host many (S3 with N buckets)\n * pick stable per-bucket strings. The orchestrator stitches\n * `<manifestId>:<subId>` for the wire format.\n */\n subId: z.string(),\n displayName: z.string(),\n description: z.string().optional(),\n kind: z.string(),\n triggerSupported: z.boolean(),\n restoreSupported: z.boolean()\n});\nconst BackupDestinationInfoSchema = BackupSubDestinationInfoSchema.extend({\n /** `<addonId>:<subId>` — globally-unique dispatch key. */\n id: z.string(),\n /**\n * Manifest id of the owning addon. The Settings button on the\n * destination card opens that addon's `globalSettingsSchema` panel.\n */\n addonId: z.string(),\n /** Operator-toggled enable flag from the destination-policy table. */\n enabled: z.boolean(),\n /** Operator-defined retention count (archives kept per destination). */\n retentionCount: z.number(),\n /** Operator-defined display label (overrides storage location displayName). */\n label: z.string().optional(),\n /** Newest-archive timestamp from `manifests.json`, or undefined. */\n lastSuccessAt: z.number().optional(),\n /** Newest-archive size from `manifests.json`, or undefined. */\n lastSuccessSizeBytes: z.number().optional(),\n /** Per-destination cron expression. Empty = manual-only (no schedule). */\n cron: z.string().optional(),\n /** ms-epoch of next computed firing for this destination's cron, if any. */\n nextRunAt: z.number().optional(),\n /** ms-epoch of last successful scheduled run (mirrors policy.lastRunAt). */\n lastRunAt: z.number().optional()\n});\nconst BackupArchiveEntrySchema = z.object({\n id: z.string(),\n filename: z.string(),\n createdAt: z.number(),\n sizeBytes: z.number(),\n label: z.string().optional(),\n /** Top-level locations included in the archive (db, addons, tls, …). */\n locations: z.array(z.string()).readonly()\n});\nconst BackupEntrySchema = z.object({\n id: z.string(),\n /** Addon id of the destination that owns this backup (e.g. `local-backup`, `s3-backup`). */\n destinationId: z.string().optional(),\n label: z.string().optional(),\n createdAt: z.number(),\n sizeBytes: z.number(),\n locations: z.array(z.string()).optional()\n});\nconst ArchiveEntrySchema = z.object({\n path: z.string(),\n kind: z.enum([\"file\", \"dir\", \"symlink\"]),\n sizeBytes: z.number(),\n mtime: z.number()\n});\nconst ArchiveManifestSchema = z.object({\n archiveVersion: z.literal(1),\n createdAt: z.number(),\n dataDir: z.string(),\n locations: z.array(z.string()),\n entries: z.array(ArchiveEntrySchema),\n totalBytes: z.number(),\n totalFiles: z.number()\n});\nconst LocationStatSchema = z.object({\n name: z.string(),\n sizeBytes: z.number(),\n fileCount: z.number(),\n present: z.boolean()\n});\nconst backupCapability = {\n name: \"backup\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n /**\n * Flat aggregate of every destination across every registered\n * `backup-destination` provider. This is the orchestrator-side\n * surface; it expands per-addon `listDestinations()` results into\n * one list the UI can render directly.\n */\n listDestinations: method(\n z.void(),\n z.array(BackupDestinationInfoSchema).readonly(),\n { auth: \"admin\" }\n ),\n /**\n * Trigger a backup. Without `destinations` the orchestrator fans\n * out to every destination flagged as enabled in the routing\n * config; with it, only the listed addons receive the archive.\n */\n trigger: method(\n z.object({\n /** Subset of registered `backup-destination` addon ids to write to. */\n destinations: z.array(z.string()).optional(),\n locations: z.array(z.string()).optional(),\n label: z.string().optional()\n }).optional(),\n z.array(BackupEntrySchema).readonly(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Union of every destination's archives, each tagged with `destinationId`. */\n list: method(z.void(), z.array(BackupEntrySchema).readonly(), { auth: \"admin\" }),\n /**\n * Pre-backup snapshot of the well-known locations on disk — sizes\n * + file counts. Powers the opt-in checklist that lets the\n * operator pick which subsections of state get archived.\n */\n listLocations: method(z.void(), z.array(LocationStatSchema).readonly(), { auth: \"admin\" }),\n /**\n * Read the embedded `.camstack-backup-manifest.json` from a\n * previously-created archive. The manifest carries the full\n * file/dir listing with sizes + mtimes — the readdir snapshot\n * the UI shows in the \"Contents\" panel. Returns `null` when the\n * archive predates manifests (created before this feature\n * shipped).\n */\n getEntries: method(\n z.object({ destinationId: z.string(), backupId: z.string() }),\n ArchiveManifestSchema.nullable(),\n { auth: \"admin\" }\n ),\n restore: method(\n z.object({\n destinationId: z.string(),\n backupId: z.string(),\n /**\n * Optional whitelist — only restore these top-level locations\n * from the archive. Default = every location the archive\n * carries (full restore). The boot-time apply hook reads\n * this list and skips entries whose path doesn't start with\n * any of them.\n */\n locations: z.array(z.string()).optional()\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n delete: method(\n z.object({ destinationId: z.string(), backupId: z.string() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * List archives at a single destination. Reads the per-location\n * `manifests.json` and returns one entry per archive (newest\n * first). Powers the destinations-table drill-in in admin UI.\n */\n listArchives: method(\n z.object({ destinationId: z.string() }),\n z.array(BackupArchiveEntrySchema).readonly(),\n { auth: \"admin\" }\n ),\n /**\n * Upsert a per-destination policy row. The `locationId` MUST be\n * the id of an existing `backups`-typed `StorageLocation`. Used\n * by the admin-UI destinations table (enable toggle + retention\n * input + optional label).\n */\n upsertDestinationPolicy: method(\n z.object({\n locationId: z.string(),\n enabled: z.boolean(),\n retentionCount: z.number().int().min(1).max(1e3),\n label: z.string().optional(),\n /**\n * Per-destination cron expression. Empty string clears the\n * schedule (manual-only). Validated server-side via croner;\n * malformed expressions reject the upsert with an actionable\n * message.\n */\n cron: z.string().optional()\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Validate a cron expression and peek the next N firing times.\n * Used by the admin-UI CronEditor to render a live \"next-run\"\n * preview as the operator edits the pattern.\n */\n previewSchedule: method(\n z.object({\n cron: z.string(),\n count: z.number().int().min(1).max(20).optional()\n }),\n z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n nextRuns: z.array(z.number()).readonly()\n })\n )\n }\n};\nconst QueryFilterSchema = z.object({\n where: z.record(z.string(), z.unknown()).optional(),\n whereIn: z.record(z.string(), z.array(z.unknown())).optional(),\n whereBetween: z.record(z.string(), z.tuple([z.unknown(), z.unknown()])).optional(),\n orderBy: z.object({\n field: z.string(),\n direction: z.enum([\"asc\", \"desc\"])\n }).optional(),\n limit: z.number().optional(),\n offset: z.number().optional()\n});\nconst SettingsRecordSchema = z.object({\n id: z.string(),\n data: z.record(z.string(), z.unknown())\n});\nconst CollectionColumnSchema = z.object({\n name: z.string(),\n type: z.enum([\"TEXT\", \"INTEGER\", \"REAL\", \"JSON\", \"BOOLEAN\"]),\n primaryKey: z.boolean().optional(),\n notNull: z.boolean().optional(),\n unique: z.boolean().optional()\n});\nconst CollectionIndexSchema = z.object({\n name: z.string(),\n columns: z.array(z.string()).readonly(),\n unique: z.boolean().optional()\n});\nconst settingsStoreCapability = {\n name: \"settings-store\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n /** Get a single value by key from a collection. */\n get: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), key: z.string() }),\n z.unknown()\n ),\n /** Set a value by key in a collection (upsert). */\n set: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), key: z.string(), value: z.unknown() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /** Get all entries matching an optional filter. */\n query: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), filter: QueryFilterSchema.optional() }),\n z.array(SettingsRecordSchema).readonly()\n ),\n /** Insert a new record. */\n insert: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), record: SettingsRecordSchema }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /** Update an existing record by ID. */\n update: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), id: z.string(), data: z.record(z.string(), z.unknown()) }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /** Delete a record by key/ID. */\n delete: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), key: z.string() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /** Count entries in a collection, optionally filtered. */\n count: method(\n z.object({ namespace: z.string().optional(), collection: z.string(), filter: QueryFilterSchema.optional() }),\n z.number()\n ),\n /** Check if a collection is empty. */\n isEmpty: method(\n z.object({ namespace: z.string().optional(), collection: z.string() }),\n z.boolean()\n ),\n /**\n * Declare a typed (SQL-backed) collection with explicit columns +\n * indexes. Idempotent: re-declaring an existing collection with the\n * same shape is a no-op; shape changes (new columns, new indexes)\n * are applied additively. Subsequent `insert` / `update` / `delete`\n * / `query` calls on this collection use typed columns instead of\n * JSON-blob storage — `record.data` fields are spread across\n * columns, `query.filter.where` matches real columns (no\n * `json_extract` overhead), `orderBy` uses column indexes.\n *\n * Addons call this in `onInitialize` before their first read/write.\n * Collection names should be namespaced by addon (e.g.\n * `pipeline-analytics:object-events`) to avoid cross-addon\n * clashes — no automatic prefix is added.\n */\n declareCollection: method(\n z.object({\n namespace: z.string().optional(),\n collection: z.string(),\n columns: z.array(CollectionColumnSchema).readonly(),\n indexes: z.array(CollectionIndexSchema).readonly().optional()\n }),\n z.void(),\n { kind: \"mutation\" }\n )\n }\n};\nconst LogLevelSchema$1 = z.enum([\"debug\", \"info\", \"warn\", \"error\"]);\nconst LogEntrySchema = z.object({\n timestamp: z.date(),\n level: LogLevelSchema$1,\n scope: z.array(z.string()),\n message: z.string(),\n meta: z.record(z.string(), z.unknown()).optional(),\n tags: z.record(z.string(), z.string()).optional()\n});\nconst logDestinationCapability = {\n name: \"log-destination\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n write: method(LogEntrySchema, z.void(), { kind: \"mutation\" }),\n query: method(\n z.object({\n scope: z.array(z.string()).optional(),\n level: LogLevelSchema$1.optional(),\n since: z.date().optional(),\n until: z.date().optional(),\n limit: z.number().optional(),\n tags: z.record(z.string(), z.string()).optional()\n }),\n z.array(LogEntrySchema).readonly()\n )\n }\n};\nconst StaticDirOutputSchema = z.object({ staticDir: z.string() });\nconst VersionOutputSchema = z.object({ version: z.string() });\nconst adminUiCapability = {\n name: \"admin-ui\",\n scope: \"system\",\n mode: \"singleton\",\n internal: true,\n methods: {\n getStaticDir: method(z.void(), StaticDirOutputSchema),\n getVersion: method(z.void(), VersionOutputSchema)\n }\n};\nconst MethodAccessSchema = z.enum([\"view\", \"create\", \"delete\"]);\nconst AllowedProviderSchema = z.union([z.literal(\"*\"), z.array(z.string())]);\nconst AllowedDevicesSchema = z.record(z.string(), z.union([z.literal(\"*\"), z.array(z.string())]));\nconst CapScopeSchema = z.enum([\"device\", \"system\"]);\nconst TokenScopeSchema = z.discriminatedUnion(\"type\", [\n z.object({\n type: z.literal(\"category\"),\n target: CapScopeSchema,\n access: z.array(MethodAccessSchema).min(1)\n }),\n z.object({\n type: z.literal(\"capability\"),\n target: z.string(),\n access: z.array(MethodAccessSchema).min(1)\n }),\n z.object({\n type: z.literal(\"addon\"),\n target: z.string(),\n access: z.array(MethodAccessSchema).min(1)\n }),\n z.object({\n type: z.literal(\"device\"),\n /**\n * One or more deviceIds (serialised as strings for wire-format\n * consistency with the rest of the union). Matcher accepts if\n * `input.deviceId` ∈ `targets`. Array shape avoids the row-explosion\n * of one scope-per-device when granting access to a set of cameras.\n */\n targets: z.array(z.string()).min(1),\n access: z.array(MethodAccessSchema).min(1)\n })\n]);\nconst UserRecordSchema = z.object({\n id: z.string(),\n username: z.string(),\n passwordHash: z.string(),\n /**\n * Admin bypass. When true, the middleware skips the scope-access\n * check entirely. There is no other axis of privilege; the legacy\n * role enum collapsed onto this boolean in v2.\n */\n isAdmin: z.boolean().default(false),\n allowedProviders: AllowedProviderSchema,\n allowedDevices: AllowedDevicesSchema,\n /**\n * Scopes granted to this user. Admins bypass; their `scopes` is\n * ignored. Non-admins without scopes are locked out of every\n * protected call.\n */\n scopes: z.array(TokenScopeSchema).default([]),\n createdAt: z.number(),\n updatedAt: z.number()\n});\nconst ApiKeyRecordSchema = z.object({\n id: z.string(),\n label: z.string(),\n isAdmin: z.boolean().default(false),\n allowedProviders: AllowedProviderSchema,\n allowedDevices: AllowedDevicesSchema,\n tokenHash: z.string(),\n tokenPrefix: z.string(),\n createdAt: z.number(),\n lastUsedAt: z.number().optional()\n});\nconst ScopedTokenSchema = z.object({\n id: z.string(),\n userId: z.string(),\n name: z.string(),\n tokenHash: z.string(),\n tokenPrefix: z.string(),\n scopes: z.array(TokenScopeSchema),\n // SQLite/JSON storage round-trips undefined → null. Use `nullish` so the\n // schema accepts both `null` (read from disk) and `undefined` (in-memory).\n expiresAt: z.number().nullish(),\n lastUsedAt: z.number().nullish(),\n createdAt: z.number()\n});\nconst SsoBridgeClaimsSchema = z.object({\n userId: z.string(),\n username: z.string(),\n isAdmin: z.boolean(),\n provider: z.string(),\n email: z.string().optional(),\n displayName: z.string().optional(),\n /**\n * Public HTTPS URL of the hub that issued this token. Used by\n * cloud-mode OAuth proxies (Alexa Smart Home Lambda, future Google\n * Home Lambda) to route a request back to the originating hub\n * without holding routing state of their own. The Lambda decodes the\n * JWT WITHOUT verifying the signature — the hub re-verifies on every\n * inbound call so trust still rests with the signing hub.\n */\n hubUrl: z.string().optional(),\n /** Permission scopes baked into the token. Set by the OAuth\n * account-linking grant; absent on ordinary SSO-login tokens. */\n scopes: z.array(TokenScopeSchema).optional(),\n /** OAuth authorization-code binding — set only on `oauth-code` tokens. */\n redirectUri: z.string().optional(),\n integrationId: z.string().optional(),\n /** JWT ID — unique per issued code; consumed-set enforces single-use. */\n jti: z.string().optional(),\n /** OAuth session registry id — set on `oauth-access`/`oauth-refresh`\n * tokens so the verify path can check the session is not revoked. */\n sessionId: z.string().optional()\n});\nconst ssoBridgeCapability = {\n name: \"sso-bridge\",\n scope: \"system\",\n mode: \"singleton\",\n internal: true,\n methods: {\n signBridgeToken: method(\n z.object({\n claims: SsoBridgeClaimsSchema,\n ttlSec: z.number().int().positive().optional()\n }),\n z.object({ token: z.string() })\n ),\n verifyBridgeToken: method(\n z.object({ token: z.string() }),\n SsoBridgeClaimsSchema.nullable()\n )\n }\n};\nconst OauthIntegrationDescriptorSchema = z.object({\n /** Stable id used as the `integration=` query param, e.g. 'export-alexa'. */\n integrationId: z.string(),\n /** Human label rendered on the consent page. */\n displayName: z.string(),\n /** Scopes baked into every token issued for this integration. */\n requestedScopes: z.array(TokenScopeSchema),\n /** Allowed redirect_uri prefixes. /api/oauth2/authorize rejects any\n * redirect_uri that does not start with one of these. Required —\n * an empty list means the integration can never complete linking. */\n allowedRedirectPrefixes: z.array(z.string()).min(1)\n});\nconst oauthIntegrationCapability = {\n name: \"oauth-integration\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n getDescriptor: method(z.void(), OauthIntegrationDescriptorSchema)\n }\n};\nconst PasskeySummarySchema = z.object({\n credentialId: z.string(),\n label: z.string(),\n createdAt: z.number(),\n lastUsedAt: z.number().nullable(),\n transports: z.array(z.string()).default([])\n});\nconst userPasskeysCapability = {\n name: \"user-passkeys\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n beginRegistration: method(\n z.object({ userId: z.string(), username: z.string() }),\n // PublicKeyCredentialCreationOptionsJSON — opaque JSON shape from\n // @simplewebauthn. The browser passes it straight to credentials.create().\n z.object({ optionsJSON: z.record(z.string(), z.unknown()) }),\n { kind: \"mutation\", auth: \"admin\", access: \"create\" }\n ),\n finishRegistration: method(\n z.object({\n userId: z.string(),\n /** RegistrationResponseJSON from the browser. */\n response: z.record(z.string(), z.unknown()),\n /** Operator-visible label (e.g. \"MacBook Touch ID\"). */\n label: z.string()\n }),\n z.object({ success: z.literal(true), credentialId: z.string() }),\n { kind: \"mutation\", auth: \"admin\", access: \"create\" }\n ),\n beginAuthentication: method(\n // userId optional — when absent, the addon emits a \"passkey discovery\"\n // (`allowCredentials: []`) so the browser shows every available\n // credential. When present, only the user's credentials are allowed.\n z.object({ userId: z.string().optional() }),\n z.object({ optionsJSON: z.record(z.string(), z.unknown()) }),\n { kind: \"mutation\", access: \"view\" }\n ),\n finishAuthentication: method(\n z.object({\n /** Required — the user the assertion belongs to (verified). */\n userId: z.string(),\n /** AuthenticationResponseJSON from the browser. */\n response: z.record(z.string(), z.unknown())\n }),\n z.object({ verified: z.boolean() }),\n { kind: \"mutation\", access: \"view\" }\n ),\n listPasskeys: method(\n z.object({ userId: z.string() }),\n z.array(PasskeySummarySchema),\n { auth: \"admin\" }\n ),\n removePasskey: method(\n z.object({ userId: z.string(), credentialId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\", access: \"delete\" }\n )\n }\n};\nconst EmailAddressSchema = z.email();\nconst SendEmailInputSchema = z.object({\n to: z.union([EmailAddressSchema, z.array(EmailAddressSchema).min(1)]),\n cc: z.array(EmailAddressSchema).optional(),\n bcc: z.array(EmailAddressSchema).optional(),\n /** RFC 5322 `From` field. Most relays will reject if the domain\n * isn't authorised — the addon is responsible for substituting a\n * sane default when omitted. */\n from: z.string().optional(),\n /** Optional `Reply-To` override. */\n replyTo: z.string().optional(),\n subject: z.string(),\n /** Plain-text body. Required even when `html` is present (fallback\n * for clients that strip HTML — including most spam filters). */\n text: z.string(),\n /** Optional HTML body. Renders alongside `text` as multi-part. */\n html: z.string().optional()\n});\nconst SendEmailResultSchema = z.object({\n messageId: z.string(),\n accepted: z.array(EmailAddressSchema).default([]),\n rejected: z.array(EmailAddressSchema).default([])\n});\nconst SmtpStatusSchema = z.object({\n /** True iff the addon has successfully verified the relay. */\n ready: z.boolean(),\n /** Operator-visible host string (no credentials). */\n host: z.string(),\n /** Last error message reported by the relay, when not ready. */\n error: z.string().optional(),\n /** Last successful verify timestamp (unix ms). */\n lastVerifiedAt: z.number().optional()\n});\nconst smtpProviderCapability = {\n name: \"smtp-provider\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n providerKind: \"email\",\n methods: {\n sendEmail: method(\n SendEmailInputSchema,\n SendEmailResultSchema,\n { kind: \"mutation\", auth: \"admin\", access: \"create\" }\n ),\n /** Round-trip ping against the SMTP relay (EHLO + AUTH if configured).\n * Used by the operator's \"Test connection\" button. */\n verify: method(\n z.void(),\n SmtpStatusSchema,\n { kind: \"mutation\", auth: \"admin\", access: \"view\" }\n ),\n getStatus: method(\n z.void(),\n SmtpStatusSchema,\n { auth: \"admin\" }\n )\n }\n};\nconst BrokerKindSchema = z.enum([\"external\", \"embedded\"]);\nconst BrokerStatusSchema = z.enum([\n \"connected\",\n \"disconnected\",\n \"auth-failed\",\n \"unreachable\",\n \"tls-error\"\n]);\nconst BrokerInfoSchema = z.object({\n id: z.string(),\n name: z.string(),\n url: z.string(),\n kind: BrokerKindSchema,\n status: BrokerStatusSchema,\n latencyMs: z.number().nullable(),\n error: z.string().optional(),\n /** Embedded brokers only: number of MQTT clients currently connected. */\n connectedClients: z.number().int().nonnegative().optional(),\n /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */\n lastCheckedAt: z.number().optional()\n});\nconst BrokerConnectionDetailsSchema = z.object({\n url: z.string(),\n username: z.string().optional(),\n password: z.string().optional(),\n /**\n * Suggested prefix for `clientId`. Each consumer should suffix this\n * with its own discriminator (addon id, instance id) so reconnects\n * don't kick each other off (MQTT spec: clientId must be unique per\n * broker).\n */\n clientIdPrefix: z.string().optional()\n});\nconst AddBrokerInputSchema = z.object({\n name: z.string().min(1),\n url: z.string().regex(/^(mqtt|mqtts|ws|wss):\\/\\//, \"URL must start with mqtt(s):// or ws(s)://\"),\n username: z.string().optional(),\n password: z.string().optional(),\n clientIdPrefix: z.string().optional()\n});\nconst AddBrokerResultSchema = z.object({\n id: z.string()\n});\nconst IdInputSchema = z.object({ id: z.string() });\nconst TestResultSchema = z.discriminatedUnion(\"ok\", [\n z.object({ ok: z.literal(true), latencyMs: z.number() }),\n z.object({ ok: z.literal(false), error: z.string() })\n]);\nconst StartEmbeddedInputSchema = z.object({\n port: z.number().int().min(1).max(65535).default(1883),\n /** Allow anonymous connect (no username/password). Default: false. */\n allowAnonymous: z.boolean().default(false),\n /** Optional shared username/password for clients. */\n username: z.string().optional(),\n password: z.string().optional()\n});\nconst StartEmbeddedResultSchema = z.object({\n id: z.string(),\n url: z.string()\n});\nconst StatusSchema = z.object({\n brokerCount: z.number(),\n embeddedRunning: z.boolean()\n});\nconst mqttBrokerCapability = {\n name: \"mqtt-broker\",\n scope: \"system\",\n mode: \"collection\",\n providerKind: \"broker\",\n status: { schema: StatusSchema, kind: \"poll\" },\n methods: {\n listBrokers: method(z.void(), z.array(BrokerInfoSchema)),\n getBrokerConfig: method(IdInputSchema, BrokerConnectionDetailsSchema),\n addBroker: method(AddBrokerInputSchema, AddBrokerResultSchema, { kind: \"mutation\" }),\n removeBroker: method(IdInputSchema, z.void(), { kind: \"mutation\" }),\n testConnection: method(IdInputSchema, TestResultSchema, { kind: \"mutation\" }),\n startEmbeddedBroker: method(StartEmbeddedInputSchema, StartEmbeddedResultSchema, { kind: \"mutation\" }),\n stopEmbeddedBroker: method(IdInputSchema, z.void(), { kind: \"mutation\" }),\n getStatus: method(z.void(), StatusSchema)\n }\n};\nconst LinkStateSchema = z.enum([\"unlinked\", \"linked\", \"error\"]);\nconst ExportSetupFieldSchema = z.object({\n label: z.string(),\n value: z.string(),\n /** Mask the value by default + render a reveal toggle (client id, secrets). */\n secret: z.boolean().optional()\n});\nconst ExportSetupSchema = z.object({\n /** A string to render as a scannable QR — HAP `X-HM://…` URI, a pairing URL, etc. Omitted when there's nothing to scan. */\n qr: z.string().optional(),\n /** Label/value rows shown with a copy button (HAP setup code, OAuth URLs, client id, linked-account count, …). */\n fields: z.array(ExportSetupFieldSchema).readonly().optional(),\n /** Free-form operator instructions rendered above the fields. */\n note: z.string().optional()\n});\nconst DeviceExportStatusSchema = z.object({\n linkState: LinkStateSchema,\n exposedDeviceCount: z.number(),\n error: z.string().optional(),\n /**\n * Optional pairing/account info the panel renders in a generic\n * \"Setup\" section. Addon-agnostic — the addon id identifies the\n * export target, never an `ecosystem` key here.\n */\n setup: ExportSetupSchema.optional()\n});\nconst DeviceKindSchema = z.string();\nconst ExposedDeviceSchema = z.object({\n deviceId: z.string(),\n exposedAs: z.string().optional(),\n capabilities: z.array(z.string()).optional()\n});\nconst ExposeInputSchema = z.object({\n deviceId: z.string(),\n capabilities: z.array(z.string()).optional()\n});\nconst UnexposeInputSchema = z.object({ deviceId: z.string() });\nconst deviceExportCapability = {\n name: \"device-export\",\n scope: \"system\",\n mode: \"collection\",\n providerKind: \"device-export\",\n status: { schema: DeviceExportStatusSchema, kind: \"poll\" },\n /**\n * Each export provider contributes its own per-device \"Export\" panel\n * (enabled toggle, preferred stream, addon-specific knobs like the\n * HA-MQTT discovery prefix). The three framework methods\n * `getDeviceSettingsContribution` / `getDeviceLiveContribution` /\n * `applyDeviceSettingsPatch` are auto-injected on the provider\n * interface and routed to the device-details aggregator.\n */\n exposesDeviceSettings: true,\n methods: {\n getStatus: method(z.void(), DeviceExportStatusSchema),\n listSupportedDeviceKinds: method(z.void(), z.array(DeviceKindSchema)),\n listExposedDevices: method(z.void(), z.array(ExposedDeviceSchema)),\n exposeDevice: method(ExposeInputSchema, z.void(), { kind: \"mutation\" }),\n unexposeDevice: method(UnexposeInputSchema, z.void(), { kind: \"mutation\" })\n }\n};\nconst AddonPageDeclarationSchema$1 = z.object({\n id: z.string(),\n label: z.string(),\n icon: z.string(),\n path: z.string(),\n remoteName: z.string(),\n bundle: z.string()\n});\nconst AddonPageInfoSchema = z.object({\n addonId: z.string(),\n page: AddonPageDeclarationSchema$1,\n bundleUrl: z.string()\n});\nconst addonPagesCapability = {\n name: \"addon-pages\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n listPages: method(z.void(), z.array(AddonPageInfoSchema).readonly())\n }\n};\nconst AddonPageDeclarationSchema = z.object({\n id: z.string(),\n label: z.string(),\n icon: z.string(),\n path: z.string(),\n /**\n * Module Federation remote name — must match the `name` field on the\n * page addon's `federation()` plugin config. Used by admin-ui's\n * `<AddonPageLoader>` to call `loadRemote('<remoteName>/page')`.\n * Conventionally `addon_<id>_page` (snake_case; MF names cannot\n * contain hyphens).\n */\n remoteName: z.string(),\n /**\n * Bundle filename inside the addon's `dist/` dir served at\n * `/api/addon-pages/<addonId>/<bundle>`. With Module Federation this\n * is always `'remoteEntry.js'`; the value is kept on the metadata so\n * the static-file route can compute an mtime-based cache-buster URL\n * without a separate filesystem stat.\n */\n bundle: z.string()\n});\nconst addonPagesSourceCapability = {\n name: \"addon-pages-source\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n listPages: method(z.void(), z.array(AddonPageDeclarationSchema).readonly())\n }\n};\nconst WidgetHostEnum = z.enum([\"device-tab\", \"dashboard\", \"integration-detail\"]);\nconst WidgetSizeEnum = z.enum([\"xs\", \"sm\", \"md\", \"lg\", \"xl\"]);\nconst WidgetRemoteSchema = z.object({\n remoteName: z.string(),\n exposedModule: z.string(),\n componentKey: z.string().optional()\n});\nconst WidgetMetadataSchema = z.object({\n // ── UiContribution core (kind:'remote') ──────────────────────────\n /** Primary host tab — `'dashboard'`, `'device-tab'`, or a device-detail tab id. */\n tab: z.string(),\n /** Optional sub-tab within `tab`. */\n subTab: z.string().optional(),\n /** Operator-facing label. */\n label: z.string(),\n /** Ordering within `(tab, subTab)`, ascending. */\n order: z.number().optional(),\n /** Always `'remote'` — a widget is a Module Federation remote. */\n kind: z.literal(\"remote\"),\n /** MF remote descriptor. */\n remote: WidgetRemoteSchema,\n // ── Widget-only metadata ─────────────────────────────────────────\n /** Stable id within the addon — kebab-case. Equals `remote.componentKey`. */\n stableId: z.string(),\n description: z.string().optional(),\n icon: z.string().optional(),\n /**\n * Bundle filename inside the addon's `dist/` dir served at\n * `/api/addon-widgets/<addonId>/<bundle>`. With Module Federation\n * this is always `'remoteEntry.js'` — the value is kept on the\n * metadata so the static-file route can compute an mtime-based\n * cache-buster URL without a separate filesystem stat.\n */\n bundle: z.string(),\n /** Every host the widget supports. The picker filters on this set. */\n hosts: z.array(WidgetHostEnum).readonly(),\n /** Required props the host must supply. Validated at `<WidgetSlot>` mount. */\n requires: z.object({\n deviceContext: z.boolean().default(false),\n integrationContext: z.boolean().default(false)\n }),\n /** Dashboard placement HINTS (operator can override per instance). */\n defaultSize: WidgetSizeEnum.default(\"md\"),\n allowedSizes: z.array(WidgetSizeEnum).readonly().default([\"sm\", \"md\", \"lg\"]),\n defaultColumns: z.number().int().min(1).max(12).default(6),\n defaultRows: z.number().int().min(1).max(12).default(1)\n});\nconst addonWidgetsSourceCapability = {\n name: \"addon-widgets-source\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n listWidgets: method(z.void(), z.array(WidgetMetadataSchema).readonly())\n }\n};\nconst EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({\n addonId: z.string(),\n bundleUrl: z.string()\n});\nconst addonWidgetsCapability = {\n name: \"addon-widgets\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n listWidgets: method(z.void(), z.array(EnrichedWidgetMetadataSchema).readonly())\n }\n};\nconst AddonHttpRouteSchema = z.object({\n method: z.enum([\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\"]),\n path: z.string(),\n access: z.enum([\"public\", \"authenticated\", \"admin\"]).optional(),\n description: z.string().optional()\n});\nconst InvokeRequestSchema = z.object({\n method: z.string(),\n path: z.string(),\n params: z.record(z.string(), z.string()),\n query: z.record(z.string(), z.string()),\n body: z.unknown(),\n headers: z.record(z.string(), z.string()),\n user: z.object({\n id: z.string(),\n username: z.string(),\n isAdmin: z.boolean()\n }).optional(),\n scopedToken: z.unknown().optional()\n});\nconst InvokeReplyEnvelopeSchema = z.object({\n status: z.number().int(),\n headers: z.record(z.string(), z.string()),\n /** When set, the hub MUST `reply.redirect(redirectUrl)` instead of\n * sending `body`. Status defaults to 302 when this is set unless\n * the handler called `reply.code(...)` explicitly. */\n redirectUrl: z.string().nullable(),\n /** JSON-serializable body. `undefined` is treated as \"no body\". */\n body: z.unknown().optional(),\n /** Set when the handler called `reply.type(mime)`. */\n contentType: z.string().optional()\n});\nconst addonRoutesCapability = {\n name: \"addon-routes\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n getRoutes: method(z.void(), z.array(AddonHttpRouteSchema)),\n /**\n * Cross-process dispatch entry point. Forked addons implement this\n * (via `buildAddonRouteProvider`) so the hub's Fastify catch-all\n * can route through Moleculer when the handler lives in a worker.\n *\n * Local addons can implement it for free with the same helper;\n * the hub bypasses the wire on co-located addons.\n */\n invoke: method(InvokeRequestSchema, InvokeReplyEnvelopeSchema, { kind: \"mutation\" })\n }\n};\nconst HWACCEL_OPTIONS = [\n { value: \"auto\", label: \"Auto (defer to probed best)\" },\n { value: \"none\", label: \"Off (software)\" },\n { value: \"videotoolbox\", label: \"VideoToolbox (macOS)\" },\n { value: \"cuda\", label: \"CUDA (NVIDIA)\" },\n { value: \"nvdec\", label: \"NVDEC (NVIDIA legacy)\" },\n { value: \"vaapi\", label: \"VAAPI (Linux Intel/AMD)\" },\n { value: \"qsv\", label: \"QuickSync (Intel)\" },\n { value: \"d3d11va\", label: \"D3D11VA (Windows)\" },\n { value: \"dxva2\", label: \"DXVA2 (Windows legacy)\" },\n { value: \"amf\", label: \"AMF (AMD)\" },\n { value: \"vdpau\", label: \"VDPAU (Linux NVIDIA legacy)\" },\n { value: \"drm\", label: \"DRM (Linux generic)\" }\n];\nconst DEFAULT_DECODER_HWACCEL_CONFIG = {\n hwaccel: \"auto\",\n probedBestHwaccel: \"\"\n};\nconst ShmRingStatsSchema = z.object({\n sessionId: z.string(),\n slotCount: z.number().int(),\n slotByteLength: z.number().int(),\n segmentBytes: z.number().int(),\n budgetMb: z.number().int(),\n framesWritten: z.number().int(),\n getFrameHits: z.number().int(),\n getFrameMisses: z.number().int()\n});\nconst decoderCapability = {\n name: \"decoder\",\n scope: \"system\",\n // Singleton — one decoder per node. `decoder-nodeav` is the default\n // install; operators can swap to a different provider via the\n // binding system's active-addon selection. The old collection shape\n // existed to let node-av + ffmpeg coexist and priority-sort at\n // stream-start; that fallback was dropped once node-av covered the\n // full codec matrix.\n mode: \"singleton\",\n methods: {\n // ── Discovery ─────────────────────────────────────────────────\n supportsCodec: method(z.object({ codec: z.string() }), z.boolean()),\n getInfo: method(z.void(), z.object({\n id: z.string(),\n name: z.string(),\n isPullMode: z.boolean().optional(),\n priority: z.number().optional()\n })),\n // ── Session lifecycle ─────────────────────────────────────────\n // `nodeId` carries the Moleculer nodeID of the decoder provider that\n // owns the session. Brokers store it so they can react to per-agent\n // events (e.g. `pipeline.agent-hwaccel-changed`) and rotate only the\n // sessions that actually live on the affected node.\n createSession: method(DecoderSessionConfigSchema, z.object({ sessionId: z.string(), nodeId: z.string() })),\n destroySession: method(z.object({ sessionId: z.string() }), z.void()),\n // ── Data plane ────────────────────────────────────────────────\n pushPacket: method(z.object({\n sessionId: z.string(),\n packet: EncodedPacketSchema\n }), z.void()),\n openStream: method(z.object({\n sessionId: z.string(),\n url: z.string()\n }), z.void()),\n // ── Output — polling-based frame retrieval ────────────────────\n // `pullFrames` drains the pixel `DecodedFrame[]` of a `frameSink:\n // 'callback'` session. `pullHandles` (Phase 5 / D9) drains the\n // zero-pixel `FrameHandle[]` of a `frameSink: 'shm'` session — the\n // broker hands each handle to a `FrameRingReader` that opens the\n // named segment and reads the pixels back zero-copy. A session is\n // one mode or the other; the unmatched method returns an empty\n // array.\n pullFrames: method(z.object({\n sessionId: z.string(),\n maxCount: z.number().default(1)\n }), z.array(DecodedFrameSchema)),\n pullHandles: method(z.object({\n sessionId: z.string(),\n maxCount: z.number().default(1)\n }), z.array(FrameHandleSchema)),\n // ── Frame fetch (Phase 5 / D9 downstream access) ──────────────\n // Read the pixels a FrameHandle refers to from this node's shm ring.\n // Returns null when the slot was already recycled (latest-wins).\n getFrame: method(z.object({ handle: FrameHandleSchema }), DecodedFrameSchema.nullable()),\n // shm ring usage stats for a session.\n getShmStats: method(z.object({ sessionId: z.string() }), ShmRingStatsSchema.nullable()),\n // ── Control ───────────────────────────────────────────────────\n updateConfig: method(z.object({\n sessionId: z.string(),\n config: DecoderSessionConfigSchema.partial()\n }), z.void()),\n getStats: method(z.object({ sessionId: z.string() }), DecoderStatsSchema),\n // ── Inventory — session-level state ONLY ─────────────────────\n // Sessions are a decoder concept, so `listActiveSessions` lives\n // here. Process-level measurements (memory/cpu) go through the\n // generic `metrics-provider` cap — decoder stays free of\n // observability concerns that aren't specific to decoding.\n listActiveSessions: method(z.void(), z.array(z.object({\n sessionId: z.string(),\n codec: z.string(),\n outputFormat: z.string(),\n createdAtMs: z.number()\n })).readonly()),\n /**\n * Re-run the host platform-probe for the decoder's hwaccel backend\n * and write the detected value into the addon's own global\n * settings (`probedBestHwaccel`). Replaces the legacy per-agent\n * `pipeline-orchestrator.reprobeAgentHwAccel` — each decoder addon\n * now owns its own probe.\n *\n * Returns the backend the probe picked (`'none'` = software-only\n * host, otherwise one of `HwAccelBackend`). The operator's\n * `hwaccel` setting (auto / none / backend) is not touched; only\n * the `probedBestHwaccel` hint.\n */\n reprobeHwaccel: method(\n z.void(),\n z.object({ backend: z.string() }),\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst RegisteredStreamSchema = z.object({\n streamId: z.string(),\n label: z.string().optional(),\n codec: z.string(),\n type: z.enum([\"video\", \"audio\"]),\n sourceUrl: z.string()\n});\nconst ExposedResourceSchema = z.object({\n streamId: z.string(),\n format: z.string(),\n value: z.string()\n});\nconst restreamerCapability = {\n name: \"restreamer\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n registerDevice: method(\n z.object({ deviceId: z.number(), streams: z.array(RegisteredStreamSchema).readonly() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n unregisterDevice: method(z.object({ deviceId: z.number() }), z.void(), { kind: \"mutation\" }),\n getExposedResources: method(\n z.object({ deviceId: z.number() }),\n z.array(ExposedResourceSchema).readonly()\n )\n }\n};\nconst webrtcClientHintsSchema = z.object({\n viewportWidth: z.number().int().positive().optional(),\n viewportHeight: z.number().int().positive().optional(),\n devicePixelRatio: z.number().positive().optional(),\n /** navigator.connection.downlink — Mbps the browser estimates. */\n downlinkMbps: z.number().nonnegative().optional(),\n /** Hard tier override; takes precedence over scoring when registered. */\n prefersTier: z.string().optional()\n}).partial();\nconst webrtcCapability = {\n name: \"webrtc\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n handleOffer: method(\n z.object({ streamId: z.string(), sdpOffer: z.string() }),\n z.string(),\n { kind: \"mutation\" }\n ),\n supportsStream: method(z.object({ streamId: z.string() }), z.boolean()),\n registerStream: method(\n z.object({ streamId: z.string(), codec: z.string() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n unregisterStream: method(z.object({ streamId: z.string() }), z.void(), { kind: \"mutation\" }),\n /**\n * Two-step server-offer signaling. `hints` is optional — providers\n * that don't care about adaptive source selection ignore it.\n */\n createSession: method(\n z.object({\n streamId: z.string(),\n hints: webrtcClientHintsSchema.optional()\n }),\n z.object({ sessionId: z.string(), sdpOffer: z.string() }),\n { kind: \"mutation\" }\n ),\n handleAnswer: method(\n z.object({ sessionId: z.string(), sdpAnswer: z.string() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n closeSession: method(z.object({ sessionId: z.string() }), z.void(), { kind: \"mutation\" }),\n /**\n * Whether this provider supports adaptive bitrate for the given stream.\n * Currently always false — adaptive selection is one-shot at session\n * start, not in-session encoder switching. Phase 5 plans to layer\n * encoder-driven adaptation on top.\n */\n hasAdaptiveBitrate: method(\n z.object({ streamId: z.string() }),\n z.boolean()\n )\n }\n};\nconst WebrtcStreamTargetSchema = z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"adaptive\") }),\n z.object({ kind: z.literal(\"profile\"), profile: CamProfileSchema }),\n z.object({ kind: z.literal(\"cam-stream\"), camStreamId: z.string().min(1) })\n]);\nconst WebrtcStreamChoiceSchema = z.object({\n /** Stable id for React keys / dropdowns (e.g. `'adaptive'`, `'profile:high'`, `'stream:native:main'`). */\n id: z.string(),\n /** Display label. */\n label: z.string(),\n /** Discriminated target — pass straight to `createSession`. */\n target: WebrtcStreamTargetSchema,\n /** Codec of the underlying broker stream (null for adaptive). */\n codec: z.string().nullable(),\n /** Resolution of the underlying stream (null for adaptive). */\n resolution: z.object({ width: z.number(), height: z.number() }).nullable(),\n /** Broker status (null for adaptive). */\n status: z.enum([\"idle\", \"connecting\", \"streaming\", \"error\", \"stopped\"]).nullable(),\n /** Input FPS from the camera (null for adaptive). */\n inputFps: z.number().nullable(),\n /** Decoded FPS (null for adaptive). */\n decodeFps: z.number().nullable(),\n /** Bitrate in kbps (null for adaptive). */\n bitrateKbps: z.number().nullable()\n});\nconst webrtcSessionCapability = {\n name: \"webrtc-session\",\n scope: \"device\",\n mode: \"singleton\",\n kind: \"wrapper\",\n defaultActive: true,\n deviceTypes: [DeviceType.Camera],\n methods: {\n /**\n * List available WebRTC streams for a device.\n * Returns adaptive (if any profile is assigned) + each assigned profile\n * with codec/resolution info. UI renders this directly — no hardcoded\n * profile names needed.\n */\n listStreams: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.array(WebrtcStreamChoiceSchema)\n ),\n /**\n * Open a WebRTC session against a specific target on the device.\n * `target.kind` discriminates between adaptive selection, a profile\n * slot, or a specific cam stream source — see `WebrtcStreamTarget`.\n * The server resolves the target to a live broker; clients never\n * build or parse brokerId strings.\n */\n createSession: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n target: WebrtcStreamTargetSchema,\n hints: webrtcClientHintsSchema.optional()\n }),\n z.object({ sessionId: z.string(), sdpOffer: z.string() }),\n { kind: \"mutation\" }\n ),\n /**\n * Accept a CLIENT-generated SDP offer and return the server's\n * SDP answer. Mirrors the WHEP / Alexa\n * `Alexa.RTCSessionController.InitiateSessionWithOffer` direction\n * (client offers, server answers) — the dual of `createSession`,\n * which has the server offer first.\n *\n * `target` defaults to the device's adaptive selection when\n * omitted; an optional `sessionId` lets the client provide its\n * own correlation id (Alexa supplies one in the directive\n * payload). The returned `sessionId` is whatever the server uses\n * to track the session and accepts via `closeSession`.\n */\n handleOffer: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n target: WebrtcStreamTargetSchema.optional(),\n sdpOffer: z.string(),\n sessionId: z.string().optional()\n }),\n z.object({ sessionId: z.string(), sdpAnswer: z.string() }),\n { kind: \"mutation\" }\n ),\n handleAnswer: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n sessionId: z.string(),\n sdpAnswer: z.string()\n }),\n z.void(),\n { kind: \"mutation\" }\n ),\n closeSession: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n sessionId: z.string()\n }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /** Whether the underlying provider supports adaptive bitrate for this profile. */\n hasAdaptiveBitrate: method(\n z.object({\n deviceId: z.number().int().nonnegative(),\n profile: CamProfileSchema\n }),\n z.boolean()\n )\n }\n};\nconst CameraPipelineConfigSchema = z.object({\n engine: PipelineEngineChoiceSchema,\n steps: z.array(PipelineStepInputSchema).readonly(),\n audio: z.object({\n engine: PipelineEngineChoiceSchema,\n modelId: z.string(),\n enabled: z.boolean(),\n settings: z.record(z.string(), z.unknown()).readonly().optional()\n }).nullable().optional()\n});\nconst PipelineTemplateSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string().optional(),\n config: CameraPipelineConfigSchema,\n createdAt: z.string(),\n updatedAt: z.string()\n});\nconst AgentAddonConfigSchema = z.object({\n enabled: z.boolean(),\n modelId: z.string(),\n settings: z.record(z.string(), z.unknown()).readonly()\n});\nconst AgentPipelineSettingsSchema = z.object({\n addonDefaults: z.record(z.string(), AgentAddonConfigSchema).readonly()\n});\nconst CameraPipelineForAgentSchema = z.object({\n steps: z.array(PipelineStepInputSchema).readonly(),\n audio: z.object({\n modelId: z.string(),\n enabled: z.boolean()\n }).nullable()\n});\nconst CameraStepOverridePatchSchema = z.object({\n enabled: z.boolean().optional(),\n modelId: z.string().optional(),\n settings: z.record(z.string(), z.unknown()).readonly().optional()\n});\nconst CameraPipelineSettingsSchema = z.object({\n pinnedAgentNodeId: z.string().optional(),\n stepToggles: z.record(z.string(), z.boolean()).optional(),\n stepOverridesByAgent: z.record(\n z.string(),\n z.record(z.string(), CameraStepOverridePatchSchema)\n ).optional(),\n pipelineByAgent: z.record(z.string(), CameraPipelineForAgentSchema).optional()\n});\nconst PipelineAssignmentSchema = z.object({\n deviceId: z.number(),\n /** Moleculer node id of the runner currently responsible for this camera. */\n agentNodeId: z.string(),\n /** True when the assignment was set manually, false when chosen by the balancer. */\n pinned: z.boolean(),\n /** Why this assignment was made — useful for debugging the load balancer. */\n reason: z.enum([\"manual\", \"capacity\", \"hardware-affinity\", \"failover\", \"rebalance\"]),\n /** Unix timestamp (ms) when the assignment was last updated. */\n assignedAt: z.number()\n});\nconst DecoderAssignmentSchema = z.object({\n deviceId: z.number(),\n /** Moleculer node id of the decoder provider currently responsible for this camera. */\n decoderNodeId: z.string(),\n /** True when the assignment was set manually via `assignDecoder`, false when chosen by the balancer. */\n pinned: z.boolean(),\n /** Why this assignment was made — useful for debugging the decoder balancer. */\n reason: z.enum([\"manual\", \"co-located\", \"capacity\", \"hardware-affinity\"])\n});\nconst AgentLoadSummarySchema = z.object({\n nodeId: z.string(),\n online: z.boolean(),\n load: RunnerLocalLoadSchema,\n /** Computed score used by the L2 capacity balancer (lower = less loaded). */\n score: z.number()\n});\nconst GlobalMetricsSchema = z.object({\n totalAgents: z.number(),\n onlineAgents: z.number(),\n totalCameras: z.number(),\n attachedCameras: z.number(),\n activeCameras: z.number(),\n /** Average inference time across all agents weighted by their camera count. */\n avgInferenceTimeMs: z.number(),\n /** Total queue depth across all agents. */\n queueDepth: z.number()\n});\nconst CapabilityBindingsSchema = z.record(z.string(), z.string());\nconst pipelineOrchestratorCapability = {\n name: \"pipeline-orchestrator\",\n scope: \"system\",\n mode: \"singleton\",\n exposesDeviceSettings: true,\n methods: {\n // ── Pipeline placement overrides ────────────────────────────────────\n /**\n * Pin a camera's pipeline to a specific agent (L1 affinity).\n * The orchestrator re-evaluates the assignment immediately.\n */\n assignPipeline: method(\n z.object({ deviceId: z.number(), agentNodeId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Clear a camera's pipeline pin and let the auto-balancer re-pick\n * the optimal agent. The orchestrator persists `preferredAgent=null`\n * (and `pipelineNodeId='auto'`), then re-runs the balancer with the\n * cached `RunnerCameraConfig` and migrates only when the chosen\n * node differs. The camera stays in `getPipelineAssignments()` —\n * just with `pinned=false`. If no runner is currently available\n * (cluster-wide), the camera is left unassigned but the cached\n * config is kept so the next dispatch event re-attaches it.\n */\n unassignPipeline: method(\n z.object({ deviceId: z.number() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Trigger a full rebalance pass. Iterates over all assigned cameras,\n * recomputes the optimal agent for each one based on current load +\n * hardware affinity, and migrates cameras whose current agent is no\n * longer optimal. Pinned cameras are never migrated.\n */\n rebalance: method(z.void(), z.object({ migrated: z.number() }), { kind: \"mutation\", auth: \"admin\" }),\n // ── Observability ────────────────────────────────────────────────\n /** Get the full camera-to-agent assignment map. */\n getPipelineAssignments: method(z.void(), z.array(PipelineAssignmentSchema).readonly()),\n /** Get one camera's assignment, or null if unassigned. */\n getPipelineAssignment: method(z.object({ deviceId: z.number() }), PipelineAssignmentSchema.nullable()),\n /** Get per-agent load summaries used by the load balancer + dashboards. */\n getAgentLoad: method(z.void(), z.array(AgentLoadSummarySchema).readonly()),\n /** Aggregate global metrics across the whole detection cluster. */\n getGlobalMetrics: method(z.void(), GlobalMetricsSchema),\n /**\n * Per-camera live metrics (phase, fps, inference, queue, drops).\n * The orchestrator owns the device→agent assignment map and is the\n * canonical place to ask \"give me the metrics for this camera\". It\n * resolves the agent that holds the camera and delegates to that\n * runner's `getCameraMetrics`. Returns null if the device is not\n * assigned or the runner has no record for it (e.g. the camera was\n * just dispatched and the runner hasn't received the first frame).\n */\n getCameraMetrics: method(z.object({ deviceId: z.number() }), CameraMetricsSchema.nullable()),\n // ── Capability bindings (which addon implements each cap on each node) ──\n /** Read the capability binding map for one node. Empty record = no overrides (first-registered wins). */\n getCapabilityBindings: method(z.object({ nodeId: z.string() }), CapabilityBindingsSchema),\n /** Set the addon that implements `capName` on `nodeId`. Emits `capability.binding-changed`. */\n setCapabilityBinding: method(\n z.object({ nodeId: z.string(), capName: z.string(), addonId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Decoder scheduling ─────────────────────────────────────────────\n /** Pin a device's decoder to a specific node. */\n assignDecoder: method(\n z.object({ deviceId: z.number(), nodeId: z.string() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Clear a device's decoder pin (revert to auto). */\n unassignDecoder: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Get every camera's decoder placement. */\n getDecoderAssignments: method(z.void(), z.array(DecoderAssignmentSchema).readonly()),\n // ── Audio scheduling ───────────────────────────────────────────────\n /** Pin a device's audio analysis to a specific cluster node. */\n assignAudio: method(\n z.object({ deviceId: z.number(), nodeId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Clear a device's audio node pin (revert to auto load-balanced). */\n unassignAudio: method(\n z.object({ deviceId: z.number() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Get the current audio assignment for one device, or null if not yet assigned. */\n getAudioAssignment: method(\n z.object({ deviceId: z.number() }),\n z.object({\n nodeId: z.string(),\n pinned: z.boolean(),\n assignedAt: z.number()\n }).nullable()\n ),\n /** Get per-node audio load (device counts) for all known audio-analyzer nodes. */\n getAudioNodeLoad: method(\n z.void(),\n z.array(z.object({ nodeId: z.string(), deviceCount: z.number() }))\n ),\n /** Get all current audio assignments across all devices. */\n getAudioAssignments: method(\n z.void(),\n z.array(z.object({\n deviceId: z.number(),\n nodeId: z.string(),\n pinned: z.boolean(),\n assignedAt: z.number()\n }))\n ),\n /**\n * Get one camera's decoder placement (computed if not yet pinned).\n * Consumed by `stream-broker.createBroker` so decoder provider\n * selection is deterministic — fixes the 2026-04-18 race where\n * `capProviders[0]` silently picked ffmpeg-on-agent-0 for a\n * hub-assigned camera.\n *\n * `pipelineNodeId` is the node already chosen to run inference for\n * this camera. When provided, the balancer prefers co-location with\n * it; omitted → falls back to the last known assignment in the\n * `assignments` map and finally to 'hub'.\n */\n getDecoderAssignment: method(\n z.object({\n deviceId: z.number(),\n pipelineNodeId: z.string().optional()\n }),\n DecoderAssignmentSchema\n ),\n // NOTE: the `getDeviceOrchestrationSettings`,\n // `getDeviceOrchestrationOverrides` and `getGlobalOrchestrationSettings`\n // methods were removed in Phase 6. Consumers now read settings via\n // the standard 3-level resolver (`resolveAddonSettings`) over the\n // addon config store — see the top of this file for details.\n // ── 3-level pipeline settings (new model) ──────────────────────────\n //\n // Replaces the per-camera full-config + cluster-default model with:\n // `agent.addonDefaults` (flat per-addon config; auto-seeded from catalog),\n // `camera.stepToggles` (bool overlay; absent = inherit agent),\n // `camera.pipelineByAgent` (wholesale override escape hatch).\n //\n // The orchestrator's `resolvePipeline` collapses these into the\n // `CameraPipelineConfig` the runner consumes at dispatch.\n // `agentNodeId` (not `nodeId`) is intentional: the generated cap router\n // auto-routes any input field literally named `nodeId` to that node's\n // provider. `pipeline-orchestrator` is a HUB-SINGLETON cap — the\n // agent-node identifier here is DATA (\"which agent to read/write\"),\n // not routing. Using `agentNodeId` keeps the call on the hub as\n // intended.\n /** Read one agent's settings. Null when not yet seeded. */\n getAgentSettings: method(\n z.object({ agentNodeId: z.string() }),\n AgentPipelineSettingsSchema.nullable()\n ),\n /** Enumerate every agent's settings (hub + remote runners). */\n listAgentSettings: method(\n z.void(),\n z.array(z.object({\n nodeId: z.string(),\n settings: AgentPipelineSettingsSchema\n })).readonly()\n ),\n /** Bulk-replace ALL addon configs on one agent. Used by the agent-level PipelineEditor which emits the full map per edit. Merges on top of existing entries — omitted addonIds are left alone. */\n setAgentAddonDefaults: method(\n z.object({\n agentNodeId: z.string(),\n defaults: z.record(z.string(), AgentAddonConfigSchema)\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Drop a single agent's persisted settings. Used by the cluster\n * \"Offline agents\" panel to evict stale entries left behind when an\n * agent's data dir was rebuilt (new random nodeId) or older code wrote\n * the env name as the nodeId. The orchestrator otherwise never deletes\n * agentSettings — entries accumulate until a hub reset.\n *\n * `success: false` indicates the nodeId wasn't in the store (no-op).\n * Refuses to remove `hub` (the orchestrator always co-resides with it).\n */\n removeAgentSettings: method(\n z.object({ agentNodeId: z.string() }),\n z.object({ success: z.boolean(), removed: z.boolean() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // Phase 2f: `setAgentEngineChoice`, `setAgentHwAccel`,\n // `reprobeAgentHwAccel` removed. Engine ownership moved to the\n // `detection-pipeline` addon (`engineRuntime/engineBackend/engineDevice`\n // + `pipelineExecutor.reprobeEngine`). Hwaccel ownership moved to\n // each decoder addon (`decoder-nodeav`/`decoder-ffmpeg` global\n // settings + `decoder.reprobeHwaccel`). UI + decoder sessions read\n // via `api.addonSettings.getGlobalSettings({addonId, nodeId})`.\n /** Read one camera's settings. Null when never touched (inherits agent defaults fully). */\n getCameraSettings: method(\n z.object({ deviceId: z.number() }),\n CameraPipelineSettingsSchema.nullable()\n ),\n /** Set or clear the 3-state toggle for one (camera, addonId). Pass `enabled: null` to clear and revert to agent default. */\n setCameraStepToggle: method(\n z.object({\n deviceId: z.number(),\n addonId: z.string(),\n enabled: z.boolean().nullable()\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Read every L2.5 override map for a device. Null when device has no overrides. */\n getCameraStepOverrides: method(\n z.object({ deviceId: z.number() }),\n z.record(\n z.string(),\n // agentNodeId\n z.record(z.string(), CameraStepOverridePatchSchema)\n ).nullable()\n ),\n /**\n * Write or clear the L2.5 per-agent override for one addonId on a device.\n * `patch: null` clears the entry entirely for that (agent, addon) pair.\n */\n setCameraStepOverride: method(\n z.object({\n deviceId: z.number(),\n agentNodeId: z.string(),\n addonId: z.string(),\n patch: CameraStepOverridePatchSchema.nullable()\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Write or clear the wholesale per-agent pipeline override. Pass `pipeline: null` to drop the override. */\n setCameraPipelineForAgent: method(\n z.object({\n deviceId: z.number(),\n agentNodeId: z.string(),\n pipeline: CameraPipelineForAgentSchema.nullable()\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Resolve the effective pipeline for `(deviceId, agentNodeId?)` — walks the full precedence chain. Read-only preview used by the UI to show what will run. */\n resolvePipeline: method(\n z.object({ deviceId: z.number(), agentNodeId: z.string().optional() }),\n CameraPipelineConfigSchema\n ),\n // ── Template library (hub-only, read by any device-details UI) ─────\n /** List every template the operator has saved. */\n listTemplates: method(z.void(), z.array(PipelineTemplateSchema).readonly()),\n /** Create a new named preset from a given CameraPipelineConfig. */\n saveTemplate: method(\n z.object({\n name: z.string(),\n description: z.string().optional(),\n config: CameraPipelineConfigSchema\n }),\n PipelineTemplateSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Partial update of a template. Any omitted field is preserved. */\n updateTemplate: method(\n z.object({\n id: z.string(),\n name: z.string().optional(),\n description: z.string().optional(),\n config: CameraPipelineConfigSchema.optional()\n }),\n PipelineTemplateSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Remove a template. Camera configs that were seeded from it keep a copy. */\n deleteTemplate: method(\n z.object({ id: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst AudioAnalysisResultSchema = z.object({\n level: AudioLevelSchema,\n classification: z.object({\n labels: z.array(AudioClassificationLabelSchema).readonly(),\n inferenceMs: z.number()\n }).optional(),\n timestamp: z.number()\n});\nconst AudioAnalysisSettingsSchema = z.object({\n minConfidence: z.number().min(0).max(1).default(0.3),\n allowedClasses: z.array(z.string()).default([])\n});\nconst AudioClassificationResultSchema = z.object({\n // Macro-aggregated labels (25-class taxonomy from `AUDIO_MACRO_LABELS`).\n // Primary surface — used by the live audio analyzer and notifications.\n labels: z.array(AudioClassificationLabelSchema).readonly(),\n // Raw backend-native labels (e.g. YAMNet's 521 classes or Apple\n // SoundAnalysis's 303 classes), unaggregated. Optional so existing\n // consumers continue to work; populated by the analyzer provider\n // for callers that want fine-grained output — the benchmark UI uses\n // this in `micro` mode.\n rawLabels: z.array(AudioClassificationLabelSchema).readonly().optional(),\n inferenceMs: z.number()\n});\nconst AUDIO_BACKEND_CHOICES = [\n { value: \"auto\", label: \"Auto (platform default)\" },\n { value: \"apple-soundanalysis\", label: \"Apple SoundAnalysis (macOS 12+)\" },\n { value: \"yamnet-onnx\", label: \"YAMNet ONNX (cross-platform)\" }\n];\nconst DEFAULT_AUDIO_ANALYZER_CONFIG = {\n audioBackend: \"auto\",\n probedBestAudioBackend: \"\",\n selectedAudioModel: \"\"\n};\nconst audioAnalyzerCapability = {\n name: \"audio-analyzer\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n analyseChunk: method(\n z.object({ chunk: AudioChunkInputSchema, settings: AudioAnalysisSettingsSchema }),\n AudioAnalysisResultSchema.nullable(),\n { kind: \"mutation\" }\n ),\n // ONNX / Apple SoundAnalysis inference can exceed the broker's default\n // 5s requestTimeout on first load or under CPU pressure. 30s covers\n // even the worst-case cold-start without hanging indefinitely.\n classify: method(AudioChunkInputSchema, AudioClassificationResultSchema, { timeoutMs: 3e4 }),\n isReady: method(z.void(), z.boolean()),\n dispose: method(z.void(), z.void(), { kind: \"mutation\" }),\n /**\n * Re-run the host platform-probe for the audio backend and persist\n * the detected value into `probedBestAudioBackend`. Replaces the\n * orchestrator's legacy `AgentPipelineSettings.audio.engine` —\n * audio-analyzer now owns the choice. Operator `audioBackend` is\n * not touched; only the probed-best hint.\n */\n reprobeAudioEngine: method(\n z.void(),\n z.object({ backend: z.string() }),\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst audioAnalysisCapability = {\n name: \"audio-analysis\",\n scope: \"device\",\n mode: \"singleton\",\n kind: \"wrapper\",\n defaultActive: true,\n deviceTypes: [DeviceType.Camera],\n exposesDeviceSettings: true,\n methods: {\n /**\n * Resolve per-device audio analysis settings (minConfidence,\n * allowedClasses) from the addon settings store for a given camera.\n * Orchestrator callers use this before handing chunks to\n * `audio-analyzer.processChunk`.\n */\n resolveDeviceSettings: method(\n z.object({ deviceId: z.number() }),\n z.custom()\n )\n },\n events: {\n onAudioLevel: event(z.object({\n deviceId: z.number(),\n rms: z.number(),\n dbfs: z.number()\n }))\n }\n};\nconst PcmSampleFormatSchema = z.enum([\"f32le\", \"s16le\"]);\nconst AudioCodecInfoSchema = z.object({\n codec: z.string(),\n canDecode: z.boolean(),\n canEncode: z.boolean(),\n label: z.string().optional()\n});\nconst AudioDecodeSessionConfigSchema = z.object({\n codec: z.string(),\n sourceSampleRate: z.number().int().positive(),\n sourceChannels: z.number().int().positive(),\n extraData: z.instanceof(Uint8Array).optional(),\n targetSampleRate: z.number().int().positive(),\n targetChannels: z.number().int().positive(),\n targetFormat: PcmSampleFormatSchema.optional(),\n idleMs: z.number().int().positive().optional(),\n tag: z.string().optional()\n});\nconst AudioEncodeSessionConfigSchema = z.object({\n codec: z.string(),\n sourceSampleRate: z.number().int().positive(),\n sourceChannels: z.number().int().positive(),\n sourceFormat: PcmSampleFormatSchema.optional(),\n targetSampleRate: z.number().int().positive(),\n targetChannels: z.number().int().positive(),\n bitrateKbps: z.number().int().positive().optional(),\n idleMs: z.number().int().positive().optional(),\n tag: z.string().optional()\n});\nconst AudioPcmChunkSchema = z.object({\n data: z.instanceof(Uint8Array),\n sampleRate: z.number().int().positive(),\n channels: z.number().int().positive(),\n format: PcmSampleFormatSchema,\n pts: z.number()\n});\nconst AudioEncodedChunkSchema = z.object({\n data: z.instanceof(Uint8Array),\n codec: z.string(),\n pts: z.number(),\n frameComplete: z.boolean()\n});\nconst SessionInventoryEntrySchema = z.object({\n sessionId: z.string(),\n kind: z.enum([\"decode\", \"encode\"]),\n codec: z.string(),\n sourceSampleRate: z.number(),\n sourceChannels: z.number(),\n targetSampleRate: z.number(),\n targetChannels: z.number(),\n format: PcmSampleFormatSchema,\n tag: z.string().optional(),\n createdAtMs: z.number(),\n lastActivityMs: z.number(),\n framesIn: z.number(),\n framesOut: z.number()\n});\nconst audioCodecCapability = {\n name: \"audio-codec\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n // ── Discovery ─────────────────────────────────────────────────────────\n /** Probe the local runtime and return the supported codec matrix. */\n listSupportedCodecs: method(z.void(), z.array(AudioCodecInfoSchema).readonly()),\n /** Cheap predicate — does the runtime support `(codec, kind)`? */\n canHandle: method(\n z.object({ codec: z.string(), kind: z.enum([\"decode\", \"encode\"]) }),\n z.boolean()\n ),\n // ── Session lifecycle ─────────────────────────────────────────────────\n createDecodeSession: method(\n AudioDecodeSessionConfigSchema,\n z.object({ sessionId: z.string(), nodeId: z.string() }),\n { kind: \"mutation\" }\n ),\n createEncodeSession: method(\n AudioEncodeSessionConfigSchema,\n z.object({ sessionId: z.string(), nodeId: z.string() }),\n { kind: \"mutation\" }\n ),\n closeSession: method(\n z.object({ sessionId: z.string(), nodeId: z.string().optional() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n // ── Decode data plane ─────────────────────────────────────────────────\n // Session-bound methods include an optional `nodeId` field so the\n // generated cap router auto-routes calls to the same node that owns\n // the session. Audio-codec sessions are process-local — without sticky\n // routing the round-robin across nodes serves \"session not found\" on\n // every other call.\n /** Push one encoded audio frame into a decode session. */\n pushEncodedFrame: method(\n z.object({\n sessionId: z.string(),\n nodeId: z.string().optional(),\n data: z.instanceof(Uint8Array),\n /** Source PTS in milliseconds. Synthesised when omitted. */\n pts: z.number().optional()\n }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /** Pull up to `maxCount` PCM chunks from a decode session. */\n pullPcm: method(\n z.object({\n sessionId: z.string(),\n nodeId: z.string().optional(),\n maxCount: z.number().int().positive().default(8)\n }),\n z.array(AudioPcmChunkSchema)\n ),\n // ── Encode data plane ─────────────────────────────────────────────────\n /** Push one PCM chunk into an encode session. */\n pushPcm: method(\n z.object({\n sessionId: z.string(),\n nodeId: z.string().optional(),\n data: z.instanceof(Uint8Array),\n /** Source PTS in milliseconds. */\n pts: z.number().optional()\n }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /** Pull up to `maxCount` encoded chunks from an encode session. */\n pullEncoded: method(\n z.object({\n sessionId: z.string(),\n nodeId: z.string().optional(),\n maxCount: z.number().int().positive().default(8)\n }),\n z.array(AudioEncodedChunkSchema)\n ),\n /** Flush any pending encoded output (call before close on graceful tear). */\n flushEncode: method(\n z.object({ sessionId: z.string(), nodeId: z.string().optional() }),\n z.array(AudioEncodedChunkSchema),\n { kind: \"mutation\" }\n ),\n // ── Inventory ─────────────────────────────────────────────────────────\n listActiveSessions: method(\n z.void(),\n z.array(SessionInventoryEntrySchema).readonly()\n )\n }\n};\nconst EmbeddingResultSchema = z.object({\n embedding: z.array(z.number()),\n inferenceMs: z.number()\n});\nconst EmbeddingInfoSchema = z.object({\n modelId: z.string(),\n embeddingDim: z.number(),\n ready: z.boolean()\n});\nconst embeddingEncoderCapability = {\n name: \"embedding-encoder\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n encode: method(\n z.object({ crop: z.instanceof(Uint8Array), width: z.number(), height: z.number() }),\n EmbeddingResultSchema\n ),\n encodeText: method(z.object({ text: z.string() }), EmbeddingResultSchema),\n getInfo: method(z.void(), EmbeddingInfoSchema)\n }\n};\nconst DeviceInfoSchema = z.object({\n /** Progressive, system-wide unique number. Allocated synchronously by\n * `device-manager.allocateDeviceId` BEFORE the owning `IDevice` is\n * constructed, so every live device exposes an `id` — no transient\n * null window. Distinct from `stableId`, which is unique per\n * integration. Ids are monotonic and never reissued on removal. */\n id: z.number(),\n stableId: z.string(),\n addonId: z.string(),\n type: z.enum(DeviceType),\n name: z.string(),\n /** Operator-organisational location label. `null` when unset. */\n location: z.string().nullable(),\n /** Soft-disabled flag. */\n disabled: z.boolean(),\n parentDeviceId: z.number().nullable(),\n /** Optional semantic role — `DeviceRole` string. null for top-level devices. */\n role: z.string().nullable().optional(),\n online: z.boolean(),\n features: z.array(z.string()),\n /** true when the device has a getStreamSources() method (ICameraDevice) */\n isCamera: z.boolean(),\n /** Current config values — serializable snapshot */\n config: z.record(z.string(), z.unknown()),\n /** Hardware + identity blob (manufacturer / model / firmware / sn /\n * uid / mac / …). Populated by drivers; editable via setMetadata. */\n metadata: z.record(z.string(), z.unknown()).nullable().optional()\n});\nconst ConfigEntrySchema$1 = z.object({\n key: z.string(),\n value: z.unknown(),\n description: z.string().optional()\n});\nconst SavedDeviceRowSchema = z.object({\n /** Numeric id reserved at allocateDeviceId time. */\n id: z.number(),\n /** External-system identifier — required for the worker's `kernel.devices.create()` call. */\n stableId: z.string(),\n type: z.string(),\n name: z.string(),\n /** Operator-organisational location label. `null` when unset. */\n location: z.string().nullable(),\n /** Soft-disabled flag. */\n disabled: z.boolean(),\n parentDeviceId: z.number().nullable(),\n /** Optional semantic role — stringified `DeviceRole` enum value. null for top-level devices. */\n role: z.string().nullable().optional()\n});\nconst DeviceMetaSchema = z.object({\n id: z.number(),\n stableId: z.string(),\n addonId: z.string(),\n type: z.string(),\n name: z.string(),\n location: z.string().nullable(),\n disabled: z.boolean(),\n parentDeviceId: z.number().nullable(),\n metadata: z.record(z.string(), z.unknown()).nullable().optional()\n});\nconst ConfigUISchemaOutput = z.unknown().nullable();\nconst StreamProbeResultSchema = z.object({\n streamId: z.string(),\n width: z.number().optional(),\n height: z.number().optional(),\n codec: z.string().optional(),\n fps: z.number().optional(),\n bitrateKbps: z.number().optional()\n});\nconst DeviceRegisterPayloadSchema = z.object({\n addonId: z.string(),\n stableId: z.string(),\n /** Pre-allocated numeric id from `allocateDeviceId`. The hub persists\n * it alongside the meta record; callers never invent this value. */\n id: z.number(),\n type: z.string(),\n name: z.string(),\n /** Operator-organisational location label. Optional on register —\n * the hub seeds `null` when omitted. */\n location: z.string().nullable().optional(),\n /** Soft-disabled flag. Optional on register — the hub seeds `false`. */\n disabled: z.boolean().optional(),\n parentDeviceId: z.number().nullable(),\n /** Optional semantic role — see `DeviceRole`. Driver authors pass this\n * at register time when the device is an accessory with a known role. */\n role: z.string().nullable().optional(),\n /** Snapshot of `device.features` at registration time. Persisted in\n * `DeviceMeta` so the hub can answer `getDevice` for forked-worker\n * devices with the right `DeviceFeature[]` even when the live\n * instance lives on a remote node. Re-published on every register\n * call (workers re-register on init), so probe-driven updates\n * (e.g. PTZ flag flipping after the abilities probe) propagate. */\n features: z.array(z.string()).optional(),\n config: z.record(z.string(), z.unknown())\n});\nconst DeviceRemovePayloadSchema = z.object({\n deviceId: z.number()\n});\nconst DevicePersistConfigPayloadSchema = z.object({\n deviceId: z.number(),\n data: z.record(z.string(), z.unknown())\n});\nconst deviceManagerCapability = {\n name: \"device-manager\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n // ── Persistence (migrated from device-persistence) ────────────────────────\n /** Reserve (or re-resolve) a progressive numeric id for `(addonId, stableId)`.\n * Idempotent: returns the existing id if one is already persisted for the\n * pair. Callers invoke this before `registerDevice` so the live IDevice\n * can bind `id` at construction time through `DeviceContext.id`. */\n allocateDeviceId: method(\n z.object({ addonId: z.string(), stableId: z.string() }),\n z.object({ id: z.number() }),\n { kind: \"mutation\" }\n ),\n /** Register a device in the DB + in-memory registry. Called by DeviceManagerApi.register(). */\n registerDevice: method(DeviceRegisterPayloadSchema, z.void(), { kind: \"mutation\" }),\n /** Remove a device from the DB + in-memory registry. Called by DeviceManagerApi.remove(). */\n removeDevice: method(DeviceRemovePayloadSchema, z.void(), { kind: \"mutation\" }),\n /** Persist device config blob. Called by DeviceConfig.set/setAll(). */\n persistConfig: method(DevicePersistConfigPayloadSchema, z.void(), { kind: \"mutation\" }),\n /** Load persisted config for a device. Called at restore time. */\n loadConfig: method(\n z.object({ deviceId: z.number() }),\n z.record(z.string(), z.unknown())\n ),\n /** Load persisted runtime state. Called at device adopt time. */\n loadRuntimeState: method(\n z.object({ deviceId: z.number() }),\n z.record(z.string(), z.unknown())\n ),\n /** Load operator-organisational meta surface for a device. Called by\n * the kernel proxy to populate `DeviceContext.deviceMeta` before\n * the device class constructor runs. Returns `null` when the id\n * doesn't resolve to a persisted row. */\n loadMeta: method(\n z.object({ deviceId: z.number() }),\n DeviceMetaSchema.nullable()\n ),\n /** Update the operator-edited display name. Persists to the meta\n * row + emits `EventCategory.DeviceMetaChanged`. */\n setName: method(\n z.object({ deviceId: z.number(), name: z.string() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Update the operator-organisational location label. `null`\n * clears it. */\n setLocation: method(\n z.object({ deviceId: z.number(), location: z.string().nullable() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Patch the device's hardware-identity metadata blob. Merges\n * `patch` over the current blob (shallow). Value `null` for a\n * given key removes that key. Drivers populate factual fields\n * on first probe (model / firmware / mac / sn / uid); operators\n * can override or augment via the Device Info tab. */\n setMetadata: method(\n z.object({\n deviceId: z.number(),\n patch: z.record(z.string(), z.unknown())\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Operator-curated location registry. Returns the union of:\n * (1) labels persisted in the registry via `addLocation`, and\n * (2) labels currently in use on at least one device's\n * `meta.location` field.\n * Sorted case-insensitively + deduped + trimmed of empty strings.\n * Drives the autocomplete in the Device Info location editor. */\n listLocations: method(\n z.void(),\n z.array(z.string())\n ),\n /** Add a label to the curated location registry. No-op when the\n * label (case-insensitive, trimmed) is already present. Empty\n * / whitespace-only inputs throw. */\n addLocation: method(\n z.object({ name: z.string() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Remove a label from the curated registry. Devices that still\n * reference this label keep their `meta.location` value — the\n * registry is purely a suggestion list. To purge from devices,\n * iterate them and call `setLocation(deviceId, null)`\n * separately (or pass `cascade: true` to do it in one shot). */\n removeLocation: method(\n z.object({ name: z.string(), cascade: z.boolean().optional() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Soft-disable / re-enable the device. Drivers consult\n * `BaseDevice.disabled` to gate lifecycle hooks. */\n setDisabled: method(\n z.object({ deviceId: z.number(), disabled: z.boolean() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** List persisted devices for an addon (DB, for restore). */\n listPersistedByAddon: method(\n z.object({ addonId: z.string() }),\n z.array(SavedDeviceRowSchema)\n ),\n // ── Query — live registry ─────────────────────────────────────────────────\n /** List all devices (live registry), optionally filtered by addonId. */\n listAll: method(\n z.object({ addonId: z.string().optional() }),\n z.array(DeviceInfoSchema)\n ),\n /** Get a single device by numeric deviceId. */\n getDevice: method(\n z.object({ deviceId: z.number() }),\n DeviceInfoSchema.nullable()\n ),\n /** List children of a parent device (by parent numeric id). */\n getChildren: method(\n z.object({ parentDeviceId: z.number() }),\n z.array(DeviceInfoSchema)\n ),\n // ── Runtime — live device operations ─────────────────────────────────────\n /** Get stream sources for a camera device. */\n getStreamSources: method(\n z.object({ deviceId: z.number() }),\n z.array(StreamSourceEntrySchema$1)\n ),\n /** Get config entries (key + value + description) for a device. */\n getConfigSchema: method(\n z.object({ deviceId: z.number() }),\n z.array(ConfigEntrySchema$1)\n ),\n /** Get the ConfigUISchema for a device's settings (for admin UI rendering). */\n getSettingsSchema: method(\n z.object({ deviceId: z.number() }),\n ConfigUISchemaOutput\n ),\n // ── Mutations — config changes, enable/disable, remove ────────────────────\n /** Update device config values (partial merge). */\n updateConfig: method(\n z.object({\n deviceId: z.number(),\n values: z.record(z.string(), z.unknown())\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Enable a device (writes enabled=true to device config). */\n enable: method(\n z.object({ deviceId: z.number() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Disable a device (writes enabled=false to device config). */\n disable: method(\n z.object({ deviceId: z.number() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Remove a device and all children: calls device.removeDevice() then removes from registry + DB. */\n remove: method(\n z.object({ deviceId: z.number() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Stream profile map ────────────────────────────────────────────────────\n /** Get quality→streamId mapping for a camera. Derived from profileHint if not explicitly set. */\n getStreamProfileMap: method(\n z.object({ deviceId: z.number() }),\n z.record(z.string(), z.string().nullable())\n ),\n /** Persist quality→streamId mapping in device config under reserved key _profileMap. */\n setStreamProfileMap: method(\n z.object({\n deviceId: z.number(),\n profileMap: z.record(z.string(), z.string().nullable())\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Run ffprobe on each stream source URL and return metadata. No-op if stream probe unavailable. */\n probeStreams: method(\n z.object({ deviceId: z.number() }),\n z.array(StreamProbeResultSchema),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Bindings — per-device capability provider map ────────────────────────\n /**\n * Return the per-capability binding map for a device. Each entry lists the\n * currently-active provider (native or wrapper) + the underlying native\n * addon id, so consumers can decide routing without re-running discovery.\n */\n getBindings: method(\n z.object({ deviceId: z.number() }),\n z.object({\n deviceId: z.number(),\n entries: z.array(z.object({\n capName: z.string(),\n kind: z.enum([\"native\", \"wrapped\"]),\n providerAddonId: z.string(),\n providerNodeId: z.string(),\n nativeAddonId: z.string()\n }))\n })\n ),\n /**\n * Return the binding map for every device known to the hub. Used by\n * `SystemManager` warm-boot: a single round-trip resolves the\n * routing for the entire fleet so subsequent `sm.getDeviceById(id)`\n * calls are sync. Bindings change rarely (only on wrapper toggle or\n * device add/remove) — clients invalidate via the\n * `capability.binding-changed` event.\n */\n getAllBindings: method(\n z.object({}),\n z.array(z.object({\n deviceId: z.number(),\n entries: z.array(z.object({\n capName: z.string(),\n kind: z.enum([\"native\", \"wrapped\"]),\n providerAddonId: z.string(),\n providerNodeId: z.string(),\n nativeAddonId: z.string()\n }))\n }))\n ),\n /**\n * Activate (or deactivate) a wrapper addon for a (device, cap) pair.\n * Persists the binding via ctx.settings. active=false clears the wrapper\n * (falls back to native if registered).\n */\n setWrapperActive: method(\n z.object({\n deviceId: z.number(),\n capName: z.string(),\n wrapperAddonId: z.string(),\n active: z.boolean()\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Return the addon ids that declared a wrapper provider for `capName`.\n * Backs the device-bindings UI's wrapper-picker dropdown. Entries are\n * sourced from `CapabilityRegistry.wrapperProviders`, populated when\n * the cap definition declares `kind: 'wrapper'`.\n */\n listWrappersForCap: method(\n z.object({ capName: z.string() }),\n z.array(z.string())\n ),\n /**\n * Return every device-scoped capability name that applies to a\n * deviceType (scope:'device' + deviceTypes includes the given type),\n * paired with the wrappers that can provide it. Backs the device\n * bindings UI so it can show rows for bindable caps even when no\n * native is registered yet — the user can still activate a wrapper\n * to light the cap up (e.g. snapshot via ffmpeg fallback for a camera\n * without `snapshotUrl`).\n */\n listBindableCapsForDeviceType: method(\n z.object({ deviceType: z.string() }),\n z.array(z.object({\n capName: z.string(),\n wrappers: z.array(z.string())\n }))\n ),\n // ── Device-details aggregators ───────────────────────────────────────────\n //\n // Single entry point the admin UI calls to render the device-details page.\n // The hub enumerates every provider of `device-settings-contributor` (a\n // `collection` cap) plus its own base section and returns a single\n // `ConfigUISchemaWithValues` with merged tabs/sections.\n //\n // Two endpoints, two cadences:\n // - `getDeviceSettingsAggregate` — editable fields + static readonly.\n // Cached on the UI side, invalidated on successful `updateDeviceField`.\n // - `getDeviceLiveInfoAggregate` — readonly, dynamic. UI polls at a\n // short interval (~2-3 s). Fields carry `source: 'live'` so the\n // renderer knows which query owns the value.\n //\n // Save flow goes through `updateDeviceField` — the aggregator routes the\n // write to `addon-settings.updateDeviceSettings` for the declared\n // `writerAddonId` (or to its own device config store when `writerAddonId`\n // equals the device-manager addon id).\n getDeviceSettingsAggregate: method(\n z.object({ deviceId: z.number() }),\n SettingsSchemaWithValuesSchema.nullable()\n ),\n getDeviceLiveInfoAggregate: method(\n z.object({ deviceId: z.number() }),\n SettingsSchemaWithValuesSchema.nullable()\n ),\n /**\n * Unified entry point — returns both settings + live in a single call\n * so the admin UI pulls the whole device-details panel with one round-\n * trip instead of firing two parallel queries. The `live` field is the\n * polled portion; the UI re-fetches the whole aggregate at the live\n * cadence and uses the `settings` slice verbatim until the user\n * writes through `updateDeviceFieldsBatch`.\n */\n getDeviceAggregate: method(\n z.object({ deviceId: z.number() }),\n z.object({\n settings: SettingsSchemaWithValuesSchema.nullable(),\n live: SettingsSchemaWithValuesSchema.nullable()\n })\n ),\n updateDeviceField: method(\n z.object({\n deviceId: z.number(),\n writerCapName: z.string(),\n writerAddonId: z.string(),\n key: z.string(),\n value: z.unknown()\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Batched counterpart of `updateDeviceField` — the admin UI groups\n * per-provider changes so a single round-trip triggers at most one\n * `applyDeviceSettingsPatch` per `(capName, addonId)` tuple. Per-patch\n * failures are reported in `failures[]` without aborting the others;\n * consumers inspect the list and surface targeted errors.\n */\n updateDeviceFieldsBatch: method(\n z.object({\n deviceId: z.number(),\n changes: z.array(z.object({\n writerCapName: z.string(),\n writerAddonId: z.string(),\n key: z.string(),\n value: z.unknown()\n }))\n }),\n z.object({\n success: z.literal(true),\n failures: z.array(z.object({\n writerCapName: z.string(),\n writerAddonId: z.string(),\n error: z.string()\n }))\n }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Device-provider operations (routed via CapabilityRegistry) ────────────\n //\n // These methods proxy to the `device-provider` capability collection,\n // routing by addonId. Moving them here from the compat router\n // (`device-ops.router.ts`) allows addon ctx.api callers to reach them\n // through the standard Moleculer-registered cap surface.\n /** Trigger device discovery on a device-provider addon. */\n discoverDevices: method(\n z.object({ addonId: z.string() }),\n z.array(DiscoveryCandidateSchema),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Adopt a discovered device via the device-provider capability. */\n adoptDevice: method(\n z.object({\n addonId: z.string(),\n candidate: DiscoveryCandidateSchema\n }),\n DeviceSummarySchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Get the creation form schema (ConfigUISchema) for a device type from a provider.\n * Returns null when the provider does not support manual creation.\n */\n getCreationSchema: method(\n z.object({\n addonId: z.string(),\n type: z.enum(DeviceType)\n }),\n z.unknown().nullable()\n ),\n /** Create a new device via the device-provider capability. */\n createDevice: method(\n z.object({\n addonId: z.string(),\n type: z.enum(DeviceType),\n config: z.record(z.string(), z.unknown())\n }),\n DeviceSummarySchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Test a single form field value during device creation (no device\n * exists yet). `formValues` carries the live snapshot of every\n * field in the form so probes that depend on multiple fields (e.g.\n * Reolink autodetect needs host + credentials + UID together) can\n * run without a separate round-trip per field. Optional for\n * backwards compatibility.\n */\n testCreationField: method(\n z.object({\n addonId: z.string(),\n type: z.enum(DeviceType),\n key: z.string(),\n value: z.unknown(),\n formValues: z.record(z.string(), z.unknown()).optional()\n }),\n FieldProbeResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Test a field value on an existing device (e.g. probe an RTSP URL).\n * Routes through the device-provider for the owning addon.\n */\n testField: method(\n z.object({\n deviceId: z.number(),\n key: z.string(),\n value: z.unknown()\n }),\n FieldProbeResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Aggregate status snapshot across every cap registered for a\n * device. Returns a flat map `{ capName: status | null }` where\n * `status` is whatever `capDef.status.schema` validates to — or\n * `null` when no provider for that cap is registered on the\n * device, or the provider returned null, or the returned value\n * failed validation.\n *\n * `caps` is a positional tuple of cap names. The runtime only\n * returns entries for caps that are KNOWN to the system (validated\n * against `CAP_NAMES_WITH_STATUS` at call time); unknown names are\n * silently skipped. The client-side hook narrows the return type\n * using `CapStatusTypeMap` so the TS-inferred shape matches the\n * runtime shape.\n *\n * When `caps` is omitted, the server returns status for EVERY\n * registered cap on the device. Use this only for debug / overview\n * pages — it's O(N caps) per call.\n */\n getDeviceStatusAggregate: method(\n z.object({\n deviceId: z.number(),\n caps: z.array(z.string()).readonly().optional()\n }),\n z.record(z.string(), z.unknown().nullable())\n )\n }\n};\nconst deviceStateCapability = {\n name: \"device-state\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n /** Full state snapshot for one device. Empty object if no\n * cap-keyed slice has been written yet. */\n getSnapshot: method(\n z.object({ deviceId: z.number() }),\n z.record(z.string(), z.record(z.string(), z.unknown()))\n ),\n /** Single cap slice. Returns null when the slice hasn't been\n * written or the device isn't registered. */\n getCapSlice: method(\n z.object({ deviceId: z.number(), capName: z.string() }),\n z.record(z.string(), z.unknown()).nullable()\n ),\n /**\n * Whole-system snapshot — every device's full state in one\n * payload. Used by `SystemManager` for warm-boot: a single\n * round-trip populates the client mirror so every subsequent\n * `sm.getDeviceById(id).state.<cap>.value` is sync. Empty inner\n * record for devices that haven't emitted any slice yet.\n */\n getAllSnapshots: method(\n z.object({}),\n z.record(z.string(), z.record(z.string(), z.record(z.string(), z.unknown())))\n ),\n /**\n * Canonical cross-layer WRITE for one cap-keyed slice. Used by\n * everyone who needs to publish runtime state for a device:\n * device providers (via `BaseDevice.runtimeState.setCapState`\n * which delegates here), system-scope addons (e.g. the pipeline\n * runner writing the `motion` slice on phase transitions), and\n * direct cap-router callers in tests.\n *\n * Behavior on the hub:\n * 1. Resolve the device — throws if unknown.\n * 2. Diff the slice against the current mirror (no-op on\n * identical writes — saves disk and event churn).\n * 3. Update the mirror in place.\n * 4. Persist the full per-device blob to disk (debounced).\n * 5. Emit `onChanged` for this cap so subscribers (UI mirror,\n * SystemManager, per-cap typed listeners) refresh.\n *\n * Schema validation is the caller's responsibility — callers\n * going through `BaseDevice.runtimeState.setCapState` get the\n * cap's `runtimeState` schema enforced in-process before the\n * write reaches here. Direct callers should validate against\n * the cap's schema themselves.\n *\n * No `patch` variant — for shallow merges read the slice via\n * `getCapSlice` first, merge, and write. The single-writer\n * conventions on each cap make atomic-merge semantics\n * unnecessary in practice.\n */\n setCapSlice: method(\n z.object({\n deviceId: z.number(),\n capName: z.string(),\n slice: z.record(z.string(), z.unknown())\n }),\n z.void(),\n { kind: \"mutation\" }\n )\n },\n events: {\n /**\n * Fires whenever a cap-keyed slice changes. Per-event payload\n * carries the slice that changed — subscribers can render off\n * the payload alone without re-querying. Filterable by `deviceId`\n * via the standard `EventFilter` helpers.\n */\n onChanged: event(z.object({\n deviceId: z.number(),\n capName: z.string(),\n slice: z.record(z.string(), z.unknown())\n }))\n }\n};\nconst AuthResultSchema = z.object({\n userId: z.string(),\n username: z.string(),\n email: z.string().optional(),\n displayName: z.string().optional(),\n /**\n * Whether the authenticating user is an admin. The auth-provider\n * surface returns this so the server's login flow can mint a JWT\n * with the correct bypass flag. Non-admin users authenticated via\n * an external IdP still need their scopes assigned by an admin via\n * `setUserScopes` — the SSO flow doesn't carry permissions.\n */\n isAdmin: z.boolean().default(false)\n});\nconst authProviderCapability = {\n name: \"auth-provider\",\n scope: \"system\",\n mode: \"collection\",\n internal: true,\n methods: {\n validateCredentials: method(\n z.object({ username: z.string(), password: z.string() }),\n AuthResultSchema.nullable(),\n { kind: \"mutation\" }\n ),\n getLoginUrl: method(z.object({ state: z.string() }), z.string()),\n handleCallback: method(z.record(z.string(), z.string()), AuthResultSchema, { kind: \"mutation\" }),\n validateToken: method(z.object({ token: z.string() }), AuthResultSchema.nullable())\n }\n};\nconst NetworkEndpointSchema = z.object({\n url: z.string(),\n hostname: z.string(),\n port: z.number(),\n protocol: z.enum([\"http\", \"https\"])\n});\nconst NetworkAccessStatusSchema = z.object({\n connected: z.boolean(),\n endpoint: NetworkEndpointSchema.nullable(),\n error: z.string().optional()\n});\nconst NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({\n /**\n * Stable id within the provider — typically `<mode>-<sourcePort>` so\n * the orchestrator can dedupe across `listEndpoints` polls.\n */\n id: z.string(),\n /** Operator-facing label (mirrors `MeshEndpoint.label`). */\n label: z.string(),\n /** Optional provider-specific mode tag, used for icon/colour in admin UI. */\n mode: z.string().optional(),\n /** Originating local port the ingress fronts (informational). */\n sourcePort: z.number().optional()\n});\nconst networkAccessCapability = {\n name: \"network-access\",\n scope: \"system\",\n mode: \"collection\",\n providerKind: \"ingress\",\n methods: {\n start: method(z.void(), NetworkEndpointSchema, { kind: \"mutation\" }),\n stop: method(z.void(), z.void(), { kind: \"mutation\" }),\n getEndpoint: method(z.void(), NetworkEndpointSchema.nullable()),\n getStatus: method(z.void(), NetworkAccessStatusSchema),\n /**\n * Enumerate every active ingress entry. Providers that expose only a\n * single endpoint may omit this method; callers fall back to\n * `getEndpoint()` in that case.\n */\n listEndpoints: method(z.void(), z.array(NetworkEndpointEntrySchema).readonly())\n }\n};\nconst TurnServerSchema = z.object({\n /** Single URL or list of URLs (e.g. \"turn:turn.example.com:3478?transport=udp\"). */\n urls: z.union([z.string(), z.array(z.string())]),\n username: z.string().optional(),\n credential: z.string().optional()\n});\nconst turnProviderCapability = {\n name: \"turn-provider\",\n scope: \"system\",\n mode: \"collection\",\n methods: {\n /**\n * Return the current list of TURN/STUN servers with credentials.\n * Implementations may fetch fresh short-lived credentials on each call\n * (e.g. Cloudflare API) — consumers SHOULD call this per-session.\n */\n getTurnServers: method(\n z.void(),\n z.array(TurnServerSchema).readonly()\n )\n }\n};\nconst SnapshotImageSchema = z.object({\n base64: z.string(),\n contentType: z.string()\n});\nconst SnapshotStatusSchema = z.object({\n /** Ms epoch of the last successful capture. Null if none yet. */\n lastCapturedAt: z.number().nullable(),\n /** Age of the cached image in ms. Null if no cache. */\n cacheAgeMs: z.number().nullable(),\n /** Size in bytes of the last captured image. Null if no capture. */\n lastBytes: z.number().nullable(),\n /** Stream id used for the last capture ('high'|'mid'|'low' or custom). Null if via HTTP endpoint. */\n lastStreamId: z.string().nullable()\n});\nconst snapshotCapability = {\n name: \"snapshot\",\n scope: \"device\",\n mode: \"singleton\",\n kind: \"wrapper\",\n defaultActive: true,\n deviceTypes: [DeviceType.Camera],\n // Owns per-device snapshot settings (preferred stream, debug logging).\n // The three DeviceSettingsContribution methods are auto-added to the\n // provider interface via `InferProvider` — `SnapshotAddon` implements\n // them and persists per-device state through `ctx.settings.writeDeviceStore`.\n exposesDeviceSettings: true,\n methods: {\n getSnapshot: method(\n z.object({\n deviceId: z.number(),\n streamId: z.string().optional(),\n /**\n * Bypass the cache freshness check and fetch directly from the\n * native (or stream-broker fallback). Triggered by the UI's\n * \"refresh\" button so an operator can force a fresh frame\n * even when the cache is well within `snapshotMaxAgeMs`.\n * On battery cams this WILL wake the camera — accept the\n * cost only when the user explicitly asks for it.\n */\n force: z.boolean().optional()\n }),\n SnapshotImageSchema.nullable()\n ),\n invalidateCache: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n },\n status: {\n schema: SnapshotStatusSchema,\n kind: \"poll\"\n }\n};\nconst snapshotProviderCapability = {\n name: \"snapshot-provider\",\n scope: \"system\",\n mode: \"collection\",\n methods: {\n supportsDevice: method(\n z.object({ deviceId: z.number() }),\n z.boolean()\n ),\n getSnapshot: method(\n z.object({\n deviceId: z.number(),\n streamId: z.string().optional()\n }),\n SnapshotImageSchema.nullable()\n )\n }\n};\nconst NotificationSchema = z.object({\n title: z.string(),\n body: z.string(),\n imageUrl: z.string().optional(),\n deviceId: z.number().optional(),\n eventId: z.string().optional(),\n priority: z.enum([\"low\", \"normal\", \"high\", \"critical\"]).default(\"normal\"),\n metadata: z.record(z.string(), z.unknown()).optional()\n});\nconst notificationOutputCapability = {\n name: \"notification-output\",\n scope: \"system\",\n mode: \"collection\",\n methods: {\n send: method(NotificationSchema, z.void(), { kind: \"mutation\" }),\n sendTest: method(\n z.void(),\n z.object({ success: z.boolean(), error: z.string().optional() }),\n { kind: \"mutation\" }\n )\n }\n};\nconst NotificationRuleConditionsSchema = z.object({\n deviceIds: z.array(z.number()).readonly().optional(),\n classNames: z.array(z.string()).readonly().optional(),\n zoneIds: z.array(z.string()).readonly().optional(),\n minConfidence: z.number().optional(),\n source: z.enum([\"pipeline\", \"onboard\", \"any\"]).optional(),\n schedule: z.object({\n days: z.array(z.number()).readonly(),\n startHour: z.number(),\n endHour: z.number()\n }).optional(),\n cooldownSeconds: z.number().optional(),\n minDwellSeconds: z.number().optional()\n});\nconst NotificationRuleTemplateSchema = z.object({\n title: z.string(),\n body: z.string(),\n imageMode: z.enum([\"crop\", \"annotated\", \"full\", \"none\"])\n});\nconst NotificationRuleSchema = z.object({\n id: z.string(),\n name: z.string(),\n enabled: z.boolean(),\n eventTypes: z.array(z.string()).readonly(),\n conditions: NotificationRuleConditionsSchema,\n outputs: z.array(z.string()).readonly(),\n template: NotificationRuleTemplateSchema.optional(),\n priority: z.enum([\"low\", \"normal\", \"high\", \"critical\"])\n});\nconst NotificationTestResultSchema = z.object({\n ruleId: z.string(),\n eventId: z.string(),\n timestamp: z.number(),\n wouldFire: z.boolean(),\n reason: z.string().optional()\n});\nconst NotificationHistoryEntrySchema = z.object({\n id: z.string(),\n ruleId: z.string(),\n ruleName: z.string(),\n eventId: z.string(),\n timestamp: z.number(),\n outputs: z.array(z.string()).readonly(),\n success: z.boolean(),\n error: z.string().optional(),\n deviceId: z.number().optional()\n});\nconst NotificationHistoryFilterSchema = z.object({\n ruleId: z.string().optional(),\n deviceId: z.number().optional(),\n from: z.number().optional(),\n to: z.number().optional(),\n limit: z.number().optional()\n});\nconst advancedNotifierCapability = {\n name: \"advanced-notifier\",\n scope: \"system\",\n mode: \"singleton\",\n internal: true,\n methods: {\n getRules: method(\n z.void(),\n z.object({ rules: z.array(NotificationRuleSchema).readonly() })\n ),\n upsertRule: method(\n z.object({ rule: NotificationRuleSchema }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\" }\n ),\n deleteRule: method(\n z.object({ ruleId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\" }\n ),\n testRule: method(\n z.object({ ruleId: z.string(), lookbackMinutes: z.number() }),\n z.object({ results: z.array(NotificationTestResultSchema).readonly() }),\n { kind: \"mutation\" }\n ),\n getHistory: method(\n z.object({ filter: NotificationHistoryFilterSchema.optional() }),\n z.object({ entries: z.array(NotificationHistoryEntrySchema).readonly() })\n )\n }\n};\nconst RecordingModeSchema = z.enum([\"continuous\", \"motion\", \"scheduled\", \"composite\"]);\nconst StreamPolicySchema = z.object({\n streamId: z.string(),\n mode: z.enum([\"always\", \"inherit\"])\n});\nconst ScheduleRuleSchema = z.object({\n days: z.array(z.number()).readonly(),\n startTime: z.string(),\n endTime: z.string(),\n mode: z.enum([\"continuous\", \"motion\"])\n});\nconst RecordingPolicySchema = z.object({\n deviceId: z.number(),\n mode: RecordingModeSchema,\n streams: z.array(StreamPolicySchema).readonly(),\n enabled: z.boolean(),\n preBufferSec: z.number(),\n postBufferSec: z.number(),\n scheduleRules: z.array(ScheduleRuleSchema).readonly().optional()\n});\nconst DataCategorySchema = z.enum([\n \"recording:main\",\n \"recording:mid\",\n \"recording:sub\",\n \"thumbnail:scrub\",\n \"thumbnail:event\"\n]);\nconst RecordingStorageConfigSchema = z.object({\n deviceId: z.number(),\n dataCategory: DataCategorySchema,\n storageName: z.string(),\n subDirectory: z.string(),\n retentionDays: z.number().nullable(),\n retentionGb: z.number().nullable()\n});\nconst RecordingSegmentSchema = z.object({\n id: z.string(),\n deviceId: z.number(),\n streamId: z.string(),\n startTime: z.number(),\n endTime: z.number(),\n duration: z.number(),\n path: z.string(),\n storageName: z.string(),\n subDirectory: z.string(),\n sizeBytes: z.number(),\n codec: z.enum([\"h264\", \"h265\"]),\n hasAudio: z.boolean()\n});\nconst RecordingThumbnailSchema = z.object({\n deviceId: z.number(),\n timestamp: z.number(),\n path: z.string(),\n storageName: z.string(),\n subDirectory: z.string(),\n sizeBytes: z.number(),\n category: z.enum([\"scrub\", \"event\"])\n});\nconst AvailabilityRangeSchema = z.object({\n startTime: z.number(),\n endTime: z.number(),\n streams: z.array(z.string()).readonly()\n});\nconst StorageUsageSchema = z.object({\n totalBytes: z.number(),\n segmentCount: z.number()\n});\nconst StreamEstimateSchema = z.object({\n bitrateKbps: z.number(),\n retentionDays: z.number().nullable(),\n retentionGb: z.number().nullable(),\n estimatedGb: z.number(),\n estimatedDaysAtCapacity: z.number().nullable()\n});\nconst StorageEstimateSchema = z.object({\n perStream: z.record(z.string(), StreamEstimateSchema),\n thumbnails: z.object({ estimatedGb: z.number() }),\n totalEstimatedGb: z.number(),\n motionEstimate: z.object({\n avgEventsPerDay: z.number(),\n avgDurationSec: z.number(),\n dutyCyclePercent: z.number()\n }).optional()\n});\nconst MotionStatsSchema = z.object({\n totalEvents: z.number(),\n avgDurationSec: z.number(),\n avgEventsPerDay: z.number(),\n dutyCyclePercent: z.number()\n});\nconst DeviceIdInput = z.object({ deviceId: z.number() });\nconst EnableInput = z.object({\n deviceId: z.number(),\n policy: RecordingPolicySchema.omit({ deviceId: true }),\n storageOverrides: z.array(RecordingStorageConfigSchema.omit({ deviceId: true })).readonly().optional(),\n ffmpegOverrides: z.record(z.string(), z.unknown()).optional()\n});\nconst TimeRangeInput = z.object({\n deviceId: z.number(),\n startTime: z.number(),\n endTime: z.number()\n});\nconst StreamTimeRangeInput = z.object({\n deviceId: z.number(),\n streamId: z.string(),\n startTime: z.number(),\n endTime: z.number()\n});\nconst PlaylistInput = z.object({\n deviceId: z.number(),\n streamId: z.string(),\n startTime: z.number(),\n endTime: z.number(),\n live: z.boolean().optional()\n});\nconst ThumbnailInput = z.object({\n deviceId: z.number(),\n timestamp: z.number(),\n category: z.string().optional()\n});\nconst DeviceStreamInput = z.object({\n deviceId: z.number(),\n streamId: z.string()\n});\nconst StorageEstimateInput = z.object({\n deviceId: z.number(),\n motionInput: z.object({\n avgEventsPerDay: z.number(),\n avgDurationSec: z.number()\n }).optional()\n});\nconst RetentionConfigInput = z.object({\n deviceId: z.number(),\n dataCategory: DataCategorySchema\n});\nconst SetPolicyInput = z.object({\n deviceId: z.number(),\n policy: RecordingPolicySchema.omit({ deviceId: true })\n});\nconst UpdateConfigInput = z.object({\n deviceId: z.number(),\n policy: RecordingPolicySchema.omit({ deviceId: true }),\n ffmpegOverrides: z.record(z.string(), z.unknown()).optional()\n});\nconst recordingEngineCapability = {\n name: \"recording-engine\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n // ── Status ────────────────────────────────────────────────────────\n getStatus: method(z.void(), z.object({\n activeRecordings: z.number(),\n totalSegments: z.number(),\n totalSizeMB: z.number()\n })),\n // ── Lifecycle ─────────────────────────────────────────────────────\n enable: method(EnableInput, z.void(), { kind: \"mutation\", auth: \"admin\" }),\n disable: method(DeviceIdInput, z.void(), { kind: \"mutation\", auth: \"admin\" }),\n // ── Config ────────────────────────────────────────────────────────\n getConfig: method(DeviceIdInput, RecordingPolicySchema.nullable()),\n updateConfig: method(UpdateConfigInput, z.void(), { kind: \"mutation\", auth: \"admin\" }),\n // ── Playback ──────────────────────────────────────────────────────\n getPlaylist: method(PlaylistInput, z.string()),\n getThumbnail: method(ThumbnailInput, RecordingThumbnailSchema.nullable()),\n getSegments: method(StreamTimeRangeInput, z.array(RecordingSegmentSchema).readonly()),\n getAvailability: method(TimeRangeInput, z.array(AvailabilityRangeSchema).readonly()),\n // ── Storage ───────────────────────────────────────────────────────\n estimateStorage: method(StorageEstimateInput, StorageEstimateSchema),\n estimateGlobalStorage: method(z.void(), StorageEstimateSchema),\n getStorageUsage: method(DeviceStreamInput, StorageUsageSchema),\n // ── Policy ────────────────────────────────────────────────────────\n setPolicy: method(SetPolicyInput, z.void(), { kind: \"mutation\", auth: \"admin\" }),\n getPolicy: method(DeviceIdInput, RecordingPolicySchema.nullable()),\n getPolicyStatus: method(DeviceIdInput, z.object({\n deviceId: z.number(),\n enabled: z.boolean(),\n mode: RecordingModeSchema,\n activeStreams: z.number()\n }).nullable()),\n // ── Retention ─────────────────────────────────────────────────────\n getRetentionConfig: method(RetentionConfigInput, RecordingStorageConfigSchema.nullable()),\n updateRetentionConfig: method(RecordingStorageConfigSchema, z.void(), { kind: \"mutation\", auth: \"admin\" }),\n // ── Motion ────────────────────────────────────────────────────────\n getMotionStats: method(TimeRangeInput, MotionStatsSchema)\n }\n};\nconst detectionPipelineCapability = {\n name: \"detection-pipeline\",\n scope: \"device\",\n mode: \"singleton\",\n kind: \"wrapper\",\n defaultActive: true,\n deviceTypes: [DeviceType.Camera],\n exposesDeviceSettings: true,\n methods: {}\n};\nconst TrackStateSchema = z.enum([\"new\", \"entered\", \"left\", \"moving\", \"idle\"]);\nconst EventKindSchema = z.enum([\"motion\", \"object\", \"audio\"]);\nconst TrackPositionSchema = z.object({\n x: z.number(),\n y: z.number(),\n timestamp: z.number(),\n bbox: BoundingBoxSchema\n});\nconst TrackSnapshotSchema = z.object({\n timestamp: z.number(),\n position: TrackPositionSchema,\n /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */\n mediaKey: z.string()\n});\nconst TrackSchema = z.object({\n trackId: z.string(),\n deviceId: z.number(),\n className: z.string(),\n label: z.string().optional(),\n firstSeen: z.number(),\n lastSeen: z.number(),\n /** Frame-rate position history (subject to maxPositionHistory cap). */\n positions: z.array(TrackPositionSchema).readonly(),\n /** Periodic snapshots at snapshotIntervalMs cadence (subject to\n * saveThumbnails policy). */\n snapshots: z.array(TrackSnapshotSchema).readonly(),\n /** Deduplicated zones the track has entered at least once. */\n zonesVisited: z.array(z.string()).readonly(),\n /** Cumulative normalized distance travelled (0..1 units = full frame width). */\n totalDistance: z.number(),\n state: TrackStateSchema,\n active: z.boolean()\n});\nconst BaseEventFields = {\n id: z.string(),\n deviceId: z.number(),\n timestamp: z.number()\n};\nconst MotionEventSchema = z.object({\n ...BaseEventFields,\n kind: z.literal(\"motion\"),\n regionCount: z.number(),\n regions: z.array(z.object({\n bbox: BoundingBoxSchema,\n pixelCount: z.number(),\n intensity: z.number()\n })).readonly(),\n frameWidth: z.number(),\n frameHeight: z.number()\n});\nconst ObjectEventSchema = z.object({\n ...BaseEventFields,\n kind: z.literal(\"object\"),\n trackId: z.string(),\n className: z.string(),\n label: z.string().optional(),\n confidence: z.number(),\n bbox: BoundingBoxSchema,\n zones: z.array(z.string()).readonly(),\n state: TrackStateSchema,\n /** MediaStore key for the crop attached to this event (if any). */\n mediaKey: z.string().optional()\n});\nconst AudioEventSchema = z.object({\n ...BaseEventFields,\n kind: z.literal(\"audio\"),\n rms: z.number(),\n dbfs: z.number(),\n classification: z.object({\n className: z.string(),\n originalClass: z.string().optional(),\n score: z.number()\n }).optional()\n});\nconst MediaFileSchema = z.object({\n key: z.string(),\n kind: z.enum([\"crop\", \"thumbnail\", \"snapshot\"]),\n base64: z.string(),\n sizeBytes: z.number(),\n timestamp: z.number()\n});\nconst DEFAULT_EVENT_QUERY_LIMIT = 1e3;\nconst MAX_EVENT_QUERY_LIMIT = 5e3;\nconst DeviceEventQueryInput = z.object({\n deviceId: z.number(),\n since: z.number().optional(),\n until: z.number().optional(),\n limit: z.number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)\n});\nconst ObjectEventQueryInput = DeviceEventQueryInput.extend({\n classFilter: z.string().optional()\n});\nconst TrackedDetectionSchema = z.object({\n trackId: z.string(),\n className: z.string(),\n confidence: z.number(),\n bbox: BoundingBoxSchema,\n zones: z.array(z.string()).readonly(),\n state: TrackStateSchema\n});\nconst pipelineAnalyticsCapability = {\n name: \"pipeline-analytics\",\n scope: \"device\",\n mode: \"singleton\",\n kind: \"wrapper\",\n defaultActive: true,\n deviceTypes: [DeviceType.Camera],\n exposesDeviceSettings: true,\n methods: {\n // ── Tracks ────────────────────────────────────────────────\n getActiveTracks: method(\n z.object({ deviceId: z.number() }),\n z.array(TrackSchema).readonly()\n ),\n getTrack: method(\n z.object({ deviceId: z.number(), trackId: z.string() }),\n TrackSchema.nullable()\n ),\n /** Historical completed tracks for a device. Queried from the\n * persisted `pipeline-analytics:tracks` collection; active tracks\n * still in RAM are not included. */\n listTracks: method(\n z.object({\n deviceId: z.number(),\n since: z.number().optional(),\n until: z.number().optional(),\n limit: z.number().optional()\n }),\n z.array(TrackSchema).readonly()\n ),\n clearTracks: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Events (per-kind, parallel-queryable) ─────────────────\n getMotionEvents: method(\n DeviceEventQueryInput,\n z.array(MotionEventSchema).readonly()\n ),\n getObjectEvents: method(\n ObjectEventQueryInput,\n z.array(ObjectEventSchema).readonly()\n ),\n getAudioEvents: method(\n DeviceEventQueryInput,\n z.array(AudioEventSchema).readonly()\n ),\n // ── Media ─────────────────────────────────────────────────\n getEventMedia: method(\n z.object({ eventId: z.string() }),\n z.array(MediaFileSchema).readonly()\n ),\n getTrackMedia: method(\n z.object({ trackId: z.string() }),\n z.array(MediaFileSchema).readonly()\n )\n },\n events: {\n /**\n * Enriched frame emitted after refinement. Carries lightweight\n * tracked-detection metadata (track id, class, zones, state) so\n * downstream consumers (stream overlays, notifications) can\n * annotate without querying full Track state.\n */\n onFrameTracked: {\n data: z.object({\n deviceId: z.number(),\n timestamp: z.number(),\n frameWidth: z.number(),\n frameHeight: z.number(),\n detections: z.array(TrackedDetectionSchema).readonly()\n })\n },\n /** Track entered active state (first-seen). */\n onTrackStarted: {\n data: z.object({\n deviceId: z.number(),\n trackId: z.string(),\n className: z.string()\n })\n },\n /** Track expired (TTL reached after last detection). */\n onTrackEnded: {\n data: z.object({\n deviceId: z.number(),\n trackId: z.string(),\n className: z.string(),\n durationMs: z.number()\n })\n },\n /** Canonical \"something happened at device X\" event, per-kind. */\n onDetectionEvent: {\n data: z.object({\n deviceId: z.number(),\n kind: EventKindSchema,\n eventId: z.string(),\n timestamp: z.number()\n })\n }\n }\n};\nconst CpuBreakdownSchema = z.object({\n total: z.number(),\n user: z.number(),\n system: z.number(),\n irq: z.number(),\n nice: z.number(),\n loadAvg: z.tuple([z.number(), z.number(), z.number()]),\n cores: z.number()\n});\nconst MemoryInfoSchema = z.object({\n percent: z.number(),\n totalBytes: z.number(),\n usedBytes: z.number(),\n availableBytes: z.number(),\n swapUsedBytes: z.number(),\n swapTotalBytes: z.number()\n});\nconst DiskIoSnapshotSchema = z.object({\n readBytes: z.number(),\n writeBytes: z.number(),\n readOps: z.number(),\n writeOps: z.number(),\n timestampMs: z.number()\n});\nconst NetworkIoSnapshotSchema = z.object({\n rxBytes: z.number(),\n txBytes: z.number(),\n rxPackets: z.number(),\n txPackets: z.number(),\n rxErrors: z.number(),\n txErrors: z.number(),\n timestampMs: z.number()\n});\nconst MetricsGpuInfoSchema = z.object({\n utilization: z.number(),\n model: z.string(),\n memoryUsedBytes: z.number(),\n memoryTotalBytes: z.number(),\n temperature: z.number().nullable()\n});\nconst ProcessResourceInfoSchema = z.object({\n openFds: z.number(),\n threadCount: z.number(),\n activeHandles: z.number(),\n activeRequests: z.number()\n});\nconst PressureAvgsSchema = z.object({\n avg10: z.number(),\n avg60: z.number(),\n avg300: z.number()\n});\nconst PressureInfoSchema = z.object({\n some: PressureAvgsSchema,\n full: PressureAvgsSchema.nullable()\n});\nconst SystemResourceSnapshotSchema = z.object({\n cpu: CpuBreakdownSchema,\n memory: MemoryInfoSchema,\n gpu: MetricsGpuInfoSchema.nullable(),\n network: NetworkIoSnapshotSchema,\n disk: DiskIoSnapshotSchema,\n pressure: z.object({\n cpu: PressureInfoSchema.nullable(),\n memory: PressureInfoSchema.nullable(),\n io: PressureInfoSchema.nullable()\n }),\n process: ProcessResourceInfoSchema,\n cpuTemperature: z.number().nullable(),\n timestampMs: z.number()\n});\nconst DiskSpaceInfoSchema = z.object({\n path: z.string(),\n totalBytes: z.number(),\n usedBytes: z.number(),\n availableBytes: z.number(),\n percent: z.number()\n});\nconst PidResourceStatsSchema = z.object({\n pid: z.number(),\n cpu: z.number(),\n memory: z.number()\n});\nconst AddonInstanceSchema = z.object({\n addonId: z.string(),\n nodeId: z.string(),\n role: z.enum([\"hub\", \"worker\"]),\n pid: z.number(),\n state: z.enum([\"starting\", \"running\", \"stopping\", \"stopped\", \"crashed\"]),\n uptimeSec: z.number()\n});\nconst NodeProcessSchema = z.object({\n pid: z.number(),\n ppid: z.number(),\n pgid: z.number(),\n classification: z.enum([\"root\", \"managed\", \"system\", \"ghost\"]),\n /** `$process` addon binding when `managed`, else null. */\n addonId: z.string().nullable(),\n /** Kernel-reported nodeId when the process is a known agent/worker. */\n nodeId: z.string().nullable(),\n /** Truncated command line. */\n command: z.string(),\n cpuPercent: z.number(),\n memoryRssBytes: z.number(),\n /** Wall-clock uptime (seconds). Parsed from `ps etime`. */\n uptimeSec: z.number(),\n /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */\n orphaned: z.boolean()\n});\nconst KillProcessInputSchema = z.object({\n pid: z.number(),\n /** Force = SIGKILL. Default is SIGTERM. */\n force: z.boolean().optional()\n});\nconst KillProcessResultSchema = z.object({\n success: z.boolean(),\n reason: z.string().optional(),\n signal: z.enum([\"SIGTERM\", \"SIGKILL\"]).optional()\n});\nconst SystemMetricsSchema = z.object({\n cpuPercent: z.number(),\n memoryPercent: z.number(),\n memoryUsedMB: z.number(),\n memoryTotalMB: z.number(),\n diskPercent: z.number().optional(),\n temperature: z.number().optional(),\n gpuPercent: z.number().optional(),\n gpuMemoryPercent: z.number().optional()\n});\nconst metricsProviderCapability = {\n name: \"metrics-provider\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n /** Fresh, full system snapshot (triggers OS-level collection). */\n collectSnapshot: method(z.void(), SystemResourceSnapshotSchema),\n /** Most recent cached snapshot from the background sampler, or null pre-first-sample. */\n getCached: method(z.void(), SystemResourceSnapshotSchema.nullable()),\n /** Light-weight cached summary for heartbeats and list views. */\n getCurrent: method(z.void(), SystemMetricsSchema),\n /** Disk space for the given mount/path. */\n getDiskSpace: method(z.object({ dirPath: z.string() }), DiskSpaceInfoSchema),\n /** GPU info (null if unavailable). */\n getGpuInfo: method(z.void(), MetricsGpuInfoSchema.nullable()),\n /** CPU temperature in °C (null if unavailable). */\n getCpuTemperature: method(z.void(), z.number().nullable()),\n /** Per-PID resource stats. Missing/dead PIDs are omitted from the result. */\n getProcessStats: method(\n z.object({ pids: z.array(z.number()) }),\n z.array(PidResourceStatsSchema)\n ),\n /**\n * List addon instances known to this node — one entry per forked worker\n * plus a synthetic 'hub' entry representing the local hub process.\n * Used by benchmarks/observability to detect whether a given addon runs\n * in its own process (measurable independently) or inline with the hub.\n */\n listAddonInstances: method(z.void(), z.array(AddonInstanceSchema).readonly()),\n /**\n * Resource stats for the process hosting the given addon.\n * Returns null when the addon runs in-process on the hub (can't measure\n * independently — caller should detect via listAddonInstances). Returns\n * hub process stats for addonId '$hub'.\n */\n getAddonStats: method(z.object({ addonId: z.string() }), PidResourceStatsSchema.nullable()),\n /**\n * Snapshot of every camstack-related process on this node with a\n * ghost/managed/root classification. Powers the Cluster → Agent →\n * Processes tab: cross-references `$process.list` against a `ps` scan\n * so orphaned trees (PPID=1) or unknown children show up as `ghost`\n * and can be killed from the UI.\n */\n listNodeProcesses: method(z.void(), z.array(NodeProcessSchema).readonly()),\n /**\n * Send SIGTERM (or SIGKILL when `force`) to a pid inside this node's\n * process tree. The provider refuses pids that aren't in the live\n * `listNodeProcesses()` snapshot — callers can't use this endpoint\n * to kill arbitrary system processes.\n */\n killProcess: method(\n KillProcessInputSchema,\n KillProcessResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst PtzPresetSchema = z.object({ id: z.string(), name: z.string() });\nconst PtzPositionSchema = z.object({ pan: z.number(), tilt: z.number(), zoom: z.number() });\nconst PtzMoveCommandSchema = z.object({\n pan: z.number().optional(),\n tilt: z.number().optional(),\n zoom: z.number().optional(),\n speed: z.number().optional()\n});\nconst PtzStatusSchema = PtzPositionSchema.extend({ autofocus: z.boolean() });\nconst PtzOptionsSchema = z.object({\n hasPan: z.boolean(),\n hasTilt: z.boolean(),\n hasZoom: z.boolean(),\n supportsPresets: z.boolean(),\n /** Max number of named presets the camera supports, when known. */\n maxPresets: z.number().optional(),\n /** Whether the camera exposes a controllable autofocus toggle\n * (boolean `hasX` per the getOptions availability convention). */\n hasAutofocus: z.boolean()\n});\nconst ptzCapability = {\n name: \"ptz\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n deviceConfig: {\n ui: { kind: \"widget\", widgetId: \"host/ptz-panel\", tab: \"ptz\", topTab: true, label: \"PTZ\", order: 0 }\n },\n methods: {\n move: method(\n PtzMoveCommandSchema.extend({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n continuousMove: method(\n PtzMoveCommandSchema.extend({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n stop: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n getPresets: method(\n z.object({ deviceId: z.number() }),\n z.array(PtzPresetSchema)\n ),\n goToPreset: method(\n z.object({ deviceId: z.number(), presetId: z.string() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n savePreset: method(\n z.object({ deviceId: z.number(), presetId: z.string(), name: z.string() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n deletePreset: method(\n z.object({ deviceId: z.number(), presetId: z.string() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n getOptions: method(\n z.object({ deviceId: z.number() }),\n PtzOptionsSchema\n ),\n goHome: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /**\n * Pull the current PTZ position. Redundant with the auto-injected\n * `getStatus` method (see `status` below); kept for callers that\n * haven't migrated. Will be folded into `getStatus` in a future\n * cleanup pass once all consumers use the typed status surface.\n */\n getPosition: method(\n z.object({ deviceId: z.number() }),\n PtzPositionSchema\n ),\n /** Toggle the camera's autofocus. Only meaningful when\n * `getOptions().hasAutofocus` is true. */\n setAutofocus: method(\n z.object({ deviceId: z.number(), enabled: z.boolean() }),\n z.void(),\n { kind: \"mutation\" }\n )\n },\n status: {\n schema: PtzStatusSchema,\n kind: \"command-driven\"\n }\n};\nconst EventItemSchema = z.object({\n id: z.string(),\n type: z.string(),\n timestamp: z.number(),\n // unix ms\n label: z.string().optional(),\n thumbnailUrl: z.string().optional(),\n clipUrl: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional()\n});\nconst eventsCapability = {\n name: \"events\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n getEvents: method(\n z.object({\n deviceId: z.number(),\n from: z.number().optional(),\n to: z.number().optional(),\n limit: z.number().optional()\n }),\n z.array(EventItemSchema)\n ),\n getEventThumbnail: method(\n z.object({ deviceId: z.number(), eventId: z.string() }),\n z.object({ base64: z.string(), contentType: z.string() }).nullable()\n ),\n getEventClipUrl: method(\n z.object({ deviceId: z.number(), eventId: z.string() }),\n z.string().nullable()\n )\n }\n};\nconst SegmentSchema = z.object({\n id: z.string(),\n startTs: z.number(),\n // unix ms\n endTs: z.number(),\n durationSec: z.number(),\n sizeBytes: z.number().optional()\n});\nconst recordingCapability = {\n name: \"recording\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n getSegments: method(\n z.object({\n deviceId: z.number(),\n from: z.number().optional(),\n to: z.number().optional()\n }),\n z.array(SegmentSchema)\n ),\n getPlaybackUrl: method(\n z.object({ deviceId: z.number(), segmentId: z.string() }),\n z.string().nullable()\n ),\n getThumbnailAt: method(\n z.object({ deviceId: z.number(), timestamp: z.number() }),\n z.object({ base64: z.string(), contentType: z.string() }).nullable()\n )\n }\n};\nconst StreamSourceEntrySchema = z.object({\n id: z.string(),\n label: z.string(),\n protocol: z.enum([\"rtsp\", \"rtmp\", \"annexb\", \"http-mjpeg\", \"webrtc\", \"custom\"]),\n url: z.string().optional(),\n resolution: z.object({ width: z.number(), height: z.number() }).optional(),\n fps: z.number().optional(),\n bitrate: z.number().optional(),\n codec: z.string().optional(),\n profileHint: z.enum([\"high\", \"mid\", \"low\"]).optional(),\n sdp: z.string().optional()\n});\nconst ConfigEntrySchema = z.object({\n key: z.string(),\n value: z.unknown()\n});\nconst deviceOpsCapability = {\n name: \"device-ops\",\n scope: \"device\",\n mode: \"singleton\",\n methods: {\n /**\n * Return stream sources for camera-like devices. Non-camera devices\n * return an empty array (the bridge did the same; preserved for compat).\n */\n getStreamSources: method(\n z.object({ deviceId: z.number() }),\n z.array(StreamSourceEntrySchema)\n ),\n /**\n * Return the device's config entries (key + current value). Used by\n * the device-manager aggregator when reading the driver's schema+values.\n */\n getConfigEntries: method(\n z.object({ deviceId: z.number() }),\n z.array(ConfigEntrySchema)\n ),\n /**\n * Bulk-apply a config patch via `IDevice.config.setAll`. Covers the\n * updateConfig / setStreamProfileMap / enable-as-config paths from\n * the old bridge.\n */\n setConfig: method(\n z.object({\n deviceId: z.number(),\n values: z.record(z.string(), z.unknown())\n }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /**\n * Invoke `IDevice.removeDevice()` so the driver can release resources\n * (close sockets, stop background tasks, …). The device-manager still\n * performs its own persistence cleanup before/after this call.\n */\n removeDevice: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\" }\n ),\n /**\n * Build the ConfigUISchema (FormBuilder input shape) from the device's\n * Zod config schema. Runs on the worker that owns the IDevice so the\n * Zod types stay local (they're function references, not\n * serializable). Returns a fully JSON-serializable schema with\n * sections/fields the admin UI renders directly.\n *\n * Needed because the hub-side `device-manager.getSettingsSchema`\n * couldn't reach forked-worker devices — it had no registry entry\n * and no cross-process lookup, so the UI silently rendered an empty\n * settings panel for every worker-owned device.\n *\n * Returns `null` when the device isn't found on this worker.\n */\n getSettingsSchema: method(\n z.object({ deviceId: z.number() }),\n z.unknown().nullable()\n )\n }\n};\nconst CameraCredentialsSchema = z.object({\n /** Camera IP or hostname (no scheme). */\n host: z.string(),\n /** Primary protocol port (varies per vendor: Baichuan 9000, ISAPI 80/443, RTSP 554). */\n port: z.number().int().positive().optional(),\n /** ONVIF service port if known by the provider. */\n onvifPort: z.number().int().positive().optional(),\n /** RTSP service port if known. */\n rtspPort: z.number().int().positive().optional(),\n /** HTTP(S) flag for the primary protocol port. */\n https: z.boolean().optional(),\n /** Login username. */\n username: z.string().optional(),\n /** Login password. CONSUMERS MUST NOT log or event-bus this value. */\n password: z.string().optional(),\n /** ONVIF profile hint advertised by the camera (`T`, `Q`, `G`, `S`). */\n onvifProfile: z.string().optional()\n});\nconst CameraCredentialsStatusSchema = z.object({\n host: z.string(),\n port: z.number().int().positive().nullable(),\n onvifPort: z.number().int().positive().nullable(),\n rtspPort: z.number().int().positive().nullable(),\n https: z.boolean().nullable(),\n hasUsername: z.boolean(),\n hasPassword: z.boolean(),\n onvifProfile: z.string().nullable()\n});\nconst cameraCredentialsCapability = {\n name: \"camera-credentials\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n /**\n * Return the camera's full credential bundle for admin consumers.\n * Each provider implementation returns a snapshot of its persisted\n * config — no I/O to the camera. Returns null when the device is\n * not owned by this addon (deviceId mismatch).\n */\n getCredentials: method(\n z.object({ deviceId: z.number() }),\n CameraCredentialsSchema.nullable(),\n { kind: \"query\", auth: \"admin\" }\n )\n },\n status: {\n schema: CameraCredentialsStatusSchema,\n kind: \"command-driven\"\n }\n};\nconst rebootCapability = {\n name: \"reboot\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera, DeviceType.Sensor, DeviceType.Switch],\n methods: {\n reboot: method(\n z.object({ deviceId: z.number().int().nonnegative() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst OsdOverlayKindEnum = z.enum([\"text\", \"timestamp\", \"watermark\"]);\nconst OsdPositionEnum = z.enum([\n \"top-left\",\n \"top-center\",\n \"top-right\",\n \"bottom-left\",\n \"bottom-center\",\n \"bottom-right\",\n \"custom\"\n]);\nconst OsdOverlaySchema = z.object({\n /** Stable driver-assigned id. Reolink uses `'channel'`, `'time'`, `'watermark'`. */\n id: z.string(),\n kind: OsdOverlayKindEnum,\n enabled: z.boolean(),\n /** Active text (text/watermark). Undefined for 'timestamp' (firmware-generated). */\n text: z.string().optional(),\n position: OsdPositionEnum.optional(),\n /**\n * Positions the firmware accepts for this specific overlay. Populated\n * by the driver at register time. Empty array → positioning not\n * configurable; the UI hides the position field.\n */\n availablePositions: z.array(OsdPositionEnum).readonly(),\n /** Firmware does not allow editing the `text` field (e.g. timestamp). */\n readOnly: z.boolean().optional()\n});\nconst OsdStatusSchema = z.object({\n overlays: z.array(OsdOverlaySchema).readonly()\n});\nconst OsdOverlayPatchSchema = z.object({\n enabled: z.boolean().optional(),\n text: z.string().optional(),\n position: OsdPositionEnum.optional()\n}).partial();\nconst osdCapability = {\n name: \"osd\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n /**\n * Patch a single overlay by id. Provider handles read-modify-write\n * against firmware APIs that require the full object (Reolink\n * `SetOsd`). Omitted patch keys are preserved. Successful\n * completion triggers `onStatusChanged`.\n */\n setOverlay: method(\n z.object({\n deviceId: z.number(),\n overlayId: z.string(),\n patch: OsdOverlayPatchSchema\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n },\n events: {\n onStatusChanged: { data: z.object({\n deviceId: z.number(),\n status: OsdStatusSchema\n }) }\n },\n status: {\n schema: OsdStatusSchema,\n kind: \"command-driven\"\n },\n settings: {\n bindings: [{\n kind: \"array\",\n statusPath: \"overlays\",\n idField: \"id\",\n method: \"setOverlay\",\n idArg: \"overlayId\",\n patchArg: \"patch\",\n sectionId: \"osd\",\n sectionTitle: \"Video overlays\",\n itemFields: {\n enabled: {\n label: (o) => `${String(o.id)} enabled`,\n kind: \"boolean\"\n },\n text: {\n label: (o) => `${String(o.id)} text`,\n kind: \"text\",\n when: (o) => o.kind !== \"timestamp\" && !o.readOnly\n },\n position: {\n label: (o) => `${String(o.id)} position`,\n kind: \"select\",\n options: (o) => o.availablePositions ?? [],\n when: (o) => Array.isArray(o.availablePositions) && o.availablePositions.length > 0\n }\n }\n }]\n }\n};\nconst AccessoriesStatusSchema = z.object({\n childDeviceIds: z.array(z.number()).readonly()\n});\nconst accessoriesCapability = {\n name: \"accessories\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera, DeviceType.Hub],\n methods: {},\n events: {\n /**\n * Emitted when a child device is created, removed, or its parent\n * assignment changes. Payload carries the fresh list.\n */\n onAccessoriesChanged: { data: z.object({\n deviceId: z.number(),\n childDeviceIds: z.array(z.number()).readonly()\n }) }\n },\n status: {\n schema: AccessoriesStatusSchema,\n kind: \"command-driven\"\n }\n};\nconst IntercomAbilitySchema = z.object({\n /** Codecs accepted by firmware, in preference order. Driver-authored strings. */\n codecs: z.array(z.string()),\n /** Sample rate (Hz) the firmware expects. Reolink typical: 16000. */\n sampleRate: z.number(),\n duplex: z.enum([\"half\", \"full\"]),\n /** Max in-flight audio backlog before drop (ms). Server uses this to bound latency. */\n maxBacklogMs: z.number()\n});\nconst IntercomStatusSchema = z.object({\n /** True while a talk session is open. */\n talking: z.boolean(),\n /** Ms epoch of the most recent session start. Null if never opened. */\n lastSessionAt: z.number().nullable(),\n /** Firmware ability cached at first session creation. Null until probed. */\n ability: IntercomAbilitySchema.nullable()\n});\nconst intercomCapability = {\n name: \"intercom\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {\n /**\n * Open a server-side WebRTC audio-only session. Returns an SDP\n * offer with a single sendonly audio m-line the client answers\n * (client → server direction). The server wakes battery cams\n * transparently before opening the upstream talk channel.\n */\n startSession: method(\n z.object({ deviceId: z.number() }),\n z.object({ sessionId: z.string(), sdpOffer: z.string() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n handleAnswer: method(\n z.object({\n deviceId: z.number(),\n sessionId: z.string(),\n sdpAnswer: z.string()\n }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Close explicitly. Server also auto-closes on 30s idle. */\n stopSession: method(\n z.object({ deviceId: z.number(), sessionId: z.string() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Open a raw-PCM talk session (no WebRTC SDP plumbing). Used by\n * non-WebRTC consumers (HomeKit export, Alexa raw audio, test\n * harnesses) that already have decoded PCM frames and just need a\n * direct path onto the camera's talk channel. Mutually exclusive\n * with `startSession` (an active WebRTC session must be stopped\n * before a raw-PCM session can be opened on the same device, and\n * vice versa).\n */\n startTalkSession: method(\n z.object({ deviceId: z.number() }),\n z.object({ sessionId: z.string() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Push a chunk of PCM s16le mono onto the active raw-PCM talk\n * session. Frames are encoded to the firmware's expected codec\n * (Reolink: IMA ADPCM @ camera sample rate; Hikvision: G.711 @\n * 8 kHz) inside the provider — callers must resample upstream to\n * the rate the camera negotiated (typical: 16 kHz Reolink,\n * 8 kHz Hikvision). PCM is shipped base64-encoded so the payload\n * survives JSON serialization across tRPC.\n */\n pushTalkPcm: method(\n z.object({\n deviceId: z.number(),\n /** PCM frames as little-endian s16, mono. Base64-encoded so\n * the payload survives tRPC JSON serialization. */\n pcmBase64: z.string(),\n /** Sequence number for ordering / dropping out-of-order frames. */\n sequenceNumber: z.number().int()\n }),\n z.object({ accepted: z.boolean() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Close the raw-PCM talk session. Idempotent. */\n endTalkSession: method(\n z.object({ deviceId: z.number() }),\n z.void(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n },\n events: {\n onStatusChanged: { data: z.object({\n deviceId: z.number(),\n status: IntercomStatusSchema\n }) }\n },\n status: {\n schema: IntercomStatusSchema,\n kind: \"command-driven\"\n }\n};\nconst NativeObjectClassEnum = z.enum([\n \"person\",\n \"vehicle\",\n \"animal\",\n \"face\",\n \"package\",\n \"other\"\n]);\nconst NativeDetectionSchema = z.object({\n class: NativeObjectClassEnum,\n timestamp: z.number(),\n /** Firmware-provided confidence [0..1]. Reolink pushes don't carry it → undefined. */\n confidence: z.number().min(0).max(1).optional()\n});\nconst NativeObjectDetectionStatusSchema = z.object({\n /**\n * Last observed instance per class. Undefined entries mean the class\n * is supported but nothing has been seen since the provider started.\n */\n lastByClass: z.record(NativeObjectClassEnum, NativeDetectionSchema.nullable()),\n /** Classes the firmware is capable of detecting — enumerated at device register. */\n supportedClasses: z.array(NativeObjectClassEnum).readonly()\n});\nconst nativeObjectDetectionCapability = {\n name: \"native-object-detection\",\n scope: \"device\",\n mode: \"singleton\",\n deviceTypes: [DeviceType.Camera],\n methods: {},\n events: {\n onDetected: { data: z.object({\n deviceId: z.number(),\n detection: NativeDetectionSchema\n }) }\n },\n status: {\n schema: NativeObjectDetectionStatusSchema,\n kind: \"push\"\n }\n};\nconst ModelFormatSchema = z.enum(MODEL_FORMATS);\nconst HwAccelBackendInputSchema = z.enum([\n \"videotoolbox\",\n \"cuda\",\n \"nvdec\",\n \"vaapi\",\n \"qsv\",\n \"d3d11va\",\n \"dxva2\",\n \"amf\",\n \"vdpau\",\n \"drm\",\n \"coreml\",\n \"tensorrt\",\n \"openvino\",\n \"directml\",\n \"webgpu\",\n \"none\"\n]).nullable().optional();\nconst HwAccelResolutionSchema = z.object({\n preferred: z.array(z.string()).readonly()\n});\nconst HardwareEncoderIdSchema = z.enum([\n \"h264_videotoolbox\",\n \"hevc_videotoolbox\",\n \"h264_vaapi\",\n \"hevc_vaapi\",\n \"h264_nvenc\",\n \"hevc_nvenc\",\n \"h264_qsv\",\n \"hevc_qsv\",\n \"h264_amf\",\n \"hevc_amf\",\n \"libx264\",\n \"libx265\"\n]);\nconst HardwareEncoderProbeSchema = z.object({\n encoder: HardwareEncoderIdSchema,\n codec: z.enum([\"H264\", \"H265\"]),\n family: z.enum([\"videotoolbox\", \"vaapi\", \"nvenc\", \"qsv\", \"amf\", \"software\"]),\n available: z.boolean(),\n reason: z.string().optional()\n});\nconst HardwareEncodersSchema = z.object({\n encoders: z.array(HardwareEncoderProbeSchema).readonly(),\n defaultH264: HardwareEncoderIdSchema,\n defaultH265: HardwareEncoderIdSchema,\n probedAt: z.number()\n});\nconst HardwarePlatformSchema = z.enum([\"darwin\", \"linux\", \"win32\"]);\nconst HardwareArchSchema = z.enum([\"arm64\", \"x64\"]);\nconst GpuInfoSchema = z.object({\n type: z.enum([\"nvidia\", \"amd\", \"intel\", \"apple\"]),\n name: z.string(),\n memoryMB: z.number().optional()\n});\nconst NpuInfoSchema = z.object({\n type: z.enum([\"apple-ane\", \"intel-npu\"])\n});\nconst HardwareInfoSchema = z.object({\n platform: HardwarePlatformSchema,\n arch: HardwareArchSchema,\n cpuModel: z.string(),\n cpuCores: z.number(),\n totalRAM_MB: z.number(),\n availableRAM_MB: z.number(),\n gpu: GpuInfoSchema.nullable(),\n npu: NpuInfoSchema.nullable()\n});\nconst PlatformScoreSchema = z.object({\n runtime: z.enum([\"node\", \"python\"]),\n backend: z.string(),\n format: z.enum([\"onnx\", \"coreml\", \"openvino\"]),\n score: z.number(),\n reason: z.string(),\n available: z.boolean()\n});\nconst PlatformCapabilitiesSchema = z.object({\n hardware: HardwareInfoSchema,\n scores: z.array(PlatformScoreSchema).readonly(),\n bestScore: PlatformScoreSchema,\n pythonPath: z.string().nullable()\n});\nconst ModelRequirementSchema = z.object({\n modelId: z.string(),\n name: z.string(),\n minRAM_MB: z.number(),\n accuracyScore: z.number(),\n formats: z.array(z.string()).readonly()\n});\nconst ResolvedInferenceConfigSchema = z.object({\n modelId: z.string(),\n runtime: z.enum([\"node\", \"python\"]),\n backend: z.string(),\n format: ModelFormatSchema,\n reason: z.string()\n});\nconst platformProbeCapability = {\n name: \"platform-probe\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n getCapabilities: method(z.void(), PlatformCapabilitiesSchema),\n getHardware: method(z.void(), HardwareInfoSchema),\n resolveInferenceConfig: method(\n z.object({ requirements: z.array(ModelRequirementSchema).readonly() }),\n ResolvedInferenceConfigSchema\n ),\n resolveHwAccel: method(\n z.object({ prefer: HwAccelBackendInputSchema, nodeId: z.string().optional() }),\n HwAccelResolutionSchema\n ),\n /**\n * Hardware-encoder probe — see Task #185. Cached after first call.\n */\n getHardwareEncoders: method(z.void(), HardwareEncodersSchema),\n refreshHardwareEncoders: method(\n z.void(),\n HardwareEncodersSchema,\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst InterfaceKindEnum = z.enum([\n \"lan\",\n // wired ethernet (en0, eth0, ...)\n \"wifi\",\n // wireless (en1, wlan*, ...)\n \"docker\",\n // docker0 / br-* / veth*\n \"vpn\",\n // tun*, utun*, wg*, tap*\n \"loopback\",\n // lo, lo0\n \"other\"\n // anything we can't classify confidently\n]);\nconst LocalInterfaceSchema = z.object({\n /** Interface name as reported by the OS (e.g. `en0`, `eth0`, `lo0`). */\n name: z.string(),\n family: z.enum([\"IPv4\", \"IPv6\"]),\n address: z.string(),\n /** CIDR shorthand (e.g. `192.168.1.10/24`). Empty when OS doesn't expose. */\n cidr: z.string(),\n /** OS netmask. Stable across calls so the SDK can hash on it. */\n netmask: z.string(),\n /** True for `127.0.0.1`/`::1`. Returned for completeness but never preferred. */\n internal: z.boolean(),\n /** Hardware MAC (empty for loopback / virtual interfaces). */\n mac: z.string(),\n /** Derived classification — see `InterfaceKindEnum`. */\n kind: InterfaceKindEnum,\n /**\n * `true` for the auto-selected outbound interface. Exactly zero or\n * one entry has this set per call; the SDK picks this one for the\n * first connection attempt.\n */\n preferred: z.boolean(),\n /**\n * Heuristic flag: `true` when the address looks usable for clients\n * (RFC 1918 / public IPv4, IPv6 ULA / GUA), `false` for link-local\n * / loopback / multicast / docker / vpn / unknown ranges. Same\n * heuristic that drives `autoSeedAllowlist`.\n */\n plausible: z.boolean(),\n /**\n * Human-readable rationale for non-plausible entries (e.g. \"IPv6\n * link-local — only reachable on the same link\"). Empty string for\n * plausible entries. The UI surfaces this verbatim as the tooltip\n * on the \"Unlikely usable\" badge so the backend stays the single\n * source of truth — front-end consumers don't re-derive the reason.\n */\n plausibleReason: z.string()\n});\nconst ListResultSchema = z.object({\n interfaces: z.array(LocalInterfaceSchema).readonly(),\n /** Wall-clock timestamp at which the snapshot was probed. */\n probedAt: z.number()\n});\nconst PreferredSchema = LocalInterfaceSchema.nullable();\nconst ConnectionEndpointSchema = z.object({\n /** Operator-facing label (e.g. \"LAN — en0\", \"Public tunnel\"). */\n label: z.string(),\n /** Fully-formed base URL with scheme + host + port. */\n baseUrl: z.string(),\n /** Network-level hint for the SDK — picks a small icon, sorts within\n * a tier. Coarse categorisation (LAN vs public vs loopback). */\n kind: z.enum([\n \"lan-ipv4\",\n // private RFC1918 / link-local IPv4\n \"lan-ipv6\",\n // private IPv6\n \"public\",\n // tunnel / external FQDN\n \"loopback\"\n // 127.0.0.1 — last-resort fallback\n ]),\n /**\n * Originating-interface kind — `lan`/`wifi`/`docker`/`vpn`/`other`/\n * `loopback`/`public`. Lets the UI render an accurate badge (e.g. a\n * VPN address gets a \"VPN\" tag instead of being lumped under\n * \"lan-ipv4\"). `'public'` for the tunnel hostname.\n */\n interfaceKind: z.enum([\"lan\", \"wifi\", \"docker\", \"vpn\", \"other\", \"loopback\", \"public\"]),\n /**\n * Mirrors `LocalInterface.plausible` — false for endpoints derived\n * from non-plausible interfaces (VPN, docker, link-local, …). The\n * UI uses it to mark \"Unlikely usable\" without re-deriving from\n * the address shape.\n */\n plausible: z.boolean(),\n /** Same as `LocalInterface.plausibleReason` — empty when plausible. */\n plausibleReason: z.string(),\n /**\n * Suggested priority for racing — lower = try first. Stable across\n * calls so the client can sort even if the cap returns a new\n * ordering between polls.\n */\n priority: z.number()\n});\nconst GetConnectionEndpointsResultSchema = z.object({\n endpoints: z.array(ConnectionEndpointSchema).readonly()\n});\nconst AllowedAddressesSchema = z.object({\n /**\n * Allowlist of interface addresses operators have explicitly opted\n * into for the connection-endpoint race. Empty array = \"auto\" — every\n * non-loopback / non-link-local interface participates. Set by the\n * Network Addresses admin page and persisted by the addon.\n */\n addresses: z.array(z.string()).readonly()\n});\nconst localNetworkCapability = {\n name: \"local-network\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n /** Return the current interface snapshot. */\n list: method(z.void(), ListResultSchema),\n /**\n * Auto-selected outbound interface. Heuristic:\n * 1. Skip internal / link-local / 169.254.*.\n * 2. Prefer LAN/wifi (real Ethernet) over docker/vpn.\n * 3. IPv4 wins over IPv6 (compat with legacy consumers).\n * 4. Tie-break on lowest CIDR mask (most-specific subnet).\n * Returns `null` only when the host has zero non-loopback addresses.\n * Honours `getAllowedAddresses()` — if the operator pinned an\n * allowlist, only those addresses are candidates.\n */\n getPreferred: method(z.void(), PreferredSchema),\n /**\n * Ordered candidate base URLs the SDK should try on connect.\n * Includes LAN IPs (one per non-internal interface), the public\n * tunnel hostname (when active), and loopback as a last-resort\n * fallback. Filterable by `includeLoopback` / `ipv4Only`.\n * Honours `getAllowedAddresses()` when set — addresses outside\n * the allowlist are dropped (the public tunnel + loopback are\n * always included as escape hatches).\n */\n getConnectionEndpoints: method(\n z.object({\n /** Local hub HTTP port to use in base URLs. */\n port: z.number().int().min(1).max(65535),\n /** Include `http(s)://127.0.0.1:<port>` as the lowest-priority\n * candidate. Default `true`. */\n includeLoopback: z.boolean().optional(),\n /** Skip IPv6 entries. Some legacy clients can't parse them.\n * Default `false`. */\n ipv4Only: z.boolean().optional(),\n /** Scheme to emit for LAN/loopback URLs. Default `'http'`.\n * Pass `'https'` when the caller is itself loaded over HTTPS\n * to avoid mixed-content blocks in the browser. The public\n * tunnel always emits `https://` regardless. */\n scheme: z.enum([\"http\", \"https\"]).optional()\n }),\n GetConnectionEndpointsResultSchema\n ),\n /**\n * Read the operator's allowlist. Empty = \"auto\" (no filter). Used\n * by the admin UI's address selector to seed its checkbox state.\n */\n getAllowedAddresses: method(z.void(), AllowedAddressesSchema),\n /**\n * Replace the allowlist atomically. Persisted via the addon store\n * (kernel-managed) so it survives restarts. Pass `[]` to revert to\n * auto mode.\n */\n setAllowedAddresses: method(\n AllowedAddressesSchema,\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\" }\n ),\n /**\n * Re-run the boot heuristic over the current interface snapshot\n * and atomically replace the allowlist with the result. Useful\n * after a major network change (new dock, new VPN, IP rebound)\n * when the operator wants to wipe their manual edits and start\n * over from the auto-detected best matches.\n */\n resetAllowlistToBestMatch: method(\n z.void(),\n AllowedAddressesSchema,\n { kind: \"mutation\" }\n )\n }\n};\nconst MeshEndpointSchema = z.object({\n /** Stable identifier within the provider (e.g. `mesh-ipv4`, `magicdns`, `funnel`). */\n id: z.string(),\n /** Operator-facing label (e.g. \"Mesh IPv4\", \"MagicDNS\"). */\n label: z.string(),\n /**\n * Where the endpoint is reachable from:\n * - `mesh`: only peers on the same mesh (Tailscale tailnet, …)\n * - `public`: open internet (Funnel, public-tunnel pass-through)\n */\n scope: z.enum([\"mesh\", \"public\"]),\n /** Full base URL (e.g. `https://camstack.tail-abc.ts.net`). */\n url: z.string(),\n /** Hostname portion (for SAN cert checks + display). */\n hostname: z.string(),\n /** Port (`443` for Funnel/Serve, anything for raw mesh IP). */\n port: z.number(),\n /** Always `http` or `https`. */\n protocol: z.enum([\"http\", \"https\"])\n});\nconst MeshPeerSchema = z.object({\n /** Stable peer id assigned by the mesh control plane. */\n id: z.string(),\n /** Hostname / device name as shown in the mesh dashboard. */\n hostname: z.string(),\n /** MagicDNS / mesh DNS name (e.g. `peer-foo.tail-abc.ts.net`). Empty when the provider doesn't support DNS or peer-side resolution is disabled. */\n magicDns: z.string(),\n /** Mesh IPv4 / IPv6 addresses combined. Multiple when dual-stacked. */\n addresses: z.array(z.string()).readonly(),\n /** Operating system reported by the peer (informational). */\n os: z.string().optional(),\n /** Whether this peer is currently reachable. */\n online: z.boolean(),\n /** Last-seen timestamp (epoch ms). 0 when never seen. */\n lastSeenMs: z.number(),\n /** True for the row representing the current host. */\n isSelf: z.boolean(),\n /**\n * Connection mode to this peer:\n * - `direct`: NAT-traversed P2P (UDP punched)\n * - `relay`: traffic relayed through provider edge (Tailscale DERP)\n * - `idle`: peer reachable but no recent traffic / handshake\n */\n connection: z.enum([\"direct\", \"relay\", \"idle\"]),\n /** DERP region / relay node identifier when `connection: relay`. Null otherwise. */\n relay: z.string().nullable(),\n /** Last successful handshake timestamp (epoch ms). 0 when never. */\n lastHandshakeMs: z.number(),\n /** Bytes received from this peer since the daemon started. */\n rxBytes: z.number(),\n /** Bytes transmitted to this peer since the daemon started. */\n txBytes: z.number(),\n /** ACL tags this peer carries (e.g. `[\"tag:server\"]`). Empty when human-owned. */\n tags: z.array(z.string()).readonly(),\n /** True when the peer advertises itself as an exit-node candidate. */\n exitNodeOption: z.boolean(),\n /** Subnet routes the peer advertises (e.g. `[\"192.168.1.0/24\"]`). */\n advertisedRoutes: z.array(z.string()).readonly(),\n /** Owner account login (e.g. `foo@example.com`). Null for tagged peers. */\n userLogin: z.string().nullable(),\n /** Pre-auth key / machine-key expiry (epoch ms). Null when keys don't expire. */\n keyExpiry: z.number().nullable()\n});\nconst MeshStatusSchema = z.object({\n /** True when the host is joined and the daemon reports healthy. */\n joined: z.boolean(),\n /** Local mesh IPv4 (e.g. `100.x.x.x` for Tailscale). Empty when not joined. */\n meshIp: z.string(),\n /** MagicDNS / mesh hostname (e.g. `camstack.tail-abc.ts.net`). Empty if not configured. */\n magicDnsHostname: z.string(),\n /** Number of peers visible to this host (excluding self). */\n peerCount: z.number(),\n /** Every endpoint this provider exposes for the current host. */\n endpoints: z.array(MeshEndpointSchema).readonly(),\n /** Last error from the daemon, when not joined. */\n error: z.string().optional(),\n // ── Account / tenant identity (generic across providers) ────────\n /**\n * Tenant / tailnet / network display name (Tailscale = tailnet\n * domain, Headscale = namespace, ZeroTier = network name). Empty\n * pre-join. Per-provider semantics, common slot.\n */\n tenantName: z.string(),\n /**\n * Mesh DNS suffix when the provider exposes peer-resolvable DNS\n * (Tailscale MagicDNS, Headscale MagicDNS, …). Empty when the\n * provider doesn't ship DNS (e.g. ZeroTier).\n */\n magicDnsSuffix: z.string(),\n /**\n * Authenticated user / account login bound to this host. Null when\n * the provider authenticates with a long-lived network token rather\n * than a user account (e.g. ZeroTier API token).\n */\n userLogin: z.string().nullable(),\n /**\n * Provider control-plane URL (Tailscale SaaS `https://login.tailscale.com`,\n * self-hosted Headscale, ZeroTier Central, …). Empty when not\n * applicable (rare).\n */\n controlPlaneUrl: z.string(),\n /**\n * Machine-key / node-key expiry (epoch ms). Null when the provider\n * doesn't rotate keys for the bound host. Operator-facing surface\n * for \"your access expires on …\" banners.\n */\n keyExpiry: z.number().nullable(),\n // ── Onboard-daemon handoff (Tailscale, generic slot) ────────────\n /**\n * When the provider runs its OWN mesh daemon (e.g. the Tailscale\n * client addon in `onboard` mode spawns a private `tailscaled`),\n * this carries the local control-socket path. Companion addons that\n * must drive the SAME daemon — chiefly `tailscale-ingress` for\n * Serve/Funnel — read it to point their CLI at the right socket\n * instead of the system default. Empty when the provider uses the\n * host's system daemon (or doesn't have the concept).\n */\n daemonSocket: z.string().optional(),\n /**\n * Path to the mesh CLI binary the provider downloaded for onboard\n * mode. Companion addons reuse it so they don't need a system\n * install when the operator chose a fully self-contained mesh.\n * Empty in host mode.\n */\n daemonCliPath: z.string().optional()\n});\nconst meshNetworkCapability = {\n name: \"mesh-network\",\n scope: \"system\",\n mode: \"collection\",\n providerKind: \"mesh\",\n methods: {\n /** Return the current join state + endpoints + peer count. Cheap\n * poll-target — admin UI hits this every few seconds. */\n getStatus: method(z.void(), MeshStatusSchema),\n /**\n * Join the host to the provider's mesh using a one-time auth key\n * (generated by the operator in the provider's admin dashboard).\n * Implementations should be idempotent — re-calling with the same\n * key while already joined is a no-op + success.\n */\n join: method(\n z.object({\n /** Provider-specific auth key. For Tailscale this is the\n * `tskey-auth-*` token from admin.tailscale.com. */\n authKey: z.string().min(8),\n /** Optional hostname override the host should advertise. */\n hostname: z.string().optional()\n }),\n z.object({ joined: z.literal(true) }),\n { kind: \"mutation\" }\n ),\n /**\n * Start an interactive browser-redirect login flow.\n *\n * The provider spawns its daemon's join command without a pre-auth\n * key, captures the verification URL the daemon prints, and returns\n * it. The admin UI opens the URL in a new tab; the user completes\n * authentication in the provider's web console and the background\n * process self-terminates. The caller then polls `getStatus()` until\n * `joined: true`.\n *\n * Mirrors the `tailscale up` (no `--auth-key`) flow.\n */\n startLogin: method(\n z.object({\n /** Optional hostname override the host should advertise once joined. */\n hostname: z.string().optional()\n }),\n z.object({\n /** Authentication URL the operator should open in a browser. */\n loginUrl: z.string()\n }),\n { kind: \"mutation\" }\n ),\n /** Leave the mesh. After this the meshIp/magicDnsHostname/etc.\n * vanish until the next `join`. The bound account stays — a\n * subsequent `join` reuses it without prompting for a new login. */\n leave: method(\n z.void(),\n z.object({ left: z.literal(true) }),\n { kind: \"mutation\" }\n ),\n /**\n * Sign out of the mesh account entirely. Distinct from `leave`:\n * `leave` only takes the host off-mesh (`tailscale down`) while the\n * account binding survives, so the next `join` reconnects silently.\n * `logout` (`tailscale logout`) wipes the daemon's stored\n * credentials — the next `startLogin` MUST go through a fresh\n * browser-redirect flow to bind a new account.\n */\n logout: method(\n z.void(),\n z.object({ loggedOut: z.literal(true) }),\n { kind: \"mutation\" }\n ),\n /** Enumerate every peer the daemon currently knows about. */\n listPeers: method(z.void(), z.object({\n peers: z.array(MeshPeerSchema).readonly()\n })),\n /**\n * Probe the mesh daemon / API for a sanity check WITHOUT joining.\n * Operator-facing \"test connection\" button: validates the auth key\n * + reaches the control plane and reports back what would happen\n * on join.\n *\n * Tailscale: dry-runs `tailscale up --auth-key=… --reset` against\n * an idempotency probe; for an already-joined node it just returns\n * the current status.\n */\n testConnection: method(\n z.object({\n /** Optional auth key — when provided, probes the key validity\n * against the provider's API. Omit when already joined to\n * just ping the daemon. */\n authKey: z.string().optional()\n }),\n z.object({\n ok: z.boolean(),\n /** Provider-side identifier resolved by the probe (tailnet\n * name for Tailscale, network id for ZeroTier, etc.). */\n tenant: z.string().optional(),\n /** Daemon binary version, when reachable. */\n daemonVersion: z.string().optional(),\n /** Human-readable error when `ok: false`. */\n error: z.string().optional()\n }),\n { kind: \"mutation\" }\n )\n // Provider-specific runtime knobs (accept-routes / advertise-routes /\n // shields-up / ssh / exit-node, …) live on the addon's own\n // `getSettingsUISchema` (form-builder), NOT here. Different mesh\n // providers (Tailscale, Headscale, ZeroTier, Nebula) have very\n // different config surfaces — picking one shape and forcing all\n // implementations to honour it would either lose options or\n // misrepresent them. The Mesh page renders the addon's settings\n // schema as a \"Settings\" tab next to the generic Status / Peers\n // tabs driven by this cap.\n }\n};\nconst UserSummarySchema = z.object({\n id: z.string(),\n username: z.string(),\n isAdmin: z.boolean().default(false),\n allowedProviders: z.union([z.array(z.string()), z.literal(\"*\")]),\n allowedDevices: z.record(z.string(), z.union([z.array(z.string()), z.literal(\"*\")])),\n scopes: z.array(TokenScopeSchema).default([]),\n /**\n * True iff this user has a CONFIRMED TOTP enrollment. Surfaced on\n * `listUsers` so the admin Users page can render the \"Remove 2FA\"\n * action conditionally without firing one `getTotpStatus` query per\n * row. Self-service enrollment lives on the user's profile page.\n */\n totpEnabled: z.boolean().default(false),\n createdAt: z.number(),\n updatedAt: z.number()\n});\nconst CreateUserInputSchema = z.object({\n username: z.string(),\n password: z.string().min(6),\n isAdmin: z.boolean().default(false),\n allowedProviders: z.union([z.array(z.string()), z.literal(\"*\")]).optional(),\n allowedDevices: z.record(z.string(), z.union([z.array(z.string()), z.literal(\"*\")])).optional(),\n scopes: z.array(TokenScopeSchema).optional()\n});\nconst UpdateUserInputSchema = z.object({\n id: z.string(),\n isAdmin: z.boolean().optional(),\n allowedProviders: z.union([z.array(z.string()), z.literal(\"*\")]).optional(),\n allowedDevices: z.record(z.string(), z.union([z.array(z.string()), z.literal(\"*\")])).optional(),\n scopes: z.array(TokenScopeSchema).optional()\n});\nconst ApiKeySummarySchema = z.object({\n id: z.string(),\n label: z.string(),\n isAdmin: z.boolean().default(false),\n allowedProviders: z.union([z.array(z.string()), z.literal(\"*\")]).optional(),\n allowedDevices: z.record(z.string(), z.union([z.array(z.string()), z.literal(\"*\")])).optional(),\n tokenPrefix: z.string(),\n createdAt: z.number(),\n lastUsedAt: z.number().optional()\n});\nconst CreateApiKeyInputSchema = z.object({\n label: z.string(),\n isAdmin: z.boolean().default(false),\n allowedProviders: z.union([z.array(z.string()), z.literal(\"*\")]).optional(),\n allowedDevices: z.record(z.string(), z.union([z.array(z.string()), z.literal(\"*\")])).optional()\n});\nconst CreateApiKeyResultSchema = z.object({\n token: z.string(),\n record: ApiKeySummarySchema\n});\nconst ScopedTokenSummarySchema = z.object({\n id: z.string(),\n userId: z.string(),\n name: z.string(),\n tokenPrefix: z.string(),\n scopes: z.array(TokenScopeSchema),\n expiresAt: z.number().nullish(),\n lastUsedAt: z.number().nullish(),\n createdAt: z.number()\n});\nconst CreateScopedTokenInputSchema = z.object({\n userId: z.string(),\n name: z.string(),\n scopes: z.array(TokenScopeSchema),\n expiresAt: z.number().optional()\n});\nconst CreateScopedTokenResultSchema = z.object({\n token: z.string(),\n record: ScopedTokenSummarySchema\n});\nconst OauthSessionSummarySchema = z.object({\n id: z.string(),\n userId: z.string(),\n username: z.string(),\n integrationId: z.string(),\n scopes: z.array(TokenScopeSchema),\n createdAt: z.number(),\n lastUsedAt: z.number(),\n revokedAt: z.number().nullable()\n});\nconst TotpSetupResultSchema = z.object({\n secret: z.string(),\n otpauthUrl: z.string()\n});\nconst TotpStatusSchema = z.object({\n /** True iff `confirmedAt != null` — a pending half-enrollment is reported as `enabled: false`. */\n enabled: z.boolean(),\n /** Null when no row exists OR the row is still pending confirmation. */\n confirmedAt: z.number().nullable()\n});\nconst userManagementCapability = {\n name: \"user-management\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n listUsers: method(z.void(), z.array(UserSummarySchema), { auth: \"admin\" }),\n createUser: method(CreateUserInputSchema, UserSummarySchema, { kind: \"mutation\", auth: \"admin\", access: \"create\" }),\n updateUser: method(UpdateUserInputSchema, z.object({ success: z.literal(true) }), { kind: \"mutation\", auth: \"admin\", access: \"create\" }),\n deleteUser: method(z.object({ id: z.string() }), z.object({ success: z.literal(true) }), { kind: \"mutation\", auth: \"admin\", access: \"delete\" }),\n resetPassword: method(\n z.object({ id: z.string(), newPassword: z.string().min(6) }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\", access: \"create\" }\n ),\n setUserScopes: method(\n z.object({ userId: z.string(), scopes: z.array(TokenScopeSchema) }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\", access: \"create\" }\n ),\n validateCredentials: method(\n z.object({ username: z.string(), password: z.string() }),\n UserSummarySchema.extend({ passwordHash: z.string() }).nullable(),\n { kind: \"mutation\", access: \"view\" }\n ),\n listApiKeys: method(z.void(), z.array(ApiKeySummarySchema), { auth: \"admin\" }),\n createApiKey: method(CreateApiKeyInputSchema, CreateApiKeyResultSchema, { kind: \"mutation\", auth: \"admin\", access: \"create\" }),\n revokeApiKey: method(z.object({ id: z.string() }), z.object({ success: z.literal(true) }), { kind: \"mutation\", auth: \"admin\", access: \"delete\" }),\n validateApiKey: method(z.object({ token: z.string() }), ApiKeySummarySchema.nullable(), { kind: \"mutation\", access: \"view\" }),\n createScopedToken: method(CreateScopedTokenInputSchema, CreateScopedTokenResultSchema, { kind: \"mutation\", auth: \"admin\", access: \"create\" }),\n revokeScopedToken: method(z.object({ id: z.string() }), z.object({ success: z.literal(true) }), { kind: \"mutation\", auth: \"admin\", access: \"delete\" }),\n validateScopedToken: method(z.object({ token: z.string() }), ScopedTokenSummarySchema.nullable(), { access: \"view\" }),\n listScopedTokens: method(z.object({ userId: z.string() }), z.array(ScopedTokenSummarySchema), { auth: \"admin\" }),\n // ── TOTP / 2FA ─────────────────────────────────────────────────\n //\n // Setup → Confirm → (Verify on login) → Disable.\n //\n // Admin-only for now: operator enrolls TOTP on a user's behalf by\n // pairing their authenticator with the returned QR. Self-service\n // enrollment is a follow-up (needs the cap framework to expose the\n // caller's identity to the provider so the provider can enforce\n // self-or-admin).\n setupTotp: method(\n z.object({ userId: z.string() }),\n TotpSetupResultSchema,\n { kind: \"mutation\", auth: \"admin\", access: \"create\" }\n ),\n confirmTotp: method(\n z.object({ userId: z.string(), code: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\", access: \"create\" }\n ),\n disableTotp: method(\n z.object({ userId: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\", access: \"delete\" }\n ),\n getTotpStatus: method(\n z.object({ userId: z.string() }),\n TotpStatusSchema,\n { auth: \"admin\" }\n ),\n // Public (no `auth`) — used by the login flow's second-step\n // challenge endpoint. The userId comes from the password-validation\n // step (signed bridge token), so this method is not a free oracle.\n verifyTotp: method(\n z.object({ userId: z.string(), code: z.string() }),\n z.object({ valid: z.boolean() }),\n { kind: \"mutation\", access: \"view\" }\n ),\n // ── OAuth account-linking grant ────────────────────────────────\n //\n // Core's /oauth2/* endpoints delegate here. Tokens are sso-bridge\n // JWTs (kinds oauth-code / oauth-access / oauth-refresh) and ALWAYS\n // carry isAdmin:false — the operator login proves hub control; the\n // issued token is minimal (device scope only).\n oauthIssueCode: method(\n z.object({\n integrationId: z.string(),\n userId: z.string(),\n username: z.string(),\n scopes: z.array(TokenScopeSchema),\n redirectUri: z.string(),\n hubUrl: z.string()\n }),\n z.object({ code: z.string() }),\n { kind: \"mutation\", access: \"create\" }\n ),\n oauthExchangeCode: method(\n z.object({ code: z.string(), redirectUri: z.string() }),\n z.object({\n accessToken: z.string(),\n refreshToken: z.string(),\n expiresIn: z.number()\n }).nullable(),\n { kind: \"mutation\", access: \"view\" }\n ),\n oauthRefresh: method(\n z.object({ refreshToken: z.string() }),\n z.object({\n accessToken: z.string(),\n refreshToken: z.string(),\n expiresIn: z.number()\n }).nullable(),\n { kind: \"mutation\", access: \"view\" }\n ),\n oauthVerifyAccessToken: method(\n z.object({ token: z.string() }),\n z.object({\n userId: z.string(),\n username: z.string(),\n scopes: z.array(TokenScopeSchema)\n }).nullable(),\n { access: \"view\" }\n ),\n // ── OAuth linked-session management (Phase D) ──────────────────\n //\n // The admin UI lists active account-linking sessions and revokes\n // them; revocation makes the linked integration's tokens fail\n // verification immediately.\n listOauthSessions: method(\n z.void(),\n z.array(OauthSessionSummarySchema),\n { auth: \"admin\" }\n ),\n revokeOauthSession: method(\n z.object({ id: z.string() }),\n z.object({ success: z.boolean() }),\n { kind: \"mutation\", auth: \"admin\", access: \"delete\" }\n )\n }\n};\nconst FeatureManifestSchema = z.object({\n streaming: z.boolean(),\n notifications: z.boolean(),\n objectDetection: z.boolean(),\n remoteAccess: z.boolean(),\n agentCluster: z.boolean(),\n smartHome: z.boolean(),\n recordings: z.boolean(),\n backup: z.boolean(),\n repl: z.boolean()\n});\nconst HealthStatusSchema = z.object({\n status: z.literal(\"ok\"),\n uptime: z.number()\n});\nconst NetworkAddressSchema = z.object({\n name: z.string(),\n address: z.string(),\n family: z.string(),\n internal: z.boolean()\n});\nconst systemCapability = {\n name: \"system\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n info: method(z.void(), FeatureManifestSchema),\n health: method(z.void(), HealthStatusSchema),\n featureFlags: method(z.void(), FeatureManifestSchema),\n networkAddresses: method(z.void(), z.array(NetworkAddressSchema).readonly()),\n // Retention config is opaque on the wire — the analytics-suite owns the\n // schema. `getRetentionConfig` returns null when the analytics addon\n // is not loaded; `setRetentionConfig` accepts a partial patch.\n getRetentionConfig: method(z.void(), z.unknown().nullable(), { auth: \"admin\" }),\n setRetentionConfig: method(\n z.record(z.string(), z.unknown()),\n z.null(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n forceRetentionCleanup: method(z.void(), z.void(), { kind: \"mutation\", auth: \"admin\" })\n }\n};\nconst StreamNetworkStatsSchema = z.object({\n nominalBitrateKbps: z.number(),\n observedBitrateKbps: z.number(),\n peakBitrateKbps: z.number(),\n packetLossPercent: z.number(),\n lastUpdated: z.number()\n});\nconst ClientNetworkStatsSchema = z.object({\n rttMs: z.number(),\n jitterMs: z.number(),\n estimatedBandwidthKbps: z.number(),\n lastUpdated: z.number()\n});\nconst DeviceNetworkStatsSchema = z.object({\n deviceId: z.number(),\n streams: z.record(z.string(), StreamNetworkStatsSchema),\n client: ClientNetworkStatsSchema.optional()\n});\nconst networkQualityCapability = {\n name: \"network-quality\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n getDeviceStats: method(\n z.object({ deviceId: z.number() }),\n DeviceNetworkStatsSchema.nullable()\n ),\n getAllStats: method(\n z.void(),\n z.array(DeviceNetworkStatsSchema).readonly()\n ),\n reportClientStats: method(\n z.object({\n deviceId: z.number(),\n rttMs: z.number().min(0).max(6e4),\n jitterMs: z.number().min(0).max(1e4),\n estimatedBandwidthKbps: z.number().min(0).max(1e6)\n }),\n z.void(),\n { kind: \"mutation\" }\n )\n }\n};\nconst ToastSchema = z.object({\n title: z.string(),\n message: z.string(),\n severity: z.enum([\"info\", \"warning\", \"critical\"]),\n duration: z.number().optional(),\n action: z.object({\n label: z.string(),\n url: z.string()\n }).optional()\n});\nconst toastCapability = {\n name: \"toast\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n onToast: method(z.void(), ToastSchema, { kind: \"subscription\" })\n }\n};\nconst TopologyServiceSchema = z.object({\n addonId: z.string(),\n capabilities: z.array(z.string()).readonly(),\n status: z.string()\n});\nconst TopologyProcessSchema = z.object({\n pid: z.number(),\n name: z.string(),\n state: z.string(),\n cpuPercent: z.number(),\n memoryRss: z.number(),\n uptimeSeconds: z.number(),\n services: z.array(TopologyServiceSchema).readonly(),\n groupId: z.string().optional()\n});\nconst TopologyNodeSchema = z.object({\n id: z.string(),\n name: z.string(),\n hostname: z.string(),\n platform: z.string(),\n arch: z.string(),\n cpuModel: z.string().nullable(),\n cpuCores: z.number(),\n memoryMB: z.number(),\n engines: z.array(z.string()).readonly(),\n isHub: z.boolean(),\n isOnline: z.boolean(),\n cpuPercent: z.number(),\n memoryPercent: z.number(),\n uptime: z.number(),\n lastSeen: z.string(),\n localIps: z.array(z.string()).readonly(),\n addons: z.array(\n z.object({\n id: z.string(),\n capabilities: z.array(z.string()).readonly(),\n status: z.string()\n })\n ).readonly(),\n processes: z.array(TopologyProcessSchema).readonly()\n});\nconst ClusterAddonNodeDeploymentSchema = z.object({\n nodeId: z.string(),\n name: z.string(),\n version: z.string(),\n status: z.string(),\n synced: z.boolean()\n});\nconst ClusterAddonStatusEntrySchema = z.object({\n hubVersion: z.string(),\n nodes: z.array(ClusterAddonNodeDeploymentSchema)\n});\nconst NodeAddonInputSchema = z.object({\n nodeId: z.string(),\n addonId: z.string()\n});\nconst NodeAddonEntrySchema = z.object({\n id: z.string(),\n status: z.string(),\n version: z.string().optional(),\n packageName: z.string().optional()\n});\nconst SuccessSchema = z.object({ success: z.boolean() });\nconst RestartProcessResultSchema = z.object({\n success: z.boolean(),\n reason: z.string().optional()\n});\nconst RestartNodeResultSchema = z.object({\n restarted: z.array(z.string()).readonly(),\n failed: z.array(z.string()).readonly()\n});\nconst RenameNodeResultSchema = z.object({\n nodeId: z.string(),\n name: z.string()\n});\nconst nodesCapability = {\n name: \"nodes\",\n scope: \"system\",\n mode: \"singleton\",\n nodeIdMode: \"data\",\n methods: {\n topology: method(\n z.void(),\n z.array(TopologyNodeSchema).readonly(),\n { auth: \"admin\" }\n ),\n deployAddon: method(NodeAddonInputSchema, SuccessSchema, {\n kind: \"mutation\",\n auth: \"admin\"\n }),\n undeployAddon: method(NodeAddonInputSchema, SuccessSchema, {\n kind: \"mutation\",\n auth: \"admin\"\n }),\n restartAddon: method(NodeAddonInputSchema, SuccessSchema, {\n kind: \"mutation\",\n auth: \"admin\"\n }),\n restartProcess: method(\n z.object({ nodeId: z.string(), processName: z.string() }),\n RestartProcessResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n restartNode: method(\n z.object({ nodeId: z.string() }),\n RestartNodeResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n shutdownNode: method(\n z.object({ nodeId: z.string() }),\n SuccessSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n renameNode: method(\n z.object({ nodeId: z.string(), name: z.string().min(1).max(64) }),\n RenameNodeResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n clusterAddonStatus: method(\n z.void(),\n z.record(z.string(), ClusterAddonStatusEntrySchema),\n { auth: \"admin\" }\n ),\n getCapUsageGraph: method(\n z.object({\n windowSeconds: z.number().int().positive().max(300).default(60)\n }),\n z.array(z.object({\n callerAddonId: z.string(),\n providerAddonId: z.string(),\n capName: z.string(),\n callsPerMin: z.number(),\n lastCallAtMs: z.number()\n })).readonly(),\n { auth: \"admin\" }\n ),\n /**\n * Direct per-node addon listing — calls `$agent.status` on the target\n * node (or returns the hub registry for `nodeId === 'hub'`) and surfaces\n * the full addon roster including `version` + `packageName`. The\n * `topology` cap also includes addons but strips them down to\n * `{id, capabilities, status}` for the cluster diagram; this method\n * is the one the per-node \"Addons\" tab should call.\n */\n getNodeAddons: method(\n z.object({ nodeId: z.string() }),\n z.array(NodeAddonEntrySchema).readonly(),\n { auth: \"admin\" }\n ),\n setProcessLogLevel: method(\n z.object({ nodeId: z.string(), level: z.string() }),\n SuccessSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n executeQuery: method(\n z.object({\n nodeId: z.string(),\n addonId: z.string(),\n queryName: z.string(),\n params: z.record(z.string(), z.unknown()).optional()\n }),\n z.unknown(),\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst IntegrationWithStateSchema = z.object({\n id: z.string(),\n addonId: z.string(),\n name: z.string(),\n enabled: z.boolean(),\n info: z.record(z.string(), z.unknown()).readonly(),\n createdAt: z.number(),\n updatedAt: z.number(),\n processState: z.string()\n});\nconst IntegrationLiteSchema = z.object({\n id: z.string(),\n addonId: z.string(),\n name: z.string(),\n enabled: z.boolean(),\n info: z.record(z.string(), z.unknown()).readonly(),\n createdAt: z.number(),\n updatedAt: z.number()\n});\nconst AvailableIntegrationTypeSchema = z.object({\n addonId: z.string(),\n name: z.string(),\n description: z.string(),\n iconUrl: z.string().nullable(),\n color: z.string(),\n instanceMode: z.string(),\n discoveryMode: z.string(),\n existingInstances: z.array(z.object({ id: z.string(), name: z.string() })),\n canAdd: z.boolean()\n});\nconst TestConnectionResultSchema = z.object({\n success: z.boolean(),\n error: z.string().optional()\n});\nconst CreateIntegrationInputSchema = z.object({\n addonId: z.string(),\n name: z.string(),\n enabled: z.boolean().optional(),\n info: z.record(z.string(), z.unknown()).optional(),\n settings: z.record(z.string(), z.unknown()).optional(),\n skipRestart: z.boolean().optional()\n});\nconst UpdateIntegrationInputSchema = z.object({\n id: z.string(),\n name: z.string().optional(),\n enabled: z.boolean().optional(),\n info: z.record(z.string(), z.unknown()).optional()\n});\nconst DeleteIntegrationResultSchema = z.object({\n success: z.boolean(),\n deletedId: z.string()\n});\nconst integrationsCapability = {\n name: \"integrations\",\n scope: \"system\",\n mode: \"singleton\",\n methods: {\n list: method(z.void(), z.array(IntegrationWithStateSchema)),\n get: method(z.object({ id: z.string() }), IntegrationWithStateSchema),\n getByAddonId: method(\n z.object({ addonId: z.string() }),\n IntegrationLiteSchema.nullable()\n ),\n create: method(\n CreateIntegrationInputSchema,\n IntegrationLiteSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n update: method(\n UpdateIntegrationInputSchema,\n IntegrationLiteSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n delete: method(\n z.object({ id: z.string() }),\n DeleteIntegrationResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n getSettings: method(\n z.object({ id: z.string() }),\n z.record(z.string(), z.unknown()),\n { auth: \"admin\" }\n ),\n setSettings: method(\n z.object({\n id: z.string(),\n settings: z.record(z.string(), z.unknown())\n }),\n z.object({ success: z.boolean() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n getAvailableTypes: method(\n z.void(),\n z.array(AvailableIntegrationTypeSchema),\n { auth: \"admin\" }\n ),\n testConnection: method(\n z.object({\n addonId: z.string(),\n settings: z.record(z.string(), z.unknown())\n }),\n TestConnectionResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n )\n }\n};\nconst LogLevelSchema = z.enum([\"debug\", \"info\", \"warn\", \"error\"]);\nconst ChannelSchema = z.enum([\"off\", \"latest\", \"beta\"]);\nconst ChannelWithInheritSchema = z.enum([\"off\", \"latest\", \"beta\", \"inherit\"]);\nconst ManifestShapeSchema = z.object({\n id: z.string(),\n name: z.string().optional(),\n version: z.string().optional(),\n description: z.string().optional(),\n icon: z.string().optional(),\n color: z.string().optional(),\n // Loose schema for `manifest.capabilities` — runtime entries are\n // either kebab-case strings (legacy form) or `CapabilityDeclaration`\n // objects. The cap output schema deliberately keeps it as\n // `readonly unknown[]` so admin-ui consumers cast to the canonical\n // `AddonListItem` (from `@camstack/types`) before reading fields.\n capabilities: z.array(z.unknown()).readonly().optional(),\n packageName: z.string(),\n packageVersion: z.string(),\n packageDisplayName: z.string().optional(),\n /**\n * Bundle metadata when the npm package ships multiple addon entries\n * (mirror of `AddonPackageManifest.bundle` in @camstack/types). When\n * present, the admin UI groups all entries with the same packageName\n * under a collapsible bundle card. Single-entry packages omit this.\n */\n bundle: z.object({\n displayName: z.string(),\n description: z.string().optional(),\n icon: z.string().optional()\n }).optional(),\n protected: z.boolean().optional(),\n removable: z.boolean().optional()\n});\nconst AddonProcessSchema = z.object({\n pid: z.number().optional(),\n mode: z.string(),\n state: z.string()\n});\nconst AddonHealthSchema = z.object({\n phase: z.enum([\"pending\", \"healthy\", \"failed\"]),\n retryCount: z.number(),\n firstFailureAt: z.number().nullable(),\n lastAttemptAt: z.number().nullable(),\n lastError: z.object({ message: z.string(), stack: z.string().optional() }).nullable(),\n nextRetryAt: z.number().nullable(),\n alertEmitted: z.boolean(),\n retrying: z.boolean(),\n inGracePeriod: z.boolean()\n});\nconst AddonListItemSchema = z.object({\n manifest: ManifestShapeSchema,\n declaration: z.unknown().optional(),\n source: z.string(),\n installSource: z.string().optional(),\n process: AddonProcessSchema.optional(),\n /**\n * True when `applyUpdate` last ran for this package and a pre-update\n * backup is still on disk (post-update health-check hasn't cleared\n * it yet, or the user hasn't called `clearBackup`). Drives the\n * Rollback button visibility in admin-ui's AddonCard.\n */\n hasBackup: z.boolean().optional(),\n /** Kernel health snapshot — null when monitor doesn't track this package. */\n health: AddonHealthSchema.nullable().optional()\n});\nconst InstalledPackageSchema = z.object({\n name: z.string(),\n version: z.string(),\n dir: z.string(),\n installSource: z.string().optional()\n});\nconst PackageUpdateSchema = z.object({\n name: z.string(),\n currentVersion: z.string(),\n latestVersion: z.string(),\n category: z.enum([\"addon\", \"core\"]),\n requiresRestart: z.boolean()\n});\nconst PackageVersionInfoSchema = z.object({\n version: z.string(),\n publishedAt: z.string(),\n deprecated: z.string().optional(),\n distTags: z.array(z.string()).readonly()\n});\nconst SearchResultSchema = z.object({\n name: z.string(),\n version: z.string(),\n description: z.string(),\n keywords: z.array(z.string()).readonly(),\n publishedAt: z.string(),\n author: z.string(),\n installed: z.boolean(),\n installedVersion: z.string().optional()\n});\nconst AutoUpdateSettingsSchema = z.object({\n channel: ChannelSchema,\n intervalSeconds: z.number()\n});\nconst AddonAutoUpdateSchema = ChannelWithInheritSchema;\nconst RestartAddonResultSchema = z.unknown();\nconst InstallPackageResultSchema = z.unknown();\nconst ReloadPackagesResultSchema = z.unknown();\nconst UpdateFrameworkPackageResultSchema = z.object({\n packageName: z.string(),\n fromVersion: z.string(),\n toVersion: z.string(),\n /** Ms-epoch the server scheduled its self-restart. */\n restartingAt: z.number()\n});\nconst FrameworkPackageStatusSchema = z.object({\n packageName: z.string(),\n currentVersion: z.string(),\n latestVersion: z.string().nullable(),\n hasUpdate: z.boolean(),\n /** Optional manifest description for the row tooltip. */\n description: z.string().optional()\n});\nconst LogStreamEntrySchema = z.object({\n timestamp: z.string(),\n level: z.string(),\n message: z.string(),\n scope: z.string().optional()\n});\nconst LogQueryEntrySchema = z.unknown();\nconst CustomActionInputSchema = z.object({\n addonId: z.string().min(1),\n action: z.string().min(1),\n input: z.unknown()\n});\nconst addonsCapability = {\n name: \"addons\",\n scope: \"system\",\n mode: \"singleton\",\n nodeIdMode: \"data\",\n methods: {\n // ── Listing ──────────────────────────────────────────────────────\n list: method(z.void(), z.array(AddonListItemSchema).readonly()),\n // ── Logs (query) ────────────────────────────────────────────────\n // Default auth (`protected`): authenticated users — including scoped\n // tokens with the right route-prefix scope. Reading logs isn't an\n // administrative action; install/restart/uninstall stay admin-only.\n getLogs: method(\n z.object({\n addonId: z.string(),\n limit: z.number().min(1).max(500).default(100),\n level: LogLevelSchema.optional()\n }),\n z.array(LogQueryEntrySchema)\n ),\n // ── Packages ────────────────────────────────────────────────────\n listPackages: method(z.void(), z.array(InstalledPackageSchema).readonly()),\n installPackage: method(\n z.object({ packageName: z.string(), version: z.string().optional() }),\n InstallPackageResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n installFromWorkspace: method(\n z.object({ packageName: z.string() }),\n InstallPackageResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n isWorkspaceAvailable: method(z.void(), z.boolean()),\n listWorkspacePackages: method(z.void(), z.array(z.unknown()).readonly()),\n uninstallPackage: method(\n z.object({ packageName: z.string() }),\n z.unknown(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n reloadPackages: method(z.void(), ReloadPackagesResultSchema, {\n kind: \"mutation\",\n auth: \"admin\"\n }),\n // Note: original router declared `searchAvailable` input as optional\n // outer object. The cap codegen requires a stable input shape — we\n // make `query` optional inside a required object to preserve client\n // call shape (`{ query?: string }`).\n searchAvailable: method(\n z.object({ query: z.string().optional() }),\n z.array(SearchResultSchema)\n ),\n /**\n * Available package updates for a node. `nodeId` omitted (or\n * `'hub'`) checks the hub's own installed packages; an agent\n * `nodeId` checks that agent's installed roster against npm\n * (the hub does the npm lookups + diff — agents stay npm-free).\n */\n listUpdates: method(\n z.object({ nodeId: z.string().optional() }),\n z.array(PackageUpdateSchema).readonly(),\n { auth: \"admin\" }\n ),\n /**\n * Update one package on a node. `nodeId` omitted (or `'hub'`)\n * installs on the hub via npm; an agent `nodeId` makes the hub\n * pack the resolved version and push the tarball to that agent\n * (`$agent.deploy` + `$agent.reload`) — agents need no npm runtime.\n */\n updatePackage: method(\n z.object({\n name: z.string().min(1),\n version: z.string().optional(),\n nodeId: z.string().optional()\n }),\n z.unknown(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Roll back an addon to the version it had before the most recent\n * `updatePackage` call. The backup directory pointer is kept in the\n * central addon manifest until the post-update health-check\n * confirms the new install works (then it's cleared automatically),\n * so this only succeeds when the most recent update either failed\n * its restart or the user explicitly wants to revert.\n *\n * Returns `{ rolledBackTo: <version> }` on success, or\n * `{ rolledBackTo: null }` when there's no backup to roll back to\n * (caller can show a \"no backup available\" UI).\n */\n rollbackPackage: method(\n z.object({ name: z.string().min(1) }),\n z.object({ rolledBackTo: z.string().nullable() }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /** Re-check updates for a node, bypassing any cache. `nodeId`\n * omitted (or `'hub'`) refreshes the hub; an agent `nodeId`\n * re-checks that agent's roster. */\n forceRefresh: method(\n z.object({ nodeId: z.string().optional() }),\n z.unknown(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n restartServer: method(\n z.object({ confirm: z.literal(true) }),\n z.unknown(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Most-recent restart marker (kind / packageName / from→to versions\n * / requestedBy / requestedAt). Returns `null` when this process\n * didn't boot from a tracked restart, or when the\n * post-boot retention window (5 min) has elapsed.\n *\n * Drives the admin-UI reconnect overlay's success toast — the\n * `system.restart-completed` event itself is fired before the\n * client has time to re-subscribe, so the client queries this on\n * first reconnect instead.\n */\n getLastRestart: method(\n z.void(),\n z.object({\n kind: z.enum([\"framework-update\", \"manual\", \"system\"]),\n packageName: z.string().optional(),\n fromVersion: z.string().optional(),\n toVersion: z.string().optional(),\n requestedBy: z.string().optional(),\n requestedAt: z.number()\n }).nullable(),\n { auth: \"admin\" }\n ),\n /**\n * Snapshot of the framework packages installed under the hub's\n * `<appRoot>/node_modules/`. Each row carries the currently\n * installed version and (best-effort) the latest version\n * available on npm. Drives the admin-UI \"System packages\" panel.\n *\n * Spec: docs/superpowers/specs/2026-05-14-framework-live-update-design.md\n */\n listFrameworkPackages: method(\n z.void(),\n z.array(FrameworkPackageStatusSchema).readonly(),\n { auth: \"admin\" }\n ),\n /**\n * Cluster-wide capability-provider discovery. Returns the list of\n * `{ addonId, mode, isActive }` tuples for whatever addon(s)\n * currently provide the requested capability across the cluster.\n *\n * Why this lives on `addons` (and not on a `capabilities` cap of\n * its own): the hub's main-process `CapabilityRegistry` already\n * aggregates registrations from every forked group-runner and\n * remote agent via Moleculer event propagation — there's no\n * cross-process registry mirror to build, just an introspection\n * shim.\n *\n * Use this from addon code when you need to know whether another\n * addon has registered a specific cap (e.g. `tailscale-ingress`\n * checking `tailscale-client` is up before calling `tailscale\n * serve`). Don't reach for `ctx.capabilities.getCollectionEntries`\n * — that reads the LOCAL registry of the calling addon's group\n * runner and never sees providers in other processes. See\n * `CLAUDE.md` → Critical rules → ctx.api vs ctx.capabilities.\n */\n listCapabilityProviders: method(\n z.object({ capName: z.string().min(1) }),\n z.array(z.object({\n addonId: z.string(),\n mode: z.enum([\"singleton\", \"collection\"]),\n isActive: z.boolean()\n })).readonly()\n ),\n /**\n * Toggle a single collection-cap provider on/off. Generic write-side\n * counterpart of `listCapabilityProviders` — drives the per-provider\n * Enable/Disable affordance in admin pages (TURN servers, etc.)\n * without needing a bespoke orchestrator cap.\n *\n * Reaches the hub's `CapabilityRegistry` directly:\n * `enableCollectionProvider` / `disableCollectionProvider` flip the\n * registry-level `disabledProviders` set. `getCollectionEntries`\n * already filters disabled providers out, so a disabled provider\n * drops out of every collection aggregate immediately. Only valid\n * for `mode: 'collection'` caps — the registry no-ops + warns for\n * singletons.\n */\n setCapabilityProviderEnabled: method(\n z.object({\n capName: z.string().min(1),\n addonId: z.string().min(1),\n enabled: z.boolean()\n }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Live-update one of the framework packages marked\n * `camstack.system: true` (`@camstack/types|kernel|core|sdk|ui-library`).\n * Runs `npm install --prefix <appRoot> <name>@<version> --no-save`,\n * writes a `.restart-pending` marker, emits `system.restarting`\n * and schedules a graceful process exit. The supervisor (Docker /\n * Electron / systemd) brings the hub back up; on first boot after\n * the restart the marker fires `system.restart-completed`.\n *\n * `version` defaults to `'latest'`. The allow-list of valid\n * `packageName` values is enforced server-side.\n *\n * Spec: docs/superpowers/specs/2026-05-14-framework-live-update-design.md\n */\n updateFrameworkPackage: method(\n z.object({\n packageName: z.string().min(1),\n version: z.string().optional()\n }),\n UpdateFrameworkPackageResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n getVersions: method(\n z.object({ name: z.string() }),\n z.array(PackageVersionInfoSchema).readonly()\n ),\n restartAddon: method(\n z.object({ addonId: z.string() }),\n RestartAddonResultSchema,\n { kind: \"mutation\", auth: \"admin\" }\n ),\n /**\n * Force-retry a failed addon NOW. Resets the retry counter so the\n * next failure starts from the 60s interval again. Used by the\n * \"Retry now\" button in the Addons admin page row + AlertCenter\n * alert action. Idempotent on healthy addons (no-op).\n */\n retryLoad: method(\n z.object({ packageName: z.string() }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Auto-update ─────────────────────────────────────────────────\n getAutoUpdateSettings: method(\n z.void(),\n AutoUpdateSettingsSchema,\n { auth: \"admin\" }\n ),\n setAutoUpdateSettings: method(\n z.object({\n channel: ChannelSchema,\n intervalSeconds: z.number().min(300).max(86400).optional()\n }),\n z.unknown(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n getAddonAutoUpdate: method(\n z.object({ addonId: z.string() }),\n AddonAutoUpdateSchema,\n { auth: \"admin\" }\n ),\n setAddonAutoUpdate: method(\n z.object({ addonId: z.string(), channel: ChannelWithInheritSchema }),\n z.unknown(),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n applyAutoUpdateToAll: method(\n z.object({ channel: ChannelSchema }),\n z.object({ success: z.literal(true) }),\n { kind: \"mutation\", auth: \"admin\" }\n ),\n // ── Custom action dispatcher ────────────────────────────────────\n // Generic dispatcher used by `bindAddonActions`. Per-action auth\n // is enforced inside the provider; the outer cap auth is\n // `protected` (any authenticated user) so individual addons can\n // gate their own actions to public/protected/admin/superAdmin.\n custom: method(CustomActionInputSchema, z.unknown(), { kind: \"mutation\" }),\n // ── Log streaming ───────────────────────────────────────────────\n onAddonLogs: method(\n z.object({\n addonId: z.string(),\n level: LogLevelSchema.optional()\n }),\n LogStreamEntrySchema,\n { kind: \"subscription\" }\n )\n }\n};\nconst PIPELINE_FLOW_CAPABILITY_NAMES = [\n \"decoder\",\n \"motion-detection\",\n \"pipeline-executor\",\n \"audio-analyzer\",\n \"pipeline-analytics\",\n \"notification-output\"\n];\nconst PIPELINE_OWNER_CAPABILITY_NAMES = [\n ...PIPELINE_FLOW_CAPABILITY_NAMES,\n \"pipeline-orchestrator\",\n \"pipeline-runner\"\n];\nexport {\n nativeObjectDetectionCapability as $,\n addonWidgetsSourceCapability as A,\n addonsCapability as B,\n adminUiCapability as C,\n advancedNotifierCapability as D,\n alertsCapability as E,\n audioAnalysisCapability as F,\n audioAnalyzerCapability as G,\n audioCodecCapability as H,\n authProviderCapability as I,\n backupCapability as J,\n cameraCredentialsCapability as K,\n decoderCapability as L,\n detectionPipelineCapability as M,\n deviceExportCapability as N,\n deviceManagerCapability as O,\n deviceOpsCapability as P,\n deviceStateCapability as Q,\n embeddingEncoderCapability as R,\n eventsCapability as S,\n integrationsCapability as T,\n intercomCapability as U,\n localNetworkCapability as V,\n logDestinationCapability as W,\n meshNetworkCapability as X,\n metricsProviderCapability as Y,\n motionDetectionCapability as Z,\n mqttBrokerCapability as _,\n zoneRulesCapability as a,\n AudioLevelSchema as a$,\n networkAccessCapability as a0,\n networkQualityCapability as a1,\n nodesCapability as a2,\n notificationOutputCapability as a3,\n oauthIntegrationCapability as a4,\n osdCapability as a5,\n pipelineAnalyticsCapability as a6,\n pipelineExecutorCapability as a7,\n pipelineOrchestratorCapability as a8,\n pipelineRunnerCapability as a9,\n AccessoriesStatusSchema as aA,\n AccessoryKind as aB,\n AddBrokerInputSchema as aC,\n AddonAutoUpdateSchema as aD,\n AddonListItemSchema as aE,\n AddonPageDeclarationSchema as aF,\n AddonPageInfoSchema as aG,\n AgentLoadSummarySchema as aH,\n AlertSchema as aI,\n AlertSeveritySchema as aJ,\n AlertSourceSchema as aK,\n AlertStatusSchema as aL,\n ApiKeyRecordSchema as aM,\n ApiKeySummarySchema as aN,\n ArchiveEntrySchema as aO,\n ArchiveManifestSchema as aP,\n AudioAnalysisResultSchema as aQ,\n AudioAnalysisSettingsSchema as aR,\n AudioChunkInputSchema as aS,\n AudioClassSummarySchema as aT,\n AudioClassificationLabelSchema as aU,\n AudioClassificationResultSchema as aV,\n AudioCodecInfoSchema as aW,\n AudioDecodeSessionConfigSchema as aX,\n AudioEncodeSessionConfigSchema as aY,\n AudioEncodedChunkSchema as aZ,\n AudioEventSchema as a_,\n platformProbeCapability as aa,\n ptzCapability as ab,\n rebootCapability as ac,\n recordingCapability as ad,\n recordingEngineCapability as ae,\n restreamerCapability as af,\n settingsStoreCapability as ag,\n smtpProviderCapability as ah,\n snapshotCapability as ai,\n snapshotProviderCapability as aj,\n ssoBridgeCapability as ak,\n storageCapability as al,\n storageProviderCapability as am,\n streamBrokerCapability as an,\n streamingEngineCapability as ao,\n systemCapability as ap,\n toastCapability as aq,\n turnProviderCapability as ar,\n userManagementCapability as as,\n userPasskeysCapability as at,\n webrtcCapability as au,\n webrtcSessionCapability as av,\n ACCESSORY_LABEL as aw,\n APPLE_SA_TO_MACRO as ax,\n AUDIO_BACKEND_CHOICES as ay,\n AUDIO_MACRO_LABELS as az,\n zoneAnalyticsCapability as b,\n UnexposeInputSchema as b$,\n AudioMetricsHistoryPointSchema as b0,\n AudioMetricsHistorySchema as b1,\n AudioMetricsSnapshotSchema as b2,\n AudioPcmChunkSchema as b3,\n AuthResultSchema as b4,\n AutoUpdateSettingsSchema as b5,\n AvailableIntegrationTypeSchema as b6,\n BATTERY_DEVICE_PROFILE as b7,\n BackupDestinationInfoSchema as b8,\n BackupEntrySchema as b9,\n CollectionColumnSchema as bA,\n CollectionIndexSchema as bB,\n ConfigEntrySchema$1 as bC,\n ConfigSectionWithValuesSchema as bD,\n ConfigTabDeclarationSchema as bE,\n CreateApiKeyInputSchema as bF,\n CreateApiKeyResultSchema as bG,\n CreateIntegrationInputSchema as bH,\n CreateScopedTokenInputSchema as bI,\n CreateScopedTokenResultSchema as bJ,\n CreateUserInputSchema as bK,\n CustomActionInputSchema as bL,\n DEFAULT_AUDIO_ANALYZER_CONFIG as bM,\n DEFAULT_DECODER_HWACCEL_CONFIG as bN,\n DEVICE_PROFILES as bO,\n DEVICE_SETTINGS_CONTRIBUTION_METHODS as bP,\n DEVICE_STATUS_METHOD as bQ,\n DecodedAudioChunkSchema as bR,\n DecodedFrameSchema as bS,\n DecoderAssignmentSchema as bT,\n DecoderSessionConfigSchema as bU,\n DecoderStatsSchema as bV,\n DeleteIntegrationResultSchema as bW,\n DetectorOutputSchema as bX,\n DeviceDiscoveryStatusSchema as bY,\n ExposeInputSchema as bZ,\n DeviceExportStatusSchema as b_,\n BatteryStatusSchema as ba,\n BoundingBoxSchema as bb,\n BrightnessStatusSchema as bc,\n BrokerAudioClientSchema as bd,\n BrokerClientsSchema as be,\n BrokerConnectionDetailsSchema as bf,\n BrokerDecodedClientSchema as bg,\n BrokerInfoSchema as bh,\n BrokerRtspClientSchema as bi,\n BrokerStatsSchema as bj,\n BrokerStatusSchema$1 as bk,\n CAM_PROFILE_ORDER as bl,\n CamProfileSchema as bm,\n CamStreamKindSchema as bn,\n CamStreamResolutionSchema as bo,\n CameraCredentialsSchema as bp,\n CameraCredentialsStatusSchema as bq,\n CameraMetricsSchema as br,\n CameraMetricsWithDeviceIdSchema as bs,\n CameraStreamSchema as bt,\n CapScopeSchema as bu,\n CapabilityBindingsSchema as bv,\n ChargingStatus as bw,\n ClientNetworkStatsSchema as bx,\n ClusterAddonNodeDeploymentSchema as by,\n ClusterAddonStatusEntrySchema as bz,\n streamParamsCapability as c,\n NetworkAddressSchema as c$,\n DeviceFeature as c0,\n DeviceInfoSchema as c1,\n DeviceNetworkStatsSchema as c2,\n DeviceRole as c3,\n DeviceStatusSchema as c4,\n DeviceType as c5,\n DiscoveredChildDeviceSchema as c6,\n DiscoveredChildStatusSchema as c7,\n DiscoveredDeviceSchema as c8,\n DoorbellPressEventSchema as c9,\n IntercomStatusSchema as cA,\n LocationStatSchema as cB,\n LogEntrySchema as cC,\n LogLevelSchema$1 as cD,\n LogStreamEntrySchema as cE,\n MODEL_FORMATS as cF,\n MediaFileSchema as cG,\n MeshPeerSchema as cH,\n MeshStatusSchema as cI,\n MethodAccessSchema as cJ,\n MotionAnalysisResultSchema as cK,\n MotionEventSchema as cL,\n MotionOnMotionChangedDataSchema as cM,\n MotionRegionSchema as cN,\n MotionSourceEnum as cO,\n MotionSourcesSchema as cP,\n MotionStatusSchema as cQ,\n MotionTriggerRuntimeStateSchema as cR,\n MotionTriggerStatusSchema as cS,\n MotionZoneOptionsSchema as cT,\n MotionZonePatchSchema as cU,\n MotionZoneStatusSchema as cV,\n StatusSchema as cW,\n NativeDetectionSchema as cX,\n NativeObjectClassEnum as cY,\n NativeObjectDetectionStatusSchema as cZ,\n NetworkAccessStatusSchema as c_,\n DoorbellStatusSchema as ca,\n EmbeddingInfoSchema as cb,\n EmbeddingResultSchema as cc,\n EncodedPacketSchema as cd,\n EnrichedWidgetMetadataSchema as ce,\n EventItemSchema as cf,\n EventKindSchema as cg,\n ExportSetupFieldSchema as ch,\n ExportSetupSchema as ci,\n ExposedDeviceSchema as cj,\n ExposedResourceSchema as ck,\n FeatureManifestSchema as cl,\n FeatureProbeStatusSchema as cm,\n FrameHandleFormatSchema as cn,\n FrameHandleSchema as co,\n FrameInputSchema as cp,\n GetStreamWithCodecInputSchema as cq,\n GlobalMetricsSchema as cr,\n HWACCEL_OPTIONS as cs,\n HealthStatusSchema as ct,\n HistoryPointSchema as cu,\n HistoryResolutionEnum as cv,\n InstalledPackageSchema as cw,\n IntegrationLiteSchema as cx,\n IntegrationWithStateSchema as cy,\n IntercomAbilitySchema as cz,\n motionTriggerCapability as d,\n StartEmbeddedInputSchema as d$,\n NetworkEndpointSchema as d0,\n NotificationHistoryEntrySchema as d1,\n NotificationRuleSchema as d2,\n NotificationSchema as d3,\n OauthIntegrationDescriptorSchema as d4,\n ObjectEventSchema as d5,\n OrchestratorMetricsSchema as d6,\n OsdOverlayKindEnum as d7,\n OsdOverlayPatchSchema as d8,\n OsdOverlaySchema as d9,\n PtzPresetSchema as dA,\n PtzStatusSchema as dB,\n QueryFilterSchema as dC,\n RegisteredStreamSchema as dD,\n ReportMotionInputSchema as dE,\n RtpSourceSchema as dF,\n RtspRestreamEntrySchema as dG,\n RunnerCameraConfigSchema as dH,\n RunnerCameraDeviceUIFields as dI,\n RunnerLocalLoadSchema as dJ,\n RunnerLocalMetricsSchema as dK,\n STORAGE_LOCATION_CARDINALITY as dL,\n ScopedTokenSchema as dM,\n ScopedTokenSummarySchema as dN,\n SearchResultSchema as dO,\n SegmentSchema as dP,\n SendEmailInputSchema as dQ,\n SendEmailResultSchema as dR,\n SettingsPatchSchema as dS,\n SettingsRecordSchema as dT,\n SettingsSchemaWithValuesSchema as dU,\n SettingsUpdateResultSchema as dV,\n ShmRingStatsSchema as dW,\n SmtpStatusSchema as dX,\n SnapshotImageSchema as dY,\n SpatialDetectionSchema as dZ,\n SsoBridgeClaimsSchema as d_,\n OsdPositionEnum as da,\n OsdStatusSchema as db,\n PIPELINE_FLOW_CAPABILITY_NAMES as dc,\n PIPELINE_OWNER_CAPABILITY_NAMES as dd,\n PackageUpdateSchema as de,\n PackageVersionInfoSchema as df,\n PasskeySummarySchema as dg,\n PcmSampleFormatSchema as dh,\n PerScopeBreakdownSchema as di,\n PipelineAssignmentSchema as dj,\n PipelineDefaultStepSchema as dk,\n PipelineEngineChoiceSchema as dl,\n PipelineRunResultBridge as dm,\n PipelineStepInputSchema as dn,\n PlaceholderReasonSchema as dp,\n PolygonPointSchema as dq,\n ProfileSlotSchema as dr,\n ProfileSlotStatusSchema as ds,\n ProviderStatusSchema as dt,\n PtzAutotrackRuntimeStateSchema as du,\n PtzAutotrackSettingsSchema as dv,\n PtzAutotrackStatusSchema as dw,\n PtzAutotrackTargetOptionSchema as dx,\n PtzMoveCommandSchema as dy,\n PtzPositionSchema as dz,\n errMsg as e,\n event as e$,\n AbortUploadInputSchema as e0,\n BeginDownloadInputSchema as e1,\n BeginDownloadResultSchema as e2,\n BeginUploadInputSchema as e3,\n BeginUploadResultSchema as e4,\n EndDownloadInputSchema as e5,\n FinalizeUploadInputSchema as e6,\n StorageLocationRefSchema as e7,\n StorageLocationSchema as e8,\n StorageLocationTypeSchema as e9,\n TopologyServiceSchema as eA,\n TrackSchema as eB,\n TrackStateSchema as eC,\n TrackedDetectionSchema as eD,\n TurnServerSchema as eE,\n UpdateIntegrationInputSchema as eF,\n UpdateUserInputSchema as eG,\n UserRecordSchema as eH,\n UserSummarySchema as eI,\n WELL_KNOWN_TABS as eJ,\n WELL_KNOWN_TAB_MAP as eK,\n WebrtcStreamChoiceSchema as eL,\n WebrtcStreamTargetSchema as eM,\n WidgetHostEnum as eN,\n WidgetMetadataSchema as eO,\n WidgetRemoteSchema as eP,\n WidgetSizeEnum as eQ,\n YAMNET_TO_MACRO as eR,\n ZoneKindEnum as eS,\n ZoneRuleModeEnum as eT,\n ZoneRuleSchema as eU,\n ZoneRuleStageEnum as eV,\n ZoneRulesArraySchema as eW,\n ZoneSchema as eX,\n ZoneScopeBreakdownSchema as eY,\n accessoryStableId as eZ,\n deviceMatchesProfile as e_,\n ProviderInfoSchema as ea,\n ReadChunkInputSchema as eb,\n TestLocationResultSchema as ec,\n WriteChunkInputSchema as ed,\n StreamFormatSchema as ee,\n StreamInfoSchema as ef,\n StreamNetworkStatsSchema as eg,\n StreamParamsOptionsSchema as eh,\n StreamParamsStatusSchema as ei,\n StreamProfileConfigSchema as ej,\n StreamProfileOptionsSchema as ek,\n StreamProfilePatchSchema as el,\n StreamProfileSchema as em,\n StreamSourceEntrySchema$1 as en,\n StreamSourceSchema as eo,\n SubscribeAudioChunksInputSchema as ep,\n SubscribeAudioChunksResultSchema as eq,\n SubscribeFramesInputSchema as er,\n SubscribeFramesResultSchema as es,\n SwitchStatusSchema as et,\n SystemMetricsSchema as eu,\n TestConnectionResultSchema as ev,\n ToastSchema as ew,\n TokenScopeSchema as ex,\n TopologyNodeSchema as ey,\n TopologyProcessSchema as ez,\n motionCapability as f,\n expandCapMethods as f0,\n getAudioMacroClassIds as f1,\n isDeviceConfigCap as f2,\n mapAudioLabelToMacro as f3,\n method as f4,\n resolveDeviceProfile as f5,\n webrtcClientHintsSchema as f6,\n featureProbeCapability as g,\n hydrateSchema as h,\n doorbellCapability as i,\n deviceStatusCapability as j,\n deviceDiscoveryCapability as k,\n cameraStreamsCapability as l,\n motionZonesCapability as m,\n brightnessCapability as n,\n batteryCapability as o,\n ptzAutotrackCapability as p,\n audioMetricsCapability as q,\n deviceProviderCapability as r,\n switchCapability as s,\n accessoriesCapability as t,\n addonPagesCapability as u,\n addonPagesSourceCapability as v,\n addonRoutesCapability as w,\n addonSettingsCapability as x,\n addonWidgetsCapability as y,\n zonesCapability as z\n};\n//# sourceMappingURL=index-CgPd35k5.mjs.map\n","import * as fs from \"node:fs\";\nimport { existsSync, mkdirSync, createWriteStream, unlinkSync, chmodSync, readdirSync, rmSync, renameSync, writeFileSync, readFileSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport { join, basename } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { Readable } from \"node:stream\";\nimport { execFileSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { e as errMsg } from \"./index-CgPd35k5.mjs\";\nimport \"zod\";\nfunction getPlatformInfo() {\n return {\n platform: process.platform,\n arch: process.arch\n };\n}\nfunction buildBinaryPath(dataDir, name, platform) {\n const ext = (platform ?? process.platform) === \"win32\" ? \".exe\" : \"\";\n return join(dataDir, \"deps\", `${name}${ext}`);\n}\nfunction findInPath(name) {\n try {\n execFileSync(name, [\"--version\"], { stdio: \"pipe\", timeout: 5e3 });\n return name;\n } catch {\n return null;\n }\n}\nasync function downloadBinary(opts) {\n const { name, url, targetDir, targetName, logger, isArchive, archiveFormat, archiveInnerPath } = opts;\n const targetPath = join(targetDir, targetName);\n if (existsSync(targetPath)) {\n logger.debug(\"Binary already exists\", { meta: { name, targetPath } });\n return targetPath;\n }\n mkdirSync(targetDir, { recursive: true });\n logger.info(\"Downloading binary\", { meta: { name, url } });\n const response = await fetch(url, { redirect: \"follow\" });\n if (!response.ok || !response.body) {\n throw new Error(`Failed to download ${name}: ${response.status} ${response.statusText}`);\n }\n if (isArchive) {\n const ext = archiveFormat ?? \"tar.gz\";\n const tmpArchive = join(targetDir, `${name}-download.${ext}`);\n const nodeStream = Readable.fromWeb(response.body);\n await pipeline(nodeStream, createWriteStream(tmpArchive));\n const tmpExtractDir = join(targetDir, `${name}-extract`);\n mkdirSync(tmpExtractDir, { recursive: true });\n if (ext === \"zip\") {\n try {\n execFileSync(\"unzip\", [\"-o\", \"-q\", tmpArchive, \"-d\", tmpExtractDir], { stdio: \"pipe\" });\n } catch {\n execFileSync(\"tar\", [\"-xf\", tmpArchive, \"-C\", tmpExtractDir], { stdio: \"pipe\" });\n }\n } else if (ext === \"tar.xz\") {\n execFileSync(\"tar\", [\"-xJf\", tmpArchive, \"-C\", tmpExtractDir], { stdio: \"pipe\" });\n } else {\n execFileSync(\"tar\", [\"-xzf\", tmpArchive, \"-C\", tmpExtractDir], { stdio: \"pipe\" });\n }\n if (archiveInnerPath) {\n const { copyFileSync } = await import(\"node:fs\");\n const sourcePath = join(tmpExtractDir, archiveInnerPath);\n if (!existsSync(sourcePath)) {\n throw new Error(`Binary not found in archive at ${archiveInnerPath}`);\n }\n copyFileSync(sourcePath, targetPath);\n }\n unlinkSync(tmpArchive);\n const { rmSync: rmSync2 } = await import(\"node:fs\");\n rmSync2(tmpExtractDir, { recursive: true, force: true });\n } else {\n const nodeStream = Readable.fromWeb(response.body);\n await pipeline(nodeStream, createWriteStream(targetPath));\n }\n chmodSync(targetPath, 493);\n logger.info(\"Binary downloaded\", { meta: { name, targetPath } });\n return targetPath;\n}\nasync function ensureBinary(opts) {\n const ext = process.platform === \"win32\" ? \".exe\" : \"\";\n const targetName = `${opts.name}${ext}`;\n const targetPath = join(opts.targetDir, targetName);\n if (existsSync(targetPath)) {\n opts.logger.debug(\"Binary found at target path\", { meta: { name: opts.name, targetPath } });\n return targetPath;\n }\n const inPath = findInPath(opts.name);\n if (inPath) {\n opts.logger.info(\"Binary found in system PATH\", { meta: { name: opts.name } });\n return inPath;\n }\n return downloadBinary({\n name: opts.name,\n url: opts.downloadUrl,\n targetDir: opts.targetDir,\n targetName,\n logger: opts.logger,\n isArchive: opts.isArchive,\n archiveFormat: opts.archiveFormat,\n archiveInnerPath: opts.archiveInnerPath\n });\n}\nconst FFMPEG_VERSION = \"7.1\";\nfunction getFfmpegDownloadUrl(platform, arch) {\n switch (platform) {\n case \"linux\": {\n const archMap = { x64: \"amd64\", arm64: \"arm64\" };\n const a = archMap[arch];\n if (!a) throw new Error(`Unsupported Linux architecture: ${arch}`);\n return `https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-${a}-static.tar.xz`;\n }\n case \"darwin\": {\n const archMap = { arm64: \"arm64\", x64: \"amd64\" };\n const a = archMap[arch];\n if (!a) throw new Error(`Unsupported macOS architecture: ${arch}`);\n return `https://www.osxexperts.net/ffmpeg${FFMPEG_VERSION.replace(\".\", \"\")}arm.zip`;\n }\n default:\n throw new Error(`Unsupported platform: ${platform}`);\n }\n}\nfunction getFfmpegArchiveInfo(platform) {\n switch (platform) {\n case \"linux\":\n return {\n isArchive: true,\n archiveFormat: \"tar.xz\",\n archiveInnerPath: `ffmpeg-${FFMPEG_VERSION}-amd64-static/ffmpeg`\n };\n case \"darwin\":\n return {\n isArchive: true,\n archiveFormat: \"zip\",\n archiveInnerPath: \"ffmpeg\"\n };\n default:\n throw new Error(`Unsupported platform: ${platform}`);\n }\n}\nasync function ensureFfmpeg(dataDir, logger) {\n const depsDir = join(dataDir, \"deps\");\n const platform = process.platform;\n const arch = process.arch;\n const archiveInfo = getFfmpegArchiveInfo(platform);\n return ensureBinary({\n name: \"ffmpeg\",\n targetDir: depsDir,\n downloadUrl: getFfmpegDownloadUrl(platform, arch),\n logger,\n ...archiveInfo\n });\n}\nconst PYTHON_VERSION = \"3.12.12\";\nconst PP_BASE = `https://github.com/bjia56/portable-python/releases/download/cpython-v${PYTHON_VERSION}-build.0`;\nfunction getPythonDownloadUrl(platform, arch) {\n switch (platform) {\n case \"linux\": {\n const archMap = { x64: \"x86_64\", arm64: \"aarch64\" };\n const a = archMap[arch];\n if (!a) throw new Error(`Unsupported Linux architecture for Python: ${arch}`);\n return `${PP_BASE}/python-headless-${PYTHON_VERSION}-linux-${a}.zip`;\n }\n case \"darwin\": {\n return `${PP_BASE}/python-headless-${PYTHON_VERSION}-darwin-universal2.zip`;\n }\n default:\n throw new Error(`Unsupported platform for portable Python: ${platform}`);\n }\n}\nasync function ensurePython(dataDir, logger) {\n const pythonDir = join(dataDir, \"deps\", \"python\");\n const pythonBin = join(pythonDir, \"bin\", \"python3\");\n if (existsSync(pythonBin)) {\n logger.debug(\"Portable Python found\", { meta: { pythonBin } });\n return pythonBin;\n }\n logger.info(\"Downloading portable Python (headless)\", { meta: { version: PYTHON_VERSION } });\n const depsDir = join(dataDir, \"deps\");\n mkdirSync(depsDir, { recursive: true });\n const url = getPythonDownloadUrl(process.platform, process.arch);\n const tmpArchive = join(depsDir, \"python-download.zip\");\n logger.info(\"Python download source\", { meta: { url } });\n const response = await fetch(url, { redirect: \"follow\" });\n if (!response.ok || !response.body) {\n logger.warn(\"Failed to download Python — ML detection will not be available\", { meta: { status: response.status } });\n return null;\n }\n const nodeStream = Readable.fromWeb(response.body);\n await pipeline(nodeStream, createWriteStream(tmpArchive));\n try {\n execFileSync(\"unzip\", [\"-o\", \"-q\", tmpArchive, \"-d\", depsDir], { stdio: \"pipe\" });\n } catch {\n execFileSync(\"python3\", [\"-m\", \"zipfile\", \"-e\", tmpArchive, depsDir], { stdio: \"pipe\" });\n }\n const { unlinkSync: unlinkSync2 } = await import(\"node:fs\");\n unlinkSync2(tmpArchive);\n if (!existsSync(pythonBin)) {\n const candidates = readdirSync(depsDir).filter(\n (name) => name.startsWith(\"python-\") && existsSync(join(depsDir, name, \"bin\", \"python3\"))\n );\n if (candidates.length === 0) {\n logger.warn(\"Python extraction succeeded but no python3 binary found in any subdir\", {\n meta: { depsDir }\n });\n return null;\n }\n const extractedRoot = join(depsDir, candidates[0]);\n if (existsSync(pythonDir)) {\n rmSync(pythonDir, { recursive: true, force: true });\n }\n renameSync(extractedRoot, pythonDir);\n }\n if (!existsSync(pythonBin)) {\n logger.warn(\"Python extraction succeeded but binary not found at expected path\", {\n meta: { pythonBin }\n });\n return null;\n }\n chmodSync(pythonBin, 493);\n if (process.platform === \"darwin\") {\n const realBin = join(pythonDir, \"bin\", \"python3.real\");\n if (!existsSync(realBin)) {\n renameSync(pythonBin, realBin);\n const archFlag = process.arch === \"arm64\" ? \"-arm64\" : \"-x86_64\";\n writeFileSync(\n pythonBin,\n `#!/bin/sh\nexec /usr/bin/arch ${archFlag} \"${realBin}\" \"$@\"\n`\n );\n chmodSync(pythonBin, 493);\n const pyAlt = join(pythonDir, \"bin\", \"python\");\n if (existsSync(pyAlt)) {\n try {\n rmSync(pyAlt, { force: true });\n } catch {\n }\n writeFileSync(\n pyAlt,\n `#!/bin/sh\nexec /usr/bin/arch ${archFlag} \"${realBin}\" \"$@\"\n`\n );\n chmodSync(pyAlt, 493);\n }\n logger.info(\"Locked python3 to host arch via shell stub\", {\n meta: { archFlag, realBin }\n });\n }\n }\n logger.info(\"Portable Python installed\", { meta: { version: PYTHON_VERSION, pythonBin } });\n return pythonBin;\n}\nasync function installPythonPackages(pythonPath, packages, logger) {\n if (packages.length === 0) return;\n logger.info(\"Installing Python packages\", { meta: { packages } });\n try {\n execFileSync(pythonPath, [\"-m\", \"pip\", \"install\", \"--quiet\", ...packages], {\n stdio: \"pipe\",\n timeout: 3e5\n // 5 minutes for large packages like torch\n });\n logger.info(\"Python packages installed successfully\");\n } catch (err) {\n logger.error(\"Failed to install Python packages\", { meta: { error: errMsg(err) } });\n throw err;\n }\n}\nasync function installPythonRequirements(pythonPath, requirementsFile, logger) {\n if (!existsSync(requirementsFile)) {\n throw new Error(`Requirements file not found: ${requirementsFile}`);\n }\n const contents = readFileSync(requirementsFile);\n const hash = createHash(\"sha256\").update(contents).digest(\"hex\").slice(0, 16);\n const fileBase = basename(requirementsFile).replace(/\\.txt$/i, \"\");\n const pythonRoot = join(pythonPath, \"..\", \"..\");\n const markerDir = join(pythonRoot, \".requirements-installed\");\n const markerPath = join(markerDir, `${fileBase}-${hash}.marker`);\n if (existsSync(markerPath)) {\n logger.debug(\"Python requirements already installed\", { meta: { requirementsFile, hash } });\n return;\n }\n logger.info(\"Installing Python requirements\", { meta: { requirementsFile, hash } });\n try {\n execFileSync(\n pythonPath,\n [\"-m\", \"pip\", \"install\", \"--quiet\", \"--disable-pip-version-check\", \"-r\", requirementsFile],\n {\n stdio: \"pipe\",\n timeout: 6e5\n // 10 minutes — coremltools + tensorflow can be slow\n }\n );\n } catch (err) {\n logger.error(\"Failed to install Python requirements\", {\n meta: { requirementsFile, error: errMsg(err) }\n });\n throw err;\n }\n mkdirSync(markerDir, { recursive: true });\n writeFileSync(markerPath, `${requirementsFile}\n${(/* @__PURE__ */ new Date()).toISOString()}\n`);\n logger.info(\"Python requirements installed\", { meta: { requirementsFile, hash } });\n}\nconst STORAGE_LOCATION_TYPES = [\n \"data\",\n \"media\",\n \"recordings\",\n \"recordings-high\",\n \"recordings-low\",\n \"recordings-clips\",\n \"event-images\",\n \"models\",\n \"addons-data\",\n \"cache\",\n \"logs\",\n \"backups\"\n];\nconst DEFAULT_LOCATION_SUBDIRS = {\n \"data\": \"db\",\n \"media\": \"media\",\n \"recordings\": \"recordings\",\n \"recordings-high\": \"recordings-high\",\n \"recordings-low\": \"recordings-low\",\n \"recordings-clips\": \"recordings-clips\",\n \"event-images\": \"event-images\",\n \"models\": \"models\",\n \"addons-data\": \"addons-data\",\n \"cache\": \"/tmp/camstack-cache\",\n \"logs\": \"logs\",\n \"backups\": \"backups\"\n};\nclass FilesystemStorageProvider {\n id = \"local\";\n name = \"Local Filesystem\";\n supportedLocations = [...STORAGE_LOCATION_TYPES];\n rootPath;\n locationPaths;\n constructor(rootPath, overrides) {\n this.rootPath = path.resolve(rootPath);\n this.locationPaths = /* @__PURE__ */ new Map();\n for (const loc of STORAGE_LOCATION_TYPES) {\n const override = overrides?.[loc];\n if (override) {\n this.locationPaths.set(loc, path.resolve(override));\n } else {\n const subdir = DEFAULT_LOCATION_SUBDIRS[loc];\n this.locationPaths.set(\n loc,\n path.isAbsolute(subdir) ? subdir : path.join(this.rootPath, subdir)\n );\n }\n }\n }\n async resolve({ location, relativePath }) {\n const base = this.locationPaths.get(location);\n if (!base) throw new Error(`Unknown storage location: ${location}`);\n return path.join(base, relativePath);\n }\n async write({ location, relativePath, data }) {\n const filePath = await this.resolve({ location, relativePath });\n await fs.promises.mkdir(path.dirname(filePath), { recursive: true });\n if (Buffer.isBuffer(data)) {\n await fs.promises.writeFile(filePath, data);\n } else {\n const writeStream = fs.createWriteStream(filePath);\n await new Promise((resolve, reject) => {\n data.pipe(writeStream);\n writeStream.on(\"finish\", resolve);\n writeStream.on(\"error\", reject);\n });\n }\n }\n async read({ location, relativePath }) {\n return fs.promises.readFile(await this.resolve({ location, relativePath }));\n }\n async exists({ location, relativePath }) {\n try {\n await fs.promises.access(await this.resolve({ location, relativePath }));\n return true;\n } catch {\n return false;\n }\n }\n async list({ location, prefix }) {\n const base = this.locationPaths.get(location);\n if (!base) return [];\n const dir = prefix ? path.join(base, prefix) : base;\n try {\n const entries = await fs.promises.readdir(dir, { withFileTypes: true });\n return entries.map((e) => prefix ? `${prefix}/${e.name}` : e.name);\n } catch {\n return [];\n }\n }\n async delete({ location, relativePath }) {\n const filePath = await this.resolve({ location, relativePath });\n await fs.promises.rm(filePath, { force: true });\n }\n async getAvailableSpace({ location }) {\n const base = this.locationPaths.get(location);\n if (!base) return null;\n try {\n let target = base;\n while (!fs.existsSync(target)) {\n const parent = path.dirname(target);\n if (!parent || parent === target) return null;\n target = parent;\n }\n const stats = await fs.promises.statfs(target);\n return stats.bavail * stats.bsize;\n } catch {\n return null;\n }\n }\n /** Get the resolved path for a location type */\n getLocationPath(location) {\n const p = this.locationPaths.get(location);\n if (!p) throw new Error(`Unknown storage location: ${location}`);\n return p;\n }\n /** Get the root path */\n getRootPath() {\n return this.rootPath;\n }\n}\nexport {\n FilesystemStorageProvider,\n PYTHON_VERSION,\n buildBinaryPath,\n downloadBinary,\n ensureBinary,\n ensureFfmpeg,\n ensurePython,\n findInPath,\n getFfmpegDownloadUrl,\n getPlatformInfo,\n getPythonDownloadUrl,\n installPythonPackages,\n installPythonRequirements\n};\n//# sourceMappingURL=node.mjs.map\n","type EventCallback<T = unknown> = (data: T) => void\n\nexport class EventBus {\n private listeners = new Map<string, Set<EventCallback>>()\n\n on<T = unknown>(event: string, callback: EventCallback<T>): () => void {\n if (!this.listeners.has(event)) this.listeners.set(event, new Set())\n const set = this.listeners.get(event)!\n set.add(callback as EventCallback)\n return () => set.delete(callback as EventCallback)\n }\n\n emit<T = unknown>(event: string, data: T): void {\n const set = this.listeners.get(event)\n if (!set) return\n for (const cb of set) {\n try { cb(data) } catch { /* don't let one listener break others */ }\n }\n }\n\n once<T = unknown>(event: string, callback: EventCallback<T>): () => void {\n const unsub = this.on<T>(event, (data) => {\n unsub()\n callback(data)\n })\n return unsub\n }\n\n removeAllListeners(event?: string): void {\n if (event) this.listeners.delete(event)\n else this.listeners.clear()\n }\n\n listenerCount(event: string): number {\n return this.listeners.get(event)?.size ?? 0\n }\n}\n","import type { ModelCatalogEntry, ModelDownloadOptions, ModelDownloadResult, ModelFormat } from '@camstack/types'\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport { createHash } from 'node:crypto'\n\n/** Build fetch headers, including HF auth token for huggingface.co URLs */\nfunction buildHeaders(url: string): Record<string, string> {\n const headers: Record<string, string> = { 'User-Agent': 'CamStack/1.0' }\n const hfToken = process.env['HF_TOKEN'] ?? process.env['HUGGING_FACE_HUB_TOKEN']\n if (hfToken && url.includes('huggingface.co')) {\n headers['Authorization'] = `Bearer ${hfToken}`\n }\n return headers\n}\n\n/**\n * Download a single file from a URL to a destination path.\n * Uses native fetch() (Node 22+) which handles redirects natively.\n * Streams to disk with optional progress callback.\n * Returns the destination path. Skips download if file already exists.\n */\nexport async function downloadFile(\n url: string,\n destPath: string,\n onProgress?: (downloaded: number, total: number) => void,\n): Promise<string> {\n if (fs.existsSync(destPath)) return destPath\n\n fs.mkdirSync(path.dirname(destPath), { recursive: true })\n\n // Atomic download: write to .downloading tmp, rename on success\n const tmpPath = destPath + '.downloading'\n\n try {\n const response = await fetch(url, {\n redirect: 'follow',\n headers: buildHeaders(url),\n })\n if (!response.ok) {\n throw new Error(`HTTP ${response.status} downloading ${url}`)\n }\n if (!response.body) {\n throw new Error(`No response body from ${url}`)\n }\n\n const total = parseInt(response.headers.get('content-length') ?? '0', 10)\n let downloaded = 0\n\n const fileStream = fs.createWriteStream(tmpPath)\n const reader = response.body.getReader()\n\n try {\n for (;;) {\n const { done, value } = await reader.read() as { done: boolean; value?: Uint8Array }\n if (done || !value) break\n fileStream.write(value)\n downloaded += value.length\n onProgress?.(downloaded, total)\n }\n } finally {\n fileStream.end()\n await new Promise<void>((resolve, reject) => {\n fileStream.on('finish', resolve)\n fileStream.on('error', reject)\n })\n }\n\n fs.renameSync(tmpPath, destPath)\n return destPath\n } catch (err) {\n // Clean up partial download\n try { fs.unlinkSync(tmpPath) } catch { /* ignore */ }\n throw err\n }\n}\n\n/**\n * Fetch JSON from a URL using native fetch().\n */\nexport async function fetchJson(url: string): Promise<unknown> {\n const response = await fetch(url, {\n redirect: 'follow',\n headers: buildHeaders(url),\n })\n if (!response.ok) {\n throw new Error(`HTTP ${response.status} fetching ${url}`)\n }\n return response.json()\n}\n\n/**\n * Download a model with fallback URLs and optional SHA256 verification.\n * Legacy API preserved for backward compatibility -- delegates to downloadFile().\n */\nexport async function downloadModel(options: ModelDownloadOptions): Promise<ModelDownloadResult> {\n const { url, fallbackUrls = [], destDir, filename, expectedSha256, onProgress } = options\n\n const fname = filename ?? url.split('/').pop() ?? 'model.bin'\n const destPath = path.join(destDir, fname)\n\n // Check cache\n if (fs.existsSync(destPath)) {\n return { filePath: destPath, downloadedBytes: 0, fromCache: true }\n }\n\n fs.mkdirSync(destDir, { recursive: true })\n\n const urls = [url, ...fallbackUrls]\n let lastError: Error | null = null\n\n for (const tryUrl of urls) {\n try {\n await downloadFile(tryUrl, destPath, onProgress)\n\n // Verify SHA256 if provided\n if (expectedSha256) {\n const hash = await computeSha256(destPath)\n if (hash !== expectedSha256) {\n fs.unlinkSync(destPath)\n throw new Error(`SHA256 mismatch: expected ${expectedSha256}, got ${hash}`)\n }\n }\n\n const stat = fs.statSync(destPath)\n return { filePath: destPath, downloadedBytes: stat.size, fromCache: false }\n } catch (e) {\n lastError = e as Error\n if (fs.existsSync(destPath)) fs.unlinkSync(destPath)\n }\n }\n\n throw lastError ?? new Error(`Failed to download model from ${url}`)\n}\n\nasync function computeSha256(filePath: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const hash = createHash('sha256')\n const stream = fs.createReadStream(filePath)\n stream.on('data', (chunk) => hash.update(chunk))\n stream.on('end', () => resolve(hash.digest('hex')))\n stream.on('error', reject)\n })\n}\n\n// ---------------------------------------------------------------------------\n// ModelCatalogEntry-based helpers\n// ---------------------------------------------------------------------------\n//\n// These are the standalone counterparts to `ModelDownloadService.ensure()`\n// for callers that don't need a class-based catalog and just want to\n// resolve a single `ModelCatalogEntry` against `modelsDir`. Detection\n// pipeline previously kept its own copy of this logic\n// (`addon-detection-pipeline/src/engine/model-downloader.ts`); merging\n// them here lets every addon (detection, audio-analyzer, embedding-\n// encoder, …) share one source of truth.\n\n/** Progress callback: (downloadedBytes, totalBytes | undefined) */\nexport type DownloadProgressCallback = (downloaded: number, total: number | undefined) => void\n\n/**\n * Download every file in a HuggingFace directory bundle (e.g.,\n * `.mlpackage` / OpenVINO IR pair) atomically. `knownFiles` lists the\n * relative paths inside the directory; the function fetches each from\n * `${url}/${file}` and renames the staging directory only on full\n * success. Mirrors `ModelDownloadService.downloadDirectory` but\n * exposed as a standalone for catalog-less callers.\n */\nasync function downloadDirectory(\n url: string,\n destDir: string,\n knownFiles: readonly string[] | undefined,\n onProgress?: DownloadProgressCallback,\n): Promise<void> {\n const match = url.match(/huggingface\\.co\\/([^/]+\\/[^/]+)\\/resolve\\/main\\/(.+)/)\n if (!match) throw new Error(`Cannot parse HuggingFace URL: ${url}`)\n const [, repo, dirPath] = match\n\n const files = (knownFiles ?? []).map(f => ({\n relativePath: f,\n fileUrl: `https://huggingface.co/${repo}/resolve/main/${dirPath}/${f}`,\n }))\n if (files.length === 0) {\n throw new Error(`Directory bundle requires explicit \\`files\\` list (got none for ${url})`)\n }\n\n const tmpDir = destDir + '.downloading'\n fs.rmSync(tmpDir, { recursive: true, force: true })\n fs.mkdirSync(tmpDir, { recursive: true })\n\n let totalDownloaded = 0\n try {\n for (const file of files) {\n const destPath = path.join(tmpDir, file.relativePath)\n fs.mkdirSync(path.dirname(destPath), { recursive: true })\n await downloadFile(file.fileUrl, destPath, (downloaded, _total) => {\n onProgress?.(totalDownloaded + downloaded, undefined)\n })\n totalDownloaded += fs.statSync(destPath).size\n }\n fs.rmSync(destDir, { recursive: true, force: true })\n fs.renameSync(tmpDir, destDir)\n } catch (err) {\n fs.rmSync(tmpDir, { recursive: true, force: true })\n throw err\n }\n}\n\n/**\n * Resolve a `ModelCatalogEntry` against `modelsDir`: download model file\n * (or directory bundle) + extra files (labels JSON, charset dict, …),\n * skip if already on disk. Returns the local model path.\n */\nexport async function ensureModel(\n modelsDir: string,\n entry: ModelCatalogEntry,\n format: ModelFormat,\n onProgress?: DownloadProgressCallback,\n): Promise<string> {\n const formatEntry = entry.formats[format]\n if (!formatEntry) {\n throw new Error(\n `Model \"${entry.id}\" has no ${format} format. Available: ${Object.keys(entry.formats).join(', ')}`,\n )\n }\n\n // Extras (labels, dicts) — independent of format.\n if (entry.extraFiles) {\n for (const extra of entry.extraFiles) {\n await downloadFile(extra.url, path.join(modelsDir, extra.filename))\n }\n }\n\n const filename = formatEntry.url.split('/').pop() ?? `${entry.id}.${format}`\n const modelPath = path.join(modelsDir, filename)\n\n if (fs.existsSync(modelPath)) {\n if (formatEntry.isDirectory && !fs.existsSync(path.join(modelPath, 'Manifest.json'))) {\n // Stale half-downloaded mlpackage — wipe and re-fetch.\n fs.rmSync(modelPath, { recursive: true, force: true })\n } else {\n return modelPath\n }\n }\n\n fs.mkdirSync(modelsDir, { recursive: true })\n\n if (formatEntry.isDirectory) {\n await downloadDirectory(formatEntry.url, modelPath, formatEntry.files, onProgress)\n } else {\n await downloadFile(formatEntry.url, modelPath, (downloaded, total) =>\n onProgress?.(downloaded, total === 0 ? undefined : total),\n )\n }\n\n return modelPath\n}\n\n/** Compute the on-disk path for a given model + format, even when not yet downloaded. */\nexport function getModelFilePath(\n modelsDir: string,\n entry: ModelCatalogEntry,\n format: ModelFormat,\n): string | null {\n const formatEntry = entry.formats[format]\n if (!formatEntry) return null\n const filename = formatEntry.url.split('/').pop() ?? `${entry.id}.${format}`\n return path.join(modelsDir, filename)\n}\n\n/** True iff the model file (or `Manifest.json` for directory bundles) exists and is non-empty. */\nexport function isModelDownloaded(\n modelsDir: string,\n entry: ModelCatalogEntry,\n format: ModelFormat,\n): boolean {\n const formatEntry = entry.formats[format]\n if (!formatEntry) return false\n const modelPath = getModelFilePath(modelsDir, entry, format)\n if (!modelPath || !fs.existsSync(modelPath)) return false\n if (formatEntry.isDirectory) return fs.existsSync(path.join(modelPath, 'Manifest.json'))\n return fs.statSync(modelPath).size > 0\n}\n\n/** Remove the on-disk model file/directory. Returns true if something was deleted. */\nexport function deleteModelFromDisk(\n modelsDir: string,\n entry: ModelCatalogEntry,\n format: ModelFormat,\n): boolean {\n const modelPath = getModelFilePath(modelsDir, entry, format)\n if (!modelPath || !fs.existsSync(modelPath)) return false\n const formatEntry = entry.formats[format]\n if (formatEntry?.isDirectory) {\n fs.rmSync(modelPath, { recursive: true, force: true })\n } else {\n fs.unlinkSync(modelPath)\n }\n return true\n}\n","import type { ModelCatalogEntry, ModelFormat, IAddonModelManager } from '@camstack/types'\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport { downloadFile, fetchJson } from './model-downloader.js'\n\n/**\n * Unified model download service.\n *\n * Handles downloading model files and extra files (labels, dicts) from a\n * catalog of ModelCatalogEntry items. Supports single-file models and\n * directory bundles (e.g., .mlpackage for CoreML).\n *\n * Addons use this via `context.models.ensure(modelId, format)`.\n */\nexport class ModelDownloadService implements IAddonModelManager {\n private readonly catalog: ReadonlyMap<string, ModelCatalogEntry>\n\n constructor(\n private readonly modelsDir: string,\n catalog: readonly ModelCatalogEntry[],\n private readonly onProgress?: (modelId: string, downloaded: number, total: number) => void,\n ) {\n const map = new Map<string, ModelCatalogEntry>()\n for (const entry of catalog) {\n map.set(entry.id, entry)\n }\n this.catalog = map\n }\n\n /**\n * Ensure a model (and its extra files) is downloaded.\n * Returns the local filesystem path to the model file/directory.\n */\n async ensure(modelId: string, format?: ModelFormat): Promise<string> {\n const entry = this.catalog.get(modelId)\n if (!entry) {\n throw new Error(`ModelDownloadService: unknown model \"${modelId}\"`)\n }\n\n // Resolve format: use provided or pick first available\n const selectedFormat = format ?? this.pickDefaultFormat(entry)\n const formatEntry = entry.formats[selectedFormat]\n if (!formatEntry) {\n throw new Error(\n `ModelDownloadService: model \"${modelId}\" has no ${selectedFormat} format`,\n )\n }\n\n // Download extra files first (labels JSON, dict.txt, etc.)\n await this.ensureExtraFiles(modelId)\n\n // Derive local path from URL\n const modelPath = this.modelFilePath(entry, selectedFormat)\n\n if (fs.existsSync(modelPath)) {\n // Validate directory bundles have required Manifest.json\n if (formatEntry.isDirectory) {\n if (!fs.existsSync(path.join(modelPath, 'Manifest.json'))) {\n fs.rmSync(modelPath, { recursive: true, force: true })\n } else {\n return modelPath\n }\n } else {\n return modelPath\n }\n }\n\n fs.mkdirSync(this.modelsDir, { recursive: true })\n\n if (formatEntry.isDirectory) {\n await this.downloadDirectory(\n formatEntry.url,\n modelPath,\n formatEntry.files,\n modelId,\n )\n } else {\n await downloadFile(\n formatEntry.url,\n modelPath,\n this.onProgress\n ? (downloaded, total) => this.onProgress!(modelId, downloaded, total)\n : undefined,\n )\n }\n\n return modelPath\n }\n\n /**\n * Ensure extra files for a model are downloaded.\n * Returns the local paths of all extra files.\n */\n async ensureExtraFiles(modelId: string): Promise<readonly string[]> {\n const entry = this.catalog.get(modelId)\n if (!entry) {\n throw new Error(`ModelDownloadService: unknown model \"${modelId}\"`)\n }\n\n const extras = entry.extraFiles\n if (!extras || extras.length === 0) return []\n\n const paths: string[] = []\n for (const extra of extras) {\n const destPath = path.join(this.modelsDir, extra.filename)\n await downloadFile(extra.url, destPath)\n paths.push(destPath)\n }\n return paths\n }\n\n /** Absolute path to the shared models directory. */\n getModelsDir(): string {\n return this.modelsDir\n }\n\n /** Check if a model file is already present on disk. */\n isDownloaded(modelId: string, format?: ModelFormat): boolean {\n const entry = this.catalog.get(modelId)\n if (!entry) return false\n\n const selectedFormat = format ?? this.pickDefaultFormat(entry)\n const formatEntry = entry.formats[selectedFormat]\n if (!formatEntry) return false\n\n const modelPath = this.modelFilePath(entry, selectedFormat)\n if (!fs.existsSync(modelPath)) return false\n\n // Validate directory bundles\n if (formatEntry.isDirectory) {\n return fs.existsSync(path.join(modelPath, 'Manifest.json'))\n }\n\n return fs.statSync(modelPath).size > 0\n }\n\n /** Get the catalog entry for a model by ID. */\n getEntry(modelId: string): ModelCatalogEntry | undefined {\n return this.catalog.get(modelId)\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private pickDefaultFormat(entry: ModelCatalogEntry): ModelFormat {\n // Prefer onnx, then others in order\n const priority: ModelFormat[] = ['onnx', 'coreml', 'openvino', 'tflite', 'pt']\n for (const fmt of priority) {\n if (entry.formats[fmt]) return fmt\n }\n // Fallback: first available format\n const first = Object.keys(entry.formats)[0] as ModelFormat | undefined\n if (first) return first\n throw new Error(`ModelDownloadService: model \"${entry.id}\" has no formats`)\n }\n\n private modelFilePath(entry: ModelCatalogEntry, format: ModelFormat): string {\n const formatEntry = entry.formats[format]\n if (!formatEntry) {\n throw new Error(`Model ${entry.id} has no ${format} format`)\n }\n const urlParts = formatEntry.url.split('/')\n const filename = urlParts[urlParts.length - 1] ?? `${entry.id}.${format}`\n return path.join(this.modelsDir, filename)\n }\n\n /**\n * Download a directory bundle (e.g., .mlpackage) from HuggingFace.\n * ATOMIC: downloads to temp dir, renames only on complete success.\n */\n private async downloadDirectory(\n url: string,\n destDir: string,\n knownFiles?: readonly string[],\n _modelId?: string,\n ): Promise<void> {\n const match = url.match(/huggingface\\.co\\/([^/]+\\/[^/]+)\\/resolve\\/main\\/(.+)/)\n if (!match) throw new Error(`Cannot parse HuggingFace URL: ${url}`)\n\n const [, repo, dirPath] = match\n\n let filesToDownload: Array<{ relativePath: string; fileUrl: string }>\n\n if (knownFiles && knownFiles.length > 0) {\n filesToDownload = knownFiles.map(f => ({\n relativePath: f,\n fileUrl: `https://huggingface.co/${repo}/resolve/main/${dirPath}/${f}`,\n }))\n } else {\n const hfFiles = await this.listHfFiles(repo!, dirPath!)\n if (hfFiles.length === 0) {\n throw new Error(`No files found in HuggingFace directory: ${dirPath}`)\n }\n filesToDownload = hfFiles.map(f => ({\n relativePath: f.path.substring(dirPath!.length + 1),\n fileUrl: `https://huggingface.co/${repo}/resolve/main/${f.path}`,\n }))\n }\n\n const tmpDir = destDir + '.downloading'\n fs.rmSync(tmpDir, { recursive: true, force: true })\n fs.mkdirSync(tmpDir, { recursive: true })\n\n try {\n for (const file of filesToDownload) {\n const destPath = path.join(tmpDir, file.relativePath)\n fs.mkdirSync(path.dirname(destPath), { recursive: true })\n await downloadFile(file.fileUrl, destPath)\n }\n\n fs.rmSync(destDir, { recursive: true, force: true })\n fs.renameSync(tmpDir, destDir)\n } catch (err) {\n fs.rmSync(tmpDir, { recursive: true, force: true })\n throw err\n }\n }\n\n /** Recursively list all files in a HuggingFace directory via API. */\n private async listHfFiles(\n repo: string,\n dirPath: string,\n ): Promise<Array<{ path: string; size: number }>> {\n const apiUrl = `https://huggingface.co/api/models/${repo}/tree/main/${dirPath}`\n const entries = (await fetchJson(apiUrl)) as ReadonlyArray<{\n readonly type: string\n readonly path: string\n readonly size?: number\n readonly lfs?: { readonly size: number }\n }>\n const files: Array<{ path: string; size: number }> = []\n\n for (const entry of entries) {\n if (entry.type === 'file') {\n files.push({ path: entry.path, size: entry.size ?? entry.lfs?.size ?? 0 })\n } else if (entry.type === 'directory') {\n const subFiles = await this.listHfFiles(repo, entry.path)\n files.push(...subFiles)\n }\n }\n\n return files\n }\n}\n","import type { IPythonEnvironment, PythonProbeResult, PythonEnvReady } from '@camstack/types'\nimport { execFile, spawn } from 'node:child_process'\nimport type { ChildProcess } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\nconst execFileAsync = promisify(execFile)\n\nexport class PythonEnvManager implements IPythonEnvironment {\n private venvPath: string\n private cachedProbe: PythonProbeResult | null = null\n\n constructor(dataDir: string) {\n this.venvPath = path.join(dataDir, '.venv')\n }\n\n async probe(): Promise<PythonProbeResult> {\n if (this.cachedProbe) return this.cachedProbe\n\n // Try python3, then python\n for (const cmd of ['python3', 'python']) {\n try {\n const { stdout } = await execFileAsync(cmd, ['--version'])\n const version = stdout.trim().replace('Python ', '')\n const major = parseInt(version.split('.')[0] ?? '0', 10)\n const minor = parseInt(version.split('.')[1] ?? '0', 10)\n\n if (major < 3 || (major === 3 && minor < 10)) continue\n\n // Get path\n const { stdout: pathOut } = await execFileAsync(cmd, ['-c', 'import sys; print(sys.executable)'])\n\n this.cachedProbe = {\n available: true,\n version,\n path: pathOut.trim(),\n }\n return this.cachedProbe\n } catch { continue }\n }\n\n this.cachedProbe = { available: false }\n return this.cachedProbe\n }\n\n async ensure(options: { packages: readonly string[] }): Promise<PythonEnvReady> {\n const probe = await this.probe()\n if (!probe.available || !probe.path) {\n throw new Error('Python 3.10+ is required but not found on this system')\n }\n\n // Create venv if needed\n if (!fs.existsSync(path.join(this.venvPath, 'bin', 'python'))) {\n await execFileAsync(probe.path, ['-m', 'venv', this.venvPath])\n }\n\n const venvPython = path.join(this.venvPath, 'bin', 'python')\n\n // Install packages\n if (options.packages.length > 0) {\n await execFileAsync(venvPython, ['-m', 'pip', 'install', '-q', ...options.packages])\n }\n\n return {\n pythonPath: venvPython,\n venvPath: this.venvPath,\n spawn: (script: string, args: readonly string[]) => {\n return spawn(venvPython, [script, ...args])\n },\n }\n }\n\n spawn(script: string, args: readonly string[]): ChildProcess {\n const venvPython = path.join(this.venvPath, 'bin', 'python')\n if (!fs.existsSync(venvPython)) {\n throw new Error('Python venv not initialized. Call ensure() first.')\n }\n return spawn(venvPython, [script, ...args])\n }\n}\n","import type { PipelineConfig, PipelineNode, ValidationIssue, ValidationResult } from '@camstack/types'\n\nexport type { ValidationIssue, ValidationResult }\n\n/**\n * Check if a pipeline step is available in the system.\n * Implementations should check the capability registry for `pipeline-step:{stepId}`.\n */\nexport type StepExistsFn = (stepId: string) => boolean\n\nexport class PipelineValidator {\n constructor(private readonly stepExists: StepExistsFn) {}\n\n validate(config: PipelineConfig): ValidationResult {\n const errors: ValidationIssue[] = []\n const warnings: ValidationIssue[] = []\n\n for (const node of config.video) {\n this.validateNode(node, errors, warnings)\n }\n\n if (config.audio) {\n this.validateNode(config.audio, errors, warnings)\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n }\n }\n\n private validateNode(\n node: PipelineNode,\n errors: ValidationIssue[],\n warnings: ValidationIssue[],\n ): void {\n if (!this.stepExists(node.addon)) {\n errors.push({\n step: node.step,\n addon: node.addon,\n message: `Step \"${node.addon}\" has no provider — the addon that provided it may have been removed`,\n severity: 'error',\n })\n return\n }\n\n if (node.children) {\n for (const child of node.children) {\n this.validateNode(child, errors, warnings)\n }\n }\n }\n}\n","import type {\n FrameInput,\n CropInput,\n PipelineConfig,\n PipelineNode,\n PipelineResult,\n StepResult,\n SpatialDetection,\n PipelineSlot,\n IAddonResolver,\n InferenceOutput,\n} from '@camstack/types'\nimport { randomUUID } from 'node:crypto'\nimport { errMsg } from '@camstack/types'\n\nexport class PipelineRunner {\n constructor(\n private readonly addonResolver: IAddonResolver,\n ) {}\n\n async run(frame: FrameInput, config: PipelineConfig): Promise<PipelineResult> {\n const startTime = performance.now()\n const results: StepResult[] = []\n const timings: Record<string, number> = {}\n\n // Execute video pipeline root nodes\n for (const rootNode of config.video) {\n await this.executeNode(rootNode, frame, null, results, timings)\n }\n\n // Execute audio node if present (independent)\n if (config.audio) {\n await this.executeNode(config.audio, frame, null, results, timings)\n }\n\n return {\n results,\n totalMs: performance.now() - startTime,\n timings,\n frameTimestamp: frame.timestamp,\n }\n }\n private async executeNode(\n node: PipelineNode,\n frame: FrameInput,\n parentDetection: { det: SpatialDetection; resultId: string } | null,\n results: StepResult[],\n timings: Record<string, number>,\n ): Promise<void> {\n const resultId = randomUUID()\n const stepStart = performance.now()\n\n try {\n // Resolve addon caller via the resolver\n const effectiveConfig = { ...node.configOverride }\n const caller = await this.addonResolver.resolve(node.addon, effectiveConfig)\n\n // Unified interface: always call process() with the appropriate input.\n // - Root nodes: FrameInput (full frame)\n // - Child nodes: CropInput (region from parent detection)\n // The addon determines output type (detections/crops/classifications/mask)\n // based on its slot — the runner doesn't need to know.\n let output: InferenceOutput\n\n if (parentDetection) {\n const cropInput: CropInput = {\n frame,\n roi: parentDetection.det.bbox,\n parentDetection: parentDetection.det,\n }\n output = await caller.process(cropInput)\n } else {\n output = await caller.process(frame)\n }\n\n const stepMs = performance.now() - stepStart\n\n // Determine slot type from output shape\n const slot: PipelineSlot =\n 'detections' in output ? 'detector' :\n 'crops' in output ? 'cropper' :\n 'classifier'\n\n const stepResult: StepResult = {\n addon: node.addon,\n slot,\n output,\n parentResultId: parentDetection?.resultId,\n resultId,\n inferenceMs: output.inferenceMs,\n preprocessMs: 0,\n totalMs: stepMs,\n }\n results.push(stepResult)\n timings[node.step] = stepMs\n\n // Process children\n if (node.children?.length) {\n const detections: readonly SpatialDetection[] =\n 'detections' in output ? output.detections :\n 'crops' in output ? output.crops :\n []\n\n // For each detection, find children with matching inputClasses and execute\n await this.executeChildren(node.children, frame, detections, resultId, results, timings)\n }\n } catch (error: unknown) {\n const stepMs = performance.now() - stepStart\n const message = errMsg(error)\n results.push({\n addon: node.addon,\n slot: 'detector',\n output: { detections: [], inferenceMs: 0, modelId: '' },\n parentResultId: parentDetection?.resultId,\n resultId,\n inferenceMs: 0,\n preprocessMs: 0,\n totalMs: stepMs,\n error: {\n code: 'ADDON_ERROR',\n message,\n childrenSkipped: true,\n },\n })\n }\n }\n\n private async executeChildren(\n children: readonly PipelineNode[],\n frame: FrameInput,\n parentDetections: readonly SpatialDetection[],\n parentResultId: string,\n results: StepResult[],\n timings: Record<string, number>,\n ): Promise<void> {\n // For each parent detection, run all matching children in parallel\n const promises: Promise<void>[] = []\n\n for (const detection of parentDetections) {\n // Skip detections with degenerate bounding boxes\n if (detection.bbox.w < 1 || detection.bbox.h < 1) continue\n\n for (const child of children) {\n // TODO: Check inputClasses matching from addon manifest\n // For now, run all children on all detections (caller configures tree correctly)\n promises.push(\n this.executeNode(child, frame, { det: detection, resultId: parentResultId }, results, timings),\n )\n }\n }\n\n await Promise.allSettled(promises)\n }\n}\n","import type {\n IAddonResolver,\n IAddonCaller,\n IEngineManager,\n InferenceOutput,\n FrameInput,\n CropInput,\n} from '@camstack/types'\n\n/**\n * Adapter that wraps an IEngineManager + addonConfigs as an IAddonResolver.\n *\n * Used for backwards compatibility — the in-process AddonEngineManager\n * still uses the old getOrCreateEngine(addonId, globalConfig, override) API.\n * This adapter bridges it to the new resolve(addonId, config) interface.\n */\nexport class EngineManagerResolver implements IAddonResolver {\n constructor(\n private readonly engineManager: IEngineManager,\n private readonly addonConfigs: Map<string, Record<string, unknown>>,\n ) {}\n\n async resolve(addonId: string, config: Record<string, unknown>): Promise<IAddonCaller> {\n const globalConfig = this.addonConfigs.get(addonId) ?? {}\n const engine = await this.engineManager.getOrCreateEngine(addonId, globalConfig, config)\n\n return {\n process: async (input: FrameInput | CropInput): Promise<InferenceOutput> => {\n return engine.process(input as FrameInput)\n },\n }\n }\n\n async shutdownAll(): Promise<void> {\n await this.engineManager.shutdownAll()\n }\n}\n","import type {\n StreamNetworkStats,\n ClientNetworkStats,\n DeviceNetworkStats,\n INetworkQualityTracker,\n} from '@camstack/types'\n\nexport type {\n StreamNetworkStats,\n ClientNetworkStats,\n DeviceNetworkStats,\n INetworkQualityTracker,\n}\n\ninterface MutableStreamStats {\n nominalBitrateKbps: number\n samples: number[]\n peakBitrateKbps: number\n packetLossSamples: number[]\n lastUpdated: number\n}\n\nexport class NetworkQualityTracker implements INetworkQualityTracker {\n private readonly devices = new Map<number, {\n streams: Map<string, MutableStreamStats>\n client: (ClientNetworkStats & { lastUpdated: number }) | null\n }>()\n\n private static readonly MAX_SAMPLES = 30 // ~5 min at 10s reporting interval\n\n reportStreamStats(deviceId: number, streamId: string, bitrateKbps: number, packetLoss?: number): void {\n const device = this.getOrCreateDevice(deviceId)\n let stream = device.streams.get(streamId)\n if (!stream) {\n stream = { nominalBitrateKbps: bitrateKbps, samples: [], peakBitrateKbps: 0, packetLossSamples: [], lastUpdated: 0 }\n device.streams.set(streamId, stream)\n }\n\n stream.samples.push(bitrateKbps)\n if (stream.samples.length > NetworkQualityTracker.MAX_SAMPLES) stream.samples.shift()\n\n stream.peakBitrateKbps = Math.max(stream.peakBitrateKbps, bitrateKbps)\n\n if (packetLoss !== undefined) {\n stream.packetLossSamples.push(packetLoss)\n if (stream.packetLossSamples.length > NetworkQualityTracker.MAX_SAMPLES) stream.packetLossSamples.shift()\n }\n\n stream.lastUpdated = Date.now()\n }\n\n reportClientStats(deviceId: number, stats: Omit<ClientNetworkStats, 'lastUpdated'>): void {\n const device = this.getOrCreateDevice(deviceId)\n device.client = { ...stats, lastUpdated: Date.now() }\n }\n\n getDeviceStats(deviceId: number): DeviceNetworkStats | null {\n const device = this.devices.get(deviceId)\n if (!device) return null\n\n const streams: Record<string, StreamNetworkStats> = {}\n for (const [streamId, s] of device.streams) {\n const avg = (arr: number[]) => arr.length === 0 ? 0 : arr.reduce((a, b) => a + b, 0) / arr.length\n streams[streamId] = {\n nominalBitrateKbps: s.nominalBitrateKbps,\n observedBitrateKbps: Math.round(avg(s.samples)),\n peakBitrateKbps: s.peakBitrateKbps,\n packetLossPercent: Math.round(avg(s.packetLossSamples) * 10) / 10,\n lastUpdated: s.lastUpdated,\n }\n }\n\n return { deviceId, streams, client: device.client ?? undefined }\n }\n\n getAllStats(): readonly DeviceNetworkStats[] {\n const results: DeviceNetworkStats[] = []\n for (const deviceId of this.devices.keys()) {\n const stats = this.getDeviceStats(deviceId)\n if (stats) results.push(stats)\n }\n return results\n }\n\n private getOrCreateDevice(deviceId: number) {\n let device = this.devices.get(deviceId)\n if (!device) {\n device = { streams: new Map(), client: null }\n this.devices.set(deviceId, device)\n }\n return device\n }\n}\n","import * as vm from 'node:vm'\nimport * as util from 'node:util'\nimport type {\n IReplEngine,\n IReplContextProvider,\n ReplSessionContext,\n ReplResult,\n} from './interfaces.js'\n\nconst EXECUTION_TIMEOUT_MS = 5000\nconst COMPLETION_TIMEOUT_MS = 1000\n\nexport class ReplEngine implements IReplEngine {\n constructor(\n private readonly contextProvider: IReplContextProvider,\n ) {}\n\n async execute(code: string, context: ReplSessionContext): Promise<ReplResult> {\n const start = Date.now()\n const sandbox = await this.buildSandbox(context)\n\n try {\n const vmContext = vm.createContext(sandbox)\n const script = new vm.Script(code)\n let result: unknown = script.runInContext(vmContext, { timeout: EXECUTION_TIMEOUT_MS })\n\n // If result is a Promise, await it with timeout\n if (result && typeof result === 'object' && 'then' in result && typeof (result as { then: unknown }).then === 'function') {\n result = await Promise.race([\n result as Promise<unknown>,\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error('Async timeout (5s)')), EXECUTION_TIMEOUT_MS),\n ),\n ])\n }\n\n const duration = Date.now() - start\n\n if (result === undefined) {\n return { output: 'undefined', type: 'void', duration }\n }\n\n return {\n output: util.inspect(result, {\n depth: 4,\n colors: false,\n maxArrayLength: 50,\n maxStringLength: 1000,\n }),\n type: 'value',\n duration,\n }\n } catch (err: unknown) {\n // Errors thrown inside vm contexts may not be instanceof Error\n // because they use a different Error constructor from the sandbox\n const message =\n err instanceof Error\n ? err.message\n : typeof err === 'object' && err !== null && 'message' in err\n ? String((err as { message: unknown }).message)\n : String(err)\n return {\n output: message,\n type: 'error',\n duration: Date.now() - start,\n }\n }\n }\n\n async getCompletions(partial: string, context: ReplSessionContext): Promise<string[]> {\n const sandbox = await this.buildSandbox(context)\n const keys = Object.keys(sandbox)\n\n if (!partial) return keys\n\n const lastDot = partial.lastIndexOf('.')\n if (lastDot === -1) {\n return keys.filter(k => k.startsWith(partial))\n }\n\n // Object property completion: \"device.get\" -> look up device, return matching keys\n const objPath = partial.substring(0, lastDot)\n const propPrefix = partial.substring(lastDot + 1)\n\n try {\n const vmContext = vm.createContext(sandbox)\n const obj: unknown = vm.runInContext(objPath, vmContext, { timeout: COMPLETION_TIMEOUT_MS })\n if (obj && typeof obj === 'object') {\n const proto: unknown = Object.getPrototypeOf(obj)\n const objKeys = Object.getOwnPropertyNames(obj)\n .concat(Object.getOwnPropertyNames(proto ?? {}))\n .filter(k => k.startsWith(propPrefix))\n return [...new Set(objKeys)].map(k => `${objPath}.${k}`)\n }\n } catch {\n // Ignore errors during completion\n }\n\n return []\n }\n\n private async buildSandbox(context: ReplSessionContext): Promise<Record<string, unknown>> {\n const base: Record<string, unknown> = {\n console: {\n log: (...args: unknown[]) => util.inspect(args),\n warn: (...args: unknown[]) => util.inspect(args),\n },\n JSON,\n Math,\n Date,\n Array,\n Object,\n String,\n Number,\n Boolean,\n Map,\n Set,\n Promise,\n Buffer,\n // Blocked globals\n setTimeout: undefined,\n setInterval: undefined,\n fetch: undefined,\n require: undefined,\n process: undefined,\n // Merge user-provided variables\n ...context.variables,\n }\n\n switch (context.scope.type) {\n case 'system':\n return { ...base, ...(await this.contextProvider.getSystemSandbox()) }\n\n case 'device':\n return { ...base, ...(await this.contextProvider.getDeviceSandbox(context.scope.deviceId!)) }\n\n case 'provider':\n return { ...base, ...(await this.contextProvider.getProviderSandbox(context.scope.providerId!)) }\n\n case 'addon':\n return { ...base, ...(await this.contextProvider.getAddonSandbox(context.scope.addonId!)) }\n\n default:\n return base\n }\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport type { IScopedLogger, IEventBus } from '@camstack/types'\n\nexport type ElementState = 'stopped' | 'starting' | 'running' | 'stopping' | 'error' | 'disabled'\n\nexport interface ElementStatus {\n state: ElementState\n error?: string\n startedAt?: number\n stoppedAt?: number\n restartCount: number\n uptime: number\n}\n\nconst VALID_TRANSITIONS: Readonly<Record<ElementState, readonly ElementState[]>> = {\n stopped: ['starting', 'disabled'],\n starting: ['running', 'error', 'stopping'],\n running: ['stopping', 'error'],\n stopping: ['stopped', 'error'],\n error: ['starting', 'stopped', 'disabled'],\n disabled: ['stopped'],\n}\n\nexport class LifecycleStateMachine {\n private _state: ElementState = 'stopped'\n private _error?: string\n private _startedAt?: number\n private _stoppedAt?: number\n private _restartCount = 0\n private _hasStartedOnce = false\n\n constructor(\n private readonly elementId: string,\n private readonly elementType: 'provider' | 'device' | 'addon' | 'process',\n private readonly eventBus: IEventBus,\n private readonly logger: IScopedLogger,\n ) {}\n\n get state(): ElementState {\n return this._state\n }\n\n getStatus(): ElementStatus {\n return {\n state: this._state,\n error: this._error,\n startedAt: this._startedAt,\n stoppedAt: this._stoppedAt,\n restartCount: this._restartCount,\n uptime:\n this._state === 'running' && this._startedAt\n ? Date.now() - this._startedAt\n : 0,\n }\n }\n\n transition(to: ElementState, error?: string): boolean {\n const from = this._state\n\n if (!this.isValidTransition(from, to)) {\n this.logger.warn('Invalid state transition', { meta: { from, to } })\n return false\n }\n\n this._state = to\n this._error = error\n\n if (to === 'running') {\n if (this._hasStartedOnce) {\n this._restartCount++\n }\n this._hasStartedOnce = true\n this._startedAt = Date.now()\n this._stoppedAt = undefined\n }\n\n if (to === 'stopped' || to === 'error' || to === 'disabled') {\n this._stoppedAt = Date.now()\n }\n\n this.logger.info('State transition', { meta: { from, to, error } })\n\n this.eventBus.emit({\n id: randomUUID(),\n timestamp: new Date(),\n source: { type: this.elementType, id: this.elementId },\n category: `${this.elementType}.state.${to}`,\n data: { from, to, error, elementId: this.elementId },\n })\n\n return true\n }\n\n incrementRestartCount(): void {\n this._restartCount++\n }\n\n private isValidTransition(from: ElementState, to: ElementState): boolean {\n return VALID_TRANSITIONS[from]?.includes(to) ?? false\n }\n}\n","import type { FeatureManifest, FeatureFlag } from '@camstack/types'\n\nexport type { FeatureManifest, FeatureFlag }\n\nexport type FeatureConfigReader = {\n readonly features: FeatureManifest\n}\n\nexport class FeatureManager {\n constructor(private readonly configReader: FeatureConfigReader) {}\n\n isEnabled(flag: FeatureFlag): boolean {\n return this.configReader.features[flag]\n }\n\n getManifest(): FeatureManifest {\n return { ...this.configReader.features }\n }\n}\n","import type {\n EventSource,\n SystemEvent,\n EventFilter,\n IEventBus,\n} from '@camstack/types'\n\nexport type { EventSource, SystemEvent, EventFilter }\n\ninterface Subscriber {\n readonly filter: EventFilter\n readonly callback: (event: SystemEvent) => void\n}\n\nclass EventRingBuffer {\n private readonly buffer: Array<SystemEvent | undefined>\n private head = 0\n private count = 0\n\n constructor(private readonly capacity: number) {\n this.buffer = Array.from<SystemEvent | undefined>({ length: capacity })\n }\n\n push(event: SystemEvent): void {\n this.buffer[this.head] = event\n this.head = (this.head + 1) % this.capacity\n if (this.count < this.capacity) {\n this.count++\n }\n }\n\n getAll(): readonly SystemEvent[] {\n const result: SystemEvent[] = []\n for (let i = 0; i < this.count; i++) {\n const index = (this.head - 1 - i + this.capacity) % this.capacity\n result.push(this.buffer[index]!)\n }\n return result\n }\n\n query(filter?: EventFilter, limit?: number): readonly SystemEvent[] {\n let result = [...this.getAll()]\n\n if (filter) {\n result = result.filter((event) => matchesFilter(event, filter))\n }\n\n if (limit !== undefined && limit > 0) {\n return result.slice(0, limit)\n }\n\n return result\n }\n}\n\nfunction matchesCategory(eventCategory: string, filterCategory: string): boolean {\n if (filterCategory.endsWith('.*')) {\n const prefix = filterCategory.slice(0, -2)\n return eventCategory.startsWith(prefix + '.') || eventCategory === prefix\n }\n return eventCategory === filterCategory\n}\n\nfunction matchesFilter(event: SystemEvent, filter: EventFilter): boolean {\n if (filter.category) {\n const raw = filter.category\n const categories: string[] = Array.isArray(raw) ? raw.map(String) : [String(raw)]\n if (!categories.some((cat) => matchesCategory(event.category, cat))) {\n return false\n }\n }\n\n if (filter.source) {\n if (event.source.type !== filter.source.type || event.source.id !== filter.source.id) {\n return false\n }\n }\n\n if (filter.agentId) {\n const eventNodeId = event.source.nodeId\n // Prefix match: 'hub' matches 'hub', 'hub/pipeline', etc.\n if (!eventNodeId || !eventNodeId.startsWith(filter.agentId)) {\n return false\n }\n }\n\n if (filter.addonId) {\n const eventAddonId = event.source.addonId\n ?? (event.source.type === 'addon' ? String(event.source.id) : undefined)\n if (eventAddonId !== filter.addonId) {\n return false\n }\n }\n\n if (filter.deviceId !== undefined) {\n const eventDeviceId = event.source.deviceId\n ?? (event.source.type === 'device' ? Number(event.source.id) : undefined)\n if (eventDeviceId !== filter.deviceId) {\n return false\n }\n }\n\n if (filter.since && event.timestamp < filter.since) {\n return false\n }\n\n return true\n}\n\nexport class SystemEventBus implements IEventBus {\n private readonly ringBuffer: EventRingBuffer\n private readonly subscribers: Subscriber[] = []\n\n constructor(bufferSize: number = 10000) {\n this.ringBuffer = new EventRingBuffer(bufferSize)\n }\n\n emit(event: SystemEvent): void {\n this.ringBuffer.push(event)\n\n for (const subscriber of this.subscribers) {\n if (matchesFilter(event, subscriber.filter)) {\n queueMicrotask(() => {\n try {\n subscriber.callback(event)\n } catch (err) {\n console.error(`[EventBus] Subscriber error for ${event.category}:`, err)\n }\n })\n }\n }\n }\n\n /**\n * Subscribe to events matching a filter.\n * When called with a typed category filter, the handler receives typed event data.\n */\n subscribe(filter: EventFilter, handler: (event: SystemEvent) => void): () => void {\n const subscriber: Subscriber = { filter, callback: handler }\n this.subscribers.push(subscriber)\n\n return () => {\n const index = this.subscribers.indexOf(subscriber)\n if (index !== -1) {\n this.subscribers.splice(index, 1)\n }\n }\n }\n\n getRecent(filter?: EventFilter, limit?: number): readonly SystemEvent[] {\n return this.ringBuffer.query(filter, limit)\n }\n}\n","import type { LogLevel, LogEntry, LogFilter, LogTags } from '@camstack/types'\n\nexport type { LogLevel, LogEntry, LogFilter }\n\n/**\n * Per-tag filter matcher with semantic-aware comparisons:\n *\n * `addonId` — matches the entry's bare addon id (strips any `@<workerId>`\n * qualifier added by the cap-router for remote providers).\n * So a UI filter for `audio-classifier` matches both the\n * addon's own log lines and bridge management lines whose\n * addonId is logged as `audio-classifier@dev-agent-0/audio-classifier`.\n *\n * `agentId` — matches when ANY of these hold:\n * * the entry was emitted by that agent (`agentId` exact)\n * * the entry's `nodeId` IS that agent (single-node case)\n * * the entry's `nodeId` starts with `<agent>/` (worker\n * inside that agent — e.g. `dev-agent-0/audio-classifier`)\n * Captures all the log emission paths for an addon hosted\n * on the agent regardless of who actually emitted the line.\n *\n * any other key — exact match (legacy semantics).\n *\n * Returns `true` when ALL filter keys match (AND), `false` otherwise.\n * `undefined` filter values are skipped.\n */\nexport function matchesLogTags(\n entryTags: LogTags | undefined,\n filterTags: Partial<LogTags>,\n): boolean {\n if (!entryTags) return false\n for (const [key, value] of Object.entries(filterTags)) {\n if (value === undefined) continue\n const entryValue = entryTags[key as keyof LogTags]\n if (key === 'addonId') {\n // Normalize away both suffix conventions so a filter on the\n // addon's manifest id matches every log line emitted by it:\n // - `<addonId>@<version>` — bridge-injected when relaying\n // logs from forked workers (kernel/capability-registry).\n // - `<addonId>::<sub-service>` — sub-component scope used by\n // addons that mount native-device-ops shims (e.g.\n // `audio-codec-nodeav::native-device-ops`). Operators\n // filtering by the addon's id expect to see those rows.\n let bare = entryValue\n if (typeof bare === 'string') {\n bare = bare.split('@')[0]\n if (typeof bare === 'string') {\n const colonIdx = bare.indexOf('::')\n if (colonIdx >= 0) bare = bare.slice(0, colonIdx)\n }\n }\n if (bare !== value) return false\n } else if (key === 'agentId') {\n const nodeId = entryTags['nodeId']\n const matchEmitter = entryValue === value\n const matchExactNode = nodeId === value\n const matchWorker = typeof nodeId === 'string' && nodeId.startsWith(`${value}/`)\n if (!matchEmitter && !matchExactNode && !matchWorker) return false\n } else {\n if (entryValue !== value) return false\n }\n }\n return true\n}\n\nexport class LogRingBuffer {\n private readonly buffer: Array<LogEntry | undefined>\n private head = 0\n private count = 0\n\n constructor(private readonly capacity: number = 10000) {\n this.buffer = Array.from<LogEntry | undefined>({ length: capacity })\n }\n\n push(entry: LogEntry): void {\n this.buffer[this.head] = entry\n this.head = (this.head + 1) % this.capacity\n if (this.count < this.capacity) {\n this.count++\n }\n }\n\n getAll(): LogEntry[] {\n const result: LogEntry[] = []\n\n for (let i = 0; i < this.count; i++) {\n const index = (this.head - 1 - i + this.capacity) % this.capacity\n result.push(this.buffer[index]!)\n }\n\n return result\n }\n\n query(filter: LogFilter): LogEntry[] {\n const all = this.getAll()\n let result = all\n\n if (filter.level) {\n result = result.filter((entry) => entry.level === filter.level)\n }\n\n if (filter.since) {\n result = result.filter((entry) => entry.timestamp >= filter.since!)\n }\n\n if (filter.until) {\n result = result.filter((entry) => entry.timestamp <= filter.until!)\n }\n\n if (filter.tags) {\n const filterTags = filter.tags\n result = result.filter((entry) => matchesLogTags(entry.tags, filterTags))\n }\n\n if (filter.limit !== undefined && filter.limit > 0) {\n result = result.slice(0, filter.limit)\n }\n\n return result\n }\n\n /**\n * Drop entries that match `filter`. Returns the number of entries\n * removed. Triggered by the UI's \"Clear logs\" button so the operator\n * can wipe the historical buffer for a specific scope (per-device,\n * per-addon, per-agent) — without it, closing and reopening the\n * panel re-populates the cleared rows from the server's ring buffer.\n *\n * Filter semantics mirror `query` (same level / since / until / tags\n * handling) — whatever you'd see listed by `query(filter)` is what\n * gets removed.\n */\n clear(filter: LogFilter = {}): number {\n if (this.count === 0) return 0\n const survivors: LogEntry[] = []\n for (let i = 0; i < this.count; i++) {\n // Same iteration order as getAll (newest first), but we'll\n // re-insert oldest-first to preserve push semantics.\n const index = (this.head - 1 - i + this.capacity) % this.capacity\n const entry = this.buffer[index]!\n let matches = true\n if (filter.level !== undefined && entry.level !== filter.level) matches = false\n if (matches && filter.since !== undefined && entry.timestamp < filter.since) matches = false\n if (matches && filter.until !== undefined && entry.timestamp > filter.until) matches = false\n if (matches && filter.tags !== undefined && !matchesLogTags(entry.tags, filter.tags)) matches = false\n if (!matches) survivors.push(entry)\n }\n const removed = this.count - survivors.length\n if (removed === 0) return 0\n // Re-seed the buffer in original push order (oldest first → newest last).\n this.buffer.fill(undefined)\n this.head = 0\n this.count = 0\n for (let i = survivors.length - 1; i >= 0; i--) {\n this.push(survivors[i]!)\n }\n return removed\n }\n}\n","import type { IScopedLogger, LogExtras, LogTags } from '@camstack/types'\nimport type { LogEntry, LogLevel } from './log-ring-buffer.js'\n\nexport type { IScopedLogger }\n\nexport class ScopedLogger implements IScopedLogger {\n constructor(\n private readonly scope: string | undefined,\n private readonly writeFn: (entry: LogEntry) => void,\n private readonly tags?: LogTags,\n ) {}\n\n debug(message: string, extras?: LogExtras): void {\n this.write('debug', message, extras)\n }\n\n info(message: string, extras?: LogExtras): void {\n this.write('info', message, extras)\n }\n\n warn(message: string, extras?: LogExtras): void {\n this.write('warn', message, extras)\n }\n\n error(message: string, extras?: LogExtras): void {\n this.write('error', message, extras)\n }\n\n child(childScope: string): IScopedLogger {\n return new ScopedLogger(childScope, this.writeFn, this.tags)\n }\n\n withTags(tags: LogTags): IScopedLogger {\n const merged = this.tags ? { ...this.tags, ...tags } : tags\n return new ScopedLogger(this.scope, this.writeFn, merged)\n }\n\n private write(level: LogLevel, message: string, extras?: LogExtras): void {\n const mergedTags = this.mergeTags(extras?.tags)\n const entry: LogEntry = {\n timestamp: new Date(),\n level,\n message,\n ...(this.scope !== undefined ? { scope: this.scope } : {}),\n ...(extras?.meta !== undefined ? { meta: extras.meta } : {}),\n ...(mergedTags ? { tags: mergedTags } : {}),\n }\n this.writeFn(entry)\n }\n\n private mergeTags(extraTags?: LogTags): LogTags | undefined {\n if (!this.tags && !extraTags) return undefined\n if (!this.tags) return extraTags\n if (!extraTags) return this.tags\n return { ...this.tags, ...extraTags }\n }\n}\n","import { LogRingBuffer, matchesLogTags, type LogEntry, type LogFilter } from './log-ring-buffer.js'\nimport { ScopedLogger, type IScopedLogger } from './scoped-logger.js'\n\nexport interface ILogDestination {\n initialize(): Promise<void>\n shutdown(): Promise<void>\n write(entry: LogEntry): void\n query?(filter: LogFilter): Promise<readonly LogEntry[]>\n}\n\nexport class LogManager {\n private readonly ringBuffer: LogRingBuffer\n private readonly destinations: ILogDestination[] = []\n private readonly subscribers = new Map<string, { filter: Partial<LogFilter>; callback: (entry: LogEntry) => void }>()\n private deviceNameLookup: ((deviceId: number) => string | null) | null = null\n\n constructor(bufferSize: number = 10000) {\n this.ringBuffer = new LogRingBuffer(bufferSize)\n }\n\n /**\n * Register a callback that resolves `deviceId → deviceName`. Called\n * for every emitted entry that carries `tags.deviceId` but no\n * explicit `tags.deviceName` — the LogManager injects the resolved\n * name directly into the entry's tags BEFORE ring-buffer / destination\n * write, so every destination (local console, file, remote forwarder,\n * addon-bundled copies of core) sees the enriched shape regardless of\n * which module instance the destination was built from.\n */\n setDeviceNameLookup(lookup: ((deviceId: number) => string | null) | null): void {\n this.deviceNameLookup = lookup\n }\n\n createLogger(scope?: string): IScopedLogger {\n return new ScopedLogger(scope, (entry: LogEntry) => {\n const enriched = this.enrichDeviceName(entry)\n this.ringBuffer.push(enriched)\n for (const dest of this.destinations) {\n dest.write(enriched)\n }\n // Notify real-time subscribers\n for (const [, sub] of this.subscribers) {\n if (this.matchesFilter(enriched, sub.filter)) {\n try { sub.callback(enriched) } catch { /* subscriber error — ignore */ }\n }\n }\n })\n }\n\n private enrichDeviceName(entry: LogEntry): LogEntry {\n if (!this.deviceNameLookup) return entry\n const tags = entry.tags\n if (!tags) return entry\n const deviceId = (tags as { deviceId?: unknown }).deviceId\n if (typeof deviceId !== 'number' || !Number.isFinite(deviceId)) return entry\n if (typeof (tags as { deviceName?: unknown }).deviceName === 'string') return entry\n const name = this.deviceNameLookup(deviceId)\n if (!name) return entry\n return { ...entry, tags: { ...tags, deviceName: name } }\n }\n\n /** Subscribe to live logs matching a filter. Returns an unsubscribe function. */\n subscribe(filter: Partial<LogFilter>, callback: (entry: LogEntry) => void): () => void {\n const id = Math.random().toString(36).slice(2)\n this.subscribers.set(id, { filter, callback })\n return () => { this.subscribers.delete(id) }\n }\n\n private matchesFilter(entry: LogEntry, filter: Partial<LogFilter>): boolean {\n if (filter.level) {\n const levels: string[] = ['debug', 'info', 'warn', 'error']\n const minIdx = levels.indexOf(filter.level)\n const entryIdx = levels.indexOf(entry.level)\n if (entryIdx < minIdx) return false\n }\n if (filter.tags) {\n if (!matchesLogTags(entry.tags, filter.tags)) return false\n }\n return true\n }\n\n /**\n * Register a log destination.\n *\n * @param opts.replay If true (default), replay every entry currently in\n * the ring buffer to the new destination before live\n * traffic starts. Lets a destination added mid-boot\n * still receive boot-time log entries.\n */\n addDestination(dest: ILogDestination, opts: { replay?: boolean } = {}): void {\n const replay = opts.replay ?? true\n this.destinations.push(dest)\n if (replay) {\n for (const entry of this.ringBuffer.query({})) {\n try { dest.write(entry) } catch { /* destination replay error — ignore */ }\n }\n }\n }\n\n removeDestination(dest: ILogDestination): void {\n const index = this.destinations.indexOf(dest)\n if (index !== -1) {\n this.destinations.splice(index, 1)\n }\n }\n\n query(filter: LogFilter): LogEntry[] {\n return this.ringBuffer.query(filter)\n }\n\n /**\n * Drop ring-buffer entries matching `filter`. Returns the count\n * removed. Backs the UI's \"Clear logs\" admin action so an operator\n * can wipe the historical window for a scope (per-device, per-addon,\n * agent-level) without restarting the server. External destinations\n * (file, forwarder) are NOT touched — only the in-memory ring.\n */\n clear(filter: LogFilter = {}): number {\n return this.ringBuffer.clear(filter)\n }\n}\n","import { existsSync, accessSync, constants } from 'node:fs'\nimport { join, resolve, dirname, isAbsolute } from 'node:path'\n\nexport interface IStorageBackend {\n /** Backend type identifier */\n readonly type: string\n /** Base path of this backend */\n readonly basePath: string\n /** Resolve a subpath to an absolute path */\n resolve(subpath: string): string\n /**\n * Check whether the backend is usable: either the base directory\n * already exists and is writable, OR we can create it on first\n * write (i.e. the nearest existing ancestor is writable).\n */\n isAvailable(): boolean\n /** No-op for lazy backends. Kept for API compatibility. */\n initialize(): Promise<void>\n}\n\n/**\n * Filesystem storage backend — lazy by design.\n *\n * `initialize()` does NOT create the base directory eagerly. Instead,\n * consumers that write via `FilesystemStorageProvider` (and other write\n * helpers in storage-manager.ts) run `fs.mkdir(dirname(filePath), { recursive: true })`\n * right before every `writeFile`, so the directory tree appears on demand.\n *\n * The previous behaviour eagerly mkdir'd every location declared in\n * `StorageLocationManager.initializeDefaults()` — six directories (`db`,\n * `media`, `recordings`, `models`, `cache`, `logs`) got created at boot\n * even if the installation had no cameras, no recording addon, no\n * analytics addon, etc. That meant every fresh install looked like it\n * was producing data when it had nothing to write. Laziness fixes that:\n * a directory only exists once an addon decides to put a file there.\n */\nexport class FsStorageBackend implements IStorageBackend {\n readonly type = 'local'\n readonly basePath: string\n\n constructor(basePath: string) {\n this.basePath = resolve(basePath)\n }\n\n resolve(subpath: string): string {\n if (isAbsolute(subpath)) return subpath\n return join(this.basePath, subpath)\n }\n\n isAvailable(): boolean {\n // If the base dir already exists, check write permission directly.\n // Otherwise walk up to the first existing ancestor (guaranteed to\n // terminate at the filesystem root) and check it is writable — we\n // can then mkdir the missing segments on first write.\n try {\n if (existsSync(this.basePath)) {\n accessSync(this.basePath, constants.W_OK)\n return true\n }\n let parent = dirname(this.basePath)\n while (parent && parent !== dirname(parent)) {\n if (existsSync(parent)) {\n accessSync(parent, constants.W_OK)\n return true\n }\n parent = dirname(parent)\n }\n return false\n } catch {\n return false\n }\n }\n\n async initialize(): Promise<void> {\n // No-op: base directory is created lazily on first write. See the\n // class docstring for the rationale.\n }\n}\n","import { join, isAbsolute } from 'node:path'\nimport { FsStorageBackend, type IStorageBackend } from './fs-storage-backend.js'\n\nexport type StorageLocationName = 'data' | 'media' | 'recordings' | 'models' | 'cache' | 'logs'\n\nexport class StorageLocationManager {\n private readonly backends: Map<StorageLocationName, IStorageBackend> = new Map()\n private readonly dataPath: string\n\n constructor(dataPath: string) {\n this.dataPath = dataPath\n }\n\n /** Initialize all locations with default paths */\n async initializeDefaults(): Promise<void> {\n const defaults: Record<StorageLocationName, string> = {\n data: join(this.dataPath, 'db'),\n media: join(this.dataPath, 'media'),\n recordings: join(this.dataPath, 'recordings'),\n models: join(this.dataPath, 'models'),\n cache: '/tmp/camstack-cache',\n logs: join(this.dataPath, 'logs'),\n }\n\n for (const [name, path] of Object.entries(defaults)) {\n const backend = new FsStorageBackend(path)\n await backend.initialize()\n this.backends.set(name as StorageLocationName, backend)\n }\n }\n\n /** Override a specific location's backend path */\n async setLocationPath(name: StorageLocationName, basePath: string): Promise<void> {\n const resolved = isAbsolute(basePath) ? basePath : join(this.dataPath, basePath)\n const backend = new FsStorageBackend(resolved)\n await backend.initialize()\n this.backends.set(name, backend)\n }\n\n /** Get the backend for a location */\n getBackend(name: StorageLocationName): IStorageBackend {\n const backend = this.backends.get(name)\n if (!backend) throw new Error(`Storage location \"${name}\" not initialized`)\n return backend\n }\n\n /** Resolve a path within a location */\n resolve(location: StorageLocationName, subpath: string): string {\n return this.getBackend(location).resolve(subpath)\n }\n\n /** Check if all locations are available */\n getStatus(): Array<{ name: StorageLocationName; available: boolean; path: string }> {\n return Array.from(this.backends.entries()).map(([name, backend]) => ({\n name,\n available: backend.isAvailable(),\n path: backend.basePath,\n }))\n }\n\n /** All location names */\n getLocationNames(): StorageLocationName[] {\n return Array.from(this.backends.keys())\n }\n}\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport { StorageLocationManager, type StorageLocationName } from './storage-location-manager.js'\nimport type {\n IStorageProvider as INewStorageProvider,\n ISettingsBackend,\n} from '@camstack/types'\n\n// Legacy interfaces — still used by consumers during migration\nexport interface IStorageProvider {\n initialize(): Promise<void>\n shutdown(): Promise<void>\n getLocation(name: StorageLocationName): IStorageLocation\n export?(locationName: StorageLocationName): Promise<Buffer>\n import?(locationName: StorageLocationName, data: Buffer): Promise<void>\n}\n\nexport interface QueryFilter {\n where?: Record<string, unknown>\n whereIn?: Record<string, unknown[]>\n whereBetween?: Record<string, [unknown, unknown]>\n orderBy?: { field: string; direction: 'asc' | 'desc' }\n limit?: number\n offset?: number\n}\n\nexport interface StorageRecord {\n collection: string\n id: string\n data: Record<string, unknown>\n}\n\nexport interface IStructuredStorage {\n query(collection: string, filter?: QueryFilter): Promise<readonly StorageRecord[]>\n insert(record: StorageRecord): Promise<StorageRecord>\n update(collection: string, id: string, data: Record<string, unknown>): Promise<StorageRecord>\n delete(collection: string, id: string): Promise<void>\n count(collection: string, filter?: QueryFilter): Promise<number>\n}\n\nexport interface IFileStorage {\n readFile(path: string): Promise<Buffer>\n writeFile(path: string, data: Buffer): Promise<void>\n deleteFile(path: string): Promise<void>\n listFiles(prefix?: string): Promise<readonly string[]>\n getFileUrl(path: string): Promise<string>\n exists(path: string): Promise<boolean>\n}\n\nexport interface IStorageLocation {\n structured?: IStructuredStorage\n files?: IFileStorage\n}\n\n/**\n * StorageManager — bridge between legacy code (getLocation/getLocationPath)\n * and the new capability-based storage system.\n *\n * Legacy consumers call getLocation('addon', namespace) to get structured + file storage.\n * This manager builds the response from:\n * - SettingsBackend (for structured queries) — provided by sqlite-settings addon\n * - LocationManager (for file paths) — set during Phase 2 boot\n */\nexport class StorageManager {\n private legacyProvider: IStorageProvider | null = null\n private locationManager: StorageLocationManager | null = null\n private newStorageProvider: INewStorageProvider | null = null\n private settingsBackend: ISettingsBackend | null = null\n\n /** @deprecated Set by legacy capability consumer — use setNewStorageProvider instead */\n setProvider(provider: IStorageProvider | INewStorageProvider): void {\n // Check if it's the new provider (has 'supportedLocations') or legacy (has 'getLocation')\n if ('getLocation' in provider) {\n this.legacyProvider = provider\n } else {\n this.newStorageProvider = provider\n }\n }\n\n setNewStorageProvider(provider: INewStorageProvider): void {\n this.newStorageProvider = provider\n }\n\n setSettingsBackend(backend: ISettingsBackend): void {\n this.settingsBackend = backend\n }\n\n getSettingsBackend(): ISettingsBackend {\n if (!this.settingsBackend) {\n throw new Error('SettingsBackend not initialized — storage addon not yet loaded')\n }\n return this.settingsBackend\n }\n\n getProvider(): IStorageProvider {\n if (this.legacyProvider) return this.legacyProvider\n if (!this.newStorageProvider && !this.settingsBackend && !this.locationManager) {\n throw new Error('No storage provider configured')\n }\n // Return a shim that wraps new providers\n return this.createLegacyShim()\n }\n\n setLocationManager(manager: StorageLocationManager): void {\n this.locationManager = manager\n }\n\n getLocationManager(): StorageLocationManager {\n if (!this.locationManager) {\n throw new Error('StorageLocationManager not initialized')\n }\n return this.locationManager\n }\n\n async initializeLocations(dataPath: string): Promise<void> {\n // Was previously a dynamic `await import(...)` for code-split, but the\n // module is also re-exported statically by core/src/index.ts so the\n // dynamic split never materialized (Rolldown reported it as\n // INEFFECTIVE_DYNAMIC_IMPORT). Switched to a top-of-file named\n // import — same shape, no chunk-graph confusion.\n const manager = new StorageLocationManager(dataPath)\n await manager.initializeDefaults()\n this.locationManager = manager\n }\n\n getLocationPath(name: StorageLocationName): string {\n return this.getLocationManager().getBackend(name).basePath\n }\n\n /**\n * Get a storage location with optional namespace scoping.\n * Builds IStorageLocation from settingsBackend (structured) + locationManager (files).\n */\n getLocation(name: StorageLocationName | string, namespace?: string): IStorageLocation {\n if (!this.legacyProvider && !this.newStorageProvider && !this.settingsBackend && !this.locationManager) {\n throw new Error('No storage provider configured')\n }\n // Try legacy provider first\n if (this.legacyProvider) {\n try {\n // Legacy alias → new location name mapping. `name` may be any string\n // coming from addon code; the final narrowing cast is the single\n // boundary between the public API (string) and the internal union.\n const LEGACY_MAP = { config: 'data', events: 'data', addon: 'data' } as const satisfies Record<string, StorageLocationName>\n const mapped = name in LEGACY_MAP ? LEGACY_MAP[name as keyof typeof LEGACY_MAP] : (name as StorageLocationName)\n const mappedName: StorageLocationName = mapped\n const location = this.legacyProvider.getLocation(mappedName)\n return namespace ? this.createNamespacedLocation(location, namespace) : location\n } catch {\n // Fall through to new approach\n }\n }\n\n // Build from new providers\n const location: IStorageLocation = {}\n\n // Structured storage from settingsBackend\n if (this.settingsBackend) {\n const backend = this.settingsBackend\n location.structured = {\n async query(collection: string, filter?: QueryFilter) {\n const results = await backend.query({ collection, filter })\n return results.map(r => ({ collection, id: r.id, data: r.data }))\n },\n async insert(record: StorageRecord) {\n const id = record.id || (await import('node:crypto')).randomUUID()\n await backend.insert({ collection: record.collection, record: { id, data: record.data } })\n return { ...record, id }\n },\n async update(collection: string, id: string, data: Record<string, unknown>) {\n await backend.update({ collection, id, data })\n return { collection, id, data }\n },\n async delete(collection: string, id: string) {\n await backend.delete({ collection, key: id })\n },\n async count(collection: string, filter?: QueryFilter) {\n return backend.count({ collection, filter })\n },\n }\n }\n\n // File storage from locationManager\n if (this.locationManager) {\n const LEGACY_MAP = { config: 'data', events: 'data', addon: 'data' } as const satisfies Record<string, StorageLocationName>\n const mappedName: StorageLocationName = name in LEGACY_MAP\n ? LEGACY_MAP[name as keyof typeof LEGACY_MAP]\n : (name as StorageLocationName)\n try {\n const basePath = this.locationManager.getBackend(mappedName).basePath\n location.files = {\n async readFile(p: string) { return fs.promises.readFile(path.join(basePath, p)) },\n async writeFile(p: string, data: Buffer) {\n const full = path.join(basePath, p)\n await fs.promises.mkdir(path.dirname(full), { recursive: true })\n await fs.promises.writeFile(full, data)\n },\n async deleteFile(p: string) { await fs.promises.rm(path.join(basePath, p), { force: true }) },\n async listFiles(prefix?: string) {\n const dir = prefix ? path.join(basePath, prefix) : basePath\n try { return (await fs.promises.readdir(dir)).map(f => prefix ? `${prefix}/${f}` : f) } catch { return [] }\n },\n async getFileUrl(p: string) { return path.join(basePath, p) },\n async exists(p: string) { try { await fs.promises.access(path.join(basePath, p)); return true } catch { return false } },\n }\n } catch {\n // Location not available\n }\n }\n\n return namespace ? this.createNamespacedLocation(location, namespace) : location\n }\n\n private createLegacyShim(): IStorageProvider {\n const self = this\n return {\n async initialize() {},\n async shutdown() {},\n getLocation(name: StorageLocationName) { return self.getLocation(name) },\n }\n }\n\n private createNamespacedLocation(location: IStorageLocation, namespace: string): IStorageLocation {\n const prefix = namespace.endsWith('/') ? namespace : `${namespace}/`\n\n return {\n structured: location.structured ? {\n async query(collection: string, filter?: QueryFilter) {\n return location.structured!.query(`${prefix}${collection}`, filter)\n },\n async insert(record: StorageRecord) {\n return location.structured!.insert({ ...record, collection: `${prefix}${record.collection}` })\n },\n async update(collection: string, id: string, data: Record<string, unknown>) {\n return location.structured!.update(`${prefix}${collection}`, id, data)\n },\n async delete(collection: string, id: string) {\n return location.structured!.delete(`${prefix}${collection}`, id)\n },\n async count(collection: string, filter?: QueryFilter) {\n return location.structured!.count(`${prefix}${collection}`, filter)\n },\n } : undefined,\n\n files: location.files ? {\n async readFile(p: string) { return location.files!.readFile(`${prefix}${p}`) },\n async writeFile(p: string, data: Buffer) { return location.files!.writeFile(`${prefix}${p}`, data) },\n async deleteFile(p: string) { return location.files!.deleteFile(`${prefix}${p}`) },\n async listFiles(filePrefix?: string) { return location.files!.listFiles(`${prefix}${filePrefix ?? ''}`) },\n async getFileUrl(p: string) { return location.files!.getFileUrl(`${prefix}${p}`) },\n async exists(p: string) { return location.files!.exists(`${prefix}${p}`) },\n } : undefined,\n }\n }\n}\n","import type { TokenScope, MethodAccess } from '@camstack/types'\n\n/**\n * True if the scope set grants `access` on device-scoped capabilities.\n * A `category:device` grant covers every device cap (the broad grant).\n * Mirrors the OR-semantics of the existing token scope matcher.\n */\nexport function scopesAllowDeviceCap(scopes: readonly TokenScope[], access: MethodAccess): boolean {\n return scopes.some(\n (s) => s.type === 'category' && s.target === 'device' && s.access.includes(access),\n )\n}\n","import type { INotificationOutput, Notification, ICapabilityRegistry } from '@camstack/types'\nimport type { IScopedLogger } from '../logging/scoped-logger.js'\nimport { errMsg } from '@camstack/types'\n\n/**\n * Central notification service that routes notifications to configured outputs.\n * Framework-agnostic — dependencies injected via constructor.\n *\n * Outputs are resolved from the ICapabilityRegistry's 'notification-output'\n * collection on each call (proxy pattern). Falls back to a local map\n * when no registry is provided (backward compat).\n */\nexport class NotificationService {\n private readonly localOutputs = new Map<string, INotificationOutput>()\n private readonly routing = new Map<string, string[]>()\n private readonly rateLimits = new Map<string, number>()\n private readonly lastSent = new Map<string, number>()\n private registry: ICapabilityRegistry | null = null\n\n constructor(private readonly logger: IScopedLogger) {}\n\n /** Set the registry for live output lookup. Called once during boot. */\n setRegistry(registry: ICapabilityRegistry): void {\n this.registry = registry\n }\n\n /** Resolve all outputs — prefers registry, falls back to local map */\n private get outputs(): ReadonlyMap<string, INotificationOutput> {\n if (this.registry) {\n const collection = this.registry.getCollection<INotificationOutput>('notification-output')\n const map = new Map<string, INotificationOutput>()\n for (const output of collection) {\n map.set(output.id, output)\n }\n return map\n }\n return this.localOutputs\n }\n\n /** Register an output in the local fallback map (used when no registry is set). */\n registerLocalOutput(output: INotificationOutput): void {\n this.localOutputs.set(output.id, output)\n this.logger.info('Notification output added', { meta: { name: output.name, outputId: output.id } })\n }\n\n /** Remove an output from the local fallback map. */\n unregisterLocalOutput(id: string): void {\n this.localOutputs.delete(id)\n this.logger.info('Notification output removed', { meta: { outputId: id } })\n }\n\n setRouting(category: string, outputIds: string[]): void {\n this.routing.set(category, [...outputIds])\n }\n\n setRateLimit(category: string, minIntervalMs: number): void {\n this.rateLimits.set(category, minIntervalMs)\n }\n\n async notify(notification: Notification): Promise<void> {\n const { category, deviceId } = notification\n\n // Rate limit check\n const rateLimitKey = deviceId ? `${category}:${deviceId}` : category\n const minInterval = this.rateLimits.get(category) ?? 0\n if (minInterval > 0) {\n const last = this.lastSent.get(rateLimitKey) ?? 0\n if (notification.timestamp - last < minInterval) {\n this.logger.debug('Rate limited', { meta: { rateLimitKey } })\n return\n }\n }\n\n // Determine target outputs\n const targetIds = this.routing.get(category) ?? this.routing.get('*') ?? []\n if (targetIds.length === 0) {\n this.logger.debug('No routing configured for category', { meta: { category } })\n return\n }\n\n const currentOutputs = this.outputs\n\n // Update last-sent timestamp\n this.lastSent.set(rateLimitKey, notification.timestamp)\n\n // Send to all targets in parallel with error isolation\n await Promise.allSettled(\n targetIds\n .map((id) => currentOutputs.get(id))\n .filter((output): output is INotificationOutput => output !== undefined)\n .map(async (output) => {\n try {\n await output.send(notification)\n } catch (err) {\n const msg = errMsg(err)\n this.logger.error('Notification output failed', { meta: { outputId: output.id, error: msg } })\n }\n }),\n )\n\n return undefined\n }\n\n getOutputs(): ReadonlyArray<{ id: string; name: string; icon: string }> {\n return Array.from(this.outputs.values()).map(({ id, name, icon }) => ({ id, name, icon }))\n }\n\n getRouting(): ReadonlyMap<string, string[]> {\n return this.routing\n }\n\n getOutput(id: string): INotificationOutput | undefined {\n return this.outputs.get(id)\n }\n}\n","import type { Toast } from '@camstack/types'\n\nexport type Unsubscribe = () => void\n\ninterface ListenerEntry {\n readonly userId: string\n readonly callback: (toast: Toast) => void\n}\n\n/**\n * Service for broadcasting toast notifications to connected UI clients.\n * Framework-agnostic — integrates with tRPC subscriptions via subscribe().\n */\nexport class ToastService {\n private readonly listeners = new Map<string, ListenerEntry>()\n\n /**\n * Subscribe to toast events for a specific user.\n * Returns an unsubscribe function.\n */\n subscribe(connectionId: string, userId: string, callback: (toast: Toast) => void): Unsubscribe {\n this.listeners.set(connectionId, { userId, callback })\n return () => {\n this.listeners.delete(connectionId)\n }\n }\n\n /**\n * Broadcast a toast to all connected clients.\n */\n broadcast(toast: Toast): void {\n for (const entry of this.listeners.values()) {\n entry.callback(toast)\n }\n }\n\n /**\n * Send a toast to a specific user's connections only.\n */\n sendToUser(userId: string, toast: Toast): void {\n for (const entry of this.listeners.values()) {\n if (entry.userId === userId) {\n entry.callback(toast)\n }\n }\n }\n}\n","import type { IAddonHttpRoute, IAddonRouteProvider } from '@camstack/types'\n\ninterface RouteMatch {\n readonly route: IAddonHttpRoute\n readonly addonId: string\n readonly params: Record<string, string>\n}\n\ninterface RegisteredRoute {\n readonly addonId: string\n readonly route: IAddonHttpRoute\n /** Full path including /addon/{addonId}/ prefix */\n readonly fullPath: string\n}\n\n/**\n * Registry for dynamic HTTP routes registered by addons.\n * Framework-agnostic — the server HTTP layer queries this registry to dispatch requests.\n */\nexport class AddonRouteRegistry {\n private readonly routes = new Map<string, RegisteredRoute[]>()\n\n /**\n * Register all routes from an addon's route provider.\n */\n registerRoutes(addonId: string, provider: IAddonRouteProvider): void {\n const addonRoutes = provider.getRoutes()\n const registered: RegisteredRoute[] = addonRoutes.map((route) => {\n const normalizedPath = route.path.startsWith('/') ? route.path : `/${route.path}`\n return {\n addonId,\n route,\n fullPath: `/addon/${addonId}${normalizedPath}`,\n }\n })\n this.routes.set(addonId, registered)\n }\n\n /**\n * Unregister all routes for an addon.\n */\n unregisterRoutes(addonId: string): void {\n this.routes.delete(addonId)\n }\n\n /**\n * Match an incoming request method + path to a registered route.\n * Supports simple path parameters (e.g., /items/:id).\n */\n matchRoute(method: string, path: string): RouteMatch | null {\n const normalizedMethod = method.toUpperCase()\n\n for (const registeredRoutes of this.routes.values()) {\n for (const entry of registeredRoutes) {\n if (entry.route.method !== normalizedMethod) continue\n\n const params = matchPath(entry.fullPath, path)\n if (params !== null) {\n return {\n route: entry.route,\n addonId: entry.addonId,\n params,\n }\n }\n }\n }\n\n return null\n }\n\n /**\n * List all registered routes across all addons.\n */\n listRoutes(): ReadonlyArray<{ addonId: string; method: string; path: string; access: string; description?: string }> {\n const result: Array<{ addonId: string; method: string; path: string; access: string; description?: string }> = []\n for (const registeredRoutes of this.routes.values()) {\n for (const entry of registeredRoutes) {\n result.push({\n addonId: entry.addonId,\n method: entry.route.method,\n path: entry.fullPath,\n access: entry.route.access,\n description: entry.route.description,\n })\n }\n }\n return result\n }\n}\n\n/**\n * Match a route pattern against an actual path.\n * Supports :param segments (e.g., /addon/:addonId/items/:id).\n * Returns extracted params or null if no match.\n */\nfunction matchPath(pattern: string, path: string): Record<string, string> | null {\n const patternParts = pattern.split('/').filter(Boolean)\n const pathParts = path.split('/').filter(Boolean)\n\n if (patternParts.length !== pathParts.length) {\n return null\n }\n\n const params: Record<string, string> = {}\n\n for (let i = 0; i < patternParts.length; i++) {\n const patternPart = patternParts[i]!\n const pathPart = pathParts[i]!\n\n if (patternPart.startsWith(':')) {\n params[patternPart.slice(1)] = pathPart\n } else if (patternPart !== pathPart) {\n return null\n }\n }\n\n return params\n}\n","import { X509Certificate } from 'node:crypto'\nimport { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport { existsSync, mkdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport * as os from 'node:os'\n\nconst execFileAsync = promisify(execFile)\n\nexport interface TlsCertPair {\n readonly cert: Buffer\n readonly key: Buffer\n}\n\nexport interface EnsureTlsResult {\n readonly certPath: string\n readonly keyPath: string\n readonly generated: boolean\n}\n\nexport interface CertOptions {\n /** Common Name for the cert (default: 'camstack.local') */\n readonly commonName?: string\n /** Validity in days (default: 825 — max for browsers) */\n readonly validDays?: number\n /** Additional SANs (DNS names or IPs) */\n readonly extraSans?: readonly string[]\n}\n\n/**\n * Ensure a self-signed TLS certificate exists in the given directory.\n * Generates one if missing. Returns paths to cert and key files.\n */\nexport async function ensureTlsCert(\n dataDir: string,\n options?: CertOptions,\n): Promise<EnsureTlsResult> {\n const tlsDir = join(dataDir, 'tls')\n const certPath = join(tlsDir, 'camstack.crt')\n const keyPath = join(tlsDir, 'camstack.key')\n\n // Already exists — reuse\n if (existsSync(certPath) && existsSync(keyPath)) {\n try {\n const certPem = readFileSync(certPath)\n const x509 = new X509Certificate(certPem)\n const validTo = new Date(x509.validTo)\n if (validTo > new Date()) {\n return { certPath, keyPath, generated: false }\n }\n // Expired — regenerate below\n } catch {\n // Corrupted — regenerate below\n }\n }\n\n mkdirSync(tlsDir, { recursive: true })\n\n const cn = options?.commonName ?? 'camstack.local'\n const validDays = options?.validDays ?? 825\n\n // Collect SANs: localhost, 127.0.0.1, all local IPs, hostname\n const sanDns = new Set<string>(['localhost', cn, os.hostname()])\n const sanIps = new Set<string>(['127.0.0.1', '::1'])\n\n // Add all local network IPs\n const interfaces = os.networkInterfaces()\n for (const addrs of Object.values(interfaces)) {\n if (!addrs) continue\n for (const addr of addrs) {\n if (!addr.internal) {\n sanIps.add(addr.address)\n }\n }\n }\n\n // Add extra SANs\n for (const san of options?.extraSans ?? []) {\n if (san.match(/^\\d+\\.\\d+\\.\\d+\\.\\d+$/) || san.includes(':')) {\n sanIps.add(san)\n } else {\n sanDns.add(san)\n }\n }\n\n // Build SAN string for openssl\n const sanParts: string[] = []\n for (const dns of sanDns) {\n sanParts.push(`DNS:${dns}`)\n }\n for (const ip of sanIps) {\n sanParts.push(`IP:${ip}`)\n }\n const sanString = sanParts.join(',')\n\n // Generate self-signed certificate using openssl CLI\n await execFileAsync('openssl', [\n 'req', '-x509',\n '-newkey', 'rsa:2048',\n '-keyout', keyPath,\n '-out', certPath,\n '-days', String(validDays),\n '-nodes',\n '-subj', `/CN=${cn}`,\n '-addext', `subjectAltName=${sanString}`,\n ])\n\n // Set restrictive permissions on the key file\n const { chmod } = await import('node:fs/promises')\n await chmod(keyPath, 0o600)\n\n return { certPath, keyPath, generated: true }\n}\n\n/**\n * Load TLS cert+key from files. Returns Buffers suitable for Node.js TLS options.\n */\nexport function loadTlsCert(certPath: string, keyPath: string): TlsCertPair {\n return {\n cert: readFileSync(certPath),\n key: readFileSync(keyPath),\n }\n}\n","/**\n * Factory for creating tRPC clients for addons.\n *\n * In-process only: `createDirectCaller()` uses tRPC's `createCallerFactory`\n * to call procedures directly (zero network overhead) and wraps the raw\n * caller in a proxy so it matches `CreateTRPCClient<AppRouter>` shape —\n * addons use `context.api.namespace.method.query(input)` identically to\n * the cross-process path.\n *\n * Cross-process calls (forked workers, remote agents) ride the Moleculer\n * broker via `brokerTransportLink` in the kernel — not this factory.\n */\n\nexport interface DirectCallerOptions {\n /** The tRPC router instance (from buildAppRouter) */\n readonly router: unknown\n /** Context for the caller (user identity, etc.) */\n readonly context: { readonly user: { readonly id: string; readonly username: string; readonly role: string } }\n}\n\n/**\n * Wrap a raw tRPC caller (from `createCallerFactory`) in a proxy that\n * exposes each leaf procedure as `{ query, mutate, subscribe }`, matching\n * the shape of `CreateTRPCClient<AppRouter>`.\n *\n * The tricky part: tRPC v11 callers expose nested routers as callable\n * no-op functions (e.g. `caller.greet` is `typeof === 'function'`), so\n * we can't use `typeof` to tell namespace from leaf. Instead, we return\n * a unified proxy that handles BOTH behaviours:\n *\n * - Accessing `.query` / `.mutate` treats the current node as a leaf\n * procedure and invokes `caller(input)` when called.\n * - Accessing `.subscribe` throws (not supported on direct caller).\n * - Accessing any other property descends into `caller[prop]` and\n * returns a nested proxy.\n */\nfunction wrapCallerAsClient<T>(caller: unknown): T {\n return new Proxy(Object.create(null) as Record<string, unknown>, {\n get(_target, prop) {\n if (typeof prop !== 'string') return undefined\n\n if (prop === 'query' || prop === 'mutate') {\n // Leaf-mode: the current `caller` is expected to be a procedure\n // function. The tRPC caller accepts the raw input as its first\n // argument and returns `Promise<output>`.\n if (typeof caller !== 'function') {\n throw new Error(\n `Cannot call .${prop}() — this tRPC node is not a procedure`,\n )\n }\n const fn = caller as (input?: unknown) => Promise<unknown>\n return (input?: unknown) => fn(input)\n }\n\n if (prop === 'subscribe') {\n return () => {\n throw new Error(\n `subscribe() is not supported on direct caller — use the WSS client for subscriptions`,\n )\n }\n }\n\n // Namespace descent — keep walking the caller tree.\n const child = (caller as Record<string, unknown> | null | undefined)?.[prop]\n if (child === undefined || child === null) return undefined\n return wrapCallerAsClient<unknown>(child)\n },\n }) as T\n}\n\nexport class AddonApiFactory {\n /**\n * Create a direct caller -- calls tRPC procedures directly in-process.\n * Zero network overhead. Used for in-process addons and dev mode.\n *\n * Returns `AddonApi` — the same tRPC client surface that broker-routed\n * callers get. Callers treat it uniformly as `context.api` regardless\n * of the underlying transport.\n */\n async createDirectCaller(options: DirectCallerOptions): Promise<import('@camstack/types').AddonApi> {\n const { initTRPC } = await import('@trpc/server')\n const t = initTRPC.create()\n type RouterLike = Parameters<typeof t.createCallerFactory>[0]\n const callerFactory = t.createCallerFactory(options.router as RouterLike)\n type CallerContext = Parameters<ReturnType<typeof t.createCallerFactory>>[0]\n const caller = callerFactory(options.context as CallerContext)\n return wrapCallerAsClient<import('@camstack/types').AddonApi>(caller)\n }\n}\n","import type {\n Integration, PersistedDevice,\n CreateIntegrationInput, CreateDeviceInput,\n IIntegrationRegistry,\n ISettingsBackend,\n TableSchema,\n} from '@camstack/types'\nimport { parseJsonObject } from '@camstack/types'\n\nfunction serializeSetting(value: unknown): { value: string; valueType: string } {\n if (typeof value === 'number') return { value: String(value), valueType: 'number' }\n if (typeof value === 'boolean') return { value: String(value), valueType: 'boolean' }\n if (typeof value === 'string') return { value, valueType: 'string' }\n return { value: JSON.stringify(value), valueType: 'json' }\n}\n\nfunction deserializeSetting(value: string, valueType: string): unknown {\n switch (valueType) {\n case 'number': return Number(value)\n case 'boolean': return value === 'true'\n case 'json': try { return JSON.parse(value) } catch { return value }\n default: return value\n }\n}\n\nlet integrationCounter = 0\nlet deviceCounter = 0\n\nfunction nextIntegrationId(): string {\n return `int_${String(++integrationCounter).padStart(4, '0')}`\n}\n\nfunction nextDeviceId(): string {\n return `dev_${String(++deviceCounter).padStart(4, '0')}`\n}\n\nconst INTEGRATIONS_SCHEMA: TableSchema = {\n columns: [\n { name: 'id', type: 'TEXT', primaryKey: true },\n { name: 'addon_id', type: 'TEXT', notNull: true },\n { name: 'name', type: 'TEXT', notNull: true },\n { name: 'enabled', type: 'INTEGER', notNull: true, defaultValue: 1 },\n { name: 'info', type: 'TEXT', notNull: true, defaultValue: '{}' },\n { name: 'created_at', type: 'INTEGER', notNull: true },\n { name: 'updated_at', type: 'INTEGER', notNull: true },\n ],\n indexes: [\n { name: 'idx_integrations_addon', columns: ['addon_id'] },\n ],\n}\n\nconst INTEGRATION_SETTINGS_SCHEMA: TableSchema = {\n columns: [\n { name: 'integration_id', type: 'TEXT', notNull: true },\n { name: 'key', type: 'TEXT', notNull: true },\n { name: 'value', type: 'TEXT', notNull: true },\n { name: 'value_type', type: 'TEXT', notNull: true, defaultValue: 'string' },\n ],\n}\n\nconst DEVICES_SCHEMA: TableSchema = {\n columns: [\n { name: 'id', type: 'TEXT', primaryKey: true },\n { name: 'integration_id', type: 'TEXT', notNull: true },\n { name: 'stable_id', type: 'TEXT', notNull: true, unique: true },\n { name: 'type', type: 'TEXT', notNull: true, defaultValue: 'camera' },\n { name: 'name', type: 'TEXT', notNull: true },\n { name: 'enabled', type: 'INTEGER', notNull: true, defaultValue: 1 },\n { name: 'info', type: 'TEXT', notNull: true, defaultValue: '{}' },\n { name: 'created_at', type: 'INTEGER', notNull: true },\n { name: 'updated_at', type: 'INTEGER', notNull: true },\n ],\n indexes: [\n { name: 'idx_devices_integration', columns: ['integration_id'] },\n { name: 'idx_devices_stable', columns: ['stable_id'], unique: true },\n { name: 'idx_devices_type', columns: ['type'] },\n ],\n}\n\nconst DEVICE_SETTINGS_SCHEMA: TableSchema = {\n columns: [\n { name: 'device_id', type: 'TEXT', notNull: true },\n { name: 'key', type: 'TEXT', notNull: true },\n { name: 'value', type: 'TEXT', notNull: true },\n { name: 'value_type', type: 'TEXT', notNull: true, defaultValue: 'string' },\n ],\n}\n\nexport class IntegrationRegistry implements IIntegrationRegistry {\n private readonly backend: ISettingsBackend\n\n constructor(backend: ISettingsBackend) {\n this.backend = backend\n }\n\n async initialize(): Promise<void> {\n await this.backend.ensureTable?.('integrations', INTEGRATIONS_SCHEMA)\n await this.backend.ensureTable?.('integration_settings', INTEGRATION_SETTINGS_SCHEMA)\n await this.backend.ensureTable?.('devices', DEVICES_SCHEMA)\n await this.backend.ensureTable?.('device_settings_kv', DEVICE_SETTINGS_SCHEMA)\n\n // Resume counters from max existing IDs\n const ints = await this.backend.tableQuery?.('integrations', { orderBy: { field: 'id', direction: 'desc' }, limit: 1 }) ?? []\n if (ints[0]) {\n const num = parseInt(String(ints[0]['id']).replace('int_', ''), 10)\n if (!isNaN(num)) integrationCounter = num\n }\n const devs = await this.backend.tableQuery?.('devices', { orderBy: { field: 'id', direction: 'desc' }, limit: 1 }) ?? []\n if (devs[0]) {\n const num = parseInt(String(devs[0]['id']).replace('dev_', ''), 10)\n if (!isNaN(num)) deviceCounter = num\n }\n }\n\n // --- Integrations ---\n\n async createIntegration(input: CreateIntegrationInput): Promise<Integration> {\n const id = nextIntegrationId()\n const now = Math.floor(Date.now() / 1000)\n\n await this.backend.tableInsert?.('integrations', {\n id,\n addon_id: input.addonId,\n name: input.name,\n enabled: input.enabled !== false ? 1 : 0,\n info: JSON.stringify(input.info ?? {}),\n created_at: now,\n updated_at: now,\n })\n\n if (input.settings) {\n await this.setIntegrationSettings(id, input.settings)\n }\n\n return {\n id,\n addonId: input.addonId,\n name: input.name,\n enabled: input.enabled !== false,\n info: input.info ?? {},\n createdAt: now,\n updatedAt: now,\n }\n }\n\n async getIntegration(id: string): Promise<Integration | null> {\n const row = await this.backend.tableGet?.('integrations', { id })\n return row ? this.mapIntegration(row) : null\n }\n\n async getIntegrationByAddonId(addonId: string): Promise<Integration | null> {\n const row = await this.backend.tableGet?.('integrations', { addon_id: addonId })\n return row ? this.mapIntegration(row) : null\n }\n\n async listIntegrations(): Promise<readonly Integration[]> {\n const rows = await this.backend.tableQuery?.('integrations', { orderBy: { field: 'created_at', direction: 'asc' } }) ?? []\n return rows.map(r => this.mapIntegration(r))\n }\n\n async updateIntegration(id: string, updates: Partial<Pick<Integration, 'name' | 'enabled' | 'info'>>): Promise<Integration | null> {\n const updateRow: Record<string, unknown> = { updated_at: Math.floor(Date.now() / 1000) }\n if (updates.name !== undefined) updateRow['name'] = updates.name\n if (updates.enabled !== undefined) updateRow['enabled'] = updates.enabled ? 1 : 0\n if (updates.info !== undefined) updateRow['info'] = JSON.stringify(updates.info)\n\n await this.backend.tableUpdate?.('integrations', { id }, updateRow)\n return this.getIntegration(id)\n }\n\n async deleteIntegration(id: string): Promise<boolean> {\n const devices = await this.listDevices(id)\n for (const d of devices) {\n await this.backend.tableDelete?.('device_settings_kv', { device_id: d.id })\n }\n await this.backend.tableDelete?.('devices', { integration_id: id })\n await this.backend.tableDelete?.('integration_settings', { integration_id: id })\n await this.backend.tableDelete?.('integrations', { id })\n return true\n }\n\n // --- Integration Settings ---\n\n async getIntegrationSettings(integrationId: string): Promise<Record<string, unknown>> {\n const result: Record<string, unknown> = {}\n const rows = await this.backend.tableQuery?.('integration_settings', { where: { integration_id: integrationId } }) ?? []\n for (const row of rows) {\n result[String(row['key'])] = deserializeSetting(String(row['value']), String(row['value_type']))\n }\n return result\n }\n\n async setIntegrationSetting(integrationId: string, key: string, value: unknown): Promise<void> {\n const s = serializeSetting(value)\n await this.backend.tableDelete?.('integration_settings', { integration_id: integrationId, key })\n await this.backend.tableInsert?.('integration_settings', {\n integration_id: integrationId,\n key,\n value: s.value,\n value_type: s.valueType,\n })\n }\n\n async setIntegrationSettings(integrationId: string, settings: Record<string, unknown>): Promise<void> {\n for (const [key, value] of Object.entries(settings)) {\n await this.setIntegrationSetting(integrationId, key, value)\n }\n }\n\n // --- Devices ---\n\n async createDevice(input: CreateDeviceInput): Promise<PersistedDevice> {\n const id = nextDeviceId()\n const now = Math.floor(Date.now() / 1000)\n\n await this.backend.tableInsert?.('devices', {\n id,\n integration_id: input.integrationId,\n stable_id: input.stableId,\n type: input.type,\n name: input.name,\n enabled: input.enabled !== false ? 1 : 0,\n info: JSON.stringify(input.info ?? {}),\n created_at: now,\n updated_at: now,\n })\n\n if (input.settings) {\n await this.setDeviceSettings(id, input.settings)\n }\n\n return {\n id,\n integrationId: input.integrationId,\n stableId: input.stableId,\n type: input.type,\n name: input.name,\n enabled: input.enabled !== false,\n info: input.info ?? {},\n createdAt: now,\n updatedAt: now,\n }\n }\n\n async getDevice(id: string): Promise<PersistedDevice | null> {\n const row = await this.backend.tableGet?.('devices', { id })\n return row ? this.mapDevice(row) : null\n }\n\n async getDeviceByStableId(stableId: string): Promise<PersistedDevice | null> {\n const row = await this.backend.tableGet?.('devices', { stable_id: stableId })\n return row ? this.mapDevice(row) : null\n }\n\n async listDevices(integrationId?: string): Promise<readonly PersistedDevice[]> {\n const options = integrationId\n ? { where: { integration_id: integrationId }, orderBy: { field: 'created_at' as const, direction: 'asc' as const } }\n : { orderBy: { field: 'created_at' as const, direction: 'asc' as const } }\n const rows = await this.backend.tableQuery?.('devices', options) ?? []\n return rows.map(r => this.mapDevice(r))\n }\n\n async listCameras(): Promise<readonly PersistedDevice[]> {\n const rows = await this.backend.tableQuery?.('devices', { where: { type: 'camera' }, orderBy: { field: 'created_at', direction: 'asc' } }) ?? []\n return rows.map(r => this.mapDevice(r))\n }\n\n async updateDevice(id: string, updates: Partial<Pick<PersistedDevice, 'name' | 'enabled' | 'info'>>): Promise<PersistedDevice | null> {\n const updateRow: Record<string, unknown> = { updated_at: Math.floor(Date.now() / 1000) }\n if (updates.name !== undefined) updateRow['name'] = updates.name\n if (updates.enabled !== undefined) updateRow['enabled'] = updates.enabled ? 1 : 0\n if (updates.info !== undefined) updateRow['info'] = JSON.stringify(updates.info)\n\n await this.backend.tableUpdate?.('devices', { id }, updateRow)\n return this.getDevice(id)\n }\n\n async deleteDevice(id: string): Promise<boolean> {\n await this.backend.tableDelete?.('device_settings_kv', { device_id: id })\n await this.backend.tableDelete?.('devices', { id })\n return true\n }\n\n // --- Device Settings ---\n\n async getDeviceSettings(deviceId: string): Promise<Record<string, unknown>> {\n const result: Record<string, unknown> = {}\n const rows = await this.backend.tableQuery?.('device_settings_kv', { where: { device_id: deviceId } }) ?? []\n for (const row of rows) {\n result[String(row['key'])] = deserializeSetting(String(row['value']), String(row['value_type']))\n }\n return result\n }\n\n async setDeviceSetting(deviceId: string, key: string, value: unknown): Promise<void> {\n const s = serializeSetting(value)\n await this.backend.tableDelete?.('device_settings_kv', { device_id: deviceId, key })\n await this.backend.tableInsert?.('device_settings_kv', {\n device_id: deviceId,\n key,\n value: s.value,\n value_type: s.valueType,\n })\n }\n\n async setDeviceSettings(deviceId: string, settings: Record<string, unknown>): Promise<void> {\n for (const [key, value] of Object.entries(settings)) {\n await this.setDeviceSetting(deviceId, key, value)\n }\n }\n\n // --- Mappers ---\n\n private mapIntegration(row: Record<string, unknown>): Integration {\n return {\n id: String(row['id']),\n addonId: String(row['addon_id']),\n name: String(row['name']),\n enabled: row['enabled'] === 1,\n info: typeof row['info'] === 'string' ? (parseJsonObject(row['info']) ?? {}) : {},\n createdAt: Number(row['created_at']),\n updatedAt: Number(row['updated_at']),\n }\n }\n\n private mapDevice(row: Record<string, unknown>): PersistedDevice {\n return {\n id: String(row['id']),\n integrationId: String(row['integration_id']),\n stableId: String(row['stable_id']),\n type: String(row['type']),\n name: String(row['name']),\n enabled: row['enabled'] === 1,\n info: typeof row['info'] === 'string' ? (parseJsonObject(row['info']) ?? {}) : {},\n createdAt: Number(row['created_at']),\n updatedAt: Number(row['updated_at']),\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,IAAM,gBAAgB;CAAC;CAAQ;CAAU;CAAY;CAAU;CAAK;AA+BzC,OAAO,YAAY;CA7B5C;EAAE,IAAI;EAAY,OAAO;EAAY,MAAM;EAAoB,OAAO;EAAK;CAC3E;EAAE,IAAI;EAAW,OAAO;EAAW,MAAM;EAAY,OAAO;EAAG;CAC/D;EAAE,IAAI;EAAS,OAAO;EAAS,MAAM;EAAS,OAAO;EAAG;CACxD;EAAE,IAAI;EAAS,OAAO;EAAS,MAAM;EAAa,OAAO;EAAG;CAC5D;EAAE,IAAI;EAAU,OAAO;EAAU,MAAM;EAAY,OAAO;EAAI;CAC9D;EAAE,IAAI;EAAS,OAAO;EAAS,MAAM;EAAO,OAAO;EAAI;CACvD;EAAE,IAAI;EAAU,OAAO;EAAU,MAAM;EAAa,OAAO;EAAI;CAC/D;EAAE,IAAI;EAAY,OAAO;EAAY,MAAM;EAAU,OAAO;EAAI;CAChE;EAAE,IAAI;EAAO,OAAO;EAAO,MAAM;EAAQ,OAAO;EAAI;CACpD;EAAE,IAAI;EAAiB,OAAO;EAAiB,MAAM;EAAS,OAAO;EAAI;CAC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