agents-relay 0.0.1__tar.gz
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.
- agents_relay-0.0.1/LICENSE +21 -0
- agents_relay-0.0.1/PKG-INFO +34 -0
- agents_relay-0.0.1/README.md +9 -0
- agents_relay-0.0.1/pyproject.toml +38 -0
- agents_relay-0.0.1/setup.cfg +4 -0
- agents_relay-0.0.1/src/agents_relay/__init__.py +3 -0
- agents_relay-0.0.1/src/agents_relay/__main__.py +76 -0
- agents_relay-0.0.1/src/agents_relay/config.py +65 -0
- agents_relay-0.0.1/src/agents_relay/http_adapter.py +133 -0
- agents_relay-0.0.1/src/agents_relay/loop_client.py +97 -0
- agents_relay-0.0.1/src/agents_relay/telegram_adapter.py +159 -0
- agents_relay-0.0.1/src/agents_relay/telegram_format.py +87 -0
- agents_relay-0.0.1/src/agents_relay.egg-info/PKG-INFO +34 -0
- agents_relay-0.0.1/src/agents_relay.egg-info/SOURCES.txt +16 -0
- agents_relay-0.0.1/src/agents_relay.egg-info/dependency_links.txt +1 -0
- agents_relay-0.0.1/src/agents_relay.egg-info/entry_points.txt +2 -0
- agents_relay-0.0.1/src/agents_relay.egg-info/top_level.txt +1 -0
- agents_relay-0.0.1/tests/test_relay.py +138 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lolaplex
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agents-relay
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: HTTP and Telegram relay to agents-harness runner.loop (stdlib only)
|
|
5
|
+
Author: Lolaplex
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Lolaplex/agents-relay
|
|
8
|
+
Project-URL: Repository, https://github.com/Lolaplex/agents-relay
|
|
9
|
+
Project-URL: Bug Tracker, https://github.com/Lolaplex/agents-relay/issues
|
|
10
|
+
Keywords: agents,relay,gateway,telegram,http,harness,cli,coding-assistant
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Communications :: Chat
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# agents-relay
|
|
27
|
+
|
|
28
|
+
Thin relay over [agents-harness](https://github.com/Lolaplex/agents-harness) `runner.loop`: one subprocess per turn, trailer parsing for session metadata. No identity store, no traces.
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install -e .
|
|
32
|
+
export RELAY_SECRET=dev
|
|
33
|
+
python -m agents_relay serve
|
|
34
|
+
```
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# agents-relay
|
|
2
|
+
|
|
3
|
+
Thin relay over [agents-harness](https://github.com/Lolaplex/agents-harness) `runner.loop`: one subprocess per turn, trailer parsing for session metadata. No identity store, no traces.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install -e .
|
|
7
|
+
export RELAY_SECRET=dev
|
|
8
|
+
python -m agents_relay serve
|
|
9
|
+
```
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "agents-relay"
|
|
7
|
+
version = "0.0.1"
|
|
8
|
+
description = "HTTP and Telegram relay to agents-harness runner.loop (stdlib only)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{ name = "Lolaplex" }]
|
|
13
|
+
requires-python = ">=3.10"
|
|
14
|
+
dependencies = []
|
|
15
|
+
keywords = ["agents", "relay", "gateway", "telegram", "http", "harness", "cli", "coding-assistant"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 4 - Beta",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Topic :: Communications :: Chat",
|
|
26
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Homepage = "https://github.com/Lolaplex/agents-relay"
|
|
31
|
+
Repository = "https://github.com/Lolaplex/agents-relay"
|
|
32
|
+
"Bug Tracker" = "https://github.com/Lolaplex/agents-relay/issues"
|
|
33
|
+
|
|
34
|
+
[project.scripts]
|
|
35
|
+
agents-relay = "agents_relay.__main__:main"
|
|
36
|
+
|
|
37
|
+
[tool.setuptools.packages.find]
|
|
38
|
+
where = ["src"]
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""CLI: serve HTTP relay and optional Telegram poll."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import signal
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
from . import __version__
|
|
12
|
+
from .config import RelayConfig
|
|
13
|
+
from .http_adapter import serve_http
|
|
14
|
+
from .telegram_adapter import start_telegram_thread
|
|
15
|
+
|
|
16
|
+
log = logging.getLogger("agents_relay")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _help_json() -> dict:
|
|
20
|
+
return {
|
|
21
|
+
"name": "agents-relay",
|
|
22
|
+
"version": __version__,
|
|
23
|
+
"commands": {"serve": {"description": "Start HTTP /v1/turn and optional Telegram polling"}},
|
|
24
|
+
"flags": ["--help-json"],
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
29
|
+
parser = argparse.ArgumentParser(prog="agents-relay")
|
|
30
|
+
parser.add_argument("--help-json", action="store_true")
|
|
31
|
+
sub = parser.add_subparsers(dest="command")
|
|
32
|
+
serve_p = sub.add_parser("serve", help="Run relay")
|
|
33
|
+
serve_p.add_argument("--no-telegram", action="store_true", help="Disable Telegram polling")
|
|
34
|
+
return parser
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def main(argv: list[str] | None = None) -> int:
|
|
38
|
+
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
|
|
39
|
+
args = build_parser().parse_args(argv)
|
|
40
|
+
if getattr(args, "help_json", False):
|
|
41
|
+
print(json.dumps(_help_json(), indent=2))
|
|
42
|
+
return 0
|
|
43
|
+
if args.command != "serve":
|
|
44
|
+
build_parser().print_help()
|
|
45
|
+
return 0
|
|
46
|
+
|
|
47
|
+
config = RelayConfig.from_env()
|
|
48
|
+
server = serve_http(config)
|
|
49
|
+
tg_thread = None
|
|
50
|
+
tg_stop = None
|
|
51
|
+
if not args.no_telegram and config.telegram_bot_token:
|
|
52
|
+
tg_thread, tg_stop = start_telegram_thread(config)
|
|
53
|
+
|
|
54
|
+
def _shutdown(*_sig) -> None:
|
|
55
|
+
log.info("shutting down")
|
|
56
|
+
if tg_stop is not None:
|
|
57
|
+
tg_stop.set()
|
|
58
|
+
server.shutdown()
|
|
59
|
+
|
|
60
|
+
signal.signal(signal.SIGINT, _shutdown)
|
|
61
|
+
if hasattr(signal, "SIGTERM"):
|
|
62
|
+
signal.signal(signal.SIGTERM, _shutdown)
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
server.serve_forever()
|
|
66
|
+
except KeyboardInterrupt:
|
|
67
|
+
_shutdown()
|
|
68
|
+
finally:
|
|
69
|
+
server.server_close()
|
|
70
|
+
if tg_thread is not None:
|
|
71
|
+
tg_thread.join(timeout=2)
|
|
72
|
+
return 0
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
if __name__ == "__main__":
|
|
76
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Relay configuration from environment."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import shlex
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _clean(val: str) -> str:
|
|
11
|
+
return val.strip().strip("'\"").strip()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _int(val: str, default: int) -> int:
|
|
15
|
+
cleaned = _clean(val)
|
|
16
|
+
if not cleaned:
|
|
17
|
+
return default
|
|
18
|
+
try:
|
|
19
|
+
return int(cleaned)
|
|
20
|
+
except ValueError:
|
|
21
|
+
return default
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _int_list(value: str) -> tuple[int, ...]:
|
|
25
|
+
cleaned = _clean(value)
|
|
26
|
+
if not cleaned:
|
|
27
|
+
return ()
|
|
28
|
+
out: list[int] = []
|
|
29
|
+
for part in cleaned.split(","):
|
|
30
|
+
part = part.strip()
|
|
31
|
+
if part:
|
|
32
|
+
out.append(int(part))
|
|
33
|
+
return tuple(out)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class RelayConfig:
|
|
38
|
+
loop_cmd: tuple[str, ...]
|
|
39
|
+
loop_provider: str
|
|
40
|
+
relay_secret: str
|
|
41
|
+
telegram_bot_token: str
|
|
42
|
+
telegram_allowed_chat_ids: tuple[int, ...]
|
|
43
|
+
relay_host: str
|
|
44
|
+
relay_port: int
|
|
45
|
+
telegram_poll_timeout: int
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def from_env(cls) -> "RelayConfig":
|
|
49
|
+
raw_loop = _clean(os.environ.get("LOOP_CMD", "python -m runner.loop"))
|
|
50
|
+
loop_cmd = tuple(shlex.split(raw_loop, posix=os.name != "nt"))
|
|
51
|
+
if not loop_cmd:
|
|
52
|
+
loop_cmd = ("python", "-m", "runner.loop")
|
|
53
|
+
return cls(
|
|
54
|
+
loop_cmd=loop_cmd,
|
|
55
|
+
loop_provider=_clean(os.environ.get("LOOP_PROVIDER", "echo")) or "echo",
|
|
56
|
+
relay_secret=_clean(os.environ.get("RELAY_SECRET", os.environ.get("GATEWAY_SECRET", ""))),
|
|
57
|
+
telegram_bot_token=_clean(os.environ.get("TELEGRAM_BOT_TOKEN", "")),
|
|
58
|
+
telegram_allowed_chat_ids=_int_list(os.environ.get("TELEGRAM_ALLOWED_CHAT_IDS", "")),
|
|
59
|
+
relay_host=_clean(os.environ.get("RELAY_HOST", os.environ.get("GATEWAY_HOST", "127.0.0.1"))) or "127.0.0.1",
|
|
60
|
+
relay_port=_int(os.environ.get("RELAY_PORT", os.environ.get("GATEWAY_PORT", "8787")), 8787),
|
|
61
|
+
telegram_poll_timeout=max(1, min(50, _int(os.environ.get("TELEGRAM_POLL_TIMEOUT", "50"), 50))),
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
GatewayConfig = RelayConfig
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""stdlib HTTP server for /v1/turn."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
8
|
+
from typing import Callable
|
|
9
|
+
|
|
10
|
+
from .config import RelayConfig
|
|
11
|
+
from .loop_client import LoopTurnResult, run_loop_turn
|
|
12
|
+
|
|
13
|
+
log = logging.getLogger("agents_relay.http")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _check_secret(handler: BaseHTTPRequestHandler, expected: str) -> bool:
|
|
17
|
+
if not expected:
|
|
18
|
+
return True
|
|
19
|
+
got = (
|
|
20
|
+
handler.headers.get("X-Relay-Secret")
|
|
21
|
+
or handler.headers.get("Relay-Secret")
|
|
22
|
+
or handler.headers.get("X-Gateway-Secret")
|
|
23
|
+
or handler.headers.get("Gateway-Secret")
|
|
24
|
+
or ""
|
|
25
|
+
)
|
|
26
|
+
return got.strip() == expected
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class _TurnHook:
|
|
30
|
+
"""Wrap a turn callable so BaseHTTPRequestHandler does not bind it as a method."""
|
|
31
|
+
|
|
32
|
+
__slots__ = ("fn",)
|
|
33
|
+
|
|
34
|
+
def __init__(self, fn: Callable[..., LoopTurnResult]) -> None:
|
|
35
|
+
self.fn = fn
|
|
36
|
+
|
|
37
|
+
def __call__(self, **kwargs) -> LoopTurnResult:
|
|
38
|
+
return self.fn(**kwargs)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class TurnHandler(BaseHTTPRequestHandler):
|
|
42
|
+
relay_secret: str = ""
|
|
43
|
+
turn_hook: _TurnHook | None = None
|
|
44
|
+
config: RelayConfig | None = None
|
|
45
|
+
|
|
46
|
+
def log_message(self, fmt: str, *args) -> None:
|
|
47
|
+
log.info("%s - %s", self.address_string(), fmt % args)
|
|
48
|
+
|
|
49
|
+
def do_POST(self) -> None:
|
|
50
|
+
path = self.path.rstrip("/")
|
|
51
|
+
if path not in ("/v1/turn", "/v1/alert", "/webhook/alert"):
|
|
52
|
+
self.send_error(404)
|
|
53
|
+
return
|
|
54
|
+
if not _check_secret(self, self.relay_secret):
|
|
55
|
+
self.send_error(401, "unauthorized")
|
|
56
|
+
return
|
|
57
|
+
length = int(self.headers.get("Content-Length") or "0")
|
|
58
|
+
raw = self.rfile.read(length).decode("utf-8", errors="replace")
|
|
59
|
+
try:
|
|
60
|
+
body = json.loads(raw) if raw else {}
|
|
61
|
+
except json.JSONDecodeError:
|
|
62
|
+
self.send_error(400, "invalid json")
|
|
63
|
+
return
|
|
64
|
+
channel = str(body.get("channel") or ("webhook" if path != "/v1/turn" else "http"))
|
|
65
|
+
user = str(body.get("user") or ("alert" if path != "/v1/turn" else "anonymous"))
|
|
66
|
+
text = str(body.get("text") or body.get("message") or "")
|
|
67
|
+
session = str(body.get("session") or "")
|
|
68
|
+
user_id = str(body.get("user_id") or "")
|
|
69
|
+
new_session = bool(body.get("new_session"))
|
|
70
|
+
notify = bool(path in ("/v1/alert", "/webhook/alert") or body.get("notify") or body.get("broadcast"))
|
|
71
|
+
|
|
72
|
+
runner = (self.turn_hook.fn if self.turn_hook else None) or run_loop_turn
|
|
73
|
+
try:
|
|
74
|
+
result = runner(
|
|
75
|
+
channel=channel,
|
|
76
|
+
user=user,
|
|
77
|
+
message=text,
|
|
78
|
+
session=session,
|
|
79
|
+
user_id=user_id,
|
|
80
|
+
new_session=new_session,
|
|
81
|
+
)
|
|
82
|
+
except Exception as exc:
|
|
83
|
+
log.exception("turn failed")
|
|
84
|
+
self.send_error(500, str(exc))
|
|
85
|
+
return
|
|
86
|
+
|
|
87
|
+
notified = False
|
|
88
|
+
if notify and self.config and self.config.telegram_bot_token and self.config.telegram_allowed_chat_ids:
|
|
89
|
+
from .telegram_adapter import send_message
|
|
90
|
+
from .telegram_format import format_telegram_html
|
|
91
|
+
try:
|
|
92
|
+
primary_chat = self.config.telegram_allowed_chat_ids[0]
|
|
93
|
+
html = format_telegram_html(result.reply, ())
|
|
94
|
+
send_message(self.config.telegram_bot_token, primary_chat, html, parse_mode="HTML")
|
|
95
|
+
notified = True
|
|
96
|
+
except Exception as exc:
|
|
97
|
+
log.warning("failed to broadcast notification to telegram: %s", exc)
|
|
98
|
+
|
|
99
|
+
payload = {
|
|
100
|
+
"reply": result.reply,
|
|
101
|
+
"session": result.session,
|
|
102
|
+
"user_id": result.user_id,
|
|
103
|
+
"alias": result.alias,
|
|
104
|
+
"returncode": result.returncode,
|
|
105
|
+
"notified": notified,
|
|
106
|
+
}
|
|
107
|
+
data = json.dumps(payload).encode("utf-8")
|
|
108
|
+
self.send_response(200 if result.returncode == 0 else 502)
|
|
109
|
+
self.send_header("Content-Type", "application/json")
|
|
110
|
+
self.send_header("Content-Length", str(len(data)))
|
|
111
|
+
self.end_headers()
|
|
112
|
+
self.wfile.write(data)
|
|
113
|
+
|
|
114
|
+
def do_GET(self) -> None:
|
|
115
|
+
if self.path.rstrip("/") in ("/health", "/"):
|
|
116
|
+
data = b'{"ok":true}'
|
|
117
|
+
self.send_response(200)
|
|
118
|
+
self.send_header("Content-Type", "application/json")
|
|
119
|
+
self.send_header("Content-Length", str(len(data)))
|
|
120
|
+
self.end_headers()
|
|
121
|
+
self.wfile.write(data)
|
|
122
|
+
return
|
|
123
|
+
self.send_error(404)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def serve_http(config: RelayConfig, *, on_turn: Callable[..., LoopTurnResult] | None = None) -> ThreadingHTTPServer:
|
|
127
|
+
attrs: dict = {"relay_secret": config.relay_secret, "config": config}
|
|
128
|
+
if on_turn is not None:
|
|
129
|
+
attrs["turn_hook"] = _TurnHook(on_turn)
|
|
130
|
+
handler = type("ConfiguredTurnHandler", (TurnHandler,), attrs)
|
|
131
|
+
server = ThreadingHTTPServer((config.relay_host, config.relay_port), handler)
|
|
132
|
+
log.info("HTTP listening on %s:%s", config.relay_host, config.relay_port)
|
|
133
|
+
return server
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Spawn runner.loop and parse buffered trailer."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import subprocess
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from .config import RelayConfig
|
|
11
|
+
|
|
12
|
+
LOOP_TRAILER_MARKER = "---agents-loop-trailer---"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class LoopTurnResult:
|
|
17
|
+
reply: str
|
|
18
|
+
session: str
|
|
19
|
+
user_id: str
|
|
20
|
+
alias: str
|
|
21
|
+
returncode: int
|
|
22
|
+
stderr: str
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def parse_loop_stdout(stdout: str) -> dict[str, Any]:
|
|
26
|
+
"""Split user reply from trailer JSON after LOOP_TRAILER_MARKER."""
|
|
27
|
+
text = stdout or ""
|
|
28
|
+
if LOOP_TRAILER_MARKER in text:
|
|
29
|
+
body, _, trailer_part = text.partition(LOOP_TRAILER_MARKER)
|
|
30
|
+
reply = body.strip()
|
|
31
|
+
trailer_line = trailer_part.strip().splitlines()[0] if trailer_part.strip() else "{}"
|
|
32
|
+
try:
|
|
33
|
+
meta = json.loads(trailer_line)
|
|
34
|
+
except json.JSONDecodeError:
|
|
35
|
+
meta = {}
|
|
36
|
+
else:
|
|
37
|
+
reply = text.strip()
|
|
38
|
+
meta = {}
|
|
39
|
+
return {
|
|
40
|
+
"reply": reply,
|
|
41
|
+
"session": str(meta.get("session") or ""),
|
|
42
|
+
"user_id": str(meta.get("user_id") or ""),
|
|
43
|
+
"alias": str(meta.get("alias") or ""),
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def run_loop_turn(
|
|
48
|
+
*,
|
|
49
|
+
channel: str,
|
|
50
|
+
user: str,
|
|
51
|
+
message: str,
|
|
52
|
+
config: RelayConfig | None = None,
|
|
53
|
+
session: str = "",
|
|
54
|
+
user_id: str = "",
|
|
55
|
+
new_session: bool = False,
|
|
56
|
+
timeout_sec: int = 600,
|
|
57
|
+
) -> LoopTurnResult:
|
|
58
|
+
cfg = config or RelayConfig.from_env()
|
|
59
|
+
argv = list(cfg.loop_cmd)
|
|
60
|
+
argv.extend(
|
|
61
|
+
[
|
|
62
|
+
"--channel",
|
|
63
|
+
channel,
|
|
64
|
+
"--user",
|
|
65
|
+
user,
|
|
66
|
+
"--message",
|
|
67
|
+
message,
|
|
68
|
+
"--complete",
|
|
69
|
+
"--provider",
|
|
70
|
+
cfg.loop_provider,
|
|
71
|
+
"--deliver",
|
|
72
|
+
"buffered",
|
|
73
|
+
]
|
|
74
|
+
)
|
|
75
|
+
if session:
|
|
76
|
+
argv.extend(["--session", session])
|
|
77
|
+
if user_id:
|
|
78
|
+
argv.extend(["--user-id", user_id])
|
|
79
|
+
if new_session:
|
|
80
|
+
argv.append("--new-session")
|
|
81
|
+
|
|
82
|
+
proc = subprocess.run(
|
|
83
|
+
argv,
|
|
84
|
+
capture_output=True,
|
|
85
|
+
text=True,
|
|
86
|
+
timeout=timeout_sec,
|
|
87
|
+
shell=False,
|
|
88
|
+
)
|
|
89
|
+
parsed = parse_loop_stdout(proc.stdout or "")
|
|
90
|
+
return LoopTurnResult(
|
|
91
|
+
reply=parsed["reply"],
|
|
92
|
+
session=parsed["session"],
|
|
93
|
+
user_id=parsed["user_id"],
|
|
94
|
+
alias=parsed["alias"],
|
|
95
|
+
returncode=int(proc.returncode),
|
|
96
|
+
stderr=proc.stderr or "",
|
|
97
|
+
)
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Telegram long-poll adapter (urllib only)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
import urllib.error
|
|
10
|
+
import urllib.parse
|
|
11
|
+
import urllib.request
|
|
12
|
+
from typing import Callable
|
|
13
|
+
|
|
14
|
+
from .config import RelayConfig
|
|
15
|
+
from .loop_client import LoopTurnResult, run_loop_turn
|
|
16
|
+
from .telegram_format import format_telegram_html, status_html
|
|
17
|
+
|
|
18
|
+
log = logging.getLogger("agents_relay.telegram")
|
|
19
|
+
|
|
20
|
+
API_BASE = "https://api.telegram.org"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _api_url(token: str, method: str) -> str:
|
|
24
|
+
return f"{API_BASE}/bot{token}/{method}"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _post_json(url: str, payload: dict) -> dict:
|
|
28
|
+
data = json.dumps(payload).encode("utf-8")
|
|
29
|
+
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"}, method="POST")
|
|
30
|
+
with urllib.request.urlopen(req, timeout=60) as resp:
|
|
31
|
+
return json.loads(resp.read().decode("utf-8"))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def send_message(token: str, chat_id: int, text: str, *, parse_mode: str = "HTML") -> dict:
|
|
35
|
+
body = {
|
|
36
|
+
"chat_id": chat_id,
|
|
37
|
+
"text": text[:4096],
|
|
38
|
+
"disable_web_page_preview": True,
|
|
39
|
+
}
|
|
40
|
+
if parse_mode:
|
|
41
|
+
body["parse_mode"] = parse_mode
|
|
42
|
+
try:
|
|
43
|
+
return _post_json(_api_url(token, "sendMessage"), body)
|
|
44
|
+
except urllib.error.HTTPError as exc:
|
|
45
|
+
if parse_mode and exc.code == 400:
|
|
46
|
+
body.pop("parse_mode", None)
|
|
47
|
+
return _post_json(_api_url(token, "sendMessage"), body)
|
|
48
|
+
raise
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def edit_message(token: str, chat_id: int, message_id: int, text: str, *, parse_mode: str = "HTML") -> dict:
|
|
52
|
+
body = {
|
|
53
|
+
"chat_id": chat_id,
|
|
54
|
+
"message_id": message_id,
|
|
55
|
+
"text": text[:4096],
|
|
56
|
+
"disable_web_page_preview": True,
|
|
57
|
+
}
|
|
58
|
+
if parse_mode:
|
|
59
|
+
body["parse_mode"] = parse_mode
|
|
60
|
+
try:
|
|
61
|
+
return _post_json(_api_url(token, "editMessageText"), body)
|
|
62
|
+
except urllib.error.HTTPError as exc:
|
|
63
|
+
if parse_mode and exc.code == 400:
|
|
64
|
+
body.pop("parse_mode", None)
|
|
65
|
+
return _post_json(_api_url(token, "editMessageText"), body)
|
|
66
|
+
raise
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _allowed(chat_id: int, allowed: tuple[int, ...]) -> bool:
|
|
70
|
+
if not allowed:
|
|
71
|
+
return True
|
|
72
|
+
return chat_id in allowed
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def process_update(
|
|
76
|
+
update: dict,
|
|
77
|
+
*,
|
|
78
|
+
config: RelayConfig,
|
|
79
|
+
on_turn: Callable[..., LoopTurnResult] | None = None,
|
|
80
|
+
) -> None:
|
|
81
|
+
message = update.get("message") or update.get("edited_message")
|
|
82
|
+
if not message:
|
|
83
|
+
return
|
|
84
|
+
chat = message.get("chat") or {}
|
|
85
|
+
chat_id = int(chat.get("id") or 0)
|
|
86
|
+
if not chat_id or not _allowed(chat_id, config.telegram_allowed_chat_ids):
|
|
87
|
+
return
|
|
88
|
+
text = str(message.get("text") or "").strip()
|
|
89
|
+
if not text:
|
|
90
|
+
return
|
|
91
|
+
user = str((message.get("from") or {}).get("username") or chat_id)
|
|
92
|
+
token = config.telegram_bot_token
|
|
93
|
+
if not token:
|
|
94
|
+
return
|
|
95
|
+
|
|
96
|
+
thinking_msg = send_message(token, chat_id, status_html("thinking..."), parse_mode="HTML")
|
|
97
|
+
thinking_id = (thinking_msg.get("result") or {}).get("message_id") if isinstance(thinking_msg, dict) else None
|
|
98
|
+
|
|
99
|
+
runner = on_turn or run_loop_turn
|
|
100
|
+
result = runner(channel="telegram", user=user, message=text)
|
|
101
|
+
reply_html = format_telegram_html(result.reply, ())
|
|
102
|
+
|
|
103
|
+
if thinking_id:
|
|
104
|
+
try:
|
|
105
|
+
edit_message(token, chat_id, thinking_id, reply_html, parse_mode="HTML")
|
|
106
|
+
return
|
|
107
|
+
except Exception:
|
|
108
|
+
pass
|
|
109
|
+
send_message(token, chat_id, reply_html, parse_mode="HTML")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def telegram_poll_loop(
|
|
113
|
+
config: RelayConfig,
|
|
114
|
+
*,
|
|
115
|
+
stop_event: threading.Event | None = None,
|
|
116
|
+
on_turn: Callable[..., LoopTurnResult] | None = None,
|
|
117
|
+
) -> None:
|
|
118
|
+
token = config.telegram_bot_token
|
|
119
|
+
if not token:
|
|
120
|
+
log.warning("TELEGRAM_BOT_TOKEN not set; telegram poll disabled")
|
|
121
|
+
return
|
|
122
|
+
offset = 0
|
|
123
|
+
stop = stop_event or threading.Event()
|
|
124
|
+
while not stop.is_set():
|
|
125
|
+
params = {
|
|
126
|
+
"timeout": config.telegram_poll_timeout,
|
|
127
|
+
"offset": offset,
|
|
128
|
+
"allowed_updates": json.dumps(["message"]),
|
|
129
|
+
}
|
|
130
|
+
url = _api_url(token, "getUpdates") + "?" + urllib.parse.urlencode(params)
|
|
131
|
+
try:
|
|
132
|
+
with urllib.request.urlopen(url, timeout=config.telegram_poll_timeout + 10) as resp:
|
|
133
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
134
|
+
except Exception as exc:
|
|
135
|
+
log.warning("getUpdates failed: %s", exc)
|
|
136
|
+
time.sleep(2)
|
|
137
|
+
continue
|
|
138
|
+
for update in data.get("result") or []:
|
|
139
|
+
offset = int(update.get("update_id", offset)) + 1
|
|
140
|
+
try:
|
|
141
|
+
process_update(update, config=config, on_turn=on_turn)
|
|
142
|
+
except Exception:
|
|
143
|
+
log.exception("telegram update failed")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def start_telegram_thread(
|
|
147
|
+
config: RelayConfig,
|
|
148
|
+
*,
|
|
149
|
+
on_turn: Callable[..., LoopTurnResult] | None = None,
|
|
150
|
+
) -> tuple[threading.Thread, threading.Event]:
|
|
151
|
+
stop_event = threading.Event()
|
|
152
|
+
thread = threading.Thread(
|
|
153
|
+
target=telegram_poll_loop,
|
|
154
|
+
kwargs={"config": config, "stop_event": stop_event, "on_turn": on_turn},
|
|
155
|
+
name="telegram-poll",
|
|
156
|
+
daemon=True,
|
|
157
|
+
)
|
|
158
|
+
thread.start()
|
|
159
|
+
return thread, stop_event
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Telegram HTML formatting (stdlib only)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
TG_LIMIT = 4096
|
|
9
|
+
_BOLD_RE = re.compile(r"\*\*(.+?)\*\*")
|
|
10
|
+
_CODE_RE = re.compile(r"`([^`]+)`")
|
|
11
|
+
_FENCE_RE = re.compile(
|
|
12
|
+
r"```(?:json|xml|javascript|tool[\w_-]*)?\s*\n[\s\S]*?```",
|
|
13
|
+
re.IGNORECASE,
|
|
14
|
+
)
|
|
15
|
+
_TOOL_TAG_RE = re.compile(
|
|
16
|
+
r"<(tool_use|tool_call|tool_result|function_call|invoke|ts|clock|timestamp)\b[^>]*>[\s\S]*?</\1>",
|
|
17
|
+
re.IGNORECASE,
|
|
18
|
+
)
|
|
19
|
+
_BARE_TAGS_RE = re.compile(r"</?(?:ts|clock|timestamp)\b[^>]*>", re.IGNORECASE)
|
|
20
|
+
_BLOB_KEYS = (
|
|
21
|
+
"tool_call",
|
|
22
|
+
"tool_calls",
|
|
23
|
+
"tool_use",
|
|
24
|
+
"function_call",
|
|
25
|
+
"tool_result",
|
|
26
|
+
'"arguments"',
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _looks_like_blob(text: str) -> bool:
|
|
31
|
+
low = text.lower()
|
|
32
|
+
return any(key in low for key in _BLOB_KEYS) or len(text) > 400
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def strip_model_dumps(text: str) -> str:
|
|
36
|
+
if not text:
|
|
37
|
+
return ""
|
|
38
|
+
out = _FENCE_RE.sub(lambda m: "" if _looks_like_blob(m.group(0)) else m.group(0), text)
|
|
39
|
+
out = _TOOL_TAG_RE.sub("", out)
|
|
40
|
+
out = _BARE_TAGS_RE.sub("", out)
|
|
41
|
+
stripped = out.strip()
|
|
42
|
+
if stripped.startswith("{") or stripped.startswith("["):
|
|
43
|
+
if _looks_like_blob(stripped):
|
|
44
|
+
return ""
|
|
45
|
+
out = re.sub(r"\n{3,}", "\n\n", out)
|
|
46
|
+
return out.strip()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def visible_reply(text: str, traces: tuple[str, ...] = ()) -> str:
|
|
50
|
+
cleaned = strip_model_dumps(text)
|
|
51
|
+
if cleaned:
|
|
52
|
+
return cleaned
|
|
53
|
+
if traces:
|
|
54
|
+
return "Fertig."
|
|
55
|
+
return "(leere Antwort)"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def status_html(text: str) -> str:
|
|
59
|
+
plain = re.sub(r"[*_`]", "", text or "").strip() or "..."
|
|
60
|
+
return f"<i>{html.escape(plain)}</i>"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def format_telegram_html(answer: str, traces: tuple[str, ...] = ()) -> str:
|
|
64
|
+
body = _light_md_html(visible_reply(answer, traces))
|
|
65
|
+
extra = _traces_block(traces)
|
|
66
|
+
out = body + extra
|
|
67
|
+
if len(out) <= TG_LIMIT:
|
|
68
|
+
return out
|
|
69
|
+
budget = TG_LIMIT - len(extra) - 1
|
|
70
|
+
if budget < 80:
|
|
71
|
+
return body[: TG_LIMIT - 1] + "..."
|
|
72
|
+
return body[:budget] + "..." + extra
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _traces_block(traces: tuple[str, ...]) -> str:
|
|
76
|
+
lines = [html.escape(line) for line in traces if str(line).strip()]
|
|
77
|
+
if not lines:
|
|
78
|
+
return ""
|
|
79
|
+
inner = "\n".join(lines)
|
|
80
|
+
return f"\n\n<blockquote expandable><b>tools</b>\n{inner}</blockquote>"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _light_md_html(text: str) -> str:
|
|
84
|
+
escaped = html.escape(text, quote=False)
|
|
85
|
+
escaped = _BOLD_RE.sub(r"<b>\1</b>", escaped)
|
|
86
|
+
escaped = _CODE_RE.sub(r"<code>\1</code>", escaped)
|
|
87
|
+
return escaped
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agents-relay
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: HTTP and Telegram relay to agents-harness runner.loop (stdlib only)
|
|
5
|
+
Author: Lolaplex
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Lolaplex/agents-relay
|
|
8
|
+
Project-URL: Repository, https://github.com/Lolaplex/agents-relay
|
|
9
|
+
Project-URL: Bug Tracker, https://github.com/Lolaplex/agents-relay/issues
|
|
10
|
+
Keywords: agents,relay,gateway,telegram,http,harness,cli,coding-assistant
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Communications :: Chat
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# agents-relay
|
|
27
|
+
|
|
28
|
+
Thin relay over [agents-harness](https://github.com/Lolaplex/agents-harness) `runner.loop`: one subprocess per turn, trailer parsing for session metadata. No identity store, no traces.
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install -e .
|
|
32
|
+
export RELAY_SECRET=dev
|
|
33
|
+
python -m agents_relay serve
|
|
34
|
+
```
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/agents_relay/__init__.py
|
|
5
|
+
src/agents_relay/__main__.py
|
|
6
|
+
src/agents_relay/config.py
|
|
7
|
+
src/agents_relay/http_adapter.py
|
|
8
|
+
src/agents_relay/loop_client.py
|
|
9
|
+
src/agents_relay/telegram_adapter.py
|
|
10
|
+
src/agents_relay/telegram_format.py
|
|
11
|
+
src/agents_relay.egg-info/PKG-INFO
|
|
12
|
+
src/agents_relay.egg-info/SOURCES.txt
|
|
13
|
+
src/agents_relay.egg-info/dependency_links.txt
|
|
14
|
+
src/agents_relay.egg-info/entry_points.txt
|
|
15
|
+
src/agents_relay.egg-info/top_level.txt
|
|
16
|
+
tests/test_relay.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
agents_relay
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Relay unit tests."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import unittest
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from http.client import HTTPConnection
|
|
9
|
+
from unittest.mock import patch
|
|
10
|
+
|
|
11
|
+
from agents_relay.config import RelayConfig
|
|
12
|
+
from agents_relay.http_adapter import serve_http
|
|
13
|
+
from agents_relay.loop_client import LOOP_TRAILER_MARKER, parse_loop_stdout, run_loop_turn
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TestTrailerParse(unittest.TestCase):
|
|
17
|
+
def test_parse_trailer(self):
|
|
18
|
+
stdout = f"hello\n{LOOP_TRAILER_MARKER}\n" + json.dumps(
|
|
19
|
+
{"session": "ses_x", "user_id": "u_y", "alias": "telegram:1"}
|
|
20
|
+
)
|
|
21
|
+
parsed = parse_loop_stdout(stdout)
|
|
22
|
+
self.assertEqual(parsed["reply"], "hello")
|
|
23
|
+
self.assertEqual(parsed["session"], "ses_x")
|
|
24
|
+
self.assertEqual(parsed["user_id"], "u_y")
|
|
25
|
+
self.assertEqual(parsed["alias"], "telegram:1")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TestLoopSubprocess(unittest.TestCase):
|
|
29
|
+
def test_mock_loop_subprocess(self):
|
|
30
|
+
trailer = json.dumps({"session": "s1", "user_id": "u1", "alias": "a1"})
|
|
31
|
+
fake_stdout = f"pong\n{LOOP_TRAILER_MARKER}\n{trailer}\n"
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class FakeProc:
|
|
35
|
+
returncode: int = 0
|
|
36
|
+
stdout: str = fake_stdout
|
|
37
|
+
stderr: str = ""
|
|
38
|
+
|
|
39
|
+
cfg = RelayConfig(
|
|
40
|
+
loop_cmd=("python", "-c", "print('skip')"),
|
|
41
|
+
loop_provider="echo",
|
|
42
|
+
relay_secret="sekrit",
|
|
43
|
+
telegram_bot_token="",
|
|
44
|
+
telegram_allowed_chat_ids=(),
|
|
45
|
+
relay_host="127.0.0.1",
|
|
46
|
+
relay_port=0,
|
|
47
|
+
telegram_poll_timeout=1,
|
|
48
|
+
)
|
|
49
|
+
with patch("agents_relay.loop_client.subprocess.run", return_value=FakeProc()):
|
|
50
|
+
result = run_loop_turn(channel="http", user="u", message="ping", config=cfg)
|
|
51
|
+
self.assertEqual(result.reply, "pong")
|
|
52
|
+
self.assertEqual(result.session, "s1")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class TestHttpTurn(unittest.TestCase):
|
|
56
|
+
def test_v1_turn_auth(self):
|
|
57
|
+
cfg = RelayConfig(
|
|
58
|
+
loop_cmd=("python", "-m", "runner.loop"),
|
|
59
|
+
loop_provider="echo",
|
|
60
|
+
relay_secret="expected",
|
|
61
|
+
telegram_bot_token="",
|
|
62
|
+
telegram_allowed_chat_ids=(),
|
|
63
|
+
relay_host="127.0.0.1",
|
|
64
|
+
relay_port=0,
|
|
65
|
+
telegram_poll_timeout=1,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
def fake_turn(**kwargs):
|
|
69
|
+
from agents_relay.loop_client import LoopTurnResult
|
|
70
|
+
|
|
71
|
+
return LoopTurnResult(reply="ok", session="", user_id="", alias="", returncode=0, stderr="")
|
|
72
|
+
|
|
73
|
+
server = serve_http(cfg, on_turn=fake_turn)
|
|
74
|
+
server.server_port # type: ignore[attr-defined]
|
|
75
|
+
host, port = server.server_address # type: ignore[misc]
|
|
76
|
+
server_thread = __import__("threading").Thread(target=server.serve_forever, daemon=True)
|
|
77
|
+
server_thread.start()
|
|
78
|
+
try:
|
|
79
|
+
conn = HTTPConnection(host, port, timeout=5)
|
|
80
|
+
body = json.dumps({"channel": "http", "user": "t", "text": "hi"})
|
|
81
|
+
conn.request("POST", "/v1/turn", body=body, headers={"Content-Type": "application/json"})
|
|
82
|
+
resp = conn.getresponse()
|
|
83
|
+
self.assertEqual(resp.status, 401)
|
|
84
|
+
|
|
85
|
+
conn = HTTPConnection(host, port, timeout=5)
|
|
86
|
+
conn.request(
|
|
87
|
+
"POST",
|
|
88
|
+
"/v1/turn",
|
|
89
|
+
body=body,
|
|
90
|
+
headers={"Content-Type": "application/json", "X-Relay-Secret": "expected"},
|
|
91
|
+
)
|
|
92
|
+
resp = conn.getresponse()
|
|
93
|
+
self.assertEqual(resp.status, 200)
|
|
94
|
+
data = json.loads(resp.read().decode())
|
|
95
|
+
self.assertEqual(data["reply"], "ok")
|
|
96
|
+
self.assertFalse(data["notified"])
|
|
97
|
+
|
|
98
|
+
# Test /v1/alert with notification mocking
|
|
99
|
+
with patch("agents_relay.telegram_adapter.send_message") as mock_send:
|
|
100
|
+
cfg_with_tg = RelayConfig(
|
|
101
|
+
loop_cmd=("python", "-m", "runner.loop"),
|
|
102
|
+
loop_provider="echo",
|
|
103
|
+
relay_secret="expected",
|
|
104
|
+
telegram_bot_token="fake_bot_token",
|
|
105
|
+
telegram_allowed_chat_ids=(12345,),
|
|
106
|
+
relay_host="127.0.0.1",
|
|
107
|
+
relay_port=0,
|
|
108
|
+
telegram_poll_timeout=1,
|
|
109
|
+
)
|
|
110
|
+
tg_server = serve_http(cfg_with_tg, on_turn=fake_turn)
|
|
111
|
+
tg_host, tg_port = tg_server.server_address
|
|
112
|
+
tg_thread = __import__("threading").Thread(target=tg_server.serve_forever, daemon=True)
|
|
113
|
+
tg_thread.start()
|
|
114
|
+
try:
|
|
115
|
+
alert_conn = HTTPConnection(tg_host, tg_port, timeout=5)
|
|
116
|
+
alert_body = json.dumps({"text": "system alert"})
|
|
117
|
+
alert_conn.request(
|
|
118
|
+
"POST",
|
|
119
|
+
"/v1/alert",
|
|
120
|
+
body=alert_body,
|
|
121
|
+
headers={"Content-Type": "application/json", "X-Relay-Secret": "expected"},
|
|
122
|
+
)
|
|
123
|
+
alert_resp = alert_conn.getresponse()
|
|
124
|
+
self.assertEqual(alert_resp.status, 200)
|
|
125
|
+
alert_data = json.loads(alert_resp.read().decode())
|
|
126
|
+
self.assertTrue(alert_data["notified"])
|
|
127
|
+
mock_send.assert_called_once()
|
|
128
|
+
finally:
|
|
129
|
+
tg_server.shutdown()
|
|
130
|
+
tg_thread.join(timeout=2)
|
|
131
|
+
finally:
|
|
132
|
+
server.shutdown()
|
|
133
|
+
server_thread.join(timeout=2)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
if __name__ == "__main__":
|
|
137
|
+
unittest.main()
|
|
138
|
+
|