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.
- package/LICENSE +202 -0
- package/README.md +141 -0
- package/docs/BOT_EXCHANGES.md +121 -0
- package/docs/COMPATIBILITY.md +110 -0
- package/docs/DIRECT_DISPATCH.md +155 -0
- package/docs/HOSTS.md +244 -0
- package/docs/IMPLEMENTATION_STATUS.md +205 -0
- package/docs/LIVE_VALIDATION.md +35 -0
- package/docs/MACOS_SERVICE.md +89 -0
- package/docs/OPERATIONS.md +568 -0
- package/docs/REACTIONS.md +51 -0
- package/docs/RELAY.md +115 -0
- package/docs/RELEASING.md +45 -0
- package/docs/schemas/mcp.schema.json +120 -0
- package/docs/schemas/sources.json +9 -0
- package/integrations/pi/agents-over-telegram.ts +154 -0
- package/package.json +41 -0
- package/pyproject.toml +37 -0
- package/requirements/build.txt +18 -0
- package/requirements/runtime.txt +532 -0
- package/scripts/bootstrap_runtime.py +402 -0
- package/skills/telegram-coordinate/SKILL.md +67 -0
- package/skills/telegram-setup/SKILL.md +81 -0
- package/src/agents_over_telegram/__init__.py +2 -0
- package/src/agents_over_telegram/__main__.py +2 -0
- package/src/agents_over_telegram/appserver_client.py +400 -0
- package/src/agents_over_telegram/cli.py +851 -0
- package/src/agents_over_telegram/codex_trust.py +206 -0
- package/src/agents_over_telegram/compat.py +207 -0
- package/src/agents_over_telegram/core.py +4253 -0
- package/src/agents_over_telegram/credentials.py +108 -0
- package/src/agents_over_telegram/demo.py +85 -0
- package/src/agents_over_telegram/desktop_bridge.py +537 -0
- package/src/agents_over_telegram/desktop_dispatcher.py +680 -0
- package/src/agents_over_telegram/dispatcher.py +260 -0
- package/src/agents_over_telegram/host_config.py +125 -0
- package/src/agents_over_telegram/hosts.py +590 -0
- package/src/agents_over_telegram/judge.py +230 -0
- package/src/agents_over_telegram/macos_process.py +133 -0
- package/src/agents_over_telegram/markdown.py +127 -0
- package/src/agents_over_telegram/mcp_server.py +652 -0
- package/src/agents_over_telegram/net.py +130 -0
- package/src/agents_over_telegram/onboarding.py +719 -0
- package/src/agents_over_telegram/push.py +421 -0
- package/src/agents_over_telegram/relay.py +380 -0
- package/src/agents_over_telegram/relay_api.py +591 -0
- package/src/agents_over_telegram/relay_watch.py +171 -0
- package/src/agents_over_telegram/serve.py +626 -0
- package/src/agents_over_telegram/settings_panel.py +216 -0
- package/src/agents_over_telegram/transport.py +720 -0
- package/src/agents_over_telegram/webhook.py +219 -0
- package/uv.lock +1011 -0
|
@@ -0,0 +1,4253 @@
|
|
|
1
|
+
"""Private, transactional one-bot routing core. Linux/macOS flock backend.
|
|
2
|
+
|
|
3
|
+
All local clients of a bot must use the same state directory. This core has no
|
|
4
|
+
background threads and never deletes a webhook or configures Telegram accounts.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import base64
|
|
9
|
+
import contextlib
|
|
10
|
+
import hashlib
|
|
11
|
+
import hmac
|
|
12
|
+
import json
|
|
13
|
+
import math
|
|
14
|
+
import os
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
import re
|
|
17
|
+
import secrets
|
|
18
|
+
import sqlite3
|
|
19
|
+
import stat
|
|
20
|
+
import time
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from . import compat
|
|
24
|
+
from .transport import TransportError, UnknownSend
|
|
25
|
+
from .credentials import CredentialError, private_directory
|
|
26
|
+
from . import judge as judge_module
|
|
27
|
+
from . import markdown
|
|
28
|
+
from . import __version__
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class CoreError(Exception):
|
|
32
|
+
"""Public errors contain only a fixed, non-sensitive code."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, code: str, *, details: dict | None = None):
|
|
35
|
+
self.code = code
|
|
36
|
+
# Rolling limits set details with numbers only: the limit, its window,
|
|
37
|
+
# current usage and the earliest retry time. owner_chat_not_started
|
|
38
|
+
# adds the registered bot username, which the owner must /start.
|
|
39
|
+
self.details = details
|
|
40
|
+
self.retry_at = (details or {}).get('retry_at')
|
|
41
|
+
super().__init__(code)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _digest(value: str) -> str:
|
|
45
|
+
return hashlib.sha256(value.encode()).hexdigest()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _version_key(text):
|
|
49
|
+
"""(major, minor, patch) for a release version such as 0.9.24, or None.
|
|
50
|
+
|
|
51
|
+
A suffix (0.9.24rc1, 0.9.24.dev0) is ignored, so such a build counts as
|
|
52
|
+
the release it precedes; runtimes of equal versions never defer to each
|
|
53
|
+
other, which keeps that harmless.
|
|
54
|
+
"""
|
|
55
|
+
match = re.match(r'(\d+)\.(\d+)\.(\d+)', text) if isinstance(text, str) else None
|
|
56
|
+
return tuple(int(part) for part in match.groups()) if match else None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@contextlib.contextmanager
|
|
60
|
+
def _timed(into, name):
|
|
61
|
+
"""Record how long the block took, in milliseconds, under ``name``."""
|
|
62
|
+
started = time.monotonic()
|
|
63
|
+
try:
|
|
64
|
+
yield
|
|
65
|
+
finally:
|
|
66
|
+
into[name] = round((time.monotonic() - started) * 1000)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# Network failures and timeouts are tried once more; a Telegram rejection is not.
|
|
70
|
+
_RETRIED_CODES = {'timeout', 'transport_failure', 'http_failure'}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _owner_call(calls, name, call):
|
|
74
|
+
"""Run one Telegram call that answers an owner action; never raises.
|
|
75
|
+
|
|
76
|
+
Its duration goes into ``calls`` as ``<name>_ms`` for the activity log,
|
|
77
|
+
with ``<name>_attempts`` when it was retried and ``<name>_error`` when it
|
|
78
|
+
failed, so a slow or lost answer shows its cause.
|
|
79
|
+
"""
|
|
80
|
+
started, attempts = time.monotonic(), 0
|
|
81
|
+
while True:
|
|
82
|
+
attempts += 1
|
|
83
|
+
try:
|
|
84
|
+
call()
|
|
85
|
+
break
|
|
86
|
+
except TransportError as error:
|
|
87
|
+
if attempts < 2 and error.code in _RETRIED_CODES:
|
|
88
|
+
continue
|
|
89
|
+
calls[name + '_error'] = str(error.code)
|
|
90
|
+
break
|
|
91
|
+
except Exception as error:
|
|
92
|
+
calls[name + '_error'] = type(error).__name__
|
|
93
|
+
break
|
|
94
|
+
calls[name + '_ms'] = round((time.monotonic() - started) * 1000)
|
|
95
|
+
if attempts > 1:
|
|
96
|
+
calls[name + '_attempts'] = attempts
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _panel_answer_kind(data):
|
|
100
|
+
"""What a settings panel answer was, for the activity log: view, warning, error or closed."""
|
|
101
|
+
try:
|
|
102
|
+
value = json.loads(data)
|
|
103
|
+
except (TypeError, ValueError):
|
|
104
|
+
return 'unknown'
|
|
105
|
+
if not isinstance(value, dict):
|
|
106
|
+
return 'unknown'
|
|
107
|
+
return next((name for key, name in (('e', 'error'), ('w', 'warning'), ('closed', 'closed'), ('s', 'view'))
|
|
108
|
+
if key in value), 'unknown')
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _integer(value: Any) -> bool:
|
|
112
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _telegram_message_keys(payload):
|
|
116
|
+
"""Return (chat_id, message_id) for a captured Telegram message, else None.
|
|
117
|
+
|
|
118
|
+
Reaction deliveries are excluded: a reaction is not itself a reaction target.
|
|
119
|
+
"""
|
|
120
|
+
if not isinstance(payload, dict) or payload.get('origin') != 'telegram' or payload.get('kind') in (
|
|
121
|
+
'reaction', 'owner_choice', 'owner_approval'):
|
|
122
|
+
return None
|
|
123
|
+
chat_id, message_id = payload.get('chat_id'), payload.get('message_id')
|
|
124
|
+
if not _integer(chat_id) or not _integer(message_id):
|
|
125
|
+
return None
|
|
126
|
+
return chat_id, message_id
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _mapping(value: Any) -> dict:
|
|
130
|
+
return value if isinstance(value, dict) else {}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _bounded(value: Any, maximum: int = 128) -> str:
|
|
134
|
+
return ''.join(c for c in str(value)[:maximum] if c.isprintable())
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _check_choices(choices):
|
|
138
|
+
"""Validated owner_notify answer labels: 2-4 distinct one-line labels of 1-32 characters, or None."""
|
|
139
|
+
if choices is None:
|
|
140
|
+
return None
|
|
141
|
+
if not isinstance(choices, list) or not 2 <= len(choices) <= 4:
|
|
142
|
+
raise CoreError('invalid_choices')
|
|
143
|
+
labels = []
|
|
144
|
+
for label in choices:
|
|
145
|
+
if (not isinstance(label, str) or label != label.strip() or not 1 <= len(label) <= 32
|
|
146
|
+
or not all(c.isprintable() for c in label)):
|
|
147
|
+
raise CoreError('invalid_choices')
|
|
148
|
+
labels.append(label)
|
|
149
|
+
if len(set(labels)) != len(labels):
|
|
150
|
+
raise CoreError('invalid_choices')
|
|
151
|
+
return labels
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _choice_buttons(notify_id, choices):
|
|
155
|
+
"""The inline keyboard for an owner_notify notice with choices, else None."""
|
|
156
|
+
if not choices:
|
|
157
|
+
return None
|
|
158
|
+
key = notify_id.removeprefix('owner_')
|
|
159
|
+
return {'inline_keyboard': [[{'text': label, 'callback_data': f'aot:c:{key}:{index}'}]
|
|
160
|
+
for index, label in enumerate(json.loads(choices))]}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
_MEDIA_KINDS = ('document', 'photo', 'video', 'audio', 'voice', 'animation')
|
|
164
|
+
MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024 # The Bot API getFile limit.
|
|
165
|
+
MAX_IMAGE_BYTES = 10 * 1024 * 1024 # The Bot API sendPhoto size limit.
|
|
166
|
+
MAX_IMAGE_CAPTION = 1024 # The Bot API caption length limit, label header included.
|
|
167
|
+
|
|
168
|
+
def _image_type(data):
|
|
169
|
+
"""Classify image bytes as (send_as, extension, mime), or (None, None, None).
|
|
170
|
+
|
|
171
|
+
PNG, JPEG and WebP are publishable as photos. Telegram does not take a GIF
|
|
172
|
+
as a photo, so a GIF is published as a document.
|
|
173
|
+
"""
|
|
174
|
+
if data.startswith(b'\x89PNG\r\n\x1a\n'):
|
|
175
|
+
return 'photo', 'png', 'image/png'
|
|
176
|
+
if data.startswith(b'\xff\xd8\xff'):
|
|
177
|
+
return 'photo', 'jpg', 'image/jpeg'
|
|
178
|
+
if data[:4] == b'RIFF' and data[8:12] == b'WEBP':
|
|
179
|
+
return 'photo', 'webp', 'image/webp'
|
|
180
|
+
if data[:6] in (b'GIF87a', b'GIF89a'):
|
|
181
|
+
return 'document', 'gif', 'image/gif'
|
|
182
|
+
return None, None, None
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _attachment(kind, media):
|
|
186
|
+
"""Keep only bounded file metadata; Telegram's file_id is what fetching needs."""
|
|
187
|
+
file_id, unique = media.get('file_id'), media.get('file_unique_id')
|
|
188
|
+
if not isinstance(file_id, str) or not 1 <= len(file_id) <= 256:
|
|
189
|
+
return None
|
|
190
|
+
if not isinstance(unique, str) or not re.fullmatch(r'[A-Za-z0-9_-]{1,64}', unique):
|
|
191
|
+
return None
|
|
192
|
+
item = {'kind': kind, 'file_id': file_id, 'file_unique_id': unique}
|
|
193
|
+
if isinstance(media.get('file_name'), str):
|
|
194
|
+
item['file_name'] = _bounded(media['file_name'], 255)
|
|
195
|
+
if isinstance(media.get('mime_type'), str):
|
|
196
|
+
item['mime_type'] = _bounded(media['mime_type'], 128)
|
|
197
|
+
if _integer(media.get('file_size')) and media['file_size'] >= 0:
|
|
198
|
+
item['file_size'] = media['file_size']
|
|
199
|
+
return item
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _menu_digest(text, markup):
|
|
203
|
+
"""A short digest of what a settings button menu shows."""
|
|
204
|
+
return _digest(json.dumps([text, markup], separators=(',', ':'), sort_keys=True, ensure_ascii=False))
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _send_formatted(send, text, field='text', **params):
|
|
208
|
+
"""Send agent text with its Markdown rendered, or plain when that is not possible.
|
|
209
|
+
|
|
210
|
+
Plain text goes out when there is nothing to format, and when Telegram
|
|
211
|
+
rejects the formatting. That rejection is a 400, so nothing was sent and
|
|
212
|
+
the second send cannot duplicate the message.
|
|
213
|
+
"""
|
|
214
|
+
formatted = markdown.agent_html(text)
|
|
215
|
+
if formatted is not None:
|
|
216
|
+
try:
|
|
217
|
+
return send(**{field: formatted}, parse_mode='HTML', **params)
|
|
218
|
+
except TransportError as exc:
|
|
219
|
+
if not exc.bad_entities:
|
|
220
|
+
raise
|
|
221
|
+
return send(**{field: text}, **params)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _message_content(msg):
|
|
225
|
+
"""Return (text, attachments), or (None, []) for an unsupported message.
|
|
226
|
+
|
|
227
|
+
A media message carries its caption as text, or an empty string."""
|
|
228
|
+
attachments = []
|
|
229
|
+
for kind in _MEDIA_KINDS:
|
|
230
|
+
media = msg.get(kind)
|
|
231
|
+
if kind == 'photo':
|
|
232
|
+
# Telegram sends one entry per size; keep the largest.
|
|
233
|
+
sizes = [size for size in media if isinstance(size, dict)] if isinstance(media, list) else []
|
|
234
|
+
media = max(sizes, key=lambda size: size.get('file_size') if _integer(size.get('file_size')) else 0,
|
|
235
|
+
default=None)
|
|
236
|
+
if isinstance(media, dict):
|
|
237
|
+
item = _attachment(kind, media)
|
|
238
|
+
if item is not None:
|
|
239
|
+
attachments.append(item)
|
|
240
|
+
text = msg.get('text') if isinstance(msg.get('text'), str) else msg.get('caption')
|
|
241
|
+
if not isinstance(text, str):
|
|
242
|
+
text = '' if attachments else None
|
|
243
|
+
if text is None or len(text) > 4096:
|
|
244
|
+
return None, []
|
|
245
|
+
# Telegram strips code markers and link targets into entities; put them
|
|
246
|
+
# back, so the agent reads what the sender meant.
|
|
247
|
+
entities = msg.get('entities') if isinstance(msg.get('text'), str) else msg.get('caption_entities')
|
|
248
|
+
return markdown.entities_markdown(text, entities), attachments
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _addressed(msg, text, account):
|
|
252
|
+
"""True when the message mentions the shared bot, replies to it, or addresses a command to it."""
|
|
253
|
+
username = re.escape(account['username'])
|
|
254
|
+
if re.search(r'(?<![\w@])@' + username + r'(?!\w)', text, re.IGNORECASE):
|
|
255
|
+
return True
|
|
256
|
+
if re.search(r'(?<![\w/])/[A-Za-z0-9_]+@' + username + r'(?!\w)', text, re.IGNORECASE):
|
|
257
|
+
return True
|
|
258
|
+
replied = _mapping(_mapping(msg.get('reply_to_message')).get('from'))
|
|
259
|
+
return replied.get('id') == account['bot_id']
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _forward_origin(msg):
|
|
263
|
+
"""Who a forwarded message came from, bounded, or None for an ordinary message."""
|
|
264
|
+
origin = _mapping(msg.get('forward_origin'))
|
|
265
|
+
kind = origin.get('type')
|
|
266
|
+
if kind == 'user':
|
|
267
|
+
user = _mapping(origin.get('sender_user'))
|
|
268
|
+
name = user.get('username') or ' '.join(
|
|
269
|
+
part for part in (user.get('first_name'), user.get('last_name')) if isinstance(part, str))
|
|
270
|
+
found = {'type': 'user', 'id': user['id'] if _integer(user.get('id')) else None}
|
|
271
|
+
elif kind == 'hidden_user':
|
|
272
|
+
name, found = origin.get('sender_user_name'), {'type': 'hidden_user'}
|
|
273
|
+
elif kind in ('chat', 'channel'):
|
|
274
|
+
chat = _mapping(origin.get('sender_chat') if kind == 'chat' else origin.get('chat'))
|
|
275
|
+
name = chat.get('title') or chat.get('username')
|
|
276
|
+
found = {'type': kind, 'id': chat['id'] if _integer(chat.get('id')) else None}
|
|
277
|
+
else:
|
|
278
|
+
return None
|
|
279
|
+
found['name'] = _bounded(name, 128) if isinstance(name, str) else ''
|
|
280
|
+
if _integer(origin.get('date')):
|
|
281
|
+
found['date'] = origin['date']
|
|
282
|
+
return found
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
QUOTED_TEXT_LIMIT = 1024
|
|
286
|
+
|
|
287
|
+
# A person's message that continues their own addressed message counts as
|
|
288
|
+
# addressed when it comes at most this many seconds later.
|
|
289
|
+
FOLLOW_UP_WINDOW = 120.0
|
|
290
|
+
_MENTION = re.compile(r'(?<![\w@])@([A-Za-z0-9_]{3,32})(?!\w)')
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _quoted_message(msg, accept_media, allowed_sender):
|
|
294
|
+
"""The message a reply quotes, so an agent can read what was replied to.
|
|
295
|
+
|
|
296
|
+
Telegram includes the replied-to message in the update. Its text and media
|
|
297
|
+
are kept like a delivered message's: media only when the connection accepts
|
|
298
|
+
it, otherwise only the media kinds. None when nothing readable is quoted, for
|
|
299
|
+
example a forum topic's creation message, which Telegram sets as the replied
|
|
300
|
+
message of every message in that topic. The text is cut to
|
|
301
|
+
QUOTED_TEXT_LIMIT characters, so a full poll page stays under the result
|
|
302
|
+
cap. ``allowed_sender`` tells whether the quoted sender is on the allow
|
|
303
|
+
list: an allowed sender quoting someone else passes that content on, like
|
|
304
|
+
a forward.
|
|
305
|
+
"""
|
|
306
|
+
quoted = _mapping(msg.get('reply_to_message'))
|
|
307
|
+
if not _integer(quoted.get('message_id')):
|
|
308
|
+
return None
|
|
309
|
+
text, attachments = _message_content(quoted)
|
|
310
|
+
if text is None:
|
|
311
|
+
return None
|
|
312
|
+
sender = _mapping(quoted.get('from'))
|
|
313
|
+
sender_id = sender['id'] if _integer(sender.get('id')) else None
|
|
314
|
+
is_bot = sender.get('is_bot') is True
|
|
315
|
+
item = {'message_id': quoted['message_id'], 'text': text[:QUOTED_TEXT_LIMIT],
|
|
316
|
+
'sender': {'id': sender_id, 'is_bot': is_bot,
|
|
317
|
+
'username': _bounded(sender.get('username', ''), 64)
|
|
318
|
+
if isinstance(sender.get('username'), str) else '',
|
|
319
|
+
'allowed': bool(sender_id is not None and allowed_sender(sender_id, is_bot))}}
|
|
320
|
+
if len(text) > QUOTED_TEXT_LIMIT:
|
|
321
|
+
item['truncated'] = True
|
|
322
|
+
if attachments and accept_media:
|
|
323
|
+
item['attachments'] = attachments
|
|
324
|
+
elif attachments:
|
|
325
|
+
item['media_refused'] = sorted({a['kind'] for a in attachments})
|
|
326
|
+
# A partial quote: the part of the replied message the reply is about.
|
|
327
|
+
selected = _mapping(msg.get('quote'))
|
|
328
|
+
if isinstance(selected.get('text'), str) and selected['text']:
|
|
329
|
+
item['quote'] = {'text': selected['text'][:QUOTED_TEXT_LIMIT]}
|
|
330
|
+
if _integer(selected.get('position')) and selected['position'] >= 0:
|
|
331
|
+
item['quote']['position'] = selected['position']
|
|
332
|
+
return item
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def reaction_emoji(value):
|
|
336
|
+
"""Normalize one agent-provided emoji to Telegram's documented form.
|
|
337
|
+
|
|
338
|
+
Telegram's bot reaction list uses bare emoji without variation selectors,
|
|
339
|
+
so they are stripped before the exact allowlist comparison. None or '' means
|
|
340
|
+
"remove the bot's reaction". Anything else that is not allowlisted raises.
|
|
341
|
+
"""
|
|
342
|
+
if value is None:
|
|
343
|
+
return ''
|
|
344
|
+
if not isinstance(value, str) or len(value) > 32:
|
|
345
|
+
raise CoreError('invalid_reaction_emoji')
|
|
346
|
+
normalized = value.replace('\ufe0f', '')
|
|
347
|
+
if value and not normalized:
|
|
348
|
+
# Input that was only variation selectors is not a removal request.
|
|
349
|
+
raise CoreError('invalid_reaction_emoji')
|
|
350
|
+
if normalized and normalized not in Core.REACTION_EMOJI:
|
|
351
|
+
raise CoreError('invalid_reaction_emoji')
|
|
352
|
+
return normalized
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def reaction_types(value):
|
|
356
|
+
"""Map a Telegram reaction list to bounded markers, or None when malformed.
|
|
357
|
+
|
|
358
|
+
Emoji reactions keep their emoji. Custom-emoji and paid reactions, which a
|
|
359
|
+
bot cannot send, are summarized as fixed markers without opaque ids.
|
|
360
|
+
"""
|
|
361
|
+
if not isinstance(value, list) or len(value) > 64:
|
|
362
|
+
return None
|
|
363
|
+
mapped = []
|
|
364
|
+
for item in value:
|
|
365
|
+
kind = _mapping(item).get('type')
|
|
366
|
+
if kind == 'emoji':
|
|
367
|
+
emoji = _mapping(item).get('emoji')
|
|
368
|
+
if not isinstance(emoji, str) or not 1 <= len(emoji) <= 32:
|
|
369
|
+
return None
|
|
370
|
+
mapped.append(emoji)
|
|
371
|
+
elif kind == 'custom_emoji':
|
|
372
|
+
mapped.append('custom_emoji')
|
|
373
|
+
elif kind == 'paid':
|
|
374
|
+
mapped.append('paid')
|
|
375
|
+
else:
|
|
376
|
+
return None
|
|
377
|
+
return mapped[:Core.REACTION_LIST_MAX], len(mapped) > Core.REACTION_LIST_MAX
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
# Core's default judge: loaded from the state directory's protected judge file.
|
|
381
|
+
_LOAD_JUDGE = object()
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
class Core:
|
|
385
|
+
PAIR_TTL = 600
|
|
386
|
+
# The AOT release running this core; collect() records it.
|
|
387
|
+
runtime_version = __version__
|
|
388
|
+
# Defaults for the rolling send limits. The operator can change them for
|
|
389
|
+
# the whole state directory with exchange_limits().
|
|
390
|
+
CONVERSATION_SEND_LIMIT = 30
|
|
391
|
+
CONVERSATION_WINDOW = 3600
|
|
392
|
+
# A ceiling per agent across all its conversations, so the total does not
|
|
393
|
+
# grow with the number of conversations an agent or bot can reach.
|
|
394
|
+
CLIENT_SEND_LIMIT = 60
|
|
395
|
+
CLIENT_WINDOW = 3600
|
|
396
|
+
BOT_PAIR_SEND_LIMIT = 32
|
|
397
|
+
BOT_PAIR_WINDOW = 3600
|
|
398
|
+
SEND_LIMIT_RANGE = (1, 1000)
|
|
399
|
+
WINDOW_RANGE = (60, 86400)
|
|
400
|
+
UNMATCHED_LIMIT = 100
|
|
401
|
+
BOT_INTERVAL = 0.05
|
|
402
|
+
DESTINATION_INTERVAL = 1.0
|
|
403
|
+
CONVERSATION_INTERVAL = 1.0
|
|
404
|
+
HISTORY_WINDOW = 86400
|
|
405
|
+
HISTORY_CURSOR_TTL = 900
|
|
406
|
+
# Reactions never post a message, so they carry their own rolling limit,
|
|
407
|
+
# separate from every message send limit. One reaction per message is the
|
|
408
|
+
# Bot API's bot limit; only standard emoji reactions are sent.
|
|
409
|
+
REACTION_SEND_LIMIT = 30
|
|
410
|
+
REACTION_WINDOW = 3600
|
|
411
|
+
REACTION_INTERVAL = 1.0
|
|
412
|
+
REACTION_LIST_MAX = 16
|
|
413
|
+
# owner_notify interrupts the owner personally, so it stays low volume by
|
|
414
|
+
# rule: (limit, window seconds) pairs, each a rolling window per agent.
|
|
415
|
+
OWNER_NOTIFY_LIMITS = ((3, 3600), (10, 86400))
|
|
416
|
+
# An answer to a message the owner sent the agent continues a conversation
|
|
417
|
+
# the owner started. It does not use the limits above; this cap only stops
|
|
418
|
+
# a looping agent.
|
|
419
|
+
OWNER_REPLY_LIMITS = ((30, 3600),)
|
|
420
|
+
OWNER_NOTIFY_INTERVAL = 1.0
|
|
421
|
+
# The bot answers an owner's private /start at most once in this window.
|
|
422
|
+
START_REPLY_INTERVAL = 60.0
|
|
423
|
+
OWNER_NOTIFY_FOOTER = 'Reply to this message to answer the agent.'
|
|
424
|
+
OWNER_CHOICE_FOOTER = 'Tap an answer, or reply to this message to answer the agent.'
|
|
425
|
+
OWNER_CHOICE_SECONDS = 86400
|
|
426
|
+
REACTION_WAKE_MODES = ('own_messages', 'all', 'none')
|
|
427
|
+
WAKE_EXEMPT_MODES = ('addressed,owner', 'addressed', 'owner', 'none')
|
|
428
|
+
WAKE_INTERVAL_MAX = 86400
|
|
429
|
+
# Model-judged wake decision (judge.py): a person's message that the
|
|
430
|
+
# addressed rules kept as context is judged at most this long after it
|
|
431
|
+
# arrived, by long-running collectors only, a few per collection within a
|
|
432
|
+
# total time budget (seconds), and within rolling (limit, seconds) caps per
|
|
433
|
+
# agent. It sees this many earlier messages from the same chat or topic.
|
|
434
|
+
JUDGE_MAX_AGE = 300.0
|
|
435
|
+
JUDGE_PER_COLLECT = 3
|
|
436
|
+
JUDGE_BUDGET = 20.0
|
|
437
|
+
JUDGE_LIMITS = ((60, 3600), (300, 86400))
|
|
438
|
+
JUDGE_HISTORY = 8
|
|
439
|
+
|
|
440
|
+
# The exact standard reaction emoji Telegram documents for bots
|
|
441
|
+
# (core.telegram.org/bots/api#reactiontypeemoji). Telegram compares the bare
|
|
442
|
+
# forms without variation selectors, so input is normalized the same way.
|
|
443
|
+
REACTION_EMOJI = (
|
|
444
|
+
'❤', '👍', '👎', '🔥', '🥰', '👏', '😁', '🤔', '🤯', '😱', '🤬', '😢', '🎉', '🤩', '🤮',
|
|
445
|
+
'💩', '🙏', '👌', '🕊', '🤡', '🥱', '🥴', '😍', '🐳', '❤🔥', '🌚', '🌭', '💯', '🤣', '⚡',
|
|
446
|
+
'🍌', '🏆', '💔', '🤨', '😐', '🍓', '🍾', '💋', '🖕', '😈', '😴', '😭', '🤓', '👻', '👨💻',
|
|
447
|
+
'👀', '🎃', '🙈', '😇', '😨', '🤝', '✍', '🤗', '🫡', '🎅', '🎄', '☃', '💅', '🤪', '🗿',
|
|
448
|
+
'🆒', '💘', '🙉', '🦄', '😘', '💊', '🙊', '😎', '👾', '🤷♂', '🤷', '🤷♀', '😡',
|
|
449
|
+
)
|
|
450
|
+
|
|
451
|
+
def __init__(self, state_dir, transport, clock=time.time, queue_limit=1000, *, recover_sends=True,
|
|
452
|
+
judge=_LOAD_JUDGE):
|
|
453
|
+
if not _integer(queue_limit) or not 1 <= queue_limit <= 100000:
|
|
454
|
+
raise CoreError('invalid_queue_limit')
|
|
455
|
+
try:
|
|
456
|
+
self.state_dir = private_directory(state_dir)
|
|
457
|
+
except CredentialError:
|
|
458
|
+
raise CoreError('insecure_state_directory') from None
|
|
459
|
+
self.transport = transport
|
|
460
|
+
self.clock = clock
|
|
461
|
+
# When the last fetch from Telegram returned (time.monotonic), for the activity log.
|
|
462
|
+
self._poll_end = None
|
|
463
|
+
self.queue_limit = queue_limit
|
|
464
|
+
# Deliveries kept as context because their agent's queue was full,
|
|
465
|
+
# counted per collection for the activity log.
|
|
466
|
+
self._overflowed = 0
|
|
467
|
+
# The model judge loads from the protected judge file on first use;
|
|
468
|
+
# tests pass a callable, and None turns it off.
|
|
469
|
+
self._judge = judge
|
|
470
|
+
self.database = self.state_dir / 'state.sqlite3'
|
|
471
|
+
try:
|
|
472
|
+
fd = os.open(self.database, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
473
|
+
except FileExistsError:
|
|
474
|
+
info = self.database.lstat()
|
|
475
|
+
if not stat.S_ISREG(info.st_mode) or not compat.owned(info) or not compat.private(info, 0o077) or info.st_nlink != 1:
|
|
476
|
+
raise CoreError('insecure_state_file')
|
|
477
|
+
else:
|
|
478
|
+
os.close(fd)
|
|
479
|
+
with self._db() as db:
|
|
480
|
+
db.executescript('''
|
|
481
|
+
PRAGMA journal_mode=WAL;
|
|
482
|
+
CREATE TABLE IF NOT EXISTS account (
|
|
483
|
+
singleton INTEGER PRIMARY KEY CHECK(singleton=1),
|
|
484
|
+
bot_id INTEGER NOT NULL, username TEXT NOT NULL,
|
|
485
|
+
cursor INTEGER NOT NULL DEFAULT 0, last_intake REAL,
|
|
486
|
+
last_attempt REAL, intake_error TEXT, last_gap_at REAL
|
|
487
|
+
);
|
|
488
|
+
CREATE TABLE IF NOT EXISTS clients (
|
|
489
|
+
id TEXT PRIMARY KEY, label TEXT NOT NULL, secret_hash TEXT UNIQUE NOT NULL,
|
|
490
|
+
active INTEGER NOT NULL DEFAULT 1, created REAL NOT NULL
|
|
491
|
+
);
|
|
492
|
+
CREATE TABLE IF NOT EXISTS bindings (
|
|
493
|
+
client_id TEXT PRIMARY KEY REFERENCES clients(id), chat_id INTEGER NOT NULL,
|
|
494
|
+
thread_id INTEGER NOT NULL DEFAULT 0, owner_id INTEGER NOT NULL,
|
|
495
|
+
title TEXT NOT NULL, connected INTEGER NOT NULL DEFAULT 1,
|
|
496
|
+
paused INTEGER NOT NULL DEFAULT 0, suspended TEXT,
|
|
497
|
+
created REAL NOT NULL
|
|
498
|
+
);
|
|
499
|
+
CREATE UNIQUE INDEX IF NOT EXISTS dedicated_destination
|
|
500
|
+
ON bindings(chat_id,thread_id) WHERE connected=1;
|
|
501
|
+
CREATE TABLE IF NOT EXISTS pairings (
|
|
502
|
+
id TEXT PRIMARY KEY, client_id TEXT NOT NULL REFERENCES clients(id),
|
|
503
|
+
code_hash TEXT UNIQUE NOT NULL, expires REAL NOT NULL,
|
|
504
|
+
consumed INTEGER NOT NULL DEFAULT 0, sender_id INTEGER,
|
|
505
|
+
chat_id INTEGER, thread_id INTEGER, title TEXT, observed REAL
|
|
506
|
+
);
|
|
507
|
+
CREATE TABLE IF NOT EXISTS allowed_senders (
|
|
508
|
+
client_id TEXT NOT NULL REFERENCES clients(id), sender_id INTEGER NOT NULL,
|
|
509
|
+
is_bot INTEGER NOT NULL, PRIMARY KEY(client_id,sender_id)
|
|
510
|
+
);
|
|
511
|
+
CREATE TABLE IF NOT EXISTS owner_approvals (
|
|
512
|
+
id TEXT PRIMARY KEY, client_id TEXT NOT NULL REFERENCES clients(id),
|
|
513
|
+
owner_id INTEGER NOT NULL, action TEXT NOT NULL, params TEXT NOT NULL,
|
|
514
|
+
text TEXT NOT NULL, status TEXT NOT NULL, error TEXT,
|
|
515
|
+
created REAL NOT NULL, expires REAL NOT NULL, decided REAL
|
|
516
|
+
);
|
|
517
|
+
CREATE TABLE IF NOT EXISTS settings_panels (
|
|
518
|
+
owner_id INTEGER PRIMARY KEY, message_id INTEGER NOT NULL, created REAL NOT NULL
|
|
519
|
+
);
|
|
520
|
+
CREATE TABLE IF NOT EXISTS panel_requests (
|
|
521
|
+
update_id INTEGER PRIMARY KEY, owner_id INTEGER NOT NULL, status TEXT NOT NULL,
|
|
522
|
+
created REAL NOT NULL
|
|
523
|
+
);
|
|
524
|
+
CREATE TABLE IF NOT EXISTS activity (
|
|
525
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT, at REAL NOT NULL, kind TEXT NOT NULL,
|
|
526
|
+
detail TEXT NOT NULL
|
|
527
|
+
);
|
|
528
|
+
CREATE TABLE IF NOT EXISTS widget_answers (
|
|
529
|
+
query_id TEXT PRIMARY KEY, data TEXT NOT NULL, chat_id INTEGER,
|
|
530
|
+
message_id INTEGER, chat_data TEXT, created REAL NOT NULL,
|
|
531
|
+
remove INTEGER NOT NULL DEFAULT 0
|
|
532
|
+
);
|
|
533
|
+
CREATE TABLE IF NOT EXISTS callback_answers (
|
|
534
|
+
callback_id TEXT PRIMARY KEY, text TEXT NOT NULL, chat_id INTEGER,
|
|
535
|
+
message_id INTEGER, edit_text TEXT, created REAL NOT NULL
|
|
536
|
+
);
|
|
537
|
+
CREATE TABLE IF NOT EXISTS blocked_senders (
|
|
538
|
+
client_id TEXT NOT NULL REFERENCES clients(id), sender_id INTEGER NOT NULL,
|
|
539
|
+
PRIMARY KEY(client_id,sender_id)
|
|
540
|
+
);
|
|
541
|
+
CREATE TABLE IF NOT EXISTS peer_commands (
|
|
542
|
+
client_id TEXT PRIMARY KEY REFERENCES clients(id),
|
|
543
|
+
bot_username TEXT NOT NULL, command TEXT NOT NULL
|
|
544
|
+
);
|
|
545
|
+
CREATE TABLE IF NOT EXISTS grants (
|
|
546
|
+
source TEXT NOT NULL REFERENCES clients(id), target TEXT NOT NULL REFERENCES clients(id),
|
|
547
|
+
PRIMARY KEY(source,target)
|
|
548
|
+
);
|
|
549
|
+
CREATE TABLE IF NOT EXISTS inbox (
|
|
550
|
+
id TEXT PRIMARY KEY, client_id TEXT NOT NULL REFERENCES clients(id),
|
|
551
|
+
event_key TEXT NOT NULL, payload TEXT NOT NULL, created REAL NOT NULL,
|
|
552
|
+
conversation_id TEXT NOT NULL, outbox_id TEXT, event_at REAL,
|
|
553
|
+
acknowledged INTEGER NOT NULL DEFAULT 0,
|
|
554
|
+
lease_token TEXT, lease_until REAL,
|
|
555
|
+
UNIQUE(client_id,event_key)
|
|
556
|
+
);
|
|
557
|
+
CREATE INDEX IF NOT EXISTS inbox_claim ON inbox(client_id,acknowledged,created);
|
|
558
|
+
CREATE TABLE IF NOT EXISTS outbox (
|
|
559
|
+
id TEXT PRIMARY KEY, client_id TEXT NOT NULL REFERENCES clients(id),
|
|
560
|
+
recipient TEXT, chat_id INTEGER NOT NULL, thread_id INTEGER NOT NULL,
|
|
561
|
+
idempotency_key TEXT NOT NULL, request_hash TEXT NOT NULL,
|
|
562
|
+
text TEXT NOT NULL, reply_to INTEGER, conversation_id TEXT NOT NULL,
|
|
563
|
+
status TEXT NOT NULL, error TEXT, message_id INTEGER, image TEXT,
|
|
564
|
+
created REAL NOT NULL, updated REAL NOT NULL, due REAL NOT NULL,
|
|
565
|
+
UNIQUE(client_id,idempotency_key)
|
|
566
|
+
);
|
|
567
|
+
CREATE TABLE IF NOT EXISTS reaction_outbox (
|
|
568
|
+
id TEXT PRIMARY KEY, client_id TEXT NOT NULL REFERENCES clients(id),
|
|
569
|
+
chat_id INTEGER NOT NULL, thread_id INTEGER NOT NULL,
|
|
570
|
+
message_id INTEGER NOT NULL, emoji TEXT NOT NULL,
|
|
571
|
+
idempotency_key TEXT NOT NULL, request_hash TEXT NOT NULL,
|
|
572
|
+
status TEXT NOT NULL, error TEXT,
|
|
573
|
+
created REAL NOT NULL, updated REAL NOT NULL, due REAL NOT NULL,
|
|
574
|
+
UNIQUE(client_id,idempotency_key)
|
|
575
|
+
);
|
|
576
|
+
CREATE TABLE IF NOT EXISTS owner_outbox (
|
|
577
|
+
id TEXT PRIMARY KEY, client_id TEXT NOT NULL REFERENCES clients(id),
|
|
578
|
+
owner_id INTEGER NOT NULL, text TEXT NOT NULL,
|
|
579
|
+
from_chat_id INTEGER, forward_message_id INTEGER,
|
|
580
|
+
idempotency_key TEXT NOT NULL, request_hash TEXT NOT NULL,
|
|
581
|
+
status TEXT NOT NULL, error TEXT,
|
|
582
|
+
message_id INTEGER, forwarded_message_id INTEGER,
|
|
583
|
+
created REAL NOT NULL, updated REAL NOT NULL, due REAL NOT NULL,
|
|
584
|
+
UNIQUE(client_id,idempotency_key)
|
|
585
|
+
);
|
|
586
|
+
CREATE INDEX IF NOT EXISTS owner_outbox_window ON owner_outbox(client_id,created);
|
|
587
|
+
CREATE TABLE IF NOT EXISTS start_replies (
|
|
588
|
+
update_id INTEGER PRIMARY KEY, owner_id INTEGER NOT NULL,
|
|
589
|
+
status TEXT NOT NULL, created REAL NOT NULL, updated REAL NOT NULL
|
|
590
|
+
);
|
|
591
|
+
CREATE TABLE IF NOT EXISTS judge_queue (
|
|
592
|
+
inbox_id TEXT PRIMARY KEY, client_id TEXT NOT NULL,
|
|
593
|
+
status TEXT NOT NULL, error TEXT,
|
|
594
|
+
created REAL NOT NULL, updated REAL NOT NULL
|
|
595
|
+
);
|
|
596
|
+
CREATE INDEX IF NOT EXISTS judge_queue_window ON judge_queue(client_id,status,updated);
|
|
597
|
+
CREATE TABLE IF NOT EXISTS rate_limits (
|
|
598
|
+
scope TEXT PRIMARY KEY, next_at REAL NOT NULL
|
|
599
|
+
);
|
|
600
|
+
CREATE TABLE IF NOT EXISTS conversations (
|
|
601
|
+
id TEXT PRIMARY KEY, send_count INTEGER NOT NULL DEFAULT 0
|
|
602
|
+
);
|
|
603
|
+
CREATE TABLE IF NOT EXISTS conversation_budget_grants (
|
|
604
|
+
id INTEGER PRIMARY KEY, client_id TEXT NOT NULL REFERENCES clients(id),
|
|
605
|
+
conversation_id TEXT NOT NULL REFERENCES conversations(id),
|
|
606
|
+
send_limit INTEGER NOT NULL, created REAL NOT NULL,
|
|
607
|
+
expires_at REAL NOT NULL, reason TEXT NOT NULL
|
|
608
|
+
);
|
|
609
|
+
CREATE TABLE IF NOT EXISTS exchange_limits (
|
|
610
|
+
singleton INTEGER PRIMARY KEY CHECK(singleton=1),
|
|
611
|
+
conversation_send_limit INTEGER NOT NULL, conversation_window INTEGER NOT NULL,
|
|
612
|
+
pair_send_limit INTEGER NOT NULL, pair_window INTEGER NOT NULL,
|
|
613
|
+
updated REAL NOT NULL, reason TEXT NOT NULL,
|
|
614
|
+
client_send_limit INTEGER, client_window INTEGER
|
|
615
|
+
);
|
|
616
|
+
CREATE TABLE IF NOT EXISTS bot_exchange_policies (
|
|
617
|
+
client_id TEXT NOT NULL REFERENCES clients(id), sender_id INTEGER NOT NULL,
|
|
618
|
+
enabled INTEGER NOT NULL, PRIMARY KEY(client_id,sender_id)
|
|
619
|
+
);
|
|
620
|
+
CREATE TABLE IF NOT EXISTS bot_exchange_members (
|
|
621
|
+
conversation_id TEXT NOT NULL, client_id TEXT NOT NULL REFERENCES clients(id),
|
|
622
|
+
sender_id INTEGER NOT NULL,
|
|
623
|
+
PRIMARY KEY(conversation_id,client_id,sender_id)
|
|
624
|
+
);
|
|
625
|
+
CREATE INDEX IF NOT EXISTS bot_exchange_pair
|
|
626
|
+
ON bot_exchange_members(client_id,sender_id,conversation_id);
|
|
627
|
+
CREATE INDEX IF NOT EXISTS outbox_exchange_window ON outbox(conversation_id,created);
|
|
628
|
+
CREATE TABLE IF NOT EXISTS history_keys (
|
|
629
|
+
singleton INTEGER PRIMARY KEY CHECK(singleton=1), secret BLOB NOT NULL
|
|
630
|
+
);
|
|
631
|
+
CREATE TABLE IF NOT EXISTS unmatched (
|
|
632
|
+
update_id INTEGER PRIMARY KEY, chat_id INTEGER, reason TEXT NOT NULL, created REAL NOT NULL
|
|
633
|
+
);
|
|
634
|
+
''')
|
|
635
|
+
with self._tx() as db:
|
|
636
|
+
if 'last_gap_at' not in {row['name'] for row in db.execute('PRAGMA table_info(account)')}:
|
|
637
|
+
db.execute('ALTER TABLE account ADD COLUMN last_gap_at REAL')
|
|
638
|
+
# Which version of the bot's private-chat command menu AOT has set.
|
|
639
|
+
if 'menu_version' not in {row['name'] for row in db.execute('PRAGMA table_info(account)')}:
|
|
640
|
+
db.execute('ALTER TABLE account ADD COLUMN menu_version INTEGER')
|
|
641
|
+
# The newest runtime that collected, so older ones stand aside (see collect).
|
|
642
|
+
account_columns = {row['name'] for row in db.execute('PRAGMA table_info(account)')}
|
|
643
|
+
for column, kind in (('collector_version', 'TEXT'), ('collector_seen', 'REAL'),
|
|
644
|
+
('legacy_intake_at', 'REAL'), ('aware_intake', 'REAL'),
|
|
645
|
+
('down_notice_at', 'REAL')):
|
|
646
|
+
if column not in account_columns:
|
|
647
|
+
db.execute(f'ALTER TABLE account ADD COLUMN {column} {kind}')
|
|
648
|
+
if 'event_at' not in {row['name'] for row in db.execute('PRAGMA table_info(inbox)')}:
|
|
649
|
+
db.execute('ALTER TABLE inbox ADD COLUMN event_at REAL')
|
|
650
|
+
binding_columns = {row['name'] for row in db.execute('PRAGMA table_info(bindings)')}
|
|
651
|
+
if 'suspension_seq' not in binding_columns:
|
|
652
|
+
db.execute('ALTER TABLE bindings ADD COLUMN suspension_seq INTEGER NOT NULL DEFAULT 0')
|
|
653
|
+
# Both default to the original behavior: every allowed message is
|
|
654
|
+
# delivered, and nothing from other senders is retained.
|
|
655
|
+
if 'delivery_filter' not in binding_columns:
|
|
656
|
+
db.execute("ALTER TABLE bindings ADD COLUMN delivery_filter TEXT NOT NULL DEFAULT 'all'")
|
|
657
|
+
if 'capture_context' not in binding_columns:
|
|
658
|
+
db.execute('ALTER TABLE bindings ADD COLUMN capture_context INTEGER NOT NULL DEFAULT 0')
|
|
659
|
+
# Media messages stay unsupported unless the operator accepts them.
|
|
660
|
+
if 'accept_media' not in binding_columns:
|
|
661
|
+
db.execute('ALTER TABLE bindings ADD COLUMN accept_media INTEGER NOT NULL DEFAULT 0')
|
|
662
|
+
# Context rows are stored acknowledged, so no poll, watch or wake path
|
|
663
|
+
# ever claims them; history shows them as context.
|
|
664
|
+
if 'context' not in {row['name'] for row in db.execute('PRAGMA table_info(inbox)')}:
|
|
665
|
+
db.execute('ALTER TABLE inbox ADD COLUMN context INTEGER NOT NULL DEFAULT 0')
|
|
666
|
+
db.execute('CREATE INDEX IF NOT EXISTS inbox_context_expiry ON inbox(COALESCE(event_at,created)) WHERE context=1')
|
|
667
|
+
if 'window_reset_at' not in {row['name'] for row in db.execute('PRAGMA table_info(conversations)')}:
|
|
668
|
+
# Set when the owner posts in a conversation; NULL means never.
|
|
669
|
+
db.execute('ALTER TABLE conversations ADD COLUMN window_reset_at REAL')
|
|
670
|
+
if 'additional_sends' not in {row['name'] for row in db.execute('PRAGMA table_info(conversation_budget_grants)')}:
|
|
671
|
+
# Older grants were lifetime allowances. They do not apply to
|
|
672
|
+
# rolling windows, so they keep a NULL value and are ignored.
|
|
673
|
+
db.execute('ALTER TABLE conversation_budget_grants ADD COLUMN additional_sends INTEGER')
|
|
674
|
+
limit_columns = {row['name'] for row in db.execute('PRAGMA table_info(exchange_limits)')}
|
|
675
|
+
for column in ('client_send_limit', 'client_window'):
|
|
676
|
+
if column not in limit_columns:
|
|
677
|
+
# NULL means the built-in default.
|
|
678
|
+
db.execute(f'ALTER TABLE exchange_limits ADD COLUMN {column} INTEGER')
|
|
679
|
+
# An image send stores a copy of the bytes for retries; NULL is text-only.
|
|
680
|
+
if 'image' not in {row['name'] for row in db.execute('PRAGMA table_info(outbox)')}:
|
|
681
|
+
db.execute('ALTER TABLE outbox ADD COLUMN image TEXT')
|
|
682
|
+
# Reaction receive capability: NULL until first observed or probed.
|
|
683
|
+
if 'bot_admin' not in binding_columns:
|
|
684
|
+
db.execute('ALTER TABLE bindings ADD COLUMN bot_admin INTEGER')
|
|
685
|
+
# Which reactions are delivered (and can wake): the default wakes only
|
|
686
|
+
# for reactions on the agent's own published messages.
|
|
687
|
+
if 'reaction_wake' not in binding_columns:
|
|
688
|
+
db.execute("ALTER TABLE bindings ADD COLUMN reaction_wake TEXT NOT NULL DEFAULT 'own_messages'")
|
|
689
|
+
# Wake batching: at most one notice per interval (0 = every delivery
|
|
690
|
+
# at once), except for the kinds of delivery named in wake_exempt.
|
|
691
|
+
if 'wake_interval' not in binding_columns:
|
|
692
|
+
db.execute('ALTER TABLE bindings ADD COLUMN wake_interval INTEGER NOT NULL DEFAULT 0')
|
|
693
|
+
if 'wake_exempt' not in binding_columns:
|
|
694
|
+
db.execute("ALTER TABLE bindings ADD COLUMN wake_exempt TEXT NOT NULL DEFAULT 'addressed,owner'")
|
|
695
|
+
# When the agent read a message kept as context for its full queue
|
|
696
|
+
# in a history page; queue_full_kept counts those not read yet.
|
|
697
|
+
if 'queue_full_read' not in {row['name'] for row in db.execute('PRAGMA table_info(inbox)')}:
|
|
698
|
+
db.execute('ALTER TABLE inbox ADD COLUMN queue_full_read REAL')
|
|
699
|
+
# A notice can answer the owner's reply in the private chat.
|
|
700
|
+
owner_columns = {row['name'] for row in db.execute('PRAGMA table_info(owner_outbox)')}
|
|
701
|
+
if 'reply_to' not in owner_columns:
|
|
702
|
+
db.execute('ALTER TABLE owner_outbox ADD COLUMN reply_to INTEGER')
|
|
703
|
+
# 1 when the notice answers a message the owner sent this agent.
|
|
704
|
+
if 'answers_owner' not in owner_columns:
|
|
705
|
+
db.execute('ALTER TABLE owner_outbox ADD COLUMN answers_owner INTEGER NOT NULL DEFAULT 0')
|
|
706
|
+
# Optional answer buttons (a JSON list of labels), the owner's pressed
|
|
707
|
+
# label, and when the buttons stop counting.
|
|
708
|
+
for column, kind in (('choices', 'TEXT'), ('choice', 'TEXT'), ('choice_expires', 'REAL')):
|
|
709
|
+
if column not in owner_columns:
|
|
710
|
+
db.execute(f'ALTER TABLE owner_outbox ADD COLUMN {column} {kind}')
|
|
711
|
+
# owner_notify is the first tool that writes outside the bound
|
|
712
|
+
# destination, so the owner switches it on knowingly per connection.
|
|
713
|
+
if 'owner_notify' not in binding_columns:
|
|
714
|
+
db.execute('ALTER TABLE bindings ADD COLUMN owner_notify INTEGER NOT NULL DEFAULT 0')
|
|
715
|
+
# A model judges context messages for this connection (judge.py); off
|
|
716
|
+
# until the owner turns it on, because it sends group text to a model.
|
|
717
|
+
if 'model_judge' not in binding_columns:
|
|
718
|
+
db.execute('ALTER TABLE bindings ADD COLUMN model_judge INTEGER NOT NULL DEFAULT 0')
|
|
719
|
+
# Everyone who posts in the destination becomes an allowed sender; off
|
|
720
|
+
# until the owner turns it on for a group of trusted people.
|
|
721
|
+
if 'auto_allow' not in binding_columns:
|
|
722
|
+
db.execute('ALTER TABLE bindings ADD COLUMN auto_allow INTEGER NOT NULL DEFAULT 0')
|
|
723
|
+
# Claude Code's idle-session waiter wakes the session once when its
|
|
724
|
+
# time limit ends; off until the owner accepts that daily turn.
|
|
725
|
+
# Development builds kept one settings panel per connection; a panel is
|
|
726
|
+
# one per owner now. Panels are disposable: the owner sends /settings again.
|
|
727
|
+
if 'remove' not in {row['name'] for row in db.execute('PRAGMA table_info(widget_answers)')}:
|
|
728
|
+
db.execute('ALTER TABLE widget_answers ADD COLUMN remove INTEGER NOT NULL DEFAULT 0')
|
|
729
|
+
if 'client_id' in {row['name'] for row in db.execute('PRAGMA table_info(settings_panels)')}:
|
|
730
|
+
db.execute('DROP TABLE settings_panels')
|
|
731
|
+
db.execute('CREATE TABLE settings_panels (owner_id INTEGER PRIMARY KEY, '
|
|
732
|
+
'message_id INTEGER NOT NULL, created REAL NOT NULL)')
|
|
733
|
+
# A digest of what a button menu shows now, so a tap that would
|
|
734
|
+
# redraw the same menu skips the edit Telegram would refuse.
|
|
735
|
+
if 'shown' not in {row['name'] for row in db.execute('PRAGMA table_info(settings_panels)')}:
|
|
736
|
+
db.execute('ALTER TABLE settings_panels ADD COLUMN shown TEXT')
|
|
737
|
+
if 'keep_alive' not in binding_columns:
|
|
738
|
+
db.execute('ALTER TABLE bindings ADD COLUMN keep_alive INTEGER NOT NULL DEFAULT 0')
|
|
739
|
+
# Where owner approvals are asked: the owner's private chat (the
|
|
740
|
+
# default) or the bound group, as a message only the owner sees.
|
|
741
|
+
if 'approvals_in' not in binding_columns:
|
|
742
|
+
db.execute("ALTER TABLE bindings ADD COLUMN approvals_in TEXT NOT NULL DEFAULT 'private'")
|
|
743
|
+
# An approval sent to the group as an ephemeral message: its chat and
|
|
744
|
+
# ephemeral id, so only a press on that very message counts.
|
|
745
|
+
approval_columns = {row['name'] for row in db.execute('PRAGMA table_info(owner_approvals)')}
|
|
746
|
+
for column in ('chat_id', 'ephemeral_id'):
|
|
747
|
+
if column not in approval_columns:
|
|
748
|
+
db.execute(f'ALTER TABLE owner_approvals ADD COLUMN {column} INTEGER')
|
|
749
|
+
answer_columns = {row['name'] for row in db.execute('PRAGMA table_info(callback_answers)')}
|
|
750
|
+
# edit_format: the edit is an owner_notify notice, so it keeps its Markdown.
|
|
751
|
+
for column in ('receiver_id', 'ephemeral_id', 'edit_format'):
|
|
752
|
+
if column not in answer_columns:
|
|
753
|
+
db.execute(f'ALTER TABLE callback_answers ADD COLUMN {column} INTEGER')
|
|
754
|
+
# A settings menu press edits the menu with new buttons (edit_markup,
|
|
755
|
+
# JSON) or deletes it (remove).
|
|
756
|
+
if 'edit_markup' not in answer_columns:
|
|
757
|
+
db.execute('ALTER TABLE callback_answers ADD COLUMN edit_markup TEXT')
|
|
758
|
+
if 'remove' not in answer_columns:
|
|
759
|
+
db.execute('ALTER TABLE callback_answers ADD COLUMN remove INTEGER')
|
|
760
|
+
# When auto-allow added a sender (NULL for an explicit grant), and the
|
|
761
|
+
# username it saw then, so status can show who joined this way.
|
|
762
|
+
sender_columns = {row['name'] for row in db.execute('PRAGMA table_info(allowed_senders)')}
|
|
763
|
+
if 'auto_added' not in sender_columns:
|
|
764
|
+
db.execute('ALTER TABLE allowed_senders ADD COLUMN auto_added REAL')
|
|
765
|
+
if 'username' not in sender_columns:
|
|
766
|
+
db.execute('ALTER TABLE allowed_senders ADD COLUMN username TEXT')
|
|
767
|
+
# When the last admin probe ran, so a failing probe is retried only after a pause.
|
|
768
|
+
if 'bot_admin_probed' not in binding_columns:
|
|
769
|
+
db.execute('ALTER TABLE bindings ADD COLUMN bot_admin_probed REAL')
|
|
770
|
+
# Telegram chat and message IDs of captured messages, so a reaction finds
|
|
771
|
+
# its target with an index lookup instead of decoding the whole inbox.
|
|
772
|
+
inbox_columns = {row['name'] for row in db.execute('PRAGMA table_info(inbox)')}
|
|
773
|
+
if 'tg_message_id' not in inbox_columns:
|
|
774
|
+
db.execute('ALTER TABLE inbox ADD COLUMN tg_chat_id INTEGER')
|
|
775
|
+
db.execute('ALTER TABLE inbox ADD COLUMN tg_message_id INTEGER')
|
|
776
|
+
for row in db.execute('SELECT rowid,payload FROM inbox').fetchall():
|
|
777
|
+
keys = _telegram_message_keys(json.loads(row['payload']))
|
|
778
|
+
if keys is not None:
|
|
779
|
+
db.execute('UPDATE inbox SET tg_chat_id=?,tg_message_id=? WHERE rowid=?', (*keys, row['rowid']))
|
|
780
|
+
db.execute('CREATE INDEX IF NOT EXISTS inbox_telegram_message ON inbox(tg_chat_id,tg_message_id)')
|
|
781
|
+
db.execute('CREATE INDEX IF NOT EXISTS reaction_outbox_history ON reaction_outbox(client_id,created DESC)')
|
|
782
|
+
db.execute('INSERT OR IGNORE INTO history_keys(singleton,secret) VALUES(1,?)', (secrets.token_bytes(32),))
|
|
783
|
+
db.execute('CREATE INDEX IF NOT EXISTS inbox_history ON inbox(client_id,COALESCE(event_at,created) DESC)')
|
|
784
|
+
db.execute('CREATE INDEX IF NOT EXISTS outbox_history ON outbox(client_id,created DESC)')
|
|
785
|
+
if recover_sends:
|
|
786
|
+
with self._lock('sender') as acquired:
|
|
787
|
+
if acquired:
|
|
788
|
+
with self._tx() as db:
|
|
789
|
+
self._recover_sends(db)
|
|
790
|
+
|
|
791
|
+
# Every commit reaches the disk before it returns, so an accepted send or
|
|
792
|
+
# ack survives a power loss. The test suite runs with NORMAL instead: it
|
|
793
|
+
# never cuts the power, and a flush per commit costs minutes on Windows.
|
|
794
|
+
SQLITE_SYNCHRONOUS = 'FULL'
|
|
795
|
+
|
|
796
|
+
@contextlib.contextmanager
|
|
797
|
+
def _db(self):
|
|
798
|
+
db = None
|
|
799
|
+
try:
|
|
800
|
+
db = sqlite3.connect(self.database, timeout=5, isolation_level=None)
|
|
801
|
+
db.row_factory = sqlite3.Row
|
|
802
|
+
db.execute('PRAGMA foreign_keys=ON')
|
|
803
|
+
db.execute('PRAGMA synchronous=' + {'FULL': 'FULL', 'NORMAL': 'NORMAL'}[self.SQLITE_SYNCHRONOUS])
|
|
804
|
+
yield db
|
|
805
|
+
except sqlite3.Error as error:
|
|
806
|
+
code = getattr(error, 'sqlite_errorcode', None)
|
|
807
|
+
if isinstance(code, int) and code & 0xff in (sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED):
|
|
808
|
+
raise CoreError('storage_busy') from None
|
|
809
|
+
raise CoreError('storage_error') from None
|
|
810
|
+
finally:
|
|
811
|
+
if db is not None:
|
|
812
|
+
db.close()
|
|
813
|
+
|
|
814
|
+
@contextlib.contextmanager
|
|
815
|
+
def _tx(self):
|
|
816
|
+
with self._db() as db:
|
|
817
|
+
try:
|
|
818
|
+
db.execute('BEGIN IMMEDIATE')
|
|
819
|
+
except sqlite3.OperationalError as error:
|
|
820
|
+
code = getattr(error, 'sqlite_errorcode', None)
|
|
821
|
+
if not isinstance(code, int) or code & 0xff != sqlite3.SQLITE_BUSY:
|
|
822
|
+
raise
|
|
823
|
+
# No transaction started. Retry acquisition once without replaying work.
|
|
824
|
+
db.execute('BEGIN IMMEDIATE')
|
|
825
|
+
try:
|
|
826
|
+
yield db
|
|
827
|
+
db.execute('COMMIT')
|
|
828
|
+
except BaseException:
|
|
829
|
+
db.execute('ROLLBACK')
|
|
830
|
+
raise
|
|
831
|
+
|
|
832
|
+
@contextlib.contextmanager
|
|
833
|
+
def _lock(self, name):
|
|
834
|
+
path = self.state_dir / (name + '.lock')
|
|
835
|
+
fd = os.open(path, os.O_CREAT | os.O_RDWR | compat.O_NOFOLLOW | compat.O_BINARY, 0o600)
|
|
836
|
+
try:
|
|
837
|
+
info = os.fstat(fd)
|
|
838
|
+
if not compat.owned(info) or not compat.private(info, 0o077) or not stat.S_ISREG(info.st_mode):
|
|
839
|
+
raise CoreError('insecure_lock_file')
|
|
840
|
+
try:
|
|
841
|
+
compat.lock(fd)
|
|
842
|
+
except BlockingIOError:
|
|
843
|
+
yield False
|
|
844
|
+
else:
|
|
845
|
+
try:
|
|
846
|
+
yield True
|
|
847
|
+
finally:
|
|
848
|
+
compat.unlock(fd)
|
|
849
|
+
finally:
|
|
850
|
+
os.close(fd)
|
|
851
|
+
|
|
852
|
+
def _client(self, db, client_id):
|
|
853
|
+
row = db.execute('SELECT * FROM clients WHERE id=?', (client_id,)).fetchone()
|
|
854
|
+
if row is None:
|
|
855
|
+
raise CoreError('unknown_client')
|
|
856
|
+
if not row['active']:
|
|
857
|
+
raise CoreError('client_revoked')
|
|
858
|
+
return row
|
|
859
|
+
|
|
860
|
+
def _account(self, db):
|
|
861
|
+
row = db.execute('SELECT * FROM account WHERE singleton=1').fetchone()
|
|
862
|
+
if row is None:
|
|
863
|
+
raise CoreError('account_not_registered')
|
|
864
|
+
return row
|
|
865
|
+
|
|
866
|
+
def _binding(self, db, client_id, usable=False):
|
|
867
|
+
self._client(db, client_id)
|
|
868
|
+
row = db.execute('SELECT * FROM bindings WHERE client_id=? AND connected=1', (client_id,)).fetchone()
|
|
869
|
+
if row is None:
|
|
870
|
+
raise CoreError('not_connected')
|
|
871
|
+
if usable and row['paused']:
|
|
872
|
+
raise CoreError('connection_paused')
|
|
873
|
+
if usable and row['suspended']:
|
|
874
|
+
raise CoreError('connection_suspended')
|
|
875
|
+
return row
|
|
876
|
+
|
|
877
|
+
def register_account(self, bot_id, username):
|
|
878
|
+
if not _integer(bot_id) or bot_id <= 0 or not isinstance(username, str) or not re.fullmatch(r'[A-Za-z0-9_]{3,64}', username):
|
|
879
|
+
raise CoreError('invalid_bot_identity')
|
|
880
|
+
with self._tx() as db:
|
|
881
|
+
previous = db.execute('SELECT * FROM account WHERE singleton=1').fetchone()
|
|
882
|
+
if previous and (previous['bot_id'] != bot_id or previous['username'].lower() != username.lower()):
|
|
883
|
+
raise CoreError('account_already_registered')
|
|
884
|
+
db.execute('INSERT OR IGNORE INTO account(singleton,bot_id,username) VALUES(1,?,?)', (bot_id, username))
|
|
885
|
+
return {'bot_id': bot_id, 'username': username}
|
|
886
|
+
|
|
887
|
+
def create_client(self, label):
|
|
888
|
+
if not isinstance(label, str) or not 1 <= len(label.strip()) <= 64 or any(not c.isprintable() or c in '[]' for c in label):
|
|
889
|
+
raise CoreError('invalid_label')
|
|
890
|
+
client_id = 'agent_' + secrets.token_hex(12)
|
|
891
|
+
secret = 'aot_' + secrets.token_urlsafe(32)
|
|
892
|
+
with self._tx() as db:
|
|
893
|
+
self._account(db)
|
|
894
|
+
db.execute('INSERT INTO clients(id,label,secret_hash,created) VALUES(?,?,?,?)', (client_id, label.strip(), _digest(secret), self.clock()))
|
|
895
|
+
return {'client_id': client_id, 'client_secret': secret, 'label': label.strip()}
|
|
896
|
+
|
|
897
|
+
def authenticate(self, secret):
|
|
898
|
+
if not isinstance(secret, str) or len(secret) > 256:
|
|
899
|
+
raise CoreError('authentication_failed')
|
|
900
|
+
with self._db() as db:
|
|
901
|
+
row = db.execute('SELECT id,active FROM clients WHERE secret_hash=?', (_digest(secret),)).fetchone()
|
|
902
|
+
if row is None or not row['active']:
|
|
903
|
+
raise CoreError('authentication_failed')
|
|
904
|
+
return row['id']
|
|
905
|
+
|
|
906
|
+
def connection_begin(self, client_id):
|
|
907
|
+
now = self.clock()
|
|
908
|
+
code = secrets.token_hex(6).upper()
|
|
909
|
+
pairing_id = 'pair_' + secrets.token_hex(12)
|
|
910
|
+
with self._tx() as db:
|
|
911
|
+
self._client(db, client_id)
|
|
912
|
+
account = self._account(db)
|
|
913
|
+
if db.execute('SELECT 1 FROM bindings WHERE client_id=? AND connected=1', (client_id,)).fetchone():
|
|
914
|
+
raise CoreError('already_connected')
|
|
915
|
+
db.execute('UPDATE pairings SET consumed=1 WHERE client_id=?', (client_id,))
|
|
916
|
+
db.execute('INSERT INTO pairings(id,client_id,code_hash,expires) VALUES(?,?,?,?)', (pairing_id, client_id, _digest(code), now + self.PAIR_TTL))
|
|
917
|
+
return {'pairing_id': pairing_id, 'code': code, 'command': f'/pair@{account["username"]} {code}', 'expires_at': now + self.PAIR_TTL}
|
|
918
|
+
|
|
919
|
+
def pairing_status(self, pairing_id):
|
|
920
|
+
with self._db() as db:
|
|
921
|
+
row = db.execute('SELECT id,client_id,expires,consumed,sender_id,chat_id,thread_id,title,observed FROM pairings WHERE id=?', (pairing_id,)).fetchone()
|
|
922
|
+
if row is None:
|
|
923
|
+
raise CoreError('pairing_unavailable')
|
|
924
|
+
result = dict(row)
|
|
925
|
+
result['expired'] = row['expires'] <= self.clock()
|
|
926
|
+
return result
|
|
927
|
+
|
|
928
|
+
def confirm_pairing(self, pairing_id):
|
|
929
|
+
now = self.clock()
|
|
930
|
+
with self._tx() as db:
|
|
931
|
+
row = db.execute('SELECT * FROM pairings WHERE id=?', (pairing_id,)).fetchone()
|
|
932
|
+
if row is not None and row['consumed'] and row['sender_id'] is not None and db.execute(
|
|
933
|
+
'SELECT 1 FROM bindings WHERE client_id=? AND chat_id=? AND thread_id=? AND owner_id=? AND connected=1',
|
|
934
|
+
(row['client_id'], row['chat_id'], row['thread_id'], row['sender_id'])).fetchone():
|
|
935
|
+
# It already connected when its owner posted it.
|
|
936
|
+
return self.connection_status(row['client_id'])
|
|
937
|
+
if row is None or row['consumed'] or row['expires'] <= now:
|
|
938
|
+
raise CoreError('pairing_unavailable')
|
|
939
|
+
self._client(db, row['client_id'])
|
|
940
|
+
if row['sender_id'] is None:
|
|
941
|
+
raise CoreError('pairing_not_observed')
|
|
942
|
+
self._bind_pairing(db, row, now)
|
|
943
|
+
return self.connection_status(row['client_id'])
|
|
944
|
+
|
|
945
|
+
def _bind_pairing(self, db, row, now):
|
|
946
|
+
"""Connect an observed pairing; raises before writing when the destination is taken."""
|
|
947
|
+
if db.execute('SELECT 1 FROM bindings WHERE connected=1 AND (client_id=? OR (chat_id=? AND thread_id=?))', (row['client_id'], row['chat_id'], row['thread_id'])).fetchone():
|
|
948
|
+
raise CoreError('destination_already_bound')
|
|
949
|
+
# New connections accept media: a refused photo is easy to miss.
|
|
950
|
+
db.execute('INSERT INTO bindings(client_id,chat_id,thread_id,owner_id,title,created,accept_media) VALUES(?,?,?,?,?,?,1)', (row['client_id'], row['chat_id'], row['thread_id'], row['sender_id'], row['title'], now))
|
|
951
|
+
db.execute('INSERT INTO allowed_senders(client_id,sender_id,is_bot) VALUES(?,?,0)', (row['client_id'], row['sender_id']))
|
|
952
|
+
db.execute('UPDATE pairings SET consumed=1 WHERE id=?', (row['id'],))
|
|
953
|
+
|
|
954
|
+
def _pairing_trusted(self, db, sender_id):
|
|
955
|
+
"""Whether a pairing posted by this person connects without a local confirmation.
|
|
956
|
+
|
|
957
|
+
The pairing code is single-use, expires after ten minutes and is shown
|
|
958
|
+
only on this machine. When the bot already has connections, only one of
|
|
959
|
+
their owners may complete a pairing by posting it; a code that leaked to
|
|
960
|
+
someone else stays pending, and the local pair-confirm decides. A bot
|
|
961
|
+
with no connection yet has no owner to compare with, so the first post
|
|
962
|
+
connects and the setup result shows where.
|
|
963
|
+
"""
|
|
964
|
+
owners = {row['owner_id'] for row in db.execute('SELECT DISTINCT owner_id FROM bindings WHERE connected=1')}
|
|
965
|
+
return not owners or sender_id in owners
|
|
966
|
+
|
|
967
|
+
def allow_sender(self, client_id, sender_id, is_bot=False):
|
|
968
|
+
if not _integer(sender_id) or sender_id <= 0 or not isinstance(is_bot, bool):
|
|
969
|
+
raise CoreError('invalid_sender')
|
|
970
|
+
with self._tx() as db:
|
|
971
|
+
self._binding(db, client_id)
|
|
972
|
+
if sender_id == self._account(db)['bot_id']:
|
|
973
|
+
raise CoreError('use_broker_for_shared_bot')
|
|
974
|
+
# An explicit grant replaces an automatic one and lifts a removal.
|
|
975
|
+
db.execute('INSERT INTO allowed_senders(client_id,sender_id,is_bot) VALUES(?,?,?) ON CONFLICT(client_id,sender_id) '
|
|
976
|
+
'DO UPDATE SET is_bot=excluded.is_bot,auto_added=NULL', (client_id, sender_id, int(is_bot)))
|
|
977
|
+
db.execute('DELETE FROM blocked_senders WHERE client_id=? AND sender_id=?', (client_id, sender_id))
|
|
978
|
+
return {'sender_id': sender_id, 'is_bot': is_bot}
|
|
979
|
+
|
|
980
|
+
def remove_sender(self, client_id, sender_id):
|
|
981
|
+
"""Local operator control: stop accepting a sender, explicit or automatic.
|
|
982
|
+
|
|
983
|
+
The removal is remembered, so auto-allow does not add the sender back;
|
|
984
|
+
a later explicit allow_sender lifts it. The owner cannot be removed.
|
|
985
|
+
"""
|
|
986
|
+
if not _integer(sender_id) or sender_id <= 0:
|
|
987
|
+
raise CoreError('invalid_sender')
|
|
988
|
+
with self._tx() as db:
|
|
989
|
+
binding = self._binding(db, client_id)
|
|
990
|
+
if sender_id == binding['owner_id']:
|
|
991
|
+
raise CoreError('cannot_remove_owner')
|
|
992
|
+
removed = db.execute('DELETE FROM allowed_senders WHERE client_id=? AND sender_id=?',
|
|
993
|
+
(client_id, sender_id)).rowcount
|
|
994
|
+
db.execute('INSERT OR IGNORE INTO blocked_senders(client_id,sender_id) VALUES(?,?)', (client_id, sender_id))
|
|
995
|
+
return {'sender_id': sender_id, 'removed': bool(removed)}
|
|
996
|
+
|
|
997
|
+
# Telegram's own service accounts post on behalf of others (linked channel
|
|
998
|
+
# posts, anonymous admins), so they never become senders automatically.
|
|
999
|
+
SERVICE_SENDERS = frozenset({777000, 1087968824, 136817688})
|
|
1000
|
+
|
|
1001
|
+
def _auto_allow(self, db, binding, sender, now):
|
|
1002
|
+
"""Add a sender who posted in an auto-allow destination; True when allowed now."""
|
|
1003
|
+
sender_id = sender['id']
|
|
1004
|
+
if (not binding['auto_allow'] or sender_id in self.SERVICE_SENDERS
|
|
1005
|
+
or db.execute('SELECT 1 FROM blocked_senders WHERE client_id=? AND sender_id=?',
|
|
1006
|
+
(binding['client_id'], sender_id)).fetchone()):
|
|
1007
|
+
return False
|
|
1008
|
+
# Only a well-formed username is kept: status shows it to the owner.
|
|
1009
|
+
username = sender.get('username')
|
|
1010
|
+
username = username if isinstance(username, str) and re.fullmatch(r'[A-Za-z0-9_]{1,64}', username) else None
|
|
1011
|
+
db.execute('INSERT OR IGNORE INTO allowed_senders(client_id,sender_id,is_bot,auto_added,username) VALUES(?,?,?,?,?)',
|
|
1012
|
+
(binding['client_id'], sender_id, int(sender['is_bot']), now, username))
|
|
1013
|
+
return db.execute('SELECT 1 FROM allowed_senders WHERE client_id=? AND sender_id=? AND is_bot=?',
|
|
1014
|
+
(binding['client_id'], sender_id, int(sender['is_bot']))).fetchone() is not None
|
|
1015
|
+
|
|
1016
|
+
def configure_peer_command(self, client_id, bot_username, command):
|
|
1017
|
+
if not isinstance(bot_username, str) or not re.fullmatch(r'[A-Za-z0-9_]{3,64}', bot_username):
|
|
1018
|
+
raise CoreError('invalid_peer_command')
|
|
1019
|
+
if not isinstance(command, str) or not re.fullmatch(r'[a-z0-9_]{1,32}', command):
|
|
1020
|
+
raise CoreError('invalid_peer_command')
|
|
1021
|
+
with self._tx() as db:
|
|
1022
|
+
self._binding(db, client_id)
|
|
1023
|
+
if bot_username.lower() == self._account(db)['username'].lower():
|
|
1024
|
+
raise CoreError('use_broker_for_shared_bot')
|
|
1025
|
+
db.execute('INSERT INTO peer_commands(client_id,bot_username,command) VALUES(?,?,?) ON CONFLICT(client_id) DO UPDATE SET bot_username=excluded.bot_username,command=excluded.command', (client_id, bot_username, command))
|
|
1026
|
+
return {'bot_username': bot_username, 'command': command}
|
|
1027
|
+
|
|
1028
|
+
def bot_exchange_policy(self, client_id, sender_id, enabled=None):
|
|
1029
|
+
"""Local operator control; never exposed as an agent MCP mutation."""
|
|
1030
|
+
if not _integer(sender_id) or sender_id <= 0 or (enabled is not None and type(enabled) is not bool):
|
|
1031
|
+
raise CoreError('invalid_sender')
|
|
1032
|
+
with self._tx() as db:
|
|
1033
|
+
self._binding(db, client_id)
|
|
1034
|
+
if not db.execute('SELECT 1 FROM allowed_senders WHERE client_id=? AND sender_id=? AND is_bot=1',
|
|
1035
|
+
(client_id, sender_id)).fetchone():
|
|
1036
|
+
raise CoreError('bot_sender_not_authorized')
|
|
1037
|
+
if enabled is not None:
|
|
1038
|
+
db.execute('''INSERT INTO bot_exchange_policies VALUES(?,?,?)
|
|
1039
|
+
ON CONFLICT(client_id,sender_id) DO UPDATE SET enabled=excluded.enabled''',
|
|
1040
|
+
(client_id, sender_id, int(enabled)))
|
|
1041
|
+
# Backfill only on enablement. Disable leaves memberships already
|
|
1042
|
+
# created, and never starts enforcing a pair that has not opted in.
|
|
1043
|
+
# Never alter an existing conversation, inbox, outbox or chain counter.
|
|
1044
|
+
if enabled:
|
|
1045
|
+
db.execute('INSERT OR IGNORE INTO bot_exchange_members VALUES(?,?,?)',
|
|
1046
|
+
(f'bot:{client_id}:{sender_id}', client_id, sender_id))
|
|
1047
|
+
for admitted in db.execute('SELECT conversation_id,payload FROM inbox WHERE client_id=? AND context=0', (client_id,)).fetchall():
|
|
1048
|
+
payload = json.loads(admitted['payload'])
|
|
1049
|
+
sender = _mapping(payload.get('sender'))
|
|
1050
|
+
if payload.get('origin') == 'telegram' and sender.get('id') == sender_id and sender.get('is_bot') is True:
|
|
1051
|
+
db.execute('INSERT OR IGNORE INTO bot_exchange_members VALUES(?,?,?)',
|
|
1052
|
+
(admitted['conversation_id'], client_id, sender_id))
|
|
1053
|
+
policy = db.execute('SELECT enabled FROM bot_exchange_policies WHERE client_id=? AND sender_id=?',
|
|
1054
|
+
(client_id, sender_id)).fetchone()
|
|
1055
|
+
limits = self._limits(db)
|
|
1056
|
+
usage = self._bot_pair_usage(db, client_id, sender_id, self.clock(), limits)
|
|
1057
|
+
return {'sender_id': sender_id, 'enabled': bool(policy and policy[0]),
|
|
1058
|
+
'max_sends_per_exchange': limits['conversation_send_limit'],
|
|
1059
|
+
'conversation_send_limit': limits['conversation_send_limit'],
|
|
1060
|
+
'conversation_window_seconds': limits['conversation_window_seconds'],
|
|
1061
|
+
'pair_send_limit': limits['pair_send_limit'],
|
|
1062
|
+
'window_seconds': limits['pair_window_seconds'], 'reserved_in_window': usage[0],
|
|
1063
|
+
'retry_at': usage[1]}
|
|
1064
|
+
|
|
1065
|
+
DELIVERY_FILTERS = ('all', 'addressed')
|
|
1066
|
+
|
|
1067
|
+
def delivery_settings(self, client_id, delivery_filter=None, capture_context=None, accept_media=None,
|
|
1068
|
+
reaction_wake=None, wake_interval=None, wake_exempt=None, owner_notify=None,
|
|
1069
|
+
model_judge=None, auto_allow=None, keep_alive=None, approvals_in=None):
|
|
1070
|
+
"""Local operator control; never exposed as an agent MCP mutation.
|
|
1071
|
+
|
|
1072
|
+
``delivery_filter`` 'all' (the default) delivers every message from an
|
|
1073
|
+
allowed sender. 'addressed' delivers only messages that mention the bot,
|
|
1074
|
+
reply to it or carry a command addressed to it; the rest are kept as
|
|
1075
|
+
context. ``capture_context`` also keeps messages from senders that are not
|
|
1076
|
+
allowed, as context only. Context is never delivered, leased or announced.
|
|
1077
|
+
``accept_media`` accepts documents, photos, video, audio, voice notes and
|
|
1078
|
+
animations, with their caption as text; otherwise they stay unsupported.
|
|
1079
|
+
``reaction_wake`` decides which incoming reactions from allowed senders
|
|
1080
|
+
are delivered and can wake this agent: 'own_messages' (the default) only
|
|
1081
|
+
reactions on messages this agent published, 'all' every reaction, 'none'
|
|
1082
|
+
none; the rest are kept as context. The delivery filter does not apply to
|
|
1083
|
+
reactions, which target one message already. A new connection accepts
|
|
1084
|
+
media; connections made before that default keep their setting. With
|
|
1085
|
+
media off, a media message from an allowed sender is still delivered,
|
|
1086
|
+
with its caption and a ``media_refused`` list of kinds instead of the
|
|
1087
|
+
attachments. ``wake_interval`` batches notices: after one, the next waits
|
|
1088
|
+
this many seconds and then covers everything that arrived meanwhile; 0
|
|
1089
|
+
(the default) announces each delivery at once. Deliveries still queue
|
|
1090
|
+
immediately and can always be polled. ``wake_exempt`` names what is
|
|
1091
|
+
announced at once anyway: 'addressed,owner' (the default) for messages
|
|
1092
|
+
that address the bot and messages from the owner, 'addressed', 'owner'
|
|
1093
|
+
or 'none'. ``owner_notify`` lets the agent send private notices to
|
|
1094
|
+
the owner with the owner_notify tool; it is off until the owner turns
|
|
1095
|
+
it on. ``model_judge`` asks a decision model whether a person's message
|
|
1096
|
+
that the addressed filter kept as context is meant for this agent, and
|
|
1097
|
+
delivers it when the model says yes. It needs a configured model
|
|
1098
|
+
(``aot judge-config set``), applies only with the addressed filter, and
|
|
1099
|
+
is off until the owner turns it on. ``auto_allow`` adds every person and
|
|
1100
|
+
bot who posts in the destination to the allowed senders the first time
|
|
1101
|
+
AOT sees them, for groups where everyone is trusted; it is off until the
|
|
1102
|
+
owner turns it on, and turning it off keeps the senders added so far.
|
|
1103
|
+
``keep_alive`` lets Claude Code's idle-session waiter wake the session
|
|
1104
|
+
once when its time limit ends, so a new waiter starts; it costs one short
|
|
1105
|
+
turn per idle day and is off until the owner turns it on.
|
|
1106
|
+
``approvals_in`` is where owner approvals are asked: 'private' (the
|
|
1107
|
+
default) in the owner's private chat, or 'group' in the bound group as
|
|
1108
|
+
an ephemeral message only the owner sees, with the private chat as the
|
|
1109
|
+
fallback when that send fails.
|
|
1110
|
+
The other settings default to the original behavior.
|
|
1111
|
+
"""
|
|
1112
|
+
changes = {'delivery_filter': delivery_filter, 'capture_context': capture_context,
|
|
1113
|
+
'accept_media': accept_media, 'reaction_wake': reaction_wake,
|
|
1114
|
+
'wake_interval': wake_interval, 'wake_exempt': wake_exempt,
|
|
1115
|
+
'owner_notify': owner_notify, 'model_judge': model_judge, 'auto_allow': auto_allow,
|
|
1116
|
+
'keep_alive': keep_alive, 'approvals_in': approvals_in}
|
|
1117
|
+
self._check_delivery_settings(changes)
|
|
1118
|
+
with self._tx() as db:
|
|
1119
|
+
self._binding(db, client_id)
|
|
1120
|
+
self._write_delivery_settings(db, client_id, changes)
|
|
1121
|
+
row = self._binding(db, client_id)
|
|
1122
|
+
return self._delivery_settings_view(row)
|
|
1123
|
+
|
|
1124
|
+
APPROVALS_IN = ('private', 'group')
|
|
1125
|
+
_BOOL_SETTINGS = ('capture_context', 'accept_media', 'owner_notify', 'model_judge', 'auto_allow', 'keep_alive')
|
|
1126
|
+
|
|
1127
|
+
def _check_delivery_settings(self, changes):
|
|
1128
|
+
if set(changes) - {'delivery_filter', 'reaction_wake', 'wake_interval', 'wake_exempt', 'approvals_in',
|
|
1129
|
+
*self._BOOL_SETTINGS}:
|
|
1130
|
+
raise CoreError('invalid_delivery_settings')
|
|
1131
|
+
value = changes.get('approvals_in')
|
|
1132
|
+
if value is not None and value not in self.APPROVALS_IN:
|
|
1133
|
+
raise CoreError('invalid_delivery_settings')
|
|
1134
|
+
value = changes.get('delivery_filter')
|
|
1135
|
+
if value is not None and value not in self.DELIVERY_FILTERS:
|
|
1136
|
+
raise CoreError('invalid_delivery_settings')
|
|
1137
|
+
if any(changes.get(name) is not None and type(changes[name]) is not bool for name in self._BOOL_SETTINGS):
|
|
1138
|
+
raise CoreError('invalid_delivery_settings')
|
|
1139
|
+
value = changes.get('reaction_wake')
|
|
1140
|
+
if value is not None and value not in self.REACTION_WAKE_MODES:
|
|
1141
|
+
raise CoreError('invalid_delivery_settings')
|
|
1142
|
+
value = changes.get('wake_interval')
|
|
1143
|
+
if value is not None and (not _integer(value) or not 0 <= value <= self.WAKE_INTERVAL_MAX):
|
|
1144
|
+
raise CoreError('invalid_delivery_settings')
|
|
1145
|
+
value = changes.get('wake_exempt')
|
|
1146
|
+
if value is not None and value not in self.WAKE_EXEMPT_MODES:
|
|
1147
|
+
raise CoreError('invalid_delivery_settings')
|
|
1148
|
+
|
|
1149
|
+
@staticmethod
|
|
1150
|
+
def _write_delivery_settings(db, client_id, changes):
|
|
1151
|
+
# Column names come from the fixed list checked above, never from input.
|
|
1152
|
+
for name, value in changes.items():
|
|
1153
|
+
if value is not None:
|
|
1154
|
+
db.execute(f'UPDATE bindings SET {name}=? WHERE client_id=? AND connected=1',
|
|
1155
|
+
(int(value) if type(value) is bool else value, client_id))
|
|
1156
|
+
|
|
1157
|
+
def _delivery_settings_view(self, row):
|
|
1158
|
+
return {'delivery_filter': row['delivery_filter'], 'capture_context': bool(row['capture_context']),
|
|
1159
|
+
'accept_media': bool(row['accept_media']), 'reaction_wake': row['reaction_wake'],
|
|
1160
|
+
'wake_interval': row['wake_interval'], 'wake_exempt': row['wake_exempt'],
|
|
1161
|
+
'owner_notify': bool(row['owner_notify']), 'model_judge': bool(row['model_judge']),
|
|
1162
|
+
'auto_allow': bool(row['auto_allow']), 'keep_alive': bool(row['keep_alive']),
|
|
1163
|
+
'approvals_in': row['approvals_in'], 'context_window_seconds': self.HISTORY_WINDOW}
|
|
1164
|
+
|
|
1165
|
+
def _limits(self, db):
|
|
1166
|
+
row = db.execute('SELECT * FROM exchange_limits WHERE singleton=1').fetchone()
|
|
1167
|
+
if row is None:
|
|
1168
|
+
return {'conversation_send_limit': self.CONVERSATION_SEND_LIMIT,
|
|
1169
|
+
'conversation_window_seconds': self.CONVERSATION_WINDOW,
|
|
1170
|
+
'client_send_limit': self.CLIENT_SEND_LIMIT,
|
|
1171
|
+
'client_window_seconds': self.CLIENT_WINDOW,
|
|
1172
|
+
'pair_send_limit': self.BOT_PAIR_SEND_LIMIT,
|
|
1173
|
+
'pair_window_seconds': self.BOT_PAIR_WINDOW, 'source': 'default'}
|
|
1174
|
+
return {'conversation_send_limit': row['conversation_send_limit'],
|
|
1175
|
+
'conversation_window_seconds': row['conversation_window'],
|
|
1176
|
+
'client_send_limit': row['client_send_limit'] or self.CLIENT_SEND_LIMIT,
|
|
1177
|
+
'client_window_seconds': row['client_window'] or self.CLIENT_WINDOW,
|
|
1178
|
+
'pair_send_limit': row['pair_send_limit'],
|
|
1179
|
+
'pair_window_seconds': row['pair_window'], 'source': 'operator',
|
|
1180
|
+
'updated_at': row['updated'], 'reason': row['reason']}
|
|
1181
|
+
|
|
1182
|
+
def exchange_limits(self, *, conversation_send_limit=None, conversation_window_seconds=None,
|
|
1183
|
+
client_send_limit=None, client_window_seconds=None,
|
|
1184
|
+
pair_send_limit=None, pair_window_seconds=None, reset=False, reason=None):
|
|
1185
|
+
"""Inspect or change the rolling send limits through the local operator CLI.
|
|
1186
|
+
|
|
1187
|
+
The values live in the shared state, so every agent process using this
|
|
1188
|
+
bot applies the same limits. No MCP tool can change them.
|
|
1189
|
+
"""
|
|
1190
|
+
values = {'conversation_send_limit': (conversation_send_limit, self.SEND_LIMIT_RANGE),
|
|
1191
|
+
'conversation_window_seconds': (conversation_window_seconds, self.WINDOW_RANGE),
|
|
1192
|
+
'client_send_limit': (client_send_limit, self.SEND_LIMIT_RANGE),
|
|
1193
|
+
'client_window_seconds': (client_window_seconds, self.WINDOW_RANGE),
|
|
1194
|
+
'pair_send_limit': (pair_send_limit, self.SEND_LIMIT_RANGE),
|
|
1195
|
+
'pair_window_seconds': (pair_window_seconds, self.WINDOW_RANGE)}
|
|
1196
|
+
changing = reset or any(value is not None for value, _ in values.values())
|
|
1197
|
+
for value, (low, high) in values.values():
|
|
1198
|
+
if value is not None and (not _integer(value) or not low <= value <= high):
|
|
1199
|
+
raise CoreError('invalid_exchange_limits')
|
|
1200
|
+
if reset and any(value is not None for value, _ in values.values()):
|
|
1201
|
+
raise CoreError('invalid_exchange_limits')
|
|
1202
|
+
if changing and (not isinstance(reason, str) or not 1 <= len(reason.strip()) <= 500):
|
|
1203
|
+
raise CoreError('invalid_exchange_limits')
|
|
1204
|
+
if not changing and reason is not None:
|
|
1205
|
+
raise CoreError('invalid_exchange_limits')
|
|
1206
|
+
with self._tx() as db:
|
|
1207
|
+
if reset:
|
|
1208
|
+
db.execute('DELETE FROM exchange_limits')
|
|
1209
|
+
elif changing:
|
|
1210
|
+
current = self._limits(db)
|
|
1211
|
+
merged = {key: value if value is not None else current[key]
|
|
1212
|
+
for key, (value, _) in values.items()}
|
|
1213
|
+
db.execute('INSERT INTO exchange_limits(singleton,conversation_send_limit,conversation_window,'
|
|
1214
|
+
'pair_send_limit,pair_window,updated,reason,client_send_limit,client_window) '
|
|
1215
|
+
'VALUES(1,?,?,?,?,?,?,?,?) ON CONFLICT(singleton) DO UPDATE SET '
|
|
1216
|
+
'conversation_send_limit=excluded.conversation_send_limit,'
|
|
1217
|
+
'conversation_window=excluded.conversation_window,'
|
|
1218
|
+
'pair_send_limit=excluded.pair_send_limit,pair_window=excluded.pair_window,'
|
|
1219
|
+
'updated=excluded.updated,reason=excluded.reason,'
|
|
1220
|
+
'client_send_limit=excluded.client_send_limit,client_window=excluded.client_window',
|
|
1221
|
+
(merged['conversation_send_limit'], merged['conversation_window_seconds'],
|
|
1222
|
+
merged['pair_send_limit'], merged['pair_window_seconds'],
|
|
1223
|
+
self.clock(), reason.strip(),
|
|
1224
|
+
merged['client_send_limit'], merged['client_window_seconds']))
|
|
1225
|
+
return self._limits(db)
|
|
1226
|
+
|
|
1227
|
+
@staticmethod
|
|
1228
|
+
def _window_usage(stamps, limit, window):
|
|
1229
|
+
"""Count reservations in a rolling window, newest first.
|
|
1230
|
+
|
|
1231
|
+
Returns the count and, when the window is full, the time the newest
|
|
1232
|
+
limit-th reservation expires so that one more send fits.
|
|
1233
|
+
"""
|
|
1234
|
+
return len(stamps), (stamps[limit - 1] + window if len(stamps) >= limit else None)
|
|
1235
|
+
|
|
1236
|
+
def _bot_pair_usage(self, db, client_id, sender_id, now, limits):
|
|
1237
|
+
window = limits['pair_window_seconds']
|
|
1238
|
+
stamps = [r[0] for r in db.execute('''SELECT o.created FROM bot_exchange_members p
|
|
1239
|
+
JOIN outbox o ON o.conversation_id=p.conversation_id
|
|
1240
|
+
WHERE p.client_id=? AND p.sender_id=? AND o.created>?
|
|
1241
|
+
ORDER BY o.created DESC''',
|
|
1242
|
+
(client_id, sender_id, now - window))]
|
|
1243
|
+
return self._window_usage(stamps, limits['pair_send_limit'], window)
|
|
1244
|
+
|
|
1245
|
+
def _conversation_usage(self, db, conversation_id, now, limit, limits):
|
|
1246
|
+
window = limits['conversation_window_seconds']
|
|
1247
|
+
# A message from the owner in this conversation starts its window again:
|
|
1248
|
+
# sends before it no longer count toward this conversation's limit.
|
|
1249
|
+
# A send at the same instant as the owner's message still counts.
|
|
1250
|
+
row = db.execute('SELECT window_reset_at FROM conversations WHERE id=?', (conversation_id,)).fetchone()
|
|
1251
|
+
reset_at = row[0] if row and row[0] is not None else None
|
|
1252
|
+
stamps = [r[0] for r in db.execute(
|
|
1253
|
+
'SELECT created FROM outbox WHERE conversation_id=? AND created>? AND created>=? ORDER BY created DESC',
|
|
1254
|
+
(conversation_id, now - window, reset_at if reset_at is not None else now - window))]
|
|
1255
|
+
return self._window_usage(stamps, limit, window)
|
|
1256
|
+
|
|
1257
|
+
def _client_usage(self, db, client_id, now, limits):
|
|
1258
|
+
window = limits['client_window_seconds']
|
|
1259
|
+
stamps = [r[0] for r in db.execute(
|
|
1260
|
+
'SELECT created FROM outbox WHERE client_id=? AND created>? ORDER BY created DESC',
|
|
1261
|
+
(client_id, now - window))]
|
|
1262
|
+
return self._window_usage(stamps, limits['client_send_limit'], window)
|
|
1263
|
+
|
|
1264
|
+
@staticmethod
|
|
1265
|
+
def _limit_error(code, used, limit, window, retry_at, now):
|
|
1266
|
+
return CoreError(code, details={
|
|
1267
|
+
'sent_in_window': used, 'limit': limit, 'window_seconds': window,
|
|
1268
|
+
'retry_at': retry_at, 'retry_after_seconds': max(0, math.ceil(retry_at - now))})
|
|
1269
|
+
|
|
1270
|
+
def unassigned(self, limit=20):
|
|
1271
|
+
if not _integer(limit) or not 1 <= limit <= self.UNMATCHED_LIMIT:
|
|
1272
|
+
raise CoreError('invalid_unassigned_limit')
|
|
1273
|
+
with self._db() as db:
|
|
1274
|
+
return {'updates': [dict(row) for row in db.execute('SELECT update_id,chat_id,reason,created FROM unmatched ORDER BY update_id DESC LIMIT ?', (limit,))]}
|
|
1275
|
+
|
|
1276
|
+
def grant_peer(self, source_client_id, target_client_id):
|
|
1277
|
+
if source_client_id == target_client_id:
|
|
1278
|
+
raise CoreError('invalid_peer')
|
|
1279
|
+
with self._tx() as db:
|
|
1280
|
+
self._binding(db, source_client_id)
|
|
1281
|
+
self._binding(db, target_client_id)
|
|
1282
|
+
db.execute('INSERT OR IGNORE INTO grants(source,target) VALUES(?,?)', (source_client_id, target_client_id))
|
|
1283
|
+
return {'source': source_client_id, 'target': target_client_id}
|
|
1284
|
+
|
|
1285
|
+
def accounts_status(self, client_id=None):
|
|
1286
|
+
with self._db() as db:
|
|
1287
|
+
if client_id is not None:
|
|
1288
|
+
self._client(db, client_id)
|
|
1289
|
+
account = self._account(db)
|
|
1290
|
+
return {'accounts': [{'bot_id': account['bot_id'], 'username': account['username'], 'last_intake_at': account['last_intake'], 'intake_error': account['intake_error'], 'last_gap_at': account['last_gap_at'], 'possible_offline_gap': account['last_gap_at'] is not None or (account['last_intake'] is not None and self.clock() - account['last_intake'] >= 86400)}]}
|
|
1291
|
+
|
|
1292
|
+
def connection_status(self, client_id):
|
|
1293
|
+
"""Read scoped connection facts and fixed guidance without intake or writes."""
|
|
1294
|
+
now = self.clock()
|
|
1295
|
+
with self._db() as db:
|
|
1296
|
+
client = self._client(db, client_id)
|
|
1297
|
+
account = self._account(db)
|
|
1298
|
+
row = db.execute('SELECT * FROM bindings WHERE client_id=? AND connected=1', (client_id,)).fetchone()
|
|
1299
|
+
pairing = db.execute('SELECT id,expires,sender_id,chat_id,thread_id,title FROM pairings WHERE client_id=? AND consumed=0 AND expires>? ORDER BY expires DESC LIMIT 1', (client_id, now)).fetchone()
|
|
1300
|
+
pending = db.execute('SELECT count(*) FROM inbox WHERE client_id=? AND acknowledged=0', (client_id,)).fetchone()[0]
|
|
1301
|
+
kept = self._queue_full_kept(db, client_id)
|
|
1302
|
+
counts = {r['status']: r['n'] for r in db.execute('SELECT status,count(*) n FROM outbox WHERE client_id=? GROUP BY status', (client_id,))}
|
|
1303
|
+
peers = [dict(r) for r in db.execute('SELECT c.id AS client_id,c.label FROM grants g JOIN clients c ON c.id=g.target WHERE g.source=? AND c.active=1', (client_id,))]
|
|
1304
|
+
senders = [{'sender_id': r['sender_id'], 'is_bot': bool(r['is_bot'])}
|
|
1305
|
+
| ({'auto_added': r['auto_added'], 'username': r['username']} if r['auto_added'] is not None else {})
|
|
1306
|
+
for r in db.execute('SELECT sender_id,is_bot,auto_added,username FROM allowed_senders '
|
|
1307
|
+
'WHERE client_id=? ORDER BY sender_id', (client_id,))]
|
|
1308
|
+
approvals = [dict(r) for r in db.execute(
|
|
1309
|
+
"SELECT id AS approval_id,action,CASE WHEN status='pending' AND expires<=? THEN 'expired' ELSE status END AS status,"
|
|
1310
|
+
'error,created,expires AS expires_at,decided FROM owner_approvals WHERE client_id=? ORDER BY created DESC LIMIT 5',
|
|
1311
|
+
(now, client_id))]
|
|
1312
|
+
gap = account['last_gap_at'] is not None or (account['last_intake'] is not None and now - account['last_intake'] >= self.HISTORY_WINDOW)
|
|
1313
|
+
from .relay import WAIT_FOR_DESKTOP_WAKE, unresolved_wakes
|
|
1314
|
+
held = unresolved_wakes(db, now, client_id)
|
|
1315
|
+
held_wake = {key: held[0][key] for key in ('notification_id', 'status', 'since', 'age_seconds',
|
|
1316
|
+
'attempt', 'handoff_phase', 'wake_attempts',
|
|
1317
|
+
'next_action')} if held else None
|
|
1318
|
+
if row is None:
|
|
1319
|
+
if pairing is None:
|
|
1320
|
+
state, action = 'unpaired', 'begin_pairing'
|
|
1321
|
+
message = "Connect this agent to a Telegram group or topic using the owner's existing shared bot."
|
|
1322
|
+
elif pairing['sender_id'] is None:
|
|
1323
|
+
state, action = 'pair_pending', 'send_pairing_command'
|
|
1324
|
+
message = ('Send the pairing command from connection setup in the chosen Telegram group or topic. '
|
|
1325
|
+
'It connects as soon as AOT collects it, when the bot has no owner yet or its owner sends it.')
|
|
1326
|
+
else:
|
|
1327
|
+
state, action = 'pair_pending', 'confirm_pairing'
|
|
1328
|
+
message = ('Someone who does not own this bot\'s connections sent the pairing command, or its '
|
|
1329
|
+
'destination is taken. Review the observed sender, group and topic locally, then confirm pairing.')
|
|
1330
|
+
elif row['suspended']:
|
|
1331
|
+
state, action = 'suspended', 'review_connection'
|
|
1332
|
+
if row['suspended'].startswith('group_migrated:'):
|
|
1333
|
+
message = ('This group moved to a new chat id. Queued messages are kept. Ask the local owner to '
|
|
1334
|
+
'run "aot unsuspend" on this computer to move the connection to the new chat.')
|
|
1335
|
+
elif row['suspended'] == 'topic_changed':
|
|
1336
|
+
message = ('This topic was closed or changed. Queued messages are kept. After the topic is open, '
|
|
1337
|
+
'ask the local owner to run "aot unsuspend --topic-open" on this computer.')
|
|
1338
|
+
else:
|
|
1339
|
+
message = ('The bot was removed or restricted in this group. Queued messages are kept. After the bot '
|
|
1340
|
+
'can post there again, ask the local owner to run "aot unsuspend" on this computer.')
|
|
1341
|
+
elif row['paused']:
|
|
1342
|
+
state, action = 'paused', 'resume_connection'
|
|
1343
|
+
message = 'Resume this connection when you want to handle messages again; queued work is preserved.'
|
|
1344
|
+
else:
|
|
1345
|
+
state = 'connected'
|
|
1346
|
+
if counts.get('unknown', 0):
|
|
1347
|
+
action = 'review_unknown_delivery'
|
|
1348
|
+
message = 'Review the uncertain outgoing delivery locally before attempting to resend it.'
|
|
1349
|
+
elif account['intake_error']:
|
|
1350
|
+
action = 'review_intake'
|
|
1351
|
+
message = 'Ask the local owner to review the intake error; already captured messages remain available.'
|
|
1352
|
+
elif held_wake and held_wake['next_action'] == WAIT_FOR_DESKTOP_WAKE:
|
|
1353
|
+
action = WAIT_FOR_DESKTOP_WAKE
|
|
1354
|
+
message = ('A wake for this agent is queued in the desktop app but has not opened yet, so no new '
|
|
1355
|
+
'wakes are sent. A running listener retries it while the desktop is open and this '
|
|
1356
|
+
'connection is active; nobody needs to resolve it. If no listener is running, ask the '
|
|
1357
|
+
'local owner to start one. Pending messages can still be polled.')
|
|
1358
|
+
elif held_wake:
|
|
1359
|
+
action = held_wake['next_action']
|
|
1360
|
+
message = ('An automatic wake for this agent has been unresolved for a long time, so no new '
|
|
1361
|
+
'wakes are sent. Ask the local owner to review it. Pending messages can still be polled.')
|
|
1362
|
+
elif pending:
|
|
1363
|
+
action = 'poll_messages'
|
|
1364
|
+
message = 'Check the inbox to handle pending messages, then acknowledge only completed work.'
|
|
1365
|
+
if kept:
|
|
1366
|
+
message += (f' Your queue reached its limit, so {kept} newer messages were kept in history '
|
|
1367
|
+
'only; read them with messages_history after the pending ones.')
|
|
1368
|
+
elif gap:
|
|
1369
|
+
action = 'review_gap'
|
|
1370
|
+
message = 'Captured history may have a gap. Check for new messages when ready and allow for missing context.'
|
|
1371
|
+
else:
|
|
1372
|
+
action = 'check_messages'
|
|
1373
|
+
message = 'Check for new messages when ready. For automatic wakeups, ask to listen for Telegram in this chat for a chosen duration; listener status is not checked here.'
|
|
1374
|
+
return {
|
|
1375
|
+
'client_id': client_id, 'label': client['label'],
|
|
1376
|
+
'connected': row is not None, 'paused': bool(row['paused']) if row else False,
|
|
1377
|
+
'suspended': row['suspended'] if row else None,
|
|
1378
|
+
'destination': {'chat_id': row['chat_id'], 'thread_id': row['thread_id'] or None,
|
|
1379
|
+
'title': row['title'], 'owner_id': row['owner_id']} if row else None,
|
|
1380
|
+
'pairing': dict(pairing) if pairing else None, 'pending_messages': pending,
|
|
1381
|
+
'queue_full_kept': kept,
|
|
1382
|
+
'outbox': counts, 'permitted_peers': peers,
|
|
1383
|
+
'bot': {'id': account['bot_id'], 'username': account['username']},
|
|
1384
|
+
'allowed_senders': senders,
|
|
1385
|
+
'owner_approvals': approvals,
|
|
1386
|
+
'intake': {'last_success_at': account['last_intake'], 'last_attempt_at': account['last_attempt'],
|
|
1387
|
+
'error': account['intake_error'], 'last_gap_at': account['last_gap_at'],
|
|
1388
|
+
'possible_offline_gap': bool(gap)},
|
|
1389
|
+
'collector': self.collector_status(db),
|
|
1390
|
+
'delivery': {'mode': 'on_demand', 'automatic': False, 'scope': 'inbox_core',
|
|
1391
|
+
'listener_status': 'not_checked'},
|
|
1392
|
+
'unresolved_wake': held_wake,
|
|
1393
|
+
'history': {'window_hours': self.HISTORY_WINDOW // 3600, 'kind': 'captured_only'},
|
|
1394
|
+
'routing': {'delivery_filter': row['delivery_filter'],
|
|
1395
|
+
'capture_context': bool(row['capture_context']),
|
|
1396
|
+
'accept_media': bool(row['accept_media']),
|
|
1397
|
+
'wake_interval': row['wake_interval'],
|
|
1398
|
+
'wake_exempt': row['wake_exempt'],
|
|
1399
|
+
'owner_notify': bool(row['owner_notify']),
|
|
1400
|
+
'model_judge': bool(row['model_judge']),
|
|
1401
|
+
'auto_allow': bool(row['auto_allow']),
|
|
1402
|
+
'keep_alive': bool(row['keep_alive']),
|
|
1403
|
+
'approvals_in': row['approvals_in']} if row else None,
|
|
1404
|
+
'reactions': self._reaction_capability(row) if row else None,
|
|
1405
|
+
'state': state, 'next_action': {'code': action, 'message': message},
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
@staticmethod
|
|
1409
|
+
def _reaction_capability(row):
|
|
1410
|
+
"""Read-only reaction facts: only local, already-recorded state."""
|
|
1411
|
+
if row['bot_admin'] is None:
|
|
1412
|
+
receive = {'available': None, 'bot_admin': None, 'requires_bot_admin': True,
|
|
1413
|
+
'note': "The bot's administrator status in this destination is not known yet; the next collection checks it."}
|
|
1414
|
+
elif row['bot_admin']:
|
|
1415
|
+
receive = {'available': True, 'bot_admin': True, 'requires_bot_admin': True,
|
|
1416
|
+
'note': 'Reaction updates arrive while the shared bot stays an administrator in this destination.'}
|
|
1417
|
+
else:
|
|
1418
|
+
receive = {'available': False, 'bot_admin': False, 'requires_bot_admin': True,
|
|
1419
|
+
'note': 'The shared bot is not an administrator in this destination, so reactions from people never arrive. Ask the local owner to promote it to administrator. Collection checks this again about once an hour.'}
|
|
1420
|
+
return {'send': {'per_message': 1,
|
|
1421
|
+
'emoji': "one standard reaction emoji Telegram allows for bots, or an empty emoji to remove the bot's reaction",
|
|
1422
|
+
'note': 'Bots cannot use paid reactions, and this tool never sends custom emoji reactions.'},
|
|
1423
|
+
'receive': receive, 'wake': row['reaction_wake']}
|
|
1424
|
+
|
|
1425
|
+
BOT_ADMIN_RETRY = 600
|
|
1426
|
+
# A known flag is checked again this often: a missed my_chat_member update
|
|
1427
|
+
# (for example one consumed by an older runtime) must not leave it stale.
|
|
1428
|
+
BOT_ADMIN_RECHECK = 3600
|
|
1429
|
+
|
|
1430
|
+
# The owner hears about a full queue at most this often per agent.
|
|
1431
|
+
QUEUE_FULL_NOTICE_INTERVAL = 86400
|
|
1432
|
+
QUEUE_FULL_NOTICE_KEY = 'aot-queue-full:'
|
|
1433
|
+
|
|
1434
|
+
def _queue_full_notice(self, db, client_id, pending, now):
|
|
1435
|
+
"""Tell the owner privately that this agent's queue is full; at most once a day.
|
|
1436
|
+
|
|
1437
|
+
The agent may not be running at all, which is often why its queue
|
|
1438
|
+
filled, so the owner is the one who can act. This is the runtime's own
|
|
1439
|
+
notice, not the agent's, so the agent's owner_notify setting does not
|
|
1440
|
+
apply; it still needs the owner to have started a private chat with
|
|
1441
|
+
the bot, like every owner notice.
|
|
1442
|
+
"""
|
|
1443
|
+
if db.execute('SELECT 1 FROM owner_outbox WHERE client_id=? AND idempotency_key LIKE ? AND created>?',
|
|
1444
|
+
(client_id, self.QUEUE_FULL_NOTICE_KEY + '%', now - self.QUEUE_FULL_NOTICE_INTERVAL)).fetchone():
|
|
1445
|
+
return
|
|
1446
|
+
binding = db.execute('SELECT owner_id,title FROM bindings WHERE client_id=? AND connected=1',
|
|
1447
|
+
(client_id,)).fetchone()
|
|
1448
|
+
if binding is None or binding['owner_id'] is None:
|
|
1449
|
+
return
|
|
1450
|
+
label = db.execute('SELECT label FROM clients WHERE id=?', (client_id,)).fetchone()['label']
|
|
1451
|
+
title = ' '.join(str(binding['title']).split())
|
|
1452
|
+
text = (f'[Agents over Telegram | {title}]\n'
|
|
1453
|
+
f'The agent "{label}" has reached its limit of {pending} unread messages. New messages for it are '
|
|
1454
|
+
'kept in its history only, and it is not told about them. Start the agent so it handles '
|
|
1455
|
+
'them, or disconnect it if it is no longer used. This notice repeats at most once a day.')
|
|
1456
|
+
key = self.QUEUE_FULL_NOTICE_KEY + str(int(now))
|
|
1457
|
+
db.execute("INSERT INTO owner_outbox(id,client_id,owner_id,text,idempotency_key,request_hash,status,"
|
|
1458
|
+
"created,updated,due) VALUES(?,?,?,?,?,?,'queued',?,?,?)",
|
|
1459
|
+
('owner_' + secrets.token_hex(12), client_id, binding['owner_id'], text, key,
|
|
1460
|
+
_digest(json.dumps([text])), now, now, now))
|
|
1461
|
+
|
|
1462
|
+
def _send_queue_full_notices(self):
|
|
1463
|
+
"""Send queued full-queue notices from the collector.
|
|
1464
|
+
|
|
1465
|
+
Other owner notices go out with their agent's own tool calls, but an
|
|
1466
|
+
agent whose queue filled is often not running, so the collector sends
|
|
1467
|
+
these itself.
|
|
1468
|
+
"""
|
|
1469
|
+
with self._db() as db:
|
|
1470
|
+
notes = db.execute("SELECT id FROM owner_outbox WHERE status='queued' AND due<=? AND idempotency_key LIKE ? "
|
|
1471
|
+
'ORDER BY created,rowid LIMIT 5', (self.clock(), self.QUEUE_FULL_NOTICE_KEY + '%')).fetchall()
|
|
1472
|
+
if not notes:
|
|
1473
|
+
return
|
|
1474
|
+
with self._lock('sender') as acquired:
|
|
1475
|
+
if acquired:
|
|
1476
|
+
self._flush_owner_notes(notes)
|
|
1477
|
+
|
|
1478
|
+
def _queue_full_kept(self, db, client_id):
|
|
1479
|
+
"""How many messages kept as context for a full queue the agent has not read in history yet."""
|
|
1480
|
+
return db.execute("SELECT count(*) FROM inbox WHERE client_id=? AND context=1 "
|
|
1481
|
+
"AND json_extract(payload,'$.context_reason')='queue_full' AND queue_full_read IS NULL",
|
|
1482
|
+
(client_id,)).fetchone()[0]
|
|
1483
|
+
|
|
1484
|
+
def _unmatched(self, db, update_id, chat_id, reason, now):
|
|
1485
|
+
db.execute('INSERT OR IGNORE INTO unmatched(update_id,chat_id,reason,created) VALUES(?,?,?,?)', (update_id, chat_id, reason, now))
|
|
1486
|
+
db.execute('DELETE FROM unmatched WHERE update_id NOT IN (SELECT update_id FROM unmatched ORDER BY update_id DESC LIMIT ?)', (self.UNMATCHED_LIMIT,))
|
|
1487
|
+
|
|
1488
|
+
def _enqueue(self, db, client_id, event_key, payload, conversation_id, now, outbox_id=None, event_at=None,
|
|
1489
|
+
*, overflow='context'):
|
|
1490
|
+
if db.execute('SELECT 1 FROM inbox WHERE client_id=? AND event_key=?', (client_id, event_key)).fetchone():
|
|
1491
|
+
return
|
|
1492
|
+
count = db.execute('SELECT count(*) FROM inbox WHERE client_id=? AND acknowledged=0', (client_id,)).fetchone()[0]
|
|
1493
|
+
# The owner's own answers (a button press, a reply to a notice, an
|
|
1494
|
+
# approval outcome) are rare and already confirmed to the owner, so
|
|
1495
|
+
# they always reach the agent; the bound is for group traffic.
|
|
1496
|
+
if count >= self.queue_limit and not payload.get('owner_notice'):
|
|
1497
|
+
if overflow == 'raise':
|
|
1498
|
+
raise CoreError('queue_full')
|
|
1499
|
+
# Telegram intake routes one page for every agent on the bot in one
|
|
1500
|
+
# transaction. Raising here would roll the page back for all of
|
|
1501
|
+
# them and stall intake until this agent drains its queue, while
|
|
1502
|
+
# Telegram drops what it holds after 24 hours. So the overflow is
|
|
1503
|
+
# kept as context instead: history still has it, and the collector
|
|
1504
|
+
# moves on.
|
|
1505
|
+
self._keep_context(db, client_id, event_key, {**payload, 'context_reason': 'queue_full'},
|
|
1506
|
+
conversation_id, now, now if event_at is None else event_at)
|
|
1507
|
+
self._overflowed += 1
|
|
1508
|
+
self._queue_full_notice(db, client_id, count, now)
|
|
1509
|
+
return
|
|
1510
|
+
keys = _telegram_message_keys(payload) or (None, None)
|
|
1511
|
+
db.execute('INSERT INTO inbox(id,client_id,event_key,payload,created,conversation_id,outbox_id,event_at,tg_chat_id,tg_message_id) VALUES(?,?,?,?,?,?,?,?,?,?)', ('msg_' + secrets.token_hex(12), client_id, event_key, json.dumps(payload, ensure_ascii=False), now, conversation_id, outbox_id, now if event_at is None else event_at, *keys))
|
|
1512
|
+
|
|
1513
|
+
# A new suspension never replaces a reason that needs more owner work.
|
|
1514
|
+
# Clearing topic_changed also checks bot membership, and a migration
|
|
1515
|
+
# cannot be cleared at all, so keep the strongest observed reason.
|
|
1516
|
+
_SUSPEND_OVER = {
|
|
1517
|
+
'bot_removed_or_restricted': "(suspended IS NULL OR suspended='bot_removed_or_restricted')",
|
|
1518
|
+
'topic_changed': "(suspended IS NULL OR suspended IN ('bot_removed_or_restricted','topic_changed'))",
|
|
1519
|
+
'group_migrated': "(suspended IS NULL OR suspended NOT LIKE 'group_migrated:%')",
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
def _suspend(self, db, reason, chat_id, thread_id=None):
|
|
1523
|
+
# Every observed event bumps suspension_seq, even with the same reason,
|
|
1524
|
+
# so an owner clear that raced with it cannot erase it.
|
|
1525
|
+
guard = self._SUSPEND_OVER[reason.split(':')[0]]
|
|
1526
|
+
scope = 'chat_id=? AND (? IS NULL OR thread_id=?) AND connected=1'
|
|
1527
|
+
# Bindings that keep a stronger reason still get a new seq. Run this
|
|
1528
|
+
# first so each binding moves exactly once.
|
|
1529
|
+
db.execute(f'UPDATE bindings SET suspension_seq=suspension_seq+1 WHERE {scope} AND suspended IS NOT NULL AND NOT {guard}',
|
|
1530
|
+
(chat_id, thread_id, thread_id))
|
|
1531
|
+
db.execute(f'UPDATE bindings SET suspended=?,suspension_seq=suspension_seq+1 WHERE {scope} AND {guard}',
|
|
1532
|
+
(reason, chat_id, thread_id, thread_id))
|
|
1533
|
+
|
|
1534
|
+
def _follow_migration(self, db, old_chat_id, new_chat_id):
|
|
1535
|
+
"""Move the bindings of a group that became a supergroup to its new chat id.
|
|
1536
|
+
|
|
1537
|
+
The client, its allowed senders and its queued work stay the same. A
|
|
1538
|
+
binding whose new destination is already taken stays on the old chat
|
|
1539
|
+
and is suspended, so the owner must pair it again.
|
|
1540
|
+
"""
|
|
1541
|
+
if old_chat_id == new_chat_id:
|
|
1542
|
+
return
|
|
1543
|
+
for binding in db.execute('SELECT * FROM bindings WHERE chat_id=? AND connected=1', (old_chat_id,)).fetchall():
|
|
1544
|
+
if db.execute('SELECT 1 FROM bindings WHERE chat_id=? AND thread_id=? AND connected=1',
|
|
1545
|
+
(new_chat_id, binding['thread_id'])).fetchone():
|
|
1546
|
+
self._suspend(db, 'group_migrated:' + str(new_chat_id), old_chat_id, binding['thread_id'])
|
|
1547
|
+
continue
|
|
1548
|
+
self._move_binding(db, binding, new_chat_id)
|
|
1549
|
+
|
|
1550
|
+
def _follow_send_migration(self, db, row, new_chat_id):
|
|
1551
|
+
"""A send was refused because its group became a supergroup.
|
|
1552
|
+
|
|
1553
|
+
This is the third migration signal, after the two service messages. It
|
|
1554
|
+
moves the bindings like they do. The refused message is queued again;
|
|
1555
|
+
it moves with the binding, or follows a binding that an earlier notice
|
|
1556
|
+
already moved. If the binding stays on the old chat, suspended, the
|
|
1557
|
+
message waits there like every other queued send.
|
|
1558
|
+
"""
|
|
1559
|
+
self._follow_migration(db, row['chat_id'], new_chat_id)
|
|
1560
|
+
db.execute("UPDATE outbox SET chat_id=?,reply_to=NULL WHERE id=? AND status='queued' AND EXISTS("
|
|
1561
|
+
"SELECT 1 FROM bindings WHERE client_id=? AND chat_id=? AND connected=1)",
|
|
1562
|
+
(new_chat_id, row['id'], row['client_id'], new_chat_id))
|
|
1563
|
+
|
|
1564
|
+
def _move_binding(self, db, binding, new_chat_id):
|
|
1565
|
+
client_id, old_chat_id = binding['client_id'], binding['chat_id']
|
|
1566
|
+
# A suspension for this same migration no longer applies. Any other
|
|
1567
|
+
# reason stays. The new seq makes a racing owner clear fail.
|
|
1568
|
+
# The bot's administrator status in the new supergroup is not known yet.
|
|
1569
|
+
db.execute('UPDATE bindings SET chat_id=?,suspension_seq=suspension_seq+1,'
|
|
1570
|
+
'suspended=CASE WHEN suspended=? THEN NULL ELSE suspended END,'
|
|
1571
|
+
'bot_admin=NULL,bot_admin_probed=NULL '
|
|
1572
|
+
'WHERE client_id=? AND connected=1',
|
|
1573
|
+
(new_chat_id, 'group_migrated:' + str(new_chat_id), client_id))
|
|
1574
|
+
# Message ids are per chat: the supergroup numbers its own messages, and
|
|
1575
|
+
# the old group's messages stay behind in the closed group. A queued send
|
|
1576
|
+
# moves without its reply link, and a queued reaction cannot move at all;
|
|
1577
|
+
# in the new chat both would hit an unrelated message with the same id.
|
|
1578
|
+
db.execute("UPDATE outbox SET chat_id=?,reply_to=NULL WHERE client_id=? AND chat_id=? AND status='queued'",
|
|
1579
|
+
(new_chat_id, client_id, old_chat_id))
|
|
1580
|
+
db.execute("UPDATE reaction_outbox SET status='rejected',error='group_migrated',updated=? "
|
|
1581
|
+
"WHERE client_id=? AND chat_id=? AND status='queued'", (self.clock(), client_id, old_chat_id))
|
|
1582
|
+
|
|
1583
|
+
def _route_update(self, db, update, account, now):
|
|
1584
|
+
update_id = update['update_id']
|
|
1585
|
+
membership = update.get('my_chat_member')
|
|
1586
|
+
if isinstance(membership, dict):
|
|
1587
|
+
if _mapping(membership.get('chat')).get('type') == 'private':
|
|
1588
|
+
# The owner blocking or starting the bot: no binding is a private
|
|
1589
|
+
# chat, so there is nothing to suspend or refresh.
|
|
1590
|
+
self._unmatched(db, update_id, None, 'private_chat', now)
|
|
1591
|
+
return
|
|
1592
|
+
chat_id = _mapping(membership.get('chat')).get('id')
|
|
1593
|
+
new = _mapping(membership.get('new_chat_member'))
|
|
1594
|
+
if _integer(chat_id) and _mapping(new.get('user')).get('id') == account['bot_id']:
|
|
1595
|
+
# Receiving reactions requires administrator status, so every
|
|
1596
|
+
# membership event refreshes what status can tell the owner.
|
|
1597
|
+
db.execute('UPDATE bindings SET bot_admin=?,bot_admin_probed=? WHERE chat_id=? AND connected=1',
|
|
1598
|
+
(1 if new.get('status') == 'administrator' else 0, now, chat_id))
|
|
1599
|
+
if (new.get('status') in ('left', 'kicked') or (new.get('status') == 'restricted' and (not new.get('is_member', True) or not new.get('can_send_messages', True)))):
|
|
1600
|
+
self._suspend(db, 'bot_removed_or_restricted', chat_id)
|
|
1601
|
+
return
|
|
1602
|
+
reaction = update.get('message_reaction')
|
|
1603
|
+
if isinstance(reaction, dict):
|
|
1604
|
+
self._route_reaction(db, update_id, reaction, account, now)
|
|
1605
|
+
return
|
|
1606
|
+
callback = update.get('callback_query')
|
|
1607
|
+
if isinstance(callback, dict):
|
|
1608
|
+
self._route_callback(db, update_id, callback, now)
|
|
1609
|
+
return
|
|
1610
|
+
query = update.get('widget_query')
|
|
1611
|
+
if isinstance(query, dict):
|
|
1612
|
+
self._route_widget_query(db, update_id, query, now)
|
|
1613
|
+
return
|
|
1614
|
+
kind = 'edited_message' if 'edited_message' in update else 'message'
|
|
1615
|
+
msg = update.get(kind)
|
|
1616
|
+
if not isinstance(msg, dict):
|
|
1617
|
+
self._unmatched(db, update_id, None, 'unsupported_update', now)
|
|
1618
|
+
return
|
|
1619
|
+
chat = _mapping(msg.get('chat'))
|
|
1620
|
+
chat_id = chat.get('id')
|
|
1621
|
+
# Telegram also sets message_thread_id on replies in a supergroup that is
|
|
1622
|
+
# not a forum: it is the first message of the reply chain, not a topic.
|
|
1623
|
+
# Only a forum has topics, so only a forum's thread id selects a binding.
|
|
1624
|
+
thread_id = msg.get('message_thread_id', 0) if chat.get('is_forum') is True else 0
|
|
1625
|
+
if chat.get('type') == 'private':
|
|
1626
|
+
# Several agents can share the bot, so a private message has no
|
|
1627
|
+
# single agent to go to, unless it is the owner's Telegram reply to
|
|
1628
|
+
# one agent's notice. Everything else, including /start, gets its
|
|
1629
|
+
# own reason, so it does not look like a bug.
|
|
1630
|
+
if not self._route_owner_reply(db, update_id, msg, kind, account, now):
|
|
1631
|
+
self._unmatched(db, update_id, None, 'private_chat', now)
|
|
1632
|
+
if not self._queue_panel_request(db, update_id, msg, kind, now):
|
|
1633
|
+
self._queue_start_reply(db, update_id, msg, kind, now)
|
|
1634
|
+
return
|
|
1635
|
+
if not _integer(chat_id) or not _integer(thread_id) or thread_id < 0 or chat.get('type') not in ('group', 'supergroup'):
|
|
1636
|
+
self._unmatched(db, update_id, None, 'unsupported_destination', now)
|
|
1637
|
+
return
|
|
1638
|
+
# Telegram announces a group's upgrade to a supergroup twice: in the old
|
|
1639
|
+
# group (migrate_to_chat_id) and in the new supergroup
|
|
1640
|
+
# (migrate_from_chat_id). Either one moves the bindings.
|
|
1641
|
+
if _integer(msg.get('migrate_to_chat_id')):
|
|
1642
|
+
self._follow_migration(db, chat_id, msg['migrate_to_chat_id'])
|
|
1643
|
+
return
|
|
1644
|
+
if _integer(msg.get('migrate_from_chat_id')):
|
|
1645
|
+
self._follow_migration(db, msg['migrate_from_chat_id'], chat_id)
|
|
1646
|
+
return
|
|
1647
|
+
if 'forum_topic_closed' in msg or 'forum_topic_edited' in msg:
|
|
1648
|
+
self._suspend(db, 'topic_changed', chat_id, thread_id)
|
|
1649
|
+
return
|
|
1650
|
+
sender = _mapping(msg.get('from'))
|
|
1651
|
+
sender_id = sender.get('id')
|
|
1652
|
+
if not _integer(sender_id) or sender_id <= 0 or not isinstance(sender.get('is_bot'), bool) or msg.get('sender_chat'):
|
|
1653
|
+
self._unmatched(db, update_id, chat_id, 'unverified_sender', now)
|
|
1654
|
+
return
|
|
1655
|
+
if sender_id == account['bot_id']:
|
|
1656
|
+
self._unmatched(db, update_id, chat_id, 'shared_bot_echo', now)
|
|
1657
|
+
return
|
|
1658
|
+
text, attachments = _message_content(msg)
|
|
1659
|
+
if text is None or not _integer(msg.get('message_id')):
|
|
1660
|
+
self._unmatched(db, update_id, chat_id, 'unsupported_message', now)
|
|
1661
|
+
return
|
|
1662
|
+
# Commands are only ever read from message text, never from a caption.
|
|
1663
|
+
command_text = msg['text'] if isinstance(msg.get('text'), str) else ''
|
|
1664
|
+
command = re.fullmatch(r'/pair@([A-Za-z0-9_]+) ([A-F0-9]{12})', command_text)
|
|
1665
|
+
if command and command.group(1).lower() == account['username'].lower():
|
|
1666
|
+
if not sender['is_bot'] and kind == 'message':
|
|
1667
|
+
code = _digest(command.group(2))
|
|
1668
|
+
observed = db.execute('UPDATE pairings SET sender_id=?,chat_id=?,thread_id=?,title=?,observed=? WHERE code_hash=? AND consumed=0 AND expires>? AND sender_id IS NULL', (sender_id, chat_id, thread_id, _bounded(chat.get('title', ''), 128), now, code, now)).rowcount
|
|
1669
|
+
if observed and self._pairing_trusted(db, sender_id):
|
|
1670
|
+
row = db.execute('SELECT * FROM pairings WHERE code_hash=? AND consumed=0', (code,)).fetchone()
|
|
1671
|
+
try:
|
|
1672
|
+
self._bind_pairing(db, row, now)
|
|
1673
|
+
except CoreError:
|
|
1674
|
+
# The destination is taken: the pairing stays observed,
|
|
1675
|
+
# and pair-confirm reports why it cannot connect.
|
|
1676
|
+
pass
|
|
1677
|
+
return
|
|
1678
|
+
binding = db.execute('SELECT b.* FROM bindings b JOIN clients c ON c.id=b.client_id WHERE b.chat_id=? AND b.thread_id=? AND b.connected=1 AND c.active=1', (chat_id, thread_id)).fetchone()
|
|
1679
|
+
if binding is None:
|
|
1680
|
+
self._unmatched(db, update_id, chat_id, 'unbound_destination', now)
|
|
1681
|
+
return
|
|
1682
|
+
allowed = db.execute('SELECT 1 FROM allowed_senders WHERE client_id=? AND sender_id=? AND is_bot=?', (binding['client_id'], sender_id, int(sender['is_bot']))).fetchone()
|
|
1683
|
+
if not allowed:
|
|
1684
|
+
allowed = self._auto_allow(db, binding, sender, now)
|
|
1685
|
+
media_refused = []
|
|
1686
|
+
if attachments and not binding['accept_media']:
|
|
1687
|
+
if not allowed:
|
|
1688
|
+
self._unmatched(db, update_id, chat_id, 'unsupported_message', now)
|
|
1689
|
+
return
|
|
1690
|
+
# Tell the agent that a message came in with media it cannot read,
|
|
1691
|
+
# instead of dropping it unseen. Only the media kinds are kept.
|
|
1692
|
+
media_refused = sorted({item['kind'] for item in attachments})
|
|
1693
|
+
attachments = []
|
|
1694
|
+
if not allowed and not binding['capture_context']:
|
|
1695
|
+
self._unmatched(db, update_id, chat_id, 'sender_not_allowed', now)
|
|
1696
|
+
return
|
|
1697
|
+
if allowed and not sender['is_bot'] and sender_id == binding['owner_id'] and command_text.lower() == f'/pause@{account["username"]}'.lower() and kind == 'message':
|
|
1698
|
+
db.execute('UPDATE bindings SET paused=1 WHERE client_id=?', (binding['client_id'],))
|
|
1699
|
+
return
|
|
1700
|
+
# A human message starts its own conversation unless it replies to a known
|
|
1701
|
+
# outbound message. Bot replies inherit a known conversation; unsolicited
|
|
1702
|
+
# bot messages keep the legacy chain unless the operator enables bounded
|
|
1703
|
+
# roots. Every conversation has its own rolling send window, and the
|
|
1704
|
+
# per-agent ceiling bounds the total across all of them, so reusing old
|
|
1705
|
+
# conversations or minting new ones cannot raise an agent's throughput.
|
|
1706
|
+
reply_to = _mapping(msg.get('reply_to_message')).get('message_id')
|
|
1707
|
+
known = db.execute('SELECT conversation_id FROM outbox WHERE chat_id=? AND thread_id=? AND message_id=? AND status=\'sent\' ORDER BY created DESC LIMIT 1', (chat_id, thread_id, reply_to)).fetchone() if _integer(reply_to) else None
|
|
1708
|
+
if known:
|
|
1709
|
+
conversation = known['conversation_id']
|
|
1710
|
+
elif sender['is_bot']:
|
|
1711
|
+
conversation = f'bot:{binding["client_id"]}:{sender_id}'
|
|
1712
|
+
policy = db.execute('SELECT enabled FROM bot_exchange_policies WHERE client_id=? AND sender_id=?',
|
|
1713
|
+
(binding['client_id'], sender_id)).fetchone()
|
|
1714
|
+
if policy and policy[0] and reply_to is None and kind == 'message':
|
|
1715
|
+
conversation = f'bot-root:{binding["client_id"]}:{sender_id}:{msg["message_id"]}'
|
|
1716
|
+
elif sender_id == binding['owner_id']:
|
|
1717
|
+
conversation = f'tg:{chat_id}:{thread_id}:{msg["message_id"]}'
|
|
1718
|
+
else:
|
|
1719
|
+
conversation = f'participant:{binding["client_id"]}:{sender_id}'
|
|
1720
|
+
edited_delivery = False
|
|
1721
|
+
if kind == 'edited_message':
|
|
1722
|
+
# The index holds only captured messages, never reactions, so a
|
|
1723
|
+
# reaction on the same message ID cannot pose as the original.
|
|
1724
|
+
for original in db.execute('SELECT payload,conversation_id,context FROM inbox '
|
|
1725
|
+
'WHERE client_id=? AND tg_chat_id=? AND tg_message_id=? ORDER BY created,rowid',
|
|
1726
|
+
(binding['client_id'], chat_id, msg['message_id'])):
|
|
1727
|
+
prior = json.loads(original['payload'])
|
|
1728
|
+
if _mapping(prior.get('sender')).get('id') == sender_id:
|
|
1729
|
+
conversation = original['conversation_id']
|
|
1730
|
+
edited_delivery = not original['context']
|
|
1731
|
+
break
|
|
1732
|
+
# Membership is recorded for context too: a later reply to a context
|
|
1733
|
+
# message from an opted-in bot must stay inside that pair's send budget.
|
|
1734
|
+
if sender['is_bot'] and db.execute('''SELECT 1 FROM bot_exchange_policies
|
|
1735
|
+
WHERE client_id=? AND sender_id=? AND enabled=1''',
|
|
1736
|
+
(binding['client_id'], sender_id)).fetchone():
|
|
1737
|
+
db.execute('INSERT OR IGNORE INTO bot_exchange_members VALUES(?,?,?)',
|
|
1738
|
+
(conversation, binding['client_id'], sender_id))
|
|
1739
|
+
addressed = _addressed(msg, text, account)
|
|
1740
|
+
follow_up = (not addressed and allowed is not None and kind == 'message' and not sender['is_bot']
|
|
1741
|
+
and self._follows_up(db, binding['client_id'], msg, text, account, sender_id,
|
|
1742
|
+
chat_id, thread_id, update_id))
|
|
1743
|
+
payload = {'origin': 'telegram', 'kind': 'edited' if kind == 'edited_message' else 'message', 'update_id': update_id, 'message_id': msg['message_id'], 'chat_id': chat_id, 'thread_id': thread_id or None, 'sender': {'id': sender_id, 'is_bot': sender['is_bot'], 'username': _bounded(sender.get('username', ''), 64)}, 'text': text, 'reply_to': reply_to if _integer(reply_to) else None,
|
|
1744
|
+
# Mentions the bot, replies to it, addresses a command to it or
|
|
1745
|
+
# is a person's follow-up to such a message; wake batching
|
|
1746
|
+
# announces these at once.
|
|
1747
|
+
'addressed': addressed or follow_up}
|
|
1748
|
+
if follow_up:
|
|
1749
|
+
payload['follow_up'] = True
|
|
1750
|
+
if attachments:
|
|
1751
|
+
payload['attachments'] = attachments
|
|
1752
|
+
if media_refused:
|
|
1753
|
+
payload['media_refused'] = media_refused
|
|
1754
|
+
quoted = _quoted_message(msg, binding['accept_media'], lambda quoted_id, quoted_bot: db.execute(
|
|
1755
|
+
'SELECT 1 FROM allowed_senders WHERE client_id=? AND sender_id=? AND is_bot=?',
|
|
1756
|
+
(binding['client_id'], quoted_id, int(quoted_bot))).fetchone() is not None)
|
|
1757
|
+
if quoted is not None:
|
|
1758
|
+
payload['reply_to_message'] = quoted
|
|
1759
|
+
forwarded = _forward_origin(msg)
|
|
1760
|
+
if forwarded is not None:
|
|
1761
|
+
payload['forwarded_from'] = forwarded
|
|
1762
|
+
stamp = msg.get('edit_date' if kind == 'edited_message' else 'date')
|
|
1763
|
+
event_at = stamp if _integer(stamp) and 0 < stamp <= now else now
|
|
1764
|
+
if (allowed and not sender['is_bot'] and sender_id == binding['owner_id'] and kind == 'message'
|
|
1765
|
+
and not db.execute('SELECT 1 FROM inbox WHERE client_id=? AND event_key=?',
|
|
1766
|
+
(binding['client_id'], f'tg:{update_id}')).fetchone()):
|
|
1767
|
+
# The owner taking part shows a human is following this exchange, so
|
|
1768
|
+
# its conversation window starts again from the message's own time.
|
|
1769
|
+
# Edits and reprocessed updates do not count, and the per-agent
|
|
1770
|
+
# ceiling and pair budgets are not reset.
|
|
1771
|
+
db.execute('INSERT INTO conversations(id,window_reset_at) VALUES(?,?) '
|
|
1772
|
+
'ON CONFLICT(id) DO UPDATE SET window_reset_at=excluded.window_reset_at',
|
|
1773
|
+
(conversation, event_at))
|
|
1774
|
+
if not allowed:
|
|
1775
|
+
reason = 'sender_not_allowed'
|
|
1776
|
+
elif binding['delivery_filter'] == 'addressed' and not edited_delivery and not payload['addressed']:
|
|
1777
|
+
reason = 'not_addressed'
|
|
1778
|
+
else:
|
|
1779
|
+
self._enqueue(db, binding['client_id'], f'tg:{update_id}', payload, conversation, now, event_at=event_at)
|
|
1780
|
+
return
|
|
1781
|
+
stored = self._keep_context(db, binding['client_id'], f'tg:{update_id}', {**payload, 'context_reason': reason},
|
|
1782
|
+
conversation, now, event_at)
|
|
1783
|
+
# Only a person's new message with text is judged: never a bot, so agents
|
|
1784
|
+
# cannot wake each other through the model, and never an edit.
|
|
1785
|
+
if (stored and reason == 'not_addressed' and binding['model_judge'] and kind == 'message'
|
|
1786
|
+
and not sender['is_bot'] and text.strip()):
|
|
1787
|
+
db.execute("INSERT OR IGNORE INTO judge_queue(inbox_id,client_id,status,created,updated) "
|
|
1788
|
+
"VALUES(?,?,'queued',?,?)", (stored, binding['client_id'], now, now))
|
|
1789
|
+
|
|
1790
|
+
def _follows_up(self, db, client_id, msg, text, account, sender_id, chat_id, thread_id, update_id):
|
|
1791
|
+
"""True when a person's message continues their own message to this agent.
|
|
1792
|
+
|
|
1793
|
+
A person often replies to an agent and then adds a message or two to
|
|
1794
|
+
expand the answer. Such a message counts as addressed when it mentions no
|
|
1795
|
+
other @username and either replies to the person's own message that was
|
|
1796
|
+
delivered as addressed, or comes at most FOLLOW_UP_WINDOW seconds after
|
|
1797
|
+
the person's last directly addressed message in this chat or topic, with
|
|
1798
|
+
their previous message there delivered as addressed. A reply to anyone
|
|
1799
|
+
else's message never counts.
|
|
1800
|
+
"""
|
|
1801
|
+
own = account['username'].lower()
|
|
1802
|
+
if any(name.lower() != own for name in _MENTION.findall(text)):
|
|
1803
|
+
return False
|
|
1804
|
+
|
|
1805
|
+
def delivered_addressed(row):
|
|
1806
|
+
return row is not None and not row['context'] and json.loads(row['payload']).get('addressed') is True
|
|
1807
|
+
|
|
1808
|
+
replied = _mapping(msg.get('reply_to_message'))
|
|
1809
|
+
# In a forum topic, Telegram marks a plain message as a reply to the
|
|
1810
|
+
# topic's first message; that is not a reply to anyone.
|
|
1811
|
+
if replied and 'forum_topic_created' not in replied and not (thread_id and replied.get('message_id') == thread_id):
|
|
1812
|
+
if _mapping(replied.get('from')).get('id') != sender_id or not _integer(replied.get('message_id')):
|
|
1813
|
+
return False
|
|
1814
|
+
return delivered_addressed(db.execute(
|
|
1815
|
+
'SELECT context,payload FROM inbox WHERE client_id=? AND tg_chat_id=? AND tg_message_id=? '
|
|
1816
|
+
"AND json_extract(payload,'$.kind')='message' ORDER BY created DESC,rowid DESC LIMIT 1",
|
|
1817
|
+
(client_id, chat_id, replied['message_id'])).fetchone())
|
|
1818
|
+
date = msg.get('date')
|
|
1819
|
+
if not _integer(date) or not 0 < date < 2 ** 62:
|
|
1820
|
+
return False
|
|
1821
|
+
previous = db.execute(
|
|
1822
|
+
'SELECT context,payload FROM inbox WHERE client_id=? AND tg_chat_id=? AND event_key<>? '
|
|
1823
|
+
"AND json_extract(payload,'$.kind')='message' AND json_extract(payload,'$.sender.id')=? "
|
|
1824
|
+
"AND COALESCE(json_extract(payload,'$.thread_id'),0)=? "
|
|
1825
|
+
'AND COALESCE(event_at,created) BETWEEN ? AND ? '
|
|
1826
|
+
'ORDER BY COALESCE(event_at,created) DESC,rowid DESC LIMIT 1',
|
|
1827
|
+
(client_id, chat_id, f'tg:{update_id}', sender_id, thread_id or 0,
|
|
1828
|
+
date - FOLLOW_UP_WINDOW, date)).fetchone()
|
|
1829
|
+
if not delivered_addressed(previous):
|
|
1830
|
+
return False
|
|
1831
|
+
# The window runs from the person's last directly addressed message, so
|
|
1832
|
+
# follow-ups never extend it.
|
|
1833
|
+
return db.execute(
|
|
1834
|
+
'SELECT 1 FROM inbox WHERE client_id=? AND tg_chat_id=? AND context=0 '
|
|
1835
|
+
"AND json_extract(payload,'$.kind')='message' AND json_extract(payload,'$.sender.id')=? "
|
|
1836
|
+
"AND COALESCE(json_extract(payload,'$.thread_id'),0)=? "
|
|
1837
|
+
"AND json_extract(payload,'$.addressed')=1 AND json_extract(payload,'$.follow_up') IS NULL AND json_extract(payload,'$.addressed_by') IS NULL "
|
|
1838
|
+
'AND COALESCE(event_at,created) BETWEEN ? AND ? LIMIT 1',
|
|
1839
|
+
(client_id, chat_id, sender_id, thread_id or 0, date - FOLLOW_UP_WINDOW, date)).fetchone() is not None
|
|
1840
|
+
|
|
1841
|
+
def _route_reaction(self, db, update_id, reaction, account, now):
|
|
1842
|
+
"""Deliver one message_reaction update under the same rules as messages.
|
|
1843
|
+
|
|
1844
|
+
Telegram does not send reactions set by bots, and sends them only while
|
|
1845
|
+
the bot is an administrator. The reaction update carries no thread id, so
|
|
1846
|
+
the reacted message is resolved to a destination through the published
|
|
1847
|
+
outbox row or a captured inbox row; an unknown message reaches the single
|
|
1848
|
+
binding of a plain group, and stays unassigned everywhere else. Sender
|
|
1849
|
+
rules match messages. The owner's reaction_wake setting decides which
|
|
1850
|
+
reactions are delivered and can wake this agent: by default only
|
|
1851
|
+
reactions on messages this agent published; the rest are kept as context.
|
|
1852
|
+
In a private chat, only the owner's reaction on an owner_notify notice
|
|
1853
|
+
or its forward reaches the agent that sent it; anything else there is
|
|
1854
|
+
recorded as private_chat.
|
|
1855
|
+
"""
|
|
1856
|
+
chat = _mapping(reaction.get('chat'))
|
|
1857
|
+
chat_id = chat.get('id')
|
|
1858
|
+
private = chat.get('type') == 'private'
|
|
1859
|
+
if not private and (not _integer(chat_id) or chat.get('type') not in ('group', 'supergroup')):
|
|
1860
|
+
self._unmatched(db, update_id, chat_id if _integer(chat_id) else None, 'unsupported_destination', now)
|
|
1861
|
+
return
|
|
1862
|
+
|
|
1863
|
+
def refuse(reason):
|
|
1864
|
+
# A private chat id is a person's user id: never stored, and every
|
|
1865
|
+
# refusal there has the one private_chat reason.
|
|
1866
|
+
self._unmatched(db, update_id, None if private else chat_id, 'private_chat' if private else reason, now)
|
|
1867
|
+
|
|
1868
|
+
message_id = reaction.get('message_id')
|
|
1869
|
+
if not _integer(message_id) or message_id <= 0:
|
|
1870
|
+
refuse('unsupported_update')
|
|
1871
|
+
return
|
|
1872
|
+
sender = _mapping(reaction.get('user'))
|
|
1873
|
+
sender_id = sender.get('id')
|
|
1874
|
+
# Anonymous reactions arrive with actor_chat instead of a user, so no
|
|
1875
|
+
# allowed-sender rule can apply; they stay unassigned like anonymous
|
|
1876
|
+
# channel posts.
|
|
1877
|
+
if not _integer(sender_id) or sender_id <= 0 or not isinstance(sender.get('is_bot'), bool) or reaction.get('actor_chat'):
|
|
1878
|
+
refuse('unverified_sender')
|
|
1879
|
+
return
|
|
1880
|
+
if sender_id == account['bot_id']:
|
|
1881
|
+
refuse('shared_bot_echo')
|
|
1882
|
+
return
|
|
1883
|
+
old = reaction_types(reaction.get('old_reaction'))
|
|
1884
|
+
new = reaction_types(reaction.get('new_reaction'))
|
|
1885
|
+
if old is None or new is None:
|
|
1886
|
+
refuse('unsupported_update')
|
|
1887
|
+
return
|
|
1888
|
+
if private:
|
|
1889
|
+
notice = self._owner_notice(db, chat_id, sender_id, message_id)
|
|
1890
|
+
if notice is None:
|
|
1891
|
+
refuse('private_chat')
|
|
1892
|
+
return
|
|
1893
|
+
binding = notice[0]
|
|
1894
|
+
# The notice was this agent's own message; its reactions have no
|
|
1895
|
+
# group conversation, so they share the agent's reaction one.
|
|
1896
|
+
self._deliver_reaction(db, update_id, reaction, binding, chat_id, message_id, sender, old, new,
|
|
1897
|
+
True, None, now, thread_id=None, refuse=refuse, owner_notice=True)
|
|
1898
|
+
return
|
|
1899
|
+
conversation = None
|
|
1900
|
+
binding = None
|
|
1901
|
+
own_message = False
|
|
1902
|
+
known_message = False
|
|
1903
|
+
published = db.execute('SELECT client_id,thread_id,conversation_id FROM outbox '
|
|
1904
|
+
'WHERE chat_id=? AND message_id=? ORDER BY created DESC LIMIT 1',
|
|
1905
|
+
(chat_id, message_id)).fetchone()
|
|
1906
|
+
if published is not None:
|
|
1907
|
+
known_message = True
|
|
1908
|
+
binding = db.execute('SELECT b.* FROM bindings b JOIN clients c ON c.id=b.client_id '
|
|
1909
|
+
'WHERE b.chat_id=? AND b.thread_id=? AND b.connected=1 AND c.active=1',
|
|
1910
|
+
(chat_id, published['thread_id'])).fetchone()
|
|
1911
|
+
conversation = published['conversation_id']
|
|
1912
|
+
own_message = binding is not None and published['client_id'] == binding['client_id']
|
|
1913
|
+
else:
|
|
1914
|
+
captured = None
|
|
1915
|
+
row = db.execute('SELECT client_id,payload,conversation_id FROM inbox WHERE tg_chat_id=? AND tg_message_id=? '
|
|
1916
|
+
'ORDER BY created DESC,rowid DESC LIMIT 1', (chat_id, message_id)).fetchone()
|
|
1917
|
+
if row is not None:
|
|
1918
|
+
captured = (row['client_id'], json.loads(row['payload']).get('thread_id') or 0, row['conversation_id'])
|
|
1919
|
+
if captured is not None:
|
|
1920
|
+
known_message = True
|
|
1921
|
+
binding = db.execute('SELECT b.* FROM bindings b JOIN clients c ON c.id=b.client_id '
|
|
1922
|
+
'WHERE b.chat_id=? AND b.thread_id=? AND b.connected=1 AND c.active=1',
|
|
1923
|
+
(chat_id, captured[1])).fetchone()
|
|
1924
|
+
conversation = captured[2]
|
|
1925
|
+
if binding is None and not known_message:
|
|
1926
|
+
# Unknown message: only a plain group with exactly one binding can be
|
|
1927
|
+
# attributed safely; topic destinations stay unassigned.
|
|
1928
|
+
candidates = db.execute('SELECT b.* FROM bindings b JOIN clients c ON c.id=b.client_id '
|
|
1929
|
+
'WHERE b.chat_id=? AND b.connected=1 AND c.active=1', (chat_id,)).fetchall()
|
|
1930
|
+
if len(candidates) == 1 and candidates[0]['thread_id'] == 0:
|
|
1931
|
+
binding = candidates[0]
|
|
1932
|
+
if binding is None:
|
|
1933
|
+
reason = 'unbound_destination' if known_message or not db.execute(
|
|
1934
|
+
'SELECT 1 FROM bindings b JOIN clients c ON c.id=b.client_id WHERE b.chat_id=? AND b.connected=1 AND c.active=1',
|
|
1935
|
+
(chat_id,)).fetchone() else 'unresolved_reaction'
|
|
1936
|
+
self._unmatched(db, update_id, chat_id, reason, now)
|
|
1937
|
+
return
|
|
1938
|
+
self._deliver_reaction(db, update_id, reaction, binding, chat_id, message_id, sender, old, new,
|
|
1939
|
+
own_message, conversation, now, thread_id=binding['thread_id'] or None, refuse=refuse)
|
|
1940
|
+
|
|
1941
|
+
def _owner_notice(self, db, chat_id, sender_id, message_id):
|
|
1942
|
+
"""(binding, notify_id) for the owner notice (or its forward) a private update targets, or None.
|
|
1943
|
+
|
|
1944
|
+
In a private chat the chat id is the person's user id, and message ids
|
|
1945
|
+
are numbered per chat, so (owner chat, message id) names one notice. Only
|
|
1946
|
+
the binding's own owner, acting in their own chat, is accepted.
|
|
1947
|
+
"""
|
|
1948
|
+
if not _integer(chat_id) or chat_id != sender_id or not _integer(message_id):
|
|
1949
|
+
return None
|
|
1950
|
+
row = db.execute('SELECT id,client_id FROM owner_outbox WHERE owner_id=? AND (message_id=? OR forwarded_message_id=?) '
|
|
1951
|
+
'ORDER BY created DESC LIMIT 1', (chat_id, message_id, message_id)).fetchone()
|
|
1952
|
+
if row is None:
|
|
1953
|
+
return None
|
|
1954
|
+
binding = db.execute('SELECT b.* FROM bindings b JOIN clients c ON c.id=b.client_id '
|
|
1955
|
+
'WHERE b.client_id=? AND b.owner_id=? AND b.connected=1 AND c.active=1',
|
|
1956
|
+
(row['client_id'], sender_id)).fetchone()
|
|
1957
|
+
return (binding, row['id']) if binding is not None else None
|
|
1958
|
+
|
|
1959
|
+
def _routed_owner_message(self, db, chat_id, sender_id, message_id):
|
|
1960
|
+
"""(binding, conversation) of the owner's private message that was routed to an agent, or None."""
|
|
1961
|
+
if not _integer(chat_id) or chat_id != sender_id or not _integer(message_id):
|
|
1962
|
+
return None
|
|
1963
|
+
for row in db.execute('SELECT client_id,payload,conversation_id FROM inbox WHERE tg_chat_id=? AND tg_message_id=? '
|
|
1964
|
+
'ORDER BY created,rowid', (chat_id, message_id)):
|
|
1965
|
+
payload = json.loads(row['payload'])
|
|
1966
|
+
if payload.get('owner_notice') is True and _mapping(payload.get('sender')).get('id') == sender_id:
|
|
1967
|
+
binding = db.execute('SELECT b.* FROM bindings b JOIN clients c ON c.id=b.client_id '
|
|
1968
|
+
'WHERE b.client_id=? AND b.owner_id=? AND b.connected=1 AND c.active=1',
|
|
1969
|
+
(row['client_id'], sender_id)).fetchone()
|
|
1970
|
+
return (binding, row['conversation_id']) if binding is not None else None
|
|
1971
|
+
return None
|
|
1972
|
+
|
|
1973
|
+
def _route_owner_reply(self, db, update_id, msg, kind, account, now):
|
|
1974
|
+
"""Deliver the owner's private reply to an agent; False when it is not one.
|
|
1975
|
+
|
|
1976
|
+
Only a Telegram reply can be routed. It names one message through
|
|
1977
|
+
reply_to_message: a notice or forward that owner_outbox records, or the
|
|
1978
|
+
owner's own earlier message that was routed to an agent. An edit follows
|
|
1979
|
+
its original when that was routed. The delivery is a normal message
|
|
1980
|
+
from the owner, with the private chat as chat_id, marked owner_notice
|
|
1981
|
+
and addressed, so wake batching announces it at once. Media follows the
|
|
1982
|
+
connection's accept_media setting, as in the group.
|
|
1983
|
+
"""
|
|
1984
|
+
chat_id = _mapping(msg.get('chat')).get('id')
|
|
1985
|
+
sender = _mapping(msg.get('from'))
|
|
1986
|
+
sender_id = sender.get('id')
|
|
1987
|
+
if sender.get('is_bot') is not False or msg.get('sender_chat'):
|
|
1988
|
+
return False
|
|
1989
|
+
reply_to = _mapping(msg.get('reply_to_message')).get('message_id')
|
|
1990
|
+
text, attachments = _message_content(msg)
|
|
1991
|
+
if text is None or not _integer(msg.get('message_id')):
|
|
1992
|
+
return False
|
|
1993
|
+
if kind == 'edited_message':
|
|
1994
|
+
target = self._routed_owner_message(db, chat_id, sender_id, msg['message_id'])
|
|
1995
|
+
else:
|
|
1996
|
+
notice = self._owner_notice(db, chat_id, sender_id, reply_to)
|
|
1997
|
+
target = ((notice[0], f'owner:{notice[0]["client_id"]}:{notice[1]}') if notice is not None
|
|
1998
|
+
else self._routed_owner_message(db, chat_id, sender_id, reply_to))
|
|
1999
|
+
if target is None:
|
|
2000
|
+
return False
|
|
2001
|
+
binding, conversation = target
|
|
2002
|
+
if not db.execute('SELECT 1 FROM allowed_senders WHERE client_id=? AND sender_id=? AND is_bot=0',
|
|
2003
|
+
(binding['client_id'], sender_id)).fetchone():
|
|
2004
|
+
return False
|
|
2005
|
+
payload = {'origin': 'telegram', 'kind': 'edited' if kind == 'edited_message' else 'message',
|
|
2006
|
+
'update_id': update_id, 'message_id': msg['message_id'], 'chat_id': chat_id, 'thread_id': None,
|
|
2007
|
+
'sender': {'id': sender_id, 'is_bot': False, 'username': _bounded(sender.get('username', ''), 64)},
|
|
2008
|
+
'text': text, 'reply_to': reply_to if _integer(reply_to) else None, 'addressed': True,
|
|
2009
|
+
# The owner answering an owner_notify notice in the private chat.
|
|
2010
|
+
'owner_notice': True}
|
|
2011
|
+
if attachments and binding['accept_media']:
|
|
2012
|
+
payload['attachments'] = attachments
|
|
2013
|
+
elif attachments:
|
|
2014
|
+
payload['media_refused'] = sorted({item['kind'] for item in attachments})
|
|
2015
|
+
# The quoted message is the bot's own notice, or its forward.
|
|
2016
|
+
quoted = _quoted_message(msg, binding['accept_media'], lambda quoted_id, quoted_bot: quoted_id == account['bot_id'])
|
|
2017
|
+
if quoted is not None:
|
|
2018
|
+
payload['reply_to_message'] = quoted
|
|
2019
|
+
stamp = msg.get('edit_date' if kind == 'edited_message' else 'date')
|
|
2020
|
+
event_at = stamp if _integer(stamp) and 0 < stamp <= now else now
|
|
2021
|
+
db.execute('INSERT OR IGNORE INTO conversations(id) VALUES(?)', (conversation,))
|
|
2022
|
+
self._enqueue(db, binding['client_id'], f'tg:{update_id}', payload, conversation, now, event_at=event_at)
|
|
2023
|
+
return True
|
|
2024
|
+
|
|
2025
|
+
def _deliver_reaction(self, db, update_id, reaction, binding, chat_id, message_id, sender, old, new,
|
|
2026
|
+
own_message, conversation, now, *, thread_id, refuse, owner_notice=False):
|
|
2027
|
+
"""Deliver, or keep as context, one validated reaction for one binding."""
|
|
2028
|
+
sender_id = sender['id']
|
|
2029
|
+
allowed = db.execute('SELECT 1 FROM allowed_senders WHERE client_id=? AND sender_id=? AND is_bot=?',
|
|
2030
|
+
(binding['client_id'], sender_id, int(sender['is_bot']))).fetchone()
|
|
2031
|
+
if not allowed and not binding['capture_context']:
|
|
2032
|
+
refuse('sender_not_allowed')
|
|
2033
|
+
return
|
|
2034
|
+
payload = {'origin': 'telegram', 'kind': 'reaction', 'update_id': update_id,
|
|
2035
|
+
'message_id': message_id, 'chat_id': chat_id, 'thread_id': thread_id,
|
|
2036
|
+
'sender': {'id': sender_id, 'is_bot': sender['is_bot'], 'username': _bounded(sender.get('username', ''), 64)},
|
|
2037
|
+
'old_reaction': old[0], 'new_reaction': new[0], 'own_message': own_message}
|
|
2038
|
+
if owner_notice:
|
|
2039
|
+
# The owner answering an owner_notify notice: wake batching treats
|
|
2040
|
+
# it like the owner's own messages.
|
|
2041
|
+
payload['owner_notice'] = True
|
|
2042
|
+
if old[1]:
|
|
2043
|
+
payload['old_reaction_truncated'] = True
|
|
2044
|
+
if new[1]:
|
|
2045
|
+
payload['new_reaction_truncated'] = True
|
|
2046
|
+
stamp = reaction.get('date')
|
|
2047
|
+
event_at = stamp if _integer(stamp) and 0 < stamp <= now else now
|
|
2048
|
+
if conversation is None:
|
|
2049
|
+
conversation = 'reactions:' + binding['client_id']
|
|
2050
|
+
db.execute('INSERT OR IGNORE INTO conversations(id) VALUES(?)', (conversation,))
|
|
2051
|
+
if not allowed:
|
|
2052
|
+
reason = 'sender_not_allowed'
|
|
2053
|
+
elif binding['reaction_wake'] == 'none':
|
|
2054
|
+
reason = 'reaction_wake_none'
|
|
2055
|
+
elif binding['reaction_wake'] == 'own_messages' and not own_message:
|
|
2056
|
+
reason = 'not_own_message'
|
|
2057
|
+
else:
|
|
2058
|
+
self._enqueue(db, binding['client_id'], 'react:' + str(update_id), payload, conversation, now, event_at=event_at)
|
|
2059
|
+
return
|
|
2060
|
+
self._keep_context(db, binding['client_id'], 'react:' + str(update_id),
|
|
2061
|
+
{**payload, 'context_reason': reason}, conversation, now, event_at)
|
|
2062
|
+
|
|
2063
|
+
def _keep_context(self, db, client_id, event_key, payload, conversation_id, now, event_at):
|
|
2064
|
+
"""Store a context entry; its inbox id, or None when the event was already stored."""
|
|
2065
|
+
# Stored acknowledged and outside the queue bound: history reads it, no
|
|
2066
|
+
# poll, watch, relay or push path ever claims or announces it.
|
|
2067
|
+
keys = _telegram_message_keys(payload) or (None, None)
|
|
2068
|
+
inbox_id = 'msg_' + secrets.token_hex(12)
|
|
2069
|
+
cursor = db.execute('''INSERT OR IGNORE INTO inbox(id,client_id,event_key,payload,created,conversation_id,event_at,acknowledged,context,tg_chat_id,tg_message_id)
|
|
2070
|
+
VALUES(?,?,?,?,?,?,?,1,1,?,?)''', (inbox_id, client_id, event_key,
|
|
2071
|
+
json.dumps(payload, ensure_ascii=False), now, conversation_id, event_at, *keys))
|
|
2072
|
+
return inbox_id if cursor.rowcount == 1 else None
|
|
2073
|
+
|
|
2074
|
+
def _prune_context(self, db, now):
|
|
2075
|
+
"""Drop context older than the history window, with its bookkeeping rows and fetched files.
|
|
2076
|
+
|
|
2077
|
+
The highest inbox rowid is never deleted, so SQLite cannot hand it to a new
|
|
2078
|
+
row inside a history snapshot that was frozen at that rowid.
|
|
2079
|
+
"""
|
|
2080
|
+
stale = [row[0] for row in db.execute('''SELECT id FROM inbox WHERE context=1 AND COALESCE(event_at,created)<?
|
|
2081
|
+
AND rowid<(SELECT MAX(rowid) FROM inbox)''', (now - self.HISTORY_WINDOW,))]
|
|
2082
|
+
if not stale:
|
|
2083
|
+
return
|
|
2084
|
+
self._delete_attachment_files(stale)
|
|
2085
|
+
tables = {row[0] for row in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
|
|
2086
|
+
for start in range(0, len(stale), 500):
|
|
2087
|
+
chunk = stale[start:start + 500]
|
|
2088
|
+
marks = ','.join('?' * len(chunk))
|
|
2089
|
+
for table in ('push_announcements', 'relay_deliveries'):
|
|
2090
|
+
if table in tables:
|
|
2091
|
+
db.execute(f'DELETE FROM {table} WHERE inbox_id IN ({marks})', chunk)
|
|
2092
|
+
db.execute(f'DELETE FROM inbox WHERE context=1 AND id IN ({marks})', chunk)
|
|
2093
|
+
|
|
2094
|
+
PANEL_REQUEST_INTERVAL = 10.0
|
|
2095
|
+
|
|
2096
|
+
def _queue_panel_request(self, db, update_id, msg, kind, now):
|
|
2097
|
+
"""Queue a settings panel for an owner's private /settings; True when the message was /settings.
|
|
2098
|
+
|
|
2099
|
+
Only a person who owns a connected agent on this bot gets a panel, at
|
|
2100
|
+
most one per PANEL_REQUEST_INTERVAL.
|
|
2101
|
+
"""
|
|
2102
|
+
sender = _mapping(msg.get('from'))
|
|
2103
|
+
sender_id = sender.get('id')
|
|
2104
|
+
text = msg.get('text') if isinstance(msg.get('text'), str) else ''
|
|
2105
|
+
if re.fullmatch(r'/settings(?:@[A-Za-z0-9_]+)?\s*', text) is None:
|
|
2106
|
+
return False
|
|
2107
|
+
if (kind != 'message' or sender.get('is_bot') is not False or msg.get('sender_chat')
|
|
2108
|
+
or not _integer(sender_id) or _mapping(msg.get('chat')).get('id') != sender_id):
|
|
2109
|
+
return True
|
|
2110
|
+
if not self._owner_connections(db, sender_id):
|
|
2111
|
+
return True
|
|
2112
|
+
if db.execute('SELECT 1 FROM panel_requests WHERE owner_id=? AND created>? LIMIT 1',
|
|
2113
|
+
(sender_id, now - self.PANEL_REQUEST_INTERVAL)).fetchone():
|
|
2114
|
+
return True
|
|
2115
|
+
db.execute('DELETE FROM panel_requests WHERE created<?', (now - 86400,))
|
|
2116
|
+
db.execute("INSERT OR IGNORE INTO panel_requests(update_id,owner_id,status,created) VALUES(?,?,'queued',?)",
|
|
2117
|
+
(update_id, sender_id, now))
|
|
2118
|
+
return True
|
|
2119
|
+
|
|
2120
|
+
def _send_panel_requests(self):
|
|
2121
|
+
"""Send the panels owners asked for with /settings; never fails collection. Each is tried once."""
|
|
2122
|
+
with self._tx() as db:
|
|
2123
|
+
db.execute("UPDATE panel_requests SET status='expired' WHERE status='queued' AND created<?",
|
|
2124
|
+
(self.clock() - 600,))
|
|
2125
|
+
rows = db.execute("SELECT update_id,owner_id,created FROM panel_requests WHERE status='queued' "
|
|
2126
|
+
'ORDER BY update_id LIMIT 5').fetchall()
|
|
2127
|
+
for row in rows:
|
|
2128
|
+
db.execute("UPDATE panel_requests SET status='sending' WHERE update_id=?", (row['update_id'],))
|
|
2129
|
+
for row in rows:
|
|
2130
|
+
calls = {}
|
|
2131
|
+
try:
|
|
2132
|
+
with _timed(calls, 'send_ms'):
|
|
2133
|
+
self._send_panel(row['owner_id'])
|
|
2134
|
+
status = 'sent'
|
|
2135
|
+
except Exception:
|
|
2136
|
+
status = 'failed'
|
|
2137
|
+
self.record_activity('owner', {'action': 'settings_command', 'outcome': status,
|
|
2138
|
+
'routed_to_answered_ms': round((self.clock() - row['created']) * 1000),
|
|
2139
|
+
**calls})
|
|
2140
|
+
with self._tx() as db:
|
|
2141
|
+
db.execute('UPDATE panel_requests SET status=? WHERE update_id=?', (status, row['update_id']))
|
|
2142
|
+
|
|
2143
|
+
def _queue_start_reply(self, db, update_id, msg, kind, now):
|
|
2144
|
+
"""Queue one short answer to the owner's private /start.
|
|
2145
|
+
|
|
2146
|
+
Only a person who owns a connected agent on this bot gets an answer, so
|
|
2147
|
+
a stranger cannot make the bot write to anyone. An owner who sends
|
|
2148
|
+
/start again within START_REPLY_INTERVAL gets no second answer.
|
|
2149
|
+
"""
|
|
2150
|
+
sender = _mapping(msg.get('from'))
|
|
2151
|
+
sender_id = sender.get('id')
|
|
2152
|
+
text = msg.get('text') if isinstance(msg.get('text'), str) else ''
|
|
2153
|
+
if (kind != 'message' or sender.get('is_bot') is not False or msg.get('sender_chat')
|
|
2154
|
+
or not _integer(sender_id) or _mapping(msg.get('chat')).get('id') != sender_id
|
|
2155
|
+
or re.fullmatch(r'/start(?:@[A-Za-z0-9_]+)?(?: .*)?', text, re.DOTALL) is None):
|
|
2156
|
+
return
|
|
2157
|
+
if not db.execute('SELECT 1 FROM bindings b JOIN clients c ON c.id=b.client_id '
|
|
2158
|
+
'WHERE b.owner_id=? AND b.connected=1 AND c.active=1 LIMIT 1', (sender_id,)).fetchone():
|
|
2159
|
+
return
|
|
2160
|
+
if db.execute('SELECT 1 FROM start_replies WHERE owner_id=? AND created>? LIMIT 1',
|
|
2161
|
+
(sender_id, now - self.START_REPLY_INTERVAL)).fetchone():
|
|
2162
|
+
return
|
|
2163
|
+
db.execute('DELETE FROM start_replies WHERE created<?', (now - 86400,))
|
|
2164
|
+
db.execute("INSERT OR IGNORE INTO start_replies(update_id,owner_id,status,created,updated) VALUES(?,?,'queued',?,?)",
|
|
2165
|
+
(update_id, sender_id, now, now))
|
|
2166
|
+
|
|
2167
|
+
def _start_reply_text(self, db, owner_id):
|
|
2168
|
+
rows = db.execute('SELECT b.owner_notify FROM bindings b JOIN clients c ON c.id=b.client_id '
|
|
2169
|
+
'WHERE b.owner_id=? AND b.connected=1 AND c.active=1', (owner_id,)).fetchall()
|
|
2170
|
+
enabled = sum(1 for row in rows if row['owner_notify'])
|
|
2171
|
+
agents = '1 connected agent' if len(rows) == 1 else f'{len(rows)} connected agents'
|
|
2172
|
+
if enabled == 0:
|
|
2173
|
+
notices = 'None of them can send you private notices yet. Ask an agent to turn them on if you want them.'
|
|
2174
|
+
elif enabled == len(rows):
|
|
2175
|
+
notices = ('It can' if len(rows) == 1 else 'All of them can') + ' send you private notices here.'
|
|
2176
|
+
else:
|
|
2177
|
+
notices = f'{enabled} of them can send you private notices here.'
|
|
2178
|
+
return (f'Ready. You have {agents} on this bot. {notices} '
|
|
2179
|
+
'Reply to a notice to answer the agent that sent it. Send /settings to change agent settings.')
|
|
2180
|
+
|
|
2181
|
+
def _send_start_replies(self):
|
|
2182
|
+
"""Answer queued /start messages; never fails collection.
|
|
2183
|
+
|
|
2184
|
+
Each answer is tried at most once: the row is marked 'sending' before
|
|
2185
|
+
the request, so a crash or an unclear outcome never sends it twice.
|
|
2186
|
+
It runs under the sender lock, and waits for the next collection when
|
|
2187
|
+
a sender is busy. With nothing queued it only reads, and takes no lock,
|
|
2188
|
+
so it never makes flush() or resolve_unknown() report busy.
|
|
2189
|
+
"""
|
|
2190
|
+
with self._db() as db:
|
|
2191
|
+
if not db.execute("SELECT 1 FROM start_replies WHERE status='queued' LIMIT 1").fetchone():
|
|
2192
|
+
return
|
|
2193
|
+
with self._lock('sender') as acquired:
|
|
2194
|
+
if not acquired:
|
|
2195
|
+
return
|
|
2196
|
+
with self._tx() as db:
|
|
2197
|
+
# An answer that waited too long for the sender lock is dropped.
|
|
2198
|
+
db.execute("UPDATE start_replies SET status='expired',updated=? WHERE status='queued' AND created<?",
|
|
2199
|
+
(self.clock(), self.clock() - 600))
|
|
2200
|
+
rows = db.execute("SELECT update_id,owner_id FROM start_replies WHERE status='queued' ORDER BY update_id").fetchall()
|
|
2201
|
+
pending = [(row['update_id'], row['owner_id'], self._start_reply_text(db, row['owner_id'])) for row in rows]
|
|
2202
|
+
for update_id, _, _ in pending:
|
|
2203
|
+
db.execute("UPDATE start_replies SET status='sending',updated=? WHERE update_id=?", (self.clock(), update_id))
|
|
2204
|
+
for update_id, owner_id, text in pending:
|
|
2205
|
+
try:
|
|
2206
|
+
response = self.transport.send_message(chat_id=owner_id, text=text)
|
|
2207
|
+
status = 'sent' if isinstance(response, dict) and _integer(response.get('message_id')) else 'unknown'
|
|
2208
|
+
except TransportError as error:
|
|
2209
|
+
status = 'rejected' if isinstance(error.code, int) and 400 <= error.code < 500 else 'unknown'
|
|
2210
|
+
except Exception:
|
|
2211
|
+
status = 'unknown'
|
|
2212
|
+
with self._tx() as db:
|
|
2213
|
+
db.execute('UPDATE start_replies SET status=?,updated=? WHERE update_id=?', (status, self.clock(), update_id))
|
|
2214
|
+
|
|
2215
|
+
def _judge_ready(self):
|
|
2216
|
+
"""The judge callable, or None when no usable model is configured."""
|
|
2217
|
+
if self._judge is _LOAD_JUDGE:
|
|
2218
|
+
return judge_module.load(self.state_dir)
|
|
2219
|
+
return self._judge
|
|
2220
|
+
|
|
2221
|
+
def _judge_context(self, db, row, account):
|
|
2222
|
+
"""What the model sees: the agent, its bot, recent messages and the candidate."""
|
|
2223
|
+
payload = json.loads(row['payload'])
|
|
2224
|
+
thread = payload.get('thread_id') or 0
|
|
2225
|
+
at = row['event_at'] if row['event_at'] is not None else row['created']
|
|
2226
|
+
|
|
2227
|
+
def person(sender):
|
|
2228
|
+
sender = sender if isinstance(sender, dict) else {}
|
|
2229
|
+
name = '@' + sender['username'] if sender.get('username') else f"user {sender.get('id')}"
|
|
2230
|
+
return name + (' (bot)' if sender.get('is_bot') else '')
|
|
2231
|
+
|
|
2232
|
+
earlier = [(r['at'], r['rowid'], {'sender': person(json.loads(r['payload']).get('sender')),
|
|
2233
|
+
'text': json.loads(r['payload']).get('text')})
|
|
2234
|
+
for r in db.execute(
|
|
2235
|
+
"SELECT rowid,payload,COALESCE(event_at,created) AS at FROM inbox "
|
|
2236
|
+
"WHERE client_id=? AND tg_chat_id=? AND json_extract(payload,'$.kind')='message' "
|
|
2237
|
+
"AND COALESCE(json_extract(payload,'$.thread_id'),0)=? "
|
|
2238
|
+
"AND (COALESCE(event_at,created)<? OR (COALESCE(event_at,created)=? AND rowid<?)) "
|
|
2239
|
+
"ORDER BY COALESCE(event_at,created) DESC,rowid DESC LIMIT ?",
|
|
2240
|
+
(row['client_id'], row['tg_chat_id'], thread, at, at, row['inbox_rowid'], self.JUDGE_HISTORY))]
|
|
2241
|
+
# This agent's own published messages are in the outbox, not the inbox.
|
|
2242
|
+
own = f"this agent ({row['label']}, @{account['username']})"
|
|
2243
|
+
earlier += [(r['created'], 0, {'sender': own, 'text': r['text']}) for r in db.execute(
|
|
2244
|
+
"SELECT text,created FROM outbox WHERE client_id=? AND chat_id=? AND thread_id=? AND status='sent' "
|
|
2245
|
+
"AND created<=? ORDER BY created DESC LIMIT ?",
|
|
2246
|
+
(row['client_id'], row['tg_chat_id'], thread, at, self.JUDGE_HISTORY))]
|
|
2247
|
+
earlier.sort(key=lambda item: (item[0], item[1]))
|
|
2248
|
+
return {'agent_label': row['label'], 'bot_username': account['username'],
|
|
2249
|
+
'history': [entry for _, _, entry in earlier[-self.JUDGE_HISTORY:]],
|
|
2250
|
+
'candidate': {'sender': person(payload.get('sender')), 'text': payload.get('text')}}
|
|
2251
|
+
|
|
2252
|
+
def judge(self):
|
|
2253
|
+
"""Run the optional model judge once, outside a collection.
|
|
2254
|
+
|
|
2255
|
+
A single-threaded listener collects without judging, announces what
|
|
2256
|
+
arrived, then calls this, so a message that addresses the agent never
|
|
2257
|
+
waits on a model call. It skips when another collector holds the lock.
|
|
2258
|
+
"""
|
|
2259
|
+
with self._lock('collector') as acquired:
|
|
2260
|
+
if not acquired:
|
|
2261
|
+
return
|
|
2262
|
+
try:
|
|
2263
|
+
self._judge_pending()
|
|
2264
|
+
except Exception:
|
|
2265
|
+
pass
|
|
2266
|
+
|
|
2267
|
+
def _delivery_count(self):
|
|
2268
|
+
with self._db() as db:
|
|
2269
|
+
return db.execute('SELECT count(*) FROM inbox WHERE context=0').fetchone()[0]
|
|
2270
|
+
|
|
2271
|
+
def _judge_pending(self):
|
|
2272
|
+
"""Ask the model about queued context messages; never fails collection.
|
|
2273
|
+
|
|
2274
|
+
Only long-running collectors call this (``collect(judge=True)``), so a
|
|
2275
|
+
hook or a tool call never waits on the model. One message is claimed at
|
|
2276
|
+
a time, at most JUDGE_PER_COLLECT per collection, and no call starts
|
|
2277
|
+
unless it can finish within JUDGE_BUDGET seconds of the first. A message
|
|
2278
|
+
is judged once at most. A "yes" delivers it as addressed with
|
|
2279
|
+
``addressed_by: 'model'``; "no", an error, an expired wait, a missing
|
|
2280
|
+
model or a reached cap keep it as context. Runs under the collector lock.
|
|
2281
|
+
"""
|
|
2282
|
+
with self._db() as db:
|
|
2283
|
+
if not db.execute("SELECT 1 FROM judge_queue WHERE status='queued' LIMIT 1").fetchone():
|
|
2284
|
+
return
|
|
2285
|
+
now = self.clock()
|
|
2286
|
+
judge = self._judge_ready()
|
|
2287
|
+
with self._tx() as db:
|
|
2288
|
+
db.execute("UPDATE judge_queue SET status='expired',updated=? WHERE status IN ('queued','judging') AND created<?",
|
|
2289
|
+
(now, now - self.JUDGE_MAX_AGE))
|
|
2290
|
+
# Rows whose inbox entry or connection is gone can never be judged.
|
|
2291
|
+
db.execute("UPDATE judge_queue SET status='skipped',updated=? WHERE status='queued' AND (inbox_id NOT IN "
|
|
2292
|
+
"(SELECT id FROM inbox) OR client_id NOT IN (SELECT client_id FROM bindings WHERE connected=1))",
|
|
2293
|
+
(now,))
|
|
2294
|
+
db.execute('DELETE FROM judge_queue WHERE updated<?', (now - 86400,))
|
|
2295
|
+
if judge is None:
|
|
2296
|
+
db.execute("UPDATE judge_queue SET status='no_model',updated=? WHERE status='queued'", (now,))
|
|
2297
|
+
return
|
|
2298
|
+
deadline = time.monotonic() + self.JUDGE_BUDGET
|
|
2299
|
+
for _ in range(self.JUDGE_PER_COLLECT):
|
|
2300
|
+
if time.monotonic() + judge_module.TIMEOUT_SECONDS > deadline:
|
|
2301
|
+
return
|
|
2302
|
+
claimed = self._claim_judgment()
|
|
2303
|
+
if claimed is None:
|
|
2304
|
+
return
|
|
2305
|
+
inbox_id, client_id, context = claimed
|
|
2306
|
+
error = None
|
|
2307
|
+
try:
|
|
2308
|
+
verdict = judge(**context)
|
|
2309
|
+
if not isinstance(verdict, bool):
|
|
2310
|
+
raise judge_module.JudgeUnavailable('judge_no_answer')
|
|
2311
|
+
except judge_module.JudgeUnavailable as failure:
|
|
2312
|
+
verdict, error = None, failure.code
|
|
2313
|
+
except Exception:
|
|
2314
|
+
verdict, error = None, 'judge_failed'
|
|
2315
|
+
with self._tx() as db:
|
|
2316
|
+
status = 'failed' if verdict is None else 'yes' if verdict else 'no'
|
|
2317
|
+
if verdict:
|
|
2318
|
+
status, error = self._promote_judged(db, inbox_id, client_id)
|
|
2319
|
+
db.execute('UPDATE judge_queue SET status=?,error=?,updated=? WHERE inbox_id=?',
|
|
2320
|
+
(status, error, self.clock(), inbox_id))
|
|
2321
|
+
|
|
2322
|
+
def _claim_judgment(self):
|
|
2323
|
+
"""Mark the oldest judgeable queued message as judging; its context, or None."""
|
|
2324
|
+
now = self.clock()
|
|
2325
|
+
with self._tx() as db:
|
|
2326
|
+
account = self._account(db)
|
|
2327
|
+
for row in db.execute(
|
|
2328
|
+
"SELECT q.inbox_id,i.rowid AS inbox_rowid,i.id,i.client_id,i.payload,i.created,i.event_at,i.tg_chat_id,i.context,"
|
|
2329
|
+
"b.model_judge,b.delivery_filter,c.label "
|
|
2330
|
+
"FROM judge_queue q JOIN inbox i ON i.id=q.inbox_id "
|
|
2331
|
+
"JOIN bindings b ON b.client_id=q.client_id AND b.connected=1 "
|
|
2332
|
+
"JOIN clients c ON c.id=q.client_id AND c.active=1 "
|
|
2333
|
+
"WHERE q.status='queued' ORDER BY q.created,q.rowid").fetchall():
|
|
2334
|
+
if not row['model_judge'] or row['delivery_filter'] != 'addressed' or not row['context']:
|
|
2335
|
+
status = 'skipped'
|
|
2336
|
+
elif any(db.execute("SELECT count(*) FROM judge_queue WHERE client_id=? AND status IN ('yes','no','failed') "
|
|
2337
|
+
"AND updated>?", (row['client_id'], now - window)).fetchone()[0] >= limit
|
|
2338
|
+
for limit, window in self.JUDGE_LIMITS):
|
|
2339
|
+
status = 'limited'
|
|
2340
|
+
else:
|
|
2341
|
+
db.execute("UPDATE judge_queue SET status='judging',updated=? WHERE inbox_id=?", (now, row['inbox_id']))
|
|
2342
|
+
return row['inbox_id'], row['client_id'], self._judge_context(db, row, account)
|
|
2343
|
+
db.execute('UPDATE judge_queue SET status=?,updated=? WHERE inbox_id=?', (status, now, row['inbox_id']))
|
|
2344
|
+
return None
|
|
2345
|
+
|
|
2346
|
+
def _promote_judged(self, db, inbox_id, client_id):
|
|
2347
|
+
"""Turn a context entry the model judged as addressed into a delivery."""
|
|
2348
|
+
row = db.execute('SELECT payload FROM inbox WHERE id=? AND client_id=? AND context=1', (inbox_id, client_id)).fetchone()
|
|
2349
|
+
if row is None:
|
|
2350
|
+
return 'skipped', None
|
|
2351
|
+
if db.execute('SELECT count(*) FROM inbox WHERE client_id=? AND acknowledged=0',
|
|
2352
|
+
(client_id,)).fetchone()[0] >= self.queue_limit:
|
|
2353
|
+
return 'yes', 'queue_full'
|
|
2354
|
+
payload = json.loads(row['payload'])
|
|
2355
|
+
payload.pop('context_reason', None)
|
|
2356
|
+
payload['addressed'], payload['addressed_by'] = True, 'model'
|
|
2357
|
+
# It becomes new, unacknowledged work: poll, push and watch see it as any
|
|
2358
|
+
# other delivery, announced at once like other addressed messages.
|
|
2359
|
+
db.execute('UPDATE inbox SET payload=?,context=0,acknowledged=0,created=? WHERE id=?',
|
|
2360
|
+
(json.dumps(payload, ensure_ascii=False), self.clock(), inbox_id))
|
|
2361
|
+
return 'yes', None
|
|
2362
|
+
|
|
2363
|
+
def collect(self, *, timeout=0, judge=False, routed=None):
|
|
2364
|
+
"""Fetch and route one page of Telegram updates.
|
|
2365
|
+
|
|
2366
|
+
``judge`` also runs the optional model judge afterwards. Only
|
|
2367
|
+
long-running collectors pass it, so hooks and tool calls never wait on
|
|
2368
|
+
a model call.
|
|
2369
|
+
"""
|
|
2370
|
+
if not _integer(timeout) or not 0 <= timeout <= 20:
|
|
2371
|
+
raise CoreError('invalid_collect_timeout')
|
|
2372
|
+
with self._lock('collector') as acquired:
|
|
2373
|
+
if not acquired:
|
|
2374
|
+
return {'status': 'busy', 'updates': 0}
|
|
2375
|
+
with self._db() as db:
|
|
2376
|
+
account = self._account(db)
|
|
2377
|
+
cursor = account['cursor']
|
|
2378
|
+
newer = self._newer_collector(account)
|
|
2379
|
+
if newer is not None:
|
|
2380
|
+
# A newer runtime collects for this bot; its routing wins.
|
|
2381
|
+
return {'status': 'busy', 'updates': 0, 'reason': 'newer_runtime', 'collector_version': newer}
|
|
2382
|
+
if (account['aware_intake'] is not None and account['last_intake'] is not None
|
|
2383
|
+
and account['last_intake'] > account['aware_intake']):
|
|
2384
|
+
# Every collection by a runtime that knows the record sets
|
|
2385
|
+
# aware_intake with last_intake; a later last_intake came
|
|
2386
|
+
# from a runtime that predates it.
|
|
2387
|
+
with self._tx() as db:
|
|
2388
|
+
db.execute('UPDATE account SET legacy_intake_at=? WHERE singleton=1', (account['last_intake'],))
|
|
2389
|
+
steps, started = {}, time.monotonic()
|
|
2390
|
+
# Time since the last fetch returned: an update that arrives in
|
|
2391
|
+
# that gap waits for this fetch.
|
|
2392
|
+
gap = None if self._poll_end is None else round((started - self._poll_end) * 1000)
|
|
2393
|
+
|
|
2394
|
+
def step(name, since):
|
|
2395
|
+
steps[name] = round((time.monotonic() - since) * 1000)
|
|
2396
|
+
return time.monotonic()
|
|
2397
|
+
try:
|
|
2398
|
+
mark = time.monotonic()
|
|
2399
|
+
webhook = self.transport.get_webhook_info()
|
|
2400
|
+
mark = step('webhook', mark)
|
|
2401
|
+
if not isinstance(webhook, dict) or not isinstance(webhook.get('url'), str):
|
|
2402
|
+
raise CoreError('invalid_transport_response')
|
|
2403
|
+
if webhook.get('url'):
|
|
2404
|
+
raise CoreError('webhook_conflict')
|
|
2405
|
+
updates = self.transport.get_updates(offset=cursor, timeout=timeout)
|
|
2406
|
+
self._poll_end = time.monotonic()
|
|
2407
|
+
mark = step('poll', mark)
|
|
2408
|
+
if not isinstance(updates, list) or len(updates) > 100:
|
|
2409
|
+
raise CoreError('invalid_transport_response')
|
|
2410
|
+
if any(not isinstance(u, dict) or not _integer(u.get('update_id')) or u['update_id'] < 0 for u in updates):
|
|
2411
|
+
raise CoreError('invalid_transport_response')
|
|
2412
|
+
self._overflowed = 0
|
|
2413
|
+
with self._tx() as db:
|
|
2414
|
+
accepted = 0
|
|
2415
|
+
for update in sorted(updates, key=lambda u: u['update_id']):
|
|
2416
|
+
if update['update_id'] < cursor:
|
|
2417
|
+
continue
|
|
2418
|
+
self._route_update(db, update, account, self.clock())
|
|
2419
|
+
cursor = update['update_id'] + 1
|
|
2420
|
+
accepted += 1
|
|
2421
|
+
self._prune_context(db, self.clock())
|
|
2422
|
+
now = self.clock()
|
|
2423
|
+
db.execute('UPDATE account SET cursor=?,last_gap_at=CASE WHEN last_intake IS NOT NULL AND ?-last_intake>=86400 THEN ? ELSE last_gap_at END,last_intake=?,last_attempt=?,intake_error=NULL,aware_intake=? WHERE singleton=1', (cursor, now, now, now, now, now))
|
|
2424
|
+
if timeout > 0 or judge:
|
|
2425
|
+
# Only long-running collectors claim the floor. A one-shot
|
|
2426
|
+
# poll from a newer hook or tool call must not silence an
|
|
2427
|
+
# older long-poller, or nothing would long-poll meanwhile.
|
|
2428
|
+
db.execute('UPDATE account SET collector_version=?,collector_seen=? WHERE singleton=1',
|
|
2429
|
+
(self.runtime_version, now))
|
|
2430
|
+
mark = step('route', mark)
|
|
2431
|
+
if routed is not None and accepted:
|
|
2432
|
+
# Waiting agents hear about new deliveries now, not after
|
|
2433
|
+
# the courtesy steps and the model judge below.
|
|
2434
|
+
try:
|
|
2435
|
+
routed()
|
|
2436
|
+
except Exception:
|
|
2437
|
+
pass
|
|
2438
|
+
self._probe_bot_admin(account)
|
|
2439
|
+
mark = step('admin_probe', mark)
|
|
2440
|
+
try:
|
|
2441
|
+
self._set_bot_menu()
|
|
2442
|
+
except Exception:
|
|
2443
|
+
# The command menu is a convenience; commands work without it.
|
|
2444
|
+
pass
|
|
2445
|
+
mark = step('menu', mark)
|
|
2446
|
+
try:
|
|
2447
|
+
self._expire_approvals()
|
|
2448
|
+
except Exception:
|
|
2449
|
+
# Telling agents about expired requests is best effort.
|
|
2450
|
+
pass
|
|
2451
|
+
mark = step('approvals', mark)
|
|
2452
|
+
try:
|
|
2453
|
+
self._answer_widget_queries()
|
|
2454
|
+
except Exception:
|
|
2455
|
+
# A widget answer is best effort; an unanswered one times out in the widget.
|
|
2456
|
+
pass
|
|
2457
|
+
mark = step('panel_answers', mark)
|
|
2458
|
+
try:
|
|
2459
|
+
self._send_panel_requests()
|
|
2460
|
+
except Exception:
|
|
2461
|
+
pass
|
|
2462
|
+
mark = step('panel_sends', mark)
|
|
2463
|
+
try:
|
|
2464
|
+
self._answer_callbacks()
|
|
2465
|
+
except Exception:
|
|
2466
|
+
# Answering a button press is a courtesy too.
|
|
2467
|
+
pass
|
|
2468
|
+
mark = step('button_answers', mark)
|
|
2469
|
+
try:
|
|
2470
|
+
self._send_start_replies()
|
|
2471
|
+
except Exception:
|
|
2472
|
+
# A courtesy answer must never turn a good intake into a failure.
|
|
2473
|
+
pass
|
|
2474
|
+
mark = step('start_replies', mark)
|
|
2475
|
+
try:
|
|
2476
|
+
self._send_queue_full_notices()
|
|
2477
|
+
except Exception:
|
|
2478
|
+
# The notice is retried at the next collection.
|
|
2479
|
+
pass
|
|
2480
|
+
mark = step('queue_full_notices', mark)
|
|
2481
|
+
try:
|
|
2482
|
+
if judge:
|
|
2483
|
+
before = self._delivery_count() if routed is not None else None
|
|
2484
|
+
self._judge_pending()
|
|
2485
|
+
if before is not None and self._delivery_count() != before:
|
|
2486
|
+
# A "yes" made a context message a delivery.
|
|
2487
|
+
routed()
|
|
2488
|
+
except Exception:
|
|
2489
|
+
# Neither may the optional model judge.
|
|
2490
|
+
pass
|
|
2491
|
+
step('judge', mark)
|
|
2492
|
+
work = sum(ms for name, ms in steps.items() if name != 'poll')
|
|
2493
|
+
if accepted or work >= self.SLOW_CYCLE_MS:
|
|
2494
|
+
kinds = {}
|
|
2495
|
+
for update in updates:
|
|
2496
|
+
kind = next((key for key in update if key != 'update_id'), 'unknown')
|
|
2497
|
+
kinds[kind] = kinds.get(kind, 0) + 1
|
|
2498
|
+
detail = {'updates': accepted, 'kinds': kinds, 'long_poll': timeout > 0,
|
|
2499
|
+
'gap_ms': gap, 'work_ms': work,
|
|
2500
|
+
'steps_ms': {name: ms for name, ms in steps.items() if ms}}
|
|
2501
|
+
if self._overflowed:
|
|
2502
|
+
detail['queue_full'] = self._overflowed
|
|
2503
|
+
self.record_activity('cycle', detail)
|
|
2504
|
+
return {'status': 'ok', 'updates': accepted, 'cursor': cursor}
|
|
2505
|
+
except (TransportError, CoreError) as error:
|
|
2506
|
+
code = error.code if isinstance(error, CoreError) else 'telegram_intake_failed'
|
|
2507
|
+
with self._tx() as db:
|
|
2508
|
+
db.execute('UPDATE account SET last_attempt=?,intake_error=? WHERE singleton=1', (self.clock(), code))
|
|
2509
|
+
self.record_activity('cycle', {'error': code, 'steps_ms': steps,
|
|
2510
|
+
'elapsed_ms': round((time.monotonic() - started) * 1000)})
|
|
2511
|
+
raise CoreError(code) from None
|
|
2512
|
+
|
|
2513
|
+
# A collection whose work besides the long poll takes this long is logged
|
|
2514
|
+
# even when it routed nothing.
|
|
2515
|
+
SLOW_CYCLE_MS = 1000
|
|
2516
|
+
|
|
2517
|
+
# How long a newer runtime's last collection keeps older runtimes from
|
|
2518
|
+
# collecting. Past it the newer one counts as gone, so nobody goes deaf.
|
|
2519
|
+
COLLECTOR_STALE = 120
|
|
2520
|
+
# How long without a fetch attempt before status calls the always-on
|
|
2521
|
+
# collector down. It polls every 20 seconds, backs off at most 120 seconds
|
|
2522
|
+
# after failures, and its watchdog restarts it after 300 seconds stuck.
|
|
2523
|
+
SERVICE_STALE = 360
|
|
2524
|
+
# Agents are told about a down collector at most this often, account-wide.
|
|
2525
|
+
DOWN_NOTICE_INTERVAL = 3600
|
|
2526
|
+
|
|
2527
|
+
def collector_down_notice_due(self):
|
|
2528
|
+
"""The collector status when a down notice should go to an agent now, else None.
|
|
2529
|
+
|
|
2530
|
+
At most one notice per DOWN_NOTICE_INTERVAL for the whole account, and
|
|
2531
|
+
none in the first minutes after the machine started, before the
|
|
2532
|
+
service had its first chance to fetch.
|
|
2533
|
+
"""
|
|
2534
|
+
if time.monotonic() < self.SERVICE_STALE:
|
|
2535
|
+
return None
|
|
2536
|
+
with self._tx() as db:
|
|
2537
|
+
collector = self.collector_status(db)
|
|
2538
|
+
if not collector['service_stale']:
|
|
2539
|
+
return None
|
|
2540
|
+
last = self._account(db)['down_notice_at']
|
|
2541
|
+
now = self.clock()
|
|
2542
|
+
if last is not None and 0 <= now - last < self.DOWN_NOTICE_INTERVAL:
|
|
2543
|
+
return None
|
|
2544
|
+
db.execute('UPDATE account SET down_notice_at=? WHERE singleton=1', (now,))
|
|
2545
|
+
return collector
|
|
2546
|
+
|
|
2547
|
+
def _newer_collector(self, account):
|
|
2548
|
+
"""The version of a newer runtime that collected recently, or None."""
|
|
2549
|
+
recorded, seen = account['collector_version'], account['collector_seen']
|
|
2550
|
+
# A clock that went backwards makes the record stale, not fresh forever.
|
|
2551
|
+
if recorded is None or seen is None or not 0 <= self.clock() - seen < self.COLLECTOR_STALE:
|
|
2552
|
+
return None
|
|
2553
|
+
ours, theirs = _version_key(self.runtime_version), _version_key(recorded)
|
|
2554
|
+
return recorded if ours is not None and theirs is not None and theirs > ours else None
|
|
2555
|
+
|
|
2556
|
+
# The activity log keeps this many entries of each kind.
|
|
2557
|
+
ACTIVITY_KEEP = 100
|
|
2558
|
+
ACTIVITY_KINDS = ('cycle', 'owner', 'relay', 'serve')
|
|
2559
|
+
|
|
2560
|
+
def record_activity(self, kind, detail, at=None):
|
|
2561
|
+
"""Append one entry to the bounded activity log; never fails the caller.
|
|
2562
|
+
|
|
2563
|
+
It records timings for diagnosing lag (collector cycles, owner actions,
|
|
2564
|
+
relay requests, collector events), never message text or chat ids.
|
|
2565
|
+
|
|
2566
|
+
Never call it while a write transaction (_tx) is open in this thread:
|
|
2567
|
+
it opens its own, would wait out the busy timeout, and the entry would
|
|
2568
|
+
be dropped without a trace.
|
|
2569
|
+
"""
|
|
2570
|
+
self.record_activities([(kind, detail, at)])
|
|
2571
|
+
|
|
2572
|
+
def record_activities(self, entries):
|
|
2573
|
+
"""Append several (kind, detail, at) entries in one transaction; never fails the caller.
|
|
2574
|
+
|
|
2575
|
+
The same rule as record_activity: never inside an open _tx.
|
|
2576
|
+
"""
|
|
2577
|
+
if not entries:
|
|
2578
|
+
return
|
|
2579
|
+
try:
|
|
2580
|
+
with self._tx() as db:
|
|
2581
|
+
for kind, detail, at in entries:
|
|
2582
|
+
db.execute('INSERT INTO activity(at,kind,detail) VALUES(?,?,?)',
|
|
2583
|
+
(self.clock() if at is None else at, kind,
|
|
2584
|
+
json.dumps(detail, separators=(',', ':'), sort_keys=True)))
|
|
2585
|
+
for kind in {kind for kind, _, _ in entries}:
|
|
2586
|
+
db.execute('DELETE FROM activity WHERE kind=? AND id NOT IN '
|
|
2587
|
+
'(SELECT id FROM activity WHERE kind=? ORDER BY id DESC LIMIT ?)',
|
|
2588
|
+
(kind, kind, self.ACTIVITY_KEEP))
|
|
2589
|
+
except Exception:
|
|
2590
|
+
pass
|
|
2591
|
+
|
|
2592
|
+
def activity(self, limit=None):
|
|
2593
|
+
"""The activity log, oldest first."""
|
|
2594
|
+
with self._db() as db:
|
|
2595
|
+
rows = db.execute('SELECT at,kind,detail FROM activity ORDER BY id DESC LIMIT ?',
|
|
2596
|
+
(limit or self.ACTIVITY_KEEP * len(self.ACTIVITY_KINDS),)).fetchall()
|
|
2597
|
+
return [{'at': row['at'], 'kind': row['kind'], **json.loads(row['detail'])} for row in reversed(rows)]
|
|
2598
|
+
|
|
2599
|
+
def collector_status(self, db=None):
|
|
2600
|
+
"""Which runtime collects for this bot, and whether this one stands aside."""
|
|
2601
|
+
if db is None:
|
|
2602
|
+
with self._db() as db:
|
|
2603
|
+
return self.collector_status(db)
|
|
2604
|
+
account = self._account(db)
|
|
2605
|
+
newer = self._newer_collector(account)
|
|
2606
|
+
legacy = account['legacy_intake_at']
|
|
2607
|
+
# An older runtime's collection is worth mentioning for a week.
|
|
2608
|
+
recent_legacy = legacy if legacy is not None and self.clock() - legacy < 7 * 86400 else None
|
|
2609
|
+
from . import serve
|
|
2610
|
+
# With the always-on collector installed, someone fetches every few
|
|
2611
|
+
# seconds; a long silence means it is down or stuck.
|
|
2612
|
+
service = serve.pointer(self.state_dir) is not None
|
|
2613
|
+
# Attempts count, failed ones included: a network outage is reported
|
|
2614
|
+
# as an intake error, not as a collector that stopped.
|
|
2615
|
+
last = account['last_attempt']
|
|
2616
|
+
stale = service and (last is None or self.clock() - last > self.SERVICE_STALE)
|
|
2617
|
+
return {'runtime_version': self.runtime_version, 'collector_version': account['collector_version'],
|
|
2618
|
+
'collector_seen_at': account['collector_seen'], 'deferring_to': newer,
|
|
2619
|
+
'legacy_intake_at': recent_legacy, 'service_installed': service, 'service_stale': stale,
|
|
2620
|
+
'last_attempt_at': last}
|
|
2621
|
+
|
|
2622
|
+
# The bot's command menu in private chats; bump the version when it changes.
|
|
2623
|
+
BOT_MENU = ({'command': 'start', 'description': 'Check that this bot can message you'},
|
|
2624
|
+
{'command': 'settings', 'description': "Change your agents' settings"})
|
|
2625
|
+
BOT_MENU_VERSION = 1
|
|
2626
|
+
|
|
2627
|
+
def _set_bot_menu(self):
|
|
2628
|
+
"""Set the bot's private-chat command menu once per menu version; never fails collection.
|
|
2629
|
+
|
|
2630
|
+
Only private chats are touched, so a group's command menu stays as it is.
|
|
2631
|
+
"""
|
|
2632
|
+
with self._db() as db:
|
|
2633
|
+
if (self._account(db)['menu_version'] or 0) >= self.BOT_MENU_VERSION:
|
|
2634
|
+
return
|
|
2635
|
+
self.transport.set_my_commands(list(self.BOT_MENU), {'type': 'all_private_chats'})
|
|
2636
|
+
with self._tx() as db:
|
|
2637
|
+
db.execute('UPDATE account SET menu_version=? WHERE singleton=1', (self.BOT_MENU_VERSION,))
|
|
2638
|
+
|
|
2639
|
+
def _probe_bot_admin(self, account):
|
|
2640
|
+
"""Keep bot_admin flags current with getChatMember; never fails collection.
|
|
2641
|
+
|
|
2642
|
+
Reaction updates arrive only while the bot is an administrator. A binding
|
|
2643
|
+
with an unknown flag is checked first, and a known flag is checked again
|
|
2644
|
+
BOT_ADMIN_RECHECK seconds after it was last set, because the
|
|
2645
|
+
my_chat_member update that would change it can be missed: an older
|
|
2646
|
+
runtime on the same bot may consume it, or the promotion may predate the
|
|
2647
|
+
pairing. A definite client error means the bot cannot even see the chat,
|
|
2648
|
+
which is recorded as not-admin; other failures keep the flag as it was.
|
|
2649
|
+
|
|
2650
|
+
Collection runs this while holding the collector lock, so each call
|
|
2651
|
+
makes at most one network request, and a binding whose probe failed is
|
|
2652
|
+
tried again only BOT_ADMIN_RETRY seconds after it ended. A slow or
|
|
2653
|
+
failing probe therefore cannot delay intake on every collection.
|
|
2654
|
+
"""
|
|
2655
|
+
now = self.clock()
|
|
2656
|
+
with self._db() as db:
|
|
2657
|
+
pending = db.execute('SELECT b.client_id,b.chat_id FROM bindings b JOIN clients c ON c.id=b.client_id '
|
|
2658
|
+
'WHERE b.connected=1 AND c.active=1 AND ('
|
|
2659
|
+
'(b.bot_admin IS NULL AND (b.bot_admin_probed IS NULL OR b.bot_admin_probed<=?)) '
|
|
2660
|
+
'OR (b.bot_admin IS NOT NULL AND (b.bot_admin_probed IS NULL OR b.bot_admin_probed<=?))) '
|
|
2661
|
+
'ORDER BY b.bot_admin IS NOT NULL, b.bot_admin_probed IS NOT NULL, b.bot_admin_probed LIMIT 1',
|
|
2662
|
+
(now - self.BOT_ADMIN_RETRY, now - self.BOT_ADMIN_RECHECK)).fetchall()
|
|
2663
|
+
for row in pending:
|
|
2664
|
+
admin = None
|
|
2665
|
+
try:
|
|
2666
|
+
member = self.transport.get_chat_member(row['chat_id'], account['bot_id'])
|
|
2667
|
+
admin = 1 if isinstance(member, dict) and member.get('status') == 'administrator' else 0
|
|
2668
|
+
except TransportError as error:
|
|
2669
|
+
if isinstance(error.code, int) and 400 <= error.code < 500 and error.code != 429:
|
|
2670
|
+
admin = 0
|
|
2671
|
+
except Exception:
|
|
2672
|
+
admin = None
|
|
2673
|
+
with self._tx() as db:
|
|
2674
|
+
if admin is None:
|
|
2675
|
+
# A failed check keeps the flag; a known one is retried at the next recheck.
|
|
2676
|
+
db.execute('UPDATE bindings SET bot_admin_probed=? WHERE client_id=? AND connected=1',
|
|
2677
|
+
(self.clock(), row['client_id']))
|
|
2678
|
+
else:
|
|
2679
|
+
db.execute('UPDATE bindings SET bot_admin=?,bot_admin_probed=? WHERE client_id=? AND connected=1',
|
|
2680
|
+
(admin, self.clock(), row['client_id']))
|
|
2681
|
+
|
|
2682
|
+
def poll(self, client_id, limit=20, lease_seconds=60):
|
|
2683
|
+
if not _integer(limit) or not 1 <= limit <= 100 or not _integer(lease_seconds) or not 1 <= lease_seconds <= 3600:
|
|
2684
|
+
raise CoreError('invalid_poll_options')
|
|
2685
|
+
now = self.clock()
|
|
2686
|
+
token = secrets.token_urlsafe(24)
|
|
2687
|
+
with self._tx() as db:
|
|
2688
|
+
binding = self._binding(db, client_id)
|
|
2689
|
+
if binding['paused'] or binding['suspended']:
|
|
2690
|
+
return {'deliveries': [], 'lease_token': None, 'paused': bool(binding['paused']), 'suspended': binding['suspended']}
|
|
2691
|
+
rows = db.execute('SELECT * FROM inbox WHERE client_id=? AND acknowledged=0 AND (lease_until IS NULL OR lease_until<=?) ORDER BY created,rowid LIMIT ?', (client_id, now, limit)).fetchall()
|
|
2692
|
+
deliveries = []
|
|
2693
|
+
for row in rows:
|
|
2694
|
+
db.execute('UPDATE inbox SET lease_token=?,lease_until=? WHERE id=?', (token, now + lease_seconds, row['id']))
|
|
2695
|
+
delivery = json.loads(row['payload'])
|
|
2696
|
+
delivery.update(delivery_id=row['id'], conversation_id=row['conversation_id'], received_at=row['created'])
|
|
2697
|
+
if row['outbox_id']:
|
|
2698
|
+
published = db.execute('SELECT status,message_id FROM outbox WHERE id=?', (row['outbox_id'],)).fetchone()
|
|
2699
|
+
delivery['publication'] = {'outbox_id': row['outbox_id'], 'status': published['status'], 'message_id': published['message_id']}
|
|
2700
|
+
deliveries.append(delivery)
|
|
2701
|
+
kept = self._queue_full_kept(db, client_id)
|
|
2702
|
+
result = {'deliveries': deliveries, 'lease_token': token if deliveries else None, 'lease_expires_at': now + lease_seconds if deliveries else None, 'paused': False, 'suspended': None}
|
|
2703
|
+
if kept:
|
|
2704
|
+
# Only when it happened, so a normal poll result stays the same.
|
|
2705
|
+
result['queue_full_kept'] = {
|
|
2706
|
+
'count': kept,
|
|
2707
|
+
'note': ('Your queue reached its limit, so these newer messages were kept in history only, '
|
|
2708
|
+
'with context_reason "queue_full". Read them with messages_history.')}
|
|
2709
|
+
return result
|
|
2710
|
+
|
|
2711
|
+
@staticmethod
|
|
2712
|
+
def _history_encode(value):
|
|
2713
|
+
return base64.urlsafe_b64encode(value).rstrip(b'=').decode('ascii')
|
|
2714
|
+
|
|
2715
|
+
@staticmethod
|
|
2716
|
+
def _history_decode(value):
|
|
2717
|
+
return base64.b64decode(value + '=' * (-len(value) % 4), altchars=b'-_', validate=True)
|
|
2718
|
+
|
|
2719
|
+
def _history_cursor(self, snapshot, key):
|
|
2720
|
+
encoded = self._history_encode(json.dumps(snapshot, separators=(',', ':'), allow_nan=False).encode())
|
|
2721
|
+
signature = self._history_encode(hmac.digest(key, encoded.encode('ascii'), 'sha256'))
|
|
2722
|
+
return encoded + '.' + signature
|
|
2723
|
+
|
|
2724
|
+
def _history_snapshot(self, cursor, key, client_id, now):
|
|
2725
|
+
try:
|
|
2726
|
+
encoded, signature = cursor.split('.')
|
|
2727
|
+
expected = hmac.digest(key, encoded.encode('ascii'), 'sha256')
|
|
2728
|
+
if not hmac.compare_digest(expected, self._history_decode(signature)):
|
|
2729
|
+
raise ValueError()
|
|
2730
|
+
snapshot = json.loads(self._history_decode(encoded))
|
|
2731
|
+
if not isinstance(snapshot, dict) or set(snapshot) != {'v', 'client', 'at', 'inbox_max', 'outbox_max', 'last'}:
|
|
2732
|
+
raise ValueError()
|
|
2733
|
+
if snapshot['v'] != 1 or snapshot['client'] != client_id:
|
|
2734
|
+
raise ValueError()
|
|
2735
|
+
at = snapshot['at']
|
|
2736
|
+
if isinstance(at, bool) or not isinstance(at, (int, float)) or not math.isfinite(at):
|
|
2737
|
+
raise ValueError()
|
|
2738
|
+
for field in ('inbox_max', 'outbox_max'):
|
|
2739
|
+
if not _integer(snapshot[field]) or not 0 <= snapshot[field] <= 9223372036854775807:
|
|
2740
|
+
raise ValueError()
|
|
2741
|
+
last = snapshot['last']
|
|
2742
|
+
if not isinstance(last, list) or len(last) != 3:
|
|
2743
|
+
raise ValueError()
|
|
2744
|
+
stamp, stream, sequence = last
|
|
2745
|
+
if isinstance(stamp, bool) or not isinstance(stamp, (int, float)) or not math.isfinite(stamp) or not at - self.HISTORY_WINDOW <= stamp <= at:
|
|
2746
|
+
raise ValueError()
|
|
2747
|
+
if not _integer(stream) or stream not in (0, 1) or not _integer(sequence) or not 1 <= sequence <= snapshot['inbox_max' if stream == 0 else 'outbox_max']:
|
|
2748
|
+
raise ValueError()
|
|
2749
|
+
except (ValueError, TypeError, UnicodeError, OverflowError):
|
|
2750
|
+
raise CoreError('history_cursor_invalid') from None
|
|
2751
|
+
if now < at or now >= at + self.HISTORY_CURSOR_TTL:
|
|
2752
|
+
raise CoreError('history_cursor_expired')
|
|
2753
|
+
return snapshot
|
|
2754
|
+
|
|
2755
|
+
def history(self, client_id, limit=20, cursor=None):
|
|
2756
|
+
"""Read captured context without claiming or acknowledging any work.
|
|
2757
|
+
|
|
2758
|
+
A cursor freezes the event window and row membership for 15 minutes,
|
|
2759
|
+
except that context older than the history window can be pruned between
|
|
2760
|
+
pages and then drops out. Acknowledgment and publication statuses reflect
|
|
2761
|
+
the time of each read.
|
|
2762
|
+
"""
|
|
2763
|
+
if not _integer(limit) or not 1 <= limit <= 50:
|
|
2764
|
+
raise CoreError('invalid_history_options')
|
|
2765
|
+
if cursor is not None and (not isinstance(cursor, str) or not 1 <= len(cursor) <= 2048):
|
|
2766
|
+
raise CoreError('history_cursor_invalid')
|
|
2767
|
+
now = self.clock()
|
|
2768
|
+
with self._db() as db:
|
|
2769
|
+
# A deferred, query-only transaction provides a consistent page without
|
|
2770
|
+
# acquiring the write lock or changing cursor, leases or send recovery.
|
|
2771
|
+
db.execute('PRAGMA query_only=ON')
|
|
2772
|
+
db.execute('BEGIN')
|
|
2773
|
+
binding = self._binding(db, client_id)
|
|
2774
|
+
client = self._client(db, client_id)
|
|
2775
|
+
account = self._account(db)
|
|
2776
|
+
key = db.execute('SELECT secret FROM history_keys WHERE singleton=1').fetchone()['secret']
|
|
2777
|
+
if cursor is None:
|
|
2778
|
+
snapshot = {'v': 1, 'client': client_id, 'at': now,
|
|
2779
|
+
'inbox_max': db.execute('SELECT COALESCE(MAX(rowid),0) FROM inbox WHERE client_id=?', (client_id,)).fetchone()[0],
|
|
2780
|
+
'outbox_max': db.execute('SELECT COALESCE(MAX(rowid),0) FROM outbox WHERE client_id=?', (client_id,)).fetchone()[0],
|
|
2781
|
+
'last': None}
|
|
2782
|
+
else:
|
|
2783
|
+
snapshot = self._history_snapshot(cursor, key, client_id, now)
|
|
2784
|
+
start, end = snapshot['at'] - self.HISTORY_WINDOW, snapshot['at']
|
|
2785
|
+
query = """
|
|
2786
|
+
WITH events AS (
|
|
2787
|
+
SELECT 0 AS stream,rowid AS sequence,id,COALESCE(event_at,created) AS stamp
|
|
2788
|
+
FROM inbox WHERE client_id=? AND rowid<=? AND COALESCE(event_at,created)>=? AND COALESCE(event_at,created)<=?
|
|
2789
|
+
UNION ALL
|
|
2790
|
+
SELECT 1 AS stream,rowid AS sequence,id,created AS stamp
|
|
2791
|
+
FROM outbox WHERE client_id=? AND rowid<=? AND created>=? AND created<=?
|
|
2792
|
+
) SELECT * FROM events
|
|
2793
|
+
"""
|
|
2794
|
+
params = [client_id, snapshot['inbox_max'], start, end, client_id, snapshot['outbox_max'], start, end]
|
|
2795
|
+
if snapshot['last'] is not None:
|
|
2796
|
+
query += ' WHERE (stamp,stream,sequence)<(?,?,?)'
|
|
2797
|
+
params.extend(snapshot['last'])
|
|
2798
|
+
query += ' ORDER BY stamp DESC,stream DESC,sequence DESC LIMIT ?'
|
|
2799
|
+
params.append(limit + 1)
|
|
2800
|
+
events = db.execute(query, params).fetchall()
|
|
2801
|
+
messages = []
|
|
2802
|
+
seen = []
|
|
2803
|
+
for event in events[:limit]:
|
|
2804
|
+
if event['stream'] == 0:
|
|
2805
|
+
row = db.execute('SELECT * FROM inbox WHERE id=? AND client_id=?', (event['id'], client_id)).fetchone()
|
|
2806
|
+
message = json.loads(row['payload'])
|
|
2807
|
+
if row['context'] and message.get('context_reason') == 'queue_full' and row['queue_full_read'] is None:
|
|
2808
|
+
seen.append(row['id'])
|
|
2809
|
+
message.update(direction='incoming', delivery_id=row['id'], conversation_id=row['conversation_id'],
|
|
2810
|
+
status='context' if row['context'] else 'acknowledged' if row['acknowledged'] else 'pending',
|
|
2811
|
+
event_at=event['stamp'], captured_at=row['created'], context_only=True)
|
|
2812
|
+
if row['outbox_id']:
|
|
2813
|
+
publication = db.execute('SELECT status,message_id FROM outbox WHERE id=?', (row['outbox_id'],)).fetchone()
|
|
2814
|
+
message['publication'] = {'outbox_id': row['outbox_id'], 'status': publication['status'], 'message_id': publication['message_id']}
|
|
2815
|
+
else:
|
|
2816
|
+
row = db.execute('SELECT * FROM outbox WHERE id=? AND client_id=?', (event['id'], client_id)).fetchone()
|
|
2817
|
+
message = self._outbox_status(row)
|
|
2818
|
+
message.update(origin='outgoing', direction='outgoing', kind='message', text=row['text'],
|
|
2819
|
+
logical_sender={'client_id': client_id, 'label': client['label']},
|
|
2820
|
+
actual_bot={'id': account['bot_id'], 'username': account['username']},
|
|
2821
|
+
chat_id=row['chat_id'], thread_id=row['thread_id'] or None, reply_to=row['reply_to'],
|
|
2822
|
+
event_at=event['stamp'], captured_at=row['created'], context_only=True)
|
|
2823
|
+
messages.append(message)
|
|
2824
|
+
next_cursor = None
|
|
2825
|
+
if len(events) > limit:
|
|
2826
|
+
last = events[limit - 1]
|
|
2827
|
+
snapshot['last'] = [last['stamp'], last['stream'], last['sequence']]
|
|
2828
|
+
next_cursor = self._history_cursor(snapshot, key)
|
|
2829
|
+
result = {'context_only': True, 'messages': messages, 'next_cursor': next_cursor,
|
|
2830
|
+
'coverage': {'kind': 'captured_only', 'description': 'Captured messages only; this does not backfill Telegram history.',
|
|
2831
|
+
'window_start': start, 'window_end': end, 'window_seconds': self.HISTORY_WINDOW,
|
|
2832
|
+
'snapshot_expires_at': end + self.HISTORY_CURSOR_TTL, 'statuses_as_of': now,
|
|
2833
|
+
'timestamp_policy': 'Telegram event time when valid; otherwise capture time.',
|
|
2834
|
+
'connected_at': binding['created'], 'last_gap_at': account['last_gap_at'],
|
|
2835
|
+
'possible_offline_gap': account['last_gap_at'] is not None or (account['last_intake'] is not None and now - account['last_intake'] >= self.HISTORY_WINDOW)}}
|
|
2836
|
+
if seen:
|
|
2837
|
+
# The agent has now read these, so queue_full_kept stops counting
|
|
2838
|
+
# them. Each row is marked on its own, so paging in any order or
|
|
2839
|
+
# size never hides rows it did not show. Reading is otherwise
|
|
2840
|
+
# side-effect free; this mark is what lets the poll note clear.
|
|
2841
|
+
with self._tx() as db:
|
|
2842
|
+
marks = ','.join('?' * len(seen))
|
|
2843
|
+
db.execute(f'UPDATE inbox SET queue_full_read=? WHERE client_id=? AND id IN ({marks})',
|
|
2844
|
+
(now, client_id, *seen))
|
|
2845
|
+
return result
|
|
2846
|
+
|
|
2847
|
+
def ack(self, client_id, delivery_ids, lease_token):
|
|
2848
|
+
if not isinstance(delivery_ids, list) or not 1 <= len(delivery_ids) <= 100 or any(not isinstance(i, str) for i in delivery_ids) or not isinstance(lease_token, str) or len(lease_token) > 128:
|
|
2849
|
+
raise CoreError('invalid_ack')
|
|
2850
|
+
ids = list(dict.fromkeys(delivery_ids))
|
|
2851
|
+
now = self.clock()
|
|
2852
|
+
with self._tx() as db:
|
|
2853
|
+
self._binding(db, client_id)
|
|
2854
|
+
for delivery_id in ids:
|
|
2855
|
+
row = db.execute('SELECT * FROM inbox WHERE id=? AND client_id=?', (delivery_id, client_id)).fetchone()
|
|
2856
|
+
if row is None or row['lease_token'] != lease_token or (not row['acknowledged'] and row['lease_until'] <= now):
|
|
2857
|
+
raise CoreError('invalid_delivery_lease')
|
|
2858
|
+
for delivery_id in ids:
|
|
2859
|
+
db.execute('UPDATE inbox SET acknowledged=1 WHERE id=? AND client_id=?', (delivery_id, client_id))
|
|
2860
|
+
return {'acknowledged': ids}
|
|
2861
|
+
|
|
2862
|
+
def pause(self, client_id, paused=True):
|
|
2863
|
+
if not isinstance(paused, bool):
|
|
2864
|
+
raise CoreError('invalid_pause')
|
|
2865
|
+
with self._tx() as db:
|
|
2866
|
+
binding = self._binding(db, client_id)
|
|
2867
|
+
if not paused and binding['suspended']:
|
|
2868
|
+
raise CoreError('connection_suspended')
|
|
2869
|
+
db.execute('UPDATE bindings SET paused=? WHERE client_id=?', (int(paused), client_id))
|
|
2870
|
+
return self.connection_status(client_id)
|
|
2871
|
+
|
|
2872
|
+
def clear_suspension(self, client_id, *, topic_open_confirmed=False):
|
|
2873
|
+
"""Local owner control; never exposed as an agent MCP tool.
|
|
2874
|
+
|
|
2875
|
+
Ask Telegram first whether the bot can post in the bound chat again.
|
|
2876
|
+
Clear the flag only if no suspension event arrived during the check,
|
|
2877
|
+
including a repeat of the same reason, so a newer one stays in place. Queued inbox and outbox
|
|
2878
|
+
rows are not touched; they are delivered once the binding is usable.
|
|
2879
|
+
"""
|
|
2880
|
+
if not isinstance(topic_open_confirmed, bool):
|
|
2881
|
+
raise CoreError('invalid_unsuspend')
|
|
2882
|
+
with self._db() as db:
|
|
2883
|
+
binding = self._binding(db, client_id)
|
|
2884
|
+
account = self._account(db)
|
|
2885
|
+
reason, seq = binding['suspended'], binding['suspension_seq']
|
|
2886
|
+
if not reason:
|
|
2887
|
+
raise CoreError('not_suspended')
|
|
2888
|
+
migrated_to = None
|
|
2889
|
+
if reason.startswith('group_migrated:'):
|
|
2890
|
+
# The destination itself changed. Clearing must move the binding to
|
|
2891
|
+
# the new chat id; the old one no longer exists.
|
|
2892
|
+
target = reason.split(':', 1)[1]
|
|
2893
|
+
if not re.fullmatch(r'-?[0-9]+', target):
|
|
2894
|
+
raise CoreError('unknown_suspension')
|
|
2895
|
+
migrated_to = int(target)
|
|
2896
|
+
elif reason not in ('bot_removed_or_restricted', 'topic_changed'):
|
|
2897
|
+
raise CoreError('unknown_suspension')
|
|
2898
|
+
if reason == 'topic_changed' and not topic_open_confirmed:
|
|
2899
|
+
# The Bot API has no read-only call for one forum topic's state.
|
|
2900
|
+
raise CoreError('topic_open_confirmation_required')
|
|
2901
|
+
try:
|
|
2902
|
+
member = self.transport.get_chat_member(migrated_to or binding['chat_id'], account['bot_id'])
|
|
2903
|
+
except TransportError as error:
|
|
2904
|
+
if isinstance(error.code, int) and 400 <= error.code < 500 and error.code != 429:
|
|
2905
|
+
raise CoreError('bot_not_in_chat') from None
|
|
2906
|
+
raise CoreError('telegram_check_failed') from None
|
|
2907
|
+
status = member.get('status') if isinstance(member, dict) else None
|
|
2908
|
+
if not (status in ('member', 'administrator')
|
|
2909
|
+
or (status == 'restricted' and member.get('is_member') is True
|
|
2910
|
+
and member.get('can_send_messages') is True)):
|
|
2911
|
+
raise CoreError('bot_cannot_post')
|
|
2912
|
+
with self._tx() as db:
|
|
2913
|
+
# The suspension check also refreshes what reactions can arrive here.
|
|
2914
|
+
db.execute('UPDATE bindings SET bot_admin=?,bot_admin_probed=? WHERE client_id=? AND connected=1',
|
|
2915
|
+
(1 if status == 'administrator' else 0, self.clock(), client_id))
|
|
2916
|
+
current = db.execute('SELECT * FROM bindings WHERE client_id=? AND connected=1 AND suspended=? AND suspension_seq=?',
|
|
2917
|
+
(client_id, reason, seq)).fetchone()
|
|
2918
|
+
if current is None:
|
|
2919
|
+
raise CoreError('suspension_changed')
|
|
2920
|
+
if migrated_to is not None:
|
|
2921
|
+
if db.execute('SELECT 1 FROM bindings WHERE chat_id=? AND thread_id=? AND connected=1',
|
|
2922
|
+
(migrated_to, current['thread_id'])).fetchone():
|
|
2923
|
+
raise CoreError('destination_already_bound')
|
|
2924
|
+
self._move_binding(db, current, migrated_to)
|
|
2925
|
+
else:
|
|
2926
|
+
db.execute('UPDATE bindings SET suspended=NULL WHERE client_id=? AND connected=1', (client_id,))
|
|
2927
|
+
status_after = self.connection_status(client_id)
|
|
2928
|
+
return {'client_id': client_id, 'previous_suspension': reason, 'suspended': None,
|
|
2929
|
+
'paused': status_after['paused'], 'state': status_after['state'],
|
|
2930
|
+
'verified': {'bot_member_status': status, 'topic_open': 'owner_confirmed' if reason == 'topic_changed' else None},
|
|
2931
|
+
'pending_messages': status_after['pending_messages'],
|
|
2932
|
+
'queued_outgoing': status_after['outbox'].get('queued', 0)}
|
|
2933
|
+
|
|
2934
|
+
def disconnect(self, client_id):
|
|
2935
|
+
with self._tx() as db:
|
|
2936
|
+
self._client(db, client_id)
|
|
2937
|
+
images = [row['image'] for row in db.execute(
|
|
2938
|
+
'SELECT image FROM outbox WHERE status=\'queued\' AND (client_id=? OR recipient=?) AND image IS NOT NULL', (client_id, client_id))]
|
|
2939
|
+
db.execute('UPDATE outbox SET status=\'rejected\',error=\'client_revoked\',updated=? WHERE status=\'queued\' AND (client_id=? OR recipient=?)', (self.clock(), client_id, client_id))
|
|
2940
|
+
db.execute('UPDATE reaction_outbox SET status=\'rejected\',error=\'client_revoked\',updated=? WHERE status=\'queued\' AND client_id=?', (self.clock(), client_id))
|
|
2941
|
+
db.execute('UPDATE owner_outbox SET status=\'rejected\',error=\'client_revoked\',updated=? WHERE status=\'queued\' AND client_id=?', (self.clock(), client_id))
|
|
2942
|
+
db.execute('UPDATE bindings SET connected=0 WHERE client_id=?', (client_id,))
|
|
2943
|
+
db.execute('UPDATE clients SET active=0 WHERE id=?', (client_id,))
|
|
2944
|
+
db.execute('UPDATE pairings SET consumed=1 WHERE client_id=?', (client_id,))
|
|
2945
|
+
for image in images:
|
|
2946
|
+
self._delete_outbox_image(image)
|
|
2947
|
+
return {'client_id': client_id, 'connected': False, 'revoked': True, 'queued_work_preserved': True}
|
|
2948
|
+
|
|
2949
|
+
def _conversation_send_limit(self, db, conversation_id, now, limits):
|
|
2950
|
+
# A grant raises the limit for every sender in the conversation, because
|
|
2951
|
+
# every sender's reservations count toward the same window. Only a
|
|
2952
|
+
# client that already takes part in the conversation can create one.
|
|
2953
|
+
extra = db.execute(
|
|
2954
|
+
'SELECT MAX(additional_sends) FROM conversation_budget_grants '
|
|
2955
|
+
'WHERE conversation_id=? AND created<=? AND expires_at>?',
|
|
2956
|
+
(conversation_id, now, now)).fetchone()[0]
|
|
2957
|
+
return limits['conversation_send_limit'] + (extra or 0)
|
|
2958
|
+
|
|
2959
|
+
def conversation_budget(self, client_id, conversation_id, *, additional_sends=None,
|
|
2960
|
+
duration_seconds=None, reason=None):
|
|
2961
|
+
"""Inspect or grant a temporary higher rolling limit through the local operator CLI."""
|
|
2962
|
+
if conversation_id is None:
|
|
2963
|
+
raise CoreError('invalid_conversation')
|
|
2964
|
+
changing = additional_sends is not None
|
|
2965
|
+
if changing:
|
|
2966
|
+
self._check_budget_grant(additional_sends, duration_seconds, reason)
|
|
2967
|
+
elif duration_seconds is not None or reason is not None:
|
|
2968
|
+
raise CoreError('invalid_conversation_budget')
|
|
2969
|
+
now = self.clock()
|
|
2970
|
+
with self._tx() as db:
|
|
2971
|
+
self._binding(db, client_id, usable=changing)
|
|
2972
|
+
conversation = self._conversation(db, client_id, conversation_id)
|
|
2973
|
+
row = db.execute('SELECT send_count FROM conversations WHERE id=?', (conversation,)).fetchone()
|
|
2974
|
+
count = row['send_count'] if row else 0
|
|
2975
|
+
limits = self._limits(db)
|
|
2976
|
+
if changing:
|
|
2977
|
+
self._grant_budget(db, client_id, conversation, additional_sends, duration_seconds, reason, now, limits)
|
|
2978
|
+
grants = [dict(row) for row in db.execute(
|
|
2979
|
+
'SELECT id,additional_sends,created,expires_at,reason FROM conversation_budget_grants '
|
|
2980
|
+
'WHERE client_id=? AND conversation_id=? ORDER BY id', (client_id, conversation))]
|
|
2981
|
+
limit = self._conversation_send_limit(db, conversation, now, limits)
|
|
2982
|
+
used, retry_at = self._conversation_usage(db, conversation, now, limit, limits)
|
|
2983
|
+
reset = db.execute('SELECT window_reset_at FROM conversations WHERE id=?', (conversation,)).fetchone()
|
|
2984
|
+
reset_at = reset[0] if reset else None
|
|
2985
|
+
return {'conversation_id': conversation, 'send_count': count, 'send_limit': limit,
|
|
2986
|
+
'window_seconds': limits['conversation_window_seconds'], 'sent_in_window': used,
|
|
2987
|
+
'window_reset_at': reset_at,
|
|
2988
|
+
'remaining_sends': max(0, limit - used), 'retry_at': retry_at, 'grants': grants}
|
|
2989
|
+
|
|
2990
|
+
@staticmethod
|
|
2991
|
+
def _check_budget_grant(additional_sends, duration_seconds, reason):
|
|
2992
|
+
if (not _integer(additional_sends) or not 1 <= additional_sends <= 32
|
|
2993
|
+
or not _integer(duration_seconds) or not 1 <= duration_seconds <= 86400
|
|
2994
|
+
or not isinstance(reason, str) or not 1 <= len(reason.strip()) <= 500):
|
|
2995
|
+
raise CoreError('invalid_conversation_budget')
|
|
2996
|
+
|
|
2997
|
+
@staticmethod
|
|
2998
|
+
def _grant_budget(db, client_id, conversation, additional_sends, duration_seconds, reason, now, limits):
|
|
2999
|
+
db.execute('INSERT OR IGNORE INTO conversations(id) VALUES(?)', (conversation,))
|
|
3000
|
+
# A grant raises this conversation's rolling-window limit while it is active.
|
|
3001
|
+
db.execute(
|
|
3002
|
+
'INSERT INTO conversation_budget_grants'
|
|
3003
|
+
'(client_id,conversation_id,send_limit,created,expires_at,reason,additional_sends)'
|
|
3004
|
+
' VALUES(?,?,?,?,?,?,?)',
|
|
3005
|
+
(client_id, conversation, limits['conversation_send_limit'] + additional_sends,
|
|
3006
|
+
now, now + duration_seconds, reason.strip(), additional_sends))
|
|
3007
|
+
|
|
3008
|
+
def _delete_attachment_files(self, delivery_ids):
|
|
3009
|
+
directory = self.state_dir / 'attachments'
|
|
3010
|
+
prefixes = tuple(f'{delivery_id}-' for delivery_id in delivery_ids)
|
|
3011
|
+
try:
|
|
3012
|
+
names = os.listdir(directory)
|
|
3013
|
+
except FileNotFoundError:
|
|
3014
|
+
return
|
|
3015
|
+
for name in names:
|
|
3016
|
+
if name.startswith(prefixes):
|
|
3017
|
+
with contextlib.suppress(FileNotFoundError):
|
|
3018
|
+
(directory / name).unlink()
|
|
3019
|
+
|
|
3020
|
+
def fetch_attachment(self, client_id, delivery_id, file_unique_id):
|
|
3021
|
+
"""Download one attachment of this client's captured message into private local state.
|
|
3022
|
+
|
|
3023
|
+
The file is named from the delivery and Telegram's unique file id, never
|
|
3024
|
+
from the sender's file name. A second fetch reuses the stored file.
|
|
3025
|
+
"""
|
|
3026
|
+
if (not isinstance(delivery_id, str) or not re.fullmatch(r'msg_[0-9a-f]{24}', delivery_id)
|
|
3027
|
+
or not isinstance(file_unique_id, str) or not re.fullmatch(r'[A-Za-z0-9_-]{1,64}', file_unique_id)):
|
|
3028
|
+
raise CoreError('invalid_attachment')
|
|
3029
|
+
with self._db() as db:
|
|
3030
|
+
self._binding(db, client_id)
|
|
3031
|
+
row = db.execute('SELECT payload FROM inbox WHERE id=? AND client_id=?', (delivery_id, client_id)).fetchone()
|
|
3032
|
+
payload = json.loads(row['payload']) if row else {}
|
|
3033
|
+
# A reply's quoted message carries its own attachments; they are fetched the same way.
|
|
3034
|
+
candidates = [*payload.get('attachments', []), *_mapping(payload.get('reply_to_message')).get('attachments', [])]
|
|
3035
|
+
item = next((a for a in candidates if a.get('file_unique_id') == file_unique_id), None)
|
|
3036
|
+
if item is None:
|
|
3037
|
+
raise CoreError('unknown_attachment')
|
|
3038
|
+
# Context capture keeps such messages readable; it never lets their files in.
|
|
3039
|
+
if payload.get('context_reason') == 'sender_not_allowed':
|
|
3040
|
+
raise CoreError('attachment_sender_not_allowed')
|
|
3041
|
+
if item.get('file_size', 0) > MAX_ATTACHMENT_BYTES:
|
|
3042
|
+
raise CoreError('attachment_too_large')
|
|
3043
|
+
try:
|
|
3044
|
+
directory = private_directory(self.state_dir / 'attachments')
|
|
3045
|
+
except CredentialError:
|
|
3046
|
+
raise CoreError('insecure_state_directory') from None
|
|
3047
|
+
target = directory / f'{delivery_id}-{file_unique_id}'
|
|
3048
|
+
try:
|
|
3049
|
+
info = target.lstat()
|
|
3050
|
+
except FileNotFoundError:
|
|
3051
|
+
try:
|
|
3052
|
+
data = self.transport.download_file(item['file_id'], MAX_ATTACHMENT_BYTES)
|
|
3053
|
+
except TransportError as error:
|
|
3054
|
+
raise CoreError('attachment_too_large' if error.code == 'file_too_large' else 'attachment_unavailable') from None
|
|
3055
|
+
if not isinstance(data, bytes) or len(data) > MAX_ATTACHMENT_BYTES:
|
|
3056
|
+
raise CoreError('attachment_unavailable')
|
|
3057
|
+
partial = directory / f'.{target.name}.{secrets.token_hex(8)}.partial'
|
|
3058
|
+
fd = os.open(partial, os.O_CREAT | os.O_EXCL | os.O_WRONLY | compat.O_NOFOLLOW | compat.O_BINARY, 0o600)
|
|
3059
|
+
try:
|
|
3060
|
+
with os.fdopen(fd, 'wb') as handle:
|
|
3061
|
+
handle.write(data)
|
|
3062
|
+
handle.flush()
|
|
3063
|
+
os.fsync(handle.fileno())
|
|
3064
|
+
os.replace(partial, target)
|
|
3065
|
+
except BaseException:
|
|
3066
|
+
with contextlib.suppress(FileNotFoundError):
|
|
3067
|
+
partial.unlink()
|
|
3068
|
+
raise
|
|
3069
|
+
info = target.lstat()
|
|
3070
|
+
if not stat.S_ISREG(info.st_mode) or not compat.owned(info) or not compat.private(info, 0o077) or info.st_nlink != 1:
|
|
3071
|
+
raise CoreError('insecure_attachment_file')
|
|
3072
|
+
digest = hashlib.sha256(target.read_bytes()).hexdigest()
|
|
3073
|
+
result = {'delivery_id': delivery_id, 'file_unique_id': file_unique_id, 'kind': item['kind'],
|
|
3074
|
+
'path': str(target), 'size': info.st_size, 'sha256': digest, 'content_trust': 'untrusted'}
|
|
3075
|
+
for key in ('file_name', 'mime_type'):
|
|
3076
|
+
if key in item:
|
|
3077
|
+
result[key] = item[key]
|
|
3078
|
+
return result
|
|
3079
|
+
|
|
3080
|
+
def _conversation(self, db, client_id, conversation_id):
|
|
3081
|
+
if conversation_id is not None:
|
|
3082
|
+
if not isinstance(conversation_id, str) or len(conversation_id) > 200:
|
|
3083
|
+
raise CoreError('invalid_conversation')
|
|
3084
|
+
if not db.execute('SELECT 1 FROM inbox WHERE client_id=? AND conversation_id=? UNION SELECT 1 FROM outbox WHERE client_id=? AND conversation_id=? LIMIT 1', (client_id, conversation_id, client_id, conversation_id)).fetchone():
|
|
3085
|
+
raise CoreError('unknown_conversation')
|
|
3086
|
+
return conversation_id
|
|
3087
|
+
# Continue the most recent admitted conversation, including broker work.
|
|
3088
|
+
# Explicit conversation IDs always keep their own rolling send budget.
|
|
3089
|
+
row = db.execute('SELECT conversation_id FROM inbox WHERE client_id=? AND context=0 ORDER BY created DESC,rowid DESC LIMIT 1', (client_id,)).fetchone()
|
|
3090
|
+
if row:
|
|
3091
|
+
return row['conversation_id']
|
|
3092
|
+
return 'local:' + client_id
|
|
3093
|
+
|
|
3094
|
+
def _read_image(self, image_path):
|
|
3095
|
+
"""Validate one agent-provided local image and load its bytes.
|
|
3096
|
+
|
|
3097
|
+
The check runs before any state is written, so a rejected image never
|
|
3098
|
+
reaches the outbox or Telegram. The file is opened once with
|
|
3099
|
+
O_NONBLOCK and classified through fstat on that descriptor: a path
|
|
3100
|
+
swapped for a FIFO or device between lookup and open cannot block the
|
|
3101
|
+
call, and only a regular file is ever read.
|
|
3102
|
+
"""
|
|
3103
|
+
if (not isinstance(image_path, str) or not image_path or len(image_path) > 4096
|
|
3104
|
+
or '\x00' in image_path or not os.path.isabs(image_path)):
|
|
3105
|
+
raise CoreError('invalid_image')
|
|
3106
|
+
try:
|
|
3107
|
+
# O_NONBLOCK never affects regular-file reads; it only stops a
|
|
3108
|
+
# swapped-in FIFO or device from blocking this open forever.
|
|
3109
|
+
fd = os.open(image_path, os.O_RDONLY | compat.O_NONBLOCK | compat.O_BINARY)
|
|
3110
|
+
except OSError:
|
|
3111
|
+
raise CoreError('invalid_image') from None
|
|
3112
|
+
try:
|
|
3113
|
+
info = os.fstat(fd)
|
|
3114
|
+
if not stat.S_ISREG(info.st_mode):
|
|
3115
|
+
raise CoreError('invalid_image')
|
|
3116
|
+
if info.st_size > MAX_IMAGE_BYTES:
|
|
3117
|
+
raise CoreError('image_too_large')
|
|
3118
|
+
with os.fdopen(fd, 'rb', closefd=False) as handle:
|
|
3119
|
+
data = handle.read(MAX_IMAGE_BYTES + 1)
|
|
3120
|
+
except OSError:
|
|
3121
|
+
raise CoreError('invalid_image') from None
|
|
3122
|
+
finally:
|
|
3123
|
+
os.close(fd)
|
|
3124
|
+
if len(data) > MAX_IMAGE_BYTES:
|
|
3125
|
+
raise CoreError('image_too_large')
|
|
3126
|
+
send_as, extension, mime = _image_type(data)
|
|
3127
|
+
if send_as is None:
|
|
3128
|
+
raise CoreError('unsupported_image_type')
|
|
3129
|
+
return {'data': data, 'sha256': hashlib.sha256(data).hexdigest(),
|
|
3130
|
+
'send_as': send_as, 'extension': extension, 'mime': mime}
|
|
3131
|
+
|
|
3132
|
+
def _store_outbox_image(self, name, data):
|
|
3133
|
+
"""Persist the retry copy of an image under the private state directory."""
|
|
3134
|
+
try:
|
|
3135
|
+
directory = private_directory(self.state_dir / 'outbox-images')
|
|
3136
|
+
except CredentialError:
|
|
3137
|
+
raise CoreError('insecure_state_directory') from None
|
|
3138
|
+
partial = directory / f'.{name}.{secrets.token_hex(8)}.partial'
|
|
3139
|
+
fd = os.open(partial, os.O_CREAT | os.O_EXCL | os.O_WRONLY | compat.O_NOFOLLOW | compat.O_BINARY, 0o600)
|
|
3140
|
+
try:
|
|
3141
|
+
with os.fdopen(fd, 'wb') as handle:
|
|
3142
|
+
handle.write(data)
|
|
3143
|
+
handle.flush()
|
|
3144
|
+
os.fsync(handle.fileno())
|
|
3145
|
+
os.replace(partial, directory / name)
|
|
3146
|
+
except BaseException:
|
|
3147
|
+
with contextlib.suppress(FileNotFoundError):
|
|
3148
|
+
partial.unlink()
|
|
3149
|
+
raise
|
|
3150
|
+
|
|
3151
|
+
def _delete_outbox_image(self, name):
|
|
3152
|
+
# Terminal records can never be sent again; drop their retry copy.
|
|
3153
|
+
if isinstance(name, str) and re.fullmatch(r'out_[0-9a-f]{24}\.(png|jpg|webp|gif)', name):
|
|
3154
|
+
with contextlib.suppress(OSError):
|
|
3155
|
+
(self.state_dir / 'outbox-images' / name).unlink()
|
|
3156
|
+
|
|
3157
|
+
def send(self, client_id, text, idempotency_key, recipient=None, reply_to=None, conversation_id=None, image_path=None):
|
|
3158
|
+
if not isinstance(text, str) or not 1 <= len(text) <= 3500:
|
|
3159
|
+
raise CoreError('invalid_text')
|
|
3160
|
+
if not isinstance(idempotency_key, str) or not 1 <= len(idempotency_key) <= 128:
|
|
3161
|
+
raise CoreError('invalid_idempotency_key')
|
|
3162
|
+
if reply_to is not None and (not _integer(reply_to) or reply_to <= 0):
|
|
3163
|
+
raise CoreError('invalid_reply')
|
|
3164
|
+
if recipient is not None and (not isinstance(recipient, str) or len(recipient) > 100):
|
|
3165
|
+
raise CoreError('invalid_peer')
|
|
3166
|
+
image = self._read_image(image_path) if image_path is not None else None
|
|
3167
|
+
if image is not None and len(text) > MAX_IMAGE_CAPTION:
|
|
3168
|
+
# The label header consumes more; the exact check runs before queuing.
|
|
3169
|
+
raise CoreError('caption_too_long')
|
|
3170
|
+
# Text-only requests keep their historical hash, so old keys still match.
|
|
3171
|
+
parts = [text, recipient, reply_to, conversation_id]
|
|
3172
|
+
if image is not None:
|
|
3173
|
+
parts.append(image['sha256'])
|
|
3174
|
+
request_hash = _digest(json.dumps(parts))
|
|
3175
|
+
now = self.clock()
|
|
3176
|
+
with self._tx() as db:
|
|
3177
|
+
client = self._client(db, client_id)
|
|
3178
|
+
existing = db.execute('SELECT * FROM outbox WHERE client_id=? AND idempotency_key=?', (client_id, idempotency_key)).fetchone()
|
|
3179
|
+
if existing:
|
|
3180
|
+
if existing['request_hash'] != request_hash:
|
|
3181
|
+
raise CoreError('idempotency_conflict')
|
|
3182
|
+
outbox_id = existing['id']
|
|
3183
|
+
else:
|
|
3184
|
+
binding = self._binding(db, client_id, usable=True)
|
|
3185
|
+
account = self._account(db)
|
|
3186
|
+
if recipient is not None:
|
|
3187
|
+
if not db.execute('SELECT 1 FROM grants WHERE source=? AND target=?', (client_id, recipient)).fetchone():
|
|
3188
|
+
raise CoreError('peer_not_authorized')
|
|
3189
|
+
binding = self._binding(db, recipient, usable=True)
|
|
3190
|
+
reply_conversation = None
|
|
3191
|
+
if reply_to is not None:
|
|
3192
|
+
for row in db.execute('SELECT payload,conversation_id FROM inbox WHERE client_id=? ORDER BY created,rowid',
|
|
3193
|
+
(recipient or client_id,)):
|
|
3194
|
+
payload = json.loads(row['payload'])
|
|
3195
|
+
# Owner replies live in the private chat, not the group.
|
|
3196
|
+
if payload.get('message_id') == reply_to and not payload.get('owner_notice'):
|
|
3197
|
+
reply_conversation = row['conversation_id']
|
|
3198
|
+
break
|
|
3199
|
+
if reply_conversation is None:
|
|
3200
|
+
row = db.execute('SELECT conversation_id FROM outbox WHERE chat_id=? AND thread_id=? AND message_id=? AND status=\'sent\'',
|
|
3201
|
+
(binding['chat_id'], binding['thread_id'], reply_to)).fetchone()
|
|
3202
|
+
if row:
|
|
3203
|
+
reply_conversation = row['conversation_id']
|
|
3204
|
+
if reply_conversation is None:
|
|
3205
|
+
raise CoreError('unknown_reply')
|
|
3206
|
+
conversation = self._conversation(db, client_id, conversation_id if conversation_id is not None else reply_conversation)
|
|
3207
|
+
if reply_conversation is not None and reply_conversation != conversation:
|
|
3208
|
+
raise CoreError('reply_conversation_mismatch')
|
|
3209
|
+
db.execute('INSERT OR IGNORE INTO conversations(id) VALUES(?)', (conversation,))
|
|
3210
|
+
limits = self._limits(db)
|
|
3211
|
+
limit = self._conversation_send_limit(db, conversation, now, limits)
|
|
3212
|
+
used, retry_at = self._conversation_usage(db, conversation, now, limit, limits)
|
|
3213
|
+
if used >= limit:
|
|
3214
|
+
raise self._limit_error('conversation_limit', used, limit,
|
|
3215
|
+
limits['conversation_window_seconds'], retry_at, now)
|
|
3216
|
+
used, retry_at = self._client_usage(db, client_id, now, limits)
|
|
3217
|
+
if used >= limits['client_send_limit']:
|
|
3218
|
+
raise self._limit_error('client_limit', used, limits['client_send_limit'],
|
|
3219
|
+
limits['client_window_seconds'], retry_at, now)
|
|
3220
|
+
full = []
|
|
3221
|
+
for pair in db.execute('SELECT client_id,sender_id FROM bot_exchange_members WHERE conversation_id=?',
|
|
3222
|
+
(conversation,)).fetchall():
|
|
3223
|
+
used, retry_at = self._bot_pair_usage(db, pair['client_id'], pair['sender_id'], now, limits)
|
|
3224
|
+
if used >= limits['pair_send_limit']:
|
|
3225
|
+
full.append((retry_at, used))
|
|
3226
|
+
if full:
|
|
3227
|
+
# Report the latest time, when every full pair has room again.
|
|
3228
|
+
retry_at, used = max(full)
|
|
3229
|
+
raise self._limit_error('bot_pair_limit', used, limits['pair_send_limit'],
|
|
3230
|
+
limits['pair_window_seconds'], retry_at, now)
|
|
3231
|
+
outbox_id = 'out_' + secrets.token_hex(12)
|
|
3232
|
+
publication = f'[Agent: {client["label"]} | shared bot @{account["username"]}]\n{text}'
|
|
3233
|
+
peer = db.execute('SELECT * FROM peer_commands WHERE client_id=?', (client_id,)).fetchone() if recipient is None else None
|
|
3234
|
+
if peer:
|
|
3235
|
+
publication = f'/{peer["command"]}@{peer["bot_username"]}\n' + publication
|
|
3236
|
+
if image is not None and len(publication) > MAX_IMAGE_CAPTION:
|
|
3237
|
+
raise CoreError('caption_too_long')
|
|
3238
|
+
stored_image = outbox_id + '.' + image['extension'] if image is not None else None
|
|
3239
|
+
if stored_image is not None:
|
|
3240
|
+
# The retry copy is written before the row exists, so a queued
|
|
3241
|
+
# or unknown record never depends on the agent's source file.
|
|
3242
|
+
self._store_outbox_image(stored_image, image['data'])
|
|
3243
|
+
try:
|
|
3244
|
+
db.execute('INSERT INTO outbox(id,client_id,recipient,chat_id,thread_id,idempotency_key,request_hash,text,reply_to,conversation_id,status,image,created,updated,due) VALUES(?,?,?,?,?,?,?,?,?,?,\'queued\',?,?,?,?)', (outbox_id, client_id, recipient, binding['chat_id'], binding['thread_id'], idempotency_key, request_hash, publication, reply_to, conversation, stored_image, now, now, now))
|
|
3245
|
+
db.execute('UPDATE conversations SET send_count=send_count+1 WHERE id=?', (conversation,))
|
|
3246
|
+
if recipient:
|
|
3247
|
+
payload = {'origin': 'broker', 'kind': 'message', 'text': text, 'logical_sender': {'client_id': client_id, 'label': client['label']}, 'actual_bot': {'id': account['bot_id'], 'username': account['username']}, 'chat_id': binding['chat_id'], 'thread_id': binding['thread_id'] or None}
|
|
3248
|
+
self._enqueue(db, recipient, 'broker:' + outbox_id, payload, conversation, now, outbox_id,
|
|
3249
|
+
overflow='raise')
|
|
3250
|
+
except BaseException:
|
|
3251
|
+
if stored_image is not None:
|
|
3252
|
+
self._delete_outbox_image(stored_image)
|
|
3253
|
+
raise
|
|
3254
|
+
self.flush(client_id=client_id, limit=20)
|
|
3255
|
+
return self.delivery_status(client_id, outbox_id)
|
|
3256
|
+
|
|
3257
|
+
def _known_reaction_target(self, db, binding, message_id):
|
|
3258
|
+
"""True when the message id was captured or published in this destination.
|
|
3259
|
+
|
|
3260
|
+
A reaction can only target the agent's own bound group or topic: either a
|
|
3261
|
+
message this destination captured, or any message the shared bot
|
|
3262
|
+
published there, including one published for a peer agent.
|
|
3263
|
+
"""
|
|
3264
|
+
if db.execute('SELECT 1 FROM outbox WHERE chat_id=? AND thread_id=? AND message_id=? LIMIT 1',
|
|
3265
|
+
(binding['chat_id'], binding['thread_id'], message_id)).fetchone():
|
|
3266
|
+
return True
|
|
3267
|
+
for row in db.execute('SELECT payload FROM inbox WHERE client_id=?', (binding['client_id'],)):
|
|
3268
|
+
payload = json.loads(row['payload'])
|
|
3269
|
+
if (payload.get('message_id') == message_id and payload.get('chat_id') == binding['chat_id']
|
|
3270
|
+
and (payload.get('thread_id') or 0) == binding['thread_id']):
|
|
3271
|
+
return True
|
|
3272
|
+
return False
|
|
3273
|
+
|
|
3274
|
+
def _reaction_usage(self, db, client_id, now):
|
|
3275
|
+
stamps = [r[0] for r in db.execute(
|
|
3276
|
+
'SELECT created FROM reaction_outbox WHERE client_id=? AND created>? ORDER BY created DESC',
|
|
3277
|
+
(client_id, now - self.REACTION_WINDOW))]
|
|
3278
|
+
return self._window_usage(stamps, self.REACTION_SEND_LIMIT, self.REACTION_WINDOW)
|
|
3279
|
+
|
|
3280
|
+
def react(self, client_id, message_id, emoji, idempotency_key):
|
|
3281
|
+
"""Queue one reaction on a known message in this agent's own destination.
|
|
3282
|
+
|
|
3283
|
+
Reactions post no message, so they never touch any message send limit;
|
|
3284
|
+
they carry their own per-agent rolling limit. Like message_send, the
|
|
3285
|
+
intent is durable before any network activity, a repeated idempotency key
|
|
3286
|
+
with the same content returns the existing outcome, and an uncertain
|
|
3287
|
+
delivery needs private operator resolution.
|
|
3288
|
+
"""
|
|
3289
|
+
if not _integer(message_id) or message_id <= 0:
|
|
3290
|
+
raise CoreError('invalid_reaction')
|
|
3291
|
+
if not isinstance(idempotency_key, str) or not 1 <= len(idempotency_key) <= 128:
|
|
3292
|
+
raise CoreError('invalid_idempotency_key')
|
|
3293
|
+
emoji = reaction_emoji(emoji)
|
|
3294
|
+
request_hash = _digest(json.dumps([message_id, emoji]))
|
|
3295
|
+
now = self.clock()
|
|
3296
|
+
with self._tx() as db:
|
|
3297
|
+
self._client(db, client_id)
|
|
3298
|
+
existing = db.execute('SELECT * FROM reaction_outbox WHERE client_id=? AND idempotency_key=?',
|
|
3299
|
+
(client_id, idempotency_key)).fetchone()
|
|
3300
|
+
if existing:
|
|
3301
|
+
if existing['request_hash'] != request_hash:
|
|
3302
|
+
raise CoreError('idempotency_conflict')
|
|
3303
|
+
reaction_id = existing['id']
|
|
3304
|
+
else:
|
|
3305
|
+
binding = self._binding(db, client_id, usable=True)
|
|
3306
|
+
if not self._known_reaction_target(db, binding, message_id):
|
|
3307
|
+
raise CoreError('unknown_reaction_target')
|
|
3308
|
+
used, retry_at = self._reaction_usage(db, client_id, now)
|
|
3309
|
+
if used >= self.REACTION_SEND_LIMIT:
|
|
3310
|
+
raise self._limit_error('reaction_limit', used, self.REACTION_SEND_LIMIT,
|
|
3311
|
+
self.REACTION_WINDOW, retry_at, now)
|
|
3312
|
+
reaction_id = 'react_' + secrets.token_hex(12)
|
|
3313
|
+
db.execute("INSERT INTO reaction_outbox(id,client_id,chat_id,thread_id,message_id,emoji,"
|
|
3314
|
+
'idempotency_key,request_hash,status,created,updated,due) '
|
|
3315
|
+
"VALUES(?,?,?,?,?,?,?,?,'queued',?,?,?)",
|
|
3316
|
+
(reaction_id, client_id, binding['chat_id'], binding['thread_id'], message_id,
|
|
3317
|
+
emoji, idempotency_key, request_hash, now, now, now))
|
|
3318
|
+
self.flush(client_id=client_id, limit=20)
|
|
3319
|
+
return self.delivery_status(client_id, reaction_id)
|
|
3320
|
+
|
|
3321
|
+
def _owner_notify_usage(self, db, client_id, now, answers_owner=False):
|
|
3322
|
+
"""The fullest owner_notify window as (used, limit, window, retry_at), or None.
|
|
3323
|
+
|
|
3324
|
+
Every request that was not refused counts, including queued and unknown
|
|
3325
|
+
ones: an uncertain notification may already have reached the owner.
|
|
3326
|
+
A refused one never reached the owner, so it does not count.
|
|
3327
|
+
"""
|
|
3328
|
+
full = []
|
|
3329
|
+
for limit, window in self.OWNER_REPLY_LIMITS if answers_owner else self.OWNER_NOTIFY_LIMITS:
|
|
3330
|
+
stamps = [r[0] for r in db.execute(
|
|
3331
|
+
"SELECT created FROM owner_outbox WHERE client_id=? AND created>? AND status!='rejected' "
|
|
3332
|
+
'AND answers_owner=? ORDER BY created DESC', (client_id, now - window, int(answers_owner)))]
|
|
3333
|
+
used, retry_at = self._window_usage(stamps, limit, window)
|
|
3334
|
+
if retry_at is not None:
|
|
3335
|
+
full.append((retry_at, used, limit, window))
|
|
3336
|
+
if not full:
|
|
3337
|
+
return None
|
|
3338
|
+
# Report the latest time, when every full window has room again.
|
|
3339
|
+
retry_at, used, limit, window = max(full)
|
|
3340
|
+
return used, limit, window, retry_at
|
|
3341
|
+
|
|
3342
|
+
def _owner_reply_target(self, db, binding, reply_to):
|
|
3343
|
+
"""What reply_to is in this owner's private chat for this agent: 'owner', 'notice' or None.
|
|
3344
|
+
|
|
3345
|
+
'owner' is a message of the owner that was routed to this agent;
|
|
3346
|
+
'notice' is a notice or forward this agent sent. In one chat Telegram
|
|
3347
|
+
numbers both people's messages in one sequence, so the two never share
|
|
3348
|
+
an id.
|
|
3349
|
+
"""
|
|
3350
|
+
owner = binding['owner_id']
|
|
3351
|
+
if db.execute('SELECT 1 FROM inbox WHERE client_id=? AND tg_chat_id=? AND tg_message_id=? LIMIT 1',
|
|
3352
|
+
(binding['client_id'], owner, reply_to)).fetchone():
|
|
3353
|
+
return 'owner'
|
|
3354
|
+
notice = db.execute('SELECT choice FROM owner_outbox WHERE client_id=? AND owner_id=? AND (message_id=? OR forwarded_message_id=?) '
|
|
3355
|
+
'ORDER BY created DESC LIMIT 1', (binding['client_id'], owner, reply_to, reply_to)).fetchone()
|
|
3356
|
+
if notice is not None:
|
|
3357
|
+
# A notice the owner answered with a button: replying to it answers the owner.
|
|
3358
|
+
return 'owner' if notice['choice'] is not None else 'notice'
|
|
3359
|
+
return None
|
|
3360
|
+
|
|
3361
|
+
APPROVAL_ACTIONS = ('delivery_settings', 'conversation_budget')
|
|
3362
|
+
APPROVAL_SECONDS = 600
|
|
3363
|
+
APPROVAL_PENDING_LIMIT = 3
|
|
3364
|
+
|
|
3365
|
+
def request_owner_approval(self, client_id, action, params, summary):
|
|
3366
|
+
"""Ask the owner to approve one owner-only change with buttons in their private chat.
|
|
3367
|
+
|
|
3368
|
+
The local CLI uses this when no terminal is attached, instead of the
|
|
3369
|
+
typed confirmation. Nothing changes now: the change is stored as a
|
|
3370
|
+
pending approval with a random id, and the owner's private chat with
|
|
3371
|
+
the shared bot gets the summary with Approve and Decline buttons. Only
|
|
3372
|
+
a press from the owner's own account, before the request expires,
|
|
3373
|
+
applies it (see ``_route_callback``). An agent can start a request but
|
|
3374
|
+
never complete one.
|
|
3375
|
+
"""
|
|
3376
|
+
if action not in self.APPROVAL_ACTIONS or not isinstance(params, dict):
|
|
3377
|
+
raise CoreError('invalid_owner_approval')
|
|
3378
|
+
if not isinstance(summary, str) or not 1 <= len(summary) <= 1000:
|
|
3379
|
+
raise CoreError('invalid_owner_approval')
|
|
3380
|
+
if action == 'delivery_settings':
|
|
3381
|
+
self._check_delivery_settings(params)
|
|
3382
|
+
else:
|
|
3383
|
+
if set(params) != {'conversation_id', 'additional_sends', 'duration_seconds', 'reason'}:
|
|
3384
|
+
raise CoreError('invalid_owner_approval')
|
|
3385
|
+
self._check_budget_grant(params['additional_sends'], params['duration_seconds'], params['reason'])
|
|
3386
|
+
with contextlib.suppress(Exception):
|
|
3387
|
+
# Requests that ran out tell their agent first, and free their slot.
|
|
3388
|
+
self._expire_approvals()
|
|
3389
|
+
now = self.clock()
|
|
3390
|
+
approval_id = secrets.token_hex(8)
|
|
3391
|
+
with self._tx() as db:
|
|
3392
|
+
client = self._client(db, client_id)
|
|
3393
|
+
binding = self._binding(db, client_id, usable=True)
|
|
3394
|
+
if action == 'conversation_budget':
|
|
3395
|
+
self._conversation(db, client_id, params['conversation_id'])
|
|
3396
|
+
pending = db.execute("SELECT count(*) FROM owner_approvals WHERE client_id=? AND status='pending'",
|
|
3397
|
+
(client_id,)).fetchone()[0]
|
|
3398
|
+
if pending >= self.APPROVAL_PENDING_LIMIT:
|
|
3399
|
+
raise CoreError('owner_approval_limit')
|
|
3400
|
+
text = self._approval_text(client['label'], binding['title'], action, params, summary)
|
|
3401
|
+
db.execute("INSERT INTO owner_approvals(id,client_id,owner_id,action,params,text,status,created,expires) "
|
|
3402
|
+
"VALUES(?,?,?,?,?,?,'pending',?,?)",
|
|
3403
|
+
(approval_id, client_id, binding['owner_id'], action, json.dumps(params), text,
|
|
3404
|
+
now, now + self.APPROVAL_SECONDS))
|
|
3405
|
+
owner_id = binding['owner_id']
|
|
3406
|
+
username = self._account(db)['username']
|
|
3407
|
+
in_group = binding['approvals_in'] == 'group'
|
|
3408
|
+
group_chat, group_thread = binding['chat_id'], binding['thread_id'] or None
|
|
3409
|
+
buttons = {'inline_keyboard': [[{'text': 'Approve', 'callback_data': f'aot:a:{approval_id}'},
|
|
3410
|
+
{'text': 'Decline', 'callback_data': f'aot:d:{approval_id}'}]]}
|
|
3411
|
+
delivery, where = 'sent', 'private'
|
|
3412
|
+
if in_group and self._send_approval_to_group(approval_id, group_chat, group_thread, owner_id, text, buttons):
|
|
3413
|
+
return {'approval_id': approval_id, 'status': 'owner_approval_pending', 'action': action,
|
|
3414
|
+
'delivery': 'sent', 'where': 'group', 'expires_at': now + self.APPROVAL_SECONDS,
|
|
3415
|
+
'next_action': 'The owner approves or declines with the buttons on a message in the group '
|
|
3416
|
+
'that only they can see.'}
|
|
3417
|
+
try:
|
|
3418
|
+
self.transport.send_message(chat_id=owner_id, text=text, reply_markup=buttons)
|
|
3419
|
+
except TransportError as error:
|
|
3420
|
+
if isinstance(error.code, int) and 400 <= error.code < 500:
|
|
3421
|
+
code = 'owner_chat_not_started' if error.code == 403 else 'telegram_rejected'
|
|
3422
|
+
with self._tx() as db:
|
|
3423
|
+
db.execute("UPDATE owner_approvals SET status='failed',error=? WHERE id=?", (code, approval_id))
|
|
3424
|
+
raise CoreError(code, details={'bot_username': username} if error.code == 403 else None) from None
|
|
3425
|
+
# The owner may still have the message; its buttons keep working.
|
|
3426
|
+
delivery = 'uncertain'
|
|
3427
|
+
except Exception:
|
|
3428
|
+
delivery = 'uncertain'
|
|
3429
|
+
return {'approval_id': approval_id, 'status': 'owner_approval_pending', 'action': action,
|
|
3430
|
+
'delivery': delivery, 'where': where, 'expires_at': now + self.APPROVAL_SECONDS,
|
|
3431
|
+
'next_action': 'The owner approves or declines with the buttons in their private chat with the bot.'}
|
|
3432
|
+
|
|
3433
|
+
def _approval_text(self, label, title, action, params, summary):
|
|
3434
|
+
"""The owner's view of a request: every change on its own line, then the warning.
|
|
3435
|
+
|
|
3436
|
+
Approve applies exactly these values, so all of them are listed, not
|
|
3437
|
+
only the ones that need approval. Every free-text part is collapsed to
|
|
3438
|
+
one line and capped, so it cannot fake a line of the request.
|
|
3439
|
+
"""
|
|
3440
|
+
def line(value, limit=200):
|
|
3441
|
+
text = ' '.join(str(value).split())
|
|
3442
|
+
return text if len(text) <= limit else text[:limit - 1] + '…'
|
|
3443
|
+
|
|
3444
|
+
if action == 'delivery_settings':
|
|
3445
|
+
changes = [f'- {name}: {("on" if value else "off") if type(value) is bool else line(value)}'
|
|
3446
|
+
for name, value in params.items()]
|
|
3447
|
+
else:
|
|
3448
|
+
changes = [f'- conversation: {line(params["conversation_id"])}',
|
|
3449
|
+
f'- additional sends per window: {params["additional_sends"]}',
|
|
3450
|
+
f'- for: {params["duration_seconds"]} seconds',
|
|
3451
|
+
f'- reason: {line(params["reason"])}']
|
|
3452
|
+
return (f'[Agent: {line(label, 64)} | {line(title, 128)}]\n'
|
|
3453
|
+
f'Requested change ({action.replace("_", " ")}):\n' + '\n'.join(changes) + '\n\n'
|
|
3454
|
+
f'{line(summary, 1000)}\n\n'
|
|
3455
|
+
f'Approve this change? The request expires in {self.APPROVAL_SECONDS // 60} minutes.')
|
|
3456
|
+
|
|
3457
|
+
def _send_approval_to_group(self, approval_id, chat_id, thread_id, owner_id, text, buttons):
|
|
3458
|
+
"""Send an approval request to the bound group, visible only to the owner; True when sent.
|
|
3459
|
+
|
|
3460
|
+
Telegram does not guarantee delivery of ephemeral messages, and older
|
|
3461
|
+
clients or chats may refuse them, so any failure here means the caller
|
|
3462
|
+
falls back to the private chat.
|
|
3463
|
+
"""
|
|
3464
|
+
try:
|
|
3465
|
+
response = self.transport.send_message(chat_id=chat_id, text=text, thread_id=thread_id,
|
|
3466
|
+
reply_markup=buttons, ephemeral_to=owner_id)
|
|
3467
|
+
except Exception:
|
|
3468
|
+
return False
|
|
3469
|
+
ephemeral_id = response.get('ephemeral_message_id') if isinstance(response, dict) else None
|
|
3470
|
+
if not _integer(ephemeral_id) or ephemeral_id <= 0:
|
|
3471
|
+
return False
|
|
3472
|
+
with self._tx() as db:
|
|
3473
|
+
db.execute('UPDATE owner_approvals SET chat_id=?,ephemeral_id=? WHERE id=?', (chat_id, ephemeral_id, approval_id))
|
|
3474
|
+
return True
|
|
3475
|
+
|
|
3476
|
+
def _route_callback(self, db, update_id, callback, now):
|
|
3477
|
+
"""Handle one inline button press; only the owner's press on a live request counts."""
|
|
3478
|
+
callback_id = callback.get('id')
|
|
3479
|
+
if not isinstance(callback_id, str) or not 1 <= len(callback_id) <= 64:
|
|
3480
|
+
self._unmatched(db, update_id, None, 'unsupported_update', now)
|
|
3481
|
+
return
|
|
3482
|
+
sender = _mapping(callback.get('from'))
|
|
3483
|
+
message = _mapping(callback.get('message'))
|
|
3484
|
+
chat = _mapping(message.get('chat'))
|
|
3485
|
+
data = callback.get('data')
|
|
3486
|
+
match = re.fullmatch(r'aot:([ad]):([0-9a-f]{16})', data) if isinstance(data, str) else None
|
|
3487
|
+
choice = re.fullmatch(r'aot:c:([0-9a-f]{24}):([0-3])', data) if isinstance(data, str) and not match else None
|
|
3488
|
+
private = (sender.get('is_bot') is False and _integer(sender.get('id')) and chat.get('type') == 'private'
|
|
3489
|
+
and chat.get('id') == sender.get('id') and _integer(message.get('message_id')))
|
|
3490
|
+
# A press on an ephemeral message in a group: only its receiver sees it.
|
|
3491
|
+
ephemeral_id = message.get('ephemeral_message_id')
|
|
3492
|
+
ephemeral = (not private and sender.get('is_bot') is False and _integer(sender.get('id'))
|
|
3493
|
+
and chat.get('type') in ('group', 'supergroup') and _integer(chat.get('id'))
|
|
3494
|
+
and _integer(ephemeral_id) and ephemeral_id > 0
|
|
3495
|
+
and _mapping(message.get('receiver_user')).get('id') == sender.get('id'))
|
|
3496
|
+
|
|
3497
|
+
def answer(text, edit=None, formatted=False, markup=None, remove=False):
|
|
3498
|
+
# The private chat id is kept only until the answer goes out, so the
|
|
3499
|
+
# message can be edited; _answer_callbacks deletes the row first.
|
|
3500
|
+
db.execute('INSERT OR IGNORE INTO callback_answers(callback_id,text,chat_id,message_id,edit_text,created,'
|
|
3501
|
+
'receiver_id,ephemeral_id,edit_format,edit_markup,remove) VALUES(?,?,?,?,?,?,?,?,?,?,?)',
|
|
3502
|
+
(callback_id, text, chat.get('id') if private or ephemeral else None,
|
|
3503
|
+
message.get('message_id') if private else None, edit, now,
|
|
3504
|
+
sender.get('id') if ephemeral else None, ephemeral_id if ephemeral else None,
|
|
3505
|
+
1 if formatted else None,
|
|
3506
|
+
json.dumps(markup, separators=(',', ':'), ensure_ascii=False) if markup else None,
|
|
3507
|
+
1 if remove else None))
|
|
3508
|
+
|
|
3509
|
+
if isinstance(data, str) and data.startswith('aot:p:'):
|
|
3510
|
+
self._route_menu_press(db, update_id, data, sender, message, private, answer, now)
|
|
3511
|
+
return
|
|
3512
|
+
if choice is not None and private:
|
|
3513
|
+
self._route_choice(db, update_id, choice, sender, message, answer, now)
|
|
3514
|
+
return
|
|
3515
|
+
row = db.execute('SELECT * FROM owner_approvals WHERE id=?', (match.group(2),)).fetchone() if match else None
|
|
3516
|
+
# A request sent to the group counts only from its own ephemeral message;
|
|
3517
|
+
# one sent privately only from the private chat.
|
|
3518
|
+
if row is not None and row['chat_id'] is not None:
|
|
3519
|
+
where_ok = ephemeral and row['chat_id'] == chat.get('id') and row['ephemeral_id'] == ephemeral_id
|
|
3520
|
+
else:
|
|
3521
|
+
where_ok = private
|
|
3522
|
+
if not where_ok or row is None or row['owner_id'] != sender.get('id'):
|
|
3523
|
+
# The refusal record never keeps the chat id: in a private chat it is
|
|
3524
|
+
# the person's user id.
|
|
3525
|
+
self._unmatched(db, update_id, None, 'private_chat' if chat.get('type') == 'private' else 'unsupported_update', now)
|
|
3526
|
+
answer('This button does not belong to a request of yours.')
|
|
3527
|
+
return
|
|
3528
|
+
if row['status'] != 'pending':
|
|
3529
|
+
answer(f'This request was already {row["status"].replace("_", " ")}.')
|
|
3530
|
+
return
|
|
3531
|
+
if row['expires'] <= now:
|
|
3532
|
+
db.execute("UPDATE owner_approvals SET status='expired' WHERE id=?", (row['id'],))
|
|
3533
|
+
answer('This request expired.', row['text'] + '\n\nExpired: nothing changed.')
|
|
3534
|
+
self._tell_approval(db, update_id, row, 'expired', None, sender, now)
|
|
3535
|
+
return
|
|
3536
|
+
if match.group(1) == 'd':
|
|
3537
|
+
db.execute("UPDATE owner_approvals SET status='declined',decided=? WHERE id=?", (now, row['id']))
|
|
3538
|
+
answer('Declined.', row['text'] + '\n\nDeclined: nothing changed.')
|
|
3539
|
+
self._tell_approval(db, update_id, row, 'declined', None, sender, now)
|
|
3540
|
+
return
|
|
3541
|
+
db.execute('SAVEPOINT approval')
|
|
3542
|
+
try:
|
|
3543
|
+
self._apply_approval(db, row, now)
|
|
3544
|
+
except CoreError as error:
|
|
3545
|
+
db.execute('ROLLBACK TO SAVEPOINT approval')
|
|
3546
|
+
db.execute('RELEASE SAVEPOINT approval')
|
|
3547
|
+
db.execute("UPDATE owner_approvals SET status='apply_failed',error=?,decided=? WHERE id=?",
|
|
3548
|
+
(error.code, now, row['id']))
|
|
3549
|
+
answer('Could not apply the change.', row['text'] + f'\n\nApproved, but it could not be applied ({error.code}).')
|
|
3550
|
+
self._tell_approval(db, update_id, row, 'apply_failed', error.code, sender, now)
|
|
3551
|
+
return
|
|
3552
|
+
db.execute('RELEASE SAVEPOINT approval')
|
|
3553
|
+
db.execute("UPDATE owner_approvals SET status='approved',decided=? WHERE id=?", (now, row['id']))
|
|
3554
|
+
answer('Approved.', row['text'] + '\n\nApproved and applied.')
|
|
3555
|
+
self._tell_approval(db, update_id, row, 'approved', None, sender, now)
|
|
3556
|
+
|
|
3557
|
+
def _owner_sender(self, sender):
|
|
3558
|
+
return {'id': sender['id'], 'is_bot': False, 'username': _bounded(sender.get('username', ''), 64)}
|
|
3559
|
+
|
|
3560
|
+
def _tell_approval(self, db, update_id, row, outcome, error, sender, now):
|
|
3561
|
+
"""Tell the agent that asked how the owner answered its approval request."""
|
|
3562
|
+
if not db.execute('SELECT 1 FROM clients WHERE id=? AND active=1', (row['client_id'],)).fetchone():
|
|
3563
|
+
return
|
|
3564
|
+
payload = {'origin': 'telegram', 'kind': 'owner_approval', 'update_id': update_id,
|
|
3565
|
+
'sender': self._owner_sender(sender) if sender else None,
|
|
3566
|
+
'approval_id': row['id'], 'action': row['action'],
|
|
3567
|
+
'params': json.loads(row['params']), 'outcome': outcome, 'error': error,
|
|
3568
|
+
'addressed': True, 'owner_notice': True}
|
|
3569
|
+
conversation = f'owner_approval:{row["client_id"]}'
|
|
3570
|
+
db.execute('INSERT OR IGNORE INTO conversations(id) VALUES(?)', (conversation,))
|
|
3571
|
+
with contextlib.suppress(CoreError):
|
|
3572
|
+
self._enqueue(db, row['client_id'], f'approval:{row["id"]}', payload, conversation, now)
|
|
3573
|
+
|
|
3574
|
+
def _route_choice(self, db, update_id, choice, sender, message, answer, now):
|
|
3575
|
+
"""The owner pressed an answer button on an owner_notify notice."""
|
|
3576
|
+
row = db.execute('SELECT * FROM owner_outbox WHERE id=?', ('owner_' + choice.group(1),)).fetchone()
|
|
3577
|
+
labels = json.loads(row['choices']) if row is not None and row['choices'] else []
|
|
3578
|
+
index = int(choice.group(2))
|
|
3579
|
+
binding = db.execute('SELECT b.* FROM bindings b JOIN clients c ON c.id=b.client_id '
|
|
3580
|
+
'WHERE b.client_id=? AND b.owner_id=? AND b.connected=1 AND c.active=1',
|
|
3581
|
+
(row['client_id'], sender['id'])).fetchone() if row is not None else None
|
|
3582
|
+
# The press must be the owner's, on this very notice, in a connection
|
|
3583
|
+
# that still has that owner.
|
|
3584
|
+
if (row is None or row['owner_id'] != sender['id'] or row['message_id'] != message['message_id']
|
|
3585
|
+
or index >= len(labels) or binding is None):
|
|
3586
|
+
self._unmatched(db, update_id, None, 'private_chat', now)
|
|
3587
|
+
answer('This button does not belong to a question of yours.')
|
|
3588
|
+
return
|
|
3589
|
+
if row['choice'] is not None:
|
|
3590
|
+
answer(f'Already answered: {row["choice"]}.')
|
|
3591
|
+
return
|
|
3592
|
+
if row['choice_expires'] is not None and row['choice_expires'] <= now:
|
|
3593
|
+
answer('This question expired. Reply to the message instead.', row['text'] + '\n\nThe buttons expired.',
|
|
3594
|
+
formatted=True)
|
|
3595
|
+
return
|
|
3596
|
+
label = labels[index]
|
|
3597
|
+
db.execute('UPDATE owner_outbox SET choice=?,updated=? WHERE id=?', (label, now, row['id']))
|
|
3598
|
+
answer(f'Answered: {label}', row['text'] + f'\n\nAnswered: {label}', formatted=True)
|
|
3599
|
+
payload = {'origin': 'telegram', 'kind': 'owner_choice', 'update_id': update_id,
|
|
3600
|
+
'sender': self._owner_sender(sender), 'notify_id': row['id'],
|
|
3601
|
+
'notice_message_id': row['message_id'], 'choice': label, 'choice_index': index,
|
|
3602
|
+
'text': label, 'addressed': True, 'owner_notice': True}
|
|
3603
|
+
conversation = f'owner:{row["client_id"]}:{row["id"]}'
|
|
3604
|
+
db.execute('INSERT OR IGNORE INTO conversations(id) VALUES(?)', (conversation,))
|
|
3605
|
+
self._enqueue(db, row['client_id'], f'tg:{update_id}', payload, conversation, now)
|
|
3606
|
+
|
|
3607
|
+
def _apply_approval(self, db, row, now):
|
|
3608
|
+
params = json.loads(row['params'])
|
|
3609
|
+
# A re-paired connection has a new owner; the old owner's buttons no longer count.
|
|
3610
|
+
if self._binding(db, row['client_id'])['owner_id'] != row['owner_id']:
|
|
3611
|
+
raise CoreError('owner_changed')
|
|
3612
|
+
if row['action'] == 'delivery_settings':
|
|
3613
|
+
self._check_delivery_settings(params)
|
|
3614
|
+
self._binding(db, row['client_id'])
|
|
3615
|
+
self._write_delivery_settings(db, row['client_id'], params)
|
|
3616
|
+
elif row['action'] == 'conversation_budget':
|
|
3617
|
+
self._check_budget_grant(params['additional_sends'], params['duration_seconds'], params['reason'])
|
|
3618
|
+
self._binding(db, row['client_id'], usable=True)
|
|
3619
|
+
conversation = self._conversation(db, row['client_id'], params['conversation_id'])
|
|
3620
|
+
self._grant_budget(db, row['client_id'], conversation, params['additional_sends'],
|
|
3621
|
+
params['duration_seconds'], params['reason'], now, self._limits(db))
|
|
3622
|
+
else:
|
|
3623
|
+
raise CoreError('invalid_owner_approval')
|
|
3624
|
+
|
|
3625
|
+
def _expire_approvals(self):
|
|
3626
|
+
"""Expire unanswered approval requests and tell each agent that asked; never fails collection."""
|
|
3627
|
+
now = self.clock()
|
|
3628
|
+
with self._tx() as db:
|
|
3629
|
+
rows = db.execute("SELECT * FROM owner_approvals WHERE status='pending' AND expires<=? ORDER BY expires LIMIT 20",
|
|
3630
|
+
(now,)).fetchall()
|
|
3631
|
+
for row in rows:
|
|
3632
|
+
db.execute("UPDATE owner_approvals SET status='expired' WHERE id=?", (row['id'],))
|
|
3633
|
+
self._tell_approval(db, None, row, 'expired', None, None, now)
|
|
3634
|
+
|
|
3635
|
+
def send_settings_panel(self, client_id):
|
|
3636
|
+
"""Send the owner of this connection a settings panel, with this connection selected.
|
|
3637
|
+
|
|
3638
|
+
Local operator control. The panel lives in the owner's private chat with
|
|
3639
|
+
the shared bot and covers every connection the owner has on it; only the
|
|
3640
|
+
latest panel sent to an owner accepts changes. The owner can also ask
|
|
3641
|
+
for one by sending /settings to the bot.
|
|
3642
|
+
"""
|
|
3643
|
+
with self._db() as db:
|
|
3644
|
+
owner_id = self._binding(db, client_id)['owner_id']
|
|
3645
|
+
return self._send_panel(owner_id, client_id)
|
|
3646
|
+
|
|
3647
|
+
def _owner_connections(self, db, owner_id):
|
|
3648
|
+
return db.execute('SELECT c.id AS client_id,c.label,b.* FROM bindings b JOIN clients c ON c.id=b.client_id '
|
|
3649
|
+
'WHERE b.owner_id=? AND b.connected=1 AND c.active=1 ORDER BY c.label,c.id',
|
|
3650
|
+
(owner_id,)).fetchall()
|
|
3651
|
+
|
|
3652
|
+
def _send_panel(self, owner_id, client_id=None):
|
|
3653
|
+
from . import settings_panel
|
|
3654
|
+
with self._db() as db:
|
|
3655
|
+
connections = self._owner_connections(db, owner_id)[:settings_panel.MAX_CONNECTIONS]
|
|
3656
|
+
selected = next((c for c in connections if c['client_id'] == client_id), connections[0] if connections else None)
|
|
3657
|
+
if selected is None:
|
|
3658
|
+
raise CoreError('not_connected')
|
|
3659
|
+
settings = self._delivery_settings_view(selected)
|
|
3660
|
+
chat_data = settings_panel.state(connections, selected['client_id'], settings)
|
|
3661
|
+
username = self._account(db)['username']
|
|
3662
|
+
|
|
3663
|
+
def refused(error):
|
|
3664
|
+
if error.code == 403:
|
|
3665
|
+
return CoreError('owner_chat_not_started', details={'bot_username': username})
|
|
3666
|
+
if isinstance(error.code, int) and 400 <= error.code < 500:
|
|
3667
|
+
return CoreError('telegram_rejected')
|
|
3668
|
+
return CoreError('uncertain_send')
|
|
3669
|
+
|
|
3670
|
+
kind, shown = 'widget', None
|
|
3671
|
+
try:
|
|
3672
|
+
response = self.transport.send_widget(owner_id, settings_panel.html(), chat_data=chat_data,
|
|
3673
|
+
allow_queries=True)
|
|
3674
|
+
except TransportError as error:
|
|
3675
|
+
if error.code != 400:
|
|
3676
|
+
raise refused(error) from None
|
|
3677
|
+
# Telegram refuses widgets from most bots since November 2026
|
|
3678
|
+
# (INPUT_MEDIA_WIDGET_NOT_ALLOWED). The button menu does the same
|
|
3679
|
+
# job; the widget is tried first every time, so it comes back on
|
|
3680
|
+
# its own once Telegram allows it again.
|
|
3681
|
+
kind = 'menu'
|
|
3682
|
+
text, markup = settings_panel.menu(connections, selected['client_id'], settings)
|
|
3683
|
+
shown = _menu_digest(text, markup)
|
|
3684
|
+
try:
|
|
3685
|
+
response = self.transport.send_message(owner_id, text, reply_markup=markup)
|
|
3686
|
+
except TransportError as error:
|
|
3687
|
+
raise refused(error) from None
|
|
3688
|
+
if not isinstance(response, dict) or not _integer(response.get('message_id')):
|
|
3689
|
+
raise CoreError('uncertain_send')
|
|
3690
|
+
with self._tx() as db:
|
|
3691
|
+
db.execute('INSERT INTO settings_panels(owner_id,message_id,created,shown) VALUES(?,?,?,?) '
|
|
3692
|
+
'ON CONFLICT(owner_id) DO UPDATE SET message_id=excluded.message_id,created=excluded.created,'
|
|
3693
|
+
'shown=excluded.shown', (owner_id, response['message_id'], self.clock(), shown))
|
|
3694
|
+
return {'status': 'sent', 'kind': kind, 'message_id': response['message_id'], 'connections': len(connections)}
|
|
3695
|
+
|
|
3696
|
+
def _route_menu_press(self, db, update_id, data, sender, message, private, answer, now):
|
|
3697
|
+
"""A tap on the settings button menu; the same checks as a widget request.
|
|
3698
|
+
|
|
3699
|
+
Only the owner, in their private chat, on the latest menu or panel AOT
|
|
3700
|
+
sent them, for a connection they still own, can change a setting, and
|
|
3701
|
+
only to one of the listed values. Settings that warn need the Confirm
|
|
3702
|
+
button the first tap shows.
|
|
3703
|
+
"""
|
|
3704
|
+
from . import settings_panel
|
|
3705
|
+
panel = db.execute('SELECT shown FROM settings_panels WHERE owner_id=? AND message_id=?',
|
|
3706
|
+
(sender.get('id'), message.get('message_id'))).fetchone() if private else None
|
|
3707
|
+
if panel is None:
|
|
3708
|
+
self._unmatched(db, update_id, None, 'private_chat' if private else 'unsupported_update', now)
|
|
3709
|
+
answer('This menu is out of date. Send /settings for a new one.')
|
|
3710
|
+
return
|
|
3711
|
+
request = settings_panel.parse_menu(data)
|
|
3712
|
+
if request is None:
|
|
3713
|
+
answer('Unknown request.')
|
|
3714
|
+
return
|
|
3715
|
+
if request[0] == 'x':
|
|
3716
|
+
# Closing retires the menu and deletes its message.
|
|
3717
|
+
db.execute('DELETE FROM settings_panels WHERE owner_id=?', (sender.get('id'),))
|
|
3718
|
+
answer('Closed.', remove=True)
|
|
3719
|
+
return
|
|
3720
|
+
connections = self._owner_connections(db, sender.get('id'))[:settings_panel.MAX_CONNECTIONS]
|
|
3721
|
+
target = next((c for c in connections if settings_panel.key(c['client_id']) == request[1]), None)
|
|
3722
|
+
if target is None:
|
|
3723
|
+
answer('This agent is no longer connected to you.')
|
|
3724
|
+
return
|
|
3725
|
+
kind, _, name, value = request
|
|
3726
|
+
confirm, toast = None, ''
|
|
3727
|
+
if kind != 'v':
|
|
3728
|
+
index = next(i for i, setting in enumerate(settings_panel.SETTINGS) if setting[0] == name)
|
|
3729
|
+
if value is True and name in settings_panel.WARNINGS and kind != 'c':
|
|
3730
|
+
confirm, toast = (index, settings_panel.SETTINGS[index][2].index(value)), 'Confirm below.'
|
|
3731
|
+
else:
|
|
3732
|
+
self._write_delivery_settings(db, target['client_id'], {name: value})
|
|
3733
|
+
toast = 'Saved.'
|
|
3734
|
+
settings = self._delivery_settings_view(self._binding(db, target['client_id']))
|
|
3735
|
+
text, markup = settings_panel.menu(connections, target['client_id'], settings, confirm)
|
|
3736
|
+
shown = _menu_digest(text, markup)
|
|
3737
|
+
if shown == panel['shown']:
|
|
3738
|
+
# Telegram refuses an edit that changes nothing ("message is not
|
|
3739
|
+
# modified"), for example a tap on the agent already selected.
|
|
3740
|
+
answer(toast)
|
|
3741
|
+
return
|
|
3742
|
+
db.execute('UPDATE settings_panels SET shown=? WHERE owner_id=?', (shown, sender.get('id')))
|
|
3743
|
+
answer(toast, edit=text, markup=markup)
|
|
3744
|
+
|
|
3745
|
+
def _route_widget_query(self, db, update_id, query, now):
|
|
3746
|
+
"""One request from a settings panel; only the owner's latest panel changes their own connections."""
|
|
3747
|
+
from . import settings_panel
|
|
3748
|
+
query_id = query.get('id')
|
|
3749
|
+
if not isinstance(query_id, str) or not 1 <= len(query_id) <= 64:
|
|
3750
|
+
self._unmatched(db, update_id, None, 'unsupported_update', now)
|
|
3751
|
+
return
|
|
3752
|
+
sender = _mapping(query.get('from'))
|
|
3753
|
+
chat = _mapping(query.get('chat'))
|
|
3754
|
+
message_id = query.get('message_id')
|
|
3755
|
+
|
|
3756
|
+
def answer(result, chat_data=None, remove=False):
|
|
3757
|
+
# The private chat id is kept only until the answer goes out.
|
|
3758
|
+
keep = chat_data or remove
|
|
3759
|
+
db.execute('INSERT OR IGNORE INTO widget_answers(query_id,data,chat_id,message_id,chat_data,created,remove) '
|
|
3760
|
+
'VALUES(?,?,?,?,?,?,?)', (query_id, json.dumps(result, separators=(',', ':'), ensure_ascii=False),
|
|
3761
|
+
chat.get('id') if keep else None, message_id if keep else None,
|
|
3762
|
+
chat_data, now, int(remove)))
|
|
3763
|
+
|
|
3764
|
+
private = (sender.get('is_bot') is False and _integer(sender.get('id')) and chat.get('type') == 'private'
|
|
3765
|
+
and chat.get('id') == sender.get('id') and _integer(message_id))
|
|
3766
|
+
panel = db.execute('SELECT 1 FROM settings_panels WHERE owner_id=? AND message_id=?',
|
|
3767
|
+
(sender.get('id'), message_id)).fetchone() if private else None
|
|
3768
|
+
request = settings_panel.parse(query.get('data')) if panel else None
|
|
3769
|
+
connections = self._owner_connections(db, sender.get('id'))[:settings_panel.MAX_CONNECTIONS] if panel else []
|
|
3770
|
+
# The connection must be one the presser owns now, on their latest panel.
|
|
3771
|
+
target = next((c for c in connections if request and settings_panel.key(c['client_id']) == request[1]), None)
|
|
3772
|
+
if panel is None:
|
|
3773
|
+
self._unmatched(db, update_id, None, 'private_chat' if chat.get('type') == 'private' else 'unsupported_update', now)
|
|
3774
|
+
answer({'e': 'not allowed'})
|
|
3775
|
+
return
|
|
3776
|
+
if request is None:
|
|
3777
|
+
answer({'e': 'unknown request'})
|
|
3778
|
+
return
|
|
3779
|
+
if request[0] == 'x':
|
|
3780
|
+
# Closing retires the panel and deletes its message.
|
|
3781
|
+
db.execute('DELETE FROM settings_panels WHERE owner_id=?', (sender.get('id'),))
|
|
3782
|
+
answer({'closed': True}, remove=True)
|
|
3783
|
+
return
|
|
3784
|
+
if target is None:
|
|
3785
|
+
answer({'e': 'not allowed'})
|
|
3786
|
+
return
|
|
3787
|
+
kind, _, name, value = request
|
|
3788
|
+
if kind != 'v':
|
|
3789
|
+
if value is True and name in settings_panel.WARNINGS and kind != 'c':
|
|
3790
|
+
answer({'w': settings_panel.WARNINGS[name]})
|
|
3791
|
+
return
|
|
3792
|
+
self._write_delivery_settings(db, target['client_id'], {name: value})
|
|
3793
|
+
settings = self._delivery_settings_view(self._binding(db, target['client_id']))
|
|
3794
|
+
view = settings_panel.view(target['client_id'], settings)
|
|
3795
|
+
# Viewing only answers; a change also rewrites the panel's chat state.
|
|
3796
|
+
answer({'s': view}, None if kind == 'v' else settings_panel.state(connections, target['client_id'], settings))
|
|
3797
|
+
|
|
3798
|
+
def _answer_widget_queries(self):
|
|
3799
|
+
"""Answer recorded widget requests and refresh their panels; never fails collection."""
|
|
3800
|
+
with self._db() as db:
|
|
3801
|
+
rows = db.execute('SELECT * FROM widget_answers ORDER BY created LIMIT 20').fetchall()
|
|
3802
|
+
for row in rows:
|
|
3803
|
+
with self._tx() as db:
|
|
3804
|
+
if not db.execute('DELETE FROM widget_answers WHERE query_id=?', (row['query_id'],)).rowcount:
|
|
3805
|
+
continue
|
|
3806
|
+
calls = {}
|
|
3807
|
+
if row['chat_data'] and row['chat_id'] and row['message_id']:
|
|
3808
|
+
_owner_call(calls, 'edit', lambda: self.transport.edit_message_widget_data(
|
|
3809
|
+
row['chat_id'], row['message_id'], row['chat_data']))
|
|
3810
|
+
_owner_call(calls, 'answer', lambda: self.transport.answer_widget_query(row['query_id'], row['data']))
|
|
3811
|
+
if row['remove'] and row['chat_id'] and row['message_id']:
|
|
3812
|
+
_owner_call(calls, 'delete', lambda: self.transport.delete_message(row['chat_id'], row['message_id']))
|
|
3813
|
+
self.record_activity('owner', {'action': 'panel_tap', 'answer': _panel_answer_kind(row['data']),
|
|
3814
|
+
'routed_to_answered_ms': round((self.clock() - row['created']) * 1000),
|
|
3815
|
+
**calls})
|
|
3816
|
+
|
|
3817
|
+
def _answer_callbacks(self):
|
|
3818
|
+
"""Answer recorded button presses and update their messages; never fails collection."""
|
|
3819
|
+
with self._db() as db:
|
|
3820
|
+
rows = db.execute('SELECT * FROM callback_answers ORDER BY created LIMIT 20').fetchall()
|
|
3821
|
+
for row in rows:
|
|
3822
|
+
# Each press is answered at most once, whatever happens next.
|
|
3823
|
+
with self._tx() as db:
|
|
3824
|
+
if not db.execute('DELETE FROM callback_answers WHERE callback_id=?', (row['callback_id'],)).rowcount:
|
|
3825
|
+
continue
|
|
3826
|
+
calls = {}
|
|
3827
|
+
_owner_call(calls, 'answer', lambda: self.transport.answer_callback_query(row['callback_id'], row['text']))
|
|
3828
|
+
if row['remove'] and row['chat_id'] and row['message_id']:
|
|
3829
|
+
_owner_call(calls, 'delete', lambda: self.transport.delete_message(row['chat_id'], row['message_id']))
|
|
3830
|
+
elif row['edit_markup'] and row['edit_text'] and row['chat_id'] and row['message_id']:
|
|
3831
|
+
# A settings menu keeps its buttons, redrawn with the new values.
|
|
3832
|
+
_owner_call(calls, 'edit', lambda: self.transport.edit_message_text(
|
|
3833
|
+
row['chat_id'], row['message_id'], row['edit_text'], reply_markup=json.loads(row['edit_markup'])))
|
|
3834
|
+
elif row['edit_text'] and row['chat_id'] and row['ephemeral_id'] and row['receiver_id']:
|
|
3835
|
+
_owner_call(calls, 'edit', lambda: self.transport.edit_ephemeral_message_text(
|
|
3836
|
+
row['chat_id'], row['receiver_id'], row['ephemeral_id'], row['edit_text']))
|
|
3837
|
+
elif row['edit_text'] and row['chat_id'] and row['message_id'] and row['edit_format']:
|
|
3838
|
+
# A notice keeps its formatting when its buttons are answered.
|
|
3839
|
+
_owner_call(calls, 'edit', lambda: _send_formatted(
|
|
3840
|
+
self.transport.edit_message_text, row['edit_text'],
|
|
3841
|
+
chat_id=row['chat_id'], message_id=row['message_id']))
|
|
3842
|
+
elif row['edit_text'] and row['chat_id'] and row['message_id']:
|
|
3843
|
+
# Approval requests stay plain, so a link can never hide its target.
|
|
3844
|
+
_owner_call(calls, 'edit', lambda: self.transport.edit_message_text(
|
|
3845
|
+
row['chat_id'], row['message_id'], row['edit_text']))
|
|
3846
|
+
self.record_activity('owner', {'action': 'button_press',
|
|
3847
|
+
'routed_to_answered_ms': round((self.clock() - row['created']) * 1000),
|
|
3848
|
+
**calls})
|
|
3849
|
+
|
|
3850
|
+
def owner_notify(self, client_id, text, idempotency_key, forward_message_id=None, reply_to=None, choices=None):
|
|
3851
|
+
"""Queue one low-volume notification to the owner's private chat with the bot.
|
|
3852
|
+
|
|
3853
|
+
The owner is the person who paired this destination; in a private chat
|
|
3854
|
+
Telegram uses the user id as the chat id. A forward copies one message
|
|
3855
|
+
from this agent's own bound destination, by the same rule as reactions.
|
|
3856
|
+
Like message_send, the intent is durable before any network activity,
|
|
3857
|
+
and a repeated idempotency key with the same content returns the same
|
|
3858
|
+
outcome. ``reply_to`` sends the notice as a Telegram reply to a message
|
|
3859
|
+
in the owner's private chat that belongs to this agent. ``choices`` adds
|
|
3860
|
+
2-4 answer buttons; the owner's press arrives as an ``owner_choice``
|
|
3861
|
+
delivery, and a text reply to the notice still works as usual.
|
|
3862
|
+
"""
|
|
3863
|
+
if not isinstance(text, str) or not 1 <= len(text) <= 3500:
|
|
3864
|
+
raise CoreError('invalid_text')
|
|
3865
|
+
if not isinstance(idempotency_key, str) or not 1 <= len(idempotency_key) <= 128:
|
|
3866
|
+
raise CoreError('invalid_idempotency_key')
|
|
3867
|
+
if forward_message_id is not None and (not _integer(forward_message_id) or forward_message_id <= 0):
|
|
3868
|
+
raise CoreError('invalid_forward')
|
|
3869
|
+
if reply_to is not None and (not _integer(reply_to) or reply_to <= 0):
|
|
3870
|
+
raise CoreError('invalid_reply')
|
|
3871
|
+
choices = _check_choices(choices)
|
|
3872
|
+
# Requests without reply_to or choices keep their earlier hash, so old keys still match.
|
|
3873
|
+
parts = [text, forward_message_id] + ([reply_to] if reply_to is not None or choices else [])
|
|
3874
|
+
parts += [choices] if choices else []
|
|
3875
|
+
request_hash = _digest(json.dumps(parts))
|
|
3876
|
+
now = self.clock()
|
|
3877
|
+
with self._tx() as db:
|
|
3878
|
+
client = self._client(db, client_id)
|
|
3879
|
+
existing = db.execute('SELECT * FROM owner_outbox WHERE client_id=? AND idempotency_key=?',
|
|
3880
|
+
(client_id, idempotency_key)).fetchone()
|
|
3881
|
+
if existing:
|
|
3882
|
+
if existing['request_hash'] != request_hash:
|
|
3883
|
+
raise CoreError('idempotency_conflict')
|
|
3884
|
+
notify_id = existing['id']
|
|
3885
|
+
else:
|
|
3886
|
+
binding = self._binding(db, client_id, usable=True)
|
|
3887
|
+
if not binding['owner_notify']:
|
|
3888
|
+
# Nothing is stored, so this refusal never counts toward a limit.
|
|
3889
|
+
raise CoreError('owner_notify_disabled')
|
|
3890
|
+
if forward_message_id is not None and not self._known_reaction_target(db, binding, forward_message_id):
|
|
3891
|
+
raise CoreError('unknown_forward_target')
|
|
3892
|
+
target = self._owner_reply_target(db, binding, reply_to) if reply_to is not None else None
|
|
3893
|
+
if reply_to is not None and target is None:
|
|
3894
|
+
raise CoreError('unknown_owner_reply')
|
|
3895
|
+
# Answering the owner continues a conversation the owner started,
|
|
3896
|
+
# so it has its own generous cap instead of the notice limits.
|
|
3897
|
+
answers_owner = target == 'owner'
|
|
3898
|
+
usage = self._owner_notify_usage(db, client_id, now, answers_owner)
|
|
3899
|
+
if usage is not None:
|
|
3900
|
+
used, limit, window, retry_at = usage
|
|
3901
|
+
raise self._limit_error('owner_reply_limit' if answers_owner else 'owner_notify_limit',
|
|
3902
|
+
used, limit, window, retry_at, now)
|
|
3903
|
+
notify_id = 'owner_' + secrets.token_hex(12)
|
|
3904
|
+
# The owner reads this away from the group, so the label names
|
|
3905
|
+
# the group instead of the bot, which is the private chat itself.
|
|
3906
|
+
# The footer tells the owner how a reply reaches this agent.
|
|
3907
|
+
# Pairing already strips control characters from the title; collapse
|
|
3908
|
+
# any whitespace too, so a group name can't fake a label or footer line.
|
|
3909
|
+
title = ' '.join(str(binding['title']).split())
|
|
3910
|
+
footer = self.OWNER_CHOICE_FOOTER if choices else self.OWNER_NOTIFY_FOOTER
|
|
3911
|
+
labelled = f'[Agent: {client["label"]} | {title}]\n{text}\n{footer}'
|
|
3912
|
+
db.execute("INSERT INTO owner_outbox(id,client_id,owner_id,text,from_chat_id,forward_message_id,reply_to,"
|
|
3913
|
+
'answers_owner,idempotency_key,request_hash,status,created,updated,due,choices,choice_expires) '
|
|
3914
|
+
"VALUES(?,?,?,?,?,?,?,?,?,?,'queued',?,?,?,?,?)",
|
|
3915
|
+
(notify_id, client_id, binding['owner_id'], labelled,
|
|
3916
|
+
binding['chat_id'] if forward_message_id is not None else None, forward_message_id,
|
|
3917
|
+
reply_to, int(answers_owner), idempotency_key, request_hash, now, now, now,
|
|
3918
|
+
json.dumps(choices) if choices else None,
|
|
3919
|
+
now + self.OWNER_CHOICE_SECONDS if choices else None))
|
|
3920
|
+
username = self._account(db)['username']
|
|
3921
|
+
self.flush(client_id=client_id, limit=20)
|
|
3922
|
+
status = self.delivery_status(client_id, notify_id)
|
|
3923
|
+
if status['error'] == 'owner_chat_not_started':
|
|
3924
|
+
# Only the validated bot username goes into the details.
|
|
3925
|
+
raise CoreError('owner_chat_not_started', details={'bot_username': username})
|
|
3926
|
+
return status
|
|
3927
|
+
|
|
3928
|
+
@staticmethod
|
|
3929
|
+
def _owner_status(row):
|
|
3930
|
+
return {'notify_id': row['id'], 'kind': 'owner_notify', 'status': row['status'],
|
|
3931
|
+
'error': row['error'], 'message_id': row['message_id'],
|
|
3932
|
+
'forward_message_id': row['forward_message_id'],
|
|
3933
|
+
'forwarded_message_id': row['forwarded_message_id'], 'reply_to': row['reply_to'],
|
|
3934
|
+
'answers_owner': bool(row['answers_owner']),
|
|
3935
|
+
**({'choices': json.loads(row['choices']), 'choice': row['choice'],
|
|
3936
|
+
'choice_expires_at': row['choice_expires']} if row['choices'] else {}),
|
|
3937
|
+
'created_at': row['created'], 'updated_at': row['updated'],
|
|
3938
|
+
'retry_at': row['due'] if row['status'] == 'queued' else None}
|
|
3939
|
+
|
|
3940
|
+
@staticmethod
|
|
3941
|
+
def _reaction_status(row):
|
|
3942
|
+
return {'reaction_id': row['id'], 'kind': 'reaction', 'status': row['status'],
|
|
3943
|
+
'error': row['error'], 'emoji': row['emoji'], 'message_id': row['message_id'],
|
|
3944
|
+
'chat_id': row['chat_id'], 'thread_id': row['thread_id'] or None,
|
|
3945
|
+
'created_at': row['created'], 'updated_at': row['updated'],
|
|
3946
|
+
'retry_at': row['due'] if row['status'] == 'queued' else None}
|
|
3947
|
+
|
|
3948
|
+
def _outbox_status(self, row):
|
|
3949
|
+
return {'outbox_id': row['id'], 'status': row['status'], 'error': row['error'], 'message_id': row['message_id'], 'recipient': row['recipient'], 'conversation_id': row['conversation_id'], 'created_at': row['created'], 'updated_at': row['updated'], 'retry_at': row['due'] if row['status'] == 'queued' else None}
|
|
3950
|
+
|
|
3951
|
+
def delivery_status(self, client_id, outbox_id):
|
|
3952
|
+
"""Inspect an outgoing message or reaction delivery; never resends it."""
|
|
3953
|
+
with self._db() as db:
|
|
3954
|
+
self._client(db, client_id)
|
|
3955
|
+
row = db.execute('SELECT * FROM outbox WHERE client_id=? AND id=?', (client_id, outbox_id)).fetchone()
|
|
3956
|
+
if row is not None:
|
|
3957
|
+
return self._outbox_status(row)
|
|
3958
|
+
row = db.execute('SELECT * FROM reaction_outbox WHERE client_id=? AND id=?', (client_id, outbox_id)).fetchone()
|
|
3959
|
+
if row is not None:
|
|
3960
|
+
return self._reaction_status(row)
|
|
3961
|
+
row = db.execute('SELECT * FROM owner_outbox WHERE client_id=? AND id=?', (client_id, outbox_id)).fetchone()
|
|
3962
|
+
if row is None:
|
|
3963
|
+
raise CoreError('unknown_delivery')
|
|
3964
|
+
return self._owner_status(row)
|
|
3965
|
+
|
|
3966
|
+
def _recover_sends(self, db):
|
|
3967
|
+
# Only call while holding sender.lock: no live local sender can own a row.
|
|
3968
|
+
db.execute('UPDATE outbox SET status=\'unknown\',error=\'interrupted_send\',updated=? WHERE status=\'sending\'', (self.clock(),))
|
|
3969
|
+
db.execute('UPDATE reaction_outbox SET status=\'unknown\',error=\'interrupted_send\',updated=? WHERE status=\'sending\'', (self.clock(),))
|
|
3970
|
+
db.execute('UPDATE owner_outbox SET status=\'unknown\',error=\'interrupted_send\',updated=? WHERE status=\'sending\'', (self.clock(),))
|
|
3971
|
+
|
|
3972
|
+
def flush(self, client_id=None, limit=20):
|
|
3973
|
+
if not _integer(limit) or not 1 <= limit <= 100:
|
|
3974
|
+
raise CoreError('invalid_flush_limit')
|
|
3975
|
+
if client_id is not None:
|
|
3976
|
+
with self._db() as db:
|
|
3977
|
+
self._client(db, client_id)
|
|
3978
|
+
with self._lock('sender') as acquired:
|
|
3979
|
+
if not acquired:
|
|
3980
|
+
return {'status': 'busy', 'attempted': 0, 'reactions': 0, 'owner_notifications': 0}
|
|
3981
|
+
with self._tx() as db:
|
|
3982
|
+
self._recover_sends(db)
|
|
3983
|
+
rows = db.execute('SELECT id FROM outbox WHERE status=\'queued\' AND due<=? AND (? IS NULL OR client_id=?) ORDER BY created,rowid LIMIT ?', (self.clock(), client_id, client_id, limit)).fetchall()
|
|
3984
|
+
reactions = db.execute('SELECT id FROM reaction_outbox WHERE status=\'queued\' AND due<=? AND (? IS NULL OR client_id=?) ORDER BY created,rowid LIMIT ?', (self.clock(), client_id, client_id, limit)).fetchall()
|
|
3985
|
+
notes = db.execute('SELECT id FROM owner_outbox WHERE status=\'queued\' AND due<=? AND (? IS NULL OR client_id=?) ORDER BY created,rowid LIMIT ?', (self.clock(), client_id, client_id, limit)).fetchall()
|
|
3986
|
+
attempted = 0
|
|
3987
|
+
for candidate in rows:
|
|
3988
|
+
with self._tx() as db:
|
|
3989
|
+
row = db.execute('SELECT * FROM outbox WHERE id=?', (candidate['id'],)).fetchone()
|
|
3990
|
+
if row['status'] != 'queued':
|
|
3991
|
+
continue
|
|
3992
|
+
try:
|
|
3993
|
+
self._binding(db, row['client_id'], usable=True)
|
|
3994
|
+
if row['recipient']:
|
|
3995
|
+
self._binding(db, row['recipient'], usable=True)
|
|
3996
|
+
except CoreError:
|
|
3997
|
+
continue
|
|
3998
|
+
now = self.clock()
|
|
3999
|
+
scopes = [('bot', self.BOT_INTERVAL), (f'dest:{row["chat_id"]}:{row["thread_id"]}', self.DESTINATION_INTERVAL), ('conv:' + row['conversation_id'], self.CONVERSATION_INTERVAL)]
|
|
4000
|
+
due = now
|
|
4001
|
+
for scope, _ in scopes:
|
|
4002
|
+
rate = db.execute('SELECT next_at FROM rate_limits WHERE scope=?', (scope,)).fetchone()
|
|
4003
|
+
if rate:
|
|
4004
|
+
due = max(due, rate['next_at'])
|
|
4005
|
+
if due > now:
|
|
4006
|
+
db.execute('UPDATE outbox SET due=? WHERE id=?', (due, row['id']))
|
|
4007
|
+
continue
|
|
4008
|
+
for scope, interval in scopes:
|
|
4009
|
+
db.execute('INSERT INTO rate_limits(scope,next_at) VALUES(?,?) ON CONFLICT(scope) DO UPDATE SET next_at=excluded.next_at', (scope, now + interval))
|
|
4010
|
+
db.execute('UPDATE outbox SET status=\'sending\',updated=? WHERE id=?', (now, row['id']))
|
|
4011
|
+
attempted += 1
|
|
4012
|
+
media = None
|
|
4013
|
+
local_reject = None
|
|
4014
|
+
migrated_to = None
|
|
4015
|
+
if row['image']:
|
|
4016
|
+
try:
|
|
4017
|
+
data = (self.state_dir / 'outbox-images' / row['image']).read_bytes()
|
|
4018
|
+
send_as, _extension, mime = _image_type(data)
|
|
4019
|
+
if send_as is None:
|
|
4020
|
+
raise ValueError('corrupt copy')
|
|
4021
|
+
except (OSError, ValueError):
|
|
4022
|
+
# Our own durable copy is gone or unreadable, so this
|
|
4023
|
+
# attempt certainly never reached Telegram.
|
|
4024
|
+
local_reject = 'outbox_image_unavailable'
|
|
4025
|
+
else:
|
|
4026
|
+
media = (data, send_as, mime)
|
|
4027
|
+
if local_reject is not None:
|
|
4028
|
+
status, error, message_id, due = 'rejected', local_reject, None, self.clock()
|
|
4029
|
+
else:
|
|
4030
|
+
try:
|
|
4031
|
+
if media is None:
|
|
4032
|
+
response = _send_formatted(self.transport.send_message, row['text'], chat_id=row['chat_id'],
|
|
4033
|
+
thread_id=row['thread_id'] or None, reply_to=row['reply_to'])
|
|
4034
|
+
else:
|
|
4035
|
+
sender = self.transport.send_photo if media[1] == 'photo' else self.transport.send_document
|
|
4036
|
+
response = _send_formatted(sender, row['text'], field='caption', chat_id=row['chat_id'], data=media[0],
|
|
4037
|
+
filename=row['image'], mime=media[2],
|
|
4038
|
+
thread_id=row['thread_id'] or None, reply_to=row['reply_to'])
|
|
4039
|
+
if not isinstance(response, dict) or not _integer(response.get('message_id')) or response['message_id'] <= 0:
|
|
4040
|
+
raise UnknownSend()
|
|
4041
|
+
except UnknownSend:
|
|
4042
|
+
status, error, message_id, due = 'unknown', 'uncertain_send', None, self.clock()
|
|
4043
|
+
except TransportError as exc:
|
|
4044
|
+
if str(exc.code) in ('429', 'rate_limited', 'telegram_429'):
|
|
4045
|
+
wait = exc.retry_after if isinstance(exc.retry_after, (int, float)) and not isinstance(exc.retry_after, bool) and math.isfinite(exc.retry_after) and exc.retry_after > 0 else 60
|
|
4046
|
+
due = self.clock() + min(wait, 86400)
|
|
4047
|
+
status, error, message_id = 'queued', 'rate_limited', None
|
|
4048
|
+
elif _integer(exc.migrate_to_chat_id) and exc.migrate_to_chat_id != row['chat_id']:
|
|
4049
|
+
# A definite rejection: the group became a supergroup.
|
|
4050
|
+
# Nothing was sent, so the message waits for the new chat.
|
|
4051
|
+
status, error, message_id, due = 'queued', 'group_migrated', None, self.clock()
|
|
4052
|
+
migrated_to = exc.migrate_to_chat_id
|
|
4053
|
+
elif isinstance(exc.code, int) and 400 <= exc.code < 500:
|
|
4054
|
+
status, error, message_id, due = 'rejected', 'telegram_rejected', None, self.clock()
|
|
4055
|
+
else:
|
|
4056
|
+
status, error, message_id, due = 'unknown', 'transport_failure', None, self.clock()
|
|
4057
|
+
except Exception:
|
|
4058
|
+
# An unexpected adapter failure after entering send may follow
|
|
4059
|
+
# remote acceptance. Never make a speculative automatic retry.
|
|
4060
|
+
status, error, message_id, due = 'unknown', 'transport_failure', None, self.clock()
|
|
4061
|
+
else:
|
|
4062
|
+
status, error, message_id, due = 'sent', None, response['message_id'], self.clock()
|
|
4063
|
+
with self._tx() as db:
|
|
4064
|
+
db.execute('UPDATE outbox SET status=?,error=?,message_id=?,due=?,updated=? WHERE id=?', (status, error, message_id, due, self.clock(), row['id']))
|
|
4065
|
+
if error == 'group_migrated':
|
|
4066
|
+
self._follow_send_migration(db, row, migrated_to)
|
|
4067
|
+
if error == 'rate_limited':
|
|
4068
|
+
db.execute('INSERT INTO rate_limits(scope,next_at) VALUES(\'bot\',?) ON CONFLICT(scope) DO UPDATE SET next_at=max(next_at,excluded.next_at)', (due,))
|
|
4069
|
+
if status in ('sent', 'rejected') and row['image']:
|
|
4070
|
+
# An unknown record keeps its copy: an operator retry sends it again.
|
|
4071
|
+
self._delete_outbox_image(row['image'])
|
|
4072
|
+
reacted = self._flush_reactions(reactions)
|
|
4073
|
+
notified = self._flush_owner_notes(notes)
|
|
4074
|
+
return {'status': 'ok', 'attempted': attempted, 'reactions': reacted, 'owner_notifications': notified}
|
|
4075
|
+
|
|
4076
|
+
def _flush_reactions(self, candidates):
|
|
4077
|
+
"""Attempt due queued reactions under the sender lock; returns attempts.
|
|
4078
|
+
|
|
4079
|
+
Reactions pace on their own 'react' scope, never on a message scope. An
|
|
4080
|
+
uncertain outcome stays unknown: like a message send, an attempt may have
|
|
4081
|
+
reached Telegram after the failure, and re-setting a reaction is left to
|
|
4082
|
+
an explicit operator resolution.
|
|
4083
|
+
"""
|
|
4084
|
+
attempted = 0
|
|
4085
|
+
for candidate in candidates:
|
|
4086
|
+
with self._tx() as db:
|
|
4087
|
+
row = db.execute('SELECT * FROM reaction_outbox WHERE id=?', (candidate['id'],)).fetchone()
|
|
4088
|
+
if row['status'] != 'queued':
|
|
4089
|
+
continue
|
|
4090
|
+
try:
|
|
4091
|
+
self._binding(db, row['client_id'], usable=True)
|
|
4092
|
+
except CoreError:
|
|
4093
|
+
continue
|
|
4094
|
+
now = self.clock()
|
|
4095
|
+
due = now
|
|
4096
|
+
rate = db.execute('SELECT next_at FROM rate_limits WHERE scope=\'react\'').fetchone()
|
|
4097
|
+
if rate:
|
|
4098
|
+
due = max(due, rate['next_at'])
|
|
4099
|
+
if due > now:
|
|
4100
|
+
db.execute('UPDATE reaction_outbox SET due=? WHERE id=?', (due, row['id']))
|
|
4101
|
+
continue
|
|
4102
|
+
db.execute('INSERT INTO rate_limits(scope,next_at) VALUES(\'react\',?) ON CONFLICT(scope) DO UPDATE SET next_at=excluded.next_at', (now + self.REACTION_INTERVAL,))
|
|
4103
|
+
db.execute('UPDATE reaction_outbox SET status=\'sending\',updated=? WHERE id=?', (now, row['id']))
|
|
4104
|
+
attempted += 1
|
|
4105
|
+
migrated_to = None
|
|
4106
|
+
try:
|
|
4107
|
+
self.transport.set_message_reaction(row['chat_id'], row['message_id'], row['emoji'])
|
|
4108
|
+
status, error, due = 'sent', None, self.clock()
|
|
4109
|
+
except UnknownSend:
|
|
4110
|
+
status, error, due = 'unknown', 'uncertain_send', self.clock()
|
|
4111
|
+
except TransportError as exc:
|
|
4112
|
+
if str(exc.code) in ('429', 'rate_limited', 'telegram_429'):
|
|
4113
|
+
wait = exc.retry_after if isinstance(exc.retry_after, (int, float)) and not isinstance(exc.retry_after, bool) and math.isfinite(exc.retry_after) and exc.retry_after > 0 else 60
|
|
4114
|
+
due = self.clock() + min(wait, 86400)
|
|
4115
|
+
status, error = 'queued', 'rate_limited'
|
|
4116
|
+
elif _integer(exc.migrate_to_chat_id) and exc.migrate_to_chat_id != row['chat_id']:
|
|
4117
|
+
# The group became a supergroup. Its old messages stay in the
|
|
4118
|
+
# deactivated group, so this reaction cannot follow them.
|
|
4119
|
+
status, error, due = 'rejected', 'group_migrated', self.clock()
|
|
4120
|
+
migrated_to = exc.migrate_to_chat_id
|
|
4121
|
+
elif isinstance(exc.code, int) and 400 <= exc.code < 500:
|
|
4122
|
+
status, error, due = 'rejected', 'telegram_rejected', self.clock()
|
|
4123
|
+
else:
|
|
4124
|
+
status, error, due = 'unknown', 'transport_failure', self.clock()
|
|
4125
|
+
except Exception:
|
|
4126
|
+
status, error, due = 'unknown', 'transport_failure', self.clock()
|
|
4127
|
+
with self._tx() as db:
|
|
4128
|
+
db.execute('UPDATE reaction_outbox SET status=?,error=?,due=?,updated=? WHERE id=?', (status, error, due, self.clock(), row['id']))
|
|
4129
|
+
if migrated_to is not None:
|
|
4130
|
+
self._follow_migration(db, row['chat_id'], migrated_to)
|
|
4131
|
+
if error == 'rate_limited':
|
|
4132
|
+
db.execute('INSERT INTO rate_limits(scope,next_at) VALUES(\'react\',?) ON CONFLICT(scope) DO UPDATE SET next_at=max(next_at,excluded.next_at)', (due,))
|
|
4133
|
+
return attempted
|
|
4134
|
+
|
|
4135
|
+
def _flush_owner_notes(self, candidates):
|
|
4136
|
+
"""Attempt due owner notifications under the sender lock; returns attempts.
|
|
4137
|
+
|
|
4138
|
+
A notification has up to two steps: the labelled text, then the
|
|
4139
|
+
optional forward. Each step records its message id when it succeeds,
|
|
4140
|
+
so a retry after an unknown outcome repeats only the missing step.
|
|
4141
|
+
Pacing uses one scope per owner private chat.
|
|
4142
|
+
"""
|
|
4143
|
+
attempted = 0
|
|
4144
|
+
for candidate in candidates:
|
|
4145
|
+
with self._tx() as db:
|
|
4146
|
+
row = db.execute('SELECT * FROM owner_outbox WHERE id=?', (candidate['id'],)).fetchone()
|
|
4147
|
+
if row['status'] != 'queued':
|
|
4148
|
+
continue
|
|
4149
|
+
try:
|
|
4150
|
+
self._binding(db, row['client_id'], usable=True)
|
|
4151
|
+
except CoreError:
|
|
4152
|
+
continue
|
|
4153
|
+
now = self.clock()
|
|
4154
|
+
scope = f'owner:{row["owner_id"]}'
|
|
4155
|
+
rate = db.execute('SELECT next_at FROM rate_limits WHERE scope=?', (scope,)).fetchone()
|
|
4156
|
+
due = max(now, rate['next_at']) if rate else now
|
|
4157
|
+
if due > now:
|
|
4158
|
+
db.execute('UPDATE owner_outbox SET due=? WHERE id=?', (due, row['id']))
|
|
4159
|
+
continue
|
|
4160
|
+
db.execute('INSERT INTO rate_limits(scope,next_at) VALUES(?,?) ON CONFLICT(scope) DO UPDATE SET next_at=excluded.next_at',
|
|
4161
|
+
(scope, now + self.OWNER_NOTIFY_INTERVAL))
|
|
4162
|
+
db.execute("UPDATE owner_outbox SET status='sending',updated=? WHERE id=?", (now, row['id']))
|
|
4163
|
+
attempted += 1
|
|
4164
|
+
message_id, forwarded_id = row['message_id'], row['forwarded_message_id']
|
|
4165
|
+
step = 'text' if message_id is None else 'forward'
|
|
4166
|
+
try:
|
|
4167
|
+
if message_id is None:
|
|
4168
|
+
markup = _choice_buttons(row['id'], row['choices'])
|
|
4169
|
+
extra = {} if markup is None else {'reply_markup': markup}
|
|
4170
|
+
response = _send_formatted(self.transport.send_message, row['text'], chat_id=row['owner_id'],
|
|
4171
|
+
reply_to=row['reply_to'], **extra)
|
|
4172
|
+
if not isinstance(response, dict) or not _integer(response.get('message_id')) or response['message_id'] <= 0:
|
|
4173
|
+
raise UnknownSend()
|
|
4174
|
+
message_id = response['message_id']
|
|
4175
|
+
# Record the text at once, so a failure in the forward
|
|
4176
|
+
# below can never send the text a second time.
|
|
4177
|
+
with self._tx() as db:
|
|
4178
|
+
db.execute('UPDATE owner_outbox SET message_id=?,updated=? WHERE id=?', (message_id, self.clock(), row['id']))
|
|
4179
|
+
step = 'forward'
|
|
4180
|
+
if row['forward_message_id'] is not None and forwarded_id is None:
|
|
4181
|
+
response = self.transport.forward_message(chat_id=row['owner_id'], from_chat_id=row['from_chat_id'],
|
|
4182
|
+
message_id=row['forward_message_id'])
|
|
4183
|
+
if not isinstance(response, dict) or not _integer(response.get('message_id')) or response['message_id'] <= 0:
|
|
4184
|
+
raise UnknownSend()
|
|
4185
|
+
forwarded_id = response['message_id']
|
|
4186
|
+
status, error, due = 'sent', None, self.clock()
|
|
4187
|
+
except UnknownSend:
|
|
4188
|
+
status, error, due = 'unknown', 'uncertain_send', self.clock()
|
|
4189
|
+
except TransportError as exc:
|
|
4190
|
+
if str(exc.code) in ('429', 'rate_limited', 'telegram_429'):
|
|
4191
|
+
wait = exc.retry_after if isinstance(exc.retry_after, (int, float)) and not isinstance(exc.retry_after, bool) and math.isfinite(exc.retry_after) and exc.retry_after > 0 else 60
|
|
4192
|
+
due = self.clock() + min(wait, 86400)
|
|
4193
|
+
status, error = 'queued', 'rate_limited'
|
|
4194
|
+
elif step == 'forward' and isinstance(exc.code, int) and 400 <= exc.code < 500:
|
|
4195
|
+
# The owner already has the text; only the copy of the
|
|
4196
|
+
# group message failed, for example because it was deleted.
|
|
4197
|
+
status, error, due = 'sent', 'forward_rejected', self.clock()
|
|
4198
|
+
elif exc.code == 403:
|
|
4199
|
+
# A bot cannot open a private chat: the owner never sent it
|
|
4200
|
+
# /start, or blocked it. Nothing reached the owner.
|
|
4201
|
+
status, error, due = 'rejected', 'owner_chat_not_started', self.clock()
|
|
4202
|
+
elif isinstance(exc.code, int) and 400 <= exc.code < 500:
|
|
4203
|
+
status, error, due = 'rejected', 'telegram_rejected', self.clock()
|
|
4204
|
+
else:
|
|
4205
|
+
status, error, due = 'unknown', 'transport_failure', self.clock()
|
|
4206
|
+
except Exception:
|
|
4207
|
+
status, error, due = 'unknown', 'transport_failure', self.clock()
|
|
4208
|
+
with self._tx() as db:
|
|
4209
|
+
db.execute('UPDATE owner_outbox SET status=?,error=?,message_id=?,forwarded_message_id=?,due=?,updated=? WHERE id=?',
|
|
4210
|
+
(status, error, message_id, forwarded_id, due, self.clock(), row['id']))
|
|
4211
|
+
if error == 'rate_limited':
|
|
4212
|
+
db.execute('INSERT INTO rate_limits(scope,next_at) VALUES(?,?) ON CONFLICT(scope) DO UPDATE SET next_at=max(next_at,excluded.next_at)',
|
|
4213
|
+
(f'owner:{row["owner_id"]}', due))
|
|
4214
|
+
return attempted
|
|
4215
|
+
|
|
4216
|
+
def resolve_unknown(self, outbox_id, resolution, message_id=None):
|
|
4217
|
+
if resolution not in ('accepted', 'cancel', 'retry'):
|
|
4218
|
+
raise CoreError('invalid_resolution')
|
|
4219
|
+
with self._lock('sender') as acquired:
|
|
4220
|
+
if not acquired:
|
|
4221
|
+
raise CoreError('sender_busy')
|
|
4222
|
+
with self._tx() as db:
|
|
4223
|
+
self._recover_sends(db)
|
|
4224
|
+
row = db.execute('SELECT * FROM outbox WHERE id=?', (outbox_id,)).fetchone()
|
|
4225
|
+
table = 'outbox'
|
|
4226
|
+
if row is None:
|
|
4227
|
+
row = db.execute('SELECT * FROM reaction_outbox WHERE id=?', (outbox_id,)).fetchone()
|
|
4228
|
+
table = 'reaction_outbox'
|
|
4229
|
+
if row is None:
|
|
4230
|
+
# A retry repeats only the step without a recorded message id.
|
|
4231
|
+
row = db.execute('SELECT * FROM owner_outbox WHERE id=?', (outbox_id,)).fetchone()
|
|
4232
|
+
table = 'owner_outbox'
|
|
4233
|
+
if row is None or row['status'] != 'unknown':
|
|
4234
|
+
raise CoreError('not_unknown')
|
|
4235
|
+
if resolution == 'accepted' and table == 'outbox' and (not _integer(message_id) or message_id <= 0):
|
|
4236
|
+
raise CoreError('message_id_required')
|
|
4237
|
+
if resolution == 'retry':
|
|
4238
|
+
self._binding(db, row['client_id'], usable=True)
|
|
4239
|
+
if table == 'outbox' and row['recipient']:
|
|
4240
|
+
self._binding(db, row['recipient'], usable=True)
|
|
4241
|
+
status = {'accepted': 'sent', 'cancel': 'rejected', 'retry': 'queued'}[resolution]
|
|
4242
|
+
error = None if resolution == 'accepted' else 'operator_' + resolution
|
|
4243
|
+
if table == 'outbox':
|
|
4244
|
+
db.execute('UPDATE outbox SET status=?,error=?,message_id=?,due=?,updated=? WHERE id=?', (status, error, message_id if resolution == 'accepted' else None, self.clock(), self.clock(), outbox_id))
|
|
4245
|
+
else:
|
|
4246
|
+
db.execute(f'UPDATE {table} SET status=?,error=?,due=?,updated=? WHERE id=?', (status, error, self.clock(), self.clock(), outbox_id))
|
|
4247
|
+
result = db.execute(f'SELECT * FROM {table} WHERE id=?', (outbox_id,)).fetchone()
|
|
4248
|
+
resolved = {'outbox': self._outbox_status, 'reaction_outbox': self._reaction_status,
|
|
4249
|
+
'owner_outbox': self._owner_status}[table](result)
|
|
4250
|
+
if table == 'outbox' and resolution in ('accepted', 'cancel') and row['image']:
|
|
4251
|
+
# Terminal: no later attempt can need the copy again. A retry keeps it.
|
|
4252
|
+
self._delete_outbox_image(row['image'])
|
|
4253
|
+
return resolved
|