ai-editor-client-dev 1.0.244__py3-none-any.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,772 @@
1
+ """
2
+ Async façade over mcp-proxy-adapter JsonRpcClient for ai-editor-server.
3
+
4
+ Author: Vasiliy Zdanovskiy
5
+ email: vasilyvz@gmail.com
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import time
12
+ import warnings
13
+ from pathlib import Path
14
+ from typing import Any, Callable, Dict, FrozenSet, Mapping, Optional, Tuple
15
+
16
+ try:
17
+ from mcp_proxy_adapter.client.jsonrpc_client.client import JsonRpcClient
18
+ except Exception: # pragma: no cover - compatibility with older layouts
19
+ from mcp_proxy_adapter.client.jsonrpc_client import JsonRpcClient
20
+
21
+ try:
22
+ from mcp_proxy_adapter.core.constants import WS_JOB_WAIT_TIMEOUT
23
+ except Exception: # pragma: no cover - compatibility with older layouts
24
+ WS_JOB_WAIT_TIMEOUT = 60.0
25
+
26
+ from ai_editor_client.commands_proxy import ValidatedCommandsProxy
27
+ from ai_editor_client.config import (
28
+ adapter_settings_from_server_config,
29
+ adapter_settings_to_jsonrpc_kwargs,
30
+ load_server_config,
31
+ )
32
+ from ai_editor_client.editor_file import EditorFileClient
33
+ from ai_editor_client.file_session import FileSessionClient
34
+ from ai_editor_client.universal_file import UniversalFileClient
35
+ from ai_editor_client.server_schema import fetch_command_schema_from_server
36
+ from ai_editor_client.server_version import (
37
+ REQUIRED_SERVER_VERSION,
38
+ SERVER_VERSION_PROBE_COMMAND,
39
+ assert_server_version_matches,
40
+ is_version_exempt,
41
+ server_version_from_health,
42
+ )
43
+ from ai_editor_client.validation import (
44
+ prepare_params_for_schema,
45
+ validate_params_against_schema,
46
+ )
47
+
48
+
49
+ def _warn_deprecated_facade(name: str, replacement: str) -> None:
50
+ """Emit a deprecation warning for legacy file-workflow facades."""
51
+ warnings.warn(
52
+ (
53
+ f"{name} is deprecated; use {replacement} "
54
+ "(thin MCP workflow C-016). Removal planned under Legacy Removal Scope (C-020)."
55
+ ),
56
+ DeprecationWarning,
57
+ stacklevel=3,
58
+ )
59
+
60
+
61
+ #: Commands that must use the adapter-native WebSocket command session
62
+ #: (``execute_command_unified``'s default WS dispatch) instead of the plain
63
+ #: synchronous ``execute_command`` round trip. Empty by default -- TODO
64
+ #: 210460c3 (bugs ba99fad9, 8306f6b2): opening a WS command session before
65
+ #: doing any work costs a fixed ~2-3s dispatch wait per call regardless of the
66
+ #: command's real cost, which is what made ordinary consumer->editor calls
67
+ #: (tens of ms over plain JSON-RPC) take seconds through this client. Mirrors
68
+ #: the identical fix already applied to the editor-side CA client for bug
69
+ #: bbc27d90 (``ai_editor/core/upstream/code_analysis_client.py``,
70
+ #: ``_WS_REQUIRED_COMMANDS``). A sync->queue conversion ack is still
71
+ #: recognized (in either envelope shape) and polled to a terminal result via
72
+ #: ``queue_get_job_status`` regardless of which path produced it, so
73
+ #: defaulting to the synchronous path never loses queue-handoff correctness.
74
+ #: Add a command name here, or pass ``force_ws=True`` for one call, only when
75
+ #: a command is proven to need the WS session itself.
76
+ _WS_REQUIRED_COMMANDS: FrozenSet[str] = frozenset()
77
+
78
+ _QUEUE_TERMINAL_STATUSES = frozenset(
79
+ {"completed", "failed", "error", "stopped", "deleted", "cancelled", "timeout"}
80
+ )
81
+ _QUEUE_FAILED_STATUSES = frozenset({"failed", "error"})
82
+ #: Default cadence for ``_poll_queued_job``'s own ``queue_get_job_status`` loop
83
+ #: when the caller does not pass ``poll_interval`` explicitly. Read from the
84
+ #: module namespace INSIDE the function body (never bound as a parameter
85
+ #: default -- a default is evaluated once, at function-definition time, so a
86
+ #: test's ``monkeypatch.setattr(module, "_QUEUE_POLL_INTERVAL_SECONDS", ...)``
87
+ #: run after import would silently do nothing; TODO 210460c3 / D3).
88
+ _QUEUE_POLL_INTERVAL_SECONDS = 0.2
89
+
90
+ _LEGACY_USE_CMD_ENDPOINT_MESSAGE = (
91
+ "use_cmd_endpoint is no longer supported (mcp-proxy-adapter >= 8.10.32)"
92
+ )
93
+
94
+
95
+ def _reject_legacy_kwargs(method_name: str, legacy: Dict[str, Any]) -> None:
96
+ """Loudly reject the removed ``use_cmd_endpoint`` kwarg -- never silently drop it.
97
+
98
+ ``use_cmd_endpoint`` was deleted from mcp-proxy-adapter's
99
+ ``execute_command``/``execute_command_unified`` in 8.10.32 (bug c940b82e);
100
+ this client no longer declares it as a real parameter anywhere. A caller
101
+ still passing ``use_cmd_endpoint=True`` asked for ``/cmd``-endpoint
102
+ routing that no longer exists on the installed adapter -- raise so the
103
+ request is never mistaken for having been honored. ``use_cmd_endpoint=False``
104
+ asked for the (already default) behaviour, so it is safe to allow through,
105
+ but is still deprecated -- warn once per call. Any other stray keyword is
106
+ a plain programming error against this method's real signature.
107
+ """
108
+ if "use_cmd_endpoint" in legacy:
109
+ value = legacy.pop("use_cmd_endpoint")
110
+ if value:
111
+ raise TypeError(_LEGACY_USE_CMD_ENDPOINT_MESSAGE)
112
+ warnings.warn(
113
+ _LEGACY_USE_CMD_ENDPOINT_MESSAGE, DeprecationWarning, stacklevel=3
114
+ )
115
+ if legacy:
116
+ unexpected = ", ".join(sorted(legacy))
117
+ raise TypeError(
118
+ f"{method_name}() got unexpected keyword argument(s): {unexpected}"
119
+ )
120
+
121
+
122
+ def _queued_job_id(response: Any) -> Optional[str]:
123
+ """Return a queued-ack job id from ``response``, else ``None``."""
124
+ if not isinstance(response, Mapping):
125
+ return None
126
+ for candidate in (response.get("job_id"), response.get("jobId")):
127
+ if isinstance(candidate, str) and candidate.strip():
128
+ return candidate.strip()
129
+ return None
130
+
131
+
132
+ def _is_queued_response(response: Any) -> bool:
133
+ """Recognize a sync->queue conversion ack in either known envelope shape.
134
+
135
+ Plain ``execute_command`` shape, verified against the deployed server
136
+ (see ``pipeline/live/client.py::_resolve_queued_ack``, bug 615495d0):
137
+ ``{"success": true, "job_id": ..., "status": "pending",
138
+ "queued_after_timeout": true, "store": "queuemgr",
139
+ "poll_with": "queue_get_job_status"}``. Adapter-native unified shape
140
+ (only ever produced by the explicit ``force_ws``/allow-list path):
141
+ ``{"mode": "queued", "job_id": ..., "status": ...}``.
142
+ """
143
+ if not isinstance(response, Mapping):
144
+ return False
145
+ job_id = _queued_job_id(response)
146
+ if not job_id:
147
+ return False
148
+ if str(response.get("mode") or "").strip().lower() == "queued":
149
+ return True
150
+ if response.get("queued_after_timeout"):
151
+ return True
152
+ if str(response.get("poll_with") or "").strip().lower() == "queue_get_job_status":
153
+ return True
154
+ status = str(response.get("status") or "").strip().lower()
155
+ return status in {"pending", "queued", "running"}
156
+
157
+
158
+ def _terminal_command_result(status_response: Any) -> Optional[Dict[str, Any]]:
159
+ """Unwrap a terminal ``queue_get_job_status`` reply down to the original
160
+ command's own result envelope -- nested at ``data.result.result`` --
161
+ exactly as a fast synchronous reply would have looked. ``None`` when the
162
+ terminal job carries no usable inner envelope (it died before producing
163
+ one)."""
164
+ data = status_response.get("data") if isinstance(status_response, Mapping) else None
165
+ inner = data.get("result") if isinstance(data, Mapping) else None
166
+ inner_result = inner.get("result") if isinstance(inner, Mapping) else None
167
+ return dict(inner_result) if isinstance(inner_result, Mapping) else None
168
+
169
+
170
+ class CodeAnalysisAsyncClient:
171
+ """Async client: domain commands via :meth:`call` / :meth:`call_unified`; full adapter API on :attr:`rpc`."""
172
+
173
+ __slots__ = (
174
+ "_rpc",
175
+ "_command_schema_cache",
176
+ "_commands_proxy",
177
+ "_verified_server_version",
178
+ )
179
+
180
+ def __init__(self, **jsonrpc_kwargs: Any) -> None:
181
+ """Same keyword arguments as ``JsonRpcClient`` (``protocol``, ``host``, ``port``, ``cert``, …)."""
182
+ self._rpc = JsonRpcClient(**jsonrpc_kwargs)
183
+ self._command_schema_cache: Dict[str, Dict[str, Any]] = {}
184
+ self._commands_proxy: Optional[ValidatedCommandsProxy] = None
185
+ # Set once the server has been confirmed to be REQUIRED_SERVER_VERSION.
186
+ # Never set to a mismatching value: a mismatch raises instead.
187
+ self._verified_server_version: Optional[str] = None
188
+
189
+ @classmethod
190
+ def from_jsonrpc_kwargs(cls, **kwargs: Any) -> CodeAnalysisAsyncClient:
191
+ """Alias for ``CodeAnalysisAsyncClient(**kwargs)``."""
192
+ return cls(**kwargs)
193
+
194
+ @classmethod
195
+ def from_adapter_settings(
196
+ cls,
197
+ settings: Mapping[str, Any],
198
+ *,
199
+ timeout: float | None = 60.0,
200
+ check_hostname: bool = False,
201
+ token_header: str | None = None,
202
+ token: str | None = None,
203
+ ) -> CodeAnalysisAsyncClient:
204
+ """Build from a dict like ``PipelineConfig.generate_adapter_client_settings()``."""
205
+ kwargs = adapter_settings_to_jsonrpc_kwargs(
206
+ settings,
207
+ timeout=timeout,
208
+ check_hostname=check_hostname,
209
+ token_header=token_header,
210
+ token=token,
211
+ )
212
+ return cls(**kwargs)
213
+
214
+ @classmethod
215
+ def from_server_config(
216
+ cls,
217
+ config: Mapping[str, Any],
218
+ *,
219
+ timeout: float | None = 60.0,
220
+ check_hostname: bool = False,
221
+ token_header: str | None = None,
222
+ token: str | None = None,
223
+ ) -> CodeAnalysisAsyncClient:
224
+ """Derive connection settings from a ai-editor server config object."""
225
+ settings = adapter_settings_from_server_config(config)
226
+ return cls.from_adapter_settings(
227
+ settings,
228
+ timeout=timeout,
229
+ check_hostname=check_hostname,
230
+ token_header=token_header,
231
+ token=token,
232
+ )
233
+
234
+ @classmethod
235
+ def from_server_config_path(
236
+ cls,
237
+ path: str | Path,
238
+ *,
239
+ timeout: float | None = 60.0,
240
+ check_hostname: bool = False,
241
+ token_header: str | None = None,
242
+ token: str | None = None,
243
+ ) -> CodeAnalysisAsyncClient:
244
+ """Load ``config.json`` and connect."""
245
+ return cls.from_server_config(
246
+ load_server_config(path),
247
+ timeout=timeout,
248
+ check_hostname=check_hostname,
249
+ token_header=token_header,
250
+ token=token,
251
+ )
252
+
253
+ @property
254
+ def rpc(self) -> JsonRpcClient:
255
+ """Underlying mcp-proxy-adapter client (queue, transfer, ``help``, ``execute_command``, …)."""
256
+ return self._rpc
257
+
258
+ @property
259
+ def commands(self) -> ValidatedCommandsProxy:
260
+ """Dynamic validated wrappers: schema is loaded from the server via ``help`` (cached)."""
261
+ if self._commands_proxy is None:
262
+ self._commands_proxy = ValidatedCommandsProxy(self)
263
+ return self._commands_proxy
264
+
265
+ def clear_command_schema_cache(self) -> None:
266
+ """Drop cached command schemas (after ``reload`` or when server definitions change)."""
267
+ self._command_schema_cache.clear()
268
+
269
+ async def ensure_server_version(self, command: str) -> None:
270
+ """Refuse to dispatch ``command`` to a server of a different version.
271
+
272
+ Runs before every call except the exempt ones (``health``, ``info``),
273
+ which stay usable across a mismatch precisely so an operator can see it.
274
+ The server's version is learned once per client instance from
275
+ ``health`` and then cached; a mismatch raises
276
+ :class:`~ai_editor_client.exceptions.ServerVersionMismatch` and nothing
277
+ is executed on the server.
278
+
279
+ The rule is exact equality (see
280
+ :mod:`ai_editor_client.server_version`). Failure is closed: if the probe
281
+ does not yield a usable version, the call is refused rather than sent.
282
+ """
283
+ if is_version_exempt(command):
284
+ return
285
+ if self._verified_server_version == REQUIRED_SERVER_VERSION:
286
+ return
287
+ envelope = await self._rpc.execute_command(
288
+ SERVER_VERSION_PROBE_COMMAND,
289
+ {},
290
+ )
291
+ reported = server_version_from_health(envelope)
292
+ assert_server_version_matches(reported, command=command)
293
+ self._verified_server_version = reported
294
+
295
+ @property
296
+ def file_sessions(self) -> FileSessionClient:
297
+ """Session workflow: ``session_*``, ``subordinate_session_*``, transfer, advisory locks."""
298
+ _warn_deprecated_facade(
299
+ "CodeAnalysisAsyncClient.file_sessions",
300
+ "CodeAnalysisAsyncClient.universal_files",
301
+ )
302
+ return FileSessionClient(self)
303
+
304
+ @property
305
+ def universal_files(self) -> UniversalFileClient:
306
+ """Sole supported file-workflow facade for MCP Workflow Surface (C-016).
307
+
308
+ Use ``universal_file_*`` commands via :class:`~ai_editor_client.universal_file.UniversalFileClient`.
309
+ """
310
+ return UniversalFileClient(self)
311
+
312
+ @property
313
+ def editor_files(self) -> EditorFileClient:
314
+ """Editor workflow via transfer (remote client staging paths)."""
315
+ _warn_deprecated_facade(
316
+ "CodeAnalysisAsyncClient.editor_files",
317
+ "CodeAnalysisAsyncClient.universal_files",
318
+ )
319
+ return EditorFileClient(self.file_sessions)
320
+
321
+ async def get_command_schema(
322
+ self, command: str, *, refresh: bool = False
323
+ ) -> Dict[str, Any]:
324
+ """Fetch input JSON schema for ``command`` using server ``help`` (with in-memory cache)."""
325
+ if not refresh and command in self._command_schema_cache:
326
+ return self._command_schema_cache[command]
327
+ schema: Dict[str, Any] = await fetch_command_schema_from_server(self._rpc, command)
328
+ self._command_schema_cache[command] = schema
329
+ return schema
330
+
331
+ async def call_validated(
332
+ self,
333
+ command: str,
334
+ params: Optional[Dict[str, Any]] = None,
335
+ *,
336
+ refresh_schema: bool = False,
337
+ **_legacy: Any,
338
+ ) -> Dict[str, Any]:
339
+ """``help`` → schema on server, shallow local validation, then ``execute_command``.
340
+
341
+ No longer accepts ``use_cmd_endpoint`` (removed from the adapter in
342
+ 8.10.32, bug c940b82e); passing it raises or warns via ``**_legacy``,
343
+ see :func:`_reject_legacy_kwargs`.
344
+ """
345
+ _reject_legacy_kwargs("call_validated", _legacy)
346
+ await self.ensure_server_version(command)
347
+ schema = await self.get_command_schema(command, refresh=refresh_schema)
348
+ merged = dict(params or {})
349
+ prepared = prepare_params_for_schema(merged, schema)
350
+ validate_params_against_schema(prepared, schema, command_name=command)
351
+ return await self._rpc.execute_command(command, prepared)
352
+
353
+ async def call_unified_validated(
354
+ self,
355
+ command: str,
356
+ params: Optional[Dict[str, Any]] = None,
357
+ *,
358
+ refresh_schema: bool = False,
359
+ expect_queue: Optional[bool] = None,
360
+ auto_poll: bool = True,
361
+ poll_interval: float = 1.0,
362
+ timeout: Optional[float] = None,
363
+ status_hook: Optional[Callable[[Dict[str, Any]], Any]] = None,
364
+ force_ws: bool = False,
365
+ **_legacy: Any,
366
+ ) -> Dict[str, Any]:
367
+ """Schema-validated unified call, sync-first (TODO 210460c3).
368
+
369
+ Like :meth:`call_validated`, but with full support for queued jobs and
370
+ their lifecycle (``auto_poll``, ``status_hook``, ``timeout``). Defaults
371
+ to the sync path (``execute_command``) for performance; pass
372
+ ``force_ws=True`` to use ``execute_command_unified`` (WS command
373
+ session) instead.
374
+
375
+ No longer accepts ``use_cmd_endpoint`` (removed from the adapter in
376
+ 8.10.32, bug c940b82e); passing it raises or warns via ``**_legacy``,
377
+ see :func:`_reject_legacy_kwargs`.
378
+ """
379
+ _reject_legacy_kwargs("call_unified_validated", _legacy)
380
+ await self.ensure_server_version(command)
381
+ schema = await self.get_command_schema(command, refresh=refresh_schema)
382
+ merged = dict(params or {})
383
+ prepared = prepare_params_for_schema(merged, schema)
384
+ validate_params_against_schema(prepared, schema, command_name=command)
385
+
386
+ # Sync-first path: use execute_command by default, except when
387
+ # force_ws=True or the command is in _WS_REQUIRED_COMMANDS
388
+ # (TODO 210460c3: bugs ba99fad9, 8306f6b2). Either way the return
389
+ # value MATCHES call_unified's own envelope contract verbatim (see
390
+ # its docstring): {"mode": "immediate"|"queued", "command": ...,
391
+ # "queued": bool, "result": ...} plus job_id/status/raw_status when
392
+ # queued -- call_unified_validated adds schema validation on top,
393
+ # nothing else.
394
+ if force_ws or command in _WS_REQUIRED_COMMANDS:
395
+ ws_envelope: Dict[str, Any] = await self._rpc.execute_command_unified(
396
+ command,
397
+ prepared,
398
+ expect_queue=expect_queue,
399
+ auto_poll=auto_poll,
400
+ poll_interval=poll_interval,
401
+ timeout=timeout,
402
+ status_hook=status_hook,
403
+ )
404
+ return ws_envelope
405
+
406
+ # Sync path (default): use plain execute_command, poll queued jobs
407
+ # manually via _poll_queued_job if they materialize.
408
+ command_result = await self._rpc.execute_command(command, prepared)
409
+ if status_hook is not None:
410
+ hook_result = status_hook(
411
+ command_result if isinstance(command_result, dict) else {}
412
+ )
413
+ if asyncio.iscoroutine(hook_result):
414
+ await hook_result
415
+
416
+ job_id = (
417
+ _queued_job_id(command_result)
418
+ if _is_queued_response(command_result)
419
+ else None
420
+ )
421
+
422
+ if expect_queue is False:
423
+ return {
424
+ "mode": "immediate",
425
+ "command": command,
426
+ "result": command_result,
427
+ "queued": False,
428
+ }
429
+ if expect_queue is True and job_id is None:
430
+ raise RuntimeError(
431
+ f"command {command!r} was expected to queue but the server "
432
+ "answered synchronously"
433
+ )
434
+ if job_id is None:
435
+ return {
436
+ "mode": "immediate",
437
+ "command": command,
438
+ "result": command_result,
439
+ "queued": False,
440
+ }
441
+
442
+ initial_status = str(command_result.get("status") or "pending").strip().lower()
443
+ if not auto_poll:
444
+ return {
445
+ "mode": "queued",
446
+ "command": command,
447
+ "queued": True,
448
+ "job_id": job_id,
449
+ "status": initial_status,
450
+ "raw_status": command_result,
451
+ "result": command_result,
452
+ }
453
+
454
+ result, status, raw_status = await self._poll_queued_job(
455
+ command,
456
+ job_id,
457
+ timeout=timeout if timeout is not None else WS_JOB_WAIT_TIMEOUT,
458
+ poll_interval=poll_interval,
459
+ status_hook=status_hook,
460
+ )
461
+ return {
462
+ "mode": "queued",
463
+ "command": command,
464
+ "queued": True,
465
+ "job_id": job_id,
466
+ "status": status,
467
+ "raw_status": raw_status,
468
+ "result": result,
469
+ }
470
+
471
+ async def _poll_queued_job(
472
+ self,
473
+ command: str,
474
+ job_id: str,
475
+ *,
476
+ timeout: Optional[float],
477
+ poll_interval: Optional[float] = None,
478
+ status_hook: Optional[Callable[[Dict[str, Any]], Any]] = None,
479
+ ) -> Tuple[Dict[str, Any], str, Dict[str, Any]]:
480
+ """Poll ``queue_get_job_status`` for ``job_id`` to a terminal status.
481
+
482
+ Returns ``(result, status, raw_status)``: ``result`` is the original
483
+ command's own result envelope (its real success -- never a bare
484
+ queued acknowledgement), ``status`` is the terminal queue status
485
+ (``"timeout"`` when the deadline passes first), ``raw_status`` is the
486
+ last ``queue_get_job_status`` response verbatim (mirrors the
487
+ adapter's WS-path ``raw_status``/terminal-event field). ``timeout`` of
488
+ ``None`` or ``<= 0`` waits without a deadline, matching the adapter's
489
+ own ``execute_command_unified`` contract ("0 = no timeout").
490
+
491
+ ``poll_interval`` of ``None`` (the default) reads
492
+ ``_QUEUE_POLL_INTERVAL_SECONDS`` from the module namespace at call
493
+ time -- not as a bound parameter default -- so a test's
494
+ ``monkeypatch.setattr`` on that constant actually takes effect
495
+ (TODO 210460c3 / D3).
496
+
497
+ A terminal ``failed``/``error`` status RAISES ``RuntimeError``
498
+ carrying the job's own error, exactly as the adapter's legacy WS
499
+ queue-wait path does for a ``job_failed`` event
500
+ (``command_api.py``: ``if ev == "job_failed": raise RuntimeError(...)``).
501
+ """
502
+ interval = (
503
+ poll_interval if poll_interval is not None else _QUEUE_POLL_INTERVAL_SECONDS
504
+ )
505
+ deadline = None if not timeout or timeout <= 0 else time.monotonic() + timeout
506
+ status_response: Dict[str, Any] = {}
507
+ status = "pending"
508
+ while True:
509
+ status_response = await self._rpc.execute_command(
510
+ "queue_get_job_status", {"job_id": job_id}
511
+ )
512
+ if status_hook is not None:
513
+ hook_result = status_hook(
514
+ status_response if isinstance(status_response, dict) else {}
515
+ )
516
+ if asyncio.iscoroutine(hook_result):
517
+ await hook_result
518
+ data = (
519
+ status_response.get("data")
520
+ if isinstance(status_response, Mapping)
521
+ else None
522
+ )
523
+ status = str((data or {}).get("status") or "").strip().lower() or "unknown"
524
+ if status in _QUEUE_TERMINAL_STATUSES:
525
+ break
526
+ if deadline is not None and time.monotonic() >= deadline:
527
+ status = "timeout"
528
+ break
529
+ await asyncio.sleep(interval)
530
+
531
+ data = (
532
+ status_response.get("data")
533
+ if isinstance(status_response, Mapping)
534
+ else None
535
+ )
536
+
537
+ if status in _QUEUE_FAILED_STATUSES:
538
+ error_obj = data.get("error") if isinstance(data, Mapping) else None
539
+ message = (
540
+ (error_obj.get("message") if isinstance(error_obj, Mapping) else None)
541
+ or f"queued command {command!r} (job_id={job_id}) ended with status {status!r}"
542
+ )
543
+ raise RuntimeError(
544
+ f"Queued command {command!r} failed (job_id={job_id}): {message}"
545
+ )
546
+
547
+ if status == "timeout":
548
+ return (
549
+ {
550
+ "success": False,
551
+ "error": {
552
+ "code": "QUEUED_ACK_POLL_TIMEOUT",
553
+ "message": (
554
+ f"command {command!r} (job_id={job_id}) did not reach a "
555
+ f"terminal queue status within {timeout}s"
556
+ ),
557
+ },
558
+ },
559
+ status,
560
+ status_response,
561
+ )
562
+ result = _terminal_command_result(status_response)
563
+ if result is None:
564
+ error_obj = data.get("error") if isinstance(data, Mapping) else None
565
+ message = (
566
+ (error_obj.get("message") if isinstance(error_obj, Mapping) else None)
567
+ or f"queued command {command!r} ended with status {status!r}, no inner result"
568
+ )
569
+ result = {
570
+ "success": False,
571
+ "error": {"code": "QUEUED_ACK_NO_INNER_RESULT", "message": message},
572
+ }
573
+ return result, status, status_response
574
+
575
+ async def call(
576
+ self,
577
+ command: str,
578
+ params: Optional[Dict[str, Any]] = None,
579
+ *,
580
+ force_ws: bool = False,
581
+ timeout: Optional[float] = None,
582
+ **_legacy: Any,
583
+ ) -> Dict[str, Any]:
584
+ """Run any registered server command (sync completion).
585
+
586
+ Defaults to plain synchronous ``execute_command`` (TODO 210460c3):
587
+ the adapter-native WS command session opened by
588
+ ``execute_command_unified`` costs a fixed ~2-3s dispatch wait per
589
+ call regardless of the command's real work (bugs ba99fad9,
590
+ 8306f6b2). Only a command on ``_WS_REQUIRED_COMMANDS`` (empty by
591
+ default), or an explicit ``force_ws=True`` for one call, goes
592
+ through that path instead. Either way, a sync->queue conversion ack
593
+ is polled to a terminal result via ``queue_get_job_status`` before
594
+ returning, so the caller always sees the command's REAL outcome --
595
+ both paths unwrap to the same shape (the command's own result,
596
+ never the ``mode``/``queued`` envelope; see :meth:`call_unified` for
597
+ that envelope). A queued job that ends ``failed``/``error`` raises
598
+ ``RuntimeError``.
599
+
600
+ ``timeout`` bounds the wait for a queued job's terminal status (both
601
+ the sync poll loop and, when ``force_ws``/allow-listed, the adapter's
602
+ own WS wait); ``None`` defaults to ``WS_JOB_WAIT_TIMEOUT`` -- no
603
+ hard-coded budget (TODO 210460c3 / D3).
604
+
605
+ No longer accepts ``use_cmd_endpoint`` (removed from the adapter in
606
+ 8.10.32, bug c940b82e); passing it raises or warns via ``**_legacy``,
607
+ see :func:`_reject_legacy_kwargs`.
608
+ """
609
+ _reject_legacy_kwargs("call", _legacy)
610
+ await self.ensure_server_version(command)
611
+ payload = params or {}
612
+ if force_ws or command in _WS_REQUIRED_COMMANDS:
613
+ unified = await self._rpc.execute_command_unified(
614
+ command,
615
+ payload,
616
+ timeout=timeout,
617
+ )
618
+ if isinstance(unified, Mapping) and "result" in unified:
619
+ unified_result: Dict[str, Any] = unified["result"]
620
+ return unified_result
621
+ unified_whole: Dict[str, Any] = unified
622
+ return unified_whole
623
+
624
+ response = await self._rpc.execute_command(command, payload)
625
+ job_id = _queued_job_id(response) if _is_queued_response(response) else None
626
+ if job_id is None:
627
+ return response
628
+ result, _status, _raw_status = await self._poll_queued_job(
629
+ command,
630
+ job_id,
631
+ timeout=timeout if timeout is not None else WS_JOB_WAIT_TIMEOUT,
632
+ )
633
+ return result
634
+
635
+ async def call_unified(
636
+ self,
637
+ command: str,
638
+ params: Optional[Dict[str, Any]] = None,
639
+ *,
640
+ expect_queue: Optional[bool] = None,
641
+ auto_poll: bool = True,
642
+ poll_interval: float = 1.0,
643
+ timeout: Optional[float] = None,
644
+ status_hook: Optional[Callable[[Dict[str, Any]], Any]] = None,
645
+ force_ws: bool = False,
646
+ **_legacy: Any,
647
+ ) -> Dict[str, Any]:
648
+ """Run a command with queue detection and polling.
649
+
650
+ Defaults to plain synchronous ``execute_command`` plus hand-rolled
651
+ ``queue_get_job_status`` polling (TODO 210460c3) instead of always
652
+ opening the adapter-native WS command session via
653
+ ``execute_command_unified``, which costs a fixed ~2-3s dispatch wait
654
+ per call regardless of the command's real work (bugs ba99fad9,
655
+ 8306f6b2). Only a command on ``_WS_REQUIRED_COMMANDS`` (empty by
656
+ default), or an explicit ``force_ws=True`` for one call, uses the WS
657
+ path -- in which case this method returns whatever the adapter's own
658
+ ``execute_command_unified`` returns, unmodified.
659
+
660
+ The returned envelope MATCHES the adapter's own
661
+ ``execute_command_unified`` contract that consumers already rely on
662
+ (``command_api.py``):
663
+
664
+ * immediate: ``{"mode": "immediate", "command": command,
665
+ "result": <data>, "queued": False}``.
666
+ * queued, not polled (``auto_poll=False``): ``{"mode": "queued",
667
+ "command": command, "queued": True, "job_id": ..., "status": ...,
668
+ "raw_status": ..., "result": <the queued ack itself>}``.
669
+ * queued, polled to a terminal result: ``{"mode": "queued",
670
+ "command": command, "queued": True, "job_id": ..., "status": ...,
671
+ "raw_status": ..., "result": <unwrapped data>}``.
672
+ * ``expect_queue=False`` with a job_id present: an immediate-mode
673
+ envelope wrapping the raw (un-polled) response, exactly as the
674
+ adapter does.
675
+ * a queued job that ends ``failed``/``error`` RAISES ``RuntimeError``
676
+ carrying the job's own error, as the adapter's WS path does for a
677
+ ``job_failed`` terminal event.
678
+
679
+ ``status_hook`` (sync or async) receives the initial ``execute_command``
680
+ response, then each ``queue_get_job_status`` poll envelope while
681
+ waiting for a terminal status.
682
+
683
+ No longer accepts ``use_cmd_endpoint`` (removed from the adapter in
684
+ 8.10.32, bug c940b82e); passing it raises or warns via ``**_legacy``,
685
+ see :func:`_reject_legacy_kwargs`.
686
+ """
687
+ _reject_legacy_kwargs("call_unified", _legacy)
688
+ await self.ensure_server_version(command)
689
+ payload = params or {}
690
+ if force_ws or command in _WS_REQUIRED_COMMANDS:
691
+ ws_unified: Dict[str, Any] = await self._rpc.execute_command_unified(
692
+ command,
693
+ payload,
694
+ expect_queue=expect_queue,
695
+ auto_poll=auto_poll,
696
+ poll_interval=poll_interval,
697
+ timeout=timeout,
698
+ status_hook=status_hook,
699
+ )
700
+ return ws_unified
701
+
702
+ command_result = await self._rpc.execute_command(command, payload)
703
+ if status_hook is not None:
704
+ hook_result = status_hook(
705
+ command_result if isinstance(command_result, dict) else {}
706
+ )
707
+ if asyncio.iscoroutine(hook_result):
708
+ await hook_result
709
+
710
+ job_id = (
711
+ _queued_job_id(command_result)
712
+ if _is_queued_response(command_result)
713
+ else None
714
+ )
715
+
716
+ if expect_queue is False:
717
+ return {
718
+ "mode": "immediate",
719
+ "command": command,
720
+ "result": command_result,
721
+ "queued": False,
722
+ }
723
+ if expect_queue is True and job_id is None:
724
+ raise RuntimeError(
725
+ f"command {command!r} was expected to queue but the server "
726
+ "answered synchronously"
727
+ )
728
+ if job_id is None:
729
+ return {
730
+ "mode": "immediate",
731
+ "command": command,
732
+ "result": command_result,
733
+ "queued": False,
734
+ }
735
+
736
+ initial_status = str(command_result.get("status") or "pending").strip().lower()
737
+ if not auto_poll:
738
+ return {
739
+ "mode": "queued",
740
+ "command": command,
741
+ "queued": True,
742
+ "job_id": job_id,
743
+ "status": initial_status,
744
+ "raw_status": command_result,
745
+ "result": command_result,
746
+ }
747
+
748
+ result, status, raw_status = await self._poll_queued_job(
749
+ command,
750
+ job_id,
751
+ timeout=timeout if timeout is not None else WS_JOB_WAIT_TIMEOUT,
752
+ poll_interval=poll_interval,
753
+ status_hook=status_hook,
754
+ )
755
+ return {
756
+ "mode": "queued",
757
+ "command": command,
758
+ "queued": True,
759
+ "job_id": job_id,
760
+ "status": status,
761
+ "raw_status": raw_status,
762
+ "result": result,
763
+ }
764
+
765
+ async def close(self) -> None:
766
+ await self._rpc.close()
767
+
768
+ async def __aenter__(self) -> CodeAnalysisAsyncClient:
769
+ return self
770
+
771
+ async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
772
+ await self.close()