feat(webui): add guided setup flows

* feat(channels): add guided setup flows

* test(channels): preserve setup config values

* fix(channels): reflect saved setup state

* refactor(channels): simplify setup state metadata

* fix(channels): harden setup lifecycle

* refactor(channels): centralize setup contracts

* fix(channels): route setup actions through webui shim

* fix(channels): adapt settings for compact screens

* fix(models): preserve default preset display

* feat(models): add curated Codex catalog

* fix(webui): stop attached gateway on interrupt

* fix(webui): simplify apps catalog

* docs(webui): clarify apps and runtime features

* feat(settings): add guided capability setup

* fix(webui): harden setup and managed services

* test: keep managed runtime checks portable

* test: scope POSIX runtime coverage

* fix(webui): simplify file settings

* feat(files): bundle document reading

* fix(webui): harden setup request boundaries

* fix(webui): prevent channel setup status squeeze

* fix(settings): group provider compatibility aliases

* refactor(settings): remove redundant setup surfaces

* fix(webui): harden guided setup lifecycle

* fix(webui): preserve channel setup compatibility
This commit is contained in:
Xubin Ren authored and GitHub committed 2026-07-13 13:11:46 +08:00
1 parent 791c7fd505
commit fe0717b385
92 files changed
+15058 -1311

No files matched your search

+184
View File
@@ -0,0 +1,184 @@
"""Helpers for channel instance configuration.
The first consumer is Feishu/Lark. Keep the helpers small and data-oriented so
ChannelManager can support Feishu assistant instances without turning every
channel into a multi-instance abstraction.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Any
from loguru import logger
from nanobot.config.loader import merge_missing_defaults
DEFAULT_INSTANCE_ID = "default"
_INSTANCE_ID_RE = re.compile(r"^[A-Za-z0-9_-]+$")
@dataclass(frozen=True)
class ChannelInstanceSpec:
"""Runtime description for one channel instance."""
base_name: str
instance_id: str
runtime_name: str
config: dict[str, Any]
def validate_instance_id(value: str) -> str:
"""Return a normalized instance id or raise ValueError."""
instance_id = value.strip()
if not instance_id or not _INSTANCE_ID_RE.fullmatch(instance_id):
raise ValueError("instance id must match [A-Za-z0-9_-]+")
return instance_id
def runtime_channel_name(base_name: str, instance_id: str) -> str:
"""Return the channel key used for routing messages at runtime."""
return base_name if instance_id == DEFAULT_INSTANCE_ID else f"{base_name}.{instance_id}"
def _base_feishu_instance_config(defaults: dict[str, Any]) -> dict[str, Any]:
config = dict(defaults)
config["instanceId"] = DEFAULT_INSTANCE_ID
config["name"] = "nanobot"
return config
def _normalize_feishu_instance(
raw: dict[str, Any],
defaults: dict[str, Any],
*,
inherited: dict[str, Any] | None = None,
fallback_id: str = DEFAULT_INSTANCE_ID,
) -> dict[str, Any]:
config = merge_missing_defaults(inherited or {}, defaults)
config = merge_missing_defaults(raw, config)
raw_id = raw.get("id") or raw.get("instanceId") or raw.get("instance_id") or fallback_id
instance_id = validate_instance_id(str(raw_id))
config["id"] = instance_id
config["instanceId"] = instance_id
config.setdefault("name", "nanobot" if instance_id == DEFAULT_INSTANCE_ID else f"nanobot {instance_id}")
return config
def feishu_instance_specs(
section: Any,
defaults: dict[str, Any],
*,
enabled_only: bool = False,
) -> list[ChannelInstanceSpec]:
"""Expand legacy or canonical Feishu config into runtime instance specs."""
if hasattr(section, "model_dump"):
section = section.model_dump(mode="json", by_alias=True)
if not isinstance(section, dict):
section = {}
instances = section.get("instances")
raw_specs: list[dict[str, Any]]
inherited: dict[str, Any] | None = None
if isinstance(instances, list):
inherited = {key: value for key, value in section.items() if key != "instances"}
raw_specs = [item for item in instances if isinstance(item, dict)]
else:
raw_specs = [section] if section else [_base_feishu_instance_config(defaults)]
specs: list[ChannelInstanceSpec] = []
for index, raw in enumerate(raw_specs):
fallback_id = DEFAULT_INSTANCE_ID if index == 0 else f"assistant-{index + 1}"
try:
config = _normalize_feishu_instance(
raw,
defaults,
inherited=inherited,
fallback_id=fallback_id,
)
except ValueError as exc:
logger.warning("Skipping invalid Feishu instance config: {}", exc)
continue
enabled = bool(config.get("enabled", defaults.get("enabled", False)))
if enabled_only and not enabled:
continue
instance_id = str(config["instanceId"])
specs.append(
ChannelInstanceSpec(
base_name="feishu",
instance_id=instance_id,
runtime_name=runtime_channel_name("feishu", instance_id),
config=config,
)
)
return specs
def canonical_feishu_section(section: Any, defaults: dict[str, Any]) -> dict[str, Any]:
"""Return Feishu config in the canonical ``instances`` shape."""
specs = feishu_instance_specs(section, defaults)
return {"instances": [dict(spec.config) for spec in specs]}
def upsert_feishu_instance(
section: Any,
defaults: dict[str, Any],
instance_id: str,
values: dict[str, Any],
) -> dict[str, Any]:
"""Return canonical Feishu section with one instance created or updated."""
instance_id = validate_instance_id(instance_id)
canonical = canonical_feishu_section(section, defaults)
instances = canonical.setdefault("instances", [])
for instance in instances:
if instance.get("id") == instance_id or instance.get("instanceId") == instance_id:
instance.update(values)
instance["id"] = instance_id
instance["instanceId"] = instance_id
instance.setdefault("name", "nanobot" if instance_id == DEFAULT_INSTANCE_ID else f"nanobot {instance_id}")
return canonical
config = _normalize_feishu_instance(
{**values, "id": instance_id},
defaults,
fallback_id=instance_id,
)
instances.append(config)
return canonical
def update_feishu_instance_preserving_shape(
section: Any,
defaults: dict[str, Any],
instance_id: str,
values: dict[str, Any],
) -> dict[str, Any]:
"""Update background metadata without migrating a legacy flat section."""
instance_id = validate_instance_id(instance_id)
if hasattr(section, "model_dump"):
section = section.model_dump(mode="json", by_alias=True)
if (
instance_id == DEFAULT_INSTANCE_ID
and isinstance(section, dict)
and not isinstance(section.get("instances"), list)
):
return {**section, **values}
return upsert_feishu_instance(section, defaults, instance_id, values)
def set_feishu_instance_enabled(
section: Any,
defaults: dict[str, Any],
instance_id: str,
enabled: bool,
) -> dict[str, Any]:
"""Return canonical Feishu section with one instance's enabled flag updated."""
return upsert_feishu_instance(section, defaults, instance_id, {"enabled": enabled})
+126
View File
@@ -0,0 +1,126 @@
"""Shared Feishu/Lark WebSocket runtime.
The official lark_oapi websocket client stores an asyncio loop in a module-level
variable. Running one blocking ``Client.start()`` per assistant would make
multiple Feishu instances fragile, so this module centralizes the loop patch and
starts each client through the SDK's async primitives on one dedicated loop.
"""
from __future__ import annotations
import asyncio
import threading
from contextlib import suppress
from dataclasses import dataclass
from typing import Any
from loguru import logger
@dataclass
class _ClientRuntime:
client: Any
stop_event: asyncio.Event
task: asyncio.Task
class FeishuWsRunner:
"""Run multiple lark_oapi websocket clients on one dedicated event loop."""
def __init__(self) -> None:
self._thread: threading.Thread | None = None
self._loop: asyncio.AbstractEventLoop | None = None
self._ready = threading.Event()
self._lock = threading.Lock()
self._clients: dict[str, _ClientRuntime] = {}
async def start_client(self, key: str, client: Any) -> None:
"""Start or replace one client runtime."""
loop = self._ensure_loop()
await asyncio.wrap_future(
asyncio.run_coroutine_threadsafe(self._start_client(key, client), loop)
)
async def stop_client(self, key: str) -> None:
"""Stop one client runtime if it is active."""
loop = self._loop
if loop is None or loop.is_closed():
return
await asyncio.wrap_future(asyncio.run_coroutine_threadsafe(self._stop_client(key), loop))
def _ensure_loop(self) -> asyncio.AbstractEventLoop:
with self._lock:
if self._loop is not None and not self._loop.is_closed():
return self._loop
self._ready.clear()
self._thread = threading.Thread(target=self._run_loop, name="feishu-ws", daemon=True)
self._thread.start()
if not self._ready.wait(timeout=10) or self._loop is None:
raise RuntimeError("Feishu WebSocket runner did not start")
return self._loop
def _run_loop(self) -> None:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
import lark_oapi.ws.client as lark_ws_client
lark_ws_client.loop = loop
self._loop = loop
self._ready.set()
loop.run_forever()
finally:
with suppress(Exception):
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
async def _start_client(self, key: str, client: Any) -> None:
await self._stop_client(key)
stop_event = asyncio.Event()
task = asyncio.create_task(self._client_main(key, client, stop_event))
self._clients[key] = _ClientRuntime(client=client, stop_event=stop_event, task=task)
async def _stop_client(self, key: str) -> None:
runtime = self._clients.pop(key, None)
if runtime is None:
return
runtime.stop_event.set()
with suppress(Exception):
await runtime.client._disconnect()
runtime.task.cancel()
with suppress(asyncio.CancelledError):
await runtime.task
async def _client_main(self, key: str, client: Any, stop_event: asyncio.Event) -> None:
ping_task: asyncio.Task | None = None
while not stop_event.is_set():
try:
await client._connect()
ping_task = asyncio.create_task(client._ping_loop())
await stop_event.wait()
except asyncio.CancelledError:
raise
except Exception as exc:
logger.warning("Feishu WebSocket client '{}' failed: {}", key, exc)
with suppress(Exception):
await client._disconnect()
if not stop_event.is_set():
await asyncio.sleep(5)
finally:
if ping_task is not None:
ping_task.cancel()
with suppress(asyncio.CancelledError):
await ping_task
with suppress(Exception):
await client._disconnect()
_RUNNER: FeishuWsRunner | None = None
def get_feishu_ws_runner() -> FeishuWsRunner:
"""Return the process-wide Feishu WebSocket runner."""
global _RUNNER
if _RUNNER is None:
_RUNNER = FeishuWsRunner()
return _RUNNER
+343
View File
@@ -0,0 +1,343 @@
"""Shared channel setup contract for configuration, display, and validation."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Literal
FieldKind = Literal["string", "secret", "list", "bool", "int", "enum"]
RouteFieldType = str | tuple[str, set[str]]
@dataclass(frozen=True)
class ChannelFieldSpec:
"""One channel field exposed through the settings contract."""
kind: FieldKind = "string"
choices: frozenset[str] = frozenset()
writable: bool = True
snapshot: bool = True
@property
def route_type(self) -> RouteFieldType:
if self.kind == "enum":
return ("enum", set(self.choices))
return self.kind
@dataclass(frozen=True)
class SetupRequirement:
"""A requirement satisfied by any one complete field group."""
alternatives: tuple[tuple[str, ...], ...]
def is_satisfied(self, values: Any) -> bool:
return any(
all(channel_value_present(channel_field_value(values, field)) for field in group)
for group in self.alternatives
)
@property
def simple_field(self) -> str | None:
if len(self.alternatives) == 1 and len(self.alternatives[0]) == 1:
return self.alternatives[0][0]
return None
@dataclass(frozen=True)
class ChannelSetupSpec:
"""Save, display, and validation contract for one channel."""
fields: dict[str, ChannelFieldSpec]
required: tuple[SetupRequirement, ...] = ()
official_url: str | None = None
@property
def secrets(self) -> frozenset[str]:
return frozenset(name for name, field in self.fields.items() if field.kind == "secret")
@property
def snapshot_fields(self) -> tuple[str, ...]:
return tuple(name for name, field in self.fields.items() if field.snapshot)
@property
def route_field_types(self) -> dict[str, RouteFieldType]:
return {
name: field.route_type
for name, field in self.fields.items()
if field.writable
}
@property
def simple_required_fields(self) -> tuple[str, ...]:
return tuple(
field
for requirement in self.required
if (field := requirement.simple_field) is not None
)
def is_configured(self, values: Any) -> bool:
return bool(self.required) and all(
requirement.is_satisfied(values) for requirement in self.required
)
def _field(
kind: FieldKind = "string",
*,
choices: set[str] | None = None,
writable: bool = True,
snapshot: bool = True,
) -> ChannelFieldSpec:
return ChannelFieldSpec(
kind=kind,
choices=frozenset(choices or ()),
writable=writable,
snapshot=snapshot,
)
def _required(field: str) -> SetupRequirement:
return SetupRequirement(((field,),))
def _one_of(*alternatives: tuple[str, ...]) -> SetupRequirement:
return SetupRequirement(alternatives)
_GROUP_POLICIES = {"mention", "open", "allowlist"}
_DIRECT_GROUP_POLICIES = {"mention", "open"}
CHANNEL_SETUP_SPECS: dict[str, ChannelSetupSpec] = {
"websocket": ChannelSetupSpec(
fields={},
official_url="http://127.0.0.1:8765",
),
"telegram": ChannelSetupSpec(
fields={
"token": _field("secret"),
"allowFrom": _field("list"),
"groupPolicy": _field("enum", choices=_GROUP_POLICIES),
},
required=(_required("token"),),
official_url="https://t.me/BotFather",
),
"slack": ChannelSetupSpec(
fields={
"appToken": _field("secret"),
"botToken": _field("secret"),
"groupPolicy": _field("enum", choices=_GROUP_POLICIES),
},
required=(_required("appToken"), _required("botToken")),
official_url="https://api.slack.com/apps",
),
"discord": ChannelSetupSpec(
fields={
"token": _field("secret"),
"allowFrom": _field("list", snapshot=False),
"allowChannels": _field("list"),
"groupPolicy": _field("enum", choices=_DIRECT_GROUP_POLICIES),
},
required=(_required("token"),),
official_url="https://discord.com/developers/applications",
),
"email": ChannelSetupSpec(
fields={
"consentGranted": _field("bool"),
"imapHost": _field(),
"imapPort": _field("int"),
"imapUsername": _field(),
"imapPassword": _field("secret"),
"smtpHost": _field(),
"smtpPort": _field("int"),
"smtpUsername": _field(),
"smtpPassword": _field("secret"),
"fromAddress": _field(),
"pollIntervalSeconds": _field("int"),
"allowFrom": _field("list"),
"verifyDkim": _field("bool"),
"verifySpf": _field("bool"),
},
required=tuple(
_required(field)
for field in (
"consentGranted",
"imapHost",
"imapUsername",
"imapPassword",
"smtpHost",
"smtpUsername",
"smtpPassword",
)
),
official_url="https://support.google.com/accounts/answer/185833",
),
"matrix": ChannelSetupSpec(
fields={
"homeserver": _field(),
"userId": _field(),
"password": _field("secret"),
"accessToken": _field("secret"),
"deviceId": _field(),
"groupPolicy": _field("enum", choices=_GROUP_POLICIES),
"allowFrom": _field("list", writable=False),
},
required=(
_required("homeserver"),
_required("userId"),
_one_of(("password",), ("accessToken", "deviceId")),
),
official_url="https://matrix.org/ecosystem/clients/",
),
"mattermost": ChannelSetupSpec(
fields={
"serverUrl": _field(),
"token": _field("secret"),
"teamId": _field(),
"groupPolicy": _field("enum", choices=_GROUP_POLICIES),
"allowFrom": _field("list"),
},
required=(_required("serverUrl"), _required("token")),
official_url="https://developers.mattermost.com/integrate/reference/bot-accounts/",
),
"whatsapp": ChannelSetupSpec(
fields={
"allowFrom": _field("list", snapshot=False),
"groupPolicy": _field("enum", choices=_DIRECT_GROUP_POLICIES, snapshot=False),
"databasePath": _field(writable=False, snapshot=False),
},
official_url="https://faq.whatsapp.com/",
),
"dingtalk": ChannelSetupSpec(
fields={
"clientId": _field(),
"clientSecret": _field("secret"),
"allowFrom": _field("list"),
},
required=(_required("clientId"), _required("clientSecret")),
official_url="https://open.dingtalk.com/",
),
"wecom": ChannelSetupSpec(
fields={
"botId": _field(),
"secret": _field("secret"),
"allowFrom": _field("list"),
},
required=(_required("botId"), _required("secret")),
official_url="https://developer.work.weixin.qq.com/",
),
"weixin": ChannelSetupSpec(
fields={
"token": _field("secret"),
"allowFrom": _field("list"),
},
required=(_required("token"),),
official_url="https://weixin.qq.com/",
),
"qq": ChannelSetupSpec(
fields={
"appId": _field(),
"secret": _field("secret"),
"allowFrom": _field("list"),
"msgFormat": _field("enum", choices={"plain", "markdown"}),
},
required=(_required("appId"), _required("secret")),
official_url="https://q.qq.com/",
),
"signal": ChannelSetupSpec(
fields={
"phoneNumber": _field(),
"daemonHost": _field(),
"daemonPort": _field("int"),
"allowFrom": _field("list", snapshot=False),
"dm.allowFrom": _field("list"),
"group.allowFrom": _field("list"),
},
required=(_required("phoneNumber"),),
official_url="https://github.com/bbernhard/signal-cli-rest-api",
),
"msteams": ChannelSetupSpec(
fields={
"appId": _field(),
"appPassword": _field("secret"),
"tenantId": _field(),
"path": _field(),
"allowFrom": _field("list"),
},
required=(_required("appId"), _required("appPassword")),
official_url="https://dev.teams.microsoft.com/apps",
),
"napcat": ChannelSetupSpec(
fields={
"wsUrl": _field(),
"accessToken": _field("secret"),
"allowFrom": _field("list"),
"groupPolicy": _field("enum", choices=_DIRECT_GROUP_POLICIES),
},
required=(_required("wsUrl"),),
official_url="https://napneko.github.io/",
),
"feishu": ChannelSetupSpec(
fields={
"appId": _field(snapshot=False),
"appSecret": _field("secret", snapshot=False),
"domain": _field("enum", choices={"feishu", "lark"}, snapshot=False),
"groupPolicy": _field(
"enum", choices=_DIRECT_GROUP_POLICIES, snapshot=False
),
"allowFrom": _field("list", snapshot=False),
"topicIsolation": _field("bool", snapshot=False),
},
required=(_required("appId"), _required("appSecret")),
official_url="https://open.feishu.cn/app",
),
}
def channel_setup_spec(name: str) -> ChannelSetupSpec | None:
return CHANNEL_SETUP_SPECS.get(name)
def channel_field_value(values: Any, field_path: str) -> Any:
current = values
for part in field_path.split("."):
candidates = (part, _camel_to_snake(part))
if isinstance(current, dict):
for candidate in candidates:
if candidate in current:
current = current[candidate]
break
else:
return None
continue
for candidate in candidates:
if hasattr(current, candidate):
current = getattr(current, candidate)
break
else:
return None
return current
def channel_value_present(value: Any) -> bool:
return value not in (None, "", [], {})
def stringify_channel_value(value: Any) -> str:
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, list):
return ", ".join(str(item) for item in value)
return str(value)
def _camel_to_snake(value: str) -> str:
chars: list[str] = []
for char in value:
if char.isupper():
if chars:
chars.append("_")
chars.append(char.lower())
else:
chars.append(char)
return "".join(chars)
+414 -69
View File
@@ -13,6 +13,7 @@ import uuid
from collections import OrderedDict
from contextlib import suppress
from dataclasses import dataclass
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any, Literal
from pydantic import Field
@@ -24,10 +25,19 @@ from rich.text import Text
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus
from nanobot.channels._feishu_instances import (
DEFAULT_INSTANCE_ID,
feishu_instance_specs,
runtime_channel_name,
update_feishu_instance_preserving_shape,
upsert_feishu_instance,
)
from nanobot.channels._feishu_ws import get_feishu_ws_runner
from nanobot.channels.base import BaseChannel
from nanobot.command.router import normalize_command_text
from nanobot.config.paths import get_media_dir
from nanobot.config.schema import Base
from nanobot.pairing import clear_channel
from nanobot.utils.helpers import safe_filename
from nanobot.utils.logging_bridge import redirect_lib_logging
@@ -38,6 +48,10 @@ FEISHU_AVAILABLE = importlib.util.find_spec("lark_oapi") is not None
_LOGIN_CONSOLE = Console()
def _identity_timestamp() -> str:
return datetime.now(UTC).isoformat(timespec="seconds").replace("+00:00", "Z")
def _load_lark_runtime() -> tuple[Any, str, str]:
"""Import the heavy Feishu SDK lazily.
@@ -68,6 +82,58 @@ def _load_lark_runtime() -> tuple[Any, str, str]:
return lark, FEISHU_DOMAIN, LARK_DOMAIN
def fetch_feishu_app_identity(
app_id: str,
app_secret: str,
domain: str = "feishu",
) -> dict[str, str]:
"""Fetch the user-facing Feishu/Lark app identity for display.
This is best-effort metadata for WebUI presentation. Callers should treat
an empty result as a normal fallback path.
"""
if not FEISHU_AVAILABLE or not app_id or not app_secret:
return {}
try:
lark, feishu_domain, lark_domain = _load_lark_runtime()
from lark_oapi.api.application.v6.model.get_application_request import (
GetApplicationRequest,
)
sdk_domain = lark_domain if domain == "lark" else feishu_domain
client = (
lark.Client.builder()
.app_id(app_id)
.app_secret(app_secret)
.domain(sdk_domain)
.timeout(5)
.build()
)
request = GetApplicationRequest.builder().app_id(app_id).lang("zh_cn").build()
response = client.application.v6.application.get(request)
if hasattr(response, "success") and not response.success():
return {}
app = getattr(getattr(response, "data", None), "app", None)
if app is None:
return {}
identity: dict[str, str] = {}
display_name = str(getattr(app, "app_name", "") or "").strip()
avatar_url = str(getattr(app, "avatar_url", "") or "").strip()
if display_name:
identity["displayName"] = display_name
if avatar_url:
identity["avatarUrl"] = avatar_url
if identity:
identity["identityFetchedAt"] = _identity_timestamp()
return identity
except Exception:
return {}
# Message type display mapping
MSG_TYPE_MAP = {
"image": "[image]",
@@ -343,6 +409,9 @@ def _extract_post_text(content_json: dict) -> str:
class FeishuConfig(Base):
"""Feishu/Lark channel configuration using WebSocket long connection."""
instance_id: str = DEFAULT_INSTANCE_ID
name: str = "nanobot"
identity_key: str = ""
enabled: bool = False
app_id: str = ""
app_secret: str = ""
@@ -448,39 +517,24 @@ def _poll_registration(
"""
deadline = time.monotonic() + expire_in
current_domain = domain
poll_count = 0
while time.monotonic() < deadline:
base_url = _accounts_base_url(current_domain)
try:
res = _post_registration(base_url, {
"action": "poll",
"device_code": device_code,
"tp": "ob_app",
})
res = poll_registration_once(device_code=device_code, domain=current_domain)
except Exception:
time.sleep(interval)
continue
poll_count += 1
current_domain = res.get("domain", current_domain)
# Domain auto-detection: if the user's tenant is on Lark, switch automatically
user_info = res.get("user_info") or {}
tenant_brand = user_info.get("tenant_brand")
if tenant_brand == "lark":
current_domain = "lark"
# Success
if res.get("client_id") and res.get("client_secret"):
if res.get("status") == "succeeded":
return {
"app_id": res["client_id"],
"app_secret": res["client_secret"],
"domain": current_domain,
"app_id": res["app_id"],
"app_secret": res["app_secret"],
"domain": res.get("domain", current_domain),
}
# Terminal errors
error = res.get("error", "")
if error in ("access_denied", "expired_token"):
if res.get("status") == "failed":
_LOGIN_CONSOLE.print("[yellow]Authorization was cancelled or expired.[/yellow]")
return None
@@ -491,6 +545,230 @@ def _poll_registration(
return None
def poll_registration_once(
*,
device_code: str,
domain: str = "feishu",
) -> dict:
"""Poll the Feishu/Lark device-code flow once.
This non-blocking shape is used by WebUI. The CLI keeps using
``_poll_registration`` to wait in the terminal.
"""
current_domain = domain
base_url = _accounts_base_url(current_domain)
res = _post_registration(base_url, {
"action": "poll",
"device_code": device_code,
"tp": "ob_app",
})
user_info = res.get("user_info") or {}
tenant_brand = user_info.get("tenant_brand")
if tenant_brand == "lark":
current_domain = "lark"
if res.get("client_id") and res.get("client_secret"):
return {
"status": "succeeded",
"app_id": res["client_id"],
"app_secret": res["client_secret"],
"domain": current_domain,
}
error = res.get("error", "")
if error in ("access_denied", "expired_token"):
return {
"status": "failed",
"error": error,
"domain": current_domain,
}
return {
"status": "pending",
"domain": current_domain,
}
def _feishu_app_identity_key(app_id: str, domain: str) -> str:
normalized_app_id = app_id.strip()
normalized_domain = "lark" if domain.strip().lower() == "lark" else "feishu"
return f"{normalized_domain}:{normalized_app_id}" if normalized_app_id else ""
def _saved_feishu_instance_identity_key(
feishu_cfg: Any,
defaults: dict[str, Any],
instance_id: str,
) -> str:
for spec in feishu_instance_specs(feishu_cfg, defaults):
if spec.instance_id == instance_id:
return _feishu_app_identity_key(
str(spec.config.get("appId") or spec.config.get("app_id") or ""),
str(spec.config.get("domain") or "feishu"),
)
return ""
def sync_saved_feishu_identity_boundary(
*,
instance_id: str,
app_id: str,
domain: str,
) -> bool:
"""Persist the Feishu app identity marker and clear access if it changed.
WebUI connect normally handles this at save time. This startup check catches
manual config edits so approved users do not accidentally carry over to a
different Feishu/Lark app in the same local instance slot.
"""
current_identity_key = _feishu_app_identity_key(app_id, domain)
if not current_identity_key:
return False
from nanobot.config.loader import load_config, save_config
full_config = load_config()
feishu_cfg = getattr(full_config.channels, "feishu", None) or {}
if not isinstance(feishu_cfg, dict):
feishu_cfg = {}
defaults = FeishuChannel.default_config()
previous_identity_key = ""
for spec in feishu_instance_specs(feishu_cfg, defaults):
if spec.instance_id == instance_id:
previous_identity_key = str(
spec.config.get("identityKey") or spec.config.get("identity_key") or ""
)
break
access_cleared = bool(previous_identity_key and previous_identity_key != current_identity_key)
values: dict[str, Any] = {"identityKey": current_identity_key}
if access_cleared:
values["allowFrom"] = []
values["allow_from"] = []
clear_channel(runtime_channel_name("feishu", instance_id))
if not previous_identity_key or access_cleared:
feishu_cfg = update_feishu_instance_preserving_shape(
feishu_cfg,
defaults,
instance_id,
values,
)
setattr(full_config.channels, "feishu", feishu_cfg)
save_config(full_config)
return access_cleared
def save_registration_result(
result: dict,
*,
instance_id: str = DEFAULT_INSTANCE_ID,
name: str | None = None,
) -> None:
"""Persist a successful Feishu/Lark registration result to config.json."""
from nanobot.config.loader import load_config, save_config
full_config = load_config()
feishu_cfg = getattr(full_config.channels, "feishu", None) or {}
if not isinstance(feishu_cfg, dict):
feishu_cfg = {}
defaults = FeishuChannel.default_config()
app_id = str(result["app_id"]).strip()
domain = str(result.get("domain", "feishu") or "feishu").strip().lower()
domain = "lark" if domain == "lark" else "feishu"
previous_identity_key = _saved_feishu_instance_identity_key(feishu_cfg, defaults, instance_id)
next_identity_key = _feishu_app_identity_key(app_id, domain)
identity_changed = bool(previous_identity_key and previous_identity_key != next_identity_key)
identity: dict[str, str] = {}
with suppress(Exception):
identity = fetch_feishu_app_identity(
app_id,
str(result["app_secret"]),
domain,
)
values = {
"name": name or ("nanobot" if instance_id == DEFAULT_INSTANCE_ID else f"nanobot {instance_id}"),
"appId": app_id,
"appSecret": result["app_secret"],
"domain": domain,
"identityKey": next_identity_key,
"enabled": True,
**identity,
}
if identity_changed:
values["allowFrom"] = []
values["allow_from"] = []
clear_channel(runtime_channel_name("feishu", instance_id))
feishu_cfg = upsert_feishu_instance(
feishu_cfg,
defaults,
instance_id,
values,
)
setattr(full_config.channels, "feishu", feishu_cfg)
save_config(full_config)
def refresh_saved_feishu_identities(config: Any | None = None) -> bool:
"""Backfill missing Feishu assistant display identity in saved config.
Existing users may already have working App ID/Secret credentials from
older builds. Fetch identity only when an instance has credentials but no
identity metadata at all, then persist the attempt so Settings does not hit
Feishu on every render.
"""
if not FEISHU_AVAILABLE:
return False
from nanobot.config.loader import load_config, save_config
full_config = config or load_config()
feishu_cfg = getattr(full_config.channels, "feishu", None)
defaults = FeishuChannel.default_config()
specs = feishu_instance_specs(feishu_cfg, defaults)
updated = False
for spec in specs:
instance = spec.config
if (
instance.get("displayName")
or instance.get("avatarUrl")
or instance.get("identityFetchedAt")
):
continue
app_id = str(instance.get("appId") or instance.get("app_id") or "").strip()
app_secret = str(instance.get("appSecret") or instance.get("app_secret") or "").strip()
if not app_id or not app_secret:
continue
identity = fetch_feishu_app_identity(
app_id,
app_secret,
str(instance.get("domain") or "feishu"),
)
if not identity:
identity = {"identityFetchedAt": _identity_timestamp()}
feishu_cfg = update_feishu_instance_preserving_shape(
feishu_cfg,
defaults,
spec.instance_id,
identity,
)
updated = True
if not updated:
return False
setattr(full_config.channels, "feishu", feishu_cfg)
save_config(full_config)
return True
def qr_register(
*,
initial_domain: str = "feishu",
@@ -600,7 +878,7 @@ class FeishuChannel(BaseChannel):
self.config: FeishuConfig = config
self._client: Any = None
self._ws_client: Any = None
self._ws_thread: threading.Thread | None = None
self._ws_runner = get_feishu_ws_runner()
self._processed_message_ids: OrderedDict[str, None] = OrderedDict() # Ordered dedup cache
self._loop: asyncio.AbstractEventLoop | None = None
self._stream_bufs: dict[str, _FeishuStreamBuf] = {}
@@ -650,18 +928,11 @@ class FeishuChannel(BaseChannel):
self.config.app_secret = result["app_secret"]
self.config.domain = result.get("domain", "feishu")
# Write credentials back to config.json
from nanobot.config.loader import load_config, save_config
full_config = load_config()
feishu_cfg = getattr(full_config.channels, "feishu", None) or {}
if isinstance(feishu_cfg, dict):
feishu_cfg["appId"] = result["app_id"]
feishu_cfg["appSecret"] = result["app_secret"]
feishu_cfg["domain"] = result.get("domain", "feishu")
feishu_cfg["enabled"] = True
setattr(full_config.channels, "feishu", feishu_cfg)
save_config(full_config)
save_registration_result(
result,
instance_id=self.config.instance_id,
name=self.config.name,
)
_LOGIN_CONSOLE.print("\n[green]Feishu/Lark login complete.[/green]")
_LOGIN_CONSOLE.print(f"App ID: {escape(result['app_id'])}")
@@ -687,6 +958,18 @@ class FeishuChannel(BaseChannel):
)
return
if sync_saved_feishu_identity_boundary(
instance_id=self.config.instance_id,
app_id=self.config.app_id,
domain=self.config.domain,
):
self.config.identity_key = _feishu_app_identity_key(self.config.app_id, self.config.domain)
self.config.allow_from = []
self.logger.info(
"Feishu app identity changed for {}; cleared paired users for this assistant",
self.name,
)
lark, feishu_domain, lark_domain = await asyncio.to_thread(_load_lark_runtime)
redirect_lib_logging("Lark")
@@ -745,38 +1028,7 @@ class FeishuChannel(BaseChannel):
log_level=lark.LogLevel.INFO,
)
# Start WebSocket client in a separate thread with reconnect loop.
# A dedicated event loop is created for this thread so that lark_oapi's
# module-level `loop = asyncio.get_event_loop()` picks up an idle loop
# instead of the already-running main asyncio loop, which would cause
# "This event loop is already running" errors.
def run_ws():
import time
import lark_oapi.ws.client as _lark_ws_client
previous_loop = getattr(_lark_ws_client, "loop", None)
ws_loop = asyncio.new_event_loop()
asyncio.set_event_loop(ws_loop)
# Patch the module-level loop used by lark's ws Client.start()
_lark_ws_client.loop = ws_loop
try:
while self._running:
try:
self._ws_client.start()
except Exception as e:
self.logger.warning("WebSocket error: {}", e)
if self._running:
time.sleep(5)
finally:
if getattr(_lark_ws_client, "loop", None) is ws_loop:
_lark_ws_client.loop = previous_loop
with suppress(Exception):
asyncio.set_event_loop(None)
ws_loop.close()
self._ws_thread = threading.Thread(target=run_ws, daemon=True)
self._ws_thread.start()
await self._ws_runner.start_client(self.name, self._ws_client)
# Fetch bot's own open_id for accurate @mention matching
self._bot_open_id = await asyncio.get_running_loop().run_in_executor(
@@ -803,6 +1055,7 @@ class FeishuChannel(BaseChannel):
Reference: https://github.com/larksuite/oapi-sdk-python/blob/v2_main/lark_oapi/ws/client.py#L86
"""
self._running = False
await self._ws_runner.stop_client(self.name)
self.logger.info("bot stopped")
def _fetch_bot_open_id(self) -> str | None:
@@ -1589,13 +1842,95 @@ class FeishuChannel(BaseChannel):
response.msg,
response.get_log_id(),
)
if msg_type == "interactive":
return self._reply_interactive_fallback_sync(
parent_message_id,
content,
reply_in_thread=reply_in_thread,
)
return False
self.logger.debug("reply sent to message {}", parent_message_id)
return True
except Exception:
self.logger.exception("Error replying to message {}", parent_message_id)
if msg_type == "interactive":
return self._reply_interactive_fallback_sync(
parent_message_id,
content,
reply_in_thread=reply_in_thread,
)
return False
@staticmethod
def _interactive_content_to_text(content: str) -> str | None:
try:
payload = json.loads(content)
except (TypeError, json.JSONDecodeError):
return None
parts = [part.strip() for part in _extract_interactive_content(payload) if part.strip()]
text = "\n".join(parts).strip()
return text or None
@staticmethod
def _fallback_text_chunks(text: str, limit: int = 3500) -> list[str]:
text = text.strip()
if not text:
return []
chunks: list[str] = []
remaining = text
while remaining:
if len(remaining) <= limit:
chunks.append(remaining)
break
split_at = remaining.rfind("\n", 0, limit)
if split_at < limit // 2:
split_at = limit
chunks.append(remaining[:split_at].strip())
remaining = remaining[split_at:].strip()
return [chunk for chunk in chunks if chunk]
def _reply_interactive_fallback_sync(
self,
parent_message_id: str,
content: str,
*,
reply_in_thread: bool = False,
) -> bool:
text = self._interactive_content_to_text(content)
if not text:
return False
sent = False
for chunk in self._fallback_text_chunks(text):
body = json.dumps({"text": chunk}, ensure_ascii=False)
sent = self._reply_message_sync(
parent_message_id,
"text",
body,
reply_in_thread=reply_in_thread,
) or sent
if sent:
self.logger.warning("Sent Feishu interactive reply as text fallback")
return sent
def _send_interactive_fallback_sync(
self,
receive_id_type: str,
receive_id: str,
content: str,
) -> str | None:
text = self._interactive_content_to_text(content)
if not text:
return None
last_message_id: str | None = None
for chunk in self._fallback_text_chunks(text):
body = json.dumps({"text": chunk}, ensure_ascii=False)
message_id = self._send_message_sync(receive_id_type, receive_id, "text", body)
if message_id:
last_message_id = message_id
if last_message_id:
self.logger.warning("Sent Feishu interactive message as text fallback")
return last_message_id
def _should_use_reply_in_thread(self, metadata: dict[str, Any]) -> bool:
"""Return whether a group reply should create a Feishu thread/topic."""
return metadata.get("chat_type", "group") == "group" and self.config.reply_to_message
@@ -1639,6 +1974,12 @@ class FeishuChannel(BaseChannel):
response.msg,
response.get_log_id(),
)
if msg_type == "interactive":
return self._send_interactive_fallback_sync(
receive_id_type,
receive_id,
content,
)
return None
msg_id = getattr(response.data, "message_id", None)
self.logger.debug("{} message sent to {}: {}", msg_type, receive_id, msg_id)
@@ -2135,11 +2476,15 @@ class FeishuChannel(BaseChannel):
Sync handler for incoming messages (called from WebSocket thread).
Schedules async handling in the main event loop.
"""
if not self._running:
return
if self._loop and self._loop.is_running():
asyncio.run_coroutine_threadsafe(self._on_message(data), self._loop)
async def _on_message(self, data: P2ImMessageReceiveV1) -> None:
"""Handle incoming message from Feishu."""
if not self._running:
return
try:
event = data.event
message = event.message
@@ -2290,9 +2635,9 @@ class FeishuChannel(BaseChannel):
# Private chat: no override — same behavior as Telegram/Slack.
if chat_type == "group":
if self.config.topic_isolation:
session_key = f"feishu:{chat_id}:{root_id or message_id}"
session_key = f"{self.name}:{chat_id}:{root_id or message_id}"
else:
session_key = f"feishu:{chat_id}"
session_key = f"{self.name}:{chat_id}"
else:
session_key = None
+270 -64
View File
@@ -24,6 +24,7 @@ from nanobot.bus.outbound_events import (
replace_outbound_event,
)
from nanobot.bus.queue import MessageBus
from nanobot.channels._feishu_instances import ChannelInstanceSpec, feishu_instance_specs
from nanobot.channels.base import BaseChannel
from nanobot.channels.registry import DEFAULT_ENABLED_CHANNELS
from nanobot.config.schema import Config
@@ -61,6 +62,10 @@ def _default_channel_config(name: str) -> dict[str, Any] | None:
def _channel_config_enabled(name: str, section: Any) -> bool:
if name == "feishu":
from nanobot.channels.feishu import FeishuChannel
return bool(feishu_instance_specs(section, FeishuChannel.default_config(), enabled_only=True))
default_enabled = name in DEFAULT_ENABLED_CHANNELS
if isinstance(section, dict):
return bool(section.get("enabled", default_enabled))
@@ -104,11 +109,108 @@ class ChannelManager:
self._webui_runtime_surface = webui_runtime_surface
self._webui_runtime_capabilities = dict(webui_runtime_capabilities or {})
self.channels: dict[str, BaseChannel] = {}
self._channel_tasks: dict[str, asyncio.Task] = {}
self._dispatch_task: asyncio.Task | None = None
self._started = False
self._origin_reply_fingerprints: dict[tuple[str, str, str], str] = {}
self._init_channels()
def _config_extra_channel_names(self, config: Config | None = None) -> set[str]:
extra = getattr((config or self.config).channels, "__pydantic_extra__", None) or {}
return set(extra.keys())
def _channel_section(
self,
name: str,
*,
config: Config | None = None,
default_sections: dict[str, Any] | None = None,
) -> Any:
config = config or self.config
section = getattr(config.channels, name, None)
if section is not None or name not in DEFAULT_ENABLED_CHANNELS:
return section
if default_sections is None:
return _default_channel_config(name)
if name not in default_sections:
default = _default_channel_config(name)
if default is not None:
default_sections[name] = default
return default_sections.get(name)
def _channel_instance_specs(
self,
name: str,
cls: type[BaseChannel],
section: Any,
*,
enabled_only: bool = True,
) -> list[ChannelInstanceSpec]:
if name == "feishu":
return feishu_instance_specs(
section,
cls.default_config(),
enabled_only=enabled_only,
)
return [
ChannelInstanceSpec(
base_name=name,
instance_id="default",
runtime_name=name,
config=section,
)
]
def _build_channel(
self,
name: str,
cls: type[BaseChannel],
section: Any,
*,
runtime_name: str | None = None,
) -> BaseChannel:
kwargs: dict[str, Any] = {}
if cls.name == "websocket":
from nanobot.channels.websocket import WebSocketConfig
from nanobot.webui.gateway_services import build_gateway_services
parsed = WebSocketConfig.model_validate(section)
static_path = _default_webui_dist() if self._webui_static_dist else None
workspace = Path(self.config.workspace_path)
gateway = build_gateway_services(
config=parsed,
bus=self.bus,
session_manager=self._session_manager,
static_dist_path=static_path,
workspace_path=workspace,
default_restrict_to_workspace=self.config.tools.restrict_to_workspace,
disabled_skills=set(self.config.agents.defaults.disabled_skills),
runtime_model_name=self._webui_runtime_model_name,
runtime_surface=self._webui_runtime_surface,
runtime_capabilities_overrides=self._webui_runtime_capabilities,
cron_service=self._cron_service,
local_trigger_store=self._local_trigger_store,
cron_pending_job_ids=self._webui_cron_pending_job_ids,
local_trigger_pending_ids=self._webui_local_trigger_pending_ids,
channel_feature_action=self.apply_channel_feature_action,
logger=logger,
)
kwargs["gateway"] = gateway
channel = cls(section, self.bus, **kwargs)
if runtime_name and runtime_name != channel.name:
channel.name = runtime_name
channel.send_progress = self._resolve_bool_override(
section, "send_progress", self.config.channels.send_progress,
)
channel.send_tool_hints = self._resolve_bool_override(
section, "send_tool_hints", self.config.channels.send_tool_hints,
)
channel.show_reasoning = self._resolve_bool_override(
section, "show_reasoning", self.config.channels.show_reasoning,
)
return channel
def _init_channels(self) -> None:
"""Initialize channels discovered via pkgutil scan + entry_points plugins."""
from nanobot.channels.registry import discover_channel_names, discover_enabled
@@ -118,24 +220,12 @@ class ChannelManager:
# extra="allow"), so we enumerate candidates from pkgutil scan
# (cheap, no imports) and any plugin keys in __pydantic_extra__.
names = discover_channel_names()
candidate_names = set(names)
extra = getattr(self.config.channels, "__pydantic_extra__", None) or {}
candidate_names.update(extra.keys())
candidate_names = set(names) | self._config_extra_channel_names()
default_sections: dict[str, Any] = {}
def section_for(name: str) -> Any:
section = getattr(self.config.channels, name, None)
if section is not None or name not in DEFAULT_ENABLED_CHANNELS:
return section
if name not in default_sections:
default = _default_channel_config(name)
if default is not None:
default_sections[name] = default
return default_sections.get(name)
enabled_names: set[str] = set()
for name in candidate_names:
section = section_for(name)
section = self._channel_section(name, default_sections=default_sections)
if section is None:
continue
if _channel_config_enabled(name, section):
@@ -146,48 +236,18 @@ class ChannelManager:
_names=names,
warn_import_errors=True,
).items():
section = section_for(name)
section = self._channel_section(name, default_sections=default_sections)
if section is None:
continue
try:
kwargs: dict[str, Any] = {}
if cls.name == "websocket":
from nanobot.channels.websocket import WebSocketConfig
from nanobot.webui.gateway_services import build_gateway_services
parsed = WebSocketConfig.model_validate(section)
static_path = _default_webui_dist() if self._webui_static_dist else None
workspace = Path(self.config.workspace_path)
gateway = build_gateway_services(
config=parsed,
bus=self.bus,
session_manager=self._session_manager,
static_dist_path=static_path,
workspace_path=workspace,
default_restrict_to_workspace=self.config.tools.restrict_to_workspace,
disabled_skills=set(self.config.agents.defaults.disabled_skills),
runtime_model_name=self._webui_runtime_model_name,
runtime_surface=self._webui_runtime_surface,
runtime_capabilities_overrides=self._webui_runtime_capabilities,
cron_service=self._cron_service,
local_trigger_store=self._local_trigger_store,
cron_pending_job_ids=self._webui_cron_pending_job_ids,
local_trigger_pending_ids=self._webui_local_trigger_pending_ids,
logger=logger,
for spec in self._channel_instance_specs(name, cls, section):
self.channels[spec.runtime_name] = self._build_channel(
name,
cls,
spec.config,
runtime_name=spec.runtime_name,
)
kwargs["gateway"] = gateway
channel = cls(section, self.bus, **kwargs)
channel.send_progress = self._resolve_bool_override(
section, "send_progress", self.config.channels.send_progress,
)
channel.send_tool_hints = self._resolve_bool_override(
section, "send_tool_hints", self.config.channels.send_tool_hints,
)
channel.show_reasoning = self._resolve_bool_override(
section, "show_reasoning", self.config.channels.show_reasoning,
)
self.channels[name] = channel
logger.info("{} channel enabled", cls.display_name)
logger.info("{} channel enabled as {}", cls.display_name, spec.runtime_name)
except Exception as e:
logger.warning("{} channel not available: {}", name, e)
@@ -243,20 +303,173 @@ class ChannelManager:
except Exception:
logger.exception("Failed to start channel {}", name)
def _start_channel_task(self, name: str, channel: BaseChannel) -> asyncio.Task:
logger.info("Starting {} channel...", name)
task = asyncio.create_task(self._start_channel(name, channel))
self._channel_tasks[name] = task
return task
async def _stop_channel(self, name: str) -> bool:
channel = self.channels.get(name)
if channel is None:
self._channel_tasks.pop(name, None)
return False
task = self._channel_tasks.pop(name, None)
try:
await channel.stop()
logger.info("Stopped {} channel", name)
except asyncio.CancelledError:
if asyncio.current_task() and asyncio.current_task().cancelling():
raise
logger.debug("Channel {} stop task was already cancelled", name)
except Exception:
logger.exception("Error stopping {}", name)
if task is not None and not task.done():
task.cancel()
with suppress(asyncio.CancelledError):
await task
return True
def _is_known_channel_name(self, name: str) -> bool:
from nanobot.channels.registry import discover_channel_names, discover_plugins
return name in set(discover_channel_names()) or name in discover_plugins()
def _load_channel_class(self, name: str) -> type[BaseChannel] | None:
from nanobot.channels.registry import discover_channel_names, discover_enabled
names = discover_channel_names()
return discover_enabled({name}, _names=names, warn_import_errors=True).get(name)
async def apply_channel_feature_action(self, action: str, name: str) -> dict[str, Any]:
"""Apply a WebUI channel enable/disable action without restarting the gateway.
Returns a small transport-neutral result. ``handled=False`` means the
optional feature is not a channel and should keep the default feature
response semantics.
"""
name = name.strip()
instance_id = ""
if "." in name:
name, instance_id = name.split(".", 1)
if not name or not self._is_known_channel_name(name):
return {"handled": False}
if name == "websocket":
return {
"handled": True,
"ok": False,
"requires_restart": True,
"message": "WebSocket hosts the WebUI and is applied on restart.",
}
from nanobot.config.loader import load_config
self.config = load_config()
section = self._channel_section(name)
if action == "disable":
runtime_names = [name if not instance_id else f"{name}.{instance_id}"]
if name == "feishu" and not instance_id:
runtime_names = [
runtime_name
for runtime_name in self.channels
if runtime_name == "feishu" or runtime_name.startswith("feishu.")
]
stopped = False
for runtime_name in runtime_names:
stopped = await self._stop_channel(runtime_name) or stopped
self.channels.pop(runtime_name, None)
return {
"handled": True,
"ok": True,
"requires_restart": False,
"message": f"{name} channel stopped." if stopped else f"{name} channel disabled.",
}
if action != "enable":
return {"handled": True, "ok": False, "requires_restart": True}
if section is None or not _channel_config_enabled(name, section):
return {
"handled": True,
"ok": False,
"requires_restart": True,
"message": f"{name} channel config was not enabled.",
}
cls = self._load_channel_class(name)
if cls is None:
return {
"handled": True,
"ok": False,
"requires_restart": True,
"message": f"{name} channel could not be loaded.",
}
specs = self._channel_instance_specs(name, cls, section)
if instance_id:
specs = [spec for spec in specs if spec.instance_id == instance_id]
if not specs:
return {
"handled": True,
"ok": False,
"requires_restart": True,
"message": f"{name} channel config was not enabled.",
}
try:
built = [
(
spec.runtime_name,
self._build_channel(
name,
cls,
spec.config,
runtime_name=spec.runtime_name,
),
)
for spec in specs
]
except Exception as exc:
logger.exception("Failed to build {} channel after settings change", name)
return {
"handled": True,
"ok": False,
"requires_restart": True,
"message": f"{name} channel could not be started: {exc}",
}
for runtime_name, _channel in built:
if runtime_name in self.channels:
await self._stop_channel(runtime_name)
for runtime_name, channel in built:
self.channels[runtime_name] = channel
if self._started:
self._start_channel_task(runtime_name, channel)
logger.info("{} channel applied without restart", runtime_name)
return {
"handled": True,
"ok": True,
"requires_restart": False,
"message": f"{cls.display_name} channel applied without restart.",
}
async def start_all(self) -> None:
"""Start all channels and the outbound dispatcher."""
if not self.channels:
logger.warning("No channels enabled")
return
self._started = True
# Start outbound dispatcher
self._dispatch_task = asyncio.create_task(self._dispatch_outbound())
# Start channels
tasks = []
for name, channel in self.channels.items():
logger.info("Starting {} channel...", name)
tasks.append(asyncio.create_task(self._start_channel(name, channel)))
tasks.append(self._start_channel_task(name, channel))
self._notify_restart_done_if_needed()
@@ -284,6 +497,7 @@ class ChannelManager:
async def stop_all(self) -> None:
"""Stop all channels and the dispatcher."""
logger.info("Stopping all channels...")
self._started = False
# Stop dispatcher
if self._dispatch_task:
@@ -292,16 +506,8 @@ class ChannelManager:
await self._dispatch_task
# Stop all channels
for name, channel in self.channels.items():
try:
await channel.stop()
logger.info("Stopped {} channel", name)
except asyncio.CancelledError:
if asyncio.current_task() and asyncio.current_task().cancelling():
raise
logger.debug("Channel {} stop task was already cancelled", name)
except Exception:
logger.exception("Error stopping {}", name)
for name in list(self.channels):
await self._stop_channel(name)
@staticmethod
def _fingerprint_content(content: str) -> str:
+56 -3
View File
@@ -1,15 +1,17 @@
"""Matrix (Element) channel — inbound sync + outbound message/media delivery."""
import asyncio
import html
import json
import mimetypes
import re
import sys
import time
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal, TypeAlias
from urllib.parse import quote, urlparse
from urllib.parse import quote, unquote, urlparse
from pydantic import Field
@@ -92,6 +94,19 @@ MATRIX_ALLOWED_HTML_ATTRIBUTES: dict[str, set[str]] = {
"img": {"src", "alt", "title", "width", "height"},
}
MATRIX_ALLOWED_URL_SCHEMES = {"https", "http", "matrix", "mailto", "mxc"}
_MXC_IMAGE_PLACEHOLDER_PREFIX = "https://nanobot.invalid/matrix-mxc/"
_MXC_MARKDOWN_IMAGE_RE = re.compile(
r"(?P<prefix>!\[[^\]]*\]\()"
r"(?P<value>mxc://[^\s)]+)"
r"(?P<suffix>(?:\s+[^)]*)?\))"
)
_MXC_IMAGE_SRC_RE = re.compile(
r"(?P<prefix>\bsrc=)(?P<quote>[\"'])(?P<value>mxc://[^\"']+)(?P=quote)",
re.IGNORECASE,
)
_MXC_PLACEHOLDER_SRC_RE = re.compile(
rf'src="{re.escape(_MXC_IMAGE_PLACEHOLDER_PREFIX)}([^"]+)"'
)
def _filter_matrix_html_attribute(tag: str, attr: str, value: str) -> str | None:
@@ -99,7 +114,10 @@ def _filter_matrix_html_attribute(tag: str, attr: str, value: str) -> str | None
if tag == "a" and attr == "href":
return value if value.lower().startswith(("https://", "http://", "matrix:", "mailto:")) else None
if tag == "img" and attr == "src":
return value if value.lower().startswith("mxc://") else None
lowered = value.lower()
if lowered.startswith("mxc://") or lowered.startswith(_MXC_IMAGE_PLACEHOLDER_PREFIX):
return value
return None
if tag == "code" and attr == "class":
classes = [c for c in value.split() if c.startswith("language-") and not c.startswith("language-_")]
return " ".join(classes) if classes else None
@@ -115,6 +133,39 @@ MATRIX_HTML_CLEANER = nh3.Cleaner(
link_rel="noopener noreferrer",
)
def _mask_mxc_markdown_image_sources(text: str) -> str:
def repl(match: re.Match[str]) -> str:
value = quote(match.group("value"), safe="")
return (
f"{match.group('prefix')}"
f"{_MXC_IMAGE_PLACEHOLDER_PREFIX}{value}"
f"{match.group('suffix')}"
)
return _MXC_MARKDOWN_IMAGE_RE.sub(repl, text)
def _mask_mxc_image_sources(rendered_html: str) -> str:
def repl(match: re.Match[str]) -> str:
value = quote(match.group("value"), safe="")
return (
f'{match.group("prefix")}{match.group("quote")}'
f"{_MXC_IMAGE_PLACEHOLDER_PREFIX}{value}"
f'{match.group("quote")}'
)
return _MXC_IMAGE_SRC_RE.sub(repl, rendered_html)
def _unmask_mxc_image_sources(cleaned_html: str) -> str:
def repl(match: re.Match[str]) -> str:
value = html.escape(unquote(match.group(1)), quote=True)
return f'src="{value}"'
return _MXC_PLACEHOLDER_SRC_RE.sub(repl, cleaned_html)
@dataclass
class _StreamBuf:
"""
@@ -135,7 +186,9 @@ class _StreamBuf:
def _render_markdown_html(text: str) -> str | None:
"""Render markdown to sanitized HTML; returns None for plain text."""
try:
formatted = MATRIX_HTML_CLEANER.clean(MATRIX_MARKDOWN(text)).strip()
masked_text = _mask_mxc_markdown_image_sources(text)
rendered = _mask_mxc_image_sources(MATRIX_MARKDOWN(masked_text))
formatted = _unmask_mxc_image_sources(MATRIX_HTML_CLEANER.clean(rendered).strip())
except Exception:
return None
if not formatted:
+6 -2
View File
@@ -10,7 +10,11 @@ from loguru import logger
if TYPE_CHECKING:
from nanobot.channels.base import BaseChannel
_INTERNAL = frozenset({"base", "manager", "registry"})
_INTERNAL = frozenset({
"base",
"manager",
"registry",
})
DEFAULT_ENABLED_CHANNELS = frozenset({"websocket"})
@@ -21,7 +25,7 @@ def discover_channel_names() -> list[str]:
return [
name
for _, name, ispkg in pkgutil.iter_modules(pkg.__path__)
if name not in _INTERNAL and not ispkg
if name not in _INTERNAL and not name.startswith("_") and not ispkg
]