piphi-runtime-kit-python 0.7.1__py3-none-any.whl → 0.9.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. piphi_runtime_kit_python/__init__.py +108 -69
  2. piphi_runtime_kit_python/adapters/fastapi.py +5 -4
  3. piphi_runtime_kit_python/automations.py +5 -4
  4. piphi_runtime_kit_python/camera.py +237 -0
  5. piphi_runtime_kit_python/runtime/__init__.py +25 -25
  6. piphi_runtime_kit_python/runtime/auth.py +2 -2
  7. piphi_runtime_kit_python/runtime/config_sync.py +4 -3
  8. piphi_runtime_kit_python/runtime/configuration.py +6 -3
  9. piphi_runtime_kit_python/runtime/discovery.py +2 -1
  10. piphi_runtime_kit_python/runtime/dispatch.py +5 -5
  11. piphi_runtime_kit_python/runtime/events.py +4 -3
  12. piphi_runtime_kit_python/runtime/health.py +2 -1
  13. piphi_runtime_kit_python/runtime/identity.py +4 -3
  14. piphi_runtime_kit_python/runtime/lifespan.py +1 -2
  15. piphi_runtime_kit_python/runtime/mqtt.py +8 -7
  16. piphi_runtime_kit_python/runtime/registry.py +2 -2
  17. piphi_runtime_kit_python/runtime/starter.py +15 -9
  18. piphi_runtime_kit_python/runtime/state_service.py +147 -0
  19. piphi_runtime_kit_python/runtime/telemetry.py +3 -4
  20. piphi_runtime_kit_python/schemas.py +3 -3
  21. {piphi_runtime_kit_python-0.7.1.dist-info → piphi_runtime_kit_python-0.9.3.dist-info}/METADATA +31 -1
  22. piphi_runtime_kit_python-0.9.3.dist-info/RECORD +32 -0
  23. {piphi_runtime_kit_python-0.7.1.dist-info → piphi_runtime_kit_python-0.9.3.dist-info}/WHEEL +1 -1
  24. piphi_runtime_kit_python-0.7.1.dist-info/RECORD +0 -30
  25. {piphi_runtime_kit_python-0.7.1.dist-info → piphi_runtime_kit_python-0.9.3.dist-info}/entry_points.txt +0 -0
  26. {piphi_runtime_kit_python-0.7.1.dist-info → piphi_runtime_kit_python-0.9.3.dist-info}/licenses/LICENSE +0 -0
@@ -5,8 +5,8 @@ from .automations import (
5
5
  AutomationClient,
6
6
  AutomationContractReport,
7
7
  AutomationEventDefinition,
8
- AutomationIdempotencyStore,
9
8
  AutomationIdempotencyClaimStore,
9
+ AutomationIdempotencyStore,
10
10
  AutomationRegistry,
11
11
  InMemoryAutomationIdempotencyStore,
12
12
  SQLiteAutomationIdempotencyStore,
@@ -14,6 +14,25 @@ from .automations import (
14
14
  audit_behaviors_contract,
15
15
  build_mock_automation_event,
16
16
  )
17
+ from .camera import (
18
+ CAMERA_MAX_SDP_BYTES,
19
+ CAMERA_MAX_SNAPSHOT_BYTES,
20
+ CAMERA_MAX_SOURCE_URL_BYTES,
21
+ CAMERA_MEDIA_CONTRACT_VERSION,
22
+ CameraCapabilityDeclaration,
23
+ CameraCapabilityEndpoints,
24
+ CameraMediaError,
25
+ CameraMediaProvider,
26
+ CameraSessionClose,
27
+ CameraSessionOffer,
28
+ CameraSessionOpened,
29
+ CameraSidecarSessionOpen,
30
+ CameraSidecarStatus,
31
+ CameraSnapshotRequest,
32
+ CameraSourceDescriptor,
33
+ CameraSourceResolver,
34
+ CameraWebRtcOffer,
35
+ )
17
36
  from .runtime.auth import (
18
37
  RUNTIME_CONTAINER_ID_HEADER_NAME,
19
38
  RUNTIME_INTERNAL_TOKEN_HEADER_NAME,
@@ -54,6 +73,13 @@ from .runtime.discovery import (
54
73
  format_discovery_attempt_log,
55
74
  normalize_discovery_inputs,
56
75
  )
76
+ from .runtime.dispatch import (
77
+ build_local_event_record,
78
+ dispatch_event_delivery,
79
+ dispatch_telemetry_delivery,
80
+ schedule_event_delivery,
81
+ schedule_telemetry_delivery,
82
+ )
57
83
  from .runtime.errors import (
58
84
  CoreAuthError,
59
85
  CoreDeliveryError,
@@ -64,13 +90,6 @@ from .runtime.errors import (
64
90
  CoreUnexpectedResponseError,
65
91
  classify_core_delivery_error,
66
92
  )
67
- from .runtime.dispatch import (
68
- build_local_event_record,
69
- dispatch_event_delivery,
70
- dispatch_telemetry_delivery,
71
- schedule_event_delivery,
72
- schedule_telemetry_delivery,
73
- )
74
93
  from .runtime.events import (
75
94
  EventClient,
76
95
  build_core_event_payload,
@@ -110,12 +129,13 @@ from .runtime.mqtt import (
110
129
  build_source_topic_root,
111
130
  )
112
131
  from .runtime.registry import RuntimeRegistry
113
- from .runtime.state import RuntimeProcessState
114
132
  from .runtime.starter import (
115
133
  RuntimeStarter,
116
134
  build_entities_response,
117
135
  create_runtime_starter,
118
136
  )
137
+ from .runtime.state import RuntimeProcessState
138
+ from .runtime.state_service import RuntimeStateService, StateReader
119
139
  from .runtime.tasks import (
120
140
  BackgroundTaskLimitError,
121
141
  create_tracked_task,
@@ -136,11 +156,6 @@ from .schemas import (
136
156
  IntegrationCommandRequest,
137
157
  IntegrationDiscoveryRequest,
138
158
  IntegrationDiscoveryResponse,
139
- RuntimeEntityCommandFieldResponse,
140
- RuntimeEntityCommandResponse,
141
- RuntimeEntityDashboardResponse,
142
- RuntimeEntitiesResponse,
143
- RuntimeEntityResponse,
144
159
  IntegrationEventIngestResponse,
145
160
  IntegrationEventListResponse,
146
161
  IntegrationEventRequest,
@@ -150,97 +165,132 @@ from .schemas import (
150
165
  RuntimeConfigSnapshot,
151
166
  RuntimeConfigSyncResponse,
152
167
  RuntimeDiagnosticsResponse,
168
+ RuntimeEntitiesResponse,
169
+ RuntimeEntityCommandFieldResponse,
170
+ RuntimeEntityCommandResponse,
171
+ RuntimeEntityDashboardResponse,
172
+ RuntimeEntityResponse,
153
173
  RuntimeHealthResponse,
154
174
  TelemetryPayload,
155
175
  )
156
176
 
157
177
  __all__ = [
178
+ "CAMERA_MAX_SDP_BYTES",
179
+ "CAMERA_MAX_SNAPSHOT_BYTES",
180
+ "CAMERA_MAX_SOURCE_URL_BYTES",
181
+ "CAMERA_MEDIA_CONTRACT_VERSION",
182
+ "CORE_BASE_URL_ENV_NAME",
183
+ "DEFAULT_CORE_CLIENT_TIMEOUT_SECONDS",
184
+ "DEFAULT_RUNTIME_CONFIG_SNAPSHOT_FILENAME",
185
+ "DEFAULT_RUNTIME_CONTAINER_ID_ENV_NAME",
186
+ "DEFAULT_RUNTIME_INTERNAL_TOKEN_ENV_NAME",
187
+ "DEFAULT_RUNTIME_VOLUME_DIR",
188
+ "DEFAULT_SOURCE_TOPIC_PREFIX",
189
+ "RUNTIME_CONFIG_SNAPSHOT_PATH_ENV_NAME",
190
+ "RUNTIME_CONTAINER_ID_HEADER_NAME",
191
+ "RUNTIME_INTERNAL_TOKEN_HEADER_NAME",
158
192
  "AutomationActionDefinition",
159
193
  "AutomationActionRequest",
160
194
  "AutomationActionResult",
161
195
  "AutomationClient",
162
196
  "AutomationContractReport",
163
197
  "AutomationEventDefinition",
164
- "AutomationIdempotencyStore",
165
198
  "AutomationIdempotencyClaimStore",
199
+ "AutomationIdempotencyStore",
166
200
  "AutomationRegistry",
167
- "InMemoryAutomationIdempotencyStore",
168
- "SQLiteAutomationIdempotencyStore",
169
201
  "BackgroundTaskLimitError",
202
+ "CameraCapabilityDeclaration",
203
+ "CameraCapabilityEndpoints",
204
+ "CameraMediaError",
205
+ "CameraMediaProvider",
206
+ "CameraSessionClose",
207
+ "CameraSessionOffer",
208
+ "CameraSessionOpened",
209
+ "CameraSidecarSessionOpen",
210
+ "CameraSidecarStatus",
211
+ "CameraSnapshotRequest",
212
+ "CameraSourceDescriptor",
213
+ "CameraSourceResolver",
214
+ "CameraWebRtcOffer",
170
215
  "ConfigSyncCoordinator",
171
216
  "CoreAuthError",
172
217
  "CoreDeliveryError",
218
+ "CoreEventPayload",
173
219
  "CoreRouteNotFoundError",
174
220
  "CoreServerError",
175
221
  "CoreTimeoutError",
176
222
  "CoreUnavailableError",
177
223
  "CoreUnexpectedResponseError",
178
- "DEFAULT_CORE_CLIENT_TIMEOUT_SECONDS",
179
- "CORE_BASE_URL_ENV_NAME",
180
- "DEFAULT_RUNTIME_CONFIG_SNAPSHOT_FILENAME",
181
- "DEFAULT_RUNTIME_VOLUME_DIR",
182
- "RUNTIME_CONFIG_SNAPSHOT_PATH_ENV_NAME",
183
- "DEFAULT_RUNTIME_CONTAINER_ID_ENV_NAME",
184
- "DEFAULT_RUNTIME_INTERNAL_TOKEN_ENV_NAME",
185
- "RUNTIME_CONTAINER_ID_HEADER_NAME",
186
- "RUNTIME_INTERNAL_TOKEN_HEADER_NAME",
224
+ "EventClient",
225
+ "EventSeverity",
226
+ "EventTransport",
227
+ "InMemoryAutomationIdempotencyStore",
187
228
  "IntegrationCommandRequest",
188
229
  "IntegrationDiscoveryRequest",
189
230
  "IntegrationDiscoveryResponse",
190
- "RuntimeEntityCommandFieldResponse",
191
- "RuntimeEntityCommandResponse",
192
- "RuntimeEntityDashboardResponse",
193
- "RuntimeEntitiesResponse",
194
- "RuntimeEntityResponse",
231
+ "IntegrationEventIngestResponse",
232
+ "IntegrationEventListResponse",
195
233
  "IntegrationEventRequest",
234
+ "MqttBrokerConfig",
235
+ "MqttJsonClient",
196
236
  "RuntimeAuthContext",
197
237
  "RuntimeAuthHeaders",
198
238
  "RuntimeConfig",
199
239
  "RuntimeConfigApplyResponse",
200
- "RuntimeConfigRemoveResponse",
201
240
  "RuntimeConfigRehydrateResult",
241
+ "RuntimeConfigRemoveResponse",
202
242
  "RuntimeConfigSnapshot",
203
243
  "RuntimeConfigSyncResponse",
204
244
  "RuntimeContext",
205
245
  "RuntimeDeviceRef",
246
+ "RuntimeDiagnosticsResponse",
247
+ "RuntimeEntitiesResponse",
248
+ "RuntimeEntityCommandFieldResponse",
249
+ "RuntimeEntityCommandResponse",
250
+ "RuntimeEntityDashboardResponse",
251
+ "RuntimeEntityResponse",
252
+ "RuntimeHealthResponse",
206
253
  "RuntimeIdentityError",
207
- "RuntimeRegistry",
208
254
  "RuntimeProcessState",
255
+ "RuntimeRegistry",
209
256
  "RuntimeStarter",
210
- "RuntimeDiagnosticsResponse",
211
- "RuntimeHealthResponse",
257
+ "RuntimeStateService",
258
+ "SQLiteAutomationIdempotencyStore",
259
+ "StateReader",
212
260
  "TelemetryClient",
261
+ "TelemetryPayload",
213
262
  "TelemetryReading",
214
263
  "TelemetryValue",
215
- "EventClient",
216
- "TelemetryPayload",
217
- "CoreEventPayload",
218
- "EventSeverity",
219
- "EventTransport",
220
- "IntegrationEventIngestResponse",
221
- "IntegrationEventListResponse",
222
- "build_runtime_config_snapshot_from_core_rows",
223
- "build_mock_automation_event",
224
- "build_discovery_response",
225
- "classify_core_delivery_error",
264
+ "assert_behaviors_contract",
265
+ "audit_behaviors_contract",
266
+ "bind_core_http_client",
267
+ "bootstrap_runtime_auth_from_env",
268
+ "build_config_apply_response",
269
+ "build_config_remove_response",
270
+ "build_core_auth_headers",
226
271
  "build_core_event_payload",
272
+ "build_discovery_response",
273
+ "build_entities_response",
227
274
  "build_event_ingest_response",
228
275
  "build_event_list_response",
229
276
  "build_local_event_record",
230
- "build_runtime_identity",
231
- "build_core_auth_headers",
232
- "build_telemetry_maps",
233
- "build_config_apply_response",
234
- "build_config_remove_response",
235
- "build_entities_response",
277
+ "build_mock_automation_event",
236
278
  "build_runtime_auth_headers",
279
+ "build_runtime_config_snapshot_from_core_rows",
237
280
  "build_runtime_diagnostics_response",
238
281
  "build_runtime_health_response",
282
+ "build_runtime_identity",
283
+ "build_source_errors_topic",
284
+ "build_source_model_packets_topic",
285
+ "build_source_packet_envelope",
286
+ "build_source_packets_topic",
287
+ "build_source_status_topic",
288
+ "build_source_topic_root",
239
289
  "build_sync_response",
240
- "bind_core_http_client",
241
- "bootstrap_runtime_auth_from_env",
242
- "create_tracked_task",
290
+ "build_telemetry_maps",
291
+ "classify_core_delivery_error",
243
292
  "create_runtime_starter",
293
+ "create_tracked_task",
244
294
  "dispatch_event_delivery",
245
295
  "dispatch_telemetry_delivery",
246
296
  "extract_runtime_auth_headers",
@@ -251,31 +301,20 @@ __all__ = [
251
301
  "format_runtime_auth_sync_log",
252
302
  "load_runtime_config_snapshot",
253
303
  "mask_token",
254
- "MqttBrokerConfig",
255
- "MqttJsonClient",
256
304
  "normalize_discovery_inputs",
257
305
  "normalize_event_payload",
258
- "redact_config_secrets",
259
306
  "reconcile_config_ids",
307
+ "redact_config_secrets",
260
308
  "rehydrate_runtime_configs",
309
+ "resolve_config_id",
261
310
  "resolve_core_base_url",
311
+ "resolve_device_id",
262
312
  "resolve_runtime_config_snapshot_path",
263
313
  "runtime_lifespan",
264
314
  "schedule_event_delivery",
265
315
  "schedule_telemetry_delivery",
266
316
  "shutdown_background_tasks",
267
317
  "track_background_task",
268
- "resolve_config_id",
269
- "resolve_device_id",
270
318
  "validate_typed_config",
271
319
  "validate_typed_configs",
272
- "assert_behaviors_contract",
273
- "audit_behaviors_contract",
274
- "DEFAULT_SOURCE_TOPIC_PREFIX",
275
- "build_source_errors_topic",
276
- "build_source_model_packets_topic",
277
- "build_source_packet_envelope",
278
- "build_source_packets_topic",
279
- "build_source_status_topic",
280
- "build_source_topic_root",
281
320
  ]
@@ -2,7 +2,8 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import TYPE_CHECKING, Any, Mapping
5
+ from collections.abc import Mapping
6
+ from typing import TYPE_CHECKING, Any
6
7
 
7
8
  from ..automations import AutomationActionResult, AutomationRegistry
8
9
  from ..runtime.auth import RuntimeAuthHeaders
@@ -14,7 +15,7 @@ if TYPE_CHECKING:
14
15
 
15
16
  async def dispatch_automation_action_from_fastapi(
16
17
  registry: AutomationRegistry,
17
- request: "Request",
18
+ request: Request,
18
19
  payload: object | Mapping[str, Any],
19
20
  ) -> AutomationActionResult:
20
21
  """Dispatch a Core command while preserving its stable idempotency key.
@@ -62,7 +63,7 @@ def get_payload_container_id(
62
63
 
63
64
  def sync_runtime_auth_from_fastapi_request(
64
65
  runtime_context: RuntimeContext,
65
- request: "Request",
66
+ request: Request,
66
67
  *,
67
68
  payload_container_id: str | None = None,
68
69
  ) -> RuntimeAuthHeaders:
@@ -83,7 +84,7 @@ def sync_runtime_auth_from_fastapi_request(
83
84
 
84
85
  def sync_runtime_auth_from_fastapi_payload(
85
86
  runtime_context: RuntimeContext,
86
- request: "Request",
87
+ request: Request,
87
88
  payload: object | Mapping[str, Any] | None,
88
89
  *,
89
90
  attribute_name: str = "container_id",
@@ -9,11 +9,11 @@ checking that runtime handlers match the published behavior schema.
9
9
  from __future__ import annotations
10
10
 
11
11
  import asyncio
12
+ import sqlite3
12
13
  from collections.abc import Awaitable, Callable, Mapping
13
14
  from contextlib import closing
14
15
  from dataclasses import dataclass
15
16
  from pathlib import Path
16
- import sqlite3
17
17
  from typing import Any, Literal, Protocol, TypeAlias, runtime_checkable
18
18
 
19
19
  from pydantic import BaseModel, ConfigDict, Field
@@ -23,6 +23,7 @@ from .runtime.events import EventClient, build_core_event_payload
23
23
  from .runtime.identity import RuntimeDeviceRef
24
24
  from .schemas import CoreEventPayload, EventSeverity
25
25
 
26
+
26
27
  class AutomationActionRequest(BaseModel):
27
28
  """Normalized action request received from PiPhi Core."""
28
29
 
@@ -64,7 +65,7 @@ class AutomationActionResult(BaseModel):
64
65
  cls,
65
66
  result: Mapping[str, Any] | None = None,
66
67
  **values: Any,
67
- ) -> "AutomationActionResult":
68
+ ) -> AutomationActionResult:
68
69
  payload = dict(result or {})
69
70
  payload.update(values)
70
71
  return cls(status="success", result=payload)
@@ -76,7 +77,7 @@ class AutomationActionResult(BaseModel):
76
77
  *,
77
78
  retryable: bool = False,
78
79
  metadata: Mapping[str, Any] | None = None,
79
- ) -> "AutomationActionResult":
80
+ ) -> AutomationActionResult:
80
81
  return cls(
81
82
  status="failed",
82
83
  error=str(error),
@@ -425,7 +426,7 @@ class AutomationRegistry:
425
426
  return AutomationActionResult.failure(
426
427
  "Automation handler returned an unsupported result type"
427
428
  )
428
- except Exception as exc:
429
+ except Exception as exc: # noqa: BLE001 - action boundary returns a typed failure.
429
430
  return AutomationActionResult.failure(str(exc), retryable=False)
430
431
 
431
432
  def contract_snapshot(self) -> dict[str, Any]:
@@ -0,0 +1,237 @@
1
+ """Versioned camera-media contract helpers for PiPhi runtimes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Awaitable, Callable
6
+ from typing import Literal, Protocol
7
+ from urllib.parse import urlsplit
8
+
9
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
10
+
11
+ CAMERA_MEDIA_CONTRACT_VERSION: Literal["camera.media.v1"] = "camera.media.v1"
12
+ CAMERA_MAX_SDP_BYTES = 256 * 1024
13
+ CAMERA_MAX_SOURCE_URL_BYTES = 4096
14
+ CAMERA_MAX_SNAPSHOT_BYTES = 8 * 1024 * 1024
15
+
16
+ CameraMediaTransport = Literal["snapshot", "webrtc", "hls"]
17
+ CameraSourceProtocol = Literal["rtsp", "rtsps", "http", "https"]
18
+ CameraSourceTransport = Literal["tcp", "udp", "auto"]
19
+ CameraMediaAudience = Literal["browser-core", "core-sidecar"]
20
+ CameraErrorCode = Literal[
21
+ "CAMERA_OFFLINE",
22
+ "CAMERA_ACCESS_DENIED",
23
+ "CAMERA_SOURCE_INVALID",
24
+ "CAMERA_CODEC_UNSUPPORTED",
25
+ "CAMERA_SIDECAR_UNAVAILABLE",
26
+ "CAMERA_CAPACITY_REACHED",
27
+ "CAMERA_SESSION_EXPIRED",
28
+ "CAMERA_NEGOTIATION_FAILED",
29
+ "CAMERA_SNAPSHOT_UNAVAILABLE",
30
+ ]
31
+
32
+
33
+ class CameraContractModel(BaseModel):
34
+ """Closed base model used by every camera-media message."""
35
+
36
+ model_config = ConfigDict(extra="forbid")
37
+
38
+ contract_version: Literal["camera.media.v1"] = CAMERA_MEDIA_CONTRACT_VERSION
39
+
40
+
41
+ class CameraCapabilityEndpoints(BaseModel):
42
+ """Path-only runtime endpoints declared for one camera capability."""
43
+
44
+ model_config = ConfigDict(extra="forbid")
45
+
46
+ source: str | None = None
47
+ snapshot: str | None = None
48
+ events: str | None = None
49
+ hls: str | None = None
50
+ webrtc: str | None = None
51
+ webrtc_close: str | None = None
52
+
53
+ @model_validator(mode="after")
54
+ def validate_paths(self) -> CameraCapabilityEndpoints:
55
+ values = [
56
+ self.source,
57
+ self.snapshot,
58
+ self.events,
59
+ self.hls,
60
+ self.webrtc,
61
+ self.webrtc_close,
62
+ ]
63
+ if not any(values):
64
+ raise ValueError("at least one camera endpoint is required")
65
+ for value in (entry for entry in values if entry is not None):
66
+ if (
67
+ not value.startswith("/")
68
+ or value.startswith("//")
69
+ or "\\" in value
70
+ or any(segment in {".", ".."} for segment in value.split("/"))
71
+ ):
72
+ raise ValueError("camera endpoints must be safe path-only values")
73
+ return self
74
+
75
+
76
+ class CameraCapabilityDeclaration(CameraContractModel):
77
+ """Portable camera capability metadata shared with Core."""
78
+
79
+ message_type: Literal["camera.capability"] = "camera.capability"
80
+ capability_id: str = Field(min_length=1, max_length=300, pattern=r"^[A-Za-z0-9][A-Za-z0-9._:-]*$")
81
+ transports: list[CameraMediaTransport] = Field(min_length=1)
82
+ audio_available: bool = False
83
+ recording_available: bool = False
84
+ refresh_seconds: int = Field(default=15, ge=2, le=300)
85
+ endpoints: CameraCapabilityEndpoints
86
+
87
+ @model_validator(mode="after")
88
+ def validate_transports(self) -> CameraCapabilityDeclaration:
89
+ if len(self.transports) != len(set(self.transports)):
90
+ raise ValueError("camera transports must be unique")
91
+ required_endpoints = {
92
+ "snapshot": self.endpoints.snapshot,
93
+ "hls": self.endpoints.hls,
94
+ "webrtc": self.endpoints.webrtc,
95
+ }
96
+ for transport, endpoint in required_endpoints.items():
97
+ if transport in self.transports and endpoint is None and self.endpoints.source is None:
98
+ raise ValueError(f"{transport} requires its endpoint or a protected source endpoint")
99
+ return self
100
+
101
+ def manifest_capability(self) -> dict[str, object]:
102
+ """Return the current PiPhi manifest representation."""
103
+
104
+ camera: dict[str, object] = {
105
+ "contract_version": CAMERA_MEDIA_CONTRACT_VERSION,
106
+ "refresh_seconds": self.refresh_seconds,
107
+ }
108
+ endpoint_keys = {
109
+ "source": "gateway_source_endpoint",
110
+ "snapshot": "snapshot_endpoint",
111
+ "events": "events_endpoint",
112
+ "hls": "stream_endpoint",
113
+ "webrtc": "webrtc_endpoint",
114
+ "webrtc_close": "webrtc_close_endpoint",
115
+ }
116
+ for field_name, manifest_name in endpoint_keys.items():
117
+ value = getattr(self.endpoints, field_name)
118
+ if value is not None:
119
+ camera[manifest_name] = value
120
+ if "hls" in self.transports:
121
+ camera["stream_type"] = "hls"
122
+ return {"kind": "camera", "value_kind": "camera", "camera": camera}
123
+
124
+
125
+ class CameraSourceDescriptor(CameraContractModel):
126
+ """Private camera source passed only between an integration, Core, and a sidecar."""
127
+
128
+ message_type: Literal["camera.source"] = "camera.source"
129
+ audience: Literal["core-sidecar"] = "core-sidecar"
130
+ camera_id: str = Field(min_length=1, max_length=300, pattern=r"^[A-Za-z0-9][A-Za-z0-9._:-]*$")
131
+ source_url: str = Field(min_length=1, max_length=CAMERA_MAX_SOURCE_URL_BYTES)
132
+ source_protocol: CameraSourceProtocol
133
+ preferred_transport: CameraSourceTransport = "auto"
134
+ connect_timeout_seconds: int = Field(default=10, ge=1, le=60)
135
+
136
+ @model_validator(mode="after")
137
+ def validate_source(self) -> CameraSourceDescriptor:
138
+ if any(character in self.source_url for character in "\r\n\0"):
139
+ raise ValueError("camera source URL contains a forbidden control character")
140
+ parsed = urlsplit(self.source_url)
141
+ if parsed.scheme.lower() != self.source_protocol or not parsed.hostname:
142
+ raise ValueError("camera source URL and source_protocol must match and include a host")
143
+ return self
144
+
145
+ def safe_summary(self) -> dict[str, object]:
146
+ """Return diagnostics that cannot disclose the URL or credentials."""
147
+
148
+ return {
149
+ "camera_id": self.camera_id,
150
+ "source_protocol": self.source_protocol,
151
+ "preferred_transport": self.preferred_transport,
152
+ "connect_timeout_seconds": self.connect_timeout_seconds,
153
+ }
154
+
155
+
156
+ class CameraWebRtcOffer(BaseModel):
157
+ """Bounded SDP offer reusable inside browser and sidecar messages."""
158
+
159
+ model_config = ConfigDict(extra="forbid")
160
+
161
+ type: Literal["offer"] = "offer"
162
+ sdp: str = Field(min_length=1, max_length=CAMERA_MAX_SDP_BYTES)
163
+ include_audio: bool = False
164
+
165
+
166
+ class CameraSessionOffer(CameraWebRtcOffer, CameraContractModel):
167
+ message_type: Literal["camera.session.offer"] = "camera.session.offer"
168
+ audience: Literal["browser-core"] = "browser-core"
169
+
170
+
171
+ class CameraSidecarSessionOpen(CameraContractModel):
172
+ message_type: Literal["camera.sidecar.session.open"] = "camera.sidecar.session.open"
173
+ audience: Literal["core-sidecar"] = "core-sidecar"
174
+ source: CameraSourceDescriptor
175
+ offer: CameraWebRtcOffer
176
+ idle_timeout_seconds: int = Field(default=60, ge=10, le=900)
177
+
178
+
179
+ class CameraSessionOpened(CameraContractModel):
180
+ message_type: Literal["camera.session.opened"] = "camera.session.opened"
181
+ audience: CameraMediaAudience
182
+ session_id: str = Field(min_length=1, max_length=4096)
183
+ type: Literal["answer"] = "answer"
184
+ sdp: str = Field(min_length=1, max_length=CAMERA_MAX_SDP_BYTES)
185
+ expires_at: str | None = Field(default=None, max_length=128)
186
+
187
+
188
+ class CameraSessionClose(CameraContractModel):
189
+ message_type: Literal["camera.session.close"] = "camera.session.close"
190
+ audience: CameraMediaAudience
191
+ session_id: str = Field(min_length=1, max_length=4096)
192
+
193
+
194
+ class CameraSnapshotRequest(CameraContractModel):
195
+ message_type: Literal["camera.snapshot.request"] = "camera.snapshot.request"
196
+ audience: CameraMediaAudience
197
+ maximum_bytes: int = Field(default=CAMERA_MAX_SNAPSHOT_BYTES, ge=1024, le=CAMERA_MAX_SNAPSHOT_BYTES)
198
+
199
+
200
+ class CameraSidecarStatus(CameraContractModel):
201
+ message_type: Literal["camera.sidecar.status"] = "camera.sidecar.status"
202
+ audience: Literal["core-sidecar"] = "core-sidecar"
203
+ ready: bool
204
+ active_sessions: int = Field(ge=0)
205
+ session_capacity: int = Field(ge=1)
206
+ degraded_reason: str | None = Field(default=None, max_length=300)
207
+ supported_source_protocols: list[CameraSourceProtocol] = Field(default_factory=list)
208
+ supported_transports: list[CameraMediaTransport] = Field(default_factory=list)
209
+
210
+
211
+ class CameraMediaError(CameraContractModel):
212
+ message_type: Literal["camera.error"] = "camera.error"
213
+ audience: CameraMediaAudience
214
+ code: CameraErrorCode
215
+ message: str = Field(min_length=1, max_length=300)
216
+ retryable: bool
217
+ retry_after_seconds: int | None = Field(default=None, ge=1, le=3600)
218
+
219
+
220
+ class CameraMediaProvider(Protocol):
221
+ """Narrow integration-owned interface consumed by Core camera brokering."""
222
+
223
+ def resolve_source(
224
+ self,
225
+ config_id: str,
226
+ capability_id: str,
227
+ ) -> Awaitable[CameraSourceDescriptor]: ...
228
+
229
+ def capture_snapshot(
230
+ self,
231
+ config_id: str,
232
+ capability_id: str,
233
+ request: CameraSnapshotRequest,
234
+ ) -> Awaitable[tuple[str, bytes]]: ...
235
+
236
+
237
+ CameraSourceResolver = Callable[[str, str], Awaitable[CameraSourceDescriptor]]