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,719 @@
1
+ """Local operator onboarding and exact-directory, non-secret profile references."""
2
+ from __future__ import annotations
3
+
4
+ from datetime import datetime, timezone
5
+ import hashlib
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import re
10
+ import shlex
11
+ import stat
12
+ import sys
13
+ import tempfile
14
+ import tomllib
15
+
16
+ from . import compat
17
+ from .credentials import CredentialError, private_directory, read_private_json, write_private_json
18
+
19
+ PROFILE_NAME = '.aot-profile.json'
20
+ SHORT_COMMANDS = {'status', 'history', 'pause', 'resume', 'unsuspend', 'tool'}
21
+ PROFILE_CLIENT_COMMANDS = SHORT_COMMANDS | {'flush', 'mcp', 'watch', 'tool'}
22
+ CONNECTED_NEXT_STEP = (
23
+ 'Open this exact project folder in Codex and trust it if prompted. Reopen its chat, then ask '
24
+ '"Telegram status" to verify that the native Telegram tools are loaded and connected. '
25
+ 'To enable automatic wakeups, ask "Listen for Telegram in this chat for one hour and reply to my messages." '
26
+ 'Setup does not start a listener.'
27
+ )
28
+
29
+ HOST_NEXT_STEPS = {
30
+ 'codex': CONNECTED_NEXT_STEP,
31
+ 'claude': (
32
+ 'Enable the Agents over Telegram Claude Code plugin for this project only, for example: '
33
+ '"claude plugin install agents-over-telegram@agents-over-telegram --scope local" run in this exact folder. '
34
+ 'Start Claude Code in this folder and ask "Telegram status". While an interactive session is open, '
35
+ 'the plugin monitor collects Telegram updates and wakes the session; hooks add notices at tool boundaries.'
36
+ ),
37
+ 'pi': (
38
+ 'Load the Agents over Telegram Pi extension for this project (see docs/HOSTS.md), start Pi in this exact '
39
+ 'folder and ask "Telegram status". While Pi runs, the extension collects Telegram updates and starts or steers a turn.'
40
+ ),
41
+ 'amp': (
42
+ 'Configure the Agents over Telegram Amp integration for this project (see docs/HOSTS.md), start Amp in this '
43
+ 'exact folder and ask "Telegram status".'
44
+ ),
45
+ 'antigravity': (
46
+ 'Setup wrote this project\'s Telegram tools to .agents/plugins/agents-over-telegram-project. The Agents over '
47
+ 'Telegram plugin installed for the user adds the hooks. Open this exact folder in Antigravity (the agy CLI '
48
+ 'or the desktop app), trust it, and ask "Telegram status". The agent keeps a background waiter running that '
49
+ 'wakes it when a message arrives.'
50
+ ),
51
+ 'grok-bot': (
52
+ 'In Grok Bot, add a custom connector of type Command with the command and arguments under "connector" in '
53
+ 'this result (Connect apps, or ask the Bot to add it), then ask "Telegram status". For wakeups, create a '
54
+ 'routine with a webhook trigger, store its URL and key with "aot webhook-save", and keep '
55
+ '"aot watch --webhook-file ... --collect" running; docs/HOSTS.md has the steps. Grok Bot support is untested.'
56
+ ),
57
+ }
58
+
59
+
60
+ def default_state_dir():
61
+ if compat.WINDOWS and not os.environ.get('XDG_DATA_HOME') and os.environ.get('LOCALAPPDATA'):
62
+ # The user's local profile folder, which other users cannot read.
63
+ return Path(os.environ['LOCALAPPDATA']) / 'agents-over-telegram'
64
+ return Path(os.environ.get('XDG_DATA_HOME', str(Path.home() / '.local/share'))) / 'agents-over-telegram'
65
+
66
+
67
+ def _read_local(path):
68
+ """Read bounded owner-controlled configuration, never follow file symlinks."""
69
+ try:
70
+ compat.refuse_link(path)
71
+ fd = os.open(path, os.O_RDONLY | compat.O_NOFOLLOW | compat.O_BINARY | compat.O_CLOEXEC)
72
+ with os.fdopen(fd, 'r', encoding='utf-8') as stream:
73
+ info = os.fstat(stream.fileno())
74
+ if not stat.S_ISREG(info.st_mode) or not compat.owned(info) or info.st_nlink != 1 or not compat.private(info, 0o022 if Path(path).name == PROFILE_NAME else 0o002):
75
+ raise CredentialError('unsafe_project_config')
76
+ raw = stream.read(262145)
77
+ if len(raw) > 262144:
78
+ raise CredentialError('invalid_project_config')
79
+ return raw
80
+ except (OSError, UnicodeError):
81
+ raise CredentialError('project_config_unavailable') from None
82
+
83
+
84
+ def _check_directory(path):
85
+ if path.exists() or path.is_symlink():
86
+ info = path.lstat()
87
+ if not stat.S_ISDIR(info.st_mode) or not compat.owned(info) or not compat.private(info, 0o002):
88
+ raise CredentialError('unsafe_project_directory')
89
+
90
+
91
+ def read_profile(project, *, required=False):
92
+ project = Path(project).resolve()
93
+ path = project / PROFILE_NAME
94
+ if not path.exists() and not path.is_symlink():
95
+ if required:
96
+ raise CredentialError('project_profile_missing_run_setup')
97
+ return None
98
+ try:
99
+ value = json.loads(_read_local(path))
100
+ keys = {'version', 'project_dir', 'state_dir', 'client_file', 'client_id', 'label', 'mode'}
101
+ if not isinstance(value, dict) or set(value) != keys or type(value['version']) is not int or value['version'] != 1:
102
+ raise ValueError()
103
+ if value['mode'] not in ('live', 'fake') or not all(isinstance(value[k], str) and value[k] for k in keys - {'version'}):
104
+ raise ValueError()
105
+ for key in ('project_dir', 'state_dir', 'client_file'):
106
+ if not Path(value[key]).is_absolute() or '\x00' in value[key] or str(Path(value[key]).resolve()) != value[key]:
107
+ raise ValueError()
108
+ if value['project_dir'] != str(project):
109
+ raise CredentialError('project_profile_scope_mismatch')
110
+ return value
111
+ except (ValueError, TypeError, KeyError):
112
+ raise CredentialError('invalid_project_profile') from None
113
+
114
+
115
+ def resolve_args(args):
116
+ """Use only the profile in cwd, never a parent or a global identity default."""
117
+ profile = read_profile(Path.cwd())
118
+ client_file = getattr(args, 'client_file', None)
119
+ if profile:
120
+ if args.state_dir is not None and Path(args.state_dir).resolve() != Path(profile['state_dir']):
121
+ raise CredentialError('project_profile_state_mismatch')
122
+ if client_file is not None and Path(client_file).resolve() != Path(profile['client_file']):
123
+ raise CredentialError('project_profile_client_mismatch')
124
+ if args.fake is not None and bool(args.fake) != (profile['mode'] == 'fake'):
125
+ raise CredentialError('project_profile_mode_mismatch')
126
+ args.state_dir = Path(profile['state_dir'])
127
+ args.fake = profile['mode'] == 'fake'
128
+ if hasattr(args, 'client_file') and client_file is None and args.command in PROFILE_CLIENT_COMMANDS:
129
+ args.client_file = Path(profile['client_file'])
130
+ args.expected_client_id = profile['client_id'] if getattr(args, 'client_file', None) is not None else None
131
+ else:
132
+ if args.command in SHORT_COMMANDS and client_file is None:
133
+ raise CredentialError('project_profile_missing_run_setup')
134
+ args.state_dir = args.state_dir or default_state_dir()
135
+ args.fake = bool(args.fake)
136
+ args.expected_client_id = None
137
+ return args
138
+
139
+
140
+ def _entry(state, client, fake):
141
+ args = ['--state-dir', str(state)]
142
+ if fake:
143
+ args.append('--fake')
144
+ args += ['mcp', '--client-file', str(client)]
145
+ return {'command': str(compat.own_aot()), 'args': args}
146
+
147
+
148
+ # The tools that handle pushed Telegram work: read the inbox, reply in the bound
149
+ # topic, and acknowledge. Codex's automatic approval reviewer rejects these calls
150
+ # when a hook notice (not the user's typed prompt) asks for them, so setup
151
+ # approves exactly these four for this project's scoped server. Pause,
152
+ # disconnect and connection changes still follow the normal approval policy.
153
+ CODEX_APPROVED_TOOLS = ('messages_poll', 'message_send', 'message_react', 'messages_ack')
154
+
155
+
156
+ def _approvals_toml():
157
+ return ''.join(f'\n[mcp_servers.telegram.tools.{name}]\napproval_mode = "approve"\n'
158
+ for name in CODEX_APPROVED_TOOLS)
159
+
160
+
161
+ def _moved_runtime(selected, expected):
162
+ """A rewrite of the Codex config that moves the same client to this runtime, or None.
163
+
164
+ It applies only when the existing entry has exactly this client's
165
+ arguments and another absolute command, written once in the file.
166
+ """
167
+ if not isinstance(selected, dict) or selected.get('args') != expected['args']:
168
+ return None
169
+ old = selected.get('command')
170
+ if not isinstance(old, str) or old == expected['command'] or not Path(old).is_absolute():
171
+ return None
172
+ needle = 'command = ' + json.dumps(old)
173
+
174
+ def rewrite(raw):
175
+ if raw.count(needle) != 1:
176
+ raise CredentialError('project_mcp_config_conflict')
177
+ return raw.replace(needle, 'command = ' + json.dumps(expected['command']))
178
+ return rewrite
179
+
180
+
181
+ def _config_plan(project, expected, approvals=True):
182
+ """Plan the project's Codex config.
183
+
184
+ With ``approvals``, a new or older ``telegram`` entry without a ``tools``
185
+ table also gets the push-handling tool approvals. An existing ``tools``
186
+ table is the user's choice and stays unchanged.
187
+ """
188
+ _check_directory(project)
189
+ folder = project / '.codex'
190
+ _check_directory(folder)
191
+ path = folder / 'config.toml'
192
+ raw = _read_local(path) if path.exists() or path.is_symlink() else None
193
+ try:
194
+ parsed = tomllib.loads(raw or '')
195
+ servers = parsed.get('mcp_servers', {})
196
+ if not isinstance(servers, dict):
197
+ raise ValueError()
198
+ if 'telegram' in servers:
199
+ selected = servers['telegram']
200
+ moved = _moved_runtime(selected, expected)
201
+ if moved is not None:
202
+ # The same client on another runtime (an update): point the
203
+ # entry at this runtime and keep everything else as written.
204
+ raw = moved(raw)
205
+ parsed = tomllib.loads(raw)
206
+ selected = parsed['mcp_servers']['telegram']
207
+ if not isinstance(selected, dict) or any(selected.get(key) != value for key, value in expected.items()):
208
+ raise CredentialError('project_mcp_config_conflict')
209
+ extras = set(selected) - set(expected) - {'tools'}
210
+ if extras - {'startup_timeout_sec', 'tool_timeout_sec'} or any(type(selected[key]) not in (int, float) or not 0 < selected[key] <= 3600 for key in extras):
211
+ raise CredentialError('project_mcp_config_conflict')
212
+ tools = selected.get('tools')
213
+ if tools is not None and (not isinstance(tools, dict) or not all(isinstance(value, dict) for value in tools.values())):
214
+ raise CredentialError('project_mcp_config_conflict')
215
+ if tools is not None or not approvals:
216
+ return path, (_read_local(path) if path.exists() or path.is_symlink() else None), raw
217
+ proposed = raw + _approvals_toml()
218
+ else:
219
+ suffix = '\n[mcp_servers.telegram]\ncommand = ' + json.dumps(expected['command']) + '\nargs = ' + json.dumps(expected['args']) + '\n'
220
+ proposed = (raw or '') + suffix + (_approvals_toml() if approvals else '')
221
+ selected = tomllib.loads(proposed)['mcp_servers']['telegram']
222
+ if {key: selected[key] for key in expected} != expected:
223
+ raise ValueError()
224
+ return path, (_read_local(path) if path.exists() or path.is_symlink() else None), proposed
225
+ except (ValueError, TypeError, KeyError):
226
+ raise CredentialError('invalid_project_config') from None
227
+
228
+
229
+ def _write_local(path, text, previous):
230
+ """Publish a profile/config atomically, preserving existing unrelated contents."""
231
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
232
+ _check_directory(path.parent)
233
+ current = _read_local(path) if path.exists() or path.is_symlink() else None
234
+ if current != previous:
235
+ raise CredentialError('project_config_changed_retry')
236
+ if current == text:
237
+ return
238
+ temp = None
239
+ try:
240
+ fd, temp = tempfile.mkstemp(prefix='.aot-', dir=path.parent)
241
+ with os.fdopen(fd, 'w', encoding='utf-8') as stream:
242
+ stream.write(text)
243
+ stream.flush()
244
+ os.fsync(stream.fileno())
245
+ # Recheck after staging, so a changed file is not silently overwritten.
246
+ actual = _read_local(path) if path.exists() or path.is_symlink() else None
247
+ if actual != previous:
248
+ raise CredentialError('project_config_changed_retry')
249
+ if previous is None:
250
+ os.link(temp, path)
251
+ os.unlink(temp)
252
+ else:
253
+ os.replace(temp, path)
254
+ temp = None
255
+ except OSError:
256
+ raise CredentialError('project_config_write_failed') from None
257
+ finally:
258
+ if temp is not None:
259
+ os.unlink(temp)
260
+
261
+
262
+ def _safe_label(label):
263
+ if not isinstance(label, str) or not 1 <= len(label.strip()) <= 64 or any(not c.isprintable() or c in '[]' for c in label):
264
+ raise CredentialError('invalid_label')
265
+ return label.strip()
266
+
267
+
268
+ def _next_setup(args, state, fake, project, client):
269
+ argv = [_entry(state, client, fake)['command'], '--state-dir', str(state)]
270
+ if fake:
271
+ argv.append('--fake')
272
+ argv += ['setup', '--label', args.label, '--project-dir', str(project),
273
+ '--host', getattr(args, 'host', None) or 'codex']
274
+ return shlex.join(argv)
275
+
276
+
277
+ def _say(text):
278
+ print(text, file=sys.stderr, flush=True)
279
+
280
+
281
+ def _answer(prompt):
282
+ _say(prompt)
283
+ return input().strip()
284
+
285
+
286
+ def setup(args):
287
+ from .cli import LazyTransport, _client, _mode, register_account
288
+ from .core import Core, CoreError
289
+
290
+ args.label = _safe_label(args.label)
291
+ project = Path(args.project_dir).resolve()
292
+ profile = read_profile(project)
293
+ if profile:
294
+ if profile['label'] != args.label:
295
+ raise CredentialError('project_profile_label_mismatch')
296
+ if args.state_dir is not None and Path(args.state_dir).resolve() != Path(profile['state_dir']):
297
+ raise CredentialError('project_profile_state_mismatch')
298
+ if args.client_file is not None and Path(args.client_file).resolve() != Path(profile['client_file']):
299
+ raise CredentialError('project_profile_client_mismatch')
300
+ if args.fake is not None and bool(args.fake) != (profile['mode'] == 'fake'):
301
+ raise CredentialError('project_profile_mode_mismatch')
302
+ state, client, fake = Path(profile['state_dir']), Path(profile['client_file']), profile['mode'] == 'fake'
303
+ else:
304
+ state = Path(args.state_dir or default_state_dir()).resolve()
305
+ fake = bool(args.fake)
306
+ slug = re.sub('[^a-z0-9]+', '-', args.label.lower()).strip('-') or 'agent'
307
+ selected = state / 'clients' / (slug + '-' + hashlib.sha256(str(project).encode()).hexdigest()[:16] + '.json')
308
+ client = Path(args.client_file).resolve() if args.client_file is not None else selected
309
+ if args.client_file is not None and not client.is_file():
310
+ raise CredentialError('existing_client_file_required')
311
+ if state == project or project in state.parents or client == project or project in client.parents:
312
+ raise CredentialError('private_state_must_be_outside_project')
313
+ host = getattr(args, 'host', None) or 'codex'
314
+ if host not in HOST_NEXT_STEPS:
315
+ raise CredentialError('unsupported_host')
316
+ plugin_plan = []
317
+ if host == 'codex':
318
+ expected = _entry(state, client, fake)
319
+ config_path, old_config, new_config = _config_plan(project, expected)
320
+ elif host in ('pi', 'amp'):
321
+ from .host_config import json_config_plan
322
+ config_path, old_config, new_config = json_config_plan(project, host, _entry(state, client, fake))
323
+ elif host == 'antigravity':
324
+ from .host_config import antigravity_plugin_plan
325
+ plugin_plan = antigravity_plugin_plan(project, _entry(state, client, fake))
326
+ config_path = old_config = new_config = None
327
+ else:
328
+ # The Claude Code plugin starts the runtime through the project runtime pointer.
329
+ _check_directory(project)
330
+ config_path = old_config = new_config = None
331
+ from .hosts import RUNTIME_POINTER, runtime_pointer
332
+ pointer_path = project / RUNTIME_POINTER
333
+ old_pointer = _read_local(pointer_path) if pointer_path.exists() or pointer_path.is_symlink() else None
334
+ new_pointer = runtime_pointer(Path(_entry(state, client, fake)['command']))
335
+ if not args.prepare_only and not sys.stdin.isatty():
336
+ raise CredentialError('private_terminal_required')
337
+ # A mode mismatch is checked before any transport can load credentials.
338
+ state = private_directory(state)
339
+ if compat.WINDOWS and not compat.restrict_directory(state):
340
+ # An existing state folder keeps the ACL it inherited otherwise.
341
+ raise CredentialError('state_directory_acl_failed')
342
+ _mode(state, fake)
343
+ core = Core(state, LazyTransport(state, fake), recover_sends=False)
344
+ try:
345
+ core.accounts_status()
346
+ except CoreError as error:
347
+ if error.code != 'account_not_registered':
348
+ raise
349
+ confirmed = args.receiver_handoff_confirmed
350
+ if not fake and not confirmed and not args.prepare_only:
351
+ _say('This bridge must be the only receiver for the selected bot. Use an unused bot, or stop its existing receiver before continuing. Setup will not stop another receiver or remove a webhook.')
352
+ confirmed = _answer('Confirm that the selected bot has no competing receiver. Type yes to continue:').lower() == 'yes'
353
+ register_account(core, state, fake, confirmed)
354
+ else:
355
+ if not (state / 'mode.json').exists():
356
+ raise CredentialError('state_mode_missing_use_account_register')
357
+ if not fake and not (state / 'credentials.json').is_file():
358
+ raise CredentialError('account_credentials_missing')
359
+ if client.exists() or client.is_symlink():
360
+ client_id = _client(core, client)
361
+ info = core.connection_status(client_id)
362
+ if info['label'] != args.label:
363
+ raise CredentialError('existing_client_label_mismatch')
364
+ if profile and profile['client_id'] != client_id:
365
+ raise CredentialError('project_profile_client_mismatch')
366
+ else:
367
+ if profile:
368
+ raise CredentialError('project_profile_client_missing')
369
+ private_directory(client.parent)
370
+ created = core.create_client(args.label)
371
+ write_private_json(client, created)
372
+ client_id = created['client_id']
373
+ new_profile = {'version': 1, 'project_dir': str(project), 'state_dir': str(state),
374
+ 'client_file': str(client), 'client_id': client_id, 'label': args.label,
375
+ 'mode': 'fake' if fake else 'live'}
376
+ old_profile = _read_local(project / PROFILE_NAME) if profile else None
377
+ # Persist the selected identity before pairing; reruns never mint a replacement.
378
+ _write_local(project / PROFILE_NAME, json.dumps(new_profile, indent=2) + '\n', old_profile)
379
+ if config_path is not None:
380
+ _write_local(config_path, new_config, old_config)
381
+ for path, old_text, new_text in plugin_plan:
382
+ _write_local(path, new_text, old_text)
383
+ if plugin_plan:
384
+ from .host_config import remove_old_antigravity_plugin
385
+ remove_old_antigravity_plugin(project)
386
+ _write_local(pointer_path, new_pointer, old_pointer)
387
+ owned = [project / PROFILE_NAME, pointer_path] + ([plugin_plan[0][0].parent] if plugin_plan else [])
388
+ git = keep_out_of_git(project, owned, [config_path] if config_path is not None else [])
389
+ from . import serve
390
+ collector = None
391
+ if not fake:
392
+ executable = Path(_entry(state, client, fake)['command'])
393
+ # An installed always-on collector moves to this runtime too, never to an older one.
394
+ moved = serve.follow(state, executable)
395
+ collector = _collector_choice(args, state, executable)
396
+ if moved:
397
+ collector['moved_to'] = str(executable)
398
+ status = core.connection_status(client_id)
399
+ next_setup = _next_setup(args, state, fake, project, client)
400
+ result = {'project_dir': str(project), 'profile_file': str(project / PROFILE_NAME),
401
+ 'config_file': str(config_path) if config_path is not None else
402
+ (str(plugin_plan[0][0].parent) if plugin_plan else None),
403
+ 'runtime_pointer': str(pointer_path), 'host': host,
404
+ 'client_id': client_id, 'label': args.label,
405
+ 'mode': new_profile['mode'], 'state_dir': str(state), 'client_file': str(client), 'connected': status['connected'],
406
+ 'host_trust_changed': False, 'automatic_delivery': False, 'git': git}
407
+ if collector is not None:
408
+ result['always_on_collector'] = collector
409
+ if host == 'grok-bot':
410
+ # Grok Bot keeps its connectors in its app, not in a project file.
411
+ result['connector'] = {'type': 'Command', **_entry(state, client, fake)}
412
+ if not status['connected'] and args.prepare_only and (status.get('pairing') or {}).get('sender_id') is None \
413
+ and status.get('pairing'):
414
+ # A rerun after the human posted the pairing command: collect once, so
415
+ # the pairing connects without a terminal (see Core._pairing_trusted).
416
+ try:
417
+ core.collect(timeout=0)
418
+ except CoreError:
419
+ pass
420
+ status = core.connection_status(client_id)
421
+ if status['connected']:
422
+ result['connection'] = status
423
+ result['next_step'] = HOST_NEXT_STEPS[host] + ' ' + _owner_start_step(core)
424
+ result['connected'] = True
425
+ return result
426
+ cache_path = state / 'setup' / (client_id + '.json')
427
+ pairing = status.get('pairing')
428
+ cached = read_private_json(cache_path) if cache_path.exists() else None
429
+ if not pairing:
430
+ cached = core.connection_begin(client_id)
431
+ write_private_json(cache_path, cached, overwrite=cache_path.exists())
432
+ pairing = core.connection_status(client_id)['pairing']
433
+ result['connection'] = core.connection_status(client_id)
434
+ matching = cached is not None and cached.get('pairing_id') == pairing['id']
435
+ command = cached.get('command') if matching else None
436
+ result['pairing_id'] = pairing['id']
437
+ result['pairing'] = {'pairing_id': pairing['id'], 'expires_at': pairing['expires']}
438
+ if command:
439
+ result['pairing_command'] = command
440
+ result['pairing']['command'] = command
441
+ bot_username = (status.get('bot') or {}).get('username')
442
+ bot_name = '@' + bot_username if bot_username else 'the bot'
443
+ destination_step = f'Create or choose this agent\'s dedicated Telegram group or topic and add {bot_name} to its group if it is not already there. '
444
+ if args.prepare_only:
445
+ if pairing.get('sender_id') is not None:
446
+ result['next_step'] = ('The pairing command was posted by someone who does not own this bot\'s '
447
+ 'connections, or its destination is taken. Review it locally with: ' + next_setup)
448
+ elif command:
449
+ result['next_step'] = (destination_step + 'Send the pairing_command there. It connects as soon as AOT '
450
+ 'collects it, with no second confirmation. To finish, the agent runs this setup '
451
+ 'again with --prepare-only, or the human can then run: ' + next_setup)
452
+ else:
453
+ result['next_step'] = ('A pairing is waiting for its command. If the human still has it, they send it; '
454
+ 'then run this setup command again with --prepare-only. Otherwise start a new '
455
+ 'pairing with: ' + next_setup)
456
+ return result
457
+ _say(f'Setting up {args.label}. The bot registration is shared; this project selects one agent.')
458
+ if pairing.get('sender_id') is None:
459
+ if not command:
460
+ result['next_step'] = 'Complete the existing pairing locally, then run: ' + next_setup
461
+ return result
462
+ _say(destination_step + 'Send this exact command in that group or topic:\n' + command)
463
+ if _answer('Press Enter after sending it, or type cancel to stop:').lower() in {'cancel', 'q', 'quit'}:
464
+ raise KeyboardInterrupt()
465
+ intake = core.collect()
466
+ status = core.connection_status(client_id)
467
+ if status['connected']:
468
+ # The owner posted it (or the bot has no owner yet): no second confirmation.
469
+ _say('Connected: ' + json.dumps({key: (status.get('destination') or {}).get(key)
470
+ for key in ('chat_id', 'thread_id', 'owner_id', 'title')}, ensure_ascii=True))
471
+ result.update(connected=True, connection=status,
472
+ next_step=HOST_NEXT_STEPS[host] + ' ' + _owner_start_step(core))
473
+ return result
474
+ pairing = core.pairing_status(pairing['id'])
475
+ if pairing.get('sender_id') is None:
476
+ result['intake'] = intake
477
+ result['next_step'] = 'Pairing has not arrived yet. Check the Telegram destination, then run: ' + next_setup
478
+ return result
479
+ _say('Observed pairing: ' + json.dumps({key: pairing.get(key) for key in ('chat_id', 'thread_id', 'sender_id', 'title')}, ensure_ascii=True))
480
+ if _answer('Connect this exact destination and allow this sender? Type yes to confirm:').lower() != 'yes':
481
+ result['next_step'] = 'No destination was confirmed. To review it again, run: ' + next_setup
482
+ return result
483
+ status = core.confirm_pairing(pairing['id'])
484
+ result.update(connected=True, connection=status, next_step=HOST_NEXT_STEPS[host] + ' ' + _owner_start_step(core))
485
+ return result
486
+
487
+
488
+ GIT_EXCLUDE_HEADER = '# Agents over Telegram: machine-specific files written by aot setup'
489
+
490
+
491
+ def _git(project, *args):
492
+ """Run git in the project; None when git is missing or this is not a repository."""
493
+ import shutil
494
+ import subprocess
495
+ if shutil.which('git') is None:
496
+ return None
497
+ try:
498
+ done = subprocess.run(['git', '-C', str(project), *args], capture_output=True, text=True, timeout=10,
499
+ stdin=subprocess.DEVNULL)
500
+ except (OSError, subprocess.SubprocessError):
501
+ return None
502
+ return done if done.returncode == 0 else None
503
+
504
+
505
+ def keep_out_of_git(project, owned, shared):
506
+ """Keep AOT's machine-specific project files out of version control.
507
+
508
+ ``owned`` files and folders belong to AOT: they go into the repository's
509
+ local .git/info/exclude, which ignores them on this machine without
510
+ changing the project's tracked .gitignore. ``shared`` files (a host's own
511
+ settings file that holds the telegram entry) may hold the project's other
512
+ settings, so they are only reported when git tracks them. Nothing in git
513
+ history changes. The files hold paths and the client id, not secrets.
514
+ """
515
+ top = _git(project, 'rev-parse', '--show-toplevel')
516
+ if top is None:
517
+ return {'repository': False}
518
+ root = Path(top.stdout.strip()).resolve()
519
+ exclude = _git(project, 'rev-parse', '--git-path', 'info/exclude')
520
+ tracked = [str(path) for path in [*owned, *shared]
521
+ if _git(project, 'ls-files', '--error-unmatch', '--', str(path)) is not None]
522
+ excluded = []
523
+ if exclude is not None:
524
+ path = Path(exclude.stdout.strip())
525
+ path = path if path.is_absolute() else Path(project) / path
526
+ try:
527
+ current = path.read_text(encoding='utf-8') if path.exists() else ''
528
+ lines = set(current.splitlines())
529
+ entries = []
530
+ for item in owned:
531
+ relative = Path(item).resolve().relative_to(root).as_posix()
532
+ entry = '/' + relative + ('/' if Path(item).is_dir() else '')
533
+ excluded.append(entry)
534
+ if entry not in lines:
535
+ entries.append(entry)
536
+ if entries:
537
+ path.parent.mkdir(parents=True, exist_ok=True)
538
+ block = ('' if not current or current.endswith('\n') else '\n')
539
+ if GIT_EXCLUDE_HEADER not in lines:
540
+ block += GIT_EXCLUDE_HEADER + '\n'
541
+ with open(path, 'a', encoding='utf-8') as stream:
542
+ stream.write(block + '\n'.join(entries) + '\n')
543
+ except (OSError, ValueError):
544
+ excluded = []
545
+ result = {'repository': True, 'excluded': excluded}
546
+ if tracked:
547
+ result['tracked'] = tracked
548
+ result['warning'] = ('Git tracks these files. They hold this machine\'s paths and AOT client id, so other '
549
+ 'clones cannot use them. Untrack AOT\'s own files with git rm --cached; for a shared '
550
+ 'settings file, keep the telegram entry out of commits.')
551
+ return result
552
+
553
+
554
+ def _owner_start_step(core):
555
+ """Tell the owner to /start the bot, or owner_notify and approvals cannot reach them."""
556
+ try:
557
+ with core._db() as db:
558
+ username = core._account(db)['username']
559
+ except Exception:
560
+ username = None
561
+ bot = '@' + username if username else 'the bot'
562
+ return (f'Also send /start to {bot} once in a private chat. Telegram does not let a bot start a private chat, '
563
+ 'so until then the agent cannot reach you with owner_notify or approval requests.')
564
+
565
+
566
+ def _serve_command(executable, state, option):
567
+ return f'"{executable}" --state-dir "{state}" serve {option}'
568
+
569
+
570
+ def _service_manager():
571
+ return {'darwin': 'launchd', 'win32': 'Task Scheduler'}.get(sys.platform, 'systemd')
572
+
573
+
574
+ def _collector_choice(args, state, executable):
575
+ """Install the always-on collector only when the human chose it.
576
+
577
+ A login service runs on the human's machine after the session ends, so it
578
+ is their call: ``--serve`` installs it, ``--no-serve`` declines it, and
579
+ the interactive wizard asks. ``--prepare-only`` without either flag (an
580
+ agent running setup) installs nothing and reports the offer, so the agent
581
+ can ask the human first.
582
+ """
583
+ import shutil
584
+ from . import serve
585
+ if serve.status(state)['installed']:
586
+ return {'installed': True, 'already_installed': True, 'service': serve.name(state),
587
+ 'remove_with': _serve_command(executable, state, '--uninstall')}
588
+ if sys.platform not in ('linux', 'darwin', 'win32') or (sys.platform == 'linux' and not shutil.which('systemctl')):
589
+ return {'installed': False, 'reason': 'unsupported_platform'}
590
+ offer = {'installed': False,
591
+ 'offer': 'An always-on collector answers settings taps, approvals and /settings, and keeps '
592
+ 'collecting messages, while no agent is running. It is installed as a login service '
593
+ f"({_service_manager()}). Ask the human; with a yes, "
594
+ 'rerun setup with --serve.',
595
+ 'install_with': _serve_command(executable, state, '--install')}
596
+ if getattr(args, 'no_serve', False):
597
+ # Also keeps agents from starting a collector on demand.
598
+ serve.opt_out(state)
599
+ return {'installed': False, 'declined': True}
600
+ chosen = getattr(args, 'serve', False)
601
+ if not chosen and not args.prepare_only and sys.stdin.isatty():
602
+ chosen = _ask_serve()
603
+ if not chosen:
604
+ return offer
605
+ return _install_collector(state, executable=executable)
606
+
607
+
608
+ def _ask_serve():
609
+ """Ask the human at the terminal whether to install the always-on collector."""
610
+ _say('Optional: install an always-on collector as a login service. It answers settings taps, '
611
+ 'approvals and /settings, and keeps collecting messages, while no agent is running.')
612
+ return _answer('Install it? Type yes to install, anything else to skip:').lower() == 'yes'
613
+
614
+
615
+ def _install_collector(state, run_command=None, executable=None):
616
+ """Install aot serve as a user service unless it is already there; never fails setup.
617
+
618
+ Hosts that cannot install a service (a sandbox, no systemd) keep working
619
+ as before, and get the command to run themselves.
620
+ """
621
+ import shutil
622
+ import subprocess
623
+ from . import serve
624
+ executable = executable or serve.own_executable()
625
+ if serve.status(state)['installed']:
626
+ return {'installed': True, 'already_installed': True, 'service': serve.name(state),
627
+ 'remove_with': _serve_command(executable, state, '--uninstall')}
628
+ if sys.platform not in ('linux', 'darwin', 'win32') or (sys.platform == 'linux' and not shutil.which('systemctl')):
629
+ return {'installed': False, 'reason': 'unsupported_platform'}
630
+ run_command = run_command or subprocess.run
631
+ try:
632
+ installed = serve.install(state, run_command=run_command)
633
+ except (OSError, subprocess.SubprocessError, CredentialError) as error:
634
+ # Leave nothing half-installed: undo what the service manager may
635
+ # already have enabled or loaded, and the pointer, which would make
636
+ # status report a collector that is down.
637
+ try:
638
+ serve.uninstall(state, run_command=run_command)
639
+ except (OSError, subprocess.SubprocessError, CredentialError):
640
+ pass
641
+ return {'installed': False, 'reason': type(error).__name__,
642
+ 'next_step': f'Run {_serve_command(executable, state, "--install")} outside the sandbox to '
643
+ 'answer settings and approvals while no agent is running.'}
644
+ return {**installed, 'remove_with': _serve_command(executable, state, '--uninstall')}
645
+
646
+
647
+ def collector_down_text(collector):
648
+ """What to tell the owner when the always-on collector stopped fetching."""
649
+ last = collector.get('last_attempt_at')
650
+ since = (' since ' + datetime.fromtimestamp(last, timezone.utc).strftime('%Y-%m-%d %H:%M UTC')
651
+ if isinstance(last, (int, float)) else ' yet')
652
+ return (f'the always-on collector (aot serve) has not tried to fetch from Telegram{since}, so new messages, '
653
+ 'settings taps and approvals are waiting. Check it with "aot serve --status" and its log '
654
+ '(journalctl --user on Linux, serve.log in the state directory on macOS).')
655
+
656
+
657
+ def human_status(value):
658
+ """Compact display derived solely from sanitized public status fields."""
659
+ bot = value.get('bot') or {}
660
+ destination = value.get('destination') or {}
661
+ intake = value.get('intake') or {}
662
+ state = value.get('state') or ('paused' if value.get('paused') else 'connected' if value.get('connected') else 'unpaired')
663
+ lines = [f"{value['label']}: {state}"]
664
+ if bot.get('username'):
665
+ lines.append('Bot: @' + str(bot['username']))
666
+ if destination:
667
+ title = json.dumps(destination.get('title', ''), ensure_ascii=True)
668
+ lines.append(f"Destination: {title} | chat {destination.get('chat_id')} | topic {destination.get('thread_id') or 'none'}")
669
+ senders = value.get('allowed_senders', [])
670
+ def sender(row):
671
+ tags = (['bot'] if row.get('is_bot') else []) + (['auto'] if row.get('auto_added') is not None else [])
672
+ tags += ['@' + row['username']] if isinstance(row.get('username'), str) and row['username'].isascii() and row['username'].replace('_', '').isalnum() else []
673
+ return str(row['sender_id']) + (f" ({', '.join(tags)})" if tags else '')
674
+ lines.append('Allowed senders: ' + (', '.join(sender(row) for row in senders) or 'none'))
675
+ if (value.get('routing') or {}).get('auto_allow'):
676
+ lines.append('Auto-allow: on; everyone who posts here becomes an allowed sender.')
677
+ lines.append(f"Pending: {value.get('pending_messages', 0)} | outgoing: " + json.dumps(value.get('outbox', {}), sort_keys=True))
678
+ reactions = value.get('reactions') or {}
679
+ receive = reactions.get('receive') or {}
680
+ if receive.get('bot_admin') is False:
681
+ lines.append('Reactions: not received (the bot is not an administrator here); ask the owner to promote it.')
682
+ else:
683
+ lines.append(f"Reactions: wake {reactions.get('wake', 'own_messages')}"
684
+ + ('' if receive.get('bot_admin') else '; admin status checked on next collection'))
685
+ lines.append('Delivery: on demand, or automatically through a running listener.')
686
+ lines.append('Listener: not checked by connection status.')
687
+ lines.append('History: captured context from the last 24 hours.')
688
+ if intake.get('error'):
689
+ lines.append('Intake: ' + str(intake['error']))
690
+ if intake.get('possible_offline_gap'):
691
+ lines.append('History coverage: a collection gap is possible.')
692
+ collector = value.get('collector') or {}
693
+ if collector.get('deferring_to'):
694
+ lines.append(f"Collector: a newer runtime ({collector['deferring_to']}) fetches from Telegram for this bot; "
695
+ f"this project's runtime ({collector.get('runtime_version')}) only reads its inbox. "
696
+ 'Rerun setup in this project to move it to the newer runtime.')
697
+ if collector.get('service_stale'):
698
+ lines.append('Collector: ' + collector_down_text(collector))
699
+ if collector.get('legacy_intake_at'):
700
+ when = datetime.fromtimestamp(collector['legacy_intake_at'], timezone.utc).strftime('%Y-%m-%d %H:%M UTC')
701
+ lines.append(f'Collector: a runtime older than 0.9.24 fetched from Telegram at {when} and routed updates '
702
+ "with its older code. Each project's .aot-runtime.json names its runtime; rerun setup in the "
703
+ 'projects still on an older one.')
704
+ wake = value.get('unresolved_wake') or {}
705
+ if wake.get('notification_id'):
706
+ since = datetime.fromtimestamp(wake['since'], timezone.utc).strftime('%Y-%m-%d %H:%M UTC')
707
+ if wake.get('next_action') == 'wait_for_desktop_wake':
708
+ lines.append(f"Wake: {wake['notification_id']} queued in the desktop since {since}; "
709
+ 'new wakes wait until the desktop opens it.')
710
+ elif wake.get('next_action') == 'review_failing_wake':
711
+ lines.append(f"Wake: {wake['notification_id']} queued in the desktop since {since}, but its wake URL "
712
+ f"failed {wake.get('wake_attempts')} times; the local owner should check the target chat.")
713
+ else:
714
+ lines.append(f"Wake: {wake['notification_id']} {wake.get('status', 'unresolved')} since {since}; "
715
+ 'new wakes are blocked until the local owner reviews it.')
716
+ action = value.get('next_action') or {}
717
+ if action.get('message'):
718
+ lines.append('Next: ' + action['message'])
719
+ return '\n'.join(lines)