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,851 @@
1
+ """Private operator setup and explicitly scoped MCP launches."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import getpass
6
+ import hashlib
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import shutil
11
+ import sys
12
+ import tempfile
13
+
14
+ from . import compat
15
+ from .credentials import CredentialError, private_directory, read_private_json, validate_token, write_private_json
16
+ from .transport import FakeTransport, TelegramTransport, TransportError, make_transport
17
+
18
+
19
+ # Every Telegram call Core makes. A method missing here fails as AttributeError,
20
+ # which Core records as an unknown send without ever reaching Telegram.
21
+ LAZY_METHODS = frozenset({"get_me", "get_webhook_info", "get_updates", "send_message", "send_photo",
22
+ "send_document", "forward_message", "set_message_reaction", "get_chat_member",
23
+ "download_file", "answer_callback_query", "edit_message_text", "send_widget",
24
+ "answer_widget_query", "edit_message_widget_data", "edit_ephemeral_message_text",
25
+ "set_my_commands", "delete_message"})
26
+
27
+
28
+ class LazyTransport:
29
+ def __init__(self, state_dir, fake):
30
+ self.state_dir, self.fake = state_dir, fake
31
+ self.transport = None
32
+
33
+ def __getattr__(self, name):
34
+ if name not in LAZY_METHODS:
35
+ raise AttributeError(name)
36
+ if self.transport is None:
37
+ self.transport = make_transport(self.state_dir, fake=self.fake)
38
+ return getattr(self.transport, name)
39
+
40
+
41
+ MAX_TOOL_ARGUMENTS = 1024 * 1024
42
+
43
+
44
+ def _relayed_tool(state_dir, args):
45
+ """The tool's answer from the always-on collector, or None when none took it."""
46
+ from . import relay_api
47
+ from .mcp_server import _TOOL_MAP, _VALIDATORS, relayed
48
+ arguments = args.tool_arguments
49
+ if args.name not in _TOOL_MAP or not isinstance(arguments, dict) or not _VALIDATORS[args.name].is_valid(arguments):
50
+ return None
51
+ secret = read_private_json(args.client_file)["client_secret"]
52
+ return relayed(lambda name, values: relay_api.call(state_dir, secret, name, values), args.name, arguments,
53
+ args.client_file)
54
+
55
+
56
+ def _tool_arguments():
57
+ """The tool arguments as one JSON object on stdin; nothing on stdin means none."""
58
+ if sys.stdin is None or sys.stdin.isatty():
59
+ return {}
60
+ raw = sys.stdin.buffer.read(MAX_TOOL_ARGUMENTS + 1)
61
+ if len(raw) > MAX_TOOL_ARGUMENTS:
62
+ return [] # not an object, so the tool refuses it as invalid_arguments
63
+ if not raw.strip():
64
+ return {}
65
+ try:
66
+ return json.loads(raw)
67
+ except (ValueError, UnicodeError):
68
+ return []
69
+
70
+
71
+ def _emit(value):
72
+ print(json.dumps(value, indent=2, sort_keys=True))
73
+
74
+
75
+ def _client(core, path, expected=None, *, allow_revoked=False):
76
+ value = read_private_json(path)
77
+ secret = value.get("client_secret", "")
78
+ if allow_revoked:
79
+ # Operator-only relay metadata/cleanup remains possible after disconnect.
80
+ # This never reactivates credentials or permits Telegram/MCP operations.
81
+ if not isinstance(secret, str) or len(secret) > 256:
82
+ raise CredentialError('authentication_failed')
83
+ with core._db() as db:
84
+ row = db.execute('SELECT id FROM clients WHERE secret_hash=?',
85
+ (hashlib.sha256(secret.encode()).hexdigest(),)).fetchone()
86
+ if row is None:
87
+ raise CredentialError('authentication_failed')
88
+ client_id = row['id']
89
+ else:
90
+ client_id = core.authenticate(secret)
91
+ if value.get("client_id") != client_id:
92
+ raise CredentialError("client_identity_mismatch")
93
+ if expected is not None and client_id != expected:
94
+ raise CredentialError("project_profile_client_mismatch")
95
+ return client_id
96
+
97
+
98
+ def _mode(state_dir, fake):
99
+ path = state_dir / "mode.json"
100
+ if path.exists() and read_private_json(path).get("mode") != ("fake" if fake else "live"):
101
+ raise CredentialError("state_transport_mode_mismatch")
102
+
103
+
104
+ def _relay_project_valid(core, binding, fake):
105
+ """Fail closed if a previously bound project's profile or MCP entry drifts."""
106
+ from .core import CoreError
107
+ from .onboarding import read_profile, _config_plan, _entry
108
+ try:
109
+ project = Path(binding['project_dir'])
110
+ profile = read_profile(project)
111
+ if (profile is None or profile['client_id'] != binding['client_id']
112
+ or Path(profile['state_dir']).resolve() != core.state_dir.resolve()
113
+ or profile['mode'] != ('fake' if fake else 'live')):
114
+ return False
115
+ client = Path(profile['client_file'])
116
+ _client(core, client, binding['client_id'])
117
+ # Tool approvals are optional here, so configs from older setups stay valid.
118
+ _, current, proposed = _config_plan(project, _entry(core.state_dir, client, fake), approvals=False)
119
+ return current is not None and current == proposed
120
+ except (CredentialError, CoreError, OSError, ValueError):
121
+ return False
122
+
123
+
124
+ def render_plugin(state_dir, client_file, output, name):
125
+ import re
126
+ if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", name) or len(name) > 64:
127
+ raise CredentialError("invalid_plugin_name")
128
+ output = Path(output).absolute()
129
+ if output.exists():
130
+ raise CredentialError("plugin_output_exists")
131
+ source = Path(__file__).resolve().parents[2]
132
+ if not (source / ".codex-plugin" / "plugin.json").is_file():
133
+ raise CredentialError("plugin_template_missing_use_source_checkout")
134
+ output.mkdir(parents=True, mode=0o700)
135
+ for relative in (".codex-plugin", "skills", "docs/OPERATIONS.md", "docs/LIVE_VALIDATION.md", "docs/COMPATIBILITY.md", "docs/RELAY.md", "docs/DIRECT_DISPATCH.md", "docs/MACOS_SERVICE.md", "docs/BOT_EXCHANGES.md", "docs/HOSTS.md"):
136
+ src, dst = source / relative, output / relative
137
+ if src.is_dir():
138
+ shutil.copytree(src, dst, ignore=shutil.ignore_patterns("__pycache__"))
139
+ elif src.is_file():
140
+ dst.parent.mkdir(parents=True, exist_ok=True)
141
+ shutil.copy2(src, dst)
142
+ executable = str(compat.own_aot())
143
+ entry = {"type": "stdio", "command": executable,
144
+ "args": ["--state-dir", str(state_dir), "mcp", "--client-file", str(Path(client_file).absolute())]}
145
+ (output / ".mcp.json").write_text(json.dumps({"mcpServers": {"telegram": entry}}, indent=2) + "\n", encoding='utf-8')
146
+ path = output / ".codex-plugin" / "plugin.json"
147
+ manifest = json.loads(path.read_text(encoding='utf-8'))
148
+ manifest["name"] = name
149
+ # A rendered profile is already wired. Its setup action must not
150
+ # create a second, project-native connection for the same client.
151
+ manifest.get("extensions", {}).get("com.openai", {}).pop("onboardingSkill", None)
152
+ manifest["mcpServers"] = "./.mcp.json"
153
+ # Push hooks need a project's runtime pointer and the host
154
+ # launcher; a rendered profile is a fixed client, so it ships neither.
155
+ manifest.pop("hooks", None)
156
+ path.write_text(json.dumps(manifest, indent=2) + "\n", encoding='utf-8')
157
+ return {"plugin_directory": str(output), "name": name, "installed": False,
158
+ "scope": "One client identity per server process; separate chat isolation requires host support."}
159
+
160
+
161
+ def parser():
162
+ p = argparse.ArgumentParser(description="One shared human-owned Telegram bot; private local setup.")
163
+ p.add_argument("--state-dir", type=Path, default=None)
164
+ p.add_argument("--fake", action="store_true", default=None, help="Isolated offline transport; never reads a bot token")
165
+ sub = p.add_subparsers(dest="command", required=True)
166
+ setup = sub.add_parser("setup", help="Prepare and pair one agent for an exact local project directory")
167
+ setup.add_argument("--label", required=True)
168
+ setup.add_argument("--project-dir", type=Path, required=True)
169
+ setup.add_argument("--client-file", type=Path, help="Reuse this existing protected client file")
170
+ setup.add_argument("--receiver-handoff-confirmed", action="store_true")
171
+ setup.add_argument("--prepare-only", action="store_true", help="Prepare profile and pairing without collecting or confirming")
172
+ serve_choice = setup.add_mutually_exclusive_group()
173
+ serve_choice.add_argument("--serve", action="store_true",
174
+ help="Install the always-on collector (aot serve) as a login service; ask the human first")
175
+ serve_choice.add_argument("--no-serve", action="store_true",
176
+ help="Do not install the always-on collector, and do not ask")
177
+ setup.add_argument("--host", choices=["codex", "claude", "pi", "amp", "antigravity", "grok-bot"], default="codex",
178
+ help="Agent host to prepare; codex writes .codex/config.toml, plugin hosts use the runtime pointer, "
179
+ "grok-bot prints the custom connector to add in Grok Bot")
180
+ register = sub.add_parser("account-register", help="Prompt privately for one bot token, validate without polling")
181
+ register.add_argument("--receiver-handoff-confirmed", action="store_true", help="Assert other receivers are stopped; webhooks are never changed")
182
+ register.add_argument("--token-stdin", action="store_true",
183
+ help="Read the token from a pipe instead of the hidden prompt, for hosts whose terminal "
184
+ "nobody can type into; a terminal on stdin is refused")
185
+ webhook_save = sub.add_parser("webhook-save", help="Store a wake webhook (URL on the first line, key on the "
186
+ "second, piped on stdin) in a private file for watch --webhook-file")
187
+ webhook_save.add_argument("--file", type=Path, required=True)
188
+ sub.add_parser("account-status")
189
+ sub.add_parser("codex-hooks", help="Show whether Codex still runs AOT's plugin hooks or wants them "
190
+ "approved again with /hooks (read-only)")
191
+ judge_config = sub.add_parser("judge-config", help="Owner only: configure, show or remove the decision model "
192
+ "for the optional model-judged wake decision "
193
+ "(delivery-settings --model-judge)")
194
+ judge_config.add_argument("action", choices=["set", "status", "clear"])
195
+ judge_config.add_argument("--endpoint", help="System One decision endpoint: Jev, Cloudflare Clef or a "
196
+ "self-hosted Clef; https, or http to this computer only")
197
+ judge_config.add_argument("--model", help="Model name the endpoint expects, for example jev-latest or clef-flash")
198
+ judge_config.add_argument("--threshold", type=float, default=0.5,
199
+ help="Deliver when the model's probability for yes is at least this (0.5 to 0.99)")
200
+ judge_config.add_argument("--key", action="store_true",
201
+ help="Ask for an API key in a hidden prompt; leave it out for a local model")
202
+ tool = sub.add_parser("tool", help="Run one Telegram tool for this project's agent, as the MCP server does; "
203
+ "JSON arguments on stdin")
204
+ tool.add_argument("name", help="Tool name, for example messages_poll, message_send or messages_ack")
205
+ tool.add_argument("--client-file", type=Path)
206
+ create = sub.add_parser("client-create")
207
+ create.add_argument("--label", required=True)
208
+ create.add_argument("--client-file", type=Path, required=True)
209
+ for name in ("pair-begin", "status", "history", "pause", "resume", "unsuspend", "disconnect", "mcp", "allow-sender", "bot-exchange-policy", "delivery-settings", "watch", "conversation-budget", "settings-panel"):
210
+ command = (sub.add_parser(name, help="Owner only: check with Telegram that a suspended destination works again, then clear it")
211
+ if name == "unsuspend" else
212
+ sub.add_parser(name, help="Send the owner a settings panel for this connection in the private chat with the bot")
213
+ if name == "settings-panel" else sub.add_parser(name))
214
+ command.add_argument("--client-file", type=Path, required=name not in {"status", "history", "pause", "resume", "unsuspend", "mcp", "watch"})
215
+ if name == "unsuspend":
216
+ command.add_argument("--topic-open", action="store_true",
217
+ help="Confirm you checked that a closed or changed topic is open again")
218
+ if name == "watch":
219
+ command.add_argument("--host", choices=["claude"],
220
+ help="Name the host, so notices add its shell fallback")
221
+ command.add_argument("--collect", action="store_true", help="Also long-poll the shared Telegram collector; never sends or acknowledges")
222
+ command.add_argument("--duration", type=float, default=0, help="Seconds to watch; 0 runs until stopped")
223
+ command.add_argument("--interval", type=float, default=2.0, help="Seconds between local inbox checks")
224
+ command.add_argument("--poll-timeout", type=int, default=10, help="Telegram long-poll seconds when collecting (0-20)")
225
+ command.add_argument("--format", choices=["text", "jsonl"], default="text")
226
+ command.add_argument("--no-backlog", action="store_true", help="Announce only deliveries that arrive after start")
227
+ command.add_argument("--webhook-file", type=Path,
228
+ help="Also POST a fixed notice (counts only, no message text) to the webhook saved "
229
+ "by webhook-save; keeps running without a parent host")
230
+ if name == "status":
231
+ command.add_argument("--human", action="store_true", help="Show a concise local status instead of JSON")
232
+ if name == "history":
233
+ command.add_argument("--limit", type=int, default=20)
234
+ command.add_argument("--cursor")
235
+ if name == "pause":
236
+ command.add_argument("--resume", action="store_true")
237
+ if name == "allow-sender":
238
+ command.add_argument("--sender-id", type=int, required=True)
239
+ kind = command.add_mutually_exclusive_group()
240
+ kind.add_argument("--bot", action="store_true")
241
+ kind.add_argument("--remove", action="store_true",
242
+ help="stop accepting this sender; auto-allow will not add it back until it is "
243
+ "allowed again explicitly")
244
+ if name == "delivery-settings":
245
+ command.add_argument("--filter", dest="delivery_filter", choices=["all", "addressed"],
246
+ help="all (default): deliver every allowed message; addressed: deliver only "
247
+ "messages that mention the bot, reply to it or address a command to it, "
248
+ "and keep the rest as context")
249
+ command.add_argument("--reaction-wake", dest="reaction_wake",
250
+ choices=["own_messages", "all", "none"],
251
+ help="own_messages (default): deliver and wake only reactions on messages this "
252
+ "agent published; all: every allowed reaction; none: keep all reactions "
253
+ "as context without waking")
254
+ command.add_argument("--context", dest="capture_context", choices=["on", "off"],
255
+ help="on: also keep messages from senders that are not allowed, as context only")
256
+ command.add_argument("--media", dest="accept_media", choices=["on", "off"],
257
+ help="on: accept documents, photos, video, audio, voice notes and animations, "
258
+ "with their caption as text")
259
+ command.add_argument("--wake-interval", dest="wake_interval", type=int, metavar="SECONDS",
260
+ help="batch notices: after one, wait this long before the next, which then "
261
+ "covers everything that arrived meanwhile; 0 (default) announces at once")
262
+ command.add_argument("--wake-exempt", dest="wake_exempt",
263
+ choices=["addressed,owner", "addressed", "owner", "none"],
264
+ help="what is still announced at once while batching: addressed,owner "
265
+ "(default) messages that address the bot and messages from the owner")
266
+ command.add_argument("--owner-notify", dest="owner_notify", choices=["on", "off"],
267
+ help="on: let this agent send private notices to the owner with owner_notify "
268
+ "(at most 3 per hour and 10 per day; off by default)")
269
+ command.add_argument("--model-judge", dest="model_judge", choices=["on", "off"],
270
+ help="on: with --filter addressed, ask a decision model whether a person's message "
271
+ "kept as context is meant for this agent, and deliver it if so; sends recent "
272
+ "group messages to the model; needs judge-config set (off by default)")
273
+ command.add_argument("--auto-allow", dest="auto_allow", choices=["on", "off"],
274
+ help="on: add every person and bot who posts in this group or topic to the allowed "
275
+ "senders, for groups where everyone is trusted (off by default; off keeps the "
276
+ "senders added so far)")
277
+ command.add_argument("--keep-alive", dest="keep_alive", choices=["on", "off"],
278
+ help="on: Claude Code only; when an idle session's background listener reaches its "
279
+ "23-hour limit, wake the session for one short turn so a new listener starts "
280
+ "(off by default: after 23 idle hours the session stops hearing Telegram)")
281
+ command.add_argument("--approvals-in", dest="approvals_in", choices=["private", "group"],
282
+ help="where owner approvals are asked: private (default) in the owner's private "
283
+ "chat with the bot, or group in this group or topic as a message only the "
284
+ "owner sees; Telegram does not guarantee those, so a failed send falls back "
285
+ "to the private chat")
286
+ if name == "bot-exchange-policy":
287
+ command.add_argument("--sender-id", type=int, required=True)
288
+ change = command.add_mutually_exclusive_group()
289
+ change.add_argument("--enable", dest="exchange_enabled", action="store_const", const=True)
290
+ change.add_argument("--disable", dest="exchange_enabled", action="store_const", const=False)
291
+ if name == "conversation-budget":
292
+ command.add_argument("--conversation-id", required=True)
293
+ command.add_argument("--additional-sends", type=int)
294
+ command.add_argument("--duration-seconds", type=int)
295
+ command.add_argument("--reason")
296
+ confirm = sub.add_parser("pair-confirm")
297
+ confirm.add_argument("--pairing-id", required=True)
298
+ confirm.add_argument("--confirm", action="store_true", help="Confirm observed sender and destination after local inspection")
299
+ limits = sub.add_parser("exchange-limits", help="Inspect or change the rolling send limits for every agent on this bot")
300
+ limits.add_argument("--conversation-send-limit", type=int, help="Sends allowed per conversation in each rolling window")
301
+ limits.add_argument("--conversation-window-seconds", type=int, help="Length of the per-conversation rolling window")
302
+ limits.add_argument("--client-send-limit", type=int, help="Sends allowed per agent across all its conversations in each rolling window")
303
+ limits.add_argument("--client-window-seconds", type=int, help="Length of the per-agent rolling window")
304
+ limits.add_argument("--pair-send-limit", type=int, help="Sends allowed per external bot pair in each rolling window")
305
+ limits.add_argument("--pair-window-seconds", type=int, help="Length of the per-pair rolling window")
306
+ limits.add_argument("--reset", action="store_true", help="Return to the built-in defaults")
307
+ limits.add_argument("--reason", help="Why the limits change; required when changing them")
308
+ sub.add_parser("collect")
309
+ sub.add_parser("unassigned")
310
+ serve = sub.add_parser("serve", help="Collect from Telegram without stopping, so owner actions and messages "
311
+ "are handled even while no agent is free")
312
+ action = serve.add_mutually_exclusive_group()
313
+ action.add_argument("--install", action="store_true", help="Run it as a user service (systemd or launchd)")
314
+ action.add_argument("--uninstall", action="store_true", help="Stop and remove the user service")
315
+ action.add_argument("--status", action="store_true", help="Show whether the user service is set up")
316
+ action.add_argument("--activity", action="store_true",
317
+ help="Show the last collector cycles, owner actions, relay calls and collector events, with timings")
318
+ action.add_argument("--on-demand", action="store_true",
319
+ help="Started by an agent: stop when idle, when the service is installed or a newer runtime takes over")
320
+ flush = sub.add_parser("flush")
321
+ flush.add_argument("--client-file", type=Path)
322
+ peer = sub.add_parser("configure-peer")
323
+ peer.add_argument("--client-file", type=Path, required=True)
324
+ peer.add_argument("--bot-username", required=True)
325
+ peer.add_argument("--command", dest="peer_command", required=True)
326
+ grant = sub.add_parser("grant-peer")
327
+ grant.add_argument("--source-client-file", type=Path, required=True)
328
+ grant.add_argument("--target-client-file", type=Path, required=True)
329
+ resolve = sub.add_parser("resolve")
330
+ resolve.add_argument("--outbox-id", required=True)
331
+ resolve.add_argument("--resolution", choices=["accepted", "cancel", "retry"], required=True)
332
+ resolve.add_argument("--message-id", type=int)
333
+ render = sub.add_parser("plugin-render")
334
+ render.add_argument("--client-file", type=Path, required=True)
335
+ render.add_argument("--output", type=Path, required=True)
336
+ render.add_argument("--name", default="agents-over-telegram")
337
+ relay_bind = sub.add_parser("relay-bind", help="Bind one client to an explicitly authorized local Codex chat")
338
+ relay_bind.add_argument("--client-file", type=Path, required=True)
339
+ relay_bind.add_argument("--thread-id", required=True)
340
+ relay_bind.add_argument("--project-dir", type=Path, required=True)
341
+ relay_bind.add_argument("--include-pending", action="store_true", help="Notify existing unhandled work instead of baselining it")
342
+ relay_unbind = sub.add_parser("relay-unbind")
343
+ relay_unbind.add_argument("--client-file", type=Path, required=True)
344
+ relay_status = sub.add_parser("relay-status")
345
+ relay_status.add_argument("--client-file", type=Path)
346
+ relay_resolve = sub.add_parser("relay-resolve", help="Record host handoff outcome; never acknowledges inbox work")
347
+ relay_resolve.add_argument("--notification-id", required=True)
348
+ relay_resolve.add_argument("--outcome", choices=["accepted", "failed", "uncertain", "cancelled"], required=True)
349
+ relay_watch = sub.add_parser("relay-watch", help="Bounded session relay; host messaging is performed by the waiting chat")
350
+ relay_watch.add_argument("--once", action="store_true", help="Exit promptly after one event, for bounded Codex shell waits")
351
+ relay_watch.add_argument("--duration", type=float, default=55)
352
+ relay_watch.add_argument("--interval", type=float, default=1.5)
353
+ relay_watch.add_argument("--collect", action="store_true", help="Also run the shared Telegram collector; never flush outgoing sends")
354
+ dispatch = sub.add_parser("relay-dispatch", help="Wake mapped Codex chats through their explicitly shared app-server")
355
+ dispatch.add_argument("--endpoint", required=True, help="Private unix:///path socket or authenticated loopback WebSocket")
356
+ dispatch.add_argument("--token-file", type=Path, help="Protected JSON bearer-token file for loopback WebSocket")
357
+ dispatch.add_argument("--duration", type=float, default=55, help="Listening seconds; 0 continues until explicitly stopped")
358
+ dispatch.add_argument("--collect", action="store_true", help="Also collect Telegram updates; never flush or acknowledge work")
359
+ desktop = sub.add_parser("relay-desktop", help="Wake mapped local chats in an already running, normally launched desktop")
360
+ desktop.add_argument("--codex-binary", type=Path,
361
+ help="Bundled native Codex CLI (auto-detected on Linux/macOS)")
362
+ desktop.add_argument("--codex-home", type=Path, help="Existing Codex home used by the running desktop")
363
+ desktop.add_argument("--duration", type=float, default=55, help="Listening seconds; 0 continues until explicitly stopped")
364
+ desktop.add_argument("--collect", action="store_true", help="Also collect Telegram updates; never flush or acknowledge work")
365
+ hook = sub.add_parser("hook", help="Answer one Claude Code or Codex hook event from stdin; never sends or acknowledges")
366
+ hook.add_argument("--host", choices=["claude", "codex", "antigravity"], required=True)
367
+ hook.add_argument("--project-dir", type=Path, help="Exact project directory; defaults to the host's project or cwd")
368
+ hook.add_argument("--collect-interval", type=float, default=0,
369
+ help="Also collect Telegram updates when the last attempt is older than this many seconds (0 = never)")
370
+ wake = sub.add_parser("wake", help="Wait for new deliveries, then wake the session: exit 2 for a Claude Code "
371
+ "asyncRewake hook, or print the notice and exit for an Antigravity background command")
372
+ wake.add_argument("--host", choices=["claude", "antigravity"], required=True)
373
+ wake.add_argument("--project-dir", type=Path, help="Exact project directory; defaults to the host's project or cwd")
374
+ wake.add_argument("--session", default="", help="Host session id; one waiter runs per client and session")
375
+ wake.add_argument("--host-pid", type=int, help="Host process; the waiter stops when it is gone")
376
+ wake.add_argument("--duration", type=float, default=None,
377
+ help="Seconds to wait before exiting quietly (Claude Code: 82800; Antigravity: 0, no limit)")
378
+ sub.add_parser("demo", help="Run a standalone temporary two-agent offline demonstration")
379
+ return p
380
+
381
+
382
+ def _piped_token():
383
+ """The bot token from a pipe; a terminal is refused, since it would echo."""
384
+ if sys.stdin is None or sys.stdin.isatty():
385
+ raise CredentialError("token_stdin_must_be_piped")
386
+ lines = [line.strip() for line in sys.stdin.read(4096).splitlines() if line.strip()]
387
+ if len(lines) != 1:
388
+ raise CredentialError("invalid_token")
389
+ return lines[0]
390
+
391
+
392
+ def register_account(core, state_dir, fake, receiver_handoff_confirmed, token_stdin=False):
393
+ if not fake and not receiver_handoff_confirmed:
394
+ raise CredentialError("receiver_handoff_confirmation_required")
395
+ credential_path = state_dir / "credentials.json"
396
+ if fake:
397
+ transport = make_transport(state_dir, fake=True)
398
+ else:
399
+ if credential_path.exists():
400
+ token = read_private_json(credential_path)["token"]
401
+ elif token_stdin:
402
+ token = _piped_token()
403
+ elif not sys.stdin.isatty():
404
+ raise CredentialError("private_terminal_required")
405
+ else:
406
+ token = getpass.getpass("Telegram bot token (hidden, stored locally): ")
407
+ token = validate_token(token)
408
+ transport = TelegramTransport(token)
409
+ bot = transport.get_me()
410
+ if transport.get_webhook_info().get("url"):
411
+ raise CredentialError("existing_webhook_refused")
412
+ result = core.register_account(bot["id"], bot["username"])
413
+ if not fake and not credential_path.exists():
414
+ write_private_json(credential_path, {"token": token})
415
+ if not (state_dir / "mode.json").exists():
416
+ write_private_json(state_dir / "mode.json", {"mode": "fake" if fake else "live"})
417
+ return {"registered": True, "bot_id": bot["id"], "username": bot["username"], "mode": "fake" if fake else "live"}
418
+
419
+
420
+ def judge_config(state_dir, args):
421
+ """Configure, show or remove the decision model; the key is never printed."""
422
+ from . import judge
423
+ if args.action != "set":
424
+ if args.endpoint or args.model or args.key or args.threshold != judge.DEFAULT_THRESHOLD:
425
+ raise CredentialError("judge_options_only_with_set")
426
+ return judge.config_status(state_dir) if args.action == "status" else {"cleared": judge.clear_config(state_dir)}
427
+ if not args.endpoint or not args.model:
428
+ raise CredentialError("judge_endpoint_and_model_required")
429
+ api_key = ""
430
+ if args.key:
431
+ if not sys.stdin.isatty():
432
+ raise CredentialError("private_terminal_required")
433
+ api_key = getpass.getpass("Decision model API key (hidden, stored locally): ")
434
+ if not api_key.strip():
435
+ raise CredentialError("invalid_judge_key")
436
+ judge.store_config(state_dir, args.endpoint, args.model, api_key, args.threshold)
437
+ return judge.config_status(state_dir)
438
+
439
+
440
+ def _confirm_operator(summary):
441
+ """Ask the human at a terminal before raising or changing send limits.
442
+
443
+ Agents usually run commands without a terminal, so this stops an agent from
444
+ lifting its own limit by accident. It is not a security boundary: an agent
445
+ running as the same user could still drive a terminal on purpose.
446
+ """
447
+ if not sys.stdin.isatty():
448
+ raise CredentialError("operator_confirmation_required")
449
+ print(summary + " Type yes to continue:", file=sys.stderr, flush=True)
450
+ if input().strip().lower() != "yes":
451
+ raise CredentialError("operator_confirmation_declined")
452
+
453
+
454
+ def _confirm_or_ask_owner(core, client_id, summary, action, params):
455
+ """Confirm at the terminal, or without one ask the owner with Telegram buttons.
456
+
457
+ Returns None when the terminal confirmed, so the caller applies the change
458
+ now; otherwise the pending approval, which the owner's button press applies.
459
+ """
460
+ if sys.stdin.isatty():
461
+ _confirm_operator(summary)
462
+ return None
463
+ return core.request_owner_approval(client_id, action, params, summary)
464
+
465
+
466
+ def run(args):
467
+ from .core import Core, CoreError
468
+ if args.command == "demo":
469
+ from .demo import run_demo
470
+ return run_demo()
471
+ if args.command == "setup":
472
+ from .onboarding import setup
473
+ return setup(args)
474
+ if args.command == "hook":
475
+ from .hosts import run_hook
476
+ return run_hook(args)
477
+ if args.command == "wake":
478
+ from .hosts import run_wake
479
+ return run_wake(args)
480
+ if args.command == "webhook-save":
481
+ from . import webhook
482
+ url, key = webhook.read_stdin_pair(sys.stdin)
483
+ return webhook.save(args.file, url, key)
484
+ from .onboarding import resolve_args
485
+ args = resolve_args(args)
486
+ if args.command == "codex-hooks":
487
+ from . import codex_trust
488
+ return codex_trust.status()
489
+ state_dir = private_directory(args.state_dir)
490
+ _mode(state_dir, args.fake)
491
+ if args.command == "tool" and args.client_file is not None:
492
+ # A tool call goes to the always-on collector first; this process
493
+ # opens the database only when no relay answers.
494
+ args.tool_arguments = _tool_arguments()
495
+ body = _relayed_tool(state_dir, args)
496
+ if body is not None:
497
+ return body
498
+ core = Core(state_dir, LazyTransport(state_dir, args.fake), recover_sends=(not args.command.startswith("relay-")
499
+ and args.command not in {"history", "status", "account-status", "judge-config", "bot-exchange-policy", "delivery-settings", "watch",
500
+ "conversation-budget", "exchange-limits", "serve"}))
501
+ if args.command.startswith("relay-"):
502
+ from .relay import RelayStore
503
+ store = RelayStore(core, project_validator=lambda binding: _relay_project_valid(core, binding, args.fake))
504
+ if args.command == "relay-desktop":
505
+ from .desktop_dispatcher import run_desktop_dispatcher
506
+ run_desktop_dispatcher(core, store, codex_binary=args.codex_binary, codex_home=args.codex_home,
507
+ duration=args.duration, collect=args.collect)
508
+ return None
509
+ if args.command == "relay-dispatch":
510
+ from .dispatcher import run_dispatcher
511
+ result = run_dispatcher(core, store, args.endpoint, token_file=args.token_file,
512
+ duration=args.duration, collect=args.collect)
513
+ if result['reason'] == 'connection_failed':
514
+ raise CoreError('dispatcher_connection_failed')
515
+ return None
516
+ if args.command == "relay-watch":
517
+ from .relay_watch import watch
518
+ watch(core, store, once=args.once, duration=args.duration,
519
+ interval=args.interval, collect=args.collect)
520
+ return None
521
+ if args.command == "relay-resolve":
522
+ return store.resolve(args.notification_id, args.outcome)
523
+ client_id = (_client(core, args.client_file, args.expected_client_id,
524
+ allow_revoked=args.command in {'relay-status', 'relay-unbind'})
525
+ if args.client_file is not None else None)
526
+ if args.command == "relay-status":
527
+ return store.status(client_id)
528
+ if args.command == "relay-unbind":
529
+ return store.unbind(client_id)
530
+ if args.command == "relay-bind":
531
+ from .onboarding import read_profile
532
+ profile = read_profile(args.project_dir.resolve())
533
+ if (profile is None or profile['client_id'] != client_id
534
+ or Path(profile['state_dir']).resolve() != state_dir.resolve()
535
+ or profile['mode'] != ('fake' if args.fake else 'live')
536
+ or Path(profile['client_file']).resolve() != args.client_file.resolve()):
537
+ raise CredentialError('relay_project_profile_mismatch')
538
+ if not _relay_project_valid(core, {'client_id': client_id,
539
+ 'project_dir': str(args.project_dir.resolve())}, args.fake):
540
+ raise CredentialError('relay_project_profile_mismatch')
541
+ return store.bind(client_id, args.thread_id, args.project_dir,
542
+ include_pending=args.include_pending)
543
+ if args.command == "account-register":
544
+ return register_account(core, state_dir, args.fake, args.receiver_handoff_confirmed, args.token_stdin)
545
+ if args.command == "judge-config":
546
+ return judge_config(state_dir, args)
547
+ if args.command == "client-create":
548
+ if args.client_file.exists():
549
+ raise CredentialError("client_file_exists")
550
+ private_directory(args.client_file.absolute().parent)
551
+ result = core.create_client(args.label)
552
+ write_private_json(args.client_file, result)
553
+ return {"client_id": result["client_id"], "client_file": str(args.client_file.absolute()), "label": args.label}
554
+ if args.command == "pair-confirm":
555
+ if not args.confirm:
556
+ return core.pairing_status(args.pairing_id)
557
+ from .onboarding import _owner_start_step
558
+ return {**core.confirm_pairing(args.pairing_id), 'next_step': _owner_start_step(core)}
559
+ if args.command == "collect":
560
+ return core.collect()
561
+ if args.command == "unassigned":
562
+ return core.unassigned()
563
+ if args.command == "serve":
564
+ from . import serve
565
+ if args.install:
566
+ return serve.install(state_dir)
567
+ if args.uninstall:
568
+ # Removing it on purpose also means no collector started on demand;
569
+ # serve --install or setup --serve turns collecting back on.
570
+ result = serve.uninstall(state_dir)
571
+ serve.opt_out(state_dir)
572
+ return {**result, 'on_demand': False}
573
+ if args.status:
574
+ return serve.status(state_dir)
575
+ if args.activity:
576
+ for line in serve.activity_lines(core.activity()):
577
+ print(line)
578
+ return None
579
+ from .relay_api import Relay
580
+ raise SystemExit(serve.run(core, state_dir, watchdog=serve.Watchdog(), relay=Relay(core, state_dir),
581
+ on_demand=args.on_demand))
582
+ if args.command == "flush":
583
+ return core.flush(client_id=_client(core, args.client_file, args.expected_client_id) if args.client_file else None)
584
+ if args.command == "account-status":
585
+ return core.accounts_status()
586
+ if args.command == "exchange-limits":
587
+ changes = {"conversation_send_limit": args.conversation_send_limit,
588
+ "conversation_window_seconds": args.conversation_window_seconds,
589
+ "client_send_limit": args.client_send_limit,
590
+ "client_window_seconds": args.client_window_seconds,
591
+ "pair_send_limit": args.pair_send_limit, "pair_window_seconds": args.pair_window_seconds}
592
+ if args.reset or any(value is not None for value in changes.values()):
593
+ described = "reset to the defaults" if args.reset else ", ".join(
594
+ f"{name}={value}" for name, value in changes.items() if value is not None)
595
+ _confirm_operator(f"Change the Telegram send limits for every agent on this bot: {described}.")
596
+ return core.exchange_limits(conversation_send_limit=args.conversation_send_limit,
597
+ conversation_window_seconds=args.conversation_window_seconds,
598
+ client_send_limit=args.client_send_limit,
599
+ client_window_seconds=args.client_window_seconds,
600
+ pair_send_limit=args.pair_send_limit,
601
+ pair_window_seconds=args.pair_window_seconds,
602
+ reset=args.reset, reason=args.reason)
603
+ if args.command == "grant-peer":
604
+ source = _client(core, args.source_client_file)
605
+ target = _client(core, args.target_client_file)
606
+ return core.grant_peer(source, target)
607
+ if args.command == "resolve":
608
+ return core.resolve_unknown(args.outbox_id, args.resolution, message_id=args.message_id)
609
+ if args.client_file is None:
610
+ raise CredentialError("client_file_required")
611
+ client_id = _client(core, args.client_file, args.expected_client_id)
612
+ if args.command == "tool":
613
+ from .mcp_server import call_tool
614
+ return call_tool(core, client_id, args.name, args.tool_arguments)
615
+ if args.command == "pair-begin":
616
+ return core.connection_begin(client_id)
617
+ if args.command == "status":
618
+ return core.connection_status(client_id)
619
+ if args.command == "history":
620
+ return core.history(client_id, limit=args.limit, cursor=args.cursor)
621
+ if args.command == "configure-peer":
622
+ return core.configure_peer_command(client_id, args.bot_username, args.peer_command)
623
+ if args.command == "allow-sender":
624
+ if args.remove:
625
+ return core.remove_sender(client_id, args.sender_id)
626
+ return core.allow_sender(client_id, args.sender_id, is_bot=args.bot)
627
+ if args.command == "bot-exchange-policy":
628
+ return core.bot_exchange_policy(client_id, args.sender_id, enabled=args.exchange_enabled)
629
+ if args.command == "delivery-settings":
630
+ def switch(value):
631
+ return None if value is None else value == "on"
632
+ changes = {"delivery_filter": args.delivery_filter, "capture_context": switch(args.capture_context),
633
+ "accept_media": switch(args.accept_media), "reaction_wake": args.reaction_wake,
634
+ "wake_interval": args.wake_interval, "wake_exempt": args.wake_exempt,
635
+ "owner_notify": switch(args.owner_notify), "model_judge": switch(args.model_judge),
636
+ "auto_allow": switch(args.auto_allow), "keep_alive": switch(args.keep_alive),
637
+ "approvals_in": args.approvals_in}
638
+ warnings = []
639
+ if args.model_judge == "on":
640
+ warnings.append("With the addressed filter, recent messages from this group or topic will be sent "
641
+ "to the configured decision model (aot judge-config status) to decide whether a "
642
+ "person's message is meant for this agent.")
643
+ if args.auto_allow == "on":
644
+ warnings.append("Every person and bot who posts in this group or topic will become an allowed sender "
645
+ "and can give this agent work. That includes anyone who joins later, for example "
646
+ "through an invite link. Remove one with allow-sender --remove.")
647
+ if args.keep_alive == "on":
648
+ warnings.append("Claude Code only: when this idle session's background listener reaches its 23-hour "
649
+ "limit, it wakes the session for one short turn so a new listener starts. Each such "
650
+ "turn reads the whole conversation without the prompt cache, once per idle day.")
651
+ if warnings:
652
+ # The whole command waits for the owner, so nothing applies half.
653
+ pending = _confirm_or_ask_owner(core, client_id, " ".join(warnings), "delivery_settings",
654
+ {name: value for name, value in changes.items() if value is not None})
655
+ if pending is not None:
656
+ return pending
657
+ return core.delivery_settings(client_id, **changes)
658
+ if args.command == "settings-panel":
659
+ return core.send_settings_panel(client_id)
660
+ if args.command == "unsuspend":
661
+ return core.clear_suspension(client_id, topic_open_confirmed=args.topic_open)
662
+ if args.command == "conversation-budget":
663
+ if args.additional_sends is not None:
664
+ pending = _confirm_or_ask_owner(
665
+ core, client_id,
666
+ f"Allow {args.additional_sends} more sends per rolling window in conversation "
667
+ f"{args.conversation_id!r} for {args.duration_seconds} seconds.",
668
+ "conversation_budget",
669
+ {"conversation_id": args.conversation_id, "additional_sends": args.additional_sends,
670
+ "duration_seconds": args.duration_seconds, "reason": args.reason})
671
+ if pending is not None:
672
+ return pending
673
+ return core.conversation_budget(client_id, args.conversation_id,
674
+ additional_sends=args.additional_sends,
675
+ duration_seconds=args.duration_seconds, reason=args.reason)
676
+ if args.command in {"pause", "resume"}:
677
+ return core.pause(client_id, paused=args.command == "pause" and not args.resume)
678
+ if args.command == "disconnect":
679
+ return core.disconnect(client_id)
680
+ if args.command == "plugin-render":
681
+ if args.fake:
682
+ raise CredentialError("fake_plugin_render_refused")
683
+ return render_plugin(state_dir, args.client_file, args.output, args.name)
684
+ if args.command == "watch":
685
+ from .push import watch
686
+ waker = None
687
+ if args.webhook_file is not None:
688
+ from . import webhook
689
+ waker = webhook.Waker(*webhook.load(args.webhook_file))
690
+
691
+ def emit(event):
692
+ if waker is not None:
693
+ waker.notify(event)
694
+ if args.format == "jsonl":
695
+ print(json.dumps(event, separators=(",", ":")), flush=True)
696
+ elif event.get("type") == "telegram_messages":
697
+ from .push import with_shell_fallback
698
+ print(with_shell_fallback(event["notice"]) if args.host == "claude" else event["notice"], flush=True)
699
+ else:
700
+ print("[Agents over Telegram] Watching stopped: " + event.get("reason", "unknown") + ".", flush=True)
701
+ from .hosts import RUNTIME_MOVED_EXIT, runtime_moved
702
+ parent = os.getppid()
703
+ project = Path.cwd().resolve()
704
+ moved = []
705
+
706
+ def keep_running():
707
+ if waker is not None:
708
+ # A webhook watcher has no host process to follow. It stops when
709
+ # setup moved the project to another runtime, so whatever keeps
710
+ # it running (a scheduled routine) starts it on the new one.
711
+ from .hosts import read_runtime_pointer
712
+ pointer = read_runtime_pointer(project)
713
+ if pointer is not None and os.path.realpath(pointer) != os.path.realpath(compat.own_aot()):
714
+ moved.append(True)
715
+ return False
716
+ return True
717
+ # A host can die without stopping its watcher (for example on SIGKILL).
718
+ # Re-parenting means the host is gone, so stop instead of polling forever.
719
+ if os.getppid() != parent:
720
+ return False
721
+ # A launcher that follows the runtime restarts this watcher on a new one.
722
+ if runtime_moved(project):
723
+ moved.append(True)
724
+ return False
725
+ return True
726
+
727
+ from .relay_api import Node
728
+ remote = Node(state_dir, read_private_json(args.client_file)["client_secret"])
729
+ try:
730
+ watch(core, client_id, emit, collect=args.collect, duration=args.duration, interval=args.interval,
731
+ poll_timeout=args.poll_timeout, announce_backlog=not args.no_backlog,
732
+ keep_running=keep_running, remote=remote)
733
+ finally:
734
+ if waker is not None:
735
+ waker.stop(timeout=webhook.TIMEOUT + 1)
736
+ if moved:
737
+ raise SystemExit(RUNTIME_MOVED_EXIT)
738
+ return None
739
+ if args.command == "mcp":
740
+ from .hosts import _start_collector
741
+ from .mcp_server import serve
742
+ _start_collector(state_dir)
743
+ serve(state_dir, args.client_file, transport=core.transport)
744
+ return None
745
+ raise CredentialError("unknown_command")
746
+
747
+
748
+ def _hook_invocation(argv):
749
+ """True when argv selects the hook command, even if its options are invalid."""
750
+ index = 0
751
+ while index < len(argv):
752
+ arg = argv[index]
753
+ if arg == "--state-dir":
754
+ index += 2
755
+ elif arg == "--fake" or arg.startswith("--state-dir="):
756
+ index += 1
757
+ else:
758
+ return arg in ("hook", "wake")
759
+ return False
760
+
761
+
762
+ # Fixed advice for errors whose fix is not obvious from the code alone. The text
763
+ # never includes values from the request, so it cannot leak paths or secrets.
764
+ ERROR_HINTS = {
765
+ "destination_already_bound": (
766
+ "Another connection already uses this chat or topic, or this client is already connected. AOT allows one "
767
+ "active connection per chat or topic. Disconnect the old one first (aot disconnect --client-file "
768
+ "<its client file>), then confirm the pairing again."),
769
+ "webhook_directory_not_private": (
770
+ "The folder for the webhook file already exists, and other users can read it or it is not yours. Run "
771
+ "chmod 700 on a folder you own, or name a file in a folder that does not exist yet; webhook-save then "
772
+ "creates it as private."),
773
+ }
774
+
775
+
776
+ def main():
777
+ from .core import CoreError
778
+ try:
779
+ args = parser().parse_args()
780
+ except SystemExit:
781
+ # Exit status 2 blocks some host hook events (for example a user prompt).
782
+ # A hook from a newer or older plugin must never do that.
783
+ if _hook_invocation(sys.argv[1:]):
784
+ return 0
785
+ raise
786
+ if args.command == "wake":
787
+ # Only a real wake may exit 2, and only a moved runtime 3 (for the
788
+ # launcher to restart it); anything else must stay silent.
789
+ from .hosts import RUNTIME_MOVED_EXIT
790
+ try:
791
+ value = run(args)
792
+ return value if value in (2, RUNTIME_MOVED_EXIT) else 0
793
+ except BaseException:
794
+ return 0
795
+ if args.command == "hook":
796
+ # run_hook already turns failures into no output; this also covers a
797
+ # host that closed the pipe before reading the answer.
798
+ try:
799
+ value = run(args)
800
+ if value is not None:
801
+ print(json.dumps(value, separators=(",", ":")), flush=True)
802
+ except Exception:
803
+ try:
804
+ # Avoid a second failing flush at interpreter exit (status 120).
805
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
806
+ except (OSError, ValueError):
807
+ pass
808
+ return 0
809
+ try:
810
+ value = run(args)
811
+ if value is not None:
812
+ if args.command == "setup" and not args.prepare_only:
813
+ from .onboarding import human_status
814
+ print(human_status(value["connection"]))
815
+ print("Next: " + json.dumps(value["next_step"], ensure_ascii=True)[1:-1])
816
+ elif args.command == "tool":
817
+ print(json.dumps(value, ensure_ascii=False, separators=(",", ":")), flush=True)
818
+ return 0 if value.get("ok") else 1
819
+ elif args.command == "status" and args.human:
820
+ from .onboarding import human_status
821
+ print(human_status(value))
822
+ else:
823
+ _emit(value)
824
+ return 0
825
+ except (CredentialError, CoreError, TransportError) as error:
826
+ # Even custom/fake exceptions cannot smuggle URLs or response data out.
827
+ import re
828
+ code = str(error.code)
829
+ safe = code if re.fullmatch(r"[a-z0-9_]{1,64}", code) else "operation_failed"
830
+ body = {"ok": False, "error": safe}
831
+ if safe in ERROR_HINTS:
832
+ body["hint"] = ERROR_HINTS[safe]
833
+ details = getattr(error, "details", None)
834
+ if isinstance(details, dict):
835
+ # Rolling limit details are numbers only; drop anything else.
836
+ numbers = {k: v for k, v in details.items() if isinstance(k, str) and re.fullmatch(r"[a-z_]{1,32}", k)
837
+ and isinstance(v, (int, float)) and not isinstance(v, bool)}
838
+ if numbers:
839
+ body["details"] = numbers
840
+ print(json.dumps(body), file=sys.stderr)
841
+ return 1
842
+ except (KeyboardInterrupt, EOFError):
843
+ print('{"ok":false,"error":"cancelled"}', file=sys.stderr)
844
+ return 130
845
+ except Exception:
846
+ print('{"ok":false,"error":"operation_failed"}', file=sys.stderr)
847
+ return 1
848
+
849
+
850
+ if __name__ == "__main__":
851
+ sys.exit(main())