plotroom 0.1.0__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.
- plotroom/__init__.py +0 -0
- plotroom/__main__.py +8 -0
- plotroom/_secret_file.py +8 -0
- plotroom/adapters/__init__.py +0 -0
- plotroom/adapters/claude_desktop.py +219 -0
- plotroom/adapters/embedding_http.py +175 -0
- plotroom/adapters/github/__init__.py +337 -0
- plotroom/adapters/github/app_credential.py +209 -0
- plotroom/adapters/github/ci.py +738 -0
- plotroom/adapters/github/commit_statuses.py +63 -0
- plotroom/adapters/github/deployments.py +213 -0
- plotroom/adapters/github/details.py +867 -0
- plotroom/adapters/github/issue_details.py +368 -0
- plotroom/adapters/github/junit.py +210 -0
- plotroom/adapters/github/junit_xml.py +162 -0
- plotroom/adapters/github/kodus_review.py +347 -0
- plotroom/adapters/github/pr_details.py +192 -0
- plotroom/adapters/github/pull_comparison.py +108 -0
- plotroom/adapters/github/read.py +530 -0
- plotroom/adapters/github/ticket_tree.py +336 -0
- plotroom/adapters/mcp/__init__.py +5 -0
- plotroom/adapters/mcp/proxy.py +722 -0
- plotroom/adapters/mcp/server.py +931 -0
- plotroom/adapters/openrouter.py +151 -0
- plotroom/adapters/store_sqlite/__init__.py +6 -0
- plotroom/adapters/store_sqlite/actions_sql.py +148 -0
- plotroom/adapters/store_sqlite/asks_sql.py +153 -0
- plotroom/adapters/store_sqlite/backfill_sql.py +138 -0
- plotroom/adapters/store_sqlite/budgets_sql.py +102 -0
- plotroom/adapters/store_sqlite/checklists_sql.py +77 -0
- plotroom/adapters/store_sqlite/claims_sql.py +54 -0
- plotroom/adapters/store_sqlite/embedding_sql.py +275 -0
- plotroom/adapters/store_sqlite/github_sql.py +331 -0
- plotroom/adapters/store_sqlite/goals_sql.py +57 -0
- plotroom/adapters/store_sqlite/human_queue_sql.py +60 -0
- plotroom/adapters/store_sqlite/items_sql.py +129 -0
- plotroom/adapters/store_sqlite/lanes_sql.py +85 -0
- plotroom/adapters/store_sqlite/ledger_sql.py +506 -0
- plotroom/adapters/store_sqlite/migrate.py +194 -0
- plotroom/adapters/store_sqlite/migrations/env.py +36 -0
- plotroom/adapters/store_sqlite/migrations/script.py.mako +19 -0
- plotroom/adapters/store_sqlite/migrations/versions/0001_project_meta.py +23 -0
- plotroom/adapters/store_sqlite/migrations/versions/0002_event_log.py +40 -0
- plotroom/adapters/store_sqlite/migrations/versions/0003_next_items.py +49 -0
- plotroom/adapters/store_sqlite/migrations/versions/0004_actions.py +28 -0
- plotroom/adapters/store_sqlite/migrations/versions/0005_lanes.py +36 -0
- plotroom/adapters/store_sqlite/migrations/versions/0006_work_items.py +22 -0
- plotroom/adapters/store_sqlite/migrations/versions/0007_item_changes.py +33 -0
- plotroom/adapters/store_sqlite/migrations/versions/0008_claude_turn_aliases.py +30 -0
- plotroom/adapters/store_sqlite/migrations/versions/0009_github_projection.py +38 -0
- plotroom/adapters/store_sqlite/migrations/versions/0010_github_pull_freshness.py +37 -0
- plotroom/adapters/store_sqlite/migrations/versions/0011_github_resources.py +27 -0
- plotroom/adapters/store_sqlite/migrations/versions/0012_local_triggers_outbox.py +80 -0
- plotroom/adapters/store_sqlite/migrations/versions/0013_lane_claims.py +22 -0
- plotroom/adapters/store_sqlite/migrations/versions/0015_recurring_triggers.py +45 -0
- plotroom/adapters/store_sqlite/migrations/versions/0016_merge_controller.py +28 -0
- plotroom/adapters/store_sqlite/migrations/versions/0017_lane_checklists.py +36 -0
- plotroom/adapters/store_sqlite/migrations/versions/0018_guardrails.py +33 -0
- plotroom/adapters/store_sqlite/migrations/versions/0019_clerk_import_metadata.py +16 -0
- plotroom/adapters/store_sqlite/migrations/versions/0020_search.py +30 -0
- plotroom/adapters/store_sqlite/migrations/versions/0021_human_queue.py +46 -0
- plotroom/adapters/store_sqlite/migrations/versions/0022_search_records.py +77 -0
- plotroom/adapters/store_sqlite/migrations/versions/0023_operator_goals.py +25 -0
- plotroom/adapters/store_sqlite/migrations/versions/0024_embedding_rejections.py +36 -0
- plotroom/adapters/store_sqlite/outbox_sql.py +78 -0
- plotroom/adapters/store_sqlite/routes_sql.py +26 -0
- plotroom/adapters/store_sqlite/search_sql.py +116 -0
- plotroom/adapters/store_sqlite/store.py +623 -0
- plotroom/adapters/store_sqlite/triggers_sql.py +111 -0
- plotroom/adapters/store_sqlite/work_items_sql.py +36 -0
- plotroom/adapters/switchboard.py +152 -0
- plotroom/adapters/usage_fixture.py +11 -0
- plotroom/adapters/work_items_bmad.py +256 -0
- plotroom/adapters/work_items_github_issues.py +323 -0
- plotroom/app/__init__.py +0 -0
- plotroom/app/bridge.py +162 -0
- plotroom/app/clerk_import.py +349 -0
- plotroom/app/cli.py +290 -0
- plotroom/app/clock.py +12 -0
- plotroom/app/config.py +984 -0
- plotroom/app/daemon_start.py +453 -0
- plotroom/app/lock.py +77 -0
- plotroom/app/logging.py +93 -0
- plotroom/app/portfile.py +218 -0
- plotroom/app/runtime.py +518 -0
- plotroom/app/serve.py +671 -0
- plotroom/app/session_intake.py +51 -0
- plotroom/app/sqlite_floor.py +35 -0
- plotroom/app/tokens.py +265 -0
- plotroom/core/__init__.py +0 -0
- plotroom/core/actions.py +67 -0
- plotroom/core/ask_checks.py +124 -0
- plotroom/core/asks.py +123 -0
- plotroom/core/branch_updates.py +207 -0
- plotroom/core/bridge.py +112 -0
- plotroom/core/briefs.py +83 -0
- plotroom/core/budgets.py +182 -0
- plotroom/core/catalog.py +464 -0
- plotroom/core/checklists.py +151 -0
- plotroom/core/claims.py +296 -0
- plotroom/core/clerk_import.py +379 -0
- plotroom/core/commands.py +85 -0
- plotroom/core/deploy_window.py +21 -0
- plotroom/core/envelope.py +20 -0
- plotroom/core/events.py +227 -0
- plotroom/core/github.py +306 -0
- plotroom/core/github_projection.py +310 -0
- plotroom/core/goal_language.py +374 -0
- plotroom/core/goal_projection.py +146 -0
- plotroom/core/human_queue.py +119 -0
- plotroom/core/intake.py +106 -0
- plotroom/core/kodus_review.py +53 -0
- plotroom/core/lanes.py +281 -0
- plotroom/core/ledger.py +808 -0
- plotroom/core/merge_controller.py +344 -0
- plotroom/core/merge_flakes.py +422 -0
- plotroom/core/merge_gate.py +724 -0
- plotroom/core/merge_lane.py +70 -0
- plotroom/core/merge_overlap.py +76 -0
- plotroom/core/next_items.py +60 -0
- plotroom/core/operator_goals.py +103 -0
- plotroom/core/outbox.py +70 -0
- plotroom/core/pull_overlaps.py +152 -0
- plotroom/core/reports.py +62 -0
- plotroom/core/roles.py +100 -0
- plotroom/core/routing.py +55 -0
- plotroom/core/run_reports.py +53 -0
- plotroom/core/search.py +266 -0
- plotroom/core/search_sources.py +94 -0
- plotroom/core/snapshot.py +204 -0
- plotroom/core/trigger_actions.py +89 -0
- plotroom/core/triggers.py +550 -0
- plotroom/core/unit_of_work.py +541 -0
- plotroom/core/watchers.py +35 -0
- plotroom/core/work_items.py +23 -0
- plotroom/core/writer.py +164 -0
- plotroom/ports/__init__.py +6 -0
- plotroom/ports/clock.py +12 -0
- plotroom/ports/github_write.py +72 -0
- plotroom/ports/search.py +197 -0
- plotroom/ports/session_reader.py +23 -0
- plotroom/ports/store.py +323 -0
- plotroom/ports/usage_meter.py +35 -0
- plotroom/ports/work_items.py +22 -0
- plotroom/py.typed +0 -0
- plotroom-0.1.0.dist-info/METADATA +230 -0
- plotroom-0.1.0.dist-info/RECORD +150 -0
- plotroom-0.1.0.dist-info/WHEEL +4 -0
- plotroom-0.1.0.dist-info/entry_points.txt +2 -0
- plotroom-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,722 @@
|
|
|
1
|
+
"""The stdio proxy behind ``plotroom connect --stdio`` (AD-7).
|
|
2
|
+
|
|
3
|
+
It forwards each JSON-RPC message body unchanged as one HTTP POST to the daemon and derives the
|
|
4
|
+
HTTP envelope from the message: the protocol-version, method and name headers in the 2026 era, and
|
|
5
|
+
the negotiated version after ``initialize`` in the handshake era. Calls run concurrently and SSE
|
|
6
|
+
responses are relayed as they arrive. Stdout carries protocol only; logs go to stderr.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import fcntl
|
|
13
|
+
import ipaddress
|
|
14
|
+
import json
|
|
15
|
+
import logging
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
import socket
|
|
19
|
+
import ssl
|
|
20
|
+
import stat
|
|
21
|
+
import struct
|
|
22
|
+
import sys
|
|
23
|
+
from collections.abc import AsyncGenerator, Awaitable, Callable, Generator, Mapping
|
|
24
|
+
from contextlib import aclosing, asynccontextmanager, contextmanager
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
from typing import Any, BinaryIO, Protocol, cast
|
|
27
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
28
|
+
|
|
29
|
+
import httpx
|
|
30
|
+
from mcp.shared.inbound import NAME_BEARING_METHODS, encode_header_value
|
|
31
|
+
from mcp_types import PROTOCOL_VERSION_META_KEY
|
|
32
|
+
|
|
33
|
+
log = logging.getLogger("plotroom.proxy")
|
|
34
|
+
|
|
35
|
+
JSONRPC_INTERNAL_ERROR = -32603
|
|
36
|
+
LISTEN_METHOD = "subscriptions/listen" # 2026 era: a request whose stream ends only when canceled
|
|
37
|
+
DEFAULT_MAX_PENDING = 256
|
|
38
|
+
_PARTIAL_LINE_DRAIN_SECONDS = 1.0
|
|
39
|
+
_BASE_HEADERS = {
|
|
40
|
+
"content-type": "application/json",
|
|
41
|
+
"accept": "application/json, text/event-stream",
|
|
42
|
+
}
|
|
43
|
+
_BEARER = re.compile(r"[A-Za-z0-9._~+/-]+=*")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class UpstreamStartError(Exception):
|
|
47
|
+
"""The server the proxy fronts is not running and could not be started; the text says why."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class _PeerStream(Protocol):
|
|
51
|
+
def get_extra_info(self, info: str) -> socket.socket | None: ...
|
|
52
|
+
|
|
53
|
+
async def aclose(self) -> None: ...
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _peer_pid(sock: socket.socket) -> int:
|
|
57
|
+
if sys.platform == "darwin":
|
|
58
|
+
# macOS sys/un.h: SOL_LOCAL = 0, LOCAL_PEERPID = 2. Python exports neither.
|
|
59
|
+
return sock.getsockopt(0, 2)
|
|
60
|
+
if sys.platform == "linux":
|
|
61
|
+
credentials = struct.Struct("iII") # struct ucred: pid, uid, gid
|
|
62
|
+
return credentials.unpack(
|
|
63
|
+
sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, credentials.size)
|
|
64
|
+
)[0]
|
|
65
|
+
raise OSError("Unix socket peer PID verification is unavailable on this platform")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class LocalEndpoint:
|
|
70
|
+
"""The lock owner's published endpoint, verified on each Unix connection before HTTP writes."""
|
|
71
|
+
|
|
72
|
+
url: str
|
|
73
|
+
host: str = field(compare=False) # Readiness may choose another Host on the same listener.
|
|
74
|
+
socket_path: str
|
|
75
|
+
pid: int
|
|
76
|
+
|
|
77
|
+
@asynccontextmanager
|
|
78
|
+
async def stream(
|
|
79
|
+
self, method: str, *, content: bytes | None = None, headers: Mapping[str, str] | None = None
|
|
80
|
+
) -> AsyncGenerator[httpx.Response]:
|
|
81
|
+
verified = False
|
|
82
|
+
|
|
83
|
+
async def verify(event: str, info: dict[str, Any]) -> None:
|
|
84
|
+
nonlocal verified
|
|
85
|
+
if event == "connection.connect_unix_socket.complete":
|
|
86
|
+
peer = cast(_PeerStream, info["return_value"])
|
|
87
|
+
try:
|
|
88
|
+
sock = peer.get_extra_info("socket")
|
|
89
|
+
verified = sock is not None and _peer_pid(sock) == self.pid
|
|
90
|
+
except OSError:
|
|
91
|
+
verified = False
|
|
92
|
+
if not verified:
|
|
93
|
+
await peer.aclose()
|
|
94
|
+
raise httpx.ConnectError("local daemon identity could not be verified")
|
|
95
|
+
elif event == "http11.send_request_headers.started" and not verified:
|
|
96
|
+
raise httpx.ConnectError("local daemon identity could not be verified")
|
|
97
|
+
|
|
98
|
+
# One request per client. Use a fresh kernel peer check for readiness, dispatch, and retry.
|
|
99
|
+
transport = httpx.AsyncHTTPTransport(uds=self.socket_path, trust_env=False)
|
|
100
|
+
async with (
|
|
101
|
+
httpx.AsyncClient(
|
|
102
|
+
transport=transport, timeout=httpx.Timeout(10.0, read=None), trust_env=False
|
|
103
|
+
) as http,
|
|
104
|
+
http.stream(
|
|
105
|
+
method,
|
|
106
|
+
self.url,
|
|
107
|
+
content=content,
|
|
108
|
+
headers={**(headers or {}), "host": self.host},
|
|
109
|
+
extensions={"trace": verify},
|
|
110
|
+
) as response,
|
|
111
|
+
):
|
|
112
|
+
yield response
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
type _Endpoint = str | LocalEndpoint
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def envelope_headers(message: Mapping[str, Any], negotiated: str | None) -> dict[str, str]:
|
|
119
|
+
"""The HTTP headers for one outgoing message.
|
|
120
|
+
|
|
121
|
+
A message whose ``params._meta`` carries a protocol version is in the 2026 era: the headers
|
|
122
|
+
mirror it. Otherwise it is in the handshake era: ``initialize`` carries no version header, and
|
|
123
|
+
every later message carries the version that ``initialize`` negotiated.
|
|
124
|
+
"""
|
|
125
|
+
headers = dict(_BASE_HEADERS)
|
|
126
|
+
params: Any = message.get("params")
|
|
127
|
+
meta: Any = params.get("_meta") if isinstance(params, dict) else None # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
|
|
128
|
+
version: Any = meta.get(PROTOCOL_VERSION_META_KEY) if isinstance(meta, dict) else None # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
|
|
129
|
+
method = message.get("method")
|
|
130
|
+
if isinstance(version, str) and isinstance(method, str):
|
|
131
|
+
headers["mcp-protocol-version"] = version
|
|
132
|
+
headers["mcp-method"] = method
|
|
133
|
+
name_key = NAME_BEARING_METHODS.get(method)
|
|
134
|
+
if name_key is not None and isinstance(params, dict):
|
|
135
|
+
name: Any = params.get(name_key) # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
|
|
136
|
+
if isinstance(name, str):
|
|
137
|
+
headers["mcp-name"] = encode_header_value(name)
|
|
138
|
+
elif method != "initialize" and negotiated is not None:
|
|
139
|
+
headers["mcp-protocol-version"] = negotiated
|
|
140
|
+
return headers
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _error_response(request_id: Any, message: str) -> dict[str, Any]:
|
|
144
|
+
return {
|
|
145
|
+
"jsonrpc": "2.0",
|
|
146
|
+
"id": request_id,
|
|
147
|
+
"error": {"code": JSONRPC_INTERNAL_ERROR, "message": message},
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _pipe_fd(stream: BinaryIO, *, anonymous_only: bool = False) -> int | None:
|
|
152
|
+
try:
|
|
153
|
+
fd = stream.fileno()
|
|
154
|
+
info = os.fstat(fd)
|
|
155
|
+
if stat.S_ISFIFO(info.st_mode) and (not anonymous_only or info.st_nlink == 0):
|
|
156
|
+
return fd
|
|
157
|
+
return None
|
|
158
|
+
except OSError, ValueError:
|
|
159
|
+
return None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _input_fd(stream: BinaryIO) -> int | None:
|
|
163
|
+
try:
|
|
164
|
+
fd = stream.fileno()
|
|
165
|
+
mode = os.fstat(fd).st_mode
|
|
166
|
+
if stat.S_ISFIFO(mode) or stat.S_ISSOCK(mode) or os.isatty(fd):
|
|
167
|
+
return fd
|
|
168
|
+
except OSError, ValueError:
|
|
169
|
+
pass
|
|
170
|
+
return None
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@contextmanager
|
|
174
|
+
def _nonblocking(fd: int) -> Generator[None]:
|
|
175
|
+
# Do not share a changed status flag with the launcher while waiting for readiness.
|
|
176
|
+
blocking = os.get_blocking(fd)
|
|
177
|
+
if blocking:
|
|
178
|
+
os.set_blocking(fd, False)
|
|
179
|
+
try:
|
|
180
|
+
yield
|
|
181
|
+
finally:
|
|
182
|
+
if blocking:
|
|
183
|
+
os.set_blocking(fd, True)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class StdioProxy:
|
|
187
|
+
"""Relays newline-delimited JSON-RPC between a client's stdio and the daemon's HTTP endpoint."""
|
|
188
|
+
|
|
189
|
+
def __init__(
|
|
190
|
+
self,
|
|
191
|
+
url: str,
|
|
192
|
+
*,
|
|
193
|
+
stdin: BinaryIO | None = None,
|
|
194
|
+
stdout: BinaryIO | None = None,
|
|
195
|
+
http: httpx.AsyncClient | None = None,
|
|
196
|
+
max_pending: int = DEFAULT_MAX_PENDING,
|
|
197
|
+
ensure: Callable[[], Awaitable[_Endpoint | None]] | None = None,
|
|
198
|
+
bearer: str | None = None,
|
|
199
|
+
current_endpoint: Callable[[], Awaitable[LocalEndpoint | None]] | None = None,
|
|
200
|
+
) -> None:
|
|
201
|
+
if bearer is not None and not _BEARER.fullmatch(bearer):
|
|
202
|
+
raise EndpointError("invalid bearer token")
|
|
203
|
+
check_endpoint(url, credentialed=bearer is not None)
|
|
204
|
+
self._target: _Endpoint = url
|
|
205
|
+
self._bearer = bearer
|
|
206
|
+
self._shown_url = _display_url(url)
|
|
207
|
+
self._max_pending = max_pending
|
|
208
|
+
self._tasks: set[asyncio.Task[None]] = set()
|
|
209
|
+
self._orphaned_writes: set[asyncio.Future[None]] = set()
|
|
210
|
+
self._partial_write: asyncio.Future[None] | None = None
|
|
211
|
+
self._stdin = stdin if stdin is not None else sys.stdin.buffer
|
|
212
|
+
# Built-in process input has no earlier buffered reads. Injected streams retain readline().
|
|
213
|
+
self._stdin_fd = _input_fd(self._stdin) if stdin is None else None
|
|
214
|
+
self._input_ready = asyncio.Event()
|
|
215
|
+
self._stdout = stdout if stdout is not None else sys.stdout.buffer
|
|
216
|
+
self._stdout_fd = _pipe_fd(self._stdout) if stdout is None else None
|
|
217
|
+
self._http = http
|
|
218
|
+
self._https_bearer_transport: httpx.AsyncHTTPTransport | None = None
|
|
219
|
+
if (
|
|
220
|
+
http is None
|
|
221
|
+
and ensure is None
|
|
222
|
+
and bearer is not None
|
|
223
|
+
and urlsplit(url).scheme == "https"
|
|
224
|
+
):
|
|
225
|
+
try:
|
|
226
|
+
# The transport reads the CA environment. Proxy discovery belongs to the client.
|
|
227
|
+
self._https_bearer_transport = httpx.AsyncHTTPTransport(trust_env=True)
|
|
228
|
+
except OSError as exc:
|
|
229
|
+
raise EndpointError("cannot load configured HTTPS CA trust") from exc
|
|
230
|
+
self._write_lock = asyncio.Lock()
|
|
231
|
+
self._inflight: dict[Any, asyncio.Task[None]] = {}
|
|
232
|
+
self._streams: set[asyncio.Task[None]] = set()
|
|
233
|
+
self._gone = False
|
|
234
|
+
self._negotiated: str | None = None
|
|
235
|
+
self._ensure = ensure
|
|
236
|
+
self._current_endpoint = current_endpoint
|
|
237
|
+
self._starting: asyncio.Task[_Endpoint | None] | None = None
|
|
238
|
+
self._ready = ensure is None
|
|
239
|
+
|
|
240
|
+
async def _input_lines(self) -> AsyncGenerator[bytes]:
|
|
241
|
+
fd = self._stdin_fd
|
|
242
|
+
if fd is None:
|
|
243
|
+
while not self._gone and (line := await asyncio.to_thread(self._stdin.readline)):
|
|
244
|
+
yield line
|
|
245
|
+
return
|
|
246
|
+
|
|
247
|
+
loop = asyncio.get_running_loop()
|
|
248
|
+
try:
|
|
249
|
+
loop.add_reader(fd, self._input_ready.set)
|
|
250
|
+
pending = bytearray()
|
|
251
|
+
turn = asyncio.Event()
|
|
252
|
+
|
|
253
|
+
async def let_forwarding_run() -> None:
|
|
254
|
+
# Give forwarding tasks and their done callbacks a turn.
|
|
255
|
+
loop.call_soon(turn.set)
|
|
256
|
+
await turn.wait()
|
|
257
|
+
turn.clear()
|
|
258
|
+
|
|
259
|
+
while not self._gone:
|
|
260
|
+
await self._input_ready.wait()
|
|
261
|
+
self._input_ready.clear()
|
|
262
|
+
if self._gone:
|
|
263
|
+
break
|
|
264
|
+
try:
|
|
265
|
+
with _nonblocking(fd):
|
|
266
|
+
chunk = os.read(fd, 64 * 1024)
|
|
267
|
+
except BlockingIOError:
|
|
268
|
+
continue
|
|
269
|
+
if not chunk:
|
|
270
|
+
if pending:
|
|
271
|
+
await let_forwarding_run()
|
|
272
|
+
if not self._gone:
|
|
273
|
+
yield bytes(pending) # readline also returns an unterminated line
|
|
274
|
+
break
|
|
275
|
+
first, *rest = chunk.split(b"\n")
|
|
276
|
+
pending.extend(first)
|
|
277
|
+
if rest:
|
|
278
|
+
yield bytes(pending)
|
|
279
|
+
for line in rest[:-1]:
|
|
280
|
+
await let_forwarding_run()
|
|
281
|
+
if self._gone:
|
|
282
|
+
return
|
|
283
|
+
yield line
|
|
284
|
+
pending = bytearray(rest[-1])
|
|
285
|
+
finally:
|
|
286
|
+
loop.remove_reader(fd)
|
|
287
|
+
|
|
288
|
+
async def run(self) -> None:
|
|
289
|
+
"""Drain in-flight calls on input EOF and abort them if stdout disconnects."""
|
|
290
|
+
owned = self._http is None
|
|
291
|
+
http = self._http or httpx.AsyncClient(
|
|
292
|
+
transport=self._https_bearer_transport,
|
|
293
|
+
timeout=httpx.Timeout(10.0, read=None),
|
|
294
|
+
trust_env=self._bearer is None,
|
|
295
|
+
)
|
|
296
|
+
tasks = self._tasks
|
|
297
|
+
# The selector reports an EOF/error on a pipe's write end when the peer closes it
|
|
298
|
+
# (the same read-side watch used by asyncio's Unix write-pipe transport). On macOS a
|
|
299
|
+
# named FIFO can signal readability while its reader is still open.
|
|
300
|
+
loop = asyncio.get_running_loop()
|
|
301
|
+
output_fd = _pipe_fd(self._stdout, anonymous_only=sys.platform == "darwin")
|
|
302
|
+
if (
|
|
303
|
+
output_fd is not None
|
|
304
|
+
and fcntl.fcntl(output_fd, fcntl.F_GETFL) & os.O_ACCMODE != os.O_WRONLY
|
|
305
|
+
):
|
|
306
|
+
output_fd = None # a read/write FIFO can become readable from our own output
|
|
307
|
+
|
|
308
|
+
def output_closed() -> None:
|
|
309
|
+
assert output_fd is not None
|
|
310
|
+
loop.remove_reader(output_fd)
|
|
311
|
+
self._client_gone()
|
|
312
|
+
|
|
313
|
+
try:
|
|
314
|
+
if output_fd is not None:
|
|
315
|
+
loop.add_reader(output_fd, output_closed)
|
|
316
|
+
async with aclosing(self._input_lines()) as lines:
|
|
317
|
+
async for line in lines:
|
|
318
|
+
body = line.strip()
|
|
319
|
+
if not body:
|
|
320
|
+
continue
|
|
321
|
+
try:
|
|
322
|
+
message: Any = json.loads(body)
|
|
323
|
+
except ValueError: # bad JSON or invalid UTF-8
|
|
324
|
+
log.error("dropped a line that is not JSON")
|
|
325
|
+
continue
|
|
326
|
+
if not isinstance(message, dict):
|
|
327
|
+
log.error("dropped a message that is not a JSON object")
|
|
328
|
+
continue
|
|
329
|
+
if self._gone:
|
|
330
|
+
break
|
|
331
|
+
if self._over_limit(message): # pyright: ignore[reportUnknownArgumentType]
|
|
332
|
+
self._reject_busy(message) # pyright: ignore[reportUnknownArgumentType]
|
|
333
|
+
continue
|
|
334
|
+
task = self._dispatch(http, body, message) # pyright: ignore[reportUnknownArgumentType]
|
|
335
|
+
if task is not None:
|
|
336
|
+
tasks.add(task)
|
|
337
|
+
task.add_done_callback(tasks.discard)
|
|
338
|
+
# stdin closed: the client is shutting down. A listen stream has no end of its own, so
|
|
339
|
+
# it would hold this process open forever; every other call may still be answered.
|
|
340
|
+
for stream in self._streams:
|
|
341
|
+
stream.cancel()
|
|
342
|
+
if tasks:
|
|
343
|
+
await asyncio.gather(*tasks, return_exceptions=True)
|
|
344
|
+
finally:
|
|
345
|
+
if output_fd is not None:
|
|
346
|
+
loop.remove_reader(output_fd)
|
|
347
|
+
try:
|
|
348
|
+
if self._stdout_fd is not None:
|
|
349
|
+
await self._finish_pipe_writes()
|
|
350
|
+
finally:
|
|
351
|
+
if owned:
|
|
352
|
+
await http.aclose()
|
|
353
|
+
|
|
354
|
+
async def _finish_pipe_writes(self) -> None:
|
|
355
|
+
for task in self._tasks:
|
|
356
|
+
task.cancel()
|
|
357
|
+
await asyncio.gather(*self._tasks, return_exceptions=True)
|
|
358
|
+
|
|
359
|
+
# After EOF, ordinary replies have drained. Drop unused canceled writes, but
|
|
360
|
+
# let a line already on the wire finish if the reader is still consuming it.
|
|
361
|
+
partial = self._partial_write
|
|
362
|
+
for write in self._orphaned_writes:
|
|
363
|
+
if write is not partial:
|
|
364
|
+
write.cancel()
|
|
365
|
+
if partial is not None and not self._gone:
|
|
366
|
+
await asyncio.wait({partial}, timeout=_PARTIAL_LINE_DRAIN_SECONDS)
|
|
367
|
+
for write in self._orphaned_writes:
|
|
368
|
+
write.cancel()
|
|
369
|
+
await asyncio.gather(*self._orphaned_writes, return_exceptions=True)
|
|
370
|
+
|
|
371
|
+
def _over_limit(self, message: Mapping[str, Any]) -> bool:
|
|
372
|
+
"""Too much work is pending; a cancel still gets through, since it frees work."""
|
|
373
|
+
return (
|
|
374
|
+
message.get("method") != "notifications/cancelled"
|
|
375
|
+
and len(self._tasks) + len(self._orphaned_writes) >= self._max_pending
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
def _reject_busy(self, message: Mapping[str, Any]) -> None:
|
|
379
|
+
"""Answer an over-limit request without waiting on stdout, which may be what is stuck."""
|
|
380
|
+
request_id = message.get("id")
|
|
381
|
+
log.error("too many pending requests; dropped one")
|
|
382
|
+
answerable = (
|
|
383
|
+
message.get("method") is not None and _valid_id(request_id) and request_id is not None
|
|
384
|
+
)
|
|
385
|
+
if answerable and len(self._tasks) + len(self._orphaned_writes) < 2 * self._max_pending:
|
|
386
|
+
refusal = asyncio.ensure_future(
|
|
387
|
+
self._emit(
|
|
388
|
+
_error_response(request_id, "plotroom proxy has too many pending requests")
|
|
389
|
+
)
|
|
390
|
+
)
|
|
391
|
+
self._tasks.add(refusal)
|
|
392
|
+
refusal.add_done_callback(self._tasks.discard)
|
|
393
|
+
|
|
394
|
+
def _dispatch(
|
|
395
|
+
self, http: httpx.AsyncClient, body: bytes, message: dict[str, Any]
|
|
396
|
+
) -> asyncio.Task[None] | None:
|
|
397
|
+
method = message.get("method")
|
|
398
|
+
request_id = message.get("id")
|
|
399
|
+
if not _valid_id(request_id):
|
|
400
|
+
log.error("dropped a message whose id is not a string or an integer")
|
|
401
|
+
return None
|
|
402
|
+
if method == "notifications/cancelled":
|
|
403
|
+
# Stateless HTTP has no session to forward a cancel to; aborting the request's own
|
|
404
|
+
# POST is the signal (a request the server already answered has nothing to cancel).
|
|
405
|
+
params: Any = message.get("params")
|
|
406
|
+
target: Any = params.get("requestId") if isinstance(params, dict) else None # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
|
|
407
|
+
if target is not None and _valid_id(target) and (pending := self._inflight.get(target)):
|
|
408
|
+
pending.cancel()
|
|
409
|
+
return None
|
|
410
|
+
task = asyncio.ensure_future(self._forward(http, body, message))
|
|
411
|
+
if method == LISTEN_METHOD:
|
|
412
|
+
self._streams.add(task)
|
|
413
|
+
task.add_done_callback(self._streams.discard)
|
|
414
|
+
if method is not None and request_id is not None:
|
|
415
|
+
self._inflight[request_id] = task
|
|
416
|
+
|
|
417
|
+
def forget(done: asyncio.Task[None], rid: Any = request_id) -> None:
|
|
418
|
+
if self._inflight.get(rid) is done: # a reused id may already name a newer task
|
|
419
|
+
del self._inflight[rid]
|
|
420
|
+
|
|
421
|
+
task.add_done_callback(forget)
|
|
422
|
+
return task
|
|
423
|
+
|
|
424
|
+
async def _ensure_ready(self) -> asyncio.Task[_Endpoint | None] | None:
|
|
425
|
+
"""Wait until the server is up, starting it once however many requests wait on it.
|
|
426
|
+
|
|
427
|
+
A start that reports where the server listens (a daemon on a port of its own choosing) moves
|
|
428
|
+
the proxy there. Returns the start this request relied on, so a refusal can tell whether
|
|
429
|
+
that start is still the current one.
|
|
430
|
+
"""
|
|
431
|
+
if self._ensure is None:
|
|
432
|
+
return None
|
|
433
|
+
if self._ready:
|
|
434
|
+
previous = self._starting
|
|
435
|
+
current = (
|
|
436
|
+
self._target if self._current_endpoint is None else await self._current_endpoint()
|
|
437
|
+
)
|
|
438
|
+
if self._ready and current == self._target:
|
|
439
|
+
return self._starting
|
|
440
|
+
if self._starting is previous:
|
|
441
|
+
self._ready = False
|
|
442
|
+
self._starting = None
|
|
443
|
+
starting = self._starting
|
|
444
|
+
if (
|
|
445
|
+
starting is None
|
|
446
|
+
or starting.cancelled()
|
|
447
|
+
or (starting.done() and starting.exception() is not None)
|
|
448
|
+
):
|
|
449
|
+
starting = self._starting = asyncio.ensure_future(self._ensure())
|
|
450
|
+
# Shielded: one canceled request must not abort the start the others are waiting on.
|
|
451
|
+
target = await asyncio.shield(starting)
|
|
452
|
+
if self._current_endpoint is not None and not isinstance(target, LocalEndpoint):
|
|
453
|
+
raise UpstreamStartError("no verified local daemon endpoint is available")
|
|
454
|
+
if target is not None:
|
|
455
|
+
url = target.url if isinstance(target, LocalEndpoint) else target
|
|
456
|
+
check_endpoint(url, credentialed=self._bearer is not None)
|
|
457
|
+
self._target = target
|
|
458
|
+
self._shown_url = _display_url(url)
|
|
459
|
+
self._ready = True
|
|
460
|
+
return starting
|
|
461
|
+
|
|
462
|
+
async def _forward(
|
|
463
|
+
self,
|
|
464
|
+
http: httpx.AsyncClient,
|
|
465
|
+
body: bytes,
|
|
466
|
+
message: dict[str, Any],
|
|
467
|
+
*,
|
|
468
|
+
retried: bool = False,
|
|
469
|
+
) -> None:
|
|
470
|
+
request_id = message.get("id")
|
|
471
|
+
is_request = message.get("method") is not None and request_id is not None
|
|
472
|
+
answered = False
|
|
473
|
+
relied_on: asyncio.Task[_Endpoint | None] | None = None
|
|
474
|
+
try:
|
|
475
|
+
relied_on = await self._ensure_ready()
|
|
476
|
+
headers = envelope_headers(message, self._negotiated)
|
|
477
|
+
if self._bearer is not None:
|
|
478
|
+
headers["authorization"] = f"Bearer {self._bearer}"
|
|
479
|
+
target = self._target
|
|
480
|
+
stream = (
|
|
481
|
+
target.stream("POST", content=body, headers=headers)
|
|
482
|
+
if isinstance(target, LocalEndpoint)
|
|
483
|
+
else http.stream("POST", target, content=body, headers=headers)
|
|
484
|
+
)
|
|
485
|
+
async with stream as response:
|
|
486
|
+
content_type = response.headers.get("content-type", "")
|
|
487
|
+
if "text/event-stream" in content_type:
|
|
488
|
+
async for payload in _sse_payloads(response):
|
|
489
|
+
relayed = await self._relay(payload, message)
|
|
490
|
+
answered = answered or (relayed and _answers(payload, request_id))
|
|
491
|
+
if is_request and not answered:
|
|
492
|
+
log.error("event stream ended without a response to request %s", request_id)
|
|
493
|
+
await self._emit(
|
|
494
|
+
_error_response(
|
|
495
|
+
request_id, "plotroom server ended the stream without a response"
|
|
496
|
+
)
|
|
497
|
+
)
|
|
498
|
+
return
|
|
499
|
+
raw = await response.aread()
|
|
500
|
+
if raw.strip() and await self._relay(raw.strip(), message):
|
|
501
|
+
return
|
|
502
|
+
if is_request or response.status_code >= 400: # a notification's 202 is expected
|
|
503
|
+
log.error("daemon answered HTTP %s with no JSON-RPC body", response.status_code)
|
|
504
|
+
if is_request:
|
|
505
|
+
await self._emit(
|
|
506
|
+
_error_response(
|
|
507
|
+
request_id,
|
|
508
|
+
f"plotroom server answered HTTP {response.status_code} without a reply",
|
|
509
|
+
)
|
|
510
|
+
)
|
|
511
|
+
except asyncio.CancelledError:
|
|
512
|
+
raise
|
|
513
|
+
except BrokenPipeError:
|
|
514
|
+
raise
|
|
515
|
+
except UpstreamStartError as exc:
|
|
516
|
+
log.error("plotroom is not running: %s", exc)
|
|
517
|
+
if is_request:
|
|
518
|
+
await self._emit(_error_response(request_id, f"plotroom is not running: {exc}"))
|
|
519
|
+
except httpx.ConnectError as exc:
|
|
520
|
+
if self._https_bearer_transport is not None and (cert_error := _certificate_error(exc)):
|
|
521
|
+
detail = f"TLS certificate verification failed: {cert_error}"
|
|
522
|
+
log.error("%s", detail)
|
|
523
|
+
if is_request:
|
|
524
|
+
await self._emit(_error_response(request_id, detail))
|
|
525
|
+
return
|
|
526
|
+
if self._ensure is not None and not retried:
|
|
527
|
+
# Refused before any byte was sent, so the daemon never saw it: start it and retry.
|
|
528
|
+
# Several requests refused together share one restart: only the first one to get
|
|
529
|
+
# here retires the start they all relied on.
|
|
530
|
+
if self._starting is relied_on:
|
|
531
|
+
self._ready = False
|
|
532
|
+
self._starting = None
|
|
533
|
+
await self._forward(http, body, message, retried=True)
|
|
534
|
+
return
|
|
535
|
+
log.error("cannot reach plotroom at %s: ConnectError", self._shown_url)
|
|
536
|
+
if is_request:
|
|
537
|
+
await self._emit(
|
|
538
|
+
_error_response(
|
|
539
|
+
request_id,
|
|
540
|
+
f"cannot reach plotroom at {self._shown_url}; run `plotroom serve`",
|
|
541
|
+
)
|
|
542
|
+
)
|
|
543
|
+
except httpx.HTTPError as exc:
|
|
544
|
+
# the exception's text can repeat the full URL, so only its type is logged
|
|
545
|
+
log.error("cannot reach plotroom at %s: %s", self._shown_url, type(exc).__name__)
|
|
546
|
+
if is_request and not answered: # a stream cut after its response needs no second one
|
|
547
|
+
await self._emit(
|
|
548
|
+
_error_response(
|
|
549
|
+
request_id,
|
|
550
|
+
f"cannot reach plotroom at {self._shown_url}; run `plotroom serve`",
|
|
551
|
+
)
|
|
552
|
+
)
|
|
553
|
+
except Exception as exc:
|
|
554
|
+
# e.g. a method name that cannot be an HTTP header: answer instead of leaving it hanging
|
|
555
|
+
log.error("could not forward a message: %s", type(exc).__name__)
|
|
556
|
+
if is_request and not answered:
|
|
557
|
+
await self._emit(
|
|
558
|
+
_error_response(request_id, "the message cannot be forwarded to plotroom")
|
|
559
|
+
)
|
|
560
|
+
|
|
561
|
+
def _client_gone(self) -> None:
|
|
562
|
+
"""Nobody reads stdout any more: abort every call, so the server stops working for them."""
|
|
563
|
+
self._gone = True
|
|
564
|
+
self._input_ready.set()
|
|
565
|
+
for task in list(self._tasks):
|
|
566
|
+
task.cancel()
|
|
567
|
+
|
|
568
|
+
async def _relay(self, payload: bytes, request: Mapping[str, Any]) -> bool:
|
|
569
|
+
"""Write one server message to stdout; ``False`` when it is not JSON-RPC."""
|
|
570
|
+
try:
|
|
571
|
+
decoded: Any = json.loads(payload)
|
|
572
|
+
except ValueError:
|
|
573
|
+
return False
|
|
574
|
+
if not isinstance(decoded, dict) or "jsonrpc" not in decoded:
|
|
575
|
+
return False
|
|
576
|
+
if request.get("method") == "initialize":
|
|
577
|
+
result: Any = decoded.get("result") # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
|
|
578
|
+
version: Any = result.get("protocolVersion") if isinstance(result, dict) else None # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
|
|
579
|
+
if isinstance(version, str):
|
|
580
|
+
self._negotiated = version
|
|
581
|
+
await self._emit(cast("dict[str, Any]", decoded)) # one line, whatever the server sent
|
|
582
|
+
return True
|
|
583
|
+
|
|
584
|
+
async def _emit(self, message: dict[str, Any]) -> None:
|
|
585
|
+
await self._write(json.dumps(message, separators=(",", ":")).encode())
|
|
586
|
+
|
|
587
|
+
async def _write(self, payload: bytes) -> None:
|
|
588
|
+
# A canceled caller must not release the lock while its protocol line is still being
|
|
589
|
+
# written. The write it leaves behind counts toward the pending limit until it finishes.
|
|
590
|
+
write = asyncio.ensure_future(self._locked_write(payload))
|
|
591
|
+
try:
|
|
592
|
+
await asyncio.shield(write)
|
|
593
|
+
except asyncio.CancelledError:
|
|
594
|
+
if not write.done():
|
|
595
|
+
self._orphaned_writes.add(write)
|
|
596
|
+
write.add_done_callback(self._orphaned_writes.discard)
|
|
597
|
+
raise
|
|
598
|
+
|
|
599
|
+
async def _locked_write(self, payload: bytes) -> None:
|
|
600
|
+
async with self._write_lock:
|
|
601
|
+
try:
|
|
602
|
+
if (fd := self._stdout_fd) is None:
|
|
603
|
+
await asyncio.to_thread(self._write_blocking, payload)
|
|
604
|
+
else:
|
|
605
|
+
await self._write_pipe(fd, payload + b"\n")
|
|
606
|
+
except BrokenPipeError:
|
|
607
|
+
log.error("stdout closed; the client is gone")
|
|
608
|
+
self._client_gone()
|
|
609
|
+
|
|
610
|
+
async def _write_pipe(self, fd: int, line: bytes) -> None:
|
|
611
|
+
# Write directly so an interrupted flush cannot leave bytes for Python to retry at exit.
|
|
612
|
+
loop = asyncio.get_running_loop()
|
|
613
|
+
ready = asyncio.Event()
|
|
614
|
+
remaining = memoryview(line)
|
|
615
|
+
try:
|
|
616
|
+
while remaining:
|
|
617
|
+
try:
|
|
618
|
+
with _nonblocking(fd):
|
|
619
|
+
written = os.write(fd, remaining)
|
|
620
|
+
remaining = remaining[written:]
|
|
621
|
+
if remaining:
|
|
622
|
+
self._partial_write = asyncio.current_task()
|
|
623
|
+
except BlockingIOError:
|
|
624
|
+
loop.add_writer(fd, ready.set)
|
|
625
|
+
try:
|
|
626
|
+
await ready.wait()
|
|
627
|
+
ready.clear()
|
|
628
|
+
finally:
|
|
629
|
+
loop.remove_writer(fd)
|
|
630
|
+
finally:
|
|
631
|
+
self._partial_write = None
|
|
632
|
+
|
|
633
|
+
def _write_blocking(self, payload: bytes) -> None:
|
|
634
|
+
"""Runs off the event loop for streams outside the process pipe path."""
|
|
635
|
+
self._stdout.write(payload + b"\n")
|
|
636
|
+
self._stdout.flush()
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
class EndpointError(ValueError):
|
|
640
|
+
"""The server URL cannot be used safely."""
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def check_endpoint(url: str, *, credentialed: bool = False) -> None:
|
|
644
|
+
"""Refuse non-HTTP endpoints and require HTTPS for remote credentials."""
|
|
645
|
+
try:
|
|
646
|
+
parts = urlsplit(url)
|
|
647
|
+
_ = parts.port
|
|
648
|
+
except ValueError as exc:
|
|
649
|
+
raise EndpointError("the endpoint URL has an invalid port") from exc
|
|
650
|
+
host = parts.hostname
|
|
651
|
+
if parts.scheme not in ("http", "https") or not host:
|
|
652
|
+
raise EndpointError("the endpoint must be an http or https URL with a host")
|
|
653
|
+
if credentialed and parts.username is not None:
|
|
654
|
+
raise EndpointError("the endpoint cannot contain user info when a bearer token is supplied")
|
|
655
|
+
carries_secret = credentialed or bool(parts.username or parts.password or parts.query)
|
|
656
|
+
if parts.scheme == "http" and carries_secret and not _is_loopback(host):
|
|
657
|
+
raise EndpointError(
|
|
658
|
+
"refusing to send a credential in a plaintext http URL to a non-local host; use https"
|
|
659
|
+
)
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
def _is_loopback(host: str) -> bool:
|
|
663
|
+
if host == "localhost":
|
|
664
|
+
return True
|
|
665
|
+
try:
|
|
666
|
+
return ipaddress.ip_address(host).is_loopback
|
|
667
|
+
except ValueError:
|
|
668
|
+
return False
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def _certificate_error(exc: BaseException) -> str | None:
|
|
672
|
+
cause: BaseException | None = exc
|
|
673
|
+
seen: set[int] = set()
|
|
674
|
+
while cause is not None and id(cause) not in seen:
|
|
675
|
+
seen.add(id(cause))
|
|
676
|
+
if isinstance(cause, ssl.SSLCertVerificationError):
|
|
677
|
+
return cause.verify_message
|
|
678
|
+
# HTTPcore can suppress the TLS exception's context when reraising its connection error.
|
|
679
|
+
cause = cause.__cause__ or cause.__context__
|
|
680
|
+
return None
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def _valid_id(request_id: Any) -> bool:
|
|
684
|
+
"""JSON-RPC ids are strings, integers or absent; anything else cannot be tracked."""
|
|
685
|
+
return request_id is None or (
|
|
686
|
+
isinstance(request_id, str | int) and not isinstance(request_id, bool)
|
|
687
|
+
)
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
def _display_url(url: str) -> str:
|
|
691
|
+
"""The endpoint without userinfo, query or fragment, for logs and error messages."""
|
|
692
|
+
parts = urlsplit(url)
|
|
693
|
+
host = parts.hostname or ""
|
|
694
|
+
host = f"[{host}]" if ":" in host else host
|
|
695
|
+
netloc = f"{host}:{parts.port}" if parts.port else host
|
|
696
|
+
return urlunsplit((parts.scheme, netloc, parts.path, "", ""))
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def _answers(payload: bytes, request_id: Any) -> bool:
|
|
700
|
+
"""Whether the payload is the response (result or error) to ``request_id``."""
|
|
701
|
+
try:
|
|
702
|
+
decoded: Any = json.loads(payload)
|
|
703
|
+
except ValueError:
|
|
704
|
+
return False
|
|
705
|
+
if not isinstance(decoded, dict):
|
|
706
|
+
return False
|
|
707
|
+
body = cast("dict[str, Any]", decoded)
|
|
708
|
+
return body.get("id") == request_id and ("result" in body or "error" in body)
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
async def _sse_payloads(response: httpx.Response):
|
|
712
|
+
"""Each complete SSE event's ``data`` as bytes."""
|
|
713
|
+
data: list[str] = []
|
|
714
|
+
async for line in response.aiter_lines():
|
|
715
|
+
if line == "":
|
|
716
|
+
if data:
|
|
717
|
+
yield "\n".join(data).encode()
|
|
718
|
+
data = []
|
|
719
|
+
elif line.startswith("data:"):
|
|
720
|
+
data.append(line[5:].removeprefix(" "))
|
|
721
|
+
if data:
|
|
722
|
+
yield "\n".join(data).encode()
|