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.
@@ -0,0 +1,296 @@
1
+ Metadata-Version: 2.4
2
+ Name: node-mantis
3
+ Version: 0.1.0
4
+ Summary: NodeMantis Python SDK: browser-driving agent sessions plus setup and installation validation tools
5
+ Author: NodeMantis
6
+ License-Expression: LicenseRef-NodeMantis-Proprietary
7
+ Project-URL: Homepage, https://github.com/Node-Mantis/CleanSlate#readme
8
+ Project-URL: Repository, https://github.com/Node-Mantis/CleanSlate
9
+ Project-URL: Issues, https://github.com/Node-Mantis/CleanSlate/issues
10
+ Keywords: browser,automation,node-mantis,nodemantis
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Operating System :: MacOS
15
+ Classifier: Operating System :: Microsoft :: Windows
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE.txt
20
+ Dynamic: license-file
21
+
22
+ # NodeMantis Python
23
+
24
+ The NodeMantis Python SDK: browser-driving agent sessions at parity with the
25
+ npm `node-mantis` package, plus configuration and installation validation
26
+ tools.
27
+
28
+ Platform wheels bundle the same compiled native runtime the npm SDK uses; the
29
+ Python layer is a thin client that spawns it and forwards requests. The
30
+ runtime launches and drives your installed Google Chrome itself; the package
31
+ has no Playwright dependency.
32
+
33
+ Requirements: Google Chrome installed in its standard location, or `CHROME_PATH`
34
+ set to a Chrome executable. `python -m nodemantis doctor` reports whether
35
+ NodeMantis can launch it and, if not, how to install it.
36
+
37
+ Customer install:
38
+
39
+ ```bash
40
+ pip install node-mantis
41
+ python -m nodemantis configure --api-key "$NODEMANTIS_API_KEY"
42
+ python -m nodemantis doctor
43
+ python -m nodemantis smoke
44
+ ```
45
+
46
+ Run a browser goal:
47
+
48
+ ```python
49
+ import asyncio
50
+ from nodemantis import NodeMantis
51
+
52
+
53
+ async def main():
54
+ async with await NodeMantis.start(start_url="https://example.com", headless=True) as mantis:
55
+ result = await mantis.run("Open the More information link.", max_iterations=5)
56
+ print(result.ok, result.reason)
57
+
58
+ asyncio.run(main())
59
+ ```
60
+
61
+ Managed sessions share compatible browser processes by default, with a separate
62
+ browser context per session. Set `shared_browser=False` for a private browser.
63
+ Closing one session leaves other shared sessions running.
64
+
65
+ The session surface mirrors the TypeScript SDK: `NodeMantis.start()` /
66
+ `NodeMantis.preflight()`, and per-session `go`, `run`, `retrieve`,
67
+ `extract`, `check`, `close` (sessions are context managers). Options are
68
+ snake_case (`max_iterations`, `result_schema`,
69
+ …); `effort` selects a size tier (`"low"`, `"medium"`,
70
+ `"high"`). `run` accepts an `on_progress` callback for per-iteration
71
+ narration; callbacks arrive on a background thread and must not call session
72
+ methods. `retrieve` returns a discriminated result with `status` of `success`
73
+ or `unavailable`. Success carries non-null `data`; unavailable carries
74
+ `data=None`, a client-readable `message`, and a `retryable` boolean. Both
75
+ outcomes include token usage, metered cost, the final URL, and an optional
76
+ trace ID. Schemas are plain JSON Schema dicts (pydantic v2 effort classes are
77
+ also accepted).
78
+
79
+ `mantis.page` is a bounded asynchronous `ManagedPage`, not a Playwright page.
80
+ It supports navigation/history, URL and title reads, binary screenshots,
81
+ cookies, local/session storage state, viewport control, file choosers, and
82
+ downloads. It intentionally has no evaluation, selector/locator, event, or
83
+ arbitrary-CDP escape hatch.
84
+
85
+ ```python
86
+ import asyncio
87
+ from nodemantis import NodeMantis
88
+
89
+
90
+ async def main():
91
+ async with await NodeMantis.start(headless=True) as mantis:
92
+ await mantis.page.navigate("https://example.com", wait_until="load")
93
+ print(await mantis.page.title())
94
+ png = await mantis.page.screenshot(full_page=True)
95
+
96
+ asyncio.run(main())
97
+ ```
98
+
99
+ If NodeMantis cannot complete a retrieval request, it raises
100
+ `RetrievalRequestError` rather than returning `unavailable`. The exception
101
+ contains only customer-actionable fields: `code`, `retryable`, `trace_id`, and
102
+ `cost_usd`, along with its message. Codes are `INVALID_REQUEST`,
103
+ `AUTHENTICATION_FAILED`, `USAGE_LIMIT`, `REQUEST_BLOCKED`,
104
+ `SERVICE_UNAVAILABLE`, `CANCELLED`, or `OPERATION_FAILED`.
105
+
106
+ ```python
107
+ import asyncio
108
+ from nodemantis import NodeMantis, RetrievalRequestError
109
+
110
+
111
+ async def main():
112
+ async with await NodeMantis.start(start_url="https://sandbox.nodemantis.com") as mantis:
113
+ try:
114
+ result = await mantis.retrieve("Retrieve the featured books and their prices.")
115
+ if result.is_unavailable and result.retryable:
116
+ print("No result was available; trying again may help.")
117
+ except RetrievalRequestError as error:
118
+ print(error.code, error.retryable)
119
+ raise
120
+
121
+
122
+ asyncio.run(main())
123
+ ```
124
+
125
+ Managed sessions accept the raw-CDP launcher's serializable context settings
126
+ as a plain `context_options` dictionary, using the same camel-case option names
127
+ as TypeScript `contextOptions`. NodeMantis owns the user agent and
128
+ device-class identity, so
129
+ `userAgent`, `isMobile`, and `hasTouch` are reserved and must not be supplied
130
+ there.
131
+
132
+ ```python
133
+ import asyncio
134
+ from nodemantis import NodeMantis
135
+
136
+
137
+ async def main():
138
+ async with await NodeMantis.start(
139
+ headless=True,
140
+ viewport={"width": 1280, "height": 720},
141
+ context_options={
142
+ "locale": "en-CA",
143
+ "timezoneId": "America/Toronto",
144
+ "screen": {"width": 1440, "height": 900},
145
+ "deviceScaleFactor": 2,
146
+ },
147
+ ) as localized:
148
+ await localized.go("https://example.com")
149
+
150
+ asyncio.run(main())
151
+ ```
152
+
153
+ ### How Phase 1 chooses a browser identity
154
+
155
+ NodeMantis chooses one coherent identity when a managed session starts and
156
+ keeps it for the life of that session. Supported values supplied by the caller
157
+ come first, followed by facts read from the installed Chrome and the host. If
158
+ those facts cannot be read, NodeMantis uses a platform-specific fallback whose
159
+ screen, viewport, language, and device scale still agree. For any value Chrome
160
+ cannot represent honestly, NodeMantis keeps Chrome's native value instead of
161
+ inventing one or replacing a JavaScript getter.
162
+
163
+ If no viewport is supplied, the managed-session default remains 1280×720.
164
+ Screen size and DPR are detected separately or taken from the coherent
165
+ platform fallback; they are not inferred by pretending the viewport is the
166
+ whole display.
167
+
168
+ The resulting profile is applied through browser controls, without page-level
169
+ JavaScript identity wrappers. Managed sessions work in both headless and headed
170
+ mode, and each session keeps its chosen profile fixed across pages, frames,
171
+ popups, and dedicated, shared, and service workers. HTTP requests retain the
172
+ resolved full `Accept-Language` preference, while browser JavaScript
173
+ consistently sees the selected primary locale. If an unrecognized Chrome
174
+ version cannot provide a coherent live Client Hints fingerprint, NodeMantis
175
+ leaves those values native rather than fabricating a brand list.
176
+
177
+ Before a managed page or worker starts running site code, NodeMantis asks
178
+ Chrome to hold it briefly, applies the native parts of the session profile,
179
+ and then lets it continue. The hold applies only to the browser context owned
180
+ by that NodeMantis session, so unrelated Playwright browsers and contexts keep
181
+ working normally. Popups and workers created later go through the same check,
182
+ including workers created by another worker.
183
+
184
+ Cross-origin frames use a safe exception to that hold because pausing both the
185
+ frame and its parent can block Chrome from attaching either one. They receive
186
+ the same launch, context, network, and top-page settings before their first
187
+ instruction, then NodeMantis reinforces the values Chrome allows on the frame
188
+ itself. If Chrome cannot apply a value there, the frame keeps its honest native
189
+ value; NodeMantis never installs a JavaScript getter to disguise the mismatch.
190
+
191
+ Pages and workers can disappear while Chrome is still setting them up. When
192
+ that happens, NodeMantis asks Chrome whether the target really ended. If it did,
193
+ the rest of the session continues; if it is still alive with only part of the
194
+ profile applied, NodeMantis closes it. If Chrome cannot give a definite answer,
195
+ that browser instance is retired and a later session starts a fresh one. This
196
+ keeps headless startup from returning a half-configured page or reusing a
197
+ browser whose shutdown was uncertain.
198
+
199
+ Chrome version, User-Agent, and Client Hints must describe the browser that is
200
+ actually running. Consequently, `userAgent`, `isMobile`, and `hasTouch` remain
201
+ reserved context options. `User-Agent` and every `Sec-CH-UA*` name are also
202
+ reserved inside `context_options["extraHTTPHeaders"]`; attempts to override
203
+ them are rejected instead of creating a mismatch between JavaScript and
204
+ network requests.
205
+
206
+ Phase 1 makes Chrome's own identity internally consistent; it does not claim
207
+ that headless Chrome defeats every detector. Graphics, the observable effects
208
+ of automation and CDP, networking, and the agent's functional page scripts are
209
+ separate hardening areas.
210
+
211
+ API keys resolve from the `api_key` argument, then `NODEMANTIS_API_KEY`,
212
+ `NODEMANTIS_AUTH_TOKEN`, and finally the `nodemantis configure` config file.
213
+ The package always connects to the hosted Node Mantis API; the service
214
+ endpoint is not customer-configurable.
215
+
216
+ NodeMantis does not install a browser. It drives the Google Chrome already on
217
+ the machine (or the one `CHROME_PATH` names); `doctor` and `smoke` check it by
218
+ opening a real NodeMantis session and print per-platform install steps when
219
+ Chrome is missing.
220
+
221
+ Installing the wheel also puts a `nodemantis` command on `PATH` (equivalent to
222
+ `python -m nodemantis`); `pipx install node-mantis` gives the same command in
223
+ an isolated environment. This CLI covers setup verbs only — `configure`,
224
+ `doctor`, `smoke`. Command-line task execution
225
+ (`nodemantis run`, `nodemantis retrieve`) ships with the npm package:
226
+ `npm install -g node-mantis`. If both are installed, whichever is first on
227
+ `PATH` wins; the setup verbs behave identically.
228
+
229
+ Validate API access, credentials, and Google Chrome from Python:
230
+
231
+ ```python
232
+ import asyncio
233
+ from nodemantis import NodeMantis
234
+
235
+
236
+ async def main():
237
+ report = await NodeMantis.preflight(check_browser=True, timeout_ms=5000)
238
+ if not report.ok:
239
+ raise RuntimeError(report.checks)
240
+
241
+ asyncio.run(main())
242
+ ```
243
+
244
+ Supported platforms: Linux x64, Windows x64, macOS x64, and macOS arm64.
245
+ Wheels without a bundled runtime (source-free builds) raise
246
+ `RUNTIME_NOT_INSTALLED` when starting a session; advanced setups can point
247
+ `NODEMANTIS_RUNTIME_PATH` at a runtime executable.
248
+
249
+ This package is proprietary software. Use is governed by `LICENSE.txt`
250
+ and applicable NodeMantis terms.
251
+
252
+ ### Keep a session open between calls
253
+
254
+ Use `run()` for a complete goal or a smaller instruction. Each call returns
255
+ control to Python while the browser session stays open. Run your own processing,
256
+ query a database, or call another service before continuing. The browser session stays open until you close it or terminate the program.
257
+
258
+ ```python
259
+ import asyncio
260
+ from nodemantis import NodeMantis
261
+
262
+
263
+ async def main():
264
+ async with await NodeMantis.start(start_url="https://sandbox.nodemantis.com") as mantis:
265
+ await mantis.run("Open the Travel & Adventure category.")
266
+ order = {"title": "Journey to the Center of the Earth", "quantity": 1}
267
+ await mantis.run(f'Open "{order["title"]}" and add {order["quantity"]} copy to the cart.')
268
+
269
+ asyncio.run(main())
270
+ ```
271
+
272
+ ### Migrating from `step()`
273
+
274
+ `step()` is deprecated and emits `DeprecationWarning`. Existing calls retain
275
+ their bounded-step behavior for compatibility. Use `run()` for new code.
276
+ Replace `max_actions` with `max_iterations` when preserving a limit, and remove
277
+ `allow_navigation`: `run()` permits navigation. The default iteration limit
278
+ changes from 15 to 30, and the special bounded-step prompt no longer applies.
279
+ Session defaults using `max_actions` only affect legacy `step()` calls; use
280
+ `max_iterations` for `run()`.
281
+
282
+ ## Async migration
283
+
284
+ Session and page operations now require `await`, including `NodeMantis.start()`,
285
+ `NodeMantis.preflight()`, and `close()`. Use `async with await NodeMantis.start()`
286
+ for automatic cleanup, and `asyncio.run(main())` at your program entry point.
287
+ Inside an existing event loop, await your coroutine directly.
288
+
289
+ Cancel an operation with `asyncio.Task.cancel()` or bound it with
290
+ `asyncio.wait_for()`. Session mutations are serialized; download and file-chooser
291
+ waits can run concurrently with the action that triggers them.
292
+
293
+ Installation helpers are no longer package-root SDK exports. Use
294
+ `nodemantis configure`, `nodemantis doctor`, and `nodemantis smoke` for setup
295
+ and diagnostics. Use `await NodeMantis.preflight()` for application preflight.
296
+ Both package CLIs also support `nodemantis run` and `nodemantis retrieve`.
@@ -0,0 +1,31 @@
1
+ node_mantis-0.1.0.dist-info/licenses/LICENSE.txt,sha256=q2h1QZGrjtxwGgFFQPcC6gzl2L5rW7DZkBx3cXst7Vs,902
2
+ nodemantis/__init__.py,sha256=rH30vdNHwqpL7fzuHaBGManNZuE4-F4nNaYoPgxUUkM,3052
3
+ nodemantis/__main__.py,sha256=0iDYjdmiXNBinFF23WUyotsdpA6wFKjoB5aw3esTSRg,83
4
+ nodemantis/_async.py,sha256=CTutsDiCPbJr2LUQTKQGs4dMdeg1aCUbuXzvxSzoGt4,2303
5
+ nodemantis/_constants.py,sha256=__WWglAoFTZZlkrx8vilipvyz8KpMOk9lY7P5-eLkX4,51
6
+ nodemantis/_framing.py,sha256=KCJQFmB-hpbQE1MWCI9t8fw7CkD3KwgOfoz1oUbkewU,4663
7
+ nodemantis/_host.py,sha256=xw27nrFqE88TqZIL0wucneCka0n-VAuBbRENEVVBoi4,4959
8
+ nodemantis/_process.py,sha256=09Wh9RK5oADYUh4OzG-TulXl1Hglj-EoG7GWETF2G6M,18039
9
+ nodemantis/_protocol.py,sha256=Cq2uWhFz3clckOJf_2erzgkULE7ajeT28bCItM4syZE,3628
10
+ nodemantis/_rpc.py,sha256=Y5gP7uCJ7pu1hBvEgblaoXpiVzFhdCI85uJ8rGJZdHY,20720
11
+ nodemantis/browser.py,sha256=2L-9maMut04KXnF0gzKGPMXVr3mWc0vR6eiuXuSCBYo,1663
12
+ nodemantis/cli.py,sha256=QaYfaL6HnNOuL6QazQcx_H3M73_6awUikgUeY4XNwfs,9984
13
+ nodemantis/config.py,sha256=PQUwTH5WNV4oBVzKp_YBFdv38n4MdRxYgDJfj1IyZIA,3703
14
+ nodemantis/errors.py,sha256=F9it56vQDkNQqivKLIat7bUITOgrScbnDBcbFAvXhyg,7129
15
+ nodemantis/managed_page.py,sha256=Wfrt0ird_QzKCytn3B_1_1nohXa8xDyfPoNmWR-KQbA,25823
16
+ nodemantis/preflight.py,sha256=ydS96u-IIFoRRA32y4bV-ahnajK8ol0EWJV92fzXwoE,4560
17
+ nodemantis/py.typed,sha256=frcCV1k9oG9oKj3dpUqdJg1PxRT2RSN_XKdLCPjaYaY,2
18
+ nodemantis/runtime.py,sha256=PO5zz7hE8KOWJ4br7nW8sHq7UP5HQo6yuOepC5adq5Y,2206
19
+ nodemantis/runtime_broker.py,sha256=0S9NlGOjfUIN-239y3DP1XIkproTA9ZV678lVspVjko,586
20
+ nodemantis/session.py,sha256=GrWNZnf3SG0smt1fYBzXzH3HNKzQySqnDhWui3LrFW8,27281
21
+ nodemantis/smoke.py,sha256=Q9DpErtDlQx4_p64wyPQm9xVCbXNeQeiNh7vAoyT_nc,3420
22
+ nodemantis/types.py,sha256=-jwpK22shrjsv_2plQgn5QS4mLJFwMsK673BMPW3YgI,10782
23
+ nodemantis/_runtime_bin/README.md,sha256=dGofV2jQVgUL02xlV-KivjjfmH0NlDSqk2gMQw9vF64,432
24
+ nodemantis/_runtime_bin/nodemantis-runtime.exe,sha256=KNcNKiLMQzzF8UFEhiO3hKIl6UNWBmAMpYJYr7nGr34,23666976
25
+ nodemantis/_runtime_bin/runtime-manifest.json,sha256=D5zdR6vLYzqdgkn7FGrwiAzzayY5uteO_7Ci26hrLwg,270
26
+ nodemantis/fixtures/smoke.html,sha256=X5vAh6WPjx3Q7KvNQOKaRqwt9BF8cql2HSPQa_0W_NQ,686
27
+ node_mantis-0.1.0.dist-info/METADATA,sha256=p1SDpzoNzByifCLx_Dt447mCYiuocFM6UJR-D03uIEY,13166
28
+ node_mantis-0.1.0.dist-info/WHEEL,sha256=79BCzrXBJOa2YV6ugKrK59dqWifMGjAkgVd_6AQrqbU,98
29
+ node_mantis-0.1.0.dist-info/entry_points.txt,sha256=4UT7-D1an0HZP7WwEP7k4ODRzWmckE2CvuelPIp-EIg,85
30
+ node_mantis-0.1.0.dist-info/top_level.txt,sha256=9kaSA3eSBIApvJUTG4Ni6h42DcfJebMhccQj_tS9Bu4,11
31
+ node_mantis-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: false
4
+ Tag: py3-none-win_amd64
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ node-mantis = nodemantis.cli:main
3
+ nodemantis = nodemantis.cli:main
@@ -0,0 +1,18 @@
1
+ NodeMantis Proprietary License
2
+
3
+ Copyright (c) NodeMantis. All rights reserved.
4
+
5
+ This package is proprietary software. You may install and use it only to
6
+ evaluate or access NodeMantis services under an active NodeMantis account,
7
+ agreement, or written authorization from NodeMantis.
8
+
9
+ You may not copy, redistribute, sublicense, sell, rent, lease, host for third
10
+ parties, or provide this software as a managed service without prior written
11
+ permission from NodeMantis. You may not reverse engineer, decompile, disassemble,
12
+ or attempt to derive source code from this software except to the extent that
13
+ applicable law prohibits this restriction.
14
+
15
+ This software is provided "as is" without warranties of any kind. It may
16
+ change, break compatibility, or be withdrawn at any time. To the maximum extent
17
+ permitted by law, NodeMantis is not liable for damages arising from use of this
18
+ software.
@@ -0,0 +1 @@
1
+ nodemantis
nodemantis/__init__.py ADDED
@@ -0,0 +1,116 @@
1
+ """NodeMantis async Python SDK for managed browser sessions."""
2
+
3
+ from .errors import (
4
+ NativeRuntimeExitedError,
5
+ NativeRuntimeHandshakeError,
6
+ NativeRuntimeResolutionError,
7
+ NativeRuntimeTerminationError,
8
+ NavigationOnlyError,
9
+ NodeMantisError,
10
+ RetrievalRequestError,
11
+ RuntimeConnectionClosedError,
12
+ RuntimeRpcError,
13
+ SessionClosedError,
14
+ )
15
+ from .preflight import NodeMantisPreflightCheck, NodeMantisPreflightResult, PreflightCheck, PreflightResult
16
+ from .managed_page import (
17
+ ManagedCookie,
18
+ ManagedCookieInput,
19
+ ManagedCookieSameSite,
20
+ ManagedDownload,
21
+ ManagedDownloadProgress,
22
+ ManagedDownloadState,
23
+ ManagedFileChooser,
24
+ ManagedHistoryResult,
25
+ ManagedOriginStorage,
26
+ ManagedPage,
27
+ ManagedStorageEntry,
28
+ ManagedStorageState,
29
+ ManagedViewport,
30
+ )
31
+ from .runtime import UnsupportedPlatformError
32
+ from .session import NodeMantis
33
+ from .types import (
34
+ Effort,
35
+ NodeMantisOptions,
36
+ NodeMantisStartOptions,
37
+ NodeMantisRunOptions,
38
+ NodeMantisStepOptions,
39
+ NodeMantisRetrieveOptions,
40
+ NodeMantisExtractOptions,
41
+ NodeMantisCheckOptions,
42
+ NodeMantisPreflightOptions,
43
+
44
+ NodeMantisAgentOptions,
45
+ NodeMantisDefaultAgentOptions,
46
+ NodeMantisLoggingOptions,
47
+ NodeMantisManagedContextOptions,
48
+
49
+ AgentOperationResult,
50
+ AgentProgressEvent,
51
+ AgentRetrievalSummary,
52
+ AgentRetrieveResult,
53
+ BrowserGoResult,
54
+ MockLLMOptions,
55
+ MockLLMResponse,
56
+ MockLLMRule,
57
+ TokenUsage,
58
+ )
59
+
60
+ __all__ = [
61
+ "Effort",
62
+ "NodeMantisOptions",
63
+ "NodeMantisStartOptions",
64
+ "NodeMantisRunOptions",
65
+ "NodeMantisStepOptions",
66
+ "NodeMantisRetrieveOptions",
67
+ "NodeMantisExtractOptions",
68
+ "NodeMantisCheckOptions",
69
+ "NodeMantisPreflightOptions",
70
+
71
+ "NodeMantisAgentOptions",
72
+ "NodeMantisDefaultAgentOptions",
73
+ "NodeMantisLoggingOptions",
74
+ "NodeMantisManagedContextOptions",
75
+
76
+ "AgentOperationResult",
77
+ "AgentProgressEvent",
78
+ "AgentRetrievalSummary",
79
+ "AgentRetrieveResult",
80
+ "BrowserGoResult",
81
+ "MockLLMOptions",
82
+ "MockLLMResponse",
83
+ "MockLLMRule",
84
+ "ManagedCookie",
85
+ "ManagedCookieInput",
86
+ "ManagedCookieSameSite",
87
+ "ManagedDownload",
88
+ "ManagedDownloadProgress",
89
+ "ManagedDownloadState",
90
+ "ManagedFileChooser",
91
+ "ManagedHistoryResult",
92
+ "ManagedOriginStorage",
93
+ "ManagedPage",
94
+ "ManagedStorageEntry",
95
+ "ManagedStorageState",
96
+ "ManagedViewport",
97
+ "NativeRuntimeExitedError",
98
+ "NativeRuntimeHandshakeError",
99
+ "NativeRuntimeResolutionError",
100
+ "NativeRuntimeTerminationError",
101
+ "NavigationOnlyError",
102
+ "NodeMantis",
103
+ "NodeMantisError",
104
+ "RetrievalRequestError",
105
+ "PreflightCheck",
106
+ "PreflightResult",
107
+ "NodeMantisPreflightCheck",
108
+ "NodeMantisPreflightResult",
109
+ "RuntimeConnectionClosedError",
110
+ "RuntimeRpcError",
111
+ "SessionClosedError",
112
+ "TokenUsage",
113
+ "UnsupportedPlatformError",
114
+ ]
115
+
116
+ __version__ = "0.1.0"
nodemantis/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
nodemantis/_async.py ADDED
@@ -0,0 +1,65 @@
1
+ """Bridge the threaded stdio transport without blocking the caller's event loop."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextvars
7
+ import threading
8
+ from typing import Any, Callable, Optional, TypeVar
9
+
10
+ T = TypeVar("T")
11
+
12
+
13
+ async def blocking(
14
+ function: Callable[..., T],
15
+ *args: Any,
16
+ abort_event: Optional[threading.Event] = None,
17
+ on_cancel_result: Optional[Callable[[T], None]] = None,
18
+ **kwargs: Any,
19
+ ) -> T:
20
+ if abort_event is not None:
21
+ kwargs["abort_event"] = abort_event
22
+ # Lifecycle waits can remain pending while another RPC triggers them. Do
23
+ # not consume the application's bounded default executor: enough download
24
+ # waits could otherwise prevent the triggering action (or close) starting.
25
+ loop = asyncio.get_running_loop()
26
+ task = loop.create_future()
27
+ context = contextvars.copy_context()
28
+
29
+ def run() -> None:
30
+ try:
31
+ result = context.run(function, *args, **kwargs)
32
+ except BaseException as error:
33
+ loop.call_soon_threadsafe(task.set_exception, error)
34
+ else:
35
+ loop.call_soon_threadsafe(task.set_result, result)
36
+
37
+ threading.Thread(target=run, name="nodemantis-rpc", daemon=True).start()
38
+ try:
39
+ return await asyncio.shield(task)
40
+ except asyncio.CancelledError:
41
+ if abort_event is not None:
42
+ abort_event.set()
43
+ # Cancellation must settle the RPC or release a just-created resource
44
+ # before the queue/lease owner can leave its scope.
45
+ while not task.done():
46
+ try:
47
+ await asyncio.shield(task)
48
+ except asyncio.CancelledError:
49
+ continue
50
+ except Exception:
51
+ break
52
+ try:
53
+ result = task.result()
54
+ except Exception:
55
+ pass
56
+ else:
57
+ if on_cancel_result is not None:
58
+ try:
59
+ await blocking(on_cancel_result, result)
60
+ except Exception:
61
+ # Cleanup failure must not turn caller cancellation into
62
+ # an unrelated transport error. The lease owner still
63
+ # performs its own final cleanup.
64
+ pass
65
+ raise
@@ -0,0 +1 @@
1
+ NODEMANTIS_API_URL = "https://api.nodemantis.com"
nodemantis/_framing.py ADDED
@@ -0,0 +1,122 @@
1
+ """NMR1 length-framed transport codec.
2
+
3
+ One frame = a fixed 12-byte header (ASCII magic ``NMR1``, u32-BE JSON length,
4
+ u32-BE attachment length) followed by the JSON payload and the raw attachment
5
+ bytes. The attachment stays raw on the wire so screenshots and capture buffers
6
+ do not pay base64 overhead.
7
+
8
+ This module is a pure codec: encoding produces ``bytes`` and decoding is an
9
+ incremental state machine fed arbitrary chunks. Blocking I/O lives in
10
+ ``_rpc``, which keeps every byte-layout rule here independently testable.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import struct
16
+ from dataclasses import dataclass
17
+
18
+ FRAME_MAGIC = b"NMR1"
19
+ FIXED_HEADER_BYTES = 12
20
+ DEFAULT_MAX_JSON_BYTES = 128 * 1024 * 1024
21
+ DEFAULT_MAX_ATTACHMENT_BYTES = 128 * 1024 * 1024
22
+
23
+ _HEADER = struct.Struct(">4sII")
24
+
25
+
26
+ class FramingError(Exception):
27
+ """A violation of the NMR1 byte contract (fatal for the connection)."""
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Frame:
32
+ json: bytes
33
+ attachment: bytes
34
+
35
+
36
+ def _validate_limit(value: int, name: str) -> int:
37
+ if not isinstance(value, int) or value <= 0 or value > 0xFFFF_FFFF:
38
+ raise ValueError(f"{name} must be a positive u32-sized integer, got {value!r}")
39
+ return value
40
+
41
+
42
+ def encode_frame(
43
+ json_bytes: bytes,
44
+ attachment: bytes = b"",
45
+ *,
46
+ max_json_bytes: int = DEFAULT_MAX_JSON_BYTES,
47
+ max_attachment_bytes: int = DEFAULT_MAX_ATTACHMENT_BYTES,
48
+ ) -> bytes:
49
+ if len(json_bytes) == 0:
50
+ raise FramingError("NMR1 JSON header must not be empty")
51
+ if len(json_bytes) > max_json_bytes:
52
+ raise FramingError(
53
+ f"JSON header is {len(json_bytes)} bytes; maximum is {max_json_bytes}"
54
+ )
55
+ if len(attachment) > max_attachment_bytes:
56
+ raise FramingError(
57
+ f"Attachment is {len(attachment)} bytes; maximum is {max_attachment_bytes}"
58
+ )
59
+ header = _HEADER.pack(FRAME_MAGIC, len(json_bytes), len(attachment))
60
+ return header + json_bytes + attachment
61
+
62
+
63
+ class FrameDecoder:
64
+ """Incremental NMR1 decoder.
65
+
66
+ ``feed()`` accepts arbitrary chunk boundaries and returns every frame that
67
+ became complete. ``finish()`` is called at EOF and raises when the stream
68
+ ended in the middle of a frame.
69
+ """
70
+
71
+ def __init__(
72
+ self,
73
+ *,
74
+ max_json_bytes: int = DEFAULT_MAX_JSON_BYTES,
75
+ max_attachment_bytes: int = DEFAULT_MAX_ATTACHMENT_BYTES,
76
+ ) -> None:
77
+ self._max_json_bytes = _validate_limit(max_json_bytes, "max_json_bytes")
78
+ self._max_attachment_bytes = _validate_limit(
79
+ max_attachment_bytes, "max_attachment_bytes"
80
+ )
81
+ self._buffer = bytearray()
82
+ self._expected: tuple[int, int] | None = None
83
+
84
+ def feed(self, chunk: bytes) -> list[Frame]:
85
+ if chunk:
86
+ self._buffer.extend(chunk)
87
+ frames: list[Frame] = []
88
+ while True:
89
+ if self._expected is None:
90
+ if len(self._buffer) < FIXED_HEADER_BYTES:
91
+ return frames
92
+ magic, json_len, attachment_len = _HEADER.unpack_from(self._buffer, 0)
93
+ if magic != FRAME_MAGIC:
94
+ raise FramingError(f"Invalid NMR1 frame magic: {magic.hex()}")
95
+ if json_len == 0:
96
+ raise FramingError("NMR1 JSON header must not be empty")
97
+ if json_len > self._max_json_bytes:
98
+ raise FramingError(
99
+ f"Incoming JSON header is {json_len} bytes; "
100
+ f"maximum is {self._max_json_bytes}"
101
+ )
102
+ if attachment_len > self._max_attachment_bytes:
103
+ raise FramingError(
104
+ f"Incoming attachment is {attachment_len} bytes; "
105
+ f"maximum is {self._max_attachment_bytes}"
106
+ )
107
+ del self._buffer[:FIXED_HEADER_BYTES]
108
+ self._expected = (json_len, attachment_len)
109
+
110
+ json_len, attachment_len = self._expected
111
+ payload = json_len + attachment_len
112
+ if len(self._buffer) < payload:
113
+ return frames
114
+ json_bytes = bytes(self._buffer[:json_len])
115
+ attachment = bytes(self._buffer[json_len:payload])
116
+ del self._buffer[:payload]
117
+ self._expected = None
118
+ frames.append(Frame(json=json_bytes, attachment=attachment))
119
+
120
+ def finish(self) -> None:
121
+ if self._expected is not None or len(self._buffer) > 0:
122
+ raise FramingError("Framed stream ended in the middle of an NMR1 frame")