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,260 @@
1
+ """Persistent local Codex dispatcher: durable inbox signals, never inbox ACKs.
2
+
3
+ The explicitly supplied endpoint must be the desktop's shared backend. This
4
+ module never starts a backend, answers server requests, supplies turn settings,
5
+ or substitutes another connection after an ambiguous mutation.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import math
11
+ from pathlib import Path
12
+ import queue
13
+ import re
14
+ import signal
15
+ import threading
16
+ import time
17
+ import uuid
18
+
19
+ from .appserver_client import AppServerConnection, AppServerError
20
+ from .core import CoreError
21
+ from .relay import WAKE_NOTICE
22
+
23
+
24
+ def _error_code(error):
25
+ value = getattr(error, 'code', '')
26
+ return value if isinstance(value, str) and re.fullmatch(r'[a-z0-9_]{1,64}', value) else 'dispatcher_failed'
27
+
28
+
29
+ def _uuid(value):
30
+ try:
31
+ return isinstance(value, str) and str(uuid.UUID(value)) == value
32
+ except (ValueError, TypeError, AttributeError):
33
+ return False
34
+
35
+
36
+ def _matches_thread(response, binding, *, resumed=False):
37
+ thread = response.get('thread') if isinstance(response, dict) else None
38
+ if not isinstance(thread, dict) or thread.get('id') != binding['thread_id']:
39
+ return False
40
+ if thread.get('canAcceptDirectInput') is False:
41
+ return False
42
+ try:
43
+ cwd = thread.get('cwd')
44
+ captured_matches = (isinstance(cwd, str) and Path(cwd).is_absolute()
45
+ and Path(cwd).is_dir() and str(Path(cwd).resolve(strict=True)) == binding['project_dir'])
46
+ if not captured_matches or not resumed:
47
+ return captured_matches
48
+ effective_cwd = response.get('cwd')
49
+ return (isinstance(effective_cwd, str) and Path(effective_cwd).is_absolute()
50
+ and Path(effective_cwd).is_dir()
51
+ and str(Path(effective_cwd).resolve(strict=True)) == binding['project_dir'])
52
+ except (OSError, ValueError, RuntimeError):
53
+ return False
54
+
55
+
56
+ def run_dispatcher(core, store, endpoint, *, token_file=None, collect=False,
57
+ duration=55, emit=None, interval=.5, stop_event=None):
58
+ """Dispatch fixed tool output to the existing thread through one connection.
59
+
60
+ ``duration=0`` runs until stopped by the owning app or a signal. Quiet waits
61
+ only drain protocol events and inspect the local durable inbox. They never
62
+ create periodic model turns. ``accepted`` is a host receipt, not proof of
63
+ completed processing or a Telegram reply. Callers construct Core with
64
+ ``recover_sends=False``; this dispatcher never flushes outgoing messages.
65
+ """
66
+ if (type(collect) is not bool or isinstance(duration, bool)
67
+ or not isinstance(duration, (int, float)) or not math.isfinite(duration)
68
+ or not 0 <= duration <= 86400 or isinstance(interval, bool)
69
+ or not isinstance(interval, (int, float)) or not math.isfinite(interval)
70
+ or not .01 <= interval <= 60):
71
+ raise CoreError('invalid_dispatcher_options')
72
+ if emit is None:
73
+ def emit(value):
74
+ print(json.dumps(value, separators=(',', ':'), ensure_ascii=True), flush=True)
75
+ stop = threading.Event() if stop_event is None else stop_event
76
+ deadline = time.monotonic() + duration if duration else float('inf')
77
+ connection = None
78
+ collector = None
79
+ errors = queue.Queue(maxsize=1)
80
+ handlers = {}
81
+ counters = {'accepted': 0, 'failed': 0, 'uncertain': 0, 'needs_attention': 0}
82
+ reason = 'duration'
83
+ last_route_errors = {}
84
+ route_backoff = {}
85
+
86
+ def signal_stop(_signum, _frame):
87
+ stop.set()
88
+
89
+ def collect_loop():
90
+ backoff = interval
91
+ last_error = None
92
+ while not stop.is_set():
93
+ try:
94
+ core.collect(timeout=10, judge=True)
95
+ backoff, last_error = interval, None
96
+ except Exception as error:
97
+ code = _error_code(error)
98
+ if code != last_error:
99
+ try:
100
+ errors.put_nowait(code)
101
+ except queue.Full:
102
+ pass
103
+ last_error = code
104
+ backoff = min(60, max(interval, backoff * 2))
105
+ stop.wait(backoff)
106
+
107
+ def drain(timeout=0):
108
+ for event in connection.drain(timeout=timeout):
109
+ # The transport already strips payloads. Keep a second allowlist
110
+ # here so future client fields cannot leak through diagnostics.
111
+ metadata = {key: event[key] for key in ('kind', 'method', 'threadId', 'turnId') if key in event}
112
+ attention = event.get('kind') == 'server_request'
113
+ if attention:
114
+ counters['needs_attention'] += 1
115
+ emit({'type': 'dispatcher_needs_attention' if attention else 'dispatcher_event', **metadata})
116
+
117
+ with core._lock('relay-watcher') as acquired:
118
+ if not acquired:
119
+ raise CoreError('relay_watcher_busy')
120
+ try:
121
+ if threading.current_thread() is threading.main_thread():
122
+ for signum in (signal.SIGTERM, signal.SIGINT):
123
+ handlers[signum] = signal.signal(signum, signal_stop)
124
+ recovered = store.recover_inflight()
125
+ # Retry only initial readiness failures, before any event is claimed.
126
+ # Each candidate is a new connection; a used connection never retries.
127
+ for attempt in range(5):
128
+ if stop.is_set() or time.monotonic() >= deadline:
129
+ break
130
+ candidate = AppServerConnection(endpoint, token_file=token_file)
131
+ try:
132
+ candidate.connect()
133
+ connection = candidate
134
+ break
135
+ except AppServerError as error:
136
+ candidate.close()
137
+ if (error.code not in ('appserver_connect_failed', 'appserver_socket_unavailable',
138
+ 'appserver_timeout', 'appserver_transport_failed') or attempt == 4):
139
+ raise
140
+ emit({'type': 'dispatcher_connect_wait', 'error': error.code, 'attempt': attempt + 1})
141
+ stop.wait(min(.1 * 2 ** attempt, max(0, deadline - time.monotonic())))
142
+ if connection is None:
143
+ reason = 'stopped' if stop.is_set() else 'connection_failed'
144
+ else:
145
+ emit({'type': 'dispatcher_ready', 'duration': duration, 'collect': collect, 'recovered': recovered})
146
+ if collect:
147
+ collector = threading.Thread(target=collect_loop, name='aot-dispatcher-collector', daemon=True)
148
+ collector.start()
149
+ next_scan = 0.0
150
+ while connection is not None and not stop.is_set() and time.monotonic() < deadline:
151
+ try:
152
+ code = errors.get_nowait()
153
+ except queue.Empty:
154
+ pass
155
+ else:
156
+ emit({'type': 'dispatcher_collection_error', 'error': code})
157
+ if time.monotonic() >= next_scan:
158
+ allowed = {}
159
+ for binding in store.status()['bindings']:
160
+ client_id = binding['client_id']
161
+ identity = (binding['thread_id'], binding['project_dir'])
162
+ previous = route_backoff.get(client_id)
163
+ if previous and (previous[0] != identity or not binding['eligible']):
164
+ route_backoff.pop(client_id, None)
165
+ last_route_errors.pop(client_id, None)
166
+ previous = None
167
+ if not binding['eligible'] or (not binding['dispatchable_messages']
168
+ and binding['retry_pending_messages'] != 0):
169
+ continue
170
+ if previous and time.monotonic() < previous[2]:
171
+ continue
172
+ try:
173
+ result = connection.request('thread/read', {
174
+ 'threadId': binding['thread_id'], 'includeTurns': False})
175
+ if not _matches_thread(result, binding):
176
+ raise CoreError('dispatcher_target_mismatch')
177
+ result = connection.request('thread/resume', {
178
+ 'threadId': binding['thread_id'], 'excludeTurns': True})
179
+ if not _matches_thread(result, binding, resumed=True):
180
+ raise CoreError('dispatcher_target_mismatch')
181
+ except (CoreError, AppServerError) as error:
182
+ if isinstance(error, AppServerError) and error.code != 'appserver_rpc_error':
183
+ raise
184
+ code = _error_code(error)
185
+ attempts = min(7, previous[1] + 1) if previous else 1
186
+ route_backoff[client_id] = (identity, attempts,
187
+ time.monotonic() + min(60, 2 ** (attempts - 1)))
188
+ if last_route_errors.get(client_id) != code:
189
+ emit({'type': 'dispatcher_route_blocked', 'client_id': client_id,
190
+ 'thread_id': binding['thread_id'], 'error': code})
191
+ last_route_errors[client_id] = code
192
+ continue
193
+ last_route_errors.pop(client_id, None)
194
+ route_backoff.pop(client_id, None)
195
+ allowed[client_id] = (binding['thread_id'], binding['project_dir'])
196
+ # The store checks pause, leases and project validity again
197
+ # in the same transaction that records the durable intent.
198
+ if stop.is_set():
199
+ break
200
+ event = store.next_event(allowed_client_ids=set(allowed))
201
+ if event is not None:
202
+ if stop.is_set():
203
+ store.resolve(event['notification_id'], 'failed')
204
+ break
205
+ if allowed.get(event['client_id']) != (event['thread_id'], event['project_dir']):
206
+ receipt = store.resolve(event['notification_id'], 'failed')
207
+ counters['failed'] += 1
208
+ emit({'type': 'dispatcher_receipt', 'client_id': event['client_id'],
209
+ 'thread_id': event['thread_id'], 'outcome': 'failed',
210
+ 'error': 'dispatcher_target_changed', **receipt})
211
+ next_scan = time.monotonic() + interval
212
+ continue
213
+ params = {'threadId': event['thread_id'], 'input': [], 'toolOutput': {
214
+ 'name': 'telegram_inbox_ready', 'namespace': 'agents_over_telegram',
215
+ 'output': json.dumps({'notification_id': event['notification_id'], 'notice': WAKE_NOTICE},
216
+ separators=(',', ':'), ensure_ascii=True),
217
+ 'retain': True}, 'turnTrigger': 'telegram'}
218
+ try:
219
+ response = connection.request('turn/start', params, mutating=True)
220
+ turn = response.get('turn') if isinstance(response, dict) else None
221
+ if (not isinstance(turn, dict) or not _uuid(turn.get('id'))
222
+ or turn.get('status') not in ('inProgress', 'completed', 'interrupted', 'failed')):
223
+ raise AppServerError('invalid_appserver_turn_response', ambiguous=True)
224
+ except AppServerError as error:
225
+ outcome = 'uncertain' if error.ambiguous else 'failed'
226
+ receipt = store.resolve(event['notification_id'], outcome)
227
+ counters[outcome] += 1
228
+ emit({'type': 'dispatcher_receipt', 'client_id': event['client_id'],
229
+ 'thread_id': event['thread_id'], 'outcome': outcome,
230
+ 'error': _error_code(error), **receipt})
231
+ if error.code != 'appserver_rpc_error':
232
+ raise
233
+ else:
234
+ receipt = store.resolve(event['notification_id'], 'accepted')
235
+ counters['accepted'] += 1
236
+ emit({'type': 'dispatcher_receipt', 'client_id': event['client_id'],
237
+ 'thread_id': event['thread_id'], 'turn_id': turn['id'],
238
+ 'outcome': 'accepted', **receipt})
239
+ next_scan = time.monotonic() + interval
240
+ drain(timeout=min(.1, max(0, deadline - time.monotonic())))
241
+ if stop.is_set():
242
+ reason = 'stopped'
243
+ except KeyboardInterrupt:
244
+ reason = 'stopped'
245
+ stop.set()
246
+ except AppServerError as error:
247
+ reason = 'connection_failed'
248
+ emit({'type': 'dispatcher_error', 'error': _error_code(error)})
249
+ finally:
250
+ stop.set()
251
+ if connection is not None:
252
+ connection.close()
253
+ if collector is not None:
254
+ collector.join(timeout=.2)
255
+ store.recover_inflight()
256
+ for signum, handler in handlers.items():
257
+ signal.signal(signum, handler)
258
+ result = {'type': 'dispatcher_stopped', 'reason': reason, **counters}
259
+ emit(result)
260
+ return result
@@ -0,0 +1,125 @@
1
+ """Project-local MCP configuration for hosts that read JSON settings files.
2
+
3
+ Codex keeps its TOML entry in onboarding. Pi reads ``.pi/mcp.json`` and Amp
4
+ reads ``.amp/settings.json``. Both are written like the Codex entry: unrelated
5
+ content is preserved, an existing different ``telegram`` entry is a conflict,
6
+ and nothing is changed before the whole plan is checked.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from pathlib import Path
12
+
13
+ from .credentials import CredentialError
14
+
15
+ SERVER = 'telegram'
16
+ DESCRIPTION = "This project's scoped Agents over Telegram inbox and replies."
17
+
18
+ # host -> (relative file, key that holds the server map)
19
+ JSON_HOSTS = {
20
+ 'pi': (Path('.pi') / 'mcp.json', 'mcpServers'),
21
+ 'amp': (Path('.amp') / 'settings.json', 'amp.mcpServers'),
22
+ }
23
+
24
+
25
+ def expected_entry(host: str, entry: dict) -> dict:
26
+ """The server entry for one host, built from the shared command and args."""
27
+ value = {'command': entry['command'], 'args': list(entry['args'])}
28
+ if host == 'pi':
29
+ # Direct exposure gives the model plain tool names instead of a code-mode wrapper.
30
+ value.update(exposure='direct', description=DESCRIPTION)
31
+ return value
32
+
33
+
34
+ def json_config_plan(project: Path, host: str, entry: dict):
35
+ """Return (path, current_text, proposed_text) without writing anything."""
36
+ from .onboarding import _check_directory, _read_local
37
+ relative, key = JSON_HOSTS[host]
38
+ folder = project / relative.parent
39
+ _check_directory(project)
40
+ _check_directory(folder)
41
+ path = project / relative
42
+ raw = _read_local(path) if path.exists() or path.is_symlink() else None
43
+ expected = expected_entry(host, entry)
44
+ try:
45
+ current = json.loads(raw) if raw and raw.strip() else {}
46
+ if not isinstance(current, dict):
47
+ raise ValueError()
48
+ servers = current.get(key, {})
49
+ if not isinstance(servers, dict):
50
+ raise ValueError()
51
+ except ValueError:
52
+ raise CredentialError('invalid_project_config') from None
53
+ if SERVER in servers:
54
+ current_entry = servers[SERVER]
55
+ if current_entry == expected:
56
+ return path, raw, raw
57
+ # The same client on another runtime (an update) moves to this one;
58
+ # anything else is someone else's entry.
59
+ if not (isinstance(current_entry, dict) and {**current_entry, 'command': expected['command']} == expected
60
+ and isinstance(current_entry.get('command'), str) and Path(current_entry['command']).is_absolute()):
61
+ raise CredentialError('project_mcp_config_conflict')
62
+ proposed = dict(current)
63
+ proposed[key] = {**servers, SERVER: expected}
64
+ return path, raw, json.dumps(proposed, indent=2) + '\n'
65
+
66
+
67
+ # Antigravity (the agy CLI and the desktop app) loads plugins from the
68
+ # project's .agents/plugins/<name>/ folder. Its hooks and skills come from the
69
+ # Agents over Telegram plugin installed once for the user (the repository root,
70
+ # through .antigravity-plugin/plugin.json). That plugin's MCP server cannot
71
+ # tell which project it serves, so setup writes a small project plugin with
72
+ # only the scoped telegram server, naming this project's runtime and client
73
+ # like the Codex, Pi and Amp entries. A rerun of setup replaces its files.
74
+ ANTIGRAVITY_PLUGIN = Path('.agents') / 'plugins' / 'agents-over-telegram-project'
75
+ # 0.10.8 wrote the hooks into the project as well, under this name. With the
76
+ # user plugin installed they would run twice, so setup removes that folder.
77
+ ANTIGRAVITY_OLD_PLUGIN = Path('.agents') / 'plugins' / 'agents-over-telegram'
78
+ ANTIGRAVITY_OLD_FILES = ('plugin.json', 'hooks.json', 'mcp_config.json')
79
+
80
+
81
+ def antigravity_plugin_files(project: Path, entry: dict) -> dict:
82
+ """The project plugin's files, relative path -> text."""
83
+ manifest = {'name': 'agents-over-telegram-project', 'displayName': 'Agents over Telegram (this project)',
84
+ 'description': "This project's Telegram tools. Written by \"aot setup --host antigravity\"; "
85
+ 'run setup again to update it.',
86
+ 'homepage': 'https://github.com/fourlastor/agents-over-telegram', 'license': 'Apache-2.0'}
87
+ servers = {'mcpServers': {SERVER: expected_entry('antigravity', entry)}}
88
+ dump = lambda value: json.dumps(value, indent=2) + '\n'
89
+ return {ANTIGRAVITY_PLUGIN / 'plugin.json': dump(manifest),
90
+ ANTIGRAVITY_PLUGIN / 'mcp_config.json': dump(servers)}
91
+
92
+
93
+ def antigravity_plugin_plan(project: Path, entry: dict):
94
+ """Return [(path, current_text, proposed_text)] without writing anything."""
95
+ from .onboarding import _check_directory, _read_local
96
+ _check_directory(project)
97
+ folder = project
98
+ for part in ANTIGRAVITY_PLUGIN.parts:
99
+ folder = folder / part
100
+ _check_directory(folder)
101
+ plan = []
102
+ for relative, text in antigravity_plugin_files(project, entry).items():
103
+ path = project / relative
104
+ current = _read_local(path) if path.exists() or path.is_symlink() else None
105
+ plan.append((path, current, text))
106
+ return plan
107
+
108
+
109
+ def remove_old_antigravity_plugin(project: Path) -> bool:
110
+ """Remove the project plugin 0.10.8 wrote, only when it is exactly that."""
111
+ folder = project / ANTIGRAVITY_OLD_PLUGIN
112
+ try:
113
+ if folder.is_symlink() or not folder.is_dir():
114
+ return False
115
+ if sorted(child.name for child in folder.iterdir()) != sorted(ANTIGRAVITY_OLD_FILES):
116
+ return False
117
+ manifest = json.loads((folder / 'plugin.json').read_text(encoding='utf-8'))
118
+ if manifest.get('name') != 'agents-over-telegram' or '--host antigravity' not in manifest.get('description', ''):
119
+ return False
120
+ for name in ANTIGRAVITY_OLD_FILES:
121
+ (folder / name).unlink()
122
+ folder.rmdir()
123
+ return True
124
+ except (OSError, ValueError, AttributeError):
125
+ return False