node-mantis 0.1.0__py3-none-win_amd64.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.
- node_mantis-0.1.0.dist-info/METADATA +296 -0
- node_mantis-0.1.0.dist-info/RECORD +31 -0
- node_mantis-0.1.0.dist-info/WHEEL +5 -0
- node_mantis-0.1.0.dist-info/entry_points.txt +3 -0
- node_mantis-0.1.0.dist-info/licenses/LICENSE.txt +18 -0
- node_mantis-0.1.0.dist-info/top_level.txt +1 -0
- nodemantis/__init__.py +116 -0
- nodemantis/__main__.py +4 -0
- nodemantis/_async.py +65 -0
- nodemantis/_constants.py +1 -0
- nodemantis/_framing.py +122 -0
- nodemantis/_host.py +152 -0
- nodemantis/_process.py +445 -0
- nodemantis/_protocol.py +126 -0
- nodemantis/_rpc.py +529 -0
- nodemantis/_runtime_bin/README.md +9 -0
- nodemantis/_runtime_bin/nodemantis-runtime.exe +0 -0
- nodemantis/_runtime_bin/runtime-manifest.json +8 -0
- nodemantis/browser.py +45 -0
- nodemantis/cli.py +236 -0
- nodemantis/config.py +116 -0
- nodemantis/errors.py +203 -0
- nodemantis/fixtures/smoke.html +22 -0
- nodemantis/managed_page.py +713 -0
- nodemantis/preflight.py +125 -0
- nodemantis/py.typed +1 -0
- nodemantis/runtime.py +74 -0
- nodemantis/runtime_broker.py +25 -0
- nodemantis/session.py +727 -0
- nodemantis/smoke.py +105 -0
- nodemantis/types.py +345 -0
nodemantis/_protocol.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Wire constants shared with the native runtime and the TS SDK.
|
|
2
|
+
|
|
3
|
+
Hand-mirrored from ``packages/protocol/src/index.ts`` (the canonical source);
|
|
4
|
+
a CI parity check asserts these stay equal to the TS values. Option-name
|
|
5
|
+
translation between the Python surface (snake_case) and the wire (camelCase)
|
|
6
|
+
uses ONLY the explicit maps below — never a generic case converter — so user
|
|
7
|
+
payloads (schemas, mock-LLM rules, result values) are preserved byte-for-byte.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
NODEMANTIS_PROTOCOL_VERSION = "0.2.0"
|
|
13
|
+
NODEMANTIS_RUNTIME_IDENTITY = "nodemantis-runtime-rust"
|
|
14
|
+
|
|
15
|
+
METHOD_RUNTIME_HELLO = "runtime/hello"
|
|
16
|
+
METHOD_RUNTIME_SHUTDOWN = "runtime/shutdown"
|
|
17
|
+
METHOD_RUNTIME_CANCEL = "runtime/cancel"
|
|
18
|
+
METHOD_MANAGED_SESSION_START = "managed/session/start"
|
|
19
|
+
METHOD_MANAGED_SESSION_PREFLIGHT = "managed/session/preflight"
|
|
20
|
+
METHOD_SESSION_CLOSE = "session/close"
|
|
21
|
+
METHOD_AGENT_RUN = "agent/run"
|
|
22
|
+
METHOD_AGENT_STEP = "agent/step"
|
|
23
|
+
METHOD_AGENT_EXTRACT = "agent/extract"
|
|
24
|
+
METHOD_AGENT_CHECK = "agent/check"
|
|
25
|
+
METHOD_AGENT_RETRIEVE = "agent/retrieve"
|
|
26
|
+
METHOD_AGENT_PROGRESS = "agent/progress"
|
|
27
|
+
|
|
28
|
+
RUNTIME_METHODS = (
|
|
29
|
+
METHOD_RUNTIME_HELLO,
|
|
30
|
+
METHOD_RUNTIME_SHUTDOWN,
|
|
31
|
+
METHOD_RUNTIME_CANCEL,
|
|
32
|
+
METHOD_MANAGED_SESSION_START,
|
|
33
|
+
METHOD_MANAGED_SESSION_PREFLIGHT,
|
|
34
|
+
METHOD_SESSION_CLOSE,
|
|
35
|
+
METHOD_AGENT_RUN,
|
|
36
|
+
METHOD_AGENT_STEP,
|
|
37
|
+
METHOD_AGENT_EXTRACT,
|
|
38
|
+
METHOD_AGENT_CHECK,
|
|
39
|
+
METHOD_AGENT_RETRIEVE,
|
|
40
|
+
METHOD_AGENT_PROGRESS,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
MAX_CANCELED_RESPONSE_TOMBSTONES = 1024
|
|
44
|
+
|
|
45
|
+
# Snake-case (Python surface) → camelCase (wire) per option family. Values that
|
|
46
|
+
# are user payloads (schema dicts, mock-LLM rule dicts, result values) are NOT
|
|
47
|
+
# translated anywhere.
|
|
48
|
+
AGENT_OPTION_KEYS = {
|
|
49
|
+
"effort": "effort",
|
|
50
|
+
"max_iterations": "maxIterations",
|
|
51
|
+
"timeout": "timeout",
|
|
52
|
+
"max_actions": "maxActions",
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
RUN_OPTION_KEYS = {
|
|
56
|
+
**AGENT_OPTION_KEYS,
|
|
57
|
+
"result_schema": "resultSchema",
|
|
58
|
+
"max_cost": "maxCost",
|
|
59
|
+
"mock_llm": "mockLLM",
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
STEP_OPTION_KEYS = {
|
|
63
|
+
**RUN_OPTION_KEYS,
|
|
64
|
+
"allow_navigation": "allowNavigation",
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
RETRIEVE_OPTION_KEYS = {
|
|
68
|
+
"schema": "schema",
|
|
69
|
+
"effort": "effort",
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
EXTRACT_OPTION_KEYS = {
|
|
73
|
+
"schema": "schema",
|
|
74
|
+
"effort": "effort",
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
CHECK_OPTION_KEYS = {
|
|
78
|
+
"effort": "effort",
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
GO_OPTION_KEYS = {
|
|
82
|
+
"wait_until": "waitUntil",
|
|
83
|
+
"timeout": "timeout",
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
LOGGING_OPTION_KEYS = {
|
|
87
|
+
"level": "level",
|
|
88
|
+
"dir": "dir",
|
|
89
|
+
"retention_days": "retentionDays",
|
|
90
|
+
"max_total_size_mb": "maxTotalSizeMb",
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
GEOMETRY_OPTION_KEYS = {
|
|
94
|
+
"profile_id": "profileId",
|
|
95
|
+
"state_directory": "stateDirectory",
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
BROWSER_OPTION_KEYS = {
|
|
99
|
+
"capability_mode": "capabilityMode",
|
|
100
|
+
"shared_browser": "sharedBrowser",
|
|
101
|
+
"horizontal_scroll": "horizontalScroll",
|
|
102
|
+
"start_url": "startUrl",
|
|
103
|
+
"headless": "headless",
|
|
104
|
+
"viewport": "viewport",
|
|
105
|
+
"use_proxy": "useProxy",
|
|
106
|
+
"default_timeout_ms": "defaultTimeoutMs",
|
|
107
|
+
"context_options": "contextOptions",
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def map_options(options: dict, key_map: "dict[str, str]", *, where: str) -> dict:
|
|
112
|
+
"""Translate a snake_case option dict to its wire shape.
|
|
113
|
+
|
|
114
|
+
Unknown keys raise instead of passing through silently — a misspelled
|
|
115
|
+
option must fail loudly, not be dropped by the runtime.
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
wire: dict = {}
|
|
119
|
+
for key, value in options.items():
|
|
120
|
+
if value is None:
|
|
121
|
+
continue
|
|
122
|
+
wire_key = key_map.get(key)
|
|
123
|
+
if wire_key is None:
|
|
124
|
+
raise TypeError(f"Unknown option {key!r} for {where}")
|
|
125
|
+
wire[wire_key] = value
|
|
126
|
+
return wire
|
nodemantis/_rpc.py
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
"""Concurrent, full-duplex JSON-RPC 2.0 over NMR1 length-framed stdio.
|
|
2
|
+
|
|
3
|
+
Port of the TS SDK's runtime client. The invariants that matter:
|
|
4
|
+
|
|
5
|
+
- The reader thread never runs user code: it decodes frames, settles pending
|
|
6
|
+
responses, and queues incoming requests/notifications for dispatch.
|
|
7
|
+
- Incoming requests are dispatched without blocking the reader, so a
|
|
8
|
+
runtime-originated request can be answered while the SDK is still awaiting
|
|
9
|
+
an outer ``agent/*`` response.
|
|
10
|
+
- A timed-out or aborted outer call sends a ``runtime/cancel`` notification and
|
|
11
|
+
leaves a tombstone so the late response is swallowed silently.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import queue
|
|
18
|
+
import threading
|
|
19
|
+
from collections import deque
|
|
20
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
from typing import Any, BinaryIO, Callable, Optional
|
|
23
|
+
|
|
24
|
+
from ._framing import (
|
|
25
|
+
DEFAULT_MAX_ATTACHMENT_BYTES,
|
|
26
|
+
DEFAULT_MAX_JSON_BYTES,
|
|
27
|
+
FrameDecoder,
|
|
28
|
+
FramingError,
|
|
29
|
+
encode_frame,
|
|
30
|
+
)
|
|
31
|
+
from ._protocol import MAX_CANCELED_RESPONSE_TOMBSTONES, METHOD_RUNTIME_CANCEL
|
|
32
|
+
from .errors import (
|
|
33
|
+
RpcAbortedError,
|
|
34
|
+
RuntimeConnectionClosedError,
|
|
35
|
+
RuntimeRpcError,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
_ABORT_POLL_SECONDS = 0.05
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class RuntimeResponseFrame:
|
|
43
|
+
result: Any
|
|
44
|
+
attachment: bytes
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class RpcContext:
|
|
49
|
+
method: str
|
|
50
|
+
id: "int | str | None"
|
|
51
|
+
notification: bool
|
|
52
|
+
client: "RuntimeClient"
|
|
53
|
+
attachment: bytes
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
RpcHandler = Callable[[Any, RpcContext], Any]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass
|
|
60
|
+
class _AttachedResult:
|
|
61
|
+
result: Any
|
|
62
|
+
attachment: bytes
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def with_attachment(result: Any, attachment: bytes) -> _AttachedResult:
|
|
66
|
+
"""Return a JSON-RPC result and one raw attachment in the same NMR1 frame."""
|
|
67
|
+
|
|
68
|
+
return _AttachedResult(result=result, attachment=bytes(attachment))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class _Pending:
|
|
73
|
+
event: threading.Event = field(default_factory=threading.Event)
|
|
74
|
+
frame: Optional[RuntimeResponseFrame] = None
|
|
75
|
+
error: Optional[Exception] = None
|
|
76
|
+
|
|
77
|
+
def settle(self, frame: Optional[RuntimeResponseFrame], error: Optional[Exception]) -> None:
|
|
78
|
+
self.frame = frame
|
|
79
|
+
self.error = error
|
|
80
|
+
self.event.set()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _is_rpc_id(value: Any) -> bool:
|
|
84
|
+
return isinstance(value, str) or (
|
|
85
|
+
isinstance(value, int) and not isinstance(value, bool)
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _is_rpc_message(value: Any) -> bool:
|
|
90
|
+
if not isinstance(value, dict) or value.get("jsonrpc") != "2.0":
|
|
91
|
+
return False
|
|
92
|
+
if "method" in value:
|
|
93
|
+
method = value["method"]
|
|
94
|
+
if not isinstance(method, str) or not method:
|
|
95
|
+
return False
|
|
96
|
+
return "id" not in value or _is_rpc_id(value["id"])
|
|
97
|
+
if "id" not in value or not _is_rpc_id(value["id"]):
|
|
98
|
+
return False
|
|
99
|
+
has_result = "result" in value
|
|
100
|
+
has_error = "error" in value
|
|
101
|
+
if has_result == has_error:
|
|
102
|
+
return False
|
|
103
|
+
if not has_error:
|
|
104
|
+
return True
|
|
105
|
+
error = value["error"]
|
|
106
|
+
return (
|
|
107
|
+
isinstance(error, dict)
|
|
108
|
+
and isinstance(error.get("code"), (str, int))
|
|
109
|
+
and isinstance(error.get("message"), str)
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class RuntimeClient:
|
|
114
|
+
"""Full-duplex RPC endpoint over a pair of binary streams.
|
|
115
|
+
|
|
116
|
+
``readable``/``writable`` are blocking binary file objects (a child
|
|
117
|
+
process's stdout/stdin, or pipe ends in tests). Call :meth:`start` after
|
|
118
|
+
construction; :meth:`dispose` is idempotent and rejects all pending calls.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
def __init__(
|
|
122
|
+
self,
|
|
123
|
+
readable: BinaryIO,
|
|
124
|
+
writable: BinaryIO,
|
|
125
|
+
*,
|
|
126
|
+
default_timeout_ms: Optional[float] = None,
|
|
127
|
+
max_json_bytes: int = DEFAULT_MAX_JSON_BYTES,
|
|
128
|
+
max_attachment_bytes: int = DEFAULT_MAX_ATTACHMENT_BYTES,
|
|
129
|
+
on_protocol_error: Optional[Callable[[Exception], None]] = None,
|
|
130
|
+
on_close: Optional[Callable[[Optional[Exception]], None]] = None,
|
|
131
|
+
) -> None:
|
|
132
|
+
self._readable = readable
|
|
133
|
+
self._writable = writable
|
|
134
|
+
self._default_timeout_ms = default_timeout_ms
|
|
135
|
+
self._max_json_bytes = max_json_bytes
|
|
136
|
+
self._max_attachment_bytes = max_attachment_bytes
|
|
137
|
+
self._on_protocol_error = on_protocol_error
|
|
138
|
+
self._on_close = on_close
|
|
139
|
+
|
|
140
|
+
self._lock = threading.Lock()
|
|
141
|
+
self._write_lock = threading.Lock()
|
|
142
|
+
self._pending: dict[Any, _Pending] = {}
|
|
143
|
+
self._handlers: dict[str, RpcHandler] = {}
|
|
144
|
+
self._tombstones: set[int] = set()
|
|
145
|
+
self._tombstone_order: deque[int] = deque()
|
|
146
|
+
self._next_request_id = 1
|
|
147
|
+
self._closed = False
|
|
148
|
+
self._close_error: Optional[Exception] = None
|
|
149
|
+
|
|
150
|
+
self._reader_thread: Optional[threading.Thread] = None
|
|
151
|
+
self._close_listeners: "list[Callable[[Optional[Exception]], None]]" = []
|
|
152
|
+
self._executor = ThreadPoolExecutor(
|
|
153
|
+
max_workers=8, thread_name_prefix="nodemantis-rpc"
|
|
154
|
+
)
|
|
155
|
+
# Notifications and responses are processed in strict arrival order on
|
|
156
|
+
# one dispatcher thread — a progress notification queued before its
|
|
157
|
+
# operation's response must reach the callback before the operation
|
|
158
|
+
# returns (the TS SDK gets this from its single-threaded event loop).
|
|
159
|
+
# Incoming REQUESTS go to the pool instead: a runtime-originated request
|
|
160
|
+
# must be able to run while an outer operation's response is pending.
|
|
161
|
+
self._ordered_queue: "queue.Queue[Optional[tuple[dict, bytes]]]" = (
|
|
162
|
+
queue.Queue()
|
|
163
|
+
)
|
|
164
|
+
self._ordered_thread = threading.Thread(
|
|
165
|
+
target=self._ordered_loop,
|
|
166
|
+
name="nodemantis-rpc-dispatch",
|
|
167
|
+
daemon=True,
|
|
168
|
+
)
|
|
169
|
+
self._ordered_thread.start()
|
|
170
|
+
|
|
171
|
+
# ── lifecycle ────────────────────────────────────────────────────────────
|
|
172
|
+
|
|
173
|
+
def start(self) -> None:
|
|
174
|
+
if self._reader_thread is not None:
|
|
175
|
+
raise RuntimeError("RuntimeClient already started")
|
|
176
|
+
self._reader_thread = threading.Thread(
|
|
177
|
+
target=self._read_loop, name="nodemantis-rpc-reader", daemon=True
|
|
178
|
+
)
|
|
179
|
+
self._reader_thread.start()
|
|
180
|
+
|
|
181
|
+
@property
|
|
182
|
+
def is_closed(self) -> bool:
|
|
183
|
+
return self._closed
|
|
184
|
+
|
|
185
|
+
def add_close_listener(
|
|
186
|
+
self, listener: Callable[[Optional[Exception]], None]
|
|
187
|
+
) -> None:
|
|
188
|
+
with self._lock:
|
|
189
|
+
if not self._closed:
|
|
190
|
+
self._close_listeners.append(listener)
|
|
191
|
+
return
|
|
192
|
+
listener(self._close_error)
|
|
193
|
+
|
|
194
|
+
def dispose(self, error: Optional[Exception] = None) -> None:
|
|
195
|
+
with self._lock:
|
|
196
|
+
if self._closed:
|
|
197
|
+
return
|
|
198
|
+
self._closed = True
|
|
199
|
+
self._close_error = error
|
|
200
|
+
pending = list(self._pending.items())
|
|
201
|
+
self._pending.clear()
|
|
202
|
+
self._tombstones.clear()
|
|
203
|
+
self._tombstone_order.clear()
|
|
204
|
+
self._handlers.clear()
|
|
205
|
+
listeners = self._close_listeners[:]
|
|
206
|
+
self._close_listeners.clear()
|
|
207
|
+
failure = error if error is not None else RuntimeConnectionClosedError()
|
|
208
|
+
for _, entry in pending:
|
|
209
|
+
entry.settle(None, failure)
|
|
210
|
+
self._ordered_queue.put(None)
|
|
211
|
+
self._executor.shutdown(wait=False)
|
|
212
|
+
for listener in [*listeners, *([self._on_close] if self._on_close else [])]:
|
|
213
|
+
try:
|
|
214
|
+
listener(error)
|
|
215
|
+
except Exception: # noqa: BLE001 - close callbacks must not raise
|
|
216
|
+
pass
|
|
217
|
+
|
|
218
|
+
# ── outgoing ─────────────────────────────────────────────────────────────
|
|
219
|
+
|
|
220
|
+
def register_handler(self, method: str, handler: RpcHandler) -> Callable[[], None]:
|
|
221
|
+
if not method or not method.strip():
|
|
222
|
+
raise ValueError("RPC method must be a non-empty string")
|
|
223
|
+
with self._lock:
|
|
224
|
+
if method in self._handlers:
|
|
225
|
+
raise ValueError(f"RPC handler already registered for {method}")
|
|
226
|
+
self._handlers[method] = handler
|
|
227
|
+
|
|
228
|
+
def unregister() -> None:
|
|
229
|
+
with self._lock:
|
|
230
|
+
if self._handlers.get(method) is handler:
|
|
231
|
+
del self._handlers[method]
|
|
232
|
+
|
|
233
|
+
return unregister
|
|
234
|
+
|
|
235
|
+
def request(
|
|
236
|
+
self,
|
|
237
|
+
method: str,
|
|
238
|
+
params: Any = None,
|
|
239
|
+
*,
|
|
240
|
+
timeout_ms: Optional[float] = None,
|
|
241
|
+
abort_event: Optional[threading.Event] = None,
|
|
242
|
+
attachment: bytes = b"",
|
|
243
|
+
) -> Any:
|
|
244
|
+
return self.request_frame(
|
|
245
|
+
method,
|
|
246
|
+
params,
|
|
247
|
+
timeout_ms=timeout_ms,
|
|
248
|
+
abort_event=abort_event,
|
|
249
|
+
attachment=attachment,
|
|
250
|
+
).result
|
|
251
|
+
|
|
252
|
+
def request_frame(
|
|
253
|
+
self,
|
|
254
|
+
method: str,
|
|
255
|
+
params: Any = None,
|
|
256
|
+
*,
|
|
257
|
+
timeout_ms: Optional[float] = None,
|
|
258
|
+
abort_event: Optional[threading.Event] = None,
|
|
259
|
+
attachment: bytes = b"",
|
|
260
|
+
) -> RuntimeResponseFrame:
|
|
261
|
+
self._assert_open()
|
|
262
|
+
if not method or not method.strip():
|
|
263
|
+
raise ValueError("RPC method must be a non-empty string")
|
|
264
|
+
effective_timeout = timeout_ms if timeout_ms not in (None, 0) else self._default_timeout_ms
|
|
265
|
+
if effective_timeout is not None and (
|
|
266
|
+
effective_timeout < 0 or effective_timeout != effective_timeout
|
|
267
|
+
):
|
|
268
|
+
raise ValueError("timeout_ms must be a non-negative finite number")
|
|
269
|
+
if abort_event is not None and abort_event.is_set():
|
|
270
|
+
raise RpcAbortedError()
|
|
271
|
+
|
|
272
|
+
entry = _Pending()
|
|
273
|
+
with self._lock:
|
|
274
|
+
if self._closed:
|
|
275
|
+
raise RuntimeConnectionClosedError()
|
|
276
|
+
request_id = self._next_request_id
|
|
277
|
+
self._next_request_id += 1
|
|
278
|
+
self._pending[request_id] = entry
|
|
279
|
+
|
|
280
|
+
message: dict[str, Any] = {"jsonrpc": "2.0", "id": request_id, "method": method}
|
|
281
|
+
if params is not None:
|
|
282
|
+
message["params"] = params
|
|
283
|
+
try:
|
|
284
|
+
self._send_message(message, attachment)
|
|
285
|
+
except Exception as error: # noqa: BLE001 - reject this call, not the client
|
|
286
|
+
self._reject_pending(request_id, error)
|
|
287
|
+
|
|
288
|
+
deadline = (
|
|
289
|
+
None
|
|
290
|
+
if effective_timeout is None
|
|
291
|
+
else _monotonic() + effective_timeout / 1000.0
|
|
292
|
+
)
|
|
293
|
+
while True:
|
|
294
|
+
wait_for = _ABORT_POLL_SECONDS
|
|
295
|
+
if deadline is not None:
|
|
296
|
+
remaining = deadline - _monotonic()
|
|
297
|
+
if remaining <= 0:
|
|
298
|
+
self._cancel_pending(
|
|
299
|
+
request_id,
|
|
300
|
+
entry,
|
|
301
|
+
RuntimeRpcError(
|
|
302
|
+
"RPC_TIMEOUT",
|
|
303
|
+
f"{method} timed out after {int(effective_timeout)}ms",
|
|
304
|
+
),
|
|
305
|
+
)
|
|
306
|
+
wait_for = min(wait_for, max(remaining, 0.0) or _ABORT_POLL_SECONDS)
|
|
307
|
+
if entry.event.wait(wait_for):
|
|
308
|
+
break
|
|
309
|
+
if abort_event is not None and abort_event.is_set():
|
|
310
|
+
self._cancel_pending(request_id, entry, RpcAbortedError())
|
|
311
|
+
|
|
312
|
+
if entry.error is not None:
|
|
313
|
+
raise entry.error
|
|
314
|
+
assert entry.frame is not None
|
|
315
|
+
return entry.frame
|
|
316
|
+
|
|
317
|
+
def notify(self, method: str, params: Any = None, *, attachment: bytes = b"") -> None:
|
|
318
|
+
self._assert_open()
|
|
319
|
+
if not method or not method.strip():
|
|
320
|
+
raise ValueError("RPC method must be a non-empty string")
|
|
321
|
+
message: dict[str, Any] = {"jsonrpc": "2.0", "method": method}
|
|
322
|
+
if params is not None:
|
|
323
|
+
message["params"] = params
|
|
324
|
+
self._send_message(message, attachment)
|
|
325
|
+
|
|
326
|
+
# ── incoming ─────────────────────────────────────────────────────────────
|
|
327
|
+
|
|
328
|
+
def _read_loop(self) -> None:
|
|
329
|
+
decoder = FrameDecoder(
|
|
330
|
+
max_json_bytes=self._max_json_bytes,
|
|
331
|
+
max_attachment_bytes=self._max_attachment_bytes,
|
|
332
|
+
)
|
|
333
|
+
# Prefer read1 (returns as soon as any bytes are available) so a
|
|
334
|
+
# buffered stream can never stall a frame waiting to fill read(n).
|
|
335
|
+
read_some = getattr(self._readable, "read1", None) or self._readable.read
|
|
336
|
+
try:
|
|
337
|
+
while not self._closed:
|
|
338
|
+
chunk = read_some(65536)
|
|
339
|
+
if not chunk:
|
|
340
|
+
decoder.finish()
|
|
341
|
+
self.dispose()
|
|
342
|
+
return
|
|
343
|
+
for frame in decoder.feed(chunk):
|
|
344
|
+
self._on_frame(frame.json, frame.attachment)
|
|
345
|
+
except FramingError as error:
|
|
346
|
+
self._emit_protocol_error(error)
|
|
347
|
+
self.dispose(error)
|
|
348
|
+
except (OSError, ValueError) as error:
|
|
349
|
+
# Stream torn down under us (child died, pipe closed).
|
|
350
|
+
if not self._closed:
|
|
351
|
+
self._emit_protocol_error(error)
|
|
352
|
+
self.dispose(RuntimeConnectionClosedError(str(error)))
|
|
353
|
+
|
|
354
|
+
def _on_frame(self, json_bytes: bytes, attachment: bytes) -> None:
|
|
355
|
+
if self._closed:
|
|
356
|
+
return
|
|
357
|
+
try:
|
|
358
|
+
parsed = json.loads(json_bytes.decode("utf-8"))
|
|
359
|
+
if not _is_rpc_message(parsed):
|
|
360
|
+
raise ValueError("Frame is not a valid JSON-RPC 2.0 message")
|
|
361
|
+
except (ValueError, UnicodeDecodeError) as error:
|
|
362
|
+
protocol_error = RuntimeRpcError("BAD_FRAME", str(error))
|
|
363
|
+
self._emit_protocol_error(protocol_error)
|
|
364
|
+
self.dispose(protocol_error)
|
|
365
|
+
return
|
|
366
|
+
|
|
367
|
+
if "method" in parsed and "id" in parsed:
|
|
368
|
+
# Deliberately concurrent: runtime-originated requests must run
|
|
369
|
+
# while an outer SDK→runtime request remains pending.
|
|
370
|
+
try:
|
|
371
|
+
self._executor.submit(self._dispatch_incoming, parsed, attachment)
|
|
372
|
+
except RuntimeError:
|
|
373
|
+
pass # executor shut down during dispose
|
|
374
|
+
else:
|
|
375
|
+
self._ordered_queue.put((parsed, attachment))
|
|
376
|
+
|
|
377
|
+
def _ordered_loop(self) -> None:
|
|
378
|
+
while True:
|
|
379
|
+
item = self._ordered_queue.get()
|
|
380
|
+
if item is None:
|
|
381
|
+
return
|
|
382
|
+
message, attachment = item
|
|
383
|
+
try:
|
|
384
|
+
if "method" in message:
|
|
385
|
+
self._dispatch_incoming(message, attachment)
|
|
386
|
+
else:
|
|
387
|
+
self._handle_response(message, attachment)
|
|
388
|
+
except Exception as error: # noqa: BLE001 - keep the loop alive
|
|
389
|
+
self._emit_protocol_error(error)
|
|
390
|
+
|
|
391
|
+
def _dispatch_incoming(self, message: dict, attachment: bytes) -> None:
|
|
392
|
+
notification = "id" not in message
|
|
393
|
+
method = message["method"]
|
|
394
|
+
with self._lock:
|
|
395
|
+
handler = self._handlers.get(method)
|
|
396
|
+
if handler is None:
|
|
397
|
+
if not notification:
|
|
398
|
+
self._try_send_failure(
|
|
399
|
+
message["id"],
|
|
400
|
+
{
|
|
401
|
+
"code": "METHOD_NOT_FOUND",
|
|
402
|
+
"message": f"No RPC handler registered for {method}",
|
|
403
|
+
},
|
|
404
|
+
)
|
|
405
|
+
return
|
|
406
|
+
|
|
407
|
+
context = RpcContext(
|
|
408
|
+
method=method,
|
|
409
|
+
id=None if notification else message["id"],
|
|
410
|
+
notification=notification,
|
|
411
|
+
client=self,
|
|
412
|
+
attachment=attachment,
|
|
413
|
+
)
|
|
414
|
+
try:
|
|
415
|
+
result = handler(message.get("params"), context)
|
|
416
|
+
if not notification:
|
|
417
|
+
attached = result if isinstance(result, _AttachedResult) else None
|
|
418
|
+
payload = attached.result if attached else result
|
|
419
|
+
reply: dict[str, Any] = {
|
|
420
|
+
"jsonrpc": "2.0",
|
|
421
|
+
"id": message["id"],
|
|
422
|
+
"result": payload if payload is not None else None,
|
|
423
|
+
}
|
|
424
|
+
self._send_message(reply, attached.attachment if attached else b"")
|
|
425
|
+
except Exception as error: # noqa: BLE001 - handler boundary
|
|
426
|
+
if notification:
|
|
427
|
+
self._emit_protocol_error(error)
|
|
428
|
+
return
|
|
429
|
+
if isinstance(error, RuntimeRpcError):
|
|
430
|
+
payload = {"code": error.code, "message": str(error)}
|
|
431
|
+
if error.data is not None:
|
|
432
|
+
payload["data"] = error.data
|
|
433
|
+
else:
|
|
434
|
+
payload = {"code": "HANDLER_ERROR", "message": str(error)}
|
|
435
|
+
self._try_send_failure(message["id"], payload)
|
|
436
|
+
|
|
437
|
+
def _handle_response(self, message: dict, attachment: bytes) -> None:
|
|
438
|
+
message_id = message["id"]
|
|
439
|
+
with self._lock:
|
|
440
|
+
entry = self._pending.pop(message_id, None)
|
|
441
|
+
if entry is None:
|
|
442
|
+
swallowed = isinstance(message_id, int) and message_id in self._tombstones
|
|
443
|
+
if swallowed:
|
|
444
|
+
self._tombstones.discard(message_id)
|
|
445
|
+
if entry is None:
|
|
446
|
+
if not swallowed:
|
|
447
|
+
self._emit_protocol_error(
|
|
448
|
+
RuntimeRpcError(
|
|
449
|
+
"UNKNOWN_RESPONSE",
|
|
450
|
+
f"Received a response for unknown request {message_id}",
|
|
451
|
+
)
|
|
452
|
+
)
|
|
453
|
+
return
|
|
454
|
+
if "error" in message:
|
|
455
|
+
error = message["error"]
|
|
456
|
+
entry.settle(
|
|
457
|
+
None,
|
|
458
|
+
RuntimeRpcError(error["code"], error["message"], error.get("data")),
|
|
459
|
+
)
|
|
460
|
+
else:
|
|
461
|
+
entry.settle(
|
|
462
|
+
RuntimeResponseFrame(result=message.get("result"), attachment=attachment),
|
|
463
|
+
None,
|
|
464
|
+
)
|
|
465
|
+
|
|
466
|
+
# ── internals ────────────────────────────────────────────────────────────
|
|
467
|
+
|
|
468
|
+
def _cancel_pending(self, request_id: int, entry: _Pending, error: Exception) -> None:
|
|
469
|
+
with self._lock:
|
|
470
|
+
if self._pending.get(request_id) is not entry:
|
|
471
|
+
return # a response raced the cancel; the wait loop will see it
|
|
472
|
+
del self._pending[request_id]
|
|
473
|
+
self._tombstones.add(request_id)
|
|
474
|
+
self._tombstone_order.append(request_id)
|
|
475
|
+
while len(self._tombstone_order) > MAX_CANCELED_RESPONSE_TOMBSTONES:
|
|
476
|
+
expired = self._tombstone_order.popleft()
|
|
477
|
+
self._tombstones.discard(expired)
|
|
478
|
+
try:
|
|
479
|
+
self.notify(METHOD_RUNTIME_CANCEL, {"id": request_id})
|
|
480
|
+
except Exception as send_error: # noqa: BLE001
|
|
481
|
+
if not self._closed:
|
|
482
|
+
self._emit_protocol_error(send_error)
|
|
483
|
+
entry.settle(None, error)
|
|
484
|
+
|
|
485
|
+
def _reject_pending(self, request_id: Any, error: Exception) -> None:
|
|
486
|
+
with self._lock:
|
|
487
|
+
entry = self._pending.pop(request_id, None)
|
|
488
|
+
if entry is not None:
|
|
489
|
+
entry.settle(None, error)
|
|
490
|
+
|
|
491
|
+
def _send_message(self, message: dict, attachment: bytes = b"") -> None:
|
|
492
|
+
try:
|
|
493
|
+
encoded = json.dumps(message, separators=(",", ":")).encode("utf-8")
|
|
494
|
+
except (TypeError, ValueError) as error:
|
|
495
|
+
raise RuntimeRpcError("SERIALIZE_ERROR", str(error)) from error
|
|
496
|
+
frame = encode_frame(
|
|
497
|
+
encoded,
|
|
498
|
+
attachment,
|
|
499
|
+
max_json_bytes=self._max_json_bytes,
|
|
500
|
+
max_attachment_bytes=self._max_attachment_bytes,
|
|
501
|
+
)
|
|
502
|
+
with self._write_lock:
|
|
503
|
+
if self._closed:
|
|
504
|
+
raise RuntimeConnectionClosedError()
|
|
505
|
+
self._writable.write(frame)
|
|
506
|
+
self._writable.flush()
|
|
507
|
+
|
|
508
|
+
def _try_send_failure(self, message_id: Any, error_payload: dict) -> None:
|
|
509
|
+
try:
|
|
510
|
+
self._send_message({"jsonrpc": "2.0", "id": message_id, "error": error_payload})
|
|
511
|
+
except Exception as error: # noqa: BLE001
|
|
512
|
+
self._emit_protocol_error(error)
|
|
513
|
+
|
|
514
|
+
def _emit_protocol_error(self, error: Exception) -> None:
|
|
515
|
+
if self._on_protocol_error is not None:
|
|
516
|
+
try:
|
|
517
|
+
self._on_protocol_error(error)
|
|
518
|
+
except Exception: # noqa: BLE001 - diagnostics must not crash the host
|
|
519
|
+
pass
|
|
520
|
+
|
|
521
|
+
def _assert_open(self) -> None:
|
|
522
|
+
if self._closed:
|
|
523
|
+
raise RuntimeConnectionClosedError()
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def _monotonic() -> float:
|
|
527
|
+
import time
|
|
528
|
+
|
|
529
|
+
return time.monotonic()
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Bundled native runtime
|
|
2
|
+
|
|
3
|
+
Empty in source control. Release builds stage `nodemantis-runtime[.exe]` and
|
|
4
|
+
its `runtime-manifest.json` here via `python/tools/stage_runtime.py`, and the
|
|
5
|
+
wheel then carries the platform tag of the staged binary
|
|
6
|
+
(`NODEMANTIS_WHEEL_PLATFORM`, enforced by setup.py).
|
|
7
|
+
|
|
8
|
+
Source-free builds ship without a binary; sessions then raise
|
|
9
|
+
`RUNTIME_NOT_INSTALLED` with a pointer at `NODEMANTIS_RUNTIME_PATH`.
|
|
Binary file
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
{
|
|
2
|
+
"packageName": "node-mantis-runtime-win32-x64",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"platform": "win32-x64",
|
|
5
|
+
"rustTarget": "x86_64-pc-windows-msvc",
|
|
6
|
+
"executable": "bin/nodemantis-runtime.exe",
|
|
7
|
+
"sha256": "28d70d2a22cc433cc5f141448623b784a225e9435606600ca58258afb9c6af7e"
|
|
8
|
+
}
|