bma-executor-sdk 0.4.6__tar.gz → 0.4.8__tar.gz
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.
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/PKG-INFO +5 -4
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/README.md +4 -3
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/pyproject.toml +1 -1
- bma_executor_sdk-0.4.8/src/bma_executor_sdk/_npipe.py +281 -0
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/src/bma_executor_sdk/client.py +1 -1
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/src/bma_executor_sdk/generated.py +16 -1
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/src/bma_executor_sdk/harness.py +31 -6
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/src/bma_executor_sdk/transport.py +13 -5
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/tests/executor_helpers.py +28 -0
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/tests/test_executor_interop.py +22 -6
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/tests/test_executor_runtime.py +23 -6
- bma_executor_sdk-0.4.8/tests/test_npipe.py +53 -0
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/.gitignore +0 -0
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/examples/agent_minimal.py +0 -0
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/examples/executor_minimal.py +0 -0
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/examples/harness_loopback.py +0 -0
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/src/bma_executor_sdk/__init__.py +0 -0
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/src/bma_executor_sdk/_rpc.py +0 -0
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/src/bma_executor_sdk/agent.py +0 -0
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/tests/test_close_codes.py +0 -0
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/tests/test_executor_conformance.py +0 -0
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/tests/test_executor_contract.py +0 -0
- {bma_executor_sdk-0.4.6 → bma_executor_sdk-0.4.8}/tests/test_executor_token_refresh.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: bma-executor-sdk
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.8
|
|
4
4
|
Summary: BMA executor protocol (bma.executor.v1.1): executor, harness and agent ends on asyncio with WebSocket, Unix socket and in-process transports.
|
|
5
5
|
Project-URL: Repository, https://github.com/beeos-ai/bma-sdks
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -17,13 +17,13 @@ asyncio executor (`ExecutorClient`), harness (`Harness`) and agent ends of the B
|
|
|
17
17
|
|
|
18
18
|
| | |
|
|
19
19
|
| --- | --- |
|
|
20
|
-
| Version | 0.4.
|
|
20
|
+
| Version | 0.4.8 (tag `executor-python/v0.4.8`), see [CHANGELOG](../../CHANGELOG.md) |
|
|
21
21
|
| Protocol | `bma.executor.v1.1` (contract 1.1.0, [`lock.json`](../../contracts/bma/executor/lock.json)) |
|
|
22
22
|
| Python | 3.10 or newer; depends on `httpx` and `websockets` |
|
|
23
23
|
| Integration guide | [docs/executor](../../docs/executor/README.md) ([中文](../../docs/executor/README.zh-CN.md)) |
|
|
24
24
|
|
|
25
25
|
```sh
|
|
26
|
-
pip install bma-executor-sdk==0.4.
|
|
26
|
+
pip install bma-executor-sdk==0.4.8
|
|
27
27
|
```
|
|
28
28
|
|
|
29
29
|
The REST / façade client is the separate package [`bma-sdk`](../../python).
|
|
@@ -87,9 +87,10 @@ Chosen by the channel URL of the token source:
|
|
|
87
87
|
| --- | --- | --- |
|
|
88
88
|
| WebSocket (`ws://`, `wss://`) | default | `await harness.serve(host, port)` |
|
|
89
89
|
| WebSocket over a Unix domain socket (`unix:///path.sock`) | `token_source=static_token("unix:///path.sock", token)` | `await harness.serve_unix(path)` |
|
|
90
|
+
| Windows named pipe (`npipe:////./pipe/<name>`, Windows ProactorEventLoop) | `token_source=static_token("npipe:////./pipe/<name>", token)` | `await harness.serve_npipe(name)` |
|
|
90
91
|
| In process | `dialer=harness.inprocess_dialer()` | — |
|
|
91
92
|
|
|
92
|
-
The executor-listens local socket
|
|
93
|
+
The executor-listens local socket is not implemented in Python (use the Go or TypeScript SDK); named pipes need the Windows `ProactorEventLoop` (the asyncio default there) and are tested on a Windows runner in CI. See [local connection](../../docs/executor/local-connection.md).
|
|
93
94
|
|
|
94
95
|
## Agent executors
|
|
95
96
|
|
|
@@ -6,13 +6,13 @@ asyncio executor (`ExecutorClient`), harness (`Harness`) and agent ends of the B
|
|
|
6
6
|
|
|
7
7
|
| | |
|
|
8
8
|
| --- | --- |
|
|
9
|
-
| Version | 0.4.
|
|
9
|
+
| Version | 0.4.8 (tag `executor-python/v0.4.8`), see [CHANGELOG](../../CHANGELOG.md) |
|
|
10
10
|
| Protocol | `bma.executor.v1.1` (contract 1.1.0, [`lock.json`](../../contracts/bma/executor/lock.json)) |
|
|
11
11
|
| Python | 3.10 or newer; depends on `httpx` and `websockets` |
|
|
12
12
|
| Integration guide | [docs/executor](../../docs/executor/README.md) ([中文](../../docs/executor/README.zh-CN.md)) |
|
|
13
13
|
|
|
14
14
|
```sh
|
|
15
|
-
pip install bma-executor-sdk==0.4.
|
|
15
|
+
pip install bma-executor-sdk==0.4.8
|
|
16
16
|
```
|
|
17
17
|
|
|
18
18
|
The REST / façade client is the separate package [`bma-sdk`](../../python).
|
|
@@ -76,9 +76,10 @@ Chosen by the channel URL of the token source:
|
|
|
76
76
|
| --- | --- | --- |
|
|
77
77
|
| WebSocket (`ws://`, `wss://`) | default | `await harness.serve(host, port)` |
|
|
78
78
|
| WebSocket over a Unix domain socket (`unix:///path.sock`) | `token_source=static_token("unix:///path.sock", token)` | `await harness.serve_unix(path)` |
|
|
79
|
+
| Windows named pipe (`npipe:////./pipe/<name>`, Windows ProactorEventLoop) | `token_source=static_token("npipe:////./pipe/<name>", token)` | `await harness.serve_npipe(name)` |
|
|
79
80
|
| In process | `dialer=harness.inprocess_dialer()` | — |
|
|
80
81
|
|
|
81
|
-
The executor-listens local socket
|
|
82
|
+
The executor-listens local socket is not implemented in Python (use the Go or TypeScript SDK); named pipes need the Windows `ProactorEventLoop` (the asyncio default there) and are tested on a Windows runner in CI. See [local connection](../../docs/executor/local-connection.md).
|
|
82
83
|
|
|
83
84
|
## Agent executors
|
|
84
85
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "bma-executor-sdk"
|
|
3
|
-
version = "0.4.
|
|
3
|
+
version = "0.4.8"
|
|
4
4
|
description = "BMA executor protocol (bma.executor.v1.1): executor, harness and agent ends on asyncio with WebSocket, Unix socket and in-process transports."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "Apache-2.0"
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""WebSocket over a Windows named pipe (``npipe:////./pipe/<name>``).
|
|
2
|
+
|
|
3
|
+
``websockets`` has no named pipe transport, so this drives its sans-I/O
|
|
4
|
+
protocol from one ``asyncio.Protocol`` that works on any asyncio transport.
|
|
5
|
+
On Windows the transport comes from the ProactorEventLoop (the default),
|
|
6
|
+
``create_pipe_connection`` and ``start_serving_pipe``; the protocol class
|
|
7
|
+
itself is transport-agnostic and is tested over a Unix socket on other
|
|
8
|
+
platforms. No pywin32.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import asyncio
|
|
14
|
+
import re
|
|
15
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
16
|
+
from http import HTTPStatus
|
|
17
|
+
from urllib.parse import urlsplit
|
|
18
|
+
|
|
19
|
+
from websockets.client import ClientProtocol
|
|
20
|
+
from websockets.frames import Frame, Opcode
|
|
21
|
+
from websockets.http11 import Request, Response
|
|
22
|
+
from websockets.server import ServerProtocol
|
|
23
|
+
from websockets.uri import parse_uri
|
|
24
|
+
|
|
25
|
+
from .transport import CLOSE_NORMAL, ChannelClosed, Connection
|
|
26
|
+
|
|
27
|
+
PIPE_DIR = "\\\\.\\pipe\\"
|
|
28
|
+
_CLOSE_TIMEOUT = 5.0
|
|
29
|
+
_OPEN_TIMEOUT = 10.0
|
|
30
|
+
_PIPE_PATH = re.compile(r"^/{1,2}(?:\./)?pipe/([^/\\]+)$")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def pipe_path(url_or_name: str) -> str:
|
|
34
|
+
"""The ``\\\\.\\pipe\\<name>`` path of an ``npipe:////./pipe/<name>`` URL, a
|
|
35
|
+
``\\\\.\\pipe\\<name>`` path or a bare pipe name."""
|
|
36
|
+
name = url_or_name
|
|
37
|
+
if url_or_name.startswith("npipe:"):
|
|
38
|
+
found = _PIPE_PATH.match(urlsplit(url_or_name).path)
|
|
39
|
+
name = found.group(1) if found else ""
|
|
40
|
+
elif url_or_name.startswith(PIPE_DIR):
|
|
41
|
+
name = url_or_name[len(PIPE_DIR):]
|
|
42
|
+
if not name or "/" in name or "\\" in name:
|
|
43
|
+
raise ValueError(f"bma_executor_sdk: invalid named pipe {url_or_name!r}")
|
|
44
|
+
return PIPE_DIR + name
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def pipe_url(path_or_name: str) -> str:
|
|
48
|
+
return "npipe:////./pipe/" + pipe_path(path_or_name)[len(PIPE_DIR):]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# What the server side does with an upgrade request (subprotocols offered,
|
|
52
|
+
# request target, headers): admit it, returning the handler that serves the
|
|
53
|
+
# connection, or refuse it with a status and a message.
|
|
54
|
+
Handler = Callable[[Connection], Awaitable[None]]
|
|
55
|
+
Admission = Handler | tuple[HTTPStatus, str]
|
|
56
|
+
Admit = Callable[[str, str, Mapping[str, str]], Awaitable[Admission]]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class PipeWebSocket(asyncio.Protocol):
|
|
60
|
+
"""One WebSocket end (client or server) on an asyncio transport; the
|
|
61
|
+
Connection interface of the executor protocol."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, protocol: ClientProtocol | ServerProtocol, *, token: str = "", admit: Admit | None = None) -> None:
|
|
64
|
+
self._protocol = protocol
|
|
65
|
+
self._token = token
|
|
66
|
+
self._admit = admit
|
|
67
|
+
self._transport: asyncio.Transport | None = None
|
|
68
|
+
self._messages: asyncio.Queue[str | ChannelClosed] = asyncio.Queue()
|
|
69
|
+
self._fragments: list[bytes] = []
|
|
70
|
+
self._closed: ChannelClosed | None = None
|
|
71
|
+
loop = asyncio.get_running_loop()
|
|
72
|
+
self._opened: asyncio.Future[None] = loop.create_future()
|
|
73
|
+
self._opened.add_done_callback(lambda done: done.cancelled() or done.exception()) # a server end never awaits it
|
|
74
|
+
self._lost = asyncio.Event()
|
|
75
|
+
self._eof = False
|
|
76
|
+
self.on_lost: Callable[[PipeWebSocket], None] | None = None
|
|
77
|
+
self.tasks: set[asyncio.Task[None]] = set()
|
|
78
|
+
|
|
79
|
+
# --- Connection ---
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def subprotocol(self) -> str | None:
|
|
83
|
+
return self._protocol.subprotocol
|
|
84
|
+
|
|
85
|
+
async def send(self, message: str) -> None:
|
|
86
|
+
if self._closed is not None or self._transport is None:
|
|
87
|
+
raise self._closed or ChannelClosed(1006, "abnormal closure")
|
|
88
|
+
try:
|
|
89
|
+
self._protocol.send_text(message.encode())
|
|
90
|
+
except Exception as error:
|
|
91
|
+
raise ChannelClosed(self._protocol.close_code or 1006, "connection closed") from error
|
|
92
|
+
self._flush()
|
|
93
|
+
|
|
94
|
+
async def recv(self) -> str:
|
|
95
|
+
if self._closed is not None and self._messages.empty():
|
|
96
|
+
raise self._closed
|
|
97
|
+
item = await self._messages.get()
|
|
98
|
+
if isinstance(item, ChannelClosed):
|
|
99
|
+
self._messages.put_nowait(item) # every later recv fails the same way
|
|
100
|
+
raise item
|
|
101
|
+
return item
|
|
102
|
+
|
|
103
|
+
async def close(self, code: int = CLOSE_NORMAL, reason: str = "") -> None:
|
|
104
|
+
if self._transport is None:
|
|
105
|
+
return
|
|
106
|
+
try:
|
|
107
|
+
self._protocol.send_close(code, reason)
|
|
108
|
+
except Exception:
|
|
109
|
+
pass # already closing
|
|
110
|
+
self._flush()
|
|
111
|
+
try:
|
|
112
|
+
await asyncio.wait_for(self._lost.wait(), _CLOSE_TIMEOUT)
|
|
113
|
+
except asyncio.TimeoutError:
|
|
114
|
+
self._transport.abort()
|
|
115
|
+
|
|
116
|
+
def abort(self) -> None:
|
|
117
|
+
if self._transport is not None:
|
|
118
|
+
self._transport.abort()
|
|
119
|
+
|
|
120
|
+
async def handshake(self) -> None:
|
|
121
|
+
"""Client: wait for the upgrade response."""
|
|
122
|
+
await asyncio.wait_for(asyncio.shield(self._opened), _OPEN_TIMEOUT)
|
|
123
|
+
|
|
124
|
+
# --- asyncio.Protocol ---
|
|
125
|
+
|
|
126
|
+
def connection_made(self, transport: asyncio.BaseTransport) -> None:
|
|
127
|
+
self._transport = transport # type: ignore[assignment]
|
|
128
|
+
if isinstance(self._protocol, ClientProtocol):
|
|
129
|
+
request = self._protocol.connect()
|
|
130
|
+
if self._token:
|
|
131
|
+
request.headers["Authorization"] = f"Bearer {self._token}"
|
|
132
|
+
self._protocol.send_request(request)
|
|
133
|
+
self._flush()
|
|
134
|
+
|
|
135
|
+
def data_received(self, data: bytes) -> None:
|
|
136
|
+
self._protocol.receive_data(data)
|
|
137
|
+
self._pump()
|
|
138
|
+
|
|
139
|
+
def eof_received(self) -> bool:
|
|
140
|
+
self._receive_eof()
|
|
141
|
+
self._pump()
|
|
142
|
+
return False # close the transport
|
|
143
|
+
|
|
144
|
+
def _receive_eof(self) -> None:
|
|
145
|
+
if not self._eof:
|
|
146
|
+
self._eof = True
|
|
147
|
+
self._protocol.receive_eof()
|
|
148
|
+
|
|
149
|
+
def connection_lost(self, exc: Exception | None) -> None:
|
|
150
|
+
self._receive_eof()
|
|
151
|
+
self._pump(lost=True)
|
|
152
|
+
close = self._protocol.close_rcvd
|
|
153
|
+
self._closed = ChannelClosed(close.code, close.reason) if close is not None else ChannelClosed(1006, "abnormal closure")
|
|
154
|
+
self._messages.put_nowait(self._closed)
|
|
155
|
+
if not self._opened.done():
|
|
156
|
+
self._opened.set_exception(ConnectionError(f"named pipe closed during the WebSocket handshake: {exc or 'EOF'}"))
|
|
157
|
+
self._lost.set()
|
|
158
|
+
if self.on_lost is not None:
|
|
159
|
+
self.on_lost(self)
|
|
160
|
+
|
|
161
|
+
# --- driving the sans-I/O protocol ---
|
|
162
|
+
|
|
163
|
+
def _flush(self) -> None:
|
|
164
|
+
transport = self._transport
|
|
165
|
+
if transport is None:
|
|
166
|
+
return
|
|
167
|
+
for data in self._protocol.data_to_send():
|
|
168
|
+
if data == b"":
|
|
169
|
+
transport.close() # the protocol is done: end the stream
|
|
170
|
+
elif not transport.is_closing():
|
|
171
|
+
transport.write(data)
|
|
172
|
+
|
|
173
|
+
def _pump(self, lost: bool = False) -> None:
|
|
174
|
+
for event in self._protocol.events_received():
|
|
175
|
+
if isinstance(event, Response):
|
|
176
|
+
self._on_response()
|
|
177
|
+
elif isinstance(event, Request):
|
|
178
|
+
self._on_request(event)
|
|
179
|
+
elif isinstance(event, Frame):
|
|
180
|
+
self._on_frame(event)
|
|
181
|
+
if not lost:
|
|
182
|
+
self._flush()
|
|
183
|
+
|
|
184
|
+
def _on_response(self) -> None:
|
|
185
|
+
error = self._protocol.handshake_exc
|
|
186
|
+
if self._opened.done():
|
|
187
|
+
return
|
|
188
|
+
if error is None:
|
|
189
|
+
self._opened.set_result(None)
|
|
190
|
+
else:
|
|
191
|
+
self._opened.set_exception(error)
|
|
192
|
+
|
|
193
|
+
def _on_request(self, request: Request) -> None:
|
|
194
|
+
task = asyncio.ensure_future(self._serve(request))
|
|
195
|
+
self.tasks.add(task)
|
|
196
|
+
task.add_done_callback(self.tasks.discard)
|
|
197
|
+
|
|
198
|
+
async def _serve(self, request: Request) -> None:
|
|
199
|
+
protocol = self._protocol
|
|
200
|
+
assert isinstance(protocol, ServerProtocol) and self._admit is not None
|
|
201
|
+
offered = ",".join(request.headers.get_all("Sec-WebSocket-Protocol"))
|
|
202
|
+
admission = await self._admit(offered, request.path, dict(request.headers.raw_items()))
|
|
203
|
+
if isinstance(admission, tuple):
|
|
204
|
+
protocol.send_response(protocol.reject(admission[0], admission[1] + "\n"))
|
|
205
|
+
self._flush()
|
|
206
|
+
return
|
|
207
|
+
handler = admission
|
|
208
|
+
response = protocol.accept(request)
|
|
209
|
+
protocol.send_response(response)
|
|
210
|
+
self._flush()
|
|
211
|
+
if protocol.handshake_exc is not None:
|
|
212
|
+
return
|
|
213
|
+
try:
|
|
214
|
+
await handler(self)
|
|
215
|
+
finally:
|
|
216
|
+
await self.close()
|
|
217
|
+
|
|
218
|
+
def _on_frame(self, frame: Frame) -> None:
|
|
219
|
+
if frame.opcode in (Opcode.TEXT, Opcode.BINARY):
|
|
220
|
+
self._fragments = [frame.data]
|
|
221
|
+
elif frame.opcode is Opcode.CONT:
|
|
222
|
+
self._fragments.append(frame.data)
|
|
223
|
+
else:
|
|
224
|
+
return # ping/pong are answered by the protocol; close ends the stream
|
|
225
|
+
if frame.fin:
|
|
226
|
+
self._messages.put_nowait(b"".join(self._fragments).decode())
|
|
227
|
+
self._fragments = []
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
async def dial(url: str, token: str, subprotocols: Sequence[str], *, max_size: int) -> PipeWebSocket:
|
|
231
|
+
"""Open a channel on the named pipe of an ``npipe://`` URL (ProactorEventLoop)."""
|
|
232
|
+
loop = asyncio.get_running_loop()
|
|
233
|
+
if not hasattr(loop, "create_pipe_connection"):
|
|
234
|
+
raise NotImplementedError("bma_executor_sdk: npipe:// needs the Windows ProactorEventLoop")
|
|
235
|
+
path = pipe_path(url)
|
|
236
|
+
query = urlsplit(url).query
|
|
237
|
+
uri = parse_uri("ws://localhost/v1/executors/channel" + (f"?{query}" if query else ""))
|
|
238
|
+
ws = PipeWebSocket(ClientProtocol(uri, subprotocols=list(subprotocols), max_size=max_size), token=token) # type: ignore[arg-type]
|
|
239
|
+
await loop.create_pipe_connection(lambda: ws, path) # type: ignore[attr-defined]
|
|
240
|
+
try:
|
|
241
|
+
await ws.handshake()
|
|
242
|
+
except BaseException:
|
|
243
|
+
ws.abort()
|
|
244
|
+
raise
|
|
245
|
+
return ws
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
class NamedPipeServer:
|
|
249
|
+
"""The listening named pipe of Harness.serve_npipe."""
|
|
250
|
+
|
|
251
|
+
def __init__(self, servers: list[object], connections: set[PipeWebSocket]) -> None:
|
|
252
|
+
self._servers = servers
|
|
253
|
+
self._connections = connections
|
|
254
|
+
|
|
255
|
+
def close(self) -> None:
|
|
256
|
+
for server in self._servers:
|
|
257
|
+
server.close() # type: ignore[attr-defined]
|
|
258
|
+
for connection in list(self._connections):
|
|
259
|
+
connection.abort()
|
|
260
|
+
|
|
261
|
+
async def wait_closed(self) -> None:
|
|
262
|
+
while self._connections:
|
|
263
|
+
await asyncio.sleep(0.01)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
async def serve(path_or_name: str, admit: Admit, subprotocols: Sequence[str], *, max_size: int) -> NamedPipeServer:
|
|
267
|
+
"""Listen on a named pipe for the current user (the first instance of the
|
|
268
|
+
pipe name; Windows ProactorEventLoop)."""
|
|
269
|
+
loop = asyncio.get_running_loop()
|
|
270
|
+
if not hasattr(loop, "start_serving_pipe"):
|
|
271
|
+
raise NotImplementedError("bma_executor_sdk: npipe:// needs the Windows ProactorEventLoop")
|
|
272
|
+
connections: set[PipeWebSocket] = set()
|
|
273
|
+
|
|
274
|
+
def factory() -> PipeWebSocket:
|
|
275
|
+
ws = PipeWebSocket(ServerProtocol(subprotocols=list(subprotocols), max_size=max_size), admit=admit) # type: ignore[arg-type]
|
|
276
|
+
connections.add(ws)
|
|
277
|
+
ws.on_lost = connections.discard
|
|
278
|
+
return ws
|
|
279
|
+
|
|
280
|
+
servers = await loop.start_serving_pipe(factory, pipe_path(path_or_name)) # type: ignore[attr-defined]
|
|
281
|
+
return NamedPipeServer(servers, connections)
|
|
@@ -91,7 +91,7 @@ class LogEvent:
|
|
|
91
91
|
|
|
92
92
|
def static_token(ws_url: str, token: str = "") -> TokenSource:
|
|
93
93
|
"""TokenSource for a harness reached directly (a local harness on
|
|
94
|
-
``ws://127.0.0.1``, ``unix:///path.sock`` or in-process). token may be empty
|
|
94
|
+
``ws://127.0.0.1``, ``unix:///path.sock``, ``npipe:////./pipe/name`` or in-process). token may be empty
|
|
95
95
|
when the harness has no authenticate hook."""
|
|
96
96
|
|
|
97
97
|
async def source() -> ExecutorTokenResponse:
|
|
@@ -413,6 +413,7 @@ class McpCapability(TypedDict):
|
|
|
413
413
|
stdio: NotRequired[bool]
|
|
414
414
|
http: NotRequired[bool]
|
|
415
415
|
max_servers: NotRequired[int]
|
|
416
|
+
secret_env: NotRequired[bool]
|
|
416
417
|
|
|
417
418
|
class McpConnectionOrigin(str, Enum):
|
|
418
419
|
"""Who connects the MCP server. environment means the executor starts/connects it; service means the harness connects."""
|
|
@@ -484,6 +485,7 @@ class McpServerTransport(TypedDict):
|
|
|
484
485
|
args: NotRequired[list[str]]
|
|
485
486
|
cwd: NotRequired[str]
|
|
486
487
|
env: NotRequired[dict[str, str]]
|
|
488
|
+
secret_env: NotRequired[dict[str, str]]
|
|
487
489
|
timeout_ms: NotRequired[int]
|
|
488
490
|
command_sha256: NotRequired[str]
|
|
489
491
|
url: NotRequired[str]
|
|
@@ -513,19 +515,26 @@ class McpTransportType(str, Enum):
|
|
|
513
515
|
Stdio = "stdio"
|
|
514
516
|
Http = "http"
|
|
515
517
|
|
|
518
|
+
class PackageManager(str, Enum):
|
|
519
|
+
"""Package manager for process.start package_install."""
|
|
520
|
+
Apt = "apt"
|
|
521
|
+
Pip = "pip"
|
|
522
|
+
Npm = "npm"
|
|
523
|
+
|
|
516
524
|
class PermissionMode(str, Enum):
|
|
517
525
|
"""Tool permission mode; always_ask means the harness already resolved approval."""
|
|
518
526
|
AlwaysAllow = "always_allow"
|
|
519
527
|
AlwaysAsk = "always_ask"
|
|
520
528
|
|
|
521
529
|
class ProcessCapability(TypedDict):
|
|
522
|
-
"""v1.1 process.* support. pty, file_transfer and git_credentials are additive: the harness only sends the matching process.start fields to an executor that set them, and fails the process explicitly otherwise."""
|
|
530
|
+
"""v1.1 process.* support. pty, file_transfer, package_install and git_credentials are additive: the harness only sends the matching process.start fields to an executor that set them, and fails the process explicitly otherwise."""
|
|
523
531
|
enabled: bool
|
|
524
532
|
max_processes: NotRequired[int]
|
|
525
533
|
buffer_bytes: NotRequired[int]
|
|
526
534
|
pty: NotRequired[bool]
|
|
527
535
|
file_transfer: NotRequired[bool]
|
|
528
536
|
git_credentials: NotRequired[bool]
|
|
537
|
+
package_install: NotRequired[bool]
|
|
529
538
|
|
|
530
539
|
class ProcessFileTransfer(TypedDict):
|
|
531
540
|
"""Replaces argv: the executor moves one file between the machine and the process BMA file endpoint and reports the outcome in ProcessState.file_transfer. Requires process.file_transfer."""
|
|
@@ -536,6 +545,11 @@ class ProcessListResult(TypedDict):
|
|
|
536
545
|
"""process.list result."""
|
|
537
546
|
processes: list[ProcessState]
|
|
538
547
|
|
|
548
|
+
class ProcessPackageInstall(TypedDict):
|
|
549
|
+
"""Replaces argv: the executor installs packages with a fixed command it builds itself, streaming the package manager output as the process output. apt installs from the machine's configured (official) sources with the executor's own privileges; pip (--user) and npm (global under the workload user's ~/.local) run as the workload user. Package names are plain names only: no options, versions, paths or URLs. Requires process.package_install."""
|
|
550
|
+
manager: PackageManager
|
|
551
|
+
packages: list[str]
|
|
552
|
+
|
|
539
553
|
class ProcessReadResult(TypedDict):
|
|
540
554
|
"""process.read result."""
|
|
541
555
|
process_id: str
|
|
@@ -926,6 +940,7 @@ class ProcessStartParams(TypedDict):
|
|
|
926
940
|
metadata: NotRequired[dict[str, str]]
|
|
927
941
|
io_mode: NotRequired[IOMode]
|
|
928
942
|
file_transfer: NotRequired[ProcessFileTransfer]
|
|
943
|
+
package_install: NotRequired[ProcessPackageInstall]
|
|
929
944
|
git_credentials: NotRequired[bool]
|
|
930
945
|
|
|
931
946
|
class ProcessReadParams(TypedDict):
|
|
@@ -12,7 +12,7 @@ from __future__ import annotations
|
|
|
12
12
|
import asyncio
|
|
13
13
|
import inspect
|
|
14
14
|
import secrets
|
|
15
|
-
from collections.abc import Awaitable, Callable, Sequence
|
|
15
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
16
16
|
from dataclasses import dataclass
|
|
17
17
|
from datetime import datetime, timezone
|
|
18
18
|
from http import HTTPStatus
|
|
@@ -215,6 +215,25 @@ class Harness:
|
|
|
215
215
|
|
|
216
216
|
return await unix_serve(self._ws_handler, path, **self._ws_options())
|
|
217
217
|
|
|
218
|
+
async def serve_npipe(self, name: str) -> Any:
|
|
219
|
+
"""Listen for WebSocket channels on the Windows named pipe
|
|
220
|
+
``\\\\.\\pipe\\<name>`` (ProactorEventLoop, the Windows default);
|
|
221
|
+
executors use ``npipe:////./pipe/<name>``. Returns a server with
|
|
222
|
+
``close()`` and ``wait_closed()``."""
|
|
223
|
+
from . import _npipe
|
|
224
|
+
|
|
225
|
+
async def admit(offered: str, target: str, headers: Mapping[str, str]) -> Any:
|
|
226
|
+
connect, principal, refusal = await self._admit_upgrade(offered, target, headers)
|
|
227
|
+
if refusal is not None:
|
|
228
|
+
return refusal
|
|
229
|
+
|
|
230
|
+
async def handler(conn: Connection) -> None:
|
|
231
|
+
await self._serve_channel(conn, connect, principal)
|
|
232
|
+
|
|
233
|
+
return handler
|
|
234
|
+
|
|
235
|
+
return await _npipe.serve(name, admit, self.protocols, max_size=MAX_FRAME_BYTES)
|
|
236
|
+
|
|
218
237
|
def inprocess_dialer(self) -> Dialer:
|
|
219
238
|
"""A Dialer that connects an ExecutorClient in the same event loop to
|
|
220
239
|
this harness without a socket (use with static_token("inprocess://"))."""
|
|
@@ -246,16 +265,22 @@ class Harness:
|
|
|
246
265
|
|
|
247
266
|
async def _process_request(self, connection: Any, request: Any) -> Any:
|
|
248
267
|
offered = ",".join(request.headers.get_all("Sec-WebSocket-Protocol"))
|
|
249
|
-
|
|
250
|
-
return connection.respond(HTTPStatus.BAD_REQUEST, "unsupported executor protocol\n")
|
|
251
|
-
parts = urlsplit(request.path)
|
|
252
|
-
connect = ConnectRequest(path=parts.path, query=dict(parse_qsl(parts.query)), headers=dict(request.headers.raw_items()))
|
|
253
|
-
principal, refusal = await self._admit(connect)
|
|
268
|
+
connect, principal, refusal = await self._admit_upgrade(offered, request.path, dict(request.headers.raw_items()))
|
|
254
269
|
if refusal is not None:
|
|
255
270
|
return connection.respond(refusal[0], refusal[1] + "\n")
|
|
256
271
|
connection.bma_connect = (connect, principal)
|
|
257
272
|
return None
|
|
258
273
|
|
|
274
|
+
async def _admit_upgrade(self, offered: str, target: str, headers: Mapping[str, str]) -> tuple[ConnectRequest, Principal, tuple[HTTPStatus, str] | None]:
|
|
275
|
+
"""Admit a WebSocket upgrade (offered Sec-WebSocket-Protocol values,
|
|
276
|
+
request target with query, headers) on any listener."""
|
|
277
|
+
parts = urlsplit(target)
|
|
278
|
+
connect = ConnectRequest(path=parts.path, query=dict(parse_qsl(parts.query)), headers=headers)
|
|
279
|
+
if not any(value.strip() in self.protocols for value in offered.split(",")):
|
|
280
|
+
return connect, Principal(), (HTTPStatus.BAD_REQUEST, "unsupported executor protocol")
|
|
281
|
+
principal, refusal = await self._admit(connect)
|
|
282
|
+
return connect, principal, refusal
|
|
283
|
+
|
|
259
284
|
async def _ws_handler(self, ws: Any) -> None:
|
|
260
285
|
connect, principal = ws.bma_connect
|
|
261
286
|
await self._serve_channel(WebSocketConnection(ws), connect, principal)
|
|
@@ -2,13 +2,16 @@
|
|
|
2
2
|
|
|
3
3
|
Every transport carries the same thing: WebSocket-style text messages, one
|
|
4
4
|
JSON-RPC (control) or raw MCP (mcp) frame per message, with WebSocket close
|
|
5
|
-
codes.
|
|
5
|
+
codes. Four are provided:
|
|
6
6
|
|
|
7
7
|
- ``ws://`` / ``wss://``: an outbound WebSocket (the BMA service, or a harness
|
|
8
8
|
on a TCP listener).
|
|
9
9
|
- ``unix:///path/to.sock``: the same WebSocket protocol over a Unix domain
|
|
10
10
|
socket, for a harness on the same machine. The query string selects the
|
|
11
|
-
channel exactly as on ``ws://``.
|
|
11
|
+
channel exactly as on ``ws://``.
|
|
12
|
+
- ``npipe:////./pipe/<name>``: the same protocol over a Windows named pipe
|
|
13
|
+
(``\\\\.\\pipe\\<name>``), on the Windows ProactorEventLoop. Not available
|
|
14
|
+
elsewhere.
|
|
12
15
|
- in-process: :meth:`Harness.inprocess_dialer` connects an executor to a
|
|
13
16
|
harness in the same event loop without a socket.
|
|
14
17
|
"""
|
|
@@ -118,12 +121,17 @@ def _closed(error: Exception) -> ChannelClosed:
|
|
|
118
121
|
|
|
119
122
|
|
|
120
123
|
async def dial(url: str, token: str, subprotocols: Sequence[str], *, max_size: int = MAX_FRAME_BYTES) -> Connection:
|
|
121
|
-
"""Default dialer: ``ws://``, ``wss
|
|
124
|
+
"""Default dialer: ``ws://``, ``wss://``, ``unix:///path?query`` and
|
|
125
|
+
``npipe:////./pipe/name?query``."""
|
|
122
126
|
from websockets.asyncio.client import connect, unix_connect
|
|
123
127
|
|
|
124
128
|
headers = {"Authorization": f"Bearer {token}"} if token else None
|
|
125
129
|
parts = urlsplit(url)
|
|
126
130
|
offered = list(subprotocols)
|
|
131
|
+
if parts.scheme == "npipe":
|
|
132
|
+
from ._npipe import dial as dial_npipe
|
|
133
|
+
|
|
134
|
+
return await dial_npipe(url, token, offered, max_size=max_size)
|
|
127
135
|
if parts.scheme == "unix":
|
|
128
136
|
uri = "ws://localhost/v1/executors/channel" + (f"?{parts.query}" if parts.query else "")
|
|
129
137
|
ws = await unix_connect(parts.path, uri, additional_headers=headers, subprotocols=offered, max_size=max_size) # type: ignore[arg-type]
|
|
@@ -137,8 +145,8 @@ async def dial(url: str, token: str, subprotocols: Sequence[str], *, max_size: i
|
|
|
137
145
|
def channel_url(base: str, **query: str) -> str:
|
|
138
146
|
"""Return base with the given query members set (used for the MCP channel)."""
|
|
139
147
|
parts = urlsplit(base)
|
|
140
|
-
if parts.scheme not in ("ws", "wss", "unix", "inprocess"):
|
|
141
|
-
raise ValueError("bma_executor_sdk: channel URL must use ws, wss or
|
|
148
|
+
if parts.scheme not in ("ws", "wss", "unix", "npipe", "inprocess"):
|
|
149
|
+
raise ValueError("bma_executor_sdk: channel URL must use ws, wss, unix or npipe")
|
|
142
150
|
merged = dict(parse_qsl(parts.query))
|
|
143
151
|
merged.update(query)
|
|
144
152
|
return parts._replace(query=urlencode(merged)).geturl()
|
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
import tempfile
|
|
6
8
|
from typing import Any
|
|
7
9
|
|
|
8
10
|
from bma_executor_sdk import AgentEventRecord
|
|
@@ -55,3 +57,29 @@ class RecordingPlatform:
|
|
|
55
57
|
await self.changed.wait()
|
|
56
58
|
|
|
57
59
|
await asyncio.wait_for(loop(), timeout)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def fake_named_pipes(loop: asyncio.AbstractEventLoop) -> None:
|
|
63
|
+
"""Back create_pipe_connection and start_serving_pipe (Windows
|
|
64
|
+
ProactorEventLoop methods) with a Unix socket on other platforms, so the
|
|
65
|
+
named pipe transport is exercised everywhere. Windows uses the real pipe."""
|
|
66
|
+
directory = tempfile.mkdtemp(prefix="bmapipe")
|
|
67
|
+
|
|
68
|
+
def path(address: str) -> str:
|
|
69
|
+
return os.path.join(directory, address.rsplit("\\", 1)[-1])
|
|
70
|
+
|
|
71
|
+
class Listener:
|
|
72
|
+
def __init__(self, address: str, factory: Any) -> None:
|
|
73
|
+
self.task = asyncio.ensure_future(loop.create_unix_server(factory, path(address)))
|
|
74
|
+
|
|
75
|
+
def close(self) -> None:
|
|
76
|
+
if self.task.done():
|
|
77
|
+
self.task.result().close()
|
|
78
|
+
else:
|
|
79
|
+
self.task.add_done_callback(lambda task: task.result().close())
|
|
80
|
+
|
|
81
|
+
loop.create_pipe_connection = lambda factory, address: loop.create_unix_connection(factory, path(address)) # type: ignore[attr-defined]
|
|
82
|
+
async def start_serving_pipe(factory: Any, address: str) -> list[Listener]:
|
|
83
|
+
return [Listener(address, factory)]
|
|
84
|
+
|
|
85
|
+
loop.start_serving_pipe = start_serving_pipe # type: ignore[attr-defined]
|
|
@@ -7,6 +7,7 @@ import asyncio
|
|
|
7
7
|
import os
|
|
8
8
|
import shutil
|
|
9
9
|
import subprocess
|
|
10
|
+
import sys
|
|
10
11
|
import tempfile
|
|
11
12
|
from pathlib import Path
|
|
12
13
|
from typing import Any
|
|
@@ -28,6 +29,13 @@ def go_bin(tmp_path_factory: pytest.TempPathFactory) -> Path:
|
|
|
28
29
|
return out
|
|
29
30
|
|
|
30
31
|
|
|
32
|
+
def _exe(go_bin: Path, name: str) -> str:
|
|
33
|
+
return str(go_bin / (name + ".exe" if sys.platform == "win32" else name))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
needs_windows = pytest.mark.skipif(sys.platform != "win32", reason="Windows named pipe")
|
|
37
|
+
|
|
38
|
+
|
|
31
39
|
async def _read_line(stream: asyncio.StreamReader, prefix: str) -> str:
|
|
32
40
|
while True:
|
|
33
41
|
line = (await asyncio.wait_for(stream.readline(), 30)).decode().strip()
|
|
@@ -37,12 +45,14 @@ async def _read_line(stream: asyncio.StreamReader, prefix: str) -> str:
|
|
|
37
45
|
return line[len(prefix):].strip()
|
|
38
46
|
|
|
39
47
|
|
|
40
|
-
@pytest.mark.parametrize("transport", ["ws", "unix"])
|
|
48
|
+
@pytest.mark.parametrize("transport", ["ws", "unix", pytest.param("npipe", marks=needs_windows)])
|
|
41
49
|
async def test_python_executor_with_go_harness(go_bin: Path, transport: str) -> None:
|
|
42
|
-
args = [
|
|
50
|
+
args = [_exe(go_bin, "goharness")]
|
|
43
51
|
directory = tempfile.mkdtemp(prefix="bmaexec")
|
|
44
52
|
if transport == "unix":
|
|
45
53
|
args += ["-unix", os.path.join(directory, "h.sock")]
|
|
54
|
+
elif transport == "npipe":
|
|
55
|
+
args += ["-npipe", f"bma-py-go-{os.getpid()}"]
|
|
46
56
|
proc = await asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE)
|
|
47
57
|
assert proc.stdout is not None
|
|
48
58
|
try:
|
|
@@ -83,13 +93,19 @@ async def test_python_executor_with_go_harness(go_bin: Path, transport: str) ->
|
|
|
83
93
|
shutil.rmtree(directory, ignore_errors=True)
|
|
84
94
|
|
|
85
95
|
|
|
86
|
-
|
|
96
|
+
@pytest.mark.parametrize("transport", ["ws", pytest.param("npipe", marks=needs_windows)])
|
|
97
|
+
async def test_python_harness_with_go_executor(go_bin: Path, transport: str) -> None:
|
|
87
98
|
platform = RecordingPlatform()
|
|
88
99
|
harness = bx.Harness(agent=platform, request_timeout=5)
|
|
89
|
-
|
|
90
|
-
|
|
100
|
+
if transport == "npipe":
|
|
101
|
+
name = f"bma-go-py-{os.getpid()}"
|
|
102
|
+
server = await harness.serve_npipe(name)
|
|
103
|
+
url = f"npipe:////./pipe/{name}"
|
|
104
|
+
else:
|
|
105
|
+
server = await harness.serve("127.0.0.1", 0)
|
|
106
|
+
url = f"ws://127.0.0.1:{server.sockets[0].getsockname()[1]}/v1/executors/channel"
|
|
91
107
|
proc = await asyncio.create_subprocess_exec(
|
|
92
|
-
|
|
108
|
+
_exe(go_bin, "goexecutor"), "-url", url,
|
|
93
109
|
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
|
|
94
110
|
)
|
|
95
111
|
assert proc.stdout is not None and proc.stdin is not None
|
|
@@ -5,7 +5,9 @@ from __future__ import annotations
|
|
|
5
5
|
|
|
6
6
|
import asyncio
|
|
7
7
|
import contextlib
|
|
8
|
+
import itertools
|
|
8
9
|
import os
|
|
10
|
+
import sys
|
|
9
11
|
import tempfile
|
|
10
12
|
from collections.abc import AsyncIterator
|
|
11
13
|
from typing import Any
|
|
@@ -14,8 +16,9 @@ import pytest
|
|
|
14
16
|
|
|
15
17
|
import bma_executor_sdk as bx
|
|
16
18
|
from bma_executor_sdk.generated import JsonRpcErrorCode
|
|
17
|
-
from executor_helpers import RecordingPlatform
|
|
19
|
+
from executor_helpers import RecordingPlatform, fake_named_pipes
|
|
18
20
|
|
|
21
|
+
_PIPE_COUNTER = itertools.count()
|
|
19
22
|
EXECUTOR = {"name": "py-test", "os": "linux", "arch": "arm64", "version": "0.1.0"}
|
|
20
23
|
|
|
21
24
|
|
|
@@ -32,6 +35,18 @@ async def listen(harness: bx.Harness, transport: str) -> AsyncIterator[tuple[str
|
|
|
32
35
|
finally:
|
|
33
36
|
server.close()
|
|
34
37
|
await server.wait_closed()
|
|
38
|
+
elif transport == "npipe":
|
|
39
|
+
# The real named pipe on Windows; a Unix socket stands in elsewhere.
|
|
40
|
+
if sys.platform != "win32":
|
|
41
|
+
fake_named_pipes(asyncio.get_running_loop())
|
|
42
|
+
name = f"bma-py-test-{os.getpid()}-{next(_PIPE_COUNTER)}"
|
|
43
|
+
server = await harness.serve_npipe(name)
|
|
44
|
+
await asyncio.sleep(0.05)
|
|
45
|
+
try:
|
|
46
|
+
yield f"npipe:////./pipe/{name}", None
|
|
47
|
+
finally:
|
|
48
|
+
server.close()
|
|
49
|
+
await server.wait_closed()
|
|
35
50
|
else:
|
|
36
51
|
directory = tempfile.mkdtemp(prefix="bmaexec")
|
|
37
52
|
path = os.path.join(directory, "h.sock")
|
|
@@ -56,7 +71,7 @@ def text_result(call: dict[str, Any], text: str) -> dict[str, Any]:
|
|
|
56
71
|
return {"session_id": call["session_id"], "tool_call_id": call["tool_call_id"], "outcome": "succeeded", "is_error": False, "content": [{"type": "text", "text": text}]}
|
|
57
72
|
|
|
58
73
|
|
|
59
|
-
@pytest.mark.parametrize("transport", ["inprocess", "ws", "unix"])
|
|
74
|
+
@pytest.mark.parametrize("transport", ["inprocess", "ws", "unix", "npipe"])
|
|
60
75
|
async def test_harness_drives_executor_client(transport: str) -> None:
|
|
61
76
|
harness = bx.Harness(request_timeout=2.0)
|
|
62
77
|
runs: list[str] = []
|
|
@@ -101,14 +116,15 @@ async def test_harness_drives_executor_client(transport: str) -> None:
|
|
|
101
116
|
assert client.state == bx.generated.ConnectionState.Closed
|
|
102
117
|
|
|
103
118
|
|
|
104
|
-
|
|
119
|
+
@pytest.mark.parametrize("transport", ["ws", "npipe"])
|
|
120
|
+
async def test_harness_authenticate_rejects_and_pins_identity(transport: str) -> None:
|
|
105
121
|
def authenticate(request: bx.ConnectRequest) -> bx.Principal:
|
|
106
122
|
if request.bearer_token != "secret":
|
|
107
123
|
raise bx.Unauthorized()
|
|
108
124
|
return bx.Principal(executor_id="exe_pinned")
|
|
109
125
|
|
|
110
126
|
harness = bx.Harness(authenticate=authenticate)
|
|
111
|
-
async with listen(harness,
|
|
127
|
+
async with listen(harness, transport) as (url, _):
|
|
112
128
|
bad = make_client(url, None, token="wrong")
|
|
113
129
|
with pytest.raises(Exception, match="401"):
|
|
114
130
|
await bad.start()
|
|
@@ -223,9 +239,10 @@ async def test_newer_connection_replaces_older_with_4004() -> None:
|
|
|
223
239
|
await first.stop()
|
|
224
240
|
|
|
225
241
|
|
|
226
|
-
|
|
242
|
+
@pytest.mark.parametrize("transport", ["unix", "npipe"])
|
|
243
|
+
async def test_mcp_channel_is_isolated_by_session_and_server_key(transport: str) -> None:
|
|
227
244
|
harness = bx.Harness()
|
|
228
|
-
async with listen(harness,
|
|
245
|
+
async with listen(harness, transport) as (url, _):
|
|
229
246
|
client = make_client(url, None)
|
|
230
247
|
await client.start()
|
|
231
248
|
executor = await harness.wait_executor()
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Named pipe (npipe://) transport: addresses, a frame near the size limit and
|
|
2
|
+
the platform guard. The end-to-end scenarios run in test_executor_runtime.py
|
|
3
|
+
on a real pipe on Windows and on a Unix socket stand-in elsewhere."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
import pytest
|
|
12
|
+
|
|
13
|
+
import bma_executor_sdk as bx
|
|
14
|
+
from bma_executor_sdk import _npipe
|
|
15
|
+
from executor_helpers import fake_named_pipes
|
|
16
|
+
from test_executor_runtime import listen, make_client
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_pipe_addresses() -> None:
|
|
20
|
+
for address in ("bma-x", "\\\\.\\pipe\\bma-x", "npipe:////./pipe/bma-x", "npipe:////./pipe/bma-x?channel=mcp"):
|
|
21
|
+
assert _npipe.pipe_path(address) == "\\\\.\\pipe\\bma-x"
|
|
22
|
+
assert _npipe.pipe_url("\\\\.\\pipe\\bma-x") == "npipe:////./pipe/bma-x"
|
|
23
|
+
for bad in ("", "\\\\.\\pipe\\", "a\\b", "npipe:////./pipe/a/b", "npipe:///other"):
|
|
24
|
+
with pytest.raises(ValueError):
|
|
25
|
+
_npipe.pipe_path(bad)
|
|
26
|
+
mcp = bx.transport.channel_url("npipe:////./pipe/bma-x", channel="mcp")
|
|
27
|
+
assert mcp.endswith("?channel=mcp") and _npipe.pipe_path(mcp) == "\\\\.\\pipe\\bma-x"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@pytest.mark.skipif(sys.platform == "win32", reason="Windows has the pipe loop methods")
|
|
31
|
+
async def test_named_pipes_need_the_windows_event_loop() -> None:
|
|
32
|
+
with pytest.raises(NotImplementedError, match="ProactorEventLoop"):
|
|
33
|
+
await bx.transport.dial("npipe:////./pipe/bma-x", "", [bx.PROTOCOL_V11], max_size=bx.transport.MAX_FRAME_BYTES)
|
|
34
|
+
with pytest.raises(NotImplementedError, match="ProactorEventLoop"):
|
|
35
|
+
await bx.Harness().serve_npipe("bma-x")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
async def test_a_large_frame_and_a_closing_harness_over_a_named_pipe() -> None:
|
|
39
|
+
harness = bx.Harness(request_timeout=5.0)
|
|
40
|
+
async with listen(harness, "npipe") as (url, _):
|
|
41
|
+
client = make_client(url, None, request_timeout=5.0)
|
|
42
|
+
|
|
43
|
+
async def on_tool(call: dict[str, object]) -> dict[str, object]:
|
|
44
|
+
return {"session_id": call["session_id"], "tool_call_id": call["tool_call_id"], "outcome": "succeeded", "is_error": False, "content": [{"type": "text", "text": "x" * 700_000}]}
|
|
45
|
+
|
|
46
|
+
client.on_tool_call(on_tool) # type: ignore[arg-type]
|
|
47
|
+
await client.start()
|
|
48
|
+
executor = await harness.wait_executor()
|
|
49
|
+
session = await executor.assign_session({"session_id": "ses_big"}) # type: ignore[typeddict-item]
|
|
50
|
+
result = await session.call_tool({"tool_call_id": "call_big", "tool": "bash", "input": {"command": "big"}}) # type: ignore[typeddict-item]
|
|
51
|
+
assert len(result["content"][0]["text"]) == 700_000
|
|
52
|
+
await client.stop()
|
|
53
|
+
assert client.state == bx.generated.ConnectionState.Closed
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|