From ee5c222bf5d94fa993c44a6d0e1f53d82c962870 Mon Sep 17 00:00:00 2001 From: Joel Kronqvist Date: Mon, 23 Nov 2026 21:33:28 +0200 Subject: initial commit --- xmpp-cli-bridge/xmpp_cli_bridge/__init__.py | 79 +++++++++++++ xmpp-cli-bridge/xmpp_cli_bridge/__main__.py | 175 ++++++++++++++++++++++++++++ xmpp-cli-bridge/xmpp_cli_bridge/agent.py | 69 +++++++++++ 3 files changed, 323 insertions(+) create mode 100644 xmpp-cli-bridge/xmpp_cli_bridge/__init__.py create mode 100644 xmpp-cli-bridge/xmpp_cli_bridge/__main__.py create mode 100644 xmpp-cli-bridge/xmpp_cli_bridge/agent.py (limited to 'xmpp-cli-bridge/xmpp_cli_bridge') diff --git a/xmpp-cli-bridge/xmpp_cli_bridge/__init__.py b/xmpp-cli-bridge/xmpp_cli_bridge/__init__.py new file mode 100644 index 0000000..f5ff805 --- /dev/null +++ b/xmpp-cli-bridge/xmpp_cli_bridge/__init__.py @@ -0,0 +1,79 @@ +"""Connect an XMPP account to a Python handler: serve(jid, password, handler).""" +from __future__ import annotations + +import asyncio +import logging +import re +import sys +from typing import Callable, Optional +from xml.etree import ElementTree as ET + +_MARK = "{xmpp-cli-bridge}mark" # tags our replies so bounces back to us are dropped + +from slixmpp import ClientXMPP + +Handler = Callable[[str, str], Optional[str]] + +# control chars are illegal in XML 1.0; sending them kills the stream +_XML_BAD = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff]") + +logger = logging.getLogger(__name__) + + +class _Bridge(ClientXMPP): + def __init__(self, jid: str, password: str, handler: Handler) -> None: + super().__init__(jid, password) + self._handler = handler + self.add_event_handler("session_start", self._on_start) + self.add_event_handler("message", self._on_message) + + async def _on_start(self, _event) -> None: + logger.info("connected as %s", self.boundjid.bare) + self.send_presence() + + async def _on_message(self, msg) -> None: + if msg["type"] in ("groupchat", "error") or not msg["body"]: + logger.debug("ignoring %s message from %s", msg["type"], msg["from"]) + return + if msg.xml.find(_MARK) is not None: # our own reply, bounced back + return + logger.info("message from %s: %.200r", msg["from"], str(msg["body"])) + try: + loop = asyncio.get_running_loop() + reply = await loop.run_in_executor( + None, self._handler, str(msg["body"]), str(msg["from"]) + ) + except Exception as exc: + reply = f"error: {exc}" + if reply is not None: + # ESC (0x1b) etc. are illegal XML; sending them kills the stream + # (seen live: pass ls output -> server ) + out = msg.reply(_XML_BAD.sub("", str(reply))) + ET.SubElement(out.xml, _MARK) + out.send() + logger.info("reply sent to %s (%d chars)", msg["from"], len(out["body"])) + + +def serve(jid: str, password: str, handler: Handler) -> None: + """Log in and dispatch messages to handler(body, sender_jid) -> reply or None. + + Blocks until Ctrl-C; handler runs in a worker thread so it may block. + """ + # one line per event on stdout; the child's stderr still goes to the + # terminal, so the two don't interleave + logging.basicConfig( + stream=sys.stdout, level=logging.INFO, format="%(asctime)s %(message)s" + ) + + async def _run() -> None: + bot = _Bridge(jid, password, handler) + bot.connect() + try: + await bot.disconnected + finally: + bot.disconnect() + + try: + asyncio.run(_run()) + except KeyboardInterrupt: + pass \ No newline at end of file diff --git a/xmpp-cli-bridge/xmpp_cli_bridge/__main__.py b/xmpp-cli-bridge/xmpp_cli_bridge/__main__.py new file mode 100644 index 0000000..b620039 --- /dev/null +++ b/xmpp-cli-bridge/xmpp_cli_bridge/__main__.py @@ -0,0 +1,175 @@ +"""xmpp-cli-bridge --jid JID [--password PW] [--allow JID]... CMD [ARGS...]""" +from __future__ import annotations + +import argparse +import logging +import os +import re +import selectors +import shlex +import subprocess +import threading +import time + +# SGR sequences and lone ESC, so terminal colors don't leak into replies +_ANSI = re.compile(r"\x1b(?:\[[0-9;?]*[A-Za-z]|\][^\x07]*\x07|.)") + +from slixmpp import JID + +from . import serve + +logger = logging.getLogger(__name__) + +QUIET = 0.5 # seconds of silent stdout before a reply is considered complete +MAX_WAIT = 30.0 +BOOT_WAIT = 30.0 # how long to wait for the child's first prompt at startup + + +def _drain(proc: subprocess.Popen) -> None: + # discard stale output (startup prompt, stragglers) so a reply only + # contains what the child produced after the current command + sel = selectors.DefaultSelector() + sel.register(proc.stdout, selectors.EVENT_READ) + while sel.select(0.05): + if not os.read(proc.stdout.fileno(), 65536): + break + sel.close() + + +def _tail_match(text: str, prompt: re.Pattern[str]) -> re.Match[str] | None: + # only a match ending at the very end of the buffer counts, and it must + # be finditer's LAST match: search()'s leftmost one can be an earlier + # prompt-like line (blockquote "> ", PS2 continuation), which shadows + # the real prompt and stalls the reply until the max-wait timeout + matches = list(prompt.finditer(text)) + return matches[-1] if matches and matches[-1].end() == len(text) else None + + +def _read_output( + proc: subprocess.Popen, prompt: re.Pattern[str] | None, max_wait: float +) -> str: + sel = selectors.DefaultSelector() + sel.register(proc.stdout, selectors.EVENT_READ) + buf = bytearray() + started = time.monotonic() + deadline = started + max_wait + while time.monotonic() < deadline: + if not sel.select(QUIET): + if prompt is None: + break + continue # prompt mode: silence doesn't end the reply + chunk = os.read(proc.stdout.fileno(), 65536) + if not chunk: + logger.info("child closed stdout after %.1fs", time.monotonic() - started) + break + buf += chunk + if prompt is not None: + # chat-sized outputs; decode() per chunk would split multibyte chars + text = bytes(buf).decode("utf-8", "replace") + m = _tail_match(text, prompt) + if m is not None: + logger.info( + "reply complete after %.1fs (prompt %r%s)", + time.monotonic() - started, + text[m.start() : m.end()], + "" if text[: m.start()].strip() else ", but empty", + ) + return _ANSI.sub("", text[: m.start()]) + sel.close() + text = _ANSI.sub("", bytes(buf).decode("utf-8", "replace")) + if prompt is not None: + m = _tail_match(text, prompt) + if m is not None: + return text[: m.start()] # timeout: still strip a trailing prompt + logger.warning( + "no prompt match after %.1fs, replying with the raw buffer; tail: %r", + time.monotonic() - started, text[-120:], + ) + return text + + +def make_handler( + argv: list[str], + allowed: set[str], + prompt: re.Pattern[str] | None = None, + max_wait: float = MAX_WAIT, +): + # MULTILINE so user-supplied ^/$ anchors work against the whole buffer + if prompt is not None and prompt.flags & re.MULTILINE == 0: + prompt = re.compile(prompt.pattern, prompt.flags | re.MULTILINE) + # argv runs directly, never via a shell -- this is the trust boundary + proc = subprocess.Popen( + argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None + ) + logger.info("child started: %s", shlex.join(argv)) + # consume the startup banner/prompt now: left in the pipe it races the + # first message into an empty reply and gets the real answer discarded + t0 = time.monotonic() + banner = _read_output(proc, prompt, BOOT_WAIT) + if proc.poll() is not None: + logger.warning("child exited during startup (code %s)", proc.returncode) + elif time.monotonic() - t0 >= BOOT_WAIT: + logger.warning("no startup prompt within %.0fs; first replies may be off", BOOT_WAIT) + else: + logger.info("child ready after %.1fs", time.monotonic() - t0) + if banner.strip(): + logger.info("discarded startup output: %.200r", banner) + lock = threading.Lock() # serialize messages: one stdin/stdout conversation + + def handle(body: str, sender: str): + if JID(sender).bare not in allowed: + logger.info("ignored message from %s (not allowlisted)", sender) + return None + with lock: + if proc.poll() is not None: + return f"process exited ({proc.returncode})" + try: + _drain(proc) + logger.info("-> child: %.200r", body) + proc.stdin.write(body.encode() + b"\n") + proc.stdin.flush() + except (BrokenPipeError, ValueError): + return f"process exited ({proc.returncode})" + out = _read_output(proc, prompt, max_wait) + if proc.poll() is not None and not out: + return f"process exited ({proc.returncode})" + if not out.strip(): + # bare prompt or empty turn: silence, not an empty XMPP message + logger.warning("child produced an empty reply; sending nothing") + return None + return out + + return handle + + +def main(argv: list[str] | None = None) -> None: + p = argparse.ArgumentParser(description="Expose a CLI application over XMPP.") + p.add_argument("--jid", required=True) + p.add_argument("--password", default=os.environ.get("XMPP_PASSWORD")) + p.add_argument("--allow", action="append", default=[], metavar="JID", + help="sender bare JID allowed to interact (repeatable)") + p.add_argument("--prompt", metavar="REGEX", default=None, + help="reply ends when stdout ends with a line matching REGEX; " + "without it replies end after %.1fs of silence" % QUIET) + p.add_argument("--max-wait", type=float, default=MAX_WAIT, metavar="SECONDS", + help="overall reply timeout (default %g)" % MAX_WAIT) + p.add_argument("cmd", nargs=argparse.REMAINDER, metavar="CMD") + args = p.parse_args(argv) + if not args.password: + p.error("--password or XMPP_PASSWORD required") + if not args.cmd: + p.error("CMD required") + if args.cmd[0] == "--": # REMAINDER keeps the separator + args.cmd.pop(0) + # default deny: only the bridge account's own bare JID + allowed = {JID(j).bare for j in args.allow} or {JID(args.jid).bare} + prompt = re.compile(args.prompt) if args.prompt else None + serve( + args.jid, + args.password, + make_handler(args.cmd, allowed, prompt, args.max_wait), + ) + + +if __name__ == "__main__": + main() diff --git a/xmpp-cli-bridge/xmpp_cli_bridge/agent.py b/xmpp-cli-bridge/xmpp_cli_bridge/agent.py new file mode 100644 index 0000000..a988320 --- /dev/null +++ b/xmpp-cli-bridge/xmpp_cli_bridge/agent.py @@ -0,0 +1,69 @@ +"""xmpp-agent-bridge --jid JID [--allow JID]... [--agent-dir DIR] + +Expose the coding agent at ~/Dev/agent (agent.py) as an XMPP bot: each +chat message becomes one agent input line, and the agent's finished turn +is sent back as the reply. Run it from the directory the agent should +work in (agent.py defaults its --workdir to the child's cwd). +""" +from __future__ import annotations + +import argparse +import os +import re +import sys +from pathlib import Path + +from slixmpp import JID + +from . import serve +from .__main__ import make_handler + +# agent.py's prompt: "> ", or "(N) > " with --show-token-usage (also +# enabled by the inherited LLM_SHOW_TOKEN_USAGE env var). re.search is +# leftmost, so a reply containing a bare "> " line only delays it to +# the max-wait timeout rather than cutting it short. +PROMPT = re.compile(r"(?:\(\d+\) )?> $") + +MAX_WAIT = 600.0 # an agent turn spans several LLM calls + + +def main(argv: list[str] | None = None) -> None: + p = argparse.ArgumentParser( + description="Expose the ~/Dev/agent coding agent over XMPP." + ) + p.add_argument("--jid", required=True) + p.add_argument("--password", default=os.environ.get("XMPP_PASSWORD")) + p.add_argument("--allow", action="append", default=[], metavar="JID", + help="sender bare JID allowed to interact (repeatable)") + p.add_argument("--agent-dir", type=Path, + default=Path("~/Dev/agent").expanduser(), + help="directory containing agent.py and its venv " + "(default: ~/Dev/agent)") + p.add_argument("--max-wait", type=float, default=MAX_WAIT, metavar="SECONDS", + help="overall reply timeout (default %g)" % MAX_WAIT) + args = p.parse_args(argv) + if not args.password: + p.error("--password or XMPP_PASSWORD required") + if not (args.agent_dir / "agent.py").is_file(): + p.error(f"no agent.py in {args.agent_dir}") + + python = args.agent_dir / "bin" / "python3" + cmd = [ + str(python if python.exists() else sys.executable), + str(args.agent_dir / "agent.py"), + # permission prompts read stdin, which the bridge feeds only one + # line per reply -- they would deadlock, so approve everything + "--trust-level", "4", + ] + + # default deny: only the bridge account's own bare JID + allowed = {JID(j).bare for j in args.allow} or {JID(args.jid).bare} + serve( + args.jid, + args.password, + make_handler(cmd, allowed, PROMPT, args.max_wait), + ) + + +if __name__ == "__main__": + main() -- cgit v1.2.3