add LXMF gateway

This commit is contained in:
gabby committed 2026-10-05 23:07:57 +00:00
1 parent 1d9730bfcb
commit 49f67575cf
11 files changed
+1135 -162

No files matched your search

+96 -51
View File
@@ -186,11 +186,16 @@ gateway/ messenger COMMAND intake/reply — and nothing else. base.py:
GatewayService maps chats onto the single-slot scheduler GatewayService maps chats onto the single-slot scheduler
(submit_request, owner maps, pending-run ownership, queue (submit_request, owner maps, pending-run ownership, queue
drain, authoring questions/repairs routed back to the origin drain, authoring questions/repairs routed back to the origin
chat). simplex.py: SimplexAdapter — command simplex-chat daemon chat); it is platform-aware and fronts one or more adapters at
over its JSON WebSocket API (lazy `websockets`, allowlist, once, keyed by platform name (source `<platform>:<chat>`, the
batching, structured `/_send`). Run with `python -m single pending-run guard shared across platforms). simplex.py:
semif_agent.cli gateway [--dashboard]`; config under SimplexAdapter — command simplex-chat daemon over its JSON
`gateway.simplex`. The gateway MUST NOT read history, show/create WebSocket API (lazy `websockets`, allowlist, batching,
structured `/_send`). lxmf.py: LxmfAdapter — LXMF/Reticulum
(lazy `lxmf`), in-process, allowlist + batching. Run with
`python -m semif_agent.cli gateway [--platform simplex,lxmf|all]
[--dashboard]`; config under `gateway.simplex` /
`gateway.lxmf`. The gateway MUST NOT read history, show/create
invite links, or compose messages — see "gateway isolation" invite links, or compose messages — see "gateway isolation"
below. below.
bridges/ standalone third-party API bridges (SimpleX first, plus the bridges/ standalone third-party API bridges (SimpleX first, plus the
@@ -217,6 +222,12 @@ simplex_ws.py neutral SimpleX daemon protocol shared by the command gateway
`/_show_address`/`/_address`, contact-request accept, contact `/_show_address`/`/_address`, contact-request accept, contact
list + chat previews/history). Knows nothing about the list + chat previews/history). Knows nothing about the
scheduler or either front end. scheduler or either front end.
lxmf_transport.py
neutral LXMF (Reticulum) transport: one in-process Reticulum
instance + LXMF router, persisted delivery identity, announce
loop, inbound normalization, outbound send queue. Lazy `RNS`/
`LXMF` imports keep the module stdlib-only. Knows nothing about
the scheduler or the gateway.
``` ```
## Run / verify ## Run / verify
@@ -409,16 +420,20 @@ CLI, unit tests (24) + integration tests (2).
dashboard gain the ability to inspect a skill's generated code body dashboard gain the ability to inspect a skill's generated code body
(read-only view of `data/skills/<category>/<name>/` and its trace) so the (read-only view of `data/skills/<category>/<name>/` and its trace) so the
author can audit what was generated. author can audit what was generated.
- **Messenger gateway (SimpleX first)** (Sep 2026): `python -m semif_agent.cli - **Messenger gateway (SimpleX first, then LXMF)** (Sep 2026; LXMF Oct 2026):
gateway` runs a dedicated process that connects to the local `simplex-chat` `python -m semif_agent.cli gateway` runs a dedicated process that connects to
daemon over its JSON WebSocket API and feeds authorized DM text through the one or more transports and feeds authorized DM text through the normal
normal gate/score/queue/dispatch pipeline; results, authoring questions, and gate/score/queue/dispatch pipeline; results, authoring questions, and repair
repair offers are sent back to the originating chat. `gateway/base.py` is the offers are sent back to the originating chat. `gateway/base.py` is the
transport contract (`GatewayAdapter`, `InboundMessage`, `OutboundMessage`), transport contract (`GatewayAdapter`, `InboundMessage`, `OutboundMessage`),
`gateway/service.py` the scheduler glue (single execution slot, owner maps, `gateway/service.py` the platform-aware scheduler glue (single execution slot,
pending-run ownership, queue drain), `gateway/simplex.py` the SimpleX adapter `(platform, chat)` owner maps, pending-run ownership shared across platforms,
(lazy `websockets`, default-deny allowlist by contactId/display name, queue drain), `gateway/simplex.py` the SimpleX adapter (lazy `websockets`,
rapid-message batching, structured `/_send`). DMs only for the first cut; default-deny allowlist by contactId/display name, rapid-message batching,
structured `/_send`), and `gateway/lxmf.py` the LXMF/Reticulum adapter (lazy
`lxmf`, in-process via the neutral `semif_agent/lxmf_transport.py`, allowlist
by LXMF address, `threading.Timer` batching). All adapters share one process
and one scheduler (`--platform simplex,lxmf|all`). DMs only for the first cut;
groups/attachments/reactions are future work. See "### gateway (messenger groups/attachments/reactions are future work. See "### gateway (messenger
intake)". intake)".
- **Bridge services (SimpleX first)** (Sep 2026): messaging *UX* — invite links, - **Bridge services (SimpleX first)** (Sep 2026): messaging *UX* — invite links,
@@ -818,22 +833,26 @@ CLI, unit tests (24) + integration tests (2).
### gateway (messenger intake) ### gateway (messenger intake)
- **Run mode.** `python -m semif_agent.cli gateway [--platform simplex] - **Run mode.** `python -m semif_agent.cli gateway [--platform simplex,lxmf|all]
[--dashboard]` builds the normal scheduler (engine lazy) and runs the [--dashboard]` builds the normal scheduler (engine lazy) and runs the enabled
configured `gateway.simplex` adapter in the foreground. `--dashboard` adapters in the foreground. `--platform` takes a comma-separated list or
co-serves the browser UI from a daemon thread. Config lives under `all`; default is `simplex`. **All adapters share one process and one
`gateway.simplex` in `config.json`; `enabled` defaults false. On a scheduler** (never run two gateway processes over one skill store) — each
bootstrap-provisioned host `scripts/bootstrap.sh` renders and enables the gets its own transport thread but they route through a single
`semif-simplex.service` bot daemon (pinned `simplex-chat` in **bot mode**, platform-aware `GatewayService`. `--dashboard` co-serves the browser UI from
profile under `.runtime/simplex/`, port from `simplex_chat.port`) and the a daemon thread. Config lives under `gateway.<platform>` in `config.json`;
`semif-gateway.service` agent process, so the gateway runs across `enabled` defaults false. On a bootstrap-provisioned host
logout/reboot. The gateway is its own process — the REPL and the gateway are `scripts/bootstrap.sh` renders and enables the `semif-simplex.service` bot
independent front ends onto the same on-disk logs/registry (do not run two daemon (pinned `simplex-chat` in **bot mode**, profile under
scheduler processes over one skill store concurrently). **On connect the `.runtime/simplex/`, port from `simplex_chat.port`) and the
gateway prints the bot's own SimpleX contact link once** (show-or-create via `semif-gateway.service` agent process (unit runs `gateway --platform all`),
the daemon it already owns, from the CLI, `_gateway_address_callback`) so a so the gateway runs across logout/reboot. The gateway is its own process —
human can reach it without running `scripts/simplex-address.py` — the operator the REPL and the gateway are independent front ends onto the same on-disk
front end prints it; the command adapter itself gains no address surface. logs/registry. **On connect the gateway prints each bot's own address once**
(the SimpleX contact link via the daemon it already owns,
`_gateway_address_callback`; the LXMF address via `_lxmf_address_callback`) so
a human can reach it without running a separate script — the operator front
end prints it; the command adapter itself gains no address surface.
- **Bot address / v7 relay gotcha.** The daemon must NOT run with `--headless` - **Bot address / v7 relay gotcha.** The daemon must NOT run with `--headless`
or `--relay`: in SimpleX Chat v7 `--headless` means "chat relay" (requires or `--relay`: in SimpleX Chat v7 `--headless` means "chat relay" (requires
`--relay`) and yields a *relay* address, not a user contact address. Run bot `--relay`) and yields a *relay* address, not a user contact address. Run bot
@@ -850,8 +869,9 @@ CLI, unit tests (24) + integration tests (2).
outbound_queue)` blocks, delivering `InboundMessage`s and draining a stdlib outbound_queue)` blocks, delivering `InboundMessage`s and draining a stdlib
`queue.Queue[OutboundMessage | None]`. Scheduler work is synchronous and can `queue.Queue[OutboundMessage | None]`. Scheduler work is synchronous and can
block on the decision engine, so the adapter bridges it off its event loop block on the decision engine, so the adapter bridges it off its event loop
(`asyncio.to_thread`) and puts replies on the queue. A second platform means (`asyncio.to_thread`) and puts replies on the queue. A new platform means a
a new adapter subclass; the service is unchanged. new adapter subclass plus a `_build_gateway_adapter` branch and a config
block; the platform-aware service routes it unchanged.
- **SimpleX adapter** (`gateway/simplex.py`): connects to the local - **SimpleX adapter** (`gateway/simplex.py`): connects to the local
`simplex-chat` daemon at `gateway.simplex.ws_url` (default port 5226, pinning `simplex-chat` daemon at `gateway.simplex.ws_url` (default port 5226, pinning
`simplex_chat.port`), XML-JSON WebSocket protocol `simplex_chat.port`), XML-JSON WebSocket protocol
@@ -869,20 +889,38 @@ CLI, unit tests (24) + integration tests (2).
attachments, reactions, and typing are out of scope for this cut. The wire attachments, reactions, and typing are out of scope for this cut. The wire
protocol itself lives in the neutral `semif_agent/simplex_ws.py` protocol itself lives in the neutral `semif_agent/simplex_ws.py`
(`SimplexDaemon`); this adapter adds only the allowlist and batching on top. (`SimplexDaemon`); this adapter adds only the allowlist and batching on top.
- **LXMF adapter** (`gateway/lxmf.py`): the Reticulum-based command transport.
Unlike SimpleX there is **no external daemon** — Reticulum and the LXMF router
run in-process (`semif_agent/lxmf_transport.py`, `LxmfDaemon`). `lxmf` (and
`rns`) are **lazy-imported**; `check_requirements()` returns a `pip install
lxmf` hint and the gateway refuses to start without it. The bot's reachable
address is its LXMF delivery destination hash (32 hex chars); the identity is
persisted under `gateway.lxmf.storage_path` (default `.runtime/lxmf/router`)
so the address is stable across restarts. Default-deny allowlist matches the
peer's LXMF address or a best-effort display name (`allowed_users`);
`allow_all_users` is the dev escape hatch. Rapid messages are batched per chat
(`text_batch_delay`) with a `threading.Timer` (no event loop).
`desired_method` is `direct` (reliable link) or `opportunistic` (single
packet); an optional `propagation_node` enables store-and-forward. **`RNS.
Reticulum` and `LXMF.LXMRouter` install process signal handlers, which only
work on the main thread** — `run_gateway` calls `daemon.prepare()` on the main
thread before the transport threads start, and `run()` reuses it.
- **Scheduler glue** (`gateway/service.py`): inbound text → - **Scheduler glue** (`gateway/service.py`): inbound text →
`Scheduler.submit_request(text, source=f"simplex:<chat_id>")`; the returned `Scheduler.submit_request(text, source=f"{platform}:{chat_id}")`; the returned
request id maps to the chat (`owners`), and `Scheduler.on_request_requeued` request id maps to the `(platform, chat)` (`owners`), and
(a scheduler hook, default `None`) copies that ownership across an updated `Scheduler.on_request_requeued` (a scheduler hook, default `None`) copies that
request so its completion still routes home. A `needs_input` pause sets ownership across an updated request so its completion still routes home. A
`pending_owner` from the pending run's source; the same chat's next message `needs_input` pause sets `pending_owner` from the pending run's source; the
goes straight to `Scheduler.answer` (no score/navigation). A *different* same chat's next message goes straight to `Scheduler.answer` (no
chat during another chat's pause is told to wait — the single-slot scheduler score/navigation). A *different* chat — **including a chat on another
must not silently abandon the first chat's run. A background poll calls platform** — during that pause is told to wait: the single-slot scheduler must
not silently abandon the first chat's run, and one service fronts all
adapters so the guard spans them. A background poll calls
`Scheduler.run_queue()` (routing each `[run_id] summary` to its owner) and `Scheduler.run_queue()` (routing each `[run_id] summary` to its owner) and
surfaces newly posted authoring questions / repair offers (`defer_questions surfaces newly posted authoring questions / repair offers (`defer_questions
= True`; the service routes them by `run_id` → origin, falling back to = True`; the service routes them by `run_id` → `(platform, chat)`, falling
`home_channel`); a chat's plain reply answers the question or picks the back to that platform's `home_channel`); a chat's plain reply answers the
repair action (`retry`/`repair`/`ask`/`no`). question or picks the repair action (`retry`/`repair`/`ask`/`no`).
- **Gateway isolation (non-negotiable).** The gateway exists only to take - **Gateway isolation (non-negotiable).** The gateway exists only to take
commands and send replies. It MUST NOT read a contact's history, show/create commands and send replies. It MUST NOT read a contact's history, show/create
invite links, or compose messages on the user's behalf: no `observer`, no invite links, or compose messages on the user's behalf: no `observer`, no
@@ -898,20 +936,27 @@ CLI, unit tests (24) + integration tests (2).
`/_show_address` / `/_address` (`SimplexDaemon.request_address`, thread-safe `/_show_address` / `/_address` (`SimplexDaemon.request_address`, thread-safe
via `run_coroutine_threadsafe`). It carries no policy: no allowlist, no via `run_coroutine_threadsafe`). It carries no policy: no allowlist, no
scheduler, no HTTP. scheduler, no HTTP.
- **Tests.** `tests/test_gateway.py` (stdlib): adapter allowlist/auth, - **Tests.** `tests/test_gateway.py` (stdlib): SimpleX adapter allowlist/auth,
structured send command, batching (real `asyncio`), and `GatewayService` structured send command, batching (real `asyncio`), LXMF adapter
routing against a real `Scheduler` (lazy engine, unreachable LLM). allowlist/auth and batching (a `threading.Timer`), cross-platform pending-run
`tests/test_simplex_ws.py` covers the neutral protocol layer (parse shapes, guard and per-platform reply routing, and `GatewayService` routing against a
accept ids, corrId round-trips, address show/create). `tests/test_bridges.py` real `Scheduler` (lazy engine, unreachable LLM).
`tests/test_lxmf_transport.py` covers the neutral LXMF transport's
missing-dep contract, default paths, and `normalize_message` (no real `lxmf`
needed). `tests/test_simplex_ws.py` covers the neutral protocol layer (parse
shapes, accept ids, corrId round-trips, address show/create).
`tests/test_bridges.py`
exercises `SimplexBridge` over a real loopback server (peek/pop, recipient exercises `SimplexBridge` over a real loopback server (peek/pop, recipient
resolution, outbound routing, token/body validation, `/address` success/503/502, resolution, outbound routing, token/body validation, `/address` success/503/502,
daemon close on stop, catalog/`describe_bridges()`). daemon close on stop, catalog/`describe_bridges()`).
`tests/test_seed_skills.py` hermetically tests every `tests/test_seed_skills.py` hermetically tests every
`seeds/<category>/<name>/` package, including `simplex.next_message` and `seeds/<category>/<name>/` package, including `simplex.next_message` and
`simplex.connect_link`. The live `websockets` transport against a real daemon `simplex.connect_link`. The live `websockets` transport against a real daemon
is a live-daemon integration concern. and the live LXMF transport against a real Reticulum network are
- **Deps.** `websockets` is pinned in `requirements/staging.txt` (staging live-integration concerns.
only); the core stays stdlib-only. - **Deps.** `websockets` and `lxmf`/`rns` are pinned in
`requirements/staging.txt` (staging only); both are lazy-imported and the core
stays stdlib-only.
### bridges (third-party API services) ### bridges (third-party API services)
+18 -1
View File
@@ -130,8 +130,9 @@
} }
}, },
"gateway": { "gateway": {
"_comment": "Messenger COMMAND intake — and nothing else. `python -m semif_agent.cli gateway` connects to the command simplex-chat daemon (`simplex_chat.port`) over its JSON WebSocket API and feeds authorized DM text through the normal gate/score/queue/dispatch pipeline; results, authoring questions, and repair offers are sent back to the originating chat. It must never read a contact's history, show/create invite links, or compose on the user's behalf — that is the independent bridge services' job (`bridges`). Requires the optional `websockets` package (lazy-imported; the gateway refuses to start without it). allowed_users entries match either a numeric contactId or a display name; default is deny-all unless allow_all_users is set. home_channel receives messages whose origin chat is unknown (e.g. a background repair offer). text_batch_delay concatenates rapid-fire messages from one contact. Groups/attachments are not supported in this first cut.", "_comment": "Messenger COMMAND intake — and nothing else. `python -m semif_agent.cli gateway` runs one or more platforms (`--platform simplex,lxmf` or `all`) in a SINGLE process sharing one scheduler/skill store — never run two gateway processes over one store. Each platform feeds authorized DM text through the normal gate/score/queue/dispatch pipeline; results, authoring questions, and repair offers are sent back to the originating chat. It must never read a contact's history, show/create invite links, or compose on the user's behalf — that is the independent bridge services' job (`bridges`). home_channel receives messages whose origin chat is unknown (e.g. a background repair offer). reply_prefix is prepended to every reply. text_batch_delay concatenates rapid-fire messages from one contact.",
"simplex": { "simplex": {
"_comment": "SimpleX command adapter. Connects to the command simplex-chat daemon (`simplex_chat.port`) over its JSON WebSocket API. Requires the optional `websockets` package (lazy-imported; the gateway refuses to start without it). allowed_users entries match either a numeric contactId or a display name; default is deny-all unless allow_all_users is set. Groups/attachments are not supported.",
"enabled": true, "enabled": true,
"ws_url": "ws://127.0.0.1:5226", "ws_url": "ws://127.0.0.1:5226",
"allowed_users": [], "allowed_users": [],
@@ -141,6 +142,22 @@
"reply_prefix": "", "reply_prefix": "",
"text_batch_delay": 0.8, "text_batch_delay": 0.8,
"reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2} "reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2}
},
"lxmf": {
"_comment": "LXMF (Reticulum) command adapter. Runs IN-PROCESS — there is no external daemon; `pip install lxmf` provides the transport (optional, lazy-imported; the gateway refuses to start with an install hint). The bot's reachable address is its LXMF delivery destination hash (32 hex chars), printed on connect. config_dir/storage_path hold Reticulum's config and the persisted identity under .runtime/lxmf/ so the address is stable across restarts (empty = the .runtime/lxmf defaults). allowed_users entries match the peer's LXMF address (32 hex chars) or a best-effort display name; default is deny-all unless allow_all_users is set. desired_method is 'direct' (reliable link) or 'opportunistic' (single packet). propagation_node is an optional LXMF propagation-node address (hex) for store-and-forward.",
"enabled": false,
"allowed_users": [],
"allow_all_users": false,
"display_name": "semif",
"announce_interval": 3600,
"stamp_cost": 8,
"desired_method": "direct",
"propagation_node": "",
"config_dir": "",
"storage_path": "",
"home_channel": "",
"reply_prefix": "",
"text_batch_delay": 0.8
} }
}, },
"dashboard": {"port": 8765, "host": "127.0.0.1"} "dashboard": {"port": 8765, "host": "127.0.0.1"}
+5
View File
@@ -16,3 +16,8 @@ pytest
# Messaging gateway transport (SimpleX adapter). Optional: lazy-imported, the # Messaging gateway transport (SimpleX adapter). Optional: lazy-imported, the
# gateway refuses to start without it. Not needed by the decision engine. # gateway refuses to start without it. Not needed by the decision engine.
websockets==15.0.1 websockets==15.0.1
# LXMF (Reticulum) gateway transport. Optional: lazy-imported, the gateway
# refuses to start without it. Runs in-process — there is no daemon binary.
# rns pulls cryptography + pyserial transitively (resolved by pip).
lxmf==1.2.0
rns==1.5.7
+14 -1
View File
@@ -178,7 +178,7 @@ echo "== pins: semif @ $SEMIF_REF | gguf sha256 ${GGUF_SHA256:0:12}… | simplex
echo "== llm $LLM_URL (local, model $LLM_MODEL) | codegen $CODEGEN_URL" echo "== llm $LLM_URL (local, model $LLM_MODEL) | codegen $CODEGEN_URL"
echo "== runtime tree: $RUNTIME" echo "== runtime tree: $RUNTIME"
mkdir -p "$RUNTIME" "$MODELS" "$HF_CACHE" "$TOOLDIR" "$SIMPLEX_DB" "$RUNTIME/simplex-forward" "$UNITS" "$USER_UNITS" mkdir -p "$RUNTIME" "$MODELS" "$HF_CACHE" "$TOOLDIR" "$SIMPLEX_DB" "$RUNTIME/simplex-forward" "$RUNTIME/lxmf" "$UNITS" "$USER_UNITS"
# --- stage 0: system prereqs + linger ---------------------------------------- # --- stage 0: system prereqs + linger ----------------------------------------
PKGS=(ca-certificates curl git rsync build-essential python3-dev python3-venv pkg-config cmake util-linux) PKGS=(ca-certificates curl git rsync build-essential python3-dev python3-venv pkg-config cmake util-linux)
@@ -471,6 +471,19 @@ SimpleX command gateway (commands only):
- The gateway takes commands and replies. It never reads history, shows invite - The gateway takes commands and replies. It never reads history, shows invite
links, or composes messages: that is the forwarding bridge's job. links, or composes messages: that is the forwarding bridge's job.
LXMF command gateway (commands only):
- Runs IN-PROCESS inside the same 'semif-gateway' service (no separate daemon);
the transport is installed from requirements/staging.txt (lxmf + rns).
Enable it in config.json with gateway.lxmf.enabled = true, then restart the
gateway (the unit runs `gateway --platform all`, so SimpleX + LXMF share one
scheduler).
- Its LXMF address (32 hex chars) is printed on connect:
journalctl --user -u semif-gateway -f
Add that address as a contact in an LXMF client (Sideband, MeshChatX, ...)
and put it in gateway.lxmf.allowed_users (discover a sender from a
'gateway_denied' trace event). With an empty allowlist it rejects everyone —
the safe default.
SimpleX forwarding bridge (messaging UX for skills): SimpleX forwarding bridge (messaging UX for skills):
- Runs as 'semif-simplex-forward' (a second bot daemon/profile, port $SIMPLEX_FORWARD_PORT) - Runs as 'semif-simplex-forward' (a second bot daemon/profile, port $SIMPLEX_FORWARD_PORT)
and 'semif-bridge' (the standalone bridge API). Its contact address is printed and 'semif-bridge' (the standalone bridge API). Its contact address is printed
+2 -2
View File
@@ -1,5 +1,5 @@
[Unit] [Unit]
Description=SemIf agent messenger gateway (SimpleX) Description=SemIf agent messenger gateway (SimpleX, LXMF)
After=network-online.target semif-simplex.service After=network-online.target semif-simplex.service
Wants=network-online.target semif-simplex.service Wants=network-online.target semif-simplex.service
@@ -8,7 +8,7 @@ Type=simple
WorkingDirectory=@REPO@ WorkingDirectory=@REPO@
Environment=HF_HOME=@REPO@/.runtime/hf Environment=HF_HOME=@REPO@/.runtime/hf
Environment=PYTHONUNBUFFERED=1 Environment=PYTHONUNBUFFERED=1
ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli gateway ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli gateway --platform all
Restart=always Restart=always
RestartSec=5 RestartSec=5
StandardOutput=journal StandardOutput=journal
+148 -25
View File
@@ -589,44 +589,137 @@ def _gateway_address_callback(adapter):
return _announce 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( def run_gateway(
scheduler: Scheduler, scheduler: Scheduler,
config: dict, config: dict,
platform: str = "simplex", platform: str = "simplex",
serve_dashboard: bool = False, serve_dashboard: bool = False,
) -> int: ) -> int:
"""Run the messenger gateway in the foreground (SimpleX first).""" """Run one or more messenger gateways in the foreground.
cfg = (config.get("gateway", {}) or {}).get(platform, {}) or {}
if not cfg.get("enabled", False): All enabled adapters share a single scheduler/process (see AGENTS.md: never
print(f"gateway.{platform} is not enabled in config") 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 return 1
if platform == "simplex": # Reticulum installs process signal handlers, which only works on the main
from .gateway.simplex import SimplexAdapter # 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) if not adapters:
# Print the bot's own contact link once, on connect, so the operator can print("no gateway platforms enabled/available")
# 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}")
return 1 return 1
from .gateway.service import GatewayService from .gateway.service import GatewayService
scheduler.defer_questions = True 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 scheduler.on_request_requeued = service.on_request_requeued
service.start() service.start()
if serve_dashboard: if serve_dashboard:
import threading
from .dashboard import serve from .dashboard import serve
dash_cfg = config.get("dashboard", {}) or {} dash_cfg = config.get("dashboard", {}) or {}
@@ -640,14 +733,40 @@ def run_gateway(
daemon=True, daemon=True,
).start() ).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: try:
adapter.run(service.handle_inbound, service.outbound) while any(thread.is_alive() for thread in threads):
time.sleep(0.5)
except KeyboardInterrupt: except KeyboardInterrupt:
pass pass
finally: finally:
service.stop() 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 return 0
@@ -697,8 +816,12 @@ def main(argv: list[str] | None = None) -> int:
help="replay mode: do not warm the decision engine", help="replay mode: do not warm the decision engine",
) )
gw_p = sub.add_parser("gateway", help="run the messenger gateway (SimpleX)") gw_p = sub.add_parser("gateway", help="run the messenger gateway (SimpleX, LXMF)")
gw_p.add_argument("--platform", default="simplex", help="gateway platform (default simplex)") 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( gw_p.add_argument(
"--dashboard", "--dashboard",
action="store_true", action="store_true",
+165
View File
@@ -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
View File
@@ -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 `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. 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 One service can front several transports at once (SimpleX, LXMF, ...). Each
scheduler (updated request) mints a new id; the scheduler's 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 `on_request_requeued` hook copies the owner across so the completion still
reaches the right chat. reaches the right chat.
""" """
@@ -19,7 +25,7 @@ import queue
import re import re
import threading import threading
from .base import GatewayAdapter, InboundMessage, OutboundMessage from .base import InboundMessage, OutboundMessage
_LEADING_RUN_ID = re.compile(r"^\[[0-9a-f]{6,}\]\s*") _LEADING_RUN_ID = re.compile(r"^\[[0-9a-f]{6,}\]\s*")
@@ -45,6 +51,9 @@ _APPROVAL_ACTIONS = {
"skip": False, "skip": False,
} }
#: An owner target is `(platform, chat_id)`.
Target = tuple[str, str]
def _strip_run_id(text: str) -> str: def _strip_run_id(text: str) -> str:
return _LEADING_RUN_ID.sub("", text or "") 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 "" 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: class GatewayService:
def __init__( def __init__(
self, self,
scheduler, scheduler,
adapter: GatewayAdapter, adapters,
config: dict | None = None, config: dict | None = None,
poll_interval: float = 1.0, poll_interval: float = 1.0,
): ):
self.scheduler = scheduler self.scheduler = scheduler
self.adapter = adapter self.adapters = _normalize_adapters(adapters)
self.platform = adapter.name self.platforms = list(self.adapters.keys())
cfg = config or {} self.config = config or {}
self.home_channel = str(cfg.get("home_channel", "") or "")
self.reply_prefix = str(cfg.get("reply_prefix", "") or "")
self.poll_interval = float(poll_interval) self.poll_interval = float(poll_interval)
self.outbound: "queue.Queue[OutboundMessage | None]" = queue.Queue() #: Per-platform outbound queue; the adapter drains its own.
self._owners: dict[str, str] = {} 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._parents: dict[str, str] = {}
self._pending_owner: str | None = None self._pending_owner: Target | None = None
self._question_for_chat: dict[str, str] = {} self._question_for_chat: dict[Target, str] = {}
self._repair_for_chat: dict[str, str] = {} self._repair_for_chat: dict[Target, str] = {}
self._approval_for_chat: dict[str, str] = {} self._approval_for_chat: dict[Target, str] = {}
self._surfaced: set[str] = set() self._surfaced: set[str] = set()
self._route_lock = threading.Lock() self._route_lock = threading.Lock()
self._stop = threading.Event() self._stop = threading.Event()
self._thread: threading.Thread | None = None 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 ---- # ---- lifecycle ----
def start(self) -> None: def start(self) -> None:
@@ -93,7 +145,8 @@ class GatewayService:
self._stop.set() self._stop.set()
if self._thread is not None: if self._thread is not None:
self._thread.join(timeout=2.0) 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: def _poll_loop(self) -> None:
while not self._stop.wait(self.poll_interval): while not self._stop.wait(self.poll_interval):
@@ -106,60 +159,65 @@ class GatewayService:
# ---- routing ---- # ---- routing ----
def source_for(self, chat_id: str) -> str: def source_for(self, platform: str, chat_id: str) -> str:
return f"{self.platform}:{chat_id}" return f"{platform}:{chat_id}"
def _owner_from_source(self, source: str) -> str | None: def _owner_from_source(self, source: str) -> Target | None:
prefix = f"{self.platform}:" for platform in self.platforms:
if source.startswith(prefix): prefix = f"{platform}:"
return source[len(prefix):] if source.startswith(prefix):
return (platform, source[len(prefix):])
return None 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.""" """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: with self._route_lock:
reply_to = msg.chat_id reply_to: Target = (platform, msg.chat_id)
pending = self.scheduler.pending pending = self.scheduler.pending
if pending is not None and self._pending_owner is None: if pending is not None and self._pending_owner is None:
self._pending_owner = self._owner_from_source(pending.request.source) 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) status, detail = self.scheduler.answer(msg.text)
if self.scheduler.pending is None: if self.scheduler.pending is None:
self._pending_owner = None self._pending_owner = None
self._reply(reply_to, detail) self._reply(*reply_to, detail)
elif pending is not None and self._pending_owner not in (None, msg.chat_id): elif pending is not None and self._pending_owner not in (None, reply_to):
self._reply( self._reply(
reply_to, *reply_to,
"I'm waiting for a reply in another conversation; please resend in a moment.", "I'm waiting for a reply in another conversation; please resend in a moment.",
) )
elif msg.chat_id in self._question_for_chat: elif reply_to in self._question_for_chat:
question_id = self._question_for_chat.pop(msg.chat_id) question_id = self._question_for_chat.pop(reply_to)
status, detail = self.scheduler.answer_question(question_id, msg.text) status, detail = self.scheduler.answer_question(question_id, msg.text)
self._surfaced.add(question_id) self._surfaced.add(question_id)
self._reply(reply_to, detail) self._reply(*reply_to, detail)
elif msg.chat_id in self._repair_for_chat and msg.text.strip().lower() in _REPAIR_ACTIONS: elif reply_to in self._repair_for_chat and msg.text.strip().lower() in _REPAIR_ACTIONS:
offer_id = self._repair_for_chat.pop(msg.chat_id) offer_id = self._repair_for_chat.pop(reply_to)
action = _REPAIR_ACTIONS[msg.text.strip().lower()] action = _REPAIR_ACTIONS[msg.text.strip().lower()]
status, detail = self.scheduler.resolve_repair(offer_id, action) status, detail = self.scheduler.resolve_repair(offer_id, action)
self._surfaced.add(offer_id) self._surfaced.add(offer_id)
self._reply(reply_to, detail) self._reply(*reply_to, detail)
elif msg.chat_id in self._approval_for_chat and msg.text.strip().lower() in _APPROVAL_ACTIONS: elif reply_to in self._approval_for_chat and msg.text.strip().lower() in _APPROVAL_ACTIONS:
approval_id = self._approval_for_chat.pop(msg.chat_id) approval_id = self._approval_for_chat.pop(reply_to)
approved = _APPROVAL_ACTIONS[msg.text.strip().lower()] approved = _APPROVAL_ACTIONS[msg.text.strip().lower()]
status, detail = self.scheduler.answer_approval(approval_id, approved) status, detail = self.scheduler.answer_approval(approval_id, approved)
self._surfaced.add(approval_id) self._surfaced.add(approval_id)
self._reply(reply_to, detail) self._reply(*reply_to, detail)
else: else:
status, detail, run_id = self.scheduler.submit_request( 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: if run_id:
self._owners[run_id] = msg.chat_id self._owners[run_id] = reply_to
if status == "needs_input": if status == "needs_input":
self._pending_owner = msg.chat_id self._pending_owner = reply_to
self._reply(reply_to, detail) self._reply(*reply_to, detail)
self.drain() self.drain()
self.surface(origin=msg.chat_id) self.surface(origin=reply_to)
def drain(self) -> None: def drain(self) -> None:
"""Run queued work and route each outcome back to its owner.""" """Run queued work and route each outcome back to its owner."""
@@ -169,16 +227,15 @@ class GatewayService:
break break
for status, detail in results: for status, detail in results:
run_id = _leading_run_id(detail) run_id = _leading_run_id(detail)
chat = self._owner_of(run_id) owner = self._owner_of(run_id)
text = _strip_run_id(detail) text = _strip_run_id(detail)
if status == "needs_input" and chat: if status == "needs_input" and owner:
self._pending_owner = chat self._pending_owner = owner
if chat is None: target = owner or self._fallback_target()
chat = self.home_channel if target:
if chat: self._reply(*target, text)
self._reply(chat, 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.""" """Send any newly posted authoring questions / repair offers."""
questions = self.scheduler.pending_questions() questions = self.scheduler.pending_questions()
live_ids = {q["id"] for q in questions} live_ids = {q["id"] for q in questions}
@@ -189,11 +246,11 @@ class GatewayService:
if item["id"] in self._surfaced: if item["id"] in self._surfaced:
continue continue
self._surfaced.add(item["id"]) self._surfaced.add(item["id"])
chat = self._owner_of(item["run_id"]) or origin or self.home_channel target = self._resolve_target(item.get("run_id"), origin)
if chat: if target:
self._question_for_chat[chat] = item["id"] self._question_for_chat[target] = item["id"]
self._reply( self._reply(
chat, *target,
f"(authoring {item['category']}.{item['skill']}) {item['question']}", f"(authoring {item['category']}.{item['skill']}) {item['question']}",
) )
@@ -206,11 +263,11 @@ class GatewayService:
if offer["id"] in self._surfaced: if offer["id"] in self._surfaced:
continue continue
self._surfaced.add(offer["id"]) self._surfaced.add(offer["id"])
chat = self._owner_of(offer["run_id"]) or origin or self.home_channel target = self._resolve_target(offer.get("run_id"), origin)
if chat: if target:
self._repair_for_chat[chat] = offer["id"] self._repair_for_chat[target] = offer["id"]
self._reply( self._reply(
chat, *target,
( (
f"{offer['category']}.{offer['skill']} failed: " f"{offer['category']}.{offer['skill']} failed: "
f"{offer['failure'][:200]}\nReply retry / repair / ask / no." f"{offer['failure'][:200]}\nReply retry / repair / ask / no."
@@ -226,26 +283,26 @@ class GatewayService:
if item["id"] in self._surfaced: if item["id"] in self._surfaced:
continue continue
self._surfaced.add(item["id"]) self._surfaced.add(item["id"])
chat = self._owner_of(item["run_id"]) or origin or self.home_channel target = self._resolve_target(item.get("run_id"), origin)
if chat: if target:
self._approval_for_chat[chat] = item["id"] self._approval_for_chat[target] = item["id"]
target = ( label = (
item["category"] item["category"]
if item["kind"] == "category" if item["kind"] == "category"
else f"{item['category']}.{item['skill']}" else f"{item['category']}.{item['skill']}"
) )
self._reply( self._reply(
chat, *target,
( (
f"Approve creating new {item['kind']} {target}: " f"Approve creating new {item['kind']} {label}: "
f"{item['description']}\nReply yes / no." f"{item['description']}\nReply yes / no."
), ),
) )
for fired in self.scheduler.timers.drain(): for fired in self.scheduler.timers.drain():
chat = self._owner_of(fired.run_id) or origin or self.home_channel target = self._resolve_target(fired.run_id, origin)
if chat: if target:
self._reply(chat, fired.message) self._reply(*target, fired.message)
# ---- scheduler requeue hook (called under the scheduler lock) ---- # ---- scheduler requeue hook (called under the scheduler lock) ----
@@ -256,7 +313,7 @@ class GatewayService:
self._owners[child_id] = owner self._owners[child_id] = owner
self._parents[child_id] = parent_id 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 seen = 0
while run_id and seen < 16: while run_id and seen < 16:
owner = self._owners.get(run_id) owner = self._owners.get(run_id)
@@ -266,11 +323,24 @@ class GatewayService:
seen += 1 seen += 1
return None 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 ---- # ---- 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) text = _strip_run_id(text)
if self.reply_prefix: prefix = str(self._platform_cfg.get(platform, {}).get("reply_prefix", "") or "")
text = f"{self.reply_prefix}{text}" if prefix:
if text: text = f"{prefix}{text}"
self.outbound.put(OutboundMessage(chat_id=str(chat_id), text=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))
+362
View File
@@ -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)
+86 -9
View File
@@ -10,6 +10,7 @@ live-daemon integration concern, not a unit test.
import asyncio import asyncio
import json import json
import time
from semif_agent.cli import _gateway_address_callback from semif_agent.cli import _gateway_address_callback
from semif_agent.decisions import Request from semif_agent.decisions import Request
@@ -42,10 +43,12 @@ def build_scheduler(tmp_path):
def drain_outbound(service) -> list[str]: def drain_outbound(service) -> list[str]:
texts = [] texts = []
while not service.outbound.empty(): for platform in service.platforms:
item = service.outbound.get_nowait() outbound = service.outbound[platform]
if item is not None: while not outbound.empty():
texts.append(item.text) item = outbound.get_nowait()
if item is not None:
texts.append(item.text)
return texts return texts
@@ -213,9 +216,9 @@ def test_service_refuses_other_chat_during_pending(tmp_path):
def test_service_requeue_hook_carries_ownership(tmp_path): def test_service_requeue_hook_carries_ownership(tmp_path):
scheduler = build_scheduler(tmp_path) scheduler = build_scheduler(tmp_path)
service = build_service(scheduler) service = build_service(scheduler)
service._owners["parent"] = "4" service._owners["parent"] = ("simplex", "4")
service.on_request_requeued("parent", "child") service.on_request_requeued("parent", "child")
assert service._owner_of("child") == "4" assert service._owner_of("child") == ("simplex", "4")
def test_service_drain_routes_queued_run_to_owner(tmp_path): def test_service_drain_routes_queued_run_to_owner(tmp_path):
@@ -223,7 +226,7 @@ def test_service_drain_routes_queued_run_to_owner(tmp_path):
service = build_service(scheduler) service = build_service(scheduler)
request = Request("queued work", source="simplex:4") request = Request("queued work", source="simplex:4")
scheduler.queue.push(request, 0.5) scheduler.queue.push(request, 0.5)
service._owners[request.id] = "4" service._owners[request.id] = ("simplex", "4")
service.drain() service.drain()
outbound = drain_outbound(service) outbound = drain_outbound(service)
@@ -245,7 +248,7 @@ def test_service_answered_question_routes_back(tmp_path):
question="Which account?", question="Which account?",
) )
) )
service._owners["r1"] = "4" service._owners["r1"] = ("simplex", "4")
service.surface() service.surface()
assert any("Which account?" in text for text in drain_outbound(service)) assert any("Which account?" in text for text in drain_outbound(service))
@@ -266,7 +269,7 @@ def test_service_surfaces_and_resolves_approval(tmp_path):
description="Follow a package.", description="Follow a package.",
) )
) )
service._owners["r1"] = "4" service._owners["r1"] = ("simplex", "4")
service.surface() service.surface()
assert any( assert any(
"Approve creating new skill tracking.track_live" in text "Approve creating new skill tracking.track_live" in text
@@ -276,3 +279,77 @@ def test_service_surfaces_and_resolves_approval(tmp_path):
service.handle_inbound(InboundMessage(text="yes", chat_id="4", contact_id="4")) service.handle_inbound(InboundMessage(text="yes", chat_id="4", contact_id="4"))
assert scheduler.pending_approvals() == [] assert scheduler.pending_approvals() == []
assert any("approved" in text for text in drain_outbound(service)) assert any("approved" in text for text in drain_outbound(service))
# ---- LXMF adapter ----
def test_lxmf_default_deny_and_allowlist():
from semif_agent.gateway.lxmf import LxmfAdapter
assert LxmfAdapter({}).is_authorized("a" * 32, "alice") is False
assert LxmfAdapter({"allowed_users": ["a" * 32]}).is_authorized("a" * 32, "alice") is True
assert LxmfAdapter({"allowed_users": ["alice"]}).is_authorized("a" * 32, "alice") is True
assert LxmfAdapter({"allowed_users": ["bob"]}).is_authorized("a" * 32, "alice") is False
assert LxmfAdapter({"allow_all_users": True}).is_authorized("a" * 32, None) is True
def test_lxmf_batching_concatenates_rapid_messages():
from semif_agent.gateway.lxmf import LxmfAdapter
adapter = LxmfAdapter({"allow_all_users": True, "text_batch_delay": 0.05})
seen: list = []
adapter._on_inbound = seen.append
for text in ("one", "two"):
adapter._on_item(
{"source_hash": "ab" * 16, "content": text, "display_name": None}
)
time.sleep(0.2)
assert len(seen) == 1
assert "one" in seen[0].text and "two" in seen[0].text
def test_lxmf_denies_unknown_sender_without_dispatch():
from semif_agent.gateway.lxmf import LxmfAdapter
adapter = LxmfAdapter({})
seen: list = []
adapter._on_inbound = seen.append
adapter._on_item({"source_hash": "cd" * 16, "content": "hi"})
time.sleep(0.1)
assert seen == []
# ---- service: multiple platforms ----
class FakeLxmfAdapter:
name = "lxmf"
def build_multi_service(scheduler):
return GatewayService(
scheduler, [FakeAdapter(), FakeLxmfAdapter()], config={}
)
def test_service_refuses_other_platform_during_pending(tmp_path):
scheduler = build_scheduler(tmp_path)
service = build_multi_service(scheduler)
scheduler._run_skill(need_input_skill([]), Request("track it", source="simplex:4"))
question = scheduler.pending.question
service.handle_inbound(
InboundMessage(text="hello", chat_id="abc", contact_id="abc"), platform="lxmf"
)
assert scheduler.pending is not None
assert scheduler.pending.question == question
assert any("another conversation" in text for text in drain_outbound(service))
def test_service_reply_routes_to_owning_platform(tmp_path):
scheduler = build_scheduler(tmp_path)
service = build_multi_service(scheduler)
service.handle_inbound(
InboundMessage(text="hi", chat_id="abc", contact_id="abc"), platform="lxmf"
)
assert not service.outbound["lxmf"].empty()
assert service.outbound["simplex"].empty()
+96
View File
@@ -0,0 +1,96 @@
"""Pure-stdlib tests for the neutral LXMF (Reticulum) transport.
`lxmf`/`rns` are optional and lazy-imported, so these tests exercise the
stdlib-only helpers and the missing-dependency contract without the real
package (and without touching a real Reticulum network). The live transport is
a live-integration concern.
"""
from semif_agent.gateway.lxmf import LxmfAdapter
from semif_agent.lxmf_transport import LxmfDaemon, normalize_message
# ---- requirements ----
def test_requires_config_dir():
ok, hint = LxmfDaemon(config_dir="", storage_path="x").check_requirements()
assert ok is False
assert "config_dir" in hint
def test_adapter_check_requirements_never_raises():
# Either lxmf is installed (True) or an install hint is returned (False);
# the adapter must never raise on a machine without the optional dep.
ok, hint = LxmfAdapter({}).check_requirements()
assert isinstance(ok, bool)
if not ok:
assert "lxmf" in hint
# ---- adapter defaults ----
def test_adapter_uses_runtime_lxmf_paths_by_default():
adapter = LxmfAdapter({})
assert adapter.config_dir.endswith(".runtime/lxmf/reticulum")
assert adapter.storage_path.endswith(".runtime/lxmf/router")
assert adapter.daemon.address == ""
# ---- normalization ----
def test_normalize_message_tolerates_fakes():
class _Src:
display_name = "alice"
class _Msg:
source_hash = bytes.fromhex("ab" * 16)
content = b"hello"
title = b"subj"
timestamp = 123.0
def get_source(self):
return _Src()
normalized = normalize_message(_Msg())
assert normalized["source_hash"] == "ab" * 16
assert normalized["content"] == "hello"
assert normalized["title"] == "subj"
assert normalized["display_name"] == "alice"
assert normalized["timestamp"] == 123.0
def test_normalize_message_prefers_as_string_helpers():
class _Msg:
source_hash = b"\x01\x02"
content = b"raw"
title = b"rawtitle"
def content_as_string(self):
return "decoded content"
def title_as_string(self):
return "decoded title"
normalized = normalize_message(_Msg())
assert normalized["source_hash"] == "0102"
assert normalized["content"] == "decoded content"
assert normalized["title"] == "decoded title"
assert normalized["display_name"] is None
def test_normalize_message_handles_none_content():
class _Msg:
source_hash = b""
content = None
title = None
def content_as_string(self):
return None
def title_as_string(self):
return None
normalized = normalize_message(_Msg())
assert normalized["source_hash"] == ""
assert normalized["content"] == ""
assert normalized["title"] == ""