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安全规则适配
zp23331dd62a4f68a21
diff --git a/jiuwenclaw/agentserver/deep_agent/rails/permission_rail.py b/jiuwenclaw/agentserver/deep_agent/rails/permission_rail.pyindex d2c4efe11b..c1db4a7a1a 100644--- a/jiuwenclaw/agentserver/deep_agent/rails/permission_rail.py+++ b/jiuwenclaw/agentserver/deep_agent/rails/permission_rail.py@@ -86,6 +86,7 @@ class PermissionInterruptRail(ConfirmInterruptRail):For bash tool: key = "bash_<command>" (e.g., "bash_dir", "bash_rm")For mcp_exec_command: key = "mcp_exec_command_<command>"+ For create_terminal: key = "create_terminal_<command>"For other tools: key = tool_nameThis enables pattern-based auto-confirm like the old mcp_exec_command patterns.@@ -96,20 +97,12 @@ class PermissionInterruptRail(ConfirmInterruptRail):tool_name = tool_call.name or ""tool_args = self._parse_tool_args(tool_call)- if tool_name == "bash":- cmd = tool_args.get("command", tool_args.get("cmd", ""))- if cmd:- cmd_base = cmd.strip().split()[0] if cmd.strip() else ""- if cmd_base:- return f"bash_{cmd_base}"- return tool_name-- if tool_name == "mcp_exec_command":+ if tool_name in {"bash", "mcp_exec_command", "create_terminal"}:cmd = tool_args.get("command", tool_args.get("cmd", ""))if cmd:cmd_base = cmd.strip().split()[0] if cmd.strip() else ""if cmd_base:- return f"mcp_exec_command_{cmd_base}"+ return f"{tool_name}_{cmd_base}"return tool_namereturn tool_name@@ -252,6 +245,31 @@ class PermissionInterruptRail(ConfirmInterruptRail):logger.info("[PermissionRail] AUTO_CONFIRM key=%s", auto_confirm_key)return self.approve()+ resolved_channel = self._resolve_channel_id()+ if resolved_channel == "acp":+ confirm_payload = await self._request_acp_permission(+ ctx=ctx,+ tool_call=tool_call,+ result=result,+ auto_confirm_key=auto_confirm_key,+ )+ if confirm_payload is None:+ return self.reject(+ tool_result=(+ f"[PERMISSION_DENIED] {result.reason or 'Operation requires approval'} "+ "(ACP permission request failed)"+ )+ )+ if confirm_payload.auto_confirm and ctx.session is not None and auto_confirm_key:+ self._store_auto_confirm(ctx, auto_confirm_key)+ if confirm_payload.approved:+ logger.info("[PermissionRail] ACP user approved tool=%s", tool_name)+ return self.approve()+ logger.info("[PermissionRail] ACP user rejected tool=%s", tool_name)+ return self.reject(+ tool_result=confirm_payload.feedback or "[PERMISSION_REJECTED] User rejected the request."+ )+logger.info("[PermissionRail] ASK - triggering interrupt for tool=%s", tool_name)message = self._build_message(tool_call, result)return self.interrupt(InterruptRequest(@@ -273,12 +291,7 @@ class PermissionInterruptRail(ConfirmInterruptRail):))if payload.auto_confirm and ctx.session is not None and auto_confirm_key:- config = ctx.session.get_state(INTERRUPT_AUTO_CONFIRM_KEY) or {}- if not isinstance(config, dict):- config = {}- config[auto_confirm_key] = True- ctx.session.update_state({INTERRUPT_AUTO_CONFIRM_KEY: config})- logger.info("[PermissionRail] Stored auto_confirm for key=%s", auto_confirm_key)+ self._store_auto_confirm(ctx, auto_confirm_key)if payload.approved:logger.info("[PermissionRail] User approved tool=%s", tool_name)@@ -328,6 +341,187 @@ class PermissionInterruptRail(ConfirmInterruptRail):return Falsereturn auto_confirm_config.get(tool_name, False)+ @staticmethod+ def _store_auto_confirm(ctx: AgentCallbackContext, auto_confirm_key: str) -> None:+ config = ctx.session.get_state(INTERRUPT_AUTO_CONFIRM_KEY) or {}+ if not isinstance(config, dict):+ config = {}+ config[auto_confirm_key] = True+ ctx.session.update_state({INTERRUPT_AUTO_CONFIRM_KEY: config})+ logger.info("[PermissionRail] Stored auto_confirm for key=%s", auto_confirm_key)++ @staticmethod+ def _read_session_attr_value(session: Any, attr_name: str) -> Any:+ attr = getattr(session, attr_name, None)+ if not callable(attr):+ return attr+ try:+ return attr()+ except Exception:+ logger.debug(+ "[PermissionRail] Failed to read session attribute: %s",+ attr_name,+ exc_info=True,+ )+ return None++ @staticmethod+ def _resolve_session_id(ctx: AgentCallbackContext) -> str | None:+ session = getattr(ctx, "session", None)+ if session is None:+ return None++ for attr_name in ("get_session_id", "session_id"):+ value = PermissionInterruptRail._read_session_attr_value(session, attr_name)+ if isinstance(value, str) and value.strip():+ return value.strip()+ return None++ @staticmethod+ def _tool_kind_for_permission(tool_name: str) -> str:+ if tool_name in {"bash", "mcp_exec_command", "create_terminal", "exec_command"}:+ return "execute"+ if tool_name in {"read_file", "read_text_file", "memory_get"}:+ return "read"+ if tool_name in {"write_file", "write_text_file", "edit_file", "write"}:+ return "edit"+ if tool_name in {"grep", "glob_file_search", "mcp_free_search", "mcp_paid_search"}:+ return "search"+ if tool_name in {"fetch_webpage", "mcp_fetch_webpage"}:+ return "fetch"+ return "other"++ def _build_acp_permission_request(+ self,+ tool_call: Optional[ToolCall],+ result: PermissionResult,+ ) -> dict[str, Any]:+ 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}`"+ if result.reason:+ title = f"{title}: {result.reason}"++ request: dict[str, Any] = {+ "toolCall": {+ "toolCallId": tool_call_id,+ "title": title,+ "kind": self._tool_kind_for_permission(tool_name),+ "status": "pending",+ },+ "options": [+ {+ "optionId": "allow-once",+ "name": "Allow once",+ "kind": "allow_once",+ },+ {+ "optionId": "allow-always",+ "name": "Always allow",+ "kind": "allow_always",+ },+ {+ "optionId": "reject-once",+ "name": "Reject",+ "kind": "reject_once",+ },+ ],+ }+ if tool_args:+ request["toolCall"]["rawInput"] = tool_args+ return request++ async def _request_acp_permission(+ self,+ ctx: AgentCallbackContext,+ tool_call: Optional[ToolCall],+ result: PermissionResult,+ auto_confirm_key: str,+ ) -> ConfirmPayload | None:+ session_id = self._resolve_session_id(ctx)+ if not session_id:+ logger.warning("[PermissionRail] ACP permission request skipped: missing session_id")+ return None++ from jiuwenclaw.agentserver.tools.acp_output_tools import get_acp_output_manager++ request_params = self._build_acp_permission_request(tool_call, result)+ logger.info(+ "[PermissionRail] ACP permission request: session_id=%s tool=%s auto_confirm_key=%s",+ session_id,+ tool_call.name if tool_call else "",+ auto_confirm_key,+ )+ try:+ response = await get_acp_output_manager().send_jsonrpc_request(+ "session/request_permission",+ request_params,+ session_id=session_id,+ )+ except Exception as exc:+ logger.warning("[PermissionRail] ACP permission request failed: %s", exc)+ return None++ if not isinstance(response, dict):+ logger.warning("[PermissionRail] ACP permission request returned invalid response: %s", response)+ return None++ if isinstance(response.get("error"), dict):+ err = response["error"]+ message = str(err.get("message") or "Permission request failed")+ logger.warning("[PermissionRail] ACP permission request error: %s", message)+ return ConfirmPayload(+ approved=False,+ auto_confirm=False,+ feedback=f"[PERMISSION_DENIED] {message}",+ )++ result_payload = response.get("result") if isinstance(response.get("result"), dict) else {}+ outcome = result_payload.get("outcome") if isinstance(result_payload.get("outcome"), dict) else {}+ outcome_kind = str(outcome.get("outcome") or "").strip().lower()+ option_id = str(outcome.get("optionId") or "").strip().lower()++ if outcome_kind == "selected":+ if option_id == "allow-once":+ return ConfirmPayload(approved=True, auto_confirm=False, feedback="")+ if option_id == "allow-always":+ return ConfirmPayload(approved=True, auto_confirm=True, feedback="")+ if option_id in {"reject-once", "reject-always"}:+ return ConfirmPayload(+ approved=False,+ auto_confirm=False,+ feedback="[PERMISSION_REJECTED] User rejected the request.",+ )+ logger.warning(+ "[PermissionRail] ACP permission request returned unknown option_id=%s",+ option_id,+ )+ return ConfirmPayload(+ approved=False,+ auto_confirm=False,+ feedback=f"[PERMISSION_DENIED] Unknown permission option: {option_id or 'empty'}",+ )++ if outcome_kind == "cancelled":+ return ConfirmPayload(+ approved=False,+ auto_confirm=False,+ feedback="[PERMISSION_REJECTED] Permission request was cancelled.",+ )++ logger.warning(+ "[PermissionRail] ACP permission request returned unknown outcome=%s payload=%s",+ outcome_kind,+ result_payload,+ )+ return ConfirmPayload(+ approved=False,+ auto_confirm=False,+ feedback="[PERMISSION_DENIED] Invalid ACP permission response.",+ )+@staticmethoddef _format_args_preview(tool_args: dict) -> str:try:@@ -382,6 +576,10 @@ class PermissionInterruptRail(ConfirmInterruptRail):cmd = tool_args.get("command", tool_args.get("cmd", ""))if cmd:return f'\n\n> 选择"总是允许"将自动放行 `{cmd}` 命令'+ if tool_name == "create_terminal":+ cmd = tool_args.get("command", tool_args.get("cmd", ""))+ if cmd:+ return f'\n\n> 选择"总是允许"将自动放行 `{cmd}` 终端命令'if auto_confirm_key:return f'\n\n> 选择"总是允许"将自动放行 `{auto_confirm_key}` 调用'return ""diff --git a/jiuwenclaw/agentserver/permissions/checker.py b/jiuwenclaw/agentserver/permissions/checker.pyindex 6c853342ae..1f4b9c0b58 100644--- a/jiuwenclaw/agentserver/permissions/checker.py+++ b/jiuwenclaw/agentserver/permissions/checker.py@@ -46,9 +46,8 @@ TOOL_PERMISSION_CHANNEL_ID: contextvars.ContextVar[str] = contextvars.ContextVardefault="",)-# 与 jiuwenclaw.channel.web_channel.WebChannel.name / channel_id 一致。-# 仅当 TOOL_PERMISSION_CHANNEL_ID strip 后等于本常量时才做工具权限与 ask 审批;其它通道跳过。-WEB_TOOL_PERMISSIONS_CHANNEL_ID = "web"+# 启用工具权限检查的通道集合。仅当通道 ID 在此集合内时才执行权限校验,其它通道跳过。+_PERMISSION_ENABLED_CHANNELS = frozenset({"web", "acp"})def collect_permission_rail_tool_names(permission_config: dict[str, Any]) -> list[str]:@@ -97,7 +96,7 @@ async def check_tool_permissions(Args:tool_calls: 待执行的工具调用列表- channel_id: 频道 ID;仅 strip 后等于 WEB_TOOL_PERMISSIONS_CHANNEL_ID 时执行校验,否则全量放行+ channel_id: 频道 ID;仅通道在 _PERMISSION_ENABLED_CHANNELS 内时执行校验,否则全量放行session_id: 会话 IDsession: 会话对象,用于发起审批弹窗request_approval_callback: 当 needs_approval 时的回调 -> "allow_always"|"allow_once"|"deny"@@ -113,7 +112,7 @@ async def check_tool_permissions(return list(tool_calls), []normalized_channel_id = (channel_id or "").strip()- if normalized_channel_id != WEB_TOOL_PERMISSIONS_CHANNEL_ID:+ if normalized_channel_id not in _PERMISSION_ENABLED_CHANNELS:logger.info("Tool permissions check skipped for channel=%s",normalized_channel_id or "(empty)",diff --git a/jiuwenclaw/agentserver/permissions/core.py b/jiuwenclaw/agentserver/permissions/core.pyindex 353bc2620c..11465793f6 100644--- a/jiuwenclaw/agentserver/permissions/core.py+++ b/jiuwenclaw/agentserver/permissions/core.py@@ -31,6 +31,8 @@ from jiuwenclaw.agentserver.permissions.tiered_policy import (logger = logging.getLogger(__name__)+_PERMISSION_ENABLED_CHANNELS = frozenset({"web", "acp"})+class PermissionEngine:"""权限引擎 - 负责加载配置、评估权限."""@@ -147,8 +149,8 @@ class PermissionEngine:)normalized_channel = (channel_id or "").strip() or "web"- if normalized_channel != "web":- logger.info("[PermissionEngine] Skipping permission check for non-web channel: %s", normalized_channel)+ if normalized_channel not in _PERMISSION_ENABLED_CHANNELS:+ logger.info("[PermissionEngine] Skipping permission check for channel: %s", normalized_channel)return PermissionResult(permission=PermissionLevel.ALLOW,reason=f"Skipped for channel: {normalized_channel}",diff --git a/jiuwenclaw/agentserver/permissions/tiered_policy.py b/jiuwenclaw/agentserver/permissions/tiered_policy.pyindex 84c94dcdbc..0107b21d5c 100644--- a/jiuwenclaw/agentserver/permissions/tiered_policy.py+++ b/jiuwenclaw/agentserver/permissions/tiered_policy.py@@ -24,7 +24,7 @@ _STRICT_ORDER = {PermissionLevel.DENY: 0, PermissionLevel.ASK: 1, PermissionLeve_TIERED_POLICY_SCHEMA_KEYS = frozenset({"tiered_policy", "v_cc", "v4.2"})# 规则内 tools 必须同类(与产品设计一致)-_SHELL_TOOLS = frozenset({"bash", "mcp_exec_command"})+_SHELL_TOOLS = frozenset({"bash", "mcp_exec_command", "create_terminal"})_PATH_TOOLS = frozenset({"read_file", "write_file", "edit_file","read_text_file", "write_text_file",@@ -439,7 +439,7 @@ def maybe_escalate_shell_operators(permission: PermissionLevel,) -> PermissionLevel:"""与旧版一致:命令含链式/注入元字符时 ALLOW→ASK."""- if tool_name not in ("mcp_exec_command", "bash"):+ if tool_name not in ("mcp_exec_command", "bash", "create_terminal"):return permissionif permission != PermissionLevel.ALLOW:return permissiondiff --git a/jiuwenclaw/app_gateway.py b/jiuwenclaw/app_gateway.pyindex 41e194650d..3c2cfe5178 100644--- a/jiuwenclaw/app_gateway.py+++ b/jiuwenclaw/app_gateway.py@@ -123,6 +123,17 @@ class _InboundGatewayServer:logger.exception("[App] Gateway inbound handling failed: id=%s", getattr(msg, "id", None))+_ACP_PENDING_RPC_TIMEOUT_SECONDS = 60.0+++@dataclass+class _GatewayAcpRequestContext:+ jsonrpc_id: str | int | None+ session_id: str+ assistant_message_id: str | None = None+ thought_message_id: str | None = None++class AcpRouteHandler:"""ACP 路由的 JSON-RPC 桥接逻辑。@@ -131,7 +142,8 @@ class AcpRouteHandler:def __init__(self, on_message_cb) -> None:self._on_message_cb = on_message_cb- self._pending_client_rpc_session_by_id: dict[str, tuple[str, Any]] = {}+ # 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 帧。"""@@ -143,12 +155,12 @@ class AcpRouteHandler:):return False- from jiuwenclaw.schema.message import Message, ReqMethod+ from jiuwenclaw.e2a.adapters import build_acp_tool_response_messagejsonrpc_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:+ if isinstance(pending, tuple) and len(pending) >= 2:session_id = str(pending[0] or "").strip()if not jsonrpc_id or not session_id:@@ -165,21 +177,11 @@ class AcpRouteHandler:)return True- msg = Message(- id=f"acp_tool_resp_{uuid_module.uuid4().hex[:12]}",- type="req",- channel_id="acp",+ msg = build_acp_tool_response_message(+ jsonrpc_id=jsonrpc_id,+ response_data=data,session_id=session_id,- params={- "jsonrpc_id": jsonrpc_id,- "response": dict(data),- "session_id": session_id,- },- timestamp=time.time(),- ok=True,- req_method=ReqMethod.ACP_TOOL_RESPONSE,- is_stream=False,- metadata={"acp": {"jsonrpc_id": jsonrpc_id, "kind": "tool_response"}},+ channel_id="acp",)if self._on_message_cb is not None:result = self._on_message_cb(msg)@@ -195,12 +197,24 @@ class AcpRouteHandler:and str(msg.payload.get("event_type") or "").strip() == "acp.output_request"):raw_jsonrpc = msg.payload.get("jsonrpc")- if isinstance(raw_jsonrpc, dict):- jsonrpc_id = str(raw_jsonrpc.get("id") or "").strip()- session_id = str(msg.session_id or "").strip()- if jsonrpc_id and session_id:- self._pending_client_rpc_session_by_id[jsonrpc_id] = (session_id, ws)- await ws.send(json.dumps(raw_jsonrpc, ensure_ascii=False))+ 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 Truereturn False@@ -208,12 +222,26 @@ class AcpRouteHandler:"""ws 断开时清理关联的 pending RPC 条目。"""stale = [jsonrpc_id- for jsonrpc_id, (_, client) in self._pending_client_rpc_session_by_id.items()- if client is ws+ 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+ )+@@ -267,7 +295,17 @@ class GatewayServerConfig:enabled: bool = Truehost: str = "127.0.0.1"port: int = 19001- routes: dict[str, RouteConfig] = field(default_factory=dict) # path -> config+ routes: dict[str, RouteConfig] = field(default_factory=dict)+ path: str | None = None+ channel_id: str | None = None++ def __post_init__(self) -> None:+ if self.routes:+ return+ path = str(self.path or "").strip()+ channel_id = str(self.channel_id or "").strip()+ if path and channel_id:+ self.routes[path] = RouteConfig(path=path, channel_id=channel_id)class GatewayServer:@@ -286,6 +324,9 @@ 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._install_default_route_hooks()@staticmethoddef _client_route_key(channel_id: str | None, scoped_id: str | None) -> tuple[str, str] | None:@@ -298,6 +339,127 @@ class GatewayServer:def on_message(self, callback) -> None:self._on_message_cb = callback+ async def _dispatch_on_message(self, msg) -> 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 _install_default_route_hooks(self) -> None:+ for route in self.config.routes.values():+ if route.channel_id != "acp":+ continue+ if 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": [],+ }++ def _resolve_route(self, request_path: str) -> tuple[RouteConfig | None, str]:+ """按精确路径匹配路由;支持常见变体(如尾部斜杠)以避免客户端握手失败。"""+ routes = self.config.routes+ p = (request_path or "").strip()+ if not p:+ return None, request_path+ if p in routes:+ return routes[p], p+ if p != "/" and p.endswith("/") and p.rstrip("/") in routes:+ return routes[p.rstrip("/")], p.rstrip("/")+ if not p.endswith("/") and f"{p}/" in routes:+ return routes[f"{p}/"], f"{p}/"+ return None, p++ async def wait_until_closed(self) -> None:+ """阻塞至底层 WebSocket 服务完全关闭(与 :meth:`start` 配对供主循环持有任务)。"""+ if self._server is None:+ return+ await self._server.wait_closed()+def register_local_handler(self, path: str, method: str, handler: Callable[..., Awaitable[None]]) -> None:"""为指定路径注册本地方法 handler。"""route = self.config.routes.get(path)@@ -388,6 +550,8 @@ class GatewayServer:request_key = self._client_route_key(getattr(msg, "channel_id", None), getattr(msg, "id", None))if request_key is not None:ws = self._request_to_client.get(request_key)+ if ws is None:+ ws = self._request_to_client.get(request_key[1])if ws is None:session_key = self._client_route_key(getattr(msg, "channel_id", None),@@ -395,9 +559,16 @@ class GatewayServer:)if session_key is not None:ws = self._session_to_client.get(session_key)+ if ws is None:+ ws = self._session_to_client.get(session_key[1])if ws is None or bool(getattr(ws, "closed", False)):return+ if getattr(msg, "channel_id", None) == "acp":+ handled = await self._send_acp_jsonrpc_message(msg, ws)+ if handled:+ return+# 让 route 的 outbound_interceptor 有机会拦截for route in self.config.routes.values():if route.channel_id == msg.channel_id and route.outbound_interceptor is not None:@@ -441,12 +612,86 @@ 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:+ text = str(payload.get("content", "") or "")+ if not text:+ return True+ source_chunk_type = str(payload.get("source_chunk_type") or "")+ if source_chunk_type == "llm_reasoning":+ if not ctx.thought_message_id:+ ctx.thought_message_id = f"thought_{uuid_module.uuid4().hex[:12]}"+ update = {+ "sessionUpdate": "agent_thought_chunk",+ "messageId": ctx.thought_message_id,+ "content": {"type": "text", "text": text},+ }+ else:+ if not ctx.assistant_message_id:+ ctx.assistant_message_id = f"msg_{uuid_module.uuid4().hex[:12]}"+ update = {+ "sessionUpdate": "agent_message_chunk",+ "messageId": ctx.assistant_message_id,+ "content": {"type": "text", "text": text},+ }+ 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:+ content = str(payload.get("content", "") or "")+ if content and not ctx.assistant_message_id:+ ctx.assistant_message_id = f"msg_{uuid_module.uuid4().hex[:12]}"+ await self._send_raw_jsonrpc_notification(+ ws,+ "session/update",+ {+ "sessionId": session_id or ctx.session_id,+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "messageId": ctx.assistant_message_id,+ "content": {"type": "text", "text": content},+ },+ },+ )+ await self._send_raw_jsonrpc_result(ws, ctx.jsonrpc_id, {"stopReason": "end_turn"})+ self._acp_request_ctx_by_request_id.pop(str(msg.id), None)+ if self._acp_active_prompt_request_by_session.get(ctx.session_id) == str(msg.id):+ self._acp_active_prompt_request_by_session.pop(ctx.session_id, None)+ return True++ if msg.type == "event" and msg.event_type == EventType.CHAT_ERROR:+ await self._send_raw_jsonrpc_error(+ ws,+ ctx.jsonrpc_id,+ -32603,+ str(payload.get("error") or payload.get("content") or "Agent error"),+ )+ self._acp_request_ctx_by_request_id.pop(str(msg.id), None)+ if self._acp_active_prompt_request_by_session.get(ctx.session_id) == str(msg.id):+ self._acp_active_prompt_request_by_session.pop(ctx.session_id, None)+ return True++ return False+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)request_path = parsed.path or raw_path- route = self.config.routes.get(request_path)+ route, matched_path = self._resolve_route(request_path)if route is None:await ws.close(code=1008, reason=f"unsupported path: {request_path}")return@@ -469,7 +714,7 @@ class GatewayServer:try:async for raw in ws:- await self._handle_raw_message(ws, raw, request_path, route)+ await self._handle_raw_message(ws, raw, matched_path, route)finally:self._clients.discard(ws)stale_request_ids = [request_id for request_id, client in self._request_to_client.items() if client is ws]@@ -502,6 +747,84 @@ 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.AGENT,+ 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))+ return+# route 级别的原始帧拦截(如 ACP JSON-RPC response)if route.inbound_interceptor is not None:try:@@ -590,6 +913,12 @@ class GatewayServer:if asyncio.iscoroutine(result):await result+ # ACP route may receive legacy ``type=req`` frames from some clients.+ # They should be forwarded upstream without falling through to the+ # generic "unknown method" error path.+ if route.channel_id == "acp":+ return+# 如果在 forward_no_local_handler_methods 中,不需要本地 ackif method in route.forward_no_local_handler_methods:return@@ -1460,7 +1789,12 @@ async def _run(await channel_manager.start_dispatch()await cron_scheduler.start()- gateway_server_task = asyncio.create_task(gateway_server.start(), name="acp-gateway-server")+ # 先同步完成监听绑定,避免 IDE/ACP 子进程在端口尚未就绪时连接导致多次重试。+ await gateway_server.start()+ gateway_server_task = asyncio.create_task(+ gateway_server.wait_until_closed(),+ name="acp-gateway-server",+ )web_task = (asyncio.create_task(web_channel.start(), name="web-channel")if web_channel is not Nonediff --git a/jiuwenclaw/channel/acp_channel.py b/jiuwenclaw/channel/acp_channel.pyindex 186e2a37fb..8dcf62636c 100644--- a/jiuwenclaw/channel/acp_channel.py+++ b/jiuwenclaw/channel/acp_channel.py@@ -33,6 +33,9 @@ _ACP_PROTOCOL_VERSION = 1_ACP_STDOUT = getattr(sys, "__stdout__", sys.stdout)_STDIN_EOF_GRACE_SECONDS = 5.0_PROMPT_IDLE_FINALIZE_SECONDS = 3.0+_ACP_PENDING_RPC_TIMEOUT_SECONDS = 60.0+_ACP_GATEWAY_CONNECT_MAX_ATTEMPTS = 12+_ACP_GATEWAY_CONNECT_BASE_DELAY_SEC = 0.15@dataclass@@ -81,7 +84,8 @@ class AcpChannel(BaseChannel):self._request_ctx: dict[str, _AcpRequestContext] = {}self._session_ctx: dict[str, dict[str, Any]] = {}self._active_prompt_request_by_session: dict[str, str] = {}- self._pending_client_rpc_session_by_id: dict[str, str] = {}+ # value: (session_id, created_at)+ self._pending_client_rpc_session_by_id: dict[str, tuple[str, float]] = {}@propertydef channel_id(self) -> str:@@ -141,6 +145,18 @@ class AcpChannel(BaseChannel):self._pending_client_rpc_session_by_id.clear()await self._close_gateway_connection()+ 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 isinstance(entry, tuple) and len(entry) >= 2 and (now - entry[1]) > _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 send(self, msg: Message) -> None:ctx = self._request_ctx.get(str(msg.id))if ctx is None:@@ -181,26 +197,19 @@ class AcpChannel(BaseChannel):await self._dispatch_message(msg)async def _handle_jsonrpc_response(self, data: dict[str, Any]) -> None:+ from jiuwenclaw.e2a.adapters import build_acp_tool_response_message+jsonrpc_id = str(data.get("id") or "").strip()if not jsonrpc_id:return- session_id = self._pending_client_rpc_session_by_id.pop(jsonrpc_id, None)- msg = Message(- id=f"acp_tool_resp_{uuid.uuid4().hex[:12]}",- type="req",- channel_id=self.channel_id,+ pending = self._pending_client_rpc_session_by_id.pop(jsonrpc_id, None)+ session_id = pending[0] if isinstance(pending, tuple) else None+ msg = build_acp_tool_response_message(+ jsonrpc_id=jsonrpc_id,+ response_data=data,session_id=session_id,- params={- "jsonrpc_id": jsonrpc_id,- "response": dict(data),- "session_id": session_id,- },- timestamp=time.time(),- ok=True,- req_method=ReqMethod.ACP_TOOL_RESPONSE,- is_stream=False,- metadata={"acp": {"jsonrpc_id": jsonrpc_id, "kind": "tool_response"}},+ channel_id=self.channel_id,)await self._dispatch_message(msg)@@ -526,11 +535,13 @@ class AcpChannel(BaseChannel):if not session_id:raise ValueError("sessionId is required")- prompt = params.get("prompt")- if not isinstance(prompt, list) or not prompt:- raise ValueError("prompt is required")-rpc_params = dict(params)+ prompt = rpc_params.get("prompt")+ if not isinstance(prompt, list) or not prompt:+ text = self._extract_prompt_text(rpc_params)+ if not text:+ raise ValueError("prompt is required")+ rpc_params["prompt"] = [{"type": "text", "text": text}]rpc_params["session_id"] = session_idsession_ctx = self._session_ctx.get(session_id)if isinstance(session_ctx, dict):@@ -617,17 +628,23 @@ class AcpChannel(BaseChannel):task = ctx.idle_finalize_taskif task is not None:task.cancel()- ctx.idle_finalize_task = asyncio.create_task(+ new_task = asyncio.create_task(self._idle_finalize_after_timeout(str(request_id)),name=f"acp-idle-finalize-{request_id}",)+ ctx.idle_finalize_task = new_taskasync def _idle_finalize_after_timeout(self, request_id: str) -> None:+ current_task = asyncio.current_task()try:await asyncio.sleep(_PROMPT_IDLE_FINALIZE_SECONDS)ctx = self._request_ctx.get(str(request_id))if ctx is None or ctx.response_mode != "jsonrpc":return+ # Guard: verify this task is still the active idle_finalize_task+ # to prevent a superseded task from finalizing after being replaced.+ if ctx.idle_finalize_task is not current_task:+ returnawait self._write_jsonrpc_result(ctx.jsonrpc_id,{@@ -937,11 +954,43 @@ class AcpChannel(BaseChannel):except Exception: # pragma: no coverfrom websockets import connect as ws_connect- self._gateway_ws = await ws_connect(self._gateway_url, ping_interval=20, ping_timeout=20)- self._gateway_reader_task = asyncio.create_task(- self._gateway_reader_loop(),- name="acp-gateway-reader",- )+ last_exc: BaseException | None = None+ for attempt in range(1, _ACP_GATEWAY_CONNECT_MAX_ATTEMPTS + 1):+ try:+ self._gateway_ws = await ws_connect(+ self._gateway_url,+ ping_interval=20,+ ping_timeout=20,+ open_timeout=30,+ )+ self._gateway_reader_task = asyncio.create_task(+ self._gateway_reader_loop(),+ name="acp-gateway-reader",+ )+ if attempt > 1:+ logger.info("[ACP] gateway connected after %d attempts: %s", attempt, self._gateway_url)+ return+ except BaseException as exc:+ last_exc = exc+ self._gateway_ws = None+ self._gateway_reader_task = None+ if attempt >= _ACP_GATEWAY_CONNECT_MAX_ATTEMPTS:+ break+ delay = min(+ _ACP_GATEWAY_CONNECT_BASE_DELAY_SEC * (2 ** (attempt - 1)),+ 2.0,+ )+ logger.warning(+ "[ACP] gateway connect attempt %d/%d failed (%s); retry in %.2fs",+ attempt,+ _ACP_GATEWAY_CONNECT_MAX_ATTEMPTS,+ exc,+ delay,+ )+ await asyncio.sleep(delay)+ raise RuntimeError(+ f"ACP gateway connect failed after {_ACP_GATEWAY_CONNECT_MAX_ATTEMPTS} attempts: {self._gateway_url}"+ ) from last_excasync def _close_gateway_connection(self) -> None:reader_task = self._gateway_reader_task@@ -1023,11 +1072,12 @@ class AcpChannel(BaseChannel):def set_pending_client_rpc_session_for_test(self, jsonrpc_id: str, session_id: str) -> None:"""Public test helper to seed ACP client RPC session mappings."""- self._pending_client_rpc_session_by_id[jsonrpc_id] = session_id+ self._pending_client_rpc_session_by_id[jsonrpc_id] = (session_id, time.time())def get_pending_client_rpc_session_for_test(self, jsonrpc_id: str) -> str | None:"""Public test helper to inspect ACP client RPC session mappings."""- return self._pending_client_rpc_session_by_id.get(jsonrpc_id)+ entry = self._pending_client_rpc_session_by_id.get(jsonrpc_id)+ return entry[0] if isinstance(entry, tuple) else Noneasync def handle_gateway_frame_for_test(self, data: dict[str, Any]) -> None:"""Public test helper that delegates to gateway frame handling."""@@ -1038,7 +1088,8 @@ 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._pending_client_rpc_session_by_id[jsonrpc_id] = session_id+ self._pending_client_rpc_session_by_id[jsonrpc_id] = (session_id, time.time())+ self._sweep_stale_pending()_ACP_STDOUT.buffer.write((json.dumps(data, ensure_ascii=False) + "\n").encode("utf-8"))_ACP_STDOUT.buffer.flush()diff --git a/jiuwenclaw/e2a/adapters.py b/jiuwenclaw/e2a/adapters.pyindex 481d63b187..b1522fde73 100644--- a/jiuwenclaw/e2a/adapters.py+++ b/jiuwenclaw/e2a/adapters.py@@ -13,6 +13,8 @@from __future__ import annotations+import time+import uuid as uuid_modulefrom typing import Anyfrom jiuwenclaw.e2a.constants import (@@ -222,3 +224,34 @@ def e2a_response_to_a2a_stream_payload(response: E2AResponse) -> dict[str, Any]if outer is None:return Nonereturn {outer: payload}+++def build_acp_tool_response_message(+ jsonrpc_id: str,+ response_data: dict[str, Any],+ session_id: str | None,+ channel_id: str = "acp",+) -> Any:+ """Build an internal Message for an ACP tool response (JSON-RPC response from client).++ Shared by AcpRouteHandler (WebSocket gateway mode) and AcpChannel (stdio mode)+ to avoid duplicated Message construction logic.+ """+ from jiuwenclaw.schema.message import Message, ReqMethod++ return Message(+ id=f"acp_tool_resp_{uuid_module.uuid4().hex[:12]}",+ type="req",+ channel_id=channel_id,+ session_id=session_id,+ params={+ "jsonrpc_id": jsonrpc_id,+ "response": dict(response_data),+ "session_id": session_id,+ },+ timestamp=time.time(),+ ok=True,+ req_method=ReqMethod.ACP_TOOL_RESPONSE,+ is_stream=False,+ metadata={"acp": {"jsonrpc_id": jsonrpc_id, "kind": "tool_response"}},+ )diff --git a/jiuwenclaw/e2a/gateway_normalize.py b/jiuwenclaw/e2a/gateway_normalize.pyindex 5fe5ce5e14..266e928db7 100644--- a/jiuwenclaw/e2a/gateway_normalize.py+++ b/jiuwenclaw/e2a/gateway_normalize.py@@ -550,7 +550,7 @@ def e2a_response_to_agent_chunk(e2a: E2AResponse) -> "AgentResponseChunk":"event_type": "acp.output_request","jsonrpc": dict(body),},- is_complete=True,+ is_complete=False,)raise ValueError(diff --git a/jiuwenclaw/resources/builtin_rules.yaml b/jiuwenclaw/resources/builtin_rules.yamlindex 120d58bd9d..86ba41ca93 100644--- a/jiuwenclaw/resources/builtin_rules.yaml+++ b/jiuwenclaw/resources/builtin_rules.yaml@@ -16,70 +16,70 @@rules:- id: shell_fs_recursive_or_forced_deletedescription: "递归、强制或批量删除关键路径,可能造成不可恢复的数据破坏"- tools: [bash, mcp_exec_command]+ tools: [bash, mcp_exec_command, create_terminal]match_type: commandpattern: 're:(?i)(^|[\s;&|()])((rm\s+[^;&|]*(-[A-Za-z]*[rR][A-Za-z]*[fF]|-[A-Za-z]*[fF][A-Za-z]*[rR]|--recursive|--force)[^;&|]*(/[^;&|\s]*|\*|~[^;&|\s]*|\$HOME[^;&|\s]*|\.{1,2}(/[^;&|\s]*)?)(\s|$))|(find\s+[^;&|]*\s-delete\b)|(shred\b)|(del\s+[^;&|]*/[A-Za-z]*[fqs][A-Za-z]*)|(rd\s+[^;&|]*/s\b[^;&|]*/q\b))'severity: CRITICAL- id: shell_disk_partition_or_raw_device_writedescription: "格式化、分区或直接写入块设备,可能破坏磁盘和文件系统"- tools: [bash, mcp_exec_command]+ tools: [bash, mcp_exec_command, create_terminal]match_type: commandpattern: 're:(?i)(^|[\s;&|()])((mkfs(\.[A-Za-z0-9_]+)?|mke2fs|fdisk|parted|diskpart|format)\b|(dd\b[^;&|]*(\bof=/dev/|\\\\\.\\PhysicalDrive))|(>\s*/dev/(sd[a-z][0-9]*|vd[a-z][0-9]*|xvd[a-z][0-9]*|nvme[0-9]+n[0-9]+(p[0-9]+)?|disk[0-9]+)))'severity: CRITICAL- id: shell_download_and_executedescription: "从网络下载内容后直接交给 shell、PowerShell 或动态执行器执行"- tools: [bash, mcp_exec_command]+ tools: [bash, mcp_exec_command, create_terminal]match_type: commandpattern: 're:(?i)(^|[\s;&|()])(((curl|wget|fetch|ftp)\b[^;&]*\|\s*(bash|sh|zsh|dash|ash|source)\b)|(iwr|irm|Invoke-WebRequest|Invoke-RestMethod)\b[^;&|]*\|\s*(iex|Invoke-Expression)\b|((bash|sh|zsh|pwsh|powershell)\b[^;&|]*<\s*<\s*\(?\s*(curl|wget)\b))'severity: CRITICAL- id: shell_obfuscated_or_dynamic_executiondescription: "编码载荷、解码后执行、eval/iex 或内联解释器执行,命令难以审计"- tools: [bash, mcp_exec_command]+ tools: [bash, mcp_exec_command, create_terminal]match_type: commandpattern: 're:(?i)(^|[\s;&|()])((base64\s+(-d|--decode)\b[^;&|]*\|\s*(bash|sh|zsh|dash|ash)\b)|(certutil\s+-decode\b)|(-EncodedCommand\b|-[Ee]nc\b)|(\[Convert\]::FromBase64String\()|(eval\s+[`$])|(\b(iex|Invoke-Expression)\b)|((python3?|perl|ruby|node)\s+(-c|-e)\b[^;&|]*(socket|subprocess|exec|eval|child_process)))'severity: CRITICAL- id: shell_reverse_shell_or_bind_shelldescription: "反向 shell、绑定 shell 或可疑网络执行通道"- tools: [bash, mcp_exec_command]+ tools: [bash, mcp_exec_command, create_terminal]match_type: commandpattern: 're:(?i)(/dev/(tcp|udp)/|(^|[\s;&|()])(nc|ncat)\b[^;&|]*\s(-e|--exec)\s|\bsocat\b[^;&|]*(EXEC:|SYSTEM:|PTY)|\bbash\s+-i\b[^;&|]*/dev/tcp/|\bpython3?\b[^;&|]*(socket|pty\.spawn|subprocess)|\bperl\b[^;&|]*Socket)'severity: CRITICAL- id: shell_privilege_escalationdescription: "通过 sudo、su、doas、pkexec、runas 或管理员启动方式提升权限"- tools: [bash, mcp_exec_command]+ tools: [bash, mcp_exec_command, create_terminal]match_type: commandpattern: 're:(?i)(^|[\s;&|()])((sudo|doas|pkexec)\s+|su\s+(-|root|\w)|runas\b|Start-Process\b[^;&|]*-Verb\s+RunAs\b|psexec\b|schtasks\b[^;&|]*/ru\s+SYSTEM\b)'severity: CRITICAL- id: shell_data_exfiltrationdescription: "通过 HTTP、scp、rsync、ftp、nc 等方式上传本地文件或命令输出"- tools: [bash, mcp_exec_command]+ tools: [bash, mcp_exec_command, create_terminal]match_type: commandpattern: 're:(?i)(^|[\s;&|()])(((curl|wget|Invoke-WebRequest|iwr|Invoke-RestMethod|irm)\b[^;&|]*(--data|--data-binary|--upload-file|-d\b|-F\b|-T\b|POST|PUT))|(scp\b[^;&|]+\s+\S+:)|(rsync\b[^;&|]+\s+\S+:)|(sftp|ftp)\b|\bnc\b[^;&|]*\s(443|80|8080|53)\b)'severity: CRITICAL- id: shell_remote_execution_or_lateral_movementdescription: "远程会话、远程进程创建或横向移动命令"- tools: [bash, mcp_exec_command]+ tools: [bash, mcp_exec_command, create_terminal]match_type: commandpattern: 're:(?i)(^|[\s;&|()])((Invoke-Command|Enter-PSSession|New-PSSession)\b|winrs\b|wmic\b[^;&|]*process\s+call\s+create|psexec\b|ssh\b[^;&|]*\s\S+\s+["''][^"'']+["''])'severity: CRITICAL- id: shell_fork_bomb_or_resource_abusedescription: "fork bomb、解除进程限制或批量终止关键进程"- tools: [bash, mcp_exec_command]+ tools: [bash, mcp_exec_command, create_terminal]match_type: commandpattern: 're:(?i)(:\s*\(\s*\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:|(^|[\s;&|()])kill\s+-9\s+(-1|1)\b|(^|[\s;&|()])ulimit\s+-u\s+unlimited\b)'severity: CRITICAL- id: shell_system_control_or_forced_process_terminationdescription: "关机、重启、停止关键服务或强制终止进程,可能直接破坏系统可用性"- tools: [bash, mcp_exec_command]+ tools: [bash, mcp_exec_command, create_terminal]match_type: commandpattern: 're:(?i)(^|[\s;&|()])((shutdown|reboot|halt|poweroff)\b|(init|telinit)\s+(0|6)\b|(systemctl\s+(stop|restart|disable|mask|kill)\b)|(service\s+\S+\s+(stop|restart|reload)\b)|(launchctl\s+(stop|kickstart|kill|bootout)\b)|((pkill|killall)\b)|(kill\s+-(9|KILL)\b)|(taskkill\b[^;&|]*/F\b)|(Stop-Process\b[^;&|]*-Force\b)|(Stop-Service|Restart-Service)\b)'action: denydiff --git a/jiuwenclaw/resources/config.yaml b/jiuwenclaw/resources/config.yamlindex 485f8e0411..1a7e8abd32 100644--- a/jiuwenclaw/resources/config.yaml+++ b/jiuwenclaw/resources/config.yaml@@ -342,6 +342,7 @@ permissions:tools:bash: askmcp_exec_command: ask+ create_terminal: askwrite: askwrite_file: askedit_file: askdiff --git a/tests/unit_tests/agentserver/test_tiered_policy_permissions.py b/tests/unit_tests/agentserver/test_tiered_policy_permissions.pyindex e89745091b..f5c4cc6380 100644--- a/tests/unit_tests/agentserver/test_tiered_policy_permissions.py+++ b/tests/unit_tests/agentserver/test_tiered_policy_permissions.py@@ -18,6 +18,7 @@ from jiuwenclaw.agentserver.permissions.patterns import persist_permission_allowfrom jiuwenclaw.agentserver.permissions.tiered_policy import (collect_builtin_permission_rail_tool_names,evaluate_tiered_policy,+ maybe_escalate_shell_operators,permissions_schema_is_tiered_policy,severity_to_decision,strictest,@@ -134,6 +135,14 @@ def test_strictest_helper():assert strictest(PermissionLevel.ALLOW, PermissionLevel.DENY) == PermissionLevel.DENY+def test_create_terminal_operator_chain_escalates_allow_to_ask():+ assert maybe_escalate_shell_operators(+ "create_terminal",+ {"command": "echo ok && whoami"},+ PermissionLevel.ALLOW,+ ) == PermissionLevel.ASK++def test_whole_tool_allow_ignores_default_ask():cfg = {"permission_mode": "normal",diff --git a/tests/unit_tests/channel/test_acp_channel.py b/tests/unit_tests/channel/test_acp_channel.pyindex 597c402caa..09fd9be04d 100644--- a/tests/unit_tests/channel/test_acp_channel.py+++ b/tests/unit_tests/channel/test_acp_channel.py@@ -267,6 +267,63 @@ async def test_jsonrpc_session_prompt_emits_updates_and_final_result(monkeypatchassert result.get("stopReason") == "end_turn"+async def test_jsonrpc_session_prompt_accepts_text_param(monkeypatch):+ fake_stdin = FakeStdin(+ [+ json_line(+ {+ "jsonrpc": "2.0",+ "id": 301,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-text",+ "text": "hello from text",+ },+ }+ )+ ]+ )+ fake_stdout = FakeStdout()+ channel = AcpChannel(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):+ seen.append(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,+ )+ )++ channel.on_message(_on_message)+ await channel.start()++ assert len(seen) == 1+ assert seen[0].req_method == ReqMethod.CHAT_SEND+ assert seen[0].session_id == "sess-text"+ assert seen[0].params.get("query") == "hello from text"++ responses = fake_stdout.buffer.json_lines()+ assert responses[-1] == {+ "jsonrpc": "2.0",+ "id": 301,+ "result": {"stopReason": "end_turn"},+ }++@pytest.mark.asyncioasync def test_jsonrpc_session_prompt_merges_session_context(monkeypatch):fake_stdin = FakeStdin(diff --git a/tests/unit_tests/gateway/test_app_gateway_acp.py b/tests/unit_tests/gateway/test_app_gateway_acp.pyindex 3370e4eb2b..86fefda0e5 100644--- a/tests/unit_tests/gateway/test_app_gateway_acp.py+++ b/tests/unit_tests/gateway/test_app_gateway_acp.py@@ -141,6 +141,53 @@ async def test_gateway_server_send_event_targets_session_client():}+async def test_gateway_server_accepts_legacy_single_route_config_and_session_map():+ server = GatewayServerProbe(+ GatewayServerConfig(+ enabled=True,+ host="127.0.0.1",+ port=19001,+ path="/acp",+ channel_id="acp",+ ),+ DummyBus(),+ )++ ws = FakeWebSocket()+ server.bind_session_client("sess-tool", ws)++ await server.send(+ Message(+ id="req-tool",+ type="event",+ channel_id="acp",+ session_id="sess-tool",+ params={},+ timestamp=time.time(),+ ok=True,+ payload={+ "event_type": "acp.output_request",+ "jsonrpc": {+ "jsonrpc": "2.0",+ "id": "tool-legacy",+ "method": "fs/read_text_file",+ "params": {"path": "workspace/demo.txt", "sessionId": "sess-tool"},+ },+ },+ )+ )++ assert ws.sent_frames == [+ {+ "jsonrpc": "2.0",+ "id": "tool-legacy",+ "method": "fs/read_text_file",+ "params": {"path": "workspace/demo.txt", "sessionId": "sess-tool"},+ }+ ]++@pytest.mark.asyncioasync def test_gateway_server_passthroughs_acp_output_request_as_raw_jsonrpc():server = build_server()@@ -239,6 +286,73 @@ async def test_gateway_server_handle_raw_jsonrpc_response_forwards_acp_tool_resp}+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,+ )+ )++ 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[0]["params"]["sessionId"] == "sess-jsonrpc"+ assert ws.sent_frames[-1] == {+ "jsonrpc": "2.0",+ "id": 99,+ "result": {"stopReason": "end_turn"},+ }++@pytest.mark.asyncioasync def test_gateway_server_handle_raw_message_forwards_request():server = build_server()@@ -275,6 +389,7 @@ async def test_gateway_server_handle_raw_message_forwards_request():assert msg.req_method == ReqMethod.CHAT_SENDassert msg.params.get("content") == "hello"assert msg.mode.value == "agent"+ assert ws.sent_frames == []@pytest.mark.asyncio