add LXMF gateway
This commit is contained in:
1 parent
1d9730bfcb
commit
49f67575cf
11 files changed
+1136
-163
No files matched your search
+148
-25
@@ -589,44 +589,137 @@ def _gateway_address_callback(adapter):
|
||||
return _announce
|
||||
|
||||
|
||||
def _lxmf_address_callback(adapter):
|
||||
"""Return a sync `on_connected` hook that prints the bot's LXMF address once.
|
||||
|
||||
Unlike SimpleX there is no daemon round-trip: the router knows its delivery
|
||||
address as soon as it is registered, so the hook just prints it once.
|
||||
"""
|
||||
printed = False
|
||||
|
||||
def _announce() -> None:
|
||||
nonlocal printed
|
||||
if printed:
|
||||
return
|
||||
address = getattr(adapter.daemon, "address", "") or ""
|
||||
if not address:
|
||||
print("gateway lxmf: no address available", file=sys.stderr)
|
||||
return
|
||||
printed = True
|
||||
print(f"gateway lxmf address: {address}")
|
||||
|
||||
return _announce
|
||||
|
||||
|
||||
def _attach_address_announcer(adapter) -> None:
|
||||
"""Wire the platform's startup address announcement onto its daemon.
|
||||
|
||||
A human cannot reach a gateway without its address. Print it once on
|
||||
connect, from the operator front end (the CLI), through the transport the
|
||||
adapter already owns — no second connection, no new transport surface.
|
||||
"""
|
||||
if adapter.name == "simplex":
|
||||
adapter.daemon.on_connected = _gateway_address_callback(adapter)
|
||||
elif adapter.name == "lxmf":
|
||||
adapter.daemon.on_connected = _lxmf_address_callback(adapter)
|
||||
|
||||
|
||||
def _build_gateway_adapter(platform: str, cfg: dict, trace):
|
||||
"""Construct one adapter from its config, or None for an unknown platform."""
|
||||
if platform == "simplex":
|
||||
from .gateway.simplex import SimplexAdapter
|
||||
|
||||
return SimplexAdapter(cfg, trace=trace)
|
||||
if platform == "lxmf":
|
||||
from .gateway.lxmf import LxmfAdapter
|
||||
|
||||
cfg = dict(cfg or {})
|
||||
# Contain Reticulum's config + identity under the checkout's .runtime/.
|
||||
cfg.setdefault("config_dir", str(REPO_ROOT / ".runtime" / "lxmf" / "reticulum"))
|
||||
cfg.setdefault("storage_path", str(REPO_ROOT / ".runtime" / "lxmf" / "router"))
|
||||
return LxmfAdapter(cfg, trace=trace)
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_platforms(requested: str, gateway_cfg: dict) -> list[str]:
|
||||
"""Turn `--platform` into a list of platform names.
|
||||
|
||||
`all`/`*` means every **enabled** gateway block in config; a
|
||||
comma-separated list is taken as-is (unknown names are kept so the caller
|
||||
can report them).
|
||||
"""
|
||||
requested = (requested or "simplex").strip()
|
||||
if requested in ("all", "*"):
|
||||
return [
|
||||
name
|
||||
for name, block in (gateway_cfg or {}).items()
|
||||
if isinstance(block, dict)
|
||||
and not name.startswith("_")
|
||||
and block.get("enabled", False)
|
||||
]
|
||||
return [name.strip() for name in requested.split(",") if name.strip()]
|
||||
|
||||
|
||||
def run_gateway(
|
||||
scheduler: Scheduler,
|
||||
config: dict,
|
||||
platform: str = "simplex",
|
||||
serve_dashboard: bool = False,
|
||||
) -> int:
|
||||
"""Run the messenger gateway in the foreground (SimpleX first)."""
|
||||
cfg = (config.get("gateway", {}) or {}).get(platform, {}) or {}
|
||||
if not cfg.get("enabled", False):
|
||||
print(f"gateway.{platform} is not enabled in config")
|
||||
"""Run one or more messenger gateways in the foreground.
|
||||
|
||||
All enabled adapters share a single scheduler/process (see AGENTS.md: never
|
||||
run two scheduler processes over one skill store), so each gets its own
|
||||
transport thread but they route through one `GatewayService`.
|
||||
"""
|
||||
gateway_cfg = config.get("gateway", {}) or {}
|
||||
platforms = _resolve_platforms(platform, gateway_cfg)
|
||||
|
||||
adapters: dict = {}
|
||||
for name in platforms:
|
||||
cfg = gateway_cfg.get(name) or {}
|
||||
if not isinstance(cfg, dict) or not cfg.get("enabled", False):
|
||||
print(f"gateway.{name} is not enabled in config")
|
||||
continue
|
||||
adapter = _build_gateway_adapter(name, cfg, scheduler.trace)
|
||||
if adapter is None:
|
||||
print(f"unknown gateway platform {name!r}")
|
||||
continue
|
||||
ok, hint = adapter.check_requirements()
|
||||
if not ok:
|
||||
print(f"gateway {name} unavailable: {hint}")
|
||||
continue
|
||||
_attach_address_announcer(adapter)
|
||||
adapters[name] = adapter
|
||||
|
||||
if not adapters:
|
||||
print("no gateway platforms enabled/available")
|
||||
return 1
|
||||
|
||||
if platform == "simplex":
|
||||
from .gateway.simplex import SimplexAdapter
|
||||
# Reticulum installs process signal handlers, which only works on the main
|
||||
# thread. Run the LXMF transport's main-thread setup (Reticulum + router)
|
||||
# here before the per-adapter transport threads start; `run()` reuses it.
|
||||
for name in list(adapters):
|
||||
prepare = getattr(adapters[name].daemon, "prepare", None)
|
||||
if callable(prepare):
|
||||
try:
|
||||
prepare()
|
||||
except Exception as exc:
|
||||
print(f"gateway {name} unavailable: {exc}", file=sys.stderr)
|
||||
del adapters[name]
|
||||
|
||||
adapter = SimplexAdapter(cfg, trace=scheduler.trace)
|
||||
# Print the bot's own contact link once, on connect, so the operator can
|
||||
# actually reach the gateway (see _gateway_address_callback).
|
||||
adapter.daemon.on_connected = _gateway_address_callback(adapter)
|
||||
else:
|
||||
print(f"unknown gateway platform {platform!r}")
|
||||
return 1
|
||||
|
||||
ok, hint = adapter.check_requirements()
|
||||
if not ok:
|
||||
print(f"gateway {platform} unavailable: {hint}")
|
||||
if not adapters:
|
||||
print("no gateway platforms enabled/available")
|
||||
return 1
|
||||
|
||||
from .gateway.service import GatewayService
|
||||
|
||||
scheduler.defer_questions = True
|
||||
service = GatewayService(scheduler, adapter, config=cfg)
|
||||
service = GatewayService(scheduler, adapters, config=gateway_cfg)
|
||||
scheduler.on_request_requeued = service.on_request_requeued
|
||||
service.start()
|
||||
|
||||
if serve_dashboard:
|
||||
import threading
|
||||
|
||||
from .dashboard import serve
|
||||
|
||||
dash_cfg = config.get("dashboard", {}) or {}
|
||||
@@ -640,14 +733,40 @@ def run_gateway(
|
||||
daemon=True,
|
||||
).start()
|
||||
|
||||
print(f"gateway {platform} listening on {adapter.ws_url} (Ctrl-C to stop)")
|
||||
threads: list[threading.Thread] = []
|
||||
for name, adapter in adapters.items():
|
||||
|
||||
def _run(adapter=adapter, name=name) -> None:
|
||||
try:
|
||||
adapter.run(
|
||||
lambda msg, _name=name: service.handle_inbound(
|
||||
msg, platform=_name
|
||||
),
|
||||
service.outbound_for(name),
|
||||
)
|
||||
except Exception as exc: # a dead transport must not kill the rest
|
||||
print(f"gateway {name} stopped: {exc}", file=sys.stderr)
|
||||
|
||||
thread = threading.Thread(target=_run, name=f"gateway-{name}", daemon=True)
|
||||
thread.start()
|
||||
threads.append(thread)
|
||||
endpoint = getattr(adapter, "ws_url", "") or getattr(adapter, "config_dir", "")
|
||||
print(f"gateway {name} listening ({endpoint}) (Ctrl-C to stop)")
|
||||
|
||||
try:
|
||||
adapter.run(service.handle_inbound, service.outbound)
|
||||
while any(thread.is_alive() for thread in threads):
|
||||
time.sleep(0.5)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
service.stop()
|
||||
adapter.close()
|
||||
for adapter in adapters.values():
|
||||
try:
|
||||
adapter.close()
|
||||
except Exception:
|
||||
pass
|
||||
for thread in threads:
|
||||
thread.join(timeout=2.0)
|
||||
return 0
|
||||
|
||||
|
||||
@@ -697,8 +816,12 @@ def main(argv: list[str] | None = None) -> int:
|
||||
help="replay mode: do not warm the decision engine",
|
||||
)
|
||||
|
||||
gw_p = sub.add_parser("gateway", help="run the messenger gateway (SimpleX)")
|
||||
gw_p.add_argument("--platform", default="simplex", help="gateway platform (default simplex)")
|
||||
gw_p = sub.add_parser("gateway", help="run the messenger gateway (SimpleX, LXMF)")
|
||||
gw_p.add_argument(
|
||||
"--platform",
|
||||
default="simplex",
|
||||
help="gateway platform(s): simplex, lxmf, a comma-separated list, or all (default simplex)",
|
||||
)
|
||||
gw_p.add_argument(
|
||||
"--dashboard",
|
||||
action="store_true",
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
"""LXMF (Reticulum) command-gateway adapter.
|
||||
|
||||
The gateway is the agent's **command** surface: allowlisted contacts send LXMF
|
||||
messages to the bot and their text is fed to the scheduler, whose reply is sent
|
||||
back. All the messaging *UX* surface (reading a contact's messages, composing on
|
||||
the user's behalf, showing a contact link) would live in a separate bridge
|
||||
service, never here — see AGENTS.md "gateway isolation".
|
||||
|
||||
This adapter is the policy layer over the neutral `LxmfDaemon` transport in
|
||||
`semif_agent.lxmf_transport`: it applies the allowlist, batches rapid messages,
|
||||
and hands authorized text to the scheduler. Unlike the SimpleX adapter there is
|
||||
no external daemon and no event loop — Reticulum runs in-process on its own
|
||||
threads, so batching uses a per-chat `threading.Timer`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import queue
|
||||
import threading
|
||||
|
||||
from semif_agent.lxmf_transport import LxmfDaemon
|
||||
|
||||
from .base import GatewayAdapter, InboundMessage, OutboundMessage
|
||||
|
||||
|
||||
class LxmfAdapter(GatewayAdapter):
|
||||
name = "lxmf"
|
||||
|
||||
def __init__(self, cfg: dict | None = None, trace=None):
|
||||
cfg = cfg or {}
|
||||
self.allowed_users = [str(u) for u in cfg.get("allowed_users", []) or []]
|
||||
self.allow_all_users = bool(cfg.get("allow_all_users", False))
|
||||
self.batch_delay = float(cfg.get("text_batch_delay", 0.8))
|
||||
config_dir = cfg.get("config_dir") or os.path.join(
|
||||
".runtime", "lxmf", "reticulum"
|
||||
)
|
||||
storage_path = cfg.get("storage_path") or os.path.join(
|
||||
".runtime", "lxmf", "router"
|
||||
)
|
||||
self.daemon = LxmfDaemon(
|
||||
config_dir=config_dir,
|
||||
storage_path=storage_path,
|
||||
display_name=cfg.get("display_name", "semif"),
|
||||
announce_interval=float(cfg.get("announce_interval", 3600)),
|
||||
stamp_cost=cfg.get("stamp_cost"),
|
||||
desired_method=cfg.get("desired_method", "direct"),
|
||||
propagation_node=cfg.get("propagation_node", ""),
|
||||
trace=trace,
|
||||
name=self.name,
|
||||
)
|
||||
self.config_dir = config_dir
|
||||
self.storage_path = storage_path
|
||||
self._buffers: dict[str, str] = {}
|
||||
self._buffered: dict[str, InboundMessage] = {}
|
||||
self._timers: dict[str, threading.Timer] = {}
|
||||
self._lock = threading.Lock()
|
||||
self._on_inbound = None
|
||||
|
||||
# ---- requirements ----
|
||||
|
||||
def check_requirements(self) -> tuple[bool, str | None]:
|
||||
return self.daemon.check_requirements()
|
||||
|
||||
# ---- authorization ----
|
||||
|
||||
def is_authorized(self, source_hash: str, display_name: str | None) -> bool:
|
||||
if self.allow_all_users:
|
||||
return True
|
||||
candidates = {str(source_hash)}
|
||||
if display_name:
|
||||
candidates.add(str(display_name))
|
||||
if not self.allowed_users:
|
||||
return False
|
||||
return any(user in candidates for user in self.allowed_users)
|
||||
|
||||
# ---- transport ----
|
||||
|
||||
def run(
|
||||
self,
|
||||
on_inbound,
|
||||
outbound: "queue.Queue[OutboundMessage | None]",
|
||||
) -> None:
|
||||
self._on_inbound = on_inbound
|
||||
|
||||
def _pump() -> None:
|
||||
# Translate the service's OutboundMessage queue onto the daemon's
|
||||
# (chat_id, text) queue without letting scheduler work touch the
|
||||
# Reticulum callback threads.
|
||||
while True:
|
||||
message = outbound.get()
|
||||
if message is None:
|
||||
self.daemon.enqueue(None)
|
||||
return
|
||||
self.daemon.enqueue(message.chat_id, message.text)
|
||||
|
||||
threading.Thread(
|
||||
target=_pump, name="lxmf-outbound-pump", daemon=True
|
||||
).start()
|
||||
self.daemon.run(self._on_item)
|
||||
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
timers = list(self._timers.values())
|
||||
self._timers.clear()
|
||||
for timer in timers:
|
||||
timer.cancel()
|
||||
self.daemon.close()
|
||||
|
||||
# ---- inbound ----
|
||||
|
||||
def _on_item(self, message: dict) -> None:
|
||||
source_hash = str(message.get("source_hash") or "")
|
||||
if not source_hash:
|
||||
return
|
||||
display_name = message.get("display_name")
|
||||
if not self.is_authorized(source_hash, display_name):
|
||||
self.daemon._event(
|
||||
"gateway_denied",
|
||||
contact_id=source_hash,
|
||||
display_name=display_name,
|
||||
)
|
||||
return
|
||||
inbound = InboundMessage(
|
||||
text=message.get("content") or "",
|
||||
chat_id=source_hash,
|
||||
chat_type="dm",
|
||||
contact_id=source_hash,
|
||||
display_name=display_name,
|
||||
raw=message.get("raw") or {},
|
||||
)
|
||||
self._schedule_flush(inbound)
|
||||
|
||||
def _schedule_flush(self, message: InboundMessage) -> None:
|
||||
chat = message.chat_id
|
||||
with self._lock:
|
||||
existing = self._buffers.get(chat)
|
||||
self._buffers[chat] = (
|
||||
f"{existing}\n{message.text}" if existing else message.text
|
||||
)
|
||||
self._buffered[chat] = message
|
||||
timer = self._timers.get(chat)
|
||||
if timer is not None:
|
||||
timer.cancel()
|
||||
timer = threading.Timer(self.batch_delay, self._flush, args=(chat,))
|
||||
timer.daemon = True
|
||||
self._timers[chat] = timer
|
||||
timer.start()
|
||||
|
||||
def _flush(self, chat: str) -> None:
|
||||
with self._lock:
|
||||
text = self._buffers.pop(chat, "")
|
||||
message = self._buffered.pop(chat, None)
|
||||
self._timers.pop(chat, None)
|
||||
if message is None or not text:
|
||||
return
|
||||
message.text = text
|
||||
self.daemon._event(
|
||||
"gateway_message",
|
||||
contact_id=message.contact_id,
|
||||
display_name=message.display_name,
|
||||
chars=len(text),
|
||||
)
|
||||
if self._on_inbound is not None:
|
||||
self._on_inbound(message)
|
||||
+143
-73
@@ -7,8 +7,14 @@ questions are routed back to the originating chat, and while one chat owns a
|
||||
`needs_input` pause that chat answers it. Another chat messaging during that
|
||||
pause is told to wait rather than silently abandoning the first chat's run.
|
||||
|
||||
Ownership: a request id maps to the chat that sent it. A run re-queued by the
|
||||
scheduler (updated request) mints a new id; the scheduler's
|
||||
One service can front several transports at once (SimpleX, LXMF, ...). Each
|
||||
adapter is addressed by its platform name, so a request source is
|
||||
`"<platform>:<chat_id>"`, the single pending-run guard is shared across
|
||||
platforms, and every reply is sent back through the queue of the platform that
|
||||
originated it.
|
||||
|
||||
Ownership: a request id maps to the `(platform, chat)` that sent it. A run
|
||||
re-queued by the scheduler (updated request) mints a new id; the scheduler's
|
||||
`on_request_requeued` hook copies the owner across so the completion still
|
||||
reaches the right chat.
|
||||
"""
|
||||
@@ -19,7 +25,7 @@ import queue
|
||||
import re
|
||||
import threading
|
||||
|
||||
from .base import GatewayAdapter, InboundMessage, OutboundMessage
|
||||
from .base import InboundMessage, OutboundMessage
|
||||
|
||||
_LEADING_RUN_ID = re.compile(r"^\[[0-9a-f]{6,}\]\s*")
|
||||
|
||||
@@ -45,6 +51,9 @@ _APPROVAL_ACTIONS = {
|
||||
"skip": False,
|
||||
}
|
||||
|
||||
#: An owner target is `(platform, chat_id)`.
|
||||
Target = tuple[str, str]
|
||||
|
||||
|
||||
def _strip_run_id(text: str) -> str:
|
||||
return _LEADING_RUN_ID.sub("", text or "")
|
||||
@@ -55,33 +64,76 @@ def _leading_run_id(text: str) -> str:
|
||||
return match.group(0)[1:-2] if match else ""
|
||||
|
||||
|
||||
def _normalize_adapters(adapters) -> dict:
|
||||
"""Accept a single adapter or a list/dict of them, keyed by platform name."""
|
||||
if isinstance(adapters, dict):
|
||||
return {str(name): adapter for name, adapter in adapters.items()}
|
||||
if hasattr(adapters, "name") and not isinstance(
|
||||
adapters, (list, tuple, set, frozenset)
|
||||
):
|
||||
return {adapters.name: adapters}
|
||||
result: dict = {}
|
||||
for adapter in adapters:
|
||||
result[adapter.name] = adapter
|
||||
return result
|
||||
|
||||
|
||||
class GatewayService:
|
||||
def __init__(
|
||||
self,
|
||||
scheduler,
|
||||
adapter: GatewayAdapter,
|
||||
adapters,
|
||||
config: dict | None = None,
|
||||
poll_interval: float = 1.0,
|
||||
):
|
||||
self.scheduler = scheduler
|
||||
self.adapter = adapter
|
||||
self.platform = adapter.name
|
||||
cfg = config or {}
|
||||
self.home_channel = str(cfg.get("home_channel", "") or "")
|
||||
self.reply_prefix = str(cfg.get("reply_prefix", "") or "")
|
||||
self.adapters = _normalize_adapters(adapters)
|
||||
self.platforms = list(self.adapters.keys())
|
||||
self.config = config or {}
|
||||
self.poll_interval = float(poll_interval)
|
||||
self.outbound: "queue.Queue[OutboundMessage | None]" = queue.Queue()
|
||||
self._owners: dict[str, str] = {}
|
||||
#: Per-platform outbound queue; the adapter drains its own.
|
||||
self.outbound: "dict[str, queue.Queue[OutboundMessage | None]]" = {
|
||||
platform: queue.Queue() for platform in self.platforms
|
||||
}
|
||||
self._platform_cfg: dict[str, dict] = {
|
||||
platform: self._config_for(platform) for platform in self.platforms
|
||||
}
|
||||
self._owners: dict[str, Target] = {}
|
||||
self._parents: dict[str, str] = {}
|
||||
self._pending_owner: str | None = None
|
||||
self._question_for_chat: dict[str, str] = {}
|
||||
self._repair_for_chat: dict[str, str] = {}
|
||||
self._approval_for_chat: dict[str, str] = {}
|
||||
self._pending_owner: Target | None = None
|
||||
self._question_for_chat: dict[Target, str] = {}
|
||||
self._repair_for_chat: dict[Target, str] = {}
|
||||
self._approval_for_chat: dict[Target, str] = {}
|
||||
self._surfaced: set[str] = set()
|
||||
self._route_lock = threading.Lock()
|
||||
self._stop = threading.Event()
|
||||
self._thread: threading.Thread | None = None
|
||||
|
||||
# ---- config ----
|
||||
|
||||
def _config_for(self, platform: str) -> dict:
|
||||
"""Per-platform settings from a nested (`{platform: {...}}`) or, for a
|
||||
single-adapter service, a flat config."""
|
||||
nested = self.config.get(platform)
|
||||
if isinstance(nested, dict):
|
||||
return nested
|
||||
if len(self.platforms) == 1:
|
||||
return self.config
|
||||
return {}
|
||||
|
||||
def outbound_for(self, platform: str) -> "queue.Queue[OutboundMessage | None]":
|
||||
return self.outbound[platform]
|
||||
|
||||
def _home_channel(self, platform: str) -> str:
|
||||
return str(self._platform_cfg.get(platform, {}).get("home_channel", "") or "")
|
||||
|
||||
def _fallback_target(self) -> Target | None:
|
||||
for platform in self.platforms:
|
||||
home = self._home_channel(platform)
|
||||
if home:
|
||||
return (platform, home)
|
||||
return None
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def start(self) -> None:
|
||||
@@ -93,7 +145,8 @@ class GatewayService:
|
||||
self._stop.set()
|
||||
if self._thread is not None:
|
||||
self._thread.join(timeout=2.0)
|
||||
self.outbound.put(None)
|
||||
for platform in self.platforms:
|
||||
self.outbound[platform].put(None)
|
||||
|
||||
def _poll_loop(self) -> None:
|
||||
while not self._stop.wait(self.poll_interval):
|
||||
@@ -106,60 +159,65 @@ class GatewayService:
|
||||
|
||||
# ---- routing ----
|
||||
|
||||
def source_for(self, chat_id: str) -> str:
|
||||
return f"{self.platform}:{chat_id}"
|
||||
def source_for(self, platform: str, chat_id: str) -> str:
|
||||
return f"{platform}:{chat_id}"
|
||||
|
||||
def _owner_from_source(self, source: str) -> str | None:
|
||||
prefix = f"{self.platform}:"
|
||||
if source.startswith(prefix):
|
||||
return source[len(prefix):]
|
||||
def _owner_from_source(self, source: str) -> Target | None:
|
||||
for platform in self.platforms:
|
||||
prefix = f"{platform}:"
|
||||
if source.startswith(prefix):
|
||||
return (platform, source[len(prefix):])
|
||||
return None
|
||||
|
||||
def handle_inbound(self, msg: InboundMessage) -> None:
|
||||
def handle_inbound(self, msg: InboundMessage, platform: str | None = None) -> None:
|
||||
"""Handle one authorized inbound command. Called by the adapter."""
|
||||
if platform is None:
|
||||
platform = self.platforms[0] if self.platforms else ""
|
||||
with self._route_lock:
|
||||
reply_to = msg.chat_id
|
||||
reply_to: Target = (platform, msg.chat_id)
|
||||
pending = self.scheduler.pending
|
||||
if pending is not None and self._pending_owner is None:
|
||||
self._pending_owner = self._owner_from_source(pending.request.source)
|
||||
if pending is not None and pending.request.source == self.source_for(msg.chat_id):
|
||||
if pending is not None and pending.request.source == self.source_for(
|
||||
platform, msg.chat_id
|
||||
):
|
||||
status, detail = self.scheduler.answer(msg.text)
|
||||
if self.scheduler.pending is None:
|
||||
self._pending_owner = None
|
||||
self._reply(reply_to, detail)
|
||||
elif pending is not None and self._pending_owner not in (None, msg.chat_id):
|
||||
self._reply(*reply_to, detail)
|
||||
elif pending is not None and self._pending_owner not in (None, reply_to):
|
||||
self._reply(
|
||||
reply_to,
|
||||
*reply_to,
|
||||
"I'm waiting for a reply in another conversation; please resend in a moment.",
|
||||
)
|
||||
elif msg.chat_id in self._question_for_chat:
|
||||
question_id = self._question_for_chat.pop(msg.chat_id)
|
||||
elif reply_to in self._question_for_chat:
|
||||
question_id = self._question_for_chat.pop(reply_to)
|
||||
status, detail = self.scheduler.answer_question(question_id, msg.text)
|
||||
self._surfaced.add(question_id)
|
||||
self._reply(reply_to, detail)
|
||||
elif msg.chat_id in self._repair_for_chat and msg.text.strip().lower() in _REPAIR_ACTIONS:
|
||||
offer_id = self._repair_for_chat.pop(msg.chat_id)
|
||||
self._reply(*reply_to, detail)
|
||||
elif reply_to in self._repair_for_chat and msg.text.strip().lower() in _REPAIR_ACTIONS:
|
||||
offer_id = self._repair_for_chat.pop(reply_to)
|
||||
action = _REPAIR_ACTIONS[msg.text.strip().lower()]
|
||||
status, detail = self.scheduler.resolve_repair(offer_id, action)
|
||||
self._surfaced.add(offer_id)
|
||||
self._reply(reply_to, detail)
|
||||
elif msg.chat_id in self._approval_for_chat and msg.text.strip().lower() in _APPROVAL_ACTIONS:
|
||||
approval_id = self._approval_for_chat.pop(msg.chat_id)
|
||||
self._reply(*reply_to, detail)
|
||||
elif reply_to in self._approval_for_chat and msg.text.strip().lower() in _APPROVAL_ACTIONS:
|
||||
approval_id = self._approval_for_chat.pop(reply_to)
|
||||
approved = _APPROVAL_ACTIONS[msg.text.strip().lower()]
|
||||
status, detail = self.scheduler.answer_approval(approval_id, approved)
|
||||
self._surfaced.add(approval_id)
|
||||
self._reply(reply_to, detail)
|
||||
self._reply(*reply_to, detail)
|
||||
else:
|
||||
status, detail, run_id = self.scheduler.submit_request(
|
||||
msg.text, source=self.source_for(msg.chat_id)
|
||||
msg.text, source=self.source_for(platform, msg.chat_id)
|
||||
)
|
||||
if run_id:
|
||||
self._owners[run_id] = msg.chat_id
|
||||
self._owners[run_id] = reply_to
|
||||
if status == "needs_input":
|
||||
self._pending_owner = msg.chat_id
|
||||
self._reply(reply_to, detail)
|
||||
self._pending_owner = reply_to
|
||||
self._reply(*reply_to, detail)
|
||||
self.drain()
|
||||
self.surface(origin=msg.chat_id)
|
||||
self.surface(origin=reply_to)
|
||||
|
||||
def drain(self) -> None:
|
||||
"""Run queued work and route each outcome back to its owner."""
|
||||
@@ -169,16 +227,15 @@ class GatewayService:
|
||||
break
|
||||
for status, detail in results:
|
||||
run_id = _leading_run_id(detail)
|
||||
chat = self._owner_of(run_id)
|
||||
owner = self._owner_of(run_id)
|
||||
text = _strip_run_id(detail)
|
||||
if status == "needs_input" and chat:
|
||||
self._pending_owner = chat
|
||||
if chat is None:
|
||||
chat = self.home_channel
|
||||
if chat:
|
||||
self._reply(chat, text)
|
||||
if status == "needs_input" and owner:
|
||||
self._pending_owner = owner
|
||||
target = owner or self._fallback_target()
|
||||
if target:
|
||||
self._reply(*target, text)
|
||||
|
||||
def surface(self, origin: str | None = None) -> None:
|
||||
def surface(self, origin: Target | None = None) -> None:
|
||||
"""Send any newly posted authoring questions / repair offers."""
|
||||
questions = self.scheduler.pending_questions()
|
||||
live_ids = {q["id"] for q in questions}
|
||||
@@ -189,11 +246,11 @@ class GatewayService:
|
||||
if item["id"] in self._surfaced:
|
||||
continue
|
||||
self._surfaced.add(item["id"])
|
||||
chat = self._owner_of(item["run_id"]) or origin or self.home_channel
|
||||
if chat:
|
||||
self._question_for_chat[chat] = item["id"]
|
||||
target = self._resolve_target(item.get("run_id"), origin)
|
||||
if target:
|
||||
self._question_for_chat[target] = item["id"]
|
||||
self._reply(
|
||||
chat,
|
||||
*target,
|
||||
f"(authoring {item['category']}.{item['skill']}) {item['question']}",
|
||||
)
|
||||
|
||||
@@ -206,11 +263,11 @@ class GatewayService:
|
||||
if offer["id"] in self._surfaced:
|
||||
continue
|
||||
self._surfaced.add(offer["id"])
|
||||
chat = self._owner_of(offer["run_id"]) or origin or self.home_channel
|
||||
if chat:
|
||||
self._repair_for_chat[chat] = offer["id"]
|
||||
target = self._resolve_target(offer.get("run_id"), origin)
|
||||
if target:
|
||||
self._repair_for_chat[target] = offer["id"]
|
||||
self._reply(
|
||||
chat,
|
||||
*target,
|
||||
(
|
||||
f"{offer['category']}.{offer['skill']} failed: "
|
||||
f"{offer['failure'][:200]}\nReply retry / repair / ask / no."
|
||||
@@ -226,26 +283,26 @@ class GatewayService:
|
||||
if item["id"] in self._surfaced:
|
||||
continue
|
||||
self._surfaced.add(item["id"])
|
||||
chat = self._owner_of(item["run_id"]) or origin or self.home_channel
|
||||
if chat:
|
||||
self._approval_for_chat[chat] = item["id"]
|
||||
target = (
|
||||
target = self._resolve_target(item.get("run_id"), origin)
|
||||
if target:
|
||||
self._approval_for_chat[target] = item["id"]
|
||||
label = (
|
||||
item["category"]
|
||||
if item["kind"] == "category"
|
||||
else f"{item['category']}.{item['skill']}"
|
||||
)
|
||||
self._reply(
|
||||
chat,
|
||||
*target,
|
||||
(
|
||||
f"Approve creating new {item['kind']} {target}: "
|
||||
f"Approve creating new {item['kind']} {label}: "
|
||||
f"{item['description']}\nReply yes / no."
|
||||
),
|
||||
)
|
||||
|
||||
for fired in self.scheduler.timers.drain():
|
||||
chat = self._owner_of(fired.run_id) or origin or self.home_channel
|
||||
if chat:
|
||||
self._reply(chat, fired.message)
|
||||
target = self._resolve_target(fired.run_id, origin)
|
||||
if target:
|
||||
self._reply(*target, fired.message)
|
||||
|
||||
# ---- scheduler requeue hook (called under the scheduler lock) ----
|
||||
|
||||
@@ -256,7 +313,7 @@ class GatewayService:
|
||||
self._owners[child_id] = owner
|
||||
self._parents[child_id] = parent_id
|
||||
|
||||
def _owner_of(self, run_id: str) -> str | None:
|
||||
def _owner_of(self, run_id: str) -> Target | None:
|
||||
seen = 0
|
||||
while run_id and seen < 16:
|
||||
owner = self._owners.get(run_id)
|
||||
@@ -266,11 +323,24 @@ class GatewayService:
|
||||
seen += 1
|
||||
return None
|
||||
|
||||
def _resolve_target(self, run_id: str | None, origin: Target | None) -> Target | None:
|
||||
owner = self._owner_of(run_id or "")
|
||||
if owner:
|
||||
return owner
|
||||
if origin:
|
||||
return origin
|
||||
return self._fallback_target()
|
||||
|
||||
# ---- outbound ----
|
||||
|
||||
def _reply(self, chat_id: str, text: str) -> None:
|
||||
def _reply(self, platform: str, chat_id: str, text: str) -> None:
|
||||
text = _strip_run_id(text)
|
||||
if self.reply_prefix:
|
||||
text = f"{self.reply_prefix}{text}"
|
||||
if text:
|
||||
self.outbound.put(OutboundMessage(chat_id=str(chat_id), text=text))
|
||||
prefix = str(self._platform_cfg.get(platform, {}).get("reply_prefix", "") or "")
|
||||
if prefix:
|
||||
text = f"{prefix}{text}"
|
||||
if not text:
|
||||
return
|
||||
target_queue = self.outbound.get(platform)
|
||||
if target_queue is None:
|
||||
return
|
||||
target_queue.put(OutboundMessage(chat_id=str(chat_id), text=text))
|
||||
@@ -0,0 +1,362 @@
|
||||
"""Low-level LXMF (Reticulum) transport (neutral).
|
||||
|
||||
This module owns the LXMF/Reticulum mechanics only: standing up a Reticulum
|
||||
instance and an `LXMRouter`, loading (or creating) the delivery identity,
|
||||
announcing reachability, normalizing inbound messages into plain dicts, and
|
||||
draining an outbound send queue. It knows nothing about the SemIf scheduler,
|
||||
the command gateway, or any bridge — a front end builds on top of it.
|
||||
|
||||
`RNS` and `LXMF` are imported lazily inside the methods that need them so
|
||||
importing this module stays stdlib-only on a machine without the optional
|
||||
`lxmf` dependency (the gateway refuses to start with an install hint instead).
|
||||
|
||||
Unlike the SimpleX transport there is no external daemon binary: Reticulum and
|
||||
the LXMF router run in-process. The bot's reachable address is its LXMF
|
||||
delivery destination hash (32 hex chars); the identity is persisted under the
|
||||
router storage path so the address is stable across restarts.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import queue
|
||||
import threading
|
||||
import time
|
||||
from typing import Any, Callable
|
||||
|
||||
#: One received direct message, normalized into a plain dict.
|
||||
InboundDict = dict[str, Any]
|
||||
#: Callback invoked for each received message.
|
||||
MessageHandler = Callable[[InboundDict], None]
|
||||
#: Zero-argument callback invoked once the router is ready to receive.
|
||||
ConnectedHandler = Callable[[], None]
|
||||
|
||||
|
||||
def _as_text(value: Any) -> str:
|
||||
"""Best-effort UTF-8 text for a `str`/`bytes`/`None` LXMF field."""
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, bytes):
|
||||
return value.decode("utf-8", "replace")
|
||||
if isinstance(value, str):
|
||||
return value
|
||||
return str(value)
|
||||
|
||||
|
||||
def normalize_message(message: Any) -> InboundDict:
|
||||
"""Normalize one LXMF message object into a plain dict.
|
||||
|
||||
Tolerates both a real `LXMessage` (bytes `content`/`title`, `source_hash`,
|
||||
`get_source()`) and a lightweight fake, so the policy layer is testable
|
||||
without the optional `lxmf` package installed.
|
||||
"""
|
||||
raw_source_hash = getattr(message, "source_hash", b"") or b""
|
||||
if isinstance(raw_source_hash, (bytes, bytearray)):
|
||||
source_hash = bytes(raw_source_hash).hex()
|
||||
else:
|
||||
source_hash = str(raw_source_hash)
|
||||
|
||||
content_fn = getattr(message, "content_as_string", None)
|
||||
if callable(content_fn):
|
||||
try:
|
||||
content = _as_text(content_fn())
|
||||
except Exception:
|
||||
content = ""
|
||||
else:
|
||||
content = _as_text(getattr(message, "content", None))
|
||||
|
||||
title_fn = getattr(message, "title_as_string", None)
|
||||
if callable(title_fn):
|
||||
try:
|
||||
title = _as_text(title_fn())
|
||||
except Exception:
|
||||
title = ""
|
||||
else:
|
||||
title = _as_text(getattr(message, "title", None))
|
||||
|
||||
display_name = ""
|
||||
source = None
|
||||
get_source = getattr(message, "get_source", None)
|
||||
if callable(get_source):
|
||||
try:
|
||||
source = get_source()
|
||||
except Exception:
|
||||
source = None
|
||||
if source is None:
|
||||
source = getattr(message, "source", None)
|
||||
if source is not None:
|
||||
display_name = _as_text(getattr(source, "display_name", None))
|
||||
|
||||
return {
|
||||
"source_hash": source_hash,
|
||||
"display_name": display_name or None,
|
||||
"title": title,
|
||||
"content": content,
|
||||
"timestamp": getattr(message, "timestamp", None),
|
||||
"raw": message,
|
||||
}
|
||||
|
||||
|
||||
class LxmfDaemon:
|
||||
"""One in-process Reticulum instance + LXMF router.
|
||||
|
||||
`run(on_message)` blocks, announcing the delivery destination periodically
|
||||
and delivering each received message to `on_message`. `enqueue(chat_id,
|
||||
text)` queues an outbound send (a `None` chat_id is the stop sentinel),
|
||||
drained by an internal pump thread. `address` is the bot's LXMF address.
|
||||
|
||||
Beware: the identity is persisted under `storage_path`; a single profile
|
||||
must not be shared by two processes.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
config_dir: str,
|
||||
storage_path: str,
|
||||
display_name: str | None = "semif",
|
||||
announce_interval: float = 3600.0,
|
||||
stamp_cost: int | None = None,
|
||||
desired_method: str = "direct",
|
||||
propagation_node: str = "",
|
||||
on_connected: ConnectedHandler | None = None,
|
||||
trace=None,
|
||||
name: str = "lxmf",
|
||||
):
|
||||
self.config_dir = str(config_dir)
|
||||
self.storage_path = str(storage_path)
|
||||
self.display_name = str(display_name) if display_name else None
|
||||
self.announce_interval = float(announce_interval or 0.0)
|
||||
self.stamp_cost = int(stamp_cost) if stamp_cost is not None else None
|
||||
self.desired_method = str(desired_method or "direct").lower()
|
||||
self.propagation_node = str(propagation_node or "")
|
||||
self.on_connected = on_connected
|
||||
self.trace = trace
|
||||
self.name = name
|
||||
self.identity_path = os.path.join(self.storage_path, "identity")
|
||||
self._router = None
|
||||
self._reticulum = None
|
||||
self._destination = None
|
||||
self._address = ""
|
||||
self._outbound: "queue.Queue[tuple[str, str] | None]" = queue.Queue()
|
||||
self._stop = threading.Event()
|
||||
self._on_message: MessageHandler | None = None
|
||||
|
||||
# ---- requirements ----
|
||||
|
||||
def check_requirements(self) -> tuple[bool, str | None]:
|
||||
if not self.config_dir:
|
||||
return False, "lxmf config_dir is required"
|
||||
try:
|
||||
import RNS # noqa: F401
|
||||
import LXMF # noqa: F401
|
||||
except ImportError:
|
||||
return False, "pip install lxmf"
|
||||
return True, None
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
@property
|
||||
def address(self) -> str:
|
||||
"""The bot's LXMF delivery address (32 hex chars), or "" before ready."""
|
||||
return self._address
|
||||
|
||||
def ensure_reticulum(self):
|
||||
"""Initialize the Reticulum instance on the calling thread.
|
||||
|
||||
Reticulum installs process signal handlers, which only works on the
|
||||
main thread. Call this once from the main thread before spawning the
|
||||
transport thread so the in-process router can coexist with other
|
||||
gateway adapters; `run()` reuses the instance when it already exists.
|
||||
"""
|
||||
import RNS
|
||||
|
||||
existing = RNS.Reticulum.get_instance()
|
||||
if existing is not None:
|
||||
self._reticulum = existing
|
||||
return existing
|
||||
os.makedirs(self.config_dir, exist_ok=True)
|
||||
self._reticulum = RNS.Reticulum(configdir=self.config_dir)
|
||||
return self._reticulum
|
||||
|
||||
def prepare(self, on_message: MessageHandler | None = None):
|
||||
"""Main-thread-sensitive setup: Reticulum instance + LXMF router.
|
||||
|
||||
Both `RNS.Reticulum` and `LXMF.LXMRouter` install process signal
|
||||
handlers, which only works on the main thread. `run_gateway` calls this
|
||||
once on the main thread before the transport threads start; `run()`
|
||||
calls it again (idempotent) when used standalone.
|
||||
"""
|
||||
if self._router is not None:
|
||||
if on_message is not None:
|
||||
self._on_message = on_message
|
||||
return self._router
|
||||
import LXMF
|
||||
import RNS
|
||||
|
||||
if on_message is not None:
|
||||
self._on_message = on_message
|
||||
os.makedirs(self.config_dir, exist_ok=True)
|
||||
os.makedirs(self.storage_path, exist_ok=True)
|
||||
|
||||
self.ensure_reticulum()
|
||||
self._router = LXMF.LXMRouter(storagepath=self.storage_path)
|
||||
identity = self._load_identity(RNS)
|
||||
self._destination = self._router.register_delivery_identity(
|
||||
identity, display_name=self.display_name, stamp_cost=self.stamp_cost
|
||||
)
|
||||
if self._destination is None:
|
||||
raise RuntimeError("could not register LXMF delivery identity")
|
||||
self._address = RNS.hexrep(self._destination.hash, delimit=False)
|
||||
self._router.register_delivery_callback(self._handle)
|
||||
if self.propagation_node:
|
||||
try:
|
||||
self._router.set_outbound_propagation_node(
|
||||
bytes.fromhex(self.propagation_node)
|
||||
)
|
||||
except Exception as exc:
|
||||
self._event("lxmf_propagation_error", message=str(exc)[:300])
|
||||
self._event("lxmf_ready", address=self._address)
|
||||
return self._router
|
||||
|
||||
def run(self, on_message: MessageHandler) -> None:
|
||||
self.prepare(on_message)
|
||||
|
||||
threading.Thread(
|
||||
target=self._pump, name="lxmf-outbound-pump", daemon=True
|
||||
).start()
|
||||
self._announce()
|
||||
if self.on_connected is not None:
|
||||
try:
|
||||
self.on_connected()
|
||||
except Exception as exc:
|
||||
self._event(
|
||||
"lxmf_error", phase="on_connected", message=str(exc)[:300]
|
||||
)
|
||||
|
||||
while not self._stop.wait(self._announce_wait()):
|
||||
self._announce()
|
||||
|
||||
def enqueue(self, chat_id: str | None, text: str = "") -> None:
|
||||
"""Queue an outbound send. `chat_id=None` is the stop sentinel."""
|
||||
if chat_id is None:
|
||||
self._outbound.put(None)
|
||||
else:
|
||||
self._outbound.put((str(chat_id), text))
|
||||
|
||||
def close(self) -> None:
|
||||
self._stop.set()
|
||||
self._outbound.put(None)
|
||||
try:
|
||||
import RNS
|
||||
|
||||
RNS.Reticulum.exit_handler()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ---- identity ----
|
||||
|
||||
def _load_identity(self, RNS):
|
||||
os.makedirs(self.storage_path, exist_ok=True)
|
||||
if os.path.isfile(self.identity_path):
|
||||
identity = RNS.Identity.from_file(self.identity_path)
|
||||
if identity is not None:
|
||||
return identity
|
||||
identity = RNS.Identity()
|
||||
try:
|
||||
identity.to_file(self.identity_path)
|
||||
os.chmod(self.identity_path, 0o600)
|
||||
except Exception as exc:
|
||||
self._event("lxmf_identity_save_failed", message=str(exc)[:300])
|
||||
return identity
|
||||
|
||||
# ---- announce ----
|
||||
|
||||
def _announce_wait(self) -> float:
|
||||
if self.announce_interval <= 0:
|
||||
return 3600.0
|
||||
return self.announce_interval
|
||||
|
||||
def _announce(self) -> None:
|
||||
if self._router is None or self._destination is None:
|
||||
return
|
||||
try:
|
||||
self._router.announce(self._destination.hash)
|
||||
self._event("lxmf_announced", address=self._address)
|
||||
except Exception as exc:
|
||||
self._event("lxmf_error", phase="announce", message=str(exc)[:300])
|
||||
|
||||
# ---- inbound ----
|
||||
|
||||
def _handle(self, message: Any) -> None:
|
||||
try:
|
||||
normalized = normalize_message(message)
|
||||
except Exception as exc:
|
||||
self._event("lxmf_parse_error", message=str(exc)[:300])
|
||||
return
|
||||
self._event(
|
||||
"lxmf_message",
|
||||
source=normalized.get("source_hash"),
|
||||
chars=len(normalized.get("content") or ""),
|
||||
)
|
||||
if self._on_message is not None:
|
||||
self._on_message(normalized)
|
||||
|
||||
# ---- outbound ----
|
||||
|
||||
def _pump(self) -> None:
|
||||
while True:
|
||||
item = self._outbound.get()
|
||||
if item is None:
|
||||
return
|
||||
chat_id, text = item
|
||||
try:
|
||||
self.send(chat_id, text)
|
||||
except Exception as exc:
|
||||
self._event(
|
||||
"lxmf_send_failed", contact=chat_id, message=str(exc)[:300]
|
||||
)
|
||||
|
||||
def send(self, destination_hex: str, text: str, timeout: float = 15.0) -> None:
|
||||
"""Send `text` to an LXMF address (destination hash hex).
|
||||
|
||||
Recalls the peer identity from the network; when the path is not yet
|
||||
known it requests it and waits briefly. Raises (never silently drops)
|
||||
when the destination cannot be resolved — a reply must be real.
|
||||
"""
|
||||
if self._router is None or self._destination is None:
|
||||
raise RuntimeError("LXMF router is not ready")
|
||||
import LXMF
|
||||
import RNS
|
||||
|
||||
try:
|
||||
dest_hash = bytes.fromhex(str(destination_hex).strip())
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"invalid LXMF address {destination_hex!r}") from exc
|
||||
|
||||
if not RNS.Transport.has_path(dest_hash):
|
||||
RNS.Transport.request_path(dest_hash)
|
||||
deadline = time.time() + timeout
|
||||
while not RNS.Transport.has_path(dest_hash) and time.time() < deadline:
|
||||
time.sleep(0.1)
|
||||
identity = RNS.Identity.recall(dest_hash)
|
||||
if identity is None:
|
||||
raise RuntimeError(f"unknown LXMF destination {destination_hex}")
|
||||
|
||||
dest = RNS.Destination(
|
||||
identity, RNS.Destination.OUT, RNS.Destination.SINGLE, "lxmf", "delivery"
|
||||
)
|
||||
method = (
|
||||
LXMF.LXMessage.OPPORTUNISTIC
|
||||
if self.desired_method == "opportunistic"
|
||||
else LXMF.LXMessage.DIRECT
|
||||
)
|
||||
message = LXMF.LXMessage(dest, self._destination, text, desired_method=method)
|
||||
self._router.handle_outbound(message)
|
||||
self._event("lxmf_sent", contact=destination_hex, chars=len(text))
|
||||
|
||||
# ---- tracing ----
|
||||
|
||||
def _event(self, kind: str, **fields) -> None:
|
||||
if self.trace is not None:
|
||||
self.trace.append(kind, "?", **fields)
|
||||
Reference in new issue
Block a user