agents-over-telegram 0.11.0
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.
- package/LICENSE +202 -0
- package/README.md +141 -0
- package/docs/BOT_EXCHANGES.md +121 -0
- package/docs/COMPATIBILITY.md +110 -0
- package/docs/DIRECT_DISPATCH.md +155 -0
- package/docs/HOSTS.md +244 -0
- package/docs/IMPLEMENTATION_STATUS.md +205 -0
- package/docs/LIVE_VALIDATION.md +35 -0
- package/docs/MACOS_SERVICE.md +89 -0
- package/docs/OPERATIONS.md +568 -0
- package/docs/REACTIONS.md +51 -0
- package/docs/RELAY.md +115 -0
- package/docs/RELEASING.md +45 -0
- package/docs/schemas/mcp.schema.json +120 -0
- package/docs/schemas/sources.json +9 -0
- package/integrations/pi/agents-over-telegram.ts +154 -0
- package/package.json +41 -0
- package/pyproject.toml +37 -0
- package/requirements/build.txt +18 -0
- package/requirements/runtime.txt +532 -0
- package/scripts/bootstrap_runtime.py +402 -0
- package/skills/telegram-coordinate/SKILL.md +67 -0
- package/skills/telegram-setup/SKILL.md +81 -0
- package/src/agents_over_telegram/__init__.py +2 -0
- package/src/agents_over_telegram/__main__.py +2 -0
- package/src/agents_over_telegram/appserver_client.py +400 -0
- package/src/agents_over_telegram/cli.py +851 -0
- package/src/agents_over_telegram/codex_trust.py +206 -0
- package/src/agents_over_telegram/compat.py +207 -0
- package/src/agents_over_telegram/core.py +4253 -0
- package/src/agents_over_telegram/credentials.py +108 -0
- package/src/agents_over_telegram/demo.py +85 -0
- package/src/agents_over_telegram/desktop_bridge.py +537 -0
- package/src/agents_over_telegram/desktop_dispatcher.py +680 -0
- package/src/agents_over_telegram/dispatcher.py +260 -0
- package/src/agents_over_telegram/host_config.py +125 -0
- package/src/agents_over_telegram/hosts.py +590 -0
- package/src/agents_over_telegram/judge.py +230 -0
- package/src/agents_over_telegram/macos_process.py +133 -0
- package/src/agents_over_telegram/markdown.py +127 -0
- package/src/agents_over_telegram/mcp_server.py +652 -0
- package/src/agents_over_telegram/net.py +130 -0
- package/src/agents_over_telegram/onboarding.py +719 -0
- package/src/agents_over_telegram/push.py +421 -0
- package/src/agents_over_telegram/relay.py +380 -0
- package/src/agents_over_telegram/relay_api.py +591 -0
- package/src/agents_over_telegram/relay_watch.py +171 -0
- package/src/agents_over_telegram/serve.py +626 -0
- package/src/agents_over_telegram/settings_panel.py +216 -0
- package/src/agents_over_telegram/transport.py +720 -0
- package/src/agents_over_telegram/webhook.py +219 -0
- package/uv.lock +1011 -0
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
"""Bounded, local-only JSON-RPC client for an explicitly selected Codex backend.
|
|
2
|
+
|
|
3
|
+
This transport never discovers a backend, reconnects a broken session, retries a
|
|
4
|
+
mutation, logs server content, or approves requests received from the server.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import ipaddress
|
|
9
|
+
import json
|
|
10
|
+
import logging
|
|
11
|
+
import math
|
|
12
|
+
import os
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
import socket
|
|
15
|
+
import stat
|
|
16
|
+
import struct
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
from urllib.parse import urlsplit
|
|
20
|
+
from uuid import UUID
|
|
21
|
+
|
|
22
|
+
from websockets.sync.client import connect, unix_connect
|
|
23
|
+
|
|
24
|
+
from . import __version__
|
|
25
|
+
from .credentials import CredentialError, read_private_json
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
_EVENT_METHODS = frozenset({
|
|
29
|
+
"thread/started", "thread/status/changed", "turn/started", "turn/completed",
|
|
30
|
+
"item/started", "item/completed", "item/commandExecution/requestApproval",
|
|
31
|
+
"item/fileChange/requestApproval", "item/tool/requestUserInput", "item/tool/call",
|
|
32
|
+
"item/permissions/requestApproval", "account/chatgptAuthTokens/refresh",
|
|
33
|
+
"execCommandApproval", "applyPatchApproval", "error", "warning",
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class AppServerError(Exception):
|
|
38
|
+
"""A secret-free error; ambiguous mutations require manual reconciliation."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, code, *, ambiguous=False, rpc_code=None):
|
|
41
|
+
self.code = code
|
|
42
|
+
self.ambiguous = ambiguous
|
|
43
|
+
self.rpc_code = rpc_code
|
|
44
|
+
super().__init__(code)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def validate_endpoint(endpoint, *, token_file=None):
|
|
48
|
+
"""Validate configuration without connecting or reading a credential."""
|
|
49
|
+
if not isinstance(endpoint, str) or not endpoint or len(endpoint) > 4096:
|
|
50
|
+
raise AppServerError("invalid_appserver_endpoint")
|
|
51
|
+
try:
|
|
52
|
+
parsed = urlsplit(endpoint)
|
|
53
|
+
if parsed.scheme == "unix":
|
|
54
|
+
if (parsed.netloc or not parsed.path.startswith("/") or parsed.query
|
|
55
|
+
or parsed.fragment or "%" in parsed.path or "\x00" in parsed.path
|
|
56
|
+
or token_file is not None):
|
|
57
|
+
raise ValueError()
|
|
58
|
+
if any(part in (".", "..") for part in parsed.path.split("/")):
|
|
59
|
+
raise ValueError()
|
|
60
|
+
return "unix", parsed.path
|
|
61
|
+
if (parsed.scheme != "ws" or parsed.username is not None
|
|
62
|
+
or parsed.password is not None or parsed.query or parsed.fragment
|
|
63
|
+
or parsed.port is None or not 1 <= parsed.port <= 65535
|
|
64
|
+
or token_file is None or not ipaddress.ip_address(parsed.hostname).is_loopback):
|
|
65
|
+
raise ValueError()
|
|
66
|
+
if any(ord(character) < 33 or ord(character) > 126 for character in endpoint):
|
|
67
|
+
raise ValueError()
|
|
68
|
+
return "ws", endpoint
|
|
69
|
+
except (ValueError, TypeError):
|
|
70
|
+
raise AppServerError("invalid_appserver_endpoint") from None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _socket_parent(path):
|
|
74
|
+
for ancestor in reversed(path.parents):
|
|
75
|
+
info = ancestor.lstat()
|
|
76
|
+
trusted_sticky = info.st_uid == 0 and info.st_mode & stat.S_ISVTX
|
|
77
|
+
if (not stat.S_ISDIR(info.st_mode) or info.st_uid not in (0, os.getuid())
|
|
78
|
+
or (info.st_mode & 0o022 and not trusted_sticky)):
|
|
79
|
+
raise AppServerError("unsafe_appserver_socket")
|
|
80
|
+
parent = path.parent.lstat()
|
|
81
|
+
if parent.st_uid != os.getuid() or parent.st_mode & 0o077:
|
|
82
|
+
raise AppServerError("unsafe_appserver_socket")
|
|
83
|
+
return parent.st_dev, parent.st_ino
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _private_socket(path):
|
|
87
|
+
"""Validate a private socket or Codex's private, owned leaf socket alias.
|
|
88
|
+
|
|
89
|
+
Codex may publish the configured endpoint as a symlink into its private
|
|
90
|
+
short-path directory. Only a single absolute leaf alias is accepted. Its
|
|
91
|
+
parent and the actual socket's parent must both pass the same protection
|
|
92
|
+
checks; the resolved target is used for connect and identities are rechecked.
|
|
93
|
+
"""
|
|
94
|
+
path = Path(path)
|
|
95
|
+
try:
|
|
96
|
+
parent_identity = _socket_parent(path)
|
|
97
|
+
info = path.lstat()
|
|
98
|
+
alias_identity = None
|
|
99
|
+
if stat.S_ISLNK(info.st_mode):
|
|
100
|
+
if info.st_uid != os.getuid():
|
|
101
|
+
raise AppServerError("unsafe_appserver_socket")
|
|
102
|
+
target = os.readlink(path)
|
|
103
|
+
if not target.startswith("/") or any(part in (".", "..") for part in target.split("/")):
|
|
104
|
+
raise AppServerError("unsafe_appserver_socket")
|
|
105
|
+
alias_identity = (info.st_dev, info.st_ino, parent_identity, target)
|
|
106
|
+
path = Path(target)
|
|
107
|
+
parent_identity = _socket_parent(path)
|
|
108
|
+
info = path.lstat()
|
|
109
|
+
if (not stat.S_ISSOCK(info.st_mode) or info.st_uid != os.getuid()
|
|
110
|
+
or info.st_mode & 0o077):
|
|
111
|
+
raise AppServerError("unsafe_appserver_socket")
|
|
112
|
+
return str(path), (info.st_dev, info.st_ino, parent_identity, alias_identity)
|
|
113
|
+
except OSError:
|
|
114
|
+
raise AppServerError("appserver_socket_unavailable") from None
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _auth_header(token_file):
|
|
118
|
+
try:
|
|
119
|
+
token = read_private_json(token_file).get("token")
|
|
120
|
+
except CredentialError:
|
|
121
|
+
raise AppServerError("appserver_credentials_unavailable") from None
|
|
122
|
+
if (not isinstance(token, str) or not 16 <= len(token) <= 4096
|
|
123
|
+
or any(ord(character) < 33 or ord(character) > 126 for character in token)):
|
|
124
|
+
raise AppServerError("invalid_appserver_credentials")
|
|
125
|
+
return {"Authorization": "Bearer " + token}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _check_peer(raw):
|
|
129
|
+
if hasattr(socket, "SO_PEERCRED"):
|
|
130
|
+
credentials = raw.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i"))
|
|
131
|
+
_, uid, _ = struct.unpack("3i", credentials)
|
|
132
|
+
if uid != os.getuid():
|
|
133
|
+
raise AppServerError("unsafe_appserver_peer")
|
|
134
|
+
elif hasattr(raw, "getpeereid"):
|
|
135
|
+
uid, _ = raw.getpeereid()
|
|
136
|
+
if uid != os.getuid():
|
|
137
|
+
raise AppServerError("unsafe_appserver_peer")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class AppServerConnection:
|
|
141
|
+
"""One serial connection. Call ``connect`` or use it as a context manager.
|
|
142
|
+
|
|
143
|
+
Requests are synchronous, but notifications and reverse requests are handled
|
|
144
|
+
while waiting for each response. They are bounded and never stored as logs.
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
def __init__(self, endpoint, *, token_file=None, timeout=10.0,
|
|
148
|
+
max_message_bytes=1024 * 1024, max_events=256):
|
|
149
|
+
self.kind, self.address = validate_endpoint(endpoint, token_file=token_file)
|
|
150
|
+
if (isinstance(timeout, bool) or not isinstance(timeout, (int, float))
|
|
151
|
+
or not math.isfinite(timeout) or not 0 < timeout <= 300
|
|
152
|
+
or type(max_message_bytes) is not int or not 256 <= max_message_bytes <= 16 * 1024 * 1024
|
|
153
|
+
or type(max_events) is not int or not 1 <= max_events <= 4096):
|
|
154
|
+
raise AppServerError("invalid_appserver_limits")
|
|
155
|
+
self.token_file = token_file
|
|
156
|
+
self.timeout = timeout
|
|
157
|
+
self.max_message_bytes = max_message_bytes
|
|
158
|
+
self.max_events = max_events
|
|
159
|
+
self.notifications_received = 0
|
|
160
|
+
self.server_requests_received = 0
|
|
161
|
+
self._events = []
|
|
162
|
+
self._socket = None
|
|
163
|
+
self._used = False
|
|
164
|
+
self._counter = 0
|
|
165
|
+
self._lock = threading.Lock()
|
|
166
|
+
|
|
167
|
+
def connect(self):
|
|
168
|
+
if self._used:
|
|
169
|
+
raise AppServerError("appserver_connection_already_used")
|
|
170
|
+
self._used = True
|
|
171
|
+
# A private logger also prevents global DEBUG settings exposing headers,
|
|
172
|
+
# prompts, tool output, or server error descriptions through websockets.
|
|
173
|
+
logger = logging.Logger("aot.appserver.private")
|
|
174
|
+
logger.disabled = True
|
|
175
|
+
options = dict(open_timeout=self.timeout, close_timeout=min(self.timeout, 1.0),
|
|
176
|
+
max_size=self.max_message_bytes, max_queue=16, proxy=None,
|
|
177
|
+
compression=None, logger=logger)
|
|
178
|
+
raw = None
|
|
179
|
+
try:
|
|
180
|
+
if self.kind == "unix":
|
|
181
|
+
identity = _private_socket(self.address)
|
|
182
|
+
raw = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
183
|
+
raw.settimeout(self.timeout)
|
|
184
|
+
raw.connect(identity[0])
|
|
185
|
+
_check_peer(raw)
|
|
186
|
+
if _private_socket(self.address) != identity:
|
|
187
|
+
raise AppServerError("unsafe_appserver_socket")
|
|
188
|
+
# websockets preserves the timeout of a supplied socket. Its
|
|
189
|
+
# reader must remain alive while this persistent client is idle;
|
|
190
|
+
# individual JSON-RPC receives have their own bounded timeout.
|
|
191
|
+
raw.settimeout(None)
|
|
192
|
+
self._socket = unix_connect(sock=raw, uri="ws://localhost/rpc", **options)
|
|
193
|
+
else:
|
|
194
|
+
self._socket = connect(self.address, additional_headers=_auth_header(self.token_file), **options)
|
|
195
|
+
self.request("initialize", {
|
|
196
|
+
"clientInfo": {"name": "agents_over_telegram_dispatcher", "version": __version__},
|
|
197
|
+
"capabilities": {"experimentalApi": True},
|
|
198
|
+
})
|
|
199
|
+
self._socket.send(json.dumps({"method": "initialized"}, separators=(",", ":")))
|
|
200
|
+
return self
|
|
201
|
+
except AppServerError:
|
|
202
|
+
self.close()
|
|
203
|
+
if raw is not None:
|
|
204
|
+
raw.close()
|
|
205
|
+
raise
|
|
206
|
+
except Exception:
|
|
207
|
+
self.close()
|
|
208
|
+
if raw is not None:
|
|
209
|
+
raw.close()
|
|
210
|
+
raise AppServerError("appserver_connect_failed") from None
|
|
211
|
+
|
|
212
|
+
def __enter__(self):
|
|
213
|
+
return self.connect()
|
|
214
|
+
|
|
215
|
+
def __exit__(self, *_):
|
|
216
|
+
self.close()
|
|
217
|
+
|
|
218
|
+
def close(self):
|
|
219
|
+
current, self._socket = self._socket, None
|
|
220
|
+
if current is not None:
|
|
221
|
+
try:
|
|
222
|
+
current.close()
|
|
223
|
+
except Exception:
|
|
224
|
+
pass
|
|
225
|
+
|
|
226
|
+
def request(self, method, params, *, mutating=False):
|
|
227
|
+
if self._socket is None:
|
|
228
|
+
raise AppServerError("appserver_not_connected")
|
|
229
|
+
if not self._lock.acquire(blocking=False):
|
|
230
|
+
raise AppServerError("appserver_concurrent_request")
|
|
231
|
+
attempted = False
|
|
232
|
+
timer = None
|
|
233
|
+
timer_lock = threading.Lock()
|
|
234
|
+
finished = False
|
|
235
|
+
timed_out = False
|
|
236
|
+
current = self._socket
|
|
237
|
+
|
|
238
|
+
def expire():
|
|
239
|
+
nonlocal timed_out
|
|
240
|
+
with timer_lock:
|
|
241
|
+
if finished:
|
|
242
|
+
return
|
|
243
|
+
timed_out = True
|
|
244
|
+
# WebSocket send() has no timeout argument. Shutdown also bounds
|
|
245
|
+
# a stalled send without changing the persistent reader timeout.
|
|
246
|
+
try:
|
|
247
|
+
current.socket.shutdown(socket.SHUT_RDWR)
|
|
248
|
+
except OSError:
|
|
249
|
+
pass
|
|
250
|
+
try:
|
|
251
|
+
if (not isinstance(method, str) or not 1 <= len(method) <= 256
|
|
252
|
+
or not isinstance(params, dict) or type(mutating) is not bool):
|
|
253
|
+
raise AppServerError("invalid_appserver_request")
|
|
254
|
+
self._counter += 1
|
|
255
|
+
request_id = f"aot-{self._counter}"
|
|
256
|
+
try:
|
|
257
|
+
outgoing = json.dumps({"id": request_id, "method": method, "params": params},
|
|
258
|
+
separators=(",", ":"), allow_nan=False)
|
|
259
|
+
except (TypeError, ValueError, RecursionError):
|
|
260
|
+
raise AppServerError("invalid_appserver_request") from None
|
|
261
|
+
if len(outgoing.encode("utf-8")) > self.max_message_bytes:
|
|
262
|
+
raise AppServerError("appserver_request_too_large")
|
|
263
|
+
deadline = time.monotonic() + self.timeout
|
|
264
|
+
timer = threading.Timer(self.timeout, expire)
|
|
265
|
+
timer.daemon = True
|
|
266
|
+
timer.start()
|
|
267
|
+
# A send exception may occur after some or all bytes reached the peer.
|
|
268
|
+
attempted = True
|
|
269
|
+
self._socket.send(outgoing)
|
|
270
|
+
while True:
|
|
271
|
+
remaining = deadline - time.monotonic()
|
|
272
|
+
if remaining <= 0:
|
|
273
|
+
raise TimeoutError()
|
|
274
|
+
raw = self._socket.recv(timeout=remaining)
|
|
275
|
+
message = self._parse(raw)
|
|
276
|
+
if "method" in message:
|
|
277
|
+
self._handle_event(message)
|
|
278
|
+
continue
|
|
279
|
+
if message.get("id") != request_id or type(message.get("id")) is not str:
|
|
280
|
+
raise AppServerError("appserver_response_id_mismatch")
|
|
281
|
+
if ("result" in message) == ("error" in message):
|
|
282
|
+
raise AppServerError("invalid_appserver_response")
|
|
283
|
+
if "error" in message:
|
|
284
|
+
error = message["error"]
|
|
285
|
+
if not isinstance(error, dict) or type(error.get("code")) is not int:
|
|
286
|
+
raise AppServerError("invalid_appserver_response")
|
|
287
|
+
# Error descriptions/data may contain secrets or chat content.
|
|
288
|
+
# Internal and application errors may follow a committed
|
|
289
|
+
# mutation. Only method/parameter rejection proves that it
|
|
290
|
+
# could not have run; -32600 is also used for runtime errors.
|
|
291
|
+
ambiguous = mutating and error["code"] not in (-32601, -32602)
|
|
292
|
+
raise AppServerError("appserver_rpc_error", ambiguous=ambiguous,
|
|
293
|
+
rpc_code=error["code"])
|
|
294
|
+
return message["result"]
|
|
295
|
+
except AppServerError as exc:
|
|
296
|
+
if attempted and exc.code != "appserver_rpc_error":
|
|
297
|
+
self.close()
|
|
298
|
+
raise AppServerError(exc.code, ambiguous=mutating) from None
|
|
299
|
+
raise
|
|
300
|
+
except TimeoutError:
|
|
301
|
+
self.close()
|
|
302
|
+
raise AppServerError("appserver_timeout", ambiguous=mutating and attempted) from None
|
|
303
|
+
except Exception:
|
|
304
|
+
self.close()
|
|
305
|
+
code = "appserver_timeout" if timed_out else "appserver_transport_failed"
|
|
306
|
+
raise AppServerError(code, ambiguous=mutating and attempted) from None
|
|
307
|
+
finally:
|
|
308
|
+
with timer_lock:
|
|
309
|
+
finished = True
|
|
310
|
+
if timer is not None:
|
|
311
|
+
timer.cancel()
|
|
312
|
+
self._lock.release()
|
|
313
|
+
|
|
314
|
+
def _handle_event(self, message):
|
|
315
|
+
if (not isinstance(message["method"], str) or not 1 <= len(message["method"]) <= 256
|
|
316
|
+
or "result" in message or "error" in message):
|
|
317
|
+
raise AppServerError("invalid_appserver_response")
|
|
318
|
+
if "id" not in message:
|
|
319
|
+
self.notifications_received += 1
|
|
320
|
+
# Busy turns can emit hundreds of deltas between RPC replies. They
|
|
321
|
+
# are irrelevant to wake delivery and must not fill the control-event
|
|
322
|
+
# buffer or make an otherwise accepted mutation look uncertain.
|
|
323
|
+
if message["method"] not in _EVENT_METHODS:
|
|
324
|
+
return
|
|
325
|
+
kind = "notification"
|
|
326
|
+
else:
|
|
327
|
+
request_id = message["id"]
|
|
328
|
+
if (type(request_id) not in (int, str)
|
|
329
|
+
or isinstance(request_id, str) and len(request_id) > 256):
|
|
330
|
+
raise AppServerError("invalid_appserver_response")
|
|
331
|
+
self.server_requests_received += 1
|
|
332
|
+
kind = "server_request"
|
|
333
|
+
# Requests are broadcast to the owning desktop too. Responding with
|
|
334
|
+
# either approval OR an error would race the actual owner's answer.
|
|
335
|
+
# Leave them unanswered and expose content-free attention metadata.
|
|
336
|
+
event = {"kind": kind, "method": message["method"] if message["method"] in _EVENT_METHODS else "other"}
|
|
337
|
+
params = message.get("params")
|
|
338
|
+
if isinstance(params, dict):
|
|
339
|
+
for field in ("threadId", "turnId"):
|
|
340
|
+
value = params.get(field)
|
|
341
|
+
if field == "turnId" and value is None and isinstance(params.get("turn"), dict):
|
|
342
|
+
value = params["turn"].get("id")
|
|
343
|
+
if isinstance(value, str):
|
|
344
|
+
try:
|
|
345
|
+
event[field] = str(UUID(value))
|
|
346
|
+
except ValueError:
|
|
347
|
+
pass
|
|
348
|
+
if len(self._events) >= self.max_events:
|
|
349
|
+
raise AppServerError("appserver_event_limit")
|
|
350
|
+
self._events.append(event)
|
|
351
|
+
|
|
352
|
+
def _parse(self, raw):
|
|
353
|
+
if not isinstance(raw, str) or len(raw.encode("utf-8")) > self.max_message_bytes:
|
|
354
|
+
raise AppServerError("invalid_appserver_response")
|
|
355
|
+
try:
|
|
356
|
+
message = json.loads(raw)
|
|
357
|
+
except (ValueError, RecursionError):
|
|
358
|
+
raise AppServerError("invalid_appserver_response") from None
|
|
359
|
+
if not isinstance(message, dict) or message.get("jsonrpc", "2.0") != "2.0":
|
|
360
|
+
raise AppServerError("invalid_appserver_response")
|
|
361
|
+
return message
|
|
362
|
+
|
|
363
|
+
def drain(self, timeout=0):
|
|
364
|
+
"""Return bounded content-free events; never answer server requests.
|
|
365
|
+
|
|
366
|
+
A nonzero timeout waits for the first new event only. Buffered events
|
|
367
|
+
from earlier requests are returned immediately. Call regularly while a
|
|
368
|
+
connection is idle; WebSocket receive buffering also has a fixed limit.
|
|
369
|
+
"""
|
|
370
|
+
if (isinstance(timeout, bool) or not isinstance(timeout, (int, float))
|
|
371
|
+
or not math.isfinite(timeout) or not 0 <= timeout <= self.timeout):
|
|
372
|
+
raise AppServerError("invalid_appserver_limits")
|
|
373
|
+
if self._socket is None:
|
|
374
|
+
raise AppServerError("appserver_not_connected")
|
|
375
|
+
if not self._lock.acquire(blocking=False):
|
|
376
|
+
raise AppServerError("appserver_concurrent_request")
|
|
377
|
+
try:
|
|
378
|
+
remaining = 0 if self._events else timeout
|
|
379
|
+
frames = 0
|
|
380
|
+
while len(self._events) < self.max_events and frames < self.max_events:
|
|
381
|
+
try:
|
|
382
|
+
raw = self._socket.recv(timeout=remaining)
|
|
383
|
+
except TimeoutError:
|
|
384
|
+
break
|
|
385
|
+
frames += 1
|
|
386
|
+
remaining = 0
|
|
387
|
+
message = self._parse(raw)
|
|
388
|
+
if "method" not in message:
|
|
389
|
+
raise AppServerError("appserver_unexpected_response")
|
|
390
|
+
self._handle_event(message)
|
|
391
|
+
events, self._events = self._events, []
|
|
392
|
+
return events
|
|
393
|
+
except AppServerError:
|
|
394
|
+
self.close()
|
|
395
|
+
raise
|
|
396
|
+
except Exception:
|
|
397
|
+
self.close()
|
|
398
|
+
raise AppServerError("appserver_transport_failed") from None
|
|
399
|
+
finally:
|
|
400
|
+
self._lock.release()
|