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,537 @@
1
+ """Preserve desktop stdio while sharing its app-server over a private Unix socket.
2
+
3
+ This executable is an opt-in CODEX_CLI_PATH replacement. It requires an explicit
4
+ AOT_CODEX_REAL_BINARY, and normal app-server launches additionally require an
5
+ AOT_CODEX_SOCKET whose parent is an existing private directory. Other CLI calls
6
+ are delegated verbatim. The bundled ``app-server proxy`` isn't suitable here:
7
+ it forwards raw bytes while ``--listen unix://...`` expects WebSocket framing.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import fcntl
12
+ import json
13
+ import logging
14
+ import os
15
+ from pathlib import Path
16
+ import signal
17
+ import socket
18
+ import stat
19
+ import struct
20
+ import subprocess
21
+ import sys
22
+ import threading
23
+ import time
24
+ from collections.abc import Mapping, Sequence
25
+
26
+ from websockets.exceptions import ConnectionClosed
27
+ from websockets.sync.client import unix_connect
28
+
29
+
30
+ MAX_MESSAGE_BYTES = 64 * 1024 * 1024
31
+ START_TIMEOUT_SECONDS = 30.0
32
+ STOP_TIMEOUT_SECONDS = 5.0
33
+ MAX_DISPATCH_LOG_BYTES = 1024 * 1024
34
+ _WEBSOCKET_LOGGER = logging.Logger("aot.desktop_bridge.websocket", level=logging.CRITICAL + 1)
35
+ _WEBSOCKET_LOGGER.disabled = True
36
+ _WEBSOCKET_LOGGER.propagate = False
37
+
38
+
39
+ class BridgeError(ValueError):
40
+ """A diagnostic which doesn't expose CLI arguments or environment values."""
41
+
42
+
43
+ def handshake_id(value) -> tuple[str, str | int] | None:
44
+ """Match bounded JSON-RPC IDs without treating bool as an integer."""
45
+ if type(value) is str and len(value) <= 256:
46
+ return "string", value
47
+ if type(value) is int and -(1 << 63) <= value < (1 << 63):
48
+ return "integer", value
49
+ return None
50
+
51
+
52
+ def is_stdio_app_server(args: Sequence[str]) -> bool:
53
+ """Recognize a plain launch, leaving explicit transports and tools alone."""
54
+ value_options = {
55
+ "-c", "--config", "--enable", "--disable", "--code-mode-host",
56
+ "--ws-auth", "--ws-token-file", "--ws-token-sha256",
57
+ "--ws-shared-secret-file", "--ws-issuer", "--ws-audience",
58
+ "--ws-max-clock-skew-seconds",
59
+ }
60
+ if any(arg in {"-h", "--help", "-V", "--version", "--stdio", "--listen"}
61
+ or arg.startswith("--listen=") for arg in args):
62
+ return False
63
+ command_seen = False
64
+ skip = False
65
+ for arg in args:
66
+ if skip:
67
+ skip = False
68
+ continue
69
+ if arg in value_options:
70
+ skip = True
71
+ elif arg.startswith("-"):
72
+ continue
73
+ elif not command_seen and arg == "app-server":
74
+ command_seen = True
75
+ else:
76
+ # Another CLI command or an app-server tooling subcommand.
77
+ return False
78
+ return command_seen and not skip
79
+
80
+
81
+ def real_binary(env: Mapping[str, str]) -> str:
82
+ value = env.get("AOT_CODEX_REAL_BINARY", "")
83
+ if not value or "\x00" in value or not Path(value).is_absolute():
84
+ raise BridgeError("Set AOT_CODEX_REAL_BINARY to the absolute bundled Codex executable.")
85
+ try:
86
+ binary = Path(value).resolve(strict=True)
87
+ current = Path(sys.argv[0]).resolve()
88
+ if not binary.is_file() or not os.access(binary, os.X_OK) or binary == current:
89
+ raise OSError
90
+ except (OSError, RuntimeError):
91
+ raise BridgeError("The selected Codex executable is unavailable or points back to this bridge.") from None
92
+ return str(binary)
93
+
94
+
95
+ def validate_socket_path(value: str) -> Path:
96
+ """Check every component before opening anything in the private directory."""
97
+ path = Path(value)
98
+ if (not value or "\x00" in value or not path.is_absolute()
99
+ or ".." in path.parts or len(os.fsencode(value)) > 107):
100
+ raise BridgeError("Set AOT_CODEX_SOCKET to an absolute Unix socket path of at most 107 bytes.")
101
+ parent = path.parent
102
+ try:
103
+ for directory in [*reversed(parent.parents), parent]:
104
+ info = directory.lstat()
105
+ if not stat.S_ISDIR(info.st_mode) or info.st_uid not in {0, os.getuid()}:
106
+ raise BridgeError("The socket path must use owned directories without symlinks.")
107
+ writable = stat.S_IMODE(info.st_mode) & 0o022
108
+ trusted_sticky = info.st_uid == 0 and bool(info.st_mode & stat.S_ISVTX)
109
+ if writable and not trusted_sticky:
110
+ raise BridgeError("The socket path has a directory writable by another user.")
111
+ info = parent.lstat()
112
+ if info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) != 0o700:
113
+ raise BridgeError("The socket parent must be an existing user-owned directory with mode 0700.")
114
+ except OSError:
115
+ raise BridgeError("The socket parent must be an existing user-owned directory with mode 0700.") from None
116
+ return path
117
+
118
+
119
+ def acquire_lock(path: Path) -> int:
120
+ lock_path = path.with_name(path.name + ".lock")
121
+ try:
122
+ descriptor = os.open(lock_path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600)
123
+ except OSError:
124
+ raise BridgeError("Could not safely open the shared backend lock.") from None
125
+ try:
126
+ info = os.fstat(descriptor)
127
+ if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid()
128
+ or stat.S_IMODE(info.st_mode) != 0o600 or info.st_nlink != 1):
129
+ raise BridgeError("The shared backend lock must be a private user-owned regular file.")
130
+ try:
131
+ fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
132
+ except BlockingIOError:
133
+ raise BridgeError("A desktop bridge already owns this backend endpoint.") from None
134
+ if os.path.lexists(path):
135
+ raise BridgeError("The shared backend endpoint already exists; refusing to replace it.")
136
+ return descriptor
137
+ except BaseException:
138
+ os.close(descriptor)
139
+ raise
140
+
141
+
142
+ def socket_identity(path: Path) -> tuple[tuple[int, int], tuple[int, int]]:
143
+ """Codex publishes a custom endpoint as an owned link to its private socket."""
144
+ info = path.lstat()
145
+ if info.st_uid != os.getuid():
146
+ raise BridgeError("The backend endpoint is not owned by the current user.")
147
+ entry = (info.st_dev, info.st_ino)
148
+ target = path
149
+ if stat.S_ISLNK(info.st_mode):
150
+ target = validate_socket_path(os.readlink(path))
151
+ info = target.lstat()
152
+ if (not stat.S_ISSOCK(info.st_mode) or info.st_uid != os.getuid()
153
+ or stat.S_IMODE(info.st_mode) & 0o077):
154
+ raise BridgeError("The backend did not create a private user-owned Unix socket.")
155
+ return entry, (info.st_dev, info.st_ino)
156
+
157
+
158
+ def connect_backend(path: Path, process: subprocess.Popen, identity):
159
+ transport = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
160
+ transport.settimeout(5)
161
+ try:
162
+ transport.connect(str(path))
163
+ if hasattr(socket, "SO_PEERCRED"):
164
+ peer_pid, peer_uid, _ = struct.unpack(
165
+ "3i", transport.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i"))
166
+ )
167
+ if peer_uid != os.getuid() or peer_pid != process.pid:
168
+ raise BridgeError("The Unix socket peer is not the backend started by this bridge.")
169
+ if socket_identity(path) != identity:
170
+ raise BridgeError("The backend endpoint changed during connection.")
171
+ # websockets retains a supplied socket's timeout for its reader thread.
172
+ # Only connect is bounded; an idle desktop must remain connected.
173
+ transport.settimeout(None)
174
+ connection = unix_connect(
175
+ sock=transport, open_timeout=5, close_timeout=1,
176
+ max_size=MAX_MESSAGE_BYTES, proxy=None, logger=_WEBSOCKET_LOGGER,
177
+ )
178
+ if socket_identity(path) != identity:
179
+ connection.close()
180
+ raise BridgeError("The backend endpoint changed during connection.")
181
+ return connection
182
+ except BaseException:
183
+ transport.close()
184
+ raise
185
+
186
+
187
+ def stop_backend(process: subprocess.Popen) -> None:
188
+ """Signal only the process group that this wrapper created."""
189
+ def send(signum):
190
+ try:
191
+ os.killpg(process.pid, signum)
192
+ except ProcessLookupError:
193
+ pass
194
+ except PermissionError:
195
+ # macOS may return EPERM after the leader has exited and the
196
+ # group is empty. Never ignore it for a live or uninspectable group.
197
+ if sys.platform != 'darwin' or process.poll() is None:
198
+ raise
199
+ from .macos_process import MacOSProcesses
200
+ if not MacOSProcesses().group_is_empty(process.pid):
201
+ raise
202
+ send(signal.SIGTERM)
203
+ try:
204
+ process.wait(timeout=STOP_TIMEOUT_SECONDS)
205
+ except subprocess.TimeoutExpired:
206
+ send(signal.SIGKILL)
207
+ process.wait(timeout=STOP_TIMEOUT_SECONDS)
208
+ # The child may have exited before descendants which inherited its pipes.
209
+ send(signal.SIGKILL)
210
+
211
+
212
+ def dispatcher_command(env: Mapping[str, str], path: Path) -> list[str] | None:
213
+ """Start a dispatcher only when an operator explicitly selected its state."""
214
+ state = env.get("AOT_DISPATCH_STATE", "")
215
+ if not state:
216
+ if env.get("AOT_DISPATCH_COLLECT") or env.get("AOT_DISPATCH_FAKE"):
217
+ raise BridgeError("Dispatcher options require an explicit AOT_DISPATCH_STATE.")
218
+ return None
219
+ if "\x00" in state or not Path(state).is_absolute() or not Path(state).is_dir():
220
+ raise BridgeError("AOT_DISPATCH_STATE must identify an existing absolute state directory.")
221
+ for key in ("AOT_DISPATCH_COLLECT", "AOT_DISPATCH_FAKE"):
222
+ if env.get(key, "0") not in {"0", "1"}:
223
+ raise BridgeError("Dispatcher switches must be explicitly 0 or 1.")
224
+ result = [sys.executable, "-m", "agents_over_telegram.cli", "--state-dir", state]
225
+ if env.get("AOT_DISPATCH_FAKE", "0") == "1":
226
+ result.append("--fake")
227
+ result.extend(["relay-dispatch", "--endpoint", "unix://" + str(path), "--duration", "0"])
228
+ if env.get("AOT_DISPATCH_COLLECT", "0") == "1":
229
+ result.append("--collect")
230
+ return result
231
+
232
+
233
+ def open_dispatch_log(path: Path) -> int:
234
+ try:
235
+ descriptor = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600)
236
+ except OSError:
237
+ raise BridgeError("Could not safely open the dispatcher metadata log.") from None
238
+ info = os.fstat(descriptor)
239
+ if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid()
240
+ or stat.S_IMODE(info.st_mode) != 0o600 or info.st_nlink != 1):
241
+ os.close(descriptor)
242
+ raise BridgeError("The dispatcher log must be a private user-owned regular file.")
243
+ if info.st_size > MAX_DISPATCH_LOG_BYTES:
244
+ os.ftruncate(descriptor, 0)
245
+ os.lseek(descriptor, 0, os.SEEK_END)
246
+ return descriptor
247
+
248
+
249
+ def append_dispatch_log(descriptor: int, chunk: bytes) -> None:
250
+ if os.lseek(descriptor, 0, os.SEEK_CUR) + len(chunk) > MAX_DISPATCH_LOG_BYTES:
251
+ os.ftruncate(descriptor, 0)
252
+ os.lseek(descriptor, 0, os.SEEK_SET)
253
+ pending = memoryview(chunk[-MAX_DISPATCH_LOG_BYTES:])
254
+ while pending:
255
+ pending = pending[os.write(descriptor, pending):]
256
+
257
+
258
+ def _owned_child_command(command: Sequence[str]) -> list[str]:
259
+ # Avoid preexec_fn after the bridge has threads: initialize parent-death
260
+ # handling in a fresh interpreter, then exec the intended child verbatim.
261
+ return [sys.executable, "-m", __spec__.name, "--owned-child", str(os.getpid()), *command]
262
+
263
+
264
+ def _exec_owned_child(args: Sequence[str]) -> int:
265
+ if len(args) < 2 or not args[0].isdigit() or int(args[0]) != os.getppid():
266
+ return 126
267
+ parent_pid = int(args[0])
268
+ if sys.platform == "linux":
269
+ import ctypes
270
+ libc = ctypes.CDLL(None, use_errno=True)
271
+ if libc.prctl(1, signal.SIGTERM, 0, 0, 0) != 0:
272
+ return 126
273
+ if os.getppid() != parent_pid:
274
+ return 126
275
+ os.execv(args[1], list(args[1:]))
276
+ return 126
277
+
278
+
279
+ def run_bridge(binary: str, args: Sequence[str], env: Mapping[str, str]) -> int:
280
+ path = validate_socket_path(env.get("AOT_CODEX_SOCKET", ""))
281
+ dispatch_args = dispatcher_command(env, path)
282
+ lock = acquire_lock(path)
283
+ process = None
284
+ dispatcher = None
285
+ log_fd = None
286
+ log_thread = None
287
+ connection = None
288
+ identity = None
289
+ done = threading.Event()
290
+ initialized = threading.Event()
291
+ handshake_lock = threading.Lock()
292
+ initialize_request_id = None
293
+ dispatch_log_failed = threading.Event()
294
+ dispatch_disabled = False
295
+ failures: list[str] = []
296
+ caught_signal: list[int] = []
297
+ handlers = {}
298
+
299
+ def on_signal(number, _frame):
300
+ caught_signal.append(number)
301
+ done.set()
302
+
303
+ try:
304
+ for number in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
305
+ handlers[number] = signal.signal(number, on_signal)
306
+ # Preserve the desktop's cwd, full configuration arguments, app-tools
307
+ # environment and normal stderr. Only the transport is changed.
308
+ process = subprocess.Popen(
309
+ _owned_child_command([binary, *args, "--listen", "unix://" + str(path)]),
310
+ stdin=subprocess.DEVNULL, stdout=sys.stderr, stderr=sys.stderr,
311
+ env=dict(env), start_new_session=True,
312
+ )
313
+ deadline = time.monotonic() + START_TIMEOUT_SECONDS
314
+ while not done.is_set():
315
+ if process.poll() is not None:
316
+ raise BridgeError("The shared Codex backend exited before accepting the desktop connection.")
317
+ try:
318
+ info = path.lstat()
319
+ except FileNotFoundError:
320
+ info = None
321
+ if info is not None:
322
+ try:
323
+ identity = socket_identity(path)
324
+ connection = connect_backend(path, process, identity)
325
+ break
326
+ except (ConnectionRefusedError, FileNotFoundError):
327
+ pass
328
+ except Exception:
329
+ raise BridgeError("Could not establish the desktop WebSocket connection.") from None
330
+ if time.monotonic() >= deadline:
331
+ raise BridgeError("Timed out waiting for the shared Codex backend.")
332
+ done.wait(0.025)
333
+ if done.is_set():
334
+ return 128 + caught_signal[0] if caught_signal else 0
335
+
336
+ def from_desktop():
337
+ nonlocal initialize_request_id
338
+ try:
339
+ pending = bytearray()
340
+ while not done.is_set():
341
+ chunk = os.read(sys.stdin.fileno(), 65536)
342
+ if not chunk:
343
+ if pending:
344
+ connection.send(bytes(pending).decode("utf-8"))
345
+ break
346
+ pending.extend(chunk)
347
+ while b"\n" in pending:
348
+ line, _, remainder = pending.partition(b"\n")
349
+ pending = bytearray(remainder)
350
+ line = line.rstrip(b"\r")
351
+ if len(line) > MAX_MESSAGE_BYTES:
352
+ raise BridgeError("A desktop protocol message exceeded the bridge size limit.")
353
+ if line:
354
+ text = bytes(line).decode("utf-8")
355
+ initialized_notification = False
356
+ if dispatch_args is not None and not initialized.is_set():
357
+ try:
358
+ value = json.loads(text)
359
+ if isinstance(value, dict):
360
+ if value.get("method") == "initialize":
361
+ # Register before send: the backend can answer
362
+ # immediately on the other bridge thread.
363
+ with handshake_lock:
364
+ initialize_request_id = handshake_id(value.get("id"))
365
+ elif value.get("method") == "initialized" and "id" not in value:
366
+ initialized_notification = True
367
+ except (ValueError, TypeError):
368
+ pass # Leave protocol validation to the actual backend.
369
+ connection.send(text)
370
+ if initialized_notification:
371
+ initialized.set()
372
+ if len(pending) > MAX_MESSAGE_BYTES:
373
+ raise BridgeError("A desktop protocol message exceeded the bridge size limit.")
374
+ except (ConnectionClosed, BrokenPipeError, OSError):
375
+ if not done.is_set():
376
+ failures.append("The desktop input connection closed unexpectedly.")
377
+ except (UnicodeError, BridgeError):
378
+ failures.append("The desktop sent an invalid or oversized protocol message.")
379
+ finally:
380
+ done.set()
381
+
382
+ def to_desktop():
383
+ try:
384
+ while not done.is_set():
385
+ message = connection.recv()
386
+ if not isinstance(message, str) or "\n" in message or "\r" in message:
387
+ raise BridgeError("The backend sent an invalid stdio protocol message.")
388
+ pending = memoryview(message.encode("utf-8") + b"\n")
389
+ while pending:
390
+ written = os.write(sys.stdout.fileno(), pending)
391
+ pending = pending[written:]
392
+ if dispatch_args is not None and not initialized.is_set():
393
+ try:
394
+ value = json.loads(message)
395
+ if (isinstance(value, dict) and "method" not in value
396
+ and "result" in value and "error" not in value):
397
+ with handshake_lock:
398
+ ready = (initialize_request_id is not None
399
+ and handshake_id(value.get("id")) == initialize_request_id)
400
+ # The desktop's main connection omits `initialized`.
401
+ # Forward its successful response first so later
402
+ # notifications remain ordered after initialization.
403
+ if ready:
404
+ initialized.set()
405
+ except (ValueError, TypeError):
406
+ pass
407
+ except (ConnectionClosed, BrokenPipeError, OSError):
408
+ if not done.is_set():
409
+ failures.append("The desktop backend connection closed unexpectedly.")
410
+ except (UnicodeError, BridgeError):
411
+ failures.append("The backend sent an invalid stdio protocol message.")
412
+ finally:
413
+ done.set()
414
+
415
+ # A blocked desktop pipe must not prevent signal handling or cleanup.
416
+ threading.Thread(target=from_desktop, name="aot-desktop-input", daemon=True).start()
417
+ threading.Thread(target=to_desktop, name="aot-desktop-output", daemon=True).start()
418
+
419
+ def disable_dispatcher(message: str):
420
+ nonlocal dispatcher, dispatch_disabled
421
+ dispatch_disabled = True
422
+ if dispatcher is not None:
423
+ stop_backend(dispatcher)
424
+ dispatcher = None
425
+ if log_thread is not None:
426
+ log_thread.join(timeout=2)
427
+ print(message, file=sys.stderr, flush=True)
428
+ if log_fd is not None and not dispatch_log_failed.is_set() and (log_thread is None or not log_thread.is_alive()):
429
+ try:
430
+ append_dispatch_log(log_fd, (json.dumps({"type": "dispatcher_error", "error": message}) + "\n").encode())
431
+ except OSError:
432
+ pass
433
+
434
+ while not done.wait(0.05):
435
+ if dispatch_args is not None and initialized.is_set() and dispatcher is None and not dispatch_disabled:
436
+ try:
437
+ log_fd = open_dispatch_log(path.parent / "dispatcher.jsonl")
438
+ dispatcher = subprocess.Popen(
439
+ _owned_child_command(dispatch_args), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
440
+ stderr=subprocess.STDOUT, env=dict(env), start_new_session=True, cwd=path.parent,
441
+ )
442
+ except (BridgeError, OSError):
443
+ disable_dispatcher("The Telegram dispatcher could not start; desktop chats remain available.")
444
+ continue
445
+
446
+ dispatch_stdout = dispatcher.stdout
447
+
448
+ def copy_dispatch_log():
449
+ try:
450
+ pending = bytearray()
451
+ dropping = False
452
+ while True:
453
+ chunk = os.read(dispatch_stdout.fileno(), 65536)
454
+ if not chunk:
455
+ if pending and not dropping:
456
+ append_dispatch_log(log_fd, bytes(pending) + b"\n")
457
+ break
458
+ pending.extend(chunk)
459
+ while b"\n" in pending:
460
+ line, _, remainder = pending.partition(b"\n")
461
+ pending = bytearray(remainder)
462
+ if dropping or len(line) > 65536:
463
+ append_dispatch_log(log_fd, b'{"type":"dispatcher_log_line_omitted"}\n')
464
+ else:
465
+ append_dispatch_log(log_fd, bytes(line) + b"\n")
466
+ dropping = False
467
+ if len(pending) > 65536:
468
+ pending.clear()
469
+ dropping = True
470
+ except OSError:
471
+ if not done.is_set():
472
+ dispatch_log_failed.set()
473
+
474
+ log_thread = threading.Thread(target=copy_dispatch_log, name="aot-dispatch-log", daemon=True)
475
+ log_thread.start()
476
+ if not dispatch_disabled and dispatch_log_failed.is_set():
477
+ disable_dispatcher("The Telegram dispatcher log failed; the dispatcher stopped and desktop chats remain available.")
478
+ elif dispatcher is not None and dispatcher.poll() is not None:
479
+ disable_dispatcher("The Telegram dispatcher exited; desktop chats remain available. Restart the desktop launcher to reconnect Telegram.")
480
+ if process.poll() is not None:
481
+ failures.append("The shared Codex backend exited.")
482
+ done.set()
483
+ if caught_signal:
484
+ return 128 + caught_signal[0]
485
+ if failures:
486
+ raise BridgeError(failures[0])
487
+ return 0
488
+ finally:
489
+ done.set()
490
+ try:
491
+ if dispatcher is not None:
492
+ stop_backend(dispatcher)
493
+ if log_thread is not None:
494
+ log_thread.join(timeout=2)
495
+ if log_fd is not None and (log_thread is None or not log_thread.is_alive()):
496
+ os.close(log_fd)
497
+ if connection is not None:
498
+ try:
499
+ connection.close()
500
+ except Exception:
501
+ pass
502
+ finally:
503
+ try:
504
+ if process is not None:
505
+ stop_backend(process)
506
+ if identity is not None:
507
+ try:
508
+ info = path.lstat()
509
+ if (info.st_dev, info.st_ino) == identity[0] and (stat.S_ISSOCK(info.st_mode) or stat.S_ISLNK(info.st_mode)):
510
+ path.unlink()
511
+ except FileNotFoundError:
512
+ pass
513
+ finally:
514
+ # Keep the lock inode stable; unlinking it permits a competing lock.
515
+ os.close(lock)
516
+ for number, previous in handlers.items():
517
+ signal.signal(number, previous)
518
+
519
+
520
+ def main() -> int:
521
+ try:
522
+ if sys.argv[1:2] == ["--owned-child"]:
523
+ return _exec_owned_child(sys.argv[2:])
524
+ binary = real_binary(os.environ)
525
+ if not is_stdio_app_server(sys.argv[1:]):
526
+ os.execv(binary, [binary, *sys.argv[1:]])
527
+ raise AssertionError("execv returned")
528
+ return run_bridge(binary, sys.argv[1:], os.environ)
529
+ except BridgeError as exc:
530
+ print(str(exc), file=sys.stderr)
531
+ except OSError:
532
+ print("The selected Codex process or private socket could not be opened.", file=sys.stderr)
533
+ return 2
534
+
535
+
536
+ if __name__ == "__main__":
537
+ raise SystemExit(main())