Skip to content

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

Python

fix: send_request 发送时流式参数错误

douran657cdeed9ae8
diff --git a/jiuwenclaw/agentserver/agent_ws_server.py b/jiuwenclaw/agentserver/agent_ws_server.py
index ba2f9450ad..e394843327 100644
--- a/jiuwenclaw/agentserver/agent_ws_server.py
+++ b/jiuwenclaw/agentserver/agent_ws_server.py
@@ -19,6 +19,7 @@ from jiuwenclaw.e2a.gateway_normalize import (
E2A_LEGACY_AGENT_REQUEST_KEY,
)
from jiuwenclaw.e2a.models import E2AEnvelope
+from jiuwenclaw.e2a.constants import E2A_WIRE_SERVER_PUSH_KEY
from jiuwenclaw.e2a.wire_codec import (
encode_agent_chunk_for_wire,
encode_agent_response_for_wire,
@@ -542,6 +543,13 @@ class AgentWebSocketServer:
response_id=str(msg.get("request_id", "")),
sequence=0,
)
+ # 与同一 request_id 上的 unary/stream RPC 响应区分,避免 Gateway 将推送当作 RPC 首包解析
+ md = dict(wire.get("metadata") or {})
+ md[E2A_WIRE_SERVER_PUSH_KEY] = True
+ wire["metadata"] = md
+ sid = msg.get("session_id")
+ if sid is not None and str(sid).strip():
+ wire["session_id"] = str(sid)
async with self._current_send_lock:
await self._current_ws.send(json.dumps(wire, ensure_ascii=False))
logger.info(
diff --git a/jiuwenclaw/agentserver/prompt_builder.py b/jiuwenclaw/agentserver/prompt_builder.py
index ebcde9f80c..39cc364ac5 100644
--- a/jiuwenclaw/agentserver/prompt_builder.py
+++ b/jiuwenclaw/agentserver/prompt_builder.py
@@ -960,7 +960,10 @@ Be a warm person, not a cold machine. Help your user unconditionally and meet th
def build_user_prompt(content: str, files: dict, channel: str, language: str) -> str:
"""Build user prompt for the agent."""
- prompt = "你收到一条消息:\n"
+ if language == "zh":
+ prompt = "你收到一条消息:\n"
+ else:
+ prompt = "You receive a new message:\n"
if channel in ["cron", "heartbeat"]:
return prompt + json.dumps(
{
diff --git a/jiuwenclaw/agentserver/tools/multi_session_toolkits.py b/jiuwenclaw/agentserver/tools/multi_session_toolkits.py
index 939943bdba..a46bd4512a 100644
--- a/jiuwenclaw/agentserver/tools/multi_session_toolkits.py
+++ b/jiuwenclaw/agentserver/tools/multi_session_toolkits.py
@@ -205,6 +205,7 @@ class MultiSessionToolkit:
msg = {
"request_id": self.request_id,
"channel_id": self.channel_id,
+ "session_id": self.session_id,
"payload": payload,
"is_complete": False,
}
@@ -269,6 +270,7 @@ class MultiSessionToolkit:
msg = {
"request_id": self.request_id,
"channel_id": self.channel_id,
+ "session_id": self.session_id,
"payload": payload,
"is_complete": True,
}
diff --git a/jiuwenclaw/agentserver/tools/send_file_to_user.py b/jiuwenclaw/agentserver/tools/send_file_to_user.py
index 8e534db414..047341c7eb 100644
--- a/jiuwenclaw/agentserver/tools/send_file_to_user.py
+++ b/jiuwenclaw/agentserver/tools/send_file_to_user.py
@@ -106,6 +106,7 @@ class SendFileToolkit:
msg = {
"request_id": self.request_id,
"channel_id": self.channel_id,
+ "session_id": self.session_id,
"payload": {
"event_type": "chat.file",
"files": files_payload,
diff --git a/jiuwenclaw/e2a/__init__.py b/jiuwenclaw/e2a/__init__.py
index f1e74a4175..731094d75f 100644
--- a/jiuwenclaw/e2a/__init__.py
+++ b/jiuwenclaw/e2a/__init__.py
@@ -21,6 +21,7 @@ from jiuwenclaw.e2a.constants import (
E2A_RESPONSE_KINDS,
E2A_WIRE_LEGACY_AGENT_CHUNK_KEY,
E2A_WIRE_LEGACY_AGENT_RESPONSE_KEY,
+ E2A_WIRE_SERVER_PUSH_KEY,
E2A_RESPONSE_KIND_ACP_JSONRPC_ERROR,
E2A_RESPONSE_KIND_ACP_PROMPT_RESULT,
E2A_RESPONSE_KIND_ACP_SESSION_UPDATE,
@@ -95,6 +96,7 @@ __all__ = [
"E2A_RESPONSE_KIND_EXT",
"E2A_WIRE_LEGACY_AGENT_CHUNK_KEY",
"E2A_WIRE_LEGACY_AGENT_RESPONSE_KEY",
+ "E2A_WIRE_SERVER_PUSH_KEY",
"E2A_RESPONSE_STATUS_FAILED",
"E2A_RESPONSE_STATUS_IN_PROGRESS",
"E2A_RESPONSE_STATUS_SUCCEEDED",
diff --git a/jiuwenclaw/e2a/constants.py b/jiuwenclaw/e2a/constants.py
index bd5eac16b9..b8e94c31fd 100644
--- a/jiuwenclaw/e2a/constants.py
+++ b/jiuwenclaw/e2a/constants.py
@@ -87,6 +87,8 @@ ACP_NOTIFICATION_NAMES: tuple[str, ...] = (
# AgentServer → Gateway WebSocket:编码失败时整包旧 JSON 写入 E2AResponse.metadata 的键(勿与业务键冲突)
E2A_WIRE_LEGACY_AGENT_RESPONSE_KEY = "_e2a_wire_legacy_agent_response"
E2A_WIRE_LEGACY_AGENT_CHUNK_KEY = "_e2a_wire_legacy_agent_chunk"
+# AgentServer send_push:与 RPC 响应共用 WebSocket,须标出以免抢占 unary/stream 等待队列
+E2A_WIRE_SERVER_PUSH_KEY = "_jiuwenclaw_server_push"
ACP_SESSION_UPDATE_KINDS: tuple[str, ...] = (
"user_message_chunk",
diff --git a/jiuwenclaw/e2a/gateway_normalize.py b/jiuwenclaw/e2a/gateway_normalize.py
index 6082d8719e..4aba8344ef 100644
--- a/jiuwenclaw/e2a/gateway_normalize.py
+++ b/jiuwenclaw/e2a/gateway_normalize.py
@@ -408,7 +408,9 @@ def e2a_response_to_agent_response(e2a: E2AResponse) -> "AgentResponse":
)
raise ValueError(
- f"e2a_response_to_agent_response: unsupported response_kind={kind!r} status={e2a.status!r}"
+ f"e2a_response_to_agent_response: unsupported response_kind={kind!r} status={e2a.status!r}. "
+ "Streaming frames (e2a.chunk / in_progress) must use parse_agent_server_wire_chunk / send_request_stream. "
+ "If unexpected, check outbound envelope is_stream and duplicate in-flight request_id on the WebSocket client."
)
diff --git a/jiuwenclaw/gateway/agent_client.py b/jiuwenclaw/gateway/agent_client.py
index dc9d38098a..12c76bbf81 100644
--- a/jiuwenclaw/gateway/agent_client.py
+++ b/jiuwenclaw/gateway/agent_client.py
@@ -8,9 +8,11 @@ import logging
import asyncio
import json
from abc import ABC, abstractmethod
+from collections.abc import Awaitable, Callable
from dataclasses import asdict
from typing import Any, AsyncIterator
+from jiuwenclaw.e2a.constants import E2A_WIRE_SERVER_PUSH_KEY
from jiuwenclaw.e2a.models import E2AEnvelope
from jiuwenclaw.e2a.wire_codec import (
parse_agent_server_wire_chunk,
@@ -22,6 +24,13 @@ from jiuwenclaw.schema.agent import AgentResponse, AgentResponseChunk
logger = logging.getLogger(__name__)
+def _wire_request_id_key(request_id: Any) -> str:
+ """与 AgentServer 回包 ``request_id`` 对齐:统一为 str,避免 JSON 数字/字符串导致队列键不一致。"""
+ if request_id is None:
+ return ""
+ return str(request_id)
+
+
def _to_json(data: Any) -> str:
"""将任意对象序列化为日志友好的 JSON 字符串."""
try:
@@ -82,6 +91,14 @@ class WebSocketAgentServerClient(AgentServerClient):
self._message_queues: dict[str, asyncio.Queue] = {}
self._receiver_task: asyncio.Task | None = None
self._running = False
+ # AgentServer send_push:旁路投递,勿进入与 request_id 绑定的 RPC 等待队列
+ self._on_server_push: Callable[[dict[str, Any]], Awaitable[None]] | None = None
+
+ def set_server_push_handler(
+ self, handler: Callable[[dict[str, Any]], Awaitable[None]] | None
+ ) -> None:
+ """注册 Agent 主动推送处理回调(metadata 含 ``E2A_WIRE_SERVER_PUSH_KEY`` 的帧)。"""
+ self._on_server_push = handler
@property
def server_ready(self) -> bool:
@@ -139,7 +156,18 @@ class WebSocketAgentServerClient(AgentServerClient):
try:
raw = await self._ws.recv()
data = json.loads(raw)
- request_id = data.get("request_id")
+ meta = data.get("metadata")
+ if isinstance(meta, dict) and meta.get(E2A_WIRE_SERVER_PUSH_KEY):
+ if self._on_server_push is not None:
+ await self._on_server_push(data)
+ else:
+ logger.warning(
+ "[WebSocketAgentServerClient] 收到 server_push 但未注册 handler,已丢弃: "
+ "request_id=%s",
+ data.get("request_id"),
+ )
+ continue
+ request_id = _wire_request_id_key(data.get("request_id"))
if request_id and request_id in self._message_queues:
# 将消息放入对应的队列
@@ -190,7 +218,9 @@ class WebSocketAgentServerClient(AgentServerClient):
async def send_request(self, envelope: E2AEnvelope) -> AgentResponse:
self._ensure_connected()
- rid = envelope.request_id or ""
+ # 非流式 API 必须与 AgentServer 的 unary 路径一致;忽略信封上误带的 is_stream=True。
+ envelope.is_stream = False
+ rid = _wire_request_id_key(envelope.request_id)
logger.info(
"[E2A][out][nostream] request_id=%s channel=%s method=%s is_stream=%s",
rid,
@@ -203,6 +233,12 @@ class WebSocketAgentServerClient(AgentServerClient):
_to_json(envelope.to_dict()),
)
+ if rid in self._message_queues:
+ raise RuntimeError(
+ f"WebSocketAgentServerClient: duplicate in-flight request_id={rid!r}; "
+ "refusing to register queue (would mis-route responses, e.g. stream chunks to unary waiters)."
+ )
+
# 创建该请求的消息队列
queue = asyncio.Queue()
self._message_queues[rid] = queue
@@ -230,7 +266,7 @@ class WebSocketAgentServerClient(AgentServerClient):
) -> AsyncIterator[AgentResponseChunk]:
self._ensure_connected()
envelope.is_stream = True
- rid = envelope.request_id or ""
+ rid = _wire_request_id_key(envelope.request_id)
logger.info(
"[E2A][out][stream] request_id=%s channel=%s method=%s is_stream=%s",
rid,
@@ -243,6 +279,12 @@ class WebSocketAgentServerClient(AgentServerClient):
_to_json(envelope.to_dict()),
)
+ if rid in self._message_queues:
+ raise RuntimeError(
+ f"WebSocketAgentServerClient: duplicate in-flight request_id={rid!r}; "
+ "refusing to register queue (would mis-route responses, e.g. stream chunks to unary waiters)."
+ )
+
# 创建该请求的消息队列
queue = asyncio.Queue()
self._message_queues[rid] = queue
diff --git a/jiuwenclaw/gateway/message_handler.py b/jiuwenclaw/gateway/message_handler.py
index d2295ab352..754723721c 100644
--- a/jiuwenclaw/gateway/message_handler.py
+++ b/jiuwenclaw/gateway/message_handler.py
@@ -93,6 +93,10 @@ class MessageHandler(ABC):
self._get_config_raw = get_config_raw
self._update_channel_in_config = update_channel_in_config
+ from jiuwenclaw.gateway.agent_client import WebSocketAgentServerClient
+
+ if isinstance(agent_client, WebSocketAgentServerClient):
+ agent_client.set_server_push_handler(self._handle_agent_server_push)
@classmethod
def get_instance(cls, agent_client: "AgentServerClient | None" = None) -> "MessageHandler":
@@ -463,6 +467,29 @@ class MessageHandler(ABC):
metadata=metadata,
)
+ async def _handle_agent_server_push(self, wire: dict[str, Any]) -> None:
+ """AgentServer ``send_push`` 下行:与 RPC 共用连接但不得占用 unary/stream 等待队列。"""
+ from jiuwenclaw.e2a.wire_codec import parse_agent_server_wire_chunk
+
+ try:
+ chunk = parse_agent_server_wire_chunk(wire)
+ except Exception as e:
+ logger.exception("[MessageHandler] server_push 解析失败: %s", e)
+ return
+ rid = str(chunk.request_id or "")
+ sid_raw = wire.get("session_id")
+ if sid_raw is not None and str(sid_raw).strip():
+ session_id: str | None = str(sid_raw)
+ else:
+ session_id = self._stream_sessions.get(rid)
+ out = self._chunk_to_message(chunk, session_id=session_id, metadata=None)
+ await self.publish_robot_messages(out)
+ logger.info(
+ "[MessageHandler] server_push 已写入 robot_messages: request_id=%s channel_id=%s",
+ rid,
+ chunk.channel_id,
+ )
+
@staticmethod
def _chunk_to_message(
chunk: AgentResponseChunk,