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,626 @@
1
+ """An always-on collector for one state directory: ``aot serve``.
2
+
3
+ Owner actions (settings panel taps, approval presses, /settings) must be
4
+ answered within seconds, and Telegram updates should keep arriving whether or
5
+ not an agent is in the middle of a turn. ``aot serve`` long-polls Telegram
6
+ without stopping and does the same work as every other collector: it routes
7
+ messages into the inbox, answers buttons and widget requests, and runs the
8
+ optional model judge. Agents' own waiters and hooks see its collector lock and
9
+ only watch the inbox, so nothing is collected twice.
10
+
11
+ ``aot serve --install`` registers it as a user service (systemd on Linux,
12
+ launchd on macOS). The service starts a small launcher that reads
13
+ ``serve-runtime.json`` in the state directory and runs that AOT executable.
14
+ Setup rewrites the pointer whenever it moves a project to a new runtime; the
15
+ running collector notices, exits, and the service manager starts it again on
16
+ the new runtime.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import hashlib
21
+ import os
22
+ import plistlib
23
+ import shutil
24
+ import subprocess
25
+ import sys
26
+ import threading
27
+ import time
28
+ from pathlib import Path
29
+
30
+ from . import compat
31
+ from .credentials import CredentialError, read_private_json, write_private_json
32
+
33
+ POINTER = 'serve-runtime.json'
34
+ LAUNCHER = 'serve_launch.py'
35
+ LOG = 'serve.log'
36
+ # Held for the whole life of one aot serve, so a state directory never has two.
37
+ SERVE_LOCK = 'serve.lock'
38
+ # Written by setup --no-serve: no service, and no collector started on demand.
39
+ NO_SERVE = 'no-serve'
40
+ ON_DEMAND = 'serve-on-demand.json'
41
+ # A collector started on demand that died is started again at most this often.
42
+ ON_DEMAND_INTERVAL = 60.0
43
+ # A collector started on demand stops after this long with no agent talking
44
+ # to it (calls and waits), so it is a temporary helper, not a hidden service.
45
+ ON_DEMAND_IDLE = 15 * 60.0
46
+ # A collector started on demand waits at most this long for another one to
47
+ # stop (a newer one replacing an older one), then gives up.
48
+ ON_DEMAND_LOCK_WAIT = 60.0
49
+ ON_DEMAND_LOCK = 'serve-on-demand.lock'
50
+ LOG_LIMIT = 1_000_000 # bytes; a bigger log is moved to serve.log.1 when the service starts
51
+ POLL_TIMEOUT = 20
52
+ BUSY_PAUSE = 2.0
53
+ BACKOFF = 2.0
54
+ # Well under WATCHDOG_LIMIT, so a long outage never looks like a stuck loop.
55
+ BACKOFF_MAX = 120.0
56
+ # A loop iteration takes at most a long poll plus a few requests; one that
57
+ # runs past this is stuck, and the collector exits so the service restarts it.
58
+ WATCHDOG_LIMIT = 300.0
59
+ STUCK_EXIT = 4
60
+
61
+ # Started by the service manager with the system Python: it only reads the
62
+ # pointer and replaces itself with the recorded AOT executable. Windows has no
63
+ # exec and Task Scheduler does not restart a task that exits, so there the
64
+ # launcher stays and restarts the collector itself, on the runtime the
65
+ # pointer names at that moment, until the service is uninstalled.
66
+ LAUNCHER_SOURCE = '''"""Start AOT's collector on the runtime named in serve-runtime.json (written by aot serve --install)."""
67
+ import json
68
+ import os
69
+ import sys
70
+
71
+ state = os.path.dirname(os.path.abspath(__file__))
72
+ pointer = os.path.join(state, 'serve-runtime.json')
73
+
74
+
75
+ def executable():
76
+ with open(pointer, encoding='utf-8') as stream:
77
+ return json.load(stream)['executable']
78
+
79
+
80
+ if os.name != 'nt':
81
+ program = executable()
82
+ os.execv(program, [program, '--state-dir', state, 'serve'])
83
+
84
+ # Windows: this launcher supervises the collector. Mark it, so the collector
85
+ # stops once the service is removed even if stopping the task left it running.
86
+ os.environ['AOT_SERVE_SUPERVISED'] = '1'
87
+
88
+ import subprocess
89
+ import time
90
+
91
+ log = os.path.join(state, 'serve.log')
92
+ while os.path.exists(pointer):
93
+ try:
94
+ if os.path.getsize(log) > 1000000:
95
+ os.replace(log, log + '.1')
96
+ except OSError:
97
+ pass
98
+ with open(log, 'ab') as output:
99
+ # CREATE_NO_WINDOW: no console window for the collector.
100
+ code = subprocess.call([executable(), '--state-dir', state, 'serve'], stdin=subprocess.DEVNULL,
101
+ stdout=output, stderr=output, creationflags=0x08000000)
102
+ # 3: a newer runtime is installed; start it at once. Anything else: wait a little.
103
+ time.sleep(1 if code == 3 else 5)
104
+ '''
105
+
106
+
107
+ def own_executable():
108
+ return compat.own_aot()
109
+
110
+
111
+ def _task_name(state):
112
+ return '\\' + name(state)
113
+
114
+
115
+ def pointer(state):
116
+ """The executable the service should run, or None when no service is set up."""
117
+ path = Path(state) / POINTER
118
+ if not path.exists() and not path.is_symlink():
119
+ return None
120
+ try:
121
+ value = read_private_json(path)
122
+ except CredentialError:
123
+ return None
124
+ executable = value.get('executable') if isinstance(value, dict) else None
125
+ return Path(executable) if isinstance(executable, str) and os.path.isabs(executable) else None
126
+
127
+
128
+ def _pointer_value(executable):
129
+ from . import __version__
130
+ return {'version': 1, 'executable': str(executable), 'aot_version': __version__}
131
+
132
+
133
+ def pointer_version(state):
134
+ """The AOT release the pointer names, when the pointer records it."""
135
+ try:
136
+ value = read_private_json(Path(state) / POINTER)
137
+ except (CredentialError, OSError):
138
+ return None
139
+ version = value.get('aot_version') if isinstance(value, dict) else None
140
+ return version if isinstance(version, str) else None
141
+
142
+
143
+ def follow(state, executable=None):
144
+ """Point an installed service at this runtime; True when the pointer changed.
145
+
146
+ Setup calls this, so moving a project to a new runtime also moves the
147
+ collector. Nothing happens when no service is installed, and the service
148
+ never moves to an older release than the one it runs: rerunning setup in
149
+ a project that is still on an older runtime leaves it alone.
150
+ """
151
+ from . import __version__
152
+ from .core import _version_key
153
+ current = pointer(state)
154
+ target = Path(executable or own_executable())
155
+ if current is None or os.path.realpath(current) == os.path.realpath(target):
156
+ return False
157
+ recorded, ours = _version_key(pointer_version(state)), _version_key(__version__)
158
+ if recorded is not None and ours is not None and recorded > ours:
159
+ return False
160
+ write_private_json(Path(state) / POINTER, _pointer_value(target), overwrite=True)
161
+ return True
162
+
163
+
164
+ def moved(state):
165
+ """True when the pointer names another runtime than the one running this collector."""
166
+ current = pointer(state)
167
+ return current is not None and os.path.realpath(current) != os.path.realpath(own_executable())
168
+
169
+
170
+ class Watchdog:
171
+ """Notices a collector loop that stopped making progress.
172
+
173
+ The service manager only restarts a process that exits; one that hangs
174
+ (a request that never returns, a lock that is never released) would leave
175
+ every agent deaf. The loop beats once per iteration, and a thread exits
176
+ the process when no beat came for ``limit`` seconds.
177
+ """
178
+
179
+ def __init__(self, limit=WATCHDOG_LIMIT, clock=time.monotonic):
180
+ self.limit, self.clock = limit, clock
181
+ self.last = clock()
182
+
183
+ def beat(self):
184
+ self.last = self.clock()
185
+
186
+ def stuck(self):
187
+ return self.clock() - self.last > self.limit
188
+
189
+ def start(self, log, exit_=os._exit, sleep=time.sleep):
190
+ def watch():
191
+ while True:
192
+ sleep(max(1.0, self.limit / 10))
193
+ if self.stuck():
194
+ log(f'aot serve: no progress for {self.limit:.0f}s; exiting so the service restarts it')
195
+ exit_(STUCK_EXIT)
196
+ return
197
+ thread = threading.Thread(target=watch, name='aot-serve-watchdog', daemon=True)
198
+ thread.start()
199
+ return thread
200
+
201
+
202
+ def run(core, state, *, poll_timeout=POLL_TIMEOUT, sleep=time.sleep, keep_running=None, log=None, watchdog=None,
203
+ relay=None, on_demand=False, clock=time.monotonic):
204
+ """Collect without stopping; return 3 when the runtime moved, 0 when told to stop.
205
+
206
+ With ``relay`` it also answers agents' tool calls on the state directory's
207
+ socket (relay_api). Agents run calls themselves when it cannot listen.
208
+ ``on_demand`` is a collector an agent started (start_on_demand): it stops
209
+ when idle, when the service is installed, when the human opts out, or
210
+ when a newer runtime takes over (see _on_demand_done).
211
+ """
212
+ log = log or (lambda text: print(text, flush=True))
213
+ rotate_log(state)
214
+ give_up = clock() + ON_DEMAND_LOCK_WAIT if on_demand else None
215
+ lock = _hold_serve_lock(state, sleep, keep_running, log, give_up=give_up, clock=clock)
216
+ if lock is None:
217
+ return 0
218
+ try:
219
+ done = (lambda: _on_demand_done(state, relay, started, clock)) if on_demand else None
220
+ started = clock()
221
+ return _serve(core, state, poll_timeout, sleep, keep_running, log, watchdog, relay, done)
222
+ finally:
223
+ os.close(lock)
224
+
225
+
226
+ def _hold_serve_lock(state, sleep, keep_running, log, give_up=None, clock=time.monotonic):
227
+ """Take this state directory's serve lock, waiting while another aot serve holds it."""
228
+ fd = os.open(Path(state) / SERVE_LOCK, os.O_RDWR | os.O_CREAT | compat.O_CLOEXEC, 0o600)
229
+ told = False
230
+ while True:
231
+ try:
232
+ compat.lock(fd)
233
+ return fd
234
+ except OSError:
235
+ pass
236
+ if not told:
237
+ log('aot serve: another aot serve runs for this state directory; waiting until it stops')
238
+ told = True
239
+ if (keep_running is not None and not keep_running()) or (give_up is not None and clock() >= give_up):
240
+ os.close(fd)
241
+ return None
242
+ sleep(BUSY_PAUSE)
243
+
244
+
245
+ def opt_out(state):
246
+ """Record that the human wants no collector: no service, and none started on demand."""
247
+ marker = Path(state) / NO_SERVE
248
+ if not marker.exists():
249
+ os.close(os.open(marker, os.O_WRONLY | os.O_CREAT | compat.O_CLOEXEC, 0o600))
250
+
251
+
252
+ def _on_demand_done(state, relay, started, clock):
253
+ """Why a collector started on demand should stop now, or None."""
254
+ state = Path(state)
255
+ if (state / NO_SERVE).exists():
256
+ return 'the human opted out (setup --no-serve)'
257
+ if status(state)['installed']:
258
+ return 'the always-on service is installed'
259
+ recorded = _on_demand_record(state).get('executable')
260
+ if isinstance(recorded, str) and os.path.realpath(recorded) != os.path.realpath(own_executable()):
261
+ return 'a newer runtime takes over'
262
+ last = max(started, getattr(relay, 'last_activity', None) or started)
263
+ if clock() - last >= ON_DEMAND_IDLE:
264
+ return 'no agent used it for a while'
265
+ return None
266
+
267
+
268
+ def _on_demand_record(state):
269
+ try:
270
+ value = read_private_json(Path(state) / ON_DEMAND)
271
+ except (CredentialError, OSError):
272
+ return {}
273
+ return value if isinstance(value, dict) else {}
274
+
275
+
276
+ def running(state):
277
+ """True when an aot serve holds this state directory's serve lock."""
278
+ try:
279
+ fd = os.open(Path(state) / SERVE_LOCK, os.O_RDWR | os.O_CREAT | compat.O_CLOEXEC, 0o600)
280
+ except OSError:
281
+ return False
282
+ try:
283
+ compat.lock(fd)
284
+ except OSError:
285
+ return True
286
+ else:
287
+ compat.unlock(fd)
288
+ return False
289
+ finally:
290
+ os.close(fd)
291
+
292
+
293
+ def start_on_demand(state, *, executable=None, spawn=subprocess.Popen, now=time.time):
294
+ """Start aot serve in the background when nothing else will collect; the reason when not.
295
+
296
+ A fallback for machines without the user service: agents call this when
297
+ they start, so owner actions and messages are still handled. It starts
298
+ nothing when the state directory is in fake mode, when setup --no-serve
299
+ opted out, when the service is installed (its manager restarts it), when
300
+ a collector of this runtime or a newer one already runs, or when one was
301
+ started less than a minute ago (so a collector that dies at once is not
302
+ restarted in a loop). An older collector started on demand is replaced:
303
+ the record names this runtime, the older one notices and stops, and the
304
+ new one takes the lock after it.
305
+
306
+ The collector is detached from the agent's session and stops by itself
307
+ after ON_DEMAND_IDLE without agents, so it is a temporary helper.
308
+ """
309
+ from . import __version__
310
+ from .core import _version_key
311
+ state = Path(state).absolute()
312
+ executable = Path(executable or own_executable())
313
+ try:
314
+ mode = read_private_json(state / 'mode.json').get('mode')
315
+ except (CredentialError, OSError):
316
+ mode = None
317
+ if mode != 'live':
318
+ return {'started': False, 'reason': 'not_live'}
319
+ if (state / NO_SERVE).exists():
320
+ return {'started': False, 'reason': 'opted_out'}
321
+ if status(state)['installed']:
322
+ return {'started': False, 'reason': 'service_installed'}
323
+ # Two agents starting at once must not both spawn one.
324
+ fd = os.open(state / ON_DEMAND_LOCK, os.O_RDWR | os.O_CREAT | compat.O_CLOEXEC, 0o600)
325
+ try:
326
+ try:
327
+ compat.lock(fd)
328
+ except OSError:
329
+ return {'started': False, 'reason': 'starting'}
330
+ record = _on_demand_record(state)
331
+ if running(state):
332
+ theirs, ours = _version_key(record.get('aot_version')), _version_key(__version__)
333
+ same = (isinstance(record.get('executable'), str)
334
+ and os.path.realpath(record['executable']) == os.path.realpath(executable))
335
+ if same or theirs is None or ours is None or theirs >= ours:
336
+ return {'started': False, 'reason': 'running'}
337
+ else:
338
+ last = record.get('started')
339
+ if isinstance(last, (int, float)) and 0 <= now() - last < ON_DEMAND_INTERVAL:
340
+ return {'started': False, 'reason': 'recently_started'}
341
+ write_private_json(state / ON_DEMAND, {'version': 1, 'started': now(), 'executable': str(executable),
342
+ 'aot_version': __version__}, overwrite=(state / ON_DEMAND).exists())
343
+ rotate_log(state)
344
+ log = os.open(state / LOG, os.O_WRONLY | os.O_CREAT | os.O_APPEND | compat.O_CLOEXEC, 0o600)
345
+ try:
346
+ # Windows: DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP, so it outlives the agent's console.
347
+ detached = {'creationflags': 0x00000008 | 0x00000200} if compat.WINDOWS else {}
348
+ process = spawn([str(executable), '--state-dir', str(state), 'serve', '--on-demand'],
349
+ stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True,
350
+ close_fds=True, **detached)
351
+ finally:
352
+ os.close(log)
353
+ finally:
354
+ os.close(fd)
355
+ # Reap it when it exits, so it never lingers as a zombie of a long-lived agent process.
356
+ if hasattr(process, 'wait'):
357
+ threading.Thread(target=process.wait, name='aot-serve-reaper', daemon=True).start()
358
+ return {'started': True, 'pid': process.pid}
359
+
360
+
361
+ def _serve(core, state, poll_timeout, sleep, keep_running, log, watchdog, relay, done=None):
362
+ log(f'aot serve: collecting for {state}' + (' (started on demand)' if done is not None else ''))
363
+ from . import __version__
364
+ core.record_activity('serve', {'event': 'started', 'version': __version__, 'on_demand': done is not None})
365
+ plain = log
366
+
367
+ def log(text):
368
+ plain(text)
369
+ # Stops, restarts and failures go to the activity log too.
370
+ if not text.startswith('aot serve: collecting'):
371
+ core.record_activity('serve', {'event': text.removeprefix('aot serve: ')})
372
+ if watchdog is not None:
373
+ watchdog.start(log)
374
+ if relay is not None:
375
+ relay.log = log
376
+ try:
377
+ relay.start()
378
+ except Exception as error:
379
+ log(f'aot serve: not answering agents ({type(error).__name__}: {error}); they run their calls themselves')
380
+ relay = None
381
+ try:
382
+ return _loop(core, state, poll_timeout, sleep, keep_running, log, watchdog, relay, done)
383
+ finally:
384
+ if relay is not None:
385
+ relay.stop()
386
+
387
+
388
+ def _loop(core, state, poll_timeout, sleep, keep_running, log, watchdog, relay=None, done=None):
389
+ from .hosts import RUNTIME_MOVED_EXIT
390
+ failures = 0
391
+ while keep_running is None or keep_running():
392
+ if watchdog is not None:
393
+ watchdog.beat()
394
+ reason = done() if done is not None else None
395
+ if (reason is None and os.environ.get('AOT_SERVE_SUPERVISED')
396
+ and not os.path.lexists(Path(state) / POINTER)):
397
+ # The service was uninstalled; a service manager that stopped only
398
+ # the launcher (Task Scheduler) must not leave this collector behind.
399
+ reason = 'the always-on service was removed'
400
+ if reason:
401
+ log(f'aot serve: stopping, {reason}')
402
+ return 0
403
+ if moved(state):
404
+ log('aot serve: a newer runtime is installed; restarting on it')
405
+ return RUNTIME_MOVED_EXIT
406
+ try:
407
+ result = core.collect(timeout=poll_timeout, judge=True,
408
+ routed=relay.notify if relay is not None else None)
409
+ except Exception as error: # the core records intake errors; keep going
410
+ failures += 1
411
+ code = getattr(error, 'code', type(error).__name__)
412
+ pause = min(BACKOFF_MAX, BACKOFF * 2 ** min(failures - 1, 16))
413
+ log(f'aot serve: collection failed ({code}); retrying in {pause:.0f}s')
414
+ # Waiting out a failure is progress: beat around the pause.
415
+ if watchdog is not None:
416
+ watchdog.beat()
417
+ sleep(pause)
418
+ if watchdog is not None:
419
+ watchdog.beat()
420
+ continue
421
+ if watchdog is not None:
422
+ watchdog.beat()
423
+ if failures:
424
+ log('aot serve: collecting again')
425
+ failures = 0
426
+ if result.get('status') == 'busy':
427
+ # Another collector holds the lock (an older one still stopping).
428
+ sleep(BUSY_PAUSE)
429
+ continue
430
+ started = time.monotonic()
431
+ try:
432
+ # Sends that waited for a rate limit go out without waiting for an agent.
433
+ core.flush(limit=20)
434
+ except Exception:
435
+ pass
436
+ flushed = round((time.monotonic() - started) * 1000)
437
+ if relay is not None:
438
+ relay.flush_activity()
439
+ if flushed >= core.SLOW_CYCLE_MS:
440
+ # Time spent sending is time no fetch runs; taps arriving now wait.
441
+ core.record_activity('cycle', {'flush_ms': flushed})
442
+ return 0
443
+
444
+
445
+ def name(state):
446
+ """The service name for one state directory, so several accounts can each have one."""
447
+ digest = hashlib.sha256(os.path.realpath(state).encode()).hexdigest()[:12]
448
+ return f'agents-over-telegram-{digest}'
449
+
450
+
451
+ def _label(state):
452
+ return 'dev.' + name(state).replace('agents-over-telegram-', 'agents-over-telegram.serve.')
453
+
454
+
455
+ def _unit_path(state):
456
+ if sys.platform == 'win32':
457
+ # The task definition handed to schtasks; Task Scheduler keeps its own copy.
458
+ return Path(state).absolute() / 'serve-task.xml'
459
+ if sys.platform == 'darwin':
460
+ return Path.home() / 'Library' / 'LaunchAgents' / f'{_label(state)}.plist'
461
+ base = Path(os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config')
462
+ return base / 'systemd' / 'user' / f'{name(state)}.service'
463
+
464
+
465
+ def _unit_encoding():
466
+ # schtasks /XML reads UTF-16.
467
+ return 'utf-16' if sys.platform == 'win32' else 'utf-8'
468
+
469
+
470
+ def _task_xml(state, python):
471
+ from xml.sax.saxutils import escape
472
+ launcher = Path(state) / LAUNCHER
473
+ user = escape(os.environ.get('USERDOMAIN', '') + '\\' + os.environ.get('USERNAME', '')
474
+ if os.environ.get('USERDOMAIN') else os.environ.get('USERNAME', ''))
475
+ return ('<?xml version="1.0" encoding="UTF-16"?>\n'
476
+ '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">\n'
477
+ f' <RegistrationInfo><Description>Agents over Telegram collector ({escape(str(state))})</Description>'
478
+ '</RegistrationInfo>\n'
479
+ f' <Triggers><LogonTrigger><Enabled>true</Enabled><UserId>{user}</UserId></LogonTrigger></Triggers>\n'
480
+ f' <Principals><Principal id="Author"><UserId>{user}</UserId><LogonType>InteractiveToken</LogonType>'
481
+ '<RunLevel>LeastPrivilege</RunLevel></Principal></Principals>\n'
482
+ ' <Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>'
483
+ '<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>'
484
+ '<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>'
485
+ '<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>'
486
+ '<RestartOnFailure><Interval>PT1M</Interval><Count>999</Count></RestartOnFailure>'
487
+ '<StartWhenAvailable>true</StartWhenAvailable><Hidden>true</Hidden></Settings>\n'
488
+ f' <Actions Context="Author"><Exec><Command>{escape(str(python))}</Command>'
489
+ f'<Arguments>"{escape(str(launcher))}"</Arguments></Exec></Actions>\n'
490
+ '</Task>\n')
491
+
492
+
493
+ def _windows_python():
494
+ """pythonw.exe of the base interpreter: no console window, and not tied to one runtime's venv."""
495
+ base = Path(getattr(sys, '_base_executable', sys.executable))
496
+ for candidate in (base.with_name('pythonw.exe'), Path(shutil.which('pythonw') or '')):
497
+ if candidate.name and candidate.is_file():
498
+ return str(candidate)
499
+ return str(base)
500
+
501
+
502
+ def _unit(state, python):
503
+ launcher = Path(state) / LAUNCHER
504
+ if sys.platform == 'win32':
505
+ return _task_xml(state, python)
506
+ if sys.platform == 'darwin':
507
+ return plistlib.dumps({'Label': _label(state), 'ProgramArguments': [str(python), str(launcher)],
508
+ 'RunAtLoad': True, 'KeepAlive': True,
509
+ 'StandardOutPath': str(Path(state) / LOG),
510
+ 'StandardErrorPath': str(Path(state) / LOG)}).decode()
511
+ # systemd unit values: quote the paths, and keep the state path out of
512
+ # specifier expansion in the description.
513
+ return (f'[Unit]\nDescription=Agents over Telegram collector ({str(state).replace("%", "%%")})\n'
514
+ 'After=network-online.target\n\n'
515
+ f'[Service]\nExecStart="{python}" "{launcher}"\nRestart=always\nRestartSec=5\n\n'
516
+ '[Install]\nWantedBy=default.target\n')
517
+
518
+
519
+ def rotate_log(state):
520
+ """Move a log over LOG_LIMIT to serve.log.1, replacing an older one (launchd only writes it)."""
521
+ log = Path(state) / LOG
522
+ try:
523
+ if log.stat().st_size > LOG_LIMIT:
524
+ os.replace(log, log.with_name(LOG + '.1'))
525
+ except OSError:
526
+ pass
527
+
528
+
529
+ def install(state, *, run_command=subprocess.run, python=None):
530
+ """Write the pointer, the launcher and the user service, then start it."""
531
+ state = Path(state).absolute()
532
+ # Installing it is the opposite of setup --no-serve.
533
+ (state / NO_SERVE).unlink(missing_ok=True)
534
+ if python is None:
535
+ python = _windows_python() if sys.platform == 'win32' else shutil.which('python3') or '/usr/bin/python3'
536
+ write_private_json(state / POINTER, _pointer_value(own_executable()), overwrite=True)
537
+ launcher = state / LAUNCHER
538
+ launcher.write_text(LAUNCHER_SOURCE, encoding='utf-8')
539
+ launcher.chmod(0o600)
540
+ unit = _unit_path(state)
541
+ unit.parent.mkdir(parents=True, exist_ok=True)
542
+ unit.write_text(_unit(state, python), encoding=_unit_encoding())
543
+ if sys.platform == 'win32':
544
+ task = _task_name(state)
545
+ run_command(['schtasks', '/End', '/TN', task], check=False, capture_output=True)
546
+ run_command(['schtasks', '/Create', '/TN', task, '/XML', str(unit), '/F'], check=True, capture_output=True)
547
+ run_command(['schtasks', '/Run', '/TN', task], check=True, capture_output=True)
548
+ elif sys.platform == 'darwin':
549
+ uid = os.getuid()
550
+ run_command(['launchctl', 'bootout', f'gui/{uid}', str(unit)], check=False, capture_output=True)
551
+ run_command(['launchctl', 'bootstrap', f'gui/{uid}', str(unit)], check=True, capture_output=True)
552
+ else:
553
+ service = f'{name(state)}.service'
554
+ run_command(['systemctl', '--user', 'daemon-reload'], check=True, capture_output=True)
555
+ run_command(['systemctl', '--user', 'enable', '--now', service], check=True, capture_output=True)
556
+ run_command(['systemctl', '--user', 'restart', service], check=True, capture_output=True)
557
+ return {'installed': True, 'service': name(state), 'unit': str(unit), 'executable': str(own_executable()),
558
+ 'state_dir': str(state)}
559
+
560
+
561
+ def uninstall(state, *, run_command=subprocess.run):
562
+ """Stop and remove the user service, the launcher and the pointer.
563
+
564
+ The files are removed even when the service manager cannot be reached
565
+ (a sandbox refusing launchctl or systemctl), so nothing is left that
566
+ makes the service look installed.
567
+ """
568
+ state = Path(state).absolute()
569
+ unit = _unit_path(state)
570
+
571
+ def attempt(argv):
572
+ try:
573
+ run_command(argv, check=False, capture_output=True)
574
+ except (OSError, subprocess.SubprocessError):
575
+ pass
576
+ if sys.platform == 'win32':
577
+ task = _task_name(state)
578
+ attempt(['schtasks', '/End', '/TN', task])
579
+ attempt(['schtasks', '/Delete', '/TN', task, '/F'])
580
+ elif sys.platform == 'darwin':
581
+ attempt(['launchctl', 'bootout', f'gui/{os.getuid()}', str(unit)])
582
+ else:
583
+ attempt(['systemctl', '--user', 'disable', '--now', f'{name(state)}.service'])
584
+ removed = unit.exists()
585
+ for path in (unit, state / LAUNCHER, state / POINTER):
586
+ try:
587
+ if path.exists() or path.is_symlink():
588
+ path.unlink()
589
+ except OSError:
590
+ pass
591
+ if sys.platform not in ('darwin', 'win32'):
592
+ attempt(['systemctl', '--user', 'daemon-reload'])
593
+ return {'installed': False, 'removed': removed}
594
+
595
+
596
+ def status(state):
597
+ """Whether this state directory's service is set up: its pointer, and a unit that starts its launcher."""
598
+ state = Path(state).absolute()
599
+ current = pointer(state)
600
+ unit = _unit_path(state)
601
+ try:
602
+ text = unit.read_text(encoding=_unit_encoding())
603
+ from xml.sax.saxutils import escape
604
+ serves_this = str(state / LAUNCHER) in text or escape(str(state / LAUNCHER)) in text
605
+ except (OSError, UnicodeError):
606
+ serves_this = False
607
+ return {'installed': current is not None and serves_this, 'service': name(state), 'unit': str(unit),
608
+ 'executable': str(current) if current else None}
609
+
610
+
611
+ def activity_lines(entries):
612
+ """The activity log as one readable line per entry, oldest first, in local time."""
613
+ from datetime import datetime
614
+ lines = []
615
+ for entry in entries:
616
+ entry = dict(entry)
617
+ at = datetime.fromtimestamp(entry.pop('at')).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
618
+ kind = entry.pop('kind')
619
+ details = ' '.join(f'{key}={json_compact(value)}' for key, value in entry.items())
620
+ lines.append(f'{at} {kind:<6} {details}')
621
+ return lines
622
+
623
+
624
+ def json_compact(value):
625
+ import json
626
+ return value if isinstance(value, str) else json.dumps(value, separators=(',', ':'), sort_keys=True)