@camstack/addon-advanced-notifier 0.1.32 → 0.1.33

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/addon.mjs CHANGED
@@ -1273,10 +1273,10 @@ const $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
1273
1273
  return;
1274
1274
  }
1275
1275
  }
1276
- const url = new URL(trimmed);
1276
+ const url2 = new URL(trimmed);
1277
1277
  if (def.hostname) {
1278
1278
  def.hostname.lastIndex = 0;
1279
- if (!def.hostname.test(url.hostname)) {
1279
+ if (!def.hostname.test(url2.hostname)) {
1280
1280
  payload.issues.push({
1281
1281
  code: "invalid_format",
1282
1282
  format: "url",
@@ -1290,7 +1290,7 @@ const $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
1290
1290
  }
1291
1291
  if (def.protocol) {
1292
1292
  def.protocol.lastIndex = 0;
1293
- if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) {
1293
+ if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) {
1294
1294
  payload.issues.push({
1295
1295
  code: "invalid_format",
1296
1296
  format: "url",
@@ -1303,7 +1303,7 @@ const $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
1303
1303
  }
1304
1304
  }
1305
1305
  if (def.normalize) {
1306
- payload.value = url.href;
1306
+ payload.value = url2.href;
1307
1307
  } else {
1308
1308
  payload.value = trimmed;
1309
1309
  }
@@ -4427,6 +4427,9 @@ const ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
4427
4427
  $ZodURL.init(inst, def);
4428
4428
  ZodStringFormat.init(inst, def);
4429
4429
  });
4430
+ function url(params) {
4431
+ return /* @__PURE__ */ _url(ZodURL, params);
4432
+ }
4430
4433
  const ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
4431
4434
  $ZodEmoji.init(inst, def);
4432
4435
  ZodStringFormat.init(inst, def);
@@ -5110,6 +5113,7 @@ const WELL_KNOWN_TABS = [
5110
5113
  { id: "stream-broker", label: "Stream Broker", icon: "radio", order: 20 },
5111
5114
  { id: "streaming", label: "Streaming", icon: "video", order: 35 },
5112
5115
  { id: "ptz", label: "PTZ", icon: "move", order: 40 },
5116
+ { id: "consumables", label: "Consumables", icon: "recycle", order: 44 },
5113
5117
  { id: "pipeline", label: "Detection Pipeline", icon: "cpu", order: 39 },
5114
5118
  { id: "zones", label: "Detection", icon: "shapes", order: 38 },
5115
5119
  { id: "live-stats", label: "Live Stats", icon: "activity", order: 39 },
@@ -5129,7 +5133,7 @@ const WELL_KNOWN_TABS = [
5129
5133
  ];
5130
5134
  Object.fromEntries(WELL_KNOWN_TABS.map((t) => [t.id, t]));
5131
5135
  function isValuelessField(field) {
5132
- return field.type === "separator" || field.type === "info" || field.type === "button" || field.type === "object-array" || field.type === "widget" || field.type === "addon-action-button";
5136
+ return field.type === "separator" || field.type === "info" || field.type === "qr-code" || field.type === "button" || field.type === "object-array" || field.type === "widget" || field.type === "addon-action-button" || field.type === "device-action-button";
5133
5137
  }
5134
5138
  function hydrateSchema(schema, values) {
5135
5139
  return {
@@ -5191,6 +5195,8 @@ function typeOf(field) {
5191
5195
  case "password":
5192
5196
  case "color":
5193
5197
  case "probe":
5198
+ case "timezone":
5199
+ case "datetime":
5194
5200
  return "string";
5195
5201
  case "number":
5196
5202
  case "slider":
@@ -5201,32 +5207,262 @@ function typeOf(field) {
5201
5207
  return "other";
5202
5208
  }
5203
5209
  }
5204
- const StorageLocationTypeSchema = _enum([
5205
- "data",
5206
- "media",
5207
- "recordings",
5208
- // Recording-stream slots — addons pick high/low/clips per use case.
5209
- // The legacy `IStorageProvider` interface enumerated these; keeping
5210
- // them in the Zod enum means the `storage` cap can route per-slot
5211
- // location refs (e.g. `'recordings-high:nas-01'`) without losing
5212
- // type safety.
5213
- "recordings-high",
5214
- "recordings-low",
5215
- "recordings-clips",
5216
- // Detection snapshots / thumbnails / crops.
5217
- "event-images",
5218
- "models",
5219
- "cache",
5220
- "logs",
5221
- "addons-data",
5222
- // `backups` owned by the backup-orchestrator builtin. Default
5223
- // root: `<dataDir>/backups`. Operators can repoint via the same
5224
- // override mechanism every other location uses (storage settings).
5225
- "backups"
5210
+ const CamProfileSchema = _enum(["high", "mid", "low"]);
5211
+ const CamStreamKindSchema = _enum([
5212
+ "pull-rtsp",
5213
+ "pull-rtmp",
5214
+ "pull-http",
5215
+ "pull-rfc4571",
5216
+ "push-annexb",
5217
+ /** Broker-spawned ffmpeg transcode plane reads from a source cam-stream
5218
+ * and writes a re-encoded RTP plane. The broker routes demand signals to
5219
+ * the source broker; the transcode process is single-flighted per
5220
+ * identical EncodeProfile so multiple derived subscribers share one ffmpeg
5221
+ * process. */
5222
+ "derived"
5223
+ ]);
5224
+ const CamStreamResolutionSchema = object({
5225
+ width: number().int().positive(),
5226
+ height: number().int().positive()
5227
+ });
5228
+ const CameraStreamSchema = object({
5229
+ /** Stable, provider-assigned id unique within the (deviceId) scope. */
5230
+ camStreamId: string().min(1),
5231
+ deviceId: number().int().nonnegative(),
5232
+ kind: CamStreamKindSchema,
5233
+ /** Required for pull-* kinds. Ignored for push-annexb. */
5234
+ url: string().optional(),
5235
+ codec: string().optional(),
5236
+ resolution: CamStreamResolutionSchema.optional(),
5237
+ fps: number().positive().optional(),
5238
+ /** Human label surfaced in the Admin UI "Camera Stream" dropdown. */
5239
+ label: string().optional(),
5240
+ /**
5241
+ * Device-level features the publisher advertised (e.g. `battery-operated`).
5242
+ * The broker, snapshot orchestrator, and prebuffer manager all consult
5243
+ * this list to derive policy — relaxed stall watchdog for battery
5244
+ * cams, prebuffer off by default, longer snapshot rate-limit, etc.
5245
+ *
5246
+ * Single source of truth replacing per-stream flags like the
5247
+ * historical `allowStall`: if the publisher knows the camera is
5248
+ * battery-powered, every downstream service derives the right policy
5249
+ * from this list.
5250
+ */
5251
+ deviceFeatures: array(string()).optional(),
5252
+ /**
5253
+ * Whether this stream participates in the broker's automatic profile
5254
+ * assignment (`computeInitialAssignment`). Defaults to `true`. Publishers
5255
+ * use `false` when they want a stream to be SELECTABLE in the UI but not
5256
+ * picked by default — e.g. Reolink publishes its native Baichuan streams
5257
+ * as `autoEligible: true` (the recommended path) and its RTSP / RTMP
5258
+ * mirrors as `autoEligible: false` (still pickable per slot, just not
5259
+ * the auto choice). Manual `assignProfile` calls remain valid for
5260
+ * non-eligible streams.
5261
+ */
5262
+ autoEligible: boolean().optional(),
5263
+ /**
5264
+ * Transport-specific opaque metadata. The broker passes it through to
5265
+ * the source reader without inspecting it. Currently used by
5266
+ * `pull-rfc4571` streams to carry the upstream SDP (so the reader can
5267
+ * route RTP packets to the right depacketizer without an in-band
5268
+ * DESCRIBE phase). Other kinds typically leave it undefined.
5269
+ */
5270
+ metadata: record(string(), unknown()).optional()
5271
+ });
5272
+ const ProfileSlotStatusSchema = _enum([
5273
+ "unassigned",
5274
+ "idle",
5275
+ "connecting",
5276
+ "streaming",
5277
+ "error"
5278
+ ]);
5279
+ const ProfileSlotSchema = object({
5280
+ deviceId: number().int().nonnegative(),
5281
+ profile: CamProfileSchema,
5282
+ /** Broker id the rest of the system addresses: `${deviceId}/${profile}`. */
5283
+ brokerId: string(),
5284
+ /** `null` when the profile is unassigned. */
5285
+ sourceCamStreamId: string().nullable(),
5286
+ status: ProfileSlotStatusSchema,
5287
+ resolution: CamStreamResolutionSchema.optional(),
5288
+ codec: string().optional(),
5289
+ preBufferSec: number().nonnegative().optional(),
5290
+ errorMessage: string().optional()
5291
+ });
5292
+ const StreamSourceEntrySchema$1 = object({
5293
+ id: string(),
5294
+ label: string(),
5295
+ protocol: _enum(["rtsp", "rtmp", "annexb", "http-mjpeg", "webrtc", "custom"]),
5296
+ url: string().optional(),
5297
+ resolution: object({ width: number(), height: number() }).readonly().optional(),
5298
+ fps: number().optional(),
5299
+ bitrate: number().optional(),
5300
+ codec: string().optional(),
5301
+ profileHint: CamProfileSchema.optional()
5302
+ });
5303
+ object({
5304
+ type: string(),
5305
+ url: string(),
5306
+ videoCodec: string().optional(),
5307
+ audioCodec: string().optional(),
5308
+ metadata: record(string(), unknown()).readonly().optional()
5309
+ });
5310
+ const EncodedPacketSchema = object({
5311
+ type: _enum(["video", "audio"]),
5312
+ data: _instanceof(Uint8Array),
5313
+ pts: number(),
5314
+ dts: number(),
5315
+ keyframe: boolean(),
5316
+ codec: string()
5317
+ });
5318
+ const DecodedFrameSchema = object({
5319
+ data: _instanceof(Uint8Array),
5320
+ width: number(),
5321
+ height: number(),
5322
+ format: _enum(["jpeg", "rgb", "bgr", "yuv420", "gray"]),
5323
+ timestamp: number()
5324
+ });
5325
+ const FrameHandleSchema = object({
5326
+ shmId: string(),
5327
+ slot: number().int().nonnegative(),
5328
+ seq: number().int().nonnegative(),
5329
+ width: number().int().positive(),
5330
+ height: number().int().positive(),
5331
+ format: _enum(["jpeg", "rgb", "bgr", "yuv420", "gray"]),
5332
+ pts: number(),
5333
+ byteLength: number().int().nonnegative(),
5334
+ nodeId: string(),
5335
+ slotCount: number().int().positive()
5336
+ });
5337
+ const FrameHandleFormatSchema = _enum(["rgb", "bgr", "yuv420", "gray"]);
5338
+ const SubscribeFramesInputSchema = object({
5339
+ brokerId: string(),
5340
+ format: FrameHandleFormatSchema,
5341
+ /**
5342
+ * Optional reader-side cadence hint in frames per second. The broker does
5343
+ * NOT throttle — latest-wins ring reads drop frames implicitly for a slow
5344
+ * consumer. The value is echoed back in `SubscribeFramesResult.maxFps` so
5345
+ * the consumer can pace its own `pullFrameHandles` polling.
5346
+ */
5347
+ maxFps: number().positive().optional(),
5348
+ /** Short caller-identity tag (`motion`, `detection`, …) for diagnostics. */
5349
+ tag: string().optional()
5350
+ });
5351
+ const SubscribeFramesResultSchema = object({
5352
+ /** Opaque id the consumer passes to `pullFrameHandles` / `unsubscribeFrames`. */
5353
+ subscriptionId: string(),
5354
+ /** Reader-side cadence hint (frames/s) — echoes `SubscribeFramesInput.maxFps`. */
5355
+ maxFps: number().nonnegative()
5356
+ });
5357
+ const DecodedAudioChunkSchema = object({
5358
+ data: _instanceof(Uint8Array),
5359
+ sampleRate: number().int().positive(),
5360
+ channels: number().int().positive(),
5361
+ timestamp: number()
5362
+ });
5363
+ const SubscribeAudioChunksInputSchema = object({
5364
+ brokerId: string(),
5365
+ /** Short caller-identity tag (`audio-analyzer`, …) for `listClients`. */
5366
+ tag: string().optional()
5367
+ });
5368
+ const SubscribeAudioChunksResultSchema = object({
5369
+ /** Opaque id passed to `pullAudioChunks` / `unsubscribeAudioChunks`. */
5370
+ subscriptionId: string()
5371
+ });
5372
+ const BrokerStatusSchema$1 = _enum(["idle", "connecting", "streaming", "error", "stopped"]);
5373
+ const BrokerStatsSchema = object({
5374
+ status: BrokerStatusSchema$1,
5375
+ inputFps: number(),
5376
+ decodeFps: number(),
5377
+ encodedSubscribers: number(),
5378
+ decodedSubscribers: number(),
5379
+ uptimeMs: number(),
5380
+ bitrateKbps: number(),
5381
+ idrIntervalMs: number(),
5382
+ codec: string().optional(),
5383
+ totalBytes: number(),
5384
+ packetCount: number(),
5385
+ rtspClients: number(),
5386
+ pipeClients: number(),
5387
+ preBufferSec: number(),
5388
+ preBufferMs: number(),
5389
+ preBufferPackets: number(),
5390
+ /**
5391
+ * Moleculer node id of the decoder provider currently servicing this
5392
+ * stream's decoded subscribers. `null` until the deferred decoder is
5393
+ * created (no decoded clients yet, or codec not detected). Surfaces the
5394
+ * runtime decoder placement so the UI can show "Decoder: <agent>" without
5395
+ * a separate cap call per broker.
5396
+ */
5397
+ decoderNodeId: string().nullable(),
5398
+ /**
5399
+ * Detected audio track parameters from the RTSP DESCRIBE / SDP. `null`
5400
+ * when the stream has no audio track or the broker is in cold start.
5401
+ * `supported = false` means the codec was detected but the local
5402
+ * decoder pipeline cannot produce PCM chunks (e.g. AAC without the
5403
+ * AAC pipeline wired). Surfaced in the UI device-overview so operators
5404
+ * can pre-pick the audio-analysis model that matches the codec.
5405
+ */
5406
+ audio: object({
5407
+ codec: string(),
5408
+ sampleRate: number(),
5409
+ channels: number(),
5410
+ supported: boolean()
5411
+ }).nullable().optional()
5412
+ });
5413
+ const ProfileRtspEntrySchema = object({
5414
+ profile: CamProfileSchema,
5415
+ /** Profile-keyed broker id, format `${deviceId}/${profile}` (e.g. `"15/high"`). */
5416
+ brokerId: string(),
5417
+ url: string(),
5418
+ mutedUrl: string(),
5419
+ enabled: boolean(),
5420
+ codec: string().optional(),
5421
+ resolution: CamStreamResolutionSchema.optional()
5422
+ });
5423
+ const RecordingWeekdaySchema = number().int().min(0).max(6);
5424
+ const HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
5425
+ const RecordingScheduleSchema = discriminatedUnion("kind", [
5426
+ object({ kind: literal("always") }),
5427
+ object({
5428
+ kind: literal("timeOfDay"),
5429
+ start: string().regex(HHMM),
5430
+ end: string().regex(HHMM),
5431
+ /** Restrict to these weekdays; omit = every day. */
5432
+ days: array(RecordingWeekdaySchema).optional()
5433
+ })
5226
5434
  ]);
5435
+ const RecordingModeSchema = _enum(["continuous", "onMotion", "onAudioThreshold"]);
5436
+ const RecordingRuleSchema = object({
5437
+ schedule: RecordingScheduleSchema,
5438
+ mode: RecordingModeSchema,
5439
+ /** Seconds of footage to retain BEFORE a trigger (applied at keep/discard). */
5440
+ preBufferSec: number().min(0).default(0),
5441
+ /** Keep recording until this many seconds after the last trigger. */
5442
+ postBufferSec: number().min(0).default(0),
5443
+ /** Each new trigger restarts the post-buffer window. */
5444
+ resetTimeoutOnNewEvent: boolean().default(true),
5445
+ /** onAudioThreshold only — dBFS level that counts as a trigger. */
5446
+ thresholdDbfs: number().optional()
5447
+ });
5448
+ const RecordingRetentionSchema = object({
5449
+ maxAgeDays: number().min(0).optional(),
5450
+ maxSizeGb: number().min(0).optional()
5451
+ });
5452
+ const RecordingConfigSchema = object({
5453
+ enabled: boolean(),
5454
+ profiles: array(CamProfileSchema).optional(),
5455
+ segmentSeconds: number().int().positive().optional(),
5456
+ rules: array(RecordingRuleSchema).optional(),
5457
+ retention: RecordingRetentionSchema.optional()
5458
+ });
5459
+ const StorageLocationTypeSchema = string().regex(/^[a-z][a-zA-Z0-9-]*$/);
5227
5460
  const StorageLocationSchema = object({
5228
- id: string().regex(/^[a-z][a-z0-9-]*:[a-z0-9-]+$/),
5229
- type: StorageLocationTypeSchema,
5461
+ id: string().regex(/^[a-z][a-zA-Z0-9-]*:[a-zA-Z0-9-]+$/),
5462
+ // Open string — the location's *kind* is an addon-declared id matching
5463
+ // `StorageLocationDeclaration.id`. All built-in ids are valid plain
5464
+ // strings, and addon-declared ids are admitted without schema changes.
5465
+ type: string(),
5230
5466
  displayName: string().min(1),
5231
5467
  providerId: string().min(1),
5232
5468
  config: record(string(), unknown()),
@@ -5237,8 +5473,36 @@ const StorageLocationSchema = object({
5237
5473
  });
5238
5474
  const StorageLocationRefSchema = union([
5239
5475
  StorageLocationTypeSchema,
5240
- string().regex(/^[a-z][a-z0-9-]*:[a-z0-9-]+$/)
5476
+ string().regex(/^[a-z][a-zA-Z0-9-]*:[a-zA-Z0-9-]+$/)
5241
5477
  ]);
5478
+ const StorageLocationDeclarationSchema = object({
5479
+ /**
5480
+ * Global location identifier, e.g. `recordings` or `recordingsLow`.
5481
+ * Must start with a lowercase letter and may contain letters, digits, and
5482
+ * hyphens.
5483
+ */
5484
+ id: string().regex(/^[a-z][a-zA-Z0-9-]*$/, {
5485
+ message: "id must start with a lowercase letter and contain only letters, digits, or hyphens"
5486
+ }),
5487
+ /** Human-readable name shown in the admin UI. */
5488
+ displayName: string().min(1, { message: "displayName must not be empty" }),
5489
+ /** Optional longer explanation of what data this location stores. */
5490
+ description: string().optional(),
5491
+ /**
5492
+ * `single` — exactly one instance of this location is allowed system-wide
5493
+ * (e.g. `logs`, `models`). The operator can edit it but not add more.
5494
+ * `multi` — the operator may register several instances (e.g. a second
5495
+ * `recordings` on a NAS for disk tiering); one is the default at any time.
5496
+ */
5497
+ cardinality: _enum(["single", "multi"]),
5498
+ /**
5499
+ * When set, the default instance for this location inherits its resolved
5500
+ * root from the named location's default instance. Useful for derivative
5501
+ * slots (e.g. `recordingsLow` → `recordings`) so operators only need to
5502
+ * configure the primary location.
5503
+ */
5504
+ defaultsTo: string().optional()
5505
+ });
5242
5506
  const DecoderStatsSchema = object({
5243
5507
  inputFps: number(),
5244
5508
  outputFps: number(),
@@ -5280,6 +5544,51 @@ const DecoderSessionConfigSchema = object({
5280
5544
  */
5281
5545
  frameSink: _enum(["callback", "shm"]).default("callback")
5282
5546
  });
5547
+ const VideoEncodeSchema = object({
5548
+ codec: _enum(["h264", "h265", "copy"]),
5549
+ profile: _enum(["baseline", "main", "high"]).optional(),
5550
+ width: number().int().positive().optional(),
5551
+ height: number().int().positive().optional(),
5552
+ fps: number().positive().optional(),
5553
+ bitrateKbps: number().int().positive().optional(),
5554
+ gopFrames: number().int().positive().optional(),
5555
+ bf: number().int().min(0).optional(),
5556
+ preset: _enum([
5557
+ "ultrafast",
5558
+ "superfast",
5559
+ "veryfast",
5560
+ "faster",
5561
+ "fast",
5562
+ "medium"
5563
+ ]).optional(),
5564
+ tune: _enum(["zerolatency", "film", "animation"]).optional()
5565
+ });
5566
+ const AudioEncodeSchema = union([
5567
+ literal("passthrough"),
5568
+ object({
5569
+ codec: _enum(["opus", "aac", "pcmu", "pcma", "copy"]),
5570
+ bitrateKbps: number().int().positive().optional(),
5571
+ sampleRateHz: number().int().positive().optional(),
5572
+ channels: union([literal(1), literal(2)]).optional()
5573
+ })
5574
+ ]);
5575
+ const EncodeProfileSchema = object({
5576
+ video: VideoEncodeSchema,
5577
+ audio: AudioEncodeSchema,
5578
+ /**
5579
+ * ffmpeg input-side args, inserted between the fixed global flags
5580
+ * (`-hide_banner -loglevel error`) and `-i pipe:0`. Free-text array
5581
+ * — the widget surfaces a textarea + suggestion chips for the most-
5582
+ * used demuxer/format options.
5583
+ */
5584
+ inputArgs: array(string()).optional(),
5585
+ /**
5586
+ * ffmpeg output-side args, inserted between the encode block and
5587
+ * the final `-f <muxer> pipe:1`. Use for muxer options, bitstream
5588
+ * filters, codec-specific overrides. Free-text array.
5589
+ */
5590
+ outputArgs: array(string()).optional()
5591
+ });
5283
5592
  const YAMNET_TO_MACRO = {
5284
5593
  mapping: {
5285
5594
  // Speech
@@ -5581,18 +5890,74 @@ var DeviceType = /* @__PURE__ */ ((DeviceType2) => {
5581
5890
  DeviceType2["Sensor"] = "sensor";
5582
5891
  DeviceType2["Thermostat"] = "thermostat";
5583
5892
  DeviceType2["Button"] = "button";
5893
+ DeviceType2["EventEmitter"] = "event-emitter";
5894
+ DeviceType2["Update"] = "update";
5584
5895
  DeviceType2["Generic"] = "generic";
5896
+ DeviceType2["Notifier"] = "notifier";
5897
+ DeviceType2["Script"] = "script";
5898
+ DeviceType2["Automation"] = "automation";
5899
+ DeviceType2["Lock"] = "lock";
5900
+ DeviceType2["Cover"] = "cover";
5901
+ DeviceType2["Valve"] = "valve";
5902
+ DeviceType2["Humidifier"] = "humidifier";
5903
+ DeviceType2["WaterHeater"] = "water-heater";
5904
+ DeviceType2["Fan"] = "fan";
5905
+ DeviceType2["MediaPlayer"] = "media-player";
5906
+ DeviceType2["AlarmPanel"] = "alarm-panel";
5907
+ DeviceType2["Control"] = "control";
5908
+ DeviceType2["Presence"] = "presence";
5909
+ DeviceType2["Weather"] = "weather";
5910
+ DeviceType2["Vacuum"] = "vacuum";
5911
+ DeviceType2["LawnMower"] = "lawn-mower";
5912
+ DeviceType2["Container"] = "container";
5913
+ DeviceType2["Image"] = "image";
5585
5914
  return DeviceType2;
5586
5915
  })(DeviceType || {});
5587
5916
  var DeviceFeature = /* @__PURE__ */ ((DeviceFeature2) => {
5588
5917
  DeviceFeature2["BatteryOperated"] = "battery-operated";
5589
5918
  DeviceFeature2["Rebootable"] = "rebootable";
5919
+ DeviceFeature2["Resyncable"] = "resyncable";
5590
5920
  DeviceFeature2["NativeSnapshot"] = "native-snapshot";
5591
5921
  DeviceFeature2["DoorbellButton"] = "doorbell-button";
5592
5922
  DeviceFeature2["TwoWayAudio"] = "two-way-audio";
5593
5923
  DeviceFeature2["PanTiltZoom"] = "pan-tilt-zoom";
5594
5924
  DeviceFeature2["PtzAutotrack"] = "ptz-autotrack";
5595
5925
  DeviceFeature2["MotionTrigger"] = "motion-trigger";
5926
+ DeviceFeature2["LightColorRgb"] = "light-color-rgb";
5927
+ DeviceFeature2["LightColorHsv"] = "light-color-hsv";
5928
+ DeviceFeature2["LightColorMired"] = "light-color-mired";
5929
+ DeviceFeature2["ClimateDualSetpoint"] = "climate-dual-setpoint";
5930
+ DeviceFeature2["ClimateHumidity"] = "climate-humidity";
5931
+ DeviceFeature2["ClimateFanMode"] = "climate-fan-mode";
5932
+ DeviceFeature2["ClimatePreset"] = "climate-preset";
5933
+ DeviceFeature2["CoverPositionable"] = "cover-positionable";
5934
+ DeviceFeature2["CoverTilt"] = "cover-tilt";
5935
+ DeviceFeature2["ValvePositionable"] = "valve-positionable";
5936
+ DeviceFeature2["FanSpeed"] = "fan-speed";
5937
+ DeviceFeature2["FanPreset"] = "fan-preset";
5938
+ DeviceFeature2["FanDirection"] = "fan-direction";
5939
+ DeviceFeature2["FanOscillating"] = "fan-oscillating";
5940
+ DeviceFeature2["LockPinRequired"] = "lock-pin-required";
5941
+ DeviceFeature2["LockOpen"] = "lock-open";
5942
+ DeviceFeature2["MediaPlayerSeek"] = "media-player-seek";
5943
+ DeviceFeature2["MediaPlayerVolume"] = "media-player-volume";
5944
+ DeviceFeature2["MediaPlayerMute"] = "media-player-mute";
5945
+ DeviceFeature2["MediaPlayerShuffle"] = "media-player-shuffle";
5946
+ DeviceFeature2["MediaPlayerRepeat"] = "media-player-repeat";
5947
+ DeviceFeature2["MediaPlayerSelectSource"] = "media-player-select-source";
5948
+ DeviceFeature2["MediaPlayerPlayMedia"] = "media-player-play-media";
5949
+ DeviceFeature2["MediaPlayerNext"] = "media-player-next";
5950
+ DeviceFeature2["MediaPlayerPrevious"] = "media-player-previous";
5951
+ DeviceFeature2["MediaPlayerStop"] = "media-player-stop";
5952
+ DeviceFeature2["AlarmPinRequired"] = "alarm-pin-required";
5953
+ DeviceFeature2["PresenceGps"] = "presence-gps";
5954
+ DeviceFeature2["NotifierImage"] = "notifier-image";
5955
+ DeviceFeature2["NotifierPriority"] = "notifier-priority";
5956
+ DeviceFeature2["NotifierData"] = "notifier-data";
5957
+ DeviceFeature2["NotifierActions"] = "notifier-actions";
5958
+ DeviceFeature2["NotifierRecipients"] = "notifier-recipients";
5959
+ DeviceFeature2["ScriptVariables"] = "script-variables";
5960
+ DeviceFeature2["AutomationSkipCondition"] = "automation-skip-condition";
5596
5961
  return DeviceFeature2;
5597
5962
  })(DeviceFeature || {});
5598
5963
  var DeviceRole = /* @__PURE__ */ ((DeviceRole2) => {
@@ -5605,6 +5970,40 @@ var DeviceRole = /* @__PURE__ */ ((DeviceRole2) => {
5605
5970
  DeviceRole2["Nightvision"] = "nightvision";
5606
5971
  DeviceRole2["PrivacyMask"] = "privacy-mask";
5607
5972
  DeviceRole2["Doorbell"] = "doorbell";
5973
+ DeviceRole2["BinaryHelper"] = "binary-helper";
5974
+ DeviceRole2["MotionSensor"] = "motion-sensor";
5975
+ DeviceRole2["ContactSensor"] = "contact-sensor";
5976
+ DeviceRole2["LeakSensor"] = "leak-sensor";
5977
+ DeviceRole2["SmokeSensor"] = "smoke-sensor";
5978
+ DeviceRole2["COSensor"] = "co-sensor";
5979
+ DeviceRole2["GasSensor"] = "gas-sensor";
5980
+ DeviceRole2["TamperSensor"] = "tamper-sensor";
5981
+ DeviceRole2["VibrationSensor"] = "vibration-sensor";
5982
+ DeviceRole2["ConnectivitySensor"] = "connectivity-sensor";
5983
+ DeviceRole2["SoundSensor"] = "sound-sensor";
5984
+ DeviceRole2["BinarySensor"] = "binary-sensor";
5985
+ DeviceRole2["TemperatureSensor"] = "temperature-sensor";
5986
+ DeviceRole2["HumiditySensor"] = "humidity-sensor";
5987
+ DeviceRole2["AmbientLightSensor"] = "ambient-light-sensor";
5988
+ DeviceRole2["PressureSensor"] = "pressure-sensor";
5989
+ DeviceRole2["PowerSensor"] = "power-sensor";
5990
+ DeviceRole2["EnergySensor"] = "energy-sensor";
5991
+ DeviceRole2["VoltageSensor"] = "voltage-sensor";
5992
+ DeviceRole2["CurrentSensor"] = "current-sensor";
5993
+ DeviceRole2["AirQualitySensor"] = "air-quality-sensor";
5994
+ DeviceRole2["BatterySensor"] = "battery-sensor";
5995
+ DeviceRole2["NumericSensor"] = "numeric-sensor";
5996
+ DeviceRole2["EnumSensor"] = "enum-sensor";
5997
+ DeviceRole2["DateTimeSensor"] = "datetime-sensor";
5998
+ DeviceRole2["GenericSensor"] = "generic-sensor";
5999
+ DeviceRole2["NumericControl"] = "numeric-control";
6000
+ DeviceRole2["SelectControl"] = "select-control";
6001
+ DeviceRole2["TextControl"] = "text-control";
6002
+ DeviceRole2["DateTimeControl"] = "datetime-control";
6003
+ DeviceRole2["MobilePushNotifier"] = "mobile-push-notifier";
6004
+ DeviceRole2["MessagingNotifier"] = "messaging-notifier";
6005
+ DeviceRole2["EmailNotifier"] = "email-notifier";
6006
+ DeviceRole2["GenericNotifier"] = "generic-notifier";
5608
6007
  return DeviceRole2;
5609
6008
  })(DeviceRole || {});
5610
6009
  ({
@@ -5686,6 +6085,33 @@ const FeatureProbeStatusSchema = object({
5686
6085
  }) }
5687
6086
  }
5688
6087
  });
6088
+ object({
6089
+ /** Carbon dioxide concentration in ppm. */
6090
+ co2Ppm: number().min(0).optional(),
6091
+ /** Total volatile organic compounds in ppb. */
6092
+ vocPpb: number().min(0).optional(),
6093
+ /** Particulate matter ≤ 2.5 μm in µg/m³. */
6094
+ pm25: number().min(0).optional(),
6095
+ /** Particulate matter ≤ 10 μm in µg/m³. */
6096
+ pm10: number().min(0).optional(),
6097
+ /** Composite AQI value (typically 0..500). */
6098
+ aqi: number().optional(),
6099
+ /** Ms epoch when the slice was last updated. */
6100
+ lastFetchedAt: number(),
6101
+ /** Live display unit of the single metric this slice carries (e.g. HA
6102
+ * `attributes.unit_of_measurement` → 'ppm' / 'ppb' / 'µg/m³'). Each
6103
+ * upstream `sensor.*` entity surfaces ONE device_class, so one unit
6104
+ * per slice is unambiguous. */
6105
+ unit: string().optional(),
6106
+ /** Suggested decimal places for numeric display.
6107
+ * Populated live from the upstream source when provided (e.g. HA
6108
+ * `attributes.suggested_display_precision`). Falls back to
6109
+ * auto-formatting when absent. */
6110
+ precision: number().int().min(0).max(10).optional()
6111
+ });
6112
+ ({
6113
+ deviceTypes: [DeviceType.Sensor]
6114
+ });
5689
6115
  const ContributionSectionSchema = object({
5690
6116
  id: string(),
5691
6117
  title: string(),
@@ -5743,27 +6169,112 @@ function method(input, output, options) {
5743
6169
  function event(data) {
5744
6170
  return { data };
5745
6171
  }
5746
- const AudioClassSummarySchema = object({
5747
- className: string(),
5748
- /** Number of windows (chunks) where this class was the top hit. */
5749
- hits: number().int().nonnegative(),
5750
- /** Mean score across those hits, clamped to [0,1]. */
5751
- avgScore: number().min(0).max(1),
5752
- /** Peak score in the window. */
5753
- peakScore: number().min(0).max(1)
6172
+ const AlarmStateSchema = _enum([
6173
+ "disarmed",
6174
+ "armed_home",
6175
+ "armed_away",
6176
+ "armed_night",
6177
+ "armed_vacation",
6178
+ "armed_custom_bypass",
6179
+ "arming",
6180
+ "disarming",
6181
+ "pending",
6182
+ "triggered"
6183
+ ]);
6184
+ const AlarmArmModeSchema = _enum([
6185
+ "home",
6186
+ "away",
6187
+ "night",
6188
+ "vacation",
6189
+ "custom_bypass"
6190
+ ]);
6191
+ object({
6192
+ /** Current lifecycle state. */
6193
+ state: AlarmStateSchema,
6194
+ /** Subset of arm modes the panel accepts. UI renders one button per
6195
+ * mode in this list. */
6196
+ availableModes: array(AlarmArmModeSchema),
6197
+ /** Whether the panel requires a PIN on arm / disarm. Mirrors
6198
+ * `DeviceFeature.AlarmPinRequired` for slice consumers. */
6199
+ requiresCode: boolean(),
6200
+ /** Ms epoch when the slice was last updated. */
6201
+ lastChangedAt: number()
5754
6202
  });
5755
- const AudioMetricsSnapshotSchema = object({
5756
- /** Wall-clock timestamp (ms) of the most recent audio window. */
5757
- ts: number().int(),
5758
- /** Sliding-window length (seconds) used for aggregation. */
5759
- windowSec: number().int().positive(),
5760
- /** Latest level reading from the most recent window. */
5761
- level: object({
5762
- rms: number(),
5763
- dbfs: number()
5764
- }),
5765
- /** Peak dBFS observed across the rolling window. */
5766
- peakDbfs: number(),
6203
+ ({
6204
+ deviceTypes: [DeviceType.AlarmPanel],
6205
+ methods: {
6206
+ arm: method(
6207
+ object({
6208
+ deviceId: number().int().nonnegative(),
6209
+ mode: AlarmArmModeSchema,
6210
+ /** Optional PIN code. Required when `requiresCode === true`.
6211
+ * Passed through to the upstream service; never persisted. */
6212
+ code: string().min(1).optional()
6213
+ }),
6214
+ _void(),
6215
+ { kind: "mutation", auth: "admin" }
6216
+ ),
6217
+ disarm: method(
6218
+ object({
6219
+ deviceId: number().int().nonnegative(),
6220
+ code: string().min(1).optional()
6221
+ }),
6222
+ _void(),
6223
+ { kind: "mutation", auth: "admin" }
6224
+ ),
6225
+ /**
6226
+ * Force the panel into the `triggered` state — used by HA
6227
+ * automations to surface external sensor events through the panel
6228
+ * (e.g. a Reolink camera intrusion event firing the security
6229
+ * system). Provider rejects when the panel hardware doesn't
6230
+ * support a software-initiated trigger.
6231
+ */
6232
+ trigger: method(
6233
+ object({ deviceId: number().int().nonnegative() }),
6234
+ _void(),
6235
+ { kind: "mutation", auth: "admin" }
6236
+ )
6237
+ }
6238
+ });
6239
+ object({
6240
+ /** Current illuminance in lux (lx). */
6241
+ lux: number().min(0),
6242
+ /** Ms epoch when the slice was last updated. */
6243
+ lastFetchedAt: number(),
6244
+ /** Live display unit from the upstream source (e.g. HA
6245
+ * `attributes.unit_of_measurement`). The UI prefers this over the
6246
+ * role's canonical unit. Absent → fall back to the canonical unit. */
6247
+ unit: string().optional(),
6248
+ /** Suggested decimal places for numeric display.
6249
+ * Populated live from the upstream source when provided (e.g. HA
6250
+ * `attributes.suggested_display_precision`). Falls back to
6251
+ * auto-formatting when absent. */
6252
+ precision: number().int().min(0).max(10).optional()
6253
+ });
6254
+ ({
6255
+ deviceTypes: [DeviceType.Sensor]
6256
+ });
6257
+ const AudioClassSummarySchema = object({
6258
+ className: string(),
6259
+ /** Number of windows (chunks) where this class was the top hit. */
6260
+ hits: number().int().nonnegative(),
6261
+ /** Mean score across those hits, clamped to [0,1]. */
6262
+ avgScore: number().min(0).max(1),
6263
+ /** Peak score in the window. */
6264
+ peakScore: number().min(0).max(1)
6265
+ });
6266
+ const AudioMetricsSnapshotSchema = object({
6267
+ /** Wall-clock timestamp (ms) of the most recent audio window. */
6268
+ ts: number().int(),
6269
+ /** Sliding-window length (seconds) used for aggregation. */
6270
+ windowSec: number().int().positive(),
6271
+ /** Latest level reading from the most recent window. */
6272
+ level: object({
6273
+ rms: number(),
6274
+ dbfs: number()
6275
+ }),
6276
+ /** Peak dBFS observed across the rolling window. */
6277
+ peakDbfs: number(),
5767
6278
  /** Mean dBFS across the rolling window. */
5768
6279
  avgDbfs: number(),
5769
6280
  /** Most recent above-threshold classification, or null on silence. */
@@ -5834,6 +6345,46 @@ const AudioMetricsHistorySchema = object({
5834
6345
  )
5835
6346
  }
5836
6347
  });
6348
+ object({
6349
+ /** Whether the automation is currently enabled. Disabled automations
6350
+ * ignore their trigger block — manual `trigger` still works. */
6351
+ enabled: boolean(),
6352
+ /** Whether the automation is currently executing its action block. */
6353
+ isRunning: boolean(),
6354
+ /** Ms epoch of the last successful run. 0 when never run. */
6355
+ lastTriggeredAt: number(),
6356
+ /** Failure description from the last completed run. Null on success
6357
+ * or when never run. */
6358
+ lastError: string().nullable(),
6359
+ /** Ms epoch when the slice was last updated. */
6360
+ lastChangedAt: number()
6361
+ });
6362
+ ({
6363
+ deviceTypes: [DeviceType.Automation],
6364
+ methods: {
6365
+ enable: method(
6366
+ object({ deviceId: number().int().nonnegative() }),
6367
+ _void(),
6368
+ { kind: "mutation", auth: "admin" }
6369
+ ),
6370
+ disable: method(
6371
+ object({ deviceId: number().int().nonnegative() }),
6372
+ _void(),
6373
+ { kind: "mutation", auth: "admin" }
6374
+ ),
6375
+ trigger: method(
6376
+ object({
6377
+ deviceId: number().int().nonnegative(),
6378
+ /** When true, fires the action block while bypassing the
6379
+ * automation's condition evaluation. Gated by
6380
+ * `DeviceFeature.AutomationSkipCondition`. */
6381
+ skipCondition: boolean().optional()
6382
+ }),
6383
+ _void(),
6384
+ { kind: "mutation", auth: "admin" }
6385
+ )
6386
+ }
6387
+ });
5837
6388
  const BatteryStatusSchema = object({
5838
6389
  /** 0..100 inclusive. Firmware-reported. */
5839
6390
  percentage: number().min(0).max(100),
@@ -5851,10 +6402,48 @@ const BatteryStatusSchema = object({
5851
6402
  */
5852
6403
  sleeping: boolean(),
5853
6404
  /** Ms epoch of the last observation. Lets consumers reason about freshness. */
5854
- lastUpdated: number()
6405
+ lastUpdated: number(),
6406
+ /**
6407
+ * True when the source is a BINARY low-battery indicator (HA
6408
+ * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real
6409
+ * charge level — `percentage` is then a coarse stand-in (100 = normal,
6410
+ * sub-threshold = low). UI MUST render "Normal"/"Low" instead of a
6411
+ * misleading exact percentage. Absent/false → genuine 0–100 % reading.
6412
+ */
6413
+ binary: boolean().optional()
5855
6414
  });
5856
6415
  ({
5857
6416
  deviceTypes: [DeviceType.Camera, DeviceType.Sensor, DeviceType.Button, DeviceType.Switch],
6417
+ methods: {
6418
+ /**
6419
+ * Explicitly wake the camera from low-power sleep ahead of a
6420
+ * streaming session start. Consumers that initiate a stream
6421
+ * against a sleeping battery cam (HomeKit Secure Video, Alexa
6422
+ * RTCSession, snapshot wrappers) call this with a short timeout
6423
+ * before establishing the media pipeline — the broker's own
6424
+ * passive wake-on-dial works but adds 5–7 seconds to first-frame,
6425
+ * during which the consumer renders a black screen. Pre-waking
6426
+ * compresses that gap.
6427
+ *
6428
+ * Returns `awoke: true` when the firmware acknowledged the wake
6429
+ * before `timeoutMs`. Returns `awoke: false` when it timed out OR
6430
+ * the cap surface is unavailable (no Baichuan / firmware
6431
+ * channel); the caller should still attempt the stream — the
6432
+ * passive broker wake remains as fallback.
6433
+ */
6434
+ wakeForStream: method(
6435
+ object({
6436
+ deviceId: number(),
6437
+ /** Bound on the wait. Sensible range 3000–10000ms. */
6438
+ timeoutMs: number().int().min(500).max(3e4).default(8e3)
6439
+ }),
6440
+ object({
6441
+ awoke: boolean(),
6442
+ durationMs: number()
6443
+ }),
6444
+ { kind: "mutation" }
6445
+ )
6446
+ },
5858
6447
  events: {
5859
6448
  /**
5860
6449
  * Emitted whenever the cached status changes (firmware push OR
@@ -5868,6 +6457,14 @@ const BatteryStatusSchema = object({
5868
6457
  }) }
5869
6458
  }
5870
6459
  });
6460
+ object({
6461
+ on: boolean(),
6462
+ /** Ms epoch of the last transition. 0 if never observed. */
6463
+ lastChangedAt: number()
6464
+ });
6465
+ ({
6466
+ deviceTypes: [DeviceType.Sensor]
6467
+ });
5871
6468
  object({
5872
6469
  /** Current level as 0..100 inclusive. Firmware-reported. */
5873
6470
  percentage: number().min(0).max(100),
@@ -5899,287 +6496,199 @@ object({
5899
6496
  }) }
5900
6497
  }
5901
6498
  });
5902
- const CamProfileSchema = _enum(["high", "mid", "low"]);
5903
- const CamStreamKindSchema = _enum([
5904
- "pull-rtsp",
5905
- "pull-rtmp",
5906
- "pull-http",
5907
- "pull-rfc4571",
5908
- "push-annexb"
5909
- ]);
5910
- const CamStreamResolutionSchema = object({
5911
- width: number().int().positive(),
5912
- height: number().int().positive()
6499
+ const StreamFormatSchema = _enum(["webrtc", "hls", "mjpeg", "rtsp"]);
6500
+ const StreamInfoSchema = object({
6501
+ streamId: string(),
6502
+ format: StreamFormatSchema,
6503
+ url: string().nullable(),
6504
+ active: boolean()
5913
6505
  });
5914
- const CameraStreamSchema = object({
5915
- /** Stable, provider-assigned id unique within the (deviceId) scope. */
5916
- camStreamId: string().min(1),
5917
- deviceId: number().int().nonnegative(),
5918
- kind: CamStreamKindSchema,
5919
- /** Required for pull-* kinds. Ignored for push-annexb. */
5920
- url: string().optional(),
6506
+ ({
6507
+ methods: {
6508
+ registerStream: method(
6509
+ object({ streamId: string(), sourceUrl: string(), codec: string().optional() }),
6510
+ _void(),
6511
+ { kind: "mutation" }
6512
+ ),
6513
+ unregisterStream: method(object({ streamId: string() }), _void(), { kind: "mutation" }),
6514
+ getStreamUrl: method(
6515
+ object({ streamId: string(), format: StreamFormatSchema }),
6516
+ string().nullable()
6517
+ ),
6518
+ listStreams: method(_void(), array(StreamInfoSchema))
6519
+ }
6520
+ });
6521
+ const RtspRestreamEntrySchema = object({
6522
+ brokerId: string(),
6523
+ url: string(),
6524
+ mutedUrl: string(),
6525
+ enabled: boolean(),
6526
+ /**
6527
+ * Source-stream codec / resolution for the camStream this entry serves
6528
+ * (the broker's "high"/"mid"/"low" profile slot for this device).
6529
+ * Used by exporter pickers (`pickPreferredRtspEntry`) to resolve
6530
+ * `streamPreference: 'auto'` to the slot whose source is closest to
6531
+ * the consumer's target — Alexa wants ~720p, HomeKit wants ~1080p,
6532
+ * and there's no point dialling the 4K slot for an Echo Show. Absent
6533
+ * when the source publisher never advertised the field; pickers fall
6534
+ * back to first-enabled in that case.
6535
+ */
5921
6536
  codec: string().optional(),
5922
- resolution: CamStreamResolutionSchema.optional(),
5923
- fps: number().positive().optional(),
5924
- /** Human label surfaced in the Admin UI "Camera Stream" dropdown. */
6537
+ resolution: object({
6538
+ width: number().int().positive(),
6539
+ height: number().int().positive()
6540
+ }).optional()
6541
+ });
6542
+ const BrokerRtspClientSchema = object({
6543
+ sessionId: string(),
6544
+ remoteAddr: string(),
6545
+ playing: boolean(),
6546
+ muted: boolean(),
6547
+ connectedAt: number(),
6548
+ lastRtpAt: number(),
6549
+ bytesSent: number()
6550
+ });
6551
+ const BrokerDecodedClientSchema = object({
6552
+ tag: string(),
6553
+ subscribedAt: number(),
6554
+ maxFps: number(),
6555
+ framesDelivered: number(),
6556
+ framesDropped: number()
6557
+ });
6558
+ const BrokerAudioClientSchema = object({
6559
+ tag: string(),
6560
+ subscribedAt: number(),
6561
+ chunksDelivered: number()
6562
+ });
6563
+ const BrokerConsumerKindSchema = _enum([
6564
+ "alexa",
6565
+ "homekit",
6566
+ "webrtc-browser",
6567
+ "webrtc-mobile",
6568
+ "webrtc-whep",
6569
+ "rtsp-listen",
6570
+ "derived-broker",
6571
+ "recording",
6572
+ "pipeline",
6573
+ "snapshot",
6574
+ "warmup",
6575
+ "unknown"
6576
+ ]);
6577
+ const BrokerConsumerAttributionSchema = object({
6578
+ kind: BrokerConsumerKindSchema,
6579
+ /**
6580
+ * Free-form label intended to disambiguate consumers OF THE SAME kind
6581
+ * on the same broker — e.g. user name, device alias. Should NOT repeat
6582
+ * the kind / cam / cam-stream / sessionId (those are surfaced by
6583
+ * dedicated fields). When empty the widget falls back to `${kind} ·
6584
+ * <sessionId tail>`.
6585
+ */
5925
6586
  label: string().optional(),
5926
6587
  /**
5927
- * Device-level features the publisher advertised (e.g. `battery-operated`).
5928
- * The broker, snapshot orchestrator, and prebuffer manager all consult
5929
- * this list to derive policy relaxed stall watchdog for battery
5930
- * cams, prebuffer off by default, longer snapshot rate-limit, etc.
6588
+ * Which part of the encoded plane this subscription consumes:
6589
+ * - `'audio'` audio packets only
6590
+ * - `'video'`video packets only
6591
+ * - `'both'` — both video + audio (typical for AnnexB push paths
6592
+ * that don't split the source RTP)
5931
6593
  *
5932
- * Single source of truth replacing per-stream flags like the
5933
- * historical `allowStall`: if the publisher knows the camera is
5934
- * battery-powered, every downstream service derives the right policy
5935
- * from this list.
6594
+ * Missing field means "unknown" older callers and the legacy
6595
+ * paths that haven't been migrated yet.
5936
6596
  */
5937
- deviceFeatures: array(string()).optional(),
6597
+ media: _enum(["audio", "video", "both"]).optional(),
5938
6598
  /**
5939
- * Whether this stream participates in the broker's automatic profile
5940
- * assignment (`computeInitialAssignment`). Defaults to `true`. Publishers
5941
- * use `false` when they want a stream to be SELECTABLE in the UI but not
5942
- * picked by default e.g. Reolink publishes its native Baichuan streams
5943
- * as `autoEligible: true` (the recommended path) and its RTSP / RTMP
5944
- * mirrors as `autoEligible: false` (still pickable per slot, just not
5945
- * the auto choice). Manual `assignProfile` calls remain valid for
5946
- * non-eligible streams.
6599
+ * Codec the consumer receives AFTER any per-session re-encoding. For
6600
+ * a WebRTC session this is the negotiated egress codec (e.g. `H264`,
6601
+ * `H265`, `Opus`, `Pcmu`); for an RTSP restreamer it mirrors the
6602
+ * source codec. Surfaced in the widget chip so operators see at a
6603
+ * glance whether a viewer is on H.264 (Echo) or H.265 (Safari).
5947
6604
  */
5948
- autoEligible: boolean().optional(),
6605
+ targetCodec: string().optional(),
5949
6606
  /**
5950
- * Transport-specific opaque metadata. The broker passes it through to
5951
- * the source reader without inspecting it. Currently used by
5952
- * `pull-rfc4571` streams to carry the upstream SDP (so the reader can
5953
- * route RTP packets to the right depacketizer without an in-band
5954
- * DESCRIBE phase). Other kinds typically leave it undefined.
6607
+ * Whether the broker is re-encoding for this consumer:
6608
+ * - `'passthrough'` bytes flow source→consumer without ffmpeg
6609
+ * - `'repacketize'` RTP payload is re-packetized but NOT re-encoded
6610
+ * (preserves frames, just rebuilds headers; e.g.
6611
+ * the H.265 repacketizer path)
6612
+ * - `'transcode'` — a full encode/decode round (ffmpeg, libx264,
6613
+ * libav…); the most expensive path
5955
6614
  */
5956
- metadata: record(string(), unknown()).optional()
6615
+ transport: _enum(["passthrough", "repacketize", "transcode"]).optional(),
6616
+ /** Remote peer IP if the consumer terminates a network socket. */
6617
+ remoteAddr: string().optional(),
6618
+ /**
6619
+ * Server-read User-Agent of the originating client; enriched by the hub
6620
+ * from the tRPC request context (browser sessions).
6621
+ */
6622
+ userAgent: string().optional(),
6623
+ /** Authenticated user id (CamStack OAuth subject) when known. */
6624
+ userId: string().optional(),
6625
+ /** Higher-level session identifier (Alexa Echo sessionId, HAP session, …). */
6626
+ sessionId: string().optional(),
6627
+ /** Free-form key/value extras (e.g. clientHints from a WebRTC offer). */
6628
+ extra: record(string(), string()).optional()
6629
+ }).readonly();
6630
+ const BrokerEncodedClientSchema = object({
6631
+ /** Stable id assigned on attach; used by `killClient`. */
6632
+ id: string(),
6633
+ /** Which broker fanout the subscriber rides — annexB encoded packets vs raw RTP. */
6634
+ channel: _enum(["annexb", "rtp"]),
6635
+ attribution: BrokerConsumerAttributionSchema,
6636
+ subscribedAt: number(),
6637
+ /** Total packets delivered (annex-B EncodedPackets or RTP byte-buffers). */
6638
+ packetsDelivered: number()
5957
6639
  });
5958
- const ProfileSlotStatusSchema = _enum([
5959
- "unassigned",
5960
- "idle",
5961
- "connecting",
5962
- "streaming",
5963
- "error"
6640
+ const BrokerClientsSchema = object({
6641
+ rtsp: array(BrokerRtspClientSchema).readonly(),
6642
+ decoded: array(BrokerDecodedClientSchema).readonly(),
6643
+ audio: array(BrokerAudioClientSchema).readonly(),
6644
+ encoded: array(BrokerEncodedClientSchema).readonly(),
6645
+ pipeClients: number(),
6646
+ /** Total encoded + raw-RTP callback subscriber count (sum of `encoded[].length`). */
6647
+ encodedSubscribers: number()
6648
+ });
6649
+ _enum([
6650
+ "reconnecting",
6651
+ "sleeping",
6652
+ "offline",
6653
+ "disabled",
6654
+ "waking"
5964
6655
  ]);
5965
- const ProfileSlotSchema = object({
6656
+ const VideoCodecTargetSchema = _enum(["h264", "h265", "copy"]);
6657
+ const AudioCodecTargetSchema = _enum(["aac", "opus", "pcmu", "copy", "none"]);
6658
+ const GetStreamWithCodecInputSchema = object({
5966
6659
  deviceId: number().int().nonnegative(),
5967
- profile: CamProfileSchema,
5968
- /** Broker id the rest of the system addresses: `${deviceId}/${profile}`. */
5969
- brokerId: string(),
5970
- /** `null` when the profile is unassigned. */
5971
- sourceCamStreamId: string().nullable(),
5972
- status: ProfileSlotStatusSchema,
5973
- resolution: CamStreamResolutionSchema.optional(),
5974
- codec: string().optional(),
5975
- preBufferSec: number().nonnegative().optional(),
5976
- errorMessage: string().optional()
5977
- });
5978
- const StreamSourceEntrySchema$1 = object({
5979
- id: string(),
5980
- label: string(),
5981
- protocol: _enum(["rtsp", "rtmp", "annexb", "http-mjpeg", "webrtc", "custom"]),
5982
- url: string().optional(),
5983
- resolution: object({ width: number(), height: number() }).readonly().optional(),
5984
- fps: number().optional(),
5985
- bitrate: number().optional(),
5986
- codec: string().optional(),
5987
- profileHint: _enum(["high", "mid", "low"]).optional()
6660
+ /** Target codec. `'copy'` = passthrough (no re-encode). */
6661
+ video: VideoCodecTargetSchema,
6662
+ /** Target audio codec. `'copy'` = passthrough. Defaults to `'aac'`. */
6663
+ audio: AudioCodecTargetSchema.optional(),
6664
+ /** Target a profile's assigned source camStream. Required to resolve a source. */
6665
+ profile: CamProfileSchema.optional(),
6666
+ /** Optional output resolution target. When set: drives the transcode
6667
+ * output scale (downscale toward WxH), and — when `profile` is absent —
6668
+ * selects the published source closest to this resolution. Ignored for
6669
+ * `video:'copy'` scaling (a copy can't be rescaled), but still used for
6670
+ * source selection. */
6671
+ targetResolution: object({ width: number().int().positive(), height: number().int().positive() }).optional(),
6672
+ /** Extra ffmpeg output flags appended verbatim by the consumer (in code).
6673
+ * Folded into the pipeline key so different args never share a child. */
6674
+ outputArgs: array(string()).optional(),
6675
+ /** Opt-in: carry transcoded audio over an RTP sidecar grafted into the
6676
+ * restreamer SDP (only for re-encoded audio targets — aac/opus/pcmu).
6677
+ * Default/absent = the live-verified video-only egress. */
6678
+ audioEgress: boolean().optional(),
6679
+ tag: string().optional()
5988
6680
  });
5989
- object({
5990
- type: string(),
6681
+ const RtpSourceSchema = object({
5991
6682
  url: string(),
5992
- videoCodec: string().optional(),
5993
- audioCodec: string().optional(),
5994
- metadata: record(string(), unknown()).readonly().optional()
5995
- });
5996
- const EncodedPacketSchema = object({
5997
- type: _enum(["video", "audio"]),
5998
- data: _instanceof(Uint8Array),
5999
- pts: number(),
6000
- dts: number(),
6001
- keyframe: boolean(),
6002
- codec: string()
6003
- });
6004
- const DecodedFrameSchema = object({
6005
- data: _instanceof(Uint8Array),
6006
- width: number(),
6007
- height: number(),
6008
- format: _enum(["jpeg", "rgb", "bgr", "yuv420", "gray"]),
6009
- timestamp: number()
6010
- });
6011
- const FrameHandleSchema = object({
6012
- shmId: string(),
6013
- slot: number().int().nonnegative(),
6014
- seq: number().int().nonnegative(),
6015
- width: number().int().positive(),
6016
- height: number().int().positive(),
6017
- format: _enum(["jpeg", "rgb", "bgr", "yuv420", "gray"]),
6018
- pts: number(),
6019
- byteLength: number().int().nonnegative(),
6020
- nodeId: string(),
6021
- slotCount: number().int().positive()
6022
- });
6023
- const FrameHandleFormatSchema = _enum(["rgb", "bgr", "yuv420", "gray"]);
6024
- const SubscribeFramesInputSchema = object({
6025
- brokerId: string(),
6026
- format: FrameHandleFormatSchema,
6027
- /**
6028
- * Optional reader-side cadence hint in frames per second. The broker does
6029
- * NOT throttle — latest-wins ring reads drop frames implicitly for a slow
6030
- * consumer. The value is echoed back in `SubscribeFramesResult.maxFps` so
6031
- * the consumer can pace its own `pullFrameHandles` polling.
6032
- */
6033
- maxFps: number().positive().optional(),
6034
- /** Short caller-identity tag (`motion`, `detection`, …) for diagnostics. */
6035
- tag: string().optional()
6036
- });
6037
- const SubscribeFramesResultSchema = object({
6038
- /** Opaque id the consumer passes to `pullFrameHandles` / `unsubscribeFrames`. */
6039
- subscriptionId: string(),
6040
- /** Reader-side cadence hint (frames/s) — echoes `SubscribeFramesInput.maxFps`. */
6041
- maxFps: number().nonnegative()
6042
- });
6043
- const DecodedAudioChunkSchema = object({
6044
- data: _instanceof(Uint8Array),
6045
- sampleRate: number().int().positive(),
6046
- channels: number().int().positive(),
6047
- timestamp: number()
6048
- });
6049
- const SubscribeAudioChunksInputSchema = object({
6050
- brokerId: string(),
6051
- /** Short caller-identity tag (`audio-analyzer`, …) for `listClients`. */
6052
- tag: string().optional()
6053
- });
6054
- const SubscribeAudioChunksResultSchema = object({
6055
- /** Opaque id passed to `pullAudioChunks` / `unsubscribeAudioChunks`. */
6056
- subscriptionId: string()
6057
- });
6058
- const BrokerStatusSchema$1 = _enum(["idle", "connecting", "streaming", "error", "stopped"]);
6059
- const BrokerStatsSchema = object({
6060
- status: BrokerStatusSchema$1,
6061
- inputFps: number(),
6062
- decodeFps: number(),
6063
- encodedSubscribers: number(),
6064
- decodedSubscribers: number(),
6065
- uptimeMs: number(),
6066
- bitrateKbps: number(),
6067
- idrIntervalMs: number(),
6068
- codec: string().optional(),
6069
- totalBytes: number(),
6070
- packetCount: number(),
6071
- rtspClients: number(),
6072
- pipeClients: number(),
6073
- preBufferSec: number(),
6074
- preBufferMs: number(),
6075
- preBufferPackets: number(),
6076
- /**
6077
- * Moleculer node id of the decoder provider currently servicing this
6078
- * stream's decoded subscribers. `null` until the deferred decoder is
6079
- * created (no decoded clients yet, or codec not detected). Surfaces the
6080
- * runtime decoder placement so the UI can show "Decoder: <agent>" without
6081
- * a separate cap call per broker.
6082
- */
6083
- decoderNodeId: string().nullable(),
6084
- /**
6085
- * Detected audio track parameters from the RTSP DESCRIBE / SDP. `null`
6086
- * when the stream has no audio track or the broker is in cold start.
6087
- * `supported = false` means the codec was detected but the local
6088
- * decoder pipeline cannot produce PCM chunks (e.g. AAC without the
6089
- * AAC pipeline wired). Surfaced in the UI device-overview so operators
6090
- * can pre-pick the audio-analysis model that matches the codec.
6091
- */
6092
- audio: object({
6093
- codec: string(),
6094
- sampleRate: number(),
6095
- channels: number(),
6096
- supported: boolean()
6097
- }).nullable().optional()
6098
- });
6099
- const StreamFormatSchema = _enum(["webrtc", "hls", "mjpeg", "rtsp"]);
6100
- const StreamInfoSchema = object({
6101
- streamId: string(),
6102
- format: StreamFormatSchema,
6103
- url: string().nullable(),
6104
- active: boolean()
6105
- });
6106
- ({
6107
- methods: {
6108
- registerStream: method(
6109
- object({ streamId: string(), sourceUrl: string(), codec: string().optional() }),
6110
- _void(),
6111
- { kind: "mutation" }
6112
- ),
6113
- unregisterStream: method(object({ streamId: string() }), _void(), { kind: "mutation" }),
6114
- getStreamUrl: method(
6115
- object({ streamId: string(), format: StreamFormatSchema }),
6116
- string().nullable()
6117
- ),
6118
- listStreams: method(_void(), array(StreamInfoSchema))
6119
- }
6120
- });
6121
- const RtspRestreamEntrySchema = object({
6122
- brokerId: string(),
6123
- url: string(),
6124
- mutedUrl: string(),
6125
- enabled: boolean()
6126
- });
6127
- const BrokerRtspClientSchema = object({
6128
- sessionId: string(),
6129
- remoteAddr: string(),
6130
- playing: boolean(),
6131
- muted: boolean(),
6132
- connectedAt: number(),
6133
- lastRtpAt: number(),
6134
- bytesSent: number()
6135
- });
6136
- const BrokerDecodedClientSchema = object({
6137
- tag: string(),
6138
- subscribedAt: number(),
6139
- maxFps: number(),
6140
- framesDelivered: number(),
6141
- framesDropped: number()
6142
- });
6143
- const BrokerAudioClientSchema = object({
6144
- tag: string(),
6145
- subscribedAt: number(),
6146
- chunksDelivered: number()
6147
- });
6148
- const BrokerClientsSchema = object({
6149
- rtsp: array(BrokerRtspClientSchema).readonly(),
6150
- decoded: array(BrokerDecodedClientSchema).readonly(),
6151
- audio: array(BrokerAudioClientSchema).readonly(),
6152
- pipeClients: number(),
6153
- encodedSubscribers: number()
6154
- });
6155
- _enum([
6156
- "reconnecting",
6157
- "sleeping",
6158
- "offline",
6159
- "disabled",
6160
- "waking"
6161
- ]);
6162
- const VideoCodecTargetSchema = _enum(["H264", "H265", "auto"]);
6163
- const AudioCodecTargetSchema = _enum(["AAC", "Opus", "PCMU", "none"]);
6164
- const MaxResolutionSchema = object({
6165
- width: number().int().positive(),
6166
- height: number().int().positive()
6167
- });
6168
- const GetStreamWithCodecInputSchema = object({
6169
- deviceId: number().int().nonnegative(),
6170
- videoCodec: VideoCodecTargetSchema,
6171
- audioCodec: AudioCodecTargetSchema.optional(),
6172
- maxResolution: MaxResolutionSchema.optional(),
6173
- tag: string().optional()
6174
- });
6175
- const RtpSourceSchema = object({
6176
- url: string(),
6177
- videoCodec: _enum(["H264", "H265"]),
6178
- audioCodec: string(),
6179
- resolution: MaxResolutionSchema,
6180
- transcoded: boolean(),
6181
- encoder: string(),
6182
- pipelineKey: string()
6683
+ videoCodec: _enum(["H264", "H265"]),
6684
+ audioCodec: string(),
6685
+ resolution: object({
6686
+ width: number().int().positive(),
6687
+ height: number().int().positive()
6688
+ }),
6689
+ transcoded: boolean(),
6690
+ encoder: string(),
6691
+ pipelineKey: string()
6183
6692
  });
6184
6693
  ({
6185
6694
  methods: {
@@ -6195,7 +6704,17 @@ const RtpSourceSchema = object({
6195
6704
  label: string().optional(),
6196
6705
  deviceFeatures: array(string()).optional(),
6197
6706
  autoEligible: boolean().optional(),
6198
- metadata: record(string(), unknown()).optional()
6707
+ metadata: record(string(), unknown()).optional(),
6708
+ /** Required when kind === 'derived' — the source camStreamId the
6709
+ * derived broker reads its encoded plane from.
6710
+ * The runtime guard (broker manager, Task 10) enforces presence for
6711
+ * kind === 'derived'; the schema stays permissive so ts-morph emits
6712
+ * full field types instead of collapsing to ZodEffects. */
6713
+ sourceCamStreamId: string().min(1).optional(),
6714
+ /** Required when kind === 'derived' — the ffmpeg params for the
6715
+ * spawn. Reuses the same brokerId for identical params (single-flight).
6716
+ * Runtime guard in broker manager; schema is permissive (see above). */
6717
+ encodeProfile: EncodeProfileSchema.optional()
6199
6718
  }),
6200
6719
  object({ success: literal(true) }),
6201
6720
  { kind: "mutation", auth: "admin" }
@@ -6258,12 +6777,21 @@ const RtpSourceSchema = object({
6258
6777
  object({ success: boolean() }),
6259
6778
  { kind: "mutation", auth: "admin" }
6260
6779
  ),
6780
+ /**
6781
+ * LEGACY / observability. Returns a raw per-broker restream URL for a
6782
+ * single stream. Prefer {@link getStreamWithCodec} for programmatic
6783
+ * CONSUMPTION — it is the single demand-counted entry that rides the
6784
+ * broker's one source dial and returns a codec-correct passthrough.
6785
+ */
6261
6786
  getStreamUrl: method(
6262
6787
  object({ streamId: string(), format: StreamFormatSchema }),
6263
6788
  object({ url: string() })
6264
6789
  ),
6265
6790
  /**
6266
- * Shared codec-targeted stream API — see Task #184.
6791
+ * Shared codec-targeted stream API — see Task #184. THE single public
6792
+ * stream-acquisition surface for programmatic consumers: single-dial
6793
+ * (rides the broker's one source pull) and passthrough-correct
6794
+ * (`videoCodec:'auto'` → `-c copy`, never a needless re-encode).
6267
6795
  * Resolution order: source-select → HW transcode → libx264/libx265.
6268
6796
  */
6269
6797
  getStreamWithCodec: method(
@@ -6357,10 +6885,20 @@ const RtpSourceSchema = object({
6357
6885
  object({ configuredSec: number(), bufferedMs: number(), packetCount: number() })
6358
6886
  ),
6359
6887
  getRtspPort: method(_void(), number()),
6888
+ /**
6889
+ * Enumeration surface — backs the admin RTSP-export picker and
6890
+ * `pickPreferredRtspEntry`. Lists every per-broker restream entry. NOT a
6891
+ * consumption API: programmatic readers use {@link getStreamWithCodec}.
6892
+ */
6360
6893
  getAllRtspEntries: method(
6361
6894
  object({ hostname: string().optional() }),
6362
6895
  array(RtspRestreamEntrySchema).readonly()
6363
6896
  ),
6897
+ /**
6898
+ * LEGACY / observability. Resolves one broker's restream entry. Prefer
6899
+ * {@link getStreamWithCodec} for programmatic CONSUMPTION so the read is
6900
+ * demand-counted and rides the single source dial.
6901
+ */
6364
6902
  getRtspEntry: method(
6365
6903
  object({ brokerId: string(), hostname: string().optional() }),
6366
6904
  RtspRestreamEntrySchema.nullable()
@@ -6397,203 +6935,1099 @@ const RtpSourceSchema = object({
6397
6935
  }))
6398
6936
  }
6399
6937
  });
6938
+ const STREAM_CODEC_VALUES = ["h264", "h265", "hevc", "av1", "mjpeg", "vp8", "vp9"];
6939
+ const StreamCodecSchema = _enum(STREAM_CODEC_VALUES);
6940
+ const PickStreamRequirementsSchema = object({
6941
+ /**
6942
+ * Codecs the consumer can decode without an intermediate transcode.
6943
+ * Match is case-insensitive against the camera stream's `codec`.
6944
+ * Default (omitted / empty array): no codec filter — useful when the
6945
+ * consumer just wants "the highest-quality stream of any codec".
6946
+ */
6947
+ acceptCodecs: array(StreamCodecSchema).readonly().optional(),
6948
+ /** Minimum vertical resolution. Streams shorter than this are dropped. */
6949
+ minHeight: number().int().positive().optional(),
6950
+ /** Minimum horizontal resolution. */
6951
+ minWidth: number().int().positive().optional(),
6952
+ /**
6953
+ * When true (default), `derived:*` streams (transcoded broker pipes)
6954
+ * are excluded — the caller wants a SOURCE stream the broker can
6955
+ * forward without a re-encode. Set false to allow derived in the
6956
+ * picker (useful for a "best playable" fallback).
6957
+ */
6958
+ excludeDerived: boolean().optional(),
6959
+ /**
6960
+ * Bypass gate. When set, the picker returns a hit ONLY IF the device
6961
+ * also exposes a non-derived stream in one of these (rejected) codecs.
6962
+ * Mirrors the Alexa "bypass only when the natural path WOULD have
6963
+ * transcoded" guard: if the device is already serving the consumer's
6964
+ * codec end-to-end, there's nothing to optimise.
6965
+ */
6966
+ requireSiblingCodec: array(StreamCodecSchema).readonly().optional()
6967
+ }).readonly();
6968
+ const PickStreamPreferencesSchema = object({
6969
+ /**
6970
+ * Ordered list of provider prefixes (e.g. `['native:', 'rtsp:']`) the
6971
+ * picker prefers — earlier entries win ties. Defaults to
6972
+ * `['native:']`, mirroring Alexa's "prefer the native dial path".
6973
+ */
6974
+ preferredProviders: array(string()).readonly().optional(),
6975
+ /**
6976
+ * Resolution preference within the surviving candidates. `'highest'`
6977
+ * picks the tallest stream; `'lowest'` picks the shortest (used by
6978
+ * memory-constrained consumers / Apple Home guest sessions).
6979
+ */
6980
+ resolutionPreference: _enum(["highest", "lowest"]).optional()
6981
+ }).readonly();
6982
+ const PickedCamStreamSchema = object({
6983
+ camStreamId: string(),
6984
+ codec: string().optional(),
6985
+ resolution: CamStreamResolutionSchema.optional(),
6986
+ /** One-line explanation of why this stream won — for logs / debug UI. */
6987
+ reason: string()
6988
+ });
6989
+ ({
6990
+ deviceTypes: [DeviceType.Camera],
6991
+ methods: {
6992
+ getCameraStreams: method(
6993
+ object({ deviceId: number().int().nonnegative() }),
6994
+ array(CameraStreamSchema).readonly()
6995
+ ),
6996
+ getBrokerStreams: method(
6997
+ object({ deviceId: number().int().nonnegative() }),
6998
+ array(ProfileSlotSchema).readonly()
6999
+ ),
7000
+ /**
7001
+ * Per-device RAW RTSP restream entries — one per published camStream
7002
+ * that has RTSP restream enabled (`native:main`, `rtsp:sub`, …).
7003
+ *
7004
+ * LIVE-VIEW ONLY. This is the surface the device-details stream
7005
+ * picker uses so an operator can hit each physical stream directly.
7006
+ * Programmatic / external consumers (HAP, Alexa, ha-mqtt, recording)
7007
+ * MUST use `getProfileRtspEntries` instead — picking from raw
7008
+ * variants makes two consumers of the same camera land on two
7009
+ * different physical pulls (e.g. Reolink `native:main` vs
7010
+ * `rtsp:main`) and trips the camera's concurrent-session limit.
7011
+ */
7012
+ getRtspEntries: method(
7013
+ object({
7014
+ deviceId: number().int().nonnegative(),
7015
+ /** Override hostname embedded in returned URLs. Defaults to the broker's bound address. */
7016
+ hostname: string().optional()
7017
+ }),
7018
+ array(RtspRestreamEntrySchema).readonly()
7019
+ ),
7020
+ /**
7021
+ * Per-device PROFILE RTSP restream entries — one per ASSIGNED
7022
+ * profile slot (high/mid/low). Each entry's `url` is a profile-keyed
7023
+ * broker restream that aliases the profile's assigned source broker,
7024
+ * so HAP / Alexa / recording / WebRTC all converge on the broker's
7025
+ * single on-demand pull for that profile. This is the supported
7026
+ * exporter-facing surface; the raw `getRtspEntries` is live-view
7027
+ * only. Returns `[]` for a device with no assigned profiles
7028
+ * (cold-start before first publish).
7029
+ */
7030
+ getProfileRtspEntries: method(
7031
+ object({
7032
+ deviceId: number().int().nonnegative(),
7033
+ /** Override hostname embedded in returned URLs. Defaults to the broker's bound address. */
7034
+ hostname: string().optional()
7035
+ }),
7036
+ array(ProfileRtspEntrySchema).readonly()
7037
+ ),
7038
+ /**
7039
+ * "Best source stream for these decode constraints". Returns the
7040
+ * camStreamId the caller should dial (or null when no stream
7041
+ * matches). See `PickStreamRequirementsSchema` for the filter shape
7042
+ * and `PickStreamPreferencesSchema` for the ranking inputs.
7043
+ *
7044
+ * Returning null instructs the caller to fall back to its existing
7045
+ * path (derived-broker transcode, profile-slot pick, etc.) — the
7046
+ * picker NEVER ranks `derived:*` candidates as a "match" because
7047
+ * its whole job is to avoid the transcode.
7048
+ */
7049
+ pickStream: method(
7050
+ object({
7051
+ deviceId: number().int().nonnegative(),
7052
+ requirements: PickStreamRequirementsSchema,
7053
+ preferences: PickStreamPreferencesSchema.optional()
7054
+ }),
7055
+ PickedCamStreamSchema.nullable()
7056
+ )
7057
+ },
7058
+ events: {
7059
+ /** Fires on publishCameraStream / retractCameraStream. */
7060
+ onCamStreamsChanged: event(object({
7061
+ deviceId: number().int().nonnegative(),
7062
+ camStreams: array(CameraStreamSchema).readonly()
7063
+ })),
7064
+ /** Fires on assignProfile / unassignProfile / runtime status change. */
7065
+ onProfileSlotsChanged: event(object({
7066
+ deviceId: number().int().nonnegative(),
7067
+ profileSlots: array(ProfileSlotSchema).readonly()
7068
+ }))
7069
+ },
7070
+ /**
7071
+ * Per-device live stream-broker state. Persistent settings (RTSP
7072
+ * tokens, profile assignments, pre-buffer config, RTSP-enabled toggles,
7073
+ * streamingDebug) stay in the broker's addon store — they survive
7074
+ * restarts. The slice below carries ONLY what's truly runtime:
7075
+ *
7076
+ * - `online` — at least one profile slot is currently `'streaming'`.
7077
+ * Drivers without a firmware liveness signal (RTSP, ONVIF…) can
7078
+ * subscribe and mirror this into `state.deviceStatus.online`.
7079
+ * - `slotStatuses` — current `ProfileSlotStatus` per profile,
7080
+ * mirroring the runtime-mutable subset of `ProfileSlot`.
7081
+ * - `slotErrors` — last error message per profile (only set when the
7082
+ * corresponding slot is in `'error'`).
7083
+ * - `lastChangedAt` — freshness signal for consumers that want to
7084
+ * reason about how stale the slice is.
7085
+ *
7086
+ * Written by the stream-broker manager on every transition that
7087
+ * affects these aggregates. Read via `device.state.cameraStreams.<field>`
7088
+ * (BaseDevice proxy) or, cross-process, via
7089
+ * `device-state.getCapSlice({deviceId, capName: 'camera-streams'})`.
7090
+ * The cap's `onChanged` event fires automatically on each write so
7091
+ * subscribers get push semantics for free.
7092
+ */
7093
+ runtimeState: object({
7094
+ online: boolean(),
7095
+ slotStatuses: object({
7096
+ high: ProfileSlotStatusSchema.optional(),
7097
+ mid: ProfileSlotStatusSchema.optional(),
7098
+ low: ProfileSlotStatusSchema.optional()
7099
+ }),
7100
+ slotErrors: object({
7101
+ high: string().optional(),
7102
+ mid: string().optional(),
7103
+ low: string().optional()
7104
+ }),
7105
+ lastChangedAt: number()
7106
+ })
7107
+ });
7108
+ object({
7109
+ detected: boolean(),
7110
+ /** Ms epoch of the last transition. 0 if never observed. */
7111
+ lastChangedAt: number()
7112
+ });
7113
+ ({
7114
+ deviceTypes: [DeviceType.Sensor]
7115
+ });
7116
+ const HvacModeSchema = _enum([
7117
+ "off",
7118
+ "heat",
7119
+ "cool",
7120
+ "auto",
7121
+ "heat_cool",
7122
+ "fan_only",
7123
+ "dry"
7124
+ ]);
7125
+ object({
7126
+ /** Active HVAC mode. */
7127
+ mode: HvacModeSchema,
7128
+ /** Available HVAC modes the device accepts. Subset of HvacMode. */
7129
+ availableModes: array(HvacModeSchema),
7130
+ /** Active fan mode (`auto` / `low` / `medium` / `high` / `on` / `off`
7131
+ * / vendor-specific) — empty string when the device has no fan
7132
+ * surface. */
7133
+ fanMode: string(),
7134
+ /** Available fan modes the device accepts. */
7135
+ availableFanModes: array(string()),
7136
+ /** Active preset (`eco` / `away` / `sleep` / vendor-specific) —
7137
+ * empty string when no preset is active or the device has no
7138
+ * preset surface. */
7139
+ preset: string(),
7140
+ /** Available presets the device accepts. */
7141
+ availablePresets: array(string()),
7142
+ /** Single setpoint in Celsius. Used by single-target modes
7143
+ * (heat / cool / dry). Null when the device is in a range mode
7144
+ * (`heat_cool`) or has no setpoint at all (`fan_only`/`off`). */
7145
+ target: number().nullable(),
7146
+ /** Upper bound of the dual setpoint in Celsius. Populated only
7147
+ * in `heat_cool` mode. */
7148
+ targetHigh: number().nullable(),
7149
+ /** Lower bound of the dual setpoint in Celsius. Populated only
7150
+ * in `heat_cool` mode. */
7151
+ targetLow: number().nullable(),
7152
+ /** Target relative humidity (0..100). Null when the device has no
7153
+ * humidity control. */
7154
+ targetHumidity: number().min(0).max(100).nullable(),
7155
+ /** Current measured temperature in Celsius. Read-only — pushed by
7156
+ * the device's internal sensor. */
7157
+ currentTemp: number().nullable(),
7158
+ /** Current measured relative humidity (0..100). Read-only. */
7159
+ currentHumidity: number().min(0).max(100).nullable(),
7160
+ /** Ms epoch when the slice was last updated (push or command). */
7161
+ lastFetchedAt: number()
7162
+ });
7163
+ ({
7164
+ deviceTypes: [DeviceType.Thermostat],
7165
+ methods: {
7166
+ setMode: method(
7167
+ object({
7168
+ deviceId: number().int().nonnegative(),
7169
+ mode: HvacModeSchema
7170
+ }),
7171
+ _void(),
7172
+ { kind: "mutation", auth: "admin" }
7173
+ ),
7174
+ setFanMode: method(
7175
+ object({
7176
+ deviceId: number().int().nonnegative(),
7177
+ fanMode: string().min(1)
7178
+ }),
7179
+ _void(),
7180
+ { kind: "mutation", auth: "admin" }
7181
+ ),
7182
+ setPreset: method(
7183
+ object({
7184
+ deviceId: number().int().nonnegative(),
7185
+ preset: string().min(1)
7186
+ }),
7187
+ _void(),
7188
+ { kind: "mutation", auth: "admin" }
7189
+ ),
7190
+ setTarget: method(
7191
+ object({
7192
+ deviceId: number().int().nonnegative(),
7193
+ target: number()
7194
+ }),
7195
+ _void(),
7196
+ { kind: "mutation", auth: "admin" }
7197
+ ),
7198
+ setTargetRange: method(
7199
+ object({
7200
+ deviceId: number().int().nonnegative(),
7201
+ targetLow: number(),
7202
+ targetHigh: number()
7203
+ }),
7204
+ _void(),
7205
+ { kind: "mutation", auth: "admin" }
7206
+ ),
7207
+ setTargetHumidity: method(
7208
+ object({
7209
+ deviceId: number().int().nonnegative(),
7210
+ targetHumidity: number().min(0).max(100)
7211
+ }),
7212
+ _void(),
7213
+ { kind: "mutation", auth: "admin" }
7214
+ )
7215
+ }
7216
+ });
7217
+ const RgbTripletSchema = object({
7218
+ r: number().int().min(0).max(255),
7219
+ g: number().int().min(0).max(255),
7220
+ b: number().int().min(0).max(255)
7221
+ });
7222
+ const HsvTripletSchema = object({
7223
+ /** Hue in degrees, 0..360. */
7224
+ h: number().min(0).max(360),
7225
+ /** Saturation as 0..100 inclusive. */
7226
+ s: number().min(0).max(100),
7227
+ /** Value/brightness as 0..100 inclusive. */
7228
+ v: number().min(0).max(100)
7229
+ });
7230
+ const ColorInputSchema = discriminatedUnion("mode", [
7231
+ object({ mode: literal("rgb"), rgb: RgbTripletSchema }),
7232
+ object({ mode: literal("hsv"), hsv: HsvTripletSchema }),
7233
+ object({ mode: literal("mired"), mireds: number().int().min(50).max(1e3) })
7234
+ ]);
7235
+ object({
7236
+ /** Active color mode — which of `rgb` / `hsv` / `mireds` reflects
7237
+ * the bulb's current state. */
7238
+ mode: _enum(["rgb", "hsv", "mired"]),
7239
+ /** Populated when `mode === 'rgb'`. */
7240
+ rgb: RgbTripletSchema.optional(),
7241
+ /** Populated when `mode === 'hsv'`. */
7242
+ hsv: HsvTripletSchema.optional(),
7243
+ /** Populated when `mode === 'mired'`. */
7244
+ mireds: number().int().optional(),
7245
+ /** Ms epoch of the last operator-driven change. */
7246
+ lastChangedAt: number()
7247
+ });
7248
+ ({
7249
+ deviceTypes: [DeviceType.Light],
7250
+ methods: {
7251
+ setColor: method(
7252
+ object({
7253
+ deviceId: number().int().nonnegative(),
7254
+ color: ColorInputSchema
7255
+ }),
7256
+ _void(),
7257
+ { kind: "mutation", auth: "admin" }
7258
+ )
7259
+ },
7260
+ events: {
7261
+ /**
7262
+ * Emitted whenever the color changes — operator action OR firmware
7263
+ * push. Subscribers (UI color pickers, automation engines) react
7264
+ * without polling.
7265
+ */
7266
+ onColorChanged: { data: object({
7267
+ deviceId: number(),
7268
+ mode: _enum(["rgb", "hsv", "mired"]),
7269
+ rgb: RgbTripletSchema.optional(),
7270
+ hsv: HsvTripletSchema.optional(),
7271
+ mireds: number().int().optional(),
7272
+ lastChangedAt: number()
7273
+ }) }
7274
+ }
7275
+ });
7276
+ object({
7277
+ /** True when the upstream system considers the entity connected. */
7278
+ connected: boolean(),
7279
+ /** Ms epoch of the last transition. 0 if never observed. */
7280
+ lastChangedAt: number()
7281
+ });
7282
+ ({
7283
+ deviceTypes: [DeviceType.Sensor]
7284
+ });
7285
+ const ConsumableItemSchema = object({
7286
+ /** Stable id, e.g. 'main-brush'. */
7287
+ key: string().min(1),
7288
+ /** Display name. */
7289
+ label: string().min(1),
7290
+ /** Remaining life % when known (0..100). */
7291
+ level: number().min(0).max(100).nullable(),
7292
+ /** Discrete state when known (binary mode). */
7293
+ status: _enum(["ok", "replace"]).nullable(),
7294
+ /** Ms epoch of the last replace, when known. */
7295
+ lastResetAt: number().nullable(),
7296
+ /** Whether `reset()` is meaningful for this item. */
7297
+ resettable: boolean()
7298
+ });
7299
+ const ConsumablesStatusSchema = object({
7300
+ items: array(ConsumableItemSchema),
7301
+ lastChangedAt: number()
7302
+ });
7303
+ ({
7304
+ // Device-agnostic — any device may expose consumables, so the cap
7305
+ // binds on EVERY DeviceType. The list enumerates every enum member
7306
+ // (kept in sync with `device-type.ts`) rather than a subset, so a
7307
+ // provider on any device type — vacuums/mowers included — can register
7308
+ // it and no future device type silently fails to bind.
7309
+ deviceTypes: [
7310
+ DeviceType.Camera,
7311
+ DeviceType.Hub,
7312
+ DeviceType.Light,
7313
+ DeviceType.Siren,
7314
+ DeviceType.Switch,
7315
+ DeviceType.Sensor,
7316
+ DeviceType.Thermostat,
7317
+ DeviceType.Button,
7318
+ DeviceType.EventEmitter,
7319
+ DeviceType.Update,
7320
+ DeviceType.Generic,
7321
+ DeviceType.Notifier,
7322
+ DeviceType.Script,
7323
+ DeviceType.Automation,
7324
+ DeviceType.Lock,
7325
+ DeviceType.Cover,
7326
+ DeviceType.Valve,
7327
+ DeviceType.Humidifier,
7328
+ DeviceType.WaterHeater,
7329
+ DeviceType.Fan,
7330
+ DeviceType.MediaPlayer,
7331
+ DeviceType.AlarmPanel,
7332
+ DeviceType.Control,
7333
+ DeviceType.Presence,
7334
+ DeviceType.Weather,
7335
+ DeviceType.Vacuum,
7336
+ DeviceType.LawnMower,
7337
+ DeviceType.Container,
7338
+ DeviceType.Image
7339
+ ],
7340
+ methods: {
7341
+ /** Mark a consumable as replaced — resets its remaining life. Only
7342
+ * meaningful when the item's `resettable` is true. */
7343
+ reset: method(
7344
+ object({ deviceId: number().int().nonnegative(), key: string().min(1) }),
7345
+ _void(),
7346
+ { kind: "mutation", auth: "admin" }
7347
+ )
7348
+ },
7349
+ // Per the cap checklist, runtimeState carries the bridge helper's
7350
+ // freshness field. The status surface stays the plain schema; only the
7351
+ // persistent slice gains `lastFetchedAt` so future poll-backed
7352
+ // providers can use the runtime-state bridge unchanged.
7353
+ runtimeState: ConsumablesStatusSchema.extend({ lastFetchedAt: number() })
7354
+ });
7355
+ object({
7356
+ /** True when the entry is open; false when closed. */
7357
+ entryOpen: boolean(),
7358
+ /** Ms epoch of the last open↔closed transition. 0 if never observed. */
7359
+ lastChangedAt: number()
7360
+ });
7361
+ ({
7362
+ deviceTypes: [DeviceType.Sensor]
7363
+ });
7364
+ const ControlKindSchema = _enum(["numeric", "select", "text", "datetime"]);
7365
+ object({
7366
+ kind: ControlKindSchema,
7367
+ /** Current value. Numeric kind → number; select/text/datetime → string.
7368
+ * Datetime values are ISO 8601 strings (full timestamp, date-only,
7369
+ * or time-only — HA accepts all three forms). */
7370
+ value: union([number(), string()]),
7371
+ /** Acceptable values when `kind === 'select'`. Empty for other kinds. */
7372
+ options: array(string()),
7373
+ /** Ms epoch when the slice was last updated. */
7374
+ lastChangedAt: number(),
7375
+ /** Display unit-of-measurement (e.g. '°C', '%', 'lx').
7376
+ * Populated live from HA `attributes.unit_of_measurement` on each push.
7377
+ * Meaningful for `kind === 'numeric'`; absent for other kinds. */
7378
+ unit: string().optional(),
7379
+ /** Minimum allowed value. Populated live from HA `attributes.min`.
7380
+ * Meaningful for `kind === 'numeric'`; absent for other kinds. */
7381
+ min: number().optional(),
7382
+ /** Maximum allowed value. Populated live from HA `attributes.max`.
7383
+ * Meaningful for `kind === 'numeric'`; absent for other kinds. */
7384
+ max: number().optional(),
7385
+ /** Step increment. Populated live from HA `attributes.step`.
7386
+ * Meaningful for `kind === 'numeric'`; absent for other kinds. */
7387
+ step: number().optional(),
7388
+ /** Suggested decimal places for numeric display. Populated live from HA
7389
+ * `attributes.suggested_display_precision`, or derived from `step` when the
7390
+ * HA attribute is absent. Meaningful for `kind === 'numeric'`; absent for
7391
+ * other kinds. Falls back to auto-formatting when absent. */
7392
+ precision: number().int().min(0).max(10).optional(),
7393
+ /** Date-picker granularity for `kind === 'datetime'`. 'date' → date-only,
7394
+ * 'time' → time-only, 'datetime' → full timestamp. Absent for other kinds
7395
+ * (UI defaults to 'datetime'). Derived live from the device's HA domain
7396
+ * (date.* / time.* / datetime.*) or, for input_datetime, from the entity's
7397
+ * `has_date`/`has_time` attributes on each push. */
7398
+ format: _enum(["date", "time", "datetime"]).optional()
7399
+ });
7400
+ const ControlSetValueInputSchema = discriminatedUnion("kind", [
7401
+ object({ kind: literal("numeric"), value: number() }),
7402
+ object({ kind: literal("select"), value: string().min(1) }),
7403
+ object({ kind: literal("text"), value: string() }),
7404
+ object({ kind: literal("datetime"), value: string().min(1) })
7405
+ ]);
7406
+ ({
7407
+ deviceTypes: [DeviceType.Control],
7408
+ methods: {
7409
+ setValue: method(
7410
+ object({
7411
+ deviceId: number().int().nonnegative(),
7412
+ control: ControlSetValueInputSchema
7413
+ }),
7414
+ _void(),
7415
+ { kind: "mutation", auth: "admin" }
7416
+ )
7417
+ }
7418
+ });
7419
+ const CoverStateSchema = _enum([
7420
+ "open",
7421
+ "opening",
7422
+ "closing",
7423
+ "closed",
7424
+ "stopped"
7425
+ ]);
7426
+ object({
7427
+ /** Lifecycle state of the cover. */
7428
+ state: CoverStateSchema,
7429
+ /** 0 = fully closed, 100 = fully open. Null when the device has
7430
+ * no intermediate position surface. */
7431
+ position: number().min(0).max(100).nullable(),
7432
+ /** 0 = closed slats, 100 = open slats. Null when no tilt support. */
7433
+ tiltPosition: number().min(0).max(100).nullable(),
7434
+ /** Ms epoch when the slice was last updated. */
7435
+ lastChangedAt: number()
7436
+ });
7437
+ ({
7438
+ deviceTypes: [DeviceType.Cover],
7439
+ methods: {
7440
+ open: method(
7441
+ object({ deviceId: number().int().nonnegative() }),
7442
+ _void(),
7443
+ { kind: "mutation", auth: "admin" }
7444
+ ),
7445
+ close: method(
7446
+ object({ deviceId: number().int().nonnegative() }),
7447
+ _void(),
7448
+ { kind: "mutation", auth: "admin" }
7449
+ ),
7450
+ stop: method(
7451
+ object({ deviceId: number().int().nonnegative() }),
7452
+ _void(),
7453
+ { kind: "mutation", auth: "admin" }
7454
+ ),
7455
+ setPosition: method(
7456
+ object({
7457
+ deviceId: number().int().nonnegative(),
7458
+ position: number().min(0).max(100)
7459
+ }),
7460
+ _void(),
7461
+ { kind: "mutation", auth: "admin" }
7462
+ ),
7463
+ setTiltPosition: method(
7464
+ object({
7465
+ deviceId: number().int().nonnegative(),
7466
+ tiltPosition: number().min(0).max(100)
7467
+ }),
7468
+ _void(),
7469
+ { kind: "mutation", auth: "admin" }
7470
+ )
7471
+ }
7472
+ });
7473
+ const SourceInfoSchema = object({
7474
+ // ── Identity (required) ─────────────────────────────────────────
7475
+ /** Live dispatch key — mutable when the source system allows rename. */
7476
+ id: string(),
7477
+ /** Source system tag — e.g. 'homeassistant' | 'reolink' | 'frigate'. */
7478
+ system: string(),
7479
+ // ── Stability (optional) ────────────────────────────────────────
7480
+ /** Immutable upstream identifier when available (HA `unique_id`, … ).
7481
+ * Used to detect rename when `id` changes. */
7482
+ uniqueId: string().optional(),
7483
+ // ── Free-form passthrough ───────────────────────────────────────
7484
+ /** Provider-specific extras that don't fit the structured slots.
7485
+ * Whitelist what goes here per provider — do NOT dump entire HA
7486
+ * attribute blobs (would explode the meta JSON column). */
7487
+ raw: record(string(), unknown()).optional()
7488
+ });
7489
+ const DiscoveredChildStatusSchema = _enum(["online", "sleeping", "offline", "unknown"]);
7490
+ const DiscoveredChildDeviceSchema = lazy(
7491
+ () => object({
7492
+ /** Stable, integration-defined identifier. Must be unique per parent and persistent across reboots. */
7493
+ childNativeId: string(),
7494
+ /** Friendly name as reported by the source (Reolink camera name, ONVIF profile, ...). */
7495
+ name: string(),
7496
+ /** DeviceType the child should be created with on adopt. */
7497
+ type: _enum(DeviceType),
7498
+ status: DiscoveredChildStatusSchema,
7499
+ /** Free-form integration-specific metadata surfaced in the panel. */
7500
+ metadata: object({
7501
+ model: string().optional(),
7502
+ serialNumber: string().optional(),
7503
+ uid: string().optional(),
7504
+ /** Reolink: 0-based channel index inside the parent NVR/Hub. */
7505
+ rtspChannel: number().int().nonnegative().optional(),
7506
+ isBattery: boolean().optional(),
7507
+ isDoorbell: boolean().optional(),
7508
+ isMultifocal: boolean().optional(),
7509
+ externalLocation: string().optional(),
7510
+ /** Vendor / manufacturer name as reported by the source (HA device
7511
+ * `manufacturer`, …). Surfaced in the adoption modal's fuzzy search. */
7512
+ manufacturer: string().optional(),
7513
+ /** Integration / platform domain the candidate belongs to (HA
7514
+ * `entity_registry.platform`, e.g. `dreame_vacuum`). Surfaced in the
7515
+ * adoption modal's fuzzy search. */
7516
+ integration: string().optional()
7517
+ }).default({}),
7518
+ /**
7519
+ * `true` when the framework already created a child device for this
7520
+ * `childNativeId` under the current parent. The panel uses it to
7521
+ * gate the Add/Remove button and surface the existing `deviceId`.
7522
+ */
7523
+ alreadyAdopted: boolean(),
7524
+ /** When `alreadyAdopted=true`, the framework-assigned child device id. */
7525
+ adoptedDeviceId: number().int().nonnegative().nullable(),
7526
+ /** Capability names the candidate advertises — integrations populate, Hubs omit. */
7527
+ capabilities: array(string()).readonly().optional(),
7528
+ /** Feature flags the candidate advertises — integrations populate, Hubs omit. */
7529
+ features: array(string()).readonly().optional(),
7530
+ /** Upstream-system identity + rendering hints for the candidate. */
7531
+ sourceInfo: SourceInfoSchema.optional(),
7532
+ /** Nested entity-children for accordion preview — integrations populate, Hubs omit. */
7533
+ children: array(DiscoveredChildDeviceSchema).readonly().optional()
7534
+ })
7535
+ );
7536
+ const DeviceDiscoveryStatusSchema = object({
7537
+ discovered: array(DiscoveredChildDeviceSchema),
7538
+ /** Wall-clock ms of the last successful enumeration. */
7539
+ lastDiscoveryAt: number().int().nonnegative().nullable(),
7540
+ /** Last error surfaced from the source (rendered as a banner). */
7541
+ lastError: string().nullable()
7542
+ });
7543
+ ({
7544
+ // Hub is the canonical parent. Other integrations (gateway-style)
7545
+ // can register against the cap by also targeting their root type.
7546
+ deviceTypes: [DeviceType.Hub],
7547
+ // Mirror status into the per-device runtime-state slice so the panel
7548
+ // hydrates from the kernel cache without a round-trip on every open.
7549
+ runtimeState: DeviceDiscoveryStatusSchema.extend({
7550
+ lastFetchedAt: number().int().nonnegative()
7551
+ }),
7552
+ methods: {
7553
+ /**
7554
+ * Snapshot of the current `discovered` list. Returns the
7555
+ * runtime-state cache — call `refreshDiscovery` first if a
7556
+ * fresh round-trip to the source is required.
7557
+ */
7558
+ listDiscovered: method(
7559
+ object({ deviceId: number().int().nonnegative() }),
7560
+ array(DiscoveredChildDeviceSchema).readonly()
7561
+ ),
7562
+ /**
7563
+ * Force the integration to re-enumerate and update the
7564
+ * runtime-state slice. Returns the freshly-enumerated list (also
7565
+ * available via `listDiscovered` post-call).
7566
+ */
7567
+ refreshDiscovery: method(
7568
+ object({ deviceId: number().int().nonnegative() }),
7569
+ array(DiscoveredChildDeviceSchema).readonly(),
7570
+ { kind: "mutation", auth: "admin" }
7571
+ ),
7572
+ /**
7573
+ * Promote a discovered entry to a real child device. The framework
7574
+ * creates the child via `kernel.devices.create()` with
7575
+ * `parentDeviceId = parent.id` and seeds the child's config from
7576
+ * `childInitialConfig` (driver-defined; usually carries channel +
7577
+ * uid + parent reference). Returns the kernel-assigned numeric id.
7578
+ */
7579
+ adoptDevice: method(
7580
+ object({
7581
+ deviceId: number().int().nonnegative(),
7582
+ childNativeId: string(),
7583
+ /** Optional override for the child's display name. */
7584
+ name: string().optional()
7585
+ }),
7586
+ object({
7587
+ deviceId: number().int().nonnegative(),
7588
+ stableId: string()
7589
+ }),
7590
+ { kind: "mutation", auth: "admin" }
7591
+ ),
7592
+ /**
7593
+ * Inverse of `adoptDevice`: removes the child device from the
7594
+ * kernel registry. The discovered entry remains in the
7595
+ * enumeration (status updates resume) so the operator can re-adopt
7596
+ * it later without a fresh refresh.
7597
+ */
7598
+ releaseDevice: method(
7599
+ object({
7600
+ deviceId: number().int().nonnegative(),
7601
+ childDeviceId: number().int().nonnegative()
7602
+ }),
7603
+ _void(),
7604
+ { kind: "mutation", auth: "admin" }
7605
+ )
7606
+ }
7607
+ });
7608
+ object({
7609
+ /** Ms epoch of the last press. null = never observed since this provider started. */
7610
+ lastPressedAt: number().nullable(),
7611
+ /** Counter since provider start. Resets on reboot. Useful for metrics/debug. */
7612
+ pressCountSinceStart: number()
7613
+ });
7614
+ object({
7615
+ deviceId: number(),
7616
+ timestamp: number()
7617
+ });
7618
+ ({
7619
+ deviceTypes: [DeviceType.Button]
7620
+ });
7621
+ const EnumSensorDateTimeFormatSchema = _enum(["date", "time", "datetime"]);
7622
+ object({
7623
+ value: string(),
7624
+ /**
7625
+ * Set for `DateTimeSensor`-role sensors so the UI renders the ISO `value`
7626
+ * as a locale date/time/datetime; absent for plain enum sensors. HA
7627
+ * `device_class=timestamp` → `'datetime'`, `device_class=date` → `'date'`,
7628
+ * a time-only sensor → `'time'`.
7629
+ */
7630
+ format: EnumSensorDateTimeFormatSchema.optional(),
7631
+ /** Ms epoch when the slice was last updated. */
7632
+ lastFetchedAt: number()
7633
+ });
7634
+ ({
7635
+ deviceTypes: [DeviceType.Sensor]
7636
+ });
7637
+ const EventFireSchema = object({
7638
+ deviceId: number(),
7639
+ eventType: string(),
7640
+ data: record(string(), unknown()).nullable(),
7641
+ timestamp: number(),
7642
+ seq: number()
7643
+ });
7644
+ object({
7645
+ eventTypes: array(string()),
7646
+ lastEvent: EventFireSchema.nullable(),
7647
+ eventCountSinceStart: number()
7648
+ });
7649
+ ({
7650
+ deviceTypes: [DeviceType.EventEmitter]
7651
+ });
7652
+ const FanDirectionSchema = _enum(["forward", "reverse"]);
7653
+ object({
7654
+ /** Active speed as 0..100 inclusive. Null when the device has no
7655
+ * speed surface (single-speed fan). */
7656
+ percentage: number().min(0).max(100).nullable(),
7657
+ /** Speed granularity the device accepts (HA `percentage_step`, e.g. 25 for
7658
+ * a 4-speed fan). Absent when unknown — the UI then falls back to step 1. */
7659
+ percentageStep: number().positive().optional(),
7660
+ /** Active preset mode (`auto` / `quiet` / `turbo` / vendor-specific)
7661
+ * — empty string when no preset is active or supported. */
7662
+ preset: string(),
7663
+ /** Available preset modes the device accepts. */
7664
+ availablePresets: array(string()),
7665
+ /** Ceiling-fan blade direction. Null when the device has no
7666
+ * direction surface. */
7667
+ direction: FanDirectionSchema.nullable(),
7668
+ /** Oscillation toggle. Null when the device has no oscillation
7669
+ * surface. */
7670
+ oscillating: boolean().nullable(),
7671
+ /** Ms epoch when the slice was last updated. */
7672
+ lastChangedAt: number()
7673
+ });
7674
+ ({
7675
+ deviceTypes: [DeviceType.Fan],
7676
+ methods: {
7677
+ setPercentage: method(
7678
+ object({
7679
+ deviceId: number().int().nonnegative(),
7680
+ percentage: number().min(0).max(100)
7681
+ }),
7682
+ _void(),
7683
+ { kind: "mutation", auth: "admin" }
7684
+ ),
7685
+ setPreset: method(
7686
+ object({
7687
+ deviceId: number().int().nonnegative(),
7688
+ preset: string().min(1)
7689
+ }),
7690
+ _void(),
7691
+ { kind: "mutation", auth: "admin" }
7692
+ ),
7693
+ setDirection: method(
7694
+ object({
7695
+ deviceId: number().int().nonnegative(),
7696
+ direction: FanDirectionSchema
7697
+ }),
7698
+ _void(),
7699
+ { kind: "mutation", auth: "admin" }
7700
+ ),
7701
+ setOscillating: method(
7702
+ object({
7703
+ deviceId: number().int().nonnegative(),
7704
+ oscillating: boolean()
7705
+ }),
7706
+ _void(),
7707
+ { kind: "mutation", auth: "admin" }
7708
+ )
7709
+ }
7710
+ });
7711
+ object({
7712
+ /** True when leak is currently detected. */
7713
+ flooded: boolean(),
7714
+ /** Ms epoch of the last flooded↔dry transition. 0 if never observed. */
7715
+ lastChangedAt: number()
7716
+ });
7717
+ ({
7718
+ deviceTypes: [DeviceType.Sensor]
7719
+ });
7720
+ object({
7721
+ detected: boolean(),
7722
+ /** Ms epoch of the last transition. 0 if never observed. */
7723
+ lastChangedAt: number()
7724
+ });
7725
+ ({
7726
+ deviceTypes: [DeviceType.Sensor]
7727
+ });
7728
+ object({
7729
+ /** Whether the humidifier is currently on. */
7730
+ on: boolean(),
7731
+ /** Current measured relative humidity (0..100). Null when not reported. */
7732
+ currentHumidity: number().min(0).max(100).nullable(),
7733
+ /** Target relative humidity (0..100). Null when no setpoint surface. */
7734
+ targetHumidity: number().min(0).max(100).nullable(),
7735
+ /** Active mode (`auto` / `normal` / `baby` / vendor). Null when the
7736
+ * device has no mode surface. */
7737
+ mode: string().nullable(),
7738
+ /** Available modes the device accepts. */
7739
+ availableModes: array(string()),
7740
+ /** HA `action` attribute, verbatim (`humidifying` / `drying` /
7741
+ * `idle` / `off`). Null when the device doesn't report it. */
7742
+ action: string().nullable(),
7743
+ /** HA `min_humidity` attribute. Null → UI uses 0. */
7744
+ minHumidity: number().nullable(),
7745
+ /** HA `max_humidity` attribute. Null → UI uses 100. */
7746
+ maxHumidity: number().nullable(),
7747
+ /** Ms epoch when the slice was last updated. */
7748
+ lastChangedAt: number()
7749
+ });
7750
+ ({
7751
+ deviceTypes: [DeviceType.Humidifier],
7752
+ methods: {
7753
+ setOn: method(
7754
+ object({
7755
+ deviceId: number().int().nonnegative(),
7756
+ on: boolean()
7757
+ }),
7758
+ _void(),
7759
+ { kind: "mutation", auth: "admin" }
7760
+ ),
7761
+ setTargetHumidity: method(
7762
+ object({
7763
+ deviceId: number().int().nonnegative(),
7764
+ humidity: number().min(0).max(100)
7765
+ }),
7766
+ _void(),
7767
+ { kind: "mutation", auth: "admin" }
7768
+ ),
7769
+ setMode: method(
7770
+ object({
7771
+ deviceId: number().int().nonnegative(),
7772
+ mode: string().min(1)
7773
+ }),
7774
+ _void(),
7775
+ { kind: "mutation", auth: "admin" }
7776
+ )
7777
+ }
7778
+ });
7779
+ object({
7780
+ /** Current relative humidity, 0..100. */
7781
+ percent: number().min(0).max(100),
7782
+ /** Ms epoch when the slice was last updated. */
7783
+ lastFetchedAt: number(),
7784
+ /** Live display unit from the upstream source (e.g. HA
7785
+ * `attributes.unit_of_measurement`). The UI prefers this over the
7786
+ * role's canonical unit. Absent → fall back to the canonical unit. */
7787
+ unit: string().optional(),
7788
+ /** Suggested decimal places for numeric display.
7789
+ * Populated live from the upstream source when provided (e.g. HA
7790
+ * `attributes.suggested_display_precision`). Falls back to
7791
+ * auto-formatting when absent. */
7792
+ precision: number().int().min(0).max(10).optional()
7793
+ });
7794
+ ({
7795
+ deviceTypes: [DeviceType.Sensor, DeviceType.Thermostat]
7796
+ });
7797
+ object({
7798
+ /** Absolute signed URL the browser loads directly. Null when the
7799
+ * entity exposes no `entity_picture` (yet). */
7800
+ url: string().nullable(),
7801
+ /** Ms epoch of the upstream last-updated timestamp. Null at cold-start. */
7802
+ lastUpdated: number().nullable()
7803
+ });
7804
+ ({
7805
+ deviceTypes: [DeviceType.Image]
7806
+ });
7807
+ const LawnMowerActivitySchema = _enum([
7808
+ "idle",
7809
+ "mowing",
7810
+ "paused",
7811
+ "docked",
7812
+ "error"
7813
+ ]);
7814
+ object({
7815
+ /** Lifecycle activity of the mower. */
7816
+ activity: LawnMowerActivitySchema,
7817
+ /** 0..100 battery percentage. Null when the device has no battery
7818
+ * reading. */
7819
+ batteryLevel: number().min(0).max(100).nullable(),
7820
+ /** Ms epoch when the slice was last updated. */
7821
+ lastChangedAt: number()
7822
+ });
6400
7823
  ({
6401
- deviceTypes: [DeviceType.Camera],
7824
+ deviceTypes: [DeviceType.LawnMower],
6402
7825
  methods: {
6403
- getCameraStreams: method(
7826
+ startMowing: method(
6404
7827
  object({ deviceId: number().int().nonnegative() }),
6405
- array(CameraStreamSchema).readonly()
7828
+ _void(),
7829
+ { kind: "mutation", auth: "admin" }
6406
7830
  ),
6407
- getBrokerStreams: method(
7831
+ pause: method(
6408
7832
  object({ deviceId: number().int().nonnegative() }),
6409
- array(ProfileSlotSchema).readonly()
7833
+ _void(),
7834
+ { kind: "mutation", auth: "admin" }
6410
7835
  ),
6411
- /**
6412
- * Per-device RTSP restream entries. Returns the broker's published
6413
- * RTSP URLs (one per `${deviceId}/${profile}`) for THIS device only,
6414
- * including the rendered `url` field with the RTSP token applied.
6415
- * Consumers (snapshot wrapper, recording, external probes) use this
6416
- * to pick a stream URL without scanning the whole cluster.
6417
- *
6418
- * The system `stream-broker.getAllRtspEntries({hostname?})` still
6419
- * exists for whole-cluster use cases (admin dashboard, settings
6420
- * exports). This device-scoped accessor is the supported handle for
6421
- * code that already has a `deviceId` in hand — keeps device-keyed
6422
- * filtering server-side and rides the DeviceProxy auto-injection.
6423
- */
6424
- getRtspEntries: method(
7836
+ dock: method(
7837
+ object({ deviceId: number().int().nonnegative() }),
7838
+ _void(),
7839
+ { kind: "mutation", auth: "admin" }
7840
+ )
7841
+ }
7842
+ });
7843
+ const LockStateSchema = _enum([
7844
+ "locked",
7845
+ "unlocked",
7846
+ "locking",
7847
+ "unlocking",
7848
+ "jammed"
7849
+ ]);
7850
+ object({
7851
+ /** Lifecycle state of the lock. `jammed` means the motor reported
7852
+ * failure to reach the target — operator intervention required. */
7853
+ state: LockStateSchema,
7854
+ /** Ms epoch when the slice was last updated. */
7855
+ lastChangedAt: number()
7856
+ });
7857
+ ({
7858
+ deviceTypes: [DeviceType.Lock],
7859
+ methods: {
7860
+ lock: method(
6425
7861
  object({
6426
7862
  deviceId: number().int().nonnegative(),
6427
- /** Override hostname embedded in returned URLs. Defaults to the broker's bound address. */
6428
- hostname: string().optional()
7863
+ /** Optional PIN code required by some keypad locks. NOT
7864
+ * persisted — passed directly to the upstream service. */
7865
+ code: string().min(1).optional()
6429
7866
  }),
6430
- array(RtspRestreamEntrySchema).readonly()
7867
+ _void(),
7868
+ { kind: "mutation", auth: "admin" }
7869
+ ),
7870
+ unlock: method(
7871
+ object({
7872
+ deviceId: number().int().nonnegative(),
7873
+ code: string().min(1).optional()
7874
+ }),
7875
+ _void(),
7876
+ { kind: "mutation", auth: "admin" }
7877
+ ),
7878
+ open: method(
7879
+ object({
7880
+ deviceId: number().int().nonnegative()
7881
+ }),
7882
+ _void(),
7883
+ { kind: "mutation", auth: "admin" }
6431
7884
  )
6432
- },
6433
- events: {
6434
- /** Fires on publishCameraStream / retractCameraStream. */
6435
- onCamStreamsChanged: event(object({
6436
- deviceId: number().int().nonnegative(),
6437
- camStreams: array(CameraStreamSchema).readonly()
6438
- })),
6439
- /** Fires on assignProfile / unassignProfile / runtime status change. */
6440
- onProfileSlotsChanged: event(object({
6441
- deviceId: number().int().nonnegative(),
6442
- profileSlots: array(ProfileSlotSchema).readonly()
6443
- }))
6444
- },
6445
- /**
6446
- * Per-device live stream-broker state. Persistent settings (RTSP
6447
- * tokens, profile assignments, pre-buffer config, RTSP-enabled toggles,
6448
- * streamingDebug) stay in the broker's addon store — they survive
6449
- * restarts. The slice below carries ONLY what's truly runtime:
6450
- *
6451
- * - `online` — at least one profile slot is currently `'streaming'`.
6452
- * Drivers without a firmware liveness signal (RTSP, ONVIF…) can
6453
- * subscribe and mirror this into `state.deviceStatus.online`.
6454
- * - `slotStatuses` — current `ProfileSlotStatus` per profile,
6455
- * mirroring the runtime-mutable subset of `ProfileSlot`.
6456
- * - `slotErrors` — last error message per profile (only set when the
6457
- * corresponding slot is in `'error'`).
6458
- * - `lastChangedAt` — freshness signal for consumers that want to
6459
- * reason about how stale the slice is.
6460
- *
6461
- * Written by the stream-broker manager on every transition that
6462
- * affects these aggregates. Read via `device.state.cameraStreams.<field>`
6463
- * (BaseDevice proxy) or, cross-process, via
6464
- * `device-state.getCapSlice({deviceId, capName: 'camera-streams'})`.
6465
- * The cap's `onChanged` event fires automatically on each write so
6466
- * subscribers get push semantics for free.
6467
- */
6468
- runtimeState: object({
6469
- online: boolean(),
6470
- slotStatuses: object({
6471
- high: ProfileSlotStatusSchema.optional(),
6472
- mid: ProfileSlotStatusSchema.optional(),
6473
- low: ProfileSlotStatusSchema.optional()
6474
- }),
6475
- slotErrors: object({
6476
- high: string().optional(),
6477
- mid: string().optional(),
6478
- low: string().optional()
6479
- }),
6480
- lastChangedAt: number()
6481
- })
7885
+ }
6482
7886
  });
6483
- const DiscoveredChildStatusSchema = _enum(["online", "sleeping", "offline", "unknown"]);
6484
- const DiscoveredChildDeviceSchema = object({
6485
- /** Stable, integration-defined identifier. Mirrors Scrypted's `nativeId`. */
6486
- childNativeId: string(),
6487
- /** Friendly name as reported by the source (Reolink camera name, ONVIF profile, ...). */
6488
- name: string(),
6489
- /** DeviceType the child should be created with on adopt. */
6490
- type: _enum(DeviceType),
6491
- status: DiscoveredChildStatusSchema,
6492
- /** Free-form integration-specific metadata surfaced in the panel. */
6493
- metadata: object({
6494
- model: string().optional(),
6495
- serialNumber: string().optional(),
6496
- uid: string().optional(),
6497
- /** Reolink: 0-based channel index inside the parent NVR/Hub. */
6498
- rtspChannel: number().int().nonnegative().optional(),
6499
- isBattery: boolean().optional(),
6500
- isDoorbell: boolean().optional(),
6501
- isMultifocal: boolean().optional()
6502
- }).default({}),
6503
- /**
6504
- * `true` when the framework already created a child device for this
6505
- * `childNativeId` under the current parent. The panel uses it to
6506
- * gate the Add/Remove button and surface the existing `deviceId`.
6507
- */
6508
- alreadyAdopted: boolean(),
6509
- /** When `alreadyAdopted=true`, the framework-assigned child device id. */
6510
- adoptedDeviceId: number().int().nonnegative().nullable()
7887
+ const MediaPlayerStateSchema = _enum([
7888
+ "off",
7889
+ "on",
7890
+ "idle",
7891
+ "playing",
7892
+ "paused",
7893
+ "buffering",
7894
+ "standby"
7895
+ ]);
7896
+ const MediaPlayerRepeatSchema = _enum(["off", "all", "one"]);
7897
+ const MediaInfoSchema = object({
7898
+ /** Free-form media kind (`music`, `tvshow`, `movie`, `app`, `channel`,
7899
+ * `podcast`, ). */
7900
+ type: string(),
7901
+ /** Human-readable title. */
7902
+ title: string(),
7903
+ /** Optional artist / channel / station label. */
7904
+ artist: string().optional(),
7905
+ /** Optional album / season / show name. */
7906
+ album: string().optional(),
7907
+ /** Optional cover-art / thumbnail URL. */
7908
+ imageUrl: string().optional()
6511
7909
  });
6512
- const DeviceDiscoveryStatusSchema = object({
6513
- discovered: array(DiscoveredChildDeviceSchema),
6514
- /** Wall-clock ms of the last successful enumeration. */
6515
- lastDiscoveryAt: number().int().nonnegative().nullable(),
6516
- /** Last error surfaced from the source (rendered as a banner). */
6517
- lastError: string().nullable()
7910
+ object({
7911
+ /** Playback lifecycle state. */
7912
+ state: MediaPlayerStateSchema,
7913
+ /** Volume as 0..100 inclusive. Null when the device has no volume
7914
+ * surface. Pair with `DeviceFeature.MediaPlayerVolume`. */
7915
+ volumeLevel: number().min(0).max(100).nullable(),
7916
+ /** Mute toggle distinct from volume=0. Null when no mute surface.
7917
+ * Pair with `DeviceFeature.MediaPlayerMute`. */
7918
+ isMuted: boolean().nullable(),
7919
+ /** Active source / input. Empty when no source surface. */
7920
+ source: string(),
7921
+ /** Selectable sources. Empty when no source surface.
7922
+ * Pair with `DeviceFeature.MediaPlayerSelectSource`. */
7923
+ availableSources: array(string()),
7924
+ /** Currently-playing media info. Null when nothing is playing. */
7925
+ currentMedia: MediaInfoSchema.nullable(),
7926
+ /** Current playback position in ms. Null when not seekable or
7927
+ * nothing is playing. Pair with `DeviceFeature.MediaPlayerSeek`. */
7928
+ positionMs: number().int().nonnegative().nullable(),
7929
+ /** Total duration of the current media in ms. Null when unknown
7930
+ * (live stream) or nothing is playing. */
7931
+ durationMs: number().int().nonnegative().nullable(),
7932
+ /** Shuffle toggle. Null when no shuffle surface.
7933
+ * Pair with `DeviceFeature.MediaPlayerShuffle`. */
7934
+ shuffle: boolean().nullable(),
7935
+ /** Repeat mode. Null when no repeat surface.
7936
+ * Pair with `DeviceFeature.MediaPlayerRepeat`. */
7937
+ repeat: MediaPlayerRepeatSchema.nullable(),
7938
+ /** Ms epoch when the slice was last updated. */
7939
+ lastChangedAt: number()
6518
7940
  });
6519
7941
  ({
6520
- // Hub is the canonical parent. Other integrations (gateway-style)
6521
- // can register against the cap by also targeting their root type.
6522
- deviceTypes: [DeviceType.Hub],
6523
- // Mirror status into the per-device runtime-state slice so the panel
6524
- // hydrates from the kernel cache without a round-trip on every open.
6525
- runtimeState: DeviceDiscoveryStatusSchema.extend({
6526
- lastFetchedAt: number().int().nonnegative()
6527
- }),
7942
+ deviceTypes: [DeviceType.MediaPlayer],
6528
7943
  methods: {
6529
- /**
6530
- * Snapshot of the current `discovered` list. Returns the
6531
- * runtime-state cache — call `refreshDiscovery` first if a
6532
- * fresh round-trip to the source is required.
6533
- */
6534
- listDiscovered: method(
7944
+ play: method(
6535
7945
  object({ deviceId: number().int().nonnegative() }),
6536
- array(DiscoveredChildDeviceSchema).readonly()
7946
+ _void(),
7947
+ { kind: "mutation", auth: "admin" }
6537
7948
  ),
6538
- /**
6539
- * Force the integration to re-enumerate and update the
6540
- * runtime-state slice. Returns the freshly-enumerated list (also
6541
- * available via `listDiscovered` post-call).
6542
- */
6543
- refreshDiscovery: method(
7949
+ pause: method(
6544
7950
  object({ deviceId: number().int().nonnegative() }),
6545
- array(DiscoveredChildDeviceSchema).readonly(),
7951
+ _void(),
6546
7952
  { kind: "mutation", auth: "admin" }
6547
7953
  ),
6548
- /**
6549
- * Promote a discovered entry to a real child device. The framework
6550
- * creates the child via `kernel.devices.create()` with
6551
- * `parentDeviceId = parent.id` and seeds the child's config from
6552
- * `childInitialConfig` (driver-defined; usually carries channel +
6553
- * uid + parent reference). Returns the kernel-assigned numeric id.
6554
- */
6555
- adoptDevice: method(
7954
+ stop: method(
7955
+ object({ deviceId: number().int().nonnegative() }),
7956
+ _void(),
7957
+ { kind: "mutation", auth: "admin" }
7958
+ ),
7959
+ next: method(
7960
+ object({ deviceId: number().int().nonnegative() }),
7961
+ _void(),
7962
+ { kind: "mutation", auth: "admin" }
7963
+ ),
7964
+ previous: method(
7965
+ object({ deviceId: number().int().nonnegative() }),
7966
+ _void(),
7967
+ { kind: "mutation", auth: "admin" }
7968
+ ),
7969
+ seek: method(
6556
7970
  object({
6557
7971
  deviceId: number().int().nonnegative(),
6558
- childNativeId: string(),
6559
- /** Optional override for the child's display name. */
6560
- name: string().optional()
7972
+ positionMs: number().int().nonnegative()
6561
7973
  }),
7974
+ _void(),
7975
+ { kind: "mutation", auth: "admin" }
7976
+ ),
7977
+ setVolume: method(
6562
7978
  object({
6563
7979
  deviceId: number().int().nonnegative(),
6564
- stableId: string()
7980
+ volumeLevel: number().min(0).max(100)
6565
7981
  }),
7982
+ _void(),
6566
7983
  { kind: "mutation", auth: "admin" }
6567
7984
  ),
6568
- /**
6569
- * Inverse of `adoptDevice`: removes the child device from the
6570
- * kernel registry. The discovered entry remains in the
6571
- * enumeration (status updates resume) so the operator can re-adopt
6572
- * it later without a fresh refresh.
6573
- */
6574
- releaseDevice: method(
7985
+ setMute: method(
6575
7986
  object({
6576
7987
  deviceId: number().int().nonnegative(),
6577
- childDeviceId: number().int().nonnegative()
7988
+ muted: boolean()
7989
+ }),
7990
+ _void(),
7991
+ { kind: "mutation", auth: "admin" }
7992
+ ),
7993
+ setShuffle: method(
7994
+ object({
7995
+ deviceId: number().int().nonnegative(),
7996
+ shuffle: boolean()
7997
+ }),
7998
+ _void(),
7999
+ { kind: "mutation", auth: "admin" }
8000
+ ),
8001
+ setRepeat: method(
8002
+ object({
8003
+ deviceId: number().int().nonnegative(),
8004
+ repeat: MediaPlayerRepeatSchema
8005
+ }),
8006
+ _void(),
8007
+ { kind: "mutation", auth: "admin" }
8008
+ ),
8009
+ selectSource: method(
8010
+ object({
8011
+ deviceId: number().int().nonnegative(),
8012
+ source: string().min(1)
8013
+ }),
8014
+ _void(),
8015
+ { kind: "mutation", auth: "admin" }
8016
+ ),
8017
+ playMedia: method(
8018
+ object({
8019
+ deviceId: number().int().nonnegative(),
8020
+ /** Media identifier / URL. */
8021
+ mediaId: string().min(1),
8022
+ /** Media kind (`music`, `tvshow`, `movie`, `app`, …) — provider
8023
+ * passes it through to the upstream service. */
8024
+ mediaType: string().min(1)
6578
8025
  }),
6579
8026
  _void(),
6580
8027
  { kind: "mutation", auth: "admin" }
6581
8028
  )
6582
8029
  }
6583
8030
  });
6584
- object({
6585
- /** Ms epoch of the last press. null = never observed since this provider started. */
6586
- lastPressedAt: number().nullable(),
6587
- /** Counter since provider start. Resets on reboot. Useful for metrics/debug. */
6588
- pressCountSinceStart: number()
6589
- });
6590
- object({
6591
- deviceId: number(),
6592
- timestamp: number()
6593
- });
6594
- ({
6595
- deviceTypes: [DeviceType.Button]
6596
- });
6597
8031
  const FrameFormatSchema = _enum(["jpeg", "rgb", "bgr", "yuv420", "gray"]);
6598
8032
  const FrameInputSchema = object({
6599
8033
  data: custom(),
@@ -7000,8 +8434,8 @@ const PipelineRunResultBridge = custom();
7000
8434
  * calls. Single root step + uniform model assumed; trees with crop
7001
8435
  * children fall back to sequential execution.
7002
8436
  *
7003
- * Used by `scripts/bench-scrypted-style.mts` to mirror Scrypted's
7004
- * `detectObjects(media, {batch})` semantics for fair comparison.
8437
+ * Used by `scripts/bench-batch-style.mts` for batch benchmarking —
8438
+ * N frames in one call to amortise per-call IPC overhead.
7005
8439
  */
7006
8440
  runPipelineBatch: method(
7007
8441
  object({
@@ -7382,8 +8816,8 @@ object({
7382
8816
  lastDetectedAt: number().nullable(),
7383
8817
  /**
7384
8818
  * Ms after which `detected` auto-reverts to false if no fresh push
7385
- * arrives. Mirrors the scrypted-reolink-native default. Null means
7386
- * the provider leaves detected state until a native "clear" event.
8819
+ * arrives. Null means the provider leaves detected state until a
8820
+ * native "clear" event.
7387
8821
  */
7388
8822
  autoClearAfterMs: number().nullable()
7389
8823
  });
@@ -7569,6 +9003,194 @@ NativeObjectDetectionStatusSchema.extend({
7569
9003
  }) }
7570
9004
  }
7571
9005
  });
9006
+ const NotifierPrioritySchema = _enum(["min", "low", "normal", "high"]);
9007
+ const NotifierActionSchema = object({
9008
+ /** Stable id used in the callback when the user taps the button. */
9009
+ id: string().min(1),
9010
+ /** User-visible button label. */
9011
+ title: string().min(1),
9012
+ /** Optional deep-link URI invoked on tap (rich notifiers only). */
9013
+ uri: url().optional(),
9014
+ /** Optional flag — when true, the action is destructive and the
9015
+ * client should render the button in a warning style. */
9016
+ destructive: boolean().optional()
9017
+ });
9018
+ const NotifierSupportsSchema = object({
9019
+ /** Inline / URL image attachment. Pair with `DeviceFeature.NotifierImage`. */
9020
+ image: boolean(),
9021
+ /** Priority hint. Pair with `DeviceFeature.NotifierPriority`. */
9022
+ priority: boolean(),
9023
+ /** Free-form platform-specific data block.
9024
+ * Pair with `DeviceFeature.NotifierData`. */
9025
+ data: boolean(),
9026
+ /** Interactive action buttons. Pair with `DeviceFeature.NotifierActions`. */
9027
+ actions: boolean(),
9028
+ /** Per-call recipient targeting (multi-user notifiers).
9029
+ * Pair with `DeviceFeature.NotifierRecipients`. */
9030
+ recipients: boolean()
9031
+ });
9032
+ object({
9033
+ /** Ms epoch of the most recent successful send. 0 if none yet. */
9034
+ lastSentAt: number(),
9035
+ /** Failure description from the most recent send attempt. Null on
9036
+ * success or when nothing has been sent yet. */
9037
+ lastError: string().nullable(),
9038
+ /** Number of deliveries currently buffered server-side (rate-limited
9039
+ * notifiers may queue). 0 when the provider sends synchronously. */
9040
+ queueDepth: number().int().nonnegative(),
9041
+ /** Per-feature capability matrix — authoritative source for the
9042
+ * compose-form field gating. */
9043
+ supports: NotifierSupportsSchema
9044
+ });
9045
+ const NotifierSendInputSchema = object({
9046
+ deviceId: number().int().nonnegative(),
9047
+ /** Optional title — many platforms render it bolder than the body. */
9048
+ title: string().optional(),
9049
+ /** Required message body. */
9050
+ body: string().min(1),
9051
+ /** Optional image URL or inline data URI (`data:image/...;base64,...`). */
9052
+ image: string().optional(),
9053
+ /** Priority hint — providers without priority support ignore the field. */
9054
+ priority: NotifierPrioritySchema.optional(),
9055
+ /** Channel / topic / tag the notifier should route through (Android
9056
+ * notification channel, Telegram chat id, ntfy topic, …). */
9057
+ channel: string().optional(),
9058
+ /** Optional list of recipient ids (multi-user notifiers). Empty /
9059
+ * omitted = the device's default recipient. */
9060
+ recipients: array(string()).optional(),
9061
+ /** Optional interactive action buttons. */
9062
+ actions: array(NotifierActionSchema).optional(),
9063
+ /** Free-form platform-specific payload — passed through to the
9064
+ * upstream service untouched. */
9065
+ data: record(string(), unknown()).optional()
9066
+ });
9067
+ const NotifierSendResultSchema = object({
9068
+ /** Provider-assigned id for the delivery. Used for `cancel`. */
9069
+ notificationId: string(),
9070
+ /** Ms epoch when the notifier accepted the send (not when delivered). */
9071
+ acceptedAt: number()
9072
+ });
9073
+ ({
9074
+ deviceTypes: [DeviceType.Notifier],
9075
+ methods: {
9076
+ send: method(
9077
+ NotifierSendInputSchema,
9078
+ NotifierSendResultSchema,
9079
+ { kind: "mutation", auth: "admin" }
9080
+ ),
9081
+ cancel: method(
9082
+ object({
9083
+ deviceId: number().int().nonnegative(),
9084
+ notificationId: string().min(1)
9085
+ }),
9086
+ _void(),
9087
+ { kind: "mutation", auth: "admin" }
9088
+ )
9089
+ },
9090
+ events: {
9091
+ /**
9092
+ * Emitted after every send attempt — success or failure. Subscribers
9093
+ * (admin UI history pane, automation engines, retry workers) react
9094
+ * without polling the provider's `lastSentAt`.
9095
+ */
9096
+ onSent: { data: object({
9097
+ deviceId: number(),
9098
+ notificationId: string(),
9099
+ success: boolean(),
9100
+ error: string().nullable(),
9101
+ acceptedAt: number()
9102
+ }) }
9103
+ }
9104
+ });
9105
+ object({
9106
+ value: number(),
9107
+ /** Display unit-of-measurement (e.g. 'dBm', 's', 'rpm', 'steps').
9108
+ * Populated live from the upstream source on each state push.
9109
+ * Absent for unitless sensors. */
9110
+ unit: string().optional(),
9111
+ /** Suggested decimal places for numeric display.
9112
+ * Populated live from the upstream source when provided.
9113
+ * Falls back to auto-formatting when absent. */
9114
+ precision: number().int().min(0).max(10).optional(),
9115
+ /** Ms epoch when the slice was last updated. */
9116
+ lastFetchedAt: number()
9117
+ });
9118
+ ({
9119
+ deviceTypes: [DeviceType.Sensor]
9120
+ });
9121
+ object({
9122
+ /** Instantaneous power draw in watts. */
9123
+ watts: number().optional(),
9124
+ /** Cumulative energy in kilowatt-hours since the meter was reset. */
9125
+ kwhTotal: number().optional(),
9126
+ /** Voltage in volts. */
9127
+ volts: number().optional(),
9128
+ /** Current in amperes. */
9129
+ amps: number().optional(),
9130
+ /** Apparent power in volt-amperes (W × power-factor reciprocal). */
9131
+ va: number().optional(),
9132
+ /** Power factor (0..1) if reported. */
9133
+ powerFactor: number().min(0).max(1).optional(),
9134
+ /** Ms epoch when the slice was last updated. */
9135
+ lastFetchedAt: number(),
9136
+ /** Live display unit of the single metric this slice carries (e.g. HA
9137
+ * `attributes.unit_of_measurement` → 'V' / 'A' / 'W' / 'kW' / 'kWh').
9138
+ * Each upstream `sensor.*` entity surfaces ONE device_class, so one
9139
+ * unit per slice is unambiguous. The UI prefers this over the role's
9140
+ * canonical unit so a 'kW' / 'Wh' feed renders verbatim. */
9141
+ unit: string().optional(),
9142
+ /** Suggested decimal places for numeric display.
9143
+ * Populated live from the upstream source when provided (e.g. HA
9144
+ * `attributes.suggested_display_precision`). Falls back to
9145
+ * auto-formatting when absent. */
9146
+ precision: number().int().min(0).max(10).optional()
9147
+ });
9148
+ ({
9149
+ deviceTypes: [DeviceType.Sensor]
9150
+ });
9151
+ const GpsLocationSchema = object({
9152
+ /** Latitude in decimal degrees, -90..90. */
9153
+ latitude: number().min(-90).max(90),
9154
+ /** Longitude in decimal degrees, -180..180. */
9155
+ longitude: number().min(-180).max(180),
9156
+ /** Reported accuracy in meters (lower = better). */
9157
+ accuracyMeters: number().nonnegative()
9158
+ });
9159
+ object({
9160
+ /** `home` / `not_home` / any user-defined zone name. */
9161
+ state: string(),
9162
+ /** Optional textual location label (zone name, city, address). Null
9163
+ * when only the binary state is known. */
9164
+ location: string().nullable(),
9165
+ /** GPS coordinates when available. Null otherwise. */
9166
+ gps: GpsLocationSchema.nullable(),
9167
+ /** Optional battery level of the tracking device (0..100). Null
9168
+ * when not reported. */
9169
+ batteryPercent: number().min(0).max(100).nullable(),
9170
+ /** Ms epoch when the slice was last updated. */
9171
+ lastChangedAt: number()
9172
+ });
9173
+ ({
9174
+ deviceTypes: [DeviceType.Presence]
9175
+ });
9176
+ object({
9177
+ /** Current pressure in hPa. */
9178
+ hpa: number(),
9179
+ /** Ms epoch when the slice was last updated. */
9180
+ lastFetchedAt: number(),
9181
+ /** Live display unit from the upstream source (e.g. HA
9182
+ * `attributes.unit_of_measurement`). The UI prefers this over the
9183
+ * role's canonical unit. Absent → fall back to the canonical unit. */
9184
+ unit: string().optional(),
9185
+ /** Suggested decimal places for numeric display.
9186
+ * Populated live from the upstream source when provided (e.g. HA
9187
+ * `attributes.suggested_display_precision`). Falls back to
9188
+ * auto-formatting when absent. */
9189
+ precision: number().int().min(0).max(10).optional()
9190
+ });
9191
+ ({
9192
+ deviceTypes: [DeviceType.Sensor]
9193
+ });
7572
9194
  const PrivacyMaskShapeSchema = discriminatedUnion("kind", [
7573
9195
  MaskRectShapeSchema,
7574
9196
  MaskPolygonShapeSchema
@@ -7697,6 +9319,51 @@ PtzAutotrackStatusSchema.extend({
7697
9319
  }) }
7698
9320
  }
7699
9321
  });
9322
+ object({
9323
+ /** Whether the script is currently executing. */
9324
+ isRunning: boolean(),
9325
+ /** Ms epoch of the last invocation start. 0 when never run. */
9326
+ lastRunAt: number(),
9327
+ /** Outcome of the last completed run. Null when never run or still
9328
+ * running. */
9329
+ lastRunSuccess: boolean().nullable(),
9330
+ /** Failure description from the last completed run. Null on success
9331
+ * or when never run. */
9332
+ lastError: string().nullable(),
9333
+ /** Ms epoch when the slice was last updated. */
9334
+ lastChangedAt: number()
9335
+ });
9336
+ ({
9337
+ deviceTypes: [DeviceType.Script],
9338
+ methods: {
9339
+ run: method(
9340
+ object({
9341
+ deviceId: number().int().nonnegative(),
9342
+ /** Optional variables map — passed through to the upstream
9343
+ * script. Provider rejects when the script doesn't declare
9344
+ * input fields (gated by `DeviceFeature.ScriptVariables`). */
9345
+ variables: record(string(), unknown()).optional()
9346
+ }),
9347
+ _void(),
9348
+ { kind: "mutation", auth: "admin" }
9349
+ ),
9350
+ /** Cancel a running script. Provider rejects when the script
9351
+ * isn't currently running. */
9352
+ stop: method(
9353
+ object({ deviceId: number().int().nonnegative() }),
9354
+ _void(),
9355
+ { kind: "mutation", auth: "admin" }
9356
+ )
9357
+ }
9358
+ });
9359
+ object({
9360
+ detected: boolean(),
9361
+ /** Ms epoch of the last transition. 0 if never observed. */
9362
+ lastChangedAt: number()
9363
+ });
9364
+ ({
9365
+ deviceTypes: [DeviceType.Sensor]
9366
+ });
7700
9367
  const StreamProfileSchema = _enum(["main", "sub", "ext"]);
7701
9368
  const StreamProfileConfigSchema = object({
7702
9369
  width: number(),
@@ -7813,6 +9480,257 @@ object({
7813
9480
  }) }
7814
9481
  }
7815
9482
  });
9483
+ object({
9484
+ /** True when the device's tamper switch / case-open contact is
9485
+ * currently triggered. */
9486
+ tampered: boolean(),
9487
+ /** Ms epoch of the last transition. 0 if never observed. */
9488
+ lastChangedAt: number()
9489
+ });
9490
+ ({
9491
+ deviceTypes: [DeviceType.Sensor]
9492
+ });
9493
+ object({
9494
+ /** Current temperature in Celsius. */
9495
+ celsius: number(),
9496
+ /** Ms epoch when the slice was last updated (push or poll). */
9497
+ lastFetchedAt: number(),
9498
+ /** Live display unit from the upstream source (e.g. HA
9499
+ * `attributes.unit_of_measurement`). The UI prefers this over the
9500
+ * role's canonical unit, so a Fahrenheit feed renders '°F' not '°C'.
9501
+ * Absent → the UI falls back to the role's canonical unit. */
9502
+ unit: string().optional(),
9503
+ /** Suggested decimal places for numeric display.
9504
+ * Populated live from the upstream source when provided (e.g. HA
9505
+ * `attributes.suggested_display_precision`). Falls back to
9506
+ * auto-formatting when absent. */
9507
+ precision: number().int().min(0).max(10).optional()
9508
+ });
9509
+ ({
9510
+ deviceTypes: [DeviceType.Sensor, DeviceType.Thermostat]
9511
+ });
9512
+ object({
9513
+ currentVersion: string().nullable(),
9514
+ availableVersion: string().nullable(),
9515
+ /**
9516
+ * DEVICE-CAPABILITY flag: the entity supports firmware updates at all — NOT
9517
+ * a per-state "an update is available right now" flag. The canonical
9518
+ * "update available" signal is `availableVersion !== currentVersion` (which
9519
+ * is what the UI uses); HA's `state === 'on'` mirrors that same condition.
9520
+ */
9521
+ updatable: boolean(),
9522
+ state: string().nullable(),
9523
+ // e.g. 'UP_TO_DATE' / 'DELIVER_FIRMWARE_IMAGE' (provider-verbatim)
9524
+ inProgress: boolean()
9525
+ });
9526
+ ({
9527
+ deviceTypes: [DeviceType.Update],
9528
+ methods: {
9529
+ installUpdate: method(_void(), _void(), { kind: "mutation", auth: "admin" })
9530
+ }
9531
+ });
9532
+ const VacuumStateSchema = _enum([
9533
+ "idle",
9534
+ "cleaning",
9535
+ "paused",
9536
+ "returning",
9537
+ "docked",
9538
+ "error"
9539
+ ]);
9540
+ const TankStatusSchema = object({
9541
+ /** Numeric fill 0..100 when the hardware reports a percentage; null otherwise. */
9542
+ level: number().min(0).max(100).nullable(),
9543
+ /** Discrete state when the hardware is binary-mode; null otherwise. */
9544
+ status: _enum(["ok", "low", "full"]).nullable()
9545
+ });
9546
+ object({
9547
+ /** Lifecycle state of the vacuum. */
9548
+ state: VacuumStateSchema,
9549
+ /** 0..100 battery percentage. Null when the device has no battery
9550
+ * reading. */
9551
+ batteryLevel: number().min(0).max(100).nullable(),
9552
+ /** Current fan-speed token (provider-verbatim). Null when unknown or
9553
+ * the vacuum has no speed control. */
9554
+ fanSpeed: string().nullable(),
9555
+ /** Speed tokens the hardware accepts — drives the UI selector. */
9556
+ availableFanSpeeds: array(string()),
9557
+ /** Clean-water (mop) tank. Null when the hardware has no clean-water tank. */
9558
+ cleanWater: TankStatusSchema.nullable(),
9559
+ /** Dirty-water (recovery) tank. Null when the hardware has no dirty-water tank. */
9560
+ dirtyWater: TankStatusSchema.nullable(),
9561
+ /** Detergent tank. Null when the hardware has no detergent tank. */
9562
+ detergent: TankStatusSchema.nullable(),
9563
+ /** Dust bin. Null when the hardware has no dust bin. */
9564
+ dustBin: TankStatusSchema.nullable(),
9565
+ /** Ms epoch when the slice was last updated. */
9566
+ lastChangedAt: number()
9567
+ });
9568
+ ({
9569
+ deviceTypes: [DeviceType.Vacuum],
9570
+ methods: {
9571
+ start: method(
9572
+ object({ deviceId: number().int().nonnegative() }),
9573
+ _void(),
9574
+ { kind: "mutation", auth: "admin" }
9575
+ ),
9576
+ pause: method(
9577
+ object({ deviceId: number().int().nonnegative() }),
9578
+ _void(),
9579
+ { kind: "mutation", auth: "admin" }
9580
+ ),
9581
+ stop: method(
9582
+ object({ deviceId: number().int().nonnegative() }),
9583
+ _void(),
9584
+ { kind: "mutation", auth: "admin" }
9585
+ ),
9586
+ returnToBase: method(
9587
+ object({ deviceId: number().int().nonnegative() }),
9588
+ _void(),
9589
+ { kind: "mutation", auth: "admin" }
9590
+ ),
9591
+ locate: method(
9592
+ object({ deviceId: number().int().nonnegative() }),
9593
+ _void(),
9594
+ { kind: "mutation", auth: "admin" }
9595
+ ),
9596
+ setFanSpeed: method(
9597
+ object({
9598
+ deviceId: number().int().nonnegative(),
9599
+ speed: string().min(1)
9600
+ }),
9601
+ _void(),
9602
+ { kind: "mutation", auth: "admin" }
9603
+ )
9604
+ }
9605
+ });
9606
+ const ValveStateSchema = _enum([
9607
+ "open",
9608
+ "opening",
9609
+ "closing",
9610
+ "closed",
9611
+ "stopped"
9612
+ ]);
9613
+ object({
9614
+ /** Lifecycle state of the valve. */
9615
+ state: ValveStateSchema,
9616
+ /** 0 = fully closed, 100 = fully open. Null when the device has no
9617
+ * intermediate position surface. */
9618
+ position: number().min(0).max(100).nullable(),
9619
+ /** Ms epoch when the slice was last updated. */
9620
+ lastChangedAt: number()
9621
+ });
9622
+ ({
9623
+ deviceTypes: [DeviceType.Valve],
9624
+ methods: {
9625
+ open: method(
9626
+ object({ deviceId: number().int().nonnegative() }),
9627
+ _void(),
9628
+ { kind: "mutation", auth: "admin" }
9629
+ ),
9630
+ close: method(
9631
+ object({ deviceId: number().int().nonnegative() }),
9632
+ _void(),
9633
+ { kind: "mutation", auth: "admin" }
9634
+ ),
9635
+ stop: method(
9636
+ object({ deviceId: number().int().nonnegative() }),
9637
+ _void(),
9638
+ { kind: "mutation", auth: "admin" }
9639
+ ),
9640
+ setPosition: method(
9641
+ object({
9642
+ deviceId: number().int().nonnegative(),
9643
+ position: number().min(0).max(100)
9644
+ }),
9645
+ _void(),
9646
+ { kind: "mutation", auth: "admin" }
9647
+ )
9648
+ }
9649
+ });
9650
+ object({
9651
+ detected: boolean(),
9652
+ /** Ms epoch of the last transition. 0 if never observed. */
9653
+ lastChangedAt: number()
9654
+ });
9655
+ ({
9656
+ deviceTypes: [DeviceType.Sensor]
9657
+ });
9658
+ object({
9659
+ /** Current measured temperature. Null when not reported. */
9660
+ currentTemp: number().nullable(),
9661
+ /** Target temperature setpoint. Null when no setpoint surface. */
9662
+ targetTemp: number().nullable(),
9663
+ /** Active operation mode = HA `state` (`eco` / `electric` / `gas` /
9664
+ * `heat_pump` / `high_demand` / `performance` / `off`). Null when the
9665
+ * device reports an unknown state. */
9666
+ operationMode: string().nullable(),
9667
+ /** Available operation modes = HA `operation_list`. */
9668
+ availableModes: array(string()),
9669
+ /** Away mode (HA `away_mode` 'on'/'off' → bool). Null when the device
9670
+ * has no away surface. */
9671
+ away: boolean().nullable(),
9672
+ /** HA `min_temp` attribute. Null when not reported. */
9673
+ minTemp: number().nullable(),
9674
+ /** HA `max_temp` attribute. Null when not reported. */
9675
+ maxTemp: number().nullable(),
9676
+ /** Ms epoch when the slice was last updated. */
9677
+ lastChangedAt: number()
9678
+ });
9679
+ ({
9680
+ deviceTypes: [DeviceType.WaterHeater],
9681
+ methods: {
9682
+ setTargetTemp: method(
9683
+ object({
9684
+ deviceId: number().int().nonnegative(),
9685
+ temp: number().finite()
9686
+ }),
9687
+ _void(),
9688
+ { kind: "mutation", auth: "admin" }
9689
+ ),
9690
+ setOperationMode: method(
9691
+ object({
9692
+ deviceId: number().int().nonnegative(),
9693
+ mode: string().min(1)
9694
+ }),
9695
+ _void(),
9696
+ { kind: "mutation", auth: "admin" }
9697
+ ),
9698
+ setAway: method(
9699
+ object({
9700
+ deviceId: number().int().nonnegative(),
9701
+ on: boolean()
9702
+ }),
9703
+ _void(),
9704
+ { kind: "mutation", auth: "admin" }
9705
+ )
9706
+ }
9707
+ });
9708
+ object({
9709
+ /** Verbatim HA condition state (`sunny`, `cloudy`, `rainy`, …). Null
9710
+ * when no condition has been reported yet. */
9711
+ condition: string().nullable(),
9712
+ /** Current temperature in the reported unit. Null when not provided. */
9713
+ temperature: number().nullable(),
9714
+ /** Temperature unit string (e.g. `°C` / `°F`). Null when not provided. */
9715
+ temperatureUnit: string().nullable(),
9716
+ /** Relative humidity (0..100). Null when not provided. */
9717
+ humidity: number().min(0).max(100).nullable(),
9718
+ /** Barometric pressure in the reported unit. Null when not provided. */
9719
+ pressure: number().nullable(),
9720
+ /** Pressure unit string (e.g. `hPa` / `inHg`). Null when not provided. */
9721
+ pressureUnit: string().nullable(),
9722
+ /** Wind speed in the reported unit. Null when not provided. */
9723
+ windSpeed: number().nullable(),
9724
+ /** Wind-speed unit string (e.g. `km/h` / `mph`). Null when not provided. */
9725
+ windSpeedUnit: string().nullable(),
9726
+ /** Wind bearing in degrees (0..360, meteorological). Null when not provided. */
9727
+ windBearing: number().nullable(),
9728
+ /** Ms epoch when the slice was last updated. */
9729
+ lastFetchedAt: number()
9730
+ });
9731
+ ({
9732
+ deviceTypes: [DeviceType.Weather]
9733
+ });
7816
9734
  const PerScopeBreakdownSchema = object({
7817
9735
  /** Total tracked objects in this scope (frame / zone / unzoned). */
7818
9736
  totalObjects: number().int().nonnegative(),
@@ -7997,7 +9915,14 @@ const DiscoveryCandidateSchema = object({
7997
9915
  stableId: string(),
7998
9916
  type: _enum(DeviceType),
7999
9917
  suggestedName: string(),
8000
- prefilledConfig: record(string(), unknown())
9918
+ prefilledConfig: record(string(), unknown()),
9919
+ /**
9920
+ * Optional upstream-system identity (HA entity_id, vendor MAC, …).
9921
+ * Discovery pre-populates this for systems that know the upstream
9922
+ * identity ahead of adoption. Rendering metadata (unit, precision)
9923
+ * flows live through the cap STATUS SLICE after adoption.
9924
+ */
9925
+ sourceInfo: SourceInfoSchema.optional()
8001
9926
  });
8002
9927
  const DeviceSummarySchema = object({
8003
9928
  id: number(),
@@ -8008,7 +9933,12 @@ const DeviceSummarySchema = object({
8008
9933
  parentDeviceId: number().nullable(),
8009
9934
  online: boolean(),
8010
9935
  features: array(string()),
8011
- config: record(string(), unknown())
9936
+ config: record(string(), unknown()),
9937
+ /** Optional upstream-system identity (dispatch key + system tag).
9938
+ * See `SourceInfo`. Present when the device has a non-synthetic
9939
+ * source identifier (HA entities, vendor MAC, …); omitted when the
9940
+ * synthetic backfill is in effect. */
9941
+ sourceInfo: SourceInfoSchema.optional()
8012
9942
  });
8013
9943
  const FieldProbeResultSchema = object({
8014
9944
  status: _enum(["ok", "error"]),
@@ -8187,6 +10117,22 @@ const AlertSchema = object({
8187
10117
  dismiss: method(object({ alertId: string() }), _void(), { kind: "mutation" })
8188
10118
  }
8189
10119
  });
10120
+ const ProviderListEntrySchema = discriminatedUnion("shouldSaveDiskSpace", [
10121
+ object({
10122
+ providerId: string().min(1),
10123
+ displayName: string().min(1),
10124
+ configSchema: unknown(),
10125
+ shouldSaveDiskSpace: literal(true),
10126
+ minFreePercent: number().min(0).max(100)
10127
+ }),
10128
+ object({
10129
+ providerId: string().min(1),
10130
+ displayName: string().min(1),
10131
+ configSchema: unknown(),
10132
+ shouldSaveDiskSpace: literal(false),
10133
+ minFreePercent: literal(null)
10134
+ })
10135
+ ]);
8190
10136
  ({
8191
10137
  methods: {
8192
10138
  // ── Small-file primitives ────────────────────────────────────────
@@ -8261,6 +10207,16 @@ const AlertSchema = object({
8261
10207
  object({ type: StorageLocationTypeSchema }),
8262
10208
  StorageLocationSchema.nullable()
8263
10209
  ),
10210
+ // The admin-UI Data screen renders one group per declared location
10211
+ // (header = `displayName`, "+ Add" shown only for `cardinality:
10212
+ // 'multi'`). Source: the kernel-aggregated `storageLocations`
10213
+ // declarations injected into the orchestrator via `setRegistry`.
10214
+ // No closed type enum in the UI — the screen is fully declaration-
10215
+ // driven.
10216
+ listLocationDeclarations: method(
10217
+ _void(),
10218
+ array(StorageLocationDeclarationSchema).readonly()
10219
+ ),
8264
10220
  upsertLocation: method(
8265
10221
  StorageLocationSchema.omit({ createdAt: true, updatedAt: true }),
8266
10222
  StorageLocationSchema,
@@ -8285,12 +10241,7 @@ const AlertSchema = object({
8285
10241
  // never changes after boot).
8286
10242
  listProviders: method(
8287
10243
  _void(),
8288
- array(object({
8289
- providerId: string(),
8290
- displayName: string(),
8291
- supportedLocationTypes: array(StorageLocationTypeSchema).readonly(),
8292
- configSchema: unknown()
8293
- })).readonly()
10244
+ array(ProviderListEntrySchema).readonly()
8294
10245
  ),
8295
10246
  // Validate a candidate config against a provider BEFORE persisting.
8296
10247
  // Used by the wizard so operators can preflight a connection
@@ -8306,12 +10257,24 @@ const AlertSchema = object({
8306
10257
  )
8307
10258
  }
8308
10259
  });
8309
- const ProviderInfoSchema = object({
8310
- providerId: string().min(1),
8311
- displayName: string().min(1),
8312
- supportedLocationTypes: array(StorageLocationTypeSchema).readonly(),
8313
- configSchema: unknown()
8314
- });
10260
+ const ProviderInfoSchema = discriminatedUnion("shouldSaveDiskSpace", [
10261
+ object({
10262
+ providerId: string().min(1),
10263
+ displayName: string().min(1),
10264
+ configSchema: unknown(),
10265
+ // Provider manages a finite volume → declares a default free-space threshold.
10266
+ shouldSaveDiskSpace: literal(true),
10267
+ minFreePercent: number().min(0).max(100)
10268
+ }),
10269
+ object({
10270
+ providerId: string().min(1),
10271
+ displayName: string().min(1),
10272
+ configSchema: unknown(),
10273
+ // No local free-space concept (remote/object store) → no threshold.
10274
+ shouldSaveDiskSpace: literal(false),
10275
+ minFreePercent: literal(null)
10276
+ })
10277
+ ]);
8315
10278
  const TestLocationResultSchema = object({
8316
10279
  ok: boolean(),
8317
10280
  error: string().optional()
@@ -8397,6 +10360,35 @@ const EndDownloadInputSchema = object({ downloadId: string() });
8397
10360
  endDownload: method(EndDownloadInputSchema, _void(), { kind: "mutation" })
8398
10361
  }
8399
10362
  });
10363
+ const EvictableUsageSchema = object({
10364
+ /** Bytes this provider currently holds on the location (0 if none). */
10365
+ bytes: number().int().nonnegative()
10366
+ });
10367
+ const EvictResultSchema = object({
10368
+ /** Bytes actually reclaimed (only successfully-deleted data counts). */
10369
+ reclaimedBytes: number().int().nonnegative(),
10370
+ /** True when the provider has nothing left it is willing to drop on this location. */
10371
+ exhausted: boolean()
10372
+ });
10373
+ ({
10374
+ methods: {
10375
+ /** Bytes this provider holds on the given location — drives proportional fan-out. */
10376
+ getEvictableUsage: method(
10377
+ object({ locationId: string() }),
10378
+ EvictableUsageSchema
10379
+ ),
10380
+ /**
10381
+ * Free approximately `targetBytes` of this provider's OWN least-valuable
10382
+ * data on the location (oldest footage, expired clips, …). Returns what it
10383
+ * actually reclaimed + whether it is now exhausted.
10384
+ */
10385
+ evict: method(
10386
+ object({ locationId: string(), targetBytes: number().int().positive() }),
10387
+ EvictResultSchema,
10388
+ { kind: "mutation" }
10389
+ )
10390
+ }
10391
+ });
8400
10392
  const BackupSubDestinationInfoSchema = object({
8401
10393
  /**
8402
10394
  * Sub-id within this addon. Convention `default` for single-
@@ -8607,7 +10599,7 @@ const QueryFilterSchema = object({
8607
10599
  limit: number().optional(),
8608
10600
  offset: number().optional()
8609
10601
  });
8610
- const SettingsRecordSchema = object({
10602
+ const SettingsRecordSchema$1 = object({
8611
10603
  id: string(),
8612
10604
  data: record(string(), unknown())
8613
10605
  });
@@ -8639,11 +10631,11 @@ const CollectionIndexSchema = object({
8639
10631
  /** Get all entries matching an optional filter. */
8640
10632
  query: method(
8641
10633
  object({ namespace: string().optional(), collection: string(), filter: QueryFilterSchema.optional() }),
8642
- array(SettingsRecordSchema).readonly()
10634
+ array(SettingsRecordSchema$1).readonly()
8643
10635
  ),
8644
10636
  /** Insert a new record. */
8645
10637
  insert: method(
8646
- object({ namespace: string().optional(), collection: string(), record: SettingsRecordSchema }),
10638
+ object({ namespace: string().optional(), collection: string(), record: SettingsRecordSchema$1 }),
8647
10639
  _void(),
8648
10640
  { kind: "mutation" }
8649
10641
  ),
@@ -8664,6 +10656,18 @@ const CollectionIndexSchema = object({
8664
10656
  object({ namespace: string().optional(), collection: string(), filter: QueryFilterSchema.optional() }),
8665
10657
  number()
8666
10658
  ),
10659
+ /** Grouped counts per ((field-origin)/bucketSize) bucket, filtered. */
10660
+ histogram: method(
10661
+ object({
10662
+ namespace: string().optional(),
10663
+ collection: string(),
10664
+ field: string(),
10665
+ bucketSize: number().int().positive(),
10666
+ origin: number().int(),
10667
+ filter: QueryFilterSchema.optional()
10668
+ }),
10669
+ array(object({ bucket: number().int(), count: number().int() })).readonly()
10670
+ ),
8667
10671
  /** Check if a collection is empty. */
8668
10672
  isEmpty: method(
8669
10673
  object({ namespace: string().optional(), collection: string() }),
@@ -8984,6 +10988,297 @@ const SmtpStatusSchema = object({
8984
10988
  )
8985
10989
  }
8986
10990
  });
10991
+ const AdoptionFilterSchema = object({
10992
+ id: string(),
10993
+ label: string(),
10994
+ isDefault: boolean().optional()
10995
+ });
10996
+ const CandidateQueryFilterSchema = object({
10997
+ /** Substring filter on name + manufacturer + model. */
10998
+ search: string().optional(),
10999
+ /** Area-name exact match. */
11000
+ area: string().optional(),
11001
+ /** Manufacturer exact match. */
11002
+ manufacturer: string().optional(),
11003
+ /** When true, only return candidates the operator already adopted. */
11004
+ adoptedOnly: boolean().optional(),
11005
+ /** When true, only return candidates the operator hasn't adopted yet. */
11006
+ unadoptedOnly: boolean().optional()
11007
+ });
11008
+ const ListCandidatesInputSchema = object({
11009
+ integrationId: string(),
11010
+ page: number().int().positive().default(1),
11011
+ // Pagination is client-side in the adoption UI: the modal fetches the whole
11012
+ // candidate set in one page and the shared list paginates locally. The cap
11013
+ // stays high enough to return every candidate at once. The large case is the
11014
+ // HA `entities` granularity — one HA device maps to many entities, so an
11015
+ // install can expose several thousand candidates; the ceiling is sized for it.
11016
+ pageSize: number().int().positive().max(2e4).default(50),
11017
+ /**
11018
+ * Optional provider-declared discovery GRANULARITY id (opaque; see
11019
+ * `AdoptionFilterSchema`). Omitted = the reserved `'devices'` granularity =
11020
+ * exactly the pre-existing behavior (fully back-compatible).
11021
+ */
11022
+ filter: string().optional(),
11023
+ /** Optional candidate-list text/query narrowing within the granularity. */
11024
+ filterText: CandidateQueryFilterSchema.optional()
11025
+ });
11026
+ const ListCandidatesOutputSchema = object({
11027
+ candidates: array(DiscoveredChildDeviceSchema).readonly(),
11028
+ totalCount: number().int().nonnegative(),
11029
+ page: number().int().positive(),
11030
+ pageSize: number().int().positive()
11031
+ });
11032
+ const GetCandidateInputSchema = object({
11033
+ integrationId: string(),
11034
+ childNativeId: string()
11035
+ });
11036
+ const AdoptionStatusSchema = object({
11037
+ /** Last refresh timestamp (ms epoch) — null when never refreshed. */
11038
+ lastDiscoveryAt: number().int().nonnegative().nullable(),
11039
+ /** Count of candidates in the discovery cache. */
11040
+ candidateCount: number().int().nonnegative(),
11041
+ /** Count of candidates the operator has already adopted. */
11042
+ adoptedCount: number().int().nonnegative(),
11043
+ /** Last error message from a refresh attempt. */
11044
+ lastError: string().nullable()
11045
+ });
11046
+ const PerCandidateSchema = object({
11047
+ /** Override the default display name for this candidate's parent. */
11048
+ name: string().min(1).optional(),
11049
+ /** Pre-hide a subset of entity-children — created (state still flows)
11050
+ * but listed in the parent's `accessories.hiddenChildIds`. */
11051
+ hiddenChildIds: array(string()).optional()
11052
+ });
11053
+ const AdoptInputSchema = object({
11054
+ integrationId: string(),
11055
+ /**
11056
+ * Candidate native ids to adopt. Their MEANING is filter-relative: under the
11057
+ * default `'devices'` granularity these are device-native ids; under a
11058
+ * provider-declared granularity (e.g. HA `'entities'`) they are that
11059
+ * granularity's native ids (e.g. entity ids). The field name is kept stable
11060
+ * to avoid a breaking rename.
11061
+ */
11062
+ childNativeIds: array(string()).min(1),
11063
+ /**
11064
+ * Optional provider-declared discovery GRANULARITY id (opaque; see
11065
+ * `AdoptionFilterSchema`). Omitted = the reserved `'devices'` granularity =
11066
+ * exactly the pre-existing behavior (fully back-compatible).
11067
+ */
11068
+ filter: string().optional(),
11069
+ /** When true, import each adopted device's source-system location (e.g. HA
11070
+ * area) into CamStack — fuzzy-match an existing location or create it, then
11071
+ * assign. Omitted/false = no location work (back-compat). */
11072
+ importLocations: boolean().optional(),
11073
+ perCandidate: record(string(), PerCandidateSchema).optional()
11074
+ });
11075
+ const AdoptResultSchema = object({
11076
+ adopted: array(
11077
+ object({
11078
+ childNativeId: string(),
11079
+ parentDeviceId: number().int().nonnegative(),
11080
+ accessoryDeviceIds: array(number().int().nonnegative()).readonly()
11081
+ })
11082
+ ).readonly()
11083
+ });
11084
+ const ReleaseInputSchema = object({
11085
+ integrationId: string(),
11086
+ /** Parent CamStack device id (NOT an accessory child id). Removing
11087
+ * the parent cascades into every accessory. */
11088
+ camDeviceId: number().int().nonnegative()
11089
+ });
11090
+ const ResyncInputSchema = object({
11091
+ /** Parent CamStack device id of an adopted device. The provider resolves its
11092
+ * source (integration/broker + native id) and re-aligns the device's
11093
+ * structural spec (type/role/capabilities/units) with the live mapping,
11094
+ * rebuilding any child whose class changed while preserving operator edits. */
11095
+ camDeviceId: number().int().nonnegative()
11096
+ });
11097
+ const ResyncResultSchema = object({
11098
+ /** True when the persisted spec actually changed (children may have been rebuilt). */
11099
+ changed: boolean(),
11100
+ /** Number of child devices rebuilt into a new class by this re-sync. */
11101
+ rebuiltChildren: number().int().nonnegative()
11102
+ });
11103
+ ({
11104
+ methods: {
11105
+ listCandidateFilters: method(
11106
+ object({ integrationId: string() }),
11107
+ object({ filters: array(AdoptionFilterSchema) }),
11108
+ { auth: "admin" }
11109
+ ),
11110
+ listCandidates: method(ListCandidatesInputSchema, ListCandidatesOutputSchema, { auth: "admin" }),
11111
+ getCandidate: method(GetCandidateInputSchema, DiscoveredChildDeviceSchema.nullable(), { auth: "admin" }),
11112
+ refresh: method(object({ integrationId: string() }), AdoptionStatusSchema, { kind: "mutation", auth: "admin" }),
11113
+ adopt: method(AdoptInputSchema, AdoptResultSchema, { kind: "mutation", auth: "admin" }),
11114
+ release: method(ReleaseInputSchema, _void(), { kind: "mutation", auth: "admin" }),
11115
+ resync: method(ResyncInputSchema, ResyncResultSchema, { kind: "mutation", auth: "admin" })
11116
+ }
11117
+ });
11118
+ const BrokerStatusEnum = _enum([
11119
+ "connected",
11120
+ "disconnected",
11121
+ "connecting",
11122
+ "auth-failed",
11123
+ "unreachable",
11124
+ "error"
11125
+ ]);
11126
+ const BrokerInfoSchema$1 = object({
11127
+ /** Stable broker id. Persisted; survives addon restarts. */
11128
+ id: string(),
11129
+ /** Addon id of the provider that OWNS this broker.
11130
+ *
11131
+ * The `broker` cap is a system-scoped collection: several addons
11132
+ * register a `broker` provider, each owning a DISJOINT set of
11133
+ * brokers (mqtt-broker owns `mqtt_*`, provider-homeassistant owns
11134
+ * `ha_*`). A broker therefore belongs to exactly one addon — like a
11135
+ * device belongs to one integration. The admin UI threads this id
11136
+ * back as the `{ addonId }` system-collection selector on every
11137
+ * id-keyed call (`get` / `getSettings` / `setSettings` / `remove` /
11138
+ * `testConnection`), so the call routes to the OWNING provider
11139
+ * instead of defaulting to the first-registered one. */
11140
+ addonId: string(),
11141
+ /** Human-readable name (operator-chosen at add-time). */
11142
+ name: string(),
11143
+ /** Provider-defined kind tag — `mqtt` / `home-assistant` / future. */
11144
+ kind: string(),
11145
+ status: BrokerStatusEnum,
11146
+ /** Free-form provider-specific info (HA version, MQTT broker
11147
+ * flavour, latency, mTLS active, …). */
11148
+ info: record(string(), unknown()),
11149
+ /** Ms epoch of the last connection probe / status update. */
11150
+ lastCheckedAt: number().nullable(),
11151
+ /** Last error message, when `status` indicates failure. */
11152
+ error: string().nullable()
11153
+ });
11154
+ const RegistryStatusSchema = object({
11155
+ brokerCount: number().int().nonnegative(),
11156
+ connectedCount: number().int().nonnegative()
11157
+ });
11158
+ const BrokerProviderInfoSchema = object({
11159
+ /** Addon id of the `broker` provider this entry describes. */
11160
+ addonId: string(),
11161
+ /** Broker kinds this provider can create, with a display label. */
11162
+ kinds: array(object({ kind: string(), label: string() }))
11163
+ });
11164
+ const ListInputSchema = object({
11165
+ /** Optional kind filter — `list({kind:'home-assistant'})` returns
11166
+ * only HA brokers. Omit to list every broker. */
11167
+ kind: string().optional()
11168
+ });
11169
+ const GetInputSchema = object({ id: string() });
11170
+ const AddInputSchema = object({
11171
+ kind: string().min(1),
11172
+ name: string().min(1),
11173
+ /** Kind-specific settings (e.g. MQTT `{url,username,password}` or HA
11174
+ * `{baseUrl,accessToken}`). Validated by the kind-specific provider
11175
+ * branch on receipt — invalid shape rejects the add. */
11176
+ settings: record(string(), unknown())
11177
+ });
11178
+ const AddResultSchema = object({ id: string() });
11179
+ const RemoveInputSchema = object({ id: string() });
11180
+ const TestConnectionResultSchema$1 = discriminatedUnion("ok", [
11181
+ object({ ok: literal(true), latencyMs: number().nonnegative() }),
11182
+ object({ ok: literal(false), error: string() })
11183
+ ]);
11184
+ const SettingsRecordSchema = record(string(), unknown());
11185
+ const SettingsSchemaInputSchema = object({ kind: string() });
11186
+ const TestSettingsInputSchema = object({
11187
+ kind: string(),
11188
+ settings: SettingsRecordSchema
11189
+ });
11190
+ const TestSettingsResultSchema = discriminatedUnion("ok", [
11191
+ // `.strict()` on the success branch so a stray `error` field is rejected,
11192
+ // not silently stripped — a success result must never carry an error.
11193
+ object({ ok: literal(true), latencyMs: number().nonnegative().optional() }).strict(),
11194
+ object({ ok: literal(false), error: string() })
11195
+ ]);
11196
+ const SettingsSchemaResultSchema = unknown().nullable();
11197
+ const PublishInputSchema = object({
11198
+ brokerId: string(),
11199
+ /** Kind-specific routing target.
11200
+ * MQTT: `{ topic: string, qos?: 0|1|2, retain?: boolean }`.
11201
+ * HA: `{ domain: string, service: string, entityId?: string, area?: string }`. */
11202
+ target: record(string(), unknown()),
11203
+ /** Kind-specific payload.
11204
+ * MQTT: raw string / number / object (provider serialises).
11205
+ * HA: service-call `data` object (transition, brightness, …). */
11206
+ payload: unknown().optional()
11207
+ });
11208
+ const SubscribeInputSchema = object({
11209
+ brokerId: string(),
11210
+ /** Kind-specific filter.
11211
+ * MQTT: `{ topic: string, qos?: 0|1|2 }` — topic can include wildcards.
11212
+ * HA: `{ entityIds: string[] }` or `{ domain: string }`. */
11213
+ filter: record(string(), unknown())
11214
+ });
11215
+ const SubscribeResultSchema = object({
11216
+ /** Stable subscription id. Used to unsubscribe and to filter the
11217
+ * matching `broker.message` events on the bus. */
11218
+ subscriptionId: string()
11219
+ });
11220
+ const UnsubscribeInputSchema = object({
11221
+ brokerId: string(),
11222
+ subscriptionId: string()
11223
+ });
11224
+ const GetStateInputSchema = object({
11225
+ brokerId: string(),
11226
+ /** Kind-specific lookup key.
11227
+ * MQTT: topic string (returns the last retained message).
11228
+ * HA: entity_id (returns the cached entity state). */
11229
+ key: string()
11230
+ });
11231
+ ({
11232
+ methods: {
11233
+ // ── Registry CRUD ────────────────────────────────────────────────
11234
+ list: method(ListInputSchema, array(BrokerInfoSchema$1)),
11235
+ get: method(GetInputSchema, BrokerInfoSchema$1.nullable()),
11236
+ /** Enumerate which addon provides which broker kind(s) for the
11237
+ * unified create picker. The auto-mount fans this array across
11238
+ * every registered `broker` provider (array-output method), so the
11239
+ * picker sees every kind from every provider in one call. */
11240
+ listProviders: method(_void(), array(BrokerProviderInfoSchema), { auth: "admin" }),
11241
+ add: method(AddInputSchema, AddResultSchema, { kind: "mutation", auth: "admin" }),
11242
+ remove: method(RemoveInputSchema, _void(), { kind: "mutation", auth: "admin" }),
11243
+ testConnection: method(GetInputSchema, TestConnectionResultSchema$1, { kind: "mutation", auth: "admin" }),
11244
+ // ── Settings ─────────────────────────────────────────────────────
11245
+ /** Read the persisted settings record for a broker (kind-specific
11246
+ * shape). Admin-only — settings may contain secrets. Returns `null`
11247
+ * when the broker id is unknown to the provider (the collection
11248
+ * fallback may route a foreign id to the first provider). */
11249
+ getSettings: method(GetInputSchema, SettingsRecordSchema.nullable(), { auth: "admin" }),
11250
+ /** Overwrite the persisted settings record. The kind-specific
11251
+ * provider validates the shape and applies the change (reconnects
11252
+ * if credentials changed). */
11253
+ setSettings: method(
11254
+ object({ id: string(), settings: SettingsRecordSchema }),
11255
+ _void(),
11256
+ { kind: "mutation", auth: "admin" }
11257
+ ),
11258
+ // ── Connection-config (for consumers that open their own client) ─
11259
+ /** Returns the kind-specific connection config the consumer needs
11260
+ * to open its own client (MQTT pattern: `{url, username, password,
11261
+ * clientIdPrefix}`). HA providers MAY return the auth envelope
11262
+ * but typical HA consumers use `publish` / `subscribe` instead.
11263
+ * Returns `null` when the broker id is unknown to the provider. */
11264
+ getBrokerConfig: method(GetInputSchema, SettingsRecordSchema.nullable(), { auth: "admin" }),
11265
+ // ── Per-kind creation schema + pre-creation test ─────────────────
11266
+ getSettingsSchema: method(SettingsSchemaInputSchema, SettingsSchemaResultSchema, { auth: "admin" }),
11267
+ testSettings: method(TestSettingsInputSchema, TestSettingsResultSchema, { kind: "mutation", auth: "admin" }),
11268
+ // ── Pub/sub primitives ───────────────────────────────────────────
11269
+ publish: method(PublishInputSchema, unknown(), { kind: "mutation", auth: "admin" }),
11270
+ subscribe: method(SubscribeInputSchema, SubscribeResultSchema, { kind: "mutation", auth: "admin" }),
11271
+ unsubscribe: method(UnsubscribeInputSchema, _void(), { kind: "mutation", auth: "admin" }),
11272
+ /** Read the broker's cached state for a key. Returns `null` when
11273
+ * unknown to the broker (never published / unknown entity). */
11274
+ getState: method(GetStateInputSchema, unknown().nullable()),
11275
+ /** Status method — explicit registration with a `z.void()` input so
11276
+ * the codegen-generated tRPC router types its input as
11277
+ * `{addonId?: string, nodeId?: string}` (system-scoped collection
11278
+ * shape) instead of the device-scoped `{deviceId}` fallback. */
11279
+ getStatus: method(_void(), RegistryStatusSchema)
11280
+ }
11281
+ });
8987
11282
  const BrokerKindSchema = _enum(["external", "embedded"]);
8988
11283
  const BrokerStatusSchema = _enum([
8989
11284
  "connected",
@@ -9493,7 +11788,15 @@ const WebrtcStreamChoiceSchema = object({
9493
11788
  * direct (host/srflx) path. Clients MUST NOT send this — the
9494
11789
  * server overwrites it from the request context.
9495
11790
  */
9496
- relayOnly: boolean().optional()
11791
+ relayOnly: boolean().optional(),
11792
+ /**
11793
+ * Subscriber attribution surfaced in the stream-broker widget's
11794
+ * client list. Callers (Alexa addon, browser hooks, WHEP server)
11795
+ * populate `kind` and any of `label`/`userId`/`sessionId`/
11796
+ * `remoteAddr` they know. The hub layer enriches `remoteAddr`
11797
+ * from the tRPC request context.
11798
+ */
11799
+ consumerAttribution: BrokerConsumerAttributionSchema.optional()
9497
11800
  }),
9498
11801
  object({ sessionId: string(), sdpOffer: string() }),
9499
11802
  { kind: "mutation" }
@@ -9531,7 +11834,62 @@ const WebrtcStreamChoiceSchema = object({
9531
11834
  * Untrusted browser clients MUST NOT send it — the hub overwrites
9532
11835
  * it from the request context.
9533
11836
  */
9534
- relayOnly: boolean().optional()
11837
+ relayOnly: boolean().optional(),
11838
+ /**
11839
+ * Force a NON-TRICKLE answer: the server awaits ICE gathering to
11840
+ * COMPLETE and returns a full-candidate answer SDP (with `a=candidate`
11841
+ * lines) instead of the default bare/trickle answer.
11842
+ *
11843
+ * Set `true` by callers that DON'T support trickle ICE — notably
11844
+ * Alexa's RTCSessionController, which never polls `getIceCandidates`
11845
+ * nor trickles back via `addIceCandidate`, so without server
11846
+ * candidates in the answer SDP its ICE agent stalls (no nominated
11847
+ * pair → DTLS never connects → Echo shows black → SessionDisconnected).
11848
+ *
11849
+ * Browser viewers leave it absent/false: they poll `getIceCandidates`
11850
+ * and trickle, so the bare answer lets media start in ~0s instead of
11851
+ * blocking on full gathering.
11852
+ */
11853
+ nonTrickle: boolean().optional(),
11854
+ /**
11855
+ * Suppress TURN servers from the per-session iceConfig: the answer
11856
+ * will carry ONLY host + srflx candidates, never a relay one.
11857
+ *
11858
+ * Set `true` by peers that are themselves directly reachable on the
11859
+ * public internet (Alexa's RTCSessionController media gateway is
11860
+ * AWS-hosted with public host candidates). Including a TURN relay
11861
+ * for such a peer is counterproductive: (a) gathering blocks on the
11862
+ * TURN allocation round-trip and slows the answer; (b) werift
11863
+ * spends ICE-checking budget on a relay-pair that the peer cannot
11864
+ * use, sometimes stalling the host/srflx pair validation enough
11865
+ * that Echo's agent times out before nominating one — visible as
11866
+ * 'ICE checking → DTLS never connected'. Browser viewers leave it
11867
+ * absent/false so the relay candidate remains as a fallback for
11868
+ * symmetric-NAT clients.
11869
+ *
11870
+ * Independent from `relayOnly`. `relayOnly: true` forces ICE to a
11871
+ * relay-only pair set; `disableTurn: true` strips the relay
11872
+ * candidate entirely. They are mutually exclusive in practice but
11873
+ * not policed at the schema level — callers MUST NOT set both.
11874
+ */
11875
+ disableTurn: boolean().optional(),
11876
+ /**
11877
+ * Suppress IPv6 host candidates from gathering and from
11878
+ * `additionalHostAddresses`. The answer SDP will contain only IPv4
11879
+ * host/srflx (and TURN, unless `disableTurn` is also set).
11880
+ *
11881
+ * Set `true` by peers that document IPv4-only ICE — Amazon's
11882
+ * `Alexa.RTCSessionController` spec states: "For ICE candidates,
11883
+ * you can use either UDP or TCP but you must use IPv4." Echo's
11884
+ * media gateway ignores IPv6 candidates and they consume budget
11885
+ * against the gateway's documented 6-second SDP processing limit.
11886
+ *
11887
+ * Browser viewers leave it absent/false so IPv6-only paths
11888
+ * (Tailscale, native dual-stack) remain available.
11889
+ */
11890
+ disableIpv6: boolean().optional(),
11891
+ /** Subscriber attribution. See `createSession` for the contract. */
11892
+ consumerAttribution: BrokerConsumerAttributionSchema.optional()
9535
11893
  }),
9536
11894
  object({ sessionId: string(), sdpAnswer: string() }),
9537
11895
  { kind: "mutation" }
@@ -9550,7 +11908,7 @@ const WebrtcStreamChoiceSchema = object({
9550
11908
  * Lets the client send its SDP offer/answer IMMEDIATELY (before ICE
9551
11909
  * gathering finishes) and deliver candidates as they arrive, so the
9552
11910
  * connection establishes in ~0s instead of waiting for full gathering.
9553
- * The dual of `getIceCandidates`. Mirrors Scrypted's signaling.
11911
+ * The dual of `getIceCandidates` in the trickle-ICE signaling exchange.
9554
11912
  */
9555
11913
  addIceCandidate: method(
9556
11914
  object({
@@ -9600,6 +11958,18 @@ const WebrtcStreamChoiceSchema = object({
9600
11958
  profile: CamProfileSchema
9601
11959
  }),
9602
11960
  boolean()
11961
+ ),
11962
+ /** Poll the live signaling state of a session. `pendingRenegotiation` is
11963
+ * non-null after an adaptive tier switch — the client re-offers on the
11964
+ * same sessionId; `epoch` guards against acting on a stale poll twice. */
11965
+ getSessionState: method(
11966
+ object({
11967
+ deviceId: number().int().nonnegative(),
11968
+ sessionId: string()
11969
+ }),
11970
+ object({
11971
+ pendingRenegotiation: object({ target: WebrtcStreamTargetSchema, epoch: number() }).nullable()
11972
+ })
9603
11973
  )
9604
11974
  }
9605
11975
  });
@@ -10208,6 +12578,26 @@ const EmbeddingInfoSchema = object({
10208
12578
  getInfo: method(_void(), EmbeddingInfoSchema)
10209
12579
  }
10210
12580
  });
12581
+ const ChildLayoutEntrySchema = object({
12582
+ childKey: string(),
12583
+ section: string(),
12584
+ order: number().optional(),
12585
+ // Section-level default-collapsed hint: when true the accordion section this
12586
+ // entry belongs to renders closed by default. The section is treated as
12587
+ // collapsed if ANY of its entries sets collapsed:true; consistent values
12588
+ // across a section's entries are recommended but not enforced. Absent ⇒ open.
12589
+ collapsed: boolean().optional()
12590
+ });
12591
+ const DeviceLinkSchema = object({
12592
+ id: string(),
12593
+ source: object({ sourceKey: string(), cap: string(), fieldPath: string() }),
12594
+ target: object({ cap: string(), fieldPath: string(), itemKey: string().optional() }),
12595
+ transform: discriminatedUnion("kind", [
12596
+ object({ kind: literal("identity") }),
12597
+ object({ kind: literal("enum-map"), mapping: record(string(), union([string(), number(), boolean()])), fallback: union([string(), number(), boolean()]).optional() }),
12598
+ object({ kind: literal("linear"), scale: number(), offset: number(), clamp: tuple([number(), number()]).readonly().optional() })
12599
+ ]).optional()
12600
+ });
10211
12601
  const DeviceInfoSchema = object({
10212
12602
  /** Progressive, system-wide unique number. Allocated synchronously by
10213
12603
  * `device-manager.allocateDeviceId` BEFORE the owning `IDevice` is
@@ -10227,6 +12617,12 @@ const DeviceInfoSchema = object({
10227
12617
  /** Optional semantic role — `DeviceRole` string. null for top-level devices. */
10228
12618
  role: string().nullable().optional(),
10229
12619
  online: boolean(),
12620
+ /** True when the device's initial feature-probe has completed (or it has
12621
+ * no probe) — exported shape is stable; exporters gate advertise on this.
12622
+ * Optional for deploy-order resilience: a record produced by an older
12623
+ * device-manager build omits it, and consumers treat absent as "not ready"
12624
+ * (export gate carries forward, never advertises a partial shape). */
12625
+ probed: boolean().optional(),
10230
12626
  features: array(string()),
10231
12627
  /** true when the device has a getStreamSources() method (ICameraDevice) */
10232
12628
  isCamera: boolean(),
@@ -10234,7 +12630,25 @@ const DeviceInfoSchema = object({
10234
12630
  config: record(string(), unknown()),
10235
12631
  /** Hardware + identity blob (manufacturer / model / firmware / sn /
10236
12632
  * uid / mac / …). Populated by drivers; editable via setMetadata. */
10237
- metadata: record(string(), unknown()).nullable().optional()
12633
+ metadata: record(string(), unknown()).nullable().optional(),
12634
+ /** Optional upstream-system identity + rendering envelope. See
12635
+ * `SourceInfo` in `packages/types/src/device/source-info.ts`. */
12636
+ sourceInfo: SourceInfoSchema.optional(),
12637
+ /** Owning integration id, stamped at create — used by the core to
12638
+ * cascade-delete an integration's devices. Optional: only present
12639
+ * when the device was created through an integration (e.g. HA). */
12640
+ integrationId: string().optional(),
12641
+ linkDeviceId: number().nullable().optional(),
12642
+ /** Durable primary-child override for a CONTAINER device, keyed on the
12643
+ * chosen child's re-sync/rename-stable `entityId`. Survives a re-sync
12644
+ * that reallocates the child's numeric id. `null` clears the override. */
12645
+ primaryChildEntityId: string().nullable().optional(),
12646
+ /** Container-level layout hint: assigns specific child/accessory devices to
12647
+ * named accordion sections (with optional intra-section order). See
12648
+ * `DeviceMeta.childLayout`. Absent ⇒ no layout declared. */
12649
+ childLayout: array(ChildLayoutEntrySchema).readonly().optional(),
12650
+ /** Operator-authored cross-device field wirings. See `DeviceMeta.deviceLinks`. */
12651
+ deviceLinks: array(DeviceLinkSchema).readonly().optional()
10238
12652
  });
10239
12653
  const ConfigEntrySchema$1 = object({
10240
12654
  key: string(),
@@ -10265,7 +12679,32 @@ const DeviceMetaSchema = object({
10265
12679
  location: string().nullable(),
10266
12680
  disabled: boolean(),
10267
12681
  parentDeviceId: number().nullable(),
10268
- metadata: record(string(), unknown()).nullable().optional()
12682
+ metadata: record(string(), unknown()).nullable().optional(),
12683
+ /** Optional upstream-system identity + rendering envelope. See
12684
+ * `SourceInfo`. Present when the device has been persisted with a
12685
+ * non-synthetic source identifier (HA entities, vendor MAC, …);
12686
+ * omitted when the synthetic `{ id: stableId, system: addonId }`
12687
+ * fallback is in effect. Persisted under
12688
+ * `DeviceMeta.metadata.sourceInfo` — the field on this schema is
12689
+ * the typed projection callers consume directly. */
12690
+ sourceInfo: SourceInfoSchema.optional(),
12691
+ /** Owning integration id, stamped at create — used by the core to
12692
+ * cascade-delete an integration's devices. Optional: only present
12693
+ * when the device was created through an integration (e.g. HA). */
12694
+ integrationId: string().optional(),
12695
+ linkDeviceId: number().nullable().optional(),
12696
+ /** Durable primary-child override for a CONTAINER device, keyed on the
12697
+ * chosen child's re-sync/rename-stable `entityId`. See `DeviceMeta`. */
12698
+ primaryChildEntityId: string().nullable().optional(),
12699
+ /** Container-level layout hint: assigns child/accessory devices to named
12700
+ * accordion sections (with optional intra-section order). See
12701
+ * `DeviceMeta.childLayout`. Absent ⇒ no layout declared. */
12702
+ childLayout: array(ChildLayoutEntrySchema).readonly().optional(),
12703
+ /** Operator-authored cross-device field wirings. See `DeviceMeta.deviceLinks`. */
12704
+ deviceLinks: array(DeviceLinkSchema).readonly().optional(),
12705
+ /** Semantic role string (`DeviceRole`) — propagated from the spawn pre-seed.
12706
+ * Optional: only present for accessory children that carry a known role. */
12707
+ role: string().nullable().optional()
10269
12708
  });
10270
12709
  const ConfigUISchemaOutput = unknown().nullable();
10271
12710
  const StreamProbeResultSchema = object({
@@ -10359,6 +12798,109 @@ const DevicePersistConfigPayloadSchema = object({
10359
12798
  _void(),
10360
12799
  { kind: "mutation", auth: "admin" }
10361
12800
  ),
12801
+ /** Update the device type. Writes the meta row, emits a
12802
+ * `DeviceMetaChanged` event. Used by the kernel to apply
12803
+ * `initialMeta.type` before device construction so the device
12804
+ * constructs with its real type instead of the allocateDeviceId
12805
+ * placeholder `'generic'`. */
12806
+ setType: method(
12807
+ object({ deviceId: number(), type: _enum(DeviceType) }),
12808
+ _void(),
12809
+ { kind: "mutation", auth: "admin" }
12810
+ ),
12811
+ /** Stamp (or update) the owning integration id on the device's meta
12812
+ * row. Called by the kernel's `create()` pre-seed path when
12813
+ * `initialMeta.integrationId` is set (analogous to `setName` /
12814
+ * `setType`). Idempotent. */
12815
+ setIntegrationId: method(
12816
+ object({ deviceId: number(), integrationId: string() }),
12817
+ _void(),
12818
+ { kind: "mutation", auth: "admin" }
12819
+ ),
12820
+ /** Stamp (or update) the soft-link device id on the device's meta
12821
+ * row. Called by the kernel `create()` pre-seed when
12822
+ * `initialMeta.linkDeviceId !== undefined`. Idempotent. */
12823
+ setLinkDeviceId: method(
12824
+ object({ deviceId: number(), linkDeviceId: number().nullable() }),
12825
+ _void(),
12826
+ { kind: "mutation", auth: "admin" }
12827
+ ),
12828
+ /** Set (or clear) the durable primary-child override on a CONTAINER
12829
+ * device's meta row, keyed on the chosen child's re-sync/rename-stable
12830
+ * `entityId`. Unlike `setLinkDeviceId` (numeric child id, goes stale on
12831
+ * re-sync), this survives a re-sync that reallocates the child's numeric
12832
+ * id. `null` clears the override → priority default. Idempotent. */
12833
+ setPrimaryChildEntityId: method(
12834
+ object({ deviceId: number(), primaryChildEntityId: string().nullable() }),
12835
+ _void(),
12836
+ { kind: "mutation", auth: "admin" }
12837
+ ),
12838
+ /** Set (or replace) the container-level `childLayout` on a device's meta
12839
+ * row — assigns specific child/accessory devices to named accordion
12840
+ * sections (with optional intra-section order). Mirrors
12841
+ * `setPrimaryChildEntityId`; the layout is parent-only. Persisted,
12842
+ * projected, and preserved across re-register/restore. Idempotent. */
12843
+ setChildLayout: method(
12844
+ object({ deviceId: number(), childLayout: array(ChildLayoutEntrySchema).readonly() }),
12845
+ _void(),
12846
+ { kind: "mutation", auth: "admin" }
12847
+ ),
12848
+ /** Set (or replace) the cross-device field wirings on a device's meta row.
12849
+ * Mirrors `setChildLayout`; persisted, projected, preserved across
12850
+ * re-register/restore. Idempotent. */
12851
+ setDeviceLinks: method(
12852
+ object({ deviceId: number(), deviceLinks: array(DeviceLinkSchema).readonly() }),
12853
+ _void(),
12854
+ { kind: "mutation", auth: "admin" }
12855
+ ),
12856
+ /** List the wireable status-schema fields per cap bound to a device.
12857
+ * Powers the Wiring tab's field pickers. Caps without a status schema are omitted. */
12858
+ getWireableFields: method(
12859
+ object({ deviceId: number() }),
12860
+ object({
12861
+ caps: array(object({
12862
+ cap: string(),
12863
+ fields: array(object({
12864
+ path: string(),
12865
+ kind: _enum(["string", "number", "boolean", "enum"]),
12866
+ enumValues: array(string()).optional()
12867
+ })).readonly()
12868
+ })).readonly()
12869
+ }),
12870
+ { kind: "query" }
12871
+ ),
12872
+ /** Stamp (or update) the semantic role on the device's meta row.
12873
+ * Called by the kernel's `create()` / `spawnAccessoryChild` pre-seed
12874
+ * path when `initialMeta.role` is set (analogous to `setIntegrationId`).
12875
+ * Idempotent. `null` explicitly clears a previous role. */
12876
+ setRole: method(
12877
+ object({ deviceId: number(), role: string().nullable() }),
12878
+ _void(),
12879
+ { kind: "mutation", auth: "admin" }
12880
+ ),
12881
+ /** Batched meta pre-seed — applies every provided field to the device's
12882
+ * meta row in ONE settings round-trip (one lock acquisition, one
12883
+ * `deviceMeta` write) and emits one `DeviceMetaChanged` event per field
12884
+ * that was supplied. Each field carries the SAME semantics as its
12885
+ * individual setter (`setName` / `setLocation` / `setType` /
12886
+ * `setIntegrationId` / `setLinkDeviceId` / `setRole`) — omitted fields are
12887
+ * left untouched; `null` clears `location` / `linkDeviceId` / `role`.
12888
+ * Idempotent. Used by the kernel's `spawnAccessoryChild` flow to collapse
12889
+ * the per-child meta pre-seed (4-6 individual setter calls) into one,
12890
+ * which is the dominant cost when reconciling a many-entity container. */
12891
+ applyInitialMeta: method(
12892
+ object({
12893
+ deviceId: number(),
12894
+ name: string().optional(),
12895
+ location: string().nullable().optional(),
12896
+ type: _enum(DeviceType).optional(),
12897
+ integrationId: string().optional(),
12898
+ linkDeviceId: number().nullable().optional(),
12899
+ role: string().nullable().optional()
12900
+ }),
12901
+ _void(),
12902
+ { kind: "mutation", auth: "admin" }
12903
+ ),
10362
12904
  /** Patch the device's hardware-identity metadata blob. Merges
10363
12905
  * `patch` over the current blob (shallow). Value `null` for a
10364
12906
  * given key removes that key. Drivers populate factual fields
@@ -10472,6 +13014,15 @@ const DevicePersistConfigPayloadSchema = object({
10472
13014
  object({ success: literal(true) }),
10473
13015
  { kind: "mutation", auth: "admin" }
10474
13016
  ),
13017
+ /** Cascade-delete every top-level device whose `integrationId` matches.
13018
+ * Children cascade automatically via the per-parent remove path.
13019
+ * Idempotent: a device whose `integrationId` was never set never matches.
13020
+ * Returns the count of top-level parents actually removed. */
13021
+ removeByIntegration: method(
13022
+ object({ integrationId: string() }),
13023
+ object({ removed: number() }),
13024
+ { kind: "mutation", auth: "admin" }
13025
+ ),
10475
13026
  // ── Stream profile map ────────────────────────────────────────────────────
10476
13027
  /** Get quality→streamId mapping for a camera. Derived from profileHint if not explicitly set. */
10477
13028
  getStreamProfileMap: method(
@@ -10615,6 +13166,15 @@ const DevicePersistConfigPayloadSchema = object({
10615
13166
  live: SettingsSchemaWithValuesSchema.nullable()
10616
13167
  })
10617
13168
  ),
13169
+ runDeviceAction: method(
13170
+ object({
13171
+ deviceId: number().int().nonnegative(),
13172
+ action: string().min(1),
13173
+ input: unknown()
13174
+ }),
13175
+ unknown(),
13176
+ { kind: "mutation" }
13177
+ ),
10618
13178
  updateDeviceField: method(
10619
13179
  object({
10620
13180
  deviceId: number(),
@@ -10669,7 +13229,11 @@ const DevicePersistConfigPayloadSchema = object({
10669
13229
  adoptDevice: method(
10670
13230
  object({
10671
13231
  addonId: string(),
10672
- candidate: DiscoveryCandidateSchema
13232
+ candidate: DiscoveryCandidateSchema,
13233
+ /** Owning integration id, stamped onto the new device's meta by the
13234
+ * device-manager forwarder so `removeByIntegration` can cascade it.
13235
+ * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
13236
+ integrationId: string().optional()
10673
13237
  }),
10674
13238
  DeviceSummarySchema,
10675
13239
  { kind: "mutation", auth: "admin" }
@@ -10690,7 +13254,11 @@ const DevicePersistConfigPayloadSchema = object({
10690
13254
  object({
10691
13255
  addonId: string(),
10692
13256
  type: _enum(DeviceType),
10693
- config: record(string(), unknown())
13257
+ config: record(string(), unknown()),
13258
+ /** Owning integration id, stamped onto the new device's meta by the
13259
+ * device-manager forwarder so `removeByIntegration` can cascade it.
13260
+ * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
13261
+ integrationId: string().optional()
10694
13262
  }),
10695
13263
  DeviceSummarySchema,
10696
13264
  { kind: "mutation", auth: "admin" }
@@ -10714,6 +13282,41 @@ const DevicePersistConfigPayloadSchema = object({
10714
13282
  FieldProbeResultSchema,
10715
13283
  { kind: "mutation", auth: "admin" }
10716
13284
  ),
13285
+ // ── Device-adoption operations (routed via CapabilityRegistry) ────────────
13286
+ //
13287
+ // These methods proxy to the `device-adoption` capability for an
13288
+ // integration-style addon (Home Assistant, …), routing by addonId —
13289
+ // the same hub-side proxy pattern as `discoverDevices`/`adoptDevice`
13290
+ // above. The admin UI's generic adopt modal calls them through this
13291
+ // singleton so it never needs a direct handle on the addon's
13292
+ // `device-adoption` provider.
13293
+ // getCandidate is not proxied — the adopt modal expands rows from
13294
+ // listCandidates' nested `children`, so a single-candidate fetch is
13295
+ // never needed at this layer.
13296
+ /** List adoption candidates for an integration via its device-adoption provider. */
13297
+ adoptionListCandidates: method(
13298
+ ListCandidatesInputSchema.extend({ addonId: string() }),
13299
+ ListCandidatesOutputSchema,
13300
+ { auth: "admin" }
13301
+ ),
13302
+ /** Trigger a discovery refresh on the integration's device-adoption provider. */
13303
+ adoptionRefresh: method(
13304
+ object({ addonId: string(), integrationId: string() }),
13305
+ AdoptionStatusSchema,
13306
+ { kind: "mutation", auth: "admin" }
13307
+ ),
13308
+ /** Adopt one or more discovered candidates via the device-adoption provider. */
13309
+ adoptionAdopt: method(
13310
+ AdoptInputSchema.extend({ addonId: string() }),
13311
+ AdoptResultSchema,
13312
+ { kind: "mutation", auth: "admin" }
13313
+ ),
13314
+ /** Release an adopted parent device via the device-adoption provider. */
13315
+ adoptionRelease: method(
13316
+ ReleaseInputSchema.extend({ addonId: string() }),
13317
+ _void(),
13318
+ { kind: "mutation", auth: "admin" }
13319
+ ),
10717
13320
  /**
10718
13321
  * Test a field value on an existing device (e.g. probe an RTSP URL).
10719
13322
  * Routes through the device-provider for the owning addon.
@@ -11004,7 +13607,11 @@ const NotificationRuleConditionsSchema = object({
11004
13607
  endHour: number()
11005
13608
  }).optional(),
11006
13609
  cooldownSeconds: number().optional(),
11007
- minDwellSeconds: number().optional()
13610
+ minDwellSeconds: number().optional(),
13611
+ /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
13612
+ * carrying a matching `data.eventType` string pass this condition. Rules without this field are
13613
+ * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
13614
+ eventTypeTokens: array(string()).readonly().optional()
11008
13615
  });
11009
13616
  const NotificationRuleTemplateSchema = object({
11010
13617
  title: string(),
@@ -11077,189 +13684,6 @@ const advancedNotifierCapability = {
11077
13684
  )
11078
13685
  }
11079
13686
  };
11080
- const RecordingModeSchema = _enum(["continuous", "motion", "scheduled", "composite"]);
11081
- const StreamPolicySchema = object({
11082
- streamId: string(),
11083
- mode: _enum(["always", "inherit"])
11084
- });
11085
- const ScheduleRuleSchema = object({
11086
- days: array(number()).readonly(),
11087
- startTime: string(),
11088
- endTime: string(),
11089
- mode: _enum(["continuous", "motion"])
11090
- });
11091
- const RecordingPolicySchema = object({
11092
- deviceId: number(),
11093
- mode: RecordingModeSchema,
11094
- streams: array(StreamPolicySchema).readonly(),
11095
- enabled: boolean(),
11096
- preBufferSec: number(),
11097
- postBufferSec: number(),
11098
- scheduleRules: array(ScheduleRuleSchema).readonly().optional()
11099
- });
11100
- const DataCategorySchema = _enum([
11101
- "recording:main",
11102
- "recording:mid",
11103
- "recording:sub",
11104
- "thumbnail:scrub",
11105
- "thumbnail:event"
11106
- ]);
11107
- const RecordingStorageConfigSchema = object({
11108
- deviceId: number(),
11109
- dataCategory: DataCategorySchema,
11110
- storageName: string(),
11111
- subDirectory: string(),
11112
- retentionDays: number().nullable(),
11113
- retentionGb: number().nullable()
11114
- });
11115
- const RecordingSegmentSchema = object({
11116
- id: string(),
11117
- deviceId: number(),
11118
- streamId: string(),
11119
- startTime: number(),
11120
- endTime: number(),
11121
- duration: number(),
11122
- path: string(),
11123
- storageName: string(),
11124
- subDirectory: string(),
11125
- sizeBytes: number(),
11126
- codec: _enum(["h264", "h265"]),
11127
- hasAudio: boolean()
11128
- });
11129
- const RecordingThumbnailSchema = object({
11130
- deviceId: number(),
11131
- timestamp: number(),
11132
- path: string(),
11133
- storageName: string(),
11134
- subDirectory: string(),
11135
- sizeBytes: number(),
11136
- category: _enum(["scrub", "event"])
11137
- });
11138
- const AvailabilityRangeSchema = object({
11139
- startTime: number(),
11140
- endTime: number(),
11141
- streams: array(string()).readonly()
11142
- });
11143
- const StorageUsageSchema = object({
11144
- totalBytes: number(),
11145
- segmentCount: number()
11146
- });
11147
- const StreamEstimateSchema = object({
11148
- bitrateKbps: number(),
11149
- retentionDays: number().nullable(),
11150
- retentionGb: number().nullable(),
11151
- estimatedGb: number(),
11152
- estimatedDaysAtCapacity: number().nullable()
11153
- });
11154
- const StorageEstimateSchema = object({
11155
- perStream: record(string(), StreamEstimateSchema),
11156
- thumbnails: object({ estimatedGb: number() }),
11157
- totalEstimatedGb: number(),
11158
- motionEstimate: object({
11159
- avgEventsPerDay: number(),
11160
- avgDurationSec: number(),
11161
- dutyCyclePercent: number()
11162
- }).optional()
11163
- });
11164
- const MotionStatsSchema = object({
11165
- totalEvents: number(),
11166
- avgDurationSec: number(),
11167
- avgEventsPerDay: number(),
11168
- dutyCyclePercent: number()
11169
- });
11170
- const DeviceIdInput = object({ deviceId: number() });
11171
- const EnableInput = object({
11172
- deviceId: number(),
11173
- policy: RecordingPolicySchema.omit({ deviceId: true }),
11174
- storageOverrides: array(RecordingStorageConfigSchema.omit({ deviceId: true })).readonly().optional(),
11175
- ffmpegOverrides: record(string(), unknown()).optional()
11176
- });
11177
- const TimeRangeInput = object({
11178
- deviceId: number(),
11179
- startTime: number(),
11180
- endTime: number()
11181
- });
11182
- const StreamTimeRangeInput = object({
11183
- deviceId: number(),
11184
- streamId: string(),
11185
- startTime: number(),
11186
- endTime: number()
11187
- });
11188
- const PlaylistInput = object({
11189
- deviceId: number(),
11190
- streamId: string(),
11191
- startTime: number(),
11192
- endTime: number(),
11193
- live: boolean().optional()
11194
- });
11195
- const ThumbnailInput = object({
11196
- deviceId: number(),
11197
- timestamp: number(),
11198
- category: string().optional()
11199
- });
11200
- const DeviceStreamInput = object({
11201
- deviceId: number(),
11202
- streamId: string()
11203
- });
11204
- const StorageEstimateInput = object({
11205
- deviceId: number(),
11206
- motionInput: object({
11207
- avgEventsPerDay: number(),
11208
- avgDurationSec: number()
11209
- }).optional()
11210
- });
11211
- const RetentionConfigInput = object({
11212
- deviceId: number(),
11213
- dataCategory: DataCategorySchema
11214
- });
11215
- const SetPolicyInput = object({
11216
- deviceId: number(),
11217
- policy: RecordingPolicySchema.omit({ deviceId: true })
11218
- });
11219
- const UpdateConfigInput = object({
11220
- deviceId: number(),
11221
- policy: RecordingPolicySchema.omit({ deviceId: true }),
11222
- ffmpegOverrides: record(string(), unknown()).optional()
11223
- });
11224
- ({
11225
- methods: {
11226
- // ── Status ────────────────────────────────────────────────────────
11227
- getStatus: method(_void(), object({
11228
- activeRecordings: number(),
11229
- totalSegments: number(),
11230
- totalSizeMB: number()
11231
- })),
11232
- // ── Lifecycle ─────────────────────────────────────────────────────
11233
- enable: method(EnableInput, _void(), { kind: "mutation", auth: "admin" }),
11234
- disable: method(DeviceIdInput, _void(), { kind: "mutation", auth: "admin" }),
11235
- // ── Config ────────────────────────────────────────────────────────
11236
- getConfig: method(DeviceIdInput, RecordingPolicySchema.nullable()),
11237
- updateConfig: method(UpdateConfigInput, _void(), { kind: "mutation", auth: "admin" }),
11238
- // ── Playback ──────────────────────────────────────────────────────
11239
- getPlaylist: method(PlaylistInput, string()),
11240
- getThumbnail: method(ThumbnailInput, RecordingThumbnailSchema.nullable()),
11241
- getSegments: method(StreamTimeRangeInput, array(RecordingSegmentSchema).readonly()),
11242
- getAvailability: method(TimeRangeInput, array(AvailabilityRangeSchema).readonly()),
11243
- // ── Storage ───────────────────────────────────────────────────────
11244
- estimateStorage: method(StorageEstimateInput, StorageEstimateSchema),
11245
- estimateGlobalStorage: method(_void(), StorageEstimateSchema),
11246
- getStorageUsage: method(DeviceStreamInput, StorageUsageSchema),
11247
- // ── Policy ────────────────────────────────────────────────────────
11248
- setPolicy: method(SetPolicyInput, _void(), { kind: "mutation", auth: "admin" }),
11249
- getPolicy: method(DeviceIdInput, RecordingPolicySchema.nullable()),
11250
- getPolicyStatus: method(DeviceIdInput, object({
11251
- deviceId: number(),
11252
- enabled: boolean(),
11253
- mode: RecordingModeSchema,
11254
- activeStreams: number()
11255
- }).nullable()),
11256
- // ── Retention ─────────────────────────────────────────────────────
11257
- getRetentionConfig: method(RetentionConfigInput, RecordingStorageConfigSchema.nullable()),
11258
- updateRetentionConfig: method(RecordingStorageConfigSchema, _void(), { kind: "mutation", auth: "admin" }),
11259
- // ── Motion ────────────────────────────────────────────────────────
11260
- getMotionStats: method(TimeRangeInput, MotionStatsSchema)
11261
- }
11262
- });
11263
13687
  ({
11264
13688
  deviceTypes: [DeviceType.Camera]
11265
13689
  });
@@ -11308,26 +13732,38 @@ const MotionEventSchema = object({
11308
13732
  ...BaseEventFields,
11309
13733
  kind: literal("motion"),
11310
13734
  regionCount: number(),
13735
+ /** Heavy JSON array — omitted in slim projection. */
11311
13736
  regions: array(object({
11312
13737
  bbox: BoundingBoxSchema,
11313
13738
  pixelCount: number(),
11314
13739
  intensity: number()
11315
- })).readonly(),
11316
- frameWidth: number(),
11317
- frameHeight: number()
13740
+ })).readonly().optional(),
13741
+ /** Omitted in slim projection. */
13742
+ frameWidth: number().optional(),
13743
+ /** Omitted in slim projection. */
13744
+ frameHeight: number().optional(),
13745
+ /** Populated by B5 (recording playback URL for this event). */
13746
+ mediaUrl: string().optional()
11318
13747
  });
11319
13748
  const ObjectEventSchema = object({
11320
13749
  ...BaseEventFields,
11321
13750
  kind: literal("object"),
11322
- trackId: string(),
13751
+ /** Omitted in slim projection. */
13752
+ trackId: string().optional(),
11323
13753
  className: string(),
11324
13754
  label: string().optional(),
11325
- confidence: number(),
11326
- bbox: BoundingBoxSchema,
11327
- zones: array(string()).readonly(),
11328
- state: TrackStateSchema,
13755
+ /** Omitted in slim projection. */
13756
+ confidence: number().optional(),
13757
+ /** Heavy JSON — omitted in slim projection. */
13758
+ bbox: BoundingBoxSchema.optional(),
13759
+ /** Heavy JSON — omitted in slim projection. */
13760
+ zones: array(string()).readonly().optional(),
13761
+ /** Omitted in slim projection. */
13762
+ state: TrackStateSchema.optional(),
11329
13763
  /** MediaStore key for the crop attached to this event (if any). */
11330
- mediaKey: string().optional()
13764
+ mediaKey: string().optional(),
13765
+ /** Populated by B5 (recording playback URL for this event). */
13766
+ mediaUrl: string().optional()
11331
13767
  });
11332
13768
  const AudioEventSchema = object({
11333
13769
  ...BaseEventFields,
@@ -11338,7 +13774,9 @@ const AudioEventSchema = object({
11338
13774
  className: string(),
11339
13775
  originalClass: string().optional(),
11340
13776
  score: number()
11341
- }).optional()
13777
+ }).optional(),
13778
+ /** Populated by B5 (recording playback URL for this event). */
13779
+ mediaUrl: string().optional()
11342
13780
  });
11343
13781
  const MediaFileSchema = object({
11344
13782
  key: string(),
@@ -11353,7 +13791,12 @@ const DeviceEventQueryInput = object({
11353
13791
  deviceId: number(),
11354
13792
  since: number().optional(),
11355
13793
  until: number().optional(),
11356
- limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)
13794
+ limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
13795
+ /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
13796
+ * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
13797
+ * exact behaviour. Callers may omit this field — the store defaults to
13798
+ * `full` when not provided. */
13799
+ projection: _enum(["full", "slim"]).optional()
11357
13800
  });
11358
13801
  const ObjectEventQueryInput = DeviceEventQueryInput.extend({
11359
13802
  classFilter: string().optional()
@@ -11408,6 +13851,37 @@ const TrackedDetectionSchema = object({
11408
13851
  DeviceEventQueryInput,
11409
13852
  array(AudioEventSchema).readonly()
11410
13853
  ),
13854
+ // ── Density (timeline histogram) ──────────────────────────
13855
+ /** Server-side bucketed event counts for the 24-hour timeline.
13856
+ * Returns one entry per non-empty bucket; empty buckets are omitted. */
13857
+ getEventDensity: method(
13858
+ object({
13859
+ deviceId: number(),
13860
+ since: number(),
13861
+ until: number(),
13862
+ bucketMs: number().int().positive()
13863
+ }),
13864
+ array(object({
13865
+ bucketStart: number(),
13866
+ motion: number().int(),
13867
+ object: number().int(),
13868
+ audio: number().int()
13869
+ })).readonly()
13870
+ ),
13871
+ // ── Maintenance ───────────────────────────────────────────
13872
+ /**
13873
+ * Delete all events (motion + object + audio) for the given device
13874
+ * that are older than `cutoffMs` (exclusive), and delete their
13875
+ * thumbnails in lockstep. Returns per-kind deleted counts.
13876
+ *
13877
+ * Called by Phase B3 recorder orchestration to keep event history
13878
+ * aligned with available footage.
13879
+ */
13880
+ pruneEventsBefore: method(
13881
+ object({ deviceId: number(), cutoffMs: number() }),
13882
+ object({ motion: number().int(), object: number().int(), audio: number().int() }),
13883
+ { kind: "mutation", auth: "admin" }
13884
+ ),
11411
13885
  // ── Media ─────────────────────────────────────────────────
11412
13886
  getEventMedia: method(
11413
13887
  object({ eventId: string() }),
@@ -11761,32 +14235,102 @@ const EventItemSchema = object({
11761
14235
  )
11762
14236
  }
11763
14237
  });
11764
- const SegmentSchema = object({
11765
- id: string(),
11766
- startTs: number(),
11767
- // unix ms
11768
- endTs: number(),
11769
- durationSec: number(),
11770
- sizeBytes: number().optional()
14238
+ const RecordingStatusSchema = object({
14239
+ deviceId: number(),
14240
+ enabled: boolean(),
14241
+ activeMode: _enum(["off", "continuous"]),
14242
+ nodeId: string(),
14243
+ storageBytes: number()
14244
+ });
14245
+ const RecordingRangeSchema = object({
14246
+ profile: string(),
14247
+ startMs: number(),
14248
+ endMs: number()
14249
+ });
14250
+ const RecordingAvailabilitySchema = object({
14251
+ deviceId: number(),
14252
+ ranges: array(RecordingRangeSchema)
14253
+ });
14254
+ const RecordingManifestSchema = object({
14255
+ deviceId: number(),
14256
+ /** Local filesystem path to the master playlist; null when no recording exists for the requested range. */
14257
+ localMasterPath: string().nullable(),
14258
+ /** HTTP(S) URL to the master playlist on the recording node's playback server
14259
+ * (the PRIMARY candidate); null when no recording / server. Carries the
14260
+ * scoped playback token in its path. */
14261
+ playbackUrl: string().nullable(),
14262
+ /**
14263
+ * Candidate master-playlist URLs the client tries in order (LAN first, then
14264
+ * remote — Tailscale/Cloudflare if the operator configured extra hosts), each
14265
+ * carrying the same scoped token. `playbackUrl` is the first entry. Empty when
14266
+ * there is no recording / server.
14267
+ */
14268
+ playbackEndpoints: array(string())
14269
+ });
14270
+ const RecordingDeviceUsageSchema = object({
14271
+ deviceId: number(),
14272
+ usedBytes: number()
14273
+ });
14274
+ const RecordingLocationUsageSchema = object({
14275
+ /** StorageLocation id; null for the legacy/degraded single-root fallback. */
14276
+ locationId: string().nullable(),
14277
+ /** Bytes of recordings stored on this location. */
14278
+ usedBytes: number(),
14279
+ /** Free bytes on the location's volume; null when capacity is unknown (remote). */
14280
+ availableBytes: number().nullable(),
14281
+ /** Total bytes of the location's volume; null when unknown. */
14282
+ totalBytes: number().nullable()
14283
+ });
14284
+ const RecordingStorageUsageSchema = object({
14285
+ nodeId: string(),
14286
+ totalUsedBytes: number(),
14287
+ devices: array(RecordingDeviceUsageSchema),
14288
+ locations: array(RecordingLocationUsageSchema)
11771
14289
  });
11772
14290
  ({
11773
- deviceTypes: [DeviceType.Camera],
11774
14291
  methods: {
11775
- getSegments: method(
11776
- object({
11777
- deviceId: number(),
11778
- from: number().optional(),
11779
- to: number().optional()
11780
- }),
11781
- array(SegmentSchema)
14292
+ getAvailability: method(
14293
+ object({ deviceId: number(), fromMs: number(), toMs: number() }),
14294
+ RecordingAvailabilitySchema,
14295
+ { kind: "query", auth: "admin" }
11782
14296
  ),
11783
- getPlaybackUrl: method(
11784
- object({ deviceId: number(), segmentId: string() }),
11785
- string().nullable()
14297
+ getPlaybackManifest: method(
14298
+ object({ deviceId: number(), fromMs: number(), toMs: number() }),
14299
+ RecordingManifestSchema,
14300
+ { kind: "query", auth: "admin" }
11786
14301
  ),
11787
- getThumbnailAt: method(
11788
- object({ deviceId: number(), timestamp: number() }),
11789
- object({ base64: string(), contentType: string() }).nullable()
14302
+ getStorageUsage: method(
14303
+ object({}),
14304
+ RecordingStorageUsageSchema,
14305
+ { kind: "query", auth: "admin" }
14306
+ ),
14307
+ getDeviceConfig: method(
14308
+ object({ deviceId: number() }),
14309
+ RecordingConfigSchema,
14310
+ { kind: "query", auth: "admin" }
14311
+ ),
14312
+ setDeviceConfig: method(
14313
+ object({ deviceId: number(), config: RecordingConfigSchema }),
14314
+ RecordingConfigSchema,
14315
+ { kind: "mutation", auth: "admin" }
14316
+ ),
14317
+ /** Re-scan this device's footage from disk (stat sizes) and reseed the
14318
+ * index, then return the fresh status. */
14319
+ rescanStorage: method(
14320
+ object({ deviceId: number() }),
14321
+ RecordingStatusSchema,
14322
+ { kind: "mutation", auth: "admin" }
14323
+ ),
14324
+ /** Apply this device's retention policy to footage now; returns the oldest
14325
+ * surviving footage start (the retention floor) or null if no footage. */
14326
+ pruneFootage: method(
14327
+ object({ deviceId: number() }),
14328
+ object({
14329
+ floorMs: number().nullable(),
14330
+ deletedBuckets: number().int(),
14331
+ reclaimedBytes: number().int()
14332
+ }),
14333
+ { kind: "mutation", auth: "admin" }
11790
14334
  )
11791
14335
  }
11792
14336
  });
@@ -11799,13 +14343,19 @@ const StreamSourceEntrySchema = object({
11799
14343
  fps: number().optional(),
11800
14344
  bitrate: number().optional(),
11801
14345
  codec: string().optional(),
11802
- profileHint: _enum(["high", "mid", "low"]).optional(),
14346
+ profileHint: CamProfileSchema.optional(),
11803
14347
  sdp: string().optional()
11804
14348
  });
11805
14349
  const ConfigEntrySchema = object({
11806
14350
  key: string(),
11807
14351
  value: unknown()
11808
14352
  });
14353
+ const RawStateResultSchema = object({
14354
+ /** Originating provider id, e.g. 'homeassistant' | 'reolink' | 'hikvision'. */
14355
+ source: string(),
14356
+ /** Opaque, DISPLAY-SAFE upstream blob (no secrets/PII). */
14357
+ data: record(string(), unknown())
14358
+ });
11809
14359
  ({
11810
14360
  methods: {
11811
14361
  /**
@@ -11837,6 +14387,21 @@ const ConfigEntrySchema = object({
11837
14387
  _void(),
11838
14388
  { kind: "mutation" }
11839
14389
  ),
14390
+ /**
14391
+ * Invoke a device custom action on a forked/remote device (the
14392
+ * cross-process transport for `IDevice.runDeviceAction`). Mirrors
14393
+ * `setConfig` — the device-manager calls this when the device is not
14394
+ * hub-local.
14395
+ */
14396
+ runAction: method(
14397
+ object({
14398
+ deviceId: number(),
14399
+ action: string().min(1),
14400
+ input: unknown()
14401
+ }),
14402
+ unknown(),
14403
+ { kind: "mutation" }
14404
+ ),
11840
14405
  /**
11841
14406
  * Invoke `IDevice.removeDevice()` so the driver can release resources
11842
14407
  * (close sockets, stop background tasks, …). The device-manager still
@@ -11864,6 +14429,18 @@ const ConfigEntrySchema = object({
11864
14429
  getSettingsSchema: method(
11865
14430
  object({ deviceId: number() }),
11866
14431
  unknown().nullable()
14432
+ ),
14433
+ /**
14434
+ * Opt-in: return the device's RAW upstream state (the provider's
14435
+ * cached values) as a display-safe `{ source, data }` blob. Returns
14436
+ * `null` when the device exposes no raw state — the State panel hides
14437
+ * its Raw toggle in that case. One-shot (read the provider's existing
14438
+ * cache; no upstream round-trip).
14439
+ */
14440
+ getRawState: method(
14441
+ object({ deviceId: number() }),
14442
+ RawStateResultSchema.nullable(),
14443
+ { auth: "protected" }
11867
14444
  )
11868
14445
  }
11869
14446
  });
@@ -11921,6 +14498,16 @@ object({
11921
14498
  )
11922
14499
  }
11923
14500
  });
14501
+ ({
14502
+ deviceTypes: [DeviceType.Button],
14503
+ methods: {
14504
+ press: method(
14505
+ object({ deviceId: number().int().nonnegative() }),
14506
+ _void(),
14507
+ { kind: "mutation", auth: "admin" }
14508
+ )
14509
+ }
14510
+ });
11924
14511
  const OsdOverlayKindEnum = _enum(["text", "timestamp", "watermark"]);
11925
14512
  const OsdPositionEnum = _enum([
11926
14513
  "top-left",
@@ -11983,18 +14570,72 @@ const OsdOverlayPatchSchema = object({
11983
14570
  }
11984
14571
  });
11985
14572
  object({
11986
- childDeviceIds: array(number()).readonly()
14573
+ /** All accessory children of the parent. */
14574
+ childDeviceIds: array(number()).readonly(),
14575
+ /** Subset of `childDeviceIds` the operator hid from the UI. The order
14576
+ * is irrelevant; the array is treated as a set by consumers. */
14577
+ hiddenChildIds: array(number()).readonly()
11987
14578
  });
11988
14579
  ({
11989
- deviceTypes: [DeviceType.Camera, DeviceType.Hub],
14580
+ // Cameras + Hubs are the historical consumers; the HA integration
14581
+ // landed in Phase E adds Switch / Light / Sensor / Thermostat / Cover
14582
+ // / Lock / Fan / MediaPlayer / AlarmPanel / Generic as parent types
14583
+ // for adopted HA devices whose entity-children sit under accessories.
14584
+ deviceTypes: [
14585
+ DeviceType.Camera,
14586
+ DeviceType.Hub,
14587
+ DeviceType.Switch,
14588
+ DeviceType.Light,
14589
+ DeviceType.Sensor,
14590
+ DeviceType.Thermostat,
14591
+ DeviceType.Cover,
14592
+ DeviceType.Lock,
14593
+ DeviceType.Fan,
14594
+ DeviceType.MediaPlayer,
14595
+ DeviceType.AlarmPanel,
14596
+ DeviceType.Generic
14597
+ ],
14598
+ methods: {
14599
+ /**
14600
+ * Toggle the UI-visibility of a single accessory child. Hidden
14601
+ * children stay registered and continue to receive state updates;
14602
+ * they're omitted only from the parent's UI accessories panel.
14603
+ *
14604
+ * Idempotent — hiding an already-hidden child or unhiding a
14605
+ * non-hidden child is a no-op. Providers that don't support
14606
+ * per-child visibility may implement this as a no-op (the UI hide
14607
+ * toggle gracefully degrades).
14608
+ */
14609
+ setChildHidden: method(
14610
+ object({
14611
+ deviceId: number().int().nonnegative(),
14612
+ childDeviceId: number().int().nonnegative(),
14613
+ hidden: boolean()
14614
+ }),
14615
+ _void(),
14616
+ { kind: "mutation", auth: "admin" }
14617
+ )
14618
+ },
11990
14619
  events: {
11991
14620
  /**
11992
14621
  * Emitted when a child device is created, removed, or its parent
11993
- * assignment changes. Payload carries the fresh list.
14622
+ * assignment changes. Payload carries the fresh list and the
14623
+ * hidden subset.
11994
14624
  */
11995
14625
  onAccessoriesChanged: { data: object({
11996
14626
  deviceId: number(),
11997
- childDeviceIds: array(number()).readonly()
14627
+ childDeviceIds: array(number()).readonly(),
14628
+ hiddenChildIds: array(number()).readonly()
14629
+ }) },
14630
+ /**
14631
+ * Emitted when the operator toggles a child's UI-visibility.
14632
+ * Subscribers (admin UI accessories panel) re-render off this
14633
+ * signal without re-fetching the full status block.
14634
+ */
14635
+ onChildVisibilityChanged: { data: object({
14636
+ deviceId: number(),
14637
+ childDeviceId: number(),
14638
+ hidden: boolean()
11998
14639
  }) }
11999
14640
  }
12000
14641
  });
@@ -12015,6 +14656,12 @@ const IntercomStatusSchema = object({
12015
14656
  /** Firmware ability cached at first session creation. Null until probed. */
12016
14657
  ability: IntercomAbilitySchema.nullable()
12017
14658
  });
14659
+ const TalkAudioCodecSchema = _enum([
14660
+ "opus",
14661
+ "s16le",
14662
+ "g711ulaw",
14663
+ "g711alaw"
14664
+ ]);
12018
14665
  ({
12019
14666
  deviceTypes: [DeviceType.Camera],
12020
14667
  methods: {
@@ -12059,20 +14706,35 @@ const IntercomStatusSchema = object({
12059
14706
  { kind: "mutation", auth: "admin" }
12060
14707
  ),
12061
14708
  /**
12062
- * Push a chunk of PCM s16le mono onto the active raw-PCM talk
12063
- * session. Frames are encoded to the firmware's expected codec
12064
- * (Reolink: IMA ADPCM @ camera sample rate; Hikvision: G.711 @
12065
- * 8 kHz) inside the provider callers must resample upstream to
12066
- * the rate the camera negotiated (typical: 16 kHz Reolink,
12067
- * 8 kHz Hikvision). PCM is shipped base64-encoded so the payload
12068
- * survives JSON serialization across tRPC.
14709
+ * Push one chunk of talk-back audio onto the active talk session.
14710
+ * The cap is codec-agnostic: the caller declares (or omits) the
14711
+ * wire format via `codec`; the provider decides between passthrough
14712
+ * (when the wire codec matches the camera's native talk channel),
14713
+ * transcoding via the `audio-codec` cap, or rejecting the call.
14714
+ *
14715
+ * Callers do NOT need to know the camera's wire format or sample
14716
+ * rate — that information lives entirely inside the provider.
14717
+ *
14718
+ * Sequence numbers MUST be monotonic per talk session; older frames
14719
+ * arriving after newer ones are dropped to avoid smearing the
14720
+ * downstream encoder state (G.711 is stateless but IMA ADPCM's
14721
+ * predictor would corrupt with re-ordering).
12069
14722
  */
12070
- pushTalkPcm: method(
14723
+ pushTalkAudio: method(
12071
14724
  object({
12072
14725
  deviceId: number(),
12073
- /** PCM frames as little-endian s16, mono. Base64-encoded so
12074
- * the payload survives tRPC JSON serialization. */
12075
- pcmBase64: string(),
14726
+ /** Audio bytes for ONE frame, base64-encoded so the payload
14727
+ * survives tRPC JSON serialization. */
14728
+ audioBase64: string(),
14729
+ /** Wire codec of the payload. Omit to let the provider default
14730
+ * to its native expected format (s16le @ provider-native rate,
14731
+ * mono). See {@link TalkAudioCodecSchema} for the supported set. */
14732
+ codec: TalkAudioCodecSchema.optional(),
14733
+ /** Sample rate (Hz). REQUIRED for `s16le`; advisory for
14734
+ * `opus` (encoder clock); ignored for `g711*` (implied 8000). */
14735
+ sampleRate: number().int().positive().optional(),
14736
+ /** Channel count. Default 1. */
14737
+ channels: number().int().positive().optional(),
12076
14738
  /** Sequence number for ordering / dropping out-of-order frames. */
12077
14739
  sequenceNumber: number().int()
12078
14740
  }),
@@ -12166,6 +14828,10 @@ const HardwareEncodersSchema = object({
12166
14828
  defaultH265: HardwareEncoderIdSchema,
12167
14829
  probedAt: number()
12168
14830
  });
14831
+ const HardwareDecodeAccelsSchema = object({
14832
+ methods: array(string()).readonly(),
14833
+ probedAt: number()
14834
+ });
12169
14835
  const HardwarePlatformSchema = _enum(["darwin", "linux", "win32"]);
12170
14836
  const HardwareArchSchema = _enum(["arm64", "x64"]);
12171
14837
  const GpuInfoSchema = object({
@@ -12234,6 +14900,16 @@ const ResolvedInferenceConfigSchema = object({
12234
14900
  _void(),
12235
14901
  HardwareEncodersSchema,
12236
14902
  { kind: "mutation", auth: "admin" }
14903
+ ),
14904
+ /**
14905
+ * Decode-side hw-accel probe — the `-hwaccel` methods the configured ffmpeg
14906
+ * binary supports (via `ffmpeg -hwaccels`). Cached after first call.
14907
+ */
14908
+ getHardwareDecodeAccels: method(_void(), HardwareDecodeAccelsSchema),
14909
+ refreshHardwareDecodeAccels: method(
14910
+ _void(),
14911
+ HardwareDecodeAccelsSchema,
14912
+ { kind: "mutation", auth: "admin" }
12237
14913
  )
12238
14914
  }
12239
14915
  });
@@ -12923,6 +15599,7 @@ const ClientNetworkStatsSchema = object({
12923
15599
  rttMs: number(),
12924
15600
  jitterMs: number(),
12925
15601
  estimatedBandwidthKbps: number(),
15602
+ packetLossPercent: number().min(0).max(100),
12926
15603
  lastUpdated: number()
12927
15604
  });
12928
15605
  const DeviceNetworkStatsSchema = object({
@@ -12945,7 +15622,8 @@ const DeviceNetworkStatsSchema = object({
12945
15622
  deviceId: number(),
12946
15623
  rttMs: number().min(0).max(6e4),
12947
15624
  jitterMs: number().min(0).max(1e4),
12948
- estimatedBandwidthKbps: number().min(0).max(1e6)
15625
+ estimatedBandwidthKbps: number().min(0).max(1e6),
15626
+ packetLossPercent: number().min(0).max(100)
12949
15627
  }),
12950
15628
  _void(),
12951
15629
  { kind: "mutation" }
@@ -13170,6 +15848,24 @@ const AvailableIntegrationTypeSchema = object({
13170
15848
  color: string(),
13171
15849
  instanceMode: string(),
13172
15850
  discoveryMode: string(),
15851
+ /**
15852
+ * Which integration-marker cap the addon declared, so the wizard can
15853
+ * branch on CAP — never on addon name. `device-adoption` integrations
15854
+ * (Home Assistant, …) route through the broker step (Approach A);
15855
+ * `device-provider` integrations (Reolink/Frigate/ONVIF) keep the
15856
+ * legacy config → discovery flow.
15857
+ */
15858
+ kind: _enum(["device-adoption", "device-provider"]),
15859
+ /**
15860
+ * For `device-adoption` addons: the broker kind to create/link
15861
+ * (e.g. `home-assistant`), declared in the addon manifest. `null` for
15862
+ * `device-provider` addons, which carry no broker.
15863
+ */
15864
+ brokerKind: string().nullable(),
15865
+ /** True when the integration's source system exposes locations the adoption
15866
+ * flow can import (e.g. HA areas). Drives the adopt modal's "import
15867
+ * locations" checkbox. Provider-declared in the addon manifest. */
15868
+ supportsLocationImport: boolean(),
13173
15869
  existingInstances: array(object({ id: string(), name: string() })),
13174
15870
  canAdd: boolean()
13175
15871
  });
@@ -13776,10 +16472,15 @@ var EventCategory = /* @__PURE__ */ ((EventCategory2) => {
13776
16472
  EventCategory2["DeviceSettingsUpdated"] = "device.settings-updated";
13777
16473
  EventCategory2["DeviceBindingsChanged"] = "device.bindings-changed";
13778
16474
  EventCategory2["DeviceMetaChanged"] = "device.meta-changed";
16475
+ EventCategory2["DeviceSourceInfoChanged"] = "device.source-info-changed";
13779
16476
  EventCategory2["DeviceStreamsRegistered"] = "device.streams-registered";
16477
+ EventCategory2["DeviceProvisioned"] = "device.provisioned";
16478
+ EventCategory2["DeviceReady"] = "device.ready";
13780
16479
  EventCategory2["IntegrationEnabled"] = "integration.enabled";
13781
16480
  EventCategory2["IntegrationDisabled"] = "integration.disabled";
13782
16481
  EventCategory2["IntegrationDeleted"] = "integration.deleted";
16482
+ EventCategory2["BrokerStatusChanged"] = "broker.status-changed";
16483
+ EventCategory2["BrokerMessage"] = "broker.message";
13783
16484
  EventCategory2["ProviderStarted"] = "provider.started";
13784
16485
  EventCategory2["ProviderStopped"] = "provider.stopped";
13785
16486
  EventCategory2["ProcessCrashed"] = "process.crashed";
@@ -13813,7 +16514,9 @@ var EventCategory = /* @__PURE__ */ ((EventCategory2) => {
13813
16514
  EventCategory2["StreamParamsChanged"] = "stream-params.changed";
13814
16515
  EventCategory2["DeviceStateChanged"] = "device.state-changed";
13815
16516
  EventCategory2["BatteryOnStatusChanged"] = "battery.onStatusChanged";
16517
+ EventCategory2["BatteryOnWakeStarted"] = "battery.onWakeStarted";
13816
16518
  EventCategory2["DoorbellOnPressed"] = "doorbell.onPressed";
16519
+ EventCategory2["EventEmitted"] = "event-emitter.event";
13817
16520
  EventCategory2["PipelineEngineMetricsSnapshot"] = "pipeline.engine-metrics-snapshot";
13818
16521
  EventCategory2["ClusterTopologySnapshot"] = "cluster.topology-snapshot";
13819
16522
  EventCategory2["MetricsNodeResourcesSnapshot"] = "metrics.node-resources-snapshot";
@@ -13896,6 +16599,27 @@ function emitReadiness(bus, params) {
13896
16599
  }
13897
16600
  ));
13898
16601
  }
16602
+ function createDurableState(deps) {
16603
+ const get = async () => {
16604
+ const store = await deps.read();
16605
+ const raw = store[deps.key];
16606
+ if (raw === void 0) return deps.fallback;
16607
+ const parsed = deps.schema.safeParse(raw);
16608
+ if (!parsed.success) {
16609
+ deps.onParseError?.(deps.key, parsed.error);
16610
+ return deps.fallback;
16611
+ }
16612
+ return parsed.data;
16613
+ };
16614
+ const set = async (next) => {
16615
+ const validated = deps.schema.parse(next);
16616
+ await deps.write({ [deps.key]: validated });
16617
+ };
16618
+ const update = async (fn2) => {
16619
+ await set(fn2(await get()));
16620
+ };
16621
+ return { get, set, update };
16622
+ }
13899
16623
  class BaseAddon {
13900
16624
  _ctx = null;
13901
16625
  _config;
@@ -14139,12 +16863,18 @@ class BaseAddon {
14139
16863
  // ── Lifecycle event emission ────────────────────────────────────────────
14140
16864
  emitLifecycle(category, data) {
14141
16865
  try {
14142
- this._ctx?.eventBus.emit({
14143
- id: `${this._ctx.id}-${Date.now()}`,
16866
+ const ctx = this._ctx;
16867
+ if (!ctx) return;
16868
+ ctx.eventBus.emit({
16869
+ id: `${ctx.id}-${Date.now()}`,
14144
16870
  timestamp: /* @__PURE__ */ new Date(),
14145
- source: { type: "addon", id: this._ctx.id, nodeId: this._ctx.kernel.localNodeId ?? "hub" },
16871
+ source: { type: "addon", id: ctx.id, nodeId: ctx.kernel.localNodeId ?? "hub" },
14146
16872
  category,
14147
- data: data ?? {}
16873
+ // Always carry `addonId` in the payload (the lifecycle event
16874
+ // contract declares it) so consumers — e.g. the alerts builder —
16875
+ // can name the addon without reaching into `source`. An explicit
16876
+ // `data.addonId` still wins if a caller provides one.
16877
+ data: { addonId: ctx.id, ...data ?? {} }
14148
16878
  });
14149
16879
  } catch {
14150
16880
  }
@@ -14217,6 +16947,44 @@ class BaseAddon {
14217
16947
  }
14218
16948
  this._config = resolved;
14219
16949
  }
16950
+ /**
16951
+ * Typed durable handle over ONE key of this addon's store. The whole
16952
+ * Zod-validated value round-trips on every read/write — no hand-listed
16953
+ * fields, so a field can never be silently dropped on persist. Reads use
16954
+ * the same retry budget as config resolution; a corrupt/legacy blob logs
16955
+ * a warning and falls back rather than crashing boot.
16956
+ */
16957
+ state(key, schema, fallback) {
16958
+ return createDurableState({
16959
+ key,
16960
+ schema,
16961
+ fallback,
16962
+ read: () => this.readAddonStoreWithRetry(),
16963
+ write: async (patch) => {
16964
+ await this._ctx?.settings?.writeAddonStore(patch);
16965
+ },
16966
+ onParseError: (k, e) => this._ctx?.logger?.warn?.(
16967
+ `durable-state: stored "${k}" failed validation — using fallback`,
16968
+ { meta: { addonId: this._ctx?.id, key: k, error: String(e) } }
16969
+ )
16970
+ });
16971
+ }
16972
+ /** Per-device variant of {@link state}, backed by the per-device store. */
16973
+ deviceState(deviceId, key, schema, fallback) {
16974
+ return createDurableState({
16975
+ key,
16976
+ schema,
16977
+ fallback,
16978
+ read: async () => await this._ctx?.settings?.readDeviceStore(deviceId) ?? {},
16979
+ write: async (patch) => {
16980
+ await this._ctx?.settings?.writeDeviceStore(deviceId, patch);
16981
+ },
16982
+ onParseError: (k, e) => this._ctx?.logger?.warn?.(
16983
+ `durable-state: stored device ${deviceId} "${k}" failed validation — using fallback`,
16984
+ { meta: { addonId: this._ctx?.id, deviceId, key: k, error: String(e) } }
16985
+ )
16986
+ });
16987
+ }
14220
16988
  /**
14221
16989
  * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
14222
16990
  * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
@@ -14322,6 +17090,11 @@ class RuleEngine {
14322
17090
  const hour = now.getHours();
14323
17091
  if (hour < startHour || hour >= endHour) return false;
14324
17092
  }
17093
+ if (conditions.eventTypeTokens?.length) {
17094
+ const rawToken = data["eventType"];
17095
+ if (typeof rawToken !== "string") return false;
17096
+ if (!conditions.eventTypeTokens.includes(rawToken)) return false;
17097
+ }
14325
17098
  return true;
14326
17099
  }
14327
17100
  }
@@ -14416,7 +17189,8 @@ class AuditLog {
14416
17189
  const EVENT_CATEGORIES = [
14417
17190
  EventCategory.DetectionRaw,
14418
17191
  EventCategory.DetectionResult,
14419
- EventCategory.DetectionCameraNative
17192
+ EventCategory.DetectionCameraNative,
17193
+ EventCategory.EventEmitted
14420
17194
  ];
14421
17195
  const DEFAULT_NOTIFIER_CONFIG = {
14422
17196
  defaultCooldownSeconds: 60,