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,230 @@
1
+ """Optional model-judged wake decision for addressed-only delivery.
2
+
3
+ With ``--filter addressed``, the rules (a mention, a reply to the bot, a
4
+ command, a person's quick follow-up) keep every other message as context. When
5
+ the owner configures a decision model and turns ``--model-judge on`` for a
6
+ connection, AOT asks that model whether such a message is meant for this
7
+ agent. A "yes" turns the context entry into a delivery; anything else,
8
+ including an error or a timeout, keeps it as context.
9
+
10
+ The model is any endpoint that speaks TypeSafe's System One decision API:
11
+ Jev, Cloudflare's Clef and Clef-flash on Workers AI, or a self-hosted Clef. The
12
+ request is one ``choice`` question with the options ``yes`` and ``no``; the
13
+ answer is a probability per option, not generated text.
14
+
15
+ The endpoint, the model and the optional key live only in a protected file in
16
+ the state directory, like the bot token. They never enter MCP arguments, tool
17
+ results or diagnostics.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import ipaddress
22
+ import json
23
+ import urllib.error
24
+ import urllib.parse
25
+ import urllib.request
26
+ from pathlib import Path
27
+
28
+ from .credentials import CredentialError, read_private_json, write_private_json
29
+ from .net import RacingHTTPSHandler
30
+
31
+ JUDGE_FILE = 'judge.json'
32
+ TIMEOUT_SECONDS = 8.0
33
+ TEXT_LIMIT = 600 # characters kept from each message sent to the model
34
+ RESPONSE_LIMIT = 1_000_000 # bytes read from a response
35
+ DEFAULT_THRESHOLD = 0.5
36
+ QUESTION = 'addressed'
37
+
38
+ INSTRUCTIONS = (
39
+ "This is a Telegram group where people talk with each other and with AI agents. All agents "
40
+ "post through shared bots, and each agent's message starts with a label such as "
41
+ "\"[Agent: Name | shared bot @bot]\". A person usually reaches an agent by mentioning its "
42
+ "bot or replying to it, but sometimes answers it without doing either, for example after a "
43
+ "pause. Is the new message meant for the agent named in the state: does it answer or continue "
44
+ "something that agent said or asked, or ask that agent to do something?"
45
+ )
46
+ CRITERIA = {
47
+ 'yes': 'The new message is meant for this agent.',
48
+ 'no': 'The new message is meant for someone else, is general chat, or it is unclear.',
49
+ }
50
+
51
+
52
+ class JudgeUnavailable(Exception):
53
+ """The judge gave no usable answer; the message stays context."""
54
+
55
+ def __init__(self, code):
56
+ self.code = code
57
+ super().__init__(code)
58
+
59
+
60
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
61
+ # A redirect could carry the key to another host; never follow one.
62
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
63
+ return None
64
+
65
+
66
+ def _loopback(host):
67
+ if host == 'localhost':
68
+ return True
69
+ try:
70
+ return ipaddress.ip_address(host).is_loopback
71
+ except ValueError:
72
+ return False
73
+
74
+
75
+ def check_endpoint(endpoint):
76
+ """An https URL, or plain http only to this computer (a self-hosted model)."""
77
+ if not isinstance(endpoint, str) or not 0 < len(endpoint) <= 2048 or any(c.isspace() for c in endpoint):
78
+ raise CredentialError('invalid_judge_endpoint')
79
+ parts = urllib.parse.urlsplit(endpoint)
80
+ if parts.username or parts.password or parts.fragment or not parts.hostname:
81
+ raise CredentialError('invalid_judge_endpoint')
82
+ if parts.scheme != 'https' and not (parts.scheme == 'http' and _loopback(parts.hostname)):
83
+ raise CredentialError('judge_endpoint_needs_https')
84
+ return endpoint
85
+
86
+
87
+ def check_model(model):
88
+ if not isinstance(model, str) or not 0 < len(model.strip()) <= 128 or any(c.isspace() for c in model.strip()):
89
+ raise CredentialError('invalid_judge_model')
90
+ return model.strip()
91
+
92
+
93
+ def check_threshold(threshold):
94
+ if isinstance(threshold, bool) or not isinstance(threshold, (int, float)) or not 0.5 <= threshold < 1:
95
+ raise CredentialError('invalid_judge_threshold')
96
+ return float(threshold)
97
+
98
+
99
+ def judge_path(state_dir):
100
+ return Path(state_dir) / JUDGE_FILE
101
+
102
+
103
+ def store_config(state_dir, endpoint, model, api_key='', threshold=DEFAULT_THRESHOLD):
104
+ """Write the judge configuration to the protected file, replacing an earlier one."""
105
+ api_key = api_key.strip() if isinstance(api_key, str) else ''
106
+ if len(api_key) > 4096 or any(c.isspace() for c in api_key):
107
+ raise CredentialError('invalid_judge_key')
108
+ write_private_json(judge_path(state_dir), {
109
+ 'endpoint': check_endpoint(endpoint), 'model': check_model(model),
110
+ 'api_key': api_key, 'threshold': check_threshold(threshold)}, overwrite=True)
111
+
112
+
113
+ def clear_config(state_dir):
114
+ path = judge_path(state_dir)
115
+ if path.exists() or path.is_symlink():
116
+ read_private_json(path) # refuse to delete a file this user does not own privately
117
+ path.unlink()
118
+ return True
119
+ return False
120
+
121
+
122
+ def config_status(state_dir):
123
+ """What is configured; never the key itself."""
124
+ path = judge_path(state_dir)
125
+ if not path.exists():
126
+ return {'configured': False}
127
+ try:
128
+ judge = _from_file(path)
129
+ except CredentialError as error:
130
+ return {'configured': False, 'error': error.code}
131
+ return {'configured': True, 'endpoint': judge.endpoint, 'model': judge.model,
132
+ 'key': bool(judge._api_key), 'threshold': judge.threshold}
133
+
134
+
135
+ def _from_file(path):
136
+ value = read_private_json(path)
137
+ api_key = value.get('api_key', '')
138
+ if not isinstance(api_key, str):
139
+ raise CredentialError('invalid_judge_key')
140
+ return DecisionJudge(check_endpoint(value.get('endpoint')), check_model(value.get('model')),
141
+ api_key, check_threshold(value.get('threshold', DEFAULT_THRESHOLD)))
142
+
143
+
144
+ def load(state_dir):
145
+ """The judge for this state directory, or None when none is usable."""
146
+ path = judge_path(state_dir)
147
+ if not path.exists():
148
+ return None
149
+ try:
150
+ return _from_file(path)
151
+ except CredentialError:
152
+ return None
153
+
154
+
155
+ def render(agent_label, bot_username, history, candidate):
156
+ """The state: the agent, recent messages oldest first, then the message to judge."""
157
+ def line(entry):
158
+ who = entry.get('sender') or 'unknown'
159
+ text = ' '.join(str(entry.get('text') or '').split())[:TEXT_LIMIT]
160
+ return f'- {who}: {text}'
161
+
162
+ recent = '\n'.join(line(entry) for entry in history) or '(no earlier messages)'
163
+ return (f'Agent: "{agent_label}", posting through @{bot_username}.\n\n'
164
+ f'Recent messages, oldest first:\n{recent}\n\n'
165
+ f'New message:\n{line(candidate)}')
166
+
167
+
168
+ class DecisionJudge:
169
+ """One yes/no choice question to a System One decision endpoint."""
170
+
171
+ def __init__(self, endpoint, model, api_key='', threshold=DEFAULT_THRESHOLD, *, opener=None):
172
+ self.endpoint, self.model, self.threshold = endpoint, model, threshold
173
+ self._api_key = api_key
174
+ # No proxies from the environment and no redirects, like the Telegram transport.
175
+ self._opener = opener or urllib.request.build_opener(
176
+ _NoRedirect(), urllib.request.ProxyHandler({}), RacingHTTPSHandler())
177
+
178
+ def __repr__(self): # never print the key
179
+ return f'DecisionJudge(endpoint={self.endpoint!r}, model={self.model!r})'
180
+
181
+ def request_body(self, *, agent_label, bot_username, history, candidate):
182
+ return {'model': self.model,
183
+ 'state': render(agent_label, bot_username, history, candidate),
184
+ 'questions': {QUESTION: {'type': 'choice', 'instructions': INSTRUCTIONS, 'criteria': CRITERIA}}}
185
+
186
+ def __call__(self, **context):
187
+ headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
188
+ if self._api_key:
189
+ headers['Authorization'] = 'Bearer ' + self._api_key
190
+ request = urllib.request.Request(self.endpoint, data=json.dumps(self.request_body(**context)).encode(),
191
+ headers=headers, method='POST')
192
+ try:
193
+ with self._opener.open(request, timeout=TIMEOUT_SECONDS) as response:
194
+ raw = response.read(RESPONSE_LIMIT + 1)
195
+ except urllib.error.HTTPError as error:
196
+ code = error.code
197
+ if code in (401, 403):
198
+ raise JudgeUnavailable('judge_key_rejected') from None
199
+ if code == 429:
200
+ raise JudgeUnavailable('judge_rate_limited') from None
201
+ if 300 <= code < 400:
202
+ raise JudgeUnavailable('judge_redirect_refused') from None
203
+ if 400 <= code < 500:
204
+ raise JudgeUnavailable('judge_request_rejected') from None
205
+ raise JudgeUnavailable('judge_api_error') from None
206
+ except (urllib.error.URLError, OSError): # includes timeouts and refused connections
207
+ raise JudgeUnavailable('judge_unreachable') from None
208
+ return self._decide(raw)
209
+
210
+ def _decide(self, raw):
211
+ if len(raw) > RESPONSE_LIMIT:
212
+ raise JudgeUnavailable('judge_no_answer')
213
+ try:
214
+ body = json.loads(raw)
215
+ except (ValueError, UnicodeError):
216
+ raise JudgeUnavailable('judge_no_answer') from None
217
+ # Cloudflare's REST API may wrap the model's answer in its envelope.
218
+ if isinstance(body, dict) and 'answers' not in body and isinstance(body.get('result'), dict):
219
+ body = body['result']
220
+ answer = body.get('answers', {}).get(QUESTION) if isinstance(body, dict) and isinstance(body.get('answers'), dict) else None
221
+ if not isinstance(answer, dict):
222
+ raise JudgeUnavailable('judge_no_answer')
223
+ probabilities = answer.get('probabilities')
224
+ if isinstance(probabilities, dict):
225
+ yes = probabilities.get('yes')
226
+ if isinstance(yes, (int, float)) and not isinstance(yes, bool) and 0 <= yes <= 1:
227
+ return yes >= self.threshold
228
+ if answer.get('choice') in CRITERIA and self.threshold == DEFAULT_THRESHOLD:
229
+ return answer['choice'] == 'yes'
230
+ raise JudgeUnavailable('judge_no_answer')
@@ -0,0 +1,133 @@
1
+ """Read-only Darwin process inspection; never expose raw process environments.
2
+
3
+ The ABI constants/layout below are from the macOS SDK's libproc.h,
4
+ sys/proc_info.h and sys/sysctl.h. Libraries are loaded only on Darwin.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import ctypes
9
+ import os
10
+ from pathlib import Path
11
+ import struct
12
+
13
+
14
+ class _BSDInfo(ctypes.Structure):
15
+ _fields_ = [(name, ctypes.c_uint32) for name in (
16
+ 'flags', 'status', 'xstatus', 'pid', 'ppid', 'uid', 'gid', 'ruid',
17
+ 'rgid', 'svuid', 'svgid', 'reserved')]
18
+ _fields_ += [('comm', ctypes.c_char * 16), ('name', ctypes.c_char * 32)]
19
+ _fields_ += [(name, ctypes.c_uint32) for name in (
20
+ 'nfiles', 'pgid', 'jobc', 'tdev', 'tpgid')]
21
+ _fields_ += [('nice', ctypes.c_int32), ('start_sec', ctypes.c_uint64),
22
+ ('start_usec', ctypes.c_uint64)]
23
+
24
+
25
+ ROUTING_KEYS = {b'HOME', b'CODEX_HOME', b'CODEX_CLI_PATH',
26
+ b'CODEX_APP_SERVER_WS_URL', b'CODEX_APP_SERVER_USE_LOCAL_DAEMON'}
27
+
28
+
29
+ def parse_procargs(raw):
30
+ """KERN_PROCARGS2: native argc, executable, padding, argv, environment.
31
+
32
+ Return argv and only routing fields. Other environment values are discarded
33
+ without decoding, logging or copying them into the returned metadata.
34
+ """
35
+ if len(raw) < 5:
36
+ raise ValueError('invalid_process_arguments')
37
+ argc = struct.unpack_from('=i', raw)[0]
38
+ if not 1 <= argc <= 65536:
39
+ raise ValueError('invalid_process_arguments')
40
+ offset = raw.index(b'\0', 4) + 1
41
+ while offset < len(raw) and raw[offset] == 0:
42
+ offset += 1
43
+ args = []
44
+ for _ in range(argc):
45
+ end = raw.index(b'\0', offset)
46
+ args.append(raw[offset:end])
47
+ offset = end + 1
48
+ routing = []
49
+ for pair in raw[offset:].split(b'\0'):
50
+ key, sep, _ = pair.partition(b'=')
51
+ if sep and key in ROUTING_KEYS:
52
+ # Ambiguous routing must fail closed, rather than depend on order.
53
+ if any(value.startswith(key + b'=') for value in routing):
54
+ raise ValueError('invalid_process_arguments')
55
+ routing.append(pair)
56
+ return args, b'\0'.join(routing)
57
+
58
+
59
+ class MacOSProcesses:
60
+ def __init__(self):
61
+ self.proc = ctypes.CDLL('/usr/lib/libproc.dylib', use_errno=True)
62
+ self.libc = ctypes.CDLL('/usr/lib/libSystem.B.dylib', use_errno=True)
63
+ self.proc.proc_listpids.argtypes = [ctypes.c_uint32, ctypes.c_uint32,
64
+ ctypes.c_void_p, ctypes.c_int]
65
+ self.proc.proc_listpids.restype = ctypes.c_int
66
+ self.proc.proc_pidinfo.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_uint64,
67
+ ctypes.c_void_p, ctypes.c_int]
68
+ self.proc.proc_pidinfo.restype = ctypes.c_int
69
+ self.proc.proc_pidpath.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32]
70
+ self.proc.proc_pidpath.restype = ctypes.c_int
71
+ self.libc.sysctl.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.c_uint,
72
+ ctypes.c_void_p, ctypes.POINTER(ctypes.c_size_t),
73
+ ctypes.c_void_p, ctypes.c_size_t]
74
+ self.libc.sysctl.restype = ctypes.c_int
75
+
76
+ def _sysctl(self, *mib, limit=4 * 1024 * 1024):
77
+ keys = (ctypes.c_int * len(mib))(*mib)
78
+ size = ctypes.c_size_t()
79
+ if self.libc.sysctl(keys, len(mib), None, ctypes.byref(size), None, 0):
80
+ raise OSError('process_inspection_unavailable')
81
+ if not 0 < size.value <= limit:
82
+ raise ValueError('invalid_process_metadata')
83
+ buffer = ctypes.create_string_buffer(size.value)
84
+ if self.libc.sysctl(keys, len(mib), buffer, ctypes.byref(size), None, 0):
85
+ raise OSError('process_inspection_unavailable')
86
+ return buffer.raw[:size.value]
87
+
88
+ def _info(self, pid):
89
+ info = _BSDInfo()
90
+ if self.proc.proc_pidinfo(pid, 3, 0, ctypes.byref(info), ctypes.sizeof(info)) != ctypes.sizeof(info):
91
+ raise OSError('process_inspection_unavailable')
92
+ if info.pid != pid or info.uid != os.getuid() or info.ruid != os.getuid():
93
+ raise ValueError('process_owner_mismatch')
94
+ return pid, info.ppid, (info.start_sec, info.start_usec)
95
+
96
+ def _path(self, pid):
97
+ path = ctypes.create_string_buffer(4096)
98
+ if self.proc.proc_pidpath(pid, path, len(path)) <= 0:
99
+ raise OSError('process_inspection_unavailable')
100
+ return Path(os.fsdecode(path.value)).resolve()
101
+
102
+ def group_is_empty(self, pgid):
103
+ # Darwin killpg can report EPERM for a group with no remaining PIDs.
104
+ # A zero result is evidence only if libproc itself reports no error.
105
+ if not isinstance(pgid, int) or pgid <= 1:
106
+ return False
107
+ pids = (ctypes.c_int * 1024)()
108
+ ctypes.set_errno(0)
109
+ count = self.proc.proc_listpids(2, pgid, pids, ctypes.sizeof(pids))
110
+ return count == 0 and ctypes.get_errno() == 0
111
+
112
+ def candidates(self, executables):
113
+ needed = self.proc.proc_listpids(1, 0, None, 0)
114
+ if needed <= 0 or needed > 4 * 1024 * 1024:
115
+ raise OSError('process_inspection_unavailable')
116
+ pids = (ctypes.c_int * (needed // ctypes.sizeof(ctypes.c_int) + 1024))()
117
+ count = self.proc.proc_listpids(1, 0, pids, ctypes.sizeof(pids))
118
+ if count <= 0 or count >= ctypes.sizeof(pids):
119
+ raise OSError('process_inventory_incomplete')
120
+ for pid in pids[:count // ctypes.sizeof(ctypes.c_int)]:
121
+ if pid <= 0:
122
+ continue
123
+ try:
124
+ before = self._info(pid)
125
+ executable = self._path(pid)
126
+ if executable not in executables:
127
+ continue
128
+ # Only inspect arguments/environment of the selected app and CLI.
129
+ args, routing = parse_procargs(self._sysctl(1, 49, pid))
130
+ if self._info(pid) == before and self._path(pid) == executable:
131
+ yield (*before, executable, args, routing)
132
+ except (OSError, ValueError, UnicodeError, RuntimeError):
133
+ continue
@@ -0,0 +1,127 @@
1
+ """A safe Markdown subset for Telegram, in both directions.
2
+
3
+ Agents write Markdown. Telegram shows it literally unless the message is
4
+ sent with a parse mode. ``agent_html`` turns the text an agent wrote into
5
+ Telegram HTML. It escapes everything, then adds tags only for a small subset:
6
+ inline code, fenced code blocks, bold, italic, strikethrough, http(s) links,
7
+ headings (as bold) and bullets. Anything else stays as written.
8
+
9
+ ``entities_markdown`` goes the other way for incoming messages. It turns
10
+ code, pre and text_link entities back into Markdown, so an agent still sees
11
+ code spans and link targets that Telegram removed from the text.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import html
17
+ import re
18
+
19
+ # Agent text always starts with this label line. It stays plain, so a label
20
+ # or a group title can never become formatting.
21
+ _HEADER = re.compile(r'\[Agent: [^\n]*\]')
22
+ _FENCE = re.compile(r'^```([A-Za-z0-9_+-]{0,32})[ \t]*\n(.*?)\n?^```[ \t]*$', re.MULTILINE | re.DOTALL)
23
+ _CODE = re.compile(r'`([^`\n]+)`')
24
+ _LINK = re.compile(r'\[([^\[\]\n]+)\]\((https?://[^\s()<>]+)\)')
25
+ # Only ** makes bold: __name__ is far more often a Python name than emphasis.
26
+ _BOLD = re.compile(r'(?<![\w*])\*\*(?=\S)(.+?)(?<=\S)\*\*(?![\w*])')
27
+ _ITALIC = re.compile(r'(?<![\w*])\*(?=[^\s*])([^*\n]+?)(?<=[^\s*])\*(?![\w*])'
28
+ r'|(?<![\w_])_(?=[^\s_])([^_\n]+?)(?<=[^\s_])_(?![\w_])')
29
+ _STRIKE = re.compile(r'(?<!~)~~(?=\S)([^~\n]+?)(?<=\S)~~(?!~)')
30
+ _HEADING = re.compile(r'^#{1,6}[ \t]+(.+?)[ \t#]*$', re.MULTILINE)
31
+ _BULLET = re.compile(r'^([ \t]*)[-*+][ \t]+', re.MULTILINE)
32
+ # Placeholders for finished pieces; NUL never survives into Telegram text.
33
+ _SLOT = re.compile('\x00(\\d+)\x00')
34
+
35
+
36
+ def agent_html(text):
37
+ """Telegram HTML for agent text that starts with its label line, or None.
38
+
39
+ None means: send the text as it is. Only agent text carries the label
40
+ line, so AOT's own notices are never reformatted.
41
+ """
42
+ if not isinstance(text, str):
43
+ return None
44
+ header, newline, body = text.partition('\n')
45
+ if not _HEADER.fullmatch(header):
46
+ return None
47
+ rendered = to_html(body)
48
+ if rendered == html.escape(body, quote=False):
49
+ return None # Nothing to format; plain text is the safer send.
50
+ return html.escape(header, quote=False) + newline + rendered
51
+
52
+
53
+ def to_html(text):
54
+ """Telegram HTML for one piece of Markdown; every other character is escaped."""
55
+ pieces = []
56
+
57
+ def keep(markup):
58
+ pieces.append(markup)
59
+ return f'\x00{len(pieces) - 1}\x00'
60
+
61
+ def fence(match):
62
+ language, code = match.group(1), html.escape(match.group(2), quote=False)
63
+ if language:
64
+ return keep(f'<pre><code class="language-{language}">{code}</code></pre>')
65
+ return keep(f'<pre>{code}</pre>')
66
+
67
+ text = text.replace('\x00', '')
68
+ text = _FENCE.sub(fence, text)
69
+ text = _CODE.sub(lambda m: keep(f'<code>{html.escape(m.group(1), quote=False)}</code>'), text)
70
+ text = _LINK.sub(lambda m: keep(f'<a href="{html.escape(m.group(2))}">{_inline(m.group(1))}</a>'), text)
71
+ text = _HEADING.sub(lambda m: keep(f'<b>{_inline(m.group(1))}</b>'), text)
72
+ text = _BULLET.sub(lambda m: m.group(1) + '• ', text)
73
+ text = _inline(text)
74
+ # A heading or link can hold a code span, so resolve until none are left.
75
+ while _SLOT.search(text):
76
+ text = _SLOT.sub(lambda m: pieces[int(m.group(1))], text)
77
+ return text
78
+
79
+
80
+ def _inline(text):
81
+ """Escape text and add bold, italic and strikethrough; placeholders pass through."""
82
+ text = html.escape(text, quote=False)
83
+ text = _BOLD.sub(lambda m: f'<b>{m.group(1)}</b>', text)
84
+ text = _ITALIC.sub(lambda m: f'<i>{m.group(1) or m.group(2)}</i>', text)
85
+ return _STRIKE.sub(lambda m: f'<s>{m.group(1)}</s>', text)
86
+
87
+
88
+ def entities_markdown(text, entities):
89
+ """Text with code, pre and text_link entities written back as Markdown.
90
+
91
+ Other entities (bold, mentions, plain URLs) keep their text as it is.
92
+ Offsets are in UTF-16 code units, as Telegram counts them. Overlapping
93
+ or malformed entities leave the text unchanged.
94
+ """
95
+ if not isinstance(text, str) or not isinstance(entities, list) or not entities:
96
+ return text
97
+ units = text.encode('utf-16-le')
98
+ spans = []
99
+ for entity in entities:
100
+ if not isinstance(entity, dict) or entity.get('type') not in ('code', 'pre', 'text_link'):
101
+ continue
102
+ offset, length = entity.get('offset'), entity.get('length')
103
+ if type(offset) is not int or type(length) is not int or offset < 0 or length <= 0:
104
+ return text
105
+ if (offset + length) * 2 > len(units):
106
+ return text
107
+ spans.append((offset, offset + length, entity))
108
+ spans.sort(key=lambda span: span[0])
109
+ if any(a[1] > b[0] for a, b in zip(spans, spans[1:])):
110
+ return text
111
+ out, at = [], 0
112
+ for start, end, entity in spans:
113
+ out.append(units[at * 2:start * 2].decode('utf-16-le', 'replace'))
114
+ inner = units[start * 2:end * 2].decode('utf-16-le', 'replace')
115
+ kind = entity['type']
116
+ if kind == 'code':
117
+ out.append(f'`{inner}`')
118
+ elif kind == 'pre':
119
+ language = entity.get('language') if isinstance(entity.get('language'), str) else ''
120
+ language = language if re.fullmatch(r'[A-Za-z0-9_+-]{0,32}', language) else ''
121
+ out.append(f'```{language}\n{inner}\n```')
122
+ else:
123
+ url = entity.get('url')
124
+ out.append(f'[{inner}]({url})' if isinstance(url, str) and not re.search(r'\s', url) else inner)
125
+ at = end
126
+ out.append(units[at * 2:].decode('utf-16-le', 'replace'))
127
+ return ''.join(out)