mcbe-ws-sdk 0.1.0__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.
- mcbe_ws_sdk/__init__.py +126 -0
- mcbe_ws_sdk/addon/__init__.py +17 -0
- mcbe_ws_sdk/addon/service.py +239 -0
- mcbe_ws_sdk/addon/session.py +256 -0
- mcbe_ws_sdk/command/__init__.py +5 -0
- mcbe_ws_sdk/command/registry.py +176 -0
- mcbe_ws_sdk/config.py +119 -0
- mcbe_ws_sdk/delivery/__init__.py +5 -0
- mcbe_ws_sdk/delivery/outbound.py +165 -0
- mcbe_ws_sdk/errors.py +45 -0
- mcbe_ws_sdk/flow/__init__.py +9 -0
- mcbe_ws_sdk/flow/flow_control.py +332 -0
- mcbe_ws_sdk/gateway/__init__.py +49 -0
- mcbe_ws_sdk/gateway/connection.py +249 -0
- mcbe_ws_sdk/gateway/events.py +138 -0
- mcbe_ws_sdk/gateway/handler.py +181 -0
- mcbe_ws_sdk/gateway/hook.py +107 -0
- mcbe_ws_sdk/gateway/messages.py +46 -0
- mcbe_ws_sdk/gateway/server_facade.py +462 -0
- mcbe_ws_sdk/gateway/sink.py +123 -0
- mcbe_ws_sdk/logging.py +90 -0
- mcbe_ws_sdk/profiles/__init__.py +36 -0
- mcbe_ws_sdk/profiles/mcbews_v1/__init__.py +8 -0
- mcbe_ws_sdk/profiles/mcbews_v1/codec.py +208 -0
- mcbe_ws_sdk/profiles/mcbews_v1/delivery.py +48 -0
- mcbe_ws_sdk/profiles/mcbews_v1/models.py +47 -0
- mcbe_ws_sdk/profiles/mcbews_v1/profile.py +34 -0
- mcbe_ws_sdk/protocol/__init__.py +13 -0
- mcbe_ws_sdk/protocol/minecraft.py +245 -0
- mcbe_ws_sdk/py.typed +1 -0
- mcbe_ws_sdk-0.1.0.dist-info/METADATA +138 -0
- mcbe_ws_sdk-0.1.0.dist-info/RECORD +34 -0
- mcbe_ws_sdk-0.1.0.dist-info/WHEEL +4 -0
- mcbe_ws_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
mcbe_ws_sdk/__init__.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Generic WebSocket gateway SDK for Minecraft Bedrock Edition.
|
|
2
|
+
|
|
3
|
+
Public surface
|
|
4
|
+
--------------
|
|
5
|
+
The gateway SDK exposes a dual-layer interface:
|
|
6
|
+
|
|
7
|
+
* Low-level: subscribe to an :class:`~mcbe_ws_sdk.gateway.events.EventBus`
|
|
8
|
+
keyed by :class:`~mcbe_ws_sdk.gateway.events.WsEventType`.
|
|
9
|
+
* High-level: implement :class:`~mcbe_ws_sdk.gateway.hook.ConnectionHook`
|
|
10
|
+
and :class:`~mcbe_ws_sdk.gateway.sink.ResponseSink`, then drive the stack
|
|
11
|
+
through :class:`~mcbe_ws_sdk.gateway.server_facade.McbeServerFacade`.
|
|
12
|
+
|
|
13
|
+
The full connection lifetime, packet request abstraction and byte-safe command
|
|
14
|
+
chunking are provided; the agent's LLM / message-broker concerns are the host's.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import importlib.metadata
|
|
20
|
+
|
|
21
|
+
from mcbe_ws_sdk.addon import (
|
|
22
|
+
AddonBridgeClient,
|
|
23
|
+
AddonBridgeService,
|
|
24
|
+
AddonBridgeSettings,
|
|
25
|
+
AddonMessageResult,
|
|
26
|
+
ConnectionAddonBridgeClient,
|
|
27
|
+
)
|
|
28
|
+
from mcbe_ws_sdk.command import CommandRegistry
|
|
29
|
+
from mcbe_ws_sdk.delivery import McbeOutboundDelivery
|
|
30
|
+
from mcbe_ws_sdk.errors import (
|
|
31
|
+
BridgeClosedError,
|
|
32
|
+
BridgeError,
|
|
33
|
+
BridgeLimitError,
|
|
34
|
+
BridgeTimeoutError,
|
|
35
|
+
ConfigurationError,
|
|
36
|
+
FacadeLifecycleError,
|
|
37
|
+
FrameTooLargeError,
|
|
38
|
+
McbeWsSdkError,
|
|
39
|
+
ProtocolError,
|
|
40
|
+
)
|
|
41
|
+
from mcbe_ws_sdk.flow import FlowControlMiddleware, FlowControlSettings
|
|
42
|
+
from mcbe_ws_sdk.gateway import (
|
|
43
|
+
ConnectionHook,
|
|
44
|
+
ConnectionManager,
|
|
45
|
+
ConnectionState,
|
|
46
|
+
DefaultResponseSink,
|
|
47
|
+
EventBus,
|
|
48
|
+
GatewaySettings,
|
|
49
|
+
McbeServerFacade,
|
|
50
|
+
MessageSurfaceConfig,
|
|
51
|
+
MinecraftProtocolHandler,
|
|
52
|
+
NoOpHook,
|
|
53
|
+
OutboundText,
|
|
54
|
+
ResponseKind,
|
|
55
|
+
ResponseSink,
|
|
56
|
+
RouteEnvelope,
|
|
57
|
+
SubscriptionToken,
|
|
58
|
+
SystemNotification,
|
|
59
|
+
WebsocketTransportConfig,
|
|
60
|
+
WsEventType,
|
|
61
|
+
enqueue_response,
|
|
62
|
+
)
|
|
63
|
+
from mcbe_ws_sdk.logging import configure_logging
|
|
64
|
+
from mcbe_ws_sdk.profiles import MCBEWS_V1, AddonBridgeProfile, McbewsV1Profile
|
|
65
|
+
from mcbe_ws_sdk.profiles.mcbews_v1.codec import encode_text_response_commands
|
|
66
|
+
from mcbe_ws_sdk.profiles.mcbews_v1.delivery import McbewsV1Delivery
|
|
67
|
+
from mcbe_ws_sdk.protocol import (
|
|
68
|
+
MinecraftCommandResponse,
|
|
69
|
+
MinecraftErrorFrame,
|
|
70
|
+
PlayerMessageEvent,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
try:
|
|
74
|
+
__version__ = importlib.metadata.version("mcbe-ws-sdk")
|
|
75
|
+
except importlib.metadata.PackageNotFoundError:
|
|
76
|
+
__version__ = "0+unknown"
|
|
77
|
+
|
|
78
|
+
__all__ = (
|
|
79
|
+
"__version__",
|
|
80
|
+
"AddonBridgeClient",
|
|
81
|
+
"AddonBridgeProfile",
|
|
82
|
+
"AddonBridgeService",
|
|
83
|
+
"AddonBridgeSettings",
|
|
84
|
+
"AddonMessageResult",
|
|
85
|
+
"BridgeClosedError",
|
|
86
|
+
"BridgeError",
|
|
87
|
+
"BridgeLimitError",
|
|
88
|
+
"BridgeTimeoutError",
|
|
89
|
+
"CommandRegistry",
|
|
90
|
+
"ConfigurationError",
|
|
91
|
+
"ConnectionAddonBridgeClient",
|
|
92
|
+
"ConnectionHook",
|
|
93
|
+
"ConnectionManager",
|
|
94
|
+
"ConnectionState",
|
|
95
|
+
"DefaultResponseSink",
|
|
96
|
+
"EventBus",
|
|
97
|
+
"FacadeLifecycleError",
|
|
98
|
+
"FlowControlMiddleware",
|
|
99
|
+
"FlowControlSettings",
|
|
100
|
+
"FrameTooLargeError",
|
|
101
|
+
"GatewaySettings",
|
|
102
|
+
"MCBEWS_V1",
|
|
103
|
+
"McbeOutboundDelivery",
|
|
104
|
+
"McbeServerFacade",
|
|
105
|
+
"McbeWsSdkError",
|
|
106
|
+
"McbewsV1Delivery",
|
|
107
|
+
"McbewsV1Profile",
|
|
108
|
+
"MessageSurfaceConfig",
|
|
109
|
+
"MinecraftCommandResponse",
|
|
110
|
+
"MinecraftErrorFrame",
|
|
111
|
+
"MinecraftProtocolHandler",
|
|
112
|
+
"NoOpHook",
|
|
113
|
+
"OutboundText",
|
|
114
|
+
"PlayerMessageEvent",
|
|
115
|
+
"ProtocolError",
|
|
116
|
+
"ResponseKind",
|
|
117
|
+
"ResponseSink",
|
|
118
|
+
"RouteEnvelope",
|
|
119
|
+
"SubscriptionToken",
|
|
120
|
+
"SystemNotification",
|
|
121
|
+
"WebsocketTransportConfig",
|
|
122
|
+
"WsEventType",
|
|
123
|
+
"configure_logging",
|
|
124
|
+
"encode_text_response_commands",
|
|
125
|
+
"enqueue_response",
|
|
126
|
+
)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Addon bridge capability for the MCBE WebSocket SDK."""
|
|
2
|
+
|
|
3
|
+
from mcbe_ws_sdk.addon.service import (
|
|
4
|
+
AddonBridgeClient,
|
|
5
|
+
AddonBridgeService,
|
|
6
|
+
AddonMessageResult,
|
|
7
|
+
ConnectionAddonBridgeClient,
|
|
8
|
+
)
|
|
9
|
+
from mcbe_ws_sdk.config import AddonBridgeSettings
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"AddonBridgeClient",
|
|
13
|
+
"AddonBridgeService",
|
|
14
|
+
"AddonBridgeSettings",
|
|
15
|
+
"AddonMessageResult",
|
|
16
|
+
"ConnectionAddonBridgeClient",
|
|
17
|
+
]
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""Addon bridge service.
|
|
2
|
+
|
|
3
|
+
Relocated from the main repo ``services/addon/service.py``
|
|
4
|
+
|
|
5
|
+
Changes vs. the original:
|
|
6
|
+
|
|
7
|
+
* No module-level ``_addon_bridge_service`` singleton and no
|
|
8
|
+
``get_addon_bridge_service()`` factory. The service is constructed with an
|
|
9
|
+
explicit :class:`AddonBridgeSettings` and any number of independent instances
|
|
10
|
+
may coexist.
|
|
11
|
+
* Timeout and profile are taken from ``AddonBridgeSettings`` instead of a
|
|
12
|
+
mutable global settings read.
|
|
13
|
+
* ``is_bridge_chat_message`` / ``is_ui_chat_message`` use the configured profile.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import asyncio
|
|
19
|
+
import json
|
|
20
|
+
from collections.abc import Awaitable, Callable
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from typing import Any, Protocol
|
|
23
|
+
from uuid import UUID
|
|
24
|
+
|
|
25
|
+
import structlog
|
|
26
|
+
|
|
27
|
+
from mcbe_ws_sdk.addon.session import AddonBridgeSession
|
|
28
|
+
from mcbe_ws_sdk.config import AddonBridgeSettings
|
|
29
|
+
from mcbe_ws_sdk.errors import BridgeTimeoutError
|
|
30
|
+
from mcbe_ws_sdk.profiles.mcbews_v1.codec import encode_bridge_request
|
|
31
|
+
from mcbe_ws_sdk.profiles.mcbews_v1.models import (
|
|
32
|
+
AddonBridgeChunk,
|
|
33
|
+
UiChatChunk,
|
|
34
|
+
UiChatMessage,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
logger = structlog.get_logger(__name__)
|
|
38
|
+
|
|
39
|
+
CommandSender = Callable[[str], Awaitable[None]]
|
|
40
|
+
UiChatCallback = Callable[[UUID, str, str], Awaitable[None]]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class AddonMessageResult:
|
|
45
|
+
handled: bool
|
|
46
|
+
bridge_chunk: AddonBridgeChunk | None = None
|
|
47
|
+
ui_chunk: UiChatChunk | None = None
|
|
48
|
+
ui_message: UiChatMessage | None = None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class AddonBridgeClient(Protocol):
|
|
52
|
+
"""Face an Agent uses to reach the addon bridge."""
|
|
53
|
+
|
|
54
|
+
async def request(self, capability: str, payload: dict[str, Any]) -> dict[str, Any]:
|
|
55
|
+
"""Issue a capability request and return the reassembled payload."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class AddonBridgeService:
|
|
59
|
+
"""Manage the request/response lifecycle between Python and the addon."""
|
|
60
|
+
|
|
61
|
+
def __init__(self, settings: AddonBridgeSettings) -> None:
|
|
62
|
+
self._settings = settings
|
|
63
|
+
self._sessions: dict[UUID, AddonBridgeSession] = {}
|
|
64
|
+
self._timeout_seconds = settings.timeout_seconds
|
|
65
|
+
self._profile = settings.profile
|
|
66
|
+
self._ui_chat_callback: UiChatCallback | None = None
|
|
67
|
+
|
|
68
|
+
def create_client(
|
|
69
|
+
self,
|
|
70
|
+
connection_id: UUID,
|
|
71
|
+
send_command: CommandSender,
|
|
72
|
+
) -> AddonBridgeClient:
|
|
73
|
+
"""Build a client bound to one connection."""
|
|
74
|
+
return ConnectionAddonBridgeClient(self, connection_id, send_command)
|
|
75
|
+
|
|
76
|
+
async def request_capability(
|
|
77
|
+
self,
|
|
78
|
+
connection_id: UUID,
|
|
79
|
+
capability: str,
|
|
80
|
+
payload: dict[str, Any],
|
|
81
|
+
send_command: CommandSender,
|
|
82
|
+
) -> dict[str, Any]:
|
|
83
|
+
"""Send a bridge request and wait for the addon's chat callback."""
|
|
84
|
+
session = self._session_for(connection_id)
|
|
85
|
+
request = session.create_request(capability=capability, payload=payload)
|
|
86
|
+
command = encode_bridge_request(
|
|
87
|
+
request_id=request.request_id,
|
|
88
|
+
capability=capability,
|
|
89
|
+
payload=payload,
|
|
90
|
+
profile=self._profile,
|
|
91
|
+
)
|
|
92
|
+
payload_bytes = len(
|
|
93
|
+
json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
94
|
+
)
|
|
95
|
+
# INFO stays free of payload/command content (may contain player data).
|
|
96
|
+
logger.info(
|
|
97
|
+
"bridge_request_outbound",
|
|
98
|
+
request_id=request.request_id,
|
|
99
|
+
capability=capability,
|
|
100
|
+
payload_bytes=payload_bytes,
|
|
101
|
+
)
|
|
102
|
+
logger.debug(
|
|
103
|
+
"bridge_request_outbound",
|
|
104
|
+
connection_id=str(connection_id),
|
|
105
|
+
request_id=request.request_id,
|
|
106
|
+
capability=capability,
|
|
107
|
+
payload=payload,
|
|
108
|
+
command=command,
|
|
109
|
+
timeout_seconds=self._timeout_seconds,
|
|
110
|
+
)
|
|
111
|
+
try:
|
|
112
|
+
await send_command(command)
|
|
113
|
+
try:
|
|
114
|
+
result = await asyncio.wait_for(request.future, self._timeout_seconds)
|
|
115
|
+
except TimeoutError as exc:
|
|
116
|
+
logger.warning(
|
|
117
|
+
"bridge_request_timeout",
|
|
118
|
+
connection_id=str(connection_id),
|
|
119
|
+
request_id=request.request_id,
|
|
120
|
+
capability=capability,
|
|
121
|
+
timeout_seconds=self._timeout_seconds,
|
|
122
|
+
)
|
|
123
|
+
raise BridgeTimeoutError(request.request_id) from exc
|
|
124
|
+
logger.info(
|
|
125
|
+
"bridge_request_resolved",
|
|
126
|
+
connection_id=str(connection_id),
|
|
127
|
+
request_id=request.request_id,
|
|
128
|
+
capability=capability,
|
|
129
|
+
result=result,
|
|
130
|
+
)
|
|
131
|
+
return result
|
|
132
|
+
finally:
|
|
133
|
+
session.cancel_request(request.request_id)
|
|
134
|
+
|
|
135
|
+
def is_bridge_chat_message(self, sender: str, message: str) -> bool:
|
|
136
|
+
"""True if the player chat message is an addon response fragment."""
|
|
137
|
+
return sender == self._profile.bridge_sender and message.startswith(
|
|
138
|
+
self._profile.bridge_response_prefix
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
def is_ui_chat_message(self, sender: str, message: str) -> bool:
|
|
142
|
+
"""True if the player chat message is a UI chat fragment."""
|
|
143
|
+
return sender == self._profile.bridge_sender and message.startswith(
|
|
144
|
+
self._profile.ui_chat_prefix
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
async def handle_player_message(
|
|
148
|
+
self, connection_id: UUID, sender: str, message: str
|
|
149
|
+
) -> AddonMessageResult:
|
|
150
|
+
"""Route a routed message from the simulated player."""
|
|
151
|
+
if self.is_bridge_chat_message(sender, message):
|
|
152
|
+
# Log every RESP chunk at INFO: these never reach the host hook because
|
|
153
|
+
# the facade short-circuits bridge frames before on_player_message.
|
|
154
|
+
logger.info(
|
|
155
|
+
"bridge_chat_chunk_raw",
|
|
156
|
+
connection_id=str(connection_id),
|
|
157
|
+
sender=sender,
|
|
158
|
+
message=message,
|
|
159
|
+
)
|
|
160
|
+
session = self._sessions.get(connection_id)
|
|
161
|
+
if session is None:
|
|
162
|
+
logger.warning(
|
|
163
|
+
"bridge_chat_no_session",
|
|
164
|
+
connection_id=str(connection_id),
|
|
165
|
+
)
|
|
166
|
+
return AddonMessageResult(handled=True)
|
|
167
|
+
|
|
168
|
+
bridge_chunk = session.handle_chat_chunk(message)
|
|
169
|
+
return AddonMessageResult(handled=True, bridge_chunk=bridge_chunk)
|
|
170
|
+
|
|
171
|
+
if self.is_ui_chat_message(sender, message):
|
|
172
|
+
logger.info(
|
|
173
|
+
"ui_chat_chunk_raw",
|
|
174
|
+
connection_id=str(connection_id),
|
|
175
|
+
sender=sender,
|
|
176
|
+
message=message,
|
|
177
|
+
)
|
|
178
|
+
session = self._session_for(connection_id)
|
|
179
|
+
|
|
180
|
+
ui_chunk, ui_message = session.handle_ui_chat_chunk(message)
|
|
181
|
+
if ui_message is not None and self._ui_chat_callback is not None:
|
|
182
|
+
logger.info(
|
|
183
|
+
"ui_chat_reassembled",
|
|
184
|
+
connection_id=str(connection_id),
|
|
185
|
+
player=ui_message.player_name,
|
|
186
|
+
message_length=len(ui_message.message),
|
|
187
|
+
callback_registered=True,
|
|
188
|
+
)
|
|
189
|
+
await self._ui_chat_callback(
|
|
190
|
+
connection_id,
|
|
191
|
+
ui_message.player_name,
|
|
192
|
+
ui_message.message,
|
|
193
|
+
)
|
|
194
|
+
return AddonMessageResult(
|
|
195
|
+
handled=True,
|
|
196
|
+
ui_chunk=ui_chunk,
|
|
197
|
+
ui_message=ui_message,
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
return AddonMessageResult(handled=False)
|
|
201
|
+
|
|
202
|
+
def set_ui_chat_callback(self, callback: UiChatCallback) -> None:
|
|
203
|
+
"""Register the UI chat message callback."""
|
|
204
|
+
self._ui_chat_callback = callback
|
|
205
|
+
|
|
206
|
+
def close_connection(self, connection_id: UUID) -> None:
|
|
207
|
+
"""Tear down the per-connection session on disconnect."""
|
|
208
|
+
session = self._sessions.pop(connection_id, None)
|
|
209
|
+
if session is not None:
|
|
210
|
+
session.close()
|
|
211
|
+
|
|
212
|
+
def _session_for(self, connection_id: UUID) -> AddonBridgeSession:
|
|
213
|
+
session = self._sessions.get(connection_id)
|
|
214
|
+
if session is None:
|
|
215
|
+
session = AddonBridgeSession(self._settings)
|
|
216
|
+
self._sessions[connection_id] = session
|
|
217
|
+
return session
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class ConnectionAddonBridgeClient:
|
|
221
|
+
"""Per-connection client bound to one bridge service instance."""
|
|
222
|
+
|
|
223
|
+
def __init__(
|
|
224
|
+
self,
|
|
225
|
+
service: AddonBridgeService,
|
|
226
|
+
connection_id: UUID,
|
|
227
|
+
send_command: CommandSender,
|
|
228
|
+
) -> None:
|
|
229
|
+
self._service = service
|
|
230
|
+
self._connection_id = connection_id
|
|
231
|
+
self._send_command = send_command
|
|
232
|
+
|
|
233
|
+
async def request(self, capability: str, payload: dict[str, Any]) -> dict[str, Any]:
|
|
234
|
+
return await self._service.request_capability(
|
|
235
|
+
connection_id=self._connection_id,
|
|
236
|
+
capability=capability,
|
|
237
|
+
payload=payload,
|
|
238
|
+
send_command=self._send_command,
|
|
239
|
+
)
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""Addon bridge session management."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any, Generic, Protocol, TypeVar
|
|
10
|
+
from uuid import uuid4
|
|
11
|
+
|
|
12
|
+
from mcbe_ws_sdk.config import AddonBridgeSettings
|
|
13
|
+
from mcbe_ws_sdk.errors import BridgeClosedError, BridgeLimitError, ProtocolError
|
|
14
|
+
from mcbe_ws_sdk.profiles.mcbews_v1.codec import (
|
|
15
|
+
decode_bridge_chat_chunk,
|
|
16
|
+
decode_ui_chat_chunk,
|
|
17
|
+
reassemble_bridge_chunks,
|
|
18
|
+
reassemble_ui_chat_chunks,
|
|
19
|
+
)
|
|
20
|
+
from mcbe_ws_sdk.profiles.mcbews_v1.models import (
|
|
21
|
+
AddonBridgeChunk,
|
|
22
|
+
UiChatChunk,
|
|
23
|
+
UiChatMessage,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class _ChunkWithContent(Protocol):
|
|
28
|
+
content: str
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
T = TypeVar("T", bound=_ChunkWithContent)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class PendingAddonRequest:
|
|
36
|
+
"""Pending state for a single bridge request."""
|
|
37
|
+
|
|
38
|
+
request_id: str
|
|
39
|
+
capability: str
|
|
40
|
+
payload: dict[str, Any]
|
|
41
|
+
future: asyncio.Future[dict[str, Any]]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class ChunkBuffer(Generic[T]):
|
|
46
|
+
total_chunks: int
|
|
47
|
+
chunks: dict[int, T]
|
|
48
|
+
byte_size: int
|
|
49
|
+
updated_at: float
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class AddonBridgeSession:
|
|
53
|
+
"""Maintain bridge requests and fragment buffers for one connection."""
|
|
54
|
+
|
|
55
|
+
def __init__(
|
|
56
|
+
self,
|
|
57
|
+
settings: AddonBridgeSettings,
|
|
58
|
+
*,
|
|
59
|
+
clock: Callable[[], float] = time.monotonic,
|
|
60
|
+
) -> None:
|
|
61
|
+
self._settings = settings
|
|
62
|
+
self._profile = settings.profile
|
|
63
|
+
self._clock = clock
|
|
64
|
+
self._pending_requests: dict[str, PendingAddonRequest] = {}
|
|
65
|
+
self._chunk_buffers: dict[str, ChunkBuffer[AddonBridgeChunk]] = {}
|
|
66
|
+
self._ui_chat_chunk_buffers: dict[str, ChunkBuffer[UiChatChunk]] = {}
|
|
67
|
+
|
|
68
|
+
def create_request(
|
|
69
|
+
self,
|
|
70
|
+
capability: str,
|
|
71
|
+
payload: dict[str, Any],
|
|
72
|
+
) -> PendingAddonRequest:
|
|
73
|
+
"""Create and register a pending request."""
|
|
74
|
+
if len(self._pending_requests) >= self._settings.max_pending_requests:
|
|
75
|
+
raise BridgeLimitError("maximum pending requests exceeded")
|
|
76
|
+
loop = asyncio.get_running_loop()
|
|
77
|
+
request = PendingAddonRequest(
|
|
78
|
+
request_id=f"addon-{uuid4().hex}",
|
|
79
|
+
capability=capability,
|
|
80
|
+
payload=payload,
|
|
81
|
+
future=loop.create_future(),
|
|
82
|
+
)
|
|
83
|
+
self._pending_requests[request.request_id] = request
|
|
84
|
+
return request
|
|
85
|
+
|
|
86
|
+
def handle_chat_chunk(self, chunk_message: str) -> AddonBridgeChunk:
|
|
87
|
+
"""Consume a chat fragment; resolve its request future once complete."""
|
|
88
|
+
try:
|
|
89
|
+
chunk = decode_bridge_chat_chunk(chunk_message, profile=self._profile)
|
|
90
|
+
except ValueError as exc:
|
|
91
|
+
protocol_error = ProtocolError(str(exc))
|
|
92
|
+
request_id = self._pending_bridge_request_id(chunk_message)
|
|
93
|
+
if request_id is not None and request_id in self._pending_requests:
|
|
94
|
+
self._fail_bridge_request(request_id, protocol_error)
|
|
95
|
+
raise protocol_error from exc
|
|
96
|
+
if chunk.request_id not in self._pending_requests:
|
|
97
|
+
return chunk
|
|
98
|
+
|
|
99
|
+
try:
|
|
100
|
+
buffer = self._accept_chunk(
|
|
101
|
+
self._chunk_buffers,
|
|
102
|
+
buffer_id=chunk.request_id,
|
|
103
|
+
index=chunk.chunk_index,
|
|
104
|
+
total=chunk.total_chunks,
|
|
105
|
+
content=chunk.content,
|
|
106
|
+
item=chunk,
|
|
107
|
+
)
|
|
108
|
+
except (BridgeLimitError, ProtocolError) as error:
|
|
109
|
+
self._fail_bridge_request(chunk.request_id, error)
|
|
110
|
+
raise
|
|
111
|
+
if set(buffer.chunks) != set(range(1, buffer.total_chunks + 1)):
|
|
112
|
+
return chunk
|
|
113
|
+
|
|
114
|
+
complete = self._chunk_buffers.pop(chunk.request_id)
|
|
115
|
+
try:
|
|
116
|
+
response = reassemble_bridge_chunks(list(complete.chunks.values()))
|
|
117
|
+
except ValueError as exc:
|
|
118
|
+
protocol_error = ProtocolError(str(exc))
|
|
119
|
+
self._fail_bridge_request(chunk.request_id, protocol_error)
|
|
120
|
+
raise protocol_error from exc
|
|
121
|
+
|
|
122
|
+
request = self._pending_requests.pop(chunk.request_id, None)
|
|
123
|
+
if request is not None and not request.future.done():
|
|
124
|
+
request.future.set_result(response.payload)
|
|
125
|
+
return chunk
|
|
126
|
+
|
|
127
|
+
def _fail_bridge_request(self, request_id: str, error: Exception) -> None:
|
|
128
|
+
request = self._pending_requests.pop(request_id, None)
|
|
129
|
+
self._chunk_buffers.pop(request_id, None)
|
|
130
|
+
if request is not None and not request.future.done():
|
|
131
|
+
request.future.set_exception(error)
|
|
132
|
+
|
|
133
|
+
def _pending_bridge_request_id(self, chunk_message: str) -> str | None:
|
|
134
|
+
parts = chunk_message.split("|", 4)
|
|
135
|
+
if len(parts) != 5:
|
|
136
|
+
return None
|
|
137
|
+
namespace, prefix, request_id, _, _ = parts
|
|
138
|
+
bridge_prefix = self._profile.bridge_response_prefix.split("|", 1)
|
|
139
|
+
if len(bridge_prefix) != 2:
|
|
140
|
+
return None
|
|
141
|
+
expected_namespace, expected_prefix = bridge_prefix
|
|
142
|
+
if namespace != expected_namespace or prefix != expected_prefix or not request_id:
|
|
143
|
+
return None
|
|
144
|
+
return request_id
|
|
145
|
+
|
|
146
|
+
def cancel_request(self, request_id: str) -> None:
|
|
147
|
+
request = self._pending_requests.pop(request_id, None)
|
|
148
|
+
self._chunk_buffers.pop(request_id, None)
|
|
149
|
+
if request is not None and not request.future.done():
|
|
150
|
+
request.future.cancel()
|
|
151
|
+
|
|
152
|
+
def close(self) -> None:
|
|
153
|
+
"""Close the session, failing every pending request."""
|
|
154
|
+
pending_ids = list(self._pending_requests)
|
|
155
|
+
for request_id in pending_ids:
|
|
156
|
+
request = self._pending_requests.pop(request_id, None)
|
|
157
|
+
self._chunk_buffers.pop(request_id, None)
|
|
158
|
+
if request is not None and not request.future.done():
|
|
159
|
+
request.future.set_exception(BridgeClosedError(request_id))
|
|
160
|
+
self._ui_chat_chunk_buffers.clear()
|
|
161
|
+
|
|
162
|
+
def handle_ui_chat_chunk(self, chunk_message: str) -> tuple[UiChatChunk, UiChatMessage | None]:
|
|
163
|
+
"""Consume a UI chat fragment; return the chunk and a completed message if available."""
|
|
164
|
+
try:
|
|
165
|
+
chunk = decode_ui_chat_chunk(chunk_message, profile=self._profile)
|
|
166
|
+
except ValueError as exc:
|
|
167
|
+
raise ProtocolError(str(exc)) from exc
|
|
168
|
+
|
|
169
|
+
buffer = self._accept_chunk(
|
|
170
|
+
self._ui_chat_chunk_buffers,
|
|
171
|
+
buffer_id=chunk.msg_id,
|
|
172
|
+
index=chunk.chunk_index,
|
|
173
|
+
total=chunk.total_chunks,
|
|
174
|
+
content=chunk.content,
|
|
175
|
+
item=chunk,
|
|
176
|
+
)
|
|
177
|
+
if set(buffer.chunks) != set(range(1, buffer.total_chunks + 1)):
|
|
178
|
+
return chunk, None
|
|
179
|
+
|
|
180
|
+
complete = self._ui_chat_chunk_buffers.pop(chunk.msg_id)
|
|
181
|
+
try:
|
|
182
|
+
ui_message = reassemble_ui_chat_chunks(list(complete.chunks.values()))
|
|
183
|
+
except ValueError as exc:
|
|
184
|
+
raise ProtocolError(str(exc)) from exc
|
|
185
|
+
return chunk, ui_message
|
|
186
|
+
|
|
187
|
+
def _accept_chunk(
|
|
188
|
+
self,
|
|
189
|
+
buffers: dict[str, ChunkBuffer[T]],
|
|
190
|
+
*,
|
|
191
|
+
buffer_id: str,
|
|
192
|
+
index: int,
|
|
193
|
+
total: int,
|
|
194
|
+
content: str,
|
|
195
|
+
item: T,
|
|
196
|
+
) -> ChunkBuffer[T]:
|
|
197
|
+
self._prune_expired()
|
|
198
|
+
if not 1 <= index <= total <= self._settings.max_chunks_per_message:
|
|
199
|
+
raise BridgeLimitError("invalid chunk index or total")
|
|
200
|
+
encoded_size = len(content.encode("utf-8"))
|
|
201
|
+
current = buffers.get(buffer_id)
|
|
202
|
+
if current is None:
|
|
203
|
+
if self._buffer_count() >= self._settings.max_buffer_ids:
|
|
204
|
+
raise BridgeLimitError("maximum buffer ids exceeded")
|
|
205
|
+
current = ChunkBuffer(total, {}, 0, self._clock())
|
|
206
|
+
buffers[buffer_id] = current
|
|
207
|
+
elif current.total_chunks != total:
|
|
208
|
+
self._drop_buffer(buffers, buffer_id)
|
|
209
|
+
raise ProtocolError("chunk total changed")
|
|
210
|
+
existing = current.chunks.get(index)
|
|
211
|
+
if existing is not None:
|
|
212
|
+
if self._chunk_content(existing) != content:
|
|
213
|
+
self._drop_buffer(buffers, buffer_id)
|
|
214
|
+
raise ProtocolError("duplicate chunk content changed")
|
|
215
|
+
return current
|
|
216
|
+
if current.byte_size + encoded_size > self._settings.max_message_bytes:
|
|
217
|
+
self._drop_buffer(buffers, buffer_id)
|
|
218
|
+
raise BridgeLimitError("message byte limit exceeded")
|
|
219
|
+
if self._total_buffer_bytes() + encoded_size > self._settings.max_total_buffer_bytes:
|
|
220
|
+
self._drop_buffer(buffers, buffer_id)
|
|
221
|
+
raise BridgeLimitError("total buffer byte limit exceeded")
|
|
222
|
+
current.chunks[index] = item
|
|
223
|
+
current.byte_size += encoded_size
|
|
224
|
+
current.updated_at = self._clock()
|
|
225
|
+
return current
|
|
226
|
+
|
|
227
|
+
def _prune_expired(self) -> None:
|
|
228
|
+
"""Drop every chunk buffer whose TTL has elapsed."""
|
|
229
|
+
now = self._clock()
|
|
230
|
+
ttl = self._settings.buffer_ttl_seconds
|
|
231
|
+
for buffer_id, bridge_buffer in list(self._chunk_buffers.items()):
|
|
232
|
+
if now - bridge_buffer.updated_at >= ttl:
|
|
233
|
+
self._drop_buffer(self._chunk_buffers, buffer_id)
|
|
234
|
+
self._fail_bridge_request(buffer_id, BridgeLimitError("chunk buffer expired"))
|
|
235
|
+
for buffer_id, ui_buffer in list(self._ui_chat_chunk_buffers.items()):
|
|
236
|
+
if now - ui_buffer.updated_at >= ttl:
|
|
237
|
+
self._drop_buffer(self._ui_chat_chunk_buffers, buffer_id)
|
|
238
|
+
|
|
239
|
+
@staticmethod
|
|
240
|
+
def _drop_buffer(
|
|
241
|
+
buffers: dict[str, ChunkBuffer[T]],
|
|
242
|
+
buffer_id: str,
|
|
243
|
+
) -> None:
|
|
244
|
+
buffers.pop(buffer_id, None)
|
|
245
|
+
|
|
246
|
+
def _buffer_count(self) -> int:
|
|
247
|
+
return len(self._chunk_buffers) + len(self._ui_chat_chunk_buffers)
|
|
248
|
+
|
|
249
|
+
def _total_buffer_bytes(self) -> int:
|
|
250
|
+
return sum(buffer.byte_size for buffer in self._chunk_buffers.values()) + sum(
|
|
251
|
+
buffer.byte_size for buffer in self._ui_chat_chunk_buffers.values()
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
@staticmethod
|
|
255
|
+
def _chunk_content(chunk: _ChunkWithContent) -> str:
|
|
256
|
+
return chunk.content
|