Decouple bridges: ship each with its pack
The core no longer owns concrete bridge implementations. A bridge now ships inside the pack that declares it (packs/<name>/bridge/<name>.py, plus its package marker, optional client module, and hermetic test), and the core registry imports it by convention from the pack's `bridges`. Core keeps only: - bridges/base.py: BridgeInfo + BridgeService (shared HTTP/JSON/auth layer), plus a new BridgeService.from_config build hook (a bridge that needs the scheduler's `llm` client or top-level fallback values declares that itself, replacing build_bridge's per-name special-casing) and checkout_root() so a pack-relative bridge can still anchor .runtime/ paths; - bridges/inbox.py: the generic MessagingInbox; - bridges/llm.py: the one shared, pack-less LLMBridge (CORE_BRIDGES); - bridges/registry.py: discovery (discover_bridge_classes/known_infos/ describe_bridges/derived_config_vars/build_bridge/run_bridges) scanning each pack's bridge/ dir, plus load_pack_bridge_module/package for tests. Moved to their packs: simplex, nextcloud (+client), outlook (+client), browser (+client) — each with its hermetic test. tests/test_bridges.py now covers the core (shared LLM bridge + registry); tests/test_packs.py runs every pack's bridge test. Docs (AGENTS.md, PACKGEN.md, README.md) updated. Packs pushed separately to pack.<name>.
This commit is contained in:
1 parent
16e8583921
commit
41c18e6c47
21 files changed
+485
-7476
No files matched your search
@@ -11,6 +11,12 @@ fronts a service, a generated body never speaks that system's native protocol
|
||||
directly: it calls a small, documented, uniform HTTP surface instead, and the
|
||||
bridge owns the messy integration details and credentials.
|
||||
|
||||
Bridges **ship with their pack**: the core owns only the shared contract
|
||||
(``bridges/base.py``) and the discovery registry (``bridges/registry.py``); a
|
||||
bridge implementation lives in ``packs/<name>/bridge/`` and is imported by
|
||||
convention from the pack that declares it. The one exception is the shared,
|
||||
pack-less LLM bridge (``bridges/llm.py``), which many packs call.
|
||||
|
||||
Two boundaries matter:
|
||||
|
||||
- **Bridges are not the gateway.** The command gateway only takes commands and
|
||||
@@ -25,14 +31,19 @@ Two boundaries matter:
|
||||
and TESTGEN.md carry only the generic pattern.
|
||||
"""
|
||||
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .base import BridgeInfo, BridgeService, checkout_root
|
||||
from .inbox import MessagingInbox
|
||||
from .registry import (
|
||||
build_bridge,
|
||||
derived_config_vars,
|
||||
describe_bridges,
|
||||
discover_bridge_classes,
|
||||
known_infos,
|
||||
load_pack_bridge_class,
|
||||
load_pack_bridge_module,
|
||||
load_pack_bridge_package,
|
||||
run_bridges,
|
||||
set_bridge_packs,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
@@ -40,8 +51,14 @@ __all__ = [
|
||||
"BridgeService",
|
||||
"MessagingInbox",
|
||||
"build_bridge",
|
||||
"checkout_root",
|
||||
"derived_config_vars",
|
||||
"describe_bridges",
|
||||
"discover_bridge_classes",
|
||||
"known_infos",
|
||||
"load_pack_bridge_class",
|
||||
"load_pack_bridge_module",
|
||||
"load_pack_bridge_package",
|
||||
"run_bridges",
|
||||
"set_bridge_packs",
|
||||
]
|
||||
@@ -14,9 +14,20 @@ import threading
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
|
||||
def checkout_root() -> Path:
|
||||
"""The agent checkout root (anchors gitignored ``.runtime/`` artifacts).
|
||||
|
||||
``semif_agent/bridges/base.py`` -> repo root. A bridge implementation ships
|
||||
inside its pack (``packs/<name>/bridge/...``), so it must not derive the root
|
||||
from its own ``__file__``; it uses this helper instead.
|
||||
"""
|
||||
return Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BridgeInfo:
|
||||
"""Static, prompt-safe metadata about a bridge.
|
||||
@@ -60,6 +71,25 @@ class BridgeService(ABC):
|
||||
self._server: ThreadingHTTPServer | None = None
|
||||
self._thread: threading.Thread | None = None
|
||||
|
||||
@classmethod
|
||||
def from_config(
|
||||
cls,
|
||||
block: dict | None,
|
||||
config: dict | None = None,
|
||||
trace=None,
|
||||
llm=None,
|
||||
) -> "BridgeService":
|
||||
"""Build a bridge from its ``bridges.<name>`` block.
|
||||
|
||||
The registry constructs every bridge through this hook so a bridge that
|
||||
needs more than its own block — the shared LLM client, or a top-level
|
||||
fallback (e.g. Nextcloud's ``nextcloud_*`` values) — can declare that
|
||||
itself instead of the core special-casing it by name. The default passes
|
||||
the block and trace straight through; override in a pack bridge that
|
||||
needs ``llm`` or the full ``config``.
|
||||
"""
|
||||
return cls(block, trace=trace)
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
@abstractmethod
|
||||
|
||||
@@ -1,369 +0,0 @@
|
||||
"""Browser bridge: real browser automation (Playwright) behind HTTP.
|
||||
|
||||
A codegen-authored skill body must never drive a browser directly, and it must
|
||||
never bundle a heavy, platform-specific automation stack. This bridge owns the
|
||||
browser — a single Chromium (or Firefox/WebKit) instance with a persistent
|
||||
profile — and exposes one uniform, token-guarded localhost JSON API for reading
|
||||
a page (text/links/screenshot) and acting on it (goto/click/fill/press/select/
|
||||
wait/back/forward), so a body only reads `browser_bridge_url` and
|
||||
`browser_bridge_token` from `ctx.config` and calls a documented route.
|
||||
|
||||
Unlike Nextcloud/Outlook this bridge needs a real optional dependency
|
||||
(`playwright` plus browser binaries), so it is **disabled by default**; install
|
||||
it with `scripts/bootstrap.sh --browser` (browsers land under
|
||||
`.runtime/browser`). The dependency and the browser are lazy: a host without
|
||||
them still runs every other bridge. `check_requirements()` deliberately always
|
||||
returns ok — `run_bridges()` aborts *all* bridges when one's requirements fail,
|
||||
and this dependency is optional, so a missing Playwright must degrade to a
|
||||
per-call 503 (with an install hint), never take down simplex/llm/nextcloud.
|
||||
|
||||
The actual Playwright work lives in `browser_client.py`; the routes here
|
||||
validate input and map a real failure (`BrowserError`) to a 502, a missing
|
||||
dependency/browser (`BrowserUnavailable`) to a 503, and bad input to a 400 —
|
||||
never a fabricated success.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .browser_client import (
|
||||
DEFAULT_MAX_TEXT_CHARS,
|
||||
DEFAULT_TIMEOUT,
|
||||
ENGINES,
|
||||
WAIT_UNTIL,
|
||||
BrowserDriver,
|
||||
BrowserError,
|
||||
BrowserUnavailable,
|
||||
)
|
||||
|
||||
#: The checkout root (`semif_agent/bridges/browser.py` -> repo root), used to
|
||||
#: anchor the browser profile, binaries, and screenshots under the gitignored
|
||||
#: `.runtime/` tree (the containment rule).
|
||||
_REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
DEFAULT_BROWSER_ROOT = str(_REPO_ROOT / ".runtime" / "browser")
|
||||
DEFAULT_PROFILE_DIR = str(Path(DEFAULT_BROWSER_ROOT) / "profile")
|
||||
DEFAULT_SCREENSHOT_DIR = str(Path(DEFAULT_BROWSER_ROOT) / "screenshots")
|
||||
|
||||
|
||||
class BrowserBridge(BridgeService):
|
||||
name = "browser"
|
||||
INFO = BridgeInfo(
|
||||
name="browser",
|
||||
service="browser",
|
||||
description=(
|
||||
"Drive a real web browser (Playwright): open a URL, read a page's "
|
||||
"text or links, take a screenshot, and click/fill/press/select to "
|
||||
"navigate a site and complete a flow. Keeps a persistent profile so "
|
||||
"logins and cookies survive across calls."
|
||||
),
|
||||
url_config_var="browser_bridge_url",
|
||||
endpoints=(
|
||||
"GET /health -> 200 {\"ok\": true, \"platform\": \"browser\", "
|
||||
"\"engine\", \"headless\"} — the bridge is up",
|
||||
"GET /state -> 200 {\"url\", \"title\"} — the current page",
|
||||
"GET /content?format=text|html&max_chars=<n> -> 200 {\"url\", "
|
||||
"\"title\", \"format\", \"content\", \"truncated\"} — the whole page's "
|
||||
"rendered text (format defaults to text, the default when you just "
|
||||
"want to read a page); content is truncated to max_chars",
|
||||
"GET /text?selector=<css> -> 200 {\"url\", \"selector\", \"count\", "
|
||||
"\"matches\": [{\"text\"}]} — text of every element matching a CSS "
|
||||
"selector",
|
||||
"GET /links?query=<text>&limit=<n> -> 200 {\"url\", \"links\": "
|
||||
"[{\"text\", \"href\"}]} — anchors on the page, optionally filtered "
|
||||
"by a substring of the label or href",
|
||||
"GET /screenshot?full_page=<bool>&selector=<css>&inline=<bool> -> 200 "
|
||||
"{\"ok\": true, \"path\", \"bytes\", \"url\", \"title\"} — saves a PNG "
|
||||
"under the checkout's .runtime/browser/screenshots (add inline=true "
|
||||
"for base64 in the reply)",
|
||||
"POST /goto {\"url\", \"wait_until\"?: commit|domcontentloaded|load|"
|
||||
"networkidle, \"timeout\"?: seconds} -> 200 {\"url\", \"title\", "
|
||||
"\"status\"} — navigates; a navigation error (bad host, TLS, timeout) "
|
||||
"is a 502",
|
||||
"POST /click {\"selector\"?| \"text\"?, \"index\"?: 0, \"timeout\"?} "
|
||||
"-> 200 {\"url\", \"title\"} — clicks by CSS selector or by visible "
|
||||
"text (index picks among several matches)",
|
||||
"POST /fill {\"selector\", \"value\", \"submit\"?: bool, "
|
||||
"\"timeout\"?} -> 200 {\"url\", \"title\"} — types into an input; "
|
||||
"submit=true presses Enter",
|
||||
"POST /press {\"key\", \"selector\"?, \"timeout\"?} -> 200 {\"url\", "
|
||||
"\"title\"} — presses a keyboard key (e.g. Enter, Escape, Tab)",
|
||||
"POST /select {\"selector\", \"value\"?|\"label\"?, \"timeout\"?} -> "
|
||||
"200 {\"url\", \"title\"} — chooses an option in a <select>",
|
||||
"POST /wait {\"selector\"?| \"text\"?, \"timeout\"?} -> 200 {\"url\", "
|
||||
"\"title\"} — waits for an element/text to appear",
|
||||
"POST /back | /forward {\"timeout\"?} -> 200 {\"url\", \"title\"}",
|
||||
"POST /reset {\"purge\"?: bool default true} -> 200 {\"ok\", "
|
||||
"\"purged\"} — closes the browser; purge=true (default) also deletes "
|
||||
"the stored profile so the next call starts logged out",
|
||||
"any request -> 401 {\"error\": \"unauthorized\"} when the token is "
|
||||
"configured and the auth header is missing or wrong",
|
||||
"503 {\"error\": \"...\"} when Playwright or its browser binaries are "
|
||||
"not installed (run scripts/bootstrap.sh --browser); 502 {\"error\": "
|
||||
"\"...\"} on a real browser failure (navigation, timeout, bad "
|
||||
"selector)",
|
||||
),
|
||||
config_vars=("browser_bridge_url", "browser_bridge_token"),
|
||||
config_var_docs=(
|
||||
(
|
||||
"browser_bridge_url",
|
||||
"Base URL of the local browser bridge (e.g. "
|
||||
"http://127.0.0.1:5232); never hardcode it in the body.",
|
||||
),
|
||||
(
|
||||
"browser_bridge_token",
|
||||
"Shared secret for the bridge, if one is configured; sent as the "
|
||||
"X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
),
|
||||
),
|
||||
auth_header="X-Semif-Token",
|
||||
auth_config_var="browser_bridge_token",
|
||||
)
|
||||
|
||||
def __init__(self, config: dict | None = None, trace=None, client=None):
|
||||
super().__init__(config, trace)
|
||||
cfg = config or {}
|
||||
engine = str(cfg.get("engine", "chromium") or "chromium").strip().lower()
|
||||
self.engine = engine if engine in ENGINES else "chromium"
|
||||
self.headless = bool(cfg.get("headless", True))
|
||||
self.profile_dir = str(cfg.get("profile_dir") or DEFAULT_PROFILE_DIR)
|
||||
self.browsers_path = str(cfg.get("browsers_path") or DEFAULT_BROWSER_ROOT)
|
||||
self.screenshot_dir = str(cfg.get("screenshot_dir") or DEFAULT_SCREENSHOT_DIR)
|
||||
self.default_timeout = float(cfg.get("default_timeout", DEFAULT_TIMEOUT))
|
||||
self.max_text_chars = int(cfg.get("max_text_chars", DEFAULT_MAX_TEXT_CHARS))
|
||||
#: Optional escape hatch: use an installed browser instead of Playwright's
|
||||
#: managed download. `channel` is a Playwright channel (chrome/msedge/...),
|
||||
#: `executable_path` a specific binary; `executable_path` wins if both set.
|
||||
self.channel = str(cfg.get("channel", "") or "").strip()
|
||||
self.executable_path = str(cfg.get("executable_path", "") or "").strip()
|
||||
#: A test seam: inject a driver double. Production builds the real one.
|
||||
self.client = client or BrowserDriver(
|
||||
engine=self.engine,
|
||||
headless=self.headless,
|
||||
profile_dir=self.profile_dir,
|
||||
browsers_path=self.browsers_path,
|
||||
screenshot_dir=self.screenshot_dir,
|
||||
default_timeout=self.default_timeout,
|
||||
max_text_chars=self.max_text_chars,
|
||||
channel=self.channel,
|
||||
executable_path=self.executable_path,
|
||||
)
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def check_requirements(self) -> tuple[bool, str | None]:
|
||||
# Deliberately never blocks startup: a missing Playwright/browser is an
|
||||
# optional-dependency problem and must not take down the other bridges
|
||||
# (run_bridges aborts them all on a failed check). It surfaces as a 503
|
||||
# on the call instead.
|
||||
return True, None
|
||||
|
||||
def _stop_transport(self) -> None:
|
||||
close = getattr(self.client, "close", None)
|
||||
if callable(close):
|
||||
try:
|
||||
close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ---- routes ----
|
||||
|
||||
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/health":
|
||||
return 200, {
|
||||
"ok": True,
|
||||
"platform": self.name,
|
||||
"engine": self.engine,
|
||||
"headless": self.headless,
|
||||
}
|
||||
try:
|
||||
return self._get(path, query)
|
||||
except BrowserUnavailable as exc:
|
||||
return 503, {"error": str(exc)[:400]}
|
||||
except BrowserError as exc:
|
||||
return 502, {"error": str(exc)[:300]}
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)[:300]}
|
||||
|
||||
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
try:
|
||||
return self._post(path, payload)
|
||||
except BrowserUnavailable as exc:
|
||||
return 503, {"error": str(exc)[:400]}
|
||||
except BrowserError as exc:
|
||||
return 502, {"error": str(exc)[:300]}
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)[:300]}
|
||||
|
||||
def _get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/state":
|
||||
return 200, self.client.state()
|
||||
if path == "/content":
|
||||
fmt = (self._q(query, "format", "text") or "text").strip().lower()
|
||||
if fmt not in ("text", "html"):
|
||||
raise ValueError("format must be text or html")
|
||||
max_chars = self._int_query_opt(query, "max_chars")
|
||||
return 200, self.client.content(fmt, max_chars)
|
||||
if path == "/text":
|
||||
return 200, self.client.text(self._required_query(query, "selector"))
|
||||
if path == "/links":
|
||||
return 200, self.client.links(
|
||||
self._q(query, "query", "") or "", self._int_query(query, "limit", 50)
|
||||
)
|
||||
if path == "/screenshot":
|
||||
return 200, self.client.screenshot(
|
||||
self._bool_query(query, "full_page", False),
|
||||
self._q(query, "selector", "") or "",
|
||||
self._bool_query(query, "inline", False),
|
||||
)
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
def _post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
if path == "/goto":
|
||||
wait_until = (
|
||||
self._optional_str(payload, "wait_until", "load") or "load"
|
||||
).strip().lower()
|
||||
if wait_until not in WAIT_UNTIL:
|
||||
raise ValueError(f"wait_until must be one of {', '.join(WAIT_UNTIL)}")
|
||||
return 200, self.client.goto(
|
||||
self._required(payload, "url"),
|
||||
wait_until,
|
||||
self._optional_float(payload, "timeout"),
|
||||
)
|
||||
if path == "/click":
|
||||
selector = self._optional_str(payload, "selector")
|
||||
text = self._optional_str(payload, "text")
|
||||
if not selector and not text:
|
||||
raise ValueError("selector or text is required")
|
||||
return 200, self.client.click(
|
||||
selector,
|
||||
text,
|
||||
self._optional_int(payload, "index", 0) or 0,
|
||||
self._optional_float(payload, "timeout"),
|
||||
)
|
||||
if path == "/fill":
|
||||
return 200, self.client.fill(
|
||||
self._required(payload, "selector"),
|
||||
self._required(payload, "value", allow_empty=True),
|
||||
self._optional_bool(payload, "submit", False),
|
||||
self._optional_float(payload, "timeout"),
|
||||
)
|
||||
if path == "/press":
|
||||
return 200, self.client.press(
|
||||
self._required(payload, "key"),
|
||||
self._optional_str(payload, "selector"),
|
||||
self._optional_float(payload, "timeout"),
|
||||
)
|
||||
if path == "/select":
|
||||
value = self._optional_str(payload, "value") or None
|
||||
label = self._optional_str(payload, "label") or None
|
||||
if value is None and label is None:
|
||||
raise ValueError("value or label is required")
|
||||
return 200, self.client.select(
|
||||
self._required(payload, "selector"),
|
||||
value,
|
||||
label,
|
||||
self._optional_float(payload, "timeout"),
|
||||
)
|
||||
if path == "/wait":
|
||||
selector = self._optional_str(payload, "selector")
|
||||
text = self._optional_str(payload, "text")
|
||||
if not selector and not text:
|
||||
raise ValueError("selector or text is required")
|
||||
return 200, self.client.wait_for(
|
||||
selector, text, self._optional_float(payload, "timeout")
|
||||
)
|
||||
if path == "/back":
|
||||
return 200, self.client.back(self._optional_float(payload, "timeout"))
|
||||
if path == "/forward":
|
||||
return 200, self.client.forward(self._optional_float(payload, "timeout"))
|
||||
if path == "/reset":
|
||||
return 200, self.client.reset(self._optional_bool(payload, "purge", True))
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
# ---- input helpers ----
|
||||
|
||||
@staticmethod
|
||||
def _q(query: dict, key: str, default=None):
|
||||
values = query.get(key)
|
||||
if not values:
|
||||
return default
|
||||
return values[0]
|
||||
|
||||
@staticmethod
|
||||
def _required_query(query: dict, key: str) -> str:
|
||||
value = BrowserBridge._q(query, key)
|
||||
if value is None or not str(value).strip():
|
||||
raise ValueError(f"{key} is required")
|
||||
return str(value).strip()
|
||||
|
||||
@staticmethod
|
||||
def _int_query(query: dict, key: str, default: int) -> int:
|
||||
value = BrowserBridge._q(query, key)
|
||||
if value is None or str(value).strip() == "":
|
||||
return default
|
||||
try:
|
||||
return int(str(value))
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"{key} must be an integer") from exc
|
||||
|
||||
@staticmethod
|
||||
def _int_query_opt(query: dict, key: str):
|
||||
value = BrowserBridge._q(query, key)
|
||||
if value is None or str(value).strip() == "":
|
||||
return None
|
||||
try:
|
||||
return int(str(value))
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"{key} must be an integer") from exc
|
||||
|
||||
@staticmethod
|
||||
def _bool_query(query: dict, key: str, default: bool) -> bool:
|
||||
value = BrowserBridge._q(query, key)
|
||||
if value is None or str(value).strip() == "":
|
||||
return default
|
||||
return str(value).strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
@staticmethod
|
||||
def _required(payload: dict, key: str, allow_empty: bool = False) -> str:
|
||||
value = payload.get(key)
|
||||
if not isinstance(value, str) or (not allow_empty and not value.strip()):
|
||||
raise ValueError(f"{key} is required")
|
||||
return value if allow_empty else value.strip()
|
||||
|
||||
@staticmethod
|
||||
def _optional_str(payload: dict, key: str, default: str = "") -> str:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(f"{key} must be a string")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_bool(payload: dict, key: str, default: bool) -> bool:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, bool):
|
||||
raise ValueError(f"{key} must be a boolean")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_int(payload: dict, key: str, default: int | None = None):
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise ValueError(f"{key} must be an integer")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_float(payload: dict, key: str):
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
raise ValueError(f"{key} must be a number")
|
||||
return float(value)
|
||||
@@ -1,441 +0,0 @@
|
||||
"""A real browser driver for the browser bridge, backed by Playwright.
|
||||
|
||||
The browser bridge calls this instead of a skill body driving a browser
|
||||
directly. It owns a single Chromium (or Firefox/WebKit) instance with a
|
||||
**persistent profile** under the checkout's `.runtime/browser/profile`, so a
|
||||
logged-in session survives across calls and restarts, and exposes plain methods
|
||||
that return dicts.
|
||||
|
||||
Playwright's synchronous API is bound to the thread that created it and is not
|
||||
thread-safe, but the bridge's HTTP server handles each request on a new thread.
|
||||
So this driver runs the **async** API on one dedicated event-loop thread and
|
||||
serializes whole operations behind an `asyncio.Lock`; route handlers submit a
|
||||
coroutine onto that loop with `run_coroutine_threadsafe` and wait for the
|
||||
result. Browser automation is inherently serial, so one loop is enough.
|
||||
|
||||
Only the standard library is imported eagerly; `playwright` is imported lazily
|
||||
the first time the browser is actually needed, so a host without it still runs
|
||||
every other bridge. A missing package (or a missing browser binary) raises
|
||||
`BrowserUnavailable`, which the bridge maps to a 503 install hint; every other
|
||||
failure is a `BrowserError`, mapped to a 502 — never a fabricated success.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import importlib.util
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import uuid
|
||||
from concurrent.futures import TimeoutError as FuturesTimeoutError
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_ENGINE = "chromium"
|
||||
ENGINES = ("chromium", "firefox", "webkit")
|
||||
DEFAULT_TIMEOUT = 30.0
|
||||
DEFAULT_MAX_TEXT_CHARS = 20000
|
||||
#: Cap on how many elements a single `text` / `links` call returns.
|
||||
DEFAULT_MAX_MATCHES = 50
|
||||
WAIT_UNTIL = ("commit", "domcontentloaded", "load", "networkidle")
|
||||
INSTALL_HINT = (
|
||||
"install the browser bridge stack: pip install -r requirements/browser.txt "
|
||||
"&& PLAYWRIGHT_BROWSERS_PATH=<repo>/.runtime/browser python -m playwright "
|
||||
"install chromium"
|
||||
)
|
||||
|
||||
|
||||
class BrowserError(Exception):
|
||||
"""A real failure driving the browser (navigation, timeout, bad selector)."""
|
||||
|
||||
|
||||
class BrowserUnavailable(BrowserError):
|
||||
"""Playwright or its browser binaries are not installed / cannot launch."""
|
||||
|
||||
|
||||
class BrowserDriver:
|
||||
"""One persistent browser, driven from a single dedicated event-loop thread."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
engine: str = DEFAULT_ENGINE,
|
||||
headless: bool = True,
|
||||
profile_dir: str = "",
|
||||
browsers_path: str = "",
|
||||
screenshot_dir: str = "",
|
||||
default_timeout: float = DEFAULT_TIMEOUT,
|
||||
max_text_chars: int = DEFAULT_MAX_TEXT_CHARS,
|
||||
channel: str = "",
|
||||
executable_path: str = "",
|
||||
):
|
||||
self.engine = engine if engine in ENGINES else DEFAULT_ENGINE
|
||||
self.headless = bool(headless)
|
||||
self.profile_dir = str(profile_dir or "")
|
||||
self.browsers_path = str(browsers_path or "")
|
||||
self.screenshot_dir = str(screenshot_dir or "")
|
||||
self.default_timeout = float(default_timeout)
|
||||
self.max_text_chars = max(200, int(max_text_chars))
|
||||
#: Use an already-installed browser instead of Playwright's own build:
|
||||
#: `channel` names a Playwright channel (`chrome`, `msedge`, ...) and
|
||||
#: `executable_path` points at a specific binary. Both bypass the
|
||||
#: managed-download requirement, useful where the CDN is unreachable.
|
||||
self.channel = str(channel or "").strip()
|
||||
self.executable_path = str(executable_path or "").strip()
|
||||
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
self._thread: threading.Thread | None = None
|
||||
self._lock: asyncio.Lock | None = None
|
||||
self._start_lock = threading.Lock()
|
||||
self._playwright = None
|
||||
self._context = None
|
||||
self._page = None
|
||||
|
||||
# ---- availability ----
|
||||
|
||||
@property
|
||||
def configured(self) -> bool:
|
||||
"""Whether the `playwright` package is importable (cheap; no browser)."""
|
||||
return importlib.util.find_spec("playwright") is not None
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def _ensure_started(self) -> None:
|
||||
with self._start_lock:
|
||||
if self._loop is not None:
|
||||
return
|
||||
if not self.configured:
|
||||
raise BrowserUnavailable(INSTALL_HINT)
|
||||
# Locate browser binaries under the checkout before Playwright reads
|
||||
# the env var. The bridge cannot rely on the shell exporting it.
|
||||
if self.browsers_path:
|
||||
os.environ["PLAYWRIGHT_BROWSERS_PATH"] = self.browsers_path
|
||||
loop = asyncio.new_event_loop()
|
||||
self._loop = loop
|
||||
ready = threading.Event()
|
||||
|
||||
def runner() -> None:
|
||||
asyncio.set_event_loop(loop)
|
||||
self._lock = asyncio.Lock()
|
||||
ready.set()
|
||||
loop.run_forever()
|
||||
|
||||
self._thread = threading.Thread(target=runner, name="browser-driver", daemon=True)
|
||||
self._thread.start()
|
||||
ready.wait(5.0)
|
||||
|
||||
def _run(self, coro, timeout: float | None = None):
|
||||
"""Schedule `coro` on the driver loop and wait for its result."""
|
||||
if self._loop is None:
|
||||
coro.close()
|
||||
raise BrowserUnavailable(INSTALL_HINT)
|
||||
budget = (timeout if timeout else self.default_timeout) + 15.0
|
||||
future = asyncio.run_coroutine_threadsafe(coro, self._loop)
|
||||
try:
|
||||
return future.result(budget)
|
||||
except FuturesTimeoutError as exc:
|
||||
future.cancel()
|
||||
raise BrowserError(f"browser operation timed out after {budget:.0f}s") from exc
|
||||
|
||||
def _operation(self, fn, timeout: float | None = None):
|
||||
"""Run `fn(page)` under the serialization lock, launching if needed."""
|
||||
self._ensure_started()
|
||||
|
||||
async def runner():
|
||||
assert self._lock is not None
|
||||
async with self._lock:
|
||||
page = await self._ensure_context()
|
||||
return await fn(page)
|
||||
|
||||
return self._run(runner(), timeout=timeout)
|
||||
|
||||
async def _ensure_context(self):
|
||||
if self._page is not None and not self._page.is_closed():
|
||||
return self._page
|
||||
if self._playwright is None:
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
self._playwright = await async_playwright().start()
|
||||
browser_type = getattr(self._playwright, self.engine, None)
|
||||
if browser_type is None:
|
||||
raise BrowserError(f"unknown browser engine {self.engine!r}")
|
||||
if self.profile_dir:
|
||||
Path(self.profile_dir).mkdir(parents=True, exist_ok=True)
|
||||
user_data_dir = self.profile_dir
|
||||
else:
|
||||
# No persistent profile configured: still a real context, just
|
||||
# ephemeral (Playwright rejects a None user_data_dir).
|
||||
user_data_dir = tempfile.mkdtemp(prefix="semif-browser-")
|
||||
try:
|
||||
# A persistent context keeps cookies/logins on disk across calls and
|
||||
# restarts; it is the browser analog of the SimpleX bridge owning its
|
||||
# own profile.
|
||||
launch_options = {
|
||||
"headless": self.headless,
|
||||
"viewport": {"width": 1280, "height": 800},
|
||||
"timeout": self.default_timeout * 1000,
|
||||
}
|
||||
if self.executable_path:
|
||||
launch_options["executable_path"] = self.executable_path
|
||||
elif self.channel:
|
||||
launch_options["channel"] = self.channel
|
||||
self._context = await browser_type.launch_persistent_context(
|
||||
user_data_dir, **launch_options
|
||||
)
|
||||
except BrowserUnavailable:
|
||||
raise
|
||||
except Exception as exc: # missing browser binary, launch failure, ...
|
||||
raise BrowserUnavailable(
|
||||
f"could not launch {self.engine} (is the browser installed? "
|
||||
f"{INSTALL_HINT}): {exc}"
|
||||
) from exc
|
||||
pages = self._context.pages
|
||||
self._page = pages[0] if pages else await self._context.new_page()
|
||||
return self._page
|
||||
|
||||
async def _close_context(self) -> None:
|
||||
self._page = None
|
||||
context, self._context = self._context, None
|
||||
if context is not None:
|
||||
try:
|
||||
await context.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def close(self) -> None:
|
||||
"""Tear down the browser and the driver loop (from `_stop_transport`)."""
|
||||
loop, self._loop = self._loop, None
|
||||
if loop is None:
|
||||
return
|
||||
try:
|
||||
future = asyncio.run_coroutine_threadsafe(self._shutdown(), loop)
|
||||
future.result(timeout=15.0)
|
||||
except Exception:
|
||||
pass
|
||||
loop.call_soon_threadsafe(loop.stop)
|
||||
thread, self._thread = self._thread, None
|
||||
if thread is not None:
|
||||
thread.join(timeout=5.0)
|
||||
try:
|
||||
loop.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
async def _shutdown(self) -> None:
|
||||
await self._close_context()
|
||||
if self._playwright is not None:
|
||||
try:
|
||||
await self._playwright.stop()
|
||||
except Exception:
|
||||
pass
|
||||
self._playwright = None
|
||||
|
||||
# ---- operations (each returns a plain dict) ----
|
||||
|
||||
def state(self) -> dict:
|
||||
async def _do(page):
|
||||
return {"url": page.url, "title": await page.title()}
|
||||
|
||||
return self._operation(_do)
|
||||
|
||||
def goto(self, url: str, wait_until: str = "load", timeout: float | None = None) -> dict:
|
||||
async def _do(page):
|
||||
response = await page.goto(
|
||||
url, wait_until=wait_until, timeout=(timeout or self.default_timeout) * 1000
|
||||
)
|
||||
return {
|
||||
"url": page.url,
|
||||
"title": await page.title(),
|
||||
"status": response.status if response is not None else None,
|
||||
}
|
||||
|
||||
return self._operation(_do, timeout=timeout)
|
||||
|
||||
def content(self, fmt: str = "text", max_chars: int | None = None) -> dict:
|
||||
limit = max(200, int(max_chars)) if max_chars else self.max_text_chars
|
||||
|
||||
async def _do(page):
|
||||
if fmt == "html":
|
||||
raw = await page.content()
|
||||
else:
|
||||
raw = await page.inner_text("body")
|
||||
text = raw or ""
|
||||
return {
|
||||
"url": page.url,
|
||||
"title": await page.title(),
|
||||
"format": fmt,
|
||||
"content": text[:limit],
|
||||
"truncated": len(text) > limit,
|
||||
}
|
||||
|
||||
return self._operation(_do)
|
||||
|
||||
def text(self, selector: str) -> dict:
|
||||
async def _do(page):
|
||||
locator = page.locator(selector)
|
||||
count = await locator.count()
|
||||
matches = []
|
||||
for index in range(min(count, DEFAULT_MAX_MATCHES)):
|
||||
value = await locator.nth(index).inner_text()
|
||||
matches.append({"text": (value or "").strip()[:2000]})
|
||||
return {
|
||||
"url": page.url,
|
||||
"selector": selector,
|
||||
"count": count,
|
||||
"matches": matches,
|
||||
}
|
||||
|
||||
return self._operation(_do)
|
||||
|
||||
def links(self, query: str = "", limit: int = 50) -> dict:
|
||||
max_links = max(1, min(int(limit), 200))
|
||||
|
||||
async def _do(page):
|
||||
anchors = await page.query_selector_all("a")
|
||||
needle = query.strip().lower()
|
||||
out = []
|
||||
for element in anchors:
|
||||
href = await element.get_attribute("href")
|
||||
if not href:
|
||||
continue
|
||||
label = ((await element.inner_text()) or "").strip()
|
||||
if needle and needle not in f"{label} {href}".lower():
|
||||
continue
|
||||
out.append({"text": label[:300], "href": href})
|
||||
if len(out) >= max_links:
|
||||
break
|
||||
return {"url": page.url, "links": out}
|
||||
|
||||
return self._operation(_do)
|
||||
|
||||
def screenshot(
|
||||
self, full_page: bool = False, selector: str = "", inline: bool = False
|
||||
) -> dict:
|
||||
async def _do(page):
|
||||
directory = self.screenshot_dir or "/tmp"
|
||||
Path(directory).mkdir(parents=True, exist_ok=True)
|
||||
path = os.path.join(directory, f"{uuid.uuid4().hex}.png")
|
||||
if selector:
|
||||
await page.locator(selector).first.screenshot(path=path)
|
||||
else:
|
||||
await page.screenshot(path=path, full_page=bool(full_page))
|
||||
result = {
|
||||
"ok": True,
|
||||
"path": path,
|
||||
"bytes": os.path.getsize(path),
|
||||
"url": page.url,
|
||||
"title": await page.title(),
|
||||
}
|
||||
if inline:
|
||||
with open(path, "rb") as handle:
|
||||
result["base64"] = base64.b64encode(handle.read()).decode("ascii")
|
||||
return result
|
||||
|
||||
return self._operation(_do)
|
||||
|
||||
def click(
|
||||
self,
|
||||
selector: str = "",
|
||||
text: str = "",
|
||||
index: int = 0,
|
||||
timeout: float | None = None,
|
||||
) -> dict:
|
||||
async def _do(page):
|
||||
if selector:
|
||||
locator = page.locator(selector).nth(int(index))
|
||||
else:
|
||||
locator = page.get_by_text(text, exact=False).nth(int(index))
|
||||
await locator.click(timeout=(timeout or self.default_timeout) * 1000)
|
||||
return {"url": page.url, "title": await page.title()}
|
||||
|
||||
return self._operation(_do, timeout=timeout)
|
||||
|
||||
def fill(
|
||||
self,
|
||||
selector: str,
|
||||
value: str,
|
||||
submit: bool = False,
|
||||
timeout: float | None = None,
|
||||
) -> dict:
|
||||
async def _do(page):
|
||||
budget = (timeout or self.default_timeout) * 1000
|
||||
await page.fill(selector, value, timeout=budget)
|
||||
if submit:
|
||||
await page.press(selector, "Enter", timeout=budget)
|
||||
return {"url": page.url, "title": await page.title()}
|
||||
|
||||
return self._operation(_do, timeout=timeout)
|
||||
|
||||
def press(self, key: str, selector: str = "", timeout: float | None = None) -> dict:
|
||||
async def _do(page):
|
||||
await page.press(
|
||||
selector or "body", key, timeout=(timeout or self.default_timeout) * 1000
|
||||
)
|
||||
return {"url": page.url, "title": await page.title()}
|
||||
|
||||
return self._operation(_do, timeout=timeout)
|
||||
|
||||
def select(
|
||||
self,
|
||||
selector: str,
|
||||
value: str | None = None,
|
||||
label: str | None = None,
|
||||
timeout: float | None = None,
|
||||
) -> dict:
|
||||
async def _do(page):
|
||||
budget = (timeout or self.default_timeout) * 1000
|
||||
if value is not None:
|
||||
await page.select_option(selector, value=value, timeout=budget)
|
||||
else:
|
||||
await page.select_option(selector, label=label, timeout=budget)
|
||||
return {"url": page.url, "title": await page.title()}
|
||||
|
||||
return self._operation(_do, timeout=timeout)
|
||||
|
||||
def wait_for(
|
||||
self, selector: str = "", text: str = "", timeout: float | None = None
|
||||
) -> dict:
|
||||
async def _do(page):
|
||||
budget = (timeout or self.default_timeout) * 1000
|
||||
if selector:
|
||||
await page.wait_for_selector(selector, timeout=budget)
|
||||
else:
|
||||
await page.get_by_text(text, exact=False).first.wait_for(timeout=budget)
|
||||
return {"url": page.url, "title": await page.title()}
|
||||
|
||||
return self._operation(_do, timeout=timeout)
|
||||
|
||||
def back(self, timeout: float | None = None) -> dict:
|
||||
async def _do(page):
|
||||
await page.go_back(
|
||||
wait_until="load", timeout=(timeout or self.default_timeout) * 1000
|
||||
)
|
||||
return {"url": page.url, "title": await page.title()}
|
||||
|
||||
return self._operation(_do, timeout=timeout)
|
||||
|
||||
def forward(self, timeout: float | None = None) -> dict:
|
||||
async def _do(page):
|
||||
await page.go_forward(
|
||||
wait_until="load", timeout=(timeout or self.default_timeout) * 1000
|
||||
)
|
||||
return {"url": page.url, "title": await page.title()}
|
||||
|
||||
return self._operation(_do, timeout=timeout)
|
||||
|
||||
def reset(self, purge: bool = True) -> dict:
|
||||
"""Close the browser; delete the stored profile when `purge` is true."""
|
||||
self._ensure_started()
|
||||
|
||||
async def _do():
|
||||
assert self._lock is not None
|
||||
async with self._lock:
|
||||
await self._close_context()
|
||||
purged = False
|
||||
if purge and self.profile_dir:
|
||||
shutil.rmtree(self.profile_dir, ignore_errors=True)
|
||||
purged = True
|
||||
return {"ok": True, "purged": purged}
|
||||
|
||||
return self._run(_do())
|
||||
@@ -60,6 +60,12 @@ class LLMBridge(BridgeService):
|
||||
#: the bridge is built without one; calls then report 502, never a guess.
|
||||
self.client = client
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, block, config=None, trace=None, llm=None) -> "LLMBridge":
|
||||
# The LLM bridge reuses the scheduler's already-configured `llm` client
|
||||
# (endpoint/model/sampler configured once in the top-level `llm` block).
|
||||
return cls(block, trace=trace, client=llm)
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def check_requirements(self) -> tuple[bool, str | None]:
|
||||
|
||||
@@ -1,604 +0,0 @@
|
||||
"""Nextcloud bridge: files, calendars, tasks, contacts, and notes over HTTP.
|
||||
|
||||
Nextcloud speaks several native protocols (WebDAV for files, CalDAV for events
|
||||
and tasks, CardDAV for contacts, and OCS for the Notes app and server info). A
|
||||
codegen-authored skill body must never speak those directly. This bridge owns the
|
||||
connection — base URL, username, and app password — and exposes one uniform,
|
||||
token-guarded localhost JSON API, so a body only reads `nextcloud_bridge_url` and
|
||||
`nextcloud_bridge_token` from `ctx.config` and calls a documented route.
|
||||
|
||||
There is no service daemon: Nextcloud is plain HTTPS, so the bridge is stdlib-only
|
||||
(`urllib` + `xml.etree`) and starts instantly. The connection comes from
|
||||
`bridges.nextcloud` (url/username/app_password/default_calendar/default_addressbook),
|
||||
falling back to the top-level `nextcloud_url`/`nextcloud_username`/
|
||||
`nextcloud_app_password`/`nextcloud_default_calendar` values the nextcloud pack's skills
|
||||
already use, so the same account is configured in one place.
|
||||
|
||||
The actual DAV/OCS work lives in `nextcloud_client.py`; the routes here validate
|
||||
input and map a real failure (`NextcloudError`) to a 502 rather than a fabricated
|
||||
success.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .nextcloud_client import DEFAULT_TIMEOUT, NextcloudClient, NextcloudError
|
||||
|
||||
#: Nextcloud Deck backs each board with a VTODO-only calendar named like this.
|
||||
_DECK_PREFIX = "app-generated--deck--"
|
||||
|
||||
_COMPONENT_KINDS = {
|
||||
"VTODO": "task list",
|
||||
"VEVENT": "event calendar",
|
||||
"VJOURNAL": "journal",
|
||||
}
|
||||
|
||||
|
||||
def _supports(calendar: dict, component: str) -> bool:
|
||||
"""Whether a calendar accepts `component`; unknown (empty) means allow."""
|
||||
components = calendar.get("components") or []
|
||||
return not components or component in components
|
||||
|
||||
|
||||
def _is_deck_board(calendar: dict) -> bool:
|
||||
return str(calendar.get("name") or "").startswith(_DECK_PREFIX)
|
||||
|
||||
|
||||
def _component_kind(component: str) -> str:
|
||||
return _COMPONENT_KINDS.get(component, "calendar of that kind")
|
||||
|
||||
|
||||
def _join_components(calendar: dict) -> str:
|
||||
components = calendar.get("components") or []
|
||||
return ", ".join(components) if components else "an unknown component set"
|
||||
|
||||
|
||||
def _task_list_hint(calendars: list[dict]) -> str:
|
||||
names = [
|
||||
c["name"]
|
||||
for c in calendars
|
||||
if _supports(c, "VTODO") and not _is_deck_board(c)
|
||||
]
|
||||
if names:
|
||||
return "task lists: " + ", ".join(names)
|
||||
return "no VTODO-capable task lists are available"
|
||||
|
||||
|
||||
class NextcloudBridge(BridgeService):
|
||||
name = "nextcloud"
|
||||
INFO = BridgeInfo(
|
||||
name="nextcloud",
|
||||
service="nextcloud",
|
||||
description=(
|
||||
"Read and write the user's Nextcloud: files (WebDAV), calendar events "
|
||||
"and tasks (CalDAV), contacts (CardDAV), and Notes (the Notes app)."
|
||||
),
|
||||
url_config_var="nextcloud_bridge_url",
|
||||
endpoints=(
|
||||
"GET /health -> 200 {\"ok\": true, \"platform\": \"nextcloud\"} — the "
|
||||
"bridge is up",
|
||||
"GET /user -> 200 {\"user\": {id, display_name, email, language, "
|
||||
"locale}} — the account (OCS)",
|
||||
"GET /capabilities -> 200 {Nextcloud server capabilities} (OCS)",
|
||||
"GET /files?path=<dir> -> 200 {\"path\", \"entries\": [{name, path, "
|
||||
"type (file|dir), size, modified, etag, content_type}]} — list a "
|
||||
"folder (default /)",
|
||||
"GET /files/stat?path=<path> -> 200 {one entry, same fields as an "
|
||||
"entries item}",
|
||||
"GET /files/read?path=<path> -> 200 {\"path\", \"content\", "
|
||||
"\"encoding\" (utf-8|base64), \"size\"} — file contents; binary is "
|
||||
"base64",
|
||||
"GET /files/search?query=<text>&path=<dir> -> 200 {\"results\": "
|
||||
"[entry]} — filename search under a folder",
|
||||
"POST /files/write {\"path\", \"content\", \"encoding\"?: "
|
||||
"utf-8|base64, \"overwrite\"?: bool} -> 200 {\"ok\": true, \"path\"}",
|
||||
"POST /files/mkdir {\"path\"} -> 200 {\"ok\": true, \"path\"}",
|
||||
"POST /files/delete {\"path\"} -> 200 {\"ok\": true, \"path\"}",
|
||||
"POST /files/move {\"path\", \"destination\", \"overwrite\"?: bool} "
|
||||
"-> 200 {\"ok\": true, \"path\", \"destination\"}",
|
||||
"POST /files/copy {\"path\", \"destination\", \"overwrite\"?: bool} "
|
||||
"-> 200 {\"ok\": true, \"path\", \"destination\"}",
|
||||
"GET /calendars -> 200 {\"calendars\": [{name, label, description, "
|
||||
"color, ctag, components}]} — components lists the CalDAV component "
|
||||
"types each collection accepts (VEVENT, VTODO, VJOURNAL)",
|
||||
"GET /tasklists -> 200 {\"tasklists\": [{name, label, description, "
|
||||
"color, ctag, components}]} — the user's task lists (calendars that "
|
||||
"accept VTODO), excluding Nextcloud Deck boards; use this to pick a "
|
||||
"target for POST /tasks",
|
||||
"GET /calendars/events?calendar=<name>&start=<iso>&end=<iso> -> 200 "
|
||||
"{\"calendar\", \"events\": [{uid, summary, start, end, all_day, "
|
||||
"location, description, rrule, status, href, etag}]} — start/end "
|
||||
"optional (ISO 8601); without them every event is returned",
|
||||
"POST /calendars/events {\"calendar\"?, \"uid\"?, \"summary\", "
|
||||
"\"start\", \"end\"?, \"all_day\"?, \"location\"?, \"description\"?, "
|
||||
"\"rrule\"?, \"overwrite\"?} -> 200 {\"ok\": true, \"uid\", "
|
||||
"\"calendar\", \"etag\"}",
|
||||
"POST /calendars/events/update {\"calendar\"?, \"uid\", \"summary\"?, "
|
||||
"\"start\"?, \"end\"?, \"all_day\"?, \"location\"?, \"description\"?, "
|
||||
"\"rrule\"?} -> 200 {\"ok\": true, \"uid\", \"calendar\", \"etag\"} — "
|
||||
"only the named fields change",
|
||||
"POST /calendars/events/delete {\"calendar\"?, \"uid\"} -> 200 "
|
||||
"{\"ok\": true, \"uid\", \"calendar\"}",
|
||||
"GET /tasks?calendar=<name> -> 200 {\"calendar\", \"tasks\": [{uid, "
|
||||
"summary, due, status, percent_complete, priority, description, href, "
|
||||
"etag}]} — CalDAV VTODO; calendar must be a VTODO-capable task list "
|
||||
"(see GET /tasklists), defaulting to the configured task calendar",
|
||||
"POST /tasks {\"calendar\"?, \"uid\"?, \"summary\", \"due\"?, "
|
||||
"\"priority\"?, \"description\"?} -> 200 {\"ok\": true, \"uid\", "
|
||||
"\"calendar\", \"etag\"} — calendar must be a VTODO-capable task list "
|
||||
"(see GET /tasklists); an event-only calendar is rejected with 400",
|
||||
"POST /tasks/update {\"calendar\"?, \"uid\", \"summary\"?, \"due\"?, "
|
||||
"\"priority\"?, \"description\"?, \"status\"?, \"percent_complete\"?} "
|
||||
"-> 200 {ok, uid}",
|
||||
"POST /tasks/complete {\"calendar\"?, \"uid\"} -> 200 {ok, uid} — "
|
||||
"marks the task COMPLETED",
|
||||
"POST /tasks/delete {\"calendar\"?, \"uid\"} -> 200 {ok}",
|
||||
"GET /addressbooks -> 200 {\"addressbooks\": [{name, label, "
|
||||
"description}]}",
|
||||
"GET /contacts?addressbook=<name>&query=<text> -> 200 "
|
||||
"{\"addressbook\", \"contacts\": [{uid, fn, n, emails, phones, org, "
|
||||
"title, note, url, href, etag}]} — query filters by name/org/email/"
|
||||
"phone",
|
||||
"POST /contacts {\"addressbook\"?, \"uid\"?, \"fn\", \"emails\"?, "
|
||||
"\"phones\"?, \"org\"?, \"title\"?, \"note\"?, \"url\"?, \"n\"?} -> "
|
||||
"200 {ok, uid}",
|
||||
"POST /contacts/update {\"addressbook\"?, \"uid\", ...fields} -> 200 "
|
||||
"{ok, uid}",
|
||||
"POST /contacts/delete {\"addressbook\"?, \"uid\"} -> 200 {ok}",
|
||||
"GET /notes -> 200 {\"notes\": [{id, title, category, modified, ...}]} "
|
||||
"— Nextcloud Notes app (metadata only)",
|
||||
"GET /notes/get?id=<id> -> 200 {\"note\": {id, title, content, "
|
||||
"category, ...}}",
|
||||
"POST /notes {\"title\", \"content\"?, \"category\"?} -> 200 "
|
||||
"{\"note\": {...}}",
|
||||
"POST /notes/update {\"id\", \"title\"?, \"content\"?, "
|
||||
"\"category\"?} -> 200 {\"note\": {...}}",
|
||||
"POST /notes/delete {\"id\"} -> 200 {\"ok\": true, \"id\"}",
|
||||
"any request -> 401 {\"error\": \"unauthorized\"} when the token is "
|
||||
"configured and the auth header is missing or wrong",
|
||||
"503 {\"error\": \"...\"} when the bridge has no Nextcloud connection "
|
||||
"configured; 502 {\"error\": \"...\"} on a real Nextcloud failure "
|
||||
"(transport, HTTP error, or bad reply)",
|
||||
),
|
||||
config_vars=("nextcloud_bridge_url", "nextcloud_bridge_token"),
|
||||
config_var_docs=(
|
||||
(
|
||||
"nextcloud_bridge_url",
|
||||
"Base URL of the local Nextcloud bridge (e.g. "
|
||||
"http://127.0.0.1:5230); never hardcode it in the body.",
|
||||
),
|
||||
(
|
||||
"nextcloud_bridge_token",
|
||||
"Shared secret for the bridge, if one is configured; sent as the "
|
||||
"X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
),
|
||||
),
|
||||
auth_header="X-Semif-Token",
|
||||
auth_config_var="nextcloud_bridge_token",
|
||||
)
|
||||
|
||||
def __init__(self, config: dict | None = None, trace=None, fallback: dict | None = None, client=None):
|
||||
super().__init__(config, trace)
|
||||
cfg = config or {}
|
||||
fb = fallback or {}
|
||||
|
||||
def pick(key: str, default=""):
|
||||
value = cfg.get(key)
|
||||
if value in (None, ""):
|
||||
value = fb.get(key)
|
||||
return default if value in (None, "") else value
|
||||
|
||||
self.url = str(pick("url")).strip()
|
||||
self.username = str(pick("username")).strip()
|
||||
self.app_password = str(pick("app_password"))
|
||||
self.default_calendar = str(pick("default_calendar")).strip()
|
||||
self.default_task_calendar = str(pick("default_task_calendar")).strip()
|
||||
self.default_addressbook = str(pick("default_addressbook")).strip()
|
||||
self.verify_tls = bool(cfg.get("verify_tls", fb.get("verify_tls", True)))
|
||||
self.timeout = float(cfg.get("timeout", DEFAULT_TIMEOUT))
|
||||
#: A test seam: inject a client double. Production builds the real one.
|
||||
self.client = client or NextcloudClient(
|
||||
self.url,
|
||||
self.username,
|
||||
self.app_password,
|
||||
timeout=self.timeout,
|
||||
verify_tls=self.verify_tls,
|
||||
default_calendar=self.default_calendar,
|
||||
default_addressbook=self.default_addressbook,
|
||||
)
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def check_requirements(self) -> tuple[bool, str | None]:
|
||||
# Stdlib only: no missing dependency can make the bridge unstartable. A
|
||||
# missing connection surfaces as a 503 on the call, not a startup failure.
|
||||
return True, None
|
||||
|
||||
# ---- routes ----
|
||||
|
||||
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/health":
|
||||
return 200, {"ok": True, "platform": self.name}
|
||||
if not self.client.configured:
|
||||
return self._unconfigured()
|
||||
try:
|
||||
return self._get(path, query)
|
||||
except NextcloudError as exc:
|
||||
return 502, {"error": str(exc)[:300]}
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)[:300]}
|
||||
|
||||
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
if not self.client.configured:
|
||||
return self._unconfigured()
|
||||
try:
|
||||
return self._post(path, payload)
|
||||
except NextcloudError as exc:
|
||||
return 502, {"error": str(exc)[:300]}
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)[:300]}
|
||||
|
||||
def _unconfigured(self) -> tuple[int, dict]:
|
||||
return 503, {
|
||||
"error": (
|
||||
"the Nextcloud bridge has no connection configured (set "
|
||||
"bridges.nextcloud.url/username/app_password, or the top-level "
|
||||
"nextcloud_url/nextcloud_username/nextcloud_app_password)"
|
||||
)
|
||||
}
|
||||
|
||||
def _get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/user":
|
||||
return 200, {"user": self.client.user_info()}
|
||||
if path == "/capabilities":
|
||||
return 200, self.client.capabilities()
|
||||
if path == "/files":
|
||||
return 200, self.client.list_files(self._q(query, "path", "/") or "/")
|
||||
if path == "/files/stat":
|
||||
return 200, self.client.stat(self._required_query(query, "path"))
|
||||
if path == "/files/read":
|
||||
return 200, self.client.read_file(self._required_query(query, "path"))
|
||||
if path == "/files/search":
|
||||
query_text = self._required_query(query, "query")
|
||||
return 200, {
|
||||
"results": self.client.search(
|
||||
query_text, self._q(query, "path", "/") or "/"
|
||||
)
|
||||
}
|
||||
if path == "/calendars":
|
||||
return 200, {"calendars": self.client.list_calendars()}
|
||||
if path == "/tasklists":
|
||||
return 200, {"tasklists": self._task_lists()}
|
||||
if path == "/calendars/events":
|
||||
calendar = self._resolve_calendar(self._q(query, "calendar"))
|
||||
return 200, {
|
||||
"calendar": calendar,
|
||||
"events": self.client.list_events(
|
||||
calendar,
|
||||
self._q(query, "start", "") or "",
|
||||
self._q(query, "end", "") or "",
|
||||
),
|
||||
}
|
||||
if path == "/tasks":
|
||||
calendar = self._resolve_calendar(self._q(query, "calendar"), "VTODO")
|
||||
return 200, {"calendar": calendar, "tasks": self.client.list_tasks(calendar)}
|
||||
if path == "/addressbooks":
|
||||
return 200, {"addressbooks": self.client.list_addressbooks()}
|
||||
if path == "/contacts":
|
||||
addressbook = self._resolve_addressbook(self._q(query, "addressbook"))
|
||||
return 200, {
|
||||
"addressbook": addressbook,
|
||||
"contacts": self.client.list_contacts(
|
||||
addressbook, self._q(query, "query", "") or ""
|
||||
),
|
||||
}
|
||||
if path == "/notes":
|
||||
return 200, {"notes": self.client.list_notes()}
|
||||
if path == "/notes/get":
|
||||
return 200, {"note": self.client.get_note(self._required_query(query, "id"))}
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
def _post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
if path == "/files/write":
|
||||
return 200, self.client.write_file(
|
||||
self._required(payload, "path"),
|
||||
self._required(payload, "content", allow_empty=True),
|
||||
self._optional_str(payload, "encoding", "utf-8"),
|
||||
self._optional_bool(payload, "overwrite", True),
|
||||
)
|
||||
if path == "/files/mkdir":
|
||||
return 200, self.client.mkdir(self._required(payload, "path"))
|
||||
if path == "/files/delete":
|
||||
return 200, self.client.delete(self._required(payload, "path"))
|
||||
if path == "/files/move":
|
||||
return 200, self.client.move(
|
||||
self._required(payload, "path"),
|
||||
self._required(payload, "destination"),
|
||||
self._optional_bool(payload, "overwrite", False),
|
||||
)
|
||||
if path == "/files/copy":
|
||||
return 200, self.client.copy(
|
||||
self._required(payload, "path"),
|
||||
self._required(payload, "destination"),
|
||||
self._optional_bool(payload, "overwrite", False),
|
||||
)
|
||||
if path == "/calendars/events":
|
||||
return 200, self._create_event(payload)
|
||||
if path == "/calendars/events/update":
|
||||
return 200, self._update_event(payload)
|
||||
if path == "/calendars/events/delete":
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"))
|
||||
return 200, self.client.delete_object(calendar, self._required(payload, "uid"))
|
||||
if path == "/tasks":
|
||||
return 200, self._create_task(payload)
|
||||
if path == "/tasks/update":
|
||||
return 200, self._update_task(payload)
|
||||
if path == "/tasks/complete":
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"), "VTODO")
|
||||
return 200, self.client.complete_task(calendar, self._required(payload, "uid"))
|
||||
if path == "/tasks/delete":
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"), "VTODO")
|
||||
return 200, self.client.delete_object(calendar, self._required(payload, "uid"))
|
||||
if path == "/contacts":
|
||||
return 200, self._create_contact(payload)
|
||||
if path == "/contacts/update":
|
||||
return 200, self._update_contact(payload)
|
||||
if path == "/contacts/delete":
|
||||
addressbook = self._resolve_addressbook(
|
||||
self._optional_str(payload, "addressbook")
|
||||
)
|
||||
return 200, self.client.delete_contact(
|
||||
addressbook, self._required(payload, "uid")
|
||||
)
|
||||
if path == "/notes":
|
||||
return 200, {
|
||||
"note": self.client.create_note(
|
||||
self._required(payload, "title"),
|
||||
self._optional_str(payload, "content"),
|
||||
self._optional_str(payload, "category"),
|
||||
)
|
||||
}
|
||||
if path == "/notes/update":
|
||||
return 200, {"note": self._update_note(payload)}
|
||||
if path == "/notes/delete":
|
||||
return 200, self.client.delete_note(self._required_id(payload))
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
# ---- calendar/task helpers ----
|
||||
|
||||
def _create_event(self, payload: dict) -> dict:
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"))
|
||||
uid = self._optional_str(payload, "uid") or uuid.uuid4().hex
|
||||
return self.client.create_event(
|
||||
calendar,
|
||||
uid,
|
||||
summary=self._required(payload, "summary"),
|
||||
start=self._required(payload, "start"),
|
||||
end=self._optional_str(payload, "end"),
|
||||
all_day=self._optional_bool(payload, "all_day", False),
|
||||
location=self._optional_str(payload, "location"),
|
||||
description=self._optional_str(payload, "description"),
|
||||
rrule=self._optional_str(payload, "rrule"),
|
||||
overwrite=self._optional_bool(payload, "overwrite", False),
|
||||
)
|
||||
|
||||
def _update_event(self, payload: dict) -> dict:
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"))
|
||||
uid = self._required(payload, "uid")
|
||||
changes = {
|
||||
key: payload[key]
|
||||
for key in ("summary", "start", "end", "location", "description", "rrule")
|
||||
if key in payload
|
||||
}
|
||||
if "all_day" in payload:
|
||||
changes["all_day"] = self._optional_bool(payload, "all_day", False)
|
||||
return self.client.update_event(calendar, uid, **changes)
|
||||
|
||||
def _create_task(self, payload: dict) -> dict:
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"), "VTODO")
|
||||
uid = self._optional_str(payload, "uid") or uuid.uuid4().hex
|
||||
return self.client.create_task(
|
||||
calendar,
|
||||
uid,
|
||||
summary=self._required(payload, "summary"),
|
||||
due=self._optional_str(payload, "due"),
|
||||
priority=self._optional_int(payload, "priority"),
|
||||
description=self._optional_str(payload, "description"),
|
||||
)
|
||||
|
||||
def _update_task(self, payload: dict) -> dict:
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"), "VTODO")
|
||||
uid = self._required(payload, "uid")
|
||||
changes = {
|
||||
key: payload[key]
|
||||
for key in ("summary", "due", "priority", "description", "status", "percent_complete")
|
||||
if key in payload
|
||||
}
|
||||
return self.client.update_task(calendar, uid, **changes)
|
||||
|
||||
# ---- contact helpers ----
|
||||
|
||||
def _create_contact(self, payload: dict) -> dict:
|
||||
addressbook = self._resolve_addressbook(self._optional_str(payload, "addressbook"))
|
||||
uid = self._optional_str(payload, "uid") or uuid.uuid4().hex
|
||||
return self.client.create_contact(
|
||||
addressbook,
|
||||
uid,
|
||||
fn=self._required(payload, "fn"),
|
||||
n=self._optional_str(payload, "n"),
|
||||
emails=self._string_list(payload, "emails"),
|
||||
phones=self._string_list(payload, "phones"),
|
||||
org=self._optional_str(payload, "org"),
|
||||
title=self._optional_str(payload, "title"),
|
||||
note=self._optional_str(payload, "note"),
|
||||
url=self._optional_str(payload, "url"),
|
||||
)
|
||||
|
||||
def _update_contact(self, payload: dict) -> dict:
|
||||
addressbook = self._resolve_addressbook(self._optional_str(payload, "addressbook"))
|
||||
uid = self._required(payload, "uid")
|
||||
changes = {}
|
||||
for key in ("fn", "n", "org", "title", "note", "url"):
|
||||
if key in payload:
|
||||
changes[key] = payload[key]
|
||||
for key in ("emails", "phones"):
|
||||
if key in payload:
|
||||
changes[key] = self._string_list(payload, key)
|
||||
return self.client.update_contact(addressbook, uid, **changes)
|
||||
|
||||
# ---- notes helpers ----
|
||||
|
||||
def _update_note(self, payload: dict) -> dict:
|
||||
note_id = self._required_id(payload)
|
||||
changes = {
|
||||
key: payload[key] for key in ("title", "content", "category") if key in payload
|
||||
}
|
||||
return self.client.update_note(note_id, **changes)
|
||||
|
||||
# ---- default resolution ----
|
||||
|
||||
def _resolve_calendar(self, name, component: str | None = None) -> str:
|
||||
"""Resolve a calendar name, honoring the CalDAV component it must accept.
|
||||
|
||||
An explicit name is validated when the collection's component set is
|
||||
known: asking a task operation to write to an event-only calendar is a
|
||||
real error (a `VTODO` PUT there is rejected), not a silent redirect. With
|
||||
no name, a task operation falls back to the configured task calendar, then
|
||||
the event default when it also accepts VTODO, then the sole user task
|
||||
list. `component=None` (events, files) keeps the historical behavior.
|
||||
"""
|
||||
requested = str(name or "").strip()
|
||||
if requested:
|
||||
if component:
|
||||
calendars = self.client.list_calendars()
|
||||
match = next((c for c in calendars if c.get("name") == requested), None)
|
||||
if match is not None and not _supports(match, component):
|
||||
raise ValueError(
|
||||
f"{requested!r} is not a {_component_kind(component)} "
|
||||
f"(it accepts {_join_components(match)}); "
|
||||
f"{_task_list_hint(calendars)}"
|
||||
)
|
||||
return requested
|
||||
|
||||
# The configured defaults, most specific first. For a task operation the
|
||||
# event default is still consulted when it also accepts VTODO.
|
||||
defaults = [self.default_task_calendar] if component == "VTODO" else []
|
||||
defaults.append(self.default_calendar)
|
||||
calendars = None
|
||||
for default in defaults:
|
||||
if not default:
|
||||
continue
|
||||
if not component:
|
||||
return default
|
||||
if calendars is None:
|
||||
calendars = self.client.list_calendars()
|
||||
match = next((c for c in calendars if c.get("name") == default), None)
|
||||
if match is None or _supports(match, component):
|
||||
return default
|
||||
|
||||
if calendars is None:
|
||||
calendars = self.client.list_calendars()
|
||||
if component:
|
||||
calendars = [c for c in calendars if _supports(c, component)]
|
||||
if component == "VTODO":
|
||||
calendars = [c for c in calendars if not _is_deck_board(c)]
|
||||
if len(calendars) == 1:
|
||||
return calendars[0]["name"]
|
||||
raise ValueError(
|
||||
f"calendar is required (name one in the request, or set "
|
||||
f"bridges.nextcloud.default_calendar"
|
||||
+ (
|
||||
" / default_task_calendar"
|
||||
if component == "VTODO"
|
||||
else ""
|
||||
)
|
||||
+ ")"
|
||||
)
|
||||
|
||||
def _task_lists(self) -> list[dict]:
|
||||
"""The user's task lists: VTODO-capable calendars, minus Deck boards."""
|
||||
return [
|
||||
calendar
|
||||
for calendar in self.client.list_calendars()
|
||||
if _supports(calendar, "VTODO") and not _is_deck_board(calendar)
|
||||
]
|
||||
|
||||
def _resolve_addressbook(self, name) -> str:
|
||||
name = str(name or self.default_addressbook or "").strip()
|
||||
if name:
|
||||
return name
|
||||
addressbooks = self.client.list_addressbooks()
|
||||
if len(addressbooks) == 1:
|
||||
return addressbooks[0]["name"]
|
||||
raise ValueError(
|
||||
"addressbook is required (name one in the request, or set "
|
||||
"bridges.nextcloud.default_addressbook)"
|
||||
)
|
||||
|
||||
# ---- input helpers ----
|
||||
|
||||
@staticmethod
|
||||
def _q(query: dict, key: str, default=None):
|
||||
values = query.get(key)
|
||||
if not values:
|
||||
return default
|
||||
return values[0]
|
||||
|
||||
@staticmethod
|
||||
def _required_query(query: dict, key: str) -> str:
|
||||
value = NextcloudBridge._q(query, key)
|
||||
if value is None or not str(value).strip():
|
||||
raise ValueError(f"{key} is required")
|
||||
return str(value).strip()
|
||||
|
||||
@staticmethod
|
||||
def _required(payload: dict, key: str, allow_empty: bool = False) -> str:
|
||||
value = payload.get(key)
|
||||
if not isinstance(value, str) or (not allow_empty and not value.strip()):
|
||||
raise ValueError(f"{key} is required")
|
||||
return value if allow_empty else value.strip()
|
||||
|
||||
@staticmethod
|
||||
def _required_id(payload: dict):
|
||||
value = payload.get("id")
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
raise ValueError("id is required")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_str(payload: dict, key: str, default: str = "") -> str:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(f"{key} must be a string")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_bool(payload: dict, key: str, default: bool) -> bool:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, bool):
|
||||
raise ValueError(f"{key} must be a boolean")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_int(payload: dict, key: str):
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise ValueError(f"{key} must be an integer")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _string_list(payload: dict, key: str) -> list[str]:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return []
|
||||
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
|
||||
raise ValueError(f"{key} must be a list of strings")
|
||||
return value
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,398 +0,0 @@
|
||||
"""Outlook bridge: the user's Microsoft account (Graph) over HTTP.
|
||||
|
||||
Microsoft Graph is a plain HTTPS/JSON API, but a codegen-authored skill body
|
||||
must still never speak it (or OAuth) directly. This bridge owns the connection —
|
||||
the Entra ID client id, the tenant, and the stored refresh token — and exposes
|
||||
one uniform, token-guarded localhost JSON API for mail, calendar, Microsoft To Do
|
||||
tasks, contacts, and OneDrive files, so a body only reads `outlook_bridge_url`
|
||||
and `outlook_bridge_token` from `ctx.config` and calls a documented route.
|
||||
|
||||
There is no service daemon and no third-party dependency: Graph is plain HTTPS,
|
||||
so the bridge is stdlib-only (`urllib`) and starts instantly, like Nextcloud.
|
||||
Authorization is the OAuth2 device code flow, run once with
|
||||
`packs/outlook/scripts/outlook-auth.py`; the resulting tokens are stored (0600) under the
|
||||
checkout's `.runtime/outlook/token.json`. The bridge starts without them and an
|
||||
unauthenticated route returns 503 telling the operator to run that helper.
|
||||
|
||||
The actual Graph work lives in `outlook_client.py`; the routes here validate
|
||||
input and map a real failure (`OutlookError`) to a 502 — or a missing
|
||||
authorization (`OutlookAuthRequired`) to a 503 — rather than a fabricated
|
||||
success.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .outlook_client import (
|
||||
DEFAULT_SCOPES,
|
||||
DEFAULT_TENANT,
|
||||
DEFAULT_TIMEOUT,
|
||||
OutlookAuthRequired,
|
||||
OutlookClient,
|
||||
OutlookError,
|
||||
)
|
||||
|
||||
#: The checkout root (`semif_agent/bridges/outlook.py` -> repo root), used to
|
||||
#: anchor the default token store under the gitignored `.runtime/` tree.
|
||||
_REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
DEFAULT_TOKEN_PATH = str(_REPO_ROOT / ".runtime" / "outlook" / "token.json")
|
||||
|
||||
|
||||
class OutlookBridge(BridgeService):
|
||||
name = "outlook"
|
||||
INFO = BridgeInfo(
|
||||
name="outlook",
|
||||
service="outlook",
|
||||
description=(
|
||||
"Read and write the user's Microsoft account (Outlook / Microsoft "
|
||||
"365) through Microsoft Graph: mail, calendar events, Microsoft To "
|
||||
"Do tasks, contacts, and OneDrive files."
|
||||
),
|
||||
url_config_var="outlook_bridge_url",
|
||||
endpoints=(
|
||||
"GET /health -> 200 {\"ok\": true, \"platform\": \"outlook\"} — the "
|
||||
"bridge is up",
|
||||
"GET /user -> 200 {\"user\": {id, display_name, mail, "
|
||||
"user_principal_name}} — the signed-in account",
|
||||
"GET /mail/folders -> 200 {\"folders\": [{id, name, total, unread}]}",
|
||||
"GET /mail/messages?folder=<name|id>&count=<n>&search=<text>&unread=<bool> "
|
||||
"-> 200 {\"folder\", \"messages\": [{id, subject, from, to, cc, "
|
||||
"received, is_read, has_attachments, importance, preview, web_link}]} "
|
||||
"— newest first; folder defaults to inbox (a well-known name like "
|
||||
"sentitems/drafts/archive or a folder display name/id)",
|
||||
"GET /mail/messages/get?id=<id> -> 200 {\"message\": {..., body, "
|
||||
"body_type}} — the full message",
|
||||
"POST /mail/send {\"to\": [addr, ...], \"cc\"?: [addr, ...], "
|
||||
"\"subject\"?, \"body\"?, \"content_type\"?: text|html} -> 200 "
|
||||
"{\"ok\": true, \"to\", \"cc\", \"subject\"} — sends immediately",
|
||||
"POST /mail/draft {\"to\"?, \"cc\"?, \"subject\"?, \"body\"?, "
|
||||
"\"content_type\"?} -> 200 {\"ok\": true, \"id\", \"subject\"} — "
|
||||
"saves a draft in the Drafts folder",
|
||||
"GET /calendars -> 200 {\"calendars\": [{id, name, color, "
|
||||
"is_default, can_edit}]}",
|
||||
"GET /calendars/events?calendar=<name|id>&start=<iso>&end=<iso> -> "
|
||||
"200 {\"calendar\", \"events\": [{id, subject, start, end, timezone, "
|
||||
"all_day, location, preview, show_as, is_online_meeting, web_link, "
|
||||
"organizer}]} — start/end are ISO 8601 (default: now to +30 days); "
|
||||
"recurring events are expanded, calendar defaults to the configured "
|
||||
"or primary calendar",
|
||||
"POST /calendars/events {\"calendar\"?, \"subject\", \"start\", "
|
||||
"\"end\"?, \"all_day\"?, \"location\"?, \"description\"?, "
|
||||
"\"attendees\"?: [addr, ...], \"timezone\"?} -> 200 {\"ok\": true, "
|
||||
"\"id\", \"subject\", \"calendar\", \"web_link\"} — start/end are "
|
||||
"local ISO 8601 in the named timezone (default UTC when absent); end "
|
||||
"defaults to +1h (+1 day when all_day)",
|
||||
"POST /calendars/events/update {\"id\", \"subject\"?, \"start\"?, "
|
||||
"\"end\"?, \"all_day\"?, \"location\"?, \"description\"?, "
|
||||
"\"timezone\"?} -> 200 {ok, id, subject} — only the named fields change",
|
||||
"POST /calendars/events/delete {\"id\"} -> 200 {\"ok\": true, \"id\"}",
|
||||
"GET /tasklists -> 200 {\"tasklists\": [{id, name, is_owner, "
|
||||
"is_default}]} — Microsoft To Do lists",
|
||||
"GET /tasks?list=<name|id> -> 200 {\"list\", \"tasks\": [{id, title, "
|
||||
"status, importance, due, completed, description, list_id}]} — list "
|
||||
"defaults to the configured or default list",
|
||||
"POST /tasks {\"list\"?, \"title\", \"due\"?, \"importance\"?, "
|
||||
"\"description\"?} -> 200 {\"ok\": true, \"id\", \"title\", "
|
||||
"\"list_id\"} — importance is low|normal|high; due is ISO 8601",
|
||||
"POST /tasks/update {\"id\", \"list\"?, \"title\"?, \"due\"?, "
|
||||
"\"importance\"?, \"status\"?, \"description\"?} -> 200 {ok, id, status}",
|
||||
"POST /tasks/complete {\"id\", \"list\"?} -> 200 {ok, id, status} — "
|
||||
"marks the task completed",
|
||||
"POST /tasks/delete {\"id\", \"list\"?} -> 200 {\"ok\": true, \"id\"}",
|
||||
"GET /contacts?query=<text>&count=<n> -> 200 {\"contacts\": [{id, "
|
||||
"display_name, given_name, surname, emails, phones, company, "
|
||||
"job_title}]} — query filters by name/email/company",
|
||||
"GET /files?path=<dir> -> 200 {\"path\", \"entries\": [{id, name, "
|
||||
"path, size, modified, is_folder, content_type, web_url}]} — OneDrive "
|
||||
"folder listing (default root)",
|
||||
"GET /files/read?path=<path> -> 200 {\"path\", \"name\", \"content\", "
|
||||
"\"encoding\" (utf-8|base64), \"size\", \"content_type\", \"modified\"} "
|
||||
"— file contents; binary is base64",
|
||||
"POST /files/write {\"path\", \"content\", \"encoding\"?: "
|
||||
"utf-8|base64, \"overwrite\"?: bool} -> 200 {\"ok\": true, \"path\", "
|
||||
"\"id\", \"size\", \"web_url\"}",
|
||||
"any request -> 401 {\"error\": \"unauthorized\"} when the token is "
|
||||
"configured and the auth header is missing or wrong",
|
||||
"503 {\"error\": \"...\"} when the bridge is not authenticated "
|
||||
"(run packs/outlook/scripts/outlook-auth.py) or has no client id configured; 502 "
|
||||
"{\"error\": \"...\"} on a real Microsoft Graph failure (transport, "
|
||||
"HTTP error, or bad reply)",
|
||||
),
|
||||
config_vars=("outlook_bridge_url", "outlook_bridge_token"),
|
||||
config_var_docs=(
|
||||
(
|
||||
"outlook_bridge_url",
|
||||
"Base URL of the local Outlook bridge (e.g. "
|
||||
"http://127.0.0.1:5231); never hardcode it in the body.",
|
||||
),
|
||||
(
|
||||
"outlook_bridge_token",
|
||||
"Shared secret for the bridge, if one is configured; sent as the "
|
||||
"X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
),
|
||||
),
|
||||
auth_header="X-Semif-Token",
|
||||
auth_config_var="outlook_bridge_token",
|
||||
)
|
||||
|
||||
def __init__(self, config: dict | None = None, trace=None, client=None):
|
||||
super().__init__(config, trace)
|
||||
cfg = config or {}
|
||||
self.client_id = str(cfg.get("client_id", "") or "").strip()
|
||||
self.tenant = str(cfg.get("tenant", DEFAULT_TENANT) or DEFAULT_TENANT).strip() or DEFAULT_TENANT
|
||||
self.token_path = str(cfg.get("token_path") or DEFAULT_TOKEN_PATH)
|
||||
self.default_timezone = str(cfg.get("default_timezone", "UTC") or "UTC").strip() or "UTC"
|
||||
self.default_mail_folder = str(cfg.get("default_mail_folder", "inbox") or "inbox").strip() or "inbox"
|
||||
#: A test seam: inject a client double. Production builds the real one.
|
||||
self.client = client or OutlookClient(
|
||||
self.client_id,
|
||||
tenant=self.tenant,
|
||||
token_path=self.token_path,
|
||||
scopes=cfg.get("scopes") or DEFAULT_SCOPES,
|
||||
timeout=float(cfg.get("timeout", DEFAULT_TIMEOUT)),
|
||||
verify_tls=bool(cfg.get("verify_tls", True)),
|
||||
default_calendar=str(cfg.get("default_calendar", "") or "").strip(),
|
||||
default_task_list=str(cfg.get("default_task_list", "") or "").strip(),
|
||||
default_mail_folder=self.default_mail_folder,
|
||||
default_timezone=self.default_timezone,
|
||||
)
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def check_requirements(self) -> tuple[bool, str | None]:
|
||||
# Stdlib only: no missing dependency can make the bridge unstartable. A
|
||||
# missing authorization surfaces as a 503 on the call, not a startup failure.
|
||||
return True, None
|
||||
|
||||
# ---- routes ----
|
||||
|
||||
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/health":
|
||||
return 200, {"ok": True, "platform": self.name}
|
||||
if not self.client.configured:
|
||||
return self._unconfigured()
|
||||
try:
|
||||
return self._get(path, query)
|
||||
except OutlookAuthRequired as exc:
|
||||
return 503, {"error": str(exc)[:300]}
|
||||
except OutlookError as exc:
|
||||
return 502, {"error": str(exc)[:300]}
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)[:300]}
|
||||
|
||||
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
if not self.client.configured:
|
||||
return self._unconfigured()
|
||||
try:
|
||||
return self._post(path, payload)
|
||||
except OutlookAuthRequired as exc:
|
||||
return 503, {"error": str(exc)[:300]}
|
||||
except OutlookError as exc:
|
||||
return 502, {"error": str(exc)[:300]}
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)[:300]}
|
||||
|
||||
def _unconfigured(self) -> tuple[int, dict]:
|
||||
return 503, {
|
||||
"error": (
|
||||
"the Outlook bridge has no connection configured (set "
|
||||
"bridges.outlook.client_id, then run packs/outlook/scripts/outlook-auth.py)"
|
||||
)
|
||||
}
|
||||
|
||||
def _get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/user":
|
||||
return 200, {"user": self.client.me()}
|
||||
if path == "/mail/folders":
|
||||
return 200, {"folders": self.client.list_mail_folders()}
|
||||
if path == "/mail/messages":
|
||||
folder = self._q(query, "folder", "") or ""
|
||||
return 200, {
|
||||
"folder": folder or self.default_mail_folder,
|
||||
"messages": self.client.list_messages(
|
||||
folder,
|
||||
self._int_query(query, "count", 25),
|
||||
self._q(query, "search", "") or "",
|
||||
self._bool_query(query, "unread", False),
|
||||
),
|
||||
}
|
||||
if path == "/mail/messages/get":
|
||||
return 200, {"message": self.client.get_message(self._required_query(query, "id"))}
|
||||
if path == "/calendars":
|
||||
return 200, {"calendars": self.client.list_calendars()}
|
||||
if path == "/calendars/events":
|
||||
return 200, {
|
||||
"calendar": self._q(query, "calendar", "") or "",
|
||||
"events": self.client.list_events(
|
||||
self._q(query, "calendar", "") or "",
|
||||
self._q(query, "start", "") or "",
|
||||
self._q(query, "end", "") or "",
|
||||
),
|
||||
}
|
||||
if path == "/tasklists":
|
||||
return 200, {"tasklists": self.client.list_task_lists()}
|
||||
if path == "/tasks":
|
||||
task_list = self._q(query, "list", "") or ""
|
||||
return 200, {"list": task_list, "tasks": self.client.list_tasks(task_list)}
|
||||
if path == "/contacts":
|
||||
return 200, {
|
||||
"contacts": self.client.list_contacts(
|
||||
self._q(query, "query", "") or "", self._int_query(query, "count", 50)
|
||||
)
|
||||
}
|
||||
if path == "/files":
|
||||
folder = self._q(query, "path", "/") or "/"
|
||||
return 200, {"path": folder, "entries": self.client.list_files(folder)}
|
||||
if path == "/files/read":
|
||||
return 200, self.client.read_file(self._required_query(query, "path"))
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
def _post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
if path == "/mail/send":
|
||||
recipients = self._string_list(payload, "to")
|
||||
if not recipients:
|
||||
raise ValueError("to is required")
|
||||
return 200, self.client.send_mail(
|
||||
recipients,
|
||||
self._optional_str(payload, "subject"),
|
||||
self._optional_str(payload, "body"),
|
||||
self._string_list(payload, "cc"),
|
||||
self._optional_str(payload, "content_type", "text") or "text",
|
||||
)
|
||||
if path == "/mail/draft":
|
||||
return 200, self.client.create_draft(
|
||||
self._string_list(payload, "to"),
|
||||
self._optional_str(payload, "subject"),
|
||||
self._optional_str(payload, "body"),
|
||||
self._string_list(payload, "cc"),
|
||||
self._optional_str(payload, "content_type", "text") or "text",
|
||||
)
|
||||
if path == "/calendars/events":
|
||||
return 200, self.client.create_event(
|
||||
calendar=self._optional_str(payload, "calendar"),
|
||||
subject=self._required(payload, "subject"),
|
||||
start=self._required(payload, "start"),
|
||||
end=self._optional_str(payload, "end"),
|
||||
all_day=self._optional_bool(payload, "all_day", False),
|
||||
location=self._optional_str(payload, "location"),
|
||||
description=self._optional_str(payload, "description"),
|
||||
attendees=self._string_list(payload, "attendees"),
|
||||
timezone_name=self._optional_str(payload, "timezone"),
|
||||
)
|
||||
if path == "/calendars/events/update":
|
||||
event_id = self._required(payload, "id")
|
||||
changes = {
|
||||
key: payload[key]
|
||||
for key in ("subject", "start", "end", "location", "description")
|
||||
if key in payload
|
||||
}
|
||||
if "all_day" in payload:
|
||||
changes["all_day"] = self._optional_bool(payload, "all_day", False)
|
||||
return 200, self.client.update_event(
|
||||
event_id, timezone_name=self._optional_str(payload, "timezone"), **changes
|
||||
)
|
||||
if path == "/calendars/events/delete":
|
||||
return 200, self.client.delete_event(self._required(payload, "id"))
|
||||
if path == "/tasks":
|
||||
return 200, self.client.create_task(
|
||||
task_list=self._optional_str(payload, "list"),
|
||||
title=self._required(payload, "title"),
|
||||
due=self._optional_str(payload, "due"),
|
||||
importance=self._optional_str(payload, "importance"),
|
||||
description=self._optional_str(payload, "description"),
|
||||
)
|
||||
if path == "/tasks/update":
|
||||
task_id = self._required(payload, "id")
|
||||
changes = {
|
||||
key: payload[key]
|
||||
for key in ("title", "due", "importance", "status", "description")
|
||||
if key in payload
|
||||
}
|
||||
return 200, self.client.update_task(
|
||||
task_id, task_list=self._optional_str(payload, "list"), **changes
|
||||
)
|
||||
if path == "/tasks/complete":
|
||||
return 200, self.client.complete_task(
|
||||
self._required(payload, "id"), task_list=self._optional_str(payload, "list")
|
||||
)
|
||||
if path == "/tasks/delete":
|
||||
return 200, self.client.delete_task(
|
||||
self._required(payload, "id"), task_list=self._optional_str(payload, "list")
|
||||
)
|
||||
if path == "/files/write":
|
||||
return 200, self.client.write_file(
|
||||
self._required(payload, "path"),
|
||||
self._required(payload, "content", allow_empty=True),
|
||||
self._optional_str(payload, "encoding", "utf-8") or "utf-8",
|
||||
self._optional_bool(payload, "overwrite", True),
|
||||
)
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
# ---- input helpers ----
|
||||
|
||||
@staticmethod
|
||||
def _q(query: dict, key: str, default=None):
|
||||
values = query.get(key)
|
||||
if not values:
|
||||
return default
|
||||
return values[0]
|
||||
|
||||
@staticmethod
|
||||
def _required_query(query: dict, key: str) -> str:
|
||||
value = OutlookBridge._q(query, key)
|
||||
if value is None or not str(value).strip():
|
||||
raise ValueError(f"{key} is required")
|
||||
return str(value).strip()
|
||||
|
||||
@staticmethod
|
||||
def _int_query(query: dict, key: str, default: int) -> int:
|
||||
value = OutlookBridge._q(query, key)
|
||||
if value is None or str(value).strip() == "":
|
||||
return default
|
||||
try:
|
||||
return int(str(value))
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"{key} must be an integer") from exc
|
||||
|
||||
@staticmethod
|
||||
def _bool_query(query: dict, key: str, default: bool) -> bool:
|
||||
value = OutlookBridge._q(query, key)
|
||||
if value is None or str(value).strip() == "":
|
||||
return default
|
||||
return str(value).strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
@staticmethod
|
||||
def _required(payload: dict, key: str, allow_empty: bool = False) -> str:
|
||||
value = payload.get(key)
|
||||
if not isinstance(value, str) or (not allow_empty and not value.strip()):
|
||||
raise ValueError(f"{key} is required")
|
||||
return value if allow_empty else value.strip()
|
||||
|
||||
@staticmethod
|
||||
def _optional_str(payload: dict, key: str, default: str = "") -> str:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(f"{key} must be a string")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_bool(payload: dict, key: str, default: bool) -> bool:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, bool):
|
||||
raise ValueError(f"{key} must be a boolean")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _string_list(payload: dict, key: str) -> list[str]:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return []
|
||||
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
|
||||
raise ValueError(f"{key} must be a list of strings")
|
||||
return value
|
||||
File diff suppressed because it is too large.
Load diff
+206
-48
@@ -1,43 +1,216 @@
|
||||
"""The bridge catalog: discovery, prompt description, and standalone runner.
|
||||
|
||||
Every known bridge class is listed in `CATALOG`. `known_infos()` exposes their
|
||||
static metadata, `describe_bridges()` renders the catalog block injected into
|
||||
the code-generation prompts, and `run_bridges()` starts the enabled ones as a
|
||||
standalone process (`python -m semif_agent.cli bridge`). Adding a bridge means
|
||||
adding its class here and a `config.example.json` block; the gateway is never
|
||||
touched.
|
||||
A bridge implementation ships **with its pack** (``packs/<name>/bridge/``); the
|
||||
core owns only the shared contract (``bridges/base.py``) and this registry. A
|
||||
pack's ``pack.json`` names its bridge(s) in ``bridges`` and ships one module per
|
||||
name under ``bridge/`` (``bridge/<name>.py``, plus optional sibling modules such
|
||||
as ``bridge/<name>_client.py``). The registry imports each enabled pack's bridge
|
||||
by convention, so nothing in the core names a concrete bridge — a new bridge is a
|
||||
new pack, not a core edit.
|
||||
|
||||
The shared, pack-less **LLM bridge** stays a core built-in (``CORE_BRIDGES``):
|
||||
many packs call it, so it belongs to no single concern. ``known_infos()`` exposes
|
||||
every bridge's static metadata, ``describe_bridges()`` renders the catalog block
|
||||
injected into the code-generation prompts, and ``run_bridges()`` starts the
|
||||
enabled ones as a standalone process (``python -m semif_agent.cli bridge``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import importlib.util
|
||||
import sys
|
||||
import threading
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .browser import BrowserBridge
|
||||
from .llm import LLMBridge
|
||||
from .nextcloud import NextcloudBridge
|
||||
from .outlook import OutlookBridge
|
||||
from .simplex import SimplexBridge
|
||||
|
||||
#: Known bridge services. Order is presentation order.
|
||||
CATALOG: tuple[type[BridgeService], ...] = (
|
||||
SimplexBridge,
|
||||
LLMBridge,
|
||||
NextcloudBridge,
|
||||
OutlookBridge,
|
||||
BrowserBridge,
|
||||
)
|
||||
#: The agent checkout root; a relative pack root resolves against it, and the
|
||||
#: default pack root is ``<checkout>/packs``.
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
DEFAULT_PACK_ROOT = REPO_ROOT / "packs"
|
||||
|
||||
#: Bridges that belong to no pack — shared services any pack may call. They
|
||||
#: still live under ``bridges.<name>`` so ``derived_config_vars`` and
|
||||
#: ``run_bridges`` find them. Order is presentation order.
|
||||
CORE_BRIDGES: tuple[type[BridgeService], ...] = (LLMBridge,)
|
||||
|
||||
#: Pack-discovered bridge classes, keyed by ``pack:bridge:path`` (loaded once
|
||||
#: per process).
|
||||
_CLASS_CACHE: dict[str, type[BridgeService]] = {}
|
||||
|
||||
#: Packs the running scheduler discovered; ``describe_bridges()`` (called from
|
||||
#: codegen with no config) prefers these over a fresh default-root scan.
|
||||
_ACTIVE_PACKS: list | None = None
|
||||
|
||||
|
||||
def _class_for(name: str) -> type[BridgeService] | None:
|
||||
for bridge_class in CATALOG:
|
||||
def set_bridge_packs(packs) -> None:
|
||||
"""Record the packs the running agent loaded, for prompt-time discovery.
|
||||
|
||||
``describe_bridges()`` is called from codegen, which has no config in hand;
|
||||
``build_scheduler`` calls this after loading packs so the catalog reflects
|
||||
the host's real ``skill_packs`` roots. ``None`` restores default discovery.
|
||||
"""
|
||||
global _ACTIVE_PACKS
|
||||
_ACTIVE_PACKS = list(packs) if packs is not None else None
|
||||
|
||||
|
||||
def _resolve_roots(roots) -> list[Path]:
|
||||
if isinstance(roots, (str, Path)):
|
||||
roots = [roots]
|
||||
if not roots:
|
||||
roots = [DEFAULT_PACK_ROOT]
|
||||
resolved = []
|
||||
for root in roots:
|
||||
path = Path(str(root))
|
||||
resolved.append(path if path.is_absolute() else REPO_ROOT / path)
|
||||
return resolved
|
||||
|
||||
|
||||
def _packs_from_roots(roots=None) -> list:
|
||||
from ..packs import PackRegistry
|
||||
|
||||
return PackRegistry(_resolve_roots(roots)).discover()
|
||||
|
||||
|
||||
def _packs_from_config(config: dict) -> list:
|
||||
return _packs_from_roots((config or {}).get("skill_packs"))
|
||||
|
||||
|
||||
def _packs(packs=None) -> list:
|
||||
if packs is not None:
|
||||
return list(packs)
|
||||
if _ACTIVE_PACKS is not None:
|
||||
return list(_ACTIVE_PACKS)
|
||||
return _packs_from_roots(None)
|
||||
|
||||
|
||||
def _load_package(module_name: str, directory: Path) -> types.ModuleType:
|
||||
"""Import ``directory`` as a package under ``module_name`` (idempotent).
|
||||
|
||||
The pack's ``bridge/`` folder is loaded from its real path (never relying on
|
||||
it being importable by name), so sibling modules and relative imports work
|
||||
regardless of where the pack was cloned. An absent ``__init__.py`` is fine —
|
||||
a synthetic package namespace is registered instead.
|
||||
"""
|
||||
existing = sys.modules.get(module_name)
|
||||
if existing is not None:
|
||||
return existing
|
||||
init = directory / "__init__.py"
|
||||
if not init.is_file():
|
||||
package = types.ModuleType(module_name)
|
||||
package.__path__ = [str(directory)] # type: ignore[attr-defined]
|
||||
package.__package__ = module_name
|
||||
sys.modules[module_name] = package
|
||||
return package
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
module_name, init, submodule_search_locations=[str(directory)]
|
||||
)
|
||||
if spec is None or spec.loader is None:
|
||||
raise ImportError(f"cannot load bridge package at {directory}")
|
||||
package = importlib.util.module_from_spec(spec)
|
||||
sys.modules[module_name] = package
|
||||
spec.loader.exec_module(package)
|
||||
return package
|
||||
|
||||
|
||||
def _find_bridge_class(module: types.ModuleType, name: str) -> type[BridgeService] | None:
|
||||
"""The ``BridgeService`` subclass a pack bridge module defines.
|
||||
|
||||
An explicit ``BRIDGE`` attribute wins; otherwise scan for subclasses defined
|
||||
in the module, preferring one whose ``INFO.name`` matches the pack's declared
|
||||
bridge name.
|
||||
"""
|
||||
explicit = getattr(module, "BRIDGE", None)
|
||||
if isinstance(explicit, type) and issubclass(explicit, BridgeService):
|
||||
return explicit
|
||||
candidates = [
|
||||
value
|
||||
for value in vars(module).values()
|
||||
if isinstance(value, type)
|
||||
and issubclass(value, BridgeService)
|
||||
and value is not BridgeService
|
||||
and getattr(value, "__module__", None) == module.__name__
|
||||
]
|
||||
for candidate in candidates:
|
||||
info = getattr(candidate, "INFO", None)
|
||||
if info is not None and getattr(info, "name", None) == name:
|
||||
return candidate
|
||||
return candidates[0] if candidates else None
|
||||
|
||||
|
||||
def load_pack_bridge_class(pack, bridge_name: str) -> type[BridgeService] | None:
|
||||
"""Import one pack's bridge module and return its bridge class (or None)."""
|
||||
bridge_dir = Path(pack.path) / "bridge"
|
||||
module_file = bridge_dir / f"{bridge_name}.py"
|
||||
if not module_file.is_file():
|
||||
return None
|
||||
package_name = f"semif_pack_bridge_{pack.name}"
|
||||
_load_package(package_name, bridge_dir)
|
||||
module = importlib.import_module(f"{package_name}.{bridge_name}")
|
||||
return _find_bridge_class(module, bridge_name)
|
||||
|
||||
|
||||
def load_pack_bridge_package(pack_name: str, packs=None) -> types.ModuleType:
|
||||
"""Import and return a pack's ``bridge/`` package.
|
||||
|
||||
The package is registered under the stable name
|
||||
``semif_pack_bridge_<pack>``, so a caller (a pack's own test, or a tool) can
|
||||
import a sibling module with ``importlib.import_module(f"{pkg.__name__}.<mod>")``.
|
||||
"""
|
||||
pack = next((p for p in _packs(packs) if p.name == pack_name), None)
|
||||
if pack is None:
|
||||
raise KeyError(f"unknown pack: {pack_name!r}")
|
||||
bridge_dir = Path(pack.path) / "bridge"
|
||||
if not bridge_dir.is_dir():
|
||||
raise KeyError(f"pack {pack_name!r} ships no bridge/ directory")
|
||||
return _load_package(f"semif_pack_bridge_{pack.name}", bridge_dir)
|
||||
|
||||
|
||||
def load_pack_bridge_module(
|
||||
pack_name: str, bridge_name: str, packs=None
|
||||
) -> types.ModuleType:
|
||||
"""Import and return one pack's bridge module (``bridge/<bridge_name>.py``)."""
|
||||
package = load_pack_bridge_package(pack_name, packs)
|
||||
return importlib.import_module(f"{package.__name__}.{bridge_name}")
|
||||
|
||||
|
||||
def discover_bridge_classes(packs=None) -> list[type[BridgeService]]:
|
||||
"""Every bridge class: the packs' bridges (in pack order) then core built-ins.
|
||||
|
||||
With no ``packs``, uses the running scheduler's packs, else a scan of the
|
||||
default pack root. A pack that declares a bridge but ships no ``bridge/``
|
||||
module is skipped (a half-authored pack never breaks the catalog).
|
||||
"""
|
||||
classes: list[type[BridgeService]] = []
|
||||
for pack in _packs(packs):
|
||||
for bridge_name in getattr(pack, "bridges", ()) or ():
|
||||
key = f"{pack.name}:{bridge_name}:{getattr(pack, 'path', '')}"
|
||||
if key not in _CLASS_CACHE:
|
||||
found = load_pack_bridge_class(pack, bridge_name)
|
||||
if found is None:
|
||||
continue
|
||||
_CLASS_CACHE[key] = found
|
||||
bridge_class = _CLASS_CACHE[key]
|
||||
if bridge_class not in classes:
|
||||
classes.append(bridge_class)
|
||||
for bridge_class in CORE_BRIDGES:
|
||||
if bridge_class not in classes:
|
||||
classes.append(bridge_class)
|
||||
return classes
|
||||
|
||||
|
||||
def _class_for(name: str, packs=None) -> type[BridgeService] | None:
|
||||
for bridge_class in discover_bridge_classes(packs):
|
||||
if bridge_class.INFO.name == name:
|
||||
return bridge_class
|
||||
return None
|
||||
|
||||
|
||||
def known_infos() -> list[BridgeInfo]:
|
||||
return [bridge_class.INFO for bridge_class in CATALOG]
|
||||
def known_infos(packs=None) -> list[BridgeInfo]:
|
||||
return [bridge_class.INFO for bridge_class in discover_bridge_classes(packs)]
|
||||
|
||||
|
||||
def derived_config_vars(config: dict) -> dict[str, str]:
|
||||
@@ -53,7 +226,7 @@ def derived_config_vars(config: dict) -> dict[str, str]:
|
||||
"""
|
||||
blocks = config.get("bridges", {}) or {}
|
||||
derived: dict[str, str] = {}
|
||||
for info in known_infos():
|
||||
for info in known_infos(_packs_from_config(config)):
|
||||
block = blocks.get(info.name)
|
||||
if not isinstance(block, dict):
|
||||
continue
|
||||
@@ -69,7 +242,7 @@ def derived_config_vars(config: dict) -> dict[str, str]:
|
||||
return derived
|
||||
|
||||
|
||||
def describe_bridges() -> str:
|
||||
def describe_bridges(packs=None) -> str:
|
||||
"""A prompt block describing every available bridge service.
|
||||
|
||||
Injected into the skill-body, retry, regen, and testgen
|
||||
@@ -87,7 +260,7 @@ def describe_bridges() -> str:
|
||||
"urllib.request rather than reaching around it; read every value from "
|
||||
"ctx.config:",
|
||||
]
|
||||
for info in known_infos():
|
||||
for info in known_infos(packs):
|
||||
lines.append(f"- {info.name} (service: {info.service}): {info.description}")
|
||||
lines.append(f" base URL config var: {info.url_config_var}")
|
||||
if info.auth_header and info.auth_config_var:
|
||||
@@ -114,32 +287,17 @@ def build_bridge(
|
||||
) -> BridgeService:
|
||||
"""Instantiate one bridge from the top-level `bridges.<name>` config block.
|
||||
|
||||
`llm` is the scheduler's configured language-model client, handed to the LLM
|
||||
bridge so it reuses the top-level `llm` endpoint/model instead of duplicating
|
||||
that config. The Nextcloud bridge gets the top-level `nextcloud_*` values as a
|
||||
fallback, so the same account the nextcloud pack's skills use is configured once. Other
|
||||
bridges ignore both.
|
||||
The class is discovered from the host's packs (plus the core built-ins); it
|
||||
is constructed through ``BridgeService.from_config``, so a bridge that needs
|
||||
the scheduler's ``llm`` client (the shared LLM bridge) or top-level fallback
|
||||
values (Nextcloud's ``nextcloud_*``) declares that itself rather than the
|
||||
core special-casing it by name.
|
||||
"""
|
||||
bridge_class = _class_for(name)
|
||||
bridge_class = _class_for(name, _packs_from_config(config))
|
||||
if bridge_class is None:
|
||||
raise KeyError(f"unknown bridge: {name!r}")
|
||||
block = (config.get("bridges", {}) or {}).get(name, {}) or {}
|
||||
if bridge_class is LLMBridge:
|
||||
return LLMBridge(block, trace=trace, client=llm)
|
||||
if bridge_class is NextcloudBridge:
|
||||
return NextcloudBridge(
|
||||
block,
|
||||
trace=trace,
|
||||
fallback={
|
||||
"url": config.get("nextcloud_url"),
|
||||
"username": config.get("nextcloud_username"),
|
||||
"app_password": config.get("nextcloud_app_password"),
|
||||
"default_calendar": config.get("nextcloud_default_calendar"),
|
||||
"default_task_calendar": config.get("nextcloud_default_task_calendar"),
|
||||
"default_addressbook": config.get("nextcloud_default_addressbook"),
|
||||
},
|
||||
)
|
||||
return bridge_class(block, trace=trace)
|
||||
return bridge_class.from_config(block, config=config, trace=trace, llm=llm)
|
||||
|
||||
|
||||
def run_bridges(
|
||||
@@ -156,7 +314,7 @@ def run_bridges(
|
||||
"""
|
||||
blocks = config.get("bridges", {}) or {}
|
||||
selected: list[BridgeService] = []
|
||||
for bridge_class in CATALOG:
|
||||
for bridge_class in discover_bridge_classes(_packs_from_config(config)):
|
||||
name = bridge_class.INFO.name
|
||||
if names and name not in names:
|
||||
continue
|
||||
|
||||
@@ -1,493 +0,0 @@
|
||||
"""SimpleX forwarding bridge: invite links, reading, and sending for skills.
|
||||
|
||||
The first third-party API bridge. It stands up a small HTTP API that a skill
|
||||
body calls instead of talking to `simplex-chat` directly, and it owns its **own**
|
||||
SimpleX daemon/profile — separate from the command gateway's. That separation is
|
||||
the point: the gateway takes commands; this bridge forwards the user's messaging
|
||||
UX (show/create the contact link, read the next message, compose a send).
|
||||
|
||||
It buffers every inbound direct message (no allowlist — the user wants to see
|
||||
who reached the bot through its invite link), and it never runs inside the
|
||||
gateway process.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
|
||||
from semif_agent.simplex_ws import SimplexDaemon, parse_send_response
|
||||
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .inbox import MessagingInbox
|
||||
|
||||
#: Send statuses that mean the message really left the agent.
|
||||
SEND_OK_STATUSES = frozenset({"sndSent", "sndRcvd"})
|
||||
#: Send statuses that are final (no further polling needed).
|
||||
SEND_TERMINAL_STATUSES = frozenset({"sndSent", "sndRcvd", "sndError"})
|
||||
#: How long to poll the daemon for a terminal send status before giving up.
|
||||
SEND_CONFIRM_TIMEOUT = 6.0
|
||||
SEND_POLL_INTERVAL = 0.5
|
||||
|
||||
|
||||
class SimplexBridge(BridgeService):
|
||||
name = "simplex"
|
||||
INFO = BridgeInfo(
|
||||
name="simplex",
|
||||
service="simplex",
|
||||
description=(
|
||||
"Read and send SimpleX messages on the user's behalf, and show or "
|
||||
"create the contact link others use to reach this agent."
|
||||
),
|
||||
url_config_var="simplex_bridge_url",
|
||||
endpoints=(
|
||||
"GET /health -> 200 {\"ok\": true, \"platform\": \"simplex\"} — the "
|
||||
"bridge is up",
|
||||
"GET /contacts -> 200 {\"contacts\": [{\"id\", \"display_name\", "
|
||||
"\"local_name\"?, \"connected\"?}]} — contacts known to the daemon "
|
||||
"(learned from inbound messages and refreshed from the daemon's "
|
||||
"contact list). `display_name` is the peer's profile name and can "
|
||||
"collide; `local_name` is the daemon's unique local name; "
|
||||
"`connected` (when the daemon reports it) is false for a peer whose "
|
||||
"connection is not ready — prefer a connected peer",
|
||||
"GET /inbox -> 200 {\"messages\": [{\"id\", \"contact_id\", "
|
||||
"\"display_name\", \"text\", \"received_at\"}]} — peek buffered "
|
||||
"inbound messages; does not consume",
|
||||
"GET /inbox/next?contact=<id> -> 200 {\"message\": {...}|null} — pop "
|
||||
"the oldest unread message (optionally from one contact); null means "
|
||||
"none buffered. The bridge owns the read cursor",
|
||||
"GET /unread -> 200 {\"chats\": [{\"contact_id\", \"display_name\", "
|
||||
"\"unread_count\", \"min_unread_item_id\", \"unread\", "
|
||||
"\"connected\"?, \"auth_errors\"?, \"messages\": "
|
||||
"[{item_id, text, status, unread, direction, sent_at}]}]} — the "
|
||||
"daemon's persistent unread chats (survives bridge restarts), not "
|
||||
"just what arrived while connected. Read-only; 503 when the daemon "
|
||||
"is not connected, 502 when the lookup fails",
|
||||
"GET /history?contact=<id>&count=<n> -> 200 {\"contact_id\", "
|
||||
"\"messages\": [{item_id, text, status, unread, direction, "
|
||||
"sent_at, error?}]} — recent message history for one contact (count "
|
||||
"default 20); status is rcvNew (unread), rcvRead, sndSent, sndRcvd, "
|
||||
"or sndError, and `error` carries the agent reason (e.g. auth) on a "
|
||||
"failed send. Read-only; 503/502 as /unread, 400 without a contact",
|
||||
"GET /address -> 200 {\"short_link\", \"full_link\", \"created\"} — "
|
||||
"the agent's contact link; creates it on first call. 503 when the "
|
||||
"daemon is not connected, 502 when the lookup fails",
|
||||
"POST /send {\"recipient\": \"<id|local_name|display_name>\", "
|
||||
"\"text\": \"...\"} -> 200 {\"ok\": bool, \"contact_id\": \"<id>\", "
|
||||
"\"item_id\": \"<id>\", \"status\": \"sndSent|sndRcvd|sndError\", "
|
||||
"\"error\": \"...\"?}. The bridge resolves the recipient, sends, and "
|
||||
"waits for the daemon's real send status: `ok` is true only for "
|
||||
"sndSent/sndRcvd, and a failed send (e.g. an auth error on a dead "
|
||||
"connection) returns ok:false with the reason — never a false "
|
||||
"success. 400 on a missing/invalid field or an unknown recipient",
|
||||
"POST /read {\"contact\": \"<id>\", \"item_ids\": [\"<id>\", ...]} -> "
|
||||
"200 {\"ok\": bool, \"contact_id\": \"<id>\", \"item_ids\": [...], "
|
||||
"\"status\": \"read|rejected|error|unavailable\", \"error\": "
|
||||
"\"...\"?} — mark the given received items read on the daemon so they "
|
||||
"leave its persistent unread state; only the listed ids are consumed. "
|
||||
"`ok` is true only when the daemon accepted it — never a fabricated "
|
||||
"success. 400 on a missing contact or empty item_ids",
|
||||
"any request -> 401 {\"error\": \"unauthorized\"} when the token is "
|
||||
"configured and the auth header is missing or wrong",
|
||||
),
|
||||
config_vars=(
|
||||
"simplex_bridge_url",
|
||||
"simplex_default_contact",
|
||||
"simplex_bridge_token",
|
||||
),
|
||||
config_var_docs=(
|
||||
(
|
||||
"simplex_bridge_url",
|
||||
"Base URL of the local SimpleX forwarding bridge "
|
||||
"(e.g. http://127.0.0.1:5227); never hardcode it in the body.",
|
||||
),
|
||||
(
|
||||
"simplex_default_contact",
|
||||
"Optional default SimpleX contact (contact id or display name) "
|
||||
"used when the request does not already make the conversation "
|
||||
"clear; leave blank to always choose among senders.",
|
||||
),
|
||||
(
|
||||
"simplex_bridge_token",
|
||||
"Shared secret for the bridge, if one is configured; sent as the "
|
||||
"X-Semif-Token header. Leave blank when the bridge requires no "
|
||||
"auth.",
|
||||
),
|
||||
),
|
||||
auth_header="X-Semif-Token",
|
||||
auth_config_var="simplex_bridge_token",
|
||||
)
|
||||
|
||||
def __init__(self, config: dict | None = None, trace=None, daemon=None):
|
||||
super().__init__(config, trace)
|
||||
cfg = config or {}
|
||||
self.inbox = MessagingInbox(int(cfg.get("max_inbox", 100)))
|
||||
self.daemon = daemon or SimplexDaemon(
|
||||
cfg.get("ws_url", "ws://127.0.0.1:5228"),
|
||||
user_id=int(cfg.get("user_id", 1)),
|
||||
auto_accept=bool(cfg.get("auto_accept", True)),
|
||||
reconnect=cfg.get("reconnect", {}) or {},
|
||||
on_connected=self._refresh_on_connect,
|
||||
trace=trace,
|
||||
name=self.name,
|
||||
)
|
||||
self._daemon_thread: threading.Thread | None = None
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def check_requirements(self) -> tuple[bool, str | None]:
|
||||
return self.daemon.check_requirements()
|
||||
|
||||
def start(self) -> int:
|
||||
port = super().start()
|
||||
self._daemon_thread = threading.Thread(
|
||||
target=self.daemon.run,
|
||||
args=(self._on_message,),
|
||||
name="bridge-simplex-daemon",
|
||||
daemon=True,
|
||||
)
|
||||
self._daemon_thread.start()
|
||||
return port
|
||||
|
||||
def _stop_transport(self) -> None:
|
||||
self.daemon.close()
|
||||
|
||||
def _on_message(self, message: dict) -> None:
|
||||
self.inbox.record(message)
|
||||
|
||||
async def _refresh_on_connect(self) -> None:
|
||||
"""Prime the contact list from the daemon on (re)connect.
|
||||
|
||||
Runs on the daemon's event loop, so it awaits `contacts()` directly
|
||||
rather than the thread-safe wrapper. A failure is traced, not fatal.
|
||||
"""
|
||||
contacts = await self.daemon.contacts()
|
||||
self.inbox.merge_contacts(contacts)
|
||||
self._event("contacts_refreshed", count=len(contacts))
|
||||
|
||||
# ---- routes ----
|
||||
|
||||
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/health":
|
||||
return 200, {"ok": True, "platform": self.name}
|
||||
if path == "/contacts":
|
||||
return 200, {"contacts": self.refresh_contacts()}
|
||||
if path == "/inbox":
|
||||
return 200, {"messages": self.inbox.peek()}
|
||||
if path == "/inbox/next":
|
||||
contact = (query.get("contact") or [None])[0]
|
||||
return 200, {"message": self.inbox.pop(contact)}
|
||||
if path == "/unread":
|
||||
return self._unread(query)
|
||||
if path == "/history":
|
||||
contact = (query.get("contact") or [None])[0]
|
||||
count = (query.get("count") or [None])[0]
|
||||
return self._history(contact, count)
|
||||
if path == "/address":
|
||||
return self._address()
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
if path == "/read":
|
||||
return self._read(payload)
|
||||
if path != "/send":
|
||||
return 404, {"error": "not found"}
|
||||
recipient = payload.get("recipient")
|
||||
text = payload.get("text")
|
||||
if not isinstance(recipient, str) or not recipient.strip():
|
||||
return 400, {"error": "recipient is required"}
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
return 400, {"error": "text is required"}
|
||||
try:
|
||||
result = self.send(recipient, text)
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)}
|
||||
return 200, result
|
||||
|
||||
# ---- actions ----
|
||||
|
||||
def _read(self, payload: dict) -> tuple[int, dict]:
|
||||
contact = payload.get("contact")
|
||||
item_ids = payload.get("item_ids")
|
||||
if not isinstance(contact, str) or not contact.strip():
|
||||
return 400, {"error": "contact is required"}
|
||||
if not isinstance(item_ids, list) or not item_ids:
|
||||
return 400, {"error": "item_ids is required"}
|
||||
try:
|
||||
result = self.mark_read(contact, item_ids)
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)}
|
||||
return 200, result
|
||||
|
||||
def mark_read(self, contact: str, item_ids) -> dict:
|
||||
"""Mark the given received items read on the bridge's own daemon.
|
||||
|
||||
Returns `{ok, contact_id, item_ids, status, error?}`. `ok` is True only
|
||||
when the daemon accepted the command; a disconnected or failing daemon
|
||||
reports the reason (never a false success). Reading is precise: only the
|
||||
listed item ids are consumed, so the rest of the chat stays unread.
|
||||
"""
|
||||
contact_id = str(contact or "").strip()
|
||||
ids = [str(i).strip() for i in (item_ids or []) if str(i).strip()]
|
||||
if not contact_id:
|
||||
raise ValueError("contact is required")
|
||||
if not ids:
|
||||
raise ValueError("item_ids is required")
|
||||
try:
|
||||
response = self.daemon.request_mark_read(contact_id, ids)
|
||||
except RuntimeError as exc:
|
||||
return {
|
||||
"ok": False,
|
||||
"contact_id": contact_id,
|
||||
"item_ids": ids,
|
||||
"status": "unavailable",
|
||||
"error": str(exc)[:300],
|
||||
}
|
||||
except Exception as exc: # TimeoutError, daemon error
|
||||
return {
|
||||
"ok": False,
|
||||
"contact_id": contact_id,
|
||||
"item_ids": ids,
|
||||
"status": "error",
|
||||
"error": str(exc)[:300],
|
||||
}
|
||||
ok = bool(response.get("ok")) if isinstance(response, dict) else False
|
||||
result = {
|
||||
"ok": ok,
|
||||
"contact_id": contact_id,
|
||||
"item_ids": ids,
|
||||
"status": "read" if ok else "rejected",
|
||||
}
|
||||
if not ok:
|
||||
detail = response.get("error") if isinstance(response, dict) else ""
|
||||
result["error"] = detail or "the daemon did not mark the items read"
|
||||
return result
|
||||
|
||||
def refresh_contacts(self) -> list[dict]:
|
||||
"""Best-effort refresh of the daemon's contact list into the inbox.
|
||||
|
||||
Never raises: when the daemon is not connected (or is slow) it returns
|
||||
whatever contacts are already cached, so `/contacts` and `/send` stay
|
||||
available. The read cursor and inbound-learned names are preserved.
|
||||
"""
|
||||
try:
|
||||
contacts = self.daemon.request_contacts()
|
||||
except Exception as exc: # RuntimeError, TimeoutError, daemon error
|
||||
self._event("contacts_refresh_failed", message=str(exc)[:200])
|
||||
return self.inbox.contacts()
|
||||
self.inbox.merge_contacts(contacts)
|
||||
self._event("contacts_refreshed", count=len(contacts))
|
||||
return self.inbox.contacts()
|
||||
|
||||
def _unread(self, query: dict) -> tuple[int, dict]:
|
||||
"""The daemon's persistent unread chats (not the live receive buffer).
|
||||
|
||||
Read-only: there is no mark-read command in v7, so this never consumes.
|
||||
Best-effort like `/address` — 503 when the daemon is not connected, 502
|
||||
when the lookup fails, never a fabricated chat.
|
||||
"""
|
||||
count = self._count((query.get("count") or [None])[0])
|
||||
try:
|
||||
chats = self.daemon.request_chats(unread_only=True, count=count)
|
||||
except RuntimeError as exc:
|
||||
return 503, {"error": f"unread lookup is not available: {exc}"[:300]}
|
||||
except Exception as exc: # TimeoutError, daemon error
|
||||
return 502, {"error": f"unread lookup failed: {exc}"[:300]}
|
||||
self._attach_health(chats)
|
||||
return 200, {"chats": chats}
|
||||
|
||||
def _attach_health(self, chats: list[dict]) -> None:
|
||||
"""Merge cached connection health into each chat summary, in place.
|
||||
|
||||
Lets a caller prefer a live conversation over a stale duplicate when
|
||||
several chats share a display name. Best-effort: a chat with no cached
|
||||
contact is left untouched.
|
||||
"""
|
||||
health = {c["id"]: c for c in self.inbox.contacts()}
|
||||
for chat in chats:
|
||||
info = health.get(str(chat.get("contact_id") or ""))
|
||||
if not info:
|
||||
continue
|
||||
for key in ("connected", "auth_errors"):
|
||||
if key in info:
|
||||
chat[key] = info[key]
|
||||
|
||||
def _history(self, contact: str | None, count: str | None) -> tuple[int, dict]:
|
||||
"""Recent message history for one contact, straight from the daemon.
|
||||
|
||||
Read-only. A missing contact is a client error; a disconnected or
|
||||
failing daemon degrades like `/unread`.
|
||||
"""
|
||||
contact = str(contact or "").strip()
|
||||
if not contact:
|
||||
return 400, {"error": "contact is required"}
|
||||
try:
|
||||
messages = self.daemon.request_chat_history(
|
||||
contact, count=self._count(count)
|
||||
)
|
||||
except RuntimeError as exc:
|
||||
return 503, {"error": f"history lookup is not available: {exc}"[:300]}
|
||||
except Exception as exc: # TimeoutError, daemon error
|
||||
return 502, {"error": f"history lookup failed: {exc}"[:300]}
|
||||
return 200, {"contact_id": contact, "messages": messages}
|
||||
|
||||
@staticmethod
|
||||
def _count(raw: str | None, default: int = 20, maximum: int = 100) -> int:
|
||||
try:
|
||||
value = int(raw) if raw is not None else default
|
||||
except (TypeError, ValueError):
|
||||
value = default
|
||||
return max(1, min(value, maximum))
|
||||
|
||||
def _address(self) -> tuple[int, dict]:
|
||||
try:
|
||||
link = self.daemon.request_address()
|
||||
except RuntimeError as exc:
|
||||
return 503, {"error": f"address lookup is not available: {exc}"[:300]}
|
||||
except Exception as exc: # TimeoutError, daemon error
|
||||
return 502, {"error": f"address lookup failed: {exc}"[:300]}
|
||||
if not isinstance(link, dict):
|
||||
return 502, {"error": "address lookup returned no link"}
|
||||
return 200, link
|
||||
|
||||
def send(self, recipient: str, text: str) -> dict:
|
||||
"""Resolve a recipient, send the text, and report the real outcome.
|
||||
|
||||
Returns `{ok, contact_id, item_id?, status?, error?}`. `ok` is True only
|
||||
when the daemon created the message and it reached a terminal status of
|
||||
`sndSent` (relayed to the server) or `sndRcvd` (delivered to the peer).
|
||||
A dead connection surfaces as `ok: false` carrying the daemon's agent
|
||||
error (e.g. `auth`) — never a false success.
|
||||
"""
|
||||
contact_id = self.resolve(recipient)
|
||||
if contact_id is None:
|
||||
raise ValueError(f"unknown SimpleX recipient: {recipient!r}")
|
||||
try:
|
||||
response = self.daemon.request_send(contact_id, text)
|
||||
except RuntimeError as exc:
|
||||
return {
|
||||
"ok": False,
|
||||
"contact_id": contact_id,
|
||||
"status": "unavailable",
|
||||
"error": str(exc)[:300],
|
||||
}
|
||||
except Exception as exc: # TimeoutError, daemon error
|
||||
return {
|
||||
"ok": False,
|
||||
"contact_id": contact_id,
|
||||
"status": "error",
|
||||
"error": str(exc)[:300],
|
||||
}
|
||||
parsed = parse_send_response(response)
|
||||
if parsed["item_id"] is None:
|
||||
return {
|
||||
"ok": False,
|
||||
"contact_id": contact_id,
|
||||
"status": "rejected",
|
||||
"error": parsed["error"] or "the daemon rejected the send",
|
||||
}
|
||||
item_id = parsed["item_id"]
|
||||
status, error = parsed["status"], parsed["error"]
|
||||
if status not in SEND_TERMINAL_STATUSES:
|
||||
status, error = self._await_send_status(contact_id, item_id, status)
|
||||
result = {
|
||||
"ok": status in SEND_OK_STATUSES,
|
||||
"contact_id": contact_id,
|
||||
"item_id": item_id,
|
||||
"status": status,
|
||||
}
|
||||
if not result["ok"]:
|
||||
result["error"] = error or f"send status {status}"
|
||||
return result
|
||||
|
||||
def _await_send_status(
|
||||
self, contact_id: str, item_id: str, current: str,
|
||||
timeout: float = SEND_CONFIRM_TIMEOUT,
|
||||
) -> tuple[str, str]:
|
||||
"""Poll the daemon for the item's terminal send status + agent error.
|
||||
|
||||
A send is `sndNew` the moment it is created; the agent then resolves it
|
||||
to `sndSent`/`sndRcvd` (success) or `sndError` (failure, with the reason
|
||||
in `agentError`). Returns `(status, error)`; a still-`sndNew` item after
|
||||
the window stays unconfirmed rather than being reported as sent.
|
||||
"""
|
||||
deadline = time.monotonic() + timeout
|
||||
status, error = current, ""
|
||||
while True:
|
||||
try:
|
||||
messages = self.daemon.request_chat_history(contact_id, count=20)
|
||||
except Exception:
|
||||
return status or "unknown", error
|
||||
for message in messages:
|
||||
if str(message.get("item_id")) == str(item_id):
|
||||
status = str(message.get("status") or "")
|
||||
error = str(message.get("error") or "")
|
||||
if status in SEND_TERMINAL_STATUSES:
|
||||
return status, error
|
||||
if time.monotonic() >= deadline:
|
||||
return status or "unknown", error
|
||||
time.sleep(SEND_POLL_INTERVAL)
|
||||
|
||||
def resolve(self, recipient: str) -> str | None:
|
||||
"""A numeric id (with or without `@`), a unique local name, or a display name.
|
||||
|
||||
An explicit id always wins. Two peers can share a profile display name
|
||||
(the daemon suffixes its own local names, e.g. `pepper` / `pepper_1`),
|
||||
so a local-name or display-name match that hits several peers prefers
|
||||
the healthiest (connected, no recorded auth errors). On a miss, refresh
|
||||
the daemon's contact list once and retry: a contact the bridge has never
|
||||
received from is still addressable as long as the daemon knows them.
|
||||
"""
|
||||
recipient = str(recipient or "").strip()
|
||||
if not recipient:
|
||||
return None
|
||||
bare = recipient.lstrip("@")
|
||||
if bare.isdigit():
|
||||
return bare
|
||||
match = self._match_contact(recipient)
|
||||
if match is None:
|
||||
self.refresh_contacts()
|
||||
match = self._match_contact(recipient)
|
||||
return match
|
||||
|
||||
def _match_contact(self, recipient: str) -> str | None:
|
||||
contacts = self.inbox.contacts()
|
||||
for contact in contacts:
|
||||
if contact["id"] == recipient:
|
||||
return contact["id"]
|
||||
exact = [
|
||||
c
|
||||
for c in contacts
|
||||
if c.get("local_name") == recipient or c["display_name"] == recipient
|
||||
]
|
||||
if exact:
|
||||
return self._prefer_connected(exact)
|
||||
lowered = recipient.lower()
|
||||
partial = [
|
||||
c
|
||||
for c in contacts
|
||||
if lowered in c["display_name"].lower()
|
||||
or lowered in str(c.get("local_name", "")).lower()
|
||||
]
|
||||
if len(partial) == 1:
|
||||
return partial[0]["id"]
|
||||
if partial:
|
||||
return self._prefer_connected(partial)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _prefer_connected(matches: list[dict]) -> str:
|
||||
"""Pick the healthiest peer among equally-named matches.
|
||||
|
||||
Prefer a ready connection, then a connection with no recorded auth
|
||||
errors (a stale duplicate that fails to send), and finally the first.
|
||||
"""
|
||||
|
||||
def rank(contact: dict) -> tuple[bool, bool]:
|
||||
try:
|
||||
clean = int(contact.get("auth_errors") or 0) == 0
|
||||
except (TypeError, ValueError):
|
||||
clean = True
|
||||
return (bool(contact.get("connected")), clean)
|
||||
|
||||
return max(matches, key=rank)["id"]
|
||||
Reference in new issue
Block a user