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): record compact boundaries and summaries
l_x_d107f68b1c88f
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/compact.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/compact.tsindex 1afef7db14..4249b74f42 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/compact.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/compact.ts@@ -8,6 +8,8 @@ interface CompactResponse {total_tokens: number;raw_total_tokens: number;};+ summary?: string;+ compact_summary?: string;}export function createCompactCommand(): SlashCommand {@@ -27,6 +29,11 @@ export function createCompactCommand(): SlashCommand {const result = payload?.result;const stats = payload?.stats;+ const compactSummary = typeof payload?.compact_summary === "string" && payload.compact_summary.trim()+ ? payload.compact_summary.trim()+ : typeof payload?.summary === "string" && payload.summary.trim()+ ? payload.summary.trim()+ : "";if (result === "busy") {ctx.addItem(@@ -42,13 +49,11 @@ export function createCompactCommand(): SlashCommand {const rate = stats.raw_total_tokens > 0? ((stats.raw_total_tokens - stats.total_tokens) / stats.raw_total_tokens * 100).toFixed(1): "0";- ctx.addItem(- addInfo(- ctx.sessionId,- `✓ Context compacted: ${afterK}K/${beforeK}K tokens (${rate}% saved)`,- "i",- ),- );+ const statsSummary = `✓ Context compacted: ${afterK}K/${beforeK}K tokens (${rate}% saved)`;+ // A compact summary is rendered by the follow-up context_compression_state push.+ if (!compactSummary) {+ ctx.addItem(addInfo(ctx.sessionId, statsSummary, "i"));+ }} else if (result === "noop") {ctx.addItem(addInfo(diff --git a/jiuwenswarm/channels/tui/frontend/src/core/compression-formatters.ts b/jiuwenswarm/channels/tui/frontend/src/core/compression-formatters.tsnew file mode 100644index 0000000000..7473f8d123--- /dev/null+++ b/jiuwenswarm/channels/tui/frontend/src/core/compression-formatters.ts@@ -0,0 +1,41 @@+function readNumber(value: unknown): number | null {+ return typeof value === "number" && Number.isFinite(value) ? value : null;+}++function formatNumber(value: unknown): string {+ const n = readNumber(value);+ return n == null ? "-" : Math.round(n).toLocaleString("en-US");+}++function formatPercent(value: unknown): string {+ const n = readNumber(value);+ return n == null ? "-" : `${Math.round(n)}%`;+}++export function formatCompressionUsage(usage: Record<string, unknown>): string {+ const parts = [+ `input ${formatNumber(usage.input_tokens)}`,+ `output ${formatNumber(usage.output_tokens)}`,+ `total ${formatNumber(usage.total_tokens)}`,+ `calls ${formatNumber(usage.calls)}`,+ ].filter((part) => !part.endsWith("-"));+ return parts.length ? parts.join(" | ") : "-";+}++export function formatCompressionStartedLine(+ processor: string,+ phase: string,+ before: Record<string, unknown>,+): string {+ const tokens = formatNumber(before.tokens);+ const messages = formatNumber(before.messages);+ const context = formatPercent(before.context_percent);+ const details = [+ processor || "unknown",+ phase || "unknown",+ tokens !== "-" ? `${tokens} tokens` : "",+ messages !== "-" ? `${messages} messages` : "",+ context !== "-" ? context : "",+ ].filter(Boolean);+ return `Context compression started${details.length ? ` (${details.join(" | ")})` : ""}`;+}diff --git a/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts b/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.tsindex 2153e0f701..9d63c9974a 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts@@ -6,6 +6,10 @@ import {isHistoryDonePayload,} from "./history-parser.js";import { normalizeFinalContent } from "./final-content.js";+import {+ formatCompressionStartedLine,+ formatCompressionUsage,+} from "./compression-formatters.js";import type { EventFrame } from "./protocol.js";import {StreamingState,@@ -690,11 +694,13 @@ function handleContextCompressionState(const before = asRecord(payload.before);const after = asRecord(payload.after);const saved = asRecord(payload.saved);+ const compressionUsage = asRecord(payload.compression_usage);const status = readString(payload.status, "unknown");const phase = readString(payload.phase, "unknown");const processor = readString(payload.processor, "unknown") || "unknown";const model = readString(payload.model);- const summary = readString(payload.summary);+ const summary = readString(payload.compact_summary);+ const statsSummary = readString(payload.summary);const error = readString(payload.error);const savedParts = [@@ -703,32 +709,107 @@ function handleContextCompressionState(formatPercent(saved.percent),].filter((part) => !part.startsWith("-"));+ const normalizedStatus = status.trim().toLowerCase();+ const hasAfterStats = readNumber(after.tokens) !== null;+ const savedTokens = readNumber(saved.tokens) ?? 0;+ const savedMessages = readNumber(saved.messages) ?? 0;+ const shouldUpdateCompressionStats =+ hasAfterStats && (normalizedStatus === "completed" || normalizedStatus === "compressed");+ if (shouldUpdateCompressionStats) {+ delegate.setContextCompression({+ rate: readNumber(after.context_percent) ?? 0,+ beforeCompressed: readNumber(before.tokens),+ afterCompressed: readNumber(after.tokens),+ ...(summary ? { summary } : {}),+ trigger: "auto",+ });+ }++ const isCompacted =+ (Boolean(summary) || savedTokens > 0 || savedMessages > 0) &&+ !error &&+ normalizedStatus !== "error" &&+ normalizedStatus !== "failed" &&+ normalizedStatus !== "skipped";+ const isError = Boolean(error) || normalizedStatus === "error" || normalizedStatus === "failed";+ const detailItems = [+ { label: "Processor", value: processor },+ { label: "Phase", value: phase },+ ...(model ? [{ label: "Model", value: model }] : []),+ { label: "Messages", value: formatChange(before.messages, after.messages) },+ { label: "Tokens", value: formatChange(before.tokens, after.tokens) },+ {+ label: "Context",+ value: formatChange(before.context_percent, after.context_percent, formatPercent),+ },+ ...(savedParts.length ? [{ label: "Saved", value: savedParts.join(" | ") }] : []),+ ...(Object.keys(compressionUsage).length+ ? [{ label: "Compression usage", value: formatCompressionUsage(compressionUsage) }]+ : []),+ { label: "Duration", value: formatDuration(payload.duration_ms) },+ ...(statsSummary ? [{ label: "Summary", description: statsSummary }] : []),+ ...(error ? [{ label: "Error", description: error }] : []),+ ];++ if (!isCompacted && !isError) {+ if (normalizedStatus === "started" || normalizedStatus === "noop") {+ const detailEntry: HistoryItem = {+ kind: "info",+ id: createId("context-compression-detail"),+ sessionId: activeSessionId,+ content: `Context compression ${status}`,+ icon: "i",+ transcriptOnly: true,+ meta: {+ title: `Context compression ${status}`,+ items: detailItems,+ },+ at: new Date().toISOString(),+ };+ if (normalizedStatus === "started") {+ appendEntry(delegate, {+ kind: "info",+ id: createId("context-compression-started"),+ sessionId: activeSessionId,+ content: formatCompressionStartedLine(processor, phase, before),+ icon: "i",+ meta: { view: "dim" },+ at: new Date().toISOString(),+ });+ }+ appendEntry(delegate, detailEntry);+ }+ return true;+ }+appendEntry(delegate, {kind: "info",id: createId("context-compression"),sessionId: activeSessionId,- content: `Context compression ${status}`,+ content: isCompacted ? "Conversation compacted" : `Context compression ${status}`,icon: "i",meta: {- title: `Context compression ${status}`,- items: [- { label: "Processor", value: processor },- { label: "Phase", value: phase },- ...(model ? [{ label: "Model", value: model }] : []),- { label: "Messages", value: formatChange(before.messages, after.messages) },- { label: "Tokens", value: formatChange(before.tokens, after.tokens) },- {- label: "Context",- value: formatChange(before.context_percent, after.context_percent, formatPercent),- },- ...(savedParts.length ? [{ label: "Saved", value: savedParts.join(" | ") }] : []),- { label: "Duration", value: formatDuration(payload.duration_ms) },- ...(summary ? [{ label: "Summary", description: summary }] : []),- ...(error ? [{ label: "Error", description: error }] : []),- ],+ ...(isCompacted ? { view: "compact_boundary" as const } : {}),+ title: isCompacted ? "Conversation compacted" : `Context compression ${status}`,+ items: detailItems,},at: new Date().toISOString(),});+ if (isCompacted) {+ appendEntry(delegate, {+ kind: "info",+ id: createId("context-compact-summary"),+ sessionId: activeSessionId,+ content: summary,+ icon: "i",+ transcriptOnly: true,+ meta: {+ view: "compact_summary",+ title: "Compaction summary",+ },+ at: new Date().toISOString(),+ });+ }return true;}diff --git a/jiuwenswarm/channels/tui/frontend/src/core/history-parser.ts b/jiuwenswarm/channels/tui/frontend/src/core/history-parser.tsindex 9067325e50..d9992a74ea 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/history-parser.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/history-parser.ts@@ -739,6 +739,39 @@ export function parseHistoryFrame(frame: EventFrame): HistoryItem | null {};}+ if (eventType === "context.compact_boundary") {+ return {+ kind: "info",+ id,+ sessionId,+ content: pickFirstString(record, ["content", "text", "body"]) ?? "Conversation compacted",+ icon: "i",+ meta: {+ view: "compact_boundary",+ title: "Conversation compacted",+ },+ at,+ };+ }++ if (eventType === "context.compact_summary") {+ const content = pickFirstString(record, ["content", "text", "body"]) ?? "";+ if (!content) return null;+ return {+ kind: "info",+ id,+ sessionId,+ content,+ icon: "i",+ transcriptOnly: true,+ meta: {+ view: "compact_summary",+ title: "Compaction summary",+ },+ at,+ };+ }+if (eventType === "context.usage" ||eventType === "chat.subtask_update" ||diff --git a/jiuwenswarm/channels/tui/frontend/src/core/types.ts b/jiuwenswarm/channels/tui/frontend/src/core/types.tsindex 57da3b8ff9..2b15f7b32a 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/types.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/types.ts@@ -28,7 +28,7 @@ export interface SystemMeta {}export interface InfoMeta {- view?: "help" | "list" | "kv" | "dim";+ view?: "help" | "list" | "kv" | "dim" | "compact_boundary" | "compact_summary";title?: string;items?: Array<{ label: string; value?: string; description?: string }>;groups?: Array<{@@ -82,6 +82,8 @@ export interface ContextCompressionStats {rate: number;beforeCompressed: number | null;afterCompressed: number | null;+ summary?: string;+ trigger?: "manual" | "auto";}export type TodoStatus = "pending" | "in_progress" | "completed";@@ -219,6 +221,7 @@ export type HistoryItem =icon?: string;meta?: InfoMeta;mediaItems?: MediaItem[];+ transcriptOnly?: boolean;at: string;}| {diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/components/messages/meta-components.ts b/jiuwenswarm/channels/tui/frontend/src/ui/components/messages/meta-components.tsindex ca48823f43..93d8c3a0c8 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/components/messages/meta-components.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/components/messages/meta-components.ts@@ -83,6 +83,62 @@ export class InfoMessageComponent implements Component {render(width: number): string[] {const meta = this.entry.meta;+ if (meta?.view === "compact_boundary") {+ const lines = renderWrappedText(+ Math.max(1, width),+ "· Conversation compacted (ctrl+o for summary)",+ palette.text.dim,+ );+ for (const item of meta.items ?? []) {+ const value = item.value ? `: ${item.value}` : "";+ lines.push(+ ...renderClaudeResponseLines(+ width,+ renderWrappedText(+ Math.max(1, width - 4),+ `${item.label}${value}`,+ palette.text.assistant,+ ),+ palette.text.assistant,+ ),+ );+ if (item.description) {+ lines.push(+ ...renderClaudeResponseLines(+ width,+ renderWrappedText(Math.max(1, width - 4), item.description, palette.text.dim),+ palette.text.dim,+ ),+ );+ }+ }+ return lines;+ }++ if (meta?.view === "compact_summary") {+ const lines: string[] = [];+ lines.push(...renderWrappedText(Math.max(1, width), "· Compaction summary", palette.text.info));+ lines.push(+ ...renderClaudeResponseLines(+ width,+ renderWrappedText(+ Math.max(1, width - 4),+ "The earlier conversation has been compacted into the following memory block, which will be used as historical context going forward:",+ palette.text.dim,+ ),+ palette.text.dim,+ ),+ );+ lines.push(+ ...renderClaudeResponseLines(+ width,+ renderWrappedText(Math.max(1, width - 4), this.entry.content, palette.text.assistant),+ palette.text.assistant,+ ),+ );+ return lines;+ }+if (meta?.view === "help" && meta.groups?.length) {return renderGroupedHelpView(width, meta);}diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/transcript-entry-selection.ts b/jiuwenswarm/channels/tui/frontend/src/ui/transcript-entry-selection.tsindex 6f964561f1..fd9a4e5fea 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/transcript-entry-selection.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/transcript-entry-selection.ts@@ -69,7 +69,9 @@ export function selectTranscriptEntries(snapshot: AppSnapshot): SelectedTranscri.find((entry) => entry.kind === "thinking")?.id ?? undefined;if (snapshot.transcriptMode === "compact") {- entries = entries.filter((entry) => entry.kind !== "thinking");+ entries = entries.filter(+ (entry) => entry.kind !== "thinking" && !(entry.kind === "info" && entry.transcriptOnly),+ );}return { entries, latestThinkingId };diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex f8c5548f4d..4f45e6f371 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -39,6 +39,7 @@ from jiuwenswarm.agents.harness.common.rails.permissions.permissions_persist impfrom jiuwenswarm.extensions.hooks_context import AgentServerChatHookContextfrom jiuwenswarm.server.runtime.agent_manager import AgentManager, ACP_DEFAULT_CAPABILITIESfrom jiuwenswarm.server.runtime.session.session_metadata import get_all_sessions_metadata, remove_session_metadata_cache+from jiuwenswarm.server.runtime.session.session_history import append_compact_history_recordsfrom jiuwenswarm.server.runtime.agent_adapter.sysop_builder import (build_filesystem_policy,find_auto_managed_match,@@ -90,10 +91,20 @@ _HISTORY_RESTORABLE_ASSISTANT_EVENT_TYPES = frozenset("chat.usage_summary","chat.file","team.message",+ "context.compact_boundary",+ "context.compact_summary",})+def _extract_compact_summary_processor(summary: str) -> str:+ for line in str(summary or "").splitlines():+ key, sep, value = line.partition(":")+ if sep and key.strip().lower() == "processor":+ return value.strip()+ return ""++def _is_restorable_history_record(record: Any) -> bool:"""Coarsely filter records that the web history UI cannot use for pagination."""if not isinstance(record, dict):@@ -1949,10 +1960,17 @@ class AgentWebSocketServer:if agent is None:raise ValueError("Failed to get agent")- result_data = await agent.compress_context(session_id=session_id)+ result_data = await agent.compress_context(session_id=session_id, return_state=True)result = result_data.get("result")stats = result_data.get("stats")+ state = result_data.get("state") if isinstance(result_data.get("state"), dict) else {}+ summary = str(+ result_data.get("compact_summary")+ or state.get("compact_summary")+ or result_data.get("summary")+ or ""+ ).strip()if result == "compressed" and stats:before_tokens = stats.get("raw_total_tokens", 0)@@ -1961,6 +1979,10 @@ class AgentWebSocketServer:rate = round((before_tokens - after_tokens) / before_tokens * 100, 1)else:rate = 0+ stats_summary = (+ f"\u2713 Context compacted: {after_tokens / 1000:.1f}K/"+ f"{before_tokens / 1000:.1f}K tokens ({rate:.1f}% saved)"+ )await self.send_push({"channel_id": channel_id,@@ -1972,6 +1994,37 @@ class AgentWebSocketServer:"afterCompressed": after_tokens,},})+ if summary:+ append_compact_history_records(+ session_id=session_id,+ request_id=request.request_id,+ channel_id=channel_id,+ summary=summary,+ timestamp=_dt.datetime.now().timestamp(),+ trigger="manual",+ stats=stats,+ mode=params.get("mode", "agent.plan"),+ )+ compression_state_payload: dict[str, Any] = {+ **state,+ "event_type": "context.compression_state",+ "status": state.get("status") or "compressed",+ "phase": state.get("phase") or "active_compress",+ "processor": state.get("processor") or _extract_compact_summary_processor(summary),+ "before": state.get("before") or {"tokens": before_tokens},+ "after": state.get("after") or {"tokens": after_tokens},+ "saved": state.get("saved") or {+ "tokens": before_tokens - after_tokens,+ "percent": rate,+ },+ "summary": stats_summary,+ "compact_summary": summary,+ }+ await self.send_push({+ "channel_id": channel_id,+ "session_id": session_id,+ "payload": compression_state_payload,+ })resp = AgentResponse(request_id=request.request_id,@@ -1980,6 +2033,8 @@ class AgentWebSocketServer:payload={"result": result,"stats": stats,+ **({"summary": summary} if summary else {}),+ **({"compact_summary": summary} if summary else {}),},)except Exception as e: # noqa: BLE001diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex 2d2dc22229..1c050c2261 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -26,7 +26,10 @@ from jiuwenswarm.server.runtime.agent_adapter.agent_adapters import (resolve_sdk_choice,)from jiuwenswarm.agents.harness.common.memory.config import get_memory_mode-from jiuwenswarm.server.runtime.session.session_history import append_history_record+from jiuwenswarm.server.runtime.session.session_history import (+ append_compact_history_records,+ append_history_record,+)from jiuwenswarm.server.runtime.session.session_manager import SessionManagerfrom jiuwenswarm.server.runtime.skill.skill_manager import SkillManagerfrom jiuwenswarm.server.utils.utils import is_team_params@@ -43,6 +46,45 @@ from jiuwenswarm.common.utils import (reset_free_search_runtime_flags,)++def _compact_stats_from_payload(payload: dict[str, Any]) -> dict[str, Any]:+ stats: dict[str, Any] = {}+ for key in ("status", "phase", "processor", "model", "before", "after", "saved", "duration_ms"):+ if key in payload:+ stats[key] = payload.get(key)+ return stats+++def _is_successful_compaction_payload(payload: dict[str, Any]) -> bool:+ if payload.get("error"):+ return False+ status = str(payload.get("status") or "").strip().lower()+ return status not in {"error", "failed", "skipped"}+++def _append_compact_history_from_payload(+ *,+ payload: dict[str, Any],+ session_id: str,+ request_id: str,+ channel_id: str,+ mode: str,+) -> None:+ summary_text = str(payload.get("compact_summary") or "").strip()+ if not summary_text or not _is_successful_compaction_payload(payload):+ return+ append_compact_history_records(+ session_id=session_id,+ request_id=request_id,+ channel_id=channel_id,+ summary=summary_text,+ timestamp=time.time(),+ trigger="auto",+ stats=_compact_stats_from_payload(payload),+ mode=mode,+ )++load_dotenv(dotenv_path=get_env_file(), override=True)reset_free_search_runtime_flags()@@ -935,6 +977,14 @@ class JiuWenClaw:should_record = et.startswith("chat.")if not should_record and et == EventType.TEAM_MESSAGE.value:should_record = True+ if et == "context_compression_state":+ _append_compact_history_from_payload(+ payload=data.payload,+ session_id=session_id,+ request_id=rid,+ channel_id=cid,+ mode=request.params.get("mode", "unknown"),+ )if should_record:payload_dict = dict(data.payload)@@ -967,6 +1017,14 @@ class JiuWenClaw:should_record = et.startswith("chat.")if not should_record and et == EventType.TEAM_MESSAGE.value:should_record = True+ if et == "context_compression_state":+ _append_compact_history_from_payload(+ payload=data,+ session_id=session_id,+ request_id=rid,+ channel_id=cid,+ mode=request.params.get("mode", "unknown"),+ )if should_record:extra_fields = {k: v for k, v in data.items() if k not in ("event_type", "content")}@@ -1027,7 +1085,13 @@ class JiuWenClaw:def get_instance(self):return self._adapter._instance- async def compress_context(self, session_id: str, session: Any = None) -> dict[str, Any]:+ async def compress_context(+ self,+ session_id: str,+ session: Any = None,+ *,+ return_state: bool = False,+ ) -> dict[str, Any]:"""主动触发上下文压缩。Args:@@ -1045,6 +1109,7 @@ class JiuWenClaw:return await adapter.compress_context(session_id=session_id,session=session,+ return_state=return_state,)async def get_context_usage(self, session_id: str) -> dict[str, Any]:diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 22addf7fd8..47595004b3 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -323,6 +323,18 @@ def _build_context_assemble_rail() -> ContextAssembleRail | None:return context_assemble_rail+def _resolve_session_memory_config(context_engine_cfg: dict[str, Any]) -> dict[str, Any] | None:+ raw_config = (+ context_engine_cfg.get("session_memory_config")+ or context_engine_cfg.get("session_memory")+ )+ if raw_config is True:+ return {}+ if isinstance(raw_config, dict):+ return raw_config+ return None++def _build_context_processor_rail(config: dict[str, Any]) -> ContextProcessorRail | None:"""Build ContextProcessorRail with user config.@@ -333,7 +345,9 @@ def _build_context_processor_rail(config: dict[str, Any]) -> ContextProcessorRai"""try:user_processors: List[Tuple[str, dict]] = []- context_engine_cfg = config.get("context_engine_config", {})+ raw_context_engine_cfg = config.get("context_engine_config", {})+ context_engine_cfg = raw_context_engine_cfg if isinstance(raw_context_engine_cfg, dict) else {}+ session_memory_cfg = _resolve_session_memory_config(context_engine_cfg)offloader_cfg = context_engine_cfg.get("message_summary_offloader_config", {})if isinstance(offloader_cfg, dict) and offloader_cfg:@@ -354,11 +368,13 @@ def _build_context_processor_rail(config: dict[str, Any]) -> ContextProcessorRaicontext_rail = ContextProcessorRail(processors=user_processors if user_processors else None,preset=True,+ session_memory=session_memory_cfg,)logger.info("[JiuWenClawDeepAdapter] ContextProcessorRail create success for agent.plan mode, "- "user_processors=%s",+ "user_processors=%s session_memory=%s",[p[0] for p in user_processors] if user_processors else "none",+ "enabled" if isinstance(session_memory_cfg, dict) else "disabled",)return context_railexcept Exception as exc:@@ -5305,7 +5321,13 @@ class JiuWenClawDeepAdapter:self._external_memory_rail = Noneself._external_memory_rail_registered = False- async def compress_context(self, session_id: str, session: Any = None) -> dict[str, Any]:+ async def compress_context(+ self,+ session_id: str,+ session: Any = None,+ *,+ return_state: bool = False,+ ) -> dict[str, Any]:"""主动触发上下文压缩。Args:@@ -5331,12 +5353,33 @@ class JiuWenClawDeepAdapter:context, react_agent, session_id)- result = await context_engine.compress_context(+ compact_result = await context_engine.compress_context(session=session,session_id=session_id,+ return_state=True,)+ summary: str | None = None+ state: dict[str, Any] | None = None+ if isinstance(compact_result, dict):+ result = compact_result.get("result") or compact_result.get("status")+ raw_state = compact_result.get("state")+ if isinstance(raw_state, dict):+ state = raw_state+ raw_summary = compact_result.get("compact_summary")+ if raw_summary is None:+ if isinstance(state, dict):+ raw_summary = state.get("compact_summary")+ if isinstance(raw_summary, str) and raw_summary.strip():+ summary = raw_summary.strip()+ else:+ result = compact_resultresponse: dict[str, Any] = {"result": result}+ if return_state and state:+ response["state"] = state+ compact_summary = state.get("compact_summary")+ if isinstance(compact_summary, str) and compact_summary.strip():+ response["compact_summary"] = compact_summary.strip()if result == "compressed":context = context_engine.get_context(session_id=session_id)@@ -5351,6 +5394,9 @@ class JiuWenClawDeepAdapter:"total_tokens": total_tokens,"raw_total_tokens": raw_total_tokens,}+ if summary:+ response["summary"] = summary+ response.setdefault("compact_summary", summary)return responsediff --git a/jiuwenswarm/server/runtime/session/session_history.py b/jiuwenswarm/server/runtime/session/session_history.pyindex 49d331116a..3063cde161 100644--- a/jiuwenswarm/server/runtime/session/session_history.py+++ b/jiuwenswarm/server/runtime/session/session_history.py@@ -155,6 +155,58 @@ def append_history_record(logger.warning("更新会话元数据失败: %s", exc)+def append_compact_history_records(+ *,+ session_id: str,+ request_id: str,+ channel_id: str,+ summary: str | None,+ timestamp: float,+ trigger: str = "auto",+ stats: dict[str, Any] | None = None,+ mode: str | None = None,+) -> None:+ """Persist a compact boundary and optional transcript-only summary."""+ clean_summary = (summary or "").strip()+ metadata = {+ "compact_metadata": {+ "trigger": trigger,+ **(_serialize_value(stats) if isinstance(stats, dict) else {}),+ },+ }++ append_history_record(+ session_id=session_id,+ request_id=request_id,+ channel_id=channel_id,+ role="assistant",+ event_type="context.compact_boundary",+ content="Conversation compacted",+ timestamp=timestamp,+ extra=metadata,+ mode=mode,+ )++ if not clean_summary:+ return++ append_history_record(+ session_id=session_id,+ request_id=request_id,+ channel_id=channel_id,+ role="assistant",+ event_type="context.compact_summary",+ content=clean_summary,+ timestamp=timestamp + 0.001,+ extra={+ **metadata,+ "is_compact_summary": True,+ "transcript_only": True,+ },+ mode=mode,+ )++def truncate_history_records(*, session_id: str, cut_index: int) -> dict[str, Any]:"""截断会话历史到指定位置(线程安全)。diff --git a/tests/unit_tests/agentserver/test_agentserver_acp.py b/tests/unit_tests/agentserver/test_agentserver_acp.pyindex 3d70f407b8..38f98f860a 100644--- a/tests/unit_tests/agentserver/test_agentserver_acp.py+++ b/tests/unit_tests/agentserver/test_agentserver_acp.py@@ -79,9 +79,10 @@ class FakeTeamManager:class FakeContextProcessorRail:- def __init__(self, *, processors=None, preset=None):+ def __init__(self, *, processors=None, preset=None, session_memory=None):self.processors = processorsself.preset = preset+ self.session_memory = session_memoryclass FakeContextAssembleRail:@@ -1232,6 +1233,34 @@ def test_build_context_processor_rail_prefers_summary_offloader_config(monkeypat]+def test_build_context_processor_rail_passes_session_memory_config(monkeypatch):+ monkeypatch.setattr(+ interface_deep_module,+ "ContextProcessorRail",+ FakeContextProcessorRail,+ )+ adapter = DeepAdapterHarness()++ rail = adapter.build_context_processor_rail_for_test(+ {+ "context_engine_config": {+ "session_memory_config": {+ "trigger_tokens": 12000,+ "update_mode": "direct_replace",+ },+ }+ }+ )++ assert isinstance(rail, FakeContextProcessorRail)+ assert rail.preset is True+ assert rail.processors is None+ assert rail.session_memory == {+ "trigger_tokens": 12000,+ "update_mode": "direct_replace",+ }++def test_build_context_assemble_rail_returns_context_assemble_rail_instance(monkeypatch):monkeypatch.setattr(interface_deep_module,diff --git a/tests/unit_tests/agentserver/test_agentserver_cli_commands.py b/tests/unit_tests/agentserver/test_agentserver_cli_commands.pyindex f93450558e..e501ac06ec 100644--- a/tests/unit_tests/agentserver/test_agentserver_cli_commands.py+++ b/tests/unit_tests/agentserver/test_agentserver_cli_commands.py@@ -117,7 +117,7 @@ async def test_handle_command_compact_returns_custom_instructions(server, fake_w)class MockAgent:- async def compress_context(self, session_id):+ async def compress_context(self, session_id, *, return_state=False):return {"result": "compressed","stats": {@@ -162,6 +162,58 @@ async def test_handle_command_compact_returns_custom_instructions(server, fake_w]+async def test_handle_command_compact_pushes_current_compression_state_event(server, fake_ws, monkeypatch):+ request = AgentRequest(+ request_id="req-compact",+ channel_id="tui",+ session_id="session-1",+ req_method=ReqMethod.COMMAND_COMPACT,+ params={"mode": "agent.plan"},+ )++ class MockAgent:+ async def compress_context(self, session_id, *, return_state=False):+ return {+ "result": "compressed",+ "stats": {+ "raw_total_tokens": 1000,+ "total_tokens": 300,+ },+ "state": {+ "status": "completed",+ "phase": "active_compress",+ "compact_summary": "manual compact summary",+ },+ "compact_summary": "manual compact summary",+ }++ pushed = []++ async def mock_get_agent(channel_id, mode, project_dir=None, sub_mode=None):+ return MockAgent()++ async def mock_send_push(msg):+ pushed.append(msg)++ monkeypatch.setattr(+ server.get_agent_manager_for_test(),+ "get_agent",+ mock_get_agent,+ )+ monkeypatch.setattr(server, "send_push", mock_send_push)++ await server.handle_command_compact_for_test(fake_ws, request, asyncio.Lock())++ compression_state_pushes = [+ item for item in pushed+ if item.get("payload", {}).get("event_type") == "context.compression_state"+ ]+ assert len(compression_state_pushes) == 1+ assert compression_state_pushes[0]["session_id"] == "session-1"+ assert compression_state_pushes[0]["payload"]["compact_summary"] == "manual compact summary"++@pytest.mark.asyncioasync def test_handle_command_diff_returns_summary_payload(server, fake_ws):request = AgentRequest(diff --git a/tests/unit_tests/test_compact_history_records.py b/tests/unit_tests/test_compact_history_records.pynew file mode 100644index 0000000000..9b83025566--- /dev/null+++ b/tests/unit_tests/test_compact_history_records.py@@ -0,0 +1,43 @@+import json+import time++from jiuwenswarm.server.runtime.session import session_history+++def _read_history_file(path):+ deadline = time.time() + 5+ while time.time() < deadline:+ if path.exists():+ data = json.loads(path.read_text(encoding="utf-8"))+ if len(data) >= 2:+ return data+ time.sleep(0.05)+ raise AssertionError(f"history file was not written: {path}")+++def test_append_compact_history_records_writes_boundary_and_transcript_summary(tmp_path, monkeypatch):+ monkeypatch.setattr(session_history, "get_agent_sessions_dir", lambda: tmp_path)++ session_history.append_compact_history_records(+ session_id="s1",+ request_id="r1",+ channel_id="tui",+ summary="Important compact summary",+ timestamp=123.0,+ trigger="auto",+ stats={"processor": "RoundLevelCompressor"},+ mode="agent.plan",+ )++ data = _read_history_file(tmp_path / "s1" / "history.json")++ assert [item["event_type"] for item in data] == [+ "context.compact_boundary",+ "context.compact_summary",+ ]+ assert data[0]["content"] == "Conversation compacted"+ assert data[0]["compact_metadata"]["trigger"] == "auto"+ assert data[0]["compact_metadata"]["processor"] == "RoundLevelCompressor"+ assert data[1]["content"] == "Important compact summary"+ assert data[1]["is_compact_summary"] is True+ assert data[1]["transcript_only"] is Truediff --git a/uv.lock b/uv.lockindex d7c1503e0b..1da298b23e 100644--- a/uv.lock+++ b/uv.lock@@ -2379,7 +2379,7 @@ wheels = [[[package]]name = "openjiuwen"version = "0.1.13"-source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#8d802727e0395f962b271789b5f71111feefe7f8" }+source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#df29f1e26cf1350922ba8de0b7c9181f68b3576c" }dependencies = [{ name = "aiofiles" },{ name = "aiohttp" },