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协议补充update事件
zp23331bff2c33855d1
diff --git a/jiuwenclaw/channel/acp_channel.py b/jiuwenclaw/channel/acp_channel.pyindex f25e5bc45d..e0bb16ffd2 100644--- a/jiuwenclaw/channel/acp_channel.py+++ b/jiuwenclaw/channel/acp_channel.py@@ -16,6 +16,7 @@ from jiuwenclaw.e2a.adapters import envelope_from_acp_jsonrpcfrom jiuwenclaw.e2a.constants import (E2A_RESPONSE_KIND_ACP_JSONRPC_ERROR,E2A_RESPONSE_KIND_ACP_PROMPT_RESULT,+ E2A_RESPONSE_KIND_ACP_SESSION_UPDATE,E2A_RESPONSE_KIND_E2A_CHUNK,E2A_RESPONSE_STATUS_FAILED,E2A_RESPONSE_STATUS_IN_PROGRESS,@@ -324,6 +325,29 @@ class AcpChannel(BaseChannel):body=result_body,)+ if msg.type == "event":+ update = self._build_acp_session_update(msg, payload, ctx)+ if update is not None:+ ctx.sequence += 1+ return E2AResponse(+ response_id=f"{msg.id}:{sequence}",+ request_id=msg.id,+ jsonrpc_id=ctx.jsonrpc_id,+ sequence=sequence,+ is_final=False,+ status=E2A_RESPONSE_STATUS_IN_PROGRESS,+ response_kind=E2A_RESPONSE_KIND_ACP_SESSION_UPDATE,+ timestamp=ts,+ provenance=self._provenance(str(msg.event_type.value if msg.event_type else "session.update")),+ channel=self.channel_id,+ session_id=msg.session_id,+ is_stream=True,+ body={+ "sessionId": str(msg.session_id or ctx.session_id or ""),+ "update": update,+ },+ )+if msg.type == "res" and msg.ok:if payload.get("accepted") is True:return None@@ -645,35 +669,25 @@ class AcpChannel(BaseChannel):if not text:return Falseself._schedule_idle_finalize(str(msg.id), ctx)- 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.uuid4().hex[:12]}"- await self._write_jsonrpc_notification(- "session/update",- {- "sessionId": session_id,- "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.uuid4().hex[:12]}"- await self._write_jsonrpc_notification(- "session/update",- {- "sessionId": session_id,- "update": {- "sessionUpdate": "agent_message_chunk",- "messageId": ctx.assistant_message_id,- "content": {"type": "text", "text": text},- },- },- )+ update = self._build_acp_session_update(msg, payload, ctx)+ if update is None:+ return False+ await self._write_acp_session_update(session_id, update)+ return False++ if msg.type == "event" and msg.event_type in (+ EventType.CHAT_TOOL_CALL,+ EventType.CHAT_TOOL_RESULT,+ 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+ await self._write_acp_session_update(session_id, update)return Falseif msg.type == "event" and msg.event_type == EventType.CHAT_FINAL:@@ -684,15 +698,21 @@ class AcpChannel(BaseChannel):content = str(payload.get("content", "") or "")if content and not ctx.assistant_message_id:ctx.assistant_message_id = f"msg_{uuid.uuid4().hex[:12]}"- await self._write_jsonrpc_notification(- "session/update",+ await self._write_acp_session_update(+ session_id,{- "sessionId": session_id,- "update": {- "sessionUpdate": "agent_message_chunk",- "messageId": ctx.assistant_message_id,- "content": {"type": "text", "text": content},- },+ "sessionUpdate": "agent_message_chunk",+ "messageId": ctx.assistant_message_id,+ "content": {"type": "text", "text": content},+ },+ )+ usage = payload.get("usage")+ if isinstance(usage, dict) and usage:+ await self._write_acp_session_update(+ session_id,+ {+ "sessionUpdate": "usage_update",+ "usage": dict(usage),},)await self._write_jsonrpc_result(@@ -729,18 +749,23 @@ class AcpChannel(BaseChannel):return Trueif msg.type == "event":- if msg.event_type == EventType.CHAT_PROCESSING_STATUS and 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._write_jsonrpc_result(- ctx.jsonrpc_id,- {- "stopReason": "end_turn",- },- )- return True+ if msg.event_type == EventType.CHAT_PROCESSING_STATUS:+ update = self._build_acp_session_update(msg, payload, ctx)+ 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+ await self._write_jsonrpc_result(+ ctx.jsonrpc_id,+ {+ "stopReason": "end_turn",+ },+ )+ return True+ return Falsereturn Falseif msg.type == "res" and msg.ok:@@ -765,6 +790,92 @@ class AcpChannel(BaseChannel):)return True+ async def _write_acp_session_update(self, session_id: str, update: dict[str, Any]) -> None:+ await self._write_jsonrpc_notification(+ "session/update",+ {+ "sessionId": session_id,+ "update": update,+ },+ )++ def _build_acp_session_update(+ self,+ msg: Message,+ payload: dict[str, Any],+ ctx: _AcpRequestContext,+ ) -> dict[str, Any] | None:+ event_type = msg.event_type+ if event_type == EventType.CHAT_DELTA:+ text = str(payload.get("content", "") or "")+ if not text:+ return None+ 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.uuid4().hex[:12]}"+ return {+ "sessionUpdate": "agent_thought_chunk",+ "messageId": ctx.thought_message_id,+ "content": {"type": "text", "text": text},+ }++ if not ctx.assistant_message_id:+ ctx.assistant_message_id = f"msg_{uuid.uuid4().hex[:12]}"+ return {+ "sessionUpdate": "agent_message_chunk",+ "messageId": ctx.assistant_message_id,+ "content": {"type": "text", "text": text},+ }++ 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", {}),+ },+ }++ 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 == EventType.CHAT_SUBTASK_UPDATE:+ return {+ "sessionUpdate": "plan",+ "plan": dict(payload),+ }++ if event_type == EventType.CHAT_PROCESSING_STATUS:+ return {+ "sessionUpdate": "session_info_update",+ "status": "processing" if bool(payload.get("is_processing", True)) else "idle",+ }++ return None+@staticmethoddef _is_jsonrpc_request(data: Any) -> bool:return (diff --git a/tests/unit_tests/channel/test_acp_channel.py b/tests/unit_tests/channel/test_acp_channel.pyindex f589ddb544..597c402caa 100644--- a/tests/unit_tests/channel/test_acp_channel.py+++ b/tests/unit_tests/channel/test_acp_channel.py@@ -54,7 +54,8 @@ class FakeStdout:class AcpChannelHarness(AcpChannel):- pass+ async def send_jsonrpc_message_for_test(self, msg, ctx):+ return await self._send_jsonrpc_message(msg, ctx)def json_line(payload):@@ -510,3 +511,449 @@ async def test_gateway_jsonrpc_request_is_written_to_stdout(monkeypatch):}]assert channel.get_pending_client_rpc_session_for_test("tool-2") == "sess-tool"+++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,+ )+ )+ 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_FINAL,+ )+ )++ channel.on_message(_on_message)+ await channel.start()++ responses = fake_stdout.buffer.json_lines()+ assert len(responses) == 3+ assert responses[0]["params"]["update"] == {+ "sessionUpdate": "tool_call",+ "toolCall": {+ "id": "tool-call-1",+ "name": "read_file",+ "arguments": {"path": "demo.txt"},+ },+ }+++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"}],+ },+ }+ )+ ]+ )+ 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_name": "read_file",+ "tool_call_id": "tool-call-2",+ "result": "file contents",+ },+ 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={"content": "done"},+ event_type=EventType.CHAT_FINAL,+ )+ )++ channel.on_message(_on_message)+ await channel.start()++ responses = fake_stdout.buffer.json_lines()+ assert len(responses) == 3+ assert responses[0]["params"]["update"] == {+ "sessionUpdate": "tool_call_update",+ "toolCallId": "tool-call-2",+ "toolName": "read_file",+ "result": "file contents",+ }+++async def test_jsonrpc_session_prompt_emits_plan_update(monkeypatch):+ fake_stdin = FakeStdin(+ [+ json_line(+ {+ "jsonrpc": "2.0",+ "id": 32,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-plan",+ "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={+ "session_id": msg.session_id,+ "description": "并行执行两个任务",+ "status": "running",+ "index": 1,+ "total": 2,+ "result": "已启动后台会话",+ "is_parallel": True,+ },+ event_type=EventType.CHAT_SUBTASK_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={"content": "done"},+ event_type=EventType.CHAT_FINAL,+ )+ )++ channel.on_message(_on_message)+ await channel.start()++ responses = fake_stdout.buffer.json_lines()+ assert len(responses) == 3+ update = responses[0]["params"]["update"]+ assert update["sessionUpdate"] == "plan"+ assert update["plan"]["description"] == "并行执行两个任务"+ assert update["plan"]["is_parallel"] is True+++async def test_jsonrpc_session_prompt_emits_processing_status_update(monkeypatch):+ fake_stdin = FakeStdin(+ [+ json_line(+ {+ "jsonrpc": "2.0",+ "id": 33,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-processing",+ "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={"is_processing": True},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )+ 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": "session_info_update",+ "status": "processing",+ }+ 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_usage_update_before_result(monkeypatch):+ fake_stdin = FakeStdin(+ [+ json_line(+ {+ "jsonrpc": "2.0",+ "id": 34,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-usage",+ "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": "done",+ "usage": {+ "inputTokens": 12,+ "outputTokens": 34,+ },+ },+ event_type=EventType.CHAT_FINAL,+ )+ )++ 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_message_chunk"+ assert responses[1]["params"]["update"] == {+ "sessionUpdate": "usage_update",+ "usage": {+ "inputTokens": 12,+ "outputTokens": 34,+ },+ }+ assert responses[2] == {+ "jsonrpc": "2.0",+ "id": 34,+ "result": {"stopReason": "end_turn"},+ }+++async def test_processing_status_true_does_not_schedule_idle_finalize(monkeypatch):+ fake_stdout = FakeStdout()+ channel = AcpChannelHarness(AcpChannelConfig(enabled=True), DummyBus())+ ctx = types.SimpleNamespace(+ jsonrpc_id=35,+ method="session/prompt",+ response_mode="jsonrpc",+ session_id="sess-processing-only",+ assistant_message_id=None,+ thought_message_id=None,+ sequence=0,+ idle_finalize_task=None,+ )++ 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(+ id="req-processing-only",+ type="event",+ channel_id="acp",+ session_id="sess-processing-only",+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": True},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ ),+ ctx,+ )++ responses = fake_stdout.buffer.json_lines()+ assert is_final is False+ assert responses == [+ {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "sessionId": "sess-processing-only",+ "update": {+ "sessionUpdate": "session_info_update",+ "status": "processing",+ },+ },+ }+ ]+ assert ctx.idle_finalize_task is None+++async def test_tool_events_cancel_idle_finalize_instead_of_scheduling(monkeypatch):+ import asyncio++ 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=36,+ method="session/prompt",+ response_mode="jsonrpc",+ session_id="sess-tool-idle",+ 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(+ id="req-tool-idle",+ type="event",+ channel_id="acp",+ session_id="sess-tool-idle",+ params={},+ timestamp=time.time(),+ ok=True,+ payload={+ "tool_call": {+ "name": "terminal_create",+ "arguments": {"cmd": "ls"},+ "tool_call_id": "tc-idle-1",+ }+ },+ event_type=EventType.CHAT_TOOL_CALL,+ ),+ ctx,+ )++ assert is_final is False+ assert ctx.idle_finalize_task is None+ assert sentinel_task.cancelled()