diff --git a/AGENTS.md b/AGENTS.md index 2794e3c..32cd418 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -210,7 +210,12 @@ gateway/ messenger COMMAND intake/reply — and nothing else. base.py: speech-to-text + text-to-speech) over the neutral `semif_agent/voice_transport.py`; no remote peer and no allowlist (physical mic access is the authorization), a single - configured `chat_id`, replies spoken back. Run with + configured `chat_id`, replies spoken back. humanize.py: + Humanizer — optional LLM cleanup of a result line (generation, + never a decision; grounded prompt + always falls back to the + raw text), gated by `gateway.humanize` / a per-platform + `humanize` override, reusing the scheduler's `llm` client with + a short per-call timeout. Run with `python -m semif_agent.cli gateway [--platform simplex,lxmf,voice|all] [--dashboard]`; config under `gateway.simplex` / `gateway.lxmf` / `gateway.voice`. The @@ -1041,6 +1046,25 @@ CLI, unit tests (24) + integration tests (2). = True`; the service routes them by `run_id` → `(platform, chat)`, falling back to that platform's `home_channel`); a chat's plain reply answers the question or picks the repair action (`retry`/`repair`/`ask`/`no`). +- **Optional result cleanup** (`gateway/humanize.py`): a gateway-only + presentation layer that rewrites a completed skill's result line from the + scheduler's deterministic `: — ` into one + grounded, friendly sentence. It is **generation, never a decision** — the + success/failure verdict and routing are already settled by SemIf and the + runner, and the rewrite is never fed back into assessment, tracing, or the + decision log (the runner and REPL keep the raw deterministic summary). The + prompt forbids adding/inferring/dropping facts, and `Humanizer.humanize` + always falls back to the original text on any error, timeout, empty/refusal + reply, or runaway length, so a cleanup failure never swallows a real result. + It reuses the scheduler's `llm` client (endpoint/model/sampler configured + once) with a short per-call `timeout` (a new optional `chat()` argument) so a + slow cleanup cannot hold the gateway poll loop for the authoring budget. Off + by default: `gateway.humanize` (`enabled`/`timeout`/`max_tokens`/`max_chars`) + sets the global default and a per-platform `gateway..humanize` + bool/`{enabled}` overrides it. Only `kind == "result"` lines are touched + (questions, repair/approval notices, and status chatter pass through); like + `result_only`, an enabled platform unwraps the result detail before cleaning. + `_resolve_platforms` skips the reserved `humanize` key. - **Gateway isolation (non-negotiable).** The gateway exists only to take 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 @@ -1061,6 +1085,10 @@ CLI, unit tests (24) + integration tests (2). allowlist/auth and batching (a `threading.Timer`), cross-platform pending-run guard and per-platform reply routing, and `GatewayService` routing against a real `Scheduler` (lazy engine, unreachable LLM). + `tests/test_humanize.py` covers the optional result cleanup with an injected + fake `llm` client (rewrite, quote/whitespace normalization, fallback on + error/empty/refusal/runaway, disabled passthrough, and the global + + per-platform gateway enable/disable wiring). `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 diff --git a/config.example.json b/config.example.json index 6318b3e..06e24ea 100644 --- a/config.example.json +++ b/config.example.json @@ -131,6 +131,13 @@ }, "gateway": { "_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.", + "humanize": { + "_comment": "Optional LLM cleanup of a skill's result line for chat replies. Off by default. When enabled, a completed result is unwrapped from the scheduler's `: — ` bookkeeping and rewritten by the scheduler's `llm` client into one grounded, friendly sentence; it never decides success/failure and always falls back to the raw result on any error. `timeout`/`max_tokens`/`max_chars` bound the auxiliary call (a slow cleanup must not hold the gateway). A platform turns it on/off with its own `humanize` key (bool or `{enabled: ...}`), overriding this global default; `timeout`/`max_tokens`/`max_chars` are global. Only result lines are cleaned — questions, repair/approval notices, and status chatter are untouched.", + "enabled": false, + "timeout": 20.0, + "max_tokens": 200, + "max_chars": 600 + }, "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, diff --git a/semif_agent/cli.py b/semif_agent/cli.py index 3d13f7f..1bc41f5 100644 --- a/semif_agent/cli.py +++ b/semif_agent/cli.py @@ -718,7 +718,8 @@ def _resolve_platforms(requested: str, gateway_cfg: dict) -> list[str]: `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). + can report them). Non-platform keys (`_comment`, the global `humanize` + defaults block) are skipped. """ requested = (requested or "simplex").strip() if requested in ("all", "*"): @@ -727,6 +728,7 @@ def _resolve_platforms(requested: str, gateway_cfg: dict) -> list[str]: for name, block in (gateway_cfg or {}).items() if isinstance(block, dict) and not name.startswith("_") + and name != "humanize" and block.get("enabled", False) ] return [name.strip() for name in requested.split(",") if name.strip()] diff --git a/semif_agent/gateway/humanize.py b/semif_agent/gateway/humanize.py new file mode 100644 index 0000000..2602d50 --- /dev/null +++ b/semif_agent/gateway/humanize.py @@ -0,0 +1,107 @@ +"""Optional LLM cleanup of a skill's result line for the messenger gateway. + +The scheduler's run summary is deterministic and technical — ``: + — ``, where the action log is whatever the skill body +wrote (often mechanical: ``PUT 201 …``, ``sent via /_send to contact 12``). +This layer rewrites only that result detail into one grounded, friendly +sentence for a chat front end. + +It is generation, never a decision: the success/failure verdict and the routing +are already settled by SemIf and the runner, and the rewrite is never fed back +into assessment, tracing, or the decision log. The prompt forbids adding, +inferring, or dropping facts, and `humanize` falls back to the original text on +any error, timeout, empty reply, refusal, or runaway length — a cleanup failure +must never swallow or corrupt a real result. + +It reuses the scheduler's configured ``llm`` client (its endpoint/model/sampler) +and passes a short per-call ``timeout`` so a slow cleanup cannot hold the +gateway's poll loop for the client's full authoring budget. It is deliberately +gateway-only: the runner and the REPL keep the raw, deterministic summary. +""" + +from __future__ import annotations + +#: The strict rephrasing instruction. Grounding is enforced by the prompt and +#: by the caller's fallback, not by a second model call. +SYSTEM_PROMPT = ( + "You rewrite an assistant's raw action result into one short, friendly " + "sentence for a chat reply.\n" + "Rules:\n" + "- Use ONLY the facts in the result. Do not add, guess, or infer anything.\n" + "- Preserve whether the action succeeded or failed exactly as stated.\n" + "- Do not mention servers, HTTP status codes, command names, file paths, " + "or internal bookkeeping unless that is the only content.\n" + "- One sentence. No preamble, no explanation, no quotes, no markdown.\n" + "- If the result is already a plain sentence, return it unchanged." +) + +#: Leading phrases that mark a meta/refusal reply rather than a rewrite. +_REFUSAL_PREFIXES = ( + "i cannot", + "i can't", + "i'm sorry", + "i am sorry", + "i'm unable", + "i am unable", + "as an ai", + "sorry,", +) + + +def _clean_reply(raw: str) -> str: + """Normalize a model reply into one bare sentence, or "" if unusable.""" + text = (raw or "").strip() + if not text: + return "" + # Drop a wrapping pair of quotes the model may add. + if len(text) >= 2 and text[0] == text[-1] and text[0] in "\"'“”‘’": + text = text[1:-1].strip() + # Collapse newlines / runs of whitespace to a single line. + return " ".join(text.split()) + + +class Humanizer: + """Rewrite a result line with an LLM, falling back to the source verbatim.""" + + def __init__( + self, + client, + *, + enabled: bool = True, + timeout: float = 20.0, + max_tokens: int = 200, + max_chars: int = 600, + ): + self.client = client + self.enabled = bool(enabled) and client is not None + self.timeout = float(timeout) + self.max_tokens = int(max_tokens) + self.max_chars = int(max_chars) + + def humanize(self, text: str) -> str: + """Return a grounded rewrite of `text`, or `text` unchanged. + + Never raises: any failure (unreachable client, timeout, empty or + unusable reply, refusal, runaway length) returns the original text. + """ + source = (text or "").strip() + if not self.enabled or not source: + return text + messages = [ + {"role": "system", "content": SYSTEM_PROMPT}, + {"role": "user", "content": source}, + ] + try: + raw = self.client.chat( + messages, max_tokens=self.max_tokens, timeout=self.timeout + ) + except Exception: + return text + cleaned = _clean_reply(raw) + if not cleaned: + return text + if cleaned.lower().startswith(_REFUSAL_PREFIXES): + return text + if len(cleaned) > self.max_chars: + return text + return cleaned diff --git a/semif_agent/gateway/service.py b/semif_agent/gateway/service.py index 56650c7..b2716be 100644 --- a/semif_agent/gateway/service.py +++ b/semif_agent/gateway/service.py @@ -26,6 +26,7 @@ import re import threading from .base import InboundMessage, OutboundMessage +from .humanize import Humanizer _LEADING_RUN_ID = re.compile(r"^\[[0-9a-f]{6,}\]\s*") @@ -112,6 +113,7 @@ class GatewayService: adapters, config: dict | None = None, poll_interval: float = 1.0, + humanizer: Humanizer | None = None, ): self.scheduler = scheduler self.adapters = _normalize_adapters(adapters) @@ -125,6 +127,17 @@ class GatewayService: self._platform_cfg: dict[str, dict] = { platform: self._config_for(platform) for platform in self.platforms } + #: Optional LLM result cleanup (gateway-only presentation). Built from + #: the scheduler's `llm` client unless one is injected; a no-op unless + #: `gateway.humanize.enabled` (or a per-platform override) turns it on. + if humanizer is not None: + self.humanizer = humanizer + self._humanize_default = bool(humanizer.enabled) + else: + humanize_cfg = self.config.get("humanize") + humanize_cfg = humanize_cfg if isinstance(humanize_cfg, dict) else {} + self._humanize_default = bool(humanize_cfg.get("enabled", False)) + self.humanizer = self._build_humanizer(humanize_cfg) self._owners: dict[str, Target] = {} self._parents: dict[str, str] = {} self._pending_owner: Target | None = None @@ -165,6 +178,44 @@ class GatewayService: return bool(cfg["result_only"]) return bool(getattr(self.adapters.get(platform), "result_only", False)) + # ---- optional LLM result cleanup ---- + + def _build_humanizer(self, cfg: dict) -> Humanizer | None: + """Build the result humanizer from config + the scheduler's `llm`. + + Global defaults live in `gateway.humanize`; a per-platform + `gateway..humanize` (bool or `{enabled, timeout, max_tokens, + max_chars}`) overrides the enable flag. Returns None when no `llm` + client is available, so a client-less scheduler degrades to no cleanup. + The instance is always built `enabled`; the global default is kept + separately so a per-platform override can turn it on or off. + """ + client = getattr(self.scheduler, "llm", None) + if client is None: + return None + return Humanizer( + client, + enabled=True, + timeout=float(cfg.get("timeout", 20.0)), + max_tokens=int(cfg.get("max_tokens", 200)), + max_chars=int(cfg.get("max_chars", 600)), + ) + + def _humanize_enabled(self, platform: str) -> bool: + """Whether this platform cleans up its result line. + + A per-platform `humanize` bool (or `{enabled: bool}`) overrides the + global `gateway.humanize.enabled`. Default is off. + """ + if self.humanizer is None: + return False + override = self._platform_cfg.get(platform, {}).get("humanize") + if isinstance(override, bool): + return override + if isinstance(override, dict) and "enabled" in override: + return bool(override["enabled"]) + return self._humanize_default + def _fallback_target(self) -> Target | None: for platform in self.platforms: home = self._home_channel(platform) @@ -379,13 +430,19 @@ class GatewayService: self, platform: str, chat_id: str, text: str, kind: str = "reply" ) -> None: text = _strip_run_id(text) - if self._result_only(platform): + result_only = self._result_only(platform) + humanize = kind == "result" and self._humanize_enabled(platform) + if result_only: # A spoken front end says the skill's result, not the scheduler's - # bookkeeping: drop queue/urgency chatter and unwrap the result line. + # bookkeeping: drop queue/urgency chatter. if kind == "status": return - if kind == "result": - text = _result_detail(text) + if kind == "result" and (result_only or humanize): + # Unwrap `: — ` to the skill's own + # result before optionally cleaning it up. + text = _result_detail(text) + if humanize: + text = self.humanizer.humanize(text) prefix = str(self._platform_cfg.get(platform, {}).get("reply_prefix", "") or "") if prefix: text = f"{prefix}{text}" diff --git a/semif_agent/provider.py b/semif_agent/provider.py index e6377d6..6e5738f 100644 --- a/semif_agent/provider.py +++ b/semif_agent/provider.py @@ -192,8 +192,13 @@ class OpenAICompatClient: top_p: float | None = None, presence_penalty: float | None = None, frequency_penalty: float | None = None, + timeout: float | None = None, degeneration_check: Callable[[str], str | None] | None = None, ) -> str: + # A per-call `timeout` overrides the constructor value for this request + # only (used by short auxiliary calls such as the gateway's result + # cleanup, which must not inherit the authoring client's long budget). + deadline = self.timeout if timeout is None else timeout budget = self._compute_budget(messages) if self.stream: self._print_budget(budget) @@ -227,15 +232,17 @@ class OpenAICompatClient: url, data=body, headers=self._headers() ) try: - with urllib.request.urlopen(request, timeout=self.timeout) as response: - return self._read_stream(response, budget, degeneration_check) + with urllib.request.urlopen(request, timeout=deadline) as response: + return self._read_stream( + response, budget, degeneration_check, timeout=deadline + ) except urllib.error.URLError as exc: raise self.error_class( f"{self.label} endpoint unreachable at {url}: {exc}. Is your local server running?" ) from exc except TimeoutError as exc: raise self.error_class( - f"{self.label} request timed out after {self.timeout}s at {url}" + f"{self.label} request timed out after {deadline:.0f}s at {url}" ) from exc def _native_base_url(self) -> str: @@ -399,6 +406,7 @@ class OpenAICompatClient: response, budget: TokenBudget, degeneration_check: Callable[[str], str | None] | None = None, + timeout: float | None = None, ) -> str: """Read an OpenAI-compatible SSE stream; echo tokens if `stream`. @@ -426,7 +434,10 @@ class OpenAICompatClient: parts: list[str] = [] sock = self._stream_socket(response) if sock is None: - return self._read_stream_blocking(response, budget, degeneration_check) + return self._read_stream_blocking( + response, budget, degeneration_check, timeout=timeout + ) + deadline = self.timeout if timeout is None else timeout start = time.monotonic() last_activity = start warned = False @@ -437,9 +448,9 @@ class OpenAICompatClient: recent_len = 0 last_check: int | None = None while True: - if time.monotonic() - start >= self.timeout: + if time.monotonic() - start >= deadline: raise self.error_class( - f"{self.label} request exceeded {self.timeout:.0f}s total budget" + f"{self.label} request exceeded {deadline:.0f}s total budget" ) ready, _, _ = select.select([sock], [], [], 1.0) now = time.monotonic() @@ -499,16 +510,18 @@ class OpenAICompatClient: response, budget: TokenBudget, degeneration_check: Callable[[str], str | None] | None = None, + timeout: float | None = None, ) -> str: """Fallback reader when the response socket can't be located. A plain blocking read relies on the per-read socket timeout for silence, but that bounds individual reads, not the whole stream — so - enforce the same total wall-clock budget `self.timeout` and the token - budget in the loop, or a continuously-streaming runaway would never be - cut short. + enforce the same total wall-clock budget (the per-call `timeout`, else + `self.timeout`) and the token budget in the loop, or a + continuously-streaming runaway would never be cut short. """ parts: list[str] = [] + deadline = self.timeout if timeout is None else timeout start = time.monotonic() warned_fill = False out_chars = 0 @@ -517,9 +530,9 @@ class OpenAICompatClient: recent_len = 0 last_check: int | None = None for raw in response: - if time.monotonic() - start >= self.timeout: + if time.monotonic() - start >= deadline: raise self.error_class( - f"{self.label} request exceeded {self.timeout:.0f}s total budget" + f"{self.label} request exceeded {deadline:.0f}s total budget" ) continues, text, reasoning, frame_usage = self._consume_frame( raw.decode("utf-8").strip() diff --git a/tests/test_humanize.py b/tests/test_humanize.py new file mode 100644 index 0000000..55653e8 --- /dev/null +++ b/tests/test_humanize.py @@ -0,0 +1,144 @@ +"""Pure-stdlib tests for the gateway's optional LLM result cleanup. + +The `Humanizer` is a thin, always-falls-back rephraser over an injected client; +the gateway wires it to the scheduler's `llm` client and only for result lines. +No engine and no real LLM endpoint are involved — a fake client records the +call and returns a canned reply. +""" + +from semif_agent.gateway.humanize import Humanizer, _clean_reply +from semif_agent.gateway.service import GatewayService + + +class FakeClient: + def __init__(self, reply="", error=None): + self.reply = reply + self.error = error + self.calls = [] + + def chat(self, messages, max_tokens=None, timeout=None, **kwargs): + self.calls.append( + {"messages": messages, "max_tokens": max_tokens, "timeout": timeout} + ) + if self.error is not None: + raise self.error + return self.reply + + +class FakeAdapter: + name = "simplex" + + +class FakeScheduler: + def __init__(self, llm): + self.llm = llm + + +# ---- Humanizer: rewriting + fallback ---- + +def test_humanize_rewrites_and_passes_timeout(): + client = FakeClient(reply="Your event was added to the calendar.") + h = Humanizer(client, timeout=7.0, max_tokens=64) + assert h.humanize("PUT 201 created") == "Your event was added to the calendar." + call = client.calls[0] + assert call["timeout"] == 7.0 + assert call["max_tokens"] == 64 + assert "PUT 201 created" in call["messages"][1]["content"] + + +def test_humanize_collapses_whitespace_and_strips_quotes(): + client = FakeClient(reply='"Done.\n All good."') + assert Humanizer(client).humanize("ok") == "Done. All good." + + +def test_humanize_falls_back_on_client_error(): + client = FakeClient(error=RuntimeError("unreachable")) + assert Humanizer(client).humanize("raw result") == "raw result" + + +def test_humanize_falls_back_on_empty_reply(): + client = FakeClient(reply=" ") + assert Humanizer(client).humanize("raw result") == "raw result" + + +def test_humanize_falls_back_on_refusal(): + client = FakeClient(reply="I cannot rewrite that.") + assert Humanizer(client).humanize("raw result") == "raw result" + + +def test_humanize_falls_back_on_runaway_length(): + client = FakeClient(reply="x" * 1000) + assert Humanizer(client, max_chars=100).humanize("raw") == "raw" + + +def test_humanize_disabled_is_passthrough_without_calling(): + client = FakeClient(reply="should not be used") + h = Humanizer(client, enabled=False) + assert h.humanize("raw result") == "raw result" + assert client.calls == [] + + +def test_humanize_no_client_is_disabled(): + h = Humanizer(None) + assert h.enabled is False + assert h.humanize("raw result") == "raw result" + + +def test_clean_reply_handles_empty(): + assert _clean_reply("") == "" + assert _clean_reply(None) == "" + + +# ---- gateway wiring ---- + +def build_service(llm, config): + return GatewayService(FakeScheduler(llm), FakeAdapter(), config=config) + + +def test_gateway_humanizes_only_result_lines(): + llm = FakeClient(reply="It is 12:00.") + service = build_service(llm, {"humanize": {"enabled": True}, "simplex": {}}) + service._reply("simplex", "c", "[high] time.now: ok — 12:00", kind="result") + service._reply("simplex", "c", "urgency low (weight 0.20)", kind="status") + service._reply("simplex", "c", "Which account?", kind="question") + assert [service.outbound["simplex"].get_nowait().text for _ in range(3)] == [ + "It is 12:00.", + "urgency low (weight 0.20)", + "Which account?", + ] + + +def test_gateway_humanize_off_by_default(): + llm = FakeClient(reply="should not be used") + service = build_service(llm, {"simplex": {}}) + service._reply("simplex", "c", "[high] time.now: ok — 12:00", kind="result") + assert service.outbound["simplex"].get_nowait().text == "[high] time.now: ok — 12:00" + assert llm.calls == [] + + +def test_gateway_per_platform_override_enables(): + llm = FakeClient(reply="It is 12:00.") + service = build_service( + llm, {"humanize": {"enabled": False}, "simplex": {"humanize": True}} + ) + service._reply("simplex", "c", "time.now: ok — 12:00", kind="result") + assert service.outbound["simplex"].get_nowait().text == "It is 12:00." + + +def test_gateway_per_platform_override_disables(): + llm = FakeClient(reply="should not be used") + service = build_service( + llm, {"humanize": {"enabled": True}, "simplex": {"humanize": False}} + ) + service._reply("simplex", "c", "time.now: ok — 12:00", kind="result") + assert service.outbound["simplex"].get_nowait().text == "time.now: ok — 12:00" + assert llm.calls == [] + + +def test_gateway_humanize_keeps_wrapper_when_result_only_off(): + # Humanize unwraps the scheduler wrapper, like result_only, but only for + # the result line — status chatter still flows on a plain chat platform. + llm = FakeClient(reply="Done.") + service = build_service(llm, {"humanize": {"enabled": True}, "simplex": {}}) + service._reply("simplex", "c", "track.manual: ok — sent", kind="result") + assert service.outbound["simplex"].get_nowait().text == "Done."