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,206 @@
1
+ """Whether Codex still trusts AOT's plugin hooks.
2
+
3
+ Codex runs a plugin hook only while two hashes match what the human approved
4
+ with ``/hooks``: the hook declaration (``trusted_hash``) and a SHA-256 of the
5
+ whole plugin folder (``trusted_content_hash``). Every AOT release changes the
6
+ plugin folder, so after each Codex plugin update Codex stops running the hooks
7
+ until the human approves them again. Codex does not say so to the agent.
8
+
9
+ This module recomputes the folder hash exactly as Codex does
10
+ (``codex-rs/hooks/src/engine/plugin_fingerprint.rs``) and compares it with the
11
+ approval stored in Codex's ``config.toml``. It only reads files.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import os
17
+ import stat
18
+ import struct
19
+ import tomllib
20
+ from pathlib import Path
21
+
22
+ PLUGIN_ID = 'agents-over-telegram@agents-over-telegram'
23
+ HOOKS_FILE = 'codex/hooks.json'
24
+ EVENTS = ('session_start', 'user_prompt_submit', 'post_tool_use', 'stop')
25
+ _SKIPPED_NAMES = ('__pycache__', '.venv')
26
+ _SKIPPED_SUFFIXES = ('.pyc', '.egg-info')
27
+
28
+ _HINT_START = ("Codex is not running AOT's plugin hooks: they changed with the last plugin update "
29
+ "and need approval again. ")
30
+ _HINT_END = " Until then, Telegram messages reach this chat only when it is idle."
31
+ _HOW_TO_APPROVE = {
32
+ 'desktop': "Ask the user to approve them in the Codex desktop app's hook review.",
33
+ 'cli': "Ask the user to run /hooks in the Codex CLI in this project and approve them.",
34
+ None: ("Ask the user to approve them in Codex: in the desktop app's hook review, or with "
35
+ "/hooks in the Codex CLI."),
36
+ }
37
+
38
+
39
+ def approve_hint(host: str | None = None) -> str:
40
+ """The fixed warning for the agent, with approval steps for the Codex host that runs it."""
41
+ return _HINT_START + _HOW_TO_APPROVE.get(host, _HOW_TO_APPROVE[None]) + _HINT_END
42
+
43
+
44
+ APPROVE_HINT = approve_hint()
45
+
46
+
47
+ def plugin_content_hash(root: Path) -> str:
48
+ """The SHA-256 Codex stores as ``trusted_content_hash`` for a plugin folder."""
49
+ root = Path(root)
50
+ if not stat.S_ISDIR(os.lstat(root).st_mode):
51
+ raise OSError('plugin root is not a directory')
52
+ digest = hashlib.sha256(b'codex-plugin-bundle-v1')
53
+ pending = [root]
54
+ while pending:
55
+ path = pending.pop()
56
+ relative = path.relative_to(root)
57
+ name = relative.name
58
+ if name and (name in _SKIPPED_NAMES or name.endswith(_SKIPPED_SUFFIXES)):
59
+ continue
60
+ encoded = os.fsencode(str(relative)) if name else b''
61
+ digest.update(struct.pack('<Q', len(encoded)))
62
+ digest.update(encoded)
63
+ info = os.lstat(path)
64
+ if stat.S_ISDIR(info.st_mode):
65
+ digest.update(b'directory')
66
+ entries = sorted(os.listdir(path), key=os.fsencode)
67
+ pending.extend(path / entry for entry in reversed(entries))
68
+ elif stat.S_ISREG(info.st_mode):
69
+ digest.update(b'file')
70
+ digest.update(struct.pack('<Q', info.st_size))
71
+ with open(path, 'rb') as handle:
72
+ read = 0
73
+ while chunk := handle.read(65536):
74
+ read += len(chunk)
75
+ digest.update(chunk)
76
+ if read != info.st_size:
77
+ raise OSError('plugin file changed while fingerprinting')
78
+ else:
79
+ raise OSError('unsupported plugin entry type')
80
+ return 'sha256:' + digest.hexdigest()
81
+
82
+
83
+ def codex_home() -> Path:
84
+ value = os.environ.get('CODEX_HOME')
85
+ return Path(value) if value else Path.home() / '.codex'
86
+
87
+
88
+ def _version_key(path: Path):
89
+ return tuple(int(part) if part.isdigit() else 0 for part in path.name.split('.'))
90
+
91
+
92
+ def installed_plugin_root(home: Path) -> Path | None:
93
+ """The installed AOT plugin folder in Codex's cache, newest version first."""
94
+ marketplace, plugin = PLUGIN_ID.split('@')[1], PLUGIN_ID.split('@')[0]
95
+ base = home / 'plugins' / 'cache' / marketplace / plugin
96
+ try:
97
+ versions = [entry for entry in base.iterdir()
98
+ if entry.is_dir() and (entry / '.codex-plugin' / 'plugin.json').is_file()]
99
+ except OSError:
100
+ return None
101
+ return max(versions, key=_version_key) if versions else None
102
+
103
+
104
+ def status(home: Path | None = None) -> dict:
105
+ """``approved``, ``needs_approval``, ``not_installed`` or ``unknown``, with a reason."""
106
+ home = Path(home) if home is not None else codex_home()
107
+ root = installed_plugin_root(home)
108
+ if root is None:
109
+ return {'status': 'not_installed'}
110
+ result = {'plugin_version': root.name}
111
+ try:
112
+ config = tomllib.loads((home / 'config.toml').read_text(encoding='utf-8'))
113
+ except (OSError, ValueError):
114
+ return {**result, 'status': 'unknown', 'reason': 'codex_config_unreadable'}
115
+ if not config.get('plugins', {}).get(PLUGIN_ID, {}).get('enabled', False):
116
+ return {**result, 'status': 'not_installed', 'reason': 'plugin_disabled'}
117
+ try:
118
+ current = plugin_content_hash(root)
119
+ except OSError:
120
+ return {**result, 'status': 'unknown', 'reason': 'plugin_unreadable'}
121
+ states = config.get('hooks', {}).get('state', {})
122
+ for event in EVENTS:
123
+ entry = states.get(f'{PLUGIN_ID}:{HOOKS_FILE}:{event}:0:0', {})
124
+ if not entry.get('trusted_hash'):
125
+ return {**result, 'status': 'needs_approval', 'reason': 'hook_never_approved'}
126
+ trusted = entry.get('trusted_content_hash')
127
+ if trusted is None:
128
+ # An older approval has no content hash. Codex compares the folder
129
+ # with a baseline file it pins on first use; with no file yet, it
130
+ # pins the current folder, so the hooks still run.
131
+ trusted = _legacy_baseline(home)
132
+ if trusted is not None and trusted != current:
133
+ return {**result, 'status': 'needs_approval', 'reason': 'plugin_changed_since_approval'}
134
+ return {**result, 'status': 'approved'}
135
+
136
+
137
+ def _legacy_baseline(home: Path) -> str | None:
138
+ """The legacy approval baseline Codex keeps in ``.hook-trust`` (``plugin_trust.rs``)."""
139
+ digest = hashlib.sha256()
140
+ for part in (os.fsencode(str(home / 'config.toml')), PLUGIN_ID.encode()):
141
+ digest.update(struct.pack('<Q', len(part)))
142
+ digest.update(part)
143
+ try:
144
+ return (home / '.hook-trust' / digest.hexdigest()).read_text(encoding='utf-8').strip() or None
145
+ except OSError:
146
+ return None
147
+
148
+
149
+ def codex_project_uses(client_file: Path, project: Path | None = None) -> bool:
150
+ """True when this project's Codex configuration runs AOT with this client file."""
151
+ start = Path(project) if project is not None else Path.cwd()
152
+ wanted = str(Path(client_file).absolute())
153
+ # Codex starts the server in the session folder, which may be below the project.
154
+ for folder in (start, *list(start.parents)[:4]):
155
+ try:
156
+ config = tomllib.loads((folder / '.codex' / 'config.toml').read_text(encoding='utf-8'))
157
+ except (OSError, ValueError):
158
+ continue
159
+ args = config.get('mcp_servers', {}).get('telegram', {}).get('args', [])
160
+ if isinstance(args, list) and wanted in [str(arg) for arg in args]:
161
+ return True
162
+ return False
163
+
164
+
165
+ def _process(pid: int) -> tuple[int, str] | None:
166
+ """(parent pid, executable path) of a process, read with ps; None when unknown."""
167
+ import subprocess
168
+ try:
169
+ out = subprocess.run(['ps', '-o', 'ppid=,comm=', '-p', str(pid)], capture_output=True,
170
+ text=True, timeout=2, check=False).stdout.strip()
171
+ parent, _, command = out.partition(' ')
172
+ return int(parent), command.strip()
173
+ except (OSError, ValueError, subprocess.SubprocessError):
174
+ return None
175
+
176
+
177
+ def codex_host(pid: int | None = None, process=_process) -> str | None:
178
+ """'desktop' or 'cli' for the Codex that started this process.
179
+
180
+ 'none' means the walk reached the top without any Codex process, so this
181
+ server does not run under Codex (for example under Claude Code in a project
182
+ set up for both). None means the processes could not be read.
183
+
184
+ Walks the parent processes. The desktop app runs its bundled Codex inside an
185
+ application bundle (for example ChatGPT.app or Codex.app); the CLI runs a
186
+ plain ``codex`` executable.
187
+ """
188
+ current = os.getppid() if pid is None else pid
189
+ saw_codex = False
190
+ for _ in range(12):
191
+ if current <= 1:
192
+ return 'cli' if saw_codex else 'none'
193
+ found = process(current)
194
+ if found is None:
195
+ break
196
+ parent, command = found
197
+ name = os.path.basename(command)
198
+ if name.lower().startswith('codex'):
199
+ saw_codex = True
200
+ if '.app/Contents/' in command and any(
201
+ bundle in command for bundle in ('/ChatGPT.app/', '/Codex.app/')):
202
+ return 'desktop'
203
+ elif command.endswith(('/ChatGPT.app/Contents/MacOS/ChatGPT', '/Codex.app/Contents/MacOS/Codex')):
204
+ return 'desktop'
205
+ current = parent
206
+ return 'cli' if saw_codex else None
@@ -0,0 +1,207 @@
1
+ """What differs between POSIX (Linux, macOS) and Windows, in one place.
2
+
3
+ POSIX keeps private state private with file modes and owners, and the core
4
+ checks both before trusting a file. Windows has neither: ``st_uid`` is 0 and
5
+ mode bits do not describe who can read a file. There the state directory
6
+ lives in the user's profile (%LOCALAPPDATA%), which other users cannot read
7
+ by default, and the checks that rely on modes and owners are skipped; the
8
+ checks that do not (regular file, single link, no symlink) still apply.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ from pathlib import Path
14
+
15
+ WINDOWS = os.name == 'nt'
16
+
17
+ # Flags Windows does not have are no-ops there.
18
+ O_NOFOLLOW = getattr(os, 'O_NOFOLLOW', 0)
19
+ O_CLOEXEC = getattr(os, 'O_CLOEXEC', 0)
20
+ O_NONBLOCK = getattr(os, 'O_NONBLOCK', 0)
21
+ # Windows opens files in text mode unless told otherwise.
22
+ O_BINARY = getattr(os, 'O_BINARY', 0)
23
+
24
+
25
+ def getuid():
26
+ """This user's id, or None on Windows."""
27
+ return os.getuid() if hasattr(os, 'getuid') else None
28
+
29
+
30
+ def owned(info, *, root=False):
31
+ """True when a stat result belongs to this user (or to root, when allowed); always on Windows."""
32
+ if WINDOWS:
33
+ return True
34
+ return info.st_uid == os.getuid() or (root and info.st_uid == 0)
35
+
36
+
37
+ def private(info, mask=0o077):
38
+ """True when no mode bit in ``mask`` is set; always on Windows, where modes say nothing."""
39
+ return WINDOWS or not info.st_mode & mask
40
+
41
+
42
+ def mode_is(info, mode):
43
+ """True when the permission bits are exactly ``mode``; always on Windows."""
44
+ import stat
45
+ return WINDOWS or stat.S_IMODE(info.st_mode) == mode
46
+
47
+
48
+ # msvcrt.locking reports a byte another process holds as EACCES, or EDEADLOCK
49
+ # after its internal retries.
50
+ _LOCK_CONTENTION = {13, 36}
51
+
52
+
53
+ def lock(fd, *, blocking=False):
54
+ """Take an exclusive lock on an open file; BlockingIOError when another process holds it.
55
+
56
+ POSIX uses flock. Windows locks the file's first byte with msvcrt, which
57
+ works past the end of an empty file and is released when the file closes.
58
+ """
59
+ fd = fd.fileno() if hasattr(fd, 'fileno') else fd
60
+ if WINDOWS:
61
+ import msvcrt
62
+ os.lseek(fd, 0, os.SEEK_SET)
63
+ while True:
64
+ try:
65
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
66
+ return
67
+ except OSError as error:
68
+ # Only contention means "held by someone else"; a bad file
69
+ # descriptor or a broken handle is a real error.
70
+ if error.errno not in _LOCK_CONTENTION:
71
+ raise
72
+ if not blocking:
73
+ raise BlockingIOError('locked') from None
74
+ import time
75
+ time.sleep(0.1)
76
+ import fcntl
77
+ fcntl.flock(fd, fcntl.LOCK_EX if blocking else fcntl.LOCK_EX | fcntl.LOCK_NB)
78
+
79
+
80
+ def unlock(fd):
81
+ fd = fd.fileno() if hasattr(fd, 'fileno') else fd
82
+ if WINDOWS:
83
+ import msvcrt
84
+ os.lseek(fd, 0, os.SEEK_SET)
85
+ try:
86
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
87
+ except OSError:
88
+ pass
89
+ return
90
+ import fcntl
91
+ fcntl.flock(fd, fcntl.LOCK_UN)
92
+
93
+
94
+ def venv_scripts(venv):
95
+ """A virtual environment's executables directory: bin on POSIX, Scripts on Windows."""
96
+ return Path(venv) / ('Scripts' if WINDOWS else 'bin')
97
+
98
+
99
+ def executable_name(name):
100
+ """``aot`` becomes ``aot.exe`` on Windows."""
101
+ return name + '.exe' if WINDOWS else name
102
+
103
+
104
+ def pid_alive(pid):
105
+ """True while a process with this id exists.
106
+
107
+ POSIX asks with signal 0. On Windows os.kill(pid, 0) terminates the
108
+ process instead, so ask the kernel for its exit code.
109
+ """
110
+ if WINDOWS:
111
+ import ctypes
112
+ from ctypes import wintypes
113
+ kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
114
+ # Declared, so 64-bit handles are passed whole.
115
+ kernel32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)
116
+ kernel32.OpenProcess.restype = wintypes.HANDLE
117
+ kernel32.GetExitCodeProcess.argtypes = (wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD))
118
+ kernel32.GetExitCodeProcess.restype = wintypes.BOOL
119
+ kernel32.CloseHandle.argtypes = (wintypes.HANDLE,)
120
+ kernel32.CloseHandle.restype = wintypes.BOOL
121
+ handle = kernel32.OpenProcess(0x1000, False, int(pid)) # PROCESS_QUERY_LIMITED_INFORMATION
122
+ if not handle:
123
+ # Access denied still means it exists; anything else means it is gone.
124
+ return ctypes.get_last_error() == 5
125
+ try:
126
+ code = wintypes.DWORD()
127
+ if not kernel32.GetExitCodeProcess(handle, ctypes.byref(code)):
128
+ return True
129
+ return code.value == 259 # STILL_ACTIVE
130
+ finally:
131
+ kernel32.CloseHandle(handle)
132
+ try:
133
+ os.kill(pid, 0)
134
+ except ProcessLookupError:
135
+ return False
136
+ except OSError:
137
+ return True
138
+ return True
139
+
140
+
141
+ def refuse_link(path):
142
+ """Raise OSError when ``path`` is a symlink, where opening cannot refuse one itself.
143
+
144
+ POSIX opens with O_NOFOLLOW. Windows has no such flag, so check first;
145
+ the window between the check and the open needs write access to the
146
+ user's own private directory.
147
+ """
148
+ if not WINDOWS:
149
+ return
150
+ info = os.lstat(path)
151
+ # Symlinks, junctions and every other reparse point redirect the open.
152
+ import stat
153
+ if stat.S_ISLNK(info.st_mode) or getattr(info, 'st_file_attributes', 0) & 0x400: # FILE_ATTRIBUTE_REPARSE_POINT
154
+ raise OSError('link or reparse point refused')
155
+
156
+
157
+ def own_aot():
158
+ """This runtime's aot executable: next to its Python, aot.exe on Windows."""
159
+ import sys
160
+ return Path(sys.executable).absolute().parent / executable_name('aot')
161
+
162
+
163
+ _SID = None
164
+
165
+
166
+ def restrict_directory(path, run=None):
167
+ """On Windows, give a private folder an ACL of its own: full control for this
168
+ user and SYSTEM, nothing inherited. True when applied, False when it failed.
169
+
170
+ POSIX folders are private by mode (0700) instead, so this does nothing there.
171
+ Windows folders inherit their parent's ACL, which outside the user's profile
172
+ (a state directory given with --state-dir, say) can let other users read
173
+ the bot token.
174
+ """
175
+ if not WINDOWS:
176
+ return True
177
+ import subprocess
178
+ global _SID
179
+ if run is None:
180
+ # The SID never changes for this process; ask whoami once.
181
+ if _SID is None:
182
+ _SID = _user_sid(subprocess.run)
183
+ sid, run = _SID, subprocess.run
184
+ else:
185
+ sid = _user_sid(run)
186
+ if sid is None:
187
+ return False
188
+ try:
189
+ # By SID, not by name, so a renamed account or a name that is also a
190
+ # group cannot pick up the grant.
191
+ result = run(['icacls', str(path), '/inheritance:r', '/grant:r', f'*{sid}:(OI)(CI)F',
192
+ '*S-1-5-18:(OI)(CI)F'], capture_output=True, check=False)
193
+ except (OSError, subprocess.SubprocessError):
194
+ return False
195
+ return getattr(result, 'returncode', 1) == 0
196
+
197
+
198
+ def _user_sid(run):
199
+ """This user's SID (S-1-5-21-...), from whoami, or None."""
200
+ import re
201
+ import subprocess
202
+ try:
203
+ result = run(['whoami', '/user', '/fo', 'csv', '/nh'], capture_output=True, text=True, check=False)
204
+ except (OSError, subprocess.SubprocessError):
205
+ return None
206
+ match = re.search(r'"(S-1-[0-9-]+)"', getattr(result, 'stdout', '') or '')
207
+ return match.group(1) if match and getattr(result, 'returncode', 1) == 0 else None