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: /context command supported

ldstyle8be515b476137
diff --git a/docs/en/SlashCommands.md b/docs/en/SlashCommands.md
index 369344d6b5..9b677411ff 100644
--- a/docs/en/SlashCommands.md
+++ b/docs/en/SlashCommands.md
@@ -20,6 +20,7 @@ Executed locally in the terminal UI, not through Gateway control pipeline.
| `/help` | Show available commands |
| `/theme` | Switch theme |
| `/config` | Modify configuration (currently local, planned to unify with Gateway) |
+| `/context` | Show context window usage and token breakdown (see below) |
| `/workspace` | Manage trusted directories (see below) |
| `/teamskills` | TeamSkills Hub publish/delete (`publish`/`delete`) |
| `/export` | Export current conversation to file or clipboard (see below) |
@@ -143,6 +144,19 @@ Manages directories AI can access for file read, edit, and execute operations.
- `compressed`: Success, shows before/after token counts and savings ratio;
- `noop`: No compression needed, context already optimal.
+### `/context` (Context Window Usage)
+
+- Usage: `/context` (no parameters, no subcommands).
+- Function: View the current session's context window occupancy and token usage details.
+- Data source: TUI requests Agent context statistics service via `command.context`, carrying the current `mode`.
+- Display contents:
+ - **Overview panel**: Context window occupancy percentage + progress bar; `context_window` (used / limit tokens), `occupancy` (rate), `messages` (count);
+ - **Token breakdown panel**: Shows token usage by `system_prompt`, `messages`, `tools`, and `total`;
+ - **DeepAgent occupancy details** (if available): Key-value list of `context_occupancy` fields;
+ - **DeepAgent usage details** (if available): Key-value list of `deepagent_usage` fields.
+- Threshold warning: When occupancy >= 90%, the overview title shows `Context window 90% full — consider /compact`.
+- Error handling: On request failure, displays `context failed: <error message>`.
+
### `/init` (Project Initialization)
- Usage: `/init` (no parameters).
@@ -437,7 +451,6 @@ If StatusView is unavailable, the command falls back to inline key-value display
| Command | Description |
|---|---|
| `/btw` | Ask question |
-| `/context` | Context status view |
| `/memory` | Memory management |
| `/export` | Export related files |
| `/permissions` | Permission management |
\ No newline at end of file
diff --git "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md" "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"
index 81a5e391d1..c4419df3ac 100644
--- "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"
+++ "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"
@@ -20,6 +20,7 @@
| `/help` | 查看可用命令 |
| `/theme` | 切换主题 |
| `/config` | 修改配置(当前为本地实现,后续计划统一到 Gateway) |
+| `/context` | 查看上下文窗口占用与 Token 用量明细(见下文) |
| `/workspace` | 管理可信目录(见下文) |
| `/teamskills` | TeamSkills 管理(`init/validate/pack/info/search/list/install/uninstall/config/publish/delete`) |
| `/export` | 导出当前会话到文件或剪贴板(见下文) |
@@ -143,6 +144,19 @@
- `compressed`:压缩成功,显示压缩前后 token 数及节省比例;
- `noop`:无需压缩,上下文已处于最优状态。
+### `/context`(上下文窗口用量)
+
+- 用法:`/context`(无参数、无子命令)。
+- 功能:查看当前会话的上下文窗口占用情况与 Token 用量明细。
+- 数据来源:TUI 通过 `command.context` 请求 Agent 侧上下文统计服务,携带当前 `mode`。
+- 展示内容:
+ - **概览面板**:上下文窗口占用百分比 + 进度条;`context_window`(已用/上限 tokens)、`occupancy`(占用率)、`messages`(消息数);
+ - **Token 拆分面板**:按 `system_prompt`、`messages`、`tools`、`total` 展示 Token 用量;
+ - **DeepAgent 占用明细**(如有数据):以键值列表展示 `context_occupancy` 各字段;
+ - **DeepAgent 用量明细**(如有数据):以键值列表展示 `deepagent_usage` 各字段。
+- 阈值提示:当占用率 >= 90% 时,概览标题显示 `Context window 90% full — consider /compact` 提示。
+- 错误处理:请求失败时显示 `context failed: <错误信息>`。
+
### `/init`(项目初始化)
- 用法:`/init`(无参数)。
@@ -448,7 +462,6 @@
| 命令 | 说明 |
|----------------|---------|
| `/btw` | 提问 |
-| `/context` | 上下文状态查看 |
| `/export` | 导出相关文件 |
| `/permissions` | 权限管理 |
diff --git "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md" "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"
index c549580061..ff0f9ac86d 100644
--- "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"
+++ "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"
@@ -64,6 +64,7 @@
| `/color` | - | 设置提示条强调色 | `/color blue` | 全部 |
| `/compact` | - | 压缩上下文,保留摘要 | `/compact` | 全部 |
| `/config` | `/settings`, `/setting` | 查看/设置后端配置 | `/config`、`/config get`、`/config set key value` | 全部 |
+| `/context` | - | 查看上下文窗口占用与 Token 用量明细 | `/context` | 全部 |
| `/diff` | - | 查看本会话按轮次的文件改动 | `/diff` | 全部 |
| `/evolve` | - | 触发技能演进或列出待处理(转发为聊天内容) | `/evolve`、`/evolve list` | 全部 |
| `/evolve_list` | - | 列出某技能的演进条目 | `/evolve_list myskill --sort score` | 全部 |
@@ -124,6 +125,20 @@
- **`/diff`**:调用 `command.diff`,展示本会话内有文件变更的轮次(非完整 `git diff` 替代)。
- **`/compact`**:调用 `command.compact`,返回 `busy` | `compressed` | `noop`;成功时展示 token 节省比例(`compact.ts`)。
+#### `/context`(上下文窗口用量)
+
+- **`/context`**(`context.ts`)
+ - 无参数,无子命令。
+ - 调用 `command.context` RPC,携带当前 `mode`,获取上下文窗口占用与 Token 用量明细。
+ - 展示分为多个面板:
+ - **概览面板**:进度条 + 占用百分比;`context_window`(已用/上限 tokens)、`occupancy`(占用率)、`messages`(消息数)。
+ - **Token 拆分面板**:按 `system_prompt`、`messages`、`tools`、`total` 展示。
+ - **DeepAgent 占用明细**(如有数据):`context_occupancy` 键值列表。
+ - **DeepAgent 用量明细**(如有数据):`deepagent_usage` 键值列表。
+ - 阈值提示:占用率 >= 90% 时,提示 `Context window 90% full — consider /compact`。
+ - 错误处理:请求失败时显示 `context failed: <错误信息>`。
+ - 与 `/status usage` 的区别:`/context` 侧重**实时上下文窗口占用**,含进度条和阈值告警;`/status usage` 侧重**会话累计用量统计**与**按模型拆分**。
+
#### `/config`
- 子命令:`get`、`set`、`list`、`edit`、`reset`;无参数时展示分组概览。
diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/context.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/context.ts
new file mode 100644
index 0000000000..bdf1ab4864
--- /dev/null
+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/context.ts
@@ -0,0 +1,98 @@
+import { addError, addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export interface ContextUsagePayload {
+ context_window_limit: number;
+ total_tokens: number;
+ system_prompt_tokens: number;
+ messages_tokens: number;
+ tools_tokens: number;
+ occupancy_rate: number;
+ message_count: number;
+ context_occupancy: unknown;
+}
+
+function toLocale(n: number | undefined): string {
+ return (n ?? 0).toLocaleString("en-US");
+}
+
+function renderBar(percent: number, width: number): string {
+ const filled = Math.round((percent / 100) * width);
+ const clamped = Math.min(filled, width);
+ const empty = width - clamped;
+ return "[" + "=".repeat(clamped) + (empty > 0 ? ">" : "") + " ".repeat(Math.max(0, empty - 1)) + "]";
+}
+
+function showContextUsage(
+ ctx: import("../types.js").CommandContext,
+ payload: ContextUsagePayload,
+): void {
+ const pct = payload.occupancy_rate;
+ const bar = renderBar(pct, 30);
+ const heading = pct >= 90 ? `Context window ${pct}% full — consider /compact` : `Context window ${pct}% full`;
+
+ ctx.addItem(
+ addInfo(ctx.sessionId, heading, "c", {
+ view: "kv",
+ title: `Context — Overview ${bar} ${pct}%`,
+ items: [
+ {
+ label: "context_window",
+ value: `${toLocale(payload.total_tokens)} / ${toLocale(payload.context_window_limit)} tokens`,
+ },
+ { label: "occupancy", value: `${pct}%` },
+ { label: "messages", value: toLocale(payload.message_count) },
+ ],
+ }),
+ );
+
+ ctx.addItem(
+ addInfo(ctx.sessionId, "Token breakdown by component", "t", {
+ view: "kv",
+ title: "Context — Token Breakdown",
+ items: [
+ { label: "system_prompt", value: toLocale(payload.system_prompt_tokens) },
+ { label: "messages", value: toLocale(payload.messages_tokens) },
+ { label: "tools", value: toLocale(payload.tools_tokens) },
+ { label: "total", value: toLocale(payload.total_tokens) },
+ ],
+ }),
+ );
+
+ if (payload.context_occupancy) {
+ const occ = payload.context_occupancy as Record<string, unknown>;
+ const occItems = Object.entries(occ).map(([k, v]) => ({
+ label: k,
+ value: typeof v === "number" ? toLocale(v) : String(v),
+ }));
+ ctx.addItem(
+ addInfo(ctx.sessionId, "DeepAgent context occupancy details", "d", {
+ view: "kv",
+ title: "Context — Occupancy",
+ items: occItems.length > 0 ? occItems : [{ label: "—", value: "No data" }],
+ }),
+ );
+ }
+}
+
+export function createContextCommand(): SlashCommand {
+ return {
+ name: "context",
+ description: "Show context window usage and token breakdown",
+ usage: "/context",
+ example: "/context",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: false,
+ action: async (ctx) => {
+ try {
+ const payload = await ctx.request<ContextUsagePayload>("command.context", {
+ mode: ctx.mode,
+ });
+ showContextUsage(ctx, payload);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `context failed: ${message}`));
+ }
+ },
+ };
+}
\ No newline at end of file
diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/recap.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/recap.ts
new file mode 100644
index 0000000000..a470667c20
--- /dev/null
+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/recap.ts
@@ -0,0 +1,48 @@
+import { addError, addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+interface RecapResponse {
+ status: "ok" | "no_turn" | "failed";
+ summary?: string;
+ error?: string;
+}
+
+const NO_TURN_MSG = "Nothing to recap yet — send a message first.";
+const FAILED_MSG = "Couldn't generate a recap. Please try again later.";
+
+export function createRecapCommand(): SlashCommand {
+ return {
+ name: "recap",
+ description: "Generate a one-line session recap now",
+ usage: "/recap",
+ example: "/recap",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: false,
+ action: async (ctx) => {
+ ctx.addItem(addInfo(ctx.sessionId, "Recaping...", "⏳"));
+
+ try {
+ const payload = await ctx.request<RecapResponse>(
+ "command.recap",
+ { mode: ctx.mode },
+ 60000,
+ );
+
+ switch (payload.status) {
+ case "ok":
+ ctx.addItem(addInfo(ctx.sessionId, `※ ${payload.summary}`, "※"));
+ break;
+ case "no_turn":
+ ctx.addItem(addInfo(ctx.sessionId, NO_TURN_MSG, "i"));
+ break;
+ case "failed":
+ ctx.addItem(addError(ctx.sessionId, FAILED_MSG));
+ break;
+ }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `recap failed: ${message}`));
+ }
+ },
+ };
+}
\ No newline at end of file
diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts
index 3e5a057b28..3745c53541 100644
--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts
+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts
@@ -5,7 +5,9 @@ import { createClearCommand } from "./builtins/clear.js";
import { createColorCommand } from "./builtins/color.js";
import { createCompactCommand } from "./builtins/compact.js";
import { createConfigCommand } from "./builtins/config.js";
+import { createContextCommand } from "./builtins/context.js";
import { createCopyCommand } from "./builtins/copy.js";
+import { createRecapCommand } from "./builtins/recap.js";
import { createDiffCommand } from "./builtins/diff.js";
import { createExportCommand } from "./builtins/export.js";
import {
@@ -43,6 +45,8 @@ export function createBuiltinCommands(): SlashCommand[] {
createColorCommand(),
createCompactCommand(),
createConfigCommand(),
+ createContextCommand(),
+ createRecapCommand(),
createCopyCommand(),
createDiffCommand(),
createExportCommand(),
diff --git a/jiuwenclaw/common/schema/message.py b/jiuwenclaw/common/schema/message.py
index d9a3b3b23c..4fe013524b 100644
--- a/jiuwenclaw/common/schema/message.py
+++ b/jiuwenclaw/common/schema/message.py
@@ -19,6 +19,8 @@ class ReqMethod(Enum):
COMMAND_ADD_DIR = "command.add_dir"
COMMAND_CHROME = "command.chrome"
COMMAND_COMPACT = "command.compact"
+ COMMAND_CONTEXT = "command.context"
+ COMMAND_RECAP = "command.recap"
COMMAND_DIFF = "command.diff"
COMMAND_MCP = "command.mcp"
COMMAND_MODEL = "command.model"
diff --git a/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py b/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py
index b3432a8f7a..ef76ff114b 100644
--- a/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py
+++ b/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py
@@ -42,6 +42,8 @@ CLI_FORWARD_REQ_METHODS = frozenset(
"command.add_dir",
"command.chrome",
"command.compact",
+ "command.context",
+ "command.recap",
"command.diff",
"command.mcp",
"command.resume",
@@ -100,6 +102,8 @@ CLI_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset(
"command.add_dir",
"command.chrome",
"command.compact",
+ "command.context",
+ "command.recap",
"command.diff",
"command.mcp",
"command.resume",
diff --git a/jiuwenclaw/gateway/message_handler/command_parser/slash_command.py b/jiuwenclaw/gateway/message_handler/command_parser/slash_command.py
index db9bdc33d2..adc65f4b8a 100644
--- a/jiuwenclaw/gateway/message_handler/command_parser/slash_command.py
+++ b/jiuwenclaw/gateway/message_handler/command_parser/slash_command.py
@@ -284,6 +284,13 @@ FIRST_BATCH_REGISTRY: tuple[SlashCommandEntry, ...] = (
req_method="session.rewind",
notes="受控通道回退对话到指定轮次;IM 须带正整数轮次编号;CLI 同路径见 builtins/rewind.ts。",
),
+ SlashCommandEntry(
+ id="recap",
+ canonical_text="/recap",
+ scope="client",
+ req_method="command.recap",
+ notes="客户端命令,生成会话快速回顾(read-only);TUI → Gateway → AgentServer。",
+ ),
)
diff --git a/jiuwenclaw/server/agent_ws_server.py b/jiuwenclaw/server/agent_ws_server.py
index 02ef02fbe0..83c4f6aeb5 100644
--- a/jiuwenclaw/server/agent_ws_server.py
+++ b/jiuwenclaw/server/agent_ws_server.py
@@ -470,6 +470,12 @@ class AgentWebSocketServer:
if request.req_method == ReqMethod.COMMAND_COMPACT:
await self._handle_command_compact(ws, request, send_lock)
return
+ if request.req_method == ReqMethod.COMMAND_CONTEXT:
+ await self._handle_command_context(ws, request, send_lock)
+ return
+ if request.req_method == ReqMethod.COMMAND_RECAP:
+ await self._handle_command_recap(ws, request, send_lock)
+ return
if request.req_method == ReqMethod.COMMAND_DIFF:
await self._handle_command_diff(ws, request, send_lock)
return
@@ -1281,6 +1287,82 @@ class AgentWebSocketServer:
async with send_lock:
await ws.send(json.dumps(wire, ensure_ascii=False))
+ async def _handle_command_context(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
+ try:
+ session_id = request.session_id or "default"
+ params = request.params or {}
+
+ channel_id = request.channel_id or "default"
+ mode, _, _ = resolve_agent_request_mode(params.get("mode", "agent.plan"))
+ agent = await self._agent_manager.get_agent(
+ channel_id=channel_id,
+ mode=mode,
+ project_dir=params.get("project_dir", None)
+ )
+
+ if agent is None:
+ raise ValueError("Failed to get agent")
+
+ result_data = await agent.get_context_usage(session_id=session_id)
+
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=True,
+ payload=result_data,
+ )
+ except Exception as e: # noqa: BLE001
+ logger.exception("[AgentWebSocketServer] command.context failed: %s", e)
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={"error": str(e)},
+ )
+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
+ async with send_lock:
+ await ws.send(json.dumps(wire, ensure_ascii=False))
+
+ async def _handle_command_recap(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
+ """处理 /recap 命令:生成会话快速回顾(read-only,不修改历史)"""
+ try:
+ session_id = request.session_id or "default"
+ params = request.params or {}
+ channel_id = request.channel_id or "default"
+ mode, _, _ = resolve_agent_request_mode(params.get("mode", "agent.plan"))
+
+ agent = await self._agent_manager.get_agent(
+ channel_id=channel_id,
+ mode=mode,
+ project_dir=params.get("project_dir", None),
+ )
+
+ if agent is None:
+ raise ValueError("Failed to get agent")
+
+ result_data = await agent.generate_recap(session_id=session_id)
+
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=True,
+ payload=result_data,
+ )
+ except Exception as e: # noqa: BLE001
+ logger.exception("[AgentWebSocketServer] command.recap failed: %s", e)
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={
+ "status": "failed",
+ "error": str(e),
+ },
+ )
+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
+ async with send_lock:
+ await ws.send(json.dumps(wire, ensure_ascii=False))
+
async def _handle_command_diff(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
from jiuwenclaw.server.utils.diff_service import get_diff_service
diff --git a/jiuwenclaw/server/runtime/agent_adapter/interface.py b/jiuwenclaw/server/runtime/agent_adapter/interface.py
index faac5a339f..aea8b515bf 100644
--- a/jiuwenclaw/server/runtime/agent_adapter/interface.py
+++ b/jiuwenclaw/server/runtime/agent_adapter/interface.py
@@ -985,6 +985,44 @@ class JiuWenClaw:
session=session,
)
+ async def get_context_usage(self, session_id: str) -> dict[str, Any]:
+ """获取当前上下文窗口占用统计。
+
+ 参考 Claude Code 的 /context 命令,展示:
+ - 上下文窗口总量与当前占用量
+ - 系统提示词、对话消息、工具定义各自的 token 消耗
+ - 上下文窗口占用百分比
+
+ Args:
+ session_id: 会话ID
+
+ Returns:
+ 包含上下文使用情况统计的字典
+ """
+ adapter = self._adapter
+ if adapter is None:
+ raise ValueError("Agent adapter not available")
+ return await adapter.get_context_usage(session_id=session_id)
+
+ async def generate_recap(self, session_id: str) -> dict[str, Any]:
+ """生成会话快速回顾(read-only,不修改对话历史)。
+
+ 取最近30条消息 → fast model → 1-2句摘要。
+
+ Args:
+ session_id: 会话ID
+
+ Returns:
+ 包含 recap 结果的字典:
+ - status: "ok" | "no_turn" | "aborted" | "failed"
+ - summary: 摘要文本(仅当 status == "ok" 时)
+ - error: 错误信息(仅当 status == "failed" 时)
+ """
+ adapter = self._adapter
+ if adapter is None:
+ raise ValueError("Agent adapter not available")
+ return await adapter.generate_recap(session_id=session_id)
+
# ---------- 资源清理 ----------
async def cancel_inflight_work(self, log_prefix: str = "[gateway disconnect] ") -> None:
diff --git a/jiuwenclaw/server/runtime/agent_adapter/interface_deep.py b/jiuwenclaw/server/runtime/agent_adapter/interface_deep.py
index cc130e86b9..3712277b7f 100644
--- a/jiuwenclaw/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenclaw/server/runtime/agent_adapter/interface_deep.py
@@ -4558,6 +4558,212 @@ class JiuWenClawDeepAdapter:
return response
+ async def get_context_usage(self, session_id: str) -> dict[str, Any]:
+ """获取当前上下文窗口占用统计。
+
+ Args:
+ session_id: 会话ID
+
+ Returns:
+ 包含上下文使用情况统计的字典:
+ - context_window_limit: 模型上下文窗口总 token 数
+ - total_tokens: 当前上下文已用 token 数
+ - system_prompt_tokens: 系统提示词 token 数
+ - messages_tokens: 对话消息 token 数
+ - tools_tokens: 工具定义 token 数
+ - occupancy_rate: 占用率 (0-100)
+ - message_count: 对话消息数量
+ - context_occupancy: 上下文占用详情(来自 deepagent)
+ """
+ if self._instance is None:
+ raise ValueError("Agent instance not available")
+
+ context_engine = self._instance.react_agent.context_engine
+ react_agent = self._instance.react_agent
+ context = context_engine.get_context(session_id=session_id)
+ if context is None:
+ return {
+ "context_window_limit": 0, "total_tokens": 0,
+ "system_prompt_tokens": 0, "messages_tokens": 0,
+ "tools_tokens": 0, "occupancy_rate": 0,
+ "message_count": 0, "context_occupancy": None,
+ }
+
+ # 分项估算:直接用 context engine 的 token counter
+ token_counter = context.token_counter()
+ from openjiuwen.core.foundation.tool import ToolInfo
+
+ # 系统提示词
+ system_prompt = ""
+ if hasattr(react_agent, "prompt_builder") and react_agent.prompt_builder is not None:
+ system_prompt = react_agent.prompt_builder.build()
+ elif hasattr(react_agent, "system_prompt_builder") and react_agent.system_prompt_builder is not None:
+ system_prompt = react_agent.system_prompt_builder.build()
+ if system_prompt and token_counter:
+ system_prompt_tokens = token_counter.count(system_prompt) or 0
+ elif system_prompt:
+ system_prompt_tokens = len(system_prompt) // 4
+ else:
+ system_prompt_tokens = 0
+
+ # 对话消息
+ context_messages = context.get_messages() or []
+ if context_messages and token_counter:
+ messages_tokens = token_counter.count_messages(context_messages) or 0
+ elif context_messages:
+ messages_tokens = sum(len(str(msg.content)) // 4 for msg in context_messages)
+ else:
+ messages_tokens = 0
+
+ # 工具定义
+ tools: list[ToolInfo] = []
+ if hasattr(react_agent, "ability_manager") and react_agent.ability_manager is not None:
+ for card in react_agent.ability_manager.list() or []:
+ if hasattr(card, "to_tool_info"):
+ tools.append(card.to_tool_info())
+ elif hasattr(card, "name") and hasattr(card, "description"):
+ tools.append(ToolInfo(
+ name=card.name,
+ description=card.description or "",
+ parameters=getattr(card, "input_params", {}),
+ ))
+ if tools and token_counter:
+ tools_tokens = token_counter.count_tools(tools) or 0
+ else:
+ tools_tokens = 0
+
+ # 总量 & 窗口限制:优先用 DeepAgent 的准确值,回退到估算
+ total_tokens = system_prompt_tokens + messages_tokens + tools_tokens
+ context_window_limit = 0
+ occupancy_rate = 0.0
+ context_occupancy = None
+
+ try:
+ usage = self._instance.get_context_usage(session_id=session_id)
+ context_occupancy = usage
+ # DeepAgent 的 total_tokens 来自 usage_metadata,比估算更准确
+ da_total = usage.get("total_tokens", 0)
+ if da_total > 0:
+ total_tokens = da_total
+ context_window_limit = usage.get("context_window_tokens", 0)
+ occupancy_rate = usage.get("usage_percent", 0)
+ except Exception as exc:
+ logger.debug("[JiuWenClaw] DeepAgent.get_context_usage failed: %s", exc)
+ from openjiuwen.core.context_engine.context.context_utils import ContextUtils
+ model_name = (
+ getattr(self._model_request_config, "model_name", "") or ""
+ if self._model_request_config else ""
+ )
+ context_window_limit = ContextUtils.resolve_context_max(model_name=model_name)
+ if context_window_limit > 0:
+ occupancy_rate = round(total_tokens / context_window_limit * 100, 1)
+
+ message_count = len(context_messages)
+
+ return {
+ "context_window_limit": context_window_limit,
+ "total_tokens": total_tokens,
+ "system_prompt_tokens": system_prompt_tokens,
+ "messages_tokens": messages_tokens,
+ "tools_tokens": tools_tokens,
+ "occupancy_rate": occupancy_rate,
+ "message_count": message_count,
+ "context_occupancy": context_occupancy,
+ }
+
+ async def generate_recap(self, session_id: str) -> dict[str, Any]:
+ """生成会话快速回顾(read-only,不修改对话历史)。
+
+ 取最近30条消息 → fast model → 1-3句摘要。
+ """
+ from jiuwenclaw.server.runtime.agent_adapter.recap_prompts import (
+ RECENT_MESSAGE_WINDOW,
+ build_recap_prompt,
+ )
+
+ messages = self._get_recent_messages(session_id, window=RECENT_MESSAGE_WINDOW)
+ if not messages:
+ return {"status": "no_turn"}
+
+ prompt = build_recap_prompt(memory=None)
+ summary_text = await self._call_model_for_recap(messages, prompt)
+ if not summary_text:
+ return {"status": "failed", "error": "Model returned empty response"}
+
+ return {"status": "ok", "summary": summary_text.strip()}
+
+ def _get_recent_messages(self, session_id: str, window: int = 30) -> list[Any]:
+ """从当前 agent 对话上下文中提取最近N条消息。"""
+ if self._instance is None or self._instance.react_agent is None:
+ return []
+
+ context_engine = self._instance.react_agent.context_engine
+ context = context_engine.get_context(session_id=session_id)
+ if context is None:
+ return []
+
+ try:
+ all_messages = list(context.get_messages() or [])
+ except Exception as exc:
+ logger.debug("[JiuWenClaw] _get_recent_messages failed: %s", exc)
+ return []
+
+ return all_messages[-window:]
+
+ async def _call_model_for_recap(
+ self,
+ messages: list[Any],
+ prompt: str,
+ ) -> str | None:
+ """调用 fast model 生成 recap 摘要。
+
+ - 不传 system prompt(空)
+ - prompt 作为最后一条 user message 追加到对话末尾
+ - 不传 tools
+ - 不启用 thinking
+ """
+ from openjiuwen.core.foundation.llm.schema.message import UserMessage, AssistantMessage
+
+ if self._model is None:
+ logger.error("[generate_recap] no model instance available")
+ return None
+
+ recap_messages: list[Any] = []
+
+ for msg in messages:
+ role = getattr(msg, "role", None) or ""
+ content = getattr(msg, "content", None) or ""
+ if isinstance(content, list):
+ # Multimodal content — extract text parts only
+ content = " ".join(
+ str(p) for p in content
+ if isinstance(p, str) or (isinstance(p, dict) and p.get("type") == "text")
+ )
+ content = str(content)
+ if not content.strip():
+ continue
+
+ if role == "user":
+ recap_messages.append(UserMessage(content=content))
+ elif role == "assistant":
+ recap_messages.append(AssistantMessage(content=content))
+ else:
+ recap_messages.append(UserMessage(content=content))
+
+ # Prompt 作为最后一条 user message 追加(对齐 Claude Code)
+ recap_messages.append(UserMessage(content=prompt))
+
+ try:
+ result = await self._model.invoke(
+ recap_messages,
+ max_tokens=300,
+ temperature=0,
+ )
+ return getattr(result, "content", None) or str(result)
+ except Exception:
+ logger.exception("[generate_recap] model call failed")
+ return None
+
async def _count_full_context_tokens(
self,
context: Any,
diff --git a/jiuwenclaw/server/runtime/agent_adapter/recap_prompts.py b/jiuwenclaw/server/runtime/agent_adapter/recap_prompts.py
new file mode 100644
index 0000000000..98dafcff55
--- /dev/null
+++ b/jiuwenclaw/server/runtime/agent_adapter/recap_prompts.py
@@ -0,0 +1,22 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""/recap 命令的 prompt 模板与常量(对齐 Claude Code awaySummary.ts 源码)。"""
+
+RECENT_MESSAGE_WINDOW = 30
+
+
+def build_recap_prompt(memory: str | None) -> str:
+ """构建 /recap prompt,对齐 Claude Code 源码 buildAwaySummaryPrompt。
+
+ Args:
+ memory: Session memory 内容(broader context),可为 None。
+ """
+ memory_block = f"Session memory (broader context):\n{memory}\n\n" if memory else ""
+ return (
+ f"{memory_block}"
+ "The user is requesting a quick recap of the current session. "
+ "Write exactly 1-3 short sentences. "
+ "Start by stating the high-level task — what they are building or debugging, not implementation details. "
+ "Next: the concrete next step. "
+ "Skip status reports and commit recaps."
+ )
\ No newline at end of file
diff --git a/tests/unit_tests/gateway/test_slash_command.py b/tests/unit_tests/gateway/test_slash_command.py
index 71e6773977..948f7e48b5 100644
--- a/tests/unit_tests/gateway/test_slash_command.py
+++ b/tests/unit_tests/gateway/test_slash_command.py
@@ -144,4 +144,4 @@ def test_format_skills_list_for_notice() -> None:
def test_first_batch_registry_ids() -> None:
ids = {e.id for e in FIRST_BATCH_REGISTRY}
- assert ids == {"new_session", "mode", "switch", "skills", "resume", "workspace_dir", "branch", "rewind"}
+ assert ids == {"new_session", "mode", "switch", "skills", "resume", "workspace_dir", "branch", "rewind", "recap"}