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,590 @@
1
+ """Host integration helpers: hook answers and the per-project runtime pointer.
2
+
3
+ Host plugins (Claude Code, Pi, Amp) are installed once but must start the
4
+ runtime chosen for each project. Setup records that runtime in a small,
5
+ non-secret ``.aot-runtime.json`` next to the project profile. Plugin launchers
6
+ read only that exact project directory; they never search parent directories.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+ import sys
14
+ import time
15
+
16
+ from . import compat
17
+ from .credentials import CredentialError
18
+
19
+ RUNTIME_POINTER = '.aot-runtime.json'
20
+ MAX_HOOK_INPUT = 1024 * 1024
21
+
22
+
23
+ def runtime_pointer(executable: Path) -> str:
24
+ return json.dumps({'version': 1, 'executable': str(executable)}, indent=2) + '\n'
25
+
26
+
27
+ # A long-running waiter that the plugin launcher started with
28
+ # AOT_FOLLOW_RUNTIME=1 exits with this status once the project's runtime
29
+ # pointer names another runtime, and the launcher starts it again on that
30
+ # one. Without the variable (an older launcher) it keeps running as before.
31
+ RUNTIME_MOVED_EXIT = 3
32
+
33
+
34
+ def runtime_moved(project: Path) -> bool:
35
+ """True when following is on and .aot-runtime.json names a runtime other than this one."""
36
+ if os.environ.get('AOT_FOLLOW_RUNTIME') != '1':
37
+ return False
38
+ pointer = read_runtime_pointer(project)
39
+ if pointer is None:
40
+ return False
41
+ own = compat.own_aot()
42
+ return os.path.realpath(pointer) != os.path.realpath(own)
43
+
44
+
45
+ def read_runtime_pointer(project: Path) -> Path | None:
46
+ """Return the recorded executable, or None if the pointer is absent or unsafe."""
47
+ from .onboarding import _read_local
48
+ path = Path(project) / RUNTIME_POINTER
49
+ if not path.exists() and not path.is_symlink():
50
+ return None
51
+ try:
52
+ # Same rule as the plugin launcher: owned, single link, not group or world writable.
53
+ if not compat.private(path.lstat(), 0o022):
54
+ return None
55
+ value = json.loads(_read_local(path))
56
+ if not isinstance(value, dict) or set(value) != {'version', 'executable'}:
57
+ return None
58
+ executable = value['executable']
59
+ if (type(value['version']) is not int or value['version'] != 1 or not isinstance(executable, str)
60
+ or '\x00' in executable or not Path(executable).is_absolute()):
61
+ return None
62
+ return Path(executable)
63
+ except (CredentialError, OSError, ValueError, TypeError, KeyError):
64
+ return None
65
+
66
+
67
+ class _NoTransport:
68
+ """Hooks never contact Telegram; any attempt fails closed."""
69
+
70
+ def __getattr__(self, name):
71
+ raise CredentialError('hook_transport_refused')
72
+
73
+
74
+ def _hook_project(args, payload: dict) -> Path:
75
+ if args.project_dir is not None:
76
+ return Path(args.project_dir)
77
+ if args.host == 'claude' and os.environ.get('CLAUDE_PROJECT_DIR'):
78
+ return Path(os.environ['CLAUDE_PROJECT_DIR'])
79
+ # Antigravity sends its workspace too; its cwd can be a subfolder.
80
+ workspaces = payload.get('workspacePaths')
81
+ cwd = workspaces[0] if isinstance(workspaces, list) and len(workspaces) == 1 else payload.get('cwd')
82
+ if isinstance(cwd, str) and cwd and '\x00' not in cwd:
83
+ return Path(cwd)
84
+ return Path.cwd()
85
+
86
+
87
+ def hook_answer(args, raw: str) -> dict | None:
88
+ from .cli import _client
89
+ from .core import Core
90
+ from .onboarding import read_profile
91
+ from .push import hook_response
92
+
93
+ payload = json.loads(raw) if raw.strip() else {}
94
+ if not isinstance(payload, dict):
95
+ return None
96
+ if args.host == 'antigravity':
97
+ return antigravity_answer(args, payload)
98
+ event = payload.get('hook_event_name')
99
+ if not isinstance(event, str):
100
+ return None
101
+ profile = read_profile(_hook_project(args, payload).resolve())
102
+ if profile is None:
103
+ return None
104
+ state = Path(profile['state_dir'])
105
+ if not state.is_dir():
106
+ return None
107
+ answer = _relayed_hook(state, Path(profile['client_file']), event, payload)
108
+ if answer is _NO_RELAY:
109
+ # No relay: this hook does the inbox work on its own database handle.
110
+ core = Core(state, _NoTransport(), recover_sends=False)
111
+ client_id = _client(core, Path(profile['client_file']), profile['client_id'])
112
+ _maybe_collect(core, state, profile['mode'] == 'fake', getattr(args, 'collect_interval', 0))
113
+ answer = hook_response(core, client_id, event, payload)
114
+ if answer is not None and args.host == 'claude':
115
+ from .push import with_shell_fallback
116
+ for container, key in ((answer, 'reason'), (answer.get('hookSpecificOutput'), 'additionalContext')):
117
+ if isinstance(container, dict) and isinstance(container.get(key), str):
118
+ container[key] = with_shell_fallback(container[key])
119
+ return answer
120
+
121
+
122
+ _NO_RELAY = object()
123
+
124
+
125
+ # Antigravity (the agy CLI and the desktop app) runs plugin hooks with its own
126
+ # event names and output. Each event is answered like the Claude Code event
127
+ # with the same job: PreInvocation runs before every model call, so it
128
+ # announces only new deliveries, like PostToolUse.
129
+ ANTIGRAVITY_EVENTS = {'SessionStart': 'SessionStart', 'PreInvocation': 'PostToolUse', 'Stop': 'Stop'}
130
+ ANTIGRAVITY_ASKS = 'antigravity-asks'
131
+ _SESSION_CHARS = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_')
132
+
133
+
134
+ def _session_id(value) -> str | None:
135
+ if isinstance(value, str) and 0 < len(value) <= 128 and set(value) <= _SESSION_CHARS:
136
+ return value
137
+ return None
138
+
139
+
140
+ def waiter_command(project: Path, session: str) -> str:
141
+ """The exact background command that keeps an idle Antigravity agent listening."""
142
+ import shlex
143
+ parts = [str(compat.own_aot()), 'wake', '--host', 'antigravity', '--project-dir', str(project),
144
+ '--session', session]
145
+ return ' '.join(shlex.quote(part) for part in parts)
146
+
147
+
148
+ def waiter_instruction(project: Path, session: str) -> str:
149
+ return ('[Agents over Telegram] To hear new Telegram messages while this agent is idle, start this '
150
+ 'command now as a background task: use run_command with WaitMsBeforeAsync 500, do not wait for it, '
151
+ 'and do not change it: ' + waiter_command(project, session) + ' . It prints a notice and exits '
152
+ 'when a message arrives. Then continue with your work, or end your turn if there is nothing else to do.')
153
+
154
+
155
+ def _waiter_running(state: Path, key: str) -> bool:
156
+ """True when a waiter for this client and session holds its lock."""
157
+ path = state / 'wake-locks' / f'{key}.lock'
158
+ try:
159
+ fd = os.open(path, os.O_RDWR | compat.O_CLOEXEC)
160
+ except OSError:
161
+ return False
162
+ try:
163
+ compat.lock(fd)
164
+ except OSError:
165
+ return True
166
+ finally:
167
+ os.close(fd)
168
+ return False
169
+
170
+
171
+ def _prompt_hash(payload: dict) -> str:
172
+ import hashlib
173
+ prompt = payload.get('lastUserInput')
174
+ return hashlib.sha256(prompt.encode('utf-8', 'replace')).hexdigest() if isinstance(prompt, str) else ''
175
+
176
+
177
+ def _record_ask(state: Path, key: str, payload: dict) -> None:
178
+ asks = state / ANTIGRAVITY_ASKS
179
+ asks.mkdir(mode=0o700, exist_ok=True)
180
+ _write_owner(asks / key, json.dumps({'at': time.time(), 'prompt': _prompt_hash(payload)}))
181
+
182
+
183
+ def _may_ask(state: Path, key: str, payload: dict) -> bool:
184
+ """Whether a Stop hook may ask again for the waiter, without looping.
185
+
186
+ Antigravity 1.5.9 never sets continuationActive, so a Stop hook that keeps
187
+ answering "continue" runs the agent forever. Ask once, then again only
188
+ after a new user prompt or after a waiter started (and has since ended).
189
+ """
190
+ path = state / ANTIGRAVITY_ASKS / key
191
+ prompt = _prompt_hash(payload)
192
+ try:
193
+ previous = json.loads(path.read_text(encoding='utf-8'))
194
+ asked, asked_prompt = float(previous['at']), previous['prompt']
195
+ except (OSError, ValueError, TypeError, KeyError):
196
+ asked, asked_prompt = None, None
197
+ if asked is not None and asked_prompt == prompt:
198
+ try:
199
+ started = (state / 'wake-locks' / f'{key}.owner').stat().st_mtime
200
+ except OSError:
201
+ started = 0
202
+ if started <= asked:
203
+ return False
204
+ return True
205
+
206
+
207
+ def antigravity_answer(args, payload: dict) -> dict | None:
208
+ """Answer one Antigravity hook event in its own output format."""
209
+ from .onboarding import read_profile
210
+ event = payload.get('hookEventName')
211
+ mapped = ANTIGRAVITY_EVENTS.get(event) if isinstance(event, str) else None
212
+ if mapped is None:
213
+ return None
214
+ project = _hook_project(args, payload).resolve()
215
+ profile = read_profile(project)
216
+ if profile is None:
217
+ return None
218
+ state = Path(profile['state_dir'])
219
+ if not state.is_dir():
220
+ return None
221
+ answer = _inbox_answer(args, state, profile, mapped, {'hook_event_name': mapped})
222
+ notice = None
223
+ if isinstance(answer, dict):
224
+ notice = answer.get('reason') or (answer.get('hookSpecificOutput') or {}).get('additionalContext')
225
+ notices = [notice] if isinstance(notice, str) and notice else []
226
+ session = _session_id(payload.get('conversationId'))
227
+ key = wake_key(profile['client_id'], session) if session else None
228
+ if key and event in ('SessionStart', 'Stop') and not _waiter_running(state, key):
229
+ # SessionStart always names the waiter; Stop only within the loop guard.
230
+ if event == 'SessionStart' or _may_ask(state, key, payload):
231
+ _record_ask(state, key, payload)
232
+ notices.append(waiter_instruction(project, session))
233
+ if not notices:
234
+ return None
235
+ text = '\n'.join(notices)
236
+ if event == 'Stop':
237
+ return {'decision': 'continue', 'reason': text}
238
+ return {'injectSteps': [{'systemMessage': {'systemMessage': text}}]}
239
+
240
+
241
+ def _inbox_answer(args, state: Path, profile: dict, event: str, payload: dict):
242
+ """The Claude Code shaped hook answer from the relay, or from this process."""
243
+ from .cli import _client
244
+ from .core import Core
245
+ from .push import hook_response
246
+ answer = _relayed_hook(state, Path(profile['client_file']), event, payload)
247
+ if answer is _NO_RELAY:
248
+ core = Core(state, _NoTransport(), recover_sends=False)
249
+ client_id = _client(core, Path(profile['client_file']), profile['client_id'])
250
+ _maybe_collect(core, state, profile['mode'] == 'fake', getattr(args, 'collect_interval', 0))
251
+ answer = hook_response(core, client_id, event, payload)
252
+ return answer
253
+ # The hook input fields hook_response reads; the rest (prompts, tool output)
254
+ # never leaves this process.
255
+ _HOOK_FIELDS = ('tool_name', 'stop_hook_active')
256
+
257
+
258
+ def _relayed_hook(state: Path, client_file: Path, event: str, payload: dict):
259
+ """The hook's answer from the always-on collector, or _NO_RELAY when none took it."""
260
+ from .credentials import read_private_json
261
+ from .relay_api import Lost, Node, Unavailable
262
+ try:
263
+ secret = read_private_json(client_file)['client_secret']
264
+ return Node(state, secret).hook(event, {k: payload[k] for k in _HOOK_FIELDS if k in payload})
265
+ except Unavailable:
266
+ return _NO_RELAY
267
+ except Lost:
268
+ # The relay may already have recorded this notice as given; doing it
269
+ # again here would find nothing. The next prompt names pending work.
270
+ return None
271
+
272
+
273
+ def _maybe_collect(core, state: Path, fake: bool, interval) -> None:
274
+ """Collect once if nobody tried recently. Hosts without a background watcher
275
+ (Codex) use this so a busy turn still sees new messages. The shared
276
+ collector lock keeps this from competing with a running listener."""
277
+ if not isinstance(interval, (int, float)) or isinstance(interval, bool) or interval <= 0:
278
+ return
279
+ with core._db() as db:
280
+ row = db.execute('SELECT last_attempt FROM account WHERE singleton=1').fetchone()
281
+ if row is None or (row['last_attempt'] is not None and core.clock() - row['last_attempt'] < interval):
282
+ return
283
+ from .cli import LazyTransport, _mode
284
+ try:
285
+ _mode(state, fake)
286
+ core.transport = LazyTransport(state, fake)
287
+ core.collect(timeout=0)
288
+ except Exception:
289
+ # Intake errors are recorded by the core; the hook still answers.
290
+ pass
291
+ finally:
292
+ core.transport = _NoTransport()
293
+
294
+
295
+ def run_hook(args) -> dict | None:
296
+ """Answer one hook event. Any failure produces no output and exit status 0,
297
+ so a broken or unconfigured project never blocks the host."""
298
+ try:
299
+ raw = sys.stdin.read(MAX_HOOK_INPUT + 1)
300
+ if len(raw) > MAX_HOOK_INPUT:
301
+ return None
302
+ return hook_answer(args, raw)
303
+ except Exception:
304
+ return None
305
+
306
+
307
+ # Exit status 2 from an ``asyncRewake`` hook wakes Claude Code, even an idle session.
308
+ WAKE_EXIT = 2
309
+ # Sent when the waiter reaches its time limit with nothing new, so the turn
310
+ # that follows ends at once and its Stop hook starts a fresh waiter.
311
+ REFRESH_NOTICE = ('[Agents over Telegram] No new Telegram messages. The background listener reached its '
312
+ 'time limit and starts again when this turn ends. Nothing to do: end this turn now, '
313
+ 'without tool calls and with at most one short line.')
314
+ # Claude Code stops the hook at its timeout (86400 seconds in claude/hooks.json).
315
+ # End a little earlier so the waiter exits on its own terms.
316
+ WAKE_DURATION = 82800
317
+ ANTIGRAVITY_RESTART = ('After you handle them, start the same background command again so this agent keeps '
318
+ 'listening: {command}')
319
+
320
+
321
+ def _write_owner(path: Path, token: str) -> None:
322
+ tmp = path.with_name(f'{path.name}.{os.getpid()}.tmp')
323
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | compat.O_CLOEXEC, 0o600)
324
+ with os.fdopen(fd, 'w') as stream:
325
+ stream.write(token)
326
+ os.replace(tmp, path)
327
+
328
+
329
+ def _read_owner(path: Path) -> str | None:
330
+ try:
331
+ return path.read_text(encoding='utf-8')[:64]
332
+ except OSError:
333
+ return None
334
+
335
+
336
+ class _Woken(Exception):
337
+ pass
338
+
339
+
340
+ WAKE_LOG = 'wake.log'
341
+ WAKE_LOG_LIMIT = 256 * 1024
342
+
343
+
344
+ def _wake_log(state: Path, key: str, event: str, reason: str) -> None:
345
+ """Append one line about a waiter's start or exit; never fails the caller.
346
+
347
+ A waiter that stops without waking its session is silent, so this private
348
+ log is the only record of why a session stopped hearing Telegram. It holds
349
+ no message text. Past WAKE_LOG_LIMIT bytes the old log moves to wake.log.1.
350
+ """
351
+ try:
352
+ path = state / WAKE_LOG
353
+ try:
354
+ if path.stat().st_size > WAKE_LOG_LIMIT:
355
+ os.replace(path, path.with_name(WAKE_LOG + '.1'))
356
+ except FileNotFoundError:
357
+ pass
358
+ line = json.dumps({'at': time.strftime('%Y-%m-%dT%H:%M:%S%z'), 'pid': os.getpid(),
359
+ 'session': key, 'event': event, 'reason': reason}) + '\n'
360
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND | compat.O_CLOEXEC, 0o600)
361
+ with os.fdopen(fd, 'a', encoding='utf-8') as stream:
362
+ stream.write(line)
363
+ except Exception:
364
+ pass
365
+
366
+
367
+ def _log_signal_exits(state: Path, key: str) -> None:
368
+ """Log an exit line when the host stops the waiter with a signal.
369
+
370
+ The handler then lets the signal end the process as before. SIGKILL
371
+ cannot be caught: such a waiter leaves a start line with no exit line.
372
+ """
373
+ import signal
374
+
375
+ def handler(number, frame):
376
+ _wake_log(state, key, 'exit', f'signal:{signal.Signals(number).name}')
377
+ signal.signal(number, signal.SIG_DFL)
378
+ os.kill(os.getpid(), number)
379
+
380
+ for name in ('SIGTERM', 'SIGHUP', 'SIGINT'):
381
+ number = getattr(signal, name, None)
382
+ if number is None:
383
+ continue
384
+ try:
385
+ signal.signal(number, handler)
386
+ except (ValueError, OSError):
387
+ # Not the main thread, or the platform refuses: log nothing.
388
+ pass
389
+
390
+
391
+ def _alive(pid: int) -> bool:
392
+ return compat.pid_alive(pid)
393
+
394
+
395
+ def run_wake(args) -> int:
396
+ """Wait in the background for new deliveries, then wake the host session.
397
+
398
+ Claude Code runs this as an ``asyncRewake`` hook. Plugin monitors do not
399
+ start in every Claude Code session (for example in the desktop app), but
400
+ this hook does. Exit status 2 wakes the session and stderr becomes the
401
+ notice; every other outcome exits 0 without output. One waiter runs per
402
+ client and host session; a newer start takes over from the running one.
403
+ """
404
+ log = []
405
+ try:
406
+ return _wake(args, log)
407
+ except Exception as error:
408
+ if log:
409
+ _wake_log(*log, 'exit', f'error:{type(error).__name__}')
410
+ return 0
411
+
412
+
413
+ def _keep_alive(core, client_id, remote=None) -> bool:
414
+ """Whether the owner turned on the daily keep-alive wake for this client."""
415
+ from .relay_api import Unavailable
416
+ try:
417
+ if remote is not None:
418
+ try:
419
+ return bool((remote.status().get('routing') or {}).get('keep_alive'))
420
+ except Unavailable:
421
+ pass
422
+ return bool((core.connection_status(client_id).get('routing') or {}).get('keep_alive'))
423
+ except Exception:
424
+ return False
425
+
426
+
427
+ def _start_collector(state: Path) -> None:
428
+ """Start aot serve on demand when this machine has no service; never fails the caller."""
429
+ from . import serve
430
+ try:
431
+ serve.start_on_demand(state)
432
+ except Exception as error:
433
+ # One line in serve.log, so a start that keeps failing (a sandbox
434
+ # around the agent, say) can be found.
435
+ try:
436
+ with open(Path(state) / serve.LOG, 'a', encoding='utf-8') as log:
437
+ log.write(f'aot: could not start aot serve on demand ({type(error).__name__}: {error})\n')
438
+ except OSError:
439
+ pass
440
+
441
+
442
+ def wake_key(client_id: str, session: str | None) -> str:
443
+ """The name of a session's wake lock and owner files in wake-locks."""
444
+ import hashlib
445
+ return hashlib.sha256(f'{client_id}\0{session or ""}'.encode()).hexdigest()[:24]
446
+
447
+
448
+ def _wake(args, log=None) -> int:
449
+ from .cli import LazyTransport, _client, _mode
450
+ from .core import Core
451
+ from .onboarding import read_profile
452
+ from .push import watch
453
+
454
+ project = _hook_project(args, {}).resolve()
455
+ profile = read_profile(project)
456
+ if profile is None:
457
+ return 0
458
+ antigravity = args.host == 'antigravity'
459
+ if antigravity:
460
+ if not _session_id(args.session):
461
+ return 0
462
+ # This waiter is the agent's own background command, with no launcher
463
+ # above it: it follows runtime updates itself (see the end).
464
+ os.environ['AOT_FOLLOW_RUNTIME'] = '1'
465
+ duration = args.duration
466
+ if duration is None:
467
+ # Claude Code stops the hook at its timeout; an Antigravity background
468
+ # command has none, so it waits until a message or its host is gone.
469
+ duration = 0 if antigravity else WAKE_DURATION
470
+ state = Path(profile['state_dir'])
471
+ if not state.is_dir():
472
+ return 0
473
+ fake = profile['mode'] == 'fake'
474
+ _mode(state, fake)
475
+ from .credentials import read_private_json
476
+ from .relay_api import LazyCore, Node
477
+ client_file = Path(profile['client_file'])
478
+ client_id = profile['client_id']
479
+
480
+ def local_core():
481
+ # Only when no relay answers: open the database and check the client
482
+ # file against it, as before the relay.
483
+ opened = Core(state, LazyTransport(state, fake), recover_sends=False)
484
+ _client(opened, client_file, client_id)
485
+ return opened
486
+ core = LazyCore(local_core)
487
+ remote = Node(state, read_private_json(client_file)['client_secret'])
488
+ _start_collector(state)
489
+ locks = state / 'wake-locks'
490
+ locks.mkdir(mode=0o700, exist_ok=True)
491
+ key = wake_key(client_id, args.session)
492
+ if log is not None:
493
+ log[:] = [state, key]
494
+ _wake_log(state, key, 'start', 'turn_end')
495
+ _log_signal_exits(state, key)
496
+ # The newest waiter for a session takes over, so the time limit counts
497
+ # from the latest turn end, not from the first waiter. It records itself
498
+ # as the owner; the running waiter sees that and exits, freeing the lock.
499
+ owner = locks / f'{key}.owner'
500
+ token = f'{os.getpid()}-{time.time_ns()}'
501
+ _write_owner(owner, token)
502
+ fd = os.open(locks / f'{key}.lock', os.O_RDWR | os.O_CREAT | compat.O_CLOEXEC, 0o600)
503
+ parent = os.getppid()
504
+ host = getattr(args, 'host_pid', None)
505
+
506
+ moved = []
507
+ stopped = []
508
+
509
+ def stop(reason):
510
+ if not stopped:
511
+ stopped.append(reason)
512
+ return False
513
+
514
+ def keep_running():
515
+ # Re-parenting or a missing host process means the host is gone,
516
+ # so stop instead of polling forever. A newer owner replaces this waiter.
517
+ if os.getppid() != parent:
518
+ return stop('parent_changed')
519
+ if host and not _alive(host):
520
+ return stop('host_gone')
521
+ if _read_owner(owner) != token:
522
+ return stop('replaced')
523
+ # An updated project runtime takes over: the launcher restarts this
524
+ # waiter on it, so collection never runs older code than the pointer.
525
+ if runtime_moved(project):
526
+ moved.append(True)
527
+ return stop('runtime_moved')
528
+ return True
529
+
530
+ def done(code, reason=None):
531
+ _wake_log(state, key, 'exit', reason or (stopped[0] if stopped else 'unknown'))
532
+ return code
533
+
534
+ # The running waiter notices the new owner only at the end of its cycle,
535
+ # which can take longer than a Telegram long poll. Wait without a fixed
536
+ # limit, so the session is never left without a waiter.
537
+ while True:
538
+ if not keep_running():
539
+ os.close(fd)
540
+ return done(0)
541
+ try:
542
+ compat.lock(fd)
543
+ break
544
+ except OSError:
545
+ time.sleep(0.2)
546
+ notices = []
547
+
548
+ def emit(event):
549
+ if event.get('type') == 'telegram_messages':
550
+ notices.append(event['notice'])
551
+ raise _Woken()
552
+
553
+ try:
554
+ result = watch(core, client_id, emit, collect=True, duration=duration, keep_running=keep_running,
555
+ remote=remote)
556
+ except _Woken:
557
+ if antigravity:
558
+ # Antigravity wakes the agent when this background command ends
559
+ # and shows it the output, so the notice goes to stdout.
560
+ sys.stdout.write(notices[0] + ' ' + ANTIGRAVITY_RESTART.format(command=waiter_command(project, args.session))
561
+ + '\n')
562
+ sys.stdout.flush()
563
+ return done(0, 'woken')
564
+ from .push import with_shell_fallback
565
+ sys.stderr.write(with_shell_fallback(notices[0]) + '\n')
566
+ sys.stderr.flush()
567
+ return done(WAKE_EXIT, 'woken')
568
+ if moved and antigravity:
569
+ # No launcher sits above this waiter: carry on in the new runtime, so
570
+ # the agent keeps listening without being woken for nothing.
571
+ done(0, 'runtime_moved')
572
+ new = read_runtime_pointer(project)
573
+ if new is not None:
574
+ sys.stdout.flush()
575
+ os.execv(str(new), [str(new)] + sys.argv[1:])
576
+ return 0
577
+ if moved:
578
+ return done(RUNTIME_MOVED_EXIT)
579
+ # A new waiter starts only when a turn ends. Without this, a session idle
580
+ # for longer than the time limit would stop hearing Telegram for good.
581
+ # With keep-alive on, the session's current waiter wakes it once when time
582
+ # is up, so the turn end starts a fresh waiter.
583
+ if result.get('reason') == 'duration_elapsed' and _keep_alive(core, client_id, remote) and keep_running():
584
+ sys.stderr.write(REFRESH_NOTICE + '\n')
585
+ sys.stderr.flush()
586
+ return done(WAKE_EXIT, 'keep_alive_refresh')
587
+ # The last check may itself have seen a moved runtime.
588
+ if moved:
589
+ return done(RUNTIME_MOVED_EXIT)
590
+ return done(0, stopped[0] if stopped else f"watch_ended:{result.get('reason') or 'unknown'}")