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显示优化
zp233319dc24f1a0488
diff --git a/jiuwenclaw/agentserver/agent_manager.py b/jiuwenclaw/agentserver/agent_manager.pyindex 30d87790f1..61cdca0d36 100644--- a/jiuwenclaw/agentserver/agent_manager.py+++ b/jiuwenclaw/agentserver/agent_manager.py@@ -8,6 +8,8 @@ import loggingimport uuidfrom typing import Any, TYPE_CHECKING+from jiuwenclaw.e2a.acp.protocol import build_acp_initialize_result+if TYPE_CHECKING:from jiuwenclaw.agentserver.interface import JiuWenClaw@@ -15,18 +17,7 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)-ACP_DEFAULT_CAPABILITIES: dict[str, Any] = {- "protocolVersion": "0.1.0",- "serverInfo": {- "name": "JiuWenClaw",- "version": "1.0.0",- },- "capabilities": {- "tools": True,- "resources": True,- "streaming": True,- },-}+ACP_DEFAULT_CAPABILITIES: dict[str, Any] = build_acp_initialize_result()def _build_acp_agent_config(extra_config: dict[str, Any] | None = None) -> dict[str, Any]:diff --git a/jiuwenclaw/agentserver/agent_ws_server.py b/jiuwenclaw/agentserver/agent_ws_server.pyindex 1c9f8bcad1..0e55ef952b 100644--- a/jiuwenclaw/agentserver/agent_ws_server.py+++ b/jiuwenclaw/agentserver/agent_ws_server.py@@ -449,8 +449,6 @@ class AgentWebSocketServer:async def _handle_stream(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:"""流式处理:调用 process_message_stream,逐条发送 E2AResponse 线 JSON。"""- from jiuwenclaw.schema.message import ReqMethod-channel_id = request.channel_id or "default"mode = request.params.get("mode", "agent.plan").split(".")[0]agent = await self._agent_manager.get_agent(channel_id=channel_id, mode=mode)@@ -1346,11 +1344,21 @@ class AgentWebSocketServer:payload={"accepted": True},)else:+ logger.info(+ "[AgentServer] ignore unknown/late acp tool response: jsonrpc_id=%s request_id=%s",+ jsonrpc_id,+ request.request_id,+ )resp = AgentResponse(request_id=request.request_id,channel_id=request.channel_id,- ok=False,- payload={"error": f"unknown acp tool response id: {jsonrpc_id}"},+ ok=True,+ payload={+ "accepted": False,+ "ignored": True,+ "reason": "unknown_or_late_response",+ "jsonrpc_id": jsonrpc_id,+ },)wire = encode_agent_response_for_wire(resp, response_id=request.request_id)diff --git a/jiuwenclaw/agentserver/deep_agent/interface_deep.py b/jiuwenclaw/agentserver/deep_agent/interface_deep.pyindex 48e3fee98d..ba072b7d39 100644--- a/jiuwenclaw/agentserver/deep_agent/interface_deep.py+++ b/jiuwenclaw/agentserver/deep_agent/interface_deep.py@@ -97,7 +97,6 @@ from jiuwenclaw.agentserver.memory.config import (clear_config_cache, get_memoryis_proactive_memory)from jiuwenclaw.agentserver.permissions.checker import TOOL_PERMISSION_CHANNEL_IDfrom jiuwenclaw.agentserver.skill_manager import SkillManager-from jiuwenclaw.agentserver.stream_utils import parse_stream_chunkfrom jiuwenclaw.agentserver.tools.multimodal_config import (apply_audio_model_config_from_yaml,apply_video_model_config_from_yaml,@@ -2940,6 +2939,21 @@ class JiuWenClawDeepAdapter:)return {"event_type": "chat.tool_call", "tool_call": tool_info}+ if chunk_type == "tool_update":+ if isinstance(payload, dict):+ update_info = payload.get("tool_update", payload)+ update_payload = (+ dict(update_info)+ if isinstance(update_info, dict)+ else {"content": str(update_info)}+ )+ else:+ update_payload = {"content": str(payload)}+ return {+ "event_type": "chat.tool_update",+ **update_payload,+ }+if chunk_type == "tool_result":if isinstance(payload, dict):result_info = payload.get("tool_result", payload)@@ -2957,6 +2971,11 @@ class JiuWenClawDeepAdapter:result_info.get("tool_call_id")or result_info.get("toolCallId"))+ raw_output = result_info.get("raw_output")+ if raw_output is None:+ raw_output = result_info.get("rawOutput")+ if raw_output is not None:+ result_payload["raw_output"] = raw_outputelse:result_payload = {"result": str(payload)}return {@@ -3056,4 +3075,4 @@ class JiuWenClawDeepAdapter:elif not is_memory_enabled(mode, config) and self._memory_rail is not None:await self._instance.unregister_rail(self._memory_rail)self._memory_rail = None- logger.info(f"[JiuWenClawDeepAdapter] MemoryRail unregistered for {mode} mode")\ No newline at end of file+ logger.info(f"[JiuWenClawDeepAdapter] MemoryRail unregistered for {mode} mode")diff --git a/jiuwenclaw/agentserver/deep_agent/rails/permission_rail.py b/jiuwenclaw/agentserver/deep_agent/rails/permission_rail.pyindex 1e11de0c19..a6b05783f6 100644--- a/jiuwenclaw/agentserver/deep_agent/rails/permission_rail.py+++ b/jiuwenclaw/agentserver/deep_agent/rails/permission_rail.py@@ -28,6 +28,7 @@ from jiuwenclaw.agentserver.permissions.checker import (collect_permission_rail_tool_names,)from jiuwenclaw.agentserver.permissions import PermissionLevel, PermissionResult+from jiuwenclaw.e2a.acp_tool_updates import build_acp_tool_descriptorfrom jiuwenclaw.utils import logger@@ -515,17 +516,21 @@ class PermissionInterruptRail(ConfirmInterruptRail):tool_name = tool_call.name if tool_call else ""tool_args = self._parse_tool_args(tool_call)tool_call_id = str(getattr(tool_call, "id", "") or f"permission_{tool_name or 'tool'}").strip()-- title = f"Approve `{tool_name}`"+ descriptor = build_acp_tool_descriptor(+ tool_name,+ tool_args,+ tool_call_id=tool_call_id,+ status="pending",+ kind=self._tool_kind_for_permission(tool_name),+ )+ title = str(descriptor.get("title") or f"Approve `{tool_name}`")if result.reason:title = f"{title}: {result.reason}"request: dict[str, Any] = {"toolCall": {- "toolCallId": tool_call_id,+ **descriptor,"title": title,- "kind": self._tool_kind_for_permission(tool_name),- "status": "pending",},"options": [{@@ -545,8 +550,6 @@ class PermissionInterruptRail(ConfirmInterruptRail):},],}- if tool_args:- request["toolCall"]["rawInput"] = tool_argsreturn requestasync def _request_acp_permission(diff --git a/jiuwenclaw/agentserver/deep_agent/rails/stream_event_rail.py b/jiuwenclaw/agentserver/deep_agent/rails/stream_event_rail.pyindex afdfcb91cc..24d0bde05d 100644--- a/jiuwenclaw/agentserver/deep_agent/rails/stream_event_rail.py+++ b/jiuwenclaw/agentserver/deep_agent/rails/stream_event_rail.py@@ -36,6 +36,12 @@ from jiuwenclaw.utils import logger_TODO_TOOL_NAMES = frozenset(["todo_create", "todo_list", "todo_modify"])+def _structured_tool_result_payload(result: Any) -> Any | None:+ if isinstance(result, (dict, list)):+ return result+ return None++class JiuClawStreamEventRail(DeepAgentRail):"""Emit frontend stream events and enforce pause/abort checkpoints.@@ -110,6 +116,7 @@ class JiuClawStreamEventRail(DeepAgentRail):if session is not None and isinstance(ctx.inputs, ToolCallInputs):tc = ctx.inputs.tool_callawait self._emit_tool_call(session, tc)+ await self._emit_tool_update(session, tc, status="in_progress")# ------------------------------------------------------------------# after_tool_call: emit tool_result + todo.updated@@ -161,21 +168,45 @@ class JiuClawStreamEventRail(DeepAgentRail):@staticmethodasync def _emit_tool_result(session: Session, tool_call: Any, result: Any) -> None:try:+ raw_output = _structured_tool_result_payload(result)+ tool_result_payload = {+ "tool_name": getattr(tool_call, "name", "") if tool_call else "",+ "tool_call_id": getattr(tool_call, "id", "") if tool_call else "",+ "result": str(result)[:1000] if result is not None else "",+ }+ if raw_output is not None:+ tool_result_payload["raw_output"] = raw_outputawait session.write_stream(OutputSchema(type="tool_result",index=0,payload={- "tool_result": {+ "tool_result": tool_result_payload+ },+ )+ )+ except Exception:+ logger.debug("tool_result emit failed", exc_info=True)++ @staticmethod+ async def _emit_tool_update(session: Session, tool_call: Any, *, status: str) -> None:+ try:+ await session.write_stream(+ OutputSchema(+ type="tool_update",+ index=0,+ payload={+ "tool_update": {"tool_name": getattr(tool_call, "name", "") if tool_call else "","tool_call_id": getattr(tool_call, "id", "") if tool_call else "",- "result": str(result)[:1000] if result is not None else "",+ "arguments": getattr(tool_call, "arguments", {}) if tool_call else {},+ "status": str(status or "").strip() or "in_progress",}},))except Exception:- logger.debug("tool_result emit failed", exc_info=True)+ logger.debug("tool_update emit failed", exc_info=True)async def _emit_todo_updated(self, agent: BaseAgent, session: Session, session_id: strdiff --git a/jiuwenclaw/agentserver/stream_utils.py b/jiuwenclaw/agentserver/stream_utils.pyindex 345864d5dd..913a0b5718 100644--- a/jiuwenclaw/agentserver/stream_utils.py+++ b/jiuwenclaw/agentserver/stream_utils.py@@ -186,6 +186,17 @@ def _parse_typed_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Any)return {"event_type": "chat.tool_call", "tool_call": tool_info}+ if chunk_type == "tool_update":+ if isinstance(payload, dict):+ update_info = payload.get("tool_update", payload)+ update_payload = dict(update_info) if isinstance(update_info, dict) else {"content": str(update_info)}+ else:+ update_payload = {"content": str(payload)}+ return {+ "event_type": "chat.tool_update",+ **update_payload,+ }+if chunk_type == "tool_result":if isinstance(payload, dict):result_info = payload.get("tool_result", payload)@@ -203,6 +214,11 @@ def _parse_typed_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Anyresult_payload["tool_call_id"] = (result_info.get("tool_call_id") or result_info.get("toolCallId"))+ raw_output = result_info.get("raw_output")+ if raw_output is None:+ raw_output = result_info.get("rawOutput")+ if raw_output is not None:+ result_payload["raw_output"] = raw_outputelse:result_payload = {"result": str(payload)}return {diff --git a/jiuwenclaw/agentserver/tools/acp_output_tools.py b/jiuwenclaw/agentserver/tools/acp_output_tools.pyindex 9613a25819..d98b3da655 100644--- a/jiuwenclaw/agentserver/tools/acp_output_tools.py+++ b/jiuwenclaw/agentserver/tools/acp_output_tools.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport asyncioimport inspectimport logging+import osimport uuidfrom dataclasses import dataclassfrom typing import Any, List, TYPE_CHECKING@@ -28,11 +29,17 @@ from jiuwenclaw.e2a.models import ()if TYPE_CHECKING:- from openjiuwen.core.foundation.tool import Tool, ToolCard, LocalFunction+ from openjiuwen.core.foundation.tool import Toollogger = logging.getLogger(__name__)_ACP_REQUEST_TIMEOUT_SECONDS = 30.0+try:+ _ACP_WAIT_FOR_EXIT_TIMEOUT_SECONDS = float(+ os.getenv("ACP_WAIT_FOR_EXIT_TIMEOUT_SECONDS", "30")+ )+except ValueError:+ _ACP_WAIT_FOR_EXIT_TIMEOUT_SECONDS = 30.0@dataclass@@ -367,9 +374,26 @@ async def wait_for_terminal_exit(mgr = get_acp_output_manager()params = {"terminalId": terminal_id}- response = await mgr.send_jsonrpc_request(- "terminal/wait_for_exit", params, session_id=session_id- )+ try:+ response = await mgr.send_jsonrpc_request(+ "terminal/wait_for_exit",+ params,+ session_id=session_id,+ timeout=_ACP_WAIT_FOR_EXIT_TIMEOUT_SECONDS,+ )+ except asyncio.TimeoutError:+ logger.info(+ "[AcpOutput] wait_for_terminal_exit soft-timeout: terminal_id=%s timeout=%.1fs",+ terminal_id,+ _ACP_WAIT_FOR_EXIT_TIMEOUT_SECONDS,+ )+ return {+ "exitCode": None,+ "signal": None,+ "timedOut": True,+ "running": True,+ "shouldRetry": True,+ }if "error" in response:err = response["error"]@@ -380,7 +404,16 @@ async def wait_for_terminal_exit(data=err.get("data"),)- return response.get("result", {})+ result = dict(response.get("result", {}) or {})+ # Normalize terminal wait result so callers can deterministically decide+ # whether they should poll again.+ result.setdefault("timedOut", False)+ if "running" not in result and (+ result.get("exitCode") is not None or result.get("signal") is not None+ ):+ result["running"] = False+ result["shouldRetry"] = bool(result.get("timedOut")) or bool(result.get("running"))+ return resultasync def release_terminal(@@ -415,7 +448,7 @@ async def release_terminal(def get_tools(session_id: str = "", request_id: str = "") -> List["Tool"]:"""返回 ACP 输出工具列表,用于注册到 Agent。"""- from openjiuwen.core.foundation.tool import Tool, ToolCard, LocalFunction+ from openjiuwen.core.foundation.tool import ToolCard, LocalFunctiondef make_tool(name: str,@@ -523,7 +556,10 @@ def get_tools(session_id: str = "", request_id: str = "") -> List["Tool"]:),make_tool(name="wait_for_terminal_exit",- description="等待终端命令执行完成。",+ description=(+ "等待终端命令执行完成。若返回 timedOut=true / running=true / shouldRetry=true,"+ "表示任务仍在执行中,应继续使用同一个 terminal_id 再次调用本工具轮询。"+ ),input_params={"type": "object","properties": {diff --git a/jiuwenclaw/app_gateway.py b/jiuwenclaw/app_gateway.pyindex a2eb180ca6..46cd1b8e58 100644--- a/jiuwenclaw/app_gateway.py+++ b/jiuwenclaw/app_gateway.py@@ -27,11 +27,8 @@ from urllib.parse import urlparsefrom dotenv import load_dotenvfrom openjiuwen.core.common.logging import LogManager-from jiuwenclaw.e2a.acp.session_updates import (- build_acp_final_text_update,- build_acp_session_update,- build_acp_usage_update,-)+import jiuwenclaw.channel.acp_channel as acp_channel_module+from jiuwenclaw.channel.acp_channel import AcpGatewayBridgefrom jiuwenclaw.gateway.route_binding import GatewayRouteBindingfrom jiuwenclaw.jiuwen_core_patch import apply_openai_model_client_patchfrom jiuwenclaw.utils import get_user_workspace_dir, get_env_file, prepare_workspace@@ -56,6 +53,9 @@ load_dotenv(dotenv_path=get_env_file())logger = logging.getLogger(__name__)+# Keep gateway idle-finalize fallback aligned with ACP channel default.+_PROMPT_IDLE_FINALIZE_SECONDS = 3.0+def _normalize_gateway_message(msg):from jiuwenclaw.schema.message import Message, ReqMethod@@ -142,130 +142,6 @@ class _InboundGatewayServer:logger.exception("[App] Gateway inbound handling failed: id=%s", getattr(msg, "id", None))-_ACP_PENDING_RPC_TIMEOUT_SECONDS = 60.0-_PROMPT_IDLE_FINALIZE_SECONDS = 3.0---@dataclass-class _GatewayAcpRequestContext:- jsonrpc_id: str | int | None- session_id: str- assistant_message_id: str | None = None- thought_message_id: str | None = None- idle_finalize_task: asyncio.Task | None = None---class AcpRouteHandler:- """ACP 路由的 JSON-RPC 桥接逻辑。-- ACP 专属协议桥接,不属于通用 GatewayServer。- """-- def __init__(self, on_message_cb) -> None:- self._on_message_cb = on_message_cb- # value: (session_id, ws, created_at)- self._pending_client_rpc_session_by_id: dict[str, tuple[str, Any, float]] = {}-- async def inbound_intercept(self, ws: Any, data: dict[str, Any]) -> bool:- """拦截 ACP JSON-RPC response 帧。"""- if not (- 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)- ):- return False-- from jiuwenclaw.e2a.adapters import build_acp_tool_response_message-- 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 True-- msg = build_acp_tool_response_message(- jsonrpc_id=jsonrpc_id,- response_data=data,- session_id=session_id,- channel_id="acp",- )- if self._on_message_cb is not None:- result = self._on_message_cb(msg)- if asyncio.iscoroutine(result):- await result- return True-- async def outbound_intercept(self, msg, ws: Any) -> bool:- """拦截 ACP output_request 出站消息。"""- 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 not isinstance(raw_jsonrpc, dict):- logger.warning(- "[ACP] outbound_intercept: invalid jsonrpc payload (not dict), dropping frame"- )- return True- jsonrpc_id = str(raw_jsonrpc.get("id") or "").strip()- session_id = str(msg.session_id or "").strip()- if not jsonrpc_id or not session_id:- logger.warning(- "[ACP] outbound_intercept: missing jsonrpc_id=%r or session_id=%r, "- "forwarding without pending registration",- jsonrpc_id,- session_id,- )- else:- self._pending_client_rpc_session_by_id[jsonrpc_id] = (session_id, ws, time.time())- self._sweep_stale_pending()- await ws.send(json.dumps(raw_jsonrpc, ensure_ascii=False))- return True- return False-- def cleanup(self, ws: Any) -> None:- """ws 断开时清理关联的 pending RPC 条目。"""- stale = [- jsonrpc_id- for jsonrpc_id, entry in self._pending_client_rpc_session_by_id.items()- if len(entry) >= 2 and entry[1] is ws- ]- for jsonrpc_id in stale:- self._pending_client_rpc_session_by_id.pop(jsonrpc_id, None)-- def _sweep_stale_pending(self) -> None:- """移除超时的 pending RPC 条目,防止永久堆积。"""- now = time.time()- stale = [- jsonrpc_id- for jsonrpc_id, entry in self._pending_client_rpc_session_by_id.items()- if len(entry) >= 3 and (now - entry[2]) > _ACP_PENDING_RPC_TIMEOUT_SECONDS- ]- for jsonrpc_id in stale:- self._pending_client_rpc_session_by_id.pop(jsonrpc_id, None)- logger.info(- "[ACP] pending RPC entry expired: jsonrpc_id=%s", jsonrpc_id- )----async def _connect_with_retry(client,uri: str,@@ -345,8 +221,12 @@ class GatewayServer:self._clients: set[Any] = set()self._request_to_client: dict[tuple[str, str], Any] = {}self._session_to_client: dict[tuple[str, str], Any] = {}- self._acp_request_ctx_by_request_id: dict[str, _GatewayAcpRequestContext] = {}- self._acp_active_prompt_request_by_session: dict[str, str] = {}+ self._acp_bridge = AcpGatewayBridge(+ self._dispatch_on_message,+ bind_session_client=self._bind_acp_session_client,+ channel_id="acp",+ idle_finalize_seconds=lambda: _PROMPT_IDLE_FINALIZE_SECONDS,+ )self._install_default_route_hooks()@staticmethod@@ -368,98 +248,20 @@ class GatewayServer:result = await resultreturn bool(result)+ def _bind_acp_session_client(self, session_id: str, ws: Any) -> None:+ session_key = self._client_route_key("acp", session_id)+ if session_key is not None:+ self._session_to_client[session_key] = ws+def _install_default_route_hooks(self) -> None:for route in self.config.routes.values():if route.channel_id != "acp":continueif route.inbound_interceptor is not None and route.outbound_interceptor is not None:continue- acp_handler = AcpRouteHandler(self._dispatch_on_message)- route.inbound_interceptor = route.inbound_interceptor or acp_handler.inbound_intercept- route.outbound_interceptor = route.outbound_interceptor or acp_handler.outbound_intercept- route.cleanup_handler = route.cleanup_handler or acp_handler.cleanup-- @staticmethod- def _is_acp_jsonrpc_request(data: Any) -> bool:- return (- isinstance(data, dict)- and data.get("jsonrpc") == "2.0"- and isinstance(data.get("method"), str)- )-- @staticmethod- def _acp_extract_prompt_text(params: dict[str, Any]) -> str:- prompt = params.get("prompt")- if isinstance(prompt, list):- texts: list[str] = []- for item in prompt:- if isinstance(item, dict) and item.get("type") == "text":- text = item.get("text")- if isinstance(text, str) and text:- texts.append(text)- if texts:- return "\n".join(texts)- for key in ("text", "content", "query"):- value = params.get(key)- if isinstance(value, str) and value.strip():- return value.strip()- return ""-- @staticmethod- async def _send_raw_jsonrpc_result(ws: Any, rpc_id: str | int | None, result: Any) -> None:- await ws.send(json.dumps({"jsonrpc": "2.0", "id": rpc_id, "result": result}, ensure_ascii=False))-- @staticmethod- async def _send_raw_jsonrpc_error(ws: Any, rpc_id: str | int | None, code: int, message: str) -> None:- await ws.send(- json.dumps(- {- "jsonrpc": "2.0",- "id": rpc_id,- "error": {"code": code, "message": message},- },- ensure_ascii=False,- )- )-- @staticmethod- async def _send_raw_jsonrpc_notification(ws: Any, method: str, params: dict[str, Any]) -> None:- await ws.send(json.dumps({"jsonrpc": "2.0", "method": method, "params": params}, ensure_ascii=False))-- @staticmethod- def _acp_initialize_result() -> dict[str, Any]:- from jiuwenclaw.version import __version__-- return {- "protocolVersion": 1,- "agentInfo": {- "name": "jiuwenclaw",- "title": "JiuwenClaw",- "version": __version__,- },- "agentCapabilities": {- "loadSession": False,- "promptCapabilities": {- "image": False,- "audio": False,- "embeddedContext": False,- },- "sessionCapabilities": {- "list": {},- },- "fs": {- "readTextFile": True,- "writeTextFile": True,- },- "terminal": {- "create": True,- "output": True,- "waitForExit": True,- "release": True,- },- },- "authMethods": [],- }+ route.inbound_interceptor = route.inbound_interceptor or self._acp_bridge.inbound_intercept+ route.outbound_interceptor = route.outbound_interceptor or self._acp_bridge.outbound_intercept+ route.cleanup_handler = route.cleanup_handler or self._acp_bridge.cleanupdef _resolve_route(self, request_path: str) -> tuple[RouteConfig | None, str]:"""按精确路径匹配路由;支持常见变体(如尾部斜杠)以避免客户端握手失败。"""@@ -586,7 +388,7 @@ class GatewayServer:returnif getattr(msg, "channel_id", None) == "acp":- handled = await self._send_acp_jsonrpc_message(msg, ws)+ handled = await self._acp_bridge.send_message(msg, ws)if handled:return@@ -633,139 +435,6 @@ class GatewayServer:frame = {"type": "event", "event": event_name, "payload": payload}await ws.send(json.dumps(frame, ensure_ascii=False))- async def _send_acp_jsonrpc_message(self, msg, ws: Any) -> bool:- from jiuwenclaw.schema.message import EventType-- ctx = self._acp_request_ctx_by_request_id.get(str(getattr(msg, "id", "")))- payload = dict(getattr(msg, "payload", None) or {})- session_id = str(getattr(msg, "session_id", None) or "")-- if ctx is None:- return False-- if msg.type == "event" and msg.event_type == EventType.CHAT_DELTA:- update = build_acp_session_update(msg, payload, ctx)- if update is None:- return True- await self._send_raw_jsonrpc_notification(- ws,- "session/update",- {"sessionId": session_id or ctx.session_id, "update": update},- )- usage_update = build_acp_usage_update(payload)- if usage_update is not None:- await self._send_raw_jsonrpc_notification(- ws,- "session/update",- {"sessionId": session_id or ctx.session_id, "update": usage_update},- )- return True-- if msg.type == "event" and msg.event_type in (- EventType.CHAT_TOOL_CALL,- EventType.CHAT_TOOL_RESULT,- EventType.CHAT_SUBTASK_UPDATE,- ):- update = build_acp_session_update(msg, payload, ctx)- if update is None:- return True- task = ctx.idle_finalize_task- if task is not None:- task.cancel()- ctx.idle_finalize_task = None- await self._send_raw_jsonrpc_notification(- ws,- "session/update",- {"sessionId": session_id or ctx.session_id, "update": update},- )- return True-- if msg.type == "event" and msg.event_type == EventType.CHAT_FINAL:- update = build_acp_final_text_update(payload, ctx)- if update is not None:- await self._send_raw_jsonrpc_notification(- ws,- "session/update",- {- "sessionId": session_id or ctx.session_id,- "update": update,- },- )- usage_update = build_acp_usage_update(payload)- if usage_update is not None:- await self._send_raw_jsonrpc_notification(- ws,- "session/update",- {- "sessionId": session_id or ctx.session_id,- "update": usage_update,- },- )- self._schedule_acp_idle_finalize(str(msg.id), ctx, ws)- return True-- if msg.type == "event" and msg.event_type == EventType.CHAT_ERROR:- task = ctx.idle_finalize_task- if task is not None:- task.cancel()- ctx.idle_finalize_task = None- await self._send_raw_jsonrpc_error(- ws,- ctx.jsonrpc_id,- -32603,- str(payload.get("error") or payload.get("content") or "Agent error"),- )- self._clear_acp_request_context(str(msg.id), ctx.session_id)- return True-- if msg.type == "event" and msg.event_type == EventType.CHAT_PROCESSING_STATUS:- update = build_acp_session_update(msg, payload, ctx)- if update is not None:- await self._send_raw_jsonrpc_notification(- ws,- "session/update",- {"sessionId": session_id or ctx.session_id, "update": update},- )- if payload.get("is_processing") is False:- task = ctx.idle_finalize_task- if task is not None:- task.cancel()- ctx.idle_finalize_task = None- await self._send_raw_jsonrpc_result(ws, ctx.jsonrpc_id, {"stopReason": "end_turn"})- self._clear_acp_request_context(str(msg.id), ctx.session_id)- return True-- return False-- def _clear_acp_request_context(self, request_id: str, session_id: str) -> None:- ctx = self._acp_request_ctx_by_request_id.pop(request_id, None)- if ctx is not None and ctx.idle_finalize_task is not None:- ctx.idle_finalize_task.cancel()- ctx.idle_finalize_task = None- if self._acp_active_prompt_request_by_session.get(session_id) == request_id:- self._acp_active_prompt_request_by_session.pop(session_id, None)-- def _schedule_acp_idle_finalize(self, request_id: str, ctx: _GatewayAcpRequestContext, ws: Any) -> None:- task = ctx.idle_finalize_task- if task is not None:- task.cancel()- ctx.idle_finalize_task = asyncio.create_task(- self._acp_idle_finalize_after_timeout(request_id, ws),- name=f"gateway-acp-idle-finalize-{request_id}",- )-- async def _acp_idle_finalize_after_timeout(self, request_id: str, ws: Any) -> None:- current_task = asyncio.current_task()- try:- await asyncio.sleep(_PROMPT_IDLE_FINALIZE_SECONDS)- ctx = self._acp_request_ctx_by_request_id.get(request_id)- if ctx is None or ctx.idle_finalize_task is not current_task:- return- await self._send_raw_jsonrpc_result(ws, ctx.jsonrpc_id, {"stopReason": "end_turn"})- self._clear_acp_request_context(request_id, ctx.session_id)- except asyncio.CancelledError:- return-async def _connection_handler(self, ws: Any, path: str | None = None) -> None:raw_path = path if path is not None else getattr(ws, "path", "")parsed = urlparse(raw_path)@@ -827,82 +496,12 @@ class GatewayServer:)return- if route.channel_id == "acp" and self._is_acp_jsonrpc_request(data):- rpc_id = data.get("id")- method = str(data.get("method") or "").strip()- params = data.get("params") if isinstance(data.get("params"), dict) else {}- try:- if method == "initialize":- await self._send_raw_jsonrpc_result(ws, rpc_id, self._acp_initialize_result())- return- if method == "session/new":- session_id = str(params.get("sessionId") or f"acp_{uuid_module.uuid4().hex[:12]}").strip()- if session_id:- session_key = self._client_route_key(route.channel_id, session_id)- if session_key is not None:- self._session_to_client[session_key] = ws- await self._send_raw_jsonrpc_result(ws, rpc_id, {"sessionId": session_id})- return- if method == "session/prompt":- session_id = str(params.get("sessionId") or "").strip()- if not session_id:- raise ValueError("sessionId is required")- text = self._acp_extract_prompt_text(params)- if not text:- raise ValueError("prompt is required")- request_id = f"acp_{uuid_module.uuid4().hex[:12]}"- session_key = self._client_route_key(route.channel_id, session_id)- if session_key is not None:- self._session_to_client[session_key] = ws- self._acp_request_ctx_by_request_id[request_id] = _GatewayAcpRequestContext(- jsonrpc_id=rpc_id,- session_id=session_id,- )- self._acp_active_prompt_request_by_session[session_id] = request_id- msg = Message(- id=request_id,- type="req",- channel_id=route.channel_id,- session_id=session_id,- params={- **dict(params),- "content": text,- "query": text,- "session_id": session_id,- },- timestamp=time.time(),- ok=True,- req_method=ReqMethod.CHAT_SEND,- mode=Mode.CODE_NORMAL,- metadata={"acp": {"jsonrpc_id": rpc_id, "method": method}},- )- if self._on_message_cb is not None:- result = self._on_message_cb(msg)- if asyncio.iscoroutine(result):- await result- return- if method == "session/cancel":- session_id = str(params.get("sessionId") or "").strip()- if session_id:- request_id = self._acp_active_prompt_request_by_session.pop(session_id, None)- if request_id is not None:- ctx = self._acp_request_ctx_by_request_id.pop(request_id, None)- if ctx is not None:- await self._send_raw_jsonrpc_result(ws, ctx.jsonrpc_id, {"stopReason": "cancelled"})- await self._send_raw_jsonrpc_result(ws, rpc_id, None)- return- if method == "session/list":- await self._send_raw_jsonrpc_result(ws, rpc_id, {"sessions": []})- return- if method == "session/load":- await self._send_raw_jsonrpc_result(ws, rpc_id, None)- return- await self._send_raw_jsonrpc_error(ws, rpc_id, -32601, f"Method not found: {method}")- except ValueError as exc:- await self._send_raw_jsonrpc_error(ws, rpc_id, -32602, str(exc))- except Exception as exc: # noqa: BLE001- logger.exception("GatewayServer ACP JSON-RPC handler failed: method=%s", method)- await self._send_raw_jsonrpc_error(ws, rpc_id, -32603, str(exc))+ if route.channel_id == "acp":+ handled = await self._acp_bridge.handle_jsonrpc_request(ws, data)+ if handled:+ return++ if route.channel_id == "acp" and self._acp_bridge.is_jsonrpc_request(data):return# route 级别的原始帧拦截(如 ACP JSON-RPC response)@@ -1040,15 +639,11 @@ def _build_acp_route_binding(forward_no_local_handler_methods: frozenset[str],on_message_cb,) -> GatewayRouteBinding:- acp_handler = AcpRouteHandler(on_message_cb)return GatewayRouteBinding(path=path,channel_id=channel_id,forward_methods=forward_methods,forward_no_local_handler_methods=forward_no_local_handler_methods,- inbound_interceptor=acp_handler.inbound_intercept,- outbound_interceptor=acp_handler.outbound_intercept,- cleanup_handler=acp_handler.cleanup,)@@ -1102,7 +697,7 @@ async def _run()from jiuwenclaw.extensions.manager import ExtensionManagerfrom jiuwenclaw.extensions.registry import ExtensionRegistry- from jiuwenclaw.schema.message import Message, ReqMethod+ from jiuwenclaw.schema.message import Messagefrom jiuwenclaw.updater import WindowsUpdaterServicefrom openjiuwen.core.runner import Runnerdiff --git a/jiuwenclaw/channel/acp_channel.py b/jiuwenclaw/channel/acp_channel.pyindex e7663758e6..643fcf9483 100644--- a/jiuwenclaw/channel/acp_channel.py+++ b/jiuwenclaw/channel/acp_channel.py@@ -12,6 +12,12 @@ from dataclasses import dataclass, fieldfrom typing import Any, Callablefrom jiuwenclaw.channel.base import BaseChannel, RobotMessageRouter+from jiuwenclaw.e2a.acp.protocol import (+ build_acp_initialize_result,+ build_acp_prompt_result,+ build_acp_session_list_result,+ build_acp_session_new_result,+)from jiuwenclaw.e2a.acp.session_updates import (build_acp_final_text_update,build_acp_session_update,@@ -29,12 +35,10 @@ from jiuwenclaw.e2a.constants import (E2A_SOURCE_PROTOCOL_E2A,)from jiuwenclaw.e2a.models import E2AEnvelope, E2AProvenance, E2AResponse, utc_now_iso-from jiuwenclaw.schema.message import EventType, Message, ReqMethod-from jiuwenclaw.version import __version__+from jiuwenclaw.schema.message import EventType, Message, Mode, ReqMethodlogger = logging.getLogger(__name__)-_ACP_PROTOCOL_VERSION = 1_ACP_STDOUT = getattr(sys, "__stdout__", sys.stdout)_STDIN_EOF_GRACE_SECONDS = 5.0_PROMPT_IDLE_FINALIZE_SECONDS = 3.0@@ -57,12 +61,598 @@ class _AcpRequestContext:method: str | Noneresponse_mode: str = "e2a"session_id: str | None = None+ user_message_id: str | None = Noneassistant_message_id: str | None = None+ assistant_text: str | None = Nonethought_message_id: str | None = None+ thought_text: str | None = None+ tool_call_cache: dict[str, dict[str, Any]] = field(default_factory=dict)+ pending_stop_reason: str | None = None+ saw_chat_final: bool = False+ saw_processing_idle: bool = Falsesequence: int = 0idle_finalize_task: asyncio.Task | None = None+@dataclass+class AcpGatewayRequestContext:+ jsonrpc_id: str | int | None+ session_id: str+ user_message_id: str | None = None+ assistant_message_id: str | None = None+ assistant_text: str | None = None+ thought_message_id: str | None = None+ thought_text: str | None = None+ tool_call_cache: dict[str, dict[str, Any]] = field(default_factory=dict)+ pending_stop_reason: str | None = None+ saw_chat_final: bool = False+ saw_processing_idle: bool = False+ client_ws: Any | None = None+ idle_finalize_task: asyncio.Task | None = None+++def _cancel_idle_finalize_task(ctx: Any) -> None:+ task = getattr(ctx, "idle_finalize_task", None)+ if task is not None:+ task.cancel()+ ctx.idle_finalize_task = None+++def _mark_stream_activity(ctx: Any) -> None:+ setattr(ctx, "saw_processing_idle", False)+ _cancel_idle_finalize_task(ctx)+++def _should_wait_for_final_text_before_end_turn(ctx: Any) -> bool:+ if bool(getattr(ctx, "saw_chat_final", False)):+ return False+ return bool(+ getattr(ctx, "assistant_text", None)+ or getattr(ctx, "assistant_message_id", None)+ )+++class AcpGatewayBridge:+ """Reusable ACP JSON-RPC bridge for Gateway websocket routes."""++ def __init__(+ self,+ on_message_cb: Callable[[Message], Any] | None,+ *,+ bind_session_client: Callable[[str, Any], None] | None = None,+ channel_id: str = "acp",+ idle_finalize_seconds: float | Callable[[], float] | None = None,+ ) -> None:+ self._on_message_cb = on_message_cb+ self._bind_session_client = bind_session_client+ self._channel_id = str(channel_id or "acp").strip() or "acp"+ self._idle_finalize_seconds = idle_finalize_seconds+ self._request_ctx_by_request_id: dict[str, AcpGatewayRequestContext] = {}+ self._active_prompt_request_by_session: dict[str, str] = {}+ self._known_sessions: set[str] = set()+ self._pending_client_rpc_count_by_session: dict[str, int] = {}+ # value: (session_id, ws, created_at)+ self._pending_client_rpc_session_by_id: dict[str, tuple[str, Any, float]] = {}++ @property+ def request_contexts(self) -> list[AcpGatewayRequestContext]:+ """Return a snapshot list of all pending gateway request contexts."""+ return list(self._request_ctx_by_request_id.values())++ async def inbound_intercept(self, ws: Any, data: dict[str, Any]) -> bool:+ """Intercept ACP JSON-RPC responses from the IDE client."""+ if not (+ 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)+ ):+ return False++ from jiuwenclaw.e2a.adapters import build_acp_tool_response_message++ 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:+ logger.info(+ "[ACP] ignoring unknown/late client rpc response: jsonrpc_id=%s session_id=%s",+ jsonrpc_id,+ session_id,+ )+ await ws.send(+ json.dumps(+ {+ "type": "res",+ "id": jsonrpc_id,+ "ok": True,+ "payload": {+ "accepted": False,+ "ignored": True,+ "reason": "unknown_or_late_response",+ },+ },+ ensure_ascii=False,+ )+ )+ return True++ msg = build_acp_tool_response_message(+ jsonrpc_id=jsonrpc_id,+ response_data=data,+ session_id=session_id,+ channel_id=self._channel_id,+ )+ await self._dispatch_message(msg)+ if session_id:+ await self._resolve_pending_client_rpc(session_id)+ return True++ async def outbound_intercept(self, msg: Message, ws: Any) -> bool:+ """Intercept ACP output_request events and relay them as raw JSON-RPC."""+ 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 not isinstance(raw_jsonrpc, dict):+ logger.warning(+ "[ACP] outbound_intercept: invalid jsonrpc payload (not dict), dropping frame"+ )+ return True+ jsonrpc_id = str(raw_jsonrpc.get("id") or "").strip()+ session_id = str(msg.session_id or "").strip()+ if not jsonrpc_id or not session_id:+ logger.warning(+ "[ACP] outbound_intercept: missing jsonrpc_id=%r or session_id=%r, "+ "forwarding without pending registration",+ jsonrpc_id,+ session_id,+ )+ else:+ self._pending_client_rpc_session_by_id[jsonrpc_id] = (session_id, ws, time.time())+ await self._register_pending_client_rpc(session_id)+ await self._sweep_stale_pending()+ await ws.send(json.dumps(raw_jsonrpc, ensure_ascii=False))+ return True+ return False++ def cleanup(self, ws: Any) -> None:+ """Clean up pending client RPC entries associated with a disconnected ws."""+ stale = [+ jsonrpc_id+ for jsonrpc_id, entry in self._pending_client_rpc_session_by_id.items()+ if len(entry) >= 2 and entry[1] is ws+ ]+ for jsonrpc_id in stale:+ entry = self._pending_client_rpc_session_by_id.pop(jsonrpc_id, None)+ if isinstance(entry, tuple) and len(entry) >= 1:+ self._decrease_pending_client_rpc_count(str(entry[0] or "").strip())++ async def handle_jsonrpc_request(self, ws: Any, data: dict[str, Any]) -> bool:+ if not self.is_jsonrpc_request(data):+ return False++ rpc_id = data.get("id")+ method = str(data.get("method") or "").strip()+ params = data.get("params") if isinstance(data.get("params"), dict) else {}+ try:+ if method == "initialize":+ await self._send_raw_jsonrpc_result(ws, rpc_id, build_acp_initialize_result())+ return True+ if method == "session/new":+ session_id = str(params.get("sessionId") or f"acp_{uuid.uuid4().hex[:12]}").strip()+ self._bind_session(ws, session_id)+ await self._send_raw_jsonrpc_result(ws, rpc_id, build_acp_session_new_result(session_id))+ return True+ if method == "session/prompt":+ session_id = str(params.get("sessionId") or "").strip()+ if not session_id:+ raise ValueError("sessionId is required")+ text = self.extract_prompt_text(params)+ if not text:+ raise ValueError("prompt is required")++ request_id = f"acp_{uuid.uuid4().hex[:12]}"+ self._bind_session(ws, session_id)+ self._request_ctx_by_request_id[request_id] = AcpGatewayRequestContext(+ jsonrpc_id=rpc_id,+ session_id=session_id,+ user_message_id=str(params.get("messageId") or "").strip() or None,+ client_ws=ws,+ )+ self._active_prompt_request_by_session[session_id] = request_id+ await self._dispatch_message(+ Message(+ id=request_id,+ type="req",+ channel_id=self._channel_id,+ session_id=session_id,+ params={+ **dict(params),+ "content": text,+ "query": text,+ "session_id": session_id,+ },+ timestamp=time.time(),+ ok=True,+ req_method=ReqMethod.CHAT_SEND,+ mode=Mode.AGENT_PLAN,+ metadata={"acp": {"jsonrpc_id": rpc_id, "method": method}},+ )+ )+ return True+ if method == "session/cancel":+ session_id = str(params.get("sessionId") or "").strip()+ if session_id:+ request_id = self._active_prompt_request_by_session.pop(session_id, None)+ if request_id is not None:+ ctx = self._request_ctx_by_request_id.pop(request_id, None)+ if ctx is not None:+ await self._send_raw_jsonrpc_result(+ ws,+ ctx.jsonrpc_id,+ build_acp_prompt_result(+ stop_reason="cancelled",+ user_message_id=ctx.user_message_id,+ ),+ )+ await self._send_raw_jsonrpc_result(ws, rpc_id, None)+ return True+ if method == "session/list":+ await self._send_raw_jsonrpc_result(+ ws,+ rpc_id,+ build_acp_session_list_result(sorted(self._known_sessions)),+ )+ return True+ if method == "session/load":+ await self._send_raw_jsonrpc_error(+ ws,+ rpc_id,+ -32601,+ "Method not supported by agent capabilities: session/load",+ )+ return True+ await self._send_raw_jsonrpc_error(ws, rpc_id, -32601, f"Method not found: {method}")+ except ValueError as exc:+ await self._send_raw_jsonrpc_error(ws, rpc_id, -32602, str(exc))+ except Exception as exc: # noqa: BLE001+ logger.exception("Gateway ACP JSON-RPC handler failed: method=%s", method)+ await self._send_raw_jsonrpc_error(ws, rpc_id, -32603, str(exc))+ return True++ async def send_message(self, msg: Message, ws: Any) -> bool:+ ctx = self._request_ctx_by_request_id.get(str(getattr(msg, "id", "")))+ payload = dict(getattr(msg, "payload", None) or {})+ session_id = str(getattr(msg, "session_id", None) or "")++ if ctx is None:+ return False++ if msg.type == "event" and msg.event_type == EventType.CHAT_DELTA:+ update = build_acp_session_update(msg, payload, ctx)+ if update is None:+ return True+ _mark_stream_activity(ctx)+ await self._send_raw_jsonrpc_notification(+ ws,+ "session/update",+ {"sessionId": session_id or ctx.session_id, "update": update},+ )+ usage_update = build_acp_usage_update(payload)+ if usage_update is not None:+ await self._send_raw_jsonrpc_notification(+ ws,+ "session/update",+ {"sessionId": session_id or ctx.session_id, "update": usage_update},+ )+ return True++ if msg.type == "event" and msg.event_type in (+ EventType.CHAT_REASONING,+ EventType.CHAT_TOOL_CALL,+ EventType.CHAT_TOOL_UPDATE,+ EventType.CHAT_TOOL_RESULT,+ EventType.TODO_UPDATED,+ EventType.CHAT_SUBTASK_UPDATE,+ ):+ update = build_acp_session_update(msg, payload, ctx)+ if update is None:+ return True+ _mark_stream_activity(ctx)+ await self._send_raw_jsonrpc_notification(+ ws,+ "session/update",+ {"sessionId": session_id or ctx.session_id, "update": update},+ )+ return True++ if msg.type == "event" and msg.event_type == EventType.CHAT_FINAL:+ ctx.saw_chat_final = True+ update = build_acp_final_text_update(payload, ctx)+ if update is not None:+ await self._send_raw_jsonrpc_notification(+ ws,+ "session/update",+ {"sessionId": session_id or ctx.session_id, "update": update},+ )+ usage_update = build_acp_usage_update(payload)+ if usage_update is not None:+ await self._send_raw_jsonrpc_notification(+ ws,+ "session/update",+ {"sessionId": session_id or ctx.session_id, "update": usage_update},+ )+ if ctx.saw_processing_idle:+ if self._session_has_pending_client_rpcs(session_id or ctx.session_id):+ ctx.pending_stop_reason = "end_turn"+ return True+ _cancel_idle_finalize_task(ctx)+ await self._send_raw_jsonrpc_result(+ ws,+ ctx.jsonrpc_id,+ build_acp_prompt_result(+ stop_reason="end_turn",+ user_message_id=ctx.user_message_id,+ ),+ )+ self._clear_request_context(str(msg.id), ctx.session_id)+ return True+ _cancel_idle_finalize_task(ctx)+ return True++ if msg.type == "event" and msg.event_type == EventType.CHAT_ERROR:+ _cancel_idle_finalize_task(ctx)+ await self._send_raw_jsonrpc_error(+ ws,+ ctx.jsonrpc_id,+ -32603,+ str(payload.get("error") or payload.get("content") or "Agent error"),+ )+ self._clear_request_context(str(msg.id), ctx.session_id)+ return True++ if msg.type == "event" and msg.event_type == EventType.CHAT_PROCESSING_STATUS:+ update = build_acp_session_update(msg, payload, ctx)+ if update is not None:+ await self._send_raw_jsonrpc_notification(+ ws,+ "session/update",+ {"sessionId": session_id or ctx.session_id, "update": update},+ )+ if payload.get("is_processing") is False:+ ctx.saw_processing_idle = True+ if self._session_has_pending_client_rpcs(session_id or ctx.session_id):+ ctx.pending_stop_reason = "end_turn"+ return True+ if _should_wait_for_final_text_before_end_turn(ctx):+ self._schedule_idle_finalize(str(msg.id), ctx, ws)+ return True+ _cancel_idle_finalize_task(ctx)+ await self._send_raw_jsonrpc_result(+ ws,+ ctx.jsonrpc_id,+ build_acp_prompt_result(+ stop_reason="end_turn",+ user_message_id=ctx.user_message_id,+ ),+ )+ self._clear_request_context(str(msg.id), ctx.session_id)+ return True+ if payload.get("is_processing") is True:+ ctx.saw_processing_idle = False+ _cancel_idle_finalize_task(ctx)+ return True++ return False++ @staticmethod+ def is_jsonrpc_request(data: Any) -> bool:+ return (+ isinstance(data, dict)+ and data.get("jsonrpc") == "2.0"+ and isinstance(data.get("method"), str)+ )++ @staticmethod+ def extract_prompt_text(params: dict[str, Any]) -> str:+ prompt = params.get("prompt")+ if isinstance(prompt, list):+ texts: list[str] = []+ for item in prompt:+ if isinstance(item, dict) and item.get("type") == "text":+ text = item.get("text")+ if isinstance(text, str) and text:+ texts.append(text)+ if texts:+ return "\n".join(texts)+ for key in ("text", "content", "query"):+ value = params.get(key)+ if isinstance(value, str) and value.strip():+ return value.strip()+ return ""++ async def _dispatch_message(self, msg: Message) -> bool:+ if self._on_message_cb is None:+ return False+ result = self._on_message_cb(msg)+ if asyncio.iscoroutine(result):+ result = await result+ return bool(result)++ def _bind_session(self, ws: Any, session_id: str) -> None:+ sid = str(session_id or "").strip()+ if not sid:+ return+ self._known_sessions.add(sid)+ if self._bind_session_client is not None:+ self._bind_session_client(sid, ws)++ async def _register_pending_client_rpc(self, session_id: str | None) -> None:+ sid = str(session_id or "").strip()+ if not sid:+ return+ self._pending_client_rpc_count_by_session[sid] = (+ self._pending_client_rpc_count_by_session.get(sid, 0) + 1+ )+ for ctx in self._request_ctx_by_request_id.values():+ if str(ctx.session_id or "") == sid:+ task = ctx.idle_finalize_task+ if task is not None:+ task.cancel()+ ctx.idle_finalize_task = None++ async def _resolve_pending_client_rpc(self, session_id: str | None) -> None:+ sid = str(session_id or "").strip()+ if not sid:+ return+ self._decrease_pending_client_rpc_count(sid)+ await self._maybe_finalize_deferred_prompts(sid)++ def _decrease_pending_client_rpc_count(self, session_id: str | None) -> None:+ sid = str(session_id or "").strip()+ if not sid:+ return+ current = self._pending_client_rpc_count_by_session.get(sid, 0)+ if current <= 1:+ self._pending_client_rpc_count_by_session.pop(sid, None)+ else:+ self._pending_client_rpc_count_by_session[sid] = current - 1++ def _session_has_pending_client_rpcs(self, session_id: str | None) -> bool:+ sid = str(session_id or "").strip()+ if not sid:+ return False+ return self._pending_client_rpc_count_by_session.get(sid, 0) > 0++ async def _maybe_finalize_deferred_prompts(self, session_id: str | None) -> None:+ sid = str(session_id or "").strip()+ if not sid or self._session_has_pending_client_rpcs(sid):+ return++ matched_ids: list[str] = []+ for request_id, ctx in self._request_ctx_by_request_id.items():+ if str(ctx.session_id or "") != sid:+ continue+ if not str(ctx.pending_stop_reason or "").strip():+ continue+ matched_ids.append(request_id)+ for request_id in matched_ids:+ ctx = self._request_ctx_by_request_id.get(request_id)+ if ctx is None:+ continue+ stop_reason = str(ctx.pending_stop_reason or "").strip()+ if not stop_reason:+ continue+ ctx.pending_stop_reason = None+ ws = ctx.client_ws+ if ws is None or bool(getattr(ws, "closed", False)):+ continue+ if _should_wait_for_final_text_before_end_turn(ctx):+ self._schedule_idle_finalize(request_id, ctx, ws)+ continue+ _cancel_idle_finalize_task(ctx)+ await self._send_raw_jsonrpc_result(+ ws,+ ctx.jsonrpc_id,+ build_acp_prompt_result(+ stop_reason=stop_reason,+ user_message_id=ctx.user_message_id,+ ),+ )+ self._clear_request_context(request_id, sid)++ def _clear_request_context(self, request_id: str, session_id: str) -> None:+ ctx = self._request_ctx_by_request_id.pop(request_id, None)+ if ctx is not None and ctx.idle_finalize_task is not None:+ ctx.idle_finalize_task.cancel()+ ctx.idle_finalize_task = None+ if self._active_prompt_request_by_session.get(session_id) == request_id:+ self._active_prompt_request_by_session.pop(session_id, None)++ def _schedule_idle_finalize(self, request_id: str, ctx: AcpGatewayRequestContext, ws: Any) -> None:+ task = ctx.idle_finalize_task+ if task is not None:+ task.cancel()+ ctx.idle_finalize_task = asyncio.create_task(+ self._idle_finalize_after_timeout(request_id, ws),+ name=f"gateway-acp-idle-finalize-{request_id}",+ )++ async def _idle_finalize_after_timeout(self, request_id: str, ws: Any) -> None:+ current_task = asyncio.current_task()+ try:+ await asyncio.sleep(self._get_idle_finalize_seconds())+ ctx = self._request_ctx_by_request_id.get(request_id)+ if ctx is None or ctx.idle_finalize_task is not current_task:+ return+ if self._session_has_pending_client_rpcs(ctx.session_id):+ ctx.pending_stop_reason = "end_turn"+ ctx.idle_finalize_task = None+ return+ await self._send_raw_jsonrpc_result(+ ws,+ ctx.jsonrpc_id,+ build_acp_prompt_result(+ stop_reason="end_turn",+ user_message_id=ctx.user_message_id,+ ),+ )+ self._clear_request_context(request_id, ctx.session_id)+ except asyncio.CancelledError:+ return++ def _get_idle_finalize_seconds(self) -> float:+ value = self._idle_finalize_seconds+ if callable(value):+ try:+ value = value()+ except Exception: # noqa: BLE001+ logger.debug("[ACP] idle finalize seconds getter failed", exc_info=True)+ value = None+ if isinstance(value, (int, float)):+ return float(value)+ return _PROMPT_IDLE_FINALIZE_SECONDS++ async def _sweep_stale_pending(self) -> None:+ now = time.time()+ stale = [+ (jsonrpc_id, str(entry[0] or "").strip())+ for jsonrpc_id, entry in self._pending_client_rpc_session_by_id.items()+ if len(entry) >= 3 and (now - entry[2]) > _ACP_PENDING_RPC_TIMEOUT_SECONDS+ ]+ for jsonrpc_id, session_id in stale:+ self._pending_client_rpc_session_by_id.pop(jsonrpc_id, None)+ logger.info("[ACP] pending RPC entry expired: jsonrpc_id=%s", jsonrpc_id)+ await self._resolve_pending_client_rpc(session_id)++ @staticmethod+ async def _send_raw_jsonrpc_result(ws: Any, rpc_id: str | int | None, result: Any) -> None:+ await ws.send(json.dumps({"jsonrpc": "2.0", "id": rpc_id, "result": result}, ensure_ascii=False))++ @staticmethod+ async def _send_raw_jsonrpc_error(ws: Any, rpc_id: str | int | None, code: int, message: str) -> None:+ await ws.send(+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": rpc_id,+ "error": {"code": code, "message": message},+ },+ ensure_ascii=False,+ )+ )++ @staticmethod+ async def _send_raw_jsonrpc_notification(ws: Any, method: str, params: dict[str, Any]) -> None:+ await ws.send(json.dumps({"jsonrpc": "2.0", "method": method, "params": params}, ensure_ascii=False))++class AcpChannel(BaseChannel):"""ACP stdio 通道。@@ -89,6 +679,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._known_sessions: set[str] = set()# value: (session_id, created_at)self._pending_client_rpc_session_by_id: dict[str, tuple[str, float]] = {}@@ -150,17 +741,22 @@ class AcpChannel(BaseChannel):self._pending_client_rpc_session_by_id.clear()await self._close_gateway_connection()- def _sweep_stale_pending(self) -> None:+ async def _sweep_stale_pending(self) -> None:"""移除超时的 pending RPC 条目,防止永久堆积。"""now = time.time()stale = [- jsonrpc_id+ (jsonrpc_id, str(entry[0] or "").strip())for jsonrpc_id, entry in self._pending_client_rpc_session_by_id.items()if isinstance(entry, tuple) and len(entry) >= 2 and (now - entry[1]) > _ACP_PENDING_RPC_TIMEOUT_SECONDS]- for jsonrpc_id in stale:+ affected_sessions: set[str] = set()+ for jsonrpc_id, session_id in stale:self._pending_client_rpc_session_by_id.pop(jsonrpc_id, None)logger.info("[ACP] pending RPC entry expired: jsonrpc_id=%s", jsonrpc_id)+ if session_id:+ affected_sessions.add(session_id)+ for session_id in affected_sessions:+ await self._maybe_finalize_deferred_prompts(session_id)async def send(self, msg: Message) -> None:ctx = self._request_ctx.get(str(msg.id))@@ -210,6 +806,12 @@ class AcpChannel(BaseChannel):pending = self._pending_client_rpc_session_by_id.pop(jsonrpc_id, None)session_id = pending[0] if isinstance(pending, tuple) else None+ if not session_id:+ logger.info(+ "[ACP] ignoring unknown/late stdio jsonrpc response: jsonrpc_id=%s",+ jsonrpc_id,+ )+ returnmsg = build_acp_tool_response_message(jsonrpc_id=jsonrpc_id,response_data=data,@@ -217,6 +819,8 @@ class AcpChannel(BaseChannel):channel_id=self.channel_id,)await self._dispatch_message(msg)+ if session_id:+ await self._maybe_finalize_deferred_prompts(session_id)def _parse_envelope(self, data: dict[str, Any]) -> E2AEnvelope:env = E2AEnvelope.from_dict(dict(data))@@ -455,10 +1059,17 @@ class AcpChannel(BaseChannel):await self._handle_jsonrpc_session_cancel(rpc_id, params)returnif method == "session/list":- await self._write_jsonrpc_result(rpc_id, {"sessions": []})+ await self._write_jsonrpc_result(+ rpc_id,+ build_acp_session_list_result(sorted(self._known_sessions)),+ )returnif method == "session/load":- await self._write_jsonrpc_result(rpc_id, None)+ await self._write_jsonrpc_error(+ rpc_id,+ -32601,+ "Method not supported by agent capabilities: session/load",+ )returnawait self._write_jsonrpc_error(rpc_id, -32601, f"Method not found: {method}")except ValueError as exc:@@ -486,36 +1097,7 @@ class AcpChannel(BaseChannel):logger.debug("[ACP] failed to forward initialize to gateway", exc_info=True)def _initialize_result(self) -> dict[str, Any]:- return {- "protocolVersion": _ACP_PROTOCOL_VERSION,- "agentInfo": {- "name": "jiuwenclaw",- "title": "JiuwenClaw",- "version": __version__,- },- "agentCapabilities": {- "loadSession": False,- "promptCapabilities": {- "image": False,- "audio": False,- "embeddedContext": False,- },- "sessionCapabilities": {- "list": {},- },- "fs": {- "readTextFile": True,- "writeTextFile": True,- },- "terminal": {- "create": True,- "output": True,- "waitForExit": True,- "release": True,- },- },- "authMethods": [],- }+ return build_acp_initialize_result()async def _handle_jsonrpc_session_new(self,@@ -523,12 +1105,11 @@ class AcpChannel(BaseChannel):params: dict[str, Any],) -> None:session_id = str(params.get("sessionId") or f"acp_{uuid.uuid4().hex[:12]}").strip()+ self._known_sessions.add(session_id)self._session_ctx[session_id] = dict(params)await self._write_jsonrpc_result(rpc_id,- {- "sessionId": session_id,- },+ build_acp_session_new_result(session_id),)async def _handle_jsonrpc_session_prompt(@@ -539,6 +1120,7 @@ class AcpChannel(BaseChannel):session_id = str(params.get("sessionId") or "").strip()if not session_id:raise ValueError("sessionId is required")+ self._known_sessions.add(session_id)rpc_params = dict(params)prompt = rpc_params.get("prompt")@@ -569,6 +1151,7 @@ class AcpChannel(BaseChannel):method=env.method,response_mode="jsonrpc",session_id=session_id,+ user_message_id=str(rpc_params.get("messageId") or "").strip() or None,)self._active_prompt_request_by_session[session_id] = msg.idawait self._dispatch_message(msg)@@ -629,6 +1212,54 @@ class AcpChannel(BaseChannel):except asyncio.CancelledError:pass+ def _session_has_pending_client_rpcs(self, session_id: str | None) -> bool:+ sid = str(session_id or "").strip()+ if not sid:+ return False+ return any(+ isinstance(entry, tuple) and len(entry) >= 1 and str(entry[0] or "").strip() == sid+ for entry in self._pending_client_rpc_session_by_id.values()+ )++ def _collect_finalizable_request_ids(self, session_id: str) -> list[str]:+ result = []+ for request_id, ctx in self._request_ctx.items():+ if ctx.response_mode != "jsonrpc":+ continue+ if str(ctx.session_id or "") != session_id:+ continue+ if not str(ctx.pending_stop_reason or "").strip():+ continue+ result.append(request_id)+ return result++ async def _maybe_finalize_deferred_prompts(self, session_id: str | None) -> None:+ sid = str(session_id or "").strip()+ if not sid or self._session_has_pending_client_rpcs(sid):+ return++ matched_ids = self._collect_finalizable_request_ids(sid)+ for request_id in matched_ids:+ ctx = self._request_ctx.get(request_id)+ if ctx is None:+ continue+ stop_reason = str(ctx.pending_stop_reason or "").strip()+ if not stop_reason:+ continue+ ctx.pending_stop_reason = None+ if _should_wait_for_final_text_before_end_turn(ctx):+ self._schedule_idle_finalize(request_id, ctx)+ continue+ _cancel_idle_finalize_task(ctx)+ await self._write_jsonrpc_result(+ ctx.jsonrpc_id,+ build_acp_prompt_result(+ stop_reason=stop_reason,+ user_message_id=ctx.user_message_id,+ ),+ )+ await self._clear_request_context(request_id)+def _schedule_idle_finalize(self, request_id: str, ctx: _AcpRequestContext) -> None:task = ctx.idle_finalize_taskif task is not None:@@ -650,11 +1281,16 @@ class AcpChannel(BaseChannel):# to prevent a superseded task from finalizing after being replaced.if ctx.idle_finalize_task is not current_task:return+ if self._session_has_pending_client_rpcs(ctx.session_id):+ ctx.pending_stop_reason = "end_turn"+ ctx.idle_finalize_task = None+ returnawait self._write_jsonrpc_result(ctx.jsonrpc_id,- {- "stopReason": "end_turn",- },+ build_acp_prompt_result(+ stop_reason="end_turn",+ user_message_id=ctx.user_message_id,+ ),)await self._clear_request_context(str(request_id))except asyncio.CancelledError:@@ -672,9 +1308,10 @@ class AcpChannel(BaseChannel):continueawait self._write_jsonrpc_result(ctx.jsonrpc_id,- {- "stopReason": stop_reason,- },+ build_acp_prompt_result(+ stop_reason=stop_reason,+ user_message_id=ctx.user_message_id,+ ),)await self._clear_request_context(request_id)@@ -693,6 +1330,7 @@ class AcpChannel(BaseChannel):update = self._build_acp_session_update(msg, payload, ctx)if update is None:return False+ _mark_stream_activity(ctx)await self._write_acp_session_update(session_id, update)# 如果 CHAT_DELTA 携带 usage,也发送 usage_updateusage_update = build_acp_usage_update(payload)@@ -701,36 +1339,47 @@ class AcpChannel(BaseChannel):return Falseif msg.type == "event" and msg.event_type in (+ EventType.CHAT_REASONING,EventType.CHAT_TOOL_CALL,+ EventType.CHAT_TOOL_UPDATE,EventType.CHAT_TOOL_RESULT,+ EventType.TODO_UPDATED,EventType.CHAT_SUBTASK_UPDATE,):update = self._build_acp_session_update(msg, payload, ctx)if update is None:return False- task = ctx.idle_finalize_task- if task is not None:- task.cancel()- ctx.idle_finalize_task = None+ _mark_stream_activity(ctx)await self._write_acp_session_update(session_id, update)return Falseif msg.type == "event" and msg.event_type == EventType.CHAT_FINAL:# ACP fallback: defer end_turn until processing stops.+ ctx.saw_chat_final = Trueupdate = build_acp_final_text_update(payload, ctx)if update is not None:await self._write_acp_session_update(session_id, update)usage_update = build_acp_usage_update(payload)if usage_update is not None:await self._write_acp_session_update(session_id, usage_update)- self._schedule_idle_finalize(str(msg.id), ctx)+ if ctx.saw_processing_idle:+ if self._session_has_pending_client_rpcs(session_id):+ ctx.pending_stop_reason = "end_turn"+ return False+ _cancel_idle_finalize_task(ctx)+ await self._write_jsonrpc_result(+ ctx.jsonrpc_id,+ build_acp_prompt_result(+ stop_reason="end_turn",+ user_message_id=ctx.user_message_id,+ ),+ )+ return True+ _cancel_idle_finalize_task(ctx)return Falseif msg.type == "event" and msg.event_type == EventType.CHAT_ERROR:- task = ctx.idle_finalize_task- if task is not None:- task.cancel()- ctx.idle_finalize_task = None+ _cancel_idle_finalize_task(ctx)await self._write_jsonrpc_error(ctx.jsonrpc_id,-32603,@@ -739,15 +1388,13 @@ class AcpChannel(BaseChannel):return Trueif msg.type == "event" and msg.event_type == EventType.CHAT_INTERRUPT_RESULT:- task = ctx.idle_finalize_task- if task is not None:- task.cancel()- ctx.idle_finalize_task = None+ _cancel_idle_finalize_task(ctx)await self._write_jsonrpc_result(ctx.jsonrpc_id,- {- "stopReason": "cancelled",- },+ build_acp_prompt_result(+ stop_reason="cancelled",+ user_message_id=ctx.user_message_id,+ ),)return True@@ -757,32 +1404,38 @@ class AcpChannel(BaseChannel):if update is not None:await self._write_acp_session_update(session_id, update)if payload.get("is_processing") is False:- task = ctx.idle_finalize_task- if task is not None:- task.cancel()- ctx.idle_finalize_task = None+ ctx.saw_processing_idle = True+ if self._session_has_pending_client_rpcs(session_id):+ ctx.pending_stop_reason = "end_turn"+ return False+ if _should_wait_for_final_text_before_end_turn(ctx):+ self._schedule_idle_finalize(str(msg.id), ctx)+ return False+ _cancel_idle_finalize_task(ctx)await self._write_jsonrpc_result(ctx.jsonrpc_id,- {- "stopReason": "end_turn",- },+ build_acp_prompt_result(+ stop_reason="end_turn",+ user_message_id=ctx.user_message_id,+ ),)return True+ if payload.get("is_processing") is True:+ ctx.saw_processing_idle = False+ _cancel_idle_finalize_task(ctx)return Falsereturn Falseif msg.type == "res" and msg.ok:if payload.get("accepted") is True:return False- task = ctx.idle_finalize_task- if task is not None:- task.cancel()- ctx.idle_finalize_task = None+ _cancel_idle_finalize_task(ctx)await self._write_jsonrpc_result(ctx.jsonrpc_id,- {- "stopReason": "end_turn",- },+ build_acp_prompt_result(+ stop_reason="end_turn",+ user_message_id=ctx.user_message_id,+ ),)return True@@ -1006,8 +1659,15 @@ class AcpChannel(BaseChannel):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._known_sessions.add(session_id)self._pending_client_rpc_session_by_id[jsonrpc_id] = (session_id, time.time())- self._sweep_stale_pending()+ for ctx in self._request_ctx.values():+ if ctx.response_mode == "jsonrpc" and str(ctx.session_id or "") == session_id:+ task = ctx.idle_finalize_task+ if task is not None:+ task.cancel()+ ctx.idle_finalize_task = None+ await self._sweep_stale_pending()_ACP_STDOUT.buffer.write((json.dumps(data, ensure_ascii=False) + "\n").encode("utf-8"))_ACP_STDOUT.buffer.flush()@@ -1067,10 +1727,6 @@ class AcpChannel(BaseChannel):for item in EventType:if item.value == event_name:return item- # ACP 兜底:AgentServer 会发送 chat.reasoning 事件,但 EventType 枚举中没有- # 这里将其映射为 CHAT_DELTA,让后续处理能正确识别- if event_name == "chat.reasoning":- return EventType.CHAT_DELTAreturn Nonediff --git a/jiuwenclaw/e2a/acp/__init__.py b/jiuwenclaw/e2a/acp/__init__.pyindex 8b20f9a354..56a616cfe2 100644--- a/jiuwenclaw/e2a/acp/__init__.py+++ b/jiuwenclaw/e2a/acp/__init__.py@@ -1,3 +1,7 @@+from jiuwenclaw.e2a.acp.protocol import (+ build_acp_initialize_result,+ build_acp_prompt_result,+)from jiuwenclaw.e2a.acp.session_updates import (AcpSessionUpdateState,build_acp_final_text_update,@@ -6,6 +10,8 @@ from jiuwenclaw.e2a.acp.session_updates import ()__all__ = [+ "build_acp_initialize_result",+ "build_acp_prompt_result","AcpSessionUpdateState","build_acp_final_text_update","build_acp_session_update",diff --git a/jiuwenclaw/e2a/acp/protocol.py b/jiuwenclaw/e2a/acp/protocol.pynew file mode 100644index 0000000000..56e76c94ee--- /dev/null+++ b/jiuwenclaw/e2a/acp/protocol.py@@ -0,0 +1,70 @@+from __future__ import annotations++from typing import Any++from jiuwenclaw.version import __version__+++def build_acp_initialize_result() -> dict[str, Any]:+ return {+ "protocolVersion": 1,+ "agentInfo": {+ "name": "jiuwenclaw",+ "title": "JiuwenClaw",+ "version": __version__,+ },+ "agentCapabilities": {+ "loadSession": False,+ "promptCapabilities": {+ "image": False,+ "audio": False,+ "embeddedContext": False,+ },+ "sessionCapabilities": {+ "list": {},+ },+ "mcpCapabilities": {+ "http": False,+ "sse": False,+ },+ },+ "authMethods": [],+ }+++def build_acp_session_new_result(session_id: str) -> dict[str, Any]:+ return {+ "sessionId": str(session_id or "").strip(),+ "configOptions": [],+ }+++def build_acp_session_list_result(session_ids: list[str]) -> dict[str, Any]:+ normalized = []+ seen: set[str] = set()+ for session_id in session_ids:+ sid = str(session_id or "").strip()+ if not sid or sid in seen:+ continue+ seen.add(sid)+ normalized.append({"sessionId": sid})+ return {"sessions": normalized}+++def build_acp_prompt_result(+ *,+ stop_reason: str,+ user_message_id: str | None = None,+) -> dict[str, Any]:+ result: dict[str, Any] = {"stopReason": stop_reason}+ if isinstance(user_message_id, str) and user_message_id.strip():+ result["userMessageId"] = user_message_id.strip()+ return result+++__all__ = [+ "build_acp_initialize_result",+ "build_acp_prompt_result",+ "build_acp_session_list_result",+ "build_acp_session_new_result",+]diff --git a/jiuwenclaw/e2a/acp/session_updates.py b/jiuwenclaw/e2a/acp/session_updates.pyindex 284b68fe0a..e962e0063b 100644--- a/jiuwenclaw/e2a/acp/session_updates.py+++ b/jiuwenclaw/e2a/acp/session_updates.py@@ -3,50 +3,120 @@ from __future__ import annotationsimport uuidfrom typing import Any, Protocol+from jiuwenclaw.e2a.acp_tool_updates import (+ build_acp_todo_update,+ build_acp_tool_call_update,+ build_acp_tool_result_update,+ is_reasoning_event,+)from jiuwenclaw.schema.message import EventType, Messageclass AcpSessionUpdateState(Protocol):assistant_message_id: str | None+ assistant_text: str | Nonethought_message_id: str | None+ thought_text: str | None+ user_message_id: str | None+ tool_call_cache: dict[str, dict[str, Any]] | None+++def _ensure_tool_call_cache(state: AcpSessionUpdateState) -> dict[str, dict[str, Any]]:+ cache = getattr(state, "tool_call_cache", None)+ if not isinstance(cache, dict):+ cache = {}+ state.tool_call_cache = cache+ return cachedef _ensure_assistant_message_id(state: AcpSessionUpdateState) -> str:if not state.assistant_message_id:- state.assistant_message_id = f"msg_{uuid.uuid4().hex[:12]}"+ state.assistant_message_id = str(uuid.uuid4())+ return str(state.assistant_message_id)+++def _reset_assistant_message_id(state: AcpSessionUpdateState) -> str:+ state.assistant_message_id = str(uuid.uuid4())return str(state.assistant_message_id)def _ensure_thought_message_id(state: AcpSessionUpdateState) -> str:if not state.thought_message_id:- state.thought_message_id = f"thought_{uuid.uuid4().hex[:12]}"+ state.thought_message_id = str(uuid.uuid4())+ return str(state.thought_message_id)+++def _reset_thought_message_id(state: AcpSessionUpdateState) -> str:+ state.thought_message_id = str(uuid.uuid4())return str(state.thought_message_id)+def _append_state_text(state: AcpSessionUpdateState, attr: str, text: str) -> None:+ current = getattr(state, attr, None)+ setattr(state, attr, f"{str(current or '')}{text}")+++def _build_incremental_text_update(+ *,+ text: str,+ state: AcpSessionUpdateState,+ text_attr: str,+ ensure_message_id,+ reset_message_id,+ update_kind: str,+) -> dict[str, Any] | None:+ if not text:+ return None++ existing_text = str(getattr(state, text_attr, None) or "")+ if existing_text:+ if text == existing_text:+ return None+ if text.startswith(existing_text):+ delta_text = text[len(existing_text):]+ if not delta_text:+ return None+ _append_state_text(state, text_attr, delta_text)+ return {+ "sessionUpdate": update_kind,+ "messageId": ensure_message_id(state),+ "content": {"type": "text", "text": delta_text},+ }++ setattr(state, text_attr, text)+ return {+ "sessionUpdate": update_kind,+ "messageId": reset_message_id(state),+ "content": {"type": "text", "text": text},+ }++ _append_state_text(state, text_attr, text)+ return {+ "sessionUpdate": update_kind,+ "messageId": ensure_message_id(state),+ "content": {"type": "text", "text": text},+ }++def build_acp_session_update(msg: Message,payload: dict[str, Any],state: AcpSessionUpdateState,) -> dict[str, Any] | None:event_type = msg.event_type- if event_type == EventType.CHAT_DELTA:+ if event_type in (EventType.CHAT_DELTA, EventType.CHAT_REASONING):text = str(payload.get("content", "") or "")if not text:return None- source_chunk_type = str(payload.get("source_chunk_type") or "")- payload_event_type = str(payload.get("event_type") or "")- is_reasoning = (- source_chunk_type == "llm_reasoning"- or payload_event_type == "chat.reasoning"- )-- if is_reasoning:+ if is_reasoning_event(event_type, payload):+ _append_state_text(state, "thought_text", text)return {"sessionUpdate": "agent_thought_chunk","messageId": _ensure_thought_message_id(state),"content": {"type": "text", "text": text},}+ _append_state_text(state, "assistant_text", text)return {"sessionUpdate": "agent_message_chunk","messageId": _ensure_assistant_message_id(state),@@ -54,38 +124,10 @@ def build_acp_session_update(}if event_type == EventType.CHAT_TOOL_CALL:- tool_call = payload.get("tool_call")- if not isinstance(tool_call, dict):- return None- tool_call_id = str(- tool_call.get("tool_call_id")- or tool_call.get("toolCallId")- or tool_call.get("id")- or ""- )- return {- "sessionUpdate": "tool_call",- "toolCall": {- "id": tool_call_id,- "name": str(tool_call.get("name") or ""),- "arguments": tool_call.get("arguments", {}),- },- }+ return build_acp_tool_call_update(payload, cache=_ensure_tool_call_cache(state))- if event_type == EventType.CHAT_TOOL_RESULT:- tool_call_id = str(payload.get("tool_call_id") or payload.get("toolCallId") or "")- tool_name = str(payload.get("tool_name") or payload.get("name") or "")- result: Any = payload.get("result")- if result is None:- result = payload.get("content", "")- update = {- "sessionUpdate": "tool_call_update",- "toolCallId": tool_call_id,- "result": result,- }- if tool_name:- update["toolName"] = tool_name- return update+ if event_type in (EventType.CHAT_TOOL_UPDATE, EventType.CHAT_TOOL_RESULT):+ return build_acp_tool_result_update(payload, cache=_ensure_tool_call_cache(state))if event_type == EventType.CHAT_SUBTASK_UPDATE:return {@@ -93,6 +135,9 @@ def build_acp_session_update("plan": dict(payload),}+ if event_type == EventType.TODO_UPDATED:+ return build_acp_todo_update(payload)+if event_type == EventType.CHAT_PROCESSING_STATUS:return {"sessionUpdate": "session_info_update",@@ -110,21 +155,24 @@ def build_acp_final_text_update(if not text:return None- if str(payload.get("event_type") or "") == "chat.reasoning":- return {- "sessionUpdate": "agent_thought_chunk",- "messageId": _ensure_thought_message_id(state),- "content": {"type": "text", "text": text},- }-- if state.assistant_message_id:- return None+ if is_reasoning_event("chat.final", payload):+ return _build_incremental_text_update(+ text=text,+ state=state,+ text_attr="thought_text",+ ensure_message_id=_ensure_thought_message_id,+ reset_message_id=_reset_thought_message_id,+ update_kind="agent_thought_chunk",+ )- return {- "sessionUpdate": "agent_message_chunk",- "messageId": _ensure_assistant_message_id(state),- "content": {"type": "text", "text": text},- }+ return _build_incremental_text_update(+ text=text,+ state=state,+ text_attr="assistant_text",+ ensure_message_id=_ensure_assistant_message_id,+ reset_message_id=_reset_assistant_message_id,+ update_kind="agent_message_chunk",+ )def build_acp_usage_update(payload: dict[str, Any]) -> dict[str, Any] | None:diff --git a/jiuwenclaw/e2a/acp_tool_updates.py b/jiuwenclaw/e2a/acp_tool_updates.pynew file mode 100644index 0000000000..6414b1548a--- /dev/null+++ b/jiuwenclaw/e2a/acp_tool_updates.py@@ -0,0 +1,519 @@+from __future__ import annotations++import json+from pathlib import PurePath+from typing import Any, Iterable+++_TOOL_NAME_ALIASES = {+ "free_search": "mcp_free_search",+ "paid_search": "mcp_paid_search",+ "fetch_webpage": "mcp_fetch_webpage",+ "exec_command": "mcp_exec_command",+}++_LIST_TOOL_ALIASES = frozenset(+ {+ "list",+ "list_dir",+ "list_directories",+ "list_directory",+ "list_files",+ "list_paths",+ "ls",+ "glob",+ }+)++_SEARCH_TOOL_NAMES = frozenset(+ {+ "grep",+ "glob",+ "glob_file_search",+ "mcp_free_search",+ "mcp_paid_search",+ "search",+ }+)++_READ_TOOL_NAMES = frozenset(+ {+ "list",+ "list_dir",+ "list_directories",+ "list_directory",+ "list_files",+ "list_paths",+ "ls",+ "memory_get",+ "read",+ "read_file",+ "read_memory",+ "read_terminal_output",+ "read_text_file",+ "view",+ }+)++_EDIT_TOOL_NAMES = frozenset(+ {+ "apply_patch",+ "edit",+ "edit_file",+ "search_replace",+ "write",+ "write_file",+ "write_memory",+ "write_text_file",+ }+)++_DELETE_TOOL_NAMES = frozenset({"delete", "remove", "remove_file", "rm"})+_MOVE_TOOL_NAMES = frozenset({"move", "move_file", "rename", "rename_file"})+_EXECUTE_TOOL_NAMES = frozenset(+ {+ "bash",+ "create_terminal",+ "exec",+ "exec_command",+ "mcp_exec_command",+ "release_terminal",+ "run",+ "shell",+ "terminal_create",+ "wait_for_terminal_exit",+ }+)+_FETCH_TOOL_NAMES = frozenset({"fetch", "fetch_webpage", "mcp_fetch_webpage"})+_TERMINAL_CREATE_TOOL_NAMES = frozenset({"create_terminal", "terminal_create"})+_TERMINAL_WAIT_EXIT_TOOL_NAMES = frozenset({"wait_for_terminal_exit"})++_PATH_KEYS = (+ "path",+ "file_path",+ "file",+ "dir_path",+ "target_path",+ "destination",+ "source",+ "cwd",+ "root",+)+++def is_reasoning_event(event_type: Any, payload: dict[str, Any]) -> bool:+ event_name = getattr(event_type, "value", event_type)+ if str(event_name or "") == "chat.reasoning":+ return True+ source_chunk_type = str(payload.get("source_chunk_type") or "")+ payload_event_type = str(payload.get("event_type") or "")+ return source_chunk_type == "llm_reasoning" or payload_event_type == "chat.reasoning"+++def normalize_tool_name(tool_name: str) -> str:+ normalized = str(tool_name or "").strip()+ return _TOOL_NAME_ALIASES.get(normalized, normalized)+++def build_acp_tool_descriptor(+ tool_name: str,+ arguments: Any,+ *,+ tool_call_id: str,+ status: str | None = None,+ raw_output: Any = None,+ title: str | None = None,+ kind: str | None = None,+) -> dict[str, Any]:+ raw_input = _normalize_arguments(arguments)+ normalized_name = normalize_tool_name(tool_name)+ resolved_kind = str(kind or _infer_tool_kind(normalized_name)).strip() or "other"+ resolved_title = str(title or _build_tool_title(normalized_name, raw_input)).strip()++ descriptor: dict[str, Any] = {+ "toolCallId": str(tool_call_id or "").strip(),+ "title": resolved_title,+ "kind": resolved_kind,+ }+ if status:+ descriptor["status"] = str(status)+ if raw_input:+ descriptor["rawInput"] = raw_input+ locations = _extract_locations(raw_input)+ if locations:+ descriptor["locations"] = locations+ if raw_output is not None and not _is_list_like_tool_name(normalized_name):+ descriptor["rawOutput"] = raw_output+ return descriptor+++def build_acp_tool_call_update(+ payload: dict[str, Any],+ cache: dict[str, dict[str, Any]] | None = None,+) -> dict[str, Any] | None:+ tool_call = payload.get("tool_call")+ if not isinstance(tool_call, dict):+ return None++ tool_call_id = _resolve_tool_call_id(tool_call)+ if not tool_call_id:+ return None++ original_name = str(tool_call.get("name") or "")+ arguments = tool_call.get("arguments", {})+ descriptor = build_acp_tool_descriptor(+ original_name,+ arguments,+ tool_call_id=tool_call_id,+ status=str(tool_call.get("status") or payload.get("status") or "pending"),+ title=tool_call.get("title") or payload.get("title"),+ kind=tool_call.get("kind") or payload.get("kind"),+ )++ update = {+ "sessionUpdate": "tool_call",+ "toolCall": {+ "id": tool_call_id,+ "name": original_name,+ "arguments": _legacy_arguments(arguments),+ },+ **descriptor,+ }++ if cache is not None:+ cache[tool_call_id] = {+ **descriptor,+ "toolName": original_name,+ }++ return update+++def build_acp_tool_result_update(+ payload: dict[str, Any],+ cache: dict[str, dict[str, Any]] | None = None,+) -> dict[str, Any]:+ result: Any = payload.get("result")+ if result is None:+ result = payload.get("content", "")++ tool_call_id = _resolve_tool_call_id(payload)+ cached = cache.get(tool_call_id, {}) if cache and tool_call_id else {}+ tool_name = str(payload.get("tool_name") or payload.get("name") or "").strip()+ if not tool_name:+ tool_call = payload.get("toolCall")+ if isinstance(tool_call, dict):+ tool_name = str(tool_call.get("name") or "").strip()+ if not tool_name:+ tool_name = str(cached.get("toolName") or "")+ arguments = payload.get("arguments") or payload.get("rawInput")+ if arguments in (None, "", [], {}):+ tool_call = payload.get("toolCall")+ if isinstance(tool_call, dict):+ arguments = tool_call.get("arguments")+ raw_output = payload.get("rawOutput")+ if raw_output is None:+ raw_output = payload.get("raw_output")+ terminal_id = _extract_terminal_id(raw_output)++ update: dict[str, Any] = {+ "sessionUpdate": "tool_call_update",+ "toolCallId": tool_call_id,+ }+ if result not in (None, "") and not terminal_id:+ update["result"] = result+ if tool_name:+ update["toolName"] = tool_name++ if isinstance(cached, dict):+ for key in ("title", "kind", "rawInput", "locations"):+ value = cached.get(key)+ if value not in (None, "", [], {}):+ update[key] = value++ descriptor = build_acp_tool_descriptor(+ tool_name,+ arguments or update.get("rawInput") or {},+ tool_call_id=tool_call_id,+ status=_resolve_tool_result_status(payload, result, tool_name, raw_output),+ raw_output=raw_output,+ title=payload.get("title") or update.get("title"),+ kind=payload.get("kind") or update.get("kind"),+ )+ for key in ("title", "kind", "status", "rawOutput"):+ value = descriptor.get(key)+ if value not in (None, ""):+ update[key] = value++ content = _build_terminal_content_blocks(terminal_id) or _build_content_blocks(result)+ if content:+ update["content"] = content++ if cache is not None and tool_call_id:+ cache[tool_call_id] = {+ **cached,+ **{+ key: value+ for key, value in descriptor.items()+ if key in {"title", "kind", "rawInput", "locations", "rawOutput"}+ },+ "toolName": tool_name or cached.get("toolName", ""),+ }++ return update+++def build_acp_todo_update(payload: dict[str, Any]) -> dict[str, Any] | None:+ todos = payload.get("todos")+ if not isinstance(todos, Iterable) or isinstance(todos, (str, bytes, dict)):+ return None++ normalized: list[Any] = []+ for item in todos:+ if isinstance(item, dict):+ normalized.append(dict(item))+ else:+ normalized.append(item)++ return {+ "sessionUpdate": "todo_update",+ "todos": normalized,+ }+++def _resolve_tool_call_id(payload: dict[str, Any]) -> str:+ return str(+ payload.get("tool_call_id")+ or payload.get("toolCallId")+ or payload.get("id")+ or ""+ ).strip()+++def _legacy_arguments(arguments: Any) -> Any:+ if isinstance(arguments, dict):+ return arguments+ parsed = _normalize_arguments(arguments)+ return parsed or arguments or {}+++def _normalize_arguments(arguments: Any) -> dict[str, Any]:+ if isinstance(arguments, dict):+ return dict(arguments)+ if isinstance(arguments, str):+ try:+ parsed = json.loads(arguments)+ except json.JSONDecodeError:+ return {"input": arguments} if arguments.strip() else {}+ return dict(parsed) if isinstance(parsed, dict) else {"input": arguments}+ return {}+++def _infer_tool_kind(tool_name: str) -> str:+ normalized = normalize_tool_name(tool_name).lower()+ if normalized in _DELETE_TOOL_NAMES:+ return "delete"+ if normalized in _MOVE_TOOL_NAMES:+ return "move"+ if normalized in _EDIT_TOOL_NAMES:+ return "edit"+ if normalized in _EXECUTE_TOOL_NAMES:+ return "execute"+ if normalized in _FETCH_TOOL_NAMES:+ return "fetch"+ if normalized in _SEARCH_TOOL_NAMES:+ return "search"+ if normalized in _READ_TOOL_NAMES or _is_list_like_tool_name(normalized):+ return "read"+ return "other"+++def _build_tool_title(tool_name: str, arguments: dict[str, Any]) -> str:+ normalized = normalize_tool_name(tool_name).lower()+ path = _summarize_path(_first_string_value(arguments, *_PATH_KEYS))+ query = _first_string_value(arguments, "pattern", "query", "term", "text")+ url = _first_string_value(arguments, "url")+ command = _first_string_value(arguments, "command", "cmd")+ terminal_id = _first_string_value(arguments, "terminalId", "terminal_id")++ if normalized in _EXECUTE_TOOL_NAMES:+ if normalized in {"read_terminal_output", "wait_for_terminal_exit", "release_terminal"} and terminal_id:+ verb = {+ "read_terminal_output": "Reading terminal output",+ "wait_for_terminal_exit": "Waiting for terminal exit",+ "release_terminal": "Releasing terminal",+ }.get(normalized, "Running command")+ return f"{verb} {terminal_id}"+ if command:+ return f"Running {command}"+ if path:+ return f"Running in {path}"+ return "Running command"++ if normalized in _FETCH_TOOL_NAMES and url:+ return f"Fetching {url}"+ if normalized in _SEARCH_TOOL_NAMES:+ if query and path:+ return f"Searching {query} in {path}"+ if query:+ return f"Searching {query}"+ if path:+ return f"Searching in {path}"+ return "Searching"+ if normalized in _EDIT_TOOL_NAMES:+ return f"Editing {path}" if path else "Editing files"+ if normalized in _DELETE_TOOL_NAMES:+ return f"Deleting {path}" if path else "Deleting files"+ if normalized in _MOVE_TOOL_NAMES:+ destination = _summarize_path(+ _first_string_value(arguments, "destination", "dest", "target_path")+ )+ if path and destination:+ return f"Moving {path} to {destination}"+ return f"Moving {path}" if path else "Moving files"+ if _is_list_like_tool_name(normalized):+ return f"Listing {path}" if path else "Listing files"+ if normalized in _READ_TOOL_NAMES:+ return f"Reading {path}" if path else "Reading data"+ return _humanize_tool_name(tool_name)+++def _build_content_blocks(result: Any) -> list[dict[str, Any]]:+ text = str(result or "").strip()+ if not text:+ return []+ return [+ {+ "type": "content",+ "content": {+ "type": "text",+ "text": text,+ },+ }+ ]+++def _build_terminal_content_blocks(terminal_id: str | None) -> list[dict[str, Any]]:+ if not terminal_id:+ return []+ return [{"type": "terminal", "terminalId": terminal_id}]+++def _extract_locations(arguments: dict[str, Any]) -> list[dict[str, Any]]:+ locations: list[dict[str, Any]] = []+ seen: set[tuple[str, int | None]] = set()+ line = _resolve_line(arguments)++ for key in _PATH_KEYS:+ location = _location_from_value(arguments.get(key), line=line)+ if location is None:+ continue+ marker = (location["path"], location.get("line"))+ if marker not in seen:+ seen.add(marker)+ locations.append(location)++ paths_value = arguments.get("paths")+ if isinstance(paths_value, list):+ for item in paths_value[:5]:+ location = _location_from_value(item, line=line)+ if location is None:+ continue+ marker = (location["path"], location.get("line"))+ if marker not in seen:+ seen.add(marker)+ locations.append(location)++ return locations+++def _location_from_value(value: Any, *, line: int | None) -> dict[str, Any] | None:+ if not isinstance(value, str) or not value.strip():+ return None+ location: dict[str, Any] = {"path": value.strip()}+ if isinstance(line, int) and line > 0:+ location["line"] = line+ return location+++def _resolve_line(arguments: dict[str, Any]) -> int | None:+ for key in ("line", "lineno", "line_number"):+ value = arguments.get(key)+ if isinstance(value, int) and value > 0:+ return value+ return None+++def _first_string_value(arguments: dict[str, Any], *keys: str) -> str | None:+ for key in keys:+ value = arguments.get(key)+ if isinstance(value, str) and value.strip():+ return value.strip()+ return None+++def _summarize_path(path: str | None) -> str | None:+ if not path:+ return None+ try:+ pure = PurePath(path)+ except Exception:+ return path+ parts = [part for part in pure.parts if part not in ("\\", "/")]+ if not parts:+ return path+ return "/".join(parts[-3:])+++def _humanize_tool_name(tool_name: str) -> str:+ parts = [part for part in str(tool_name or "").replace(".", "_").split("_") if part]+ if not parts:+ return "Using tool"+ return " ".join(part[:1].upper() + part[1:] for part in parts)+++def _extract_terminal_id(raw_output: Any) -> str | None:+ if not isinstance(raw_output, dict):+ return None+ return _first_string_value(raw_output, "terminalId", "terminal_id")+++def _resolve_tool_result_status(+ payload: dict[str, Any],+ result: Any,+ tool_name: str,+ raw_output: Any,+) -> str:+ status = str(payload.get("status") or "").strip()+ if status:+ return status+ terminal_id = _extract_terminal_id(raw_output)+ normalized_tool_name = normalize_tool_name(tool_name).strip().lower()+ if terminal_id and normalized_tool_name in _TERMINAL_CREATE_TOOL_NAMES:+ return "in_progress"+ if (+ isinstance(raw_output, dict)+ and bool(raw_output.get("timedOut"))+ and normalized_tool_name in _TERMINAL_WAIT_EXIT_TOOL_NAMES+ ):+ return "in_progress"+ if payload.get("error") not in (None, ""):+ return "failed"+ if result not in (None, ""):+ return "completed"+ return "in_progress"+++def _is_list_like_tool_name(tool_name: str) -> bool:+ normalized = normalize_tool_name(tool_name).strip().lower()+ return normalized in _LIST_TOOL_ALIASES+++__all__ = [+ "build_acp_todo_update",+ "build_acp_tool_call_update",+ "build_acp_tool_descriptor",+ "build_acp_tool_result_update",+ "is_reasoning_event",+ "normalize_tool_name",+]diff --git a/jiuwenclaw/e2a/constants.py b/jiuwenclaw/e2a/constants.pyindex 93391e37ef..3fa93db1ea 100644--- a/jiuwenclaw/e2a/constants.py+++ b/jiuwenclaw/e2a/constants.py@@ -109,6 +109,7 @@ ACP_SESSION_UPDATE_KINDS: tuple[str, ...] = ("agent_thought_chunk","tool_call","tool_call_update",+ "todo_update","plan","available_commands_update","current_mode_update",diff --git a/jiuwenclaw/schema/message.py b/jiuwenclaw/schema/message.pyindex 70c6c0ecff..bedae90727 100644--- a/jiuwenclaw/schema/message.py+++ b/jiuwenclaw/schema/message.py@@ -122,6 +122,7 @@ class EventType(Enum):CHAT_MEDIA = "chat.media"CHAT_FILE = "chat.file"CHAT_TOOL_CALL = "chat.tool_call"+ CHAT_TOOL_UPDATE = "chat.tool_update"CHAT_TOOL_RESULT = "chat.tool_result"CONTEXT_COMPRESSED = "context.compressed"TODO_UPDATED = "todo.updated"diff --git a/tests/unit_tests/agentserver/memory/test_coding_memory_rail.py b/tests/unit_tests/agentserver/memory/test_coding_memory_rail.pyindex ad19875ec7..601d646a9b 100644--- a/tests/unit_tests/agentserver/memory/test_coding_memory_rail.py+++ b/tests/unit_tests/agentserver/memory/test_coding_memory_rail.py@@ -526,7 +526,7 @@ class TestCodingMemoryRailBeforeModelCall:"""Test read-only mode content."""coding_rail.init(mock_agent)- with open(os.path.join(temp_memory_dir, "MEMORY.md"), "w") as f:+ with open(os.path.join(temp_memory_dir, "MEMORY.md"), "w", encoding="utf-8") as f:f.write("- [Test](test.md) — Test description")inputs = MockInvokeInputs(is_cron=True)@@ -547,7 +547,7 @@ class TestCodingMemoryRailBeforeModelCall:"""Test that memory index is included."""coding_rail.init(mock_agent)- with open(os.path.join(temp_memory_dir, "MEMORY.md"), "w") as f:+ with open(os.path.join(temp_memory_dir, "MEMORY.md"), "w", encoding="utf-8") as f:f.write("- [Test](test.md) — Test description")ctx = MockContext()@@ -571,7 +571,7 @@ class TestCodingMemoryRailIntegration:coding_rail.init(mock_agent)os.makedirs(temp_memory_dir, exist_ok=True)- with open(os.path.join(temp_memory_dir, "python.md"), "w") as f:+ with open(os.path.join(temp_memory_dir, "python.md"), "w", encoding="utf-8") as f:f.write("---\n""name: Python Guide\n"@@ -580,7 +580,7 @@ class TestCodingMemoryRailIntegration:"---\n\n""Python content")- with open(os.path.join(temp_memory_dir, "MEMORY.md"), "w") as f:+ with open(os.path.join(temp_memory_dir, "MEMORY.md"), "w", encoding="utf-8") as f:f.write("- [Python Guide](python.md) — Python programming guide")inputs = MockInvokeInputs(messages=[{"role": "user", "content": "Tell me about Python"}])diff --git a/tests/unit_tests/agentserver/test_agentserver_acp.py b/tests/unit_tests/agentserver/test_agentserver_acp.pyindex 2174995971..160c71f346 100644--- a/tests/unit_tests/agentserver/test_agentserver_acp.py+++ b/tests/unit_tests/agentserver/test_agentserver_acp.py@@ -1,12 +1,15 @@import asyncioimport json+import typesimport pytestfrom jiuwenclaw.agentserver import agent_ws_server as agent_ws_server_modulefrom jiuwenclaw.agentserver.agent_manager import ACP_DEFAULT_CAPABILITIES+from jiuwenclaw.agentserver.tools import acp_output_toolsfrom 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.agentserver.stream_utils import parse_stream_chunkfrom jiuwenclaw.agentserver.deep_agent.interface_deep import _build_context_engineering_railfrom jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fieldsfrom jiuwenclaw.schema.agent import AgentRequest@@ -86,6 +89,28 @@ def _reset_acp_output_manager():mgr.set_send_push_callback(None)+def test_interface_deep_parse_stream_chunk_preserves_tool_update():+ parsed = parse_stream_chunk(+ types.SimpleNamespace(+ type="tool_update",+ payload={+ "tool_update": {+ "tool_call_id": "call-1",+ "tool_name": "read_file",+ "status": "in_progress",+ }+ },+ )+ )++ assert parsed == {+ "event_type": "chat.tool_update",+ "tool_call_id": "call-1",+ "tool_name": "read_file",+ "status": "in_progress",+ }++@pytest.mark.asyncioasync def test_handle_initialize_uses_agent_manager_capabilities(monkeypatch):server = AgentWebSocketServerHarness()@@ -277,6 +302,47 @@ async def test_handle_acp_tool_response_completes_pending_future(monkeypatch):]+async def test_handle_acp_tool_response_unknown_id_is_soft_ignored(monkeypatch):+ server = AgentWebSocketServerHarness()+ 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-acp-tool-response-unknown",+ channel_id="acp",+ req_method=ReqMethod.ACP_TOOL_RESPONSE,+ params={+ "jsonrpc_id": "unknown-42",+ "response": {+ "jsonrpc": "2.0",+ "id": "unknown-42",+ "result": {"content": "late"},+ },+ },+ )++ await server.handle_acp_tool_response_for_test(fake_ws, request, asyncio.Lock())++ assert fake_ws.sent == [+ {+ "response_id": "req-acp-tool-response-unknown",+ "payload": {+ "accepted": False,+ "ignored": True,+ "reason": "unknown_or_late_response",+ "jsonrpc_id": "unknown-42",+ },+ "ok": True,+ }+ ]++@pytest.mark.asyncioasync def test_handle_message_uses_ws_scoped_acp_client_capabilities(monkeypatch):ws_a = FakeWebSocket()@@ -330,6 +396,78 @@ async def test_handle_message_uses_ws_scoped_acp_client_capabilities(monkeypatchassert captured[id(ws_b)]["acp_client_capabilities"] == {"terminal": {"create": True}}+async def test_wait_for_terminal_exit_returns_soft_timeout(monkeypatch):+ mgr = get_acp_output_manager()+ captured: dict[str, object] = {}++ async def _fake_send_jsonrpc_request(+ method,+ params,+ *,+ channel_id="acp",+ session_id=None,+ timeout=0.0,+ ):+ captured["method"] = method+ captured["params"] = params+ captured["channel_id"] = channel_id+ captured["session_id"] = session_id+ captured["timeout"] = timeout+ raise asyncio.TimeoutError++ monkeypatch.setattr(mgr, "send_jsonrpc_request", _fake_send_jsonrpc_request)+ monkeypatch.setattr(acp_output_tools, "_ACP_WAIT_FOR_EXIT_TIMEOUT_SECONDS", 123.0)++ result = await acp_output_tools.wait_for_terminal_exit("term-soft-timeout", session_id="sess-soft")++ assert captured == {+ "method": "terminal/wait_for_exit",+ "params": {"terminalId": "term-soft-timeout"},+ "channel_id": "acp",+ "session_id": "sess-soft",+ "timeout": 123.0,+ }+ assert result == {+ "exitCode": None,+ "signal": None,+ "timedOut": True,+ "running": True,+ "shouldRetry": True,+ }+++async def test_wait_for_terminal_exit_completed_result_sets_should_retry_false(monkeypatch):+ mgr = get_acp_output_manager()++ async def _fake_send_jsonrpc_request(+ method,+ params,+ *,+ channel_id="acp",+ session_id=None,+ timeout=0.0,+ ):+ return {+ "jsonrpc": "2.0",+ "id": "ok-1",+ "result": {"exitCode": 0, "signal": None},+ }++ monkeypatch.setattr(mgr, "send_jsonrpc_request", _fake_send_jsonrpc_request)++ result = await acp_output_tools.wait_for_terminal_exit("term-done", session_id="sess-done")++ assert result == {+ "exitCode": 0,+ "signal": None,+ "timedOut": False,+ "running": False,+ "shouldRetry": False,+ }++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 ecd8293793..b2b32e3ee7 100644--- a/tests/unit_tests/channel/test_acp_channel.py+++ b/tests/unit_tests/channel/test_acp_channel.py@@ -57,6 +57,18 @@ class AcpChannelHarness(AcpChannel):async def send_jsonrpc_message_for_test(self, msg, ctx):return await self._send_jsonrpc_message(msg, ctx)+ def set_request_context_for_test(self, request_id, ctx):+ self._request_ctx[request_id] = ctx++ def set_active_prompt_request_for_test(self, session_id: str, request_id: str):+ self._active_prompt_request_by_session[session_id] = request_id++ async def handle_jsonrpc_response_for_test(self, data):+ await self._handle_jsonrpc_response(data)++ def has_request_context_for_test(self, request_id: str) -> bool:+ return request_id in self._request_ctx+def json_line(payload):return json.dumps(payload, ensure_ascii=False)@@ -175,11 +187,72 @@ async def test_jsonrpc_initialize_and_session_new(monkeypatch):agent_info = init_result.get("agentInfo")assert isinstance(agent_info, dict)assert agent_info.get("name") == "jiuwenclaw"+ capabilities = init_result.get("agentCapabilities")+ assert isinstance(capabilities, dict)+ assert capabilities.get("loadSession") is False+ assert capabilities.get("sessionCapabilities") == {"list": {}}+ assert capabilities.get("mcpCapabilities") == {"http": False, "sse": False}+ assert "fs" not in capabilities+ assert "terminal" not in capabilitiesnew_result = responses[1].get("result")assert isinstance(new_result, dict)assert responses[1].get("id") == 2assert new_result.get("sessionId") == "sess-1"+ assert new_result.get("configOptions") == []+++async def test_jsonrpc_session_list_returns_known_sessions(monkeypatch):+ fake_stdin = FakeStdin(+ [+ json_line({"jsonrpc": "2.0", "id": 10, "method": "session/new", "params": {"sessionId": "sess-1"}}),+ json_line({"jsonrpc": "2.0", "id": 11, "method": "session/list", "params": {}}),+ ]+ )+ fake_stdout = FakeStdout()+ channel = AcpChannelHarness(AcpChannelConfig(enabled=True), DummyBus())++ monkeypatch.setattr("sys.stdin", fake_stdin)+ monkeypatch.setattr("sys.stdout", fake_stdout)+ monkeypatch.setattr("jiuwenclaw.channel.acp_channel._ACP_STDOUT", fake_stdout)++ await channel.start()++ responses = fake_stdout.buffer.json_lines()+ assert responses[1] == {+ "jsonrpc": "2.0",+ "id": 11,+ "result": {"sessions": [{"sessionId": "sess-1"}]},+ }+++async def test_jsonrpc_session_load_is_rejected_when_capability_is_disabled(monkeypatch):+ fake_stdin = FakeStdin(+ [+ json_line({"jsonrpc": "2.0", "id": 21, "method": "session/load", "params": {"sessionId": "sess-1"}}),+ ]+ )+ fake_stdout = FakeStdout()+ channel = AcpChannelHarness(AcpChannelConfig(enabled=True), DummyBus())++ monkeypatch.setattr("sys.stdin", fake_stdin)+ monkeypatch.setattr("sys.stdout", fake_stdout)+ monkeypatch.setattr("jiuwenclaw.channel.acp_channel._ACP_STDOUT", fake_stdout)++ await channel.start()++ assert fake_stdout.buffer.json_lines() == [+ {+ "jsonrpc": "2.0",+ "id": 21,+ "error": {+ "code": -32601,+ "message": "Method not supported by agent capabilities: session/load",+ },+ }+ ]@pytest.mark.asyncio@@ -290,6 +363,72 @@ async def test_jsonrpc_session_prompt_emits_updates_and_final_result(monkeypatchassert result.get("stopReason") == "end_turn"+async def test_jsonrpc_session_prompt_echoes_user_message_id_in_result(monkeypatch):+ fake_stdin = FakeStdin(+ [+ json_line(+ {+ "jsonrpc": "2.0",+ "id": 303,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-user-message-id",+ "messageId": "user-msg-1",+ "text": "hello",+ },+ }+ )+ ]+ )+ fake_stdout = FakeStdout()+ channel = AcpChannel(AcpChannelConfig(enabled=True), DummyBus())++ 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):+ await channel.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "final answer"},+ event_type=EventType.CHAT_FINAL,+ )+ )+ await channel.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )+ channel.on_message(_on_message)+ await channel.start()++ responses = fake_stdout.buffer.json_lines()+ assert responses[-1] == {+ "jsonrpc": "2.0",+ "id": 303,+ "result": {+ "stopReason": "end_turn",+ "userMessageId": "user-msg-1",+ },+ }++@pytest.mark.asyncioasync def test_jsonrpc_session_prompt_accepts_text_param(monkeypatch):fake_stdin = FakeStdin(@@ -530,7 +669,7 @@ async def test_jsonrpc_session_prompt_merges_session_context(monkeypatch):@pytest.mark.asyncio-async def test_jsonrpc_session_prompt_auto_finalizes_after_idle_after_chat_final(monkeypatch):+async def test_jsonrpc_session_prompt_does_not_end_turn_from_chat_final_before_late_tool_result(monkeypatch):fake_stdin = FakeStdin([json_line(@@ -569,22 +708,66 @@ async def test_jsonrpc_session_prompt_auto_finalizes_after_idle_after_chat_finalevent_type=EventType.CHAT_FINAL,))+ await channel.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={+ "tool_name": "write_text_file",+ "tool_call_id": "tool-call-late-2",+ "result": "index.html written",+ },+ event_type=EventType.CHAT_TOOL_RESULT,+ )+ )+ await channel.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )channel.on_message(_on_message)await channel.start()responses = fake_stdout.buffer.json_lines()- assert len(responses) == 2+ assert len(responses) == 4# 第一个响应是 agent_message_chunkassert responses[0].get("method") == "session/update"message_chunk = responses[0].get("params")assert isinstance(message_chunk, dict)assert message_chunk.get("update").get("sessionUpdate") == "agent_message_chunk"- # 第二个响应是 idle finalize 触发的 end_turn- result = responses[1].get("result")+ # 第二个响应是晚到的 tool result update+ assert responses[1]["params"]["update"] == {+ "sessionUpdate": "tool_call_update",+ "toolCallId": "tool-call-late-2",+ "toolName": "write_text_file",+ "title": "Editing files",+ "kind": "edit",+ "status": "completed",+ "result": "index.html written",+ "content": [{"type": "content", "content": {"type": "text", "text": "index.html written"}}],+ }+ assert responses[2]["params"]["update"] == {+ "sessionUpdate": "session_info_update",+ "status": "idle",+ }+ result = responses[3].get("result")assert isinstance(result, dict)- assert responses[1].get("id") == 12+ assert responses[3].get("id") == 12assert result.get("stopReason") == "end_turn"@@ -745,146 +928,433 @@ async def test_jsonrpc_response_is_forwarded_as_acp_tool_response(monkeypatch):@pytest.mark.asyncio-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"---async def test_jsonrpc_session_prompt_emits_tool_call_update(monkeypatch):+async def test_jsonrpc_response_without_pending_mapping_is_ignored(monkeypatch):fake_stdin = FakeStdin([json_line({"jsonrpc": "2.0",- "id": 30,- "method": "session/prompt",- "params": {- "sessionId": "sess-tool-call",- "prompt": [{"type": "text", "text": "hello"}],- },+ "id": "tool-missing",+ "result": {"content": "late"},})])fake_stdout = FakeStdout()- channel = AcpChannel(AcpChannelConfig(enabled=True), DummyBus())+ channel = AcpChannelHarness(AcpChannelConfig(enabled=True), DummyBus())+ seen = []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):- # 发送工具调用- await channel.send(- Message(- id=msg.id,- type="event",- channel_id="acp",- session_id=msg.session_id,- params={},- timestamp=time.time(),- ok=True,- payload={- "tool_call": {- "name": "read_file",- "arguments": {"path": "demo.txt"},- "tool_call_id": "tool-call-1",- }- },- event_type=EventType.CHAT_TOOL_CALL,- )- )- # 发送最终回复 (CHAT_DELTA)- await channel.send(- Message(- id=msg.id,- type="event",- channel_id="acp",- session_id=msg.session_id,- params={},- timestamp=time.time(),- ok=True,- payload={"content": "done"},- event_type=EventType.CHAT_DELTA,- )- )- # 发送 is_processing=false 触发最终响应- await channel.send(- Message(- id=msg.id,- type="event",- channel_id="acp",- session_id=msg.session_id,- params={},- timestamp=time.time(),- ok=True,- payload={"is_processing": False},- event_type=EventType.CHAT_PROCESSING_STATUS,- )- )+ seen.append(msg)channel.on_message(_on_message)await channel.start()- responses = fake_stdout.buffer.json_lines()- assert len(responses) == 4- assert responses[0]["params"]["update"] == {- "sessionUpdate": "tool_call",- "toolCall": {- "id": "tool-call-1",- "name": "read_file",- "arguments": {"path": "demo.txt"},- },- }-- message_chunk = responses[1]["params"]["update"]- assert message_chunk["sessionUpdate"] == "agent_message_chunk"-- idle_update = responses[2]["params"]["update"]- assert idle_update["sessionUpdate"] == "session_info_update"- assert idle_update["status"] == "idle"-- assert responses[3]["result"]["stopReason"] == "end_turn"+ assert seen == []+ assert fake_stdout.buffer.json_lines() == []@pytest.mark.asyncio-async def test_jsonrpc_session_prompt_emits_tool_result_update(monkeypatch):- fake_stdin = FakeStdin(- [- json_line(- {- "jsonrpc": "2.0",- "id": 31,- "method": "session/prompt",- "params": {- "sessionId": "sess-tool-result",- "prompt": [{"type": "text", "text": "hello"}],- },- }+async def test_processing_idle_defers_end_turn_until_pending_client_rpc_resolves(monkeypatch):+ fake_stdout = FakeStdout()+ channel = AcpChannelHarness(AcpChannelConfig(enabled=True), DummyBus())+ seen = []+ request_id = "req-pending-client-rpc"+ session_id = "sess-pending-client-rpc"+ ctx = types.SimpleNamespace(+ jsonrpc_id=501,+ method="session/prompt",+ response_mode="jsonrpc",+ session_id=session_id,+ user_message_id="user-msg-pending",+ assistant_message_id=None,+ thought_message_id=None,+ tool_call_cache={},+ pending_stop_reason=None,+ sequence=0,+ idle_finalize_task=None,+ )++ channel.set_request_context_for_test(request_id, ctx)+ channel.set_pending_client_rpc_session_for_test("tool-pending-1", session_id)++ 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)++ is_final = await channel.send_jsonrpc_message_for_test(+ Message(+ id=request_id,+ type="event",+ channel_id="acp",+ session_id=session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ ),+ ctx,+ )++ assert is_final is False+ assert ctx.pending_stop_reason == "end_turn"+ assert fake_stdout.buffer.json_lines() == [+ {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "sessionId": session_id,+ "update": {+ "sessionUpdate": "session_info_update",+ "status": "idle",+ },+ },+ }+ ]++ await channel.handle_jsonrpc_response_for_test(+ {+ "jsonrpc": "2.0",+ "id": "tool-pending-1",+ "result": {"ok": True},+ }+ )++ responses = fake_stdout.buffer.json_lines()+ assert responses[-1] == {+ "jsonrpc": "2.0",+ "id": 501,+ "result": {+ "stopReason": "end_turn",+ "userMessageId": "user-msg-pending",+ },+ }+ assert channel.has_request_context_for_test(request_id) is False+ assert len(seen) == 1+ assert seen[0].req_method == ReqMethod.ACP_TOOL_RESPONSE+ assert seen[0].session_id == session_id+++async def test_processing_idle_waits_for_late_chat_final_and_only_emits_missing_suffix(monkeypatch):+ fake_stdout = FakeStdout()+ channel = AcpChannelHarness(AcpChannelConfig(enabled=True), DummyBus())+ request_id = "req-late-final"+ session_id = "sess-late-final"+ ctx = types.SimpleNamespace(+ jsonrpc_id=551,+ method="session/prompt",+ response_mode="jsonrpc",+ session_id=session_id,+ user_message_id=None,+ assistant_message_id=None,+ assistant_text=None,+ thought_message_id=None,+ thought_text=None,+ tool_call_cache={},+ pending_stop_reason=None,+ saw_chat_final=False,+ saw_processing_idle=False,+ sequence=0,+ idle_finalize_task=None,+ )++ monkeypatch.setattr("sys.stdout", fake_stdout)+ monkeypatch.setattr("jiuwenclaw.channel.acp_channel._ACP_STDOUT", fake_stdout)++ first_is_final = await channel.send_jsonrpc_message_for_test(+ Message(+ id=request_id,+ type="event",+ channel_id="acp",+ session_id=session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "partial"},+ event_type=EventType.CHAT_DELTA,+ ),+ ctx,+ )+ second_is_final = await channel.send_jsonrpc_message_for_test(+ Message(+ id=request_id,+ type="event",+ channel_id="acp",+ session_id=session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ ),+ ctx,+ )+ third_is_final = await channel.send_jsonrpc_message_for_test(+ Message(+ id=request_id,+ type="event",+ channel_id="acp",+ session_id=session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "partial final answer"},+ event_type=EventType.CHAT_FINAL,+ ),+ ctx,+ )++ assert first_is_final is False+ assert second_is_final is False+ assert third_is_final is True++ responses = fake_stdout.buffer.json_lines()+ assert responses == [+ {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "sessionId": session_id,+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "messageId": ctx.assistant_message_id,+ "content": {"type": "text", "text": "partial"},+ },+ },+ },+ {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "sessionId": session_id,+ "update": {+ "sessionUpdate": "session_info_update",+ "status": "idle",+ },+ },+ },+ {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "sessionId": session_id,+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "messageId": ctx.assistant_message_id,+ "content": {"type": "text", "text": " final answer"},+ },+ },+ },+ {+ "jsonrpc": "2.0",+ "id": 551,+ "result": {"stopReason": "end_turn"},+ },+ ]+++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"+++async def test_gateway_jsonrpc_request_only_writes_raw_jsonrpc_for_active_prompt(monkeypatch):+ fake_stdout = FakeStdout()+ channel = AcpChannelHarness(AcpChannelConfig(enabled=True), DummyBus())+ request_id = "req-visible-pending-rpc"+ session_id = "sess-visible-pending-rpc"+ ctx = types.SimpleNamespace(+ jsonrpc_id=777,+ method="session/prompt",+ response_mode="jsonrpc",+ session_id=session_id,+ user_message_id="user-msg-visible-rpc",+ assistant_message_id=None,+ thought_message_id=None,+ tool_call_cache={},+ pending_stop_reason=None,+ sequence=0,+ idle_finalize_task=None,+ )+ channel.set_request_context_for_test(request_id, ctx)+ channel.set_active_prompt_request_for_test(session_id, request_id)++ 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-3",+ "method": "fs/read_text_file",+ "params": {"path": "workspace/demo.txt", "sessionId": session_id},+ }+ )++ responses = fake_stdout.buffer.json_lines()+ assert responses == [+ {+ "jsonrpc": "2.0",+ "id": "tool-3",+ "method": "fs/read_text_file",+ "params": {"path": "workspace/demo.txt", "sessionId": session_id},+ }+ ]+++async def test_jsonrpc_session_prompt_emits_tool_call_update(monkeypatch):+ fake_stdin = FakeStdin(+ [+ json_line(+ {+ "jsonrpc": "2.0",+ "id": 30,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-tool-call",+ "prompt": [{"type": "text", "text": "hello"}],+ },+ }+ )+ ]+ )+ fake_stdout = FakeStdout()+ channel = AcpChannel(AcpChannelConfig(enabled=True), DummyBus())++ 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):+ # 发送工具调用+ await channel.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={+ "tool_call": {+ "name": "read_file",+ "arguments": {"path": "demo.txt"},+ "tool_call_id": "tool-call-1",+ }+ },+ event_type=EventType.CHAT_TOOL_CALL,+ )+ )+ # 发送最终回复 (CHAT_DELTA)+ await channel.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "done"},+ event_type=EventType.CHAT_DELTA,+ )+ )+ # 发送 is_processing=false 触发最终响应+ await channel.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )++ channel.on_message(_on_message)+ await channel.start()++ responses = fake_stdout.buffer.json_lines()+ assert len(responses) == 4+ assert responses[0]["params"]["update"] == {+ "sessionUpdate": "tool_call",+ "toolCall": {+ "id": "tool-call-1",+ "name": "read_file",+ "arguments": {"path": "demo.txt"},+ },+ "toolCallId": "tool-call-1",+ "title": "Reading demo.txt",+ "kind": "read",+ "status": "pending",+ "rawInput": {"path": "demo.txt"},+ "locations": [{"path": "demo.txt"}],+ }++ message_chunk = responses[1]["params"]["update"]+ assert message_chunk["sessionUpdate"] == "agent_message_chunk"++ idle_update = responses[2]["params"]["update"]+ assert idle_update["sessionUpdate"] == "session_info_update"+ assert idle_update["status"] == "idle"++ assert responses[3]["result"]["stopReason"] == "end_turn"+++async def test_jsonrpc_session_prompt_emits_tool_result_update(monkeypatch):+ fake_stdin = FakeStdin(+ [+ json_line(+ {+ "jsonrpc": "2.0",+ "id": 31,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-tool-result",+ "prompt": [{"type": "text", "text": "hello"}],+ },+ })])@@ -952,7 +1422,11 @@ async def test_jsonrpc_session_prompt_emits_tool_result_update(monkeypatch):"sessionUpdate": "tool_call_update","toolCallId": "tool-call-2","toolName": "read_file",+ "title": "Reading data",+ "kind": "read",+ "status": "completed","result": "file contents",+ "content": [{"type": "content", "content": {"type": "text", "text": "file contents"}}],}message_chunk = responses[1]["params"]["update"]@@ -965,6 +1439,110 @@ async def test_jsonrpc_session_prompt_emits_tool_result_update(monkeypatch):assert responses[3]["result"]["stopReason"] == "end_turn"+async def test_jsonrpc_session_prompt_emits_tool_in_progress_update(monkeypatch):+ fake_stdin = FakeStdin(+ [+ json_line(+ {+ "jsonrpc": "2.0",+ "id": 311,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-tool-progress",+ "prompt": [{"type": "text", "text": "hello"}],+ },+ }+ )+ ]+ )+ fake_stdout = FakeStdout()+ channel = AcpChannel(AcpChannelConfig(enabled=True), DummyBus())++ 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):+ await channel.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={+ "tool_call": {+ "name": "read_file",+ "arguments": {"path": "demo.txt"},+ "tool_call_id": "tool-call-progress-1",+ }+ },+ event_type=EventType.CHAT_TOOL_CALL,+ )+ )+ await channel.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={+ "tool_call_id": "tool-call-progress-1",+ "status": "in_progress",+ },+ event_type=EventType.CHAT_TOOL_UPDATE,+ )+ )+ await channel.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )++ channel.on_message(_on_message)+ await channel.start()++ responses = fake_stdout.buffer.json_lines()+ assert responses[0]["params"]["update"] == {+ "sessionUpdate": "tool_call",+ "toolCall": {+ "id": "tool-call-progress-1",+ "name": "read_file",+ "arguments": {"path": "demo.txt"},+ },+ "toolCallId": "tool-call-progress-1",+ "title": "Reading demo.txt",+ "kind": "read",+ "status": "pending",+ "rawInput": {"path": "demo.txt"},+ "locations": [{"path": "demo.txt"}],+ }+ assert responses[1]["params"]["update"] == {+ "sessionUpdate": "tool_call_update",+ "toolCallId": "tool-call-progress-1",+ "toolName": "read_file",+ "title": "Reading demo.txt",+ "kind": "read",+ "status": "in_progress",+ "rawInput": {"path": "demo.txt"},+ "locations": [{"path": "demo.txt"}],+ }++@pytest.mark.asyncioasync def test_jsonrpc_session_prompt_emits_plan_update(monkeypatch):fake_stdin = FakeStdin(@@ -1312,3 +1890,244 @@ async def test_tool_events_cancel_idle_finalize_instead_of_scheduling(monkeypatcassert is_final is Falseassert ctx.idle_finalize_task is Noneassert sentinel_task.cancelled()+++async def test_jsonrpc_session_prompt_emits_direct_reasoning_update(monkeypatch):+ fake_stdin = FakeStdin(+ [+ json_line(+ {+ "jsonrpc": "2.0",+ "id": 37,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-reasoning-direct",+ "prompt": [{"type": "text", "text": "hello"}],+ },+ }+ )+ ]+ )+ fake_stdout = FakeStdout()+ channel = AcpChannel(AcpChannelConfig(enabled=True), DummyBus())++ 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):+ await channel.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "reasoning step", "event_type": "chat.reasoning"},+ event_type=EventType.CHAT_REASONING,+ )+ )+ await channel.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )++ channel.on_message(_on_message)+ await channel.start()++ responses = fake_stdout.buffer.json_lines()+ assert len(responses) == 3+ assert responses[0]["params"]["update"]["sessionUpdate"] == "agent_thought_chunk"+ assert responses[0]["params"]["update"]["content"] == {+ "type": "text",+ "text": "reasoning step",+ }+ assert responses[1]["params"]["update"] == {+ "sessionUpdate": "session_info_update",+ "status": "idle",+ }+ assert responses[2]["result"] == {"stopReason": "end_turn"}+++async def test_jsonrpc_session_prompt_emits_todo_update(monkeypatch):+ fake_stdin = FakeStdin(+ [+ json_line(+ {+ "jsonrpc": "2.0",+ "id": 38,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-todo-update",+ "prompt": [{"type": "text", "text": "hello"}],+ },+ }+ )+ ]+ )+ fake_stdout = FakeStdout()+ channel = AcpChannel(AcpChannelConfig(enabled=True), DummyBus())++ 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):+ await channel.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={+ "todos": [+ {+ "id": "todo-1",+ "content": "Implement ACP todo update",+ "activeForm": "Implementing ACP todo update",+ "status": "in_progress",+ "createdAt": "2026-04-16T00:00:00Z",+ "updatedAt": "2026-04-16T00:05:00Z",+ }+ ]+ },+ event_type=EventType.TODO_UPDATED,+ )+ )+ await channel.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )++ channel.on_message(_on_message)+ await channel.start()++ responses = fake_stdout.buffer.json_lines()+ assert len(responses) == 3+ assert responses[0]["params"]["update"] == {+ "sessionUpdate": "todo_update",+ "todos": [+ {+ "id": "todo-1",+ "content": "Implement ACP todo update",+ "activeForm": "Implementing ACP todo update",+ "status": "in_progress",+ "createdAt": "2026-04-16T00:00:00Z",+ "updatedAt": "2026-04-16T00:05:00Z",+ }+ ],+ }+ assert responses[1]["params"]["update"] == {+ "sessionUpdate": "session_info_update",+ "status": "idle",+ }+ assert responses[2]["result"] == {"stopReason": "end_turn"}+++async def test_reasoning_and_todo_events_cancel_idle_finalize(monkeypatch):+ import asyncio++ async def _assert_event_cancels_idle_finalize(message: Message, jsonrpc_id: int) -> None:+ fake_stdout = FakeStdout()+ channel = AcpChannelHarness(AcpChannelConfig(enabled=True), DummyBus())+ sentinel_future = asyncio.get_event_loop().create_future()+ sentinel_task = asyncio.ensure_future(sentinel_future)+ ctx = types.SimpleNamespace(+ jsonrpc_id=jsonrpc_id,+ method="session/prompt",+ response_mode="jsonrpc",+ session_id="sess-idle-cancel",+ assistant_message_id=None,+ thought_message_id=None,+ sequence=0,+ idle_finalize_task=sentinel_task,+ )++ monkeypatch.setattr("sys.stdout", fake_stdout)+ monkeypatch.setattr("jiuwenclaw.channel.acp_channel._ACP_STDOUT", fake_stdout)++ is_final = await channel.send_jsonrpc_message_for_test(message, ctx)++ assert is_final is False+ assert ctx.idle_finalize_task is None+ assert sentinel_task.cancelled()++ await _assert_event_cancels_idle_finalize(+ Message(+ id="req-reasoning-delta-idle",+ type="event",+ channel_id="acp",+ session_id="sess-idle-cancel",+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "reasoning", "source_chunk_type": "llm_reasoning"},+ event_type=EventType.CHAT_DELTA,+ ),+ 39,+ )+ await _assert_event_cancels_idle_finalize(+ Message(+ id="req-reasoning-idle",+ type="event",+ channel_id="acp",+ session_id="sess-idle-cancel",+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "reasoning", "event_type": "chat.reasoning"},+ event_type=EventType.CHAT_REASONING,+ ),+ 40,+ )+ await _assert_event_cancels_idle_finalize(+ Message(+ id="req-todo-idle",+ type="event",+ channel_id="acp",+ session_id="sess-idle-cancel",+ params={},+ timestamp=time.time(),+ ok=True,+ payload={+ "todos": [+ {+ "id": "todo-2",+ "content": "Keep session alive",+ "activeForm": "Keeping session alive",+ "status": "pending",+ "createdAt": "2026-04-16T00:00:00Z",+ "updatedAt": "2026-04-16T00:05:00Z",+ }+ ]+ },+ event_type=EventType.TODO_UPDATED,+ ),+ 41,+ )diff --git a/tests/unit_tests/e2a/test_acp_session_updates.py b/tests/unit_tests/e2a/test_acp_session_updates.pynew file mode 100644index 0000000000..2048f7d08c--- /dev/null+++ b/tests/unit_tests/e2a/test_acp_session_updates.py@@ -0,0 +1,235 @@+from types import SimpleNamespace++from jiuwenclaw.e2a.acp.session_updates import (+ build_acp_final_text_update,+ build_acp_session_update,+)+from jiuwenclaw.schema.message import EventType, Message+++def _build_message(event_type: EventType) -> Message:+ return Message(+ id="req-1",+ type="event",+ channel_id="acp",+ session_id="sess-1",+ params={},+ timestamp=0.0,+ ok=True,+ payload={},+ event_type=event_type,+ )+++def _build_state() -> SimpleNamespace:+ return SimpleNamespace(+ assistant_message_id=None,+ thought_message_id=None,+ user_message_id=None,+ tool_call_cache={},+ )+++def test_build_acp_session_update_maps_todo_updated_to_todo_update():+ update = build_acp_session_update(+ _build_message(EventType.TODO_UPDATED),+ {+ "todos": [+ {+ "id": "todo-1",+ "content": "Implement ACP todo update",+ "activeForm": "Implementing ACP todo update",+ "status": "in_progress",+ "createdAt": "2026-04-16T00:00:00Z",+ "updatedAt": "2026-04-16T00:05:00Z",+ }+ ]+ },+ _build_state(),+ )++ assert update == {+ "sessionUpdate": "todo_update",+ "todos": [+ {+ "id": "todo-1",+ "content": "Implement ACP todo update",+ "activeForm": "Implementing ACP todo update",+ "status": "in_progress",+ "createdAt": "2026-04-16T00:00:00Z",+ "updatedAt": "2026-04-16T00:05:00Z",+ }+ ],+ }+++def test_build_acp_session_update_maps_chat_reasoning_to_agent_thought_chunk():+ state = _build_state()+ update = build_acp_session_update(+ _build_message(EventType.CHAT_REASONING),+ {"content": "Reasoning chunk", "event_type": "chat.reasoning"},+ state,+ )++ assert update == {+ "sessionUpdate": "agent_thought_chunk",+ "messageId": state.thought_message_id,+ "content": {"type": "text", "text": "Reasoning chunk"},+ }+ assert isinstance(state.thought_message_id, str)+++def test_build_acp_session_update_keeps_reasoning_consistent_between_delta_and_reasoning():+ delta_state = _build_state()+ reasoning_state = _build_state()++ delta_update = build_acp_session_update(+ _build_message(EventType.CHAT_DELTA),+ {"content": "Shared reasoning", "source_chunk_type": "llm_reasoning"},+ delta_state,+ )+ reasoning_update = build_acp_session_update(+ _build_message(EventType.CHAT_REASONING),+ {"content": "Shared reasoning", "event_type": "chat.reasoning"},+ reasoning_state,+ )++ assert delta_update is not None+ assert reasoning_update is not None+ assert delta_update["sessionUpdate"] == "agent_thought_chunk"+ assert reasoning_update["sessionUpdate"] == "agent_thought_chunk"+ assert delta_update["content"] == reasoning_update["content"] == {+ "type": "text",+ "text": "Shared reasoning",+ }+++def test_build_acp_session_update_caches_tool_metadata_for_tool_result():+ state = _build_state()++ tool_call_update = build_acp_session_update(+ _build_message(EventType.CHAT_TOOL_CALL),+ {+ "tool_call": {+ "tool_call_id": "call-1",+ "name": "read_file",+ "arguments": {"path": "src/main.py"},+ }+ },+ state,+ )+ tool_result_update = build_acp_session_update(+ _build_message(EventType.CHAT_TOOL_RESULT),+ {+ "tool_call_id": "call-1",+ "result": "file contents",+ },+ state,+ )++ assert tool_call_update is not None+ assert tool_result_update == {+ "sessionUpdate": "tool_call_update",+ "toolCallId": "call-1",+ "toolName": "read_file",+ "title": "Reading src/main.py",+ "kind": "read",+ "status": "completed",+ "rawInput": {"path": "src/main.py"},+ "locations": [{"path": "src/main.py"}],+ "result": "file contents",+ "content": [{"type": "content", "content": {"type": "text", "text": "file contents"}}],+ }+++def test_build_acp_session_update_maps_tool_update_to_in_progress_status():+ state = _build_state()++ tool_call_update = build_acp_session_update(+ _build_message(EventType.CHAT_TOOL_CALL),+ {+ "tool_call": {+ "tool_call_id": "call-2",+ "name": "read_file",+ "arguments": {"path": "src/main.py"},+ }+ },+ state,+ )+ tool_progress_update = build_acp_session_update(+ _build_message(EventType.CHAT_TOOL_UPDATE),+ {+ "tool_call_id": "call-2",+ "status": "in_progress",+ },+ state,+ )++ assert tool_call_update is not None+ assert tool_progress_update == {+ "sessionUpdate": "tool_call_update",+ "toolCallId": "call-2",+ "toolName": "read_file",+ "title": "Reading src/main.py",+ "kind": "read",+ "status": "in_progress",+ "rawInput": {"path": "src/main.py"},+ "locations": [{"path": "src/main.py"}],+ }+++def test_build_acp_session_update_embeds_terminal_for_create_terminal_result():+ state = _build_state()++ tool_call_update = build_acp_session_update(+ _build_message(EventType.CHAT_TOOL_CALL),+ {+ "tool_call": {+ "tool_call_id": "call-term-1",+ "name": "create_terminal",+ "arguments": {"command": "uv run python batch_convert.py"},+ }+ },+ state,+ )+ tool_result_update = build_acp_session_update(+ _build_message(EventType.CHAT_TOOL_RESULT),+ {+ "tool_call_id": "call-term-1",+ "tool_name": "create_terminal",+ "result": "{'terminalId': 'term_1'}",+ "raw_output": {"terminalId": "term_1"},+ },+ state,+ )++ assert tool_call_update is not None+ assert tool_result_update == {+ "sessionUpdate": "tool_call_update",+ "toolCallId": "call-term-1",+ "toolName": "create_terminal",+ "title": "Running uv run python batch_convert.py",+ "kind": "execute",+ "status": "in_progress",+ "rawInput": {"command": "uv run python batch_convert.py"},+ "rawOutput": {"terminalId": "term_1"},+ "content": [{"type": "terminal", "terminalId": "term_1"}],+ }+++def test_build_acp_final_text_update_maps_reasoning_final_to_agent_thought_chunk():+ state = _build_state()++ update = build_acp_final_text_update(+ {+ "content": "Final reasoning",+ "event_type": "chat.reasoning",+ },+ state,+ )++ assert update == {+ "sessionUpdate": "agent_thought_chunk",+ "messageId": state.thought_message_id,+ "content": {"type": "text", "text": "Final reasoning"},+ }diff --git a/tests/unit_tests/e2a/test_acp_tool_updates.py b/tests/unit_tests/e2a/test_acp_tool_updates.pynew file mode 100644index 0000000000..4aa2a12178--- /dev/null+++ b/tests/unit_tests/e2a/test_acp_tool_updates.py@@ -0,0 +1,264 @@+from jiuwenclaw.e2a.acp_tool_updates import (+ build_acp_todo_update,+ build_acp_tool_call_update,+ build_acp_tool_result_update,+)+++def test_build_acp_tool_call_update_enriches_display_fields_and_preserves_legacy_shape():+ cache = {}+ update = build_acp_tool_call_update(+ {+ "tool_call": {+ "id": "call-1",+ "name": "read_file",+ "arguments": {"path": "src/main.py"},+ }+ },+ cache=cache,+ )++ assert update == {+ "sessionUpdate": "tool_call",+ "toolCall": {+ "id": "call-1",+ "name": "read_file",+ "arguments": {"path": "src/main.py"},+ },+ "toolCallId": "call-1",+ "title": "Reading src/main.py",+ "kind": "read",+ "status": "pending",+ "rawInput": {"path": "src/main.py"},+ "locations": [{"path": "src/main.py"}],+ }+ assert cache == {+ "call-1": {+ "toolCallId": "call-1",+ "title": "Reading src/main.py",+ "kind": "read",+ "status": "pending",+ "rawInput": {"path": "src/main.py"},+ "locations": [{"path": "src/main.py"}],+ "toolName": "read_file",+ }+ }+++def test_build_acp_tool_result_update_reuses_cached_metadata_and_adds_content():+ cache = {+ "call-1": {+ "toolCallId": "call-1",+ "title": "Reading src/main.py",+ "kind": "read",+ "rawInput": {"path": "src/main.py"},+ "locations": [{"path": "src/main.py"}],+ "toolName": "read_file",+ }+ }++ update = build_acp_tool_result_update(+ {+ "tool_call_id": "call-1",+ "result": "file contents",+ },+ cache=cache,+ )++ assert update == {+ "sessionUpdate": "tool_call_update",+ "toolCallId": "call-1",+ "toolName": "read_file",+ "title": "Reading src/main.py",+ "kind": "read",+ "status": "completed",+ "rawInput": {"path": "src/main.py"},+ "locations": [{"path": "src/main.py"}],+ "result": "file contents",+ "content": [{"type": "content", "content": {"type": "text", "text": "file contents"}}],+ }+++def test_build_acp_tool_result_update_supports_in_progress_without_result():+ cache = {+ "call-1": {+ "toolCallId": "call-1",+ "title": "Reading src/main.py",+ "kind": "read",+ "rawInput": {"path": "src/main.py"},+ "locations": [{"path": "src/main.py"}],+ "toolName": "read_file",+ }+ }++ update = build_acp_tool_result_update(+ {+ "tool_call_id": "call-1",+ "status": "in_progress",+ },+ cache=cache,+ )++ assert update == {+ "sessionUpdate": "tool_call_update",+ "toolCallId": "call-1",+ "toolName": "read_file",+ "title": "Reading src/main.py",+ "kind": "read",+ "status": "in_progress",+ "rawInput": {"path": "src/main.py"},+ "locations": [{"path": "src/main.py"}],+ }+++def test_build_acp_tool_result_update_embeds_terminal_for_create_terminal():+ cache = {+ "call-term-1": {+ "toolCallId": "call-term-1",+ "title": "Running uv run python batch_convert.py",+ "kind": "execute",+ "rawInput": {"command": "uv run python batch_convert.py"},+ "toolName": "create_terminal",+ }+ }++ update = build_acp_tool_result_update(+ {+ "tool_call_id": "call-term-1",+ "tool_name": "create_terminal",+ "result": "{'terminalId': 'term_1'}",+ "raw_output": {"terminalId": "term_1"},+ },+ cache=cache,+ )++ assert update == {+ "sessionUpdate": "tool_call_update",+ "toolCallId": "call-term-1",+ "toolName": "create_terminal",+ "title": "Running uv run python batch_convert.py",+ "kind": "execute",+ "status": "in_progress",+ "rawInput": {"command": "uv run python batch_convert.py"},+ "rawOutput": {"terminalId": "term_1"},+ "content": [{"type": "terminal", "terminalId": "term_1"}],+ }+++def test_build_acp_tool_result_update_keeps_wait_for_terminal_exit_timeout_in_progress():+ cache = {+ "call-wait-1": {+ "toolCallId": "call-wait-1",+ "title": "Waiting for terminal exit term_1",+ "kind": "execute",+ "rawInput": {"terminalId": "term_1"},+ "toolName": "wait_for_terminal_exit",+ }+ }++ update = build_acp_tool_result_update(+ {+ "tool_call_id": "call-wait-1",+ "tool_name": "wait_for_terminal_exit",+ "raw_output": {"timedOut": True, "running": True},+ },+ cache=cache,+ )++ assert update == {+ "sessionUpdate": "tool_call_update",+ "toolCallId": "call-wait-1",+ "toolName": "wait_for_terminal_exit",+ "title": "Waiting for terminal exit term_1",+ "kind": "execute",+ "status": "in_progress",+ "rawInput": {"terminalId": "term_1"},+ "rawOutput": {"timedOut": True, "running": True},+ }+++def test_build_acp_tool_result_update_supports_failed_without_result():+ cache = {+ "call-1": {+ "toolCallId": "call-1",+ "title": "Running pwd",+ "kind": "execute",+ "rawInput": {"command": "pwd"},+ "toolName": "terminal_create",+ }+ }++ update = build_acp_tool_result_update(+ {+ "tool_call_id": "call-1",+ "status": "failed",+ "content": "Permission denied",+ },+ cache=cache,+ )++ assert update == {+ "sessionUpdate": "tool_call_update",+ "toolCallId": "call-1",+ "toolName": "terminal_create",+ "title": "Running pwd",+ "kind": "execute",+ "status": "failed",+ "rawInput": {"command": "pwd"},+ "result": "Permission denied",+ "content": [{"type": "content", "content": {"type": "text", "text": "Permission denied"}}],+ }+++def test_build_acp_tool_result_update_omits_raw_output_for_list_directory_alias():+ update = build_acp_tool_result_update(+ {+ "tool_name": "list_directories",+ "tool_call_id": "call-list-1",+ "status": "completed",+ "rawOutput": {"list_items": [{"name": "src", "is_directory": True}]},+ "result": "[dir] src",+ }+ )++ assert update == {+ "sessionUpdate": "tool_call_update",+ "toolCallId": "call-list-1",+ "toolName": "list_directories",+ "title": "Listing files",+ "kind": "read",+ "status": "completed",+ "result": "[dir] src",+ "content": [{"type": "content", "content": {"type": "text", "text": "[dir] src"}}],+ }+++def test_build_acp_todo_update_keeps_full_snapshot_shape():+ update = build_acp_todo_update(+ {+ "todos": [+ {+ "id": "todo-1",+ "content": "Add ACP todo session update",+ "activeForm": "Adding ACP todo session update",+ "status": "in_progress",+ "createdAt": "2026-04-16T00:00:00Z",+ "updatedAt": "2026-04-16T00:05:00Z",+ }+ ]+ }+ )++ assert update == {+ "sessionUpdate": "todo_update",+ "todos": [+ {+ "id": "todo-1",+ "content": "Add ACP todo session update",+ "activeForm": "Adding ACP todo session update",+ "status": "in_progress",+ "createdAt": "2026-04-16T00:00:00Z",+ "updatedAt": "2026-04-16T00:05:00Z",+ }+ ],+ }diff --git a/tests/unit_tests/gateway/test_agent_client.py b/tests/unit_tests/gateway/test_agent_client.pynew file mode 100644index 0000000000..a0ed0a854c--- /dev/null+++ b/tests/unit_tests/gateway/test_agent_client.py@@ -0,0 +1,148 @@+import asyncio++import pytest++from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields+from jiuwenclaw.e2a.wire_codec import encode_agent_chunk_for_wire+from jiuwenclaw.gateway.agent_client import WebSocketAgentServerClient+from jiuwenclaw.schema.agent import AgentResponseChunk+++class FakeWebSocket:+ def __init__(self) -> None:+ self.sent_payloads: list[dict] = []++ async def send(self, data: str) -> None:+ self.sent_payloads.append(data)+++class AgentClientHarness(WebSocketAgentServerClient):+ def set_ws_for_test(self, ws) -> None:+ self._ws = ws++ def has_message_queue_for_test(self, request_id: str) -> bool:+ return request_id in self._message_queues++ def get_message_queue_for_test(self, request_id: str):+ return self._message_queues[request_id]+++async def test_send_request_stream_keeps_tail_window_for_processing_status(monkeypatch):+ client = AgentClientHarness()+ client.set_ws_for_test(FakeWebSocket())++ monkeypatch.setattr(+ "jiuwenclaw.gateway.agent_client._STREAM_TRAILING_MESSAGE_GRACE_SECONDS",+ 0.05,+ )++ env = e2a_from_agent_fields(+ request_id="rid-tail",+ channel_id="acp",+ session_id="sess-tail",+ params={"content": "hello"},+ is_stream=True,+ )++ async def inject_frames():+ while not client.has_message_queue_for_test("rid-tail"):+ await asyncio.sleep(0.001)+ queue = client.get_message_queue_for_test("rid-tail")+ await queue.put(+ encode_agent_chunk_for_wire(+ AgentResponseChunk(+ request_id="rid-tail",+ channel_id="acp",+ payload={"content": "partial", "event_type": "chat.delta"},+ is_complete=False,+ ),+ response_id="rid-tail",+ sequence=0,+ )+ )+ await queue.put(+ encode_agent_chunk_for_wire(+ AgentResponseChunk(+ request_id="rid-tail",+ channel_id="acp",+ payload={"is_complete": True},+ is_complete=True,+ ),+ response_id="rid-tail",+ sequence=1,+ )+ )+ await asyncio.sleep(0.01)+ await queue.put(+ encode_agent_chunk_for_wire(+ AgentResponseChunk(+ request_id="rid-tail",+ channel_id="acp",+ payload={"event_type": "chat.processing_status", "is_processing": False},+ is_complete=False,+ ),+ response_id="rid-tail",+ sequence=2,+ )+ )++ injector = asyncio.create_task(inject_frames())+ chunks = []+ async for chunk in client.send_request_stream(env):+ chunks.append(chunk)+ await injector++ assert [chunk.payload for chunk in chunks] == [+ {"content": "partial", "event_type": "chat.delta"},+ {"is_complete": True},+ {"event_type": "chat.processing_status", "is_processing": False},+ ]+ assert client.has_message_queue_for_test("rid-tail") is False+++async def test_send_request_stream_absorbs_duplicate_complete_frames(monkeypatch):+ client = AgentClientHarness()+ client.set_ws_for_test(FakeWebSocket())++ monkeypatch.setattr(+ "jiuwenclaw.gateway.agent_client._STREAM_TRAILING_MESSAGE_GRACE_SECONDS",+ 0.05,+ )++ env = e2a_from_agent_fields(+ request_id="rid-complete",+ channel_id="acp",+ session_id="sess-complete",+ params={"content": "hello"},+ is_stream=True,+ )++ async def inject_frames():+ while not client.has_message_queue_for_test("rid-complete"):+ await asyncio.sleep(0.001)+ queue = client.get_message_queue_for_test("rid-complete")+ for seq in (0, 1):+ await queue.put(+ encode_agent_chunk_for_wire(+ AgentResponseChunk(+ request_id="rid-complete",+ channel_id="acp",+ payload={"is_complete": True},+ is_complete=True,+ ),+ response_id="rid-complete",+ sequence=seq,+ )+ )++ injector = asyncio.create_task(inject_frames())+ chunks = []+ async for chunk in client.send_request_stream(env):+ chunks.append(chunk)+ await injector++ assert len(chunks) == 2+ assert all(chunk.is_complete for chunk in chunks)+ assert client.has_message_queue_for_test("rid-complete") is Falsediff --git a/tests/unit_tests/gateway/test_app_gateway_acp.py b/tests/unit_tests/gateway/test_app_gateway_acp.pyindex ee862b371a..4586e00c79 100644--- a/tests/unit_tests/gateway/test_app_gateway_acp.py+++ b/tests/unit_tests/gateway/test_app_gateway_acp.py@@ -1,4 +1,3 @@-import asyncioimport jsonimport timefrom typing import Any@@ -6,7 +5,6 @@ from typing import Anyimport pytestfrom jiuwenclaw.app_gateway import (- AcpRouteHandler,GatewayServer,GatewayServerConfig,RouteConfig,@@ -60,30 +58,29 @@ class GatewayServerProbe(GatewayServer):result = await resultreturn bool(result)+ def get_acp_pending_request_contexts_for_test(self) -> list[Any]:+ return list(self._acp_bridge.request_contexts)+def build_server() -> GatewayServerProbe:config = GatewayServerConfig(enabled=True,host="127.0.0.1",port=19001,- routes={},+ routes={+ "/acp": RouteConfig(+ path="/acp",+ channel_id="acp",+ forward_methods=frozenset({ReqMethod.CHAT_SEND.value, ReqMethod.HISTORY_GET.value}),+ ),+ "/tui": RouteConfig(+ path="/tui",+ channel_id="tui",+ forward_methods=frozenset({ReqMethod.CHAT_SEND.value, ReqMethod.HISTORY_GET.value}),+ ),+ },)server = GatewayServerProbe(config, DummyBus())- acp_handler = AcpRouteHandler(server.dispatch_public_message)- config.routes.update({- "/acp": RouteConfig(- path="/acp",- channel_id="acp",- forward_methods=frozenset({ReqMethod.CHAT_SEND.value, ReqMethod.HISTORY_GET.value}),- outbound_interceptor=acp_handler.outbound_intercept,- inbound_interceptor=acp_handler.inbound_intercept,- ),- "/tui": RouteConfig(- path="/tui",- channel_id="tui",- forward_methods=frozenset({ReqMethod.CHAT_SEND.value, ReqMethod.HISTORY_GET.value}),- ),- })return server@@ -106,6 +103,118 @@ def test_normalize_gateway_message_maps_chat_resume_to_interrupt_resume():assert normalized.session_id == "sess-1"+async def test_gateway_server_initialize_returns_current_acp_capabilities():+ server = build_server()+ ws = FakeWebSocket()++ await server.handle_raw_message_public(+ ws,+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": 1,+ "method": "initialize",+ "params": {},+ },+ ensure_ascii=False,+ ),+ )++ assert len(ws.sent_frames) == 1+ frame = ws.sent_frames[0]+ assert frame["jsonrpc"] == "2.0"+ assert frame["id"] == 1+ result = frame["result"]+ assert result["protocolVersion"] == 1+ assert result["agentInfo"]["name"] == "jiuwenclaw"+ assert result["agentCapabilities"] == {+ "loadSession": False,+ "promptCapabilities": {+ "image": False,+ "audio": False,+ "embeddedContext": False,+ },+ "sessionCapabilities": {"list": {}},+ "mcpCapabilities": {"http": False, "sse": False},+ }+ assert result["authMethods"] == []+++async def test_gateway_server_rejects_session_load_when_capability_is_disabled():+ server = build_server()+ ws = FakeWebSocket()++ await server.handle_raw_message_public(+ ws,+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": 2,+ "method": "session/load",+ "params": {"sessionId": "sess-load"},+ },+ ensure_ascii=False,+ ),+ )++ assert ws.sent_frames == [+ {+ "jsonrpc": "2.0",+ "id": 2,+ "error": {+ "code": -32601,+ "message": "Method not supported by agent capabilities: session/load",+ },+ }+ ]+++async def test_gateway_server_session_new_and_list_return_known_sessions():+ server = build_server()+ ws = FakeWebSocket()++ await server.handle_raw_message_public(+ ws,+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": 3,+ "method": "session/new",+ "params": {"sessionId": "sess-known"},+ },+ ensure_ascii=False,+ ),+ )+ await server.handle_raw_message_public(+ ws,+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": 4,+ "method": "session/list",+ "params": {},+ },+ ensure_ascii=False,+ ),+ )++ assert ws.sent_frames == [+ {+ "jsonrpc": "2.0",+ "id": 3,+ "result": {"sessionId": "sess-known", "configOptions": []},+ },+ {+ "jsonrpc": "2.0",+ "id": 4,+ "result": {"sessions": [{"sessionId": "sess-known"}]},+ },+ ]++@pytest.mark.asyncioasync def test_gateway_server_send_response_targets_request_client():server = build_server()@@ -252,74 +361,15 @@ async def test_gateway_server_passthroughs_acp_output_request_as_raw_jsonrpc():@pytest.mark.asyncio-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",- }---async def test_gateway_server_handles_acp_jsonrpc_prompt_and_streams_back_jsonrpc():+async def test_gateway_server_defers_end_turn_until_pending_client_rpc_resolves():server = build_server()ws = FakeWebSocket()seen = []async def on_message(msg):seen.append(msg)+ if msg.req_method != ReqMethod.CHAT_SEND:+ returnawait server.send(Message(id=msg.id,@@ -329,8 +379,8 @@ async def test_gateway_server_handles_acp_jsonrpc_prompt_and_streams_back_jsonrpparams={},timestamp=time.time(),ok=True,- payload={"content": "hello from gateway"},- event_type=EventType.CHAT_DELTA,+ payload={"content": "final before client rpc"},+ event_type=EventType.CHAT_FINAL,))await server.send(@@ -342,8 +392,19 @@ async def test_gateway_server_handles_acp_jsonrpc_prompt_and_streams_back_jsonrpparams={},timestamp=time.time(),ok=True,- payload={"content": "hello from gateway"},- event_type=EventType.CHAT_FINAL,+ payload={+ "event_type": "acp.output_request",+ "jsonrpc": {+ "jsonrpc": "2.0",+ "id": "tool-pending-2",+ "method": "fs/write_text_file",+ "params": {+ "path": "workspace/demo.txt",+ "content": "hello",+ "sessionId": msg.session_id,+ },+ },+ },))await server.send(@@ -367,10 +428,11 @@ async def test_gateway_server_handles_acp_jsonrpc_prompt_and_streams_back_jsonrpjson.dumps({"jsonrpc": "2.0",- "id": 99,+ "id": 211,"method": "session/prompt","params": {- "sessionId": "sess-jsonrpc",+ "sessionId": "sess-pending-rpc",+ "messageId": "user-msg-pending-rpc","text": "hello",},},@@ -378,97 +440,60 @@ async def test_gateway_server_handles_acp_jsonrpc_prompt_and_streams_back_jsonrp),)- assert len(seen) == 1- assert seen[0].req_method == ReqMethod.CHAT_SEND- assert seen[0].session_id == "sess-jsonrpc"- assert seen[0].params["query"] == "hello"-- assert ws.sent_frames[0]["method"] == "session/update"- assert ws.sent_frames[1]["method"] == "session/update"- assert ws.sent_frames[0]["params"]["sessionId"] == "sess-jsonrpc"- assert ws.sent_frames[-1] == {+ assert [frame.get("method") for frame in ws.sent_frames] == [+ "session/update",+ "fs/write_text_file",+ "session/update",+ ]+ assert ws.sent_frames[0]["params"]["update"]["sessionUpdate"] == "agent_message_chunk"+ assert ws.sent_frames[1] == {"jsonrpc": "2.0",- "id": 99,- "result": {"stopReason": "end_turn"},+ "id": "tool-pending-2",+ "method": "fs/write_text_file",+ "params": {+ "path": "workspace/demo.txt",+ "content": "hello",+ "sessionId": "sess-pending-rpc",+ },}---async def test_gateway_server_emits_agent_message_chunk_from_chat_final_when_no_delta():- server = build_server()- ws = FakeWebSocket()-- async def on_message(msg):- await server.send(- Message(- id=msg.id,- type="event",- channel_id="acp",- session_id=msg.session_id,- params={},- timestamp=time.time(),- ok=True,- payload={"content": "gateway final only"},- event_type=EventType.CHAT_FINAL,- )- )- await server.send(- Message(- id=msg.id,- type="event",- channel_id="acp",- session_id=msg.session_id,- params={},- timestamp=time.time(),- ok=True,- payload={"is_processing": False},- event_type=EventType.CHAT_PROCESSING_STATUS,- )- )-- server.on_message(on_message)+ assert ws.sent_frames[2]["params"]["update"] == {+ "sessionUpdate": "session_info_update",+ "status": "idle",+ }+ assert not any(frame.get("id") == 211 and "result" in frame for frame in ws.sent_frames)await server.handle_raw_message_public(ws,json.dumps({"jsonrpc": "2.0",- "id": 199,- "method": "session/prompt",- "params": {- "sessionId": "sess-gateway-final",- "text": "hello",- },+ "id": "tool-pending-2",+ "result": {"ok": True},},ensure_ascii=False,),)- assert ws.sent_frames[0]["method"] == "session/update"- assert ws.sent_frames[0]["params"]["sessionId"] == "sess-gateway-final"- assert ws.sent_frames[0]["params"]["update"]["sessionUpdate"] == "agent_message_chunk"- assert ws.sent_frames[0]["params"]["update"]["content"] == {- "type": "text",- "text": "gateway final only",- }- assert ws.sent_frames[1]["method"] == "session/update"- assert ws.sent_frames[1]["params"]["update"] == {- "sessionUpdate": "session_info_update",- "status": "idle",- }- assert ws.sent_frames[2] == {+ assert ws.sent_frames[-1] == {"jsonrpc": "2.0",- "id": 199,- "result": {"stopReason": "end_turn"},+ "id": 211,+ "result": {+ "stopReason": "end_turn",+ "userMessageId": "user-msg-pending-rpc",+ },}+ assert any(msg.req_method == ReqMethod.ACP_TOOL_RESPONSE for msg in seen)@pytest.mark.asyncio-async def test_gateway_server_defers_end_turn_until_processing_idle_after_final_and_tool_updates():+async def test_gateway_server_expired_pending_rpc_does_not_block_end_turn(monkeypatch):server = build_server()ws = FakeWebSocket()+ monkeypatch.setattr("jiuwenclaw.channel.acp_channel._ACP_PENDING_RPC_TIMEOUT_SECONDS", -1.0)async def on_message(msg):+ if msg.req_method != ReqMethod.CHAT_SEND:+ returnawait server.send(Message(id=msg.id,@@ -478,20 +503,7 @@ async def test_gateway_server_defers_end_turn_until_processing_idle_after_final_params={},timestamp=time.time(),ok=True,- payload={"content": "partial"},- event_type=EventType.CHAT_DELTA,- )- )- await server.send(- Message(- id=msg.id,- type="event",- channel_id="acp",- session_id=msg.session_id,- params={},- timestamp=time.time(),- ok=True,- payload={"content": "final"},+ payload={"content": "final before expired rpc"},event_type=EventType.CHAT_FINAL,))@@ -505,11 +517,18 @@ async def test_gateway_server_defers_end_turn_until_processing_idle_after_final_timestamp=time.time(),ok=True,payload={- "tool_name": "read_file",- "tool_call_id": "tool-call-9",- "result": "still running",+ "event_type": "acp.output_request",+ "jsonrpc": {+ "jsonrpc": "2.0",+ "id": "tool-expired",+ "method": "fs/write_text_file",+ "params": {+ "path": "workspace/demo.txt",+ "content": "hello",+ "sessionId": msg.session_id,+ },+ },},- event_type=EventType.CHAT_TOOL_RESULT,))await server.send(@@ -533,10 +552,10 @@ async def test_gateway_server_defers_end_turn_until_processing_idle_after_final_json.dumps({"jsonrpc": "2.0",- "id": 299,+ "id": 212,"method": "session/prompt","params": {- "sessionId": "sess-final-tool",+ "sessionId": "sess-expired-rpc","text": "hello",},},@@ -545,13 +564,645 @@ async def test_gateway_server_defers_end_turn_until_processing_idle_after_final_)assert ws.sent_frames[0]["method"] == "session/update"- assert ws.sent_frames[0]["params"]["update"]["sessionUpdate"] == "agent_message_chunk"- assert ws.sent_frames[1]["method"] == "session/update"+ assert ws.sent_frames[1] == {+ "jsonrpc": "2.0",+ "id": "tool-expired",+ "method": "fs/write_text_file",+ "params": {+ "path": "workspace/demo.txt",+ "content": "hello",+ "sessionId": "sess-expired-rpc",+ },+ }+ assert ws.sent_frames[2] == {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "sessionId": "sess-expired-rpc",+ "update": {"sessionUpdate": "session_info_update", "status": "idle"},+ },+ }+ assert ws.sent_frames[3] == {+ "jsonrpc": "2.0",+ "id": 212,+ "result": {"stopReason": "end_turn"},+ }+++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",+ }+++async def test_gateway_server_handle_unknown_jsonrpc_response_is_soft_ignored():+ server = build_server()+ ws = FakeWebSocket()+ seen = []++ async def on_message(msg):+ seen.append(msg)++ server.on_message(on_message)++ await server.handle_raw_message_public(+ ws,+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": "tool-unknown",+ "result": {"content": "late"},+ },+ ensure_ascii=False,+ ),+ )++ assert seen == []+ assert ws.sent_frames == [+ {+ "type": "res",+ "id": "tool-unknown",+ "ok": True,+ "payload": {+ "accepted": False,+ "ignored": True,+ "reason": "unknown_or_late_response",+ },+ }+ ]+++async def test_gateway_server_handles_acp_jsonrpc_prompt_and_streams_back_jsonrpc():+ server = build_server()+ ws = FakeWebSocket()+ seen = []++ async def on_message(msg):+ seen.append(msg)+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "hello from gateway"},+ event_type=EventType.CHAT_DELTA,+ )+ )+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "hello from gateway"},+ event_type=EventType.CHAT_FINAL,+ )+ )+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )++ server.on_message(on_message)++ await server.handle_raw_message_public(+ ws,+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": 99,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-jsonrpc",+ "text": "hello",+ },+ },+ ensure_ascii=False,+ ),+ )++ assert len(seen) == 1+ assert seen[0].req_method == ReqMethod.CHAT_SEND+ assert seen[0].session_id == "sess-jsonrpc"+ assert seen[0].params["query"] == "hello"++ assert ws.sent_frames[0]["method"] == "session/update"+ assert ws.sent_frames[1]["method"] == "session/update"+ assert ws.sent_frames[0]["params"]["sessionId"] == "sess-jsonrpc"+ assert ws.sent_frames[-1] == {+ "jsonrpc": "2.0",+ "id": 99,+ "result": {"stopReason": "end_turn"},+ }+++async def test_gateway_server_emits_agent_message_chunk_from_chat_final_when_no_delta():+ server = build_server()+ ws = FakeWebSocket()++ async def on_message(msg):+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "gateway final only"},+ event_type=EventType.CHAT_FINAL,+ )+ )+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )++ server.on_message(on_message)++ await server.handle_raw_message_public(+ ws,+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": 199,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-gateway-final",+ "text": "hello",+ },+ },+ ensure_ascii=False,+ ),+ )++ assert ws.sent_frames[0]["method"] == "session/update"+ assert ws.sent_frames[0]["params"]["sessionId"] == "sess-gateway-final"+ assert ws.sent_frames[0]["params"]["update"]["sessionUpdate"] == "agent_message_chunk"+ assert ws.sent_frames[0]["params"]["update"]["content"] == {+ "type": "text",+ "text": "gateway final only",+ }+ assert ws.sent_frames[1]["method"] == "session/update"+ assert ws.sent_frames[1]["params"]["update"] == {+ "sessionUpdate": "session_info_update",+ "status": "idle",+ }+ assert ws.sent_frames[2] == {+ "jsonrpc": "2.0",+ "id": 199,+ "result": {"stopReason": "end_turn"},+ }+++async def test_gateway_server_defers_end_turn_until_processing_idle_after_final_and_tool_updates():+ server = build_server()+ ws = FakeWebSocket()++ async def on_message(msg):+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "partial"},+ event_type=EventType.CHAT_DELTA,+ )+ )+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "final"},+ event_type=EventType.CHAT_FINAL,+ )+ )+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={+ "tool_name": "read_file",+ "tool_call_id": "tool-call-9",+ "result": "still running",+ },+ event_type=EventType.CHAT_TOOL_RESULT,+ )+ )+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )++ server.on_message(on_message)++ await server.handle_raw_message_public(+ ws,+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": 299,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-final-tool",+ "text": "hello",+ },+ },+ ensure_ascii=False,+ ),+ )++ assert ws.sent_frames[0]["method"] == "session/update"+ assert ws.sent_frames[0]["params"]["update"]["sessionUpdate"] == "agent_message_chunk"+ assert ws.sent_frames[1]["method"] == "session/update"+ assert ws.sent_frames[1]["params"]["update"]["sessionUpdate"] == "agent_message_chunk"+ assert ws.sent_frames[1]["params"]["update"]["content"] == {+ "type": "text",+ "text": "final",+ }+ assert ws.sent_frames[2]["method"] == "session/update"+ assert ws.sent_frames[2]["params"]["update"] == {+ "sessionUpdate": "tool_call_update",+ "toolCallId": "tool-call-9",+ "toolName": "read_file",+ "title": "Reading data",+ "kind": "read",+ "status": "completed",+ "result": "still running",+ "content": [{"type": "content", "content": {"type": "text", "text": "still running"}}],+ }+ assert ws.sent_frames[3]["method"] == "session/update"+ assert ws.sent_frames[3]["params"]["update"] == {+ "sessionUpdate": "session_info_update",+ "status": "idle",+ }+ assert ws.sent_frames[4] == {+ "jsonrpc": "2.0",+ "id": 299,+ "result": {"stopReason": "end_turn"},+ }+++async def test_gateway_server_waits_for_late_chat_final_after_idle_and_only_emits_missing_suffix():+ server = build_server()+ ws = FakeWebSocket()++ async def on_message(msg):+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "partial"},+ event_type=EventType.CHAT_DELTA,+ )+ )+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "partial final answer"},+ event_type=EventType.CHAT_FINAL,+ )+ )++ server.on_message(on_message)++ await server.handle_raw_message_public(+ ws,+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": 301,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-gateway-late-final",+ "text": "hello",+ },+ },+ ensure_ascii=False,+ ),+ )++ assert ws.sent_frames == [+ {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "sessionId": "sess-gateway-late-final",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "messageId": ws.sent_frames[0]["params"]["update"]["messageId"],+ "content": {"type": "text", "text": "partial"},+ },+ },+ },+ {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "sessionId": "sess-gateway-late-final",+ "update": {+ "sessionUpdate": "session_info_update",+ "status": "idle",+ },+ },+ },+ {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "sessionId": "sess-gateway-late-final",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "messageId": ws.sent_frames[0]["params"]["update"]["messageId"],+ "content": {"type": "text", "text": " final answer"},+ },+ },+ },+ {+ "jsonrpc": "2.0",+ "id": 301,+ "result": {"stopReason": "end_turn"},+ },+ ]+++async def test_gateway_server_prompt_result_echoes_user_message_id():+ server = build_server()+ ws = FakeWebSocket()++ async def on_message(msg):+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "gateway final"},+ event_type=EventType.CHAT_FINAL,+ )+ )+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )++ server.on_message(on_message)++ await server.handle_raw_message_public(+ ws,+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": 300,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-user-message-id",+ "messageId": "user-msg-1",+ "text": "hello",+ },+ },+ ensure_ascii=False,+ ),+ )++ assert ws.sent_frames[-1] == {+ "jsonrpc": "2.0",+ "id": 300,+ "result": {+ "stopReason": "end_turn",+ "userMessageId": "user-msg-1",+ },+ }+++async def test_gateway_server_does_not_end_turn_from_chat_final_before_late_tool_result(monkeypatch):+ import jiuwenclaw.app_gateway as gateway_module++ monkeypatch.setattr(gateway_module, "_PROMPT_IDLE_FINALIZE_SECONDS", 0.01)+ server = build_server()+ ws = FakeWebSocket()++ async def on_message(msg):+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "final answer"},+ event_type=EventType.CHAT_FINAL,+ )+ )+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={+ "tool_name": "write_text_file",+ "tool_call_id": "tool-call-late-1",+ "result": "index.html written",+ },+ event_type=EventType.CHAT_TOOL_RESULT,+ )+ )+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )++ server.on_message(on_message)++ await server.handle_raw_message_public(+ ws,+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": 399,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-idle-fallback",+ "text": "hello",+ },+ },+ ensure_ascii=False,+ ),+ )+ assert ws.sent_frames[0]["method"] == "session/update"+ assert ws.sent_frames[0]["params"]["update"]["sessionUpdate"] == "agent_message_chunk"+ assert ws.sent_frames[1]["method"] == "session/update"assert ws.sent_frames[1]["params"]["update"] == {"sessionUpdate": "tool_call_update",- "toolCallId": "tool-call-9",- "toolName": "read_file",- "result": "still running",+ "toolCallId": "tool-call-late-1",+ "toolName": "write_text_file",+ "title": "Editing files",+ "kind": "edit",+ "status": "completed",+ "result": "index.html written",+ "content": [{"type": "content", "content": {"type": "text", "text": "index.html written"}}],}assert ws.sent_frames[2]["method"] == "session/update"assert ws.sent_frames[2]["params"]["update"] == {@@ -560,16 +1211,82 @@ async def test_gateway_server_defers_end_turn_until_processing_idle_after_final_}assert ws.sent_frames[3] == {"jsonrpc": "2.0",- "id": 299,+ "id": 399,"result": {"stopReason": "end_turn"},}@pytest.mark.asyncio-async def test_gateway_server_idle_finalize_falls_back_when_processing_status_missing_after_chat_final(monkeypatch):- import jiuwenclaw.app_gateway as gateway_module+async def test_gateway_server_emits_direct_reasoning_update_then_waits_for_idle():+ server = build_server()+ ws = FakeWebSocket()- monkeypatch.setattr(gateway_module, "_PROMPT_IDLE_FINALIZE_SECONDS", 0.01)+ async def on_message(msg):+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "reasoning step", "event_type": "chat.reasoning"},+ event_type=EventType.CHAT_REASONING,+ )+ )+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )++ server.on_message(on_message)++ await server.handle_raw_message_public(+ ws,+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": 401,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-reasoning-gateway",+ "text": "hello",+ },+ },+ ensure_ascii=False,+ ),+ )++ assert ws.sent_frames[0]["method"] == "session/update"+ assert ws.sent_frames[0]["params"]["update"]["sessionUpdate"] == "agent_thought_chunk"+ assert ws.sent_frames[0]["params"]["update"]["content"] == {+ "type": "text",+ "text": "reasoning step",+ }+ assert ws.sent_frames[1]["method"] == "session/update"+ assert ws.sent_frames[1]["params"]["update"] == {+ "sessionUpdate": "session_info_update",+ "status": "idle",+ }+ assert ws.sent_frames[2] == {+ "jsonrpc": "2.0",+ "id": 401,+ "result": {"stopReason": "end_turn"},+ }+++async def test_gateway_server_emits_todo_update_then_waits_for_idle():server = build_server()ws = FakeWebSocket()@@ -583,8 +1300,32 @@ async def test_gateway_server_idle_finalize_falls_back_when_processing_status_miparams={},timestamp=time.time(),ok=True,- payload={"content": "final answer"},- event_type=EventType.CHAT_FINAL,+ payload={+ "todos": [+ {+ "id": "todo-1",+ "content": "Implement ACP todo update",+ "activeForm": "Implementing ACP todo update",+ "status": "in_progress",+ "createdAt": "2026-04-16T00:00:00Z",+ "updatedAt": "2026-04-16T00:05:00Z",+ }+ ]+ },+ event_type=EventType.TODO_UPDATED,+ )+ )+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,))@@ -595,23 +1336,39 @@ async def test_gateway_server_idle_finalize_falls_back_when_processing_status_mijson.dumps({"jsonrpc": "2.0",- "id": 399,+ "id": 402,"method": "session/prompt","params": {- "sessionId": "sess-idle-fallback",+ "sessionId": "sess-todo-gateway","text": "hello",},},ensure_ascii=False,),)- await asyncio.sleep(0.03)assert ws.sent_frames[0]["method"] == "session/update"- assert ws.sent_frames[0]["params"]["update"]["sessionUpdate"] == "agent_message_chunk"- assert ws.sent_frames[1] == {+ assert ws.sent_frames[0]["params"]["update"] == {+ "sessionUpdate": "todo_update",+ "todos": [+ {+ "id": "todo-1",+ "content": "Implement ACP todo update",+ "activeForm": "Implementing ACP todo update",+ "status": "in_progress",+ "createdAt": "2026-04-16T00:00:00Z",+ "updatedAt": "2026-04-16T00:05:00Z",+ }+ ],+ }+ assert ws.sent_frames[1]["method"] == "session/update"+ assert ws.sent_frames[1]["params"]["update"] == {+ "sessionUpdate": "session_info_update",+ "status": "idle",+ }+ assert ws.sent_frames[2] == {"jsonrpc": "2.0",- "id": 399,+ "id": 402,"result": {"stopReason": "end_turn"},}@@ -656,7 +1413,10 @@ async def test_gateway_server_delta_only_does_not_trigger_idle_finalize(monkeypaensure_ascii=False,),)- await asyncio.sleep(0.03)++ pending_ctx = server.get_acp_pending_request_contexts_for_test()+ assert len(pending_ctx) == 1+ assert pending_ctx[0].idle_finalize_task is Noneassert len(ws.sent_frames) == 1assert ws.sent_frames[0]["jsonrpc"] == "2.0"