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.
nodemantis/smoke.py ADDED
@@ -0,0 +1,105 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ from dataclasses import dataclass
5
+ from importlib import resources
6
+ from typing import Optional
7
+ from urllib.error import HTTPError
8
+ from urllib.request import Request, urlopen
9
+
10
+ from ._async import blocking
11
+ from ._constants import NODEMANTIS_API_URL
12
+ from .browser import check_chrome, missing_chrome_message
13
+ from .config import resolve_config
14
+ from .runtime import broker_hello, runtime_platform_info
15
+
16
+ SMOKE_FIXTURE_TITLE = "NodeMantis CLI smoke"
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class SmokeResult:
21
+ ok: bool
22
+ backend_checked: bool
23
+ runtime_platform: str
24
+ assertion: str
25
+
26
+
27
+ async def run_smoke(
28
+ *,
29
+ api_key: str | None = None,
30
+ headless: bool = True,
31
+ skip_backend: bool = False,
32
+ timeout_seconds: int = 15,
33
+ ) -> SmokeResult:
34
+ config = resolve_config(api_key=api_key)
35
+ platform_info = runtime_platform_info()
36
+
37
+ if not config.api_key and not skip_backend:
38
+ raise RuntimeError(
39
+ "NodeMantis API key is not configured.\n"
40
+ "Set NODEMANTIS_API_KEY, NODEMANTIS_AUTH_TOKEN, or run: "
41
+ "python -m nodemantis configure --api-key <key>"
42
+ )
43
+
44
+ await blocking(broker_hello)
45
+
46
+ browser_check = await check_chrome()
47
+ if not browser_check.available:
48
+ raise RuntimeError(missing_chrome_message(browser_check.error))
49
+
50
+ if not skip_backend:
51
+ await blocking(_verify_backend_usage,
52
+ api_key=config.api_key or "",
53
+ timeout_seconds=timeout_seconds,
54
+ )
55
+
56
+ await _verify_fixture(api_key=config.api_key, headless=headless)
57
+
58
+ return SmokeResult(
59
+ ok=True,
60
+ backend_checked=not skip_backend,
61
+ runtime_platform=platform_info.tag,
62
+ assertion="managed page title and screenshot were read from the local fixture",
63
+ )
64
+
65
+
66
+ def _verify_backend_usage(
67
+ *,
68
+ api_key: str,
69
+ timeout_seconds: int,
70
+ ) -> None:
71
+ url = f"{NODEMANTIS_API_URL}/v2/usage"
72
+ request = Request(
73
+ url,
74
+ method="GET",
75
+ headers={
76
+ "authorization": f"Bearer {api_key}",
77
+ },
78
+ )
79
+
80
+ try:
81
+ with urlopen(request, timeout=timeout_seconds) as response:
82
+ if response.status < 200 or response.status >= 300:
83
+ raise RuntimeError(f"NodeMantis backend usage check failed: HTTP {response.status}")
84
+ except HTTPError as exc:
85
+ try:
86
+ body = exc.read(500).decode("utf-8", errors="replace")
87
+ finally:
88
+ exc.close()
89
+ raise RuntimeError(
90
+ f"NodeMantis backend usage check failed: HTTP {exc.code}{chr(10) + body if body else ''}"
91
+ ) from exc
92
+
93
+
94
+ async def _verify_fixture(*, api_key: Optional[str], headless: bool) -> None:
95
+ from .session import NodeMantis
96
+
97
+ html = resources.files("nodemantis.fixtures").joinpath("smoke.html").read_text(encoding="utf-8")
98
+ data_url = "data:text/html;base64," + base64.b64encode(html.encode("utf-8")).decode("ascii")
99
+
100
+ async with await NodeMantis.start(start_url=data_url, headless=headless, api_key=api_key) as mantis:
101
+ title = await mantis.page.title()
102
+ if title != SMOKE_FIXTURE_TITLE:
103
+ raise RuntimeError(f'Smoke fixture title mismatch: got "{title}"')
104
+ if not await mantis.page.screenshot():
105
+ raise RuntimeError("Smoke fixture screenshot was empty")
nodemantis/types.py ADDED
@@ -0,0 +1,345 @@
1
+ """Public result and option types for the NodeMantis Python SDK.
2
+
3
+ Frozen dataclasses parsed tolerantly from wire dicts: unknown keys are
4
+ ignored, missing optionals default to ``None``, and every result keeps the
5
+ raw wire dict on ``.raw``. Field names are snake_case; the wire stays
6
+ camelCase (the SDK translates option names through an explicit map only —
7
+ user payloads such as schemas and result values are never touched).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass, field
13
+ from typing import Any, Callable, List, Optional
14
+
15
+ try: # Literal is typing-only sugar; keep 3.9 compatibility explicit.
16
+ from typing import Literal
17
+
18
+ Effort = Literal["low", "medium", "high", "xhigh"]
19
+ RetrievalStatus = Literal["success", "unavailable"]
20
+ except ImportError: # pragma: no cover
21
+ Effort = str # type: ignore[misc]
22
+ RetrievalStatus = str # type: ignore[misc]
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class BrowserGoResult:
27
+ ok: bool
28
+ url: str
29
+ title: str
30
+ raw: "dict[str, Any]" = field(repr=False, default_factory=dict)
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class TokenUsage:
35
+ input: int
36
+ output: int
37
+ cached: int
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class AgentProgressEvent:
42
+ iteration: int
43
+ max_iterations: Optional[int] = None
44
+ message: Optional[str] = None
45
+ action: Optional[str] = None
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class AgentOperationResult:
50
+ ok: bool
51
+ reason: str
52
+ cost_usd: Optional[float] = None
53
+ iterations: Optional[int] = None
54
+ trace_id: Optional[str] = None
55
+ value: Any = None
56
+ retrieval: Optional["AgentRetrievalSummary"] = None
57
+ raw: "dict[str, Any]" = field(repr=False, default_factory=dict)
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class AgentRetrievalSummary:
62
+ status: str
63
+ message: str
64
+ retryable: Optional[bool] = None
65
+ raw: "dict[str, Any]" = field(repr=False, default_factory=dict)
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class AgentRetrieveResult:
70
+ status: str
71
+ data: Any
72
+ message: str
73
+ retryable: Optional[bool] = None
74
+ cost_usd: Optional[float] = None
75
+ tokens: Optional[TokenUsage] = None
76
+ final_url: Optional[str] = None
77
+ trace_id: Optional[str] = None
78
+ raw: "dict[str, Any]" = field(repr=False, default_factory=dict)
79
+
80
+ @property
81
+ def is_success(self) -> bool:
82
+ return self.status == "success"
83
+
84
+ @property
85
+ def is_unavailable(self) -> bool:
86
+ return self.status == "unavailable"
87
+
88
+
89
+ @dataclass(frozen=True)
90
+ class MockLLMResponse:
91
+ text: Optional[str] = None
92
+ tool_calls: Optional[List["dict[str, Any]"]] = None
93
+
94
+ def to_wire(self) -> "dict[str, Any]":
95
+ wire: "dict[str, Any]" = {}
96
+ if self.text is not None:
97
+ wire["text"] = self.text
98
+ if self.tool_calls is not None:
99
+ wire["toolCalls"] = self.tool_calls
100
+ return wire
101
+
102
+
103
+ @dataclass(frozen=True)
104
+ class MockLLMRule:
105
+ input_contains: List[str]
106
+ response: MockLLMResponse
107
+ input_excludes: Optional[List[str]] = None
108
+
109
+ def to_wire(self) -> "dict[str, Any]":
110
+ wire: "dict[str, Any]" = {
111
+ "inputContains": list(self.input_contains),
112
+ "response": self.response.to_wire(),
113
+ }
114
+ if self.input_excludes is not None:
115
+ wire["inputExcludes"] = list(self.input_excludes)
116
+ return wire
117
+
118
+
119
+ @dataclass(frozen=True)
120
+ class MockLLMOptions:
121
+ rules: List[MockLLMRule]
122
+
123
+ def to_wire(self) -> "dict[str, Any]":
124
+ return {"rules": [rule.to_wire() for rule in self.rules]}
125
+
126
+
127
+ # ── wire parsers ─────────────────────────────────────────────────────────────
128
+
129
+
130
+ def _opt_str(value: Any) -> Optional[str]:
131
+ return value if isinstance(value, str) and value else None
132
+
133
+
134
+ def _opt_number(value: Any) -> Optional[float]:
135
+ return value if isinstance(value, (int, float)) and not isinstance(value, bool) else None
136
+
137
+
138
+ def _opt_int(value: Any) -> Optional[int]:
139
+ return value if isinstance(value, int) and not isinstance(value, bool) else None
140
+
141
+
142
+ def parse_go_result(raw: Any) -> BrowserGoResult:
143
+ record = raw if isinstance(raw, dict) else {}
144
+ return BrowserGoResult(
145
+ ok=bool(record.get("ok")),
146
+ url=record.get("url") if isinstance(record.get("url"), str) else "",
147
+ title=record.get("title") if isinstance(record.get("title"), str) else "",
148
+ raw=record,
149
+ )
150
+
151
+
152
+ def parse_operation_result(raw: Any) -> AgentOperationResult:
153
+ record = raw if isinstance(raw, dict) else {}
154
+ retrieval_record = record.get("retrieval")
155
+ retrieval = (
156
+ AgentRetrievalSummary(
157
+ status=retrieval_record.get("status", ""),
158
+ message=retrieval_record.get("message", ""),
159
+ retryable=(
160
+ retrieval_record.get("retryable")
161
+ if isinstance(retrieval_record.get("retryable"), bool)
162
+ else None
163
+ ),
164
+ raw=retrieval_record,
165
+ )
166
+ if isinstance(retrieval_record, dict)
167
+ else None
168
+ )
169
+ return AgentOperationResult(
170
+ ok=bool(record.get("ok")),
171
+ reason=record.get("reason") if isinstance(record.get("reason"), str) else "",
172
+ cost_usd=_opt_number(record.get("costUsd")),
173
+ iterations=_opt_int(record.get("iterations")),
174
+ trace_id=_opt_str(record.get("traceId")),
175
+ value=record.get("value"),
176
+ retrieval=retrieval,
177
+ raw=record,
178
+ )
179
+
180
+
181
+ def parse_retrieve_result(raw: Any) -> AgentRetrieveResult:
182
+ record = raw if isinstance(raw, dict) else {}
183
+ tokens_record = record.get("tokens")
184
+ tokens = (
185
+ TokenUsage(
186
+ input=tokens_record.get("input", 0),
187
+ output=tokens_record.get("output", 0),
188
+ cached=tokens_record.get("cached", 0),
189
+ )
190
+ if isinstance(tokens_record, dict)
191
+ else None
192
+ )
193
+ raw_status = record.get("status") if isinstance(record.get("status"), str) else "unavailable"
194
+ status = "success" if raw_status == "success" else "unavailable"
195
+ message = record.get("message")
196
+ if not isinstance(message, str):
197
+ message = record.get("reason") if isinstance(record.get("reason"), str) else ""
198
+ return AgentRetrieveResult(
199
+ status=status,
200
+ data=record.get("data") if status == "success" else None,
201
+ message=message,
202
+ retryable=(
203
+ record.get("retryable")
204
+ if isinstance(record.get("retryable"), bool)
205
+ else (False if status == "unavailable" else None)
206
+ ),
207
+ cost_usd=_opt_number(record.get("costUsd")),
208
+ tokens=tokens,
209
+ final_url=_opt_str(record.get("finalUrl")),
210
+ trace_id=_opt_str(record.get("traceId")),
211
+ raw=record,
212
+ )
213
+
214
+
215
+ def parse_progress_notification(params: Any) -> "Optional[tuple[str, AgentProgressEvent]]":
216
+ if not isinstance(params, dict):
217
+ return None
218
+ session_id = params.get("sessionId")
219
+ iteration = params.get("iteration")
220
+ if not isinstance(session_id, str) or not isinstance(iteration, int):
221
+ return None
222
+ return session_id, AgentProgressEvent(
223
+ iteration=iteration,
224
+ max_iterations=_opt_int(params.get("maxIterations")),
225
+ message=_opt_str(params.get("message")),
226
+ action=_opt_str(params.get("action")),
227
+ )
228
+
229
+
230
+ def to_json_schema(schema: Any) -> Any:
231
+ """Pass a JSON Schema dict through; accept pydantic v2 models by duck type."""
232
+
233
+ if schema is None:
234
+ return None
235
+ model_json_schema = getattr(schema, "model_json_schema", None)
236
+ if callable(model_json_schema):
237
+ return model_json_schema()
238
+ if isinstance(schema, dict):
239
+ return schema
240
+ raise TypeError(
241
+ "schema must be a JSON Schema dict (or a pydantic model class), got "
242
+ f"{type(schema).__name__}"
243
+ )
244
+
245
+
246
+ def to_mock_llm_wire(mock_llm: Any) -> Any:
247
+ if mock_llm is None:
248
+ return None
249
+ if isinstance(mock_llm, MockLLMOptions):
250
+ return mock_llm.to_wire()
251
+ if isinstance(mock_llm, dict):
252
+ return mock_llm
253
+ raise TypeError("mock_llm must be MockLLMOptions or a wire-format dict")
254
+
255
+ # Option dictionaries use the same public type names as the other SDKs.
256
+ from typing import TypedDict
257
+
258
+
259
+ class NodeMantisAgentOptions(TypedDict, total=False):
260
+ effort: Effort
261
+ max_iterations: int
262
+ timeout: int
263
+
264
+
265
+ class NodeMantisDefaultAgentOptions(NodeMantisAgentOptions, total=False):
266
+ max_actions: int
267
+
268
+
269
+ class NodeMantisLoggingOptions(TypedDict, total=False):
270
+ level: Literal["off", "info", "debug"]
271
+ dir: str
272
+ retention_days: int
273
+ max_total_size_mb: int
274
+
275
+
276
+ class NodeMantisManagedContextOptions(TypedDict, total=False):
277
+ geometry: dict[str, str]
278
+ color_scheme: Optional[Literal["dark", "light", "no-preference"]]
279
+ contrast: Optional[Literal["more", "no-preference"]]
280
+ device_scale_factor: float
281
+ extra_http_headers: dict[str, str]
282
+ forced_colors: Optional[Literal["active", "none"]]
283
+ geolocation: dict[str, float]
284
+ java_script_enabled: bool
285
+ locale: str
286
+ offline: bool
287
+ permissions: list[str]
288
+ reduced_motion: Optional[Literal["reduce", "no-preference"]]
289
+ screen: dict[str, int]
290
+ timezone_id: str
291
+
292
+
293
+ class NodeMantisOptions(TypedDict, total=False):
294
+ api_key: str
295
+ llm_timeout_ms: int
296
+ default_agent_options: NodeMantisDefaultAgentOptions
297
+ logging: NodeMantisLoggingOptions
298
+
299
+
300
+ class NodeMantisStartOptions(NodeMantisOptions, total=False):
301
+ shared_browser: bool
302
+ horizontal_scroll: bool
303
+ start_url: str
304
+ headless: bool
305
+ viewport: dict[str, int]
306
+ geometry: dict[str, str]
307
+ use_proxy: bool
308
+ default_timeout_ms: int
309
+ context_options: NodeMantisManagedContextOptions
310
+
311
+
312
+ class NodeMantisRunOptions(NodeMantisAgentOptions, total=False):
313
+ result_schema: Any
314
+ max_cost: float
315
+ mock_llm: MockLLMOptions
316
+ on_progress: "Callable[[AgentProgressEvent], None]"
317
+
318
+
319
+ class NodeMantisStepOptions(TypedDict, total=False):
320
+ effort: Effort
321
+ timeout: int
322
+ max_actions: int
323
+ allow_navigation: bool
324
+ result_schema: Any
325
+ max_cost: float
326
+ on_progress: "Callable[[AgentProgressEvent], None]"
327
+
328
+
329
+ class NodeMantisRetrieveOptions(TypedDict, total=False):
330
+ schema: Any
331
+ effort: Effort
332
+
333
+
334
+ class NodeMantisExtractOptions(NodeMantisRetrieveOptions, total=False):
335
+ pass
336
+
337
+
338
+ class NodeMantisCheckOptions(TypedDict, total=False):
339
+ effort: Effort
340
+
341
+
342
+ class NodeMantisPreflightOptions(TypedDict, total=False):
343
+ api_key: str
344
+ check_browser: bool
345
+ timeout_ms: int