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.
Files changed (52) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +141 -0
  3. package/docs/BOT_EXCHANGES.md +121 -0
  4. package/docs/COMPATIBILITY.md +110 -0
  5. package/docs/DIRECT_DISPATCH.md +155 -0
  6. package/docs/HOSTS.md +244 -0
  7. package/docs/IMPLEMENTATION_STATUS.md +205 -0
  8. package/docs/LIVE_VALIDATION.md +35 -0
  9. package/docs/MACOS_SERVICE.md +89 -0
  10. package/docs/OPERATIONS.md +568 -0
  11. package/docs/REACTIONS.md +51 -0
  12. package/docs/RELAY.md +115 -0
  13. package/docs/RELEASING.md +45 -0
  14. package/docs/schemas/mcp.schema.json +120 -0
  15. package/docs/schemas/sources.json +9 -0
  16. package/integrations/pi/agents-over-telegram.ts +154 -0
  17. package/package.json +41 -0
  18. package/pyproject.toml +37 -0
  19. package/requirements/build.txt +18 -0
  20. package/requirements/runtime.txt +532 -0
  21. package/scripts/bootstrap_runtime.py +402 -0
  22. package/skills/telegram-coordinate/SKILL.md +67 -0
  23. package/skills/telegram-setup/SKILL.md +81 -0
  24. package/src/agents_over_telegram/__init__.py +2 -0
  25. package/src/agents_over_telegram/__main__.py +2 -0
  26. package/src/agents_over_telegram/appserver_client.py +400 -0
  27. package/src/agents_over_telegram/cli.py +851 -0
  28. package/src/agents_over_telegram/codex_trust.py +206 -0
  29. package/src/agents_over_telegram/compat.py +207 -0
  30. package/src/agents_over_telegram/core.py +4253 -0
  31. package/src/agents_over_telegram/credentials.py +108 -0
  32. package/src/agents_over_telegram/demo.py +85 -0
  33. package/src/agents_over_telegram/desktop_bridge.py +537 -0
  34. package/src/agents_over_telegram/desktop_dispatcher.py +680 -0
  35. package/src/agents_over_telegram/dispatcher.py +260 -0
  36. package/src/agents_over_telegram/host_config.py +125 -0
  37. package/src/agents_over_telegram/hosts.py +590 -0
  38. package/src/agents_over_telegram/judge.py +230 -0
  39. package/src/agents_over_telegram/macos_process.py +133 -0
  40. package/src/agents_over_telegram/markdown.py +127 -0
  41. package/src/agents_over_telegram/mcp_server.py +652 -0
  42. package/src/agents_over_telegram/net.py +130 -0
  43. package/src/agents_over_telegram/onboarding.py +719 -0
  44. package/src/agents_over_telegram/push.py +421 -0
  45. package/src/agents_over_telegram/relay.py +380 -0
  46. package/src/agents_over_telegram/relay_api.py +591 -0
  47. package/src/agents_over_telegram/relay_watch.py +171 -0
  48. package/src/agents_over_telegram/serve.py +626 -0
  49. package/src/agents_over_telegram/settings_panel.py +216 -0
  50. package/src/agents_over_telegram/transport.py +720 -0
  51. package/src/agents_over_telegram/webhook.py +219 -0
  52. package/uv.lock +1011 -0
@@ -0,0 +1,591 @@
1
+ """The relay API: agents' tool calls go to the always-on collector over a local socket.
2
+
3
+ (relay.py is the older Codex desktop relay's notification store; it is unrelated.)
4
+
5
+ ``aot serve`` runs the newest installed runtime and is the one process that
6
+ fetches from Telegram. Since the relay API it also answers agents' tool calls
7
+ (``messages_poll``, ``message_send`` and the rest): an agent's MCP server or
8
+ ``aot tool`` command sends the call over a Unix socket in the state directory,
9
+ and the relay runs it with the same validation, scoping and envelope as a
10
+ local call (mcp_server.call_tool). So every agent's work runs on the relay's
11
+ code, whatever runtime its project points at.
12
+
13
+ Access needs all of:
14
+ - the socket directory (0700) and socket (0600) belong to this user;
15
+ - the connecting process runs as this user (SO_PEERCRED / LOCAL_PEERCRED);
16
+ - the request carries the client's secret, which picks the only inbox it
17
+ can reach.
18
+
19
+ Each request names its protocol version. A relay refuses a node older than
20
+ MIN_PROTOCOL with ``node_too_old``; a node finding an older relay, or none,
21
+ runs the call itself as before. Once a request has been sent the node never
22
+ runs it a second time: a lost answer is reported, not retried, because a send
23
+ may already have gone out.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import errno
28
+ import json
29
+ import os
30
+ import secrets
31
+ import socket
32
+ import socketserver
33
+ import stat
34
+ import struct
35
+ import sys
36
+ import threading
37
+ import time
38
+ from pathlib import Path
39
+
40
+ from . import compat
41
+ from .credentials import private_directory
42
+
43
+ PROTOCOL = 1
44
+ MIN_PROTOCOL = 1
45
+ SOCKET_DIR = 'relay'
46
+ SOCKET_NAME = 'relay.sock'
47
+ MAX_REQUEST = 1024 * 1024
48
+ MAX_RESPONSE = 4 * 1024 * 1024
49
+ # A call can wait on a Telegram request (a send, an attachment download).
50
+ CALL_TIMEOUT = 90.0
51
+ CONNECT_TIMEOUT = 2.0
52
+ # The longest a waiting agent's request is held before it is answered anyway.
53
+ WAIT_LIMIT = 50.0
54
+ # The inbox work of hooks and waiters (push.py) the relay runs for agents.
55
+ NODE_OPS = frozenset({'hook', 'claim', 'watch_prepare'})
56
+ # Calls after which other agents may have something new (a peer delivery).
57
+ _CHANGING_TOOLS = frozenset({'message_send'})
58
+ # A request line must arrive within this, however slowly its bytes trickle in.
59
+ REQUEST_DEADLINE = 10.0
60
+ # At most this many requests are handled at once; more get "busy" and the
61
+ # agents run those calls themselves.
62
+ MAX_ACTIVE = 32
63
+ # Waiting agents (one per session) have their own slots.
64
+ MAX_WAITS = 64
65
+ # Hooks and inbox claims run inside host hooks with short time limits.
66
+ NODE_TIMEOUT = 4.0
67
+ # On stop, requests already in flight get this long to finish.
68
+ DRAIN_SECONDS = 3.0
69
+ # The relay records the socket it listens on here, inside the state
70
+ # directory, so agents whose environment differs (another TMPDIR) find it.
71
+ SOCKET_RECORD = 'relay-socket.json'
72
+
73
+
74
+ class Unavailable(Exception):
75
+ """No relay took the request; the caller may run it locally."""
76
+
77
+
78
+ # Unix socket paths are limited to about 104 bytes (macOS) or 108 (Linux).
79
+ MAX_SOCKET_PATH = 100
80
+
81
+
82
+ def socket_path(state):
83
+ """The relay socket for a state directory.
84
+
85
+ Normally ``<state>/relay/relay.sock``. A state directory whose path is too
86
+ long for a Unix socket gets a short one in a private per-user directory
87
+ instead, named after the state directory's path, so the relay and its
88
+ agents agree on it: $XDG_RUNTIME_DIR (Linux), $TMPDIR (per-user on
89
+ macOS), whichever exists, is ours and private and fits, else
90
+ /tmp/aot-<uid>.
91
+ """
92
+ state = Path(state).absolute()
93
+ path = state / SOCKET_DIR / SOCKET_NAME
94
+ if len(os.fsencode(path)) <= MAX_SOCKET_PATH:
95
+ return path
96
+ import hashlib
97
+ digest = hashlib.sha256(os.fsencode(os.path.realpath(state))).hexdigest()[:16]
98
+ for base in [*_private_runtime_dirs(), _short_base()]:
99
+ short = base / f'aot-relay-{digest}' / SOCKET_NAME
100
+ if len(os.fsencode(short)) <= MAX_SOCKET_PATH:
101
+ return short
102
+ return short
103
+
104
+
105
+ def _private_runtime_dirs():
106
+ """Per-user runtime directories from the environment that exist, are ours and nobody else's."""
107
+ for name in ('XDG_RUNTIME_DIR', 'TMPDIR'):
108
+ value = os.environ.get(name)
109
+ if not value or not os.path.isabs(value):
110
+ continue
111
+ try:
112
+ info = os.lstat(value)
113
+ except OSError:
114
+ continue
115
+ if stat.S_ISDIR(info.st_mode) and info.st_uid == compat.getuid() and not info.st_mode & 0o077:
116
+ yield Path(value)
117
+
118
+
119
+ def _short_base():
120
+ return Path('/tmp') / f'aot-{compat.getuid()}'
121
+
122
+
123
+ def peer_uid(connection):
124
+ """The user id of the process on the other end of a Unix socket, or None when unknown."""
125
+ if hasattr(socket, 'SO_PEERCRED'):
126
+ size = struct.calcsize('3i')
127
+ _pid, uid, _gid = struct.unpack('3i', connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, size))
128
+ return uid
129
+ if sys.platform == 'darwin':
130
+ # SOL_LOCAL=0, LOCAL_PEERCRED=1: struct xucred {u_int version; uid_t uid; short ngroups; gid_t groups[16]}.
131
+ data = connection.getsockopt(0, 1, struct.calcsize('IIh16I'))
132
+ return struct.unpack_from('II', data)[1]
133
+ return None
134
+
135
+
136
+ def _read_line(connection, limit, deadline=None):
137
+ chunks, size = [], 0
138
+ while True:
139
+ if deadline is not None:
140
+ left = deadline - time.monotonic()
141
+ if left <= 0:
142
+ raise ValueError('too_slow')
143
+ connection.settimeout(left)
144
+ try:
145
+ chunk = connection.recv(65536)
146
+ except TimeoutError:
147
+ if deadline is None:
148
+ raise
149
+ raise ValueError('too_slow') from None
150
+ if not chunk:
151
+ break
152
+ chunks.append(chunk)
153
+ size += len(chunk)
154
+ if b'\n' in chunk:
155
+ break
156
+ if size > limit:
157
+ raise ValueError('too_large')
158
+ data = b''.join(chunks)
159
+ line, _, _ = data.partition(b'\n')
160
+ if len(line) > limit:
161
+ raise ValueError('too_large')
162
+ return line
163
+
164
+
165
+ def _send(connection, value):
166
+ connection.sendall(json.dumps(value, ensure_ascii=False, separators=(',', ':')).encode('utf-8') + b'\n')
167
+
168
+
169
+ class Relay:
170
+ """Answers tool calls on the state directory's socket from a background thread."""
171
+
172
+ def __init__(self, core, state, log=None):
173
+ self.core, self.state = core, Path(state)
174
+ self.log = log or (lambda text: None)
175
+ self.server = None
176
+ # Waiting agents hold a request until the generation moves: after a
177
+ # collection routed updates, or a call that may deliver to a peer. The
178
+ # instance tells a waiter that the relay restarted.
179
+ self.instance = secrets.token_hex(8)
180
+ self.generation = 0
181
+ self.closing = False
182
+ self.changed = threading.Condition()
183
+ self.path = None
184
+ self.active = threading.BoundedSemaphore(MAX_ACTIVE)
185
+ self.waits = threading.BoundedSemaphore(MAX_WAITS)
186
+ self.connections = threading.BoundedSemaphore(MAX_ACTIVE + MAX_WAITS)
187
+ # When an agent last called or waited (time.monotonic), for a
188
+ # collector started on demand that stops when idle.
189
+ self.last_activity = None
190
+ # Call entries for the activity log, written once per collector cycle.
191
+ self._activity = []
192
+
193
+ def notify(self):
194
+ """Wake every waiting agent; each then checks its own inbox."""
195
+ with self.changed:
196
+ self.generation += 1
197
+ self.changed.notify_all()
198
+
199
+ def _wait(self, instance, generation, timeout):
200
+ with self.changed:
201
+ if instance == self.instance and generation == self.generation:
202
+ self.changed.wait_for(lambda: self.generation != generation or self.closing, timeout)
203
+ return {'instance': self.instance, 'generation': self.generation}
204
+
205
+ def answer(self, request):
206
+ """One request's answer; never raises."""
207
+ from .core import CoreError
208
+ from .mcp_server import _error_body, call_tool
209
+ if not isinstance(request, dict) or not isinstance(request.get('protocol'), int):
210
+ return {'protocol': PROTOCOL, 'ok': False, 'error': 'bad_request'}
211
+ if request['protocol'] < MIN_PROTOCOL:
212
+ # Fixed text: the node's project points at a runtime this relay no longer serves.
213
+ return {'protocol': PROTOCOL, 'ok': False, 'error': 'node_too_old', 'min_protocol': MIN_PROTOCOL}
214
+ if request['protocol'] > PROTOCOL:
215
+ return {'protocol': PROTOCOL, 'ok': False, 'error': 'relay_too_old'}
216
+ secret, tool, arguments = request.get('secret'), request.get('tool'), request.get('arguments')
217
+ op = request.get('op')
218
+ if not isinstance(secret, str) or not (isinstance(tool, str) or op == 'wait' or op in NODE_OPS):
219
+ return {'protocol': PROTOCOL, 'ok': False, 'error': 'bad_request'}
220
+ try:
221
+ client_id = self.core.authenticate(secret)
222
+ except CoreError:
223
+ if op in NODE_OPS:
224
+ return {'protocol': PROTOCOL, 'ok': True, 'error_code': 'authentication_failed'}
225
+ return {'protocol': PROTOCOL, 'ok': True, 'body': _error_body('authentication_failed')}
226
+ if op in NODE_OPS:
227
+ return self._node_op(op, client_id, request)
228
+ if request.get('op') == 'wait':
229
+ timeout = request.get('timeout')
230
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not 0 <= timeout <= WAIT_LIMIT:
231
+ return {'protocol': PROTOCOL, 'ok': False, 'error': 'bad_request'}
232
+ return {'protocol': PROTOCOL, 'ok': True,
233
+ 'wait': self._wait(request.get('instance'), request.get('generation'), timeout)}
234
+ from .mcp_server import _TOOL_MAP, _VALIDATORS
235
+ if tool not in _TOOL_MAP or not isinstance(arguments, dict) or not _VALIDATORS[tool].is_valid(arguments):
236
+ # A newer agent may know a tool or argument this relay does not.
237
+ # Nothing ran, so it can run the call itself.
238
+ return {'protocol': PROTOCOL, 'ok': False, 'error': 'not_handled'}
239
+ body = call_tool(self.core, client_id, tool, arguments)
240
+ if tool in _CHANGING_TOOLS and body.get('ok'):
241
+ # A send can deliver to a peer agent; every waiter then checks its
242
+ # own inbox, which is cheap and finds nothing for most of them.
243
+ self.notify()
244
+ return {'protocol': PROTOCOL, 'ok': True, 'body': body}
245
+
246
+ def _record(self, request, answer, started):
247
+ """Log a call's duration and outcome; waits are not logged, they block by design."""
248
+ op = request.get('op') if isinstance(request, dict) else None
249
+ name = op or (request.get('tool') if isinstance(request, dict) else None)
250
+ body = answer.get('body') if isinstance(answer, dict) else None
251
+ if not isinstance(answer, dict) or not answer.get('ok'):
252
+ outcome = (answer or {}).get('error') or 'bad_request'
253
+ elif answer.get('error_code'):
254
+ outcome = answer['error_code']
255
+ elif isinstance(body, dict) and not body.get('ok'):
256
+ outcome = (body.get('error') or {}).get('code') or 'error'
257
+ else:
258
+ outcome = 'ok'
259
+ entry = ('relay', {'call': name if isinstance(name, str) else 'unknown', 'outcome': outcome,
260
+ 'ms': round((time.monotonic() - started) * 1000)}, self.core.clock())
261
+ # Buffered: a write per call would add a transaction to every hook.
262
+ # The collector writes them once per cycle (flush_activity).
263
+ with self.changed:
264
+ self._activity.append(entry)
265
+ del self._activity[:-self.core.ACTIVITY_KEEP]
266
+
267
+ def flush_activity(self):
268
+ """Write the buffered call entries to the activity log in one transaction."""
269
+ with self.changed:
270
+ entries, self._activity = self._activity, []
271
+ self.core.record_activities(entries)
272
+
273
+ def _node_op(self, op, client_id, request):
274
+ """The inbox work of hooks and waiters, run here so agents never open the database."""
275
+ from . import push
276
+ from .core import CoreError
277
+ try:
278
+ if op == 'hook':
279
+ event, payload = request.get('event'), request.get('payload')
280
+ if not isinstance(event, str) or not isinstance(payload, dict):
281
+ return {'protocol': PROTOCOL, 'ok': False, 'error': 'bad_request'}
282
+ result = push.hook_response(self.core, client_id, event, payload)
283
+ elif op == 'claim':
284
+ result = push.claim_new(self.core, client_id, request.get('surface'))
285
+ else: # watch_prepare
286
+ push.prepare_watch(self.core, client_id, request.get('announce_backlog') is not False)
287
+ result = None
288
+ except CoreError as error:
289
+ return {'protocol': PROTOCOL, 'ok': True, 'error_code': error.code}
290
+ return {'protocol': PROTOCOL, 'ok': True, 'result': result}
291
+
292
+ def handle(self, connection):
293
+ self.last_activity = time.monotonic()
294
+
295
+ def busy():
296
+ try:
297
+ _send(connection, {'protocol': PROTOCOL, 'ok': False, 'error': 'busy'})
298
+ except OSError:
299
+ pass
300
+ # A connection slot covers reading the request (bounded by
301
+ # REQUEST_DEADLINE); then a call slot or, for a wait, a wait slot, so
302
+ # waiting agents cannot use up the slots calls need.
303
+ if not self.connections.acquire(blocking=False):
304
+ busy()
305
+ return
306
+ try:
307
+ # A peer whose user cannot be determined is refused, like another user.
308
+ if peer_uid(connection) != compat.getuid():
309
+ _send(connection, {'protocol': PROTOCOL, 'ok': False, 'error': 'forbidden'})
310
+ return
311
+ try:
312
+ request = json.loads(_read_line(connection, MAX_REQUEST, time.monotonic() + REQUEST_DEADLINE))
313
+ except (ValueError, UnicodeDecodeError, RecursionError):
314
+ _send(connection, {'protocol': PROTOCOL, 'ok': False, 'error': 'bad_request'})
315
+ return
316
+ slot = self.waits if isinstance(request, dict) and request.get('op') == 'wait' else self.active
317
+ if not slot.acquire(blocking=False):
318
+ busy()
319
+ return
320
+ try:
321
+ connection.settimeout(CALL_TIMEOUT)
322
+ started = time.monotonic()
323
+ try:
324
+ answer = self.answer(request)
325
+ except Exception:
326
+ answer = {'protocol': PROTOCOL, 'ok': False, 'error': 'bad_request'}
327
+ _send(connection, answer)
328
+ if slot is self.active:
329
+ self._record(request, answer, started)
330
+ finally:
331
+ slot.release()
332
+ except OSError:
333
+ pass
334
+ finally:
335
+ self.connections.release()
336
+
337
+ def start(self):
338
+ """Listen on the socket; returns the server thread."""
339
+ if not hasattr(socket, 'AF_UNIX'):
340
+ # Python on Windows has no Unix sockets; agents run their calls themselves.
341
+ raise OSError(errno.EAFNOSUPPORT, 'Unix sockets are not available on this platform')
342
+ path = socket_path(self.state)
343
+ if self.state.absolute() not in path.parents:
344
+ # The short path's runtime directory must be ours too, not one
345
+ # another user created first in /tmp.
346
+ private_directory(path.parent.parent)
347
+ private_directory(path.parent)
348
+ try:
349
+ info = path.lstat()
350
+ except FileNotFoundError:
351
+ pass
352
+ else:
353
+ # Only a socket of ours, left by a relay that stopped, is replaced.
354
+ if not stat.S_ISSOCK(info.st_mode) or info.st_uid != compat.getuid():
355
+ raise OSError(errno.EEXIST, 'relay socket path is taken')
356
+ probe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
357
+ probe.settimeout(CONNECT_TIMEOUT)
358
+ try:
359
+ probe.connect(str(path))
360
+ except ConnectionRefusedError:
361
+ # Nobody listens: a relay that stopped left it behind.
362
+ path.unlink()
363
+ except OSError:
364
+ # A timeout can be a busy relay with a full backlog; keep its socket.
365
+ raise OSError(errno.EADDRINUSE, 'the relay socket did not answer') from None
366
+ else:
367
+ raise OSError(errno.EADDRINUSE, 'another relay answers on this socket')
368
+ finally:
369
+ probe.close()
370
+ relay = self
371
+
372
+ class Handler(socketserver.BaseRequestHandler):
373
+ def handle(self):
374
+ relay.handle(self.request)
375
+
376
+ class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
377
+ daemon_threads = True
378
+
379
+ previous = os.umask(0o177)
380
+ try:
381
+ self.server = Server(str(path), Handler)
382
+ finally:
383
+ os.umask(previous)
384
+ os.chmod(path, 0o600)
385
+ self.path = path
386
+ from .credentials import write_private_json
387
+ record = self.state / SOCKET_RECORD
388
+ write_private_json(record, {'version': 1, 'socket': str(path)}, overwrite=record.exists())
389
+ thread = threading.Thread(target=self.server.serve_forever, name='aot-relay', daemon=True)
390
+ thread.start()
391
+ self.log(f'aot serve: answering agents on {path}')
392
+ return thread
393
+
394
+ def stop(self):
395
+ with self.changed:
396
+ self.closing = True
397
+ self.changed.notify_all()
398
+ if self.server is not None:
399
+ # Stop accepting, then let the requests already in flight finish:
400
+ # a claim cut off mid-way leaves its agent with a lost answer and a
401
+ # "messages may be waiting" notice for nothing.
402
+ self.server.shutdown()
403
+ self._drain()
404
+ self.server.server_close()
405
+ for leftover in (self.path or socket_path(self.state), self.state / SOCKET_RECORD):
406
+ try:
407
+ leftover.unlink()
408
+ except OSError:
409
+ pass
410
+ self.server = None
411
+ self.flush_activity()
412
+
413
+ def _drain(self):
414
+ """Wait up to DRAIN_SECONDS for every request in flight to finish."""
415
+ deadline, taken = time.monotonic() + DRAIN_SECONDS, 0
416
+ while taken < MAX_ACTIVE + MAX_WAITS:
417
+ left = deadline - time.monotonic()
418
+ if left <= 0 or not self.connections.acquire(timeout=left):
419
+ break
420
+ taken += 1
421
+ for _ in range(taken):
422
+ self.connections.release()
423
+
424
+
425
+ def recorded_socket(state):
426
+ """The socket the running relay recorded, or None."""
427
+ from .credentials import CredentialError, read_private_json
428
+ try:
429
+ value = read_private_json(Path(state) / SOCKET_RECORD).get('socket')
430
+ except (CredentialError, OSError):
431
+ return None
432
+ return Path(value) if isinstance(value, str) and os.path.isabs(value) else None
433
+
434
+
435
+
436
+ def _request(state, request, timeout):
437
+ """Send one request; its answer, None when the answer was lost, Unavailable when nobody took it."""
438
+ if not hasattr(socket, 'AF_UNIX'):
439
+ raise Unavailable('no_unix_sockets')
440
+ path = recorded_socket(state) or socket_path(state)
441
+ try:
442
+ info = path.parent.lstat()
443
+ if not stat.S_ISDIR(info.st_mode) or info.st_uid != compat.getuid() or info.st_mode & 0o077:
444
+ raise Unavailable('unsafe_relay_directory')
445
+ except FileNotFoundError:
446
+ raise Unavailable('no_relay') from None
447
+ connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
448
+ try:
449
+ connection.settimeout(CONNECT_TIMEOUT)
450
+ try:
451
+ connection.connect(str(path))
452
+ except OSError:
453
+ raise Unavailable('no_relay') from None
454
+ if peer_uid(connection) != compat.getuid():
455
+ raise Unavailable('foreign_relay')
456
+ connection.settimeout(timeout)
457
+ try:
458
+ _send(connection, {'protocol': PROTOCOL, **request})
459
+ except OSError:
460
+ # A busy relay answers and closes before reading the request, so
461
+ # the send can fail; its answer may still be waiting to be read.
462
+ pass
463
+ try:
464
+ answer = json.loads(_read_line(connection, MAX_RESPONSE))
465
+ except (OSError, ValueError, UnicodeDecodeError):
466
+ return None
467
+ finally:
468
+ connection.close()
469
+ if not isinstance(answer, dict):
470
+ return None
471
+ if answer.get('error') in ('relay_too_old', 'not_handled', 'busy'):
472
+ # Nothing ran on the relay; the agent runs the call itself.
473
+ raise Unavailable(answer['error'])
474
+ return answer
475
+
476
+
477
+ def call(state, secret, tool, arguments, timeout=CALL_TIMEOUT):
478
+ """Run one tool call on the relay and return its body.
479
+
480
+ Raises Unavailable when no relay took the request (no socket, nobody
481
+ listening, a relay older than this node); the caller then runs it itself.
482
+ A request that was sent is never run again: a lost answer comes back as
483
+ relay_no_answer.
484
+ """
485
+ from .mcp_server import _error_body
486
+ answer = _request(state, {'secret': secret, 'tool': tool, 'arguments': arguments}, timeout)
487
+ if answer is None:
488
+ return _error_body('relay_no_answer')
489
+ if answer.get('ok') and isinstance(answer.get('body'), dict):
490
+ return answer['body']
491
+ if answer.get('error') == 'node_too_old':
492
+ return _error_body('node_too_old')
493
+ return _error_body('relay_refused')
494
+
495
+
496
+ class Waiter:
497
+ """Blocks a watching agent until the relay has news, instead of polling the inbox.
498
+
499
+ Calling it waits up to ``timeout`` seconds and returns True when the relay
500
+ answered (with news or not), False when no relay is there; the watcher
501
+ then collects and paces itself as before.
502
+ """
503
+
504
+ def __init__(self, state, secret):
505
+ self.state, self.secret = Path(state), secret
506
+ self.instance = self.generation = None
507
+
508
+ def __call__(self, timeout):
509
+ timeout = max(0.0, min(float(timeout), WAIT_LIMIT))
510
+ try:
511
+ answer = _request(self.state, {'op': 'wait', 'secret': self.secret, 'instance': self.instance,
512
+ 'generation': self.generation, 'timeout': timeout}, timeout + 10)
513
+ except Unavailable:
514
+ return False
515
+ wait = answer.get('wait') if isinstance(answer, dict) else None
516
+ if not isinstance(wait, dict):
517
+ return False
518
+ self.instance, self.generation = wait.get('instance'), wait.get('generation')
519
+ return True
520
+
521
+
522
+ class Lost(Exception):
523
+ """The relay took the request but its answer never arrived.
524
+
525
+ The work may have run there (a claim may have recorded announcements), so
526
+ the agent must not run it a second time on its own database handle.
527
+ """
528
+
529
+
530
+ class Node:
531
+ """An agent's side of the relay: hook answers, inbox claims, waits and status.
532
+
533
+ Every method raises Unavailable when no relay took the request, and the
534
+ caller then does the work itself on its own database handle. A relay that
535
+ predates an operation answers bad_request before running anything, which
536
+ counts as unavailable too.
537
+ """
538
+
539
+ def __init__(self, state, secret):
540
+ self.state, self.secret = Path(state), secret
541
+ self.waiter = Waiter(state, secret)
542
+
543
+ def _op(self, op, **fields):
544
+ answer = _request(self.state, {'op': op, 'secret': self.secret, **fields}, NODE_TIMEOUT)
545
+ if answer is None:
546
+ raise Lost(op)
547
+ if not isinstance(answer, dict) or not answer.get('ok'):
548
+ raise Unavailable(answer.get('error') or 'no_answer')
549
+ if answer.get('error_code'):
550
+ from .core import CoreError
551
+ raise CoreError(answer['error_code'])
552
+ return answer.get('result')
553
+
554
+ def hook(self, event, payload):
555
+ return self._op('hook', event=event, payload=payload)
556
+
557
+ def claim(self, surface):
558
+ return self._op('claim', surface=surface)
559
+
560
+ def prepare_watch(self, announce_backlog):
561
+ self._op('watch_prepare', announce_backlog=announce_backlog)
562
+
563
+ def wait(self, timeout):
564
+ return self.waiter(timeout)
565
+
566
+ def status(self):
567
+ body = call(self.state, self.secret, 'connection_status', {}, timeout=NODE_TIMEOUT * 2)
568
+ if not body.get('ok'):
569
+ from .core import CoreError
570
+ raise CoreError((body.get('error') or {}).get('code') or 'relay_refused')
571
+ return body['result']
572
+
573
+
574
+ class LazyCore:
575
+ """A database handle opened on first use, for agents that use the relay.
576
+
577
+ Agents keep a local path for when no relay answers; building a Core opens
578
+ and migrates the database, so it waits until that path is actually taken.
579
+ """
580
+
581
+ def __init__(self, factory):
582
+ self._factory, self._core = factory, None
583
+
584
+ @property
585
+ def opened(self):
586
+ return self._core is not None
587
+
588
+ def __getattr__(self, name):
589
+ if self._core is None:
590
+ self._core = self._factory()
591
+ return getattr(self._core, name)