agents-over-telegram 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +141 -0
  3. package/docs/BOT_EXCHANGES.md +121 -0
  4. package/docs/COMPATIBILITY.md +110 -0
  5. package/docs/DIRECT_DISPATCH.md +155 -0
  6. package/docs/HOSTS.md +244 -0
  7. package/docs/IMPLEMENTATION_STATUS.md +205 -0
  8. package/docs/LIVE_VALIDATION.md +35 -0
  9. package/docs/MACOS_SERVICE.md +89 -0
  10. package/docs/OPERATIONS.md +568 -0
  11. package/docs/REACTIONS.md +51 -0
  12. package/docs/RELAY.md +115 -0
  13. package/docs/RELEASING.md +45 -0
  14. package/docs/schemas/mcp.schema.json +120 -0
  15. package/docs/schemas/sources.json +9 -0
  16. package/integrations/pi/agents-over-telegram.ts +154 -0
  17. package/package.json +41 -0
  18. package/pyproject.toml +37 -0
  19. package/requirements/build.txt +18 -0
  20. package/requirements/runtime.txt +532 -0
  21. package/scripts/bootstrap_runtime.py +402 -0
  22. package/skills/telegram-coordinate/SKILL.md +67 -0
  23. package/skills/telegram-setup/SKILL.md +81 -0
  24. package/src/agents_over_telegram/__init__.py +2 -0
  25. package/src/agents_over_telegram/__main__.py +2 -0
  26. package/src/agents_over_telegram/appserver_client.py +400 -0
  27. package/src/agents_over_telegram/cli.py +851 -0
  28. package/src/agents_over_telegram/codex_trust.py +206 -0
  29. package/src/agents_over_telegram/compat.py +207 -0
  30. package/src/agents_over_telegram/core.py +4253 -0
  31. package/src/agents_over_telegram/credentials.py +108 -0
  32. package/src/agents_over_telegram/demo.py +85 -0
  33. package/src/agents_over_telegram/desktop_bridge.py +537 -0
  34. package/src/agents_over_telegram/desktop_dispatcher.py +680 -0
  35. package/src/agents_over_telegram/dispatcher.py +260 -0
  36. package/src/agents_over_telegram/host_config.py +125 -0
  37. package/src/agents_over_telegram/hosts.py +590 -0
  38. package/src/agents_over_telegram/judge.py +230 -0
  39. package/src/agents_over_telegram/macos_process.py +133 -0
  40. package/src/agents_over_telegram/markdown.py +127 -0
  41. package/src/agents_over_telegram/mcp_server.py +652 -0
  42. package/src/agents_over_telegram/net.py +130 -0
  43. package/src/agents_over_telegram/onboarding.py +719 -0
  44. package/src/agents_over_telegram/push.py +421 -0
  45. package/src/agents_over_telegram/relay.py +380 -0
  46. package/src/agents_over_telegram/relay_api.py +591 -0
  47. package/src/agents_over_telegram/relay_watch.py +171 -0
  48. package/src/agents_over_telegram/serve.py +626 -0
  49. package/src/agents_over_telegram/settings_panel.py +216 -0
  50. package/src/agents_over_telegram/transport.py +720 -0
  51. package/src/agents_over_telegram/webhook.py +219 -0
  52. package/uv.lock +1011 -0
@@ -0,0 +1,216 @@
1
+ """The owner's settings panel: a Telegram HTML widget in the private chat with the shared bot.
2
+
3
+ One panel per owner covers every connection that owner has on the bot, with a
4
+ picker at the top. The widget draws from its chat state and asks the bot with
5
+ requests of a few bytes; the bot checks every request
6
+ (core.Core._route_widget_query): only the owner, in their private chat, on the
7
+ latest panel AOT sent them, for a connection they still own, can change a
8
+ setting, and only to one of the values listed here. Settings that warn need a
9
+ second tap, with the warning the terminal shows.
10
+
11
+ Widgets currently work only in the private chat with the bot (Bot API 10.4).
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import re
17
+
18
+ # (setting, label, values, value labels). The order is part of the request
19
+ # format, so only append to it; SECTIONS groups them for drawing.
20
+ SETTINGS = (
21
+ ('delivery_filter', 'Deliver', ('all', 'addressed'), ('All', 'Addressed')),
22
+ ('capture_context', 'Others as context', (False, True), ('Off', 'On')),
23
+ ('accept_media', 'Media', (False, True), ('Off', 'On')),
24
+ ('reaction_wake', 'Reactions wake', ('own_messages', 'all', 'none'), ('Own', 'All', 'None')),
25
+ ('wake_interval', 'Batch notices', (0, 60, 300, 600, 1800), ('Off', '1m', '5m', '10m', '30m')),
26
+ ('wake_exempt', 'Skip batching', ('addressed,owner', 'addressed', 'owner', 'none'),
27
+ ('Both', 'Addr', 'Owner', 'None')),
28
+ ('owner_notify', 'Notices to you', (False, True), ('Off', 'On')),
29
+ ('model_judge', 'Model judge', (False, True), ('Off', 'On')),
30
+ ('auto_allow', 'Auto-allow', (False, True), ('Off', 'On')),
31
+ ('keep_alive', 'Keep-alive', (False, True), ('Off', 'On')),
32
+ ('approvals_in', 'Ask approvals in', ('private', 'group'), ('Private', 'Group')),
33
+ )
34
+ SECTIONS = (('Messages', (0, 1, 2)), ('Wake-ups', (3, 4, 5, 9)), ('Access', (8, 7, 6, 10)))
35
+
36
+ # Turning these on needs a second tap, with the warning the terminal shows.
37
+ WARNINGS = {
38
+ 'model_judge': 'With the addressed filter, recent messages from this group are sent to the configured '
39
+ 'decision model to decide whether a message is meant for this agent.',
40
+ 'auto_allow': 'Everyone who posts in this group, people and bots, becomes an allowed sender and can give '
41
+ 'this agent work, including anyone who joins later through an invite link.',
42
+ 'keep_alive': 'An idle Claude Code session is woken for one short turn per idle day, which reads the '
43
+ 'whole conversation without the prompt cache.',
44
+ }
45
+
46
+ MAX_CONNECTIONS = 8
47
+
48
+
49
+ def key(client_id):
50
+ """The short form of a client id used in requests: its 24 hex digits."""
51
+ return client_id.removeprefix('agent_')
52
+
53
+
54
+ def _line(text, limit):
55
+ text = ' '.join(str(text).split())
56
+ return text if len(text) <= limit else text[:limit - 1] + '…'
57
+
58
+
59
+ def values(settings):
60
+ """The index of each current value, -1 when it is not one of the presets."""
61
+ return [options.index(settings.get(name)) if settings.get(name) in options else -1
62
+ for name, _, options, _ in SETTINGS]
63
+
64
+
65
+ def view(client_id, settings):
66
+ """What the widget draws for one connection."""
67
+ return {'k': key(client_id), 'v': values(settings), 'wi': settings.get('wake_interval')}
68
+
69
+
70
+ def state(connections, client_id, settings):
71
+ """The panel's chat state: the owner's connections and the selected one's values.
72
+
73
+ ``connections`` are rows with client_id, label and title; at most
74
+ MAX_CONNECTIONS are listed, which keeps the state far below 1 KB.
75
+ """
76
+ listed = [[_line(c['label'], 24), _line(c['title'], 40), key(c['client_id'])]
77
+ for c in connections[:MAX_CONNECTIONS]]
78
+ return json.dumps({'c': listed, **view(client_id, settings)}, separators=(',', ':'), ensure_ascii=False)
79
+
80
+
81
+ def parse(data):
82
+ """(kind, client key, setting name, value) for a request, or None when it is not valid.
83
+
84
+ ``v:<key>`` asks for one connection's values (when the panel appears or a
85
+ connection is picked). ``s:<key>:<i>:<j>`` sets setting i to value j, and
86
+ ``c:<key>:<i>:<j>`` is the second tap that confirms a setting that warns.
87
+ ``x`` closes the panel: the bot deletes its message.
88
+ """
89
+ if not isinstance(data, str):
90
+ return None
91
+ if data == 'x':
92
+ return 'x', None, None, None
93
+ match = re.fullmatch(r'v:([0-9a-f]{24})', data)
94
+ if match:
95
+ return 'v', match.group(1), None, None
96
+ match = re.fullmatch(r'([sc]):([0-9a-f]{24}):([0-9]{1,2}):([0-9]{1,2})', data)
97
+ if match is None:
98
+ return None
99
+ i, j = int(match.group(3)), int(match.group(4))
100
+ if i >= len(SETTINGS) or j >= len(SETTINGS[i][2]):
101
+ return None
102
+ name, _, options, _ = SETTINGS[i]
103
+ return match.group(1), match.group(2), name, options[j]
104
+
105
+
106
+ # The button menu: the same settings as an ordinary message with inline
107
+ # buttons, sent when Telegram refuses the widget (since November 2026 it
108
+ # refuses widgets from most bots). Each button's data is a widget request
109
+ # behind this prefix, so the bot checks it exactly like a widget request.
110
+ MENU_PREFIX = 'aot:p:'
111
+ MENU_NOTE = 'Telegram has turned off settings panels for bots for now, so these are buttons instead.'
112
+
113
+
114
+ def _button(text, request):
115
+ return {'text': text, 'callback_data': MENU_PREFIX + request}
116
+
117
+
118
+ def menu(connections, client_id, settings, confirm=None):
119
+ """(text, reply_markup) for the button menu of one selected connection.
120
+
121
+ A tap on a setting moves it to its next value. ``confirm`` is the
122
+ (setting index, value index) of a change that warns: the menu then shows
123
+ the warning with Confirm and Cancel instead of the settings.
124
+ """
125
+ listed = connections[:MAX_CONNECTIONS]
126
+ selected = next(c for c in listed if c['client_id'] == client_id)
127
+ k = key(client_id)
128
+ lines = [f"Settings for {_line(selected['label'], 40)} in {_line(selected['title'], 60)}"]
129
+ rows = []
130
+ if len(listed) > 1:
131
+ pickers = [_button(('• ' if c['client_id'] == client_id else '') + _line(c['label'], 20),
132
+ f"v:{key(c['client_id'])}") for c in listed]
133
+ rows += [pickers[n:n + 2] for n in range(0, len(pickers), 2)]
134
+ if confirm is not None:
135
+ i, j = confirm
136
+ name, label = SETTINGS[i][0], SETTINGS[i][1]
137
+ lines += ['', WARNINGS[name], '', f'Turn on {label}?']
138
+ rows.append([_button(f'Turn on {label}', f'c:{k}:{i}:{j}'), _button('Cancel', f'v:{k}')])
139
+ else:
140
+ lines += ['Tap a setting to switch it to its next value.', '', MENU_NOTE]
141
+ current = values(settings)
142
+ for _, indexes in SECTIONS:
143
+ for i in indexes:
144
+ name, label, options, shown = SETTINGS[i]
145
+ now = current[i]
146
+ if now >= 0:
147
+ value = shown[now]
148
+ elif name == 'wake_interval' and isinstance(settings.get(name), int):
149
+ value = f'{settings[name]}s'
150
+ else:
151
+ value = str(settings.get(name))
152
+ rows.append([_button(f'{label}: {value}', f's:{k}:{i}:{(now + 1) % len(options)}')])
153
+ rows.append([_button('Close', 'x')])
154
+ return '\n'.join(lines), {'inline_keyboard': rows}
155
+
156
+
157
+ def parse_menu(data):
158
+ """parse() for a menu button's data, or None when it is not a menu button."""
159
+ if not isinstance(data, str) or not data.startswith(MENU_PREFIX):
160
+ return None
161
+ return parse(data[len(MENU_PREFIX):])
162
+
163
+
164
+ # The widget only draws its state and sends requests; the bot decides.
165
+ HTML = '''<style>
166
+ body{margin:0;padding:8px 10px 10px;font-size:13px}
167
+ .top{display:flex;align-items:flex-start;justify-content:space-between;gap:8px}.top>div{min-width:0}
168
+ #x{border:0;border-radius:12px;padding:3px 9px;font-size:12px;background:var(--tg-theme-secondary-bg-color);color:var(--tg-theme-hint-color)}
169
+ .hd{font-weight:600;font-size:14px}.sub{color:var(--tg-theme-hint-color);font-size:12px;margin:0 0 6px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
170
+ .pk{display:flex;gap:4px;flex-wrap:wrap;margin:0 0 2px}
171
+ .pk button{border:0;border-radius:12px;padding:3px 9px;font-size:12px;background:var(--tg-theme-secondary-bg-color);color:var(--tg-theme-text-color)}
172
+ .pk button.on{background:var(--tg-theme-button-color);color:var(--tg-theme-button-text-color)}
173
+ .sec{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.04em;color:var(--tg-theme-section-header-text-color,var(--tg-theme-hint-color));margin:8px 0 2px}
174
+ .row{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:2px 8px;padding:3px 0}
175
+ .lb{flex:1 1 90px;min-width:0}.lb i{color:var(--tg-theme-hint-color);font-style:normal}
176
+ .seg{display:flex;flex:0 0 auto;gap:1px;padding:2px;border-radius:8px;background:var(--tg-theme-secondary-bg-color)}
177
+ .seg button{border:0;border-radius:6px;padding:3px 7px;font-size:12px;background:transparent;color:var(--tg-theme-text-color)}
178
+ .seg button.on{background:var(--tg-theme-button-color);color:var(--tg-theme-button-text-color);font-weight:600}
179
+ #w{display:none;border-radius:10px;padding:8px 10px;margin:2px 0 6px;background:var(--tg-theme-secondary-bg-color)}
180
+ #w p{margin:0 0 6px;font-size:12px;color:var(--tg-theme-destructive-text-color)}#w .seg{background:none;gap:6px;padding:0}
181
+ #w .seg button{background:var(--tg-theme-bg-color);padding:5px 12px}#w .seg button.on{background:var(--tg-theme-button-color)}
182
+ #m{font-size:11px;color:var(--tg-theme-hint-color);min-height:14px;margin-top:2px}
183
+ </style><div class="top"><div><div class="hd" id="t">Settings</div><div class="sub" id="g"></div></div><button id="x">Close</button></div><div class="pk" id="p"></div>
184
+ <div id="w"><p id="wt"></p><div class="seg"><button class="on" id="wy">Turn on</button><button id="wn">Cancel</button></div></div>
185
+ <div id="s"></div><div id="m"></div>
186
+ <script>
187
+ const W=window.TelegramWidget,S=__SETTINGS__,G=__SECTIONS__;let st=null,busy=0;
188
+ const $=i=>document.getElementById(i),el=(t,c,x)=>{const e=document.createElement(t);if(c)e.className=c;if(x!=null)e.textContent=x;return e};
189
+ function msg(t){$('m').textContent=t||''}
190
+ function load(){try{st=JSON.parse(W.chatData)}catch(e){st=null}draw()}
191
+ function cur(){return st&&st.c&&st.c.find(c=>c[2]==st.k)}
192
+ function draw(){const s=$('s'),p=$('p'),w=$('w');w.style.display='none';document.body.appendChild(w);s.innerHTML='';p.innerHTML='';const c=cur();
193
+ if(!c){$('t').textContent='Settings';$('g').textContent='No connected agents.';return}
194
+ $('t').textContent=c[0];$('g').textContent=c[1];
195
+ if(st.c.length>1)st.c.forEach(x=>{const b=el('button',x[2]==st.k?'on':'',x[0]);b.onclick=()=>ask('v:'+x[2]);p.appendChild(b)});
196
+ G.forEach(([h,ix])=>{s.appendChild(el('div','sec',h));ix.forEach(i=>{const r=el('div','row'),l=el('div','lb',S[i][0]);
197
+ if(st.v[i]<0&&i==4&&st.wi!=null)l.appendChild(el('i','',' ('+st.wi+'s)'));r.appendChild(l);const g=el('div','seg');
198
+ S[i][1].forEach((n,j)=>{const b=el('button',j==st.v[i]?'on':'',n);b.onclick=()=>ask('s:'+st.k+':'+i+':'+j,r);g.appendChild(b)});
199
+ r.appendChild(g);s.appendChild(r)})})}
200
+ function ask(d,row){if(busy)return;busy=1;msg('Saving…');W.request(d).then(a=>{busy=0;let r={};
201
+ try{r=JSON.parse(a.result||'{}')}catch(e){}
202
+ if(r.w){const w=$('w');$('wt').textContent=r.w;if(row)row.parentNode.insertBefore(w,row.nextSibling);w.style.display='block';
203
+ $('wy').onclick=()=>{w.style.display='none';ask('c'+d.slice(1),row)};$('wn').onclick=()=>{w.style.display='none';msg('')};msg('');return}
204
+ if(r.s){st=Object.assign(st||{},r.s);draw()}msg(r.e?'Not changed: '+r.e:d[0]=='v'?'':'Saved.')},e=>{busy=0;msg('Not changed: '+e.code)})}
205
+ $('x').onclick=()=>{if(busy)return;busy=1;msg('Closing…');W.request('x').then(()=>{busy=0},e=>{busy=0;msg('Not closed: '+e.code)})};
206
+ W.onEvent('chatDataChanged',load);load();W.ready();
207
+ if(st&&st.k)W.request('v:'+st.k).then(a=>{try{const r=JSON.parse(a.result||'{}');if(r.s&&!busy){Object.assign(st,r.s);draw()}}catch(e){}},()=>{});
208
+ </script>'''
209
+
210
+
211
+ def html():
212
+ """The widget's HTML, with the setting labels and sections for drawing."""
213
+ labels = [[label, list(names)] for _, label, _, names in SETTINGS]
214
+ sections = [[title, list(indexes)] for title, indexes in SECTIONS]
215
+ return (HTML.replace('__SETTINGS__', json.dumps(labels, separators=(',', ':'), ensure_ascii=False))
216
+ .replace('__SECTIONS__', json.dumps(sections, separators=(',', ':'), ensure_ascii=False)))