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,720 @@
1
+ """Telegram HTTP and deterministic fake transport; no network exception text escapes."""
2
+ from __future__ import annotations
3
+
4
+ from contextlib import contextmanager
5
+ import copy
6
+ import base64
7
+ import hashlib
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+ import re
12
+ import secrets
13
+ import threading
14
+ import urllib.error
15
+ import urllib.request
16
+
17
+ from . import compat
18
+ from .net import RacingHTTPSHandler
19
+ from .credentials import load_token, private_directory, read_private_json, validate_token, write_private_json
20
+
21
+
22
+ class TransportError(Exception):
23
+ def __init__(self, code="transport_failure", retry_after=None, migrate_to_chat_id=None, bad_entities=False):
24
+ # Codes are controlled by us; never use Telegram descriptions/URLs here.
25
+ self.code = code if isinstance(code, (int, str)) else "transport_failure"
26
+ self.retry_after = retry_after
27
+ # Set only on a 400 that says the group became this supergroup.
28
+ self.migrate_to_chat_id = migrate_to_chat_id
29
+ # Set only on a 400 that says the formatted text could not be parsed.
30
+ # Nothing was sent, so the caller may send the plain text instead.
31
+ self.bad_entities = bad_entities
32
+ super().__init__(str(self.code))
33
+
34
+
35
+ def _bad_entities(description):
36
+ """True when a 400 description says Telegram could not parse the formatting."""
37
+ return isinstance(description, str) and "can't parse entities" in description.lower()
38
+
39
+
40
+ def _migrate_to(parameters):
41
+ """The new chat id a rejection names after a group became a supergroup, or None."""
42
+ target = parameters.get("migrate_to_chat_id") if isinstance(parameters, dict) else None
43
+ return target if type(target) is int and target < 0 else None
44
+
45
+
46
+ class UnknownSend(TransportError):
47
+ def __init__(self, code="unknown_send", retry_after=None):
48
+ super().__init__(code, retry_after)
49
+
50
+
51
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
52
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
53
+ return None
54
+
55
+
56
+ # Owner-action answers (panel answers and edits, button answers) wait at most
57
+ # this long per attempt; the core tries once more after a timeout. Telegram
58
+ # drops a widget answer that comes later than 15 s anyway.
59
+ OWNER_ANSWER_TIMEOUT = 5
60
+
61
+
62
+ class TelegramTransport:
63
+ def __init__(self, token, *, opener=None):
64
+ self._token = validate_token(token)
65
+ self._opener = opener or urllib.request.build_opener(
66
+ _NoRedirect(), urllib.request.ProxyHandler({}), RacingHTTPSHandler())
67
+
68
+ def _call(self, method, params, *, sending=False, timeout=15, expects="message"):
69
+ return self._post(method, json.dumps(params).encode(), "application/json",
70
+ sending=sending, timeout=timeout, expects=expects)
71
+
72
+ def _post(self, method, body, content_type, *, sending=False, timeout=15, expects="message"):
73
+ request = urllib.request.Request(
74
+ "https://api.telegram.org/bot" + self._token + "/" + method,
75
+ data=body, headers={"Content-Type": content_type}, method="POST")
76
+ try:
77
+ try:
78
+ with self._opener.open(request, timeout=timeout) as response:
79
+ data = response.read(2_000_001)
80
+ except urllib.error.HTTPError as error:
81
+ code = error.code
82
+ # Do not trust response bodies or redirects. Only definite client
83
+ # rejection is retryable; server failure may follow acceptance.
84
+ if code == 429:
85
+ try:
86
+ raw = json.loads(error.read(16384))
87
+ retry = raw.get("parameters", {}).get("retry_after", 30)
88
+ retry = max(1, min(86400, int(retry)))
89
+ except Exception:
90
+ retry = 30
91
+ raise TransportError(429, retry) from None
92
+ if code == 400:
93
+ # Only the integer migrate_to_chat_id and whether the
94
+ # formatting failed to parse are read from the body.
95
+ try:
96
+ raw = json.loads(error.read(16384))
97
+ migrate, bad = _migrate_to(raw.get("parameters")), _bad_entities(raw.get("description"))
98
+ except Exception:
99
+ migrate, bad = None, False
100
+ raise TransportError(code, migrate_to_chat_id=migrate, bad_entities=bad) from None
101
+ if 400 <= code < 500:
102
+ raise TransportError(code) from None
103
+ raise UnknownSend() if sending else TransportError("http_failure") from None
104
+ if len(data) > 2_000_000:
105
+ raise ValueError()
106
+ payload = json.loads(data)
107
+ if not isinstance(payload, dict):
108
+ raise ValueError()
109
+ if payload.get("ok") is not True:
110
+ code = payload.get("error_code")
111
+ if type(code) is int and 400 <= code < 500:
112
+ retry = payload.get("parameters", {}).get("retry_after", 30) if code == 429 else None
113
+ if retry is not None:
114
+ retry = max(1, min(86400, int(retry)))
115
+ migrate = _migrate_to(payload.get("parameters")) if code == 400 else None
116
+ bad = code == 400 and _bad_entities(payload.get("description"))
117
+ raise TransportError(code, retry, migrate_to_chat_id=migrate, bad_entities=bad)
118
+ raise UnknownSend() if sending else TransportError("invalid_response")
119
+ result = payload["result"]
120
+ if sending and expects == "message" and (not isinstance(result, dict) or type(result.get("message_id")) is not int):
121
+ raise ValueError()
122
+ # setMessageReaction answers with the bare boolean True.
123
+ if sending and expects == "bool" and result is not True:
124
+ raise ValueError()
125
+ return result
126
+ except TransportError:
127
+ raise
128
+ except Exception as error:
129
+ if sending:
130
+ raise UnknownSend() from None
131
+ # Named apart, so a call that hung until its timeout can be told
132
+ # from one the network refused.
133
+ timed_out = isinstance(error, TimeoutError) or isinstance(getattr(error, "reason", None), TimeoutError)
134
+ raise TransportError("timeout" if timed_out else "transport_failure") from None
135
+
136
+ def get_me(self):
137
+ result = self._call("getMe", {})
138
+ if not isinstance(result, dict) or type(result.get("id")) is not int or result.get("is_bot") is not True:
139
+ raise TransportError("invalid_bot_identity")
140
+ return result
141
+
142
+ def get_webhook_info(self):
143
+ result = self._call("getWebhookInfo", {})
144
+ if not isinstance(result, dict) or not isinstance(result.get("url"), str):
145
+ raise TransportError("invalid_webhook_status")
146
+ return {"url": result["url"]} # Never exposed as diagnostic output.
147
+
148
+ def get_updates(self, offset, timeout=0):
149
+ timeout = max(0, min(20, int(timeout)))
150
+ result = self._call("getUpdates", {"offset": offset, "timeout": timeout, "limit": 100,
151
+ # message_reaction must be named explicitly; Telegram never sends it by
152
+ # default, and only while the bot is an administrator in the chat.
153
+ # callback_query carries the owner's Approve or Decline button presses.
154
+ # widget_query carries requests from the owner's settings panel.
155
+ "allowed_updates": ["message", "edited_message", "my_chat_member", "message_reaction",
156
+ "callback_query", "widget_query"]}, timeout=timeout + 15)
157
+ if not isinstance(result, list):
158
+ raise TransportError("invalid_updates")
159
+ return result
160
+
161
+ def send_message(self, chat_id, text, thread_id=None, reply_to=None, reply_markup=None, ephemeral_to=None,
162
+ parse_mode=None):
163
+ params = {"chat_id": chat_id, "text": text, "link_preview_options": {"is_disabled": True}}
164
+ if parse_mode is not None:
165
+ params["parse_mode"] = parse_mode
166
+ if thread_id is not None:
167
+ params["message_thread_id"] = thread_id
168
+ if reply_to is not None:
169
+ params["reply_parameters"] = {"message_id": reply_to}
170
+ if reply_markup is not None:
171
+ params["reply_markup"] = reply_markup
172
+ if ephemeral_to is not None:
173
+ # Visible only to this user and the bot (Bot API 10.3+).
174
+ params["ephemeral_message_parameters"] = {"receiver_user_id": ephemeral_to}
175
+ return self._call("sendMessage", params, sending=True)
176
+
177
+ def answer_callback_query(self, callback_query_id, text):
178
+ return self._call("answerCallbackQuery", {"callback_query_id": callback_query_id, "text": text[:200]},
179
+ timeout=OWNER_ANSWER_TIMEOUT)
180
+
181
+ def set_my_commands(self, commands, scope):
182
+ return self._call("setMyCommands", {"commands": commands, "scope": scope})
183
+
184
+ def delete_message(self, chat_id, message_id):
185
+ return self._call("deleteMessage", {"chat_id": chat_id, "message_id": message_id}, timeout=OWNER_ANSWER_TIMEOUT)
186
+
187
+ def send_widget(self, chat_id, html, *, chat_data=None, allow_queries=False):
188
+ params = {"chat_id": chat_id, "html": html, "allow_queries": allow_queries}
189
+ if chat_data is not None:
190
+ params["chat_data"] = chat_data
191
+ return self._call("sendWidget", params, sending=True)
192
+
193
+ def answer_widget_query(self, widget_query_id, data):
194
+ return self._call("answerWidgetQuery", {"widget_query_id": widget_query_id, "data": data},
195
+ timeout=OWNER_ANSWER_TIMEOUT)
196
+
197
+ def edit_message_widget_data(self, chat_id, message_id, chat_data):
198
+ return self._call("editMessageWidgetData", {"chat_id": chat_id, "message_id": message_id,
199
+ "chat_data": chat_data}, timeout=OWNER_ANSWER_TIMEOUT)
200
+
201
+ def edit_message_text(self, chat_id, message_id, text, parse_mode=None, reply_markup=None):
202
+ # Without reply_markup, Telegram removes the message's inline buttons.
203
+ params = {"chat_id": chat_id, "message_id": message_id, "text": text,
204
+ "link_preview_options": {"is_disabled": True}}
205
+ if parse_mode is not None:
206
+ params["parse_mode"] = parse_mode
207
+ if reply_markup is not None:
208
+ params["reply_markup"] = reply_markup
209
+ return self._call("editMessageText", params)
210
+
211
+ def edit_ephemeral_message_text(self, chat_id, receiver_user_id, ephemeral_message_id, text):
212
+ # Without reply_markup, Telegram removes the message's inline buttons.
213
+ return self._call("editEphemeralMessageText", {"chat_id": chat_id, "receiver_user_id": receiver_user_id,
214
+ "ephemeral_message_id": ephemeral_message_id, "text": text,
215
+ "link_preview_options": {"is_disabled": True}})
216
+
217
+ def send_photo(self, chat_id, data, *, caption=None, filename="photo.png",
218
+ mime="image/png", thread_id=None, reply_to=None, parse_mode=None):
219
+ """Upload one local image as a photo; caption length is the caller's duty."""
220
+ return self._send_media("sendPhoto", "photo", chat_id, data, caption=caption, filename=filename,
221
+ mime=mime, thread_id=thread_id, reply_to=reply_to, parse_mode=parse_mode)
222
+
223
+ def send_document(self, chat_id, data, *, caption=None, filename="document.bin",
224
+ mime="application/octet-stream", thread_id=None, reply_to=None, parse_mode=None):
225
+ """Upload one local file as a document; caption length is the caller's duty."""
226
+ return self._send_media("sendDocument", "document", chat_id, data, caption=caption, filename=filename,
227
+ mime=mime, thread_id=thread_id, reply_to=reply_to, parse_mode=parse_mode)
228
+
229
+ def _send_media(self, method, field, chat_id, data, *, caption, filename, mime, thread_id, reply_to,
230
+ parse_mode=None):
231
+ fields = {"chat_id": str(chat_id)}
232
+ if caption:
233
+ fields["caption"] = caption
234
+ if parse_mode is not None:
235
+ fields["parse_mode"] = parse_mode
236
+ if thread_id is not None:
237
+ fields["message_thread_id"] = str(thread_id)
238
+ if reply_to is not None:
239
+ fields["reply_parameters"] = json.dumps({"message_id": reply_to})
240
+ body, content_type = _multipart(fields, [(field, filename, mime, bytes(data))])
241
+ return self._post(method, body, content_type, sending=True)
242
+
243
+ def forward_message(self, chat_id, from_chat_id, message_id):
244
+ """Forward one message, for example from a group to the owner's private chat."""
245
+ return self._call("forwardMessage", {"chat_id": chat_id, "from_chat_id": from_chat_id,
246
+ "message_id": message_id}, sending=True)
247
+
248
+ def set_message_reaction(self, chat_id, message_id, emoji):
249
+ """Set the bot's one standard-emoji reaction, or remove it when emoji is empty.
250
+
251
+ The Bot API answers True; an empty reaction list clears the bot's
252
+ reaction. Anything but a definite True is an uncertain outcome.
253
+ """
254
+ params = {"chat_id": chat_id, "message_id": message_id,
255
+ "reaction": [{"type": "emoji", "emoji": emoji}] if emoji else []}
256
+ return self._call("setMessageReaction", params, sending=True, expects="bool")
257
+
258
+ def get_chat_member(self, chat_id, user_id):
259
+ result = self._call("getChatMember", {"chat_id": chat_id, "user_id": user_id})
260
+ if not isinstance(result, dict) or not isinstance(result.get("status"), str):
261
+ raise TransportError("invalid_chat_member")
262
+ return _chat_member(result)
263
+
264
+ def download_file(self, file_id, max_bytes):
265
+ """Resolve a file with getFile, then read at most max_bytes; no redirects."""
266
+ result = self._call("getFile", {"file_id": file_id})
267
+ if not isinstance(result, dict):
268
+ raise TransportError("invalid_file")
269
+ size = result.get("file_size")
270
+ if type(size) is int and size > max_bytes:
271
+ raise TransportError("file_too_large")
272
+ request = urllib.request.Request(
273
+ "https://api.telegram.org/file/bot" + self._token + "/" + _file_path(result.get("file_path")), method="GET")
274
+ try:
275
+ with self._opener.open(request, timeout=60) as response:
276
+ data = response.read(max_bytes + 1)
277
+ except urllib.error.HTTPError as error:
278
+ raise TransportError(error.code if 400 <= error.code < 500 else "http_failure") from None
279
+ except Exception:
280
+ raise TransportError("transport_failure") from None
281
+ if len(data) > max_bytes:
282
+ raise TransportError("file_too_large")
283
+ return data
284
+
285
+
286
+ def _file_path(value):
287
+ """Telegram's relative file path, refused unless it is plainly relative."""
288
+ if (not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_./-]{1,256}", value)
289
+ or value.startswith("/") or ".." in value.split("/")):
290
+ raise TransportError("invalid_file")
291
+ return value
292
+
293
+
294
+ def _multipart(fields, files):
295
+ """Encode multipart/form-data with text fields and byte file parts."""
296
+ boundary = "----aot" + secrets.token_hex(16)
297
+ parts = []
298
+ for name, value in fields.items():
299
+ parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode())
300
+ for name, filename, mime, data in files:
301
+ parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"; '
302
+ f'filename="{filename}"\r\nContent-Type: {mime}\r\n\r\n'.encode() + data + b"\r\n")
303
+ parts.append(f"--{boundary}--\r\n".encode())
304
+ return b"".join(parts), "multipart/form-data; boundary=" + boundary
305
+
306
+
307
+ def _fake_file(files, file_id, max_bytes):
308
+ entry = files.get(file_id)
309
+ if not isinstance(entry, dict):
310
+ raise TransportError(400)
311
+ data = base64.b64decode(entry["content_b64"]) if "content_b64" in entry else entry["content"]
312
+ if len(data) > max_bytes:
313
+ raise TransportError("file_too_large")
314
+ return bytes(data)
315
+
316
+
317
+ def _chat_member(value):
318
+ """Keep only the fields the suspension check reads; never user profile data."""
319
+ member = {"status": value.get("status")}
320
+ for key in ("is_member", "can_send_messages"):
321
+ if isinstance(value.get(key), bool):
322
+ member[key] = value[key]
323
+ return member
324
+
325
+
326
+ def _fake_chat_member(members, chat_id, user_id):
327
+ # Telegram answers 400/403 when the bot cannot see the chat. Model that for
328
+ # chats with no explicit entry, so tests fail closed like the real API.
329
+ member = members.get(str(chat_id), {}).get(str(user_id))
330
+ if member is None:
331
+ raise TransportError(403)
332
+ return _chat_member(member)
333
+
334
+
335
+ class FakeTransport:
336
+ """No sockets; modes sent/reject/rate_limit/unknown/crash model failure windows.
337
+
338
+ bad_entities rejects a formatted send the way Telegram rejects HTML it
339
+ cannot parse; it is not consumed by a plain send."""
340
+ def __init__(self, updates=None, *, bot_id=900001, username="aot_test_bot", webhook="", outcomes=None):
341
+ self.updates = list(updates or [])
342
+ self.bot_id = bot_id
343
+ self.username = username
344
+ self.webhook = webhook
345
+ self.outcomes = list(outcomes or [])
346
+ self.sent = []
347
+ self.reactions = []
348
+ self.forwards = []
349
+ self.poll_offsets = []
350
+ self.chat_members = {} # {str(chat_id): {str(user_id): ChatMember dict}}
351
+ self.files = {} # {file_id: {"content": bytes}}
352
+ self.callback_answers = []
353
+ self.edits = []
354
+ self.widgets = []
355
+ self.menus = []
356
+ self.deleted = []
357
+ self.widget_answers = []
358
+ self.widget_edits = []
359
+ self._lock = threading.RLock()
360
+
361
+ def get_me(self):
362
+ return {"id": self.bot_id, "username": self.username, "is_bot": True}
363
+
364
+ def get_webhook_info(self):
365
+ return {"url": self.webhook}
366
+
367
+ def get_updates(self, offset, timeout=0):
368
+ with self._lock:
369
+ self.poll_offsets.append(offset)
370
+ return copy.deepcopy(sorted((u for u in self.updates if u["update_id"] >= offset), key=lambda x:x["update_id"])[:100])
371
+
372
+ def send_message(self, chat_id, text, thread_id=None, reply_to=None, reply_markup=None, ephemeral_to=None,
373
+ parse_mode=None):
374
+ with self._lock:
375
+ outcome = self._outcome(parse_mode)
376
+ if isinstance(outcome, BaseException):
377
+ raise outcome
378
+ if outcome == "reject":
379
+ raise TransportError(403)
380
+ if outcome == "rate_limit":
381
+ raise TransportError(429, 30)
382
+ message = {"message_id": len(self.sent)+1, "chat": {"id": chat_id}, "text": text,
383
+ "message_thread_id": thread_id, "reply_to_message_id": reply_to}
384
+ if parse_mode is not None:
385
+ message["parse_mode"] = parse_mode
386
+ if reply_markup is not None:
387
+ message["reply_markup"] = copy.deepcopy(reply_markup)
388
+ if ephemeral_to is not None:
389
+ message.update(message_id=0, ephemeral_message_id=len(self.sent)+1, receiver_user={"id": ephemeral_to})
390
+ self.sent.append(message)
391
+ if outcome == "unknown":
392
+ raise UnknownSend()
393
+ if outcome == "crash":
394
+ raise SystemExit("fake crash after acceptance")
395
+ return copy.deepcopy(message)
396
+
397
+ def send_photo(self, chat_id, data, *, caption=None, filename=None, mime=None,
398
+ thread_id=None, reply_to=None, parse_mode=None):
399
+ return self._send_media("photo", chat_id, data, caption, filename, mime, thread_id, reply_to, parse_mode)
400
+
401
+ def send_document(self, chat_id, data, *, caption=None, filename=None, mime=None,
402
+ thread_id=None, reply_to=None, parse_mode=None):
403
+ return self._send_media("document", chat_id, data, caption, filename, mime, thread_id, reply_to, parse_mode)
404
+
405
+ def _outcome(self, parse_mode):
406
+ if self.outcomes and self.outcomes[0] == "bad_entities":
407
+ if parse_mode is None:
408
+ return "sent"
409
+ self.outcomes.pop(0)
410
+ return TransportError(400, bad_entities=True)
411
+ return self.outcomes.pop(0) if self.outcomes else "sent"
412
+
413
+ def _send_media(self, kind, chat_id, data, caption, filename, mime, thread_id, reply_to, parse_mode=None):
414
+ with self._lock:
415
+ outcome = self._outcome(parse_mode)
416
+ if isinstance(outcome, BaseException):
417
+ raise outcome
418
+ if outcome == "reject":
419
+ raise TransportError(403)
420
+ if outcome == "rate_limit":
421
+ raise TransportError(429, 30)
422
+ message = {"message_id": len(self.sent)+1, "chat": {"id": chat_id}, "caption": caption,
423
+ "message_thread_id": thread_id, "reply_to_message_id": reply_to,
424
+ "media": {"kind": kind, "data": bytes(data), "filename": filename,
425
+ "mime": mime, "sha256": hashlib.sha256(bytes(data)).hexdigest()}}
426
+ if parse_mode is not None:
427
+ message["parse_mode"] = parse_mode
428
+ self.sent.append(message)
429
+ if outcome == "unknown":
430
+ raise UnknownSend()
431
+ if outcome == "crash":
432
+ raise SystemExit("fake crash after acceptance")
433
+ return copy.deepcopy(message)
434
+
435
+ def answer_callback_query(self, callback_query_id, text):
436
+ with self._lock:
437
+ self.callback_answers.append({"id": callback_query_id, "text": text})
438
+ return True
439
+
440
+ def edit_message_text(self, chat_id, message_id, text, parse_mode=None, reply_markup=None):
441
+ with self._lock:
442
+ outcome = self._outcome(parse_mode) if self.outcomes and self.outcomes[0] == "bad_entities" else None
443
+ if isinstance(outcome, BaseException):
444
+ raise outcome
445
+ edit = {"chat_id": chat_id, "message_id": message_id, "text": text}
446
+ if parse_mode is not None:
447
+ edit["parse_mode"] = parse_mode
448
+ if reply_markup is not None:
449
+ edit["reply_markup"] = copy.deepcopy(reply_markup)
450
+ self.edits.append(edit)
451
+ return {"message_id": message_id, "chat": {"id": chat_id}, "text": text}
452
+
453
+ def delete_message(self, chat_id, message_id):
454
+ with self._lock:
455
+ self.deleted.append({"chat_id": chat_id, "message_id": message_id})
456
+ return True
457
+
458
+ def set_my_commands(self, commands, scope):
459
+ with self._lock:
460
+ self.menus.append({"commands": copy.deepcopy(commands), "scope": scope})
461
+ return True
462
+
463
+ def send_widget(self, chat_id, html, *, chat_data=None, allow_queries=False):
464
+ with self._lock:
465
+ outcome = self.outcomes.pop(0) if self.outcomes else "sent"
466
+ if outcome == "reject":
467
+ raise TransportError(403)
468
+ if outcome == "widget_refused":
469
+ # Telegram's INPUT_MEDIA_WIDGET_NOT_ALLOWED for bots it doesn't let send widgets.
470
+ raise TransportError(400)
471
+ message = {"message_id": len(self.sent) + 1, "chat": {"id": chat_id},
472
+ "widget": {"html": html, "chat_data": chat_data, "allow_queries": allow_queries}}
473
+ self.sent.append(message)
474
+ self.widgets.append(message)
475
+ if outcome == "unknown":
476
+ raise UnknownSend()
477
+ return copy.deepcopy(message)
478
+
479
+ def answer_widget_query(self, widget_query_id, data):
480
+ with self._lock:
481
+ self.widget_answers.append({"id": widget_query_id, "data": data})
482
+ return True
483
+
484
+ def edit_message_widget_data(self, chat_id, message_id, chat_data):
485
+ with self._lock:
486
+ self.widget_edits.append({"chat_id": chat_id, "message_id": message_id, "chat_data": chat_data})
487
+
488
+ def edit_ephemeral_message_text(self, chat_id, receiver_user_id, ephemeral_message_id, text):
489
+ with self._lock:
490
+ self.edits.append({"chat_id": chat_id, "receiver_user_id": receiver_user_id,
491
+ "ephemeral_message_id": ephemeral_message_id, "text": text})
492
+ return True
493
+
494
+ def set_message_reaction(self, chat_id, message_id, emoji):
495
+ with self._lock:
496
+ outcome = self.outcomes.pop(0) if self.outcomes else "sent"
497
+ if isinstance(outcome, BaseException):
498
+ raise outcome
499
+ if outcome == "reject":
500
+ raise TransportError(403)
501
+ if outcome == "rate_limit":
502
+ raise TransportError(429, 30)
503
+ self.reactions.append({"chat_id": chat_id, "message_id": message_id, "emoji": emoji})
504
+ if outcome == "unknown":
505
+ raise UnknownSend()
506
+ if outcome == "crash":
507
+ raise SystemExit("fake crash after acceptance")
508
+ return True
509
+
510
+ def forward_message(self, chat_id, from_chat_id, message_id):
511
+ with self._lock:
512
+ outcome = self.outcomes.pop(0) if self.outcomes else "sent"
513
+ if isinstance(outcome, BaseException):
514
+ raise outcome
515
+ if outcome == "reject":
516
+ raise TransportError(403)
517
+ if outcome == "not_found":
518
+ raise TransportError(400)
519
+ if outcome == "rate_limit":
520
+ raise TransportError(429, 30)
521
+ message = {"message_id": len(self.sent)+1, "chat": {"id": chat_id},
522
+ "forwarded_from": {"chat_id": from_chat_id, "message_id": message_id}}
523
+ self.sent.append(message)
524
+ self.forwards.append({"chat_id": chat_id, "from_chat_id": from_chat_id, "message_id": message_id})
525
+ if outcome == "unknown":
526
+ raise UnknownSend()
527
+ if outcome == "crash":
528
+ raise SystemExit("fake crash after acceptance")
529
+ return copy.deepcopy(message)
530
+
531
+ def get_chat_member(self, chat_id, user_id):
532
+ with self._lock:
533
+ return _fake_chat_member(self.chat_members, chat_id, user_id)
534
+
535
+ def download_file(self, file_id, max_bytes):
536
+ with self._lock:
537
+ return _fake_file(self.files, file_id, max_bytes)
538
+
539
+
540
+ class FileFakeTransport:
541
+ """Explicit offline mode shared by independent test MCP subprocesses."""
542
+ def __init__(self, path):
543
+ self.path = Path(path)
544
+ private_directory(self.path.parent)
545
+
546
+ @contextmanager
547
+ def _data(self):
548
+ fd = os.open(str(self.path) + ".lock", os.O_CREAT | os.O_RDWR | compat.O_NOFOLLOW | compat.O_BINARY, 0o600)
549
+ try:
550
+ compat.lock(fd, blocking=True)
551
+ data = read_private_json(self.path) if self.path.exists() else {
552
+ "bot_id": 900001, "username": "aot_test_bot", "updates": [], "sent": [], "reactions": [], "outcomes": [], "poll_offsets": []}
553
+ data.setdefault("reactions", [])
554
+ yield data
555
+ write_private_json(self.path, data, overwrite=self.path.exists())
556
+ finally:
557
+ os.close(fd)
558
+
559
+ def get_me(self):
560
+ with self._data() as data:
561
+ return {"id": data["bot_id"], "username": data["username"], "is_bot": True}
562
+
563
+ def get_webhook_info(self):
564
+ with self._data() as data:
565
+ return {"url": data.get("webhook", "")}
566
+
567
+ def get_updates(self, offset, timeout=0):
568
+ with self._data() as data:
569
+ data["poll_offsets"].append(offset)
570
+ return sorted([u for u in data["updates"] if u["update_id"] >= offset], key=lambda x:x["update_id"])[:100]
571
+
572
+ def send_message(self, chat_id, text, thread_id=None, reply_to=None, reply_markup=None, ephemeral_to=None,
573
+ parse_mode=None):
574
+ with self._data() as data:
575
+ outcome = data["outcomes"].pop(0) if data["outcomes"] else "sent"
576
+ result = {"message_id": len(data["sent"])+1, "chat": {"id": chat_id}, "text": text,
577
+ "message_thread_id": thread_id, "reply_to_message_id": reply_to}
578
+ if parse_mode is not None:
579
+ result["parse_mode"] = parse_mode
580
+ if reply_markup is not None:
581
+ result["reply_markup"] = reply_markup
582
+ if ephemeral_to is not None:
583
+ result.update(message_id=0, ephemeral_message_id=len(data["sent"])+1, receiver_user={"id": ephemeral_to})
584
+ if outcome not in ("reject", "rate_limit"):
585
+ data["sent"].append(result)
586
+ if outcome == "reject":
587
+ raise TransportError(403)
588
+ if outcome == "rate_limit":
589
+ raise TransportError(429, 30)
590
+ if outcome == "unknown":
591
+ raise UnknownSend()
592
+ if outcome == "crash":
593
+ raise SystemExit("fake crash after acceptance")
594
+ return result
595
+
596
+ def send_photo(self, chat_id, data, *, caption=None, filename=None, mime=None,
597
+ thread_id=None, reply_to=None, parse_mode=None):
598
+ return self._send_media("photo", chat_id, data, caption, filename, mime, thread_id, reply_to)
599
+
600
+ def send_document(self, chat_id, data, *, caption=None, filename=None, mime=None,
601
+ thread_id=None, reply_to=None, parse_mode=None):
602
+ return self._send_media("document", chat_id, data, caption, filename, mime, thread_id, reply_to)
603
+
604
+ def _send_media(self, kind, chat_id, data, caption, filename, mime, thread_id, reply_to):
605
+ payload = bytes(data)
606
+ with self._data() as stored:
607
+ outcome = stored["outcomes"].pop(0) if stored["outcomes"] else "sent"
608
+ result = {"message_id": len(stored["sent"])+1, "chat": {"id": chat_id}, "caption": caption,
609
+ "message_thread_id": thread_id, "reply_to_message_id": reply_to,
610
+ "media": {"kind": kind, "sha256": hashlib.sha256(payload).hexdigest(),
611
+ "size": len(payload), "filename": filename, "mime": mime}}
612
+ if outcome not in ("reject", "rate_limit"):
613
+ stored["sent"].append(result)
614
+ if outcome == "reject":
615
+ raise TransportError(403)
616
+ if outcome == "rate_limit":
617
+ raise TransportError(429, 30)
618
+ if outcome == "unknown":
619
+ raise UnknownSend()
620
+ if outcome == "crash":
621
+ raise SystemExit("fake crash after acceptance")
622
+ return result
623
+
624
+ def answer_callback_query(self, callback_query_id, text):
625
+ with self._data() as data:
626
+ data.setdefault("callback_answers", []).append({"id": callback_query_id, "text": text})
627
+ return True
628
+
629
+ def edit_message_text(self, chat_id, message_id, text, parse_mode=None, reply_markup=None):
630
+ with self._data() as data:
631
+ edit = {"chat_id": chat_id, "message_id": message_id, "text": text}
632
+ if reply_markup is not None:
633
+ edit["reply_markup"] = reply_markup
634
+ data.setdefault("edits", []).append(edit)
635
+ return {"message_id": message_id, "chat": {"id": chat_id}, "text": text}
636
+
637
+ def delete_message(self, chat_id, message_id):
638
+ with self._data() as data:
639
+ data.setdefault("deleted", []).append({"chat_id": chat_id, "message_id": message_id})
640
+ return True
641
+
642
+ def set_my_commands(self, commands, scope):
643
+ with self._data() as data:
644
+ data.setdefault("menus", []).append({"commands": commands, "scope": scope})
645
+ return True
646
+
647
+ def send_widget(self, chat_id, html, *, chat_data=None, allow_queries=False):
648
+ with self._data() as data:
649
+ outcome = data["outcomes"].pop(0) if data["outcomes"] else "sent"
650
+ result = {"message_id": len(data["sent"]) + 1, "chat": {"id": chat_id},
651
+ "widget": {"html": html, "chat_data": chat_data, "allow_queries": allow_queries}}
652
+ if outcome not in ("reject", "widget_refused"):
653
+ data["sent"].append(result)
654
+ if outcome == "reject":
655
+ raise TransportError(403)
656
+ if outcome == "widget_refused":
657
+ raise TransportError(400)
658
+ if outcome == "unknown":
659
+ raise UnknownSend()
660
+ return result
661
+
662
+ def answer_widget_query(self, widget_query_id, data):
663
+ with self._data() as stored:
664
+ stored.setdefault("widget_answers", []).append({"id": widget_query_id, "data": data})
665
+ return True
666
+
667
+ def edit_message_widget_data(self, chat_id, message_id, chat_data):
668
+ with self._data() as stored:
669
+ stored.setdefault("widget_edits", []).append(
670
+ {"chat_id": chat_id, "message_id": message_id, "chat_data": chat_data})
671
+
672
+ def edit_ephemeral_message_text(self, chat_id, receiver_user_id, ephemeral_message_id, text):
673
+ with self._data() as data:
674
+ data.setdefault("edits", []).append({"chat_id": chat_id, "receiver_user_id": receiver_user_id,
675
+ "ephemeral_message_id": ephemeral_message_id, "text": text})
676
+ return True
677
+
678
+ def set_message_reaction(self, chat_id, message_id, emoji):
679
+ with self._data() as data:
680
+ outcome = data["outcomes"].pop(0) if data["outcomes"] else "sent"
681
+ if outcome not in ("reject", "rate_limit"):
682
+ data["reactions"].append({"chat_id": chat_id, "message_id": message_id, "emoji": emoji})
683
+ if outcome == "reject":
684
+ raise TransportError(403)
685
+ if outcome == "rate_limit":
686
+ raise TransportError(429, 30)
687
+ if outcome == "unknown":
688
+ raise UnknownSend()
689
+ if outcome == "crash":
690
+ raise SystemExit("fake crash after acceptance")
691
+ return True
692
+
693
+ def forward_message(self, chat_id, from_chat_id, message_id):
694
+ with self._data() as data:
695
+ outcome = data["outcomes"].pop(0) if data["outcomes"] else "sent"
696
+ result = {"message_id": len(data["sent"])+1, "chat": {"id": chat_id},
697
+ "forwarded_from": {"chat_id": from_chat_id, "message_id": message_id}}
698
+ if outcome not in ("reject", "rate_limit"):
699
+ data["sent"].append(result)
700
+ if outcome == "reject":
701
+ raise TransportError(403)
702
+ if outcome == "rate_limit":
703
+ raise TransportError(429, 30)
704
+ if outcome == "unknown":
705
+ raise UnknownSend()
706
+ if outcome == "crash":
707
+ raise SystemExit("fake crash after acceptance")
708
+ return result
709
+
710
+ def get_chat_member(self, chat_id, user_id):
711
+ with self._data() as data:
712
+ return _fake_chat_member(data.get("chat_members", {}), chat_id, user_id)
713
+
714
+ def download_file(self, file_id, max_bytes):
715
+ with self._data() as data:
716
+ return _fake_file(data.get("files", {}), file_id, max_bytes)
717
+
718
+
719
+ def make_transport(state_dir, *, fake=False):
720
+ return FileFakeTransport(Path(state_dir) / "fake-transport.json") if fake else TelegramTransport(load_token(state_dir))