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:ACP端到端流程打通
zp23331d77c65b65550
diff --git a/jiuwenclaw/agentserver/agent_manager.py b/jiuwenclaw/agentserver/agent_manager.pyindex fe095e0eea..5c5c8cca4e 100644--- a/jiuwenclaw/agentserver/agent_manager.py+++ b/jiuwenclaw/agentserver/agent_manager.py@@ -29,6 +29,25 @@ ACP_DEFAULT_CAPABILITIES: dict[str, Any] = {}+def _build_acp_agent_config(extra_config: dict[str, Any] | None = None) -> dict[str, Any]:+ """Return the dedicated ACP agent profile config.++ ACP sessions should use ACP-native filesystem/terminal tools instead of the+ default openjiuwen filesystem/bash toolchain.+ """+ config: dict[str, Any] = {+ "agent_name": "acp_agent",+ "channel_id": "acp",+ "tool_profile": "acp",+ "enable_filesystem_rail": True,+ }+ if isinstance(extra_config, dict):+ config.update(extra_config)+ config["channel_id"] = "acp"+ config["tool_profile"] = "acp"+ return config++class AgentManager:"""管理多个 Agent 实例.@@ -39,6 +58,7 @@ class AgentManager:def __init__(self) -> None:self.agents: dict[str, "JiuWenClaw"] = {}+ self._client_capabilities_by_channel: dict[str, dict[str, Any]] = {}async def _create_agent(self, agent_key: str, config: dict[str, Any] | None = None@@ -77,6 +97,10 @@ class AgentManager:"""if channel_id == "acp":logger.info("[AgentManager] ACP initialize")+ if extra_config:+ client_capabilities = extra_config.get("client_capabilities")+ if isinstance(client_capabilities, dict):+ self._client_capabilities_by_channel["acp"] = dict(client_capabilities)if "acp" in self.agents:logger.info("[AgentManager] Resetting ACP agent")@@ -86,15 +110,18 @@ class AgentManager:logger.warning("[AgentManager] ACP agent cleanup failed: %s", e)del self.agents["acp"]- config: dict[str, Any] = {"agent_name": "acp_agent"}- if extra_config:- config.update(extra_config)+ config = _build_acp_agent_config(extra_config)await self._create_agent("acp", config)return ACP_DEFAULT_CAPABILITIES.copy()return None- async def create_session(self, channel_id: str = "") -> str:+ def get_client_capabilities(self, channel_id: str = "") -> dict[str, Any]:+ channel_key = str(channel_id or "").strip()+ caps = self._client_capabilities_by_channel.get(channel_key)+ return dict(caps) if isinstance(caps, dict) else {}++ async def create_session(self, channel_id: str = "", session_id: str | None = None) -> str:"""创建会话.Args:@@ -103,6 +130,10 @@ class AgentManager:Returns:会话 ID"""+ explicit_session_id = str(session_id or "").strip()+ if explicit_session_id:+ logger.info("[AgentManager] session ensured: channel_id=%s session_id=%s", channel_id, explicit_session_id)+ return explicit_session_idif channel_id == "acp":session_id = f"acp_{uuid.uuid4().hex[:8]}"logger.info("[AgentManager] ACP session created: session_id=%s", session_id)@@ -124,7 +155,7 @@ class AgentManager:if agent_key not in self.agents:config: dict[str, Any] | None = Noneif channel_id == "acp":- config = {"agent_name": "acp_agent"}+ config = _build_acp_agent_config()await self._create_agent(agent_key, config)return self.agents.get(agent_key)@@ -149,4 +180,5 @@ class AgentManager:except Exception as e:logger.warning("[AgentManager] Agent cleanup failed: %s", e)del self.agents[key]+ self._client_capabilities_by_channel.clear()logger.info("[AgentManager] All agents cleaned up")diff --git a/jiuwenclaw/agentserver/agent_ws_server.py b/jiuwenclaw/agentserver/agent_ws_server.pyindex 1bd5af7bd0..4901397241 100644--- a/jiuwenclaw/agentserver/agent_ws_server.py+++ b/jiuwenclaw/agentserver/agent_ws_server.py@@ -12,6 +12,7 @@ from pathlib import Pathfrom typing import Any, ClassVarfrom jiuwenclaw.agentserver.gateway_push.wire import build_server_push_wire+from jiuwenclaw.agentserver.tools.acp_output_tools import get_acp_output_managerfrom jiuwenclaw.utils import get_agent_sessions_dir, get_config_filefrom jiuwenclaw.e2a.agent_compat import e2a_to_agent_requestfrom jiuwenclaw.e2a.gateway_normalize import (@@ -85,8 +86,31 @@ class AgentWebSocketServer:# 当前 Gateway 连接,用于 send_push 主动推送self._current_ws: Any = Noneself._current_send_lock: asyncio.Lock | None = None+ self._acp_client_capabilities_by_ws: dict[int, dict[str, Any]] = {}# AgentManager 实例self._agent_manager = AgentManager()+ get_acp_output_manager().set_send_push_callback(+ lambda msg: asyncio.create_task(self.send_push(msg))+ )++ @staticmethod+ def _ws_capabilities_key(ws: Any) -> int:+ return id(ws)++ def _set_ws_acp_client_capabilities(self, ws: Any, capabilities: dict[str, Any] | None) -> None:+ key = self._ws_capabilities_key(ws)+ if isinstance(capabilities, dict):+ self._acp_client_capabilities_by_ws[key] = dict(capabilities)+ else:+ self._acp_client_capabilities_by_ws.pop(key, None)++ def _get_ws_acp_client_capabilities(self, ws: Any) -> dict[str, Any]:+ key = self._ws_capabilities_key(ws)+ caps = self._acp_client_capabilities_by_ws.get(key)+ return dict(caps) if isinstance(caps, dict) else {}++ def _clear_ws_acp_client_capabilities(self, ws: Any) -> None:+ self._acp_client_capabilities_by_ws.pop(self._ws_capabilities_key(ws), None)@classmethoddef get_instance(@@ -202,6 +226,7 @@ class AgentWebSocketServer:finally:self._current_ws = Noneself._current_send_lock = None+ self._clear_ws_acp_client_capabilities(ws)if tasks:await asyncio.gather(*tasks, return_exceptions=True)@@ -258,6 +283,15 @@ class AgentWebSocketServer:try:from jiuwenclaw.schema.message import ReqMethod+ if request.channel_id == "acp" and request.req_method != ReqMethod.INITIALIZE:+ metadata = dict(request.metadata or {})+ ws_caps = self._get_ws_acp_client_capabilities(ws)+ metadata.setdefault(+ "acp_client_capabilities",+ ws_caps or self._agent_manager.get_client_capabilities("acp"),+ )+ request.metadata = metadata+await self._trigger_before_chat_request_hook(request)if request.req_method == ReqMethod.HISTORY_GET:@@ -355,6 +389,10 @@ class AgentWebSocketServer:await self._handle_session_create(ws, request, send_lock)return+ if request.req_method == ReqMethod.ACP_TOOL_RESPONSE:+ await self._handle_acp_tool_response(ws, request, send_lock)+ return+agent = await self._agent_manager.get_agent(channel_id=channel_id)if agent is None:raise ValueError("Failed to get agent")@@ -807,16 +845,22 @@ class AgentWebSocketServer:request: AgentRequestsend_lock: 发送锁"""- logger.info("[AgentServer] initialize: request_id=%s", request.request_id)+ logger.info("[AgentServer] initialize: request_id=%s channel_id=%s", request.request_id, request.channel_id)try:params = request.params if isinstance(request.params, dict) else {}client_capabilities = params.get("clientCapabilities", {})+ logger.info(+ "[AgentServer] initialize clientCapabilities: %s",+ client_capabilities,+ )extra_config = {"protocol_version": params.get("protocolVersion", "0.1.0"),"client_capabilities": client_capabilities,}+ if request.channel_id == "acp":+ self._set_ws_acp_client_capabilities(ws, client_capabilities)channel_id = request.channel_id or "default"capabilities = await self._agent_manager.initialize(@@ -866,7 +910,12 @@ class AgentWebSocketServer:try:channel_id = request.channel_id or "default"- session_id = await self._agent_manager.create_session(channel_id=channel_id)+ params = request.params if isinstance(request.params, dict) else {}+ explicit_session_id = params.get("session_id")+ session_id = await self._agent_manager.create_session(+ channel_id=channel_id,+ session_id=str(explicit_session_id).strip() if isinstance(explicit_session_id, str) else None,+ )resp = AgentResponse(request_id=request.request_id,@@ -891,3 +940,43 @@ class AgentWebSocketServer:wire = encode_agent_response_for_wire(resp, response_id=request.request_id)async with send_lock:await ws.send(json.dumps(wire, ensure_ascii=False))++ async def _handle_acp_tool_response(+ self,+ ws: Any,+ request: AgentRequest,+ send_lock: asyncio.Lock,+ ) -> None:+ params = request.params if isinstance(request.params, dict) else {}+ jsonrpc_id = params.get("jsonrpc_id")+ response_payload = params.get("response")+ if not isinstance(response_payload, dict):+ response_payload = {}++ if get_acp_output_manager().complete_jsonrpc_response(jsonrpc_id, response_payload):+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload={"accepted": True},+ )+ else:+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": f"unknown acp tool response id: {jsonrpc_id}"},+ )++ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)+ async with send_lock:+ await ws.send(json.dumps(wire, ensure_ascii=False))++ async def handle_acp_tool_response_for_test(+ self,+ ws: Any,+ request: AgentRequest,+ send_lock: asyncio.Lock,+ ) -> None:+ """Public test helper that delegates to ACP tool-response handling."""+ await self._handle_acp_tool_response(ws, request, send_lock)diff --git a/jiuwenclaw/agentserver/deep_agent/interface_deep.py b/jiuwenclaw/agentserver/deep_agent/interface_deep.pyindex 0ce2ee263f..4fd6f6e043 100644--- a/jiuwenclaw/agentserver/deep_agent/interface_deep.py+++ b/jiuwenclaw/agentserver/deep_agent/interface_deep.py@@ -78,6 +78,7 @@ from jiuwenclaw.agentserver.tools.multimodal_config import (from jiuwenclaw.agentserver.tools.video_tools import video_understandingfrom jiuwenclaw.agentserver.tools import SendFileToolkit+from jiuwenclaw.agentserver.tools.acp_output_tools import get_tools as get_acp_output_toolsfrom jiuwenclaw.agentserver.tools.multi_session_toolkits import MultiSessionToolkitfrom jiuwenclaw.agentserver.tools.xiaoyi_phone_tools import (get_user_location,@@ -137,6 +138,16 @@ _CRON_TOOL_MODE: ContextVar[str | None] = ContextVar(logger = logging.getLogger(__name__)+_ACP_BLOCKED_DEFAULT_TOOL_NAMES = frozenset(+ {+ "read_file",+ "write_file",+ "edit_file",+ "bash",+ "code",+ }+)+def _parse_int(value: Any, default: int) -> int:"""Parse integer-like values safely."""@@ -216,6 +227,7 @@ class JiuWenClawDeepAdapter:self._video_model_config: bool = Falseself._vision_tools: list[Any] = []self._audio_tools: list[Any] = []+ self._instance_overrides: dict[str, Any] = {}self._xiaoyi_phone_tools_registered: bool = Falseself._paid_search_registered: bool = Falseself._paid_search_tool: WebPaidSearchTool | None = None@@ -224,6 +236,25 @@ class JiuWenClawDeepAdapter:tool_scope=f"runtime_{id(self):x}",)+ @staticmethod+ def _is_acp_tool_profile(config: dict[str, Any] | None = None) -> bool:+ if not isinstance(config, dict):+ return False+ tool_profile = str(config.get("tool_profile") or "").strip().lower()+ if tool_profile:+ return tool_profile == "acp"+ channel_id = str(config.get("channel_id") or "").strip().lower()+ return channel_id == "acp"++ def _filesystem_rail_enabled_for_profile(self) -> bool:+ raw = self._instance_overrides.get("enable_filesystem_rail", True)+ return bool(raw)++ def _skill_include_tools_for_profile(self) -> bool:+ if self._is_acp_tool_profile(self._instance_overrides):+ return False+ return self._filesystem_rail is None+@staticmethoddef _resolve_prompt_channel(session_id: str | None = None) -> str:"""Resolve prompt channel from session id."""@@ -233,7 +264,7 @@ class JiuWenClawDeepAdapter:channel = session_id.split("_", 1)[0]if channel == "sess":return "web"- if channel in {"cron", "heartbeat", "feishu", "web"}:+ if channel in {"acp", "cron", "heartbeat", "feishu", "web"}:return channelreturn "web"@@ -760,9 +791,13 @@ class JiuWenClawDeepAdapter:def _build_runtime_prompt_rail(self) -> RuntimePromptRail | None:"""Build RuntimePromptRail for per-model-call time/channel injection."""try:+ default_channel = (+ "acp" if self._is_acp_tool_profile(self._instance_overrides)+ else self._resolve_prompt_channel()+ )rail = RuntimePromptRail(language=self._resolve_runtime_language(),- channel=self._resolve_prompt_channel(),+ channel=default_channel,)logger.info("[JiuWenClawDeepAdapter] RuntimePromptRail create success")except Exception as exc:@@ -784,9 +819,6 @@ class JiuWenClawDeepAdapter:rail_infos = [_RailBuildInfo("_runtime_prompt_rail", self._build_runtime_prompt_rail),- _RailBuildInfo("_filesystem_rail", self._build_filesystem_rail),- _RailBuildInfo("_skill_rail", self._build_skill_rail,- {"config": config, "include_tools": self._filesystem_rail is None}),_RailBuildInfo("_stream_event_rail", self._build_stream_event_rail),_RailBuildInfo("_task_planning_rail", self._build_task_planning_rail),_RailBuildInfo("_security_rail", self._build_security_rail),@@ -804,6 +836,19 @@ class JiuWenClawDeepAdapter:# MemoryRail 不在冷启动时挂载,由 _update_rails_for_mode 按 mode 按需注册/注销+ if self._filesystem_rail_enabled_for_profile():+ rail_infos.insert(1, _RailBuildInfo("_filesystem_rail", self._build_filesystem_rail))+ else:+ self._filesystem_rail = None+ rail_infos.insert(+ 2 if self._filesystem_rail_enabled_for_profile() else 1,+ _RailBuildInfo(+ "_skill_rail",+ self._build_skill_rail,+ {"config": config, "include_tools": self._skill_include_tools_for_profile()},+ ),+ )+rails_list = []for info in rail_infos:logger.info("[JiuWenClawDeepAdapter] Building rail: %s with params: %s", info.attr_name, info.params)@@ -844,7 +889,10 @@ class JiuWenClawDeepAdapter:system_prompt=build_identity_prompt(mode="agent",language=self._resolve_prompt_language(),- channel=self._resolve_prompt_channel(),+ channel=(+ "acp" if self._is_acp_tool_profile(self._instance_overrides)+ else self._resolve_prompt_channel()+ ),),enable_task_loop=config.get("enable_task_loop", True),max_iterations=config.get("max_iterations", 15),@@ -892,7 +940,13 @@ class JiuWenClawDeepAdapter:if _env_auto_scan is not None:self._skill_evolution_rail.auto_scan = _env_auto_scan.lower() in ("true", "1", "yes")- self._skill_rail = self._build_skill_rail(config, include_tools=self._filesystem_rail is None)+ self._skill_rail = self._build_skill_rail(+ config,+ include_tools=self._skill_include_tools_for_profile(),+ )++ if not self._filesystem_rail_enabled_for_profile():+ self._filesystem_rail = Noneself._update_permission_rail(config_base)@@ -1026,11 +1080,12 @@ class JiuWenClawDeepAdapter:"""await self.set_checkpoint()+ self._instance_overrides = dict(config or {}) if isinstance(config, dict) else {}config_base = get_config()self._refresh_multimodal_configs(config_base)config = config_base.get('react', {}).copy()self._config_cache = config.copy()- self._agent_name = config.get("agent_name", "main_agent")+ self._agent_name = self._instance_overrides.get("agent_name", config.get("agent_name", "main_agent"))model = self._create_model(config_base)agent_card = AgentCard(name=self._agent_name, id='jiuwenclaw')@@ -1051,7 +1106,10 @@ class JiuWenClawDeepAdapter:system_prompt=build_identity_prompt(mode="agent",language=self._resolve_prompt_language(),- channel=self._resolve_prompt_channel(),+ channel=(+ "acp" if self._is_acp_tool_profile(self._instance_overrides)+ else self._resolve_prompt_channel()+ ),),tools=tool_cards if tool_cards else [],subagents=browser_subagents,@@ -1137,11 +1195,18 @@ class JiuWenClawDeepAdapter:self._config_cache = config.copy()model = self._create_model(config_base)- self._agent_name = config.get("agent_name", "main_agent")+ self._agent_name = self._instance_overrides.get("agent_name", config.get("agent_name", "main_agent"))agent_card = AgentCard(name=self._agent_name, id='jiuwenclaw')self._sync_multimodal_tools_for_runtime()self._sync_paid_search_tool_for_runtime()+ if not self._filesystem_rail_enabled_for_profile() and self._filesystem_rail is not None:+ try:+ await self._instance.unregister_rail(self._filesystem_rail)+ except Exception as exc:+ logger.warning("[JiuWenClawDeepAdapter] ACP filesystem rail unregister failed: %s", exc)+ self._filesystem_rail = None+rails_list = self._get_current_agent_rails(config, config_base)# 加载用户自定义的 Rail 扩展@@ -1243,6 +1308,44 @@ class JiuWenClawDeepAdapter:self._skill_evolution_rail = Nonelogger.info("[JiuWenClawDeepAdapter] SkillEvolutionRail unregistered for agent mode")+ @staticmethod+ def _acp_runtime_tools_enabled(+ request_metadata: dict[str, Any] | None,+ ) -> tuple[bool, bool]:+ caps = (+ dict(request_metadata.get("acp_client_capabilities") or {})+ if isinstance(request_metadata, dict)+ else {}+ )+ logger.info(+ "[ACP] _acp_runtime_tools_enabled: metadata_keys=%s caps=%s",+ list((request_metadata or {}).keys()),+ caps,+ )++ fs_raw = caps.get("fs")+ if fs_raw is True:+ fs_enabled = True+ elif isinstance(fs_raw, dict):+ fs_enabled = bool(fs_raw.get("readTextFile") or fs_raw.get("writeTextFile"))+ else:+ fs_enabled = False++ terminal_raw = caps.get("terminal")+ if terminal_raw is True:+ terminal_enabled = True+ elif isinstance(terminal_raw, dict):+ terminal_enabled = bool(+ terminal_raw.get("create")+ or terminal_raw.get("output")+ or terminal_raw.get("waitForExit")+ or terminal_raw.get("release")+ )+ else:+ terminal_enabled = False++ return fs_enabled, terminal_enabled+async def _update_tools_for_mode(self, mode: str, session_id: str | None, request_id: str | None) -> None:"""按 mode 注册或卸载 multi-session 工具。"""if mode != "agent":@@ -1270,7 +1373,12 @@ class JiuWenClawDeepAdapter:except Exception as exc:logger.error("[JiuWenClawDeepAdapter] MultiSessionToolkit 注册失败: %s", exc)- async def _update_session_tools(self, session_id: str | None, request_id: str | None) -> None:+ async def _update_session_tools(+ self,+ session_id: str | None,+ request_id: str | None,+ channel_id: str | None = None,+ ) -> None:"""注册 cron 和 send_file 工具(与 mode 无关,每次请求刷新)。"""# 定时工具:按当前 session 的 channel 注册(contextvar 已由 _bind_runtime_cron_context 设置)if session_id not in ("heartbeat", "cron"):@@ -1285,7 +1393,7 @@ class JiuWenClawDeepAdapter:# send_file 工具:由 channels.<channel>.send_file_allowed 控制,每次请求重新注册# channel_id/metadata 由调用前的 _bind_runtime_cron_context 已写入 contextvarconfig_base = get_config()- channel = self._resolve_prompt_channel(session_id)+ channel = str(channel_id or self._resolve_prompt_channel(session_id) or "web").strip() or "web"send_file_enabled = config_base.get("channels", {}).get(channel, {}).get("send_file_allowed", False)if send_file_enabled and request_id and session_id:# 先卸载上一次请求遗留的 send_file 工具@@ -1302,6 +1410,76 @@ class JiuWenClawDeepAdapter:Runner.resource_mgr.add_tool(sf_tool)self._instance.ability_manager.add(sf_tool.card)+ def _refresh_acp_runtime_tools(+ self,+ session_id: str | None,+ request_id: str | None,+ channel_id: str | None,+ request_metadata: dict[str, Any] | None,+ ) -> None:+ """Refresh ACP tools for the current request based on client capabilities."""+ acp_tool_names = (+ "read_text_file",+ "write_text_file",+ "create_terminal",+ "read_terminal_output",+ "wait_for_terminal_exit",+ "release_terminal",+ )+ if channel_id == "acp":+ for existing in list(self._instance.ability_manager.list() or []):+ if getattr(existing, "name", "") in _ACP_BLOCKED_DEFAULT_TOOL_NAMES:+ self._instance.ability_manager.remove(existing.name)+ for existing in list(self._instance.ability_manager.list() or []):+ if getattr(existing, "name", "") in acp_tool_names:+ self._instance.ability_manager.remove(existing.name)++ fs_enabled, terminal_enabled = self._acp_runtime_tools_enabled(request_metadata)+ has_runtime_capability = fs_enabled or terminal_enabled+ can_register_acp_runtime_tools = self._should_register_acp_runtime_tools(+ channel_id=channel_id,+ request_id=request_id,+ session_id=session_id,+ has_runtime_capability=has_runtime_capability,+ )+ if can_register_acp_runtime_tools:+ for tool in get_acp_output_tools(session_id=session_id, request_id=request_id):+ if tool.card.name in {"read_text_file", "write_text_file"}:+ if not fs_enabled:+ continue+ elif not terminal_enabled:+ continue+ Runner.resource_mgr.add_tool(tool)+ self._instance.ability_manager.add(tool.card)++ if channel_id == "acp":+ ability_names = sorted(+ self._collect_registered_ability_names()+ )+ runtime_tool_candidates = (+ "read_text_file",+ "write_text_file",+ "create_terminal",+ "read_terminal_output",+ "wait_for_terminal_exit",+ "release_terminal",+ )+ acp_runtime_names = self._select_registered_runtime_tool_names(+ runtime_tool_candidates,+ ability_names,+ )+ logger.info(+ "[ACP] runtime tool snapshot: session_id=%s request_id=%s fs_enabled=%s terminal_enabled=%s "+ "acp_runtime_tools=%s ability_count=%d abilities=%s",+ session_id,+ request_id,+ fs_enabled,+ terminal_enabled,+ acp_runtime_names,+ len(ability_names),+ ability_names,+ )+def _update_prompt_for_mode(self, mode: str, resolved_language: str) -> None:"""同步 system_prompt_builder 的语言。"""if self._instance.system_prompt_builder is not None:@@ -1314,6 +1492,8 @@ class JiuWenClawDeepAdapter:session_id: str | None,mode: str = "plan",request_id: str | None = None,+ channel_id: str | None = None,+ request_metadata: dict[str, Any] | None = None,) -> None:"""Register per-request tools for current agent execution."""if self._instance is None:@@ -1322,13 +1502,47 @@ class JiuWenClawDeepAdapter:resolved_language = self._resolve_runtime_language()if self._runtime_prompt_rail:self._runtime_prompt_rail.set_language(resolved_language)- self._runtime_prompt_rail.set_channel(self._resolve_prompt_channel(session_id))+ resolved_channel = str(channel_id or self._resolve_prompt_channel(session_id) or "web").strip() or "web"+ self._runtime_prompt_rail.set_channel(resolved_channel)await self._update_rails_for_mode(mode)await self._update_tools_for_mode(mode, session_id, request_id)- await self._update_session_tools(session_id, request_id)+ await self._update_session_tools(session_id, request_id, channel_id=channel_id)+ self._refresh_acp_runtime_tools(session_id, request_id, channel_id, request_metadata)self._update_prompt_for_mode(mode, resolved_language)+ @staticmethod+ def _should_register_acp_runtime_tools(+ channel_id: str | None,+ request_id: str | None,+ session_id: str | None,+ has_runtime_capability: bool,+ ) -> bool:+ if channel_id != "acp":+ return False+ if not request_id or not session_id:+ return False+ return has_runtime_capability++ def _collect_registered_ability_names(self) -> set[str]:+ ability_names: set[str] = set()+ for card in self._instance.ability_manager.list() or []:+ ability_name = str(getattr(card, "name", "") or "").strip()+ if ability_name:+ ability_names.add(ability_name)+ return ability_names++ @staticmethod+ def _select_registered_runtime_tool_names(+ runtime_tool_candidates: tuple[str, ...],+ ability_names: set[str],+ ) -> list[str]:+ selected_names: list[str] = []+ for name in runtime_tool_candidates:+ if name in ability_names:+ selected_names.append(name)+ return selected_names+async def process_interrupt(self, request: AgentRequest) -> AgentResponse:"""处理 interrupt 请求.@@ -1850,7 +2064,13 @@ class JiuWenClawDeepAdapter:)token_cid = TOOL_PERMISSION_CHANNEL_ID.set((request.channel_id or "").strip())try:- await self._update_runtime_config(request.session_id, mode, request_id=request.request_id)+ await self._update_runtime_config(+ request.session_id,+ mode,+ request_id=request.request_id,+ channel_id=request.channel_id,+ request_metadata=request.metadata,+ )result = await Runner.run_agent(agent=self._instance, inputs=inputs)except asyncio.CancelledError:logger.info("[JiuWenClawDeepAdapter] Agent 任务被取消: request_id=%s session_id=%s", request.request_id,@@ -1946,7 +2166,13 @@ class JiuWenClawDeepAdapter:)token_cid = TOOL_PERMISSION_CHANNEL_ID.set((request.channel_id or "").strip())try:- await self._update_runtime_config(request.session_id, mode, request_id=request.request_id)+ await self._update_runtime_config(+ request.session_id,+ mode,+ request_id=request.request_id,+ channel_id=request.channel_id,+ request_metadata=request.metadata,+ )if self._stream_event_rail is not None:self._stream_event_rail.reset_abort()async for chunk in Runner.run_agent_streaming(self._instance, inputs):diff --git a/jiuwenclaw/agentserver/tools/acp_output_tools.py b/jiuwenclaw/agentserver/tools/acp_output_tools.pyindex 393fa24289..4773674fdd 100644--- a/jiuwenclaw/agentserver/tools/acp_output_tools.py+++ b/jiuwenclaw/agentserver/tools/acp_output_tools.py@@ -7,6 +7,7 @@ ACP 输出工具:AgentServer 向 IDE 发送请求。from __future__ import annotationsimport asyncio+import inspectimport loggingimport uuidfrom dataclasses import dataclass@@ -63,6 +64,68 @@ class AcpOutputManager:def set_send_push_callback(self, callback: Any) -> None:self._send_push_callback = callback+ def reset_state(self) -> None:+ """Reset runtime state.++ Intended for unit tests and controlled lifecycle cleanup.+ """+ self._pending.clear()+ self._jsonrpc_counter = 0++ def add_pending_request(self, request: AcpOutputRequest) -> None:+ """Register a pending request explicitly.++ Used by tests to seed pending state without touching protected members.+ """+ self._pending[str(request.jsonrpc_id)] = request++ def complete_jsonrpc_response(+ self,+ jsonrpc_id: str | int | None,+ response: dict[str, Any],+ ) -> bool:+ """Complete a pending ACP JSON-RPC request."""+ jsonrpc_key = str(jsonrpc_id or "").strip()+ if not jsonrpc_key:+ return False++ pending = self._pending.pop(jsonrpc_key, None)+ if pending is None:+ logger.warning(+ "[AcpOutput] completion dropped: jsonrpc_id=%s pending_keys=%s",+ jsonrpc_key,+ list(self._pending.keys()),+ )+ return False++ if pending.future.done():+ return False++ pending.future.set_result(dict(response or {}))+ logger.info(+ "[AcpOutput] request completed: jsonrpc_id=%s method=%s",+ jsonrpc_key,+ pending.method,+ )+ return True++ def fail_jsonrpc_response(+ self,+ jsonrpc_id: str | int | None,+ exc: BaseException,+ ) -> bool:+ jsonrpc_key = str(jsonrpc_id or "").strip()+ if not jsonrpc_key:+ return False++ pending = self._pending.pop(jsonrpc_key, None)+ if pending is None:+ return False+ if pending.future.done():+ return False+ pending.future.set_exception(exc)+ return True+async def send_jsonrpc_request(self,method: str,@@ -140,7 +203,9 @@ class AcpOutputManager:push_msg["payload"] = push_msg["body"]try:- self._send_push_callback(push_msg)+ callback_result = self._send_push_callback(push_msg)+ if inspect.isawaitable(callback_result):+ await callback_resultexcept Exception as exc:self._pending.pop(jsonrpc_id, None)raise RuntimeError(f"Failed to send ACP output request: {exc}") from exc@@ -482,3 +547,4 @@ def get_tools(session_id: str = "", request_id: str = "") -> List["Tool"]:func=release_terminal_bound,),]+diff --git a/jiuwenclaw/app_gateway.py b/jiuwenclaw/app_gateway.pyindex 3902bd0743..6d18bf86fc 100644--- a/jiuwenclaw/app_gateway.py+++ b/jiuwenclaw/app_gateway.py@@ -19,6 +19,7 @@ import loggingimport osimport sysimport time+import uuid as uuid_modulefrom dataclasses import dataclassfrom typing import Anyfrom urllib.parse import urlparse@@ -182,6 +183,7 @@ class GatewayServer:self._clients: set[Any] = set()self._request_to_client: dict[str, Any] = {}self._session_to_client: dict[str, Any] = {}+ self._pending_client_rpc_session_by_id: dict[str, tuple[str, Any]] = {}@propertydef channel_id(self) -> str:@@ -221,6 +223,7 @@ class GatewayServer:self._clients.clear()self._request_to_client.clear()self._session_to_client.clear()+ self._pending_client_rpc_session_by_id.clear()if self._server is not None:self._server.close()await self._server.wait_closed()@@ -234,6 +237,20 @@ class GatewayServer:if ws is None or bool(getattr(ws, "closed", False)):return+ if (+ msg.type == "event"+ and isinstance(msg.payload, dict)+ and str(msg.payload.get("event_type") or "").strip() == "acp.output_request"+ ):+ raw_jsonrpc = msg.payload.get("jsonrpc")+ if isinstance(raw_jsonrpc, dict):+ jsonrpc_id = str(raw_jsonrpc.get("id") or "").strip()+ session_id = str(msg.session_id or "").strip()+ if jsonrpc_id and session_id:+ self._pending_client_rpc_session_by_id[jsonrpc_id] = (session_id, ws)+ await ws.send(json.dumps(raw_jsonrpc, ensure_ascii=False))+ return+if msg.type == "res":payload = dict(msg.payload or {}) if isinstance(msg.payload, dict) else {}frame: dict[str, Any] = {@@ -280,6 +297,67 @@ class GatewayServer:stale_session_ids = [session_id for session_id, client in self._session_to_client.items() if client is ws]for session_id in stale_session_ids:self._session_to_client.pop(session_id, None)+ stale_jsonrpc_ids = [+ jsonrpc_id+ for jsonrpc_id, (_, client) in self._pending_client_rpc_session_by_id.items()+ if client is ws+ ]+ for jsonrpc_id in stale_jsonrpc_ids:+ self._pending_client_rpc_session_by_id.pop(jsonrpc_id, None)++ @staticmethod+ def _is_jsonrpc_response(data: dict[str, Any]) -> bool:+ return (+ isinstance(data, dict)+ and str(data.get("jsonrpc") or "").strip() == "2.0"+ and str(data.get("id") or "").strip() != ""+ and ("result" in data or "error" in data)+ )++ async def _handle_jsonrpc_response(self, ws: Any, data: dict[str, Any]) -> None:+ from jiuwenclaw.schema.message import Message, ReqMethod++ jsonrpc_id = str(data.get("id") or "").strip()+ pending = self._pending_client_rpc_session_by_id.pop(jsonrpc_id, None)+ session_id = ""+ if isinstance(pending, tuple) and len(pending) == 2:+ session_id = str(pending[0] or "").strip()++ if not jsonrpc_id or not session_id:+ await ws.send(+ json.dumps(+ {+ "type": "res",+ "id": jsonrpc_id,+ "ok": False,+ "error": f"unknown acp tool response id: {jsonrpc_id}",+ },+ ensure_ascii=False,+ )+ )+ return++ msg = Message(+ id=f"acp_tool_resp_{uuid_module.uuid4().hex[:12]}",+ type="req",+ channel_id=self.channel_id,+ session_id=session_id,+ params={+ "jsonrpc_id": jsonrpc_id,+ "response": dict(data),+ "session_id": session_id,+ },+ timestamp=time.time(),+ ok=True,+ req_method=ReqMethod.ACP_TOOL_RESPONSE,+ is_stream=False,+ metadata={"acp": {"jsonrpc_id": jsonrpc_id, "kind": "tool_response"}},+ )+ if self._on_message_cb is None:+ return+ result = self._on_message_cb(msg)+ if asyncio.iscoroutine(result):+ await resultasync def _handle_raw_message(self, ws: Any, raw: str) -> None:from jiuwenclaw.schema.message import Message, Mode, ReqMethod@@ -295,6 +373,10 @@ class GatewayServer:)return+ if self._is_jsonrpc_response(data):+ await self._handle_jsonrpc_response(ws, data)+ return+if not isinstance(data, dict) or data.get("type") != "req":await ws.send(json.dumps(@@ -532,10 +614,9 @@ async def _run(from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fieldsfrom jiuwenclaw.schema.message import ReqMethod- import uuidreload_env = e2a_from_agent_fields(- request_id=f"agent-reload-{uuid.uuid4().hex[:8]}",+ request_id=f"agent-reload-{uuid_module.uuid4().hex[:8]}",channel_id="",req_method=ReqMethod.AGENT_RELOAD_CONFIG,params={@@ -549,7 +630,7 @@ async def _run(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]}",+ request_id=f"browser-restart-{uuid_module.uuid4().hex[:8]}",channel_id="",req_method=ReqMethod.BROWSER_RUNTIME_RESTART,)diff --git a/jiuwenclaw/app_web_handlers.py b/jiuwenclaw/app_web_handlers.pyindex acc8b73fd4..fe468034c4 100644--- a/jiuwenclaw/app_web_handlers.py+++ b/jiuwenclaw/app_web_handlers.py@@ -66,6 +66,9 @@ class _DummyBus:# 仅转发到 Agent 的 Web method_FORWARD_REQ_METHODS = frozenset({+ "initialize",+ "session.create",+ "acp.tool_response","chat.send","chat.interrupt","chat.resume",@@ -101,6 +104,9 @@ _FORWARD_REQ_METHODS = frozenset({})_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset({+ "initialize",+ "session.create",+ "acp.tool_response","browser.start","skills.marketplace.list","skills.list",diff --git a/jiuwenclaw/channel/acp_channel.py b/jiuwenclaw/channel/acp_channel.pyindex e5e86b6d98..f25e5bc45d 100644--- a/jiuwenclaw/channel/acp_channel.py+++ b/jiuwenclaw/channel/acp_channel.py@@ -80,6 +80,7 @@ class AcpChannel(BaseChannel):self._request_ctx: dict[str, _AcpRequestContext] = {}self._session_ctx: dict[str, dict[str, Any]] = {}self._active_prompt_request_by_session: dict[str, str] = {}+ self._pending_client_rpc_session_by_id: dict[str, str] = {}@propertydef channel_id(self) -> str:@@ -98,7 +99,7 @@ class AcpChannel(BaseChannel):stdin_eof_since: float | None = Nonewhile self._running:if stdin_eof:- if not self._request_ctx and stdin_eof_since is not None:+ if not self._request_ctx and not self._pending_client_rpc_session_by_id and stdin_eof_since is not None:if (time.time() - stdin_eof_since) >= _STDIN_EOF_GRACE_SECONDS:breakawait asyncio.sleep(0.05)@@ -136,6 +137,7 @@ class AcpChannel(BaseChannel):self._running = Falsefor request_id in list(self._request_ctx.keys()):await self._clear_request_context(request_id)+ self._pending_client_rpc_session_by_id.clear()await self._close_gateway_connection()async def send(self, msg: Message) -> None:@@ -162,6 +164,9 @@ class AcpChannel(BaseChannel):if self._is_jsonrpc_request(data):await self._handle_jsonrpc_request(data)return+ if self._is_jsonrpc_response(data):+ await self._handle_jsonrpc_response(data)+ returnenv = self._parse_envelope(data)msg = self._envelope_to_message(env)@@ -174,6 +179,30 @@ class AcpChannel(BaseChannel):await self._dispatch_message(msg)+ async def _handle_jsonrpc_response(self, data: dict[str, Any]) -> None:+ jsonrpc_id = str(data.get("id") or "").strip()+ if not jsonrpc_id:+ return++ session_id = self._pending_client_rpc_session_by_id.pop(jsonrpc_id, None)+ msg = Message(+ id=f"acp_tool_resp_{uuid.uuid4().hex[:12]}",+ type="req",+ channel_id=self.channel_id,+ session_id=session_id,+ params={+ "jsonrpc_id": jsonrpc_id,+ "response": dict(data),+ "session_id": session_id,+ },+ timestamp=time.time(),+ ok=True,+ req_method=ReqMethod.ACP_TOOL_RESPONSE,+ is_stream=False,+ metadata={"acp": {"jsonrpc_id": jsonrpc_id, "kind": "tool_response"}},+ )+ await self._dispatch_message(msg)+def _parse_envelope(self, data: dict[str, Any]) -> E2AEnvelope:env = E2AEnvelope.from_dict(dict(data))if not env.request_id:@@ -376,6 +405,7 @@ class AcpChannel(BaseChannel):try:if method == "initialize":await self._write_jsonrpc_result(rpc_id, self._initialize_result())+ await self._notify_agent_initialize(params)returnif method == "session/new":await self._handle_jsonrpc_session_new(rpc_id, params)@@ -399,6 +429,24 @@ class AcpChannel(BaseChannel):logger.exception("[ACP] jsonrpc request failed: %s", exc)await self._write_jsonrpc_error(rpc_id, -32603, str(exc))+ async def _notify_agent_initialize(self, params: dict[str, Any]) -> None:+ msg = Message(+ id=f"acp_init_{uuid.uuid4().hex[:12]}",+ type="req",+ channel_id=self.channel_id,+ session_id=self.config.default_session_id,+ params=dict(params),+ timestamp=time.time(),+ ok=True,+ req_method=ReqMethod.INITIALIZE,+ is_stream=False,+ metadata={"acp": {"method": "initialize"}},+ )+ try:+ await self._dispatch_message(msg)+ except Exception:+ logger.debug("[ACP] failed to forward initialize to gateway", exc_info=True)+def _initialize_result(self) -> dict[str, Any]:return {"protocolVersion": _ACP_PROTOCOL_VERSION,@@ -417,6 +465,16 @@ class AcpChannel(BaseChannel):"sessionCapabilities": {"list": {},},+ "fs": {+ "readTextFile": True,+ "writeTextFile": True,+ },+ "terminal": {+ "create": True,+ "output": True,+ "waitForExit": True,+ "release": True,+ },},"authMethods": [],}@@ -715,6 +773,16 @@ class AcpChannel(BaseChannel):and isinstance(data.get("method"), str))+ @staticmethod+ def _is_jsonrpc_response(data: Any) -> bool:+ return (+ isinstance(data, dict)+ and data.get("jsonrpc") == "2.0"+ and "id" in data+ and not isinstance(data.get("method"), str)+ and ("result" in data or "error" in data)+ )+@staticmethoddef _extract_prompt_text(params: dict[str, Any]) -> str:prompt = params.get("prompt")@@ -827,6 +895,10 @@ class AcpChannel(BaseChannel):if not isinstance(data, dict):return+ if self._is_jsonrpc_request(data):+ await self._handle_gateway_jsonrpc_request(data)+ return+frame_type = str(data.get("type") or "").strip()if frame_type == "res":msg = self._message_from_gateway_response(data)@@ -838,6 +910,27 @@ class AcpChannel(BaseChannel):if msg is not None:await self.send(msg)+ def set_pending_client_rpc_session_for_test(self, jsonrpc_id: str, session_id: str) -> None:+ """Public test helper to seed ACP client RPC session mappings."""+ self._pending_client_rpc_session_by_id[jsonrpc_id] = session_id++ def get_pending_client_rpc_session_for_test(self, jsonrpc_id: str) -> str | None:+ """Public test helper to inspect ACP client RPC session mappings."""+ return self._pending_client_rpc_session_by_id.get(jsonrpc_id)++ async def handle_gateway_frame_for_test(self, data: dict[str, Any]) -> None:+ """Public test helper that delegates to gateway frame handling."""+ await self._handle_gateway_frame(data)++ async def _handle_gateway_jsonrpc_request(self, data: dict[str, Any]) -> None:+ jsonrpc_id = str(data.get("id") or "").strip()+ params = data.get("params") if isinstance(data.get("params"), dict) else {}+ session_id = str(params.get("sessionId") or params.get("session_id") or "").strip()+ if jsonrpc_id and session_id:+ self._pending_client_rpc_session_by_id[jsonrpc_id] = session_id+ _ACP_STDOUT.buffer.write((json.dumps(data, ensure_ascii=False) + "\n").encode("utf-8"))+ _ACP_STDOUT.buffer.flush()+def _message_from_gateway_response(self, data: dict[str, Any]) -> Message | None:request_id = str(data.get("id") or "").strip()if not request_id:diff --git a/jiuwenclaw/e2a/gateway_normalize.py b/jiuwenclaw/e2a/gateway_normalize.pyindex b360f969b9..d052f75792 100644--- a/jiuwenclaw/e2a/gateway_normalize.py+++ b/jiuwenclaw/e2a/gateway_normalize.py@@ -9,6 +9,7 @@ import loggingfrom typing import TYPE_CHECKING, Anyfrom jiuwenclaw.e2a.constants import (+ E2A_RESPONSE_KIND_ACP_OUTPUT_REQUEST,E2A_RESPONSE_KIND_CRON,E2A_RESPONSE_KIND_E2A_CHUNK,E2A_RESPONSE_KIND_E2A_COMPLETE,@@ -516,6 +517,17 @@ def e2a_response_to_agent_chunk(e2a: E2AResponse) -> "AgentResponseChunk":is_complete=True,)+ if kind == E2A_RESPONSE_KIND_ACP_OUTPUT_REQUEST:+ return AgentResponseChunk(+ request_id=rid,+ channel_id=ch,+ payload={+ "event_type": "acp.output_request",+ "jsonrpc": dict(body),+ },+ is_complete=True,+ )+raise ValueError(f"e2a_response_to_agent_chunk: unsupported response_kind={kind!r} is_final={e2a.is_final!r}")diff --git a/jiuwenclaw/gateway/message_handler.py b/jiuwenclaw/gateway/message_handler.pyindex 40518cdd1a..4366b602da 100644--- a/jiuwenclaw/gateway/message_handler.py+++ b/jiuwenclaw/gateway/message_handler.py@@ -9,7 +9,7 @@ import asyncioimport secretsimport timefrom abc import ABC, abstractmethod-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom enum import Enumfrom typing import TYPE_CHECKING, Any, Dictfrom jiuwenclaw.channel.base import ChannelType@@ -20,6 +20,22 @@ from jiuwenclaw.schema.hooks_context import GatewayChatHookContextlogger = logging.getLogger(__name__)+_ACP_CHANNEL_ID = "acp"+_ACP_ORIGINAL_SESSION_ID_KEY = "acp_original_session_id"+_KNOWN_JIUWENCLAW_SESSION_PREFIXES = (+ "sess_",+ "acp_",+ "cron_",+ "feishu_",+ "wechat_",+ "xiaoyi_",+ "dingtalk_",+ "wecom_",+ "telegram_",+ "discord_",+ "whatsapp_",+)+class ChannelMode(str, Enum):@@ -75,6 +91,8 @@ class MessageHandler(ABC):self._pending_evolution_approval: dict[str, str] = {} # session_id -> approval_request_idself._queued_supplement_input: dict[str, str] = {} # session_id -> queued_new_inputself._session_evolution_in_progress: set[str] = set()+ self._acp_session_aliases: dict[str, str] = {} # external_session_id -> internal_session_id+ self._acp_session_alias_lock = asyncio.Lock()# per-channel 控制状态:支持 \new_session / \mode 指令。# 使用 ChannelType 的 value 作为标准键,避免散落的硬编码字符串。@@ -403,6 +421,118 @@ class MessageHandler(ABC):except asyncio.TimeoutError:return None+ @staticmethod+ def _is_session_map_style_session_id(session_id: str) -> bool:+ parts = [part.strip() for part in str(session_id or "").split("::")]+ if len(parts) not in (5, 6):+ return False+ return all(parts)++ @classmethod+ def _is_known_jiuwenclaw_session_id(cls, session_id: str | None) -> bool:+ sid = str(session_id or "").strip()+ if not sid:+ return False+ if sid.startswith(_KNOWN_JIUWENCLAW_SESSION_PREFIXES):+ return True+ return cls._is_session_map_style_session_id(sid)++ async def _ensure_acp_agent_session(self, session_id: str) -> str:+ from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields+ from jiuwenclaw.schema.message import ReqMethod++ env = e2a_from_agent_fields(+ request_id=f"acp-session-create-{int(time.time() * 1000):x}-{secrets.token_hex(3)}",+ channel_id=_ACP_CHANNEL_ID,+ session_id=session_id,+ req_method=ReqMethod.SESSION_CREATE,+ params={"session_id": session_id},+ is_stream=False,+ timestamp=time.time(),+ )+ resp = await self._agent_client.send_request(env)+ if not resp.ok:+ payload = dict(resp.payload or {}) if isinstance(resp.payload, dict) else {}+ raise RuntimeError(str(payload.get("error") or "acp session.create failed"))+ payload = dict(resp.payload or {}) if isinstance(resp.payload, dict) else {}+ resolved = payload.get("sessionId") or payload.get("session_id") or session_id+ resolved_str = str(resolved or "").strip()+ if not resolved_str:+ raise RuntimeError("acp session.create returned empty session_id")+ return resolved_str++ async def _resolve_acp_internal_session_id(+ self,+ external_session_id: str | None,+ ) -> tuple[str | None, bool]:+ external = str(external_session_id or "").strip()+ if not external:+ return None, False++ cached = self._acp_session_aliases.get(external)+ if cached:+ return cached, cached != external++ async with self._acp_session_alias_lock:+ cached = self._acp_session_aliases.get(external)+ if cached:+ return cached, cached != external++ desired = (+ external+ if self._is_known_jiuwenclaw_session_id(external)+ else self._generate_channel_session_id(_ACP_CHANNEL_ID)+ )+ ensured = await self._ensure_acp_agent_session(desired)+ self._acp_session_aliases[external] = ensured+ return ensured, ensured != external++ async def _prepare_agent_dispatch_message(self, msg: "Message") -> "Message":+ from jiuwenclaw.schema.message import ReqMethod++ if msg.channel_id != _ACP_CHANNEL_ID:+ return msg+ if msg.req_method in (ReqMethod.INITIALIZE, ReqMethod.SESSION_CREATE):+ return msg++ internal_session_id, aliased = await self._resolve_acp_internal_session_id(msg.session_id)+ if not internal_session_id:+ return msg++ params = dict(msg.params or {})+ params["session_id"] = internal_session_id++ metadata = dict(msg.metadata or {})+ if aliased:+ metadata.setdefault(_ACP_ORIGINAL_SESSION_ID_KEY, str(msg.session_id or ""))++ return replace(+ msg,+ session_id=internal_session_id,+ params=params,+ metadata=metadata or None,+ )++ def _resolve_acp_external_session_id(+ self,+ session_id: str | None,+ metadata: dict[str, Any] | None = None,+ ) -> str | None:+ sid = str(session_id or "").strip()+ if not sid:+ return None++ original = ""+ if isinstance(metadata, dict):+ original = str(metadata.get(_ACP_ORIGINAL_SESSION_ID_KEY) or "").strip()+ if original:+ return original++ for external, internal in self._acp_session_aliases.items():+ if internal == sid:+ return external+ return sid+@staticmethoddef message_to_e2a(msg: "Message") -> "E2AEnvelope":from jiuwenclaw.e2a.gateway_normalize import message_to_e2a_or_fallback@@ -500,6 +630,8 @@ class MessageHandler(ABC):bus_metadata: dict[str, Any] | None = bus_md if bus_md else Noneelse:bus_metadata = None+ if chunk.channel_id == _ACP_CHANNEL_ID:+ session_id = self._resolve_acp_external_session_id(session_id, bus_metadata)if isinstance(chunk.payload, dict) and chunk.payload.get("event_type") == "cron.response":await self._handle_cron_push_payload(payload=dict(chunk.payload),@@ -509,6 +641,12 @@ class MessageHandler(ABC):metadata=bus_metadata,)return+ if self._is_terminal_stream_chunk(chunk):+ logger.debug(+ "[MessageHandler] 忽略 server_push 终止 chunk: request_id=%s",+ chunk.request_id,+ )+ returnout = self._chunk_to_message(chunk, session_id=session_id, metadata=bus_metadata@@ -614,6 +752,24 @@ class MessageHandler(ABC):metadata=metadata,)+ @staticmethod+ def _is_terminal_stream_chunk(chunk: AgentResponseChunk) -> bool:+ """识别仅用于结束流的哨兵 chunk,避免被当作业务事件继续下发。"""+ if not bool(getattr(chunk, "is_complete", False)):+ return False+ payload = getattr(chunk, "payload", None)+ if not payload:+ return True+ if not isinstance(payload, dict):+ return False+ if payload.get("event_type"):+ return False+ if payload.get("content") not in (None, ""):+ return False+ if payload.get("error") not in (None, ""):+ return False+ return payload.get("is_complete") is True and set(payload.keys()) <= {"is_complete"}+@staticmethoddef _non_stream_rpc_may_run_parallel(env: "E2AEnvelope") -> bool:"""可与其它非流式 RPC 并发,不阻塞 _forward_loop。@@ -780,7 +936,8 @@ class MessageHandler(ABC):# 检查是否是中断请求if msg.req_method == ReqMethod.CHAT_ANSWER:# 先正常转发用户审批答案,再按会话自动派发排队的新输入- env = self.message_to_e2a(msg)+ agent_msg = await self._prepare_agent_dispatch_message(msg)+ env = self.message_to_e2a(agent_msg)await self._process_non_stream_request(msg, env)answer_request_id = (msg.params or {}).get("request_id")if self._is_evolution_approval_request_id(answer_request_id):@@ -852,12 +1009,13 @@ class MessageHandler(ABC):# 用 await 确保 agent 侧先完成取消再启动新任务from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields+ agent_msg = await self._prepare_agent_dispatch_message(msg)supplement_env = e2a_from_agent_fields(request_id=f"supplement_{int(time.time() * 1000):x}",channel_id=msg.channel_id,- session_id=msg.session_id,+ session_id=agent_msg.session_id,req_method=ReqMethod.CHAT_CANCEL,- params={"intent": "supplement"},+ params={"intent": "supplement", "session_id": agent_msg.session_id},is_stream=False,timestamp=time.time(),)@@ -911,12 +1069,14 @@ class MessageHandler(ABC):rid, msg.channel_id, sid, "cancel",)# Fire-and-forget: 发送取消请求到 AgentServer- env_interrupt = self.message_to_e2a(msg)+ agent_msg = await self._prepare_agent_dispatch_message(msg)+ env_interrupt = self.message_to_e2a(agent_msg)asyncio.create_task(self._send_interrupt_to_agent(env_interrupt))elif intent in ("pause", "resume"):# 暂停/恢复:不取消流式任务,转发给 AgentServer 处理 ReAct 循环- env_interrupt = self.message_to_e2a(msg)+ agent_msg = await self._prepare_agent_dispatch_message(msg)+ env_interrupt = self.message_to_e2a(agent_msg)asyncio.create_task(self._send_interrupt_to_agent(env_interrupt))# 通知前端状态变更await self._send_interrupt_result_notification(@@ -929,8 +1089,9 @@ class MessageHandler(ABC):"[MessageHandler] 从 user_messages 取出,发往 AgentServer: id=%s channel_id=%s is_stream=%s",msg.id, msg.channel_id, msg.is_stream,)- await self._trigger_before_chat_request_hook(msg)- env = self.message_to_e2a(msg)+ agent_msg = await self._prepare_agent_dispatch_message(msg)+ await self._trigger_before_chat_request_hook(agent_msg)+ env = self.message_to_e2a(agent_msg)stream_rid = env.request_id or msg.idtry:if env.is_stream:@@ -992,7 +1153,7 @@ class MessageHandler(ABC):try:async for chunk in self._agent_client.send_request_stream(env):# 跳过终止 chunk(仅作为流结束信号,不含实际数据)- if chunk.is_complete and not chunk.payload:+ if self._is_terminal_stream_chunk(chunk):logger.debug("[MessageHandler] 跳过终止 chunk: request_id=%s",chunk.request_id,diff --git a/jiuwenclaw/schema/message.py b/jiuwenclaw/schema/message.pyindex 624a35ff59..a81b003681 100644--- a/jiuwenclaw/schema/message.py+++ b/jiuwenclaw/schema/message.py@@ -9,6 +9,7 @@ from typing import Any, Literalclass ReqMethod(Enum):INITIALIZE = "initialize"+ ACP_TOOL_RESPONSE = "acp.tool_response"CHAT_SEND = "chat.send"CHAT_RESUME = "chat.resume"diff --git a/tests/unit_tests/agentserver/test_agentserver_acp.py b/tests/unit_tests/agentserver/test_agentserver_acp.pyindex 839706a6cf..e8f8ae00ec 100644--- a/tests/unit_tests/agentserver/test_agentserver_acp.py+++ b/tests/unit_tests/agentserver/test_agentserver_acp.py@@ -5,7 +5,9 @@ import pytestfrom jiuwenclaw.agentserver import agent_ws_server as agent_ws_server_modulefrom jiuwenclaw.agentserver.agent_manager import ACP_DEFAULT_CAPABILITIES+from jiuwenclaw.agentserver.tools.acp_output_tools import AcpOutputRequest, get_acp_output_managerfrom jiuwenclaw.agentserver.deep_agent import interface_deep as interface_deep_module+from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fieldsfrom jiuwenclaw.schema.agent import AgentRequestfrom jiuwenclaw.schema.message import ReqMethod@@ -19,9 +21,10 @@ class FakeWebSocket:class FakeAgentManager:- def __init__(self, *, capabilities=None, session_id="sess-created"):+ def __init__(self, *, capabilities=None, session_id="sess-created", client_capabilities=None):self.capabilities = capabilitiesself.session_id = session_id+ self.client_capabilities = client_capabilities or {}self.initialize_calls = []self.create_session_calls = []@@ -31,9 +34,12 @@ class FakeAgentManager:)return self.capabilities- async def create_session(self, channel_id=""):- self.create_session_calls.append(channel_id)- return self.session_id+ async def create_session(self, channel_id="", session_id=None):+ self.create_session_calls.append({"channel_id": channel_id, "session_id": session_id})+ return session_id or self.session_id++ def get_client_capabilities(self, channel_id=""):+ return dict(self.client_capabilities)class FakeJiuClawContextEngineeringRail:@@ -52,6 +58,9 @@ class AgentWebSocketServerHarness(agent_ws_server_module.AgentWebSocketServer):async def handle_session_create_for_test(self, ws, request, send_lock):await self._handle_session_create(ws, request, send_lock)+ async def handle_message_for_test(self, ws, raw, send_lock):+ await self._handle_message(ws, raw, send_lock)+class DeepAdapterHarness(interface_deep_module.JiuWenClawDeepAdapter):def build_context_engineering_rail_for_test(self, config):@@ -66,6 +75,16 @@ def fake_encode_agent_response_for_wire(resp, response_id):}[email protected](autouse=True)+def _reset_acp_output_manager():+ mgr = get_acp_output_manager()+ mgr.reset_state()+ mgr.set_send_push_callback(None)+ yield+ mgr.reset_state()+ mgr.set_send_push_callback(None)++@pytest.mark.asyncioasync def test_handle_initialize_uses_agent_manager_capabilities(monkeypatch):server = AgentWebSocketServerHarness()@@ -162,7 +181,7 @@ async def test_handle_session_create_returns_session_id(monkeypatch):await server.handle_session_create_for_test(fake_ws, request, asyncio.Lock())- assert fake_manager.create_session_calls == ["acp"]+ assert fake_manager.create_session_calls == [{"channel_id": "acp", "session_id": None}]assert fake_ws.sent == [{"response_id": "req-session-create",@@ -172,6 +191,144 @@ async def test_handle_session_create_returns_session_id(monkeypatch):]+async def test_handle_session_create_returns_explicit_session_id(monkeypatch):+ server = AgentWebSocketServerHarness()+ fake_manager = FakeAgentManager(session_id="unused-default")+ server.set_agent_manager_for_test(fake_manager)+ fake_ws = FakeWebSocket()++ monkeypatch.setattr(+ agent_ws_server_module,+ "encode_agent_response_for_wire",+ fake_encode_agent_response_for_wire,+ )++ request = AgentRequest(+ request_id="req-session-create-explicit",+ channel_id="acp",+ req_method=ReqMethod.SESSION_CREATE,+ params={"session_id": "sess_explicit_001"},+ )++ await server.handle_session_create_for_test(fake_ws, request, asyncio.Lock())++ assert fake_manager.create_session_calls == [+ {"channel_id": "acp", "session_id": "sess_explicit_001"}+ ]+ assert fake_ws.sent == [+ {+ "response_id": "req-session-create-explicit",+ "payload": {"sessionId": "sess_explicit_001"},+ "ok": True,+ }+ ]+++async def test_handle_acp_tool_response_completes_pending_future(monkeypatch):+ server = AgentWebSocketServerHarness()+ fake_ws = FakeWebSocket()+ mgr = get_acp_output_manager()+ future: asyncio.Future[dict] = asyncio.get_running_loop().create_future()+ mgr.add_pending_request(AcpOutputRequest(+ jsonrpc_id="42",+ method="fs/read_text_file",+ params={"path": "workspace/demo.txt"},+ future=future,+ request_id="req-pending",+ ))++ monkeypatch.setattr(+ agent_ws_server_module,+ "encode_agent_response_for_wire",+ fake_encode_agent_response_for_wire,+ )++ request = AgentRequest(+ request_id="req-acp-tool-response",+ channel_id="acp",+ req_method=ReqMethod.ACP_TOOL_RESPONSE,+ params={+ "jsonrpc_id": "42",+ "response": {+ "jsonrpc": "2.0",+ "id": "42",+ "result": {"content": "hello"},+ },+ },+ )++ await server.handle_acp_tool_response_for_test(fake_ws, request, asyncio.Lock())++ assert future.done() is True+ assert future.result() == {+ "jsonrpc": "2.0",+ "id": "42",+ "result": {"content": "hello"},+ }+ assert fake_ws.sent == [+ {+ "response_id": "req-acp-tool-response",+ "payload": {"accepted": True},+ "ok": True,+ }+ ]+++async def test_handle_message_uses_ws_scoped_acp_client_capabilities(monkeypatch):+ ws_a = FakeWebSocket()+ ws_b = FakeWebSocket()+ server = AgentWebSocketServerHarness()+ fake_manager = FakeAgentManager(+ capabilities=ACP_DEFAULT_CAPABILITIES,+ client_capabilities={"fs": {"readTextFile": True}},+ )+ server.set_agent_manager_for_test(fake_manager)++ monkeypatch.setattr(+ agent_ws_server_module,+ "encode_agent_response_for_wire",+ fake_encode_agent_response_for_wire,+ )++ init_request_a = AgentRequest(+ request_id="req-init-a",+ channel_id="acp",+ req_method=ReqMethod.INITIALIZE,+ params={"clientCapabilities": {"fs": {"readTextFile": True}}},+ )+ init_request_b = AgentRequest(+ request_id="req-init-b",+ channel_id="acp",+ req_method=ReqMethod.INITIALIZE,+ params={"clientCapabilities": {"terminal": {"create": True}}},+ )+ await server.handle_initialize_for_test(ws_a, init_request_a, asyncio.Lock())+ await server.handle_initialize_for_test(ws_b, init_request_b, asyncio.Lock())++ captured = {}++ async def fake_handle_session_create(ws, request, send_lock):+ captured[id(ws)] = dict(request.metadata or {})++ monkeypatch.setattr(server, "_handle_session_create", fake_handle_session_create)++ env = e2a_from_agent_fields(+ request_id="req-session-create",+ channel_id="acp",+ session_id="sess-b",+ req_method=ReqMethod.SESSION_CREATE,+ params={"session_id": "sess-b"},+ is_stream=False,+ timestamp=0.0,+ )+ await server.handle_message_for_test(ws_b, json.dumps(env.to_dict(), ensure_ascii=False), asyncio.Lock())++ assert captured[id(ws_b)]["acp_client_capabilities"] == {"terminal": {"create": True}}++def test_build_context_engineering_rail_uses_summary_offloader_config(monkeypatch):monkeypatch.setattr(interface_deep_module,diff --git a/tests/unit_tests/channel/test_acp_channel.py b/tests/unit_tests/channel/test_acp_channel.pyindex d1bfd84046..f589ddb544 100644--- a/tests/unit_tests/channel/test_acp_channel.py+++ b/tests/unit_tests/channel/test_acp_channel.py@@ -53,6 +53,10 @@ class FakeStdout:self.buffer = FakeStdoutBuffer()+class AcpChannelHarness(AcpChannel):+ pass++def json_line(payload):return json.dumps(payload, ensure_ascii=False)@@ -152,7 +156,7 @@ async def test_jsonrpc_initialize_and_session_new(monkeypatch):])fake_stdout = FakeStdout()- channel = AcpChannel(AcpChannelConfig(enabled=True), DummyBus())+ channel = AcpChannelHarness(AcpChannelConfig(enabled=True), DummyBus())monkeypatch.setattr("sys.stdin", fake_stdin)monkeypatch.setattr("sys.stdout", fake_stdout)@@ -440,3 +444,69 @@ async def test_jsonrpc_session_cancel_finalizes_active_prompt(monkeypatch):assert isinstance(prompt_result.get("result"), dict)assert prompt_result["result"].get("stopReason") == "cancelled"assert cancel_result == {"jsonrpc": "2.0", "id": 21, "result": None}+++async def test_jsonrpc_response_is_forwarded_as_acp_tool_response(monkeypatch):+ fake_stdin = FakeStdin(+ [+ json_line(+ {+ "jsonrpc": "2.0",+ "id": "tool-1",+ "result": {"content": "from client"},+ }+ )+ ]+ )+ fake_stdout = FakeStdout()+ channel = AcpChannelHarness(AcpChannelConfig(enabled=True), DummyBus())+ seen = []++ channel.set_pending_client_rpc_session_for_test("tool-1", "sess-tool")++ monkeypatch.setattr("sys.stdin", fake_stdin)+ monkeypatch.setattr("sys.stdout", fake_stdout)+ monkeypatch.setattr("jiuwenclaw.channel.acp_channel._ACP_STDOUT", fake_stdout)++ async def _on_message(msg):+ seen.append(msg)++ channel.on_message(_on_message)+ await channel.start()++ assert len(seen) == 1+ msg = seen[0]+ assert msg.req_method == ReqMethod.ACP_TOOL_RESPONSE+ assert msg.session_id == "sess-tool"+ assert msg.params["jsonrpc_id"] == "tool-1"+ assert msg.params["response"]["result"] == {"content": "from client"}+++async def test_gateway_jsonrpc_request_is_written_to_stdout(monkeypatch):+ fake_stdout = FakeStdout()+ channel = AcpChannelHarness(AcpChannelConfig(enabled=True), DummyBus())++ monkeypatch.setattr("sys.stdout", fake_stdout)+ monkeypatch.setattr("jiuwenclaw.channel.acp_channel._ACP_STDOUT", fake_stdout)++ await channel.handle_gateway_frame_for_test(+ {+ "jsonrpc": "2.0",+ "id": "tool-2",+ "method": "fs/read_text_file",+ "params": {"path": "workspace/demo.txt", "sessionId": "sess-tool"},+ }+ )++ responses = fake_stdout.buffer.json_lines()+ assert responses == [+ {+ "jsonrpc": "2.0",+ "id": "tool-2",+ "method": "fs/read_text_file",+ "params": {"path": "workspace/demo.txt", "sessionId": "sess-tool"},+ }+ ]+ assert channel.get_pending_client_rpc_session_for_test("tool-2") == "sess-tool"diff --git a/tests/unit_tests/gateway/test_app_gateway_acp.py b/tests/unit_tests/gateway/test_app_gateway_acp.pyindex 27c9bd4fb9..03c4677824 100644--- a/tests/unit_tests/gateway/test_app_gateway_acp.py+++ b/tests/unit_tests/gateway/test_app_gateway_acp.py@@ -109,6 +109,104 @@ async def test_gateway_server_send_event_targets_session_client():}+async def test_gateway_server_passthroughs_acp_output_request_as_raw_jsonrpc():+ server = build_server()+ ws = FakeWebSocket()+ server.bind_session_client("sess-tool", ws)++ await server.send(+ Message(+ id="req-tool",+ type="event",+ channel_id="acp",+ session_id="sess-tool",+ params={},+ timestamp=time.time(),+ ok=True,+ payload={+ "event_type": "acp.output_request",+ "jsonrpc": {+ "jsonrpc": "2.0",+ "id": "tool-1",+ "method": "fs/read_text_file",+ "params": {"path": "workspace/demo.txt", "sessionId": "sess-tool"},+ },+ },+ )+ )++ assert ws.sent_frames == [+ {+ "jsonrpc": "2.0",+ "id": "tool-1",+ "method": "fs/read_text_file",+ "params": {"path": "workspace/demo.txt", "sessionId": "sess-tool"},+ }+ ]+++async def test_gateway_server_handle_raw_jsonrpc_response_forwards_acp_tool_response():+ server = build_server()+ ws = FakeWebSocket()+ server.bind_session_client("sess-tool", ws)+ seen = []++ async def on_message(msg):+ seen.append(msg)++ server.on_message(on_message)++ await server.send(+ Message(+ id="req-tool",+ type="event",+ channel_id="acp",+ session_id="sess-tool",+ params={},+ timestamp=time.time(),+ ok=True,+ payload={+ "event_type": "acp.output_request",+ "jsonrpc": {+ "jsonrpc": "2.0",+ "id": "tool-1",+ "method": "fs/read_text_file",+ "params": {"path": "workspace/demo.txt", "sessionId": "sess-tool"},+ },+ },+ )+ )++ await server.handle_raw_message_public(+ ws,+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": "tool-1",+ "result": {"content": "hello"},+ },+ ensure_ascii=False,+ ),+ )++ assert len(seen) == 1+ msg = seen[0]+ assert msg.channel_id == "acp"+ assert msg.session_id == "sess-tool"+ assert msg.req_method == ReqMethod.ACP_TOOL_RESPONSE+ assert msg.params == {+ "jsonrpc_id": "tool-1",+ "response": {+ "jsonrpc": "2.0",+ "id": "tool-1",+ "result": {"content": "hello"},+ },+ "session_id": "sess-tool",+ }++@pytest.mark.asyncioasync def test_gateway_server_handle_raw_message_forwards_request():server = build_server()