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

feat: 1. interface所有接收的输入,产生的输出落盘 2. agent_server 里添加 get_conversation_history 方法. 返回历史消息和总页数 3. gateway提供history.get,调用agent server定义的方法,将返回的内容流式返回,每条历史消息发一个事件

Haowei_Du52d4235f1cdc
diff --git a/jiuwenclaw/agentserver/agent_ws_server.py b/jiuwenclaw/agentserver/agent_ws_server.py
index 4f52bad6cd..1818d77657 100644
--- a/jiuwenclaw/agentserver/agent_ws_server.py
+++ b/jiuwenclaw/agentserver/agent_ws_server.py
@@ -6,10 +6,12 @@ from __future__ import annotations
import asyncio
import json
+import math
from dataclasses import asdict
+from pathlib import Path
from typing import Any, ClassVar
-from jiuwenclaw.utils import logger
+from jiuwenclaw.utils import get_agent_sessions_dir, logger
from jiuwenclaw.schema.agent import AgentRequest, AgentResponse, AgentResponseChunk
@@ -227,6 +229,14 @@ class AgentWebSocketServer:
)
try:
+ from jiuwenclaw.schema.message import ReqMethod
+
+ if request.req_method == ReqMethod.HISTORY_GET:
+ if request.is_stream:
+ await self._handle_history_get_stream(ws, request, send_lock)
+ else:
+ await self._handle_history_get(ws, request, send_lock)
+ return
if request.is_stream:
await self._handle_stream(ws, request, send_lock)
else:
@@ -273,6 +283,80 @@ class AgentWebSocketServer:
chunk_count,
)
+ async def _handle_history_get(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
+ params = request.params if isinstance(request.params, dict) else {}
+ session_id = params.get("session_id")
+ page_idx = params.get("page_idx")
+ data = self.get_conversation_history(session_id=session_id, page_idx=page_idx)
+ if data is None:
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={"error": "invalid page_idx or session history not found"},
+ )
+ else:
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=True,
+ payload=data,
+ )
+ async with send_lock:
+ await ws.send(json.dumps(_response_to_payload(resp), ensure_ascii=False))
+
+ async def _handle_history_get_stream(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
+ params = request.params if isinstance(request.params, dict) else {}
+ session_id = params.get("session_id")
+ page_idx = params.get("page_idx")
+ data = self.get_conversation_history(session_id=session_id, page_idx=page_idx)
+ if data is None:
+ err_chunk = AgentResponseChunk(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ payload={
+ "event_type": "chat.error",
+ "error": "invalid page_idx or session history not found",
+ },
+ is_complete=True,
+ )
+ async with send_lock:
+ await ws.send(json.dumps(_chunk_to_payload(err_chunk), ensure_ascii=False))
+ return
+
+ messages = data.get("messages", [])
+ total_pages = data.get("total_pages")
+ page = data.get("page_idx")
+ if isinstance(messages, list):
+ for item in messages:
+ chunk = AgentResponseChunk(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ payload={
+ "event_type": "history.message",
+ "message": item,
+ "total_pages": total_pages,
+ "page_idx": page,
+ },
+ is_complete=False,
+ )
+ async with send_lock:
+ await ws.send(json.dumps(_chunk_to_payload(chunk), ensure_ascii=False))
+
+ done_chunk = AgentResponseChunk(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ payload={
+ "event_type": "history.message",
+ "status": "done",
+ "total_pages": total_pages,
+ "page_idx": page,
+ },
+ is_complete=True,
+ )
+ async with send_lock:
+ await ws.send(json.dumps(_chunk_to_payload(done_chunk), ensure_ascii=False))
+
async def send_push(self, msg) -> None:
"""AgentServer 主动向 Gateway 推送消息。
@@ -296,4 +380,37 @@ class AgentWebSocketServer:
logger.warning("[AgentWebSocketServer] send_push 失败: %s", e)
def get_agent(self):
- return getattr(self._agent, "_instance", None)
\ No newline at end of file
+ return getattr(self._agent, "_instance", None)
+
+ @staticmethod
+ def get_conversation_history(session_id: str, page_idx: int) -> dict[str, Any] | None:
+ # 按照 session_id 和分页消息获取历史记录
+ if not isinstance(session_id, str) or not session_id.strip():
+ return None
+ if not isinstance(page_idx, int) or page_idx <= 0:
+ return None
+
+ history_path: Path = get_agent_sessions_dir() / session_id.strip() / "history.json"
+ if not history_path.exists():
+ return None
+ try:
+ raw = json.loads(history_path.read_text(encoding="utf-8"))
+ except Exception:
+ return None
+ if not isinstance(raw, list):
+ return None
+
+ page_size = 50
+ total = len(raw)
+ total_pages = max(1, math.ceil(total / page_size))
+ if page_idx > total_pages:
+ return None
+
+ ordered = list(reversed(raw))
+ start = (page_idx - 1) * page_size
+ end = start + page_size
+ return {
+ "messages": ordered[start:end],
+ "total_pages": total_pages,
+ "page_idx": page_idx,
+ }
\ No newline at end of file
diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.py
index 703c9af91e..1c6669ecf3 100644
--- a/jiuwenclaw/agentserver/interface.py
+++ b/jiuwenclaw/agentserver/interface.py
@@ -7,6 +7,7 @@ from __future__ import annotations
import asyncio
import json
import os
+import time
from typing import Any, AsyncIterator
from dotenv import load_dotenv
@@ -85,6 +86,7 @@ from jiuwenclaw.agentserver.skill_manager import SkillManager, _SKILLS_DIR
from jiuwenclaw.evolution.service import EvolutionService
from jiuwenclaw.schema.agent import AgentRequest, AgentResponse, AgentResponseChunk
from jiuwenclaw.agentserver.memory import get_memory_manager
+from jiuwenclaw.agentserver.session_history import append_history_record
from jiuwenclaw.schema.message import ReqMethod
load_dotenv(dotenv_path=get_env_file())
@@ -1011,6 +1013,15 @@ class JiuWenClaw:
)
session_id = self._get_session_id(request)
+ query = request.params.get("query", "")
+ append_history_record(
+ session_id=session_id,
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ role="user",
+ content=query,
+ timestamp=time.time(),
+ )
# 确保 session 的任务处理器在运行
await self._ensure_session_processor(session_id)
@@ -1030,7 +1041,6 @@ class JiuWenClaw:
),
}
- query = request.params.get("query", "")
if self._compaction_manager:
self._compaction_manager.add_message("user", query)
@@ -1094,6 +1104,17 @@ class JiuWenClaw:
content_str = str(content)
self._compaction_manager.add_message("assistant", content_str)
+ assistant_content = content if isinstance(content, str) else str(content)
+ append_history_record(
+ session_id=session_id,
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ role="assistant",
+ event_type="chat.final",
+ content=assistant_content,
+ timestamp=time.time(),
+ )
+
return AgentResponse(
request_id=request.request_id,
channel_id=request.channel_id,
@@ -1132,6 +1153,15 @@ class JiuWenClaw:
return
session_id = self._get_session_id(request)
+ query = request.params.get("query", "")
+ append_history_record(
+ session_id=session_id,
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ role="user",
+ content=query,
+ timestamp=time.time(),
+ )
await self._ensure_session_processor(session_id)
logger.info(
@@ -1150,7 +1180,6 @@ class JiuWenClaw:
}
# supplement 任务:读取现有 todo 待办,拼入 query 让 agent 知道有未完成的任务
- query = request.params.get("query", "")
if self._compaction_manager:
self._compaction_manager.add_message("user", query)
memory_mgr = await get_memory_manager(
@@ -1215,6 +1244,15 @@ class JiuWenClaw:
if isinstance(data, asyncio.CancelledError):
logger.info("[JiuWenClaw] 流式处理被中断: request_id=%s", rid)
raise data
+ append_history_record(
+ session_id=session_id,
+ request_id=rid,
+ channel_id=cid,
+ role="assistant",
+ event_type="chat.error",
+ content=str(data),
+ timestamp=time.time(),
+ )
yield AgentResponseChunk(
request_id=rid,
channel_id=cid,
@@ -1222,6 +1260,17 @@ class JiuWenClaw:
is_complete=False,
)
else:
+ if isinstance(data, dict) and isinstance(data.get("event_type"), str):
+ append_history_record(
+ session_id=session_id,
+ request_id=rid,
+ channel_id=cid,
+ role="assistant",
+ event_type=str(data.get("event_type")),
+ content=data.get("content") or data.get("error") or "",
+ timestamp=time.time(),
+ extra={"event_payload": dict(data)},
+ )
yield AgentResponseChunk(
request_id=rid,
channel_id=cid,
diff --git a/jiuwenclaw/agentserver/session_history.py b/jiuwenclaw/agentserver/session_history.py
new file mode 100644
index 0000000000..ad52b891f5
--- /dev/null
+++ b/jiuwenclaw/agentserver/session_history.py
@@ -0,0 +1,106 @@
+from __future__ import annotations
+
+import json
+import queue
+import threading
+from pathlib import Path
+from typing import Any
+
+from jiuwenclaw.utils import get_agent_sessions_dir, logger
+
+_FILE_LOCK = threading.Lock()
+_WRITE_QUEUE: queue.Queue[tuple[str, dict[str, Any]]] = queue.Queue(maxsize=20000)
+_WORKER_STARTED = False
+_WORKER_LOCK = threading.Lock()
+
+
+def _history_file(session_id: str) -> Path:
+ session_dir = get_agent_sessions_dir() / session_id
+ session_dir.mkdir(parents=True, exist_ok=True)
+ return session_dir / "history.json"
+
+
+def _read_history(path: Path) -> list[dict[str, Any]]:
+ if not path.exists():
+ return []
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except Exception as exc: # noqa: BLE001
+ logger.warning("读取 history.json 失败,已忽略并重建: %s", exc)
+ return []
+ if isinstance(data, list):
+ return data
+ return []
+
+
+def _write_item(session_id: str, item: dict[str, Any]) -> None:
+ fpath = _history_file(session_id)
+ with _FILE_LOCK:
+ history = _read_history(fpath)
+ history.append(item)
+ fpath.write_text(
+ json.dumps(history, ensure_ascii=False, indent=2),
+ encoding="utf-8",
+ )
+
+
+def _ensure_worker_started() -> None:
+ global _WORKER_STARTED
+ if _WORKER_STARTED:
+ return
+ with _WORKER_LOCK:
+ if _WORKER_STARTED:
+ return
+
+ def _worker() -> None:
+ while True:
+ sid, item = _WRITE_QUEUE.get()
+ try:
+ _write_item(sid, item)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("history 异步写入失败: %s", exc)
+ finally:
+ _WRITE_QUEUE.task_done()
+
+ t = threading.Thread(target=_worker, name="session-history-writer", daemon=True)
+ t.start()
+ _WORKER_STARTED = True
+
+
+def append_history_record(
+ *,
+ session_id: str,
+ request_id: str,
+ channel_id: str,
+ role: str,
+ content: Any,
+ timestamp: float,
+ event_type: str | None = None,
+ extra: dict[str, Any] | None = None,
+) -> None:
+ """向指定 session 的 history.json 异步追加一条记录."""
+ sid = (session_id or "default").strip() or "default"
+ rid = str(request_id or "").strip()
+ cid = str(channel_id or "").strip()
+ role_norm = "assistant" if role == "assistant" else "user"
+ content_text = content if isinstance(content, str) else str(content)
+
+ item: dict[str, Any] = {
+ "id": f"{rid}:{role_norm}",
+ "role": role_norm,
+ "request_id": rid,
+ "channel_id": cid,
+ "timestamp": float(timestamp),
+ "content": content_text,
+ }
+ if role_norm == "assistant" and event_type:
+ item["event_type"] = event_type
+ if isinstance(extra, dict) and extra:
+ item.update(extra)
+
+ _ensure_worker_started()
+ try:
+ _WRITE_QUEUE.put_nowait((sid, item))
+ except queue.Full:
+ # 队列满时退化为同步写,避免丢历史记录。
+ _write_item(sid, item)
diff --git a/jiuwenclaw/app.py b/jiuwenclaw/app.py
index ce745ed4ac..7fd1690917 100644
--- a/jiuwenclaw/app.py
+++ b/jiuwenclaw/app.py
@@ -102,6 +102,7 @@ _FORWARD_REQ_METHODS = frozenset({
"chat.interrupt",
"chat.resume",
"chat.user_answer",
+ "history.get",
# "tts.synthesize",
"skills.marketplace.list",
"skills.list",
@@ -580,6 +581,15 @@ def _register_web_handlers(
payload["request_id"] = request_id
await channel.send_response(ws, req_id, ok=True, payload=payload)
+ async def _history_get(ws, req_id, params, session_id):
+ payload = {"accepted": True, "session_id": session_id}
+ if isinstance(params, dict):
+ if "session_id" in params:
+ payload["session_id"] = params.get("session_id")
+ if "page_idx" in params:
+ payload["page_idx"] = params.get("page_idx")
+ await channel.send_response(ws, req_id, ok=True, payload=payload)
+
async def _locale_get_conf(ws, req_id, params, session_id):
"""返回当前 preferred_language 配置(zh / en)。"""
try:
@@ -1206,6 +1216,7 @@ def _register_web_handlers(
channel.register_method("chat.resume", _chat_resume)
channel.register_method("chat.interrupt", _chat_interrupt)
channel.register_method("chat.user_answer", _chat_user_answer)
+ channel.register_method("history.get", _history_get)
channel.register_method("locale.get_conf", _locale_get_conf)
channel.register_method("locale.set_conf", _locale_set_conf)
channel.register_method("heartbeat.get_conf", _heartbeat_get_conf)
@@ -1383,7 +1394,10 @@ async def _run() -> None:
method_val = getattr(getattr(msg, "req_method", None), "value", None) or ""
if method_val not in _FORWARD_REQ_METHODS:
return False
- is_stream = bool(msg.is_stream or method_val == ReqMethod.CHAT_SEND.value)
+ is_stream = bool(
+ msg.is_stream
+ or method_val in (ReqMethod.CHAT_SEND.value, ReqMethod.HISTORY_GET.value)
+ )
params = dict(msg.params or {})
if "query" not in params and "content" in params:
params["query"] = params["content"]
diff --git a/jiuwenclaw/channel/web_channel.py b/jiuwenclaw/channel/web_channel.py
index d0fd6ab24e..62b2dc9218 100644
--- a/jiuwenclaw/channel/web_channel.py
+++ b/jiuwenclaw/channel/web_channel.py
@@ -306,6 +306,7 @@ class WebChannel(BaseChannel):
if event_name in ("connection.ack", "todo.updated", "chat.tool_call", "chat.tool_result",
"chat.processing_status", "chat.interrupt_result", "chat.error", "heartbeat.relay",
"context.compressed", "chat.ask_user_question", "chat.subtask_update",
+ "history.message",
"chat.session_result"):
# 传递完整 payload,保留所有字段
payload = {**msg.payload}
diff --git a/jiuwenclaw/schema/message.py b/jiuwenclaw/schema/message.py
index 674006ac2f..b7fdd024b7 100644
--- a/jiuwenclaw/schema/message.py
+++ b/jiuwenclaw/schema/message.py
@@ -12,6 +12,7 @@ class ReqMethod(Enum):
CHAT_RESUME = "chat.resume"
CHAT_CANCEL = "chat.interrupt"
CHAT_ANSWER = "chat.user_answer"
+ HISTORY_GET = "history.get"
CONFIG_GET = "config.get"
CONFIG_SET = "config.set"
@@ -81,6 +82,7 @@ class EventType(Enum):
CHAT_ASK_USER_QUESTION = "chat.ask_user_question"
CHAT_SESSION_RESULT = "chat.session_result"
HEARTBEAT_RELAY = "heartbeat.relay"
+ HISTORY_GET = "history.message"
class Mode(Enum):