Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat: 重新分拆app到gateway和agentserver,由主入口app直接拉起子进程

yukuanjba4cff78e60d
diff --git a/jiuwenclaw/app.py b/jiuwenclaw/app.py
index b9340596ce..9fac4587b4 100644
--- a/jiuwenclaw/app.py
+++ b/jiuwenclaw/app.py
@@ -1,2110 +1,75 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
-# 启动入口:WebChannel + FeishuChannel 共用一个 ChannelManager,端到端联调 JiuWenClaw。
-# 环境变量从 .env 加载。
+"""Orchestrate AgentServer + Gateway in two processes (split layout, one command).
+
+Runs ``jiuwenclaw.app_agentserver`` then ``jiuwenclaw.app_gateway`` with the same
+environment as a normal CLI launch. Web RPC handlers live in ``app_web_handlers``.
+"""
from __future__ import annotations
-import asyncio
-import inspect
-import logging
-import os
-import secrets
-import shutil
+import subprocess
import sys
import time
-import re
from dotenv import load_dotenv
-from typing import Any
-import psutil
+from jiuwenclaw.utils import USER_WORKSPACE_DIR, get_env_file, prepare_workspace
-from jiuwenclaw.utils import USER_WORKSPACE_DIR, prepare_workspace
_config_file = USER_WORKSPACE_DIR / "config" / "config.yaml"
if not _config_file.exists():
prepare_workspace(overwrite=False)
-# 减少日志打印
-from openjiuwen.core.common.logging import LogManager
-
-from jiuwenclaw.channel import (
- DingTalkChannel,
- DingTalkConfig,
- WhatsAppChannel,
- WhatsAppChannelConfig,
- WechatChannel,
- WechatConfig,
-)
-
-for logger in LogManager.get_all_loggers().values():
- logger.set_level(logging.CRITICAL)
-
-import openjiuwen.core.foundation.llm.schema.config as as_config_module
-import openjiuwen.core.foundation.llm as as_llm_module
-from openjiuwen.core.foundation.llm.model_clients.openai_model_client import OpenAIModelClient
-from jiuwenclaw.jiuwen_core_patch import PatchOpenAIModelClient
-
-OpenAIModelClient._create_async_openai_client = PatchOpenAIModelClient._create_async_openai_client
-OpenAIModelClient._parse_stream_chunk = PatchOpenAIModelClient._parse_stream_chunk
-
-from openjiuwen.core.foundation.llm import ProviderType
-from jiuwenclaw.security.base_crypto import get_crypto_provider
-
-from jiuwenclaw.utils import (
- get_agent_sessions_dir,
- get_config_file,
- get_env_file,
- get_root_dir,
-)
-from jiuwenclaw.config import (
- get_config,
- get_config_raw,
- update_heartbeat_in_config,
- update_channel_in_config,
- update_browser_in_config,
- update_preferred_language_in_config,
- update_context_engine_enabled_in_config,
- update_permissions_enabled_in_config,
- update_updater_in_config,
-)
-from jiuwenclaw.updater import WindowsUpdaterService
-from jiuwenclaw.version import __version__
-
-logger = logging.getLogger(__name__)
-
-_PROJECT_ROOT = get_root_dir()
-_ENV_FILE = get_env_file()
-load_dotenv(dotenv_path=_ENV_FILE)
-
-
-# 仅满足 Channel 构造所需,不入队、不路由;仅用 channel_manager + message_handler 做入站/出站
-class _DummyBus:
- async def publish_user_messages(self, msg): # noqa: ANN001, ARG002
- pass
-
- async def route_incoming_message(self, msg): # noqa: ANN001, ARG002
- pass
-
- async def route_user_message(self, msg):
- pass
-
-
-# 仅转发到 Agent 的 Web method
-_FORWARD_REQ_METHODS = frozenset({
- "chat.send",
- "chat.interrupt",
- "chat.resume",
- "chat.user_answer",
- "history.get",
- "browser.start",
- # "tts.synthesize",
- "skills.marketplace.list",
- "skills.list",
- "skills.installed",
- "skills.get",
- "skills.install",
- "skills.import_local",
- "skills.marketplace.add",
- "skills.marketplace.remove",
- "skills.marketplace.toggle",
- "skills.uninstall",
- "skills.skillnet.search",
- "skills.skillnet.install",
- "skills.skillnet.install_status",
- "skills.skillnet.evaluate",
- "skills.clawhub.get_token",
- "skills.clawhub.set_token",
- "skills.clawhub.search",
- "skills.clawhub.download",
-})
-
-_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset({
- "browser.start",
- "skills.marketplace.list",
- "skills.list",
- "skills.installed",
- "skills.get",
- "skills.install",
- "skills.import_local",
- "skills.marketplace.add",
- "skills.marketplace.remove",
- "skills.marketplace.toggle",
- "skills.uninstall",
- "skills.skillnet.search",
- "skills.skillnet.install",
- "skills.skillnet.install_status",
- "skills.skillnet.evaluate",
- "skills.clawhub.get_token",
- "skills.clawhub.set_token",
- "skills.clawhub.search",
- "skills.clawhub.download",
-})
-
-# 配置信息:config.get 返回、config.set 可修改的键(前端 param 名 -> 环境变量名)
-# default 模型 + video/audio/vision 多模型
-_CONFIG_SET_ENV_MAP = {
- # default 模型(主对话)
- "model_provider": "MODEL_PROVIDER",
- "model": "MODEL_NAME",
- "api_base": "API_BASE",
- "api_key": "API_KEY",
- # video 模型
- "video_api_base": "VIDEO_API_BASE",
- "video_api_key": "VIDEO_API_KEY",
- "video_model": "VIDEO_MODEL_NAME",
- "video_provider": "VIDEO_PROVIDER",
- # audio 模型
- "audio_api_base": "AUDIO_API_BASE",
- "audio_api_key": "AUDIO_API_KEY",
- "audio_model": "AUDIO_MODEL_NAME",
- "audio_provider": "AUDIO_PROVIDER",
- # vision 模型
- "vision_api_base": "VISION_API_BASE",
- "vision_api_key": "VISION_API_KEY",
- "vision_model": "VISION_MODEL_NAME",
- "vision_provider": "VISION_PROVIDER",
- # 其他
- "email_address": "EMAIL_ADDRESS",
- "email_token": "EMAIL_TOKEN",
- "embed_api_key": "EMBED_API_KEY",
- "embed_api_base": "EMBED_API_BASE",
- "embed_model": "EMBED_MODEL",
- "jina_api_key": "JINA_API_KEY",
- "serper_api_key": "SERPER_API_KEY",
- "perplexity_api_key": "PERPLEXITY_API_KEY",
- "github_token": "GITHUB_TOKEN",
- "evolution_auto_scan": "EVOLUTION_AUTO_SCAN",
-}
-# 配置项键名列表,用于日志等说明
-CONFIG_KEYS = tuple(_CONFIG_SET_ENV_MAP.keys())
-
-# 来自 config.yaml 的配置项(前端 param 名 -> config.yaml 路径)
-_CONFIG_YAML_KEYS = frozenset({"context_engine_enabled", "permissions_enabled"})
-
-
-async def _clear_agent_config_cache(agent_client=None) -> None:
- """写回 config.yaml 后清除 agent 侧配置缓存,使下次读取时得到最新文件内容。"""
- try:
- if agent_client is not None:
- from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields
- from jiuwenclaw.schema.message import ReqMethod
- import uuid
- env = e2a_from_agent_fields(
- request_id=f"cfg-cache-clear-{uuid.uuid4().hex[:8]}",
- channel_id="",
- req_method=ReqMethod.CONFIG_CACHE_CLEAR,
- )
- await agent_client.send_request(env)
- else:
- get_config()
- except Exception: # noqa: BLE001
- pass
-
-
-def _make_session_id() -> str:
- # 与前端 generateSessionId 保持一致:毫秒时间戳(16进制) + 6位随机16进制
- ts = format(int(time.time() * 1000), "x")
- suffix = secrets.token_hex(3)
- return f"sess_{ts}_{suffix}"
-
-
-def _register_web_handlers(
- channel,
- agent_client=None,
- message_handler=None,
- channel_manager=None,
- on_config_saved=None,
- heartbeat_service=None,
- cron_controller=None,
- updater_service: WindowsUpdaterService | None = None,
-):
- """注册 Web 前端需要的 method 与 on_connect。
- on_config_saved: 可选,config.set 写回 .env 后调用的回调;返回 True 表示已热更新未重启,False 表示已安排进程重启。
- heartbeat_service: 可选,GatewayHeartbeatService 实例,用于处理 heartbeat.get_conf / heartbeat.set_conf。
- """
- from jiuwenclaw.schema.message import Message, EventType
-
- def _resolve(ref, key="value"):
- """若为 ref 字典则取 key(无则返回 None),否则返回自身。"""
- if isinstance(ref, dict):
- return ref.get(key)
- return ref
-
- def _resolve_env_vars(value: Any) -> Any:
- """Recursively resolve environment variables in config values."""
- if isinstance(value, str):
- pattern = r'\$\{([^:}]+)(?::-([^}]*))?\}'
-
- def replace_env(match):
- var_name = match.group(1)
- default = match.group(2) if match.group(2) is not None else ""
- return os.getenv(var_name, default)
-
- return re.sub(pattern, replace_env, value)
- elif isinstance(value, dict):
- return {k: _resolve_env_vars(v) for k, v in value.items()}
- elif isinstance(value, list):
- return [_resolve_env_vars(item) for item in value]
- else:
- return value
-
- async def _on_connect(ws):
- ac = _resolve(agent_client)
- if ac is None or not getattr(ac, "server_ready", False):
- logger.debug("[_on_connect] Agent 未就绪,跳过 connection.ack")
- return
- sid = _make_session_id()
- ack_msg = Message(
- id=f"ack-{sid}",
- type="event",
- channel_id=channel.channel_id,
- session_id=sid,
- params={},
- timestamp=time.time(),
- ok=True,
- event_type=EventType.CONNECTION_ACK,
- payload={
- "session_id": sid,
- "mode": "BUILD",
- "tools": [],
- "protocol_version": "1.0",
- },
- )
- mh = _resolve(message_handler)
- if mh:
- await mh.publish_robot_messages(ack_msg)
- else:
- await channel.send(ack_msg)
-
- channel.on_connect(_on_connect)
-
- async def _config_get(ws, req_id, params, session_id):
- # 返回 _CONFIG_SET_ENV_MAP 里所有键对应的环境变量当前值
- payload = {
- param_key: (os.getenv(env_key) or "")
- for param_key, env_key in _CONFIG_SET_ENV_MAP.items()
- }
- payload["app_version"] = __version__
- # 合并 config.yaml 中的配置项
- try:
- raw = get_config_raw()
- for key, val in payload.items():
- if ("api_key" in key or "token" in key) and get_crypto_provider():
- payload[key] = get_crypto_provider().decrypt(val)
- ctx_cfg = (raw.get("react") or {}).get("context_engine_config") or {}
- payload["context_engine_enabled"] = "true" if ctx_cfg.get("enabled", False) else "false"
- perm_cfg = raw.get("permissions") or {}
- payload["permissions_enabled"] = "true" if perm_cfg.get("enabled", False) else "false"
- except Exception: # noqa: BLE001
- payload.setdefault("context_engine_enabled", "false")
- payload.setdefault("permissions_enabled", "false")
- await channel.send_response(ws, req_id, ok=True, payload=payload)
-
- def _persist_env_updates(updates: dict[str, str]) -> None:
- """把已更新的环境变量写回 .env(仅覆盖或追加对应 KEY=value 行)。"""
- env_path = _ENV_FILE
- if not updates:
- return
- try:
- lines: list[str] = []
- if env_path.is_file():
- with open(env_path, "r", encoding="utf-8") as f:
- lines = f.readlines()
- updated_keys = set(updates.keys())
- new_lines: list[str] = []
- for line in lines:
- stripped = line.strip()
- found = False
- for env_key, value in updates.items():
- if stripped.startswith(env_key + "="):
- new_lines.append(f'{env_key}="{value}"\n' if value else f"{env_key}=\n")
- found = True
- break
- if not found:
- new_lines.append(line)
- for env_key, value in updates.items():
- if not any(s.strip().startswith(env_key + "=") for s in new_lines):
- new_lines.append(f'{env_key}="{value}"\n' if value else f"{env_key}=\n")
- env_path.parent.mkdir(parents=True, exist_ok=True)
- with open(env_path, "w", encoding="utf-8") as f:
- f.writelines(new_lines)
- except OSError as e:
- logger.warning("[config.set] 写回 .env 失败: %s", e)
-
- async def _config_set(ws, req_id, params, session_id):
- """根据前端消息内容更新配置(支持 .env 与 config.yaml 中的键),并写回对应文件。"""
- if not isinstance(params, dict):
- await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
- return
- for key, val in params.items():
- if ("api_key" in key or "token" in key) and get_crypto_provider():
- params[key] = get_crypto_provider().encrypt(val)
- env_updates: dict[str, str] = {}
- yaml_updated: list[str] = []
- available_model_providers = [provider.value for provider in ProviderType]
-
- for param_key, env_key in _CONFIG_SET_ENV_MAP.items():
- if param_key not in params:
- continue
- val = params[param_key]
- if param_key.endswith("_provider") and val and val not in available_model_providers:
- await channel.send_response(
- ws, req_id, ok=False,
- error=f"Model provider must in: {available_model_providers} ",
- code="BAD_REQUEST"
- )
- return
- if val is None:
- env_updates[env_key] = ""
- else:
- env_updates[env_key] = str(val).strip()
-
- for param_key in _CONFIG_YAML_KEYS:
- if param_key not in params:
- continue
- val = params[param_key]
- parsed = str(val).strip().lower() in ("true", "1", "yes")
- try:
- if param_key == "context_engine_enabled":
- update_context_engine_enabled_in_config(parsed)
- elif param_key == "permissions_enabled":
- update_permissions_enabled_in_config(parsed)
- yaml_updated.append(param_key)
- except Exception as e: # noqa: BLE001
- logger.warning("[config.set] 写回 config.yaml 失败 %s: %s", param_key, e)
-
- for env_key, value in env_updates.items():
- os.environ[env_key] = value
- applied_without_restart = True
-
- if env_updates:
- _persist_env_updates(env_updates)
- logger.info("[config.set] 已更新 .env: %s", list(env_updates.keys()))
- if yaml_updated:
- await _clear_agent_config_cache(_resolve(agent_client))
- logger.info("[config.set] 已更新 config.yaml: %s", yaml_updated)
-
- if env_updates or yaml_updated:
- if on_config_saved:
- callback_result = on_config_saved(set(env_updates.keys()) | set(yaml_updated))
- if inspect.isawaitable(callback_result):
- callback_result = await callback_result
- applied_without_restart = bool(callback_result)
-
- updated_param_keys = [k for k, e in _CONFIG_SET_ENV_MAP.items() if e in env_updates] + yaml_updated
- await channel.send_response(
- ws, req_id, ok=True,
- payload={"updated": updated_param_keys, "applied_without_restart": applied_without_restart},
- )
-
- async def _channel_get(ws, req_id, params, session_id):
- """返回已注册的 channel 列表."""
- cm = _resolve(channel_manager)
- if cm is not None:
- channels = [{"channel_id": cid} for cid in cm.enabled_channels]
- else:
- channels = []
- await channel.send_response(ws, req_id, ok=True, payload={"channels": channels})
-
- async def _updater_get_status(ws, req_id, params, session_id):
- service = updater_service or WindowsUpdaterService()
- await channel.send_response(ws, req_id, ok=True, payload=service.get_status())
-
- async def _updater_check(ws, req_id, params, session_id):
- service = updater_service or WindowsUpdaterService()
- manual = bool((params or {}).get("manual", False)) if isinstance(params, dict) else False
- payload = await asyncio.to_thread(service.check, manual)
- await channel.send_response(ws, req_id, ok=True, payload=payload)
-
- async def _updater_download(ws, req_id, params, session_id):
- service = updater_service or WindowsUpdaterService()
- payload = service.start_download()
- await channel.send_response(ws, req_id, ok=True, payload=payload)
-
- async def _updater_get_conf(ws, req_id, params, session_id):
- service = updater_service or WindowsUpdaterService()
- await channel.send_response(ws, req_id, ok=True, payload=service.get_runtime_config())
-
- async def _updater_set_conf(ws, req_id, params, session_id):
- if not isinstance(params, dict):
- await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
- return
-
- updates: dict[str, Any] = {}
- if "enabled" in params:
- updates["enabled"] = bool(params.get("enabled"))
- for key in ("repo_owner", "repo_name", "release_api_url", "asset_name_pattern", "sha256_name_pattern"):
- if key in params:
- updates[key] = str(params.get(key) or "").strip()
- if "timeout_seconds" in params:
- try:
- updates["timeout_seconds"] = max(5, int(params.get("timeout_seconds")))
- except (TypeError, ValueError):
- await channel.send_response(ws, req_id, ok=False,
- error="timeout_seconds must be integer", code="BAD_REQUEST")
- return
-
- try:
- update_updater_in_config(updates)
- except Exception as exc: # noqa: BLE001
- logger.warning("[updater.set_conf] 写回 config.yaml 失败: %s", exc)
- await channel.send_response(ws, req_id, ok=False,
- error=str(exc), code="INTERNAL_ERROR")
- return
-
- service = updater_service or WindowsUpdaterService()
- await channel.send_response(ws, req_id, ok=True, payload=service.get_runtime_config())
-
- async def _session_list(ws, req_id, params, session_id):
- """返回 agent/sessions 下的 session_id 列表(子目录名)。"""
- limit = 20
- if isinstance(params, dict):
- raw_limit = params.get("limit")
- if isinstance(raw_limit, int):
- limit = raw_limit
- elif isinstance(raw_limit, str) and raw_limit.strip().isdigit():
- limit = int(raw_limit.strip())
- limit = max(1, min(limit, 200))
-
- workspace_session_dir = get_agent_sessions_dir()
- if not workspace_session_dir.exists() or not workspace_session_dir.is_dir():
- sessions = []
- else:
- sessions_with_mtime = []
- for d in workspace_session_dir.iterdir():
- if not d.is_dir():
- continue
- try:
- mtime = d.stat().st_mtime
- sessions_with_mtime.append((d.name, mtime))
- except OSError:
- continue
- # 按修改时间倒序排序
- sessions_with_mtime.sort(key=lambda x: x[1], reverse=True)
- sessions = [name for name, _ in sessions_with_mtime[:limit]]
- await channel.send_response(ws, req_id, ok=True, payload={"sessions": sessions})
-
- async def _session_create(ws, req_id, params, session_id):
- """创建一个新 session(在 agent/sessions 下创建一个新目录)。"""
- if not isinstance(params, dict):
- await channel.send_response(
- ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST",
- )
- return
- session_id_to_create = params.get("session_id")
- if not isinstance(session_id_to_create, str) or not session_id_to_create.strip():
- await channel.send_response(
- ws, req_id, ok=False, error="session_id is required", code="BAD_REQUEST",
- )
- return
- session_id_to_create = session_id_to_create.strip()
-
- workspace_session_dir = get_agent_sessions_dir()
- if not workspace_session_dir.exists():
- workspace_session_dir.mkdir(parents=True)
- session_dir = workspace_session_dir / session_id_to_create
- if session_dir.exists():
- await channel.send_response(
- ws, req_id, ok=False, error="session already exists", code="ALREADY_EXISTS",
- )
- return
- session_dir.mkdir()
- await channel.send_response(ws, req_id, ok=True, payload={"session_id": session_id_to_create})
-
- async def _session_delete(ws, req_id, params, session_id):
- """删除一个 session(在 agent/sessions 下删除一个目录)。"""
- if not isinstance(params, dict):
- await channel.send_response(
- ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST",
- )
- return
- session_id_to_delete = params.get("session_id")
- if not isinstance(session_id_to_delete, str) or not session_id_to_delete.strip():
- await channel.send_response(
- ws, req_id, ok=False, error="session_id is required", code="BAD_REQUEST",
- )
- return
- session_id_to_delete = session_id_to_delete.strip()
-
- workspace_session_dir = get_agent_sessions_dir()
- session_dir = workspace_session_dir / session_id_to_delete
- if not session_dir.exists():
- await channel.send_response(
- ws, req_id, ok=False, error="session not found", code="NOT_FOUND",
- )
- return
- if not session_dir.is_dir():
- await channel.send_response(
- ws, req_id, ok=False, error="session is not a directory", code="BAD_REQUEST",
- )
- return
- shutil.rmtree(session_dir)
- await channel.send_response(ws, req_id, ok=True, payload={"session_id": session_id_to_delete})
-
- async def _path_get(ws, req_id, params, session_id):
- """读 browser.chrome_path 并返回给前端(会解析环境变量)。"""
- try:
- config_base = get_config()
- except FileNotFoundError:
- await channel.send_response(
- ws,
- req_id,
- ok=True,
- payload={"chrome_path": ""},
- )
- return
-
- if not isinstance(config_base, dict):
- config_base = {}
-
- config = _resolve_env_vars(config_base)
- browser_cfg = config.get("browser", {}) if isinstance(config, dict) else {}
- chrome_path = ""
- if isinstance(browser_cfg, dict):
- value = browser_cfg.get("chrome_path", "")
- if isinstance(value, str):
- chrome_path = value
-
- await channel.send_response(ws, req_id, ok=True, payload={"chrome_path": chrome_path})
-
- async def _path_set(ws, req_id, params, session_id):
- """更新 browser.chrome_path 并写回 config。"""
- if not isinstance(params, dict):
- await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
- return
-
- chrome_path = params.get("chrome_path")
- if not isinstance(chrome_path, str):
- await channel.send_response(ws, req_id, ok=False, error="chrome_path must be string", code="BAD_REQUEST")
- return
- chrome_path = chrome_path.strip()
-
- try:
- update_browser_in_config({"chrome_path": chrome_path})
- await _clear_agent_config_cache(_resolve(agent_client))
- except Exception as e: # noqa: BLE001
- logger.warning("[path.set] 写回 config.yaml 失败: %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
- return
-
- await channel.send_response(ws, req_id, ok=True, payload={"chrome_path": chrome_path})
-
- async def _memory_compute(ws, req_id, params, session_id):
-
- process = psutil.Process()
- rss_bytes = process.memory_info().rss # 物理内存
- rss_mb = rss_bytes / (1024 * 1024)
-
- mem = psutil.virtual_memory()
- total_mb = mem.total / (1024 * 1024)
- available_mb = mem.available / (1024 * 1024)
- used_percent = mem.percent
-
- await channel.send_response(ws, req_id, ok=True,
- payload={"rss_mb": rss_mb, "total_mb": total_mb,
- "available_mb": available_mb})
-
-
-
- async def _chat_send(ws, req_id, params, session_id):
- await channel.send_response(
- ws,
- req_id,
- ok=True,
- payload={"accepted": True, "session_id": session_id},
- )
-
- async def _chat_resume(ws, req_id, params, session_id):
- await channel.send_response(
- ws,
- req_id,
- ok=True,
- payload={"accepted": True, "session_id": session_id},
- )
-
- async def _chat_interrupt(ws, req_id, params, session_id):
- intent = params.get("intent") if isinstance(params, dict) else None
- payload = {"accepted": True, "session_id": session_id}
- if isinstance(intent, str) and intent:
- payload["intent"] = intent
- await channel.send_response(ws, req_id, ok=True, payload=payload)
-
- async def _chat_user_answer(ws, req_id, params, session_id):
- payload = {"accepted": True, "session_id": session_id}
- request_id = params.get("request_id") if isinstance(params, dict) else None
- if isinstance(request_id, str) and request_id:
- payload["request_id"] = request_id
- await channel.send_response(ws, req_id, ok=True, payload=payload)
-
- async def _history_get(ws, req_id, params, session_id):
- payload = {"accepted": True, "session_id": session_id}
- if isinstance(params, dict):
- if "session_id" in params:
- payload["session_id"] = params.get("session_id")
- if "page_idx" in params:
- payload["page_idx"] = params.get("page_idx")
- await channel.send_response(ws, req_id, ok=True, payload=payload)
-
- async def _locale_get_conf(ws, req_id, params, session_id):
- """返回当前 preferred_language 配置(zh / en)。"""
- try:
- cfg = get_config()
- lang = str(cfg.get("preferred_language") or "zh").strip().lower()
- if lang not in ("zh", "en"):
- lang = "zh"
- await channel.send_response(
- ws,
- req_id,
- ok=True,
- payload={"preferred_language": lang}
- )
- except Exception as e:
- logger.exception("[locale.get_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- async def _locale_set_conf(ws, req_id, params, session_id):
- """更新 preferred_language 并写回 config.yaml。"""
- if not isinstance(params, dict):
- await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
- return
- lang_raw = params.get("preferred_language")
- if not isinstance(lang_raw, str):
- await channel.send_response(
- ws, req_id, ok=False, error="preferred_language must be string", code="BAD_REQUEST"
- )
- return
- lang = lang_raw.strip().lower()
- if lang not in ("zh", "en"):
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="preferred_language must be zh or en",
- code="BAD_REQUEST"
- )
- return
- try:
- update_preferred_language_in_config(lang)
- await channel.send_response(ws, req_id, ok=True, payload={"preferred_language": lang})
- except Exception as e:
- logger.warning("[locale.set_conf] 写回 config.yaml 失败: %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- async def _heartbeat_get_conf(ws, req_id, params, session_id):
- """返回当前心跳配置(every / target / active_hours)。"""
- hb = _resolve(heartbeat_service)
- if hb is None:
- await channel.send_response(ws, req_id, ok=False, error="heartbeat service not available",
- code="SERVICE_UNAVAILABLE")
- return
- try:
- payload = dict(hb.get_heartbeat_conf())
- await channel.send_response(ws, req_id, ok=True, payload=payload)
- except Exception as e:
- logger.exception("[heartbeat.get_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- async def _heartbeat_set_conf(ws, req_id, params, session_id):
- """更新心跳配置并重启心跳服务;params 可含 every、target、active_hours。"""
- hb = _resolve(heartbeat_service)
- if hb is None:
- await channel.send_response(ws, req_id, ok=False, error="heartbeat service not available",
- code="SERVICE_UNAVAILABLE")
- return
- if not isinstance(params, dict):
- await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
- return
- try:
- every = params.get("every")
- target = params.get("target")
- active_hours = params.get("active_hours")
- if every is not None:
- every = float(every)
- if target is not None:
- target = str(target)
- if active_hours is not None:
- if not isinstance(active_hours, dict):
- active_hours = None
- elif active_hours and ("start" not in active_hours or "end" not in active_hours):
- # 必须同时包含 start/end,否则视为清除时间段(始终生效)
- active_hours = None
- await hb.set_heartbeat_conf(every=every, target=target, active_hours=active_hours)
- payload = dict(hb.get_heartbeat_conf())
- try:
- update_heartbeat_in_config(payload)
- await _clear_agent_config_cache(_resolve(agent_client))
- except Exception as e: # noqa: BLE001
- logger.warning("[heartbeat.set_conf] 写回 config.yaml 失败: %s", e)
- await channel.send_response(ws, req_id, ok=True, payload=payload)
- except ValueError as e:
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="BAD_REQUEST")
- except Exception as e:
- logger.exception("[heartbeat.set_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- async def _channel_feishu_get_conf(ws, req_id, params, session_id):
- """返回 FeishuChannel 的当前配置(由 ChannelManager 管理)。"""
- cm = _resolve(channel_manager)
- if cm is None:
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="channel manager not available",
- code="SERVICE_UNAVAILABLE",
- )
- return
- try:
- conf = cm.get_conf("feishu")
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
- except Exception as e: # noqa: BLE001
- logger.exception("[channel.feishu.get_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- async def _channel_feishu_set_conf(ws, req_id, params, session_id):
- """更新 FeishuChannel 的配置,并按新配置重新实例化通道。"""
- cm = _resolve(channel_manager)
- if cm is None:
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="channel manager not available",
- code="SERVICE_UNAVAILABLE",
- )
- return
- if not isinstance(params, dict):
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="params must be object",
- code="BAD_REQUEST",
- )
- return
- try:
- await cm.set_conf("feishu", params)
- conf = cm.get_conf("feishu")
- try:
- update_channel_in_config("feishu", conf)
- await _clear_agent_config_cache(_resolve(agent_client))
- except Exception as e: # noqa: BLE001
- logger.warning("[channel.feishu.set_conf] 写回 config.yaml 失败: %s", e)
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
- except Exception as e: # noqa: BLE001
- logger.exception("[channel.feishu.set_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- async def _channel_xiaoyi_get_conf(ws, req_id, params, session_id):
- """返回 XiaoyiChannel 的当前配置(由 ChannelManager 管理)。"""
- cm = _resolve(channel_manager)
- if cm is None:
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="channel manager not available",
- code="SERVICE_UNAVAILABLE",
- )
- return
- try:
- conf = cm.get_conf("xiaoyi")
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
- except Exception as e: # noqa: BLE001
- logger.exception("[channel.xiaoyi.get_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- async def _channel_xiaoyi_set_conf(ws, req_id, params, session_id):
- """更新 XiaoyiChannel 的配置,并按新配置重新实例化通道。"""
- cm = _resolve(channel_manager)
- if cm is None:
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="channel manager not available",
- code="SERVICE_UNAVAILABLE",
- )
- return
- if not isinstance(params, dict):
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="params must be object",
- code="BAD_REQUEST",
- )
- return
- try:
- await cm.set_conf("xiaoyi", params)
- conf = cm.get_conf("xiaoyi")
- try:
- update_channel_in_config("xiaoyi", conf)
- await _clear_agent_config_cache(_resolve(agent_client))
- except Exception as e: # noqa: BLE001
- logger.warning("[channel.xiaoyi.set_conf] 写回 config.yaml 失败: %s", e)
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
- except Exception as e: # noqa: BLE001
- logger.exception("[channel.xiaoyi.set_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- async def _channel_telegram_get_conf(ws, req_id, params, session_id):
- """返回 TelegramChannel 的当前配置(由 ChannelManager 管理)。"""
- cm = _resolve(channel_manager)
- if cm is None:
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="channel manager not available",
- code="SERVICE_UNAVAILABLE",
- )
- return
- try:
- conf = cm.get_conf("telegram")
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
- except Exception as e: # noqa: BLE001
- logger.exception("[channel.telegram.get_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- async def _channel_telegram_set_conf(ws, req_id, params, session_id):
- """更新 TelegramChannel 的配置,并按新配置重新实例化通道。"""
- cm = _resolve(channel_manager)
- if cm is None:
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="channel manager not available",
- code="SERVICE_UNAVAILABLE",
- )
- return
- if not isinstance(params, dict):
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="params must be object",
- code="BAD_REQUEST",
- )
- return
- try:
- await cm.set_conf("telegram", params)
- conf = cm.get_conf("telegram")
- try:
- update_channel_in_config("telegram", conf)
- await _clear_agent_config_cache(_resolve(agent_client))
- except Exception as e: # noqa: BLE001
- logger.warning("[channel.telegram.set_conf] 写回 config.yaml 失败: %s", e)
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
- except Exception as e: # noqa: BLE001
- logger.exception("[channel.telegram.set_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- async def _channel_dingtalk_get_conf(ws, req_id, params, session_id):
- cm = _resolve(channel_manager)
- if cm is None:
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="channel manager not available",
- code="SERVICE_UNAVAILABLE",
- )
- return
- try:
- conf = cm.get_conf("dingtalk")
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
- except Exception as e: # noqa: BLE001
- logger.exception("[channel.dingtalk.get_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- async def _channel_dingtalk_set_conf(ws, req_id, params, session_id):
- cm = _resolve(channel_manager)
- if cm is None:
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="channel manager not available",
- code="SERVICE_UNAVAILABLE",
- )
- return
- if not isinstance(params, dict):
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="params must be object",
- code="BAD_REQUEST",
- )
- return
- try:
- await cm.set_conf("dingtalk", params)
- conf = cm.get_conf("dingtalk")
- try:
- update_channel_in_config("dingtalk", conf)
- await _clear_agent_config_cache(_resolve(agent_client))
- except Exception as e: # noqa: BLE001
- logger.warning("[channel.dingtalk.set_conf] 写回 config.yaml 失败: %s", e)
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
- except Exception as e: # noqa: BLE001
- logger.exception("[channel.dingtalk.set_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
- async def _channel_whatsapp_get_conf(ws, req_id, params, session_id):
- cm = _resolve(channel_manager)
- if cm is None:
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="channel manager not available",
- code="SERVICE_UNAVAILABLE",
- )
- return
- try:
- conf = cm.get_conf("whatsapp")
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
- except Exception as e: # noqa: BLE001
- logger.exception("[channel.whatsapp.get_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- async def _channel_whatsapp_set_conf(ws, req_id, params, session_id):
- cm = _resolve(channel_manager)
- if cm is None:
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="channel manager not available",
- code="SERVICE_UNAVAILABLE",
- )
- return
- if not isinstance(params, dict):
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="params must be object",
- code="BAD_REQUEST",
- )
- return
- try:
- await cm.set_conf("whatsapp", params)
- conf = cm.get_conf("whatsapp")
- try:
- update_channel_in_config("whatsapp", conf)
- await _clear_agent_config_cache(_resolve(agent_client))
- except Exception as e: # noqa: BLE001
- logger.warning("[channel.whatsapp.set_conf] 写回 config.yaml 失败: %s", e)
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
- except Exception as e: # noqa: BLE001
- logger.exception("[channel.whatsapp.set_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+load_dotenv(dotenv_path=get_env_file())
- async def _channel_discord_get_conf(ws, req_id, params, session_id):
- cm = _resolve(channel_manager)
- if cm is None:
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="channel manager not available",
- code="SERVICE_UNAVAILABLE",
- )
- return
- try:
- conf = cm.get_conf("discord")
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
- except Exception as e: # noqa: BLE001
- logger.exception("[channel.discord.get_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
- async def _channel_discord_set_conf(ws, req_id, params, session_id):
- cm = _resolve(channel_manager)
- if cm is None:
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="channel manager not available",
- code="SERVICE_UNAVAILABLE",
- )
- return
- if not isinstance(params, dict):
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="params must be object",
- code="BAD_REQUEST",
- )
- return
- try:
- await cm.set_conf("discord", params)
- conf = cm.get_conf("discord")
- try:
- update_channel_in_config("discord", conf)
- await _clear_agent_config_cache(_resolve(agent_client))
- except Exception as e: # noqa: BLE001
- logger.warning("[channel.discord.set_conf] 写回 config.yaml 失败: %s", e)
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
- except Exception as e: # noqa: BLE001
- logger.exception("[channel.discord.set_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- async def _channel_wecom_get_conf(ws, req_id, params, session_id):
- cm = _resolve(channel_manager)
- if cm is None:
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="channel manager not available",
- code="SERVICE_UNAVAILABLE",
- )
- return
- try:
- conf = cm.get_conf("wecom")
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
- except Exception as e: # noqa: BLE001
- logger.exception("[channel.wecom.get_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- async def _channel_wecom_set_conf(ws, req_id, params, session_id):
- cm = _resolve(channel_manager)
- if cm is None:
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="channel manager not available",
- code="SERVICE_UNAVAILABLE",
- )
- return
- if not isinstance(params, dict):
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="params must be object",
- code="BAD_REQUEST",
- )
- return
- try:
- await cm.set_conf("wecom", params)
- conf = cm.get_conf("wecom")
- try:
- update_channel_in_config("wecom", conf)
- await _clear_agent_config_cache(_resolve(agent_client))
- except Exception as e: # noqa: BLE001
- logger.warning("[channel.wecom.set_conf] 写回 config.yaml 失败: %s", e)
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
- except Exception as e: # noqa: BLE001
- logger.exception("[channel.wecom.set_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- async def _channel_wechat_get_conf(ws, req_id, params, session_id):
- cm = _resolve(channel_manager)
- if cm is None:
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="channel manager not available",
- code="SERVICE_UNAVAILABLE",
- )
- return
- try:
- conf = cm.get_conf("wechat")
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
- except Exception as e: # noqa: BLE001
- logger.exception("[channel.wechat.get_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- async def _channel_wechat_set_conf(ws, req_id, params, session_id):
- cm = _resolve(channel_manager)
- if cm is None:
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="channel manager not available",
- code="SERVICE_UNAVAILABLE",
- )
- return
- if not isinstance(params, dict):
- await channel.send_response(
- ws,
- req_id,
- ok=False,
- error="params must be object",
- code="BAD_REQUEST",
- )
- return
- try:
- await cm.set_conf("wechat", params)
- conf = cm.get_conf("wechat")
- try:
- update_channel_in_config("wechat", conf)
- await _clear_agent_config_cache(_resolve(agent_client))
- except Exception as e: # noqa: BLE001
- logger.warning("[channel.wechat.set_conf] 写回 config.yaml 失败: %s", e)
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
- except Exception as e: # noqa: BLE001
- logger.exception("[channel.wechat.set_conf] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- async def _channel_wechat_get_login_ui(ws, req_id, params, session_id):
- from jiuwenclaw.channel.wechat_channel import snapshot_wechat_login_ui_state
-
- try:
- ui = await snapshot_wechat_login_ui_state()
- if "updated_at" in ui and isinstance(ui["updated_at"], (int, float)):
- ui["updated_at"] = int(ui["updated_at"])
- await channel.send_response(ws, req_id, ok=True, payload=ui)
- except Exception as e: # noqa: BLE001
- logger.exception("[channel.wechat.get_login_ui] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- # ----- cron jobs -----
-
- def _get_cron():
- return _resolve(cron_controller)
-
- async def _cron_job_list(ws, req_id, params, session_id):
- cc = _get_cron()
- if cc is None:
- await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
- return
- jobs = await cc.list_jobs()
- await channel.send_response(ws, req_id, ok=True, payload={"jobs": jobs})
-
- async def _cron_job_get(ws, req_id, params, session_id):
- cc = _get_cron()
- if cc is None:
- await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
- return
- if not isinstance(params, dict):
- await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
- return
- job_id = str(params.get("id") or "").strip()
- if not job_id:
- await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
- return
- job = await cc.get_job(job_id)
- if job is None:
- await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
- return
- await channel.send_response(ws, req_id, ok=True, payload={"job": job})
-
- async def _cron_job_create(ws, req_id, params, session_id):
- cc = _get_cron()
- if cc is None:
- await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
- return
- if not isinstance(params, dict):
- await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
- return
- try:
- job = await cc.create_job(params)
- await channel.send_response(ws, req_id, ok=True, payload={"job": job})
- except Exception as e: # noqa: BLE001
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="BAD_REQUEST")
-
- async def _cron_job_update(ws, req_id, params, session_id):
- cc = _get_cron()
- if cc is None:
- await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
- return
- if not isinstance(params, dict):
- await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
- return
- job_id = str(params.get("id") or "").strip()
- patch = params.get("patch") or {}
- if not job_id:
- await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
- return
- if not isinstance(patch, dict):
- await channel.send_response(ws, req_id, ok=False, error="patch must be object", code="BAD_REQUEST")
- return
- try:
- job = await cc.update_job(job_id, patch)
- await channel.send_response(ws, req_id, ok=True, payload={"job": job})
- except KeyError:
- await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
- except Exception as e: # noqa: BLE001
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="BAD_REQUEST")
-
- async def _cron_job_delete(ws, req_id, params, session_id):
- cc = _get_cron()
- if cc is None:
- await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
- return
- if not isinstance(params, dict):
- await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
- return
- job_id = str(params.get("id") or "").strip()
- if not job_id:
- await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
- return
- deleted = await cc.delete_job(job_id)
- if not deleted:
- await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
- return
- await channel.send_response(ws, req_id, ok=True, payload={"deleted": True})
-
- async def _cron_job_toggle(ws, req_id, params, session_id):
- cc = _get_cron()
- if cc is None:
- await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
- return
- if not isinstance(params, dict):
- await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
- return
- job_id = str(params.get("id") or "").strip()
- enabled = params.get("enabled", None)
- if not job_id:
- await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
- return
- if enabled is None:
- await channel.send_response(ws, req_id, ok=False, error="enabled is required", code="BAD_REQUEST")
- return
- try:
- job = await cc.toggle_job(job_id, bool(enabled))
- await channel.send_response(ws, req_id, ok=True, payload={"job": job})
- except KeyError:
- await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
-
- async def _cron_job_preview(ws, req_id, params, session_id):
- cc = _get_cron()
- if cc is None:
- await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
- return
- if not isinstance(params, dict):
- await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
- return
- job_id = str(params.get("id") or "").strip()
- count = params.get("count", 5)
- if not job_id:
- await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
- return
- try:
- next_runs = await cc.preview_job(job_id, int(count) if count is not None else 5)
- await channel.send_response(ws, req_id, ok=True, payload={"next": next_runs})
- except KeyError:
- await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
- except Exception as e: # noqa: BLE001
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="BAD_REQUEST")
-
- async def _cron_job_run_now(ws, req_id, params, session_id):
- cc = _get_cron()
- if cc is None:
- await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
- return
- if not isinstance(params, dict):
- await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
- return
- job_id = str(params.get("id") or "").strip()
- if not job_id:
- await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
- return
- try:
- run_id = await cc.run_now(job_id)
- await channel.send_response(ws, req_id, ok=True, payload={"run_id": run_id})
- except KeyError:
- await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
- except Exception as e: # noqa: BLE001
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- channel.register_method("config.get", _config_get)
- channel.register_method("config.set", _config_set)
- channel.register_method("channel.get", _channel_get)
-
- channel.register_method("session.list", _session_list)
- channel.register_method("session.create", _session_create)
- channel.register_method("session.delete", _session_delete)
-
- channel.register_method("path.get", _path_get)
- channel.register_method("path.set", _path_set)
-
- channel.register_method("memory.compute", _memory_compute)
-
- channel.register_method("chat.send", _chat_send)
- channel.register_method("chat.resume", _chat_resume)
- channel.register_method("chat.interrupt", _chat_interrupt)
- channel.register_method("chat.user_answer", _chat_user_answer)
- channel.register_method("history.get", _history_get)
- channel.register_method("locale.get_conf", _locale_get_conf)
- channel.register_method("locale.set_conf", _locale_set_conf)
- channel.register_method("updater.get_status", _updater_get_status)
- channel.register_method("updater.check", _updater_check)
- channel.register_method("updater.download", _updater_download)
- channel.register_method("updater.get_conf", _updater_get_conf)
- channel.register_method("updater.set_conf", _updater_set_conf)
- channel.register_method("heartbeat.get_conf", _heartbeat_get_conf)
- channel.register_method("heartbeat.set_conf", _heartbeat_set_conf)
- channel.register_method("channel.feishu.get_conf", _channel_feishu_get_conf)
- channel.register_method("channel.feishu.set_conf", _channel_feishu_set_conf)
- channel.register_method("channel.xiaoyi.get_conf", _channel_xiaoyi_get_conf)
- channel.register_method("channel.xiaoyi.set_conf", _channel_xiaoyi_set_conf)
- channel.register_method("channel.telegram.get_conf", _channel_telegram_get_conf)
- channel.register_method("channel.telegram.set_conf", _channel_telegram_set_conf)
- channel.register_method("channel.dingtalk.get_conf", _channel_dingtalk_get_conf)
- channel.register_method("channel.dingtalk.set_conf", _channel_dingtalk_set_conf)
- channel.register_method("channel.whatsapp.get_conf", _channel_whatsapp_get_conf)
- channel.register_method("channel.whatsapp.set_conf", _channel_whatsapp_set_conf)
- channel.register_method("channel.discord.get_conf", _channel_discord_get_conf)
- channel.register_method("channel.discord.set_conf", _channel_discord_set_conf)
- channel.register_method("channel.wecom.get_conf", _channel_wecom_get_conf)
- channel.register_method("channel.wecom.set_conf", _channel_wecom_set_conf)
- channel.register_method("channel.wechat.get_conf", _channel_wechat_get_conf)
- channel.register_method("channel.wechat.set_conf", _channel_wechat_set_conf)
- channel.register_method("channel.wechat.get_login_ui", _channel_wechat_get_login_ui)
- channel.register_method("cron.job.list", _cron_job_list)
- channel.register_method("cron.job.get", _cron_job_get)
- channel.register_method("cron.job.create", _cron_job_create)
- channel.register_method("cron.job.update", _cron_job_update)
- channel.register_method("cron.job.delete", _cron_job_delete)
- channel.register_method("cron.job.toggle", _cron_job_toggle)
- channel.register_method("cron.job.preview", _cron_job_preview)
- channel.register_method("cron.job.run_now", _cron_job_run_now)
-
-
-async def _run() -> None:
- from jiuwenclaw.channel.feishu import FeishuChannel, FeishuConfig
- from jiuwenclaw.channel.web_channel import WebChannel, WebChannelConfig
- from jiuwenclaw.channel.xiaoyi_channel import XiaoyiChannel, XiaoyiChannelConfig
- from jiuwenclaw.channel.telegram_channel import TelegramChannel, TelegramChannelConfig
- from jiuwenclaw.channel.discord_channel import DiscordChannel, DiscordChannelConfig
- from jiuwenclaw.channel.wecom_channel import WecomChannel, WecomConfig
- from jiuwenclaw.gateway import (
- AgentWebSocketServer,
- GatewayHeartbeatService,
- HeartbeatConfig,
- WebSocketAgentServerClient,
- )
- from jiuwenclaw.gateway.channel_manager import ChannelManager
- from jiuwenclaw.gateway.cron import CronController, CronJobStore, CronSchedulerService
- from jiuwenclaw.gateway.message_handler import MessageHandler
- from jiuwenclaw.schema.message import Message, EventType, ReqMethod
-
- agent_port = int(os.getenv("AGENT_PORT", "18092"))
- web_host = os.getenv("WEB_HOST", "127.0.0.1")
- web_port = int(os.getenv("WEB_PORT", "19000"))
- web_path = os.getenv("WEB_PATH", "/ws")
-
- def _do_restart() -> None:
- """重新执行当前进程以加载新 .env(配置修改后重启服务)。"""
- logger.info("[App] 配置已写回 .env,正在重启服务…")
- os.execv(sys.executable, [sys.executable, *sys.argv])
-
- def _schedule_restart() -> None:
- """延迟 2 秒后重启,便于先返回 config.set 的响应。"""
- try:
- loop = asyncio.get_running_loop()
- loop.call_later(2.0, _do_restart)
- except RuntimeError:
- _do_restart()
-
- server = AgentWebSocketServer.get_instance(
- host="127.0.0.1",
- port=agent_port,
- ping_interval=20.0,
- ping_timeout=20.0,
- )
- await server.start()
- await asyncio.sleep(0.3)
- uri = f"ws://127.0.0.1:{agent_port}"
-
- # ---------- 扩展系统初始化 ----------
- from openjiuwen.core.runner import Runner
- from jiuwenclaw.extensions import ExtensionManager, ExtensionRegistry
-
- callback_framework = Runner.callback_framework
- extension_registry = ExtensionRegistry.create_instance(
- callback_framework=callback_framework,
- config={},
- logger=logger,
- )
-
- extension_manager = ExtensionManager(
- registry=extension_registry,
- )
-
- await extension_manager.load_all_extensions()
- logger.info("[App] 扩展加载完成,共 %d 个", len(extension_manager.list_extensions()))
-
- # 检查是否有扩展提供 AgentServerClient
- agent_server_ext = extension_registry.get_agent_server_client_extension()
- if agent_server_ext is not None:
- logger.info("[App] 使用扩展提供的 AgentServerClient: %s", agent_server_ext.metadata.name)
- client = agent_server_ext.get_client()
- await client.connect(uri)
- else:
- client = WebSocketAgentServerClient(ping_interval=20.0, ping_timeout=20.0)
- await client.connect(uri)
+def main() -> None:
+ from jiuwenclaw.telemetry import init_telemetry
- message_handler = MessageHandler(client)
- await message_handler.start_forwarding()
+ init_telemetry()
- cron_store = CronJobStore()
- cron_scheduler = CronSchedulerService(store=cron_store, agent_client=client, message_handler=message_handler)
- cron_controller = CronController.get_instance(store=cron_store, scheduler=cron_scheduler)
+ python = sys.executable
- # 探活:周期性向 AgentServer 发送心跳,便于检测连接与 Agent 可用性
- # 优先从 config/config.yaml 的 heartbeat 段读取配置,其次回退到环境变量/默认值
- heartbeat_cfg: dict | None = None
- channels_cfg: dict | None = None
+ agent = subprocess.Popen([python, "-m", "jiuwenclaw.app_agentserver"])
+ gateway = None
try:
- full_cfg = get_config()
- heartbeat_cfg = full_cfg.get("heartbeat") if isinstance(full_cfg, dict) else None
- channels_cfg = full_cfg.get("channels") if isinstance(full_cfg, dict) else None
- except Exception as e: # noqa: BLE001
- logger.warning("[App] 读取 config.yaml heartbeat 配置失败,将使用默认值: %s", e)
- heartbeat_cfg = None
- channels_cfg = None
-
- if isinstance(heartbeat_cfg, dict):
- cfg_every = heartbeat_cfg.get("every")
- cfg_target = heartbeat_cfg.get("target")
- cfg_active_hours = heartbeat_cfg.get("active_hours")
- else:
- cfg_every = None
- cfg_target = None
- cfg_active_hours = None
-
- # interval_seconds:环境变量优先,其次 heartbeat.every,最后默认 60
- heartbeat_interval = float(
- os.getenv("HEARTBEAT_INTERVAL")
- or (str(cfg_every) if cfg_every is not None else "60")
- )
- # timeout_seconds 依旧仅由环境变量控制,保持兼容
- heartbeat_timeout = float(os.getenv("HEARTBEAT_TIMEOUT", "30")) if os.getenv("HEARTBEAT_TIMEOUT") else None
- # relay_channel_id:环境变量优先,其次 heartbeat.target,最后默认 "web"
- heartbeat_relay_channel = os.getenv("HEARTBEAT_RELAY_CHANNEL_ID") or (
- str(cfg_target) if cfg_target is not None else "web"
- )
-
- heartbeat_config = HeartbeatConfig(
- interval_seconds=heartbeat_interval,
- timeout_seconds=heartbeat_timeout,
- relay_channel_id=heartbeat_relay_channel,
- active_hours=cfg_active_hours if isinstance(cfg_active_hours, dict) else None,
- )
- heartbeat_service = GatewayHeartbeatService(client, heartbeat_config, message_handler=message_handler)
- await heartbeat_service.start()
-
- # 初始 Channel 配置(来自 config.yaml 的 channels 段,若不存在则为空)
- initial_channels_conf: dict = channels_cfg if isinstance(channels_cfg, dict) else {}
-
- channel_manager = ChannelManager(message_handler, config=initial_channels_conf)
- updater_service = WindowsUpdaterService()
-
- async def _on_config_saved(updated_env_keys: set[str] | None = None) -> bool:
- """先尝试热更新,失败则安排延迟重启。返回 True 表示已热更新未重启,False 表示已安排重启。"""
- browser_runtime_keys = {
- "MODEL_PROVIDER", "MODEL_NAME", "API_BASE", "API_KEY",
- "VIDEO_PROVIDER", "VIDEO_MODEL_NAME", "VIDEO_API_BASE", "VIDEO_API_KEY",
- "AUDIO_PROVIDER", "AUDIO_MODEL_NAME", "AUDIO_API_BASE", "AUDIO_API_KEY",
- "VISION_PROVIDER", "VISION_MODEL_NAME", "VISION_API_BASE", "VISION_API_KEY",
- }
- try:
- from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields
- from jiuwenclaw.schema.message import ReqMethod
- import uuid
-
- reload_env = e2a_from_agent_fields(
- request_id=f"agent-reload-{uuid.uuid4().hex[:8]}",
- channel_id="",
- req_method=ReqMethod.AGENT_RELOAD_CONFIG,
- )
- await client.send_request(reload_env)
-
- if updated_env_keys and (browser_runtime_keys & set(updated_env_keys)):
- restart_env = e2a_from_agent_fields(
- request_id=f"browser-restart-{uuid.uuid4().hex[:8]}",
- channel_id="",
- req_method=ReqMethod.BROWSER_RUNTIME_RESTART,
- )
- await client.send_request(restart_env)
- return True
- except Exception as e: # noqa: BLE001
- logger.warning("[App] 配置热更新失败,将延迟重启: %s", e)
- _schedule_restart()
- return False
-
- web_config = WebChannelConfig(
- enabled=True, host=web_host, port=web_port, path=web_path,
- )
- web_channel = WebChannel(web_config, _DummyBus())
- _register_web_handlers(
- web_channel,
- agent_client=client,
- message_handler=message_handler,
- channel_manager=channel_manager,
- on_config_saved=_on_config_saved,
- heartbeat_service=heartbeat_service,
- cron_controller=cron_controller,
- updater_service=updater_service,
- )
-
- def _norm_and_forward(msg: Message) -> bool:
- method_val = getattr(getattr(msg, "req_method", None), "value", None) or ""
- if method_val not in _FORWARD_REQ_METHODS:
- return False
- is_stream = bool(
- msg.is_stream
- or method_val in (ReqMethod.CHAT_SEND.value, ReqMethod.HISTORY_GET.value)
- )
- params = dict(msg.params or {})
- if "query" not in params and "content" in params:
- params["query"] = params["content"]
- normalized = Message(
- id=msg.id,
- type=msg.type,
- channel_id=msg.channel_id,
- session_id=msg.session_id,
- params=params,
- timestamp=msg.timestamp,
- ok=msg.ok,
- req_method=getattr(msg, "req_method", None) or ReqMethod.CHAT_SEND,
- mode=msg.mode,
- is_stream=is_stream,
- stream_seq=msg.stream_seq,
- stream_id=msg.stream_id,
- metadata=msg.metadata,
- )
- channel_manager._message_handler.handle_message(normalized)
- logger.info("[App] Web 入站 -> MessageHandler: id=%s channel_id=%s", msg.id, msg.channel_id)
- # 对仅转发、无本地处理器的方法,标记为“已处理”,避免 WebChannel 再返回 METHOD_NOT_FOUND。
- if method_val in _FORWARD_NO_LOCAL_HANDLER_METHODS:
- return True
- return False
-
- web_channel.on_message(_norm_and_forward)
- channel_manager._channels[web_channel.channel_id] = web_channel
-
- # ---------- 按配置管理各 Channel(配置来源:config/config.yaml -> channels.*) ----------
- feishu_channel = None
- feishu_task = None
- xiaoyi_channel = None
- xiaoyi_task = None
- dingtalk_channel = None
- dingtalk_task = None
- telegram_channel = None
- telegram_task = None
- discord_channel = None
- discord_task = None
- whatsapp_channel = None
- whatsapp_task = None
- wecom_channel = None
- wecom_task = None
- wechat_channel = None
- wechat_task = None
- feishu_enterprise_channels: dict[str, FeishuChannel] = {}
- feishu_enterprise_tasks: dict[str, asyncio.Task] = {}
-
- _last_channels_conf = {} # Store previous config to detect changes
-
- def _should_restart_channel(channel_name: str, old_conf: dict, new_conf: dict) -> bool:
- old_channel_conf = old_conf.get(channel_name) if isinstance(old_conf, dict) else None
- new_channel_conf = new_conf.get(channel_name) if isinstance(new_conf, dict) else None
- if (old_channel_conf is None) != (new_channel_conf is None):
- return True
- if old_channel_conf is None:
- return False
- return old_channel_conf != new_channel_conf
-
- async def _stop_channel(channel, task, channel_name: str, background_wait: bool = False) -> None:
- if task is not None:
- task.cancel()
- if background_wait:
- async def wait_cancel():
- try:
- await task
- except (TypeError, asyncio.CancelledError):
- logger.info("[App] 取消旧 %sChannel 任务成功", channel_name.capitalize())
- except Exception as e: # noqa: BLE001
- logger.warning("[App] 等待旧 %sChannel 任务结束时忽略异常: %s", channel_name.capitalize(), e)
- asyncio.create_task(wait_cancel(), name=f"wait_{channel_name}_cancel")
- else:
- try:
- await asyncio.wait_for(task, timeout=5.0)
- except asyncio.TimeoutError:
- logger.warning("[App] 等待 %sChannel 任务取消超时", channel_name.capitalize())
- except asyncio.CancelledError:
- pass
- except Exception as e: # noqa: BLE001
- logger.warning("[App] 等待旧 %sChannel 任务结束时忽略异常: %s", channel_name.capitalize(), e)
-
- if channel is not None:
- try:
- await asyncio.wait_for(channel.stop(), timeout=10.0)
- except asyncio.TimeoutError:
- logger.warning("[App] 停止 %sChannel 超时", channel_name.capitalize())
- except Exception as e: # noqa: BLE001
- logger.warning("[App] 停止旧 %sChannel 失败: %s", channel_name.capitalize(), e)
- channel_manager.unregister_channel(channel.channel_id)
-
- def _is_channel_enabled(conf: dict | None, required_fields: list[str]) -> tuple[bool, str]:
- if conf is None:
- return False, "未配置或格式错误"
- enabled_raw = conf.get("enabled", None)
- if enabled_raw is None:
- all_fields_present = all(conf.get(f) for f in required_fields)
- return all_fields_present, f"缺少 {','.join(required_fields)}" if not all_fields_present else ""
- return bool(enabled_raw), "enabled = false" if not enabled_raw else ""
-
- async def _apply_channel_config(conf: dict) -> None:
- """根据最新 Channel 配置重新实例化各 Channel。"""
- nonlocal feishu_channel, feishu_task, xiaoyi_channel, xiaoyi_task
- nonlocal dingtalk_channel, dingtalk_task, telegram_channel, telegram_task
- nonlocal discord_channel, discord_task
- nonlocal whatsapp_channel, whatsapp_task
- nonlocal wecom_channel, wecom_task
- nonlocal wechat_channel, wechat_task
- nonlocal _last_channels_conf
- nonlocal feishu_enterprise_channels, feishu_enterprise_tasks
-
- changed_channels: list[str] = []
- for channel_name in [
- "feishu",
- "feishu_enterprise",
- "xiaoyi",
- "dingtalk",
- "telegram",
- "whatsapp",
- "discord",
- "wecom",
- "wechat",
- ]:
- if _should_restart_channel(channel_name, _last_channels_conf, conf):
- changed_channels.append(channel_name)
- _last_channels_conf = dict(conf or {})
-
- if "feishu" in changed_channels:
- feishu_conf = conf.get("feishu") if isinstance(conf, dict) else None
- await _stop_channel(feishu_channel, feishu_task, "feishu")
- feishu_channel, feishu_task = None, None
-
- if isinstance(feishu_conf, dict):
- enabled, reason = _is_channel_enabled(feishu_conf, ["app_id", "app_secret"])
- if not enabled:
- logger.info("[App] channels.feishu.%s,FeishuChannel 未启用", reason)
- else:
- feishu_config = FeishuConfig(
- enabled=True,
- app_id=str(feishu_conf.get("app_id") or "").strip(),
- app_secret=str(feishu_conf.get("app_secret") or "").strip(),
- encrypt_key=str(feishu_conf.get("encrypt_key") or "").strip(),
- verification_token=str(feishu_conf.get("verification_token") or "").strip(),
- allow_from=feishu_conf.get("allow_from") or [],
- enable_streaming=bool(feishu_conf.get("enable_streaming", True)),
- chat_id=str(feishu_conf.get("chat_id") or "").strip(),
- last_chat_id=str(feishu_conf.get("last_chat_id") or "").strip(),
- last_open_id=str(feishu_conf.get("last_open_id") or "").strip(),
- )
- feishu_channel = FeishuChannel(feishu_config, _DummyBus())
- channel_manager.register_channel(feishu_channel)
- feishu_task = asyncio.create_task(feishu_channel.start(), name="feishu")
- logger.info("[App] 已按 config.yaml.channels.feishu 注册 FeishuChannel")
- else:
- logger.info("[App] channels.feishu 未配置或格式错误,FeishuChannel 不启用")
-
- if "feishu_enterprise" in changed_channels:
- for bot_key, task in list(feishu_enterprise_tasks.items()):
- await _stop_channel(feishu_enterprise_channels.get(bot_key), task, f"feishu_enterprise[{bot_key}]")
- feishu_enterprise_channels = {}
- feishu_enterprise_tasks = {}
-
- enterprise_conf = conf.get("feishu_enterprise") if isinstance(conf, dict) else None
- if not isinstance(enterprise_conf, dict):
- logger.info("[App] channels.feishu_enterprise 未配置或格式错误,FeishuEnterpriseChannel 不启用")
- else:
- for bot_key, bot_conf_raw in enterprise_conf.items():
- if not isinstance(bot_key, str) or not bot_key.strip():
- continue
- bot_conf = bot_conf_raw if isinstance(bot_conf_raw, dict) else None
- if bot_conf is None:
- logger.info("[App] channels.feishu_enterprise.%s 配置格式错误,跳过", bot_key)
- continue
- enabled, reason = _is_channel_enabled(bot_conf, ["app_id", "app_secret"])
- if not enabled:
- logger.info(
- "[App] channels.feishu_enterprise.%s.%s,FeishuEnterpriseChannel 未启用",
- bot_key,
- reason,
- )
- continue
-
- bot_key = bot_key.strip()
- app_id = str(bot_conf.get("app_id") or "").strip()
- channel_id = f"feishu_enterprise:{app_id}"
- feishu_config = FeishuConfig(
- enabled=True,
- app_id=app_id,
- app_secret=str(bot_conf.get("app_secret") or "").strip(),
- encrypt_key=str(bot_conf.get("encrypt_key") or "").strip(),
- verification_token=str(bot_conf.get("verification_token") or "").strip(),
- allow_from=bot_conf.get("allow_from") or [],
- enable_streaming=bool(bot_conf.get("enable_streaming", True)),
- chat_id=str(bot_conf.get("chat_id") or "").strip(),
- channel_id=channel_id,
- bot_key=bot_key,
- last_chat_id=str(bot_conf.get("last_chat_id") or "").strip(),
- last_open_id=str(bot_conf.get("last_open_id") or "").strip(),
- )
- channel = FeishuChannel(feishu_config, _DummyBus())
- channel_manager.register_channel(channel)
- task = asyncio.create_task(channel.start(), name=f"feishu-enterprise-{bot_key}")
- feishu_enterprise_channels[bot_key] = channel
- feishu_enterprise_tasks[bot_key] = task
- logger.info(
- "[App] 已按 config.yaml.channels.feishu_enterprise.%s 注册 FeishuChannel(%s)",
- bot_key,
- channel_id,
- )
-
- if "xiaoyi" in changed_channels:
- xiaoyi_conf = conf.get("xiaoyi") if isinstance(conf, dict) else None
- await _stop_channel(xiaoyi_channel, xiaoyi_task, "xiaoyi")
- xiaoyi_channel, xiaoyi_task = None, None
-
- if isinstance(xiaoyi_conf, dict):
- enabled, reason = _is_channel_enabled(xiaoyi_conf, ["ak", "sk", "agent_id"])
- if not enabled:
- logger.info("[App] channels.xiaoyi.%s,XiaoyiChannel 未启用", reason)
- else:
- if xiaoyi_conf.get("mode") == "xiaoyi_claw":
- xiaoyi_config = XiaoyiChannelConfig(
- enabled=True,
- mode=str(xiaoyi_conf.get("mode") or "xiaoyi_claw").strip(),
- api_id=str(xiaoyi_conf.get("api_id") or "").strip(),
- push_id=str(xiaoyi_conf.get("push_id") or "").strip(),
- push_url=str(xiaoyi_conf.get("push_url") or "").strip(),
- agent_id=str(xiaoyi_conf.get("agent_id") or "").strip(),
- uid=str(xiaoyi_conf.get("uid") or "").strip(),
- api_key=str(xiaoyi_conf.get("api_key") or "").strip(),
- file_upload_url=str(xiaoyi_conf.get("file_upload_url") or "").strip(),
- ws_url1=str(xiaoyi_conf.get("ws_url1")).strip(),
- ws_url2=str(xiaoyi_conf.get("ws_url2")).strip(),
- enable_streaming=bool(xiaoyi_conf.get("enable_streaming", True)),
- )
- else:
- xiaoyi_config = XiaoyiChannelConfig(
- enabled=True,
- mode=str(xiaoyi_conf.get("mode") or "xiaoyi_channel").strip(),
- ak=str(xiaoyi_conf.get("ak") or "").strip(),
- sk=str(xiaoyi_conf.get("sk") or "").strip(),
- api_id=str(xiaoyi_conf.get("api_id") or "").strip(),
- push_id=str(xiaoyi_conf.get("push_id") or "").strip(),
- push_url=str(xiaoyi_conf.get("push_url") or "").strip(),
- agent_id=str(xiaoyi_conf.get("agent_id") or "").strip(),
- ws_url1=str(xiaoyi_conf.get("ws_url1") or "").strip() \
- or "wss://hag.cloud.huawei.com/openclaw/v1/ws/link",
- ws_url2=str(xiaoyi_conf.get("ws_url2") or "").strip() \
- or "wss://116.63.174.231/openclaw/v1/ws/link",
- enable_streaming=bool(xiaoyi_conf.get("enable_streaming", True)),
- )
- xiaoyi_channel = XiaoyiChannel(xiaoyi_config, _DummyBus())
- channel_manager.register_channel(xiaoyi_channel)
- xiaoyi_task = asyncio.create_task(xiaoyi_channel.start(), name="xiaoyi")
- logger.info("[App] 已按 config.yaml.channels.xiaoyi 注册 XiaoyiChannel")
- else:
- logger.info("[App] channels.xiaoyi 未配置或格式错误,XiaoyiChannel 不启用")
-
- if "dingtalk" in changed_channels:
- dingtalk_conf = conf.get("dingtalk") if isinstance(conf, dict) else None
- await _stop_channel(dingtalk_channel, dingtalk_task, "dingtalk", background_wait=True)
- dingtalk_channel, dingtalk_task = None, None
-
- if isinstance(dingtalk_conf, dict):
- enabled, reason = _is_channel_enabled(dingtalk_conf, ["client_id", "client_secret"])
- if not enabled:
- logger.info("[App] channels.dingtalk.%s,DingtalkChannel 未启用", reason)
- else:
- dingtalk_config = DingTalkConfig(
- enabled=True,
- client_id=str(dingtalk_conf.get("client_id") or "").strip(),
- client_secret=str(dingtalk_conf.get("client_secret") or "").strip(),
- allow_from=dingtalk_conf.get("allow_from") or [],
- )
- dingtalk_channel = DingTalkChannel(dingtalk_config, _DummyBus())
- channel_manager.register_channel(dingtalk_channel)
- dingtalk_task = asyncio.create_task(dingtalk_channel.start(), name="dingtalk")
- logger.info("[App] 已按 config.yaml.channels.dingtalk 注册 DingtalkChannel")
- else:
- logger.info("[App] channels.dingtalk 未配置或格式错误,DingtalkChannel 不启用")
-
- if "telegram" in changed_channels:
- telegram_conf = conf.get("telegram") if isinstance(conf, dict) else None
- await _stop_channel(telegram_channel, telegram_task, "telegram")
- telegram_channel, telegram_task = None, None
-
- if isinstance(telegram_conf, dict):
- enabled, reason = _is_channel_enabled(telegram_conf, ["bot_token"])
- if not enabled:
- logger.info("[App] channels.telegram.%s,TelegramChannel 未启用", reason)
- else:
- telegram_config = TelegramChannelConfig(
- enabled=True,
- bot_token=str(telegram_conf.get("bot_token") or "").strip(),
- allow_from=telegram_conf.get("allow_from") or [],
- parse_mode=str(telegram_conf.get("parse_mode") or "Markdown").strip(),
- group_chat_mode=str(telegram_conf.get("group_chat_mode") or "mention").strip(),
- )
- telegram_channel = TelegramChannel(telegram_config, _DummyBus())
- channel_manager.register_channel(telegram_channel)
- telegram_task = asyncio.create_task(telegram_channel.start(), name="telegram")
- logger.info("[App] 已按 config.yaml.channels.telegram 注册 TelegramChannel")
- else:
- logger.info("[App] channels.telegram 未配置或格式错误,TelegramChannel 不启用")
-
- if "discord" in changed_channels:
- discord_conf = conf.get("discord") if isinstance(conf, dict) else None
- await _stop_channel(discord_channel, discord_task, "discord")
- discord_channel, discord_task = None, None
-
- if isinstance(discord_conf, dict):
- enabled, reason = _is_channel_enabled(discord_conf, ["bot_token"])
- if not enabled:
- logger.info("[App] channels.discord.%s,DiscordChannel 未启用", reason)
- else:
- discord_config = DiscordChannelConfig(
- enabled=True,
- bot_token=str(discord_conf.get("bot_token") or "").strip(),
- application_id=str(discord_conf.get("application_id") or "").strip(),
- guild_id=str(discord_conf.get("guild_id") or "").strip(),
- channel_id=str(discord_conf.get("channel_id") or "").strip(),
- allow_from=discord_conf.get("allow_from") or [],
- block_dm=(str(discord_conf.get("block_dm")).lower() in ["true", "1"]) or False,
- )
- discord_channel = DiscordChannel(discord_config, _DummyBus())
- channel_manager.register_channel(discord_channel)
- discord_task = asyncio.create_task(discord_channel.start(), name="discord")
- logger.info("[App] 已按 config.yaml.channels.discord 注册 DiscordChannel")
- else:
- logger.info("[App] channels.discord 未配置或格式错误,DiscordChannel 不启用")
-
- # ----- WhatsAppChannel -----
- if "whatsapp" in changed_channels:
- whatsapp_conf = conf.get("whatsapp") if isinstance(conf, dict) else None
- await _stop_channel(whatsapp_channel, whatsapp_task, "whatsapp")
- whatsapp_channel, whatsapp_task = None, None
-
- if isinstance(whatsapp_conf, dict):
- bridge_ws_url = str(whatsapp_conf.get("bridge_ws_url") or "ws://127.0.0.1:19600/ws").strip()
- default_jid = str(whatsapp_conf.get("default_jid") or "").strip()
- allow_from = whatsapp_conf.get("allow_from") or []
- enable_streaming = bool(whatsapp_conf.get("enable_streaming", True))
- auto_start_bridge = bool(whatsapp_conf.get("auto_start_bridge", False))
- bridge_command = str(whatsapp_conf.get("bridge_command") or "node scripts/whatsapp-bridge.js").strip()
- bridge_workdir = str(whatsapp_conf.get("bridge_workdir") or "").strip()
- bridge_env_raw = whatsapp_conf.get("bridge_env") or {}
- bridge_env = bridge_env_raw if isinstance(bridge_env_raw, dict) else {}
-
- enabled_raw = whatsapp_conf.get("enabled", None)
- if enabled_raw is None:
- enabled = bool(bridge_ws_url)
- else:
- enabled = bool(enabled_raw)
-
- if not enabled:
- logger.info("[App] channels.whatsapp.enabled = false,WhatsAppChannel 未启用")
- elif not bridge_ws_url:
- logger.info("[App] channels.whatsapp 缺少 bridge_ws_url,WhatsAppChannel 未启用")
- else:
- whatsapp_config = WhatsAppChannelConfig(
- enabled=True,
- enable_streaming=enable_streaming,
- bridge_ws_url=bridge_ws_url,
- allow_from=allow_from,
- default_jid=default_jid,
- auto_start_bridge=auto_start_bridge,
- bridge_command=bridge_command,
- bridge_workdir=bridge_workdir,
- bridge_env={str(k): str(v) for k, v in bridge_env.items()},
- )
- whatsapp_channel = WhatsAppChannel(whatsapp_config, _DummyBus())
- channel_manager.register_channel(whatsapp_channel)
- whatsapp_task = asyncio.create_task(whatsapp_channel.start(), name="whatsapp")
- logger.info("[App] 已按 config.yaml.channels.whatsapp 注册 WhatsAppChannel")
- else:
- logger.info("[App] channels.whatsapp 未配置或格式错误,WhatsAppChannel 不启用")
-
- # ----- WecomChannel -----
- if "wecom" in changed_channels:
- wecom_conf = conf.get("wecom") if isinstance(conf, dict) else None
- await _stop_channel(wecom_channel, wecom_task, "wecom")
- wecom_channel, wecom_task = None, None
-
- if isinstance(wecom_conf, dict):
- enabled, reason = _is_channel_enabled(wecom_conf, ["bot_id", "secret"])
- if not enabled:
- logger.info("[App] channels.wecom.%s,WecomChannel 未启用", reason)
- else:
- wecom_config = WecomConfig(
- enabled=True,
- bot_id=str(wecom_conf.get("bot_id") or "").strip(),
- secret=str(wecom_conf.get("secret") or "").strip(),
- ws_url=str(wecom_conf.get("ws_url") or "wss://openws.work.weixin.qq.com").strip(),
- allow_from=wecom_conf.get("allow_from") or [],
- enable_streaming=bool(wecom_conf.get("enable_streaming", True)),
- send_thinking_message=bool(wecom_conf.get("send_thinking_message", True)),
- )
- wecom_channel = WecomChannel(wecom_config, _DummyBus())
- channel_manager.register_channel(wecom_channel)
- wecom_task = asyncio.create_task(wecom_channel.start(), name="wecom")
- logger.info("[App] 已按 config.yaml.channels.wecom 注册 WecomChannel")
- else:
- logger.info("[App] channels.wecom 未配置或格式错误,WecomChannel 不启用")
-
- # ----- WechatChannel -----
- if "wechat" in changed_channels:
- wechat_conf = conf.get("wechat") if isinstance(conf, dict) else None
- await _stop_channel(wechat_channel, wechat_task, "wechat")
- wechat_channel, wechat_task = None, None
-
- if isinstance(wechat_conf, dict):
- enabled, reason = _is_channel_enabled(wechat_conf, [])
- if not enabled:
- logger.info("[App] channels.wechat.%s,WechatChannel 未启用", reason)
- else:
- wechat_config = WechatConfig(
- enabled=True,
- base_url=str(wechat_conf.get("base_url") or "https://ilinkai.weixin.qq.com").strip(),
- bot_token=str(wechat_conf.get("bot_token") or "").strip(),
- ilink_bot_id=str(wechat_conf.get("ilink_bot_id") or "").strip(),
- ilink_user_id=str(wechat_conf.get("ilink_user_id") or "").strip(),
- allow_from=wechat_conf.get("allow_from") or [],
- auto_login=bool(wechat_conf.get("auto_login", True)),
- qrcode_poll_interval_sec=float(wechat_conf.get("qrcode_poll_interval_sec", 2.0)),
- long_poll_timeout_sec=int(wechat_conf.get("long_poll_timeout_sec", 45)),
- backoff_base_sec=float(wechat_conf.get("backoff_base_sec", 1.0)),
- backoff_max_sec=float(wechat_conf.get("backoff_max_sec", 30.0)),
- credential_file=str(
- wechat_conf.get("credential_file") or "~/.wx-ai-bridge/credentials.json"
- ).strip(),
- enable_streaming=bool(wechat_conf.get("enable_streaming", True)),
- )
- wechat_channel = WechatChannel(wechat_config, _DummyBus())
- channel_manager.register_channel(wechat_channel)
- wechat_task = asyncio.create_task(wechat_channel.start(), name="wechat")
- logger.info("[App] 已按 config.yaml.channels.wechat 注册 WechatChannel")
- else:
- logger.info("[App] channels.wechat 未配置或格式错误,WechatChannel 不启用")
-
- # 将「配置更新时如何重新实例化 Channel」逻辑注册到 ChannelManager
- channel_manager.set_config_callback(_apply_channel_config)
- # 使用初始配置实例化一次(启动时,针对动态管理的各 Channel)
- await channel_manager.set_config(initial_channels_conf)
-
- await channel_manager.start_dispatch()
- await cron_scheduler.start()
- web_task = asyncio.create_task(web_channel.start(), name="web-channel")
- logger.info(
- "[App] 已启动: Web ws://%s:%s%s 修改配置后将自动重启服务。Ctrl+C 退出。",
- web_host, web_port, web_path,
- )
-
- # 主循环仅以 WebChannel 的生命周期为准:
- # Feishu/Xiaoyi/Dingtalk/Telegram/WhatsApp 等 Channel 的 start/stop 由 _apply_channel_config 动态管理,
- # 不再将其任务纳入这里的 gather,以避免在热更新(如关闭 Feishu)时取消任务导致整个 E2E 提前退出。
+ time.sleep(0.4)
+ gateway = subprocess.Popen([python, "-m", "jiuwenclaw.app_gateway"])
+ except Exception:
+ if agent.poll() is None:
+ agent.terminate()
+ raise
+
+ procs: list[subprocess.Popen] = [agent] + ([gateway] if gateway else [])
+
+ def _terminate_all() -> None:
+ for p in procs:
+ if p.poll() is None:
+ p.terminate()
+ deadline = time.time() + 12
+ while time.time() < deadline:
+ if all(p.poll() is not None for p in procs):
+ break
+ time.sleep(0.1)
+ for p in procs:
+ if p.poll() is None:
+ p.kill()
+
+ exit_code = 0
try:
- # 仅等待 WebChannel 主任务。Feishu/Xiaoyi 任务会在配置更新时动态重建,
- # 若把旧任务放进 gather,set_conf 取消旧任务会导致主流程提前退出。
- await web_task
+ while True:
+ if agent.poll() is not None:
+ exit_code = agent.returncode or 0
+ break
+ if gateway is not None and gateway.poll() is not None:
+ exit_code = gateway.returncode or 0
+ break
+ time.sleep(0.25)
except KeyboardInterrupt:
- logger.info("收到 Ctrl+C,正在退出…")
- except asyncio.CancelledError:
- pass
+ exit_code = 130
finally:
- web_task.cancel()
- try:
- await web_task
- except asyncio.CancelledError:
- pass
- await web_channel.stop()
- if feishu_channel is not None and feishu_task is not None:
- feishu_task.cancel()
- try:
- await feishu_task
- except asyncio.CancelledError:
- pass
- await feishu_channel.stop()
- for bot_key, task in list(feishu_enterprise_tasks.items()):
- task.cancel()
- try:
- await task
- except asyncio.CancelledError:
- pass
- channel = feishu_enterprise_channels.get(bot_key)
- if channel is not None:
- await channel.stop()
- if xiaoyi_channel is not None and xiaoyi_task is not None:
- xiaoyi_task.cancel()
- try:
- await xiaoyi_task
- except asyncio.CancelledError:
- pass
- await xiaoyi_channel.stop()
- if dingtalk_channel is not None and dingtalk_task is not None:
- dingtalk_task.cancel()
- try:
- await dingtalk_task
- except (TypeError, asyncio.CancelledError):
- pass
- await dingtalk_channel.stop()
- if telegram_channel is not None and telegram_task is not None:
- telegram_task.cancel()
- try:
- await telegram_task
- except asyncio.CancelledError:
- pass
- await telegram_channel.stop()
- if discord_channel is not None and discord_task is not None:
- discord_task.cancel()
- try:
- await discord_task
- except asyncio.CancelledError:
- pass
- await discord_channel.stop()
- if whatsapp_channel is not None and whatsapp_task is not None:
- whatsapp_task.cancel()
- try:
- await whatsapp_task
- except asyncio.CancelledError:
- pass
- await whatsapp_channel.stop()
- if wecom_channel is not None and wecom_task is not None:
- wecom_task.cancel()
- try:
- await wecom_task
- except asyncio.CancelledError:
- pass
- await wecom_channel.stop()
- if wechat_channel is not None and wechat_task is not None:
- wechat_task.cancel()
- try:
- await wechat_task
- except asyncio.CancelledError:
- pass
- await wechat_channel.stop()
- await cron_scheduler.stop()
- await channel_manager.stop_dispatch()
- await heartbeat_service.stop()
- await message_handler.stop_forwarding()
- await client.disconnect()
- await server.stop()
- logger.info("[App] E2E 已停止")
+ _terminate_all()
-
-def main() -> None:
- from jiuwenclaw.telemetry import init_telemetry
-
- init_telemetry()
- asyncio.run(_run())
+ raise SystemExit(exit_code)
if __name__ == "__main__":
diff --git a/jiuwenclaw/app_agentserver.py b/jiuwenclaw/app_agentserver.py
index aa9cde6369..b0fe928a03 100644
--- a/jiuwenclaw/app_agentserver.py
+++ b/jiuwenclaw/app_agentserver.py
@@ -13,18 +13,25 @@ from __future__ import annotations
import argparse
import asyncio
+import logging
import os
from dotenv import load_dotenv
+from openjiuwen.core.common.logging import LogManager
+from jiuwenclaw.jiuwen_core_patch import apply_openai_model_client_patch
from jiuwenclaw.utils import USER_WORKSPACE_DIR, get_env_file, prepare_workspace, logger
+apply_openai_model_client_patch()
# Ensure workspace initialized
_config_file = USER_WORKSPACE_DIR / "config" / "config.yaml"
if not _config_file.exists():
prepare_workspace(overwrite=False)
+for _lg in LogManager.get_all_loggers().values():
+ _lg.set_level(logging.CRITICAL)
+
# Load env from user workspace config/.env
load_dotenv(dotenv_path=get_env_file())
@@ -141,7 +148,15 @@ def main() -> None:
args = parser.parse_args()
host = args.host or os.getenv("AGENT_SERVER_HOST", "127.0.0.1")
- port = args.port or int(os.getenv("AGENT_SERVER_PORT", "18092"))
+ port = args.port
+ if port is None:
+ for key in ("AGENT_SERVER_PORT", "AGENT_PORT"):
+ raw = os.getenv(key)
+ if raw:
+ port = int(raw)
+ break
+ else:
+ port = 18092
asyncio.run(_run(host=host, port=port))
diff --git a/jiuwenclaw/app_gateway.py b/jiuwenclaw/app_gateway.py
index 6cdb695b61..dfe7abb7eb 100644
--- a/jiuwenclaw/app_gateway.py
+++ b/jiuwenclaw/app_gateway.py
@@ -16,29 +16,16 @@ import argparse
import asyncio
import logging
import os
-import secrets
+import sys
import time
from dotenv import load_dotenv
from openjiuwen.core.common.logging import LogManager
-from jiuwenclaw.utils import USER_WORKSPACE_DIR, get_env_file, prepare_workspace, logger
-
-from jiuwenclaw.app import (
- _CONFIG_SET_ENV_MAP,
- _DummyBus,
- _FORWARD_NO_LOCAL_HANDLER_METHODS,
- _FORWARD_REQ_METHODS,
- _register_web_handlers,
-)
-from jiuwenclaw.channel import (
- DingTalkChannel,
- DingTalkConfig,
- WhatsAppChannel,
- WhatsAppChannelConfig,
- WechatChannel,
- WechatConfig,
-)
+from jiuwenclaw.jiuwen_core_patch import apply_openai_model_client_patch
+from jiuwenclaw.utils import USER_WORKSPACE_DIR, get_env_file, prepare_workspace
+
+apply_openai_model_client_patch()
# Ensure workspace initialized
_config_file = USER_WORKSPACE_DIR / "config" / "config.yaml"
@@ -49,15 +36,9 @@ if not _config_file.exists():
for _lg in LogManager.get_all_loggers().values():
_lg.set_level(logging.CRITICAL)
-# Load env from user workspace config/.env
load_dotenv(dotenv_path=get_env_file())
-
-# ---- Reuse app.py helpers/constants for WebChannel methods ----
-def _make_session_id() -> str:
- ts = format(int(time.time() * 1000), "x")
- suffix = secrets.token_hex(3)
- return f"sess_{ts}_{suffix}"
+logger = logging.getLogger(__name__)
async def _connect_with_retry(
@@ -70,19 +51,19 @@ async def _connect_with_retry(
for attempt in range(1, max_retries + 1):
try:
await client.connect(uri)
- logger.info("[Gateway] connected to AgentServer: %s", uri)
+ logger.info("[App] connected to AgentServer: %s", uri)
return
except Exception as exc: # noqa: BLE001
if attempt >= max_retries:
logger.error(
- "[Gateway] connect AgentServer failed after %d tries: %s last=%s",
+ "[App] connect AgentServer failed after %d tries: %s last=%s",
attempt,
uri,
exc,
)
raise
logger.warning(
- "[Gateway] connect AgentServer failed (%d/%d): %s retry in %s s…",
+ "[App] connect AgentServer failed (%d/%d): %s retry in %s s…",
attempt,
max_retries,
exc,
@@ -92,12 +73,21 @@ async def _connect_with_retry(
async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: str) -> None:
- from openjiuwen.core.runner import Runner
- from jiuwenclaw.channel.discord_channel import DiscordChannel, DiscordChannelConfig
+ from jiuwenclaw.channel import (
+ DingTalkChannel,
+ DingTalkConfig,
+ WhatsAppChannel,
+ WhatsAppChannelConfig,
+ WechatChannel,
+ WechatConfig,
+ )
from jiuwenclaw.channel.feishu import FeishuChannel, FeishuConfig
- from jiuwenclaw.channel.telegram_channel import TelegramChannel, TelegramChannelConfig
from jiuwenclaw.channel.web_channel import WebChannel, WebChannelConfig
from jiuwenclaw.channel.xiaoyi_channel import XiaoyiChannel, XiaoyiChannelConfig
+ from jiuwenclaw.channel.telegram_channel import TelegramChannel, TelegramChannelConfig
+ from jiuwenclaw.channel.discord_channel import DiscordChannel, DiscordChannelConfig
+ from jiuwenclaw.channel.wecom_channel import WecomChannel, WecomConfig
+ from jiuwenclaw.config import get_config
from jiuwenclaw.gateway import (
GatewayHeartbeatService,
HeartbeatConfig,
@@ -106,32 +96,47 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
from jiuwenclaw.gateway.channel_manager import ChannelManager
from jiuwenclaw.gateway.cron import CronController, CronJobStore, CronSchedulerService
from jiuwenclaw.gateway.message_handler import MessageHandler
+ from jiuwenclaw.app_web_handlers import (
+ WebHandlersBindParams,
+ _DummyBus,
+ _FORWARD_NO_LOCAL_HANDLER_METHODS,
+ _FORWARD_REQ_METHODS,
+ _register_web_handlers,
+ )
from jiuwenclaw.extensions import ExtensionManager, ExtensionRegistry
from jiuwenclaw.schema.message import Message, ReqMethod
- from jiuwenclaw.agentserver.memory.config import _load_config as _load_agent_config
- from jiuwenclaw.agentserver.tools.browser_tools import restart_local_browser_runtime_server
+ from jiuwenclaw.updater import WindowsUpdaterService
+ from openjiuwen.core.runner import Runner
- logger.info("[Gateway] starting, connecting AgentServer: %s", agent_server_url)
+ def _do_restart() -> None:
+ logger.info("[App] 配置已写回 .env,正在重启 Gateway 服务…")
+ os.execv(sys.executable, [sys.executable, *sys.argv])
+
+ def _schedule_restart() -> None:
+ try:
+ loop = asyncio.get_running_loop()
+ loop.call_later(2.0, _do_restart)
+ except RuntimeError:
+ _do_restart()
+
+ logger.info("[App] Gateway starting, connecting AgentServer: %s", agent_server_url)
- # ---------- 扩展系统初始化 ----------
callback_framework = Runner.callback_framework
extension_registry = ExtensionRegistry.create_instance(
callback_framework=callback_framework,
config={},
logger=logger,
)
- extension_manager = ExtensionManager(
- registry=extension_registry,
- )
+ extension_manager = ExtensionManager(registry=extension_registry)
await extension_manager.load_all_extensions()
- logger.info("[Gateway] 扩展加载完成,共 %d 个", len(extension_manager.list_extensions()))
+ logger.info("[App] 扩展加载完成,共 %d 个", len(extension_manager.list_extensions()))
max_retries = int(os.getenv("AGENT_CONNECT_RETRY", "20"))
retry_interval = float(os.getenv("AGENT_CONNECT_RETRY_INTERVAL", "3"))
agent_server_ext = extension_registry.get_agent_server_client_extension()
if agent_server_ext is not None:
- logger.info("[Gateway] 使用扩展提供的 AgentServerClient: %s", agent_server_ext.metadata.name)
+ logger.info("[App] 使用扩展提供的 AgentServerClient: %s", agent_server_ext.metadata.name)
client = agent_server_ext.get_client()
else:
client = WebSocketAgentServerClient(ping_interval=20.0, ping_timeout=20.0)
@@ -156,11 +161,13 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
heartbeat_cfg: dict | None = None
channels_cfg: dict | None = None
try:
- full_cfg = _load_agent_config()
+ full_cfg = get_config()
heartbeat_cfg = full_cfg.get("heartbeat") if isinstance(full_cfg, dict) else None
channels_cfg = full_cfg.get("channels") if isinstance(full_cfg, dict) else None
- except Exception as exc: # noqa: BLE001
- logger.warning("[Gateway] failed to read config.yaml heartbeat/channels, fallback to defaults: %s", exc)
+ except Exception as e: # noqa: BLE001
+ logger.warning("[App] 读取 config.yaml heartbeat 配置失败,将使用默认值: %s", e)
+ heartbeat_cfg = None
+ channels_cfg = None
if isinstance(heartbeat_cfg, dict):
cfg_every = heartbeat_cfg.get("every")
@@ -195,48 +202,75 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
initial_channels_conf: dict = channels_cfg if isinstance(channels_cfg, dict) else {}
channel_manager = ChannelManager(message_handler, config=initial_channels_conf)
-
- def _on_config_saved(updated_env_keys: set[str] | None = None) -> bool:
+ updater_service = WindowsUpdaterService()
+
+ async def _on_config_saved(updated_env_keys: set[str] | None = None) -> bool:
+ browser_runtime_keys = {
+ "MODEL_PROVIDER",
+ "MODEL_NAME",
+ "API_BASE",
+ "API_KEY",
+ "VIDEO_PROVIDER",
+ "VIDEO_MODEL_NAME",
+ "VIDEO_API_BASE",
+ "VIDEO_API_KEY",
+ "AUDIO_PROVIDER",
+ "AUDIO_MODEL_NAME",
+ "AUDIO_API_BASE",
+ "AUDIO_API_KEY",
+ "VISION_PROVIDER",
+ "VISION_MODEL_NAME",
+ "VISION_API_BASE",
+ "VISION_API_KEY",
+ }
try:
- browser_runtime_keys = {"MODEL_PROVIDER", "MODEL_NAME", "API_BASE", "API_KEY"}
+ from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields
+ from jiuwenclaw.schema.message import ReqMethod
+ import uuid
+
+ reload_env = e2a_from_agent_fields(
+ request_id=f"agent-reload-{uuid.uuid4().hex[:8]}",
+ channel_id="",
+ req_method=ReqMethod.AGENT_RELOAD_CONFIG,
+ )
+ await client.send_request(reload_env)
+
if updated_env_keys and (browser_runtime_keys & set(updated_env_keys)):
- restart_local_browser_runtime_server()
+ restart_env = e2a_from_agent_fields(
+ request_id=f"browser-restart-{uuid.uuid4().hex[:8]}",
+ channel_id="",
+ req_method=ReqMethod.BROWSER_RUNTIME_RESTART,
+ )
+ await client.send_request(restart_env)
return True
- except Exception as exc: # noqa: BLE001
- logger.warning("[Gateway] config hot reload failed; scheduling restart: %s", exc)
+ except Exception as e: # noqa: BLE001
+ logger.warning("[App] 配置热更新失败,将延迟重启: %s", e)
_schedule_restart()
return False
- def _do_restart() -> None:
- import sys
-
- logger.info("[Gateway] restarting process…")
- os.execv(sys.executable, [sys.executable, *sys.argv])
-
- def _schedule_restart() -> None:
- try:
- loop = asyncio.get_running_loop()
- loop.call_later(2.0, _do_restart)
- except RuntimeError:
- _do_restart()
-
web_config = WebChannelConfig(enabled=True, host=web_host, port=web_port, path=web_path)
web_channel = WebChannel(web_config, _DummyBus())
_register_web_handlers(
- web_channel,
- agent_client=client,
- message_handler=message_handler,
- channel_manager=channel_manager,
- on_config_saved=_on_config_saved,
- heartbeat_service=heartbeat_service,
- cron_controller=cron_controller,
+ WebHandlersBindParams(
+ channel=web_channel,
+ agent_client=client,
+ message_handler=message_handler,
+ channel_manager=channel_manager,
+ on_config_saved=_on_config_saved,
+ heartbeat_service=heartbeat_service,
+ cron_controller=cron_controller,
+ updater_service=updater_service,
+ )
)
def _norm_and_forward(msg: Message) -> bool:
method_val = getattr(getattr(msg, "req_method", None), "value", None) or ""
if method_val not in _FORWARD_REQ_METHODS:
return False
- is_stream = bool(msg.is_stream or method_val == ReqMethod.CHAT_SEND.value)
+ is_stream = bool(
+ msg.is_stream
+ or method_val in (ReqMethod.CHAT_SEND.value, ReqMethod.HISTORY_GET.value)
+ )
params = dict(msg.params or {})
if "query" not in params and "content" in params:
params["query"] = params["content"]
@@ -255,14 +289,13 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
stream_id=msg.stream_id,
metadata=msg.metadata,
)
- message_handler.handle_message(normalized)
+ channel_manager.deliver_to_message_handler(normalized)
+ logger.info("[App] Web 入站 -> MessageHandler: id=%s channel_id=%s", msg.id, msg.channel_id)
if method_val in _FORWARD_NO_LOCAL_HANDLER_METHODS:
return True
return False
- # register_channel 会设置默认 on_message;WebChannel.on_message 会整体替换回调,故先注册再挂上自定义转发
- channel_manager.register_channel(web_channel)
- web_channel.on_message(_norm_and_forward)
+ channel_manager.register_channel_with_inbound(web_channel, _norm_and_forward)
feishu_channel = None
feishu_task = None
@@ -278,6 +311,8 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
discord_task = None
whatsapp_channel = None
whatsapp_task = None
+ wecom_channel = None
+ wecom_task = None
wechat_channel = None
wechat_task = None
@@ -296,64 +331,88 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
if task is not None:
task.cancel()
if background_wait:
- async def _wait_cancel():
+
+ async def wait_cancel():
try:
await task
except (TypeError, asyncio.CancelledError):
- logger.info("[Gateway] cancelled %s channel task", channel_name)
- except Exception as exc: # noqa: BLE001
- logger.warning("[Gateway] ignore exception while cancelling %s: %s", channel_name, exc)
+ logger.info("[App] 取消旧 %sChannel 任务成功", channel_name.capitalize())
+ except Exception as e: # noqa: BLE001
+ logger.warning(
+ "[App] 等待旧 %sChannel 任务结束时忽略异常: %s",
+ channel_name.capitalize(),
+ e,
+ )
- asyncio.create_task(_wait_cancel(), name=f"wait_{channel_name}_cancel")
+ asyncio.create_task(wait_cancel(), name=f"wait_{channel_name}_cancel")
else:
try:
await asyncio.wait_for(task, timeout=5.0)
- except (asyncio.TimeoutError, asyncio.CancelledError):
+ except asyncio.TimeoutError:
+ logger.warning("[App] 等待 %sChannel 任务取消超时", channel_name.capitalize())
+ except asyncio.CancelledError:
pass
- except Exception as exc: # noqa: BLE001
- logger.warning("[Gateway] ignore exception while waiting %s stop: %s", channel_name, exc)
+ except Exception as e: # noqa: BLE001
+ logger.warning(
+ "[App] 等待旧 %sChannel 任务结束时忽略异常: %s",
+ channel_name.capitalize(),
+ e,
+ )
if channel is not None:
try:
await asyncio.wait_for(channel.stop(), timeout=10.0)
except asyncio.TimeoutError:
- pass
- except Exception: # noqa: BLE001
- pass
+ logger.warning("[App] 停止 %sChannel 超时", channel_name.capitalize())
+ except Exception as e: # noqa: BLE001
+ logger.warning("[App] 停止旧 %sChannel 失败: %s", channel_name.capitalize(), e)
channel_manager.unregister_channel(channel.channel_id)
def _is_channel_enabled(conf: dict | None, required_fields: list[str]) -> tuple[bool, str]:
if conf is None:
- return False, "not configured"
+ return False, "未配置或格式错误"
enabled_raw = conf.get("enabled", None)
if enabled_raw is None:
all_fields_present = all(conf.get(f) for f in required_fields)
- return all_fields_present, "missing required fields" if not all_fields_present else ""
- return bool(enabled_raw), "enabled=false" if not enabled_raw else ""
+ return all_fields_present, f"缺少 {','.join(required_fields)}" if not all_fields_present else ""
+ return bool(enabled_raw), "enabled = false" if not enabled_raw else ""
async def _apply_channel_config(conf: dict) -> None:
nonlocal feishu_channel, feishu_task, xiaoyi_channel, xiaoyi_task
nonlocal dingtalk_channel, dingtalk_task, telegram_channel, telegram_task
nonlocal discord_channel, discord_task
nonlocal whatsapp_channel, whatsapp_task
+ nonlocal wecom_channel, wecom_task
nonlocal wechat_channel, wechat_task
nonlocal _last_channels_conf
nonlocal feishu_enterprise_channels, feishu_enterprise_tasks
- changed = [
- c
- for c in ["feishu", "feishu_enterprise", "xiaoyi", "dingtalk", "telegram", "discord", "whatsapp", "wechat"]
- if _should_restart_channel(c, _last_channels_conf, conf)
- ]
+ changed_channels: list[str] = []
+ for channel_name in [
+ "feishu",
+ "feishu_enterprise",
+ "xiaoyi",
+ "dingtalk",
+ "telegram",
+ "whatsapp",
+ "discord",
+ "wecom",
+ "wechat",
+ ]:
+ if _should_restart_channel(channel_name, _last_channels_conf, conf):
+ changed_channels.append(channel_name)
_last_channels_conf = dict(conf or {})
- if "feishu" in changed:
+ if "feishu" in changed_channels:
feishu_conf = conf.get("feishu") if isinstance(conf, dict) else None
await _stop_channel(feishu_channel, feishu_task, "feishu")
feishu_channel, feishu_task = None, None
+
if isinstance(feishu_conf, dict):
- enabled, _ = _is_channel_enabled(feishu_conf, ["app_id", "app_secret"])
- if enabled:
+ enabled, reason = _is_channel_enabled(feishu_conf, ["app_id", "app_secret"])
+ if not enabled:
+ logger.info("[App] channels.feishu.%s,FeishuChannel 未启用", reason)
+ else:
feishu_config = FeishuConfig(
enabled=True,
app_id=str(feishu_conf.get("app_id") or "").strip(),
@@ -369,8 +428,11 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
feishu_channel = FeishuChannel(feishu_config, _DummyBus())
channel_manager.register_channel(feishu_channel)
feishu_task = asyncio.create_task(feishu_channel.start(), name="feishu")
+ logger.info("[App] 已按 config.yaml.channels.feishu 注册 FeishuChannel")
+ else:
+ logger.info("[App] channels.feishu 未配置或格式错误,FeishuChannel 不启用")
- if "feishu_enterprise" in changed:
+ if "feishu_enterprise" in changed_channels:
for bot_key, task in list(feishu_enterprise_tasks.items()):
await _stop_channel(
feishu_enterprise_channels.get(bot_key),
@@ -382,19 +444,19 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
enterprise_conf = conf.get("feishu_enterprise") if isinstance(conf, dict) else None
if not isinstance(enterprise_conf, dict):
- logger.info("[Gateway] channels.feishu_enterprise 未配置或格式错误,FeishuEnterpriseChannel 不启用")
+ logger.info("[App] channels.feishu_enterprise 未配置或格式错误,FeishuEnterpriseChannel 不启用")
else:
for bot_key, bot_conf_raw in enterprise_conf.items():
if not isinstance(bot_key, str) or not bot_key.strip():
continue
bot_conf = bot_conf_raw if isinstance(bot_conf_raw, dict) else None
if bot_conf is None:
- logger.info("[Gateway] channels.feishu_enterprise.%s 配置格式错误,跳过", bot_key)
+ logger.info("[App] channels.feishu_enterprise.%s 配置格式错误,跳过", bot_key)
continue
enabled, reason = _is_channel_enabled(bot_conf, ["app_id", "app_secret"])
if not enabled:
logger.info(
- "[Gateway] channels.feishu_enterprise.%s.%s,FeishuEnterpriseChannel 未启用",
+ "[App] channels.feishu_enterprise.%s.%s,FeishuEnterpriseChannel 未启用",
bot_key,
reason,
)
@@ -423,45 +485,69 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
feishu_enterprise_channels[bot_key] = channel
feishu_enterprise_tasks[bot_key] = task
logger.info(
- "[Gateway] 已按 config.yaml.channels.feishu_enterprise.%s 注册 FeishuChannel(%s)",
+ "[App] 已按 config.yaml.channels.feishu_enterprise.%s 注册 FeishuChannel(%s)",
bot_key,
channel_id,
)
- if "xiaoyi" in changed:
+ if "xiaoyi" in changed_channels:
xiaoyi_conf = conf.get("xiaoyi") if isinstance(conf, dict) else None
await _stop_channel(xiaoyi_channel, xiaoyi_task, "xiaoyi")
xiaoyi_channel, xiaoyi_task = None, None
+
if isinstance(xiaoyi_conf, dict):
- enabled, _ = _is_channel_enabled(xiaoyi_conf, ["ak", "sk", "agent_id"])
- if enabled:
- xiaoyi_config = XiaoyiChannelConfig(
- enabled=True,
- mode=str(xiaoyi_conf.get("mode") or "xiaoyi_claw").strip(),
- ak=str(xiaoyi_conf.get("ak") or "").strip(),
- sk=str(xiaoyi_conf.get("sk") or "").strip(),
- api_id=str(xiaoyi_conf.get("api_id") or "").strip(),
- push_id=str(xiaoyi_conf.get("push_id") or "").strip(),
- push_url=str(xiaoyi_conf.get("push_url") or "").strip(),
- agent_id=str(xiaoyi_conf.get("agent_id") or "").strip(),
- uid=str(xiaoyi_conf.get("uid") or "").strip(),
- api_key=str(xiaoyi_conf.get("api_key") or "").strip(),
- file_upload_url=str(xiaoyi_conf.get("file_upload_url") or "").strip(),
- ws_url1=str(xiaoyi_conf.get("ws_url1")).strip(),
- ws_url2=str(xiaoyi_conf.get("ws_url2")).strip(),
- enable_streaming=bool(xiaoyi_conf.get("enable_streaming", True)),
- )
+ enabled, reason = _is_channel_enabled(xiaoyi_conf, ["ak", "sk", "agent_id"])
+ if not enabled:
+ logger.info("[App] channels.xiaoyi.%s,XiaoyiChannel 未启用", reason)
+ else:
+ if xiaoyi_conf.get("mode") == "xiaoyi_claw":
+ xiaoyi_config = XiaoyiChannelConfig(
+ enabled=True,
+ mode=str(xiaoyi_conf.get("mode") or "xiaoyi_claw").strip(),
+ api_id=str(xiaoyi_conf.get("api_id") or "").strip(),
+ push_id=str(xiaoyi_conf.get("push_id") or "").strip(),
+ push_url=str(xiaoyi_conf.get("push_url") or "").strip(),
+ agent_id=str(xiaoyi_conf.get("agent_id") or "").strip(),
+ uid=str(xiaoyi_conf.get("uid") or "").strip(),
+ api_key=str(xiaoyi_conf.get("api_key") or "").strip(),
+ file_upload_url=str(xiaoyi_conf.get("file_upload_url") or "").strip(),
+ ws_url1=str(xiaoyi_conf.get("ws_url1")).strip(),
+ ws_url2=str(xiaoyi_conf.get("ws_url2")).strip(),
+ enable_streaming=bool(xiaoyi_conf.get("enable_streaming", True)),
+ )
+ else:
+ xiaoyi_config = XiaoyiChannelConfig(
+ enabled=True,
+ mode=str(xiaoyi_conf.get("mode") or "xiaoyi_channel").strip(),
+ ak=str(xiaoyi_conf.get("ak") or "").strip(),
+ sk=str(xiaoyi_conf.get("sk") or "").strip(),
+ api_id=str(xiaoyi_conf.get("api_id") or "").strip(),
+ push_id=str(xiaoyi_conf.get("push_id") or "").strip(),
+ push_url=str(xiaoyi_conf.get("push_url") or "").strip(),
+ agent_id=str(xiaoyi_conf.get("agent_id") or "").strip(),
+ ws_url1=str(xiaoyi_conf.get("ws_url1") or "").strip()
+ or "wss://hag.cloud.huawei.com/openclaw/v1/ws/link",
+ ws_url2=str(xiaoyi_conf.get("ws_url2") or "").strip()
+ or "wss://116.63.174.231/openclaw/v1/ws/link",
+ enable_streaming=bool(xiaoyi_conf.get("enable_streaming", True)),
+ )
xiaoyi_channel = XiaoyiChannel(xiaoyi_config, _DummyBus())
channel_manager.register_channel(xiaoyi_channel)
xiaoyi_task = asyncio.create_task(xiaoyi_channel.start(), name="xiaoyi")
+ logger.info("[App] 已按 config.yaml.channels.xiaoyi 注册 XiaoyiChannel")
+ else:
+ logger.info("[App] channels.xiaoyi 未配置或格式错误,XiaoyiChannel 不启用")
- if "dingtalk" in changed:
+ if "dingtalk" in changed_channels:
dingtalk_conf = conf.get("dingtalk") if isinstance(conf, dict) else None
await _stop_channel(dingtalk_channel, dingtalk_task, "dingtalk", background_wait=True)
dingtalk_channel, dingtalk_task = None, None
+
if isinstance(dingtalk_conf, dict):
- enabled, _ = _is_channel_enabled(dingtalk_conf, ["client_id", "client_secret"])
- if enabled:
+ enabled, reason = _is_channel_enabled(dingtalk_conf, ["client_id", "client_secret"])
+ if not enabled:
+ logger.info("[App] channels.dingtalk.%s,DingtalkChannel 未启用", reason)
+ else:
dingtalk_config = DingTalkConfig(
enabled=True,
client_id=str(dingtalk_conf.get("client_id") or "").strip(),
@@ -471,14 +557,20 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
dingtalk_channel = DingTalkChannel(dingtalk_config, _DummyBus())
channel_manager.register_channel(dingtalk_channel)
dingtalk_task = asyncio.create_task(dingtalk_channel.start(), name="dingtalk")
+ logger.info("[App] 已按 config.yaml.channels.dingtalk 注册 DingtalkChannel")
+ else:
+ logger.info("[App] channels.dingtalk 未配置或格式错误,DingtalkChannel 不启用")
- if "telegram" in changed:
+ if "telegram" in changed_channels:
telegram_conf = conf.get("telegram") if isinstance(conf, dict) else None
await _stop_channel(telegram_channel, telegram_task, "telegram")
telegram_channel, telegram_task = None, None
+
if isinstance(telegram_conf, dict):
- enabled, _ = _is_channel_enabled(telegram_conf, ["bot_token"])
- if enabled:
+ enabled, reason = _is_channel_enabled(telegram_conf, ["bot_token"])
+ if not enabled:
+ logger.info("[App] channels.telegram.%s,TelegramChannel 未启用", reason)
+ else:
telegram_config = TelegramChannelConfig(
enabled=True,
bot_token=str(telegram_conf.get("bot_token") or "").strip(),
@@ -489,14 +581,20 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
telegram_channel = TelegramChannel(telegram_config, _DummyBus())
channel_manager.register_channel(telegram_channel)
telegram_task = asyncio.create_task(telegram_channel.start(), name="telegram")
+ logger.info("[App] 已按 config.yaml.channels.telegram 注册 TelegramChannel")
+ else:
+ logger.info("[App] channels.telegram 未配置或格式错误,TelegramChannel 不启用")
- if "discord" in changed:
+ if "discord" in changed_channels:
discord_conf = conf.get("discord") if isinstance(conf, dict) else None
await _stop_channel(discord_channel, discord_task, "discord")
discord_channel, discord_task = None, None
+
if isinstance(discord_conf, dict):
- enabled, _ = _is_channel_enabled(discord_conf, ["bot_token"])
- if enabled:
+ enabled, reason = _is_channel_enabled(discord_conf, ["bot_token"])
+ if not enabled:
+ logger.info("[App] channels.discord.%s,DiscordChannel 未启用", reason)
+ else:
discord_config = DiscordChannelConfig(
enabled=True,
bot_token=str(discord_conf.get("bot_token") or "").strip(),
@@ -509,40 +607,93 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
discord_channel = DiscordChannel(discord_config, _DummyBus())
channel_manager.register_channel(discord_channel)
discord_task = asyncio.create_task(discord_channel.start(), name="discord")
+ logger.info("[App] 已按 config.yaml.channels.discord 注册 DiscordChannel")
+ else:
+ logger.info("[App] channels.discord 未配置或格式错误,DiscordChannel 不启用")
- if "whatsapp" in changed:
+ if "whatsapp" in changed_channels:
whatsapp_conf = conf.get("whatsapp") if isinstance(conf, dict) else None
await _stop_channel(whatsapp_channel, whatsapp_task, "whatsapp")
whatsapp_channel, whatsapp_task = None, None
+
if isinstance(whatsapp_conf, dict):
bridge_ws_url = str(whatsapp_conf.get("bridge_ws_url") or "ws://127.0.0.1:19600/ws").strip()
+ default_jid = str(whatsapp_conf.get("default_jid") or "").strip()
+ allow_from = whatsapp_conf.get("allow_from") or []
+ enable_streaming = bool(whatsapp_conf.get("enable_streaming", True))
+ auto_start_bridge = bool(whatsapp_conf.get("auto_start_bridge", False))
+ bridge_command = str(
+ whatsapp_conf.get("bridge_command") or "node scripts/whatsapp-bridge.js"
+ ).strip()
+ bridge_workdir = str(whatsapp_conf.get("bridge_workdir") or "").strip()
+ bridge_env_raw = whatsapp_conf.get("bridge_env") or {}
+ bridge_env = bridge_env_raw if isinstance(bridge_env_raw, dict) else {}
+
enabled_raw = whatsapp_conf.get("enabled", None)
- enabled = bool(bridge_ws_url) if enabled_raw is None else bool(enabled_raw)
- if enabled and bridge_ws_url:
+ if enabled_raw is None:
+ enabled = bool(bridge_ws_url)
+ else:
+ enabled = bool(enabled_raw)
+
+ if not enabled:
+ logger.info("[App] channels.whatsapp.enabled = false,WhatsAppChannel 未启用")
+ elif not bridge_ws_url:
+ logger.info("[App] channels.whatsapp 缺少 bridge_ws_url,WhatsAppChannel 未启用")
+ else:
whatsapp_config = WhatsAppChannelConfig(
enabled=True,
- enable_streaming=bool(whatsapp_conf.get("enable_streaming", True)),
+ enable_streaming=enable_streaming,
bridge_ws_url=bridge_ws_url,
- allow_from=whatsapp_conf.get("allow_from") or [],
- default_jid=str(whatsapp_conf.get("default_jid") or "").strip(),
- auto_start_bridge=bool(whatsapp_conf.get("auto_start_bridge", False)),
- bridge_command=str(
- whatsapp_conf.get("bridge_command") or "node scripts/whatsapp-bridge.js"
- ).strip(),
- bridge_workdir=str(whatsapp_conf.get("bridge_workdir") or "").strip(),
- bridge_env={str(k): str(v) for k, v in (whatsapp_conf.get("bridge_env") or {}).items()},
+ allow_from=allow_from,
+ default_jid=default_jid,
+ auto_start_bridge=auto_start_bridge,
+ bridge_command=bridge_command,
+ bridge_workdir=bridge_workdir,
+ bridge_env={str(k): str(v) for k, v in bridge_env.items()},
)
whatsapp_channel = WhatsAppChannel(whatsapp_config, _DummyBus())
channel_manager.register_channel(whatsapp_channel)
whatsapp_task = asyncio.create_task(whatsapp_channel.start(), name="whatsapp")
+ logger.info("[App] 已按 config.yaml.channels.whatsapp 注册 WhatsAppChannel")
+ else:
+ logger.info("[App] channels.whatsapp 未配置或格式错误,WhatsAppChannel 不启用")
+
+ if "wecom" in changed_channels:
+ wecom_conf = conf.get("wecom") if isinstance(conf, dict) else None
+ await _stop_channel(wecom_channel, wecom_task, "wecom")
+ wecom_channel, wecom_task = None, None
+
+ if isinstance(wecom_conf, dict):
+ enabled, reason = _is_channel_enabled(wecom_conf, ["bot_id", "secret"])
+ if not enabled:
+ logger.info("[App] channels.wecom.%s,WecomChannel 未启用", reason)
+ else:
+ wecom_config = WecomConfig(
+ enabled=True,
+ bot_id=str(wecom_conf.get("bot_id") or "").strip(),
+ secret=str(wecom_conf.get("secret") or "").strip(),
+ ws_url=str(wecom_conf.get("ws_url") or "wss://openws.work.weixin.qq.com").strip(),
+ allow_from=wecom_conf.get("allow_from") or [],
+ enable_streaming=bool(wecom_conf.get("enable_streaming", True)),
+ send_thinking_message=bool(wecom_conf.get("send_thinking_message", True)),
+ )
+ wecom_channel = WecomChannel(wecom_config, _DummyBus())
+ channel_manager.register_channel(wecom_channel)
+ wecom_task = asyncio.create_task(wecom_channel.start(), name="wecom")
+ logger.info("[App] 已按 config.yaml.channels.wecom 注册 WecomChannel")
+ else:
+ logger.info("[App] channels.wecom 未配置或格式错误,WecomChannel 不启用")
- if "wechat" in changed:
+ if "wechat" in changed_channels:
wechat_conf = conf.get("wechat") if isinstance(conf, dict) else None
await _stop_channel(wechat_channel, wechat_task, "wechat")
wechat_channel, wechat_task = None, None
+
if isinstance(wechat_conf, dict):
- enabled, _ = _is_channel_enabled(wechat_conf, [])
- if enabled:
+ enabled, reason = _is_channel_enabled(wechat_conf, [])
+ if not enabled:
+ logger.info("[App] channels.wechat.%s,WechatChannel 未启用", reason)
+ else:
wechat_config = WechatConfig(
enabled=True,
base_url=str(wechat_conf.get("base_url") or "https://ilinkai.weixin.qq.com").strip(),
@@ -563,6 +714,9 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
wechat_channel = WechatChannel(wechat_config, _DummyBus())
channel_manager.register_channel(wechat_channel)
wechat_task = asyncio.create_task(wechat_channel.start(), name="wechat")
+ logger.info("[App] 已按 config.yaml.channels.wechat 注册 WechatChannel")
+ else:
+ logger.info("[App] channels.wechat 未配置或格式错误,WechatChannel 不启用")
channel_manager.set_config_callback(_apply_channel_config)
await channel_manager.set_config(initial_channels_conf)
@@ -570,9 +724,8 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
await channel_manager.start_dispatch()
await cron_scheduler.start()
web_task = asyncio.create_task(web_channel.start(), name="web-channel")
-
logger.info(
- "[Gateway] ready: Web ws://%s:%s%s AgentServer: %s Ctrl+C to stop",
+ "[App] 已启动: Web ws://%s:%s%s AgentServer: %s Ctrl+C 退出。",
web_host,
web_port,
web_path,
@@ -581,7 +734,9 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
try:
await web_task
- except (KeyboardInterrupt, asyncio.CancelledError):
+ except KeyboardInterrupt:
+ logger.info("收到 Ctrl+C,正在退出…")
+ except asyncio.CancelledError:
pass
finally:
web_task.cancel()
@@ -591,23 +746,13 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
pass
await web_channel.stop()
- for ch, task, name in [
- (feishu_channel, feishu_task, "feishu"),
- (xiaoyi_channel, xiaoyi_task, "xiaoyi"),
- (dingtalk_channel, dingtalk_task, "dingtalk"),
- (telegram_channel, telegram_task, "telegram"),
- (discord_channel, discord_task, "discord"),
- (whatsapp_channel, whatsapp_task, "whatsapp"),
- (wechat_channel, wechat_task, "wechat"),
- ]:
- if ch is not None and task is not None:
- task.cancel()
- try:
- await task
- except (TypeError, asyncio.CancelledError):
- pass
- await ch.stop()
-
+ if feishu_channel is not None and feishu_task is not None:
+ feishu_task.cancel()
+ try:
+ await feishu_task
+ except asyncio.CancelledError:
+ pass
+ await feishu_channel.stop()
for bot_key, task in list(feishu_enterprise_tasks.items()):
task.cancel()
try:
@@ -617,13 +762,62 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: st
channel = feishu_enterprise_channels.get(bot_key)
if channel is not None:
await channel.stop()
+ if xiaoyi_channel is not None and xiaoyi_task is not None:
+ xiaoyi_task.cancel()
+ try:
+ await xiaoyi_task
+ except asyncio.CancelledError:
+ pass
+ await xiaoyi_channel.stop()
+ if dingtalk_channel is not None and dingtalk_task is not None:
+ dingtalk_task.cancel()
+ try:
+ await dingtalk_task
+ except (TypeError, asyncio.CancelledError):
+ pass
+ await dingtalk_channel.stop()
+ if telegram_channel is not None and telegram_task is not None:
+ telegram_task.cancel()
+ try:
+ await telegram_task
+ except asyncio.CancelledError:
+ pass
+ await telegram_channel.stop()
+ if discord_channel is not None and discord_task is not None:
+ discord_task.cancel()
+ try:
+ await discord_task
+ except asyncio.CancelledError:
+ pass
+ await discord_channel.stop()
+ if whatsapp_channel is not None and whatsapp_task is not None:
+ whatsapp_task.cancel()
+ try:
+ await whatsapp_task
+ except asyncio.CancelledError:
+ pass
+ await whatsapp_channel.stop()
+ if wecom_channel is not None and wecom_task is not None:
+ wecom_task.cancel()
+ try:
+ await wecom_task
+ except asyncio.CancelledError:
+ pass
+ await wecom_channel.stop()
+ if wechat_channel is not None and wechat_task is not None:
+ wechat_task.cancel()
+ try:
+ await wechat_task
+ except asyncio.CancelledError:
+ pass
+ await wechat_channel.stop()
await cron_scheduler.stop()
await channel_manager.stop_dispatch()
await heartbeat_service.stop()
await message_handler.stop_forwarding()
await client.disconnect()
- logger.info("[Gateway] stopped")
+ logger.info("[App] Gateway 已停止")
def main() -> None:
@@ -665,10 +859,12 @@ def main() -> None:
)
args = parser.parse_args()
+ default_host = os.getenv("AGENT_SERVER_HOST", "127.0.0.1")
+ default_port = os.getenv("AGENT_SERVER_PORT") or os.getenv("AGENT_PORT", "18092")
agent_server_url = (
args.agent_server_url
or os.getenv("AGENT_SERVER_URL")
- or f"ws://{os.getenv('AGENT_SERVER_HOST', '127.0.0.1')}:{os.getenv('AGENT_SERVER_PORT', '18092')}"
+ or f"ws://{default_host}:{default_port}"
)
web_host = args.host or os.getenv("WEB_HOST", "127.0.0.1")
web_port = args.port or int(os.getenv("WEB_PORT", "19000"))
@@ -686,4 +882,3 @@ def main() -> None:
if __name__ == "__main__":
main()
-
diff --git a/jiuwenclaw/app_web_handlers.py b/jiuwenclaw/app_web_handlers.py
new file mode 100644
index 0000000000..c0a0c3dfc5
--- /dev/null
+++ b/jiuwenclaw/app_web_handlers.py
@@ -0,0 +1,1361 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+"""WebChannel RPC handlers and shared constants (used by app gateway; single source with app.py)."""
+
+from __future__ import annotations
+
+import asyncio
+import inspect
+import logging
+import os
+import re
+import secrets
+import shutil
+import time
+from dataclasses import dataclass
+from typing import Any
+
+from dotenv import load_dotenv
+import psutil
+from openjiuwen.core.common.logging import LogManager
+from openjiuwen.core.foundation.llm import ProviderType
+
+from jiuwenclaw.config import (
+ get_config,
+ get_config_raw,
+ update_heartbeat_in_config,
+ update_channel_in_config,
+ update_browser_in_config,
+ update_preferred_language_in_config,
+ update_context_engine_enabled_in_config,
+ update_permissions_enabled_in_config,
+ update_updater_in_config,
+)
+from jiuwenclaw.jiuwen_core_patch import apply_openai_model_client_patch
+from jiuwenclaw.security.base_crypto import get_crypto_provider
+from jiuwenclaw.updater import WindowsUpdaterService
+from jiuwenclaw.utils import (
+ USER_WORKSPACE_DIR,
+ get_agent_sessions_dir,
+ get_env_file,
+ get_root_dir,
+ prepare_workspace,
+)
+from jiuwenclaw.version import __version__
+
+_config_file = USER_WORKSPACE_DIR / "config" / "config.yaml"
+if not _config_file.exists():
+ prepare_workspace(overwrite=False)
+
+apply_openai_model_client_patch()
+
+for _jiuwen_log in LogManager.get_all_loggers().values():
+ _jiuwen_log.set_level(logging.CRITICAL)
+
+logger = logging.getLogger(__name__)
+
+_PROJECT_ROOT = get_root_dir()
+_ENV_FILE = get_env_file()
+load_dotenv(dotenv_path=_ENV_FILE)
+
+
+# 仅满足 Channel 构造所需,不入队、不路由;仅用 channel_manager + message_handler 做入站/出站
+class _DummyBus:
+ async def publish_user_messages(self, msg): # noqa: ANN001, ARG002
+ pass
+
+ async def route_incoming_message(self, msg): # noqa: ANN001, ARG002
+ pass
+
+ async def route_user_message(self, msg):
+ pass
+
+
+# 仅转发到 Agent 的 Web method
+_FORWARD_REQ_METHODS = frozenset({
+ "chat.send",
+ "chat.interrupt",
+ "chat.resume",
+ "chat.user_answer",
+ "history.get",
+ "browser.start",
+ # "tts.synthesize",
+ "skills.marketplace.list",
+ "skills.list",
+ "skills.installed",
+ "skills.get",
+ "skills.install",
+ "skills.import_local",
+ "skills.marketplace.add",
+ "skills.marketplace.remove",
+ "skills.marketplace.toggle",
+ "skills.uninstall",
+ "skills.skillnet.search",
+ "skills.skillnet.install",
+ "skills.skillnet.install_status",
+ "skills.skillnet.evaluate",
+ "skills.clawhub.get_token",
+ "skills.clawhub.set_token",
+ "skills.clawhub.search",
+ "skills.clawhub.download",
+})
+
+_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset({
+ "browser.start",
+ "skills.marketplace.list",
+ "skills.list",
+ "skills.installed",
+ "skills.get",
+ "skills.install",
+ "skills.import_local",
+ "skills.marketplace.add",
+ "skills.marketplace.remove",
+ "skills.marketplace.toggle",
+ "skills.uninstall",
+ "skills.skillnet.search",
+ "skills.skillnet.install",
+ "skills.skillnet.install_status",
+ "skills.skillnet.evaluate",
+ "skills.clawhub.get_token",
+ "skills.clawhub.set_token",
+ "skills.clawhub.search",
+ "skills.clawhub.download",
+})
+
+# 配置信息:config.get 返回、config.set 可修改的键(前端 param 名 -> 环境变量名)
+# default 模型 + video/audio/vision 多模型
+_CONFIG_SET_ENV_MAP = {
+ # default 模型(主对话)
+ "model_provider": "MODEL_PROVIDER",
+ "model": "MODEL_NAME",
+ "api_base": "API_BASE",
+ "api_key": "API_KEY",
+ # video 模型
+ "video_api_base": "VIDEO_API_BASE",
+ "video_api_key": "VIDEO_API_KEY",
+ "video_model": "VIDEO_MODEL_NAME",
+ "video_provider": "VIDEO_PROVIDER",
+ # audio 模型
+ "audio_api_base": "AUDIO_API_BASE",
+ "audio_api_key": "AUDIO_API_KEY",
+ "audio_model": "AUDIO_MODEL_NAME",
+ "audio_provider": "AUDIO_PROVIDER",
+ # vision 模型
+ "vision_api_base": "VISION_API_BASE",
+ "vision_api_key": "VISION_API_KEY",
+ "vision_model": "VISION_MODEL_NAME",
+ "vision_provider": "VISION_PROVIDER",
+ # 其他
+ "email_address": "EMAIL_ADDRESS",
+ "email_token": "EMAIL_TOKEN",
+ "embed_api_key": "EMBED_API_KEY",
+ "embed_api_base": "EMBED_API_BASE",
+ "embed_model": "EMBED_MODEL",
+ "jina_api_key": "JINA_API_KEY",
+ "serper_api_key": "SERPER_API_KEY",
+ "perplexity_api_key": "PERPLEXITY_API_KEY",
+ "github_token": "GITHUB_TOKEN",
+ "evolution_auto_scan": "EVOLUTION_AUTO_SCAN",
+}
+# 配置项键名列表,用于日志等说明
+CONFIG_KEYS = tuple(_CONFIG_SET_ENV_MAP.keys())
+
+# 来自 config.yaml 的配置项(前端 param 名 -> config.yaml 路径)
+_CONFIG_YAML_KEYS = frozenset({"context_engine_enabled", "permissions_enabled"})
+
+
+async def _clear_agent_config_cache(agent_client=None) -> None:
+ """写回 config.yaml 后清除 agent 侧配置缓存,使下次读取时得到最新文件内容。"""
+ try:
+ if agent_client is not None:
+ from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields
+ from jiuwenclaw.schema.message import ReqMethod
+ import uuid
+ env = e2a_from_agent_fields(
+ request_id=f"cfg-cache-clear-{uuid.uuid4().hex[:8]}",
+ channel_id="",
+ req_method=ReqMethod.CONFIG_CACHE_CLEAR,
+ )
+ await agent_client.send_request(env)
+ else:
+ get_config()
+ except Exception: # noqa: BLE001
+ pass
+
+
+def _make_session_id() -> str:
+ # 与前端 generateSessionId 保持一致:毫秒时间戳(16进制) + 6位随机16进制
+ ts = format(int(time.time() * 1000), "x")
+ suffix = secrets.token_hex(3)
+ return f"sess_{ts}_{suffix}"
+
+
+@dataclass
+class WebHandlersBindParams:
+ """Named bundle for :func:`_register_web_handlers` (avoids long positional / keyword lists)."""
+
+ channel: Any
+ agent_client: Any = None
+ message_handler: Any = None
+ channel_manager: Any = None
+ on_config_saved: Any = None
+ heartbeat_service: Any = None
+ cron_controller: Any = None
+ updater_service: WindowsUpdaterService | None = None
+
+
+def _register_web_handlers(bind: WebHandlersBindParams) -> None:
+ """注册 Web 前端需要的 method 与 on_connect。
+ on_config_saved: 可选,config.set 写回 .env 后调用的回调;返回 True 表示已热更新未重启,False 表示已安排进程重启。
+ heartbeat_service: 可选,GatewayHeartbeatService 实例,用于处理 heartbeat.get_conf / heartbeat.set_conf。
+ """
+ channel = bind.channel
+ agent_client = bind.agent_client
+ message_handler = bind.message_handler
+ channel_manager = bind.channel_manager
+ on_config_saved = bind.on_config_saved
+ heartbeat_service = bind.heartbeat_service
+ cron_controller = bind.cron_controller
+ updater_service = bind.updater_service
+
+ from jiuwenclaw.schema.message import Message, EventType
+
+ def _resolve(ref, key="value"):
+ """若为 ref 字典则取 key(无则返回 None),否则返回自身。"""
+ if isinstance(ref, dict):
+ return ref.get(key)
+ return ref
+
+ def _resolve_env_vars(value: Any) -> Any:
+ """Recursively resolve environment variables in config values."""
+ if isinstance(value, str):
+ pattern = r'\$\{([^:}]+)(?::-([^}]*))?\}'
+
+ def replace_env(match):
+ var_name = match.group(1)
+ default = match.group(2) if match.group(2) is not None else ""
+ return os.getenv(var_name, default)
+
+ return re.sub(pattern, replace_env, value)
+ elif isinstance(value, dict):
+ return {k: _resolve_env_vars(v) for k, v in value.items()}
+ elif isinstance(value, list):
+ return [_resolve_env_vars(item) for item in value]
+ else:
+ return value
+
+ async def _on_connect(ws):
+ ac = _resolve(agent_client)
+ if ac is None or not getattr(ac, "server_ready", False):
+ logger.debug("[_on_connect] Agent 未就绪,跳过 connection.ack")
+ return
+ sid = _make_session_id()
+ ack_msg = Message(
+ id=f"ack-{sid}",
+ type="event",
+ channel_id=channel.channel_id,
+ session_id=sid,
+ params={},
+ timestamp=time.time(),
+ ok=True,
+ event_type=EventType.CONNECTION_ACK,
+ payload={
+ "session_id": sid,
+ "mode": "BUILD",
+ "tools": [],
+ "protocol_version": "1.0",
+ },
+ )
+ mh = _resolve(message_handler)
+ if mh:
+ await mh.publish_robot_messages(ack_msg)
+ else:
+ await channel.send(ack_msg)
+
+ channel.on_connect(_on_connect)
+
+ async def _config_get(ws, req_id, params, session_id):
+ # 返回 _CONFIG_SET_ENV_MAP 里所有键对应的环境变量当前值
+ payload = {
+ param_key: (os.getenv(env_key) or "")
+ for param_key, env_key in _CONFIG_SET_ENV_MAP.items()
+ }
+ payload["app_version"] = __version__
+ # 合并 config.yaml 中的配置项
+ try:
+ raw = get_config_raw()
+ for key, val in payload.items():
+ if ("api_key" in key or "token" in key) and get_crypto_provider():
+ payload[key] = get_crypto_provider().decrypt(val)
+ ctx_cfg = (raw.get("react") or {}).get("context_engine_config") or {}
+ payload["context_engine_enabled"] = "true" if ctx_cfg.get("enabled", False) else "false"
+ perm_cfg = raw.get("permissions") or {}
+ payload["permissions_enabled"] = "true" if perm_cfg.get("enabled", False) else "false"
+ except Exception: # noqa: BLE001
+ payload.setdefault("context_engine_enabled", "false")
+ payload.setdefault("permissions_enabled", "false")
+ await channel.send_response(ws, req_id, ok=True, payload=payload)
+
+ def _persist_env_updates(updates: dict[str, str]) -> None:
+ """把已更新的环境变量写回 .env(仅覆盖或追加对应 KEY=value 行)。"""
+ env_path = _ENV_FILE
+ if not updates:
+ return
+ try:
+ lines: list[str] = []
+ if env_path.is_file():
+ with open(env_path, "r", encoding="utf-8") as f:
+ lines = f.readlines()
+ updated_keys = set(updates.keys())
+ new_lines: list[str] = []
+ for line in lines:
+ stripped = line.strip()
+ found = False
+ for env_key, value in updates.items():
+ if stripped.startswith(env_key + "="):
+ new_lines.append(f'{env_key}="{value}"\n' if value else f"{env_key}=\n")
+ found = True
+ break
+ if not found:
+ new_lines.append(line)
+ for env_key, value in updates.items():
+ if not any(s.strip().startswith(env_key + "=") for s in new_lines):
+ new_lines.append(f'{env_key}="{value}"\n' if value else f"{env_key}=\n")
+ env_path.parent.mkdir(parents=True, exist_ok=True)
+ with open(env_path, "w", encoding="utf-8") as f:
+ f.writelines(new_lines)
+ except OSError as e:
+ logger.warning("[config.set] 写回 .env 失败: %s", e)
+
+ async def _config_set(ws, req_id, params, session_id):
+ """根据前端消息内容更新配置(支持 .env 与 config.yaml 中的键),并写回对应文件。"""
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ for key, val in params.items():
+ if ("api_key" in key or "token" in key) and get_crypto_provider():
+ params[key] = get_crypto_provider().encrypt(val)
+ env_updates: dict[str, str] = {}
+ yaml_updated: list[str] = []
+ available_model_providers = [provider.value for provider in ProviderType]
+
+ for param_key, env_key in _CONFIG_SET_ENV_MAP.items():
+ if param_key not in params:
+ continue
+ val = params[param_key]
+ if param_key.endswith("_provider") and val and val not in available_model_providers:
+ await channel.send_response(
+ ws, req_id, ok=False,
+ error=f"Model provider must in: {available_model_providers} ",
+ code="BAD_REQUEST"
+ )
+ return
+ if val is None:
+ env_updates[env_key] = ""
+ else:
+ env_updates[env_key] = str(val).strip()
+
+ for param_key in _CONFIG_YAML_KEYS:
+ if param_key not in params:
+ continue
+ val = params[param_key]
+ parsed = str(val).strip().lower() in ("true", "1", "yes")
+ try:
+ if param_key == "context_engine_enabled":
+ update_context_engine_enabled_in_config(parsed)
+ elif param_key == "permissions_enabled":
+ update_permissions_enabled_in_config(parsed)
+ yaml_updated.append(param_key)
+ except Exception as e: # noqa: BLE001
+ logger.warning("[config.set] 写回 config.yaml 失败 %s: %s", param_key, e)
+
+ for env_key, value in env_updates.items():
+ os.environ[env_key] = value
+ applied_without_restart = True
+
+ if env_updates:
+ _persist_env_updates(env_updates)
+ logger.info("[config.set] 已更新 .env: %s", list(env_updates.keys()))
+ if yaml_updated:
+ await _clear_agent_config_cache(_resolve(agent_client))
+ logger.info("[config.set] 已更新 config.yaml: %s", yaml_updated)
+
+ if env_updates or yaml_updated:
+ if on_config_saved:
+ callback_result = on_config_saved(set(env_updates.keys()) | set(yaml_updated))
+ if inspect.isawaitable(callback_result):
+ callback_result = await callback_result
+ applied_without_restart = bool(callback_result)
+
+ updated_param_keys = [k for k, e in _CONFIG_SET_ENV_MAP.items() if e in env_updates] + yaml_updated
+ await channel.send_response(
+ ws, req_id, ok=True,
+ payload={"updated": updated_param_keys, "applied_without_restart": applied_without_restart},
+ )
+
+ async def _channel_get(ws, req_id, params, session_id):
+ """返回已注册的 channel 列表."""
+ cm = _resolve(channel_manager)
+ if cm is not None:
+ channels = [{"channel_id": cid} for cid in cm.enabled_channels]
+ else:
+ channels = []
+ await channel.send_response(ws, req_id, ok=True, payload={"channels": channels})
+
+ async def _updater_get_status(ws, req_id, params, session_id):
+ service = updater_service or WindowsUpdaterService()
+ await channel.send_response(ws, req_id, ok=True, payload=service.get_status())
+
+ async def _updater_check(ws, req_id, params, session_id):
+ service = updater_service or WindowsUpdaterService()
+ manual = bool((params or {}).get("manual", False)) if isinstance(params, dict) else False
+ payload = await asyncio.to_thread(service.check, manual)
+ await channel.send_response(ws, req_id, ok=True, payload=payload)
+
+ async def _updater_download(ws, req_id, params, session_id):
+ service = updater_service or WindowsUpdaterService()
+ payload = service.start_download()
+ await channel.send_response(ws, req_id, ok=True, payload=payload)
+
+ async def _updater_get_conf(ws, req_id, params, session_id):
+ service = updater_service or WindowsUpdaterService()
+ await channel.send_response(ws, req_id, ok=True, payload=service.get_runtime_config())
+
+ async def _updater_set_conf(ws, req_id, params, session_id):
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+
+ updates: dict[str, Any] = {}
+ if "enabled" in params:
+ updates["enabled"] = bool(params.get("enabled"))
+ for key in ("repo_owner", "repo_name", "release_api_url", "asset_name_pattern", "sha256_name_pattern"):
+ if key in params:
+ updates[key] = str(params.get(key) or "").strip()
+ if "timeout_seconds" in params:
+ try:
+ updates["timeout_seconds"] = max(5, int(params.get("timeout_seconds")))
+ except (TypeError, ValueError):
+ await channel.send_response(ws, req_id, ok=False,
+ error="timeout_seconds must be integer", code="BAD_REQUEST")
+ return
+
+ try:
+ update_updater_in_config(updates)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("[updater.set_conf] 写回 config.yaml 失败: %s", exc)
+ await channel.send_response(ws, req_id, ok=False,
+ error=str(exc), code="INTERNAL_ERROR")
+ return
+
+ service = updater_service or WindowsUpdaterService()
+ await channel.send_response(ws, req_id, ok=True, payload=service.get_runtime_config())
+
+ async def _session_list(ws, req_id, params, session_id):
+ """返回 agent/sessions 下的 session_id 列表(子目录名)。"""
+ limit = 20
+ if isinstance(params, dict):
+ raw_limit = params.get("limit")
+ if isinstance(raw_limit, int):
+ limit = raw_limit
+ elif isinstance(raw_limit, str) and raw_limit.strip().isdigit():
+ limit = int(raw_limit.strip())
+ limit = max(1, min(limit, 200))
+
+ workspace_session_dir = get_agent_sessions_dir()
+ if not workspace_session_dir.exists() or not workspace_session_dir.is_dir():
+ sessions = []
+ else:
+ sessions = sorted(
+ [d.name for d in workspace_session_dir.iterdir() if d.is_dir()],
+ reverse=True,
+ )
+ sessions = sessions[:limit]
+ await channel.send_response(ws, req_id, ok=True, payload={"sessions": sessions})
+
+ async def _session_create(ws, req_id, params, session_id):
+ """创建一个新 session(在 agent/sessions 下创建一个新目录)。"""
+ if not isinstance(params, dict):
+ await channel.send_response(
+ ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST",
+ )
+ return
+ session_id_to_create = params.get("session_id")
+ if not isinstance(session_id_to_create, str) or not session_id_to_create.strip():
+ await channel.send_response(
+ ws, req_id, ok=False, error="session_id is required", code="BAD_REQUEST",
+ )
+ return
+ session_id_to_create = session_id_to_create.strip()
+
+ workspace_session_dir = get_agent_sessions_dir()
+ if not workspace_session_dir.exists():
+ workspace_session_dir.mkdir(parents=True)
+ session_dir = workspace_session_dir / session_id_to_create
+ if session_dir.exists():
+ await channel.send_response(
+ ws, req_id, ok=False, error="session already exists", code="ALREADY_EXISTS",
+ )
+ return
+ session_dir.mkdir()
+ await channel.send_response(ws, req_id, ok=True, payload={"session_id": session_id_to_create})
+
+ async def _session_delete(ws, req_id, params, session_id):
+ """删除一个 session(在 agent/sessions 下删除一个目录)。"""
+ if not isinstance(params, dict):
+ await channel.send_response(
+ ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST",
+ )
+ return
+ session_id_to_delete = params.get("session_id")
+ if not isinstance(session_id_to_delete, str) or not session_id_to_delete.strip():
+ await channel.send_response(
+ ws, req_id, ok=False, error="session_id is required", code="BAD_REQUEST",
+ )
+ return
+ session_id_to_delete = session_id_to_delete.strip()
+
+ workspace_session_dir = get_agent_sessions_dir()
+ session_dir = workspace_session_dir / session_id_to_delete
+ if not session_dir.exists():
+ await channel.send_response(
+ ws, req_id, ok=False, error="session not found", code="NOT_FOUND",
+ )
+ return
+ if not session_dir.is_dir():
+ await channel.send_response(
+ ws, req_id, ok=False, error="session is not a directory", code="BAD_REQUEST",
+ )
+ return
+ shutil.rmtree(session_dir)
+ await channel.send_response(ws, req_id, ok=True, payload={"session_id": session_id_to_delete})
+
+ async def _path_get(ws, req_id, params, session_id):
+ """读 browser.chrome_path 并返回给前端(会解析环境变量)。"""
+ try:
+ config_base = get_config()
+ except FileNotFoundError:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=True,
+ payload={"chrome_path": ""},
+ )
+ return
+
+ if not isinstance(config_base, dict):
+ config_base = {}
+
+ config = _resolve_env_vars(config_base)
+ browser_cfg = config.get("browser", {}) if isinstance(config, dict) else {}
+ chrome_path = ""
+ if isinstance(browser_cfg, dict):
+ value = browser_cfg.get("chrome_path", "")
+ if isinstance(value, str):
+ chrome_path = value
+
+ await channel.send_response(ws, req_id, ok=True, payload={"chrome_path": chrome_path})
+
+ async def _path_set(ws, req_id, params, session_id):
+ """更新 browser.chrome_path 并写回 config。"""
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+
+ chrome_path = params.get("chrome_path")
+ if not isinstance(chrome_path, str):
+ await channel.send_response(ws, req_id, ok=False, error="chrome_path must be string", code="BAD_REQUEST")
+ return
+ chrome_path = chrome_path.strip()
+
+ try:
+ update_browser_in_config({"chrome_path": chrome_path})
+ await _clear_agent_config_cache(_resolve(agent_client))
+ except Exception as e: # noqa: BLE001
+ logger.warning("[path.set] 写回 config.yaml 失败: %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+ return
+
+ await channel.send_response(ws, req_id, ok=True, payload={"chrome_path": chrome_path})
+
+ async def _memory_compute(ws, req_id, params, session_id):
+
+ process = psutil.Process()
+ rss_bytes = process.memory_info().rss # 物理内存
+ rss_mb = rss_bytes / (1024 * 1024)
+
+ mem = psutil.virtual_memory()
+ total_mb = mem.total / (1024 * 1024)
+ available_mb = mem.available / (1024 * 1024)
+ used_percent = mem.percent
+
+ await channel.send_response(ws, req_id, ok=True,
+ payload={"rss_mb": rss_mb, "total_mb": total_mb,
+ "available_mb": available_mb})
+
+
+
+ async def _chat_send(ws, req_id, params, session_id):
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=True,
+ payload={"accepted": True, "session_id": session_id},
+ )
+
+ async def _chat_resume(ws, req_id, params, session_id):
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=True,
+ payload={"accepted": True, "session_id": session_id},
+ )
+
+ async def _chat_interrupt(ws, req_id, params, session_id):
+ intent = params.get("intent") if isinstance(params, dict) else None
+ payload = {"accepted": True, "session_id": session_id}
+ if isinstance(intent, str) and intent:
+ payload["intent"] = intent
+ await channel.send_response(ws, req_id, ok=True, payload=payload)
+
+ async def _chat_user_answer(ws, req_id, params, session_id):
+ payload = {"accepted": True, "session_id": session_id}
+ request_id = params.get("request_id") if isinstance(params, dict) else None
+ if isinstance(request_id, str) and request_id:
+ payload["request_id"] = request_id
+ await channel.send_response(ws, req_id, ok=True, payload=payload)
+
+ async def _history_get(ws, req_id, params, session_id):
+ payload = {"accepted": True, "session_id": session_id}
+ if isinstance(params, dict):
+ if "session_id" in params:
+ payload["session_id"] = params.get("session_id")
+ if "page_idx" in params:
+ payload["page_idx"] = params.get("page_idx")
+ await channel.send_response(ws, req_id, ok=True, payload=payload)
+
+ async def _locale_get_conf(ws, req_id, params, session_id):
+ """返回当前 preferred_language 配置(zh / en)。"""
+ try:
+ cfg = get_config()
+ lang = str(cfg.get("preferred_language") or "zh").strip().lower()
+ if lang not in ("zh", "en"):
+ lang = "zh"
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=True,
+ payload={"preferred_language": lang}
+ )
+ except Exception as e:
+ logger.exception("[locale.get_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _locale_set_conf(ws, req_id, params, session_id):
+ """更新 preferred_language 并写回 config.yaml。"""
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ lang_raw = params.get("preferred_language")
+ if not isinstance(lang_raw, str):
+ await channel.send_response(
+ ws, req_id, ok=False, error="preferred_language must be string", code="BAD_REQUEST"
+ )
+ return
+ lang = lang_raw.strip().lower()
+ if lang not in ("zh", "en"):
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="preferred_language must be zh or en",
+ code="BAD_REQUEST"
+ )
+ return
+ try:
+ update_preferred_language_in_config(lang)
+ await channel.send_response(ws, req_id, ok=True, payload={"preferred_language": lang})
+ except Exception as e:
+ logger.warning("[locale.set_conf] 写回 config.yaml 失败: %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _heartbeat_get_conf(ws, req_id, params, session_id):
+ """返回当前心跳配置(every / target / active_hours)。"""
+ hb = _resolve(heartbeat_service)
+ if hb is None:
+ await channel.send_response(ws, req_id, ok=False, error="heartbeat service not available",
+ code="SERVICE_UNAVAILABLE")
+ return
+ try:
+ payload = dict(hb.get_heartbeat_conf())
+ await channel.send_response(ws, req_id, ok=True, payload=payload)
+ except Exception as e:
+ logger.exception("[heartbeat.get_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _heartbeat_set_conf(ws, req_id, params, session_id):
+ """更新心跳配置并重启心跳服务;params 可含 every、target、active_hours。"""
+ hb = _resolve(heartbeat_service)
+ if hb is None:
+ await channel.send_response(ws, req_id, ok=False, error="heartbeat service not available",
+ code="SERVICE_UNAVAILABLE")
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ try:
+ every = params.get("every")
+ target = params.get("target")
+ active_hours = params.get("active_hours")
+ if every is not None:
+ every = float(every)
+ if target is not None:
+ target = str(target)
+ if active_hours is not None:
+ if not isinstance(active_hours, dict):
+ active_hours = None
+ elif active_hours and ("start" not in active_hours or "end" not in active_hours):
+ # 必须同时包含 start/end,否则视为清除时间段(始终生效)
+ active_hours = None
+ await hb.set_heartbeat_conf(every=every, target=target, active_hours=active_hours)
+ payload = dict(hb.get_heartbeat_conf())
+ try:
+ update_heartbeat_in_config(payload)
+ await _clear_agent_config_cache(_resolve(agent_client))
+ except Exception as e: # noqa: BLE001
+ logger.warning("[heartbeat.set_conf] 写回 config.yaml 失败: %s", e)
+ await channel.send_response(ws, req_id, ok=True, payload=payload)
+ except ValueError as e:
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="BAD_REQUEST")
+ except Exception as e:
+ logger.exception("[heartbeat.set_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_feishu_get_conf(ws, req_id, params, session_id):
+ """返回 FeishuChannel 的当前配置(由 ChannelManager 管理)。"""
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ try:
+ conf = cm.get_conf("feishu")
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.feishu.get_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_feishu_set_conf(ws, req_id, params, session_id):
+ """更新 FeishuChannel 的配置,并按新配置重新实例化通道。"""
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="params must be object",
+ code="BAD_REQUEST",
+ )
+ return
+ try:
+ await cm.set_conf("feishu", params)
+ conf = cm.get_conf("feishu")
+ try:
+ update_channel_in_config("feishu", conf)
+ await _clear_agent_config_cache(_resolve(agent_client))
+ except Exception as e: # noqa: BLE001
+ logger.warning("[channel.feishu.set_conf] 写回 config.yaml 失败: %s", e)
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.feishu.set_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_xiaoyi_get_conf(ws, req_id, params, session_id):
+ """返回 XiaoyiChannel 的当前配置(由 ChannelManager 管理)。"""
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ try:
+ conf = cm.get_conf("xiaoyi")
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.xiaoyi.get_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_xiaoyi_set_conf(ws, req_id, params, session_id):
+ """更新 XiaoyiChannel 的配置,并按新配置重新实例化通道。"""
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="params must be object",
+ code="BAD_REQUEST",
+ )
+ return
+ try:
+ await cm.set_conf("xiaoyi", params)
+ conf = cm.get_conf("xiaoyi")
+ try:
+ update_channel_in_config("xiaoyi", conf)
+ await _clear_agent_config_cache(_resolve(agent_client))
+ except Exception as e: # noqa: BLE001
+ logger.warning("[channel.xiaoyi.set_conf] 写回 config.yaml 失败: %s", e)
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.xiaoyi.set_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_telegram_get_conf(ws, req_id, params, session_id):
+ """返回 TelegramChannel 的当前配置(由 ChannelManager 管理)。"""
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ try:
+ conf = cm.get_conf("telegram")
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.telegram.get_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_telegram_set_conf(ws, req_id, params, session_id):
+ """更新 TelegramChannel 的配置,并按新配置重新实例化通道。"""
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="params must be object",
+ code="BAD_REQUEST",
+ )
+ return
+ try:
+ await cm.set_conf("telegram", params)
+ conf = cm.get_conf("telegram")
+ try:
+ update_channel_in_config("telegram", conf)
+ await _clear_agent_config_cache(_resolve(agent_client))
+ except Exception as e: # noqa: BLE001
+ logger.warning("[channel.telegram.set_conf] 写回 config.yaml 失败: %s", e)
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.telegram.set_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_dingtalk_get_conf(ws, req_id, params, session_id):
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ try:
+ conf = cm.get_conf("dingtalk")
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.dingtalk.get_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_dingtalk_set_conf(ws, req_id, params, session_id):
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="params must be object",
+ code="BAD_REQUEST",
+ )
+ return
+ try:
+ await cm.set_conf("dingtalk", params)
+ conf = cm.get_conf("dingtalk")
+ try:
+ update_channel_in_config("dingtalk", conf)
+ await _clear_agent_config_cache(_resolve(agent_client))
+ except Exception as e: # noqa: BLE001
+ logger.warning("[channel.dingtalk.set_conf] 写回 config.yaml 失败: %s", e)
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.dingtalk.set_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_whatsapp_get_conf(ws, req_id, params, session_id):
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ try:
+ conf = cm.get_conf("whatsapp")
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.whatsapp.get_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_whatsapp_set_conf(ws, req_id, params, session_id):
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="params must be object",
+ code="BAD_REQUEST",
+ )
+ return
+ try:
+ await cm.set_conf("whatsapp", params)
+ conf = cm.get_conf("whatsapp")
+ try:
+ update_channel_in_config("whatsapp", conf)
+ await _clear_agent_config_cache(_resolve(agent_client))
+ except Exception as e: # noqa: BLE001
+ logger.warning("[channel.whatsapp.set_conf] 写回 config.yaml 失败: %s", e)
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.whatsapp.set_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_discord_get_conf(ws, req_id, params, session_id):
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ try:
+ conf = cm.get_conf("discord")
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.discord.get_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_discord_set_conf(ws, req_id, params, session_id):
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="params must be object",
+ code="BAD_REQUEST",
+ )
+ return
+ try:
+ await cm.set_conf("discord", params)
+ conf = cm.get_conf("discord")
+ try:
+ update_channel_in_config("discord", conf)
+ await _clear_agent_config_cache(_resolve(agent_client))
+ except Exception as e: # noqa: BLE001
+ logger.warning("[channel.discord.set_conf] 写回 config.yaml 失败: %s", e)
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.discord.set_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_wecom_get_conf(ws, req_id, params, session_id):
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ try:
+ conf = cm.get_conf("wecom")
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.wecom.get_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_wecom_set_conf(ws, req_id, params, session_id):
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="params must be object",
+ code="BAD_REQUEST",
+ )
+ return
+ try:
+ await cm.set_conf("wecom", params)
+ conf = cm.get_conf("wecom")
+ try:
+ update_channel_in_config("wecom", conf)
+ await _clear_agent_config_cache(_resolve(agent_client))
+ except Exception as e: # noqa: BLE001
+ logger.warning("[channel.wecom.set_conf] 写回 config.yaml 失败: %s", e)
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.wecom.set_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_wechat_get_conf(ws, req_id, params, session_id):
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ try:
+ conf = cm.get_conf("wechat")
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.wechat.get_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_wechat_set_conf(ws, req_id, params, session_id):
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="params must be object",
+ code="BAD_REQUEST",
+ )
+ return
+ try:
+ await cm.set_conf("wechat", params)
+ conf = cm.get_conf("wechat")
+ try:
+ update_channel_in_config("wechat", conf)
+ await _clear_agent_config_cache(_resolve(agent_client))
+ except Exception as e: # noqa: BLE001
+ logger.warning("[channel.wechat.set_conf] 写回 config.yaml 失败: %s", e)
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.wechat.set_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_wechat_get_login_ui(ws, req_id, params, session_id):
+ from jiuwenclaw.channel.wechat_channel import snapshot_wechat_login_ui_state
+
+ try:
+ ui = await snapshot_wechat_login_ui_state()
+ if "updated_at" in ui and isinstance(ui["updated_at"], (int, float)):
+ ui["updated_at"] = int(ui["updated_at"])
+ await channel.send_response(ws, req_id, ok=True, payload=ui)
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.wechat.get_login_ui] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ # ----- cron jobs -----
+
+ def _get_cron():
+ return _resolve(cron_controller)
+
+ async def _cron_job_list(ws, req_id, params, session_id):
+ cc = _get_cron()
+ if cc is None:
+ await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
+ return
+ jobs = await cc.list_jobs()
+ await channel.send_response(ws, req_id, ok=True, payload={"jobs": jobs})
+
+ async def _cron_job_get(ws, req_id, params, session_id):
+ cc = _get_cron()
+ if cc is None:
+ await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ job_id = str(params.get("id") or "").strip()
+ if not job_id:
+ await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
+ return
+ job = await cc.get_job(job_id)
+ if job is None:
+ await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
+ return
+ await channel.send_response(ws, req_id, ok=True, payload={"job": job})
+
+ async def _cron_job_create(ws, req_id, params, session_id):
+ cc = _get_cron()
+ if cc is None:
+ await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ try:
+ job = await cc.create_job(params)
+ await channel.send_response(ws, req_id, ok=True, payload={"job": job})
+ except Exception as e: # noqa: BLE001
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="BAD_REQUEST")
+
+ async def _cron_job_update(ws, req_id, params, session_id):
+ cc = _get_cron()
+ if cc is None:
+ await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ job_id = str(params.get("id") or "").strip()
+ patch = params.get("patch") or {}
+ if not job_id:
+ await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
+ return
+ if not isinstance(patch, dict):
+ await channel.send_response(ws, req_id, ok=False, error="patch must be object", code="BAD_REQUEST")
+ return
+ try:
+ job = await cc.update_job(job_id, patch)
+ await channel.send_response(ws, req_id, ok=True, payload={"job": job})
+ except KeyError:
+ await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
+ except Exception as e: # noqa: BLE001
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="BAD_REQUEST")
+
+ async def _cron_job_delete(ws, req_id, params, session_id):
+ cc = _get_cron()
+ if cc is None:
+ await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ job_id = str(params.get("id") or "").strip()
+ if not job_id:
+ await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
+ return
+ deleted = await cc.delete_job(job_id)
+ if not deleted:
+ await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
+ return
+ await channel.send_response(ws, req_id, ok=True, payload={"deleted": True})
+
+ async def _cron_job_toggle(ws, req_id, params, session_id):
+ cc = _get_cron()
+ if cc is None:
+ await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ job_id = str(params.get("id") or "").strip()
+ enabled = params.get("enabled", None)
+ if not job_id:
+ await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
+ return
+ if enabled is None:
+ await channel.send_response(ws, req_id, ok=False, error="enabled is required", code="BAD_REQUEST")
+ return
+ try:
+ job = await cc.toggle_job(job_id, bool(enabled))
+ await channel.send_response(ws, req_id, ok=True, payload={"job": job})
+ except KeyError:
+ await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
+
+ async def _cron_job_preview(ws, req_id, params, session_id):
+ cc = _get_cron()
+ if cc is None:
+ await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ job_id = str(params.get("id") or "").strip()
+ count = params.get("count", 5)
+ if not job_id:
+ await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
+ return
+ try:
+ next_runs = await cc.preview_job(job_id, int(count) if count is not None else 5)
+ await channel.send_response(ws, req_id, ok=True, payload={"next": next_runs})
+ except KeyError:
+ await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
+ except Exception as e: # noqa: BLE001
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="BAD_REQUEST")
+
+ async def _cron_job_run_now(ws, req_id, params, session_id):
+ cc = _get_cron()
+ if cc is None:
+ await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ job_id = str(params.get("id") or "").strip()
+ if not job_id:
+ await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
+ return
+ try:
+ run_id = await cc.run_now(job_id)
+ await channel.send_response(ws, req_id, ok=True, payload={"run_id": run_id})
+ except KeyError:
+ await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
+ except Exception as e: # noqa: BLE001
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ channel.register_method("config.get", _config_get)
+ channel.register_method("config.set", _config_set)
+ channel.register_method("channel.get", _channel_get)
+
+ channel.register_method("session.list", _session_list)
+ channel.register_method("session.create", _session_create)
+ channel.register_method("session.delete", _session_delete)
+
+ channel.register_method("path.get", _path_get)
+ channel.register_method("path.set", _path_set)
+
+ channel.register_method("memory.compute", _memory_compute)
+
+ channel.register_method("chat.send", _chat_send)
+ channel.register_method("chat.resume", _chat_resume)
+ channel.register_method("chat.interrupt", _chat_interrupt)
+ channel.register_method("chat.user_answer", _chat_user_answer)
+ channel.register_method("history.get", _history_get)
+ channel.register_method("locale.get_conf", _locale_get_conf)
+ channel.register_method("locale.set_conf", _locale_set_conf)
+ channel.register_method("updater.get_status", _updater_get_status)
+ channel.register_method("updater.check", _updater_check)
+ channel.register_method("updater.download", _updater_download)
+ channel.register_method("updater.get_conf", _updater_get_conf)
+ channel.register_method("updater.set_conf", _updater_set_conf)
+ channel.register_method("heartbeat.get_conf", _heartbeat_get_conf)
+ channel.register_method("heartbeat.set_conf", _heartbeat_set_conf)
+ channel.register_method("channel.feishu.get_conf", _channel_feishu_get_conf)
+ channel.register_method("channel.feishu.set_conf", _channel_feishu_set_conf)
+ channel.register_method("channel.xiaoyi.get_conf", _channel_xiaoyi_get_conf)
+ channel.register_method("channel.xiaoyi.set_conf", _channel_xiaoyi_set_conf)
+ channel.register_method("channel.telegram.get_conf", _channel_telegram_get_conf)
+ channel.register_method("channel.telegram.set_conf", _channel_telegram_set_conf)
+ channel.register_method("channel.dingtalk.get_conf", _channel_dingtalk_get_conf)
+ channel.register_method("channel.dingtalk.set_conf", _channel_dingtalk_set_conf)
+ channel.register_method("channel.whatsapp.get_conf", _channel_whatsapp_get_conf)
+ channel.register_method("channel.whatsapp.set_conf", _channel_whatsapp_set_conf)
+ channel.register_method("channel.discord.get_conf", _channel_discord_get_conf)
+ channel.register_method("channel.discord.set_conf", _channel_discord_set_conf)
+ channel.register_method("channel.wecom.get_conf", _channel_wecom_get_conf)
+ channel.register_method("channel.wecom.set_conf", _channel_wecom_set_conf)
+ channel.register_method("channel.wechat.get_conf", _channel_wechat_get_conf)
+ channel.register_method("channel.wechat.set_conf", _channel_wechat_set_conf)
+ channel.register_method("channel.wechat.get_login_ui", _channel_wechat_get_login_ui)
+ channel.register_method("cron.job.list", _cron_job_list)
+ channel.register_method("cron.job.get", _cron_job_get)
+ channel.register_method("cron.job.create", _cron_job_create)
+ channel.register_method("cron.job.update", _cron_job_update)
+ channel.register_method("cron.job.delete", _cron_job_delete)
+ channel.register_method("cron.job.toggle", _cron_job_toggle)
+ channel.register_method("cron.job.preview", _cron_job_preview)
+ channel.register_method("cron.job.run_now", _cron_job_run_now)
+
diff --git a/jiuwenclaw/gateway/channel_manager.py b/jiuwenclaw/gateway/channel_manager.py
index f677f7ba2d..790ab5fa81 100644
--- a/jiuwenclaw/gateway/channel_manager.py
+++ b/jiuwenclaw/gateway/channel_manager.py
@@ -60,6 +60,19 @@ class ChannelManager(ABC):
channel.on_message(self._on_channel_message)
logger.info("[ChannelManager] 已注册 Channel: channel_id=%s, 当前共 %d 个", cid, len(self._channels))
+ def register_channel_with_inbound(
+ self,
+ channel: "BaseChannel",
+ on_message: Callable[["Message"], Any],
+ ) -> None:
+ """登记 Channel 并使用自定义入站回调(不替换为默认 _on_channel_message)。"""
+ self._channels[channel.channel_id] = channel
+ channel.on_message(on_message)
+
+ def deliver_to_message_handler(self, msg: "Message") -> None:
+ """将消息交给 MessageHandler(供自定义入站路径使用)。"""
+ self._message_handler.handle_message(msg)
+
def unregister_channel(self, channel_id: str) -> None:
"""注销指定 Channel."""
self._channels.pop(channel_id, None)
diff --git a/jiuwenclaw/jiuwen_core_patch.py b/jiuwenclaw/jiuwen_core_patch.py
index 53681e841a..a8b48e6ce2 100644
--- a/jiuwenclaw/jiuwen_core_patch.py
+++ b/jiuwenclaw/jiuwen_core_patch.py
@@ -110,3 +110,9 @@ class PatchOpenAIModelClient(OpenAIModelClient):
finish_reason=choice.finish_reason or "null"
)
+
+def apply_openai_model_client_patch() -> None:
+ """Monkey-patch upstream OpenAIModelClient with JiuwenClaw SSL/headers/stream behavior."""
+ _impl = PatchOpenAIModelClient.__dict__
+ setattr(OpenAIModelClient, "_create_async_openai_client", _impl["_create_async_openai_client"])
+ setattr(OpenAIModelClient, "_parse_stream_chunk", _impl["_parse_stream_chunk"])