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/session.py ADDED
@@ -0,0 +1,727 @@
1
+ """The NodeMantis session facade — the Python parity surface of the TS SDK.
2
+
3
+ All operations are awaitable. Mutations are serialized per session; lifecycle
4
+ waits bypass that queue so a chooser/download can be armed before an action.
5
+ Cancellation aborts the RPC, and close releases the shared runtime lease.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import contextvars
12
+ import inspect
13
+ import os
14
+ import threading
15
+ import time
16
+ import uuid
17
+ import weakref
18
+ import warnings
19
+ from typing import Any, Callable, Optional
20
+
21
+ from ._async import blocking
22
+ from ._host import RuntimeLease, get_runtime_host
23
+ from ._protocol import (
24
+ BROWSER_OPTION_KEYS,
25
+ GEOMETRY_OPTION_KEYS,
26
+ METHOD_AGENT_CHECK,
27
+ METHOD_AGENT_EXTRACT,
28
+ METHOD_AGENT_PROGRESS,
29
+ METHOD_AGENT_RETRIEVE,
30
+ METHOD_AGENT_RUN,
31
+ METHOD_AGENT_STEP,
32
+ METHOD_MANAGED_SESSION_PREFLIGHT,
33
+ METHOD_MANAGED_SESSION_START,
34
+ METHOD_SESSION_CLOSE,
35
+ map_options,
36
+ )
37
+ from .config import read_config_file
38
+ from .errors import (
39
+ NavigationOnlyError,
40
+ NodeMantisError,
41
+ RetrievalRequestError,
42
+ RpcAbortedError,
43
+ RuntimeRpcError,
44
+ SessionClosedError,
45
+ as_retrieval_request_error,
46
+ )
47
+ from .managed_page import ManagedPage
48
+ from .preflight import NodeMantisPreflightCheck, NodeMantisPreflightResult
49
+ from .types import (
50
+ NodeMantisDefaultAgentOptions,
51
+ NodeMantisLoggingOptions,
52
+ NodeMantisManagedContextOptions,
53
+ AgentOperationResult,
54
+ Effort,
55
+ AgentProgressEvent,
56
+ AgentRetrieveResult,
57
+ BrowserGoResult,
58
+ parse_operation_result,
59
+ parse_progress_notification,
60
+ parse_retrieve_result,
61
+ to_json_schema,
62
+ to_mock_llm_wire,
63
+ )
64
+
65
+ SESSION_CLOSE_TIMEOUT_MS = 2_000
66
+
67
+ _LOGGING_ENV_KEYS = {
68
+ "level": "NODEMANTIS_LOG_LEVEL",
69
+ "dir": "NODEMANTIS_LOG_DIR",
70
+ "retention_days": "NODEMANTIS_LOG_RETENTION_DAYS",
71
+ "max_total_size_mb": "NODEMANTIS_LOG_MAX_MB",
72
+ }
73
+
74
+ _AGENT_OPTION_WIRE = {
75
+ "effort": "effort",
76
+ "max_iterations": "maxIterations",
77
+ "timeout": "timeout",
78
+ }
79
+
80
+
81
+ def _compact(record: "dict[str, Any]") -> "dict[str, Any]":
82
+ return {key: value for key, value in record.items() if value is not None}
83
+
84
+
85
+ def _resolve_api_key(api_key: Optional[str]) -> Optional[str]:
86
+ resolved = (
87
+ api_key
88
+ or os.environ.get("NODEMANTIS_API_KEY")
89
+ or os.environ.get("NODEMANTIS_AUTH_TOKEN")
90
+ or os.environ.get("AGENT_API_KEY")
91
+ )
92
+ if resolved:
93
+ return resolved
94
+ # Shared SDK precedence: explicit key, environment, then saved config.
95
+ try:
96
+ file_config = read_config_file()
97
+ except Exception: # noqa: BLE001 - a broken config file must not block env use
98
+ return None
99
+ return file_config.api_key or file_config.auth_token
100
+
101
+
102
+ def _logging_env(logging: Optional[NodeMantisLoggingOptions]) -> Optional["dict[str, str]"]:
103
+ if not logging:
104
+ return None
105
+ env: "dict[str, str]" = {}
106
+ for key, value in logging.items():
107
+ env_key = _LOGGING_ENV_KEYS.get(key)
108
+ if env_key is None:
109
+ raise TypeError(f"Unknown logging option {key!r}")
110
+ if value is not None:
111
+ env[env_key] = str(value)
112
+ return env or None
113
+
114
+
115
+ def _agent_options_wire(options: Optional["dict[str, Any]"]) -> "tuple[Any, Any]":
116
+ """Split default agent options into (agent options, default step options)."""
117
+
118
+ if not options:
119
+ return None, None
120
+ wire: "dict[str, Any]" = {}
121
+ step_wire: "dict[str, Any]" = {}
122
+ for key, value in options.items():
123
+ if value is None:
124
+ continue
125
+ if key == "max_actions":
126
+ step_wire["maxActions"] = value
127
+ continue
128
+ wire_key = _AGENT_OPTION_WIRE.get(key)
129
+ if wire_key is None:
130
+ raise TypeError(f"Unknown agent option {key!r}")
131
+ wire[wire_key] = value
132
+ return wire or None, step_wire or None
133
+
134
+
135
+ def _normalize_managed_context_options(
136
+ options: Optional["dict[str, Any]"],
137
+ geometry: Optional["dict[str, Any]"] = None,
138
+ ) -> Optional["dict[str, Any]"]:
139
+ if options is None and geometry is None:
140
+ return None
141
+ if options is not None and not isinstance(options, dict):
142
+ raise TypeError("context_options must be a dictionary")
143
+ context_keys = {
144
+ "color_scheme": "colorScheme", "device_scale_factor": "deviceScaleFactor",
145
+ "extra_http_headers": "extraHTTPHeaders", "forced_colors": "forcedColors",
146
+ "java_script_enabled": "javaScriptEnabled",
147
+ "reduced_motion": "reducedMotion",
148
+ "timezone_id": "timezoneId",
149
+ "geometry": "geometry", "contrast": "contrast", "geolocation": "geolocation",
150
+ "locale": "locale", "offline": "offline", "permissions": "permissions", "screen": "screen",
151
+ }
152
+ merged = {}
153
+ for key, value in (options or {}).items():
154
+ wire_key = context_keys.get(key, key)
155
+ if wire_key in merged:
156
+ raise ValueError(f"Duplicate context option: {wire_key}")
157
+ merged[wire_key] = value
158
+ if "extraHttpHeaders" in merged:
159
+ raise ValueError(
160
+ "context_options.extraHttpHeaders is unsupported; use the canonical "
161
+ "extraHTTPHeaders spelling"
162
+ )
163
+ for key in merged:
164
+ if key not in context_keys.values():
165
+ raise ValueError(f"Unsupported context option: {key}")
166
+ if geometry is not None:
167
+ if not isinstance(geometry, dict):
168
+ raise TypeError("geometry must be a dictionary")
169
+ merged["geometry"] = map_options(geometry, GEOMETRY_OPTION_KEYS, where="geometry")
170
+ return _compact(merged)
171
+
172
+
173
+ def _managed_backend_error(error: Exception) -> Exception:
174
+ if isinstance(error, NodeMantisError) and "raw-CDP managed session" in str(error):
175
+ return error
176
+ if isinstance(error, RuntimeRpcError) and str(error.code) in {
177
+ "METHOD_NOT_FOUND",
178
+ "CAPABILITY_UNAVAILABLE",
179
+ }:
180
+ return NodeMantisError(
181
+ "This native runtime does not support managed raw-CDP sessions. "
182
+ "Upgrade the node-mantis package to get a compatible runtime."
183
+ )
184
+ return error
185
+
186
+
187
+ def _create_sdk_session_id() -> str:
188
+ return f"sdk_{int(time.time() * 1000)}_{uuid.uuid4().hex[:8]}"
189
+
190
+
191
+ _progress_routes: "weakref.WeakKeyDictionary[Any, dict[str, Callable[[AgentProgressEvent], None]]]" = (
192
+ weakref.WeakKeyDictionary()
193
+ )
194
+ _progress_lock = threading.Lock()
195
+
196
+
197
+ def _ensure_progress_routes(client: Any) -> "dict[str, Callable[[AgentProgressEvent], None]]":
198
+ with _progress_lock:
199
+ routes = _progress_routes.get(client)
200
+ if routes is not None:
201
+ return routes
202
+ created: "dict[str, Callable[[AgentProgressEvent], None]]" = {}
203
+ _progress_routes[client] = created
204
+
205
+ def handler(params: Any, _context: Any) -> None:
206
+ parsed = parse_progress_notification(params)
207
+ if parsed is None:
208
+ return
209
+ session_id, event = parsed
210
+ callback = created.get(session_id)
211
+ if callback is not None:
212
+ callback(event)
213
+
214
+ client.register_handler(METHOD_AGENT_PROGRESS, handler)
215
+ return created
216
+
217
+
218
+ class NodeMantis:
219
+ """A browser-driving session backed by the shared native runtime.
220
+
221
+ Create instances with :meth:`start`; the constructor is internal.
222
+ """
223
+
224
+ def __init__(
225
+ self,
226
+ *,
227
+ page: Any,
228
+ sdk_session_id: str,
229
+ session_id: str,
230
+ lease: RuntimeLease,
231
+ capability_mode: str,
232
+ ) -> None:
233
+ self.page = page
234
+ self.sdk_session_id = sdk_session_id
235
+ self._capability_mode = capability_mode
236
+ self._session_id = session_id
237
+ self._lease = lease
238
+ self._closed = False
239
+ self._close_task: Optional[asyncio.Task[None]] = None
240
+ self._op_lock = asyncio.Lock()
241
+ self._abort_events: "set[threading.Event]" = set()
242
+ self._progress = contextvars.ContextVar("nodemantis_progress", default=None)
243
+
244
+ # ── lifecycle ────────────────────────────────────────────────────────────
245
+
246
+ @classmethod
247
+ async def start(
248
+ cls,
249
+ *,
250
+ api_key: Optional[str] = None,
251
+ llm_timeout_ms: Optional[int] = None,
252
+ default_agent_options: Optional[NodeMantisDefaultAgentOptions] = None,
253
+ logging: Optional[NodeMantisLoggingOptions] = None,
254
+ start_url: Optional[str] = None,
255
+ headless: Optional[bool] = None,
256
+ _navigation_only: bool = False,
257
+ shared_browser: bool = True,
258
+ horizontal_scroll: bool = False,
259
+ viewport: Optional["dict[str, int]"] = None,
260
+ geometry: Optional["dict[str, str]"] = None,
261
+ use_proxy: Optional[bool] = None,
262
+ default_timeout_ms: Optional[int] = None,
263
+ context_options: Optional[NodeMantisManagedContextOptions] = None,
264
+ runtime_path: Optional[str] = None,
265
+ ) -> "NodeMantis":
266
+ lease = await blocking(
267
+ get_runtime_host().acquire, env=_logging_env(logging), runtime_path=runtime_path,
268
+ on_cancel_result=lambda lease: lease.release(),
269
+ )
270
+ session_id: Optional[str] = None
271
+ try:
272
+ sdk_session_id = _create_sdk_session_id()
273
+ capability_mode = "navigation-only" if _navigation_only else "agent"
274
+ agent_options, default_step_options = _agent_options_wire(
275
+ default_agent_options
276
+ )
277
+ def cleanup_started(result: Any) -> None:
278
+ if isinstance(result, dict) and isinstance(result.get("sessionId"), str):
279
+ lease.client.request(METHOD_SESSION_CLOSE, {"sessionId": result["sessionId"]},
280
+ timeout_ms=SESSION_CLOSE_TIMEOUT_MS)
281
+
282
+ result = await blocking(
283
+ lease.client.request, METHOD_MANAGED_SESSION_START,
284
+ _compact(
285
+ {
286
+ "sdkSessionId": sdk_session_id,
287
+ "apiKey": await blocking(_resolve_api_key, api_key),
288
+ "llmTimeoutMs": llm_timeout_ms,
289
+ "defaultAgentOptions": agent_options,
290
+ "defaultStepOptions": default_step_options,
291
+ "logging": (
292
+ {"level": logging["level"]}
293
+ if logging and logging.get("level")
294
+ else None
295
+ ),
296
+ "browser": map_options(
297
+ {
298
+ "capability_mode": capability_mode,
299
+ "shared_browser": shared_browser,
300
+ "horizontal_scroll": horizontal_scroll,
301
+ "start_url": start_url,
302
+ "headless": headless,
303
+ "viewport": viewport,
304
+ "use_proxy": use_proxy,
305
+ "default_timeout_ms": default_timeout_ms,
306
+ "context_options": _normalize_managed_context_options(
307
+ context_options, geometry
308
+ ),
309
+ },
310
+ BROWSER_OPTION_KEYS,
311
+ where="start browser",
312
+ ),
313
+ }
314
+ ),
315
+ on_cancel_result=cleanup_started,
316
+ )
317
+ if (
318
+ isinstance(result, dict)
319
+ and isinstance(result.get("sessionId"), str)
320
+ and result["sessionId"]
321
+ ):
322
+ session_id = result["sessionId"]
323
+ session_id, page_id = cls._validate_managed_session_result(result)
324
+ instance = cls(
325
+ page=None,
326
+ sdk_session_id=sdk_session_id,
327
+ session_id=session_id,
328
+ lease=lease,
329
+ capability_mode=capability_mode,
330
+ )
331
+ instance.page = ManagedPage(
332
+ lambda method, params=None: instance._managed_page_request(
333
+ method, page_id, params
334
+ ),
335
+ lambda method, params=None: instance._managed_page_concurrent(
336
+ method, page_id, params
337
+ ),
338
+ lambda method, params=None: instance._managed_page_attachment(
339
+ method, page_id, params
340
+ ),
341
+ )
342
+ return instance
343
+ except BaseException as error:
344
+ if session_id is not None:
345
+ try:
346
+ await blocking(lease.client.request,
347
+ METHOD_SESSION_CLOSE,
348
+ {"sessionId": session_id},
349
+ timeout_ms=SESSION_CLOSE_TIMEOUT_MS,
350
+ )
351
+ except Exception: # noqa: BLE001 - best-effort unwind
352
+ pass
353
+ await blocking(lease.release)
354
+ if isinstance(error, Exception):
355
+ raise _managed_backend_error(error)
356
+ raise
357
+
358
+ @classmethod
359
+ async def preflight(
360
+ cls,
361
+ *,
362
+ api_key: Optional[str] = None,
363
+ check_browser: bool = True,
364
+ timeout_ms: Optional[int] = None,
365
+ runtime_path: Optional[str] = None,
366
+ ) -> NodeMantisPreflightResult:
367
+ lease = await blocking(get_runtime_host().acquire, runtime_path=runtime_path,
368
+ on_cancel_result=lambda lease: lease.release())
369
+ try:
370
+ raw = await blocking(lease.client.request,
371
+ METHOD_MANAGED_SESSION_PREFLIGHT,
372
+ _compact(
373
+ {
374
+ "apiKey": await blocking(_resolve_api_key, api_key),
375
+ "timeoutMs": timeout_ms,
376
+ "checkBrowser": check_browser,
377
+ }
378
+ ),
379
+ abort_event=threading.Event(),
380
+ )
381
+ return cls._parse_preflight(raw)
382
+ except Exception as error:
383
+ raise _managed_backend_error(error)
384
+ finally:
385
+ await blocking(lease.release)
386
+
387
+ async def close(self) -> None:
388
+ if self._close_task is None:
389
+ self._closed = True
390
+ for event in self._abort_events:
391
+ event.set()
392
+ self._close_task = asyncio.create_task(self._close_once())
393
+ await asyncio.shield(self._close_task)
394
+
395
+ async def _close_once(self) -> None:
396
+ try:
397
+ await blocking(self._lease.client.request, METHOD_SESSION_CLOSE,
398
+ {"sessionId": self._session_id}, timeout_ms=SESSION_CLOSE_TIMEOUT_MS)
399
+ except Exception: # noqa: BLE001 - close is bounded and best-effort
400
+ pass
401
+ finally:
402
+ await blocking(self._lease.release)
403
+
404
+ async def __aenter__(self) -> "NodeMantis":
405
+ self._assert_open()
406
+ return self
407
+
408
+ async def __aexit__(self, *_exc_info: Any) -> None:
409
+ await self.close()
410
+
411
+ # ── operations ───────────────────────────────────────────────────────────
412
+
413
+ async def go(
414
+ self,
415
+ url: str,
416
+ *,
417
+ wait_until: Optional[str] = None,
418
+ timeout: Optional[int] = None,
419
+ ) -> BrowserGoResult:
420
+ return await self.page.navigate(url, wait_until=wait_until, timeout=timeout)
421
+
422
+ async def run(
423
+ self,
424
+ goal: str,
425
+ *,
426
+ effort: Optional[Effort] = None,
427
+ max_iterations: Optional[int] = None,
428
+ timeout: Optional[int] = None,
429
+ result_schema: Any = None,
430
+ max_cost: Optional[float] = None,
431
+ mock_llm: Any = None,
432
+ on_progress: Optional[Callable[[AgentProgressEvent], None]] = None,
433
+ ) -> AgentOperationResult:
434
+ self._assert_agent_capable("run")
435
+ options = _compact(
436
+ {
437
+ "effort": effort,
438
+ "maxIterations": max_iterations,
439
+ "timeout": timeout,
440
+ "resultSchema": to_json_schema(result_schema),
441
+ "maxCost": max_cost,
442
+ "mockLLM": to_mock_llm_wire(mock_llm),
443
+ }
444
+ )
445
+ operation = (
446
+ self._retrieval_operation
447
+ if result_schema is not None
448
+ else self._operation
449
+ )
450
+ raw = await self._with_progress(
451
+ on_progress,
452
+ lambda: operation(
453
+ METHOD_AGENT_RUN,
454
+ _compact(
455
+ {
456
+ "sessionId": self._session_id,
457
+ "goal": goal,
458
+ "options": options or None,
459
+ }
460
+ ),
461
+ ),
462
+ )
463
+ return parse_operation_result(raw)
464
+
465
+ async def step(
466
+ self,
467
+ instruction: str,
468
+ *,
469
+ effort: Optional[Effort] = None,
470
+ timeout: Optional[int] = None,
471
+ max_actions: Optional[int] = None,
472
+ allow_navigation: Optional[bool] = None,
473
+ result_schema: Any = None,
474
+ max_cost: Optional[float] = None,
475
+ on_progress: Optional[Callable[[AgentProgressEvent], None]] = None,
476
+ ) -> AgentOperationResult:
477
+ """Deprecated: use run() and keep this session open between calls.
478
+
479
+ Retains the existing bounded-step behavior for compatibility. When
480
+ migrating, use max_iterations instead of max_actions; run() permits
481
+ navigation without an allow_navigation option.
482
+ """
483
+ warnings.warn(
484
+ "NodeMantis.step() is deprecated; use run() on the same session instead.",
485
+ DeprecationWarning,
486
+ stacklevel=2,
487
+ )
488
+ self._assert_agent_capable("step")
489
+ options = _compact(
490
+ {
491
+ "effort": effort,
492
+ "timeout": timeout,
493
+ "maxActions": max_actions,
494
+ "allowNavigation": allow_navigation,
495
+ "resultSchema": to_json_schema(result_schema),
496
+ "maxCost": max_cost,
497
+ }
498
+ )
499
+ operation = (
500
+ self._retrieval_operation
501
+ if result_schema is not None
502
+ else self._operation
503
+ )
504
+ raw = await self._with_progress(
505
+ on_progress,
506
+ lambda: operation(
507
+ METHOD_AGENT_STEP,
508
+ _compact(
509
+ {
510
+ "sessionId": self._session_id,
511
+ "instruction": instruction,
512
+ "options": options or None,
513
+ }
514
+ ),
515
+ ),
516
+ )
517
+ return parse_operation_result(raw)
518
+
519
+ async def retrieve(
520
+ self,
521
+ prompt: str,
522
+ *,
523
+ schema: Any = None,
524
+ effort: Optional[Effort] = None,
525
+ ) -> AgentRetrieveResult:
526
+ self._assert_agent_capable("retrieve")
527
+ options = _compact({"effort": effort})
528
+ raw = await self._retrieval_operation(
529
+ METHOD_AGENT_RETRIEVE,
530
+ _compact(
531
+ {
532
+ "sessionId": self._session_id,
533
+ "prompt": prompt,
534
+ "schema": to_json_schema(schema),
535
+ "options": options or None,
536
+ }
537
+ ),
538
+ )
539
+ return parse_retrieve_result(raw)
540
+
541
+ async def extract(
542
+ self,
543
+ prompt: str,
544
+ *,
545
+ schema: Any = None,
546
+ effort: Optional[Effort] = None,
547
+ ) -> AgentOperationResult:
548
+ self._assert_agent_capable("extract")
549
+ raw = await self._retrieval_operation(
550
+ METHOD_AGENT_EXTRACT,
551
+ _compact(
552
+ {
553
+ "sessionId": self._session_id,
554
+ "prompt": prompt,
555
+ "schema": to_json_schema(schema),
556
+ "effort": effort,
557
+ }
558
+ ),
559
+ )
560
+ return parse_operation_result(raw)
561
+
562
+ async def check(self, prompt: str, *, effort: Optional[Effort] = None) -> AgentOperationResult:
563
+ self._assert_agent_capable("check")
564
+ raw = await self._retrieval_operation(
565
+ METHOD_AGENT_CHECK,
566
+ _compact(
567
+ {
568
+ "sessionId": self._session_id,
569
+ "prompt": prompt,
570
+ "effort": effort,
571
+ }
572
+ ),
573
+ )
574
+ return parse_operation_result(raw)
575
+
576
+ # ── internals ────────────────────────────────────────────────────────────
577
+
578
+ async def _with_progress(
579
+ self,
580
+ on_progress: Optional[Callable[[AgentProgressEvent], Any]],
581
+ operation: Callable[[], Any],
582
+ ) -> Any:
583
+ token = self._progress.set(on_progress)
584
+ try:
585
+ return await operation()
586
+ finally:
587
+ self._progress.reset(token)
588
+
589
+ async def _request(self, method: str, params: Any, *, attachment: bool = False) -> Any:
590
+ self._assert_open()
591
+ abort_event = threading.Event()
592
+ self._abort_events.add(abort_event)
593
+ callback = self._progress.get() if method in {METHOD_AGENT_RUN, METHOD_AGENT_STEP} else None
594
+ routes = _ensure_progress_routes(self._lease.client) if callback else None
595
+ loop = asyncio.get_running_loop()
596
+
597
+ def consume_error(task: asyncio.Task[Any]) -> None:
598
+ if not task.cancelled():
599
+ task.exception()
600
+
601
+ def dispatch(event: AgentProgressEvent) -> None:
602
+ try:
603
+ result = callback(event)
604
+ if inspect.isawaitable(result):
605
+ task = asyncio.ensure_future(result)
606
+ task.add_done_callback(consume_error)
607
+ except Exception: # noqa: BLE001 - listeners cannot fail the operation
608
+ pass
609
+
610
+ if routes is not None:
611
+ routes[self._session_id] = lambda event: loop.call_soon_threadsafe(dispatch, event)
612
+ try:
613
+ request = self._lease.client.request_frame if attachment else self._lease.client.request
614
+ try:
615
+ return await blocking(request, method, params, abort_event=abort_event)
616
+ except RpcAbortedError as error:
617
+ if self._closed:
618
+ raise SessionClosedError() from error
619
+ raise
620
+ finally:
621
+ self._abort_events.discard(abort_event)
622
+ if routes is not None:
623
+ routes.pop(self._session_id, None)
624
+
625
+ async def _operation(self, method: str, params: Any) -> Any:
626
+ self._assert_open()
627
+ async with self._op_lock:
628
+ return await self._request(method, params)
629
+
630
+ async def _concurrent_operation(self, method: str, params: Any) -> Any:
631
+ return await self._request(method, params)
632
+
633
+ async def _managed_page_request(
634
+ self, method: str, page_id: str, params: Optional["dict[str, Any]"]
635
+ ) -> Any:
636
+ return await self._operation(
637
+ method,
638
+ {"sessionId": self._session_id, "pageId": page_id, **(params or {})},
639
+ )
640
+
641
+ async def _managed_page_concurrent(
642
+ self, method: str, page_id: str, params: Optional["dict[str, Any]"]
643
+ ) -> Any:
644
+ return await self._concurrent_operation(
645
+ method,
646
+ {"sessionId": self._session_id, "pageId": page_id, **(params or {})},
647
+ )
648
+
649
+ async def _managed_page_attachment(
650
+ self, method: str, page_id: str, params: Optional["dict[str, Any]"]
651
+ ) -> Any:
652
+ self._assert_open()
653
+ async with self._op_lock:
654
+ return await self._request(method,
655
+ {"sessionId": self._session_id, "pageId": page_id, **(params or {})},
656
+ attachment=True)
657
+
658
+ async def _retrieval_operation(self, method: str, params: Any) -> Any:
659
+ public_error: Optional[RetrievalRequestError] = None
660
+ try:
661
+ return await self._operation(method, params)
662
+ except Exception as error:
663
+ mapped = as_retrieval_request_error(error)
664
+ if mapped is not None:
665
+ public_error = mapped
666
+ else:
667
+ raise
668
+ # Raise outside the except block so Python does not attach the private
669
+ # RuntimeRpcError as __cause__/__context__ or print it in a traceback.
670
+ assert public_error is not None
671
+ raise public_error
672
+
673
+ def _assert_open(self) -> None:
674
+ if self._closed:
675
+ raise SessionClosedError()
676
+
677
+ def _assert_agent_capable(self, operation: str) -> None:
678
+ self._assert_open()
679
+ if self._capability_mode == "navigation-only":
680
+ raise NavigationOnlyError(operation)
681
+
682
+ @staticmethod
683
+ def _validate_managed_session_result(value: Any) -> "tuple[str, str]":
684
+ if not isinstance(value, dict):
685
+ raise NodeMantisError(
686
+ "Native runtime did not provide a raw-CDP managed session; "
687
+ "upgrade the node-mantis package to get a compatible runtime."
688
+ )
689
+ session_id = value.get("sessionId")
690
+ page = value.get("page")
691
+ if (
692
+ not isinstance(session_id, str)
693
+ or not session_id
694
+ or value.get("backend") != "raw-cdp"
695
+ or not isinstance(page, dict)
696
+ or not isinstance(page.get("id"), str)
697
+ or not page["id"]
698
+ or type(page.get("apiVersion")) is not int
699
+ or page["apiVersion"] != 1
700
+ ):
701
+ raise NodeMantisError(
702
+ "Native runtime did not provide a raw-CDP managed session; "
703
+ "upgrade the node-mantis package to get a compatible runtime."
704
+ )
705
+ return session_id, page["id"]
706
+
707
+ @staticmethod
708
+ def _parse_preflight(raw: Any) -> NodeMantisPreflightResult:
709
+ record = raw if isinstance(raw, dict) else {}
710
+ checks = []
711
+ for item in record.get("checks", []) or []:
712
+ if not isinstance(item, dict):
713
+ continue
714
+ checks.append(
715
+ NodeMantisPreflightCheck(
716
+ name=item.get("name", ""),
717
+ ok=bool(item.get("ok")),
718
+ message=item.get("message", ""),
719
+ skipped=bool(item.get("skipped", False)),
720
+ details=item.get("details"),
721
+ )
722
+ )
723
+ return NodeMantisPreflightResult(
724
+ ok=bool(record.get("ok")),
725
+ has_api_key=bool(record.get("hasApiKey")),
726
+ checks=tuple(checks),
727
+ )