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,680 @@
1
+ """Wake local chats in an already running desktop through its native queue.
2
+
3
+ The CLI records a fixed USER-role note. The OS URL contains only the bound chat
4
+ UUID. No model text, Telegram contents, credentials, app launch configuration,
5
+ or backend protocol are synthesized. OS URL handling still has an exit race:
6
+ if the desktop exits after our final process check, its handler may reopen it.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import errno
11
+ import json
12
+ import math
13
+ import os
14
+ from pathlib import Path
15
+ import plistlib
16
+ import queue
17
+ import re
18
+ import signal
19
+ import sqlite3
20
+ import stat
21
+ import subprocess
22
+ import sys
23
+ import threading
24
+ import time
25
+ import uuid
26
+
27
+ from .core import CoreError
28
+ from .relay import WAKE_NOTICE
29
+
30
+
31
+ def default_codex_binary():
32
+ if sys.platform == 'darwin':
33
+ for root in (Path('/Applications'), Path.home() / 'Applications'):
34
+ for name in ('ChatGPT.app', 'Codex.app'):
35
+ resources = root / name / 'Contents' / 'Resources'
36
+ for binary in (resources / 'codex-cli/CodexCLI.app/Contents/MacOS/codex',
37
+ resources / 'codex'):
38
+ if binary.is_file():
39
+ return binary
40
+ return Path('/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex')
41
+ return Path('/usr/lib/chatgpt/resources/codex')
42
+
43
+
44
+ DEFAULT_CODEX_BINARY = default_codex_binary()
45
+ PROC_ROOT = Path('/proc')
46
+ # How often the listener looks for long-held unresolved wakes, and how often it
47
+ # repeats the warning for the same notification while it stays unresolved. The
48
+ # repeat state lives in memory, so a restarted listener warns again once.
49
+ STUCK_WAKE_CHECK_SECONDS = 60
50
+ # An enqueue whose outcome is unknown is checked against the desktop's own
51
+ # records once its child process has surely ended (it is killed after 30 s).
52
+ UNKNOWN_ENQUEUE_CHECK_AFTER_SECONDS = 120
53
+ # A chat whose latest turn is in progress and showed activity this recently is
54
+ # busy: AOT's Codex hooks deliver the notice inside that turn, so the listener
55
+ # does not also queue one. An older in-progress turn is treated as stale (for
56
+ # example left open by a crash), and the listener queues as usual.
57
+ BUSY_TURN_ACTIVITY_SECONDS = 600
58
+ STUCK_WAKE_WARNING_REPEAT_SECONDS = 3600
59
+ STUCK_WAKE_MESSAGES = {
60
+ 'review_uncertain_wake': (
61
+ 'Unresolved wake notification blocks every later wake for this client. Reconcile it against '
62
+ 'the target chat, then record the outcome with relay-resolve. A running desktop listener '
63
+ 'settles an unknown enqueue by itself when the desktop records show its outcome.'),
64
+ 'wait_for_desktop_wake': (
65
+ 'Queued wake has not opened in the desktop yet, so later wakes for this client wait. The '
66
+ 'listener retries only its wake URL while the desktop is open and the connection is active. '
67
+ 'Do not resolve it by hand: that stops the retries.'),
68
+ 'review_failing_wake': (
69
+ 'Queued wake URL keeps failing while the desktop is open and the connection is active, so later '
70
+ 'wakes for this client wait. Check that the target chat still exists and that its wake URL opens. '
71
+ 'Opening that chat in the desktop app delivers the queued notice; then record accepted with '
72
+ 'relay-resolve, or cancelled to dismiss it. The listener keeps retrying until then.'),
73
+ }
74
+
75
+ def _uuid(value):
76
+ try:
77
+ return isinstance(value, str) and str(uuid.UUID(value)) == value
78
+ except (ValueError, TypeError, AttributeError):
79
+ return False
80
+
81
+
82
+ def _code(error):
83
+ value = getattr(error, 'code', '')
84
+ return value if isinstance(value, str) and re.fullmatch(r'[a-z0-9_]{1,64}', value) else 'desktop_dispatcher_failed'
85
+
86
+
87
+ class DesktopQueueError(CoreError):
88
+ def __init__(self, code, *, ambiguous=False):
89
+ super().__init__(code)
90
+ self.ambiguous = ambiguous
91
+
92
+
93
+ class NativeDesktopQueue:
94
+ """Linux/macOS adapter for a bundled CLI with native queue capabilities."""
95
+
96
+ def __init__(self, codex_binary=None, codex_home=None):
97
+ self.binary = Path(codex_binary) if codex_binary is not None else default_codex_binary()
98
+ self.home = Path(codex_home if codex_home is not None else
99
+ os.environ.get('CODEX_HOME', Path.home() / '.codex')).expanduser()
100
+ self.desktop = self.binary.parent.parent / 'ChatGPT'
101
+ self.opener = Path('/usr/bin/open' if sys.platform == 'darwin' else '/usr/bin/xdg-open')
102
+ self.bundle = None
103
+ self.cli_aliases = {self.binary.resolve()}
104
+ if sys.platform == 'darwin':
105
+ self._macos_layout()
106
+ self.env = {k: v for k, v in os.environ.items()
107
+ if not k.startswith(('CODEX_', 'AOT_'))}
108
+ self.env['CODEX_HOME'] = str(self.home)
109
+
110
+ def _macos_layout(self):
111
+ # The CLI can be nested inside CodexCLI.app. Match the *outer* app,
112
+ # not the helper bundle, and never accept a PATH CLI as its backend.
113
+ for bundle in self.binary.parents:
114
+ if bundle.suffix != '.app':
115
+ continue
116
+ contents = bundle / 'Contents'
117
+ resources = contents / 'Resources'
118
+ allowed = (resources / 'codex',
119
+ resources / 'codex-cli/CodexCLI.app/Contents/MacOS/codex')
120
+ if self.binary not in allowed:
121
+ continue
122
+ try:
123
+ path = contents / 'Info.plist'
124
+ info = path.stat()
125
+ if (not stat.S_ISREG(info.st_mode) or info.st_uid not in (0, os.getuid())
126
+ or info.st_mode & 0o022 or info.st_size > 1024 * 1024):
127
+ raise ValueError
128
+ metadata = plistlib.loads(path.read_bytes())
129
+ if not isinstance(metadata, dict):
130
+ raise ValueError
131
+ executable = metadata.get('CFBundleExecutable')
132
+ if (metadata.get('CFBundleIdentifier') != 'com.openai.codex'
133
+ or not isinstance(executable, str)
134
+ or re.fullmatch(r'[A-Za-z0-9 _-]+', executable) is None):
135
+ raise ValueError
136
+ self.desktop = contents / 'MacOS' / executable
137
+ self.bundle = bundle
138
+ self.cli_aliases.add((resources / 'codex-cli/bin/codex').resolve())
139
+ return
140
+ except (OSError, ValueError, plistlib.InvalidFileException):
141
+ break
142
+
143
+ def check_capability(self):
144
+ if sys.platform not in ('linux', 'darwin') or (
145
+ sys.platform == 'linux' and not Path('/proc/self/stat').is_file()):
146
+ raise DesktopQueueError('desktop_queue_unsupported_platform')
147
+ try:
148
+ if (not self.binary.is_absolute() or self.binary.name != 'codex'
149
+ or (sys.platform == 'linux' and self.binary.parent.name != 'resources')
150
+ or (sys.platform == 'darwin' and self.bundle is None) or not self.home.is_absolute()
151
+ or not self.home.is_dir()):
152
+ raise ValueError
153
+ self.home = self.home.resolve(strict=True)
154
+ self.env['CODEX_HOME'] = str(self.home)
155
+ for executable in (self.binary, self.desktop, self.opener):
156
+ info = executable.stat()
157
+ if (not stat.S_ISREG(info.st_mode) or info.st_uid not in (0, os.getuid())
158
+ or info.st_mode & 0o022 or not os.access(executable, os.X_OK)):
159
+ raise ValueError
160
+ result = subprocess.run([str(self.binary), 'queue', '--help'], stdin=subprocess.DEVNULL,
161
+ capture_output=True, text=True, timeout=10, check=False, env=self.env)
162
+ help_text = result.stdout + '\n' + result.stderr
163
+ if result.returncode != 0 or any(
164
+ re.search(r'(?<![\w-])' + option + r'(?![\w-])', help_text) is None
165
+ for option in ('--thread', '--message')):
166
+ raise DesktopQueueError('desktop_queue_unsupported_capability')
167
+ # Check only the local-state fields this adapter needs; do not scan history.
168
+ with sqlite3.connect((self.home / 'state_5.sqlite').as_uri() + '?mode=ro', uri=True) as db:
169
+ db.execute('SELECT id,cwd,archived FROM threads WHERE id=?', ('',)).fetchone()
170
+ except DesktopQueueError:
171
+ raise
172
+ except (OSError, ValueError, sqlite3.Error, subprocess.SubprocessError):
173
+ raise DesktopQueueError('desktop_queue_unavailable') from None
174
+
175
+ def _routing_matches(self, raw):
176
+ # Only selected routing fields are retained; no authentication is read
177
+ # from disk, logged, copied, or used by this adapter.
178
+ routing = {}
179
+ for pair in raw.split(b'\0'):
180
+ key, _, value = pair.partition(b'=')
181
+ if key in (b'HOME', b'CODEX_HOME', b'CODEX_CLI_PATH', b'CODEX_APP_SERVER_WS_URL',
182
+ b'CODEX_APP_SERVER_USE_LOCAL_DAEMON'):
183
+ routing[key] = value.decode(errors='strict')
184
+ actual_home = Path(routing.get(b'CODEX_HOME') or
185
+ str(Path(routing.get(b'HOME', '')) / '.codex'))
186
+ cli = routing.get(b'CODEX_CLI_PATH')
187
+ return (actual_home.is_absolute() and actual_home.resolve() == self.home
188
+ and (not cli or (Path(cli).is_absolute() and Path(cli).resolve() in self.cli_aliases))
189
+ and not routing.get(b'CODEX_APP_SERVER_WS_URL')
190
+ and not routing.get(b'CODEX_APP_SERVER_USE_LOCAL_DAEMON'))
191
+
192
+ def _desktop_identity(self):
193
+ """Match the desktop and its direct native local stdio backend.
194
+
195
+ Electron erases its main process environment and rewrites helper argv.
196
+ Its direct native app-server child retains the effective Codex home and
197
+ distinguishes this route from a wrapped or external backend.
198
+ """
199
+ if sys.platform == 'darwin':
200
+ return self._macos_desktop_identity()
201
+ mains, backends = {}, []
202
+ for entry in PROC_ROOT.iterdir():
203
+ if not entry.name.isdigit():
204
+ continue
205
+ try:
206
+ if entry.stat().st_uid != os.getuid():
207
+ continue
208
+ executable = (entry / 'exe').resolve()
209
+ if executable not in (self.desktop.resolve(), self.binary.resolve()):
210
+ continue
211
+ args = (entry / 'cmdline').read_bytes().split(b'\0')
212
+ fields = (entry / 'stat').read_text(encoding='utf-8').rsplit(')', 1)[1].split()
213
+ pid, parent, start = int(entry.name), int(fields[1]), fields[19]
214
+ if executable == self.desktop.resolve():
215
+ # Some Electron helpers expose their entire command line
216
+ # in argv[0], so searching only argument prefixes is wrong.
217
+ if not any(re.search(rb'(?:^|\s)--type=', arg) for arg in args):
218
+ mains[pid] = start
219
+ elif (b'app-server' in args and not any(
220
+ arg.startswith((b'--listen', b'--remote')) for arg in args)
221
+ and self._routing_matches((entry / 'environ').read_bytes())):
222
+ backends.append((pid, parent, start))
223
+ except (OSError, ValueError, UnicodeError, IndexError, RuntimeError):
224
+ continue
225
+ identities = [(parent, mains[parent], pid, start) for pid, parent, start in backends
226
+ if parent in mains]
227
+ return identities[0] if len(identities) == 1 else None
228
+
229
+ def _macos_desktop_identity(self):
230
+ from .macos_process import MacOSProcesses
231
+ if self.bundle is None:
232
+ return None
233
+ mains, backends = {}, []
234
+ try:
235
+ for pid, parent, start, executable, args, routing in MacOSProcesses().candidates(
236
+ {self.desktop.resolve(), self.binary.resolve()}):
237
+ if executable == self.desktop.resolve():
238
+ if not any(re.search(rb'(?:^|\s)--type=', arg) for arg in args):
239
+ mains[pid] = start
240
+ elif (b'app-server' in args and not any(
241
+ arg.startswith((b'--listen', b'--remote')) for arg in args)
242
+ and self._routing_matches(routing)):
243
+ backends.append((pid, parent, start))
244
+ except (OSError, ValueError, UnicodeError, RuntimeError):
245
+ return None
246
+ identities = [(parent, mains[parent], pid, start) for pid, parent, start in backends
247
+ if parent in mains]
248
+ return identities[0] if len(identities) == 1 else None
249
+
250
+ def desktop_running(self):
251
+ return self._desktop_identity() is not None
252
+
253
+ def validate_target(self, binding):
254
+ if not _uuid(binding.get('thread_id')):
255
+ raise DesktopQueueError('desktop_queue_target_mismatch')
256
+ try:
257
+ with sqlite3.connect((self.home / 'state_5.sqlite').as_uri() + '?mode=ro', uri=True) as db:
258
+ row = db.execute('SELECT id,cwd,archived FROM threads WHERE id=?',
259
+ (binding['thread_id'],)).fetchone()
260
+ project = Path(binding['project_dir'])
261
+ if (row is None or row[0] != binding['thread_id'] or row[2] != 0
262
+ or not isinstance(row[1], str) or not Path(row[1]).is_absolute()
263
+ or not project.is_absolute() or not project.is_dir()
264
+ or str(project.resolve(strict=True)) != binding['project_dir']
265
+ or Path(row[1]).resolve(strict=True) != project):
266
+ raise ValueError
267
+ except (OSError, ValueError, KeyError, sqlite3.Error, RuntimeError, TypeError):
268
+ raise DesktopQueueError('desktop_queue_target_mismatch') from None
269
+
270
+ def _guard(self, binding):
271
+ identity = self._desktop_identity()
272
+ if identity is None:
273
+ raise DesktopQueueError('desktop_not_running')
274
+ self.validate_target(binding)
275
+ if self._desktop_identity() != identity:
276
+ raise DesktopQueueError('desktop_process_changed')
277
+
278
+ def enqueue(self, binding):
279
+ self._guard(binding)
280
+ try:
281
+ child = subprocess.Popen([str(self.binary), 'queue', '--thread', binding['thread_id'],
282
+ '--message', WAKE_NOTICE], cwd=binding['project_dir'], env=self.env,
283
+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
284
+ stderr=subprocess.DEVNULL, text=True)
285
+ except OSError as error:
286
+ # These constructor failures mean exec never reached the bundled
287
+ # CLI. Unexpected setup errors remain held rather than guessed safe.
288
+ no_exec = (isinstance(error, (FileNotFoundError, PermissionError))
289
+ or error.errno in (errno.EMFILE, errno.ENFILE, errno.EAGAIN, errno.ENOMEM))
290
+ raise DesktopQueueError('desktop_queue_start_failed' if no_exec else
291
+ 'desktop_queue_outcome_unknown', ambiguous=not no_exec) from None
292
+ try:
293
+ stdout, _ = child.communicate(timeout=30)
294
+ except (OSError, subprocess.SubprocessError, UnicodeError):
295
+ # A child existed: it may have committed the queue item before any
296
+ # output/error. Terminate only this owned child, then hold the item.
297
+ try:
298
+ child.kill()
299
+ except OSError:
300
+ pass
301
+ try:
302
+ child.wait(timeout=1)
303
+ except (OSError, subprocess.SubprocessError):
304
+ pass
305
+ raise DesktopQueueError('desktop_queue_outcome_unknown', ambiguous=True) from None
306
+ finally:
307
+ # Avoid leaving captured output descriptors alive after exceptions.
308
+ if child.stdout is not None:
309
+ child.stdout.close()
310
+ match = re.fullmatch(r'Queued message ([0-9a-f-]{36}) for thread '
311
+ + re.escape(binding['thread_id']) + r'\.\s*', stdout)
312
+ if child.returncode != 0 or match is None or not _uuid(match.group(1)):
313
+ raise DesktopQueueError('desktop_queue_outcome_unknown', ambiguous=True)
314
+ return match.group(1)
315
+
316
+ def notice_outcome(self, thread_id, since):
317
+ """Look for one wake notice in the desktop's own records. Read-only.
318
+
319
+ Returns ('queued', queue_id) while the notice waits in the native queue,
320
+ ('delivered', None) once the chat holds it as a user message, or
321
+ ('absent', None) when neither database has it since ``since``. Raises
322
+ DesktopQueueError when either database cannot be read, so an unreadable
323
+ record never counts as absent.
324
+
325
+ ``since`` is the creation time of the notification being settled. Its
326
+ Telegram message was already collected then, so any turn that a notice
327
+ from after that time started will see it. A notice from an earlier
328
+ notification may have polled before the message arrived, so it must not
329
+ match. Both clocks are this machine's, so no slack is added.
330
+
331
+ The two databases are read one after the other. If the desktop moves the
332
+ item from the queue to the chat between the reads, both miss it and the
333
+ wake is enqueued again: the agent gets a second, identical notice, which
334
+ is the accepted cost. The check assumes only ``relay-desktop`` writes
335
+ WAKE_NOTICE into a desktop chat.
336
+ """
337
+ if not _uuid(thread_id):
338
+ raise DesktopQueueError('desktop_queue_target_mismatch')
339
+ since_ms = math.floor(since * 1000)
340
+ try:
341
+ with sqlite3.connect((self.home / 'queue_1.sqlite').as_uri() + '?mode=ro', uri=True) as db:
342
+ row = db.execute('SELECT id FROM queued_items WHERE thread_id=? AND created_at_ms>=? '
343
+ 'AND instr(payload_json,?)>0 ORDER BY created_at_ms LIMIT 1',
344
+ (thread_id, since_ms, WAKE_NOTICE)).fetchone()
345
+ if row is not None:
346
+ if not _uuid(row[0]):
347
+ raise ValueError
348
+ return 'queued', row[0]
349
+ with sqlite3.connect((self.home / 'thread_history_1.sqlite').as_uri() + '?mode=ro', uri=True) as db:
350
+ row = db.execute("SELECT 1 FROM thread_items WHERE thread_id=? AND created_at_ms>=? "
351
+ "AND item_type='userMessage' AND instr(item_json,?)>0 LIMIT 1",
352
+ (thread_id, since_ms, WAKE_NOTICE)).fetchone()
353
+ except (OSError, sqlite3.Error, ValueError):
354
+ raise DesktopQueueError('desktop_records_unreadable') from None
355
+ return ('delivered', None) if row is not None else ('absent', None)
356
+
357
+ def thread_busy(self, thread_id, now):
358
+ """True while the chat's latest turn is in progress and recently active. Read-only.
359
+
360
+ Unreadable records count as not busy, so the listener falls back to
361
+ queueing, which was the behavior before this check.
362
+ """
363
+ if not _uuid(thread_id):
364
+ return False
365
+ try:
366
+ with sqlite3.connect((self.home / 'thread_history_1.sqlite').as_uri() + '?mode=ro', uri=True) as db:
367
+ row = db.execute(
368
+ 'SELECT t.status, t.started_at, (SELECT MAX(i.created_at_ms) FROM thread_items i '
369
+ 'WHERE i.thread_id=t.thread_id AND i.turn_id=t.turn_id) '
370
+ 'FROM thread_turns t WHERE t.thread_id=? ORDER BY t.rollout_ordinal DESC LIMIT 1',
371
+ (thread_id,)).fetchone()
372
+ except (OSError, sqlite3.Error, ValueError):
373
+ return False
374
+ # thread_turns.started_at is in seconds and thread_items.created_at_ms in
375
+ # milliseconds (checked against a live desktop database).
376
+ if row is None or row[0] != 'inProgress':
377
+ return False
378
+ activity = [value for value in (row[1], row[2] / 1000 if isinstance(row[2], (int, float)) else None)
379
+ if isinstance(value, (int, float))]
380
+ return bool(activity) and now - max(activity) <= BUSY_TURN_ACTIVITY_SECONDS
381
+
382
+ def wake(self, binding):
383
+ self._guard(binding)
384
+ try:
385
+ command = [str(self.opener)]
386
+ if self.bundle is not None:
387
+ # Pin the selected installed app rather than the default URL handler.
388
+ command += ['-a', str(self.bundle)]
389
+ result = subprocess.run([*command, 'codex://threads/wake/' + binding['thread_id']],
390
+ stdin=subprocess.DEVNULL, capture_output=True, timeout=20, check=False,
391
+ env=self.env)
392
+ if result.returncode != 0:
393
+ raise DesktopQueueError('desktop_wake_failed')
394
+ except (OSError, subprocess.SubprocessError):
395
+ raise DesktopQueueError('desktop_wake_failed') from None
396
+
397
+
398
+ class DesktopHandoffs:
399
+ """Queue receipts survive restarts independently of inbox ACKs and wake URLs."""
400
+
401
+ def __init__(self, store):
402
+ self.store = store
403
+ self.core = store.core
404
+
405
+ def prepare(self, event):
406
+ with self.core._tx() as db:
407
+ db.execute('''INSERT INTO relay_desktop_handoffs
408
+ (notification_id,phase,queue_id,wake_attempt,next_wake_at,updated)
409
+ VALUES(?,'enqueuing',NULL,0,NULL,?)''', (event['notification_id'], self.core.clock()))
410
+
411
+ def queued(self, event, queue_id):
412
+ if not _uuid(queue_id):
413
+ raise DesktopQueueError('desktop_queue_outcome_unknown', ambiguous=True)
414
+ with self.core._tx() as db:
415
+ now = self.core.clock()
416
+ db.execute('''UPDATE relay_desktop_handoffs SET phase='queued',queue_id=?,
417
+ next_wake_at=?,updated=? WHERE notification_id=? AND phase='enqueuing' ''',
418
+ (queue_id, now, now, event['notification_id']))
419
+ # The native queue accepted work, but URL handoff has not completed.
420
+ # This state blocks every other relay mode from enqueuing a duplicate.
421
+ db.execute("UPDATE relay_notifications SET status='uncertain',updated=?,next_attempt_at=NULL WHERE id=?",
422
+ (now, event['notification_id']))
423
+
424
+ def unknown_enqueues(self, older_than):
425
+ """Handoffs whose enqueue outcome was unknown and that still have no receipt."""
426
+ with self.core._db() as db:
427
+ return [dict(row) for row in db.execute('''SELECT n.id AS notification_id,
428
+ n.client_id,n.thread_id,n.project_dir,n.created AS since
429
+ FROM relay_desktop_handoffs h JOIN relay_notifications n ON n.id=h.notification_id
430
+ WHERE h.phase='enqueuing' AND h.queue_id IS NULL AND n.status='uncertain'
431
+ AND h.updated<=? ORDER BY n.created,n.id''', (older_than,))]
432
+
433
+ def delivered(self, event):
434
+ """The desktop chat already holds the notice: record it as handed off."""
435
+ receipt = self.store.resolve(event['notification_id'], 'accepted')
436
+ with self.core._tx() as db:
437
+ db.execute("UPDATE relay_desktop_handoffs SET phase='done',next_wake_at=NULL,updated=? WHERE notification_id=?",
438
+ (self.core.clock(), event['notification_id']))
439
+ return receipt
440
+
441
+ def pending(self):
442
+ with self.core._db() as db:
443
+ return [dict(row) for row in db.execute('''SELECT n.id AS notification_id,
444
+ n.client_id,n.thread_id,n.project_dir,h.queue_id,h.wake_attempt
445
+ FROM relay_desktop_handoffs h JOIN relay_notifications n ON n.id=h.notification_id
446
+ WHERE h.phase='queued' AND n.status IN ('inflight','uncertain')
447
+ AND h.next_wake_at<=? ORDER BY n.created,n.id''', (self.core.clock(),))]
448
+
449
+ def wake_started(self, event):
450
+ # Persist a backoff before invoking the opener, including process crashes.
451
+ with self.core._tx() as db:
452
+ row = db.execute('SELECT wake_attempt FROM relay_desktop_handoffs WHERE notification_id=?',
453
+ (event['notification_id'],)).fetchone()
454
+ attempt = row['wake_attempt'] + 1
455
+ now = self.core.clock()
456
+ db.execute('''UPDATE relay_desktop_handoffs SET wake_attempt=?,next_wake_at=?,updated=?
457
+ WHERE notification_id=?''', (attempt, now + min(60, 2 ** min(attempt - 1, 6)),
458
+ now, event['notification_id']))
459
+
460
+ def done(self, event):
461
+ receipt = self.store.resolve(event['notification_id'], 'accepted')
462
+ with self.core._tx() as db:
463
+ db.execute("UPDATE relay_desktop_handoffs SET phase='done',next_wake_at=NULL,updated=? WHERE notification_id=?",
464
+ (self.core.clock(), event['notification_id']))
465
+ return receipt
466
+
467
+
468
+ def run_desktop_dispatcher(core, store, *, codex_binary=None, codex_home=None,
469
+ duration=55, collect=False, interval=.5, emit=None, stop_event=None):
470
+ """Run with the ordinary desktop open; duration 0 is explicitly continuous.
471
+
472
+ Acceptance means the native queue accepted the note and the OS accepted the
473
+ wake URL, not that a turn completed or any Telegram message was handled.
474
+ """
475
+ if (type(collect) is not bool or isinstance(duration, bool)
476
+ or not isinstance(duration, (int, float)) or not math.isfinite(duration)
477
+ or not 0 <= duration <= 86400 or isinstance(interval, bool)
478
+ or not isinstance(interval, (int, float)) or not math.isfinite(interval)
479
+ or not .01 <= interval <= 60):
480
+ raise CoreError('invalid_desktop_dispatcher_options')
481
+ if emit is None:
482
+ def emit(value):
483
+ print(json.dumps(value, separators=(',', ':'), ensure_ascii=True), flush=True)
484
+ transport = NativeDesktopQueue(codex_binary=codex_binary, codex_home=codex_home)
485
+ stop = threading.Event() if stop_event is None else stop_event
486
+ deadline = time.monotonic() + duration if duration else float('inf')
487
+ collector = None
488
+ handlers = {}
489
+ errors = queue.Queue(maxsize=1)
490
+ counters = {'accepted': 0, 'failed': 0, 'uncertain': 0, 'wake_retries': 0}
491
+ reason = 'duration'
492
+ handoffs = DesktopHandoffs(store)
493
+ last_errors = {}
494
+ route_backoff = {}
495
+ stuck_warned = {}
496
+ stuck_check_at = 0.0
497
+
498
+ def settle_unknown_enqueues():
499
+ # An enqueue whose child died without a receipt may or may not have
500
+ # queued the notice. The desktop's own records answer that: still queued
501
+ # (keep its id and wake it), already in the chat (accepted), or in
502
+ # neither (it never landed, so retry). Unreadable records settle nothing.
503
+ older_than = core.clock() - UNKNOWN_ENQUEUE_CHECK_AFTER_SECONDS
504
+ for event in handoffs.unknown_enqueues(older_than):
505
+ try:
506
+ found, queue_id = transport.notice_outcome(event['thread_id'], event['since'])
507
+ if found == 'queued':
508
+ handoffs.queued(event, queue_id)
509
+ outcome, receipt = 'queued', {'queue_id': queue_id}
510
+ elif found == 'delivered':
511
+ outcome, receipt = 'accepted', handoffs.delivered(event)
512
+ else:
513
+ outcome, receipt = 'failed', store.resolve(event['notification_id'], 'failed')
514
+ except CoreError as error:
515
+ report(event['notification_id'], {'type': 'desktop_unknown_enqueue_unsettled',
516
+ 'notification_id': event['notification_id'], 'error': _code(error)})
517
+ continue
518
+ emit({'type': 'desktop_unknown_enqueue_settled', 'client_id': event['client_id'],
519
+ 'thread_id': event['thread_id'], 'outcome': outcome,
520
+ 'notification_id': event['notification_id'], **receipt})
521
+
522
+ def warn_stuck_wakes():
523
+ # Report only. An unresolved handoff may already have reached the target,
524
+ # so DIRECT_DISPATCH.md requires a human to reconcile it.
525
+ now = time.monotonic()
526
+ wakes = store.unresolved_wakes()
527
+ current = {wake['notification_id'] for wake in wakes}
528
+ for key in set(stuck_warned) - current:
529
+ del stuck_warned[key]
530
+ for wake in wakes:
531
+ if now < stuck_warned.get(wake['notification_id'], 0):
532
+ continue
533
+ stuck_warned[wake['notification_id']] = now + STUCK_WAKE_WARNING_REPEAT_SECONDS
534
+ emit({'type': 'desktop_wake_stuck', 'level': 'warning', **wake,
535
+ 'message': STUCK_WAKE_MESSAGES[wake['next_action']]})
536
+
537
+ def report(key, event):
538
+ if last_errors.get(key) != event.get('error'):
539
+ emit(event)
540
+ last_errors[key] = event.get('error')
541
+
542
+ def signal_stop(_signum, _frame):
543
+ stop.set()
544
+
545
+ def collect_loop():
546
+ backoff = interval
547
+ while not stop.is_set():
548
+ try:
549
+ core.collect(timeout=10, judge=True)
550
+ backoff = interval
551
+ except Exception as error:
552
+ try:
553
+ errors.put_nowait(_code(error))
554
+ except queue.Full:
555
+ pass
556
+ backoff = min(60, max(interval, backoff * 2))
557
+ stop.wait(backoff)
558
+
559
+ with core._lock('relay-watcher') as acquired:
560
+ if not acquired:
561
+ raise CoreError('relay_watcher_busy')
562
+ try:
563
+ transport.check_capability()
564
+ if threading.current_thread() is threading.main_thread():
565
+ for signum in (signal.SIGTERM, signal.SIGINT):
566
+ handlers[signum] = signal.signal(signum, signal_stop)
567
+ recovered = store.recover_inflight()
568
+ emit({'type': 'desktop_dispatcher_ready', 'duration': duration, 'collect': collect,
569
+ 'recovered': recovered, 'delivery_role': 'user'})
570
+ if collect:
571
+ collector = threading.Thread(target=collect_loop, name='aot-desktop-collector', daemon=True)
572
+ collector.start()
573
+ while not stop.is_set() and time.monotonic() < deadline:
574
+ try:
575
+ error = errors.get_nowait()
576
+ except queue.Empty:
577
+ pass
578
+ else:
579
+ report('collector', {'type': 'desktop_collection_error', 'error': error})
580
+ if time.monotonic() >= stuck_check_at:
581
+ stuck_check_at = time.monotonic() + STUCK_WAKE_CHECK_SECONDS
582
+ settle_unknown_enqueues()
583
+ warn_stuck_wakes()
584
+ if not transport.desktop_running():
585
+ report('desktop', {'type': 'desktop_waiting', 'error': 'desktop_not_running'})
586
+ stop.wait(min(interval, max(0, deadline - time.monotonic())))
587
+ continue
588
+ last_errors.pop('desktop', None)
589
+ bindings = {b['client_id']: b for b in store.status()['bindings']}
590
+ # Accepted native queue items are never re-enqueued, even after
591
+ # a failed opener or process restart. Retry only the wake URL.
592
+ for event in handoffs.pending():
593
+ binding = bindings.get(event['client_id'])
594
+ if (stop.is_set() or binding is None or not binding['eligible']
595
+ or (binding['thread_id'], binding['project_dir']) !=
596
+ (event['thread_id'], event['project_dir'])):
597
+ continue
598
+ try:
599
+ handoffs.wake_started(event)
600
+ if stop.is_set():
601
+ break
602
+ transport.wake(event)
603
+ except DesktopQueueError as error:
604
+ counters['wake_retries'] += 1
605
+ report(event['notification_id'], {'type': 'desktop_wake_pending',
606
+ 'notification_id': event['notification_id'], 'queue_id': event['queue_id'],
607
+ 'error': _code(error)})
608
+ else:
609
+ receipt = handoffs.done(event)
610
+ counters['accepted'] += 1
611
+ emit({'type': 'desktop_dispatcher_receipt', 'client_id': event['client_id'],
612
+ 'thread_id': event['thread_id'], 'queue_id': event['queue_id'],
613
+ 'outcome': 'accepted', **receipt})
614
+ allowed = {}
615
+ for binding in bindings.values():
616
+ client = binding['client_id']
617
+ if (not binding['eligible'] or not binding['dispatchable_messages']
618
+ or time.monotonic() < route_backoff.get(client, 0)):
619
+ continue
620
+ try:
621
+ transport.validate_target(binding)
622
+ except DesktopQueueError as error:
623
+ route_backoff[client] = time.monotonic() + 5
624
+ report(client, {'type': 'desktop_route_blocked', 'client_id': client,
625
+ 'thread_id': binding['thread_id'], 'error': _code(error)})
626
+ else:
627
+ last_errors.pop(client, None)
628
+ allowed[client] = (binding['thread_id'], binding['project_dir'])
629
+ if not stop.is_set() and transport.desktop_running():
630
+ event = store.next_event(allowed_client_ids=set(allowed))
631
+ if event is not None:
632
+ current = next((b for b in store.status(event['client_id'])['bindings']
633
+ if b['client_id'] == event['client_id']), None)
634
+ if (stop.is_set() or not transport.desktop_running()
635
+ or current is None or not current['eligible']
636
+ or allowed.get(event['client_id']) != (event['thread_id'], event['project_dir'])
637
+ or (current['thread_id'], current['project_dir']) !=
638
+ (event['thread_id'], event['project_dir'])):
639
+ store.resolve(event['notification_id'], 'failed')
640
+ elif transport.thread_busy(event['thread_id'], core.clock()):
641
+ # The hooks reach a busy chat inside its turn. Try
642
+ # again later; once it is idle, the notice is queued.
643
+ receipt = store.resolve(event['notification_id'], 'failed')
644
+ report('busy:' + event['client_id'], {'type': 'desktop_wake_deferred_busy',
645
+ 'client_id': event['client_id'], 'thread_id': event['thread_id'],
646
+ 'error': 'thread_busy', **receipt})
647
+ else:
648
+ last_errors.pop('busy:' + event['client_id'], None)
649
+ handoffs.prepare(event)
650
+ if stop.is_set() or not transport.desktop_running():
651
+ store.resolve(event['notification_id'], 'failed')
652
+ continue
653
+ try:
654
+ queue_id = transport.enqueue(event)
655
+ handoffs.queued(event, queue_id)
656
+ except DesktopQueueError as error:
657
+ outcome = 'uncertain' if error.ambiguous else 'failed'
658
+ receipt = store.resolve(event['notification_id'], outcome)
659
+ counters[outcome] += 1
660
+ emit({'type': 'desktop_dispatcher_receipt', 'client_id': event['client_id'],
661
+ 'thread_id': event['thread_id'], 'outcome': outcome,
662
+ 'error': _code(error), **receipt})
663
+ else:
664
+ emit({'type': 'desktop_queued', 'notification_id': event['notification_id'],
665
+ 'thread_id': event['thread_id'], 'queue_id': queue_id})
666
+ stop.wait(min(interval, max(0, deadline - time.monotonic())))
667
+ if stop.is_set():
668
+ reason = 'stopped'
669
+ except KeyboardInterrupt:
670
+ reason = 'stopped'
671
+ finally:
672
+ stop.set()
673
+ if collector is not None:
674
+ collector.join(timeout=.2)
675
+ store.recover_inflight()
676
+ for signum, handler in handlers.items():
677
+ signal.signal(signum, handler)
678
+ result = {'type': 'desktop_dispatcher_stopped', 'reason': reason, **counters}
679
+ emit(result)
680
+ return result