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:实现/resume list 返回所有 cli_channel 历史会话

douran09fa56e6458f
diff --git a/jiuwenclaw/agentserver/agent_ws_server.py b/jiuwenclaw/agentserver/agent_ws_server.py
index f4b4b327ff..f0b5c0a337 100644
--- a/jiuwenclaw/agentserver/agent_ws_server.py
+++ b/jiuwenclaw/agentserver/agent_ws_server.py
@@ -460,6 +460,8 @@ class AgentWebSocketServer:
async def _handle_session_list(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""处理 session.list 请求:扫描 sessions 目录,返回历史会话基础信息列表."""
+ from jiuwenclaw.agentserver.session_metadata import get_session_metadata
+
sessions_dir = get_agent_sessions_dir()
sessions = []
@@ -468,13 +470,16 @@ class AgentWebSocketServer:
for entry in sorted(sessions_dir.iterdir(), key=lambda e: e.stat().st_mtime, reverse=True):
if not entry.is_dir():
continue
- history_path = entry / "history.json"
- if not history_path.exists():
- continue
- sessions.append({
- "session_id": entry.name,
- "last_modified": history_path.stat().st_mtime,
- })
+ meta = get_session_metadata(entry.name)
+ if not meta:
+ meta = {
+ "session_id": entry.name,
+ "channel_id": "",
+ "title": "",
+ "message_count": 0,
+ "last_message_at": entry.stat().st_mtime,
+ }
+ sessions.append(meta)
except Exception as exc:
logger.warning("[AgentWebSocketServer] 扫描 sessions 目录失败: %s", exc)
diff --git a/jiuwenclaw/channel/cli_channel.py b/jiuwenclaw/channel/cli_channel.py
index 54299bdcc4..5c7a25ac41 100644
--- a/jiuwenclaw/channel/cli_channel.py
+++ b/jiuwenclaw/channel/cli_channel.py
@@ -332,7 +332,9 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
)
async def _session_list(ws, req_id, params, session_id):
- from jiuwenclaw.utils import get_agent_sessions_dir
+ import time
+ from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields
+ from jiuwenclaw.schema.message import ReqMethod
limit = 20
if isinstance(params, dict):
@@ -343,15 +345,26 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
limit = int(raw_limit.strip())
limit = max(1, min(limit, 200))
- workspace_session_dir = get_agent_sessions_dir()
- if not workspace_session_dir.exists() or not workspace_session_dir.is_dir():
- sessions = []
- else:
- sessions = sorted(
- [d.name for d in workspace_session_dir.iterdir() if d.is_dir()],
- reverse=True,
- )[:limit]
- await channel.send_response(ws, req_id, ok=True, payload={"sessions": sessions})
+ real_client = agent_client.get("value") if isinstance(agent_client, dict) else agent_client
+ if real_client is None:
+ await channel.send_response(ws, req_id, ok=True, payload={"sessions": []})
+ return
+ env = e2a_from_agent_fields(
+ request_id=req_id,
+ channel_id="cli",
+ session_id=session_id,
+ req_method=ReqMethod.SESSION_LIST,
+ params=params or {},
+ is_stream=False,
+ timestamp=time.time(),
+ )
+ resp = await real_client.send_request(env)
+ if not resp.ok:
+ await channel.send_response(ws, req_id, ok=False, error="session.list failed")
+ return
+ all_sessions = resp.payload.get("sessions", []) if isinstance(resp.payload, dict) else []
+ cli_sessions = [s for s in all_sessions if s.get("channel_id", "") == "cli"][:limit]
+ await channel.send_response(ws, req_id, ok=True, payload={"sessions": cli_sessions})
async def _session_create(ws, req_id, params, session_id):
from jiuwenclaw.utils import get_agent_sessions_dir
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/resume.ts b/jiuwenclaw/cli/src/core/commands/builtins/resume.ts
index b1a951cb65..d2defdee4b 100644
--- a/jiuwenclaw/cli/src/core/commands/builtins/resume.ts
+++ b/jiuwenclaw/cli/src/core/commands/builtins/resume.ts
@@ -1,24 +1,80 @@
import { addError, addInfo } from "../helpers.js";
import { CommandKind, type SlashCommand } from "../types.js";
+interface SessionMeta {
+ session_id: string;
+ title?: string;
+ channel_id?: string;
+ created_at?: number;
+ last_message_at?: number;
+ message_count?: number;
+}
+
+interface SessionListPayload {
+ sessions?: SessionMeta[];
+ total?: number;
+ limit?: number;
+ offset?: number;
+}
+
+interface ResumeResumePayload {
+ session_id?: string;
+ query?: string;
+ resumed?: boolean;
+ preview?: string;
+}
+
+type ResumePayload = SessionListPayload | ResumeResumePayload;
+
+function isListPayload(payload: ResumePayload): payload is SessionListPayload {
+ return Array.isArray((payload as SessionListPayload).sessions);
+}
+
export function createResumeCommand(): SlashCommand {
return {
name: "resume",
altNames: ["continue"],
- description: "Resume a previous conversation",
- usage: "/resume [conversation id or search term]",
- example: "/resume sess_1234",
+ description: "Resume a previous conversation, or list sessions with /resume list",
+ usage: "/resume [list | conversation id or search term]",
+ example: "/resume list",
kind: CommandKind.BUILT_IN,
takesArgs: true,
action: async (ctx, args) => {
const value = args.trim();
try {
- const payload = await ctx.request<{
- session_id?: string;
- query?: string;
- resumed?: boolean;
- preview?: string;
- }>("command.resume", value ? { query: value } : {});
+ if (value === "list") {
+ const payload = await ctx.request<SessionListPayload>("session.list", {});
+ const sessions = payload.sessions ?? [];
+ const total = payload.total ?? sessions.length;
+ if (sessions.length === 0) {
+ ctx.addItem(addInfo(ctx.sessionId, "No sessions found", "r"));
+ return;
+ }
+ const items = sessions.map((s, i) => {
+ const lastActive = s.last_message_at
+ ? new Date(s.last_message_at * 1000).toLocaleString()
+ : "-";
+ const title = s.title || "-";
+ return {
+ label: String(i + 1),
+ value: `${s.session_id} | ${title} | msgs: ${s.message_count ?? 0} | ${lastActive}`,
+ };
+ });
+ ctx.addItem(
+ addInfo(ctx.sessionId, `Sessions (${total} total)`, "r", {
+ view: "list",
+ title: "Resume Sessions",
+ items,
+ }),
+ );
+ return;
+ }
+
+ const payload = await ctx.request<ResumeResumePayload>(
+ "command.resume",
+ value ? { query: value } : {},
+ );
+
const nextSessionId = payload.session_id?.trim();
if (payload.resumed && nextSessionId) {
ctx.updateSession(nextSessionId);