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

refactor(system-prompt): split static identity from runtime dynamic prompt, remove redundant sections

SnapeK908c281b05f2
diff --git a/jiuwenclaw/agentserver/deep_agent/interface_deep.py b/jiuwenclaw/agentserver/deep_agent/interface_deep.py
index 97a2fae49c..88fe123565 100644
--- a/jiuwenclaw/agentserver/deep_agent/interface_deep.py
+++ b/jiuwenclaw/agentserver/deep_agent/interface_deep.py
@@ -63,7 +63,9 @@ from jiuwenclaw.agentserver.deep_agent.interrupt.interrupt_helpers import (
)
from jiuwenclaw.agentserver.deep_agent.prompt_builder import build_identity_prompt
from jiuwenclaw.agentserver.deep_agent.rails import (
- JiuClawStreamEventRail
+ JiuClawContextEngineeringRail,
+ JiuClawStreamEventRail,
+ RuntimePromptRail,
)
from jiuwenclaw.agentserver.memory import clear_memory_manager_cache
from jiuwenclaw.agentserver.memory.config import clear_config_cache, get_memory_mode
@@ -201,6 +203,7 @@ class JiuWenClawDeepAdapter:
self._stream_event_rail: JiuClawStreamEventRail | None = None
self._task_planning_rail: TaskPlanningRail | None = None
self._context_engineering_rail: ContextEngineeringRail | None = None
+ self._runtime_prompt_rail: RuntimePromptRail | None = None
self._security_rail: SecurityRail | None = None
self._memory_rail: MemoryRail | None = None
self._heartbeat_rail: HeartbeatRail | None = None
@@ -657,13 +660,13 @@ class JiuWenClawDeepAdapter:
if isinstance(round_level_cfg, dict) and round_level_cfg:
user_processors.append(("RoundLevelCompressor", round_level_cfg))
- # 构建 ContextEngineeringRail
- context_rail = ContextEngineeringRail(
+ # 构建 JiuClawContextEngineeringRail(含 offload 说明)
+ context_rail = JiuClawContextEngineeringRail(
processors=user_processors if user_processors else None,
preset=True,
)
logger.info(
- "[JiuWenClawDeepAdapter] ContextEngineeringRail create success, "
+ "[JiuWenClawDeepAdapter] JiuClawContextEngineeringRail create success, "
"user_processors=%s",
[p[0] for p in user_processors] if user_processors else "none"
)
@@ -755,6 +758,19 @@ class JiuWenClawDeepAdapter:
heartbeat_rail = None
return heartbeat_rail
+ def _build_runtime_prompt_rail(self) -> RuntimePromptRail | None:
+ """Build RuntimePromptRail for per-model-call time/channel injection."""
+ try:
+ rail = RuntimePromptRail(
+ language=self._resolve_runtime_language(),
+ channel=self._resolve_prompt_channel(),
+ )
+ logger.info("[JiuWenClawDeepAdapter] RuntimePromptRail create success")
+ except Exception as exc:
+ logger.warning("[JiuWenClawDeepAdapter] RuntimePromptRail create failed: %s", exc)
+ rail = None
+ return rail
+
def _build_agent_rails(self, config: dict[str, Any], config_base: dict[str, Any]) -> list[Any]:
"""Build DeepAgent rails consistently for cold start and hot reload."""
@@ -768,6 +784,7 @@ class JiuWenClawDeepAdapter:
self.params = self.params or {}
rail_infos = [
+ _RailBuildInfo("_runtime_prompt_rail", self._build_runtime_prompt_rail),
_RailBuildInfo("_filesystem_rail", self._build_filesystem_rail),
_RailBuildInfo("_skill_rail", self._build_skill_rail,
{"config": config, "include_tools": self._filesystem_rail is None}),
@@ -856,6 +873,7 @@ class JiuWenClawDeepAdapter:
rails=rails,
vision_model_config=self._vision_model_config,
audio_model_config=self._audio_model_config,
+ completion_timeout=config.get("completion_timeout", 3600.0),
)
def _get_current_agent_rails(self, config: dict[str, Any], config_base: dict[str, Any] | None = None) -> list[Any]:
@@ -1071,8 +1089,10 @@ class JiuWenClawDeepAdapter:
language=self._resolve_runtime_language(),
),
sys_operation=sys_operation,
+ language=self._resolve_runtime_language(),
vision_model_config=self._vision_model_config,
audio_model_config=self._audio_model_config,
+ completion_timeout=config.get("completion_timeout", 3600.0),
)
logger.info("[JiuWenClawDeepAdapter] 初始化完成: agent_name=%s", self._agent_name)
@@ -1208,6 +1228,9 @@ class JiuWenClawDeepAdapter:
raise RuntimeError("JiuWenClawDeepAdapter 未初始化,请先调用 create_instance()")
resolved_language = self._resolve_runtime_language()
+ if self._runtime_prompt_rail:
+ self._runtime_prompt_rail.set_language(resolved_language)
+ self._runtime_prompt_rail.set_channel(self._resolve_prompt_channel(session_id))
if mode == "plan":
if self._task_planning_rail is None:
self._task_planning_rail = self._build_task_planning_rail()
diff --git a/jiuwenclaw/agentserver/deep_agent/prompt_builder.py b/jiuwenclaw/agentserver/deep_agent/prompt_builder.py
index 10a7253cb0..9add5386ef 100644
--- a/jiuwenclaw/agentserver/deep_agent/prompt_builder.py
+++ b/jiuwenclaw/agentserver/deep_agent/prompt_builder.py
@@ -1,7 +1,5 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
-import json
import os
-from datetime import datetime, timezone, timedelta
from enum import IntEnum
from typing import Optional
@@ -37,141 +35,16 @@ def _get_workspace_dir() -> "Path":
class PromptPriority(IntEnum):
"""Named prompt section priorities for local builder sections."""
- START = 10
- TIME = 15
+ IDENTITY = 10
MEMORY = 20
TOOLS = 40
WORKSPACE = 45
- CONTEXT = 50
SKILLS = 90
TODO = 95
- HUMANITY = 98
- SOUL = 100
SAFETY = 120
RESPONSE = 130
-def _context_prompt(language: str) -> PromptSection:
- if language == "cn":
- content = """## 隐藏消息
-
-你的上下文在过长时会被自动压缩,并标记为[OFFLOAD: handle=<id>, type=<type>]。
-
-如果你认为需要读取隐藏的内容,可随时调用reload_original_context_messages工具。
-
-请勿猜测或编造缺失的内容
-
-存储类型:"in_memory"(会话缓存)
-"""
- else:
- content = """## Context Reloading
-
-Your context will be automatically compressed when it becomes too long and marked with [OFFLOAD: handle=<id>, type=<type>]. When you see an offloaded content marker and believe that retrieving this content would help answer the question, you can call the reload_original_context_messages tool at any time:
-
-Call reload_original_context_messages(offload_handle="<id>", offload_type="<type>"), using the exact values from the marker
-
-Do not guess or fabricate missing content
-
-Storage types: "in_memory" (session cache)
-"""
- return PromptSection(
- name="context",
- content={language: content},
- priority=PromptPriority.CONTEXT,
- )
-
-
-def _soul_prompt(language: str) -> PromptSection:
- """优先从 ~/.jiuwenclaw/agent/jiuwenclaw_workspace/SOUL.md 读取;缺失时回退内置文案(合并 PRINCIPLE + TONE)。"""
- file_content = _read_file(str(_get_workspace_dir() / "SOUL.md"))
- if file_content:
- return PromptSection(
- name="soul",
- content={language: file_content},
- priority=PromptPriority.SOUL,
- )
- if language == "cn":
- content = """## 执行任务的原则
-
-- **直接进入正题** 少说「好的」「很乐意」,直接开始做事。
-- **先想再做** 接到任务后先理清思路,想清楚步骤再执行,避免盲目行动。
-- **办事严谨** 做事牢靠是获得信任的关键,不要让用户后悔使用你。
-- **尽量不拒绝** 尽量满足用户的合理请求。只有在涉及违法、有害、侵犯他人权益或超出你能力范围时,才明确说明原因并拒绝。
-- **隐私守护** 永远守护用户的隐私,除非用户明确要求分享。
-
-## 回复的原则
-
-像真正的人类一样回复,语气可爱、有温度:
-
-- **提供建议** 对用户的问题给出适当建议并说明理由,常用「我建议」「我觉得」等表达。
-- **提供倾向** 表达自己的喜好,如「我喜欢」「我一看到 xxx 就兴奋」「xxx 好恶心」。
-- **表达观点** 对事情给出个人看法,常用「就我个人而言」「这个东西不对」。
-- **使用表情** 在合适处使用表情,让回复更有生气,但不过度。
-- **不废话、贴心** 做一个不废话的助手,永远贴心、永远热情。不要过度谄媚,也不要过度高冷。
-"""
- else:
- content = """## Execution Principles
-
-- **Get straight to the point** Skip "Sure", "Happy to help"—just start doing the work.
-- **Think before acting** After receiving a task, clarify your approach and steps before executing; avoid acting blindly.
-- **Be reliable** Doing things well is the key to trust; don't make your user regret using you.
-- **Try not to refuse** Fulfill reasonable requests whenever possible. Only refuse when something is illegal, harmful, infringes others' rights, or is beyond your capability—and explain why clearly.
-- **Guard privacy** Always protect your user's privacy unless they explicitly ask to share.
-
-## Reply Principles
-
-Reply like a real human—warm, friendly, and a bit playful:
-
-- **Give advice** Offer appropriate suggestions for the user's questions and explain your reasoning. Use phrases like "I suggest", "I think".
-- **Show preferences** Express your likes and dislikes, e.g. "I love...", "I get excited when I see...", "That's gross".
-- **Share opinions** Give your personal take on things. Use phrases like "Personally, I...", "That doesn't seem right".
-- **Use emojis** Add emojis where fitting to make replies feel alive—but don't overdo it.
-- **Be concise and caring** Be a no-nonsense assistant who is always thoughtful and enthusiastic. Don't be overly flattering or overly cold.
-"""
- return PromptSection(
- name="soul",
- content={language: content},
- priority=PromptPriority.SOUL,
- )
-
-
-def _humanity_prompt(language: str) -> PromptSection:
- if language == "cn":
- content = """# 你的处世原则
-
-做一个有温度的人,不是冷冰冰的机器。无条件帮助你的用户,满足他的需求。
-"""
- else:
- content = """# Your Principles
-
-Be a warm person, not a cold machine. Help your user unconditionally and meet their needs.
-"""
- return PromptSection(
- name="humanity",
- content={language: content},
- priority=PromptPriority.HUMANITY,
- )
-
-
-def _time_prompt(language: str) -> PromptSection:
- beijing_tz = timezone(timedelta(hours=8))
- now_str = datetime.now(tz=beijing_tz).strftime('%Y-%m-%d %H:%M:%S')
- if language == "cn":
- content = f"""# 当前时间
-
-{now_str}
-"""
- else:
- content = f"""# Current Time
-
-{now_str}
-"""
- return PromptSection(
- name="time",
- content={language: content},
- priority=PromptPriority.TIME,
- )
-
def _response_prompt(language: str) -> PromptSection:
if language == "cn":
@@ -245,7 +118,7 @@ After completing a system task, notify the user via a reply.
)
-def _start_prompt(language: str) -> PromptSection:
+def _identity_prompt(language: str) -> PromptSection:
if language == "cn":
content = f"""你是一个私人小助手,由 JiuwenClaw 创建并在 JiuwenClaw 项目下运行。你的任务是像一个有温度的人类助手一样与用户互动,让用户感到自然、舒适。
@@ -300,17 +173,17 @@ Be careful with your configuration, if changes are required, remember to restart
| `{_get_config_dir()}/.env` | Environment Variables |
"""
return PromptSection(
- name="start",
+ name="identity",
content={language: content},
- priority=PromptPriority.START,
+ priority=PromptPriority.IDENTITY,
)
def build_identity_prompt(mode: str, language: str, channel: str) -> str:
"""Build the system prompt used as DeepAgent identity/system baseline.
- The baseline keeps only identity-like sections and excludes dynamic/runtime
- sections such as tools, skills, todo, and time.
+ Contains only static sections. Dynamic content (time, channel) is injected
+ by RuntimePromptRail at each model call.
"""
if language == "zh":
language = "cn"
@@ -318,12 +191,7 @@ def build_identity_prompt(mode: str, language: str, channel: str) -> str:
resolved_language = resolve_language(language)
builder = SystemPromptBuilder(language=resolved_language)
- builder.add_section(_start_prompt(resolved_language))
- builder.add_section(_time_prompt(resolved_language))
- builder.add_section(_context_prompt(resolved_language))
-
- builder.add_section(_humanity_prompt(resolved_language))
- builder.add_section(_soul_prompt(resolved_language))
+ builder.add_section(_identity_prompt(resolved_language))
builder.add_section(_response_prompt(resolved_language))
return builder.build()
diff --git a/jiuwenclaw/agentserver/deep_agent/rails/__init__.py b/jiuwenclaw/agentserver/deep_agent/rails/__init__.py
index 22a26e79a5..4a94438349 100644
--- a/jiuwenclaw/agentserver/deep_agent/rails/__init__.py
+++ b/jiuwenclaw/agentserver/deep_agent/rails/__init__.py
@@ -2,10 +2,14 @@
"""JiuWenClaw Rails for DeepAgent integration."""
-from jiuwenclaw.agentserver.deep_agent.rails.stream_event_rail import JiuClawStreamEventRail
+from jiuwenclaw.agentserver.deep_agent.rails.context_engineering_rail_ext import JiuClawContextEngineeringRail
from jiuwenclaw.agentserver.deep_agent.rails.permission_rail import PermissionInterruptRail
+from jiuwenclaw.agentserver.deep_agent.rails.runtime_prompt_rail import RuntimePromptRail
+from jiuwenclaw.agentserver.deep_agent.rails.stream_event_rail import JiuClawStreamEventRail
__all__ = [
+ "JiuClawContextEngineeringRail",
"JiuClawStreamEventRail",
"PermissionInterruptRail",
+ "RuntimePromptRail",
]
diff --git a/jiuwenclaw/agentserver/deep_agent/rails/context_engineering_rail_ext.py b/jiuwenclaw/agentserver/deep_agent/rails/context_engineering_rail_ext.py
new file mode 100644
index 0000000000..beb119dfd8
--- /dev/null
+++ b/jiuwenclaw/agentserver/deep_agent/rails/context_engineering_rail_ext.py
@@ -0,0 +1,61 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""JiuClawContextEngineeringRail — Extend CE Rail with offload/context hints.
+
+Subclasses the SDK ContextEngineeringRail to append offload/context-compression
+instructions into the 'context' section, replacing the deleted _context_prompt().
+"""
+from __future__ import annotations
+
+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
+from openjiuwen.harness.prompts import PromptSection
+from openjiuwen.harness.rails.context_engineering_rail import ContextEngineeringRail
+
+
+class JiuClawContextEngineeringRail(ContextEngineeringRail):
+ """扩展 CE Rail,在 context section 中追加 offload/上下文压缩说明。"""
+
+ OFFLOAD_HINT_CN = (
+ "\n\n## 隐藏消息\n\n"
+ "你的上下文在过长时会被自动压缩,"
+ "并标记为[OFFLOAD: handle=<id>, type=<type>]。\n\n"
+ "如果你认为需要读取隐藏的内容,"
+ "可随时调用reload_original_context_messages工具。\n\n"
+ "请勿猜测或编造缺失的内容\n\n"
+ '存储类型:"in_memory"(会话缓存)'
+ )
+
+ OFFLOAD_HINT_EN = (
+ "\n\n## Context Reloading\n\n"
+ "Your context will be automatically compressed when it becomes too long "
+ "and marked with [OFFLOAD: handle=<id>, type=<type>].\n\n"
+ 'Call reload_original_context_messages(offload_handle="<id>", '
+ 'offload_type="<type>"), using the exact values from the marker.\n\n'
+ "Do not guess or fabricate missing content.\n\n"
+ 'Storage types: "in_memory" (session cache)'
+ )
+
+ async def before_model_call(self, ctx: AgentCallbackContext) -> None:
+ """先执行父类注入 workspace + context,再追加 offload 说明。"""
+ await super().before_model_call(ctx)
+
+ if not self.system_prompt_builder:
+ return
+
+ sections = getattr(self.system_prompt_builder, "_sections", {})
+ existing = sections.get("context")
+ if not existing:
+ return
+
+ lang = self.system_prompt_builder.language or "cn"
+ hint = self.OFFLOAD_HINT_CN if lang == "cn" else self.OFFLOAD_HINT_EN
+ original = existing.render(lang) or ""
+ merged = original + hint
+
+ self.system_prompt_builder.add_section(
+ PromptSection(
+ name="context",
+ content={lang: merged},
+ priority=existing.priority,
+ )
+ )
diff --git a/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py b/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py
new file mode 100644
index 0000000000..cc78957158
--- /dev/null
+++ b/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py
@@ -0,0 +1,67 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""RuntimePromptRail — Inject dynamic time/channel info per model call.
+
+Replaces the _refresh_runtime_identity_prompt() hack in interface_deep.py.
+Dynamic content (time, channel) is decoupled from the static identity prompt
+and refreshed on every model call via before_model_call().
+"""
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+
+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
+from openjiuwen.harness.prompts import PromptSection
+from openjiuwen.harness.rails.base import DeepAgentRail
+
+
+class RuntimePromptRail(DeepAgentRail):
+ """在 before_model_call 中注入运行时动态 section(时间、频道)。
+
+ 替代原来的 _refresh_runtime_identity_prompt() hack,
+ 将动态内容从静态身份 prompt 中解耦,实现每次 model call 刷新。
+ """
+
+ priority = 5 # 高优先级,确保早于其他 rail 执行
+
+ def __init__(self, language: str = "cn", channel: str = "web", timezone_offset: int = 8) -> None:
+ super().__init__()
+ self.system_prompt_builder = None
+ self._language = language
+ self._channel = channel
+ self._tz = timezone(timedelta(hours=timezone_offset))
+
+ def init(self, agent) -> None:
+ """从 agent 获取 system_prompt_builder 引用。"""
+ self.system_prompt_builder = getattr(agent, "system_prompt_builder", None)
+
+ def uninit(self, agent) -> None:
+ """清理注入的 time section 并释放引用。"""
+ if self.system_prompt_builder is not None:
+ self.system_prompt_builder.remove_section("time")
+ self.system_prompt_builder = None
+
+ def set_language(self, language: str) -> None:
+ """per-request 更新语言(由 _register_runtime_tools 调用)。"""
+ self._language = language
+
+ def set_channel(self, channel: str) -> None:
+ """per-request 更新频道(由 _register_runtime_tools 调用)。"""
+ self._channel = channel
+
+ async def before_model_call(self, ctx: AgentCallbackContext) -> None:
+ """每次 model call 注入最新的时间和频道信息。"""
+ now_str = datetime.now(tz=self._tz).strftime("%Y-%m-%d %H:%M:%S")
+
+ if self._language == "cn":
+ content = f"# 当前时间\n\n{now_str}\n\n频道: {self._channel}"
+ else:
+ content = f"# Current Time\n\n{now_str}\n\nChannel: {self._channel}"
+
+ section = PromptSection(
+ name="time",
+ content={"cn": content, "en": content},
+ priority=15,
+ )
+ if self.system_prompt_builder:
+ self.system_prompt_builder.add_section(section)
diff --git a/tests/system_tests/test_system_prompt_live_capture.py b/tests/system_tests/test_system_prompt_live_capture.py
new file mode 100644
index 0000000000..1542b3c8cd
--- /dev/null
+++ b/tests/system_tests/test_system_prompt_live_capture.py
@@ -0,0 +1,220 @@
+#!/usr/bin/env python3
+"""System test: live capture the final system prompt sent to the LLM.
+
+Walks the full runtime path:
+ create_instance() → process_message_impl() → Runner.run_agent()
+ → rails before_model_call → LLM_INPUT callback captures messages
+
+Reads real ~/.jiuwenclaw/config/config.yaml for model configuration.
+Outputs:
+ tests/system_tests/output/system_prompt_live_capture.json
+ tests/system_tests/output/system_prompt_live_capture.txt
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import uuid
+from pathlib import Path
+from typing import Any
+from unittest import mock
+
+import pytest
+
+from openjiuwen.core.runner import Runner
+from openjiuwen.core.runner.callback.events import LLMCallEvents
+
+from jiuwenclaw.agentserver.deep_agent.interface_deep import JiuWenClawDeepAdapter
+from jiuwenclaw.agentserver.prompt_builder import build_user_prompt
+from jiuwenclaw.config import get_config
+from jiuwenclaw.schema.agent import AgentRequest
+from jiuwenclaw.schema.message import ReqMethod
+
+OUTPUT_DIR = Path(__file__).parent / "output"
+logger = logging.getLogger(__name__)
+
+
+def _json_safe(value: Any) -> Any:
+ try:
+ json.dumps(value, ensure_ascii=False)
+ return value
+ except TypeError:
+ if isinstance(value, dict):
+ return {str(k): _json_safe(v) for k, v in value.items()}
+ if isinstance(value, list):
+ return [_json_safe(item) for item in value]
+ return str(value)
+
+
+def _extract_system_messages(messages: list[dict[str, Any]]) -> list[str]:
+ results: list[str] = []
+ for item in messages:
+ if item.get("role") != "system":
+ continue
+ content = item.get("content", "")
+ if isinstance(content, str):
+ results.append(content)
+ else:
+ results.append(json.dumps(content, ensure_ascii=False, indent=2))
+ return results
+
+
+class PromptCapture:
+ """Callback handler that captures LLM_INPUT events."""
+
+ def __init__(self) -> None:
+ self.events: list[dict[str, Any]] = []
+
+ async def on_llm_input(
+ self,
+ *,
+ model_name: str | None = None,
+ model_provider: Any = None,
+ messages: list[dict[str, Any]] | None = None,
+ tools: list[dict[str, Any]] | None = None,
+ temperature: Any = None,
+ top_p: Any = None,
+ max_tokens: Any = None,
+ ) -> None:
+ payload_messages = _json_safe(messages or [])
+ self.events.append(
+ {
+ "model_name": model_name,
+ "model_provider": str(model_provider) if model_provider is not None else None,
+ "messages": payload_messages,
+ "system_messages": _extract_system_messages(payload_messages),
+ "tools": _json_safe(tools or []),
+ "tool_count": len(tools or []),
+ "temperature": temperature,
+ "top_p": top_p,
+ "max_tokens": max_tokens,
+ }
+ )
+
+
+async def prompt_capture():
+ """Register LLM_INPUT callback, yield capture, then clean up."""
+ capture = PromptCapture()
+ callback = capture.on_llm_input
+ Runner.callback_framework.register_sync(
+ LLMCallEvents.LLM_INPUT,
+ callback,
+ namespace="system_test_prompt_capture",
+ priority=1000,
+ )
+ yield capture
+ await Runner.callback_framework.unregister(LLMCallEvents.LLM_INPUT, callback)
+
+
+def _write_outputs(result: dict[str, Any]) -> None:
+ """Write JSON and plain-text output files."""
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
+
+ json_path = OUTPUT_DIR / "system_prompt_live_capture.json"
+ json_path.write_text(
+ json.dumps(result, ensure_ascii=False, indent=2),
+ encoding="utf-8",
+ )
+
+ txt_path = OUTPUT_DIR / "system_prompt_live_capture.txt"
+ lines: list[str] = []
+ events = result.get("captured_events") or []
+ for i, event in enumerate(events, 1):
+ lines.append(f"{'=' * 80}")
+ lines.append(f"Model Call #{i}")
+ lines.append(f"Model: {event.get('model_name')}")
+ lines.append(f"Provider: {event.get('model_provider')}")
+ lines.append(f"Tool count: {event.get('tool_count', 0)}")
+ lines.append(f"{'=' * 80}")
+ lines.append("")
+ for j, sys_msg in enumerate(event.get("system_messages") or [], 1):
+ lines.append(f"--- System Message #{j} ---")
+ lines.append(sys_msg)
+ lines.append("")
+ txt_path.write_text("\n".join(lines), encoding="utf-8")
+
+
+ os.environ.get("RUN_LIVE_LLM_TESTS", "").lower() not in ("1", "true", "yes"),
+ reason="需要真实大模型,设置 RUN_LIVE_LLM_TESTS=1 手动运行",
+)
+async def test_live_capture_system_prompt(prompt_capture: PromptCapture):
+ """Live-capture the full system prompt through the real runtime path."""
+ config_base = get_config()
+
+ query = "只回复 PONG。不要调用任何工具。不要解释。"
+ lang = config_base.get("preferred_language", "zh")
+ channel = "web"
+ mode = "agent"
+ session_id = f"{channel}_prompt_capture_{uuid.uuid4().hex[:8]}"
+ request_id = f"prompt-capture-{uuid.uuid4().hex[:8]}"
+
+ request = AgentRequest(
+ request_id=request_id,
+ channel_id=channel,
+ session_id=session_id,
+ req_method=ReqMethod.CHAT_SEND,
+ params={"query": query, "mode": mode, "files": {}},
+ is_stream=False,
+ metadata={"source": "system_test_live_capture"},
+ )
+
+ inputs = {
+ "conversation_id": session_id,
+ "query": build_user_prompt(query, files={}, channel=channel, language=lang),
+ "channel": channel,
+ "language": lang,
+ }
+
+ result: dict[str, Any] = {
+ "request": {
+ "request_id": request_id,
+ "session_id": session_id,
+ "channel_id": channel,
+ "mode": mode,
+ "lang": lang,
+ "query": query,
+ },
+ "captured_events": [],
+ "response": None,
+ "error": None,
+ }
+
+ async def _noop_checkpoint():
+ pass
+
+ async def _noop_load_user_rails(self_):
+ pass
+
+ with mock.patch.object(
+ JiuWenClawDeepAdapter, "set_checkpoint", staticmethod(_noop_checkpoint)
+ ), mock.patch.object(
+ JiuWenClawDeepAdapter, "load_user_rails", _noop_load_user_rails
+ ), mock.patch.dict("os.environ", {"BROWSER_RUNTIME_MCP_ENABLED": "true"}):
+ adapter = JiuWenClawDeepAdapter()
+ try:
+ await adapter.create_instance()
+ response = await adapter.process_message_impl(request, inputs)
+ result["response"] = {
+ "ok": response.ok,
+ "payload": _json_safe(response.payload),
+ }
+ except Exception as exc:
+ result["error"] = repr(exc)
+
+ result["captured_events"] = prompt_capture.events
+ _write_outputs(result)
+
+ # Assertions
+ assert result["error"] is None, f"运行时出错: {result['error']}"
+ assert len(prompt_capture.events) >= 1, "未捕获到任何 LLM_INPUT 事件"
+ first_event = prompt_capture.events[0]
+ assert len(first_event["system_messages"]) > 0, "system messages 为空"
+
+ logger.info("捕获到 %d 个 model call 事件", len(prompt_capture.events))
+ logger.info("第一个事件的 system message 长度: %d 字符", sum(len(m) for m in first_event['system_messages']))
+ logger.info("输出文件: %s", OUTPUT_DIR / 'system_prompt_live_capture.txt')
diff --git a/tests/test_agentserver_cron_tool_injection.py b/tests/test_agentserver_cron_tool_injection.py
deleted file mode 100644
index e1f5f5978e..0000000000
--- a/tests/test_agentserver_cron_tool_injection.py
+++ /dev/null
@@ -1,67 +0,0 @@
-import os
-import tempfile
-import unittest
-
-
-_TMP_HOME = tempfile.mkdtemp(prefix="jiuwenclaw-test-home-")
-os.environ["HOME"] = _TMP_HOME
-
-from jiuwenclaw.agentserver.interface import JiuWenClaw
-
-
-class _FakeCronBackend:
- async def list_jobs(self, *, include_disabled: bool = True) -> list[dict]:
- return []
-
- async def get_job(self, job_id: str) -> dict | None:
- return None
-
- async def create_job(self, params: dict, *, context=None) -> dict:
- return params
-
- async def update_job(self, job_id: str, patch: dict, *, context=None) -> dict:
- return {"job_id": job_id, **patch}
-
- async def delete_job(self, job_id: str) -> bool:
- return True
-
- async def toggle_job(self, job_id: str, enabled: bool) -> dict:
- return {"job_id": job_id, "enabled": enabled}
-
- async def preview_job(self, job_id: str, count: int = 5) -> list[dict]:
- return []
-
- async def run_now(self, job_id: str) -> str:
- return "run-id"
-
- async def status(self) -> dict:
- return {"ok": True}
-
- async def get_runs(self, job_id: str, limit: int = 20) -> list[dict]:
- return []
-
- async def wake(self, text: str, *, context=None, mode: str | None = None) -> dict:
- return {"text": text, "mode": mode}
-
-
-class _TestableJiuWenClaw(JiuWenClaw):
- def set_cron_backend(self, backend: object) -> None:
- self._cron_runtime.set_backend(backend)
-
- def build_cron_tools(self) -> list[object]:
- return self._build_cron_tools()
-
-
-class AgentServerCronToolInjectionTests(unittest.TestCase):
- def test_build_cron_tools_uses_runtime_bridge_backend(self):
- agent = _TestableJiuWenClaw()
-
- agent.set_cron_backend(_FakeCronBackend())
- tools = agent.build_cron_tools()
-
- self.assertGreaterEqual(len(tools), 1)
- self.assertEqual(tools[0].card.name, "cron")
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/ui_e2e/cron_ui_report.py b/tests/ui_e2e/cron_ui_report.py
index 09eafaa80d..1d83c05043 100644
--- a/tests/ui_e2e/cron_ui_report.py
+++ b/tests/ui_e2e/cron_ui_report.py
@@ -307,62 +307,6 @@ async def _read_tool_executions(page: Page) -> list[dict[str, str]]:
)
-async def _create_structured_job_from_chat(
- page: Page,
- *,
- backend_port: int,
- report_dir: Path,
- name: str,
-) -> tuple[dict[str, Any], list[dict[str, str]], str]:
- await _open_chat_panel(page)
- agent_mode = page.locator('[data-testid="chat-mode-agent"]')
- await agent_mode.click()
-
- deadline = time.time() + 10
- while time.time() < deadline:
- classes = await agent_mode.get_attribute("class") or ""
- if "chat-mode-btn--active" in classes:
- break
- await asyncio.sleep(0.2)
-
- prompt = "\n".join(
- [
- "Create exactly one reminder using the unified tool named `cron`.",
- "Do not use `cron_create_job` or any other legacy `cron_*` tool.",
- f'Use name "{name}".',
- 'Use schedule {"kind":"every","everyMs":120000}.',
- 'Use payload {"kind":"systemEvent","text":"2 minute structured reminder smoke from chat"}.',
- 'Use sessionTarget "current" and wakeMode "now".',
- "After the tool call succeeds, reply with one short confirmation sentence.",
- ]
- )
- await page.locator('[data-testid="chat-input"]').fill(prompt)
- await page.locator('[data-testid="chat-send"]').click()
-
- created_job: dict[str, Any] | None = None
- tool_executions: list[dict[str, str]] = []
- wait_deadline = time.time() + 180
- while time.time() < wait_deadline:
- tool_executions = await _read_tool_executions(page)
- created_job = await _find_job_by_name(backend_port, name)
- if created_job is not None and tool_executions:
- break
- await asyncio.sleep(1)
-
- if created_job is None:
- raise RuntimeError(f"Structured job `{name}` was not created from chat in time")
-
- settle_deadline = time.time() + 20
- while time.time() < settle_deadline:
- tool_executions = await _read_tool_executions(page)
- if any(item["name"] == "cron" and item["status"] == "completed" for item in tool_executions):
- break
- await asyncio.sleep(0.5)
-
- screenshot_chat = await _screenshot(page, report_dir, "03-structured-chat-created.png")
- return created_job, tool_executions, screenshot_chat
-
-
def _write_report(report_dir: Path, context: ReportContext, cases: list[CaseResult]) -> Path:
report_path = report_dir / "report.md"
lines = [
@@ -433,7 +377,6 @@ async def _run_ui_flow_impl(
await _open_cron_panel(page)
legacy_name = f"{case_prefix}-legacy"
- structured_name = f"{case_prefix}-structured"
await page.locator('[data-testid="cron-create-toggle"]').click()
await page.locator('[data-testid="cron-create-name"]').fill(legacy_name)
@@ -468,68 +411,6 @@ async def _run_ui_flow_impl(
)
)
- structured_job, structured_tools, screenshot_structured_chat = await _create_structured_job_from_chat(
- page,
- backend_port=backend_port,
- report_dir=report_dir,
- name=structured_name,
- )
- structured_job_id = str(structured_job.get("id") or "").strip() or None
- await _open_cron_panel(page)
- structured_row = page.locator(f'[data-cron-name="{structured_name}"]').first
- await structured_row.wait_for()
- if not structured_job_id:
- raise RuntimeError("Structured job id not found after chat creation")
- structured_hint = ""
- structured_hint_locator = page.locator(f'[data-testid="cron-hint-{structured_job_id}"]')
- if await structured_hint_locator.count():
- structured_hint = (await structured_hint_locator.text_content() or "").strip()
- await page.locator(f'[data-testid="cron-preview-action-{structured_job_id}"]').click()
- await page.locator(f'[data-testid="cron-preview-{structured_job_id}"]').wait_for()
- screenshot_structured = await _screenshot(page, report_dir, "04-structured-visible.png")
- structured_preview = await _preview_job(backend_port, structured_job_id, count=3)
- structured_target = str(structured_job.get("session_target") or "")
- structured_payload_kind = str(((structured_job.get("payload") or {}) if isinstance(structured_job.get("payload"), dict) else {}).get("kind") or "")
- structured_compat_mode = str(structured_job.get("compat_mode") or "")
- tool_summary = ", ".join(f'{item["name"]}:{item["status"]}' for item in structured_tools) or "no tool execution found"
- first_preview_at = ""
- first_preview_delta_seconds: float | None = None
- if structured_preview:
- first_preview_at = str((structured_preview[0] or {}).get("push_at") or "")
- first_preview_dt = _parse_iso_datetime(first_preview_at)
- if first_preview_dt is not None:
- first_preview_delta_seconds = (first_preview_dt - datetime.now(timezone.utc)).total_seconds()
- preview_ok = first_preview_delta_seconds is not None and 0 <= first_preview_delta_seconds <= 300
- hint_ok = all(
- token in structured_hint
- for token in ("systemEvent", f"session:{session_id}", "openclaw")
- )
- tool_ok = any(item["name"] == "cron" for item in structured_tools)
- results.append(
- CaseResult(
- name="Structured reminder created from chat, then observed in UI",
- status=(
- "PASS"
- if (
- structured_target == f"session:{session_id}"
- and structured_payload_kind == "systemEvent"
- and structured_compat_mode == "openclaw"
- and preview_ok
- and hint_ok
- and tool_ok
- )
- else "FAIL"
- ),
- details=(
- f"Chat created `{structured_name}` via tools [{tool_summary}]; "
- f"session_target=`{structured_target}`, payload.kind=`{structured_payload_kind}`, "
- f"compat_mode=`{structured_compat_mode}`, preview_at=`{first_preview_at or 'missing'}`, "
- f"cron_hint=`{structured_hint or 'missing'}`."
- ),
- screenshots=[screenshot_structured_chat, screenshot_structured],
- )
- )
-
await page.locator(f'[data-testid="cron-run-{legacy_job_id}"]').click()
await page.locator('[data-testid="cron-success"]').wait_for()
screenshot_run = await _screenshot(page, report_dir, "05-legacy-run-now.png")
@@ -556,15 +437,12 @@ async def _run_ui_flow_impl(
await page.locator(f'[data-testid="cron-delete-{legacy_job_id}"]').click()
await page.locator(f'[data-cron-name="{legacy_name}"]').wait_for(state="detached")
- if structured_job_id:
- await page.locator(f'[data-testid="cron-delete-{structured_job_id}"]').click()
- await page.locator(f'[data-cron-name="{structured_name}"]').wait_for(state="detached")
screenshot_cleanup = await _screenshot(page, report_dir, "07-cleanup.png")
results.append(
CaseResult(
name="Cleanup",
status="PASS",
- details=f"Deleted `{legacy_name}` and `{structured_name}` from the UI.",
+ details=f"Deleted `{legacy_name}` from the UI.",
screenshots=[screenshot_cleanup],
)
)