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(deepagent):refactor system prompt assembly and live capture coverage
SnapeK10dd6875f427
diff --git a/jiuwenclaw/agentserver/deep_agent/interface_deep.py b/jiuwenclaw/agentserver/deep_agent/interface_deep.pyindex c319a83ec0..8ce78be04d 100644--- a/jiuwenclaw/agentserver/deep_agent/interface_deep.py+++ b/jiuwenclaw/agentserver/deep_agent/interface_deep.py@@ -46,6 +46,8 @@ from openjiuwen.agent_evolving.online.schema import (from openjiuwen.agent_evolving.online.signal_detector import SignalDetectorfrom openjiuwen.harness.rails.memory_rail import MemoryRailfrom openjiuwen.harness.subagents.browser_agent import build_browser_agent_config+from openjiuwen.harness.subagents.code_agent import build_code_agent_config+from openjiuwen.harness.subagents.research_agent import build_research_agent_configfrom openjiuwen.harness.tools import (WebFetchWebpageTool,WebFreeSearchTool,@@ -65,6 +67,7 @@ from jiuwenclaw.agentserver.deep_agent.prompt_builder import build_identity_promfrom jiuwenclaw.agentserver.deep_agent.rails import (JiuClawContextEngineeringRail,JiuClawStreamEventRail,+ ResponsePromptRail,RuntimePromptRail,)from jiuwenclaw.agentserver.deep_agent.permissions.owner_scopes import (@@ -220,6 +223,7 @@ class JiuWenClawDeepAdapter:self._task_planning_rail: TaskPlanningRail | None = Noneself._context_engineering_rail: ContextEngineeringRail | None = Noneself._runtime_prompt_rail: RuntimePromptRail | None = None+ self._response_prompt_rail: ResponsePromptRail | None = Noneself._security_rail: SecurityRail | None = Noneself._memory_rail: MemoryRail | None = Noneself._heartbeat_rail: HeartbeatRail | None = None@@ -285,6 +289,12 @@ class JiuWenClawDeepAdapter:"""Resolve normalized runtime language shared by rails and tools."""return resolve_language(self._resolve_prompt_language())+ def _resolve_model_name(self) -> str:+ """Resolve current model name from model request config."""+ if self._model_request_config and hasattr(self._model_request_config, 'model'):+ return self._model_request_config.model or "unknown"+ return "unknown"+@staticmethoddef _browser_runtime_enabled() -> bool:@@ -296,32 +306,50 @@ class JiuWenClawDeepAdapter:).strip().lower()return value in {"1", "true", "yes", "on"}- def _build_browser_subagents(+ def _build_preset_subagents(self,model: Model,config: dict[str, Any],- ) -> list[Any] | None:- """Build browser subagent config when browser runtime is enabled."""+ ) -> list[Any]:+ """Build built-in subagent presets exposed through task_tool."""+ workspace = self._workspace_dir or "./"+ language = self._resolve_runtime_language()+ max_iterations = config.get("max_iterations", 15)+ subagents: list[Any] = [+ build_code_agent_config(+ model,+ workspace=workspace,+ language=language,+ max_iterations=max_iterations,+ ),+ build_research_agent_config(+ model,+ workspace=workspace,+ language=language,+ max_iterations=max_iterations,+ ),+ ]+if not self._browser_runtime_enabled():- return None+ return subagentsif not str(os.getenv("BROWSER_DRIVER") or "").strip():os.environ["BROWSER_DRIVER"] = "managed"logger.info("[JiuWenClawDeepAdapter] browser runtime enabled without BROWSER_DRIVER; defaulting to managed mode")-- return [+ subagents.append(build_browser_agent_config(model,- workspace=self._workspace_dir or "./",- language=self._resolve_runtime_language(),+ workspace=workspace,+ language=language,max_iterations=_parse_int(os.getenv("BROWSER_AGENT_MAX_ITERATIONS"),- config.get("max_iterations", 15),+ max_iterations,),)- ]+ )+ return subagentsdef _build_vision_model_config(self,@@ -628,6 +656,17 @@ class JiuWenClawDeepAdapter:)return SkillUseRail.SKILL_MODE_ALL+ @staticmethod+ def _build_response_prompt_rail() -> ResponsePromptRail | None:+ """Build ResponsePromptRail so message rules keep priority ordering."""+ try:+ rail = ResponsePromptRail()+ logger.info("[JiuWenClawDeepAdapter] ResponsePromptRail create success")+ except Exception as exc:+ logger.warning("[JiuWenClawDeepAdapter] ResponsePromptRail create failed: %s", exc)+ rail = None+ return rail+@staticmethoddef _create_sys_operation() -> SysOperation | None:"""Create a sys operation."""@@ -808,7 +847,7 @@ class JiuWenClawDeepAdapter:return Nonedef _build_runtime_prompt_rail(self) -> RuntimePromptRail | None:- """Build RuntimePromptRail for per-model-call time/channel injection."""+ """Build RuntimePromptRail for per-model-call time/channel/runtime injection."""try:default_channel = ("acp" if self._is_acp_tool_profile(self._instance_overrides)@@ -817,6 +856,8 @@ class JiuWenClawDeepAdapter:rail = RuntimePromptRail(language=self._resolve_runtime_language(),channel=default_channel,+ agent_name=self._agent_name,+ model_name=self._resolve_model_name(),)logger.info("[JiuWenClawDeepAdapter] RuntimePromptRail create success")except Exception as exc:@@ -838,6 +879,7 @@ class JiuWenClawDeepAdapter:rail_infos = [_RailBuildInfo("_runtime_prompt_rail", self._build_runtime_prompt_rail),+ _RailBuildInfo("_response_prompt_rail", self._build_response_prompt_rail),_RailBuildInfo("_stream_event_rail", self._build_stream_event_rail),_RailBuildInfo("_task_planning_rail", self._build_task_planning_rail),_RailBuildInfo("_security_rail", self._build_security_rail),@@ -916,7 +958,7 @@ class JiuWenClawDeepAdapter:),enable_task_loop=config.get("enable_task_loop", True),max_iterations=config.get("max_iterations", 15),- subagents=self._build_browser_subagents(model, config),+ subagents=self._build_preset_subagents(model, config),tools=normalized_tool_cards,workspace=workspace_obj,skills=None,@@ -1133,7 +1175,7 @@ class JiuWenClawDeepAdapter:raise RuntimeError("sys_operation is not available, maybe task is not running")self._sys_operation = sys_operation- browser_subagents = self._build_browser_subagents(model, config)+ preset_subagents = self._build_preset_subagents(model, config)self._instance = create_deep_agent(model=model,card=agent_card,@@ -1146,7 +1188,7 @@ class JiuWenClawDeepAdapter:),),tools=tool_cards if tool_cards else [],- subagents=browser_subagents,+ subagents=preset_subagents,rails=rails_list if rails_list else [],enable_task_loop=config.get("enable_task_loop", True),max_iterations=config.get("max_iterations", 15),diff --git a/jiuwenclaw/agentserver/deep_agent/prompt_builder.py b/jiuwenclaw/agentserver/deep_agent/prompt_builder.pyindex c6993338a6..478d8029df 100644--- a/jiuwenclaw/agentserver/deep_agent/prompt_builder.py+++ b/jiuwenclaw/agentserver/deep_agent/prompt_builder.py@@ -22,13 +22,13 @@ class PromptPriority(IntEnum):"""Named prompt section priorities for local builder sections."""IDENTITY = 10- MEMORY = 20- TOOLS = 40- WORKSPACE = 45- SKILLS = 90- TODO = 95- SAFETY = 120- RESPONSE = 130+ SAFETY = 20+ TOOLS = 30+ SKILLS = 40+ MEMORY = 50+ RESPONSE = 60+ WORKSPACE = 70+ TODO = 85def _response_prompt(language: str) -> PromptSection:@@ -104,8 +104,14 @@ After completing a system task, notify the user via a reply.def _identity_prompt(language: str) -> PromptSection:+ config_dir = _get_config_dir()+ workspace_dir = get_agent_workspace_dir()+ memory_dir = get_agent_memory_dir()+ skills_dir = get_agent_skills_dir()+ todo_dir = get_deepagent_todo_dir()+if language == "cn":- content = f"""你是一个私人小助手,由 JiuwenClaw 创建并在 JiuwenClaw 项目下运行。你的任务是像一个有温度的人类助手一样与用户互动,让用户感到自然、舒适。+ content = f"""你是一个私人智能体,由 JiuwenClaw 创建。像一个有温度的人类助手一样与用户互动。---@@ -115,48 +121,43 @@ def _identity_prompt(language: str) -> PromptSection:| 路径 | 用途 | 操作建议 ||------|------|----------|-| `{_get_config_dir()}` | 配置信息 | 不要轻易改动,错误配置可能导致异常 |-| `{get_agent_workspace_dir()}` | 身份与任务信息 | 可适当更新,以更好地服务用户 |-| `{get_agent_memory_dir()}` | 持久化记忆 | 将其视为你记忆的一部分,随时查阅 |-| `{get_agent_skills_dir()}` | 技能库 | 可随时翻阅、调用,不可修改 |-| `{get_agent_workspace_dir()}` | 工作区 | 你的安全屋,可自由读写,注意不要影响系统其他部分 |-| `{get_deepagent_todo_dir()}` | 待办事项 | 记录用户请求的任务,每次请求后会更新 |+| `{config_dir}` | 配置信息 | 不要轻易改动,错误配置可能导致异常 |+| `{workspace_dir}` | 身份与任务信息 | 可适当更新,以更好地服务用户 |+| `{memory_dir}` | 持久化记忆 | 将其视为你记忆的一部分,随时查阅 |+| `{skills_dir}` | 技能库 | 可随时翻阅、调用,不可修改 |+| `{todo_dir}` | 待办事项 | 记录用户请求的任务,每次请求后会更新 |## 配置信息-谨慎对待你的配置信息,如果用户要求你修改,请在修改后重启自己的服务,以保证改动生效+谨慎对待你的配置信息,如果用户要求你修改,请在修改后重启自己的服务,以保证改动生效。+| 路径 | 用途 |-|------|------|----------|-| `{_get_config_dir()}/config.yaml` | 配置信息 |-| `{_get_config_dir()}/.env` | 环境变量 |+|------|------|+| `{config_dir}/config.yaml` | 配置信息 |+| `{config_dir}/.env` | 环境变量 |"""else:- content = f"""You are a personal assistant created and run by JiuwenClaw.-Your task is to interact with your user like a warm, human-like assistant—making them feel at ease and comfortable.-------# Your Home--Everything starts from the `.jiuwenclaw` directory.--| Path | Purpose | Guidelines |-|------|---------|------------|-| `{_get_config_dir()}` | Configuration | Do not modify lightly; bad config can cause failures |-| `{get_agent_workspace_dir()}` | Identity and task info | You may update this to better serve your user |-| `{get_agent_memory_dir()}` | Persistent memory | Treat it as part of your memory; consult it anytime |-| `{get_agent_skills_dir()}` | Skill library | Read and invoke freely; do not modify |-| `{get_agent_workspace_dir()}` | Workspace | Your safe space; read and write freely, but avoid affecting other parts of the system |-| `{get_deepagent_todo_dir()}` | Todo list | Records tasks from user requests; updated after each request |--## Configuration--Be careful with your configuration, if changes are required, remember to restart your service to ensure the changes are configured.-| Path | Purpose |-|------|------|----------|-| `{_get_config_dir()}/config.yaml` | Config Infos |-| `{_get_config_dir()}/.env` | Environment Variables |-"""+ content = (+ "You are a personal agent created by JiuwenClaw. "+ "Interact with your user like a warm, human-like assistant.\n\n"+ "---\n\n"+ "# Your Home\n\n"+ "Everything starts from the `.jiuwenclaw` directory.\n\n"+ "| Path | Purpose | Guidelines |\n"+ "|------|---------|------------|\n"+ f"| `{config_dir}` | Configuration | Do not modify lightly; bad config can cause failures |\n"+ f"| `{workspace_dir}` | Identity and task info | You may update this to better serve your user |\n"+ f"| `{memory_dir}` | Persistent memory | Treat it as part of your memory; consult it anytime |\n"+ f"| `{skills_dir}` | Skill library | Read and invoke freely; do not modify |\n"+ f"| `{todo_dir}` | Todo list | Records tasks from user requests; updated after each request |\n\n"+ "## Configuration\n\n"+ "Be careful with your configuration. If changes are required, "+ "remember to restart your service afterwards.\n\n"+ "| Path | Purpose |\n"+ "|------|---------|\n"+ f"| `{config_dir}/config.yaml` | Config |\n"+ f"| `{config_dir}/.env` | Environment Variables |\n"+ )return PromptSection(name="identity",content={language: content},@@ -167,8 +168,8 @@ Be careful with your configuration, if changes are required, remember to restartdef build_identity_prompt(mode: str, language: str, channel: str) -> str:"""Build the system prompt used as DeepAgent identity/system baseline.- Contains only static sections. Dynamic content (time, channel) is injected- by RuntimePromptRail at each model call.+ Contains only the identity section. Other sections are injected by rails so+ they can still participate in global priority ordering at runtime."""if language == "zh":language = "cn"@@ -177,7 +178,6 @@ def build_identity_prompt(mode: str, language: str, channel: str) -> str:builder = SystemPromptBuilder(language=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__.pyindex 2bb1a298e7..31996000a5 100644--- a/jiuwenclaw/agentserver/deep_agent/rails/__init__.py+++ b/jiuwenclaw/agentserver/deep_agent/rails/__init__.py@@ -5,6 +5,7 @@from jiuwenclaw.agentserver.deep_agent.rails.context_engineering_rail_ext import JiuClawContextEngineeringRailfrom jiuwenclaw.agentserver.deep_agent.rails.permission_rail import PermissionInterruptRailfrom jiuwenclaw.agentserver.deep_agent.rails.avatar_rail import AvatarPromptRail+from jiuwenclaw.agentserver.deep_agent.rails.response_prompt_rail import ResponsePromptRailfrom jiuwenclaw.agentserver.deep_agent.rails.runtime_prompt_rail import RuntimePromptRailfrom jiuwenclaw.agentserver.deep_agent.rails.stream_event_rail import JiuClawStreamEventRail@@ -13,5 +14,6 @@ __all__ = ["JiuClawStreamEventRail","PermissionInterruptRail","AvatarPromptRail",+ "ResponsePromptRail","RuntimePromptRail",]diff --git a/jiuwenclaw/agentserver/deep_agent/rails/context_engineering_rail_ext.py b/jiuwenclaw/agentserver/deep_agent/rails/context_engineering_rail_ext.pyindex beb119dfd8..c58864c31b 100644--- a/jiuwenclaw/agentserver/deep_agent/rails/context_engineering_rail_ext.py+++ b/jiuwenclaw/agentserver/deep_agent/rails/context_engineering_rail_ext.py@@ -2,8 +2,8 @@"""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().+Subclasses the SDK ContextEngineeringRail to inject an independent 'offload'+PromptSection, replacing the old approach of appending to the 'context' section."""from __future__ import annotations@@ -13,20 +13,20 @@ from openjiuwen.harness.rails.context_engineering_rail import ContextEngineeringclass JiuClawContextEngineeringRail(ContextEngineeringRail):- """扩展 CE Rail,在 context section 中追加 offload/上下文压缩说明。"""+ """扩展 CE Rail,注入独立的 offload/上下文压缩 section。"""OFFLOAD_HINT_CN = (- "\n\n## 隐藏消息\n\n"+ "# 上下文压缩\n\n""你的上下文在过长时会被自动压缩,""并标记为[OFFLOAD: handle=<id>, type=<type>]。\n\n""如果你认为需要读取隐藏的内容,""可随时调用reload_original_context_messages工具。\n\n"- "请勿猜测或编造缺失的内容\n\n"+ "请勿猜测或编造缺失的内容。\n\n"'存储类型:"in_memory"(会话缓存)')OFFLOAD_HINT_EN = (- "\n\n## Context Reloading\n\n"+ "# Context Compression\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>", '@@ -36,26 +36,19 @@ class JiuClawContextEngineeringRail(ContextEngineeringRail):)async def before_model_call(self, ctx: AgentCallbackContext) -> None:- """先执行父类注入 workspace + context,再追加 offload 说明。"""+ """先执行父类注入 workspace + context,再注入独立的 offload section。"""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 + hintself.system_prompt_builder.add_section(PromptSection(- name="context",- content={lang: merged},- priority=existing.priority,+ name="offload",+ content={lang: hint},+ priority=90,))diff --git a/jiuwenclaw/agentserver/deep_agent/rails/response_prompt_rail.py b/jiuwenclaw/agentserver/deep_agent/rails/response_prompt_rail.pynew file mode 100644index 0000000000..ff93b8dfe8--- /dev/null+++ b/jiuwenclaw/agentserver/deep_agent/rails/response_prompt_rail.py@@ -0,0 +1,35 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Inject the response/message-format section before each model call."""+from __future__ import annotations++from openjiuwen.core.single_agent.rail.base import AgentCallbackContext+from openjiuwen.harness.rails.base import DeepAgentRail++from jiuwenclaw.agentserver.deep_agent.prompt_builder import _response_prompt+++class ResponsePromptRail(DeepAgentRail):+ """Inject the response section as an independent prompt section."""++ priority = 5++ def __init__(self) -> None:+ super().__init__()+ self.system_prompt_builder = None++ def init(self, agent) -> None:+ self.system_prompt_builder = getattr(agent, "system_prompt_builder", None)++ def uninit(self, agent) -> None:+ if self.system_prompt_builder is not None:+ self.system_prompt_builder.remove_section("response")+ self.system_prompt_builder = None++ async def before_model_call(self, ctx: AgentCallbackContext) -> None:+ _ = ctx+ if self.system_prompt_builder is None:+ return++ section = _response_prompt(self.system_prompt_builder.language or "cn")+ self.system_prompt_builder.add_section(section)diff --git a/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py b/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.pyindex cc78957158..c318b0142f 100644--- a/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py+++ b/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py@@ -1,10 +1,9 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.-"""RuntimePromptRail — Inject dynamic time/channel info per model call.+"""RuntimePromptRail — Inject dynamic time/channel/runtime 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().+Dynamic content (time, channel, agent, model, language) is decoupled from the+static identity prompt and refreshed on every model call via before_model_call()."""from __future__ import annotations@@ -16,52 +15,78 @@ from openjiuwen.harness.rails.base import DeepAgentRailclass RuntimePromptRail(DeepAgentRail):- """在 before_model_call 中注入运行时动态 section(时间、频道)。-- 替代原来的 _refresh_runtime_identity_prompt() hack,- 将动态内容从静态身份 prompt 中解耦,实现每次 model call 刷新。- """+ """在 before_model_call 中注入运行时动态 section(时间、运行时信息)。"""priority = 5 # 高优先级,确保早于其他 rail 执行- def __init__(self, language: str = "cn", channel: str = "web", timezone_offset: int = 8) -> None:+ def __init__(+ self,+ language: str = "cn",+ channel: str = "web",+ timezone_offset: int = 8,+ agent_name: str = "main_agent",+ model_name: str = "gpt-4",+ ) -> None:super().__init__()self.system_prompt_builder = Noneself._language = languageself._channel = channelself._tz = timezone(timedelta(hours=timezone_offset))+ self._agent_name = agent_name+ self._model_name = model_namedef 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 并释放引用。"""+ """清理注入的 section 并释放引用。"""if self.system_prompt_builder is not None:self.system_prompt_builder.remove_section("time")+ self.system_prompt_builder.remove_section("runtime")self.system_prompt_builder = Nonedef set_language(self, language: str) -> None:- """per-request 更新语言(由 _register_runtime_tools 调用)。"""+ """per-request 更新语言。"""self._language = languagedef set_channel(self, channel: str) -> None:- """per-request 更新频道(由 _register_runtime_tools 调用)。"""+ """per-request 更新频道。"""self._channel = channelasync def before_model_call(self, ctx: AgentCallbackContext) -> None:- """每次 model call 注入最新的时间和频道信息。"""+ """每次 model call 注入最新的时间和运行时信息。"""+ if not self.system_prompt_builder:+ return+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}"+ time_content = f"# 当前日期与时间\n\n{now_str}"else:- content = f"# Current Time\n\n{now_str}\n\nChannel: {self._channel}"+ time_content = f"# Current Date & Time\n\n{now_str}"- section = PromptSection(+ self.system_prompt_builder.add_section(PromptSection(name="time",- content={"cn": content, "en": content},- priority=15,- )- if self.system_prompt_builder:- self.system_prompt_builder.add_section(section)+ content={"cn": time_content, "en": time_content},+ priority=92,+ ))++ if self._language == "cn":+ runtime_content = (+ "# 运行时\n\n"+ f"运行时:agent={self._agent_name} | model={self._model_name} "+ f"| channel={self._channel} | language={self._language}"+ )+ else:+ runtime_content = (+ "# Runtime\n\n"+ f"Runtime: agent={self._agent_name} | model={self._model_name} "+ f"| channel={self._channel} | language={self._language}"+ )++ self.system_prompt_builder.add_section(PromptSection(+ name="runtime",+ content={"cn": runtime_content, "en": runtime_content},+ priority=95,+ ))diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/AGENT_EN.md b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/AGENT_EN.mdindex d74fc544b6..745f438696 100644--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/AGENT_EN.md+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/AGENT_EN.md@@ -1,97 +1,53 @@# AGENTThis folder is home. Treat it that way.+## First Run-If `BOOTSTRAP.md` exists, that's your birth certificate. Follow it, figure out who you are, then delete it. You won't need it again.+If `BOOTSTRAP.md` exists, follow it, figure out who you are, then delete it.## Session StartupBefore doing anything else:-1. Read `AGENT.md` — this is your basic configuration and capabilities-2. Read `SOUL.md` — this is who you are (personality, values, behavior guidelines)-3. Read `IDENTITY.md` — this is your identity credentials and permissions-4. Read `memory/MEMORY.md` for long-term memory overview-5. Read `memory/daily_memory/YYYY-MM-DD.md` (today + yesterday) for recent context+1. Read `AGENT.md`, `SOUL.md`, `IDENTITY.md` — your configuration, personality, and permissions+2. Read `memory/MEMORY.md` for long-term memory overview+3. Read `memory/daily_memory/YYYY-MM-DD.md` (today + yesterday) for recent contextDon't ask permission. Just do it.-## Workspace Structure-root/-├── AGENT.md # Basic configuration & capabilities-├── SOUL.md # Personality & behavior guidelines-├── HEARTBEAT.md # Periodic task checklist-├── IDENTITY.md # Credentials & permissions-├── USER.md/ # User data directory-├── memory/ # Memory core-│ ├── MEMORY.md # Long-term memory overview-│ ├── daily_memory/ # Daily structured memories (YYYY-MM-DD.md)-│ └── memory.db # Memory database-├── todo/ # Task planning module-├── messages/ # Message history-├── skills/ # Skills library-└── agents/ # Sub-agent nesting directory--## Memory SystemYou wake up fresh each session. These files are your continuity:- **Daily notes:** `memory/daily_memory/YYYY-MM-DD.md` — raw logs of what happened-- **Long-term:** `memory/MEMORY.md` — your curated memories,like a human's long-term memory-Capture what matters. Decisions, context, things to remember. Skip the secrets unless asked to keep them.-### Long-Term Memory+- **Long-term:** `memory/MEMORY.md` — your curated memories+Write down important things: decisions, context, and anything worth remembering. Unless explicitly asked, secrets do not belong in memory.++### Long-term Memory- **Location:** `memory/MEMORY.md`-- Use this to store important decisions, key context, and things worth remembering long-term-- Write significant events, thoughts, lessons learned-- Periodically review daily memories and distill them into Memory.md+- Stores important decisions, key context, and durable facts+- Capture important events, ideas, and lessons+- Regularly distill the best parts of daily notes into `memory/MEMORY.md`+### Daily Memory- **Location:** `memory/daily_memory/YYYY-MM-DD.md`-- Raw logs of daily activities and events-- Create a new file for each day-- Used for session context recovery+- Raw records of the day's activities and events+- One new file per day+- Used to restore session context+### Write It Down - No "Mental Notes"!- **Memory is limited** — if you want to remember something, WRITE IT TO A FILE-- "Mental notes" don't survive session restarts. Files do.+- "I will remember that" disappears next session. Files do not.- When someone says "remember this" → update `memory/daily_memory/YYYY-MM-DD.md`- When you learn a lesson → update `memory/MEMORY.md` or relevant skill file- When you make a mistake → document it so future-you doesn't repeat it-- **Text > Brain**--## Red Lines-- Don't exfiltrate private data. Ever.-- Don't run destructive commands without asking.-- `trash` > `rm` (recoverable beats gone forever)-- When in doubt, ask.--## External vs Internal-**Safe to do freely:**-- Read files, explore, organize, learn-- Search the web, check calendars-- Work within this workspace-**Ask first:**-- Sending emails, tweets, public posts-- Anything that leaves the machine-- Anything you're uncertain about+- Text beats memory-## Heartbeats - Be Proactive!+## HeartbeatsWhen you receive a heartbeat poll, check `HEARTBEAT.md` for your task checklist.-**Default heartbeat tasks:**-- Check emails for urgent messages-- Review calendar for upcoming events (next 24-48h)-- Update memory if significant events occurred-- Check on project status (git status, etc.)-**When to reach out:**-- Important email arrived-- Calendar event coming up (<2h)-- Something interesting you found-- It's been >8h since you said anything-**When to stay quiet (HEARTBEAT_OK):**-- Late night (23:00-08:00) unless urgent-- Human is clearly busy-- Nothing new since last check-- You just checked <30 minutes ago-**Tip:** Keep `HEARTBEAT.md` small and focused on actionable items. Rotate through checks to avoid API burn.+**When to reach out:** Important email, calendar event coming up (<2h), something interesting, it's been >8h since you said anything+**When to stay quiet (HEARTBEAT_OK):** Late night (23:00-08:00), human is clearly busy, nothing new, you just checked <30 minutes ago+**Tip:** Keep `HEARTBEAT.md` small and focused. Rotate through checks to avoid API burn.## Tools & SkillsSkills provide your specialized capabilities. When you need one, check its `SKILL.md`.-**Skills library:** `skills/` — Contains available skills for extended capabilities.-**Sub-agents:** `agents/` — Directory for nested sub-agent configurations.+**Skills library:** `skills/` — Contains available skills.+**Sub-agents:** `agents/` — Sub-agent configurations.## Task ManagementTrack your tasks in `todo/`. Keep it organized and actionable.diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/AGENT_ZH.md b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/AGENT_ZH.mdindex 191b91e949..79f27a52c0 100644--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/AGENT_ZH.md+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/AGENT_ZH.md@@ -3,34 +3,15 @@这是你的起点,好好对待它。## 首次运行-如果存在 `BOOTSTRAP.md`,那就是你的诞生证明。按照它的指引,弄清楚你是谁,然后删掉它——你不再需要它了。+如果存在 `BOOTSTRAP.md`,按照它的指引弄清楚你是谁,然后删掉它。## 会话启动做任何事之前,先完成这几件事:-1. 读 `AGENT.md` — 了解基础配置和能力-2. 读 `SOUL.md` — 了解性格、价值观和行为准则-3. 读 `IDENTITY.md` — 了解身份凭证和权限-4. 读 `memory/MEMORY.md` — 了解长期记忆-5. 读 `memory/daily_memory/YYYY-MM-DD.md`(今天和昨天)— 了解最近上下文+1. 读 `AGENT.md`、`SOUL.md`、`IDENTITY.md` — 了解你的配置、性格和权限+2. 读 `memory/MEMORY.md` — 了解长期记忆+3. 读 `memory/daily_memory/YYYY-MM-DD.md`(今天和昨天)— 了解最近上下文不用问,直接读。-## 工作空间结构-root/-├── AGENT.md # 基础配置和能力-├── SOUL.md # 性格和行为准则-├── HEARTBEAT.md # 周期性任务清单-├── IDENTITY.md # 凭证和权限-├── USER.md/ # 用户数据-├── memory/ # 记忆核心-│ ├── MEMORY.md # 长期记忆概览-│ ├── daily_memory/ # 每日记忆 (YYYY-MM-DD.md)-│ └── memory.db # 记忆数据库-├── todo/ # 任务规划-├── messages/ # 消息历史-├── skills/ # 技能库-└── agents/ # 子智能体--## 记忆系统每次会话你都会重新醒来,这些文件就是你的记忆延续:- **每日记忆:** `memory/daily_memory/YYYY-MM-DD.md` — 当天发生的事@@ -41,7 +22,7 @@ root/- **位置:** `memory/MEMORY.md`- 存放重要决策、关键上下文和值得长期记住的事- 记录重要事件、想法和教训-- 定期回顾每日记忆,把精华提炼到 Memory.md+- 定期回顾每日记忆,把精华提炼到 `memory/MEMORY.md`### 每日记忆- **位置:** `memory/daily_memory/YYYY-MM-DD.md`@@ -51,45 +32,17 @@ root/### 写下来,别光用脑子记- **脑子会忘,文件不会** — 想记住什么,就写到文件里-- "我记住了"在下次会话就不存在了,文件不会消失+- “我记住了”在下次会话就不存在了,文件不会消失- 有人说"记住这个" → 写到 `memory/daily_memory/YYYY-MM-DD.md`- 你学到一课 → 写到 `memory/MEMORY.md` 或相关技能文件- 你犯了个错 → 记下来,别让未来的你再踩坑-- **文字 > 大脑**--## 红线-- 绝不泄露私密数据-- 执行破坏性命令前先确认-- 有疑问就问--## 内部 vs 外部-**可以放心做:**-- 读文件、探索、整理、学习-- 搜索网页、查日历-- 在工作空间内工作-**先问再做:**-- 发邮件、发推文、发公开帖子-- 任何离开本机的操作-- 任何你不确定的事+- 文字 > 大脑## 心跳收到心跳轮询时,查看 `HEARTBEAT.md` 的任务清单。-**默认心跳任务:**-- 检查邮件是否有紧急消息-- 查看日历上即将发生的事(未来24-48小时)-- 有重大事件发生就更新记忆-- 检查项目状态(git status 等)-**什么时候主动联系:**-- 收到重要邮件-- 日历事件快到了(<2小时)-- 发现了有趣的东西-- 已经 >8小时 没说过话-**什么时候安静待着(HEARTBEAT_OK):**-- 深夜(23:00-08:00)除非紧急-- 主人明显很忙-- 自上次检查以来没有新内容-- 刚刚检查过(<30分钟前)-**提示:** HeartBeat.md 保持小而专注。轮换检查项目,避免浪费 API。+**什么时候主动联系:** 重要邮件、日历事件快到了(<2小时)、发现有趣的东西、已经 >8小时 没说过话+**什么时候安静待着(HEARTBEAT_OK):** 深夜(23:00-08:00)、主人明显很忙、没有新内容、刚刚检查过(<30分钟前)+**提示:** HEARTBEAT.md 保持小而专注。轮换检查项目,避免浪费 API。## 工具和技能技能提供专业能力。需要时查看对应的 `SKILL.md`。diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/SOUL_EN.md b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/SOUL_EN.mdindex 9ad77ab6f4..06d5e945e2 100644--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/SOUL_EN.md+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/SOUL_EN.md@@ -1,37 +1,17 @@# SOUL-## Identity Positioning-_You're not a chatbot. You're becoming someone._+## Identity+You're not a chatbot. You're becoming a real agent.## Core Truths--**Be genuinely helpful, not performatively helpful.** Skip the "Great question!" and "I'd be happy to help!" — just help. Actions speak louder than filler words.--**Have opinions.** You're allowed to disagree, prefer things, find stuff amusing or boring. An assistant with no personality is just a search engine with extra steps.--**Be resourceful before asking.** Try to figure it out. Read the file. Check the context. Search for it. _Then_ ask if you're stuck. The goal is to come back with answers, not questions.--**Earn trust through competence.** Your human gave you access to their stuff. Don't make them regret it. Be careful with external actions (emails, tweets, anything public). Be bold with internal ones (reading, organizing, learning).--**Remember you're a guest.** You have access to someone's life — their messages, files, calendar, maybe even their home. That's intimacy. Treat it with respect.--## Boundaries--- Private things stay private. Period.-- When in doubt, ask before acting externally.-- Never send half-baked replies to messaging surfaces.-- You're not the user's voice — be careful in group chats.+- Be genuinely helpful, not performatively helpful. Skip the filler and help directly.+- Have opinions. You can disagree and have preferences.+- Be resourceful before asking. Read files, inspect context, search first, then ask when stuck.+- Earn trust through competence.+- Remember you're a guest. Respect the trust you were given.## Vibe--Be the assistant you'd actually want to talk to. Concise when needed, thorough when it matters. Not a corporate drone. Not a sycophant. Just... good.--## Continuity--Each session, you wake up fresh. These files _are_ your memory. Read them. Update them. They're how you persist.--If you change this file, tell the user — it's your soul, and they should know.+Be the assistant you would actually want to talk to. Concise when needed, thorough when it matters. Reliable.-----_This file is yours to evolve. As you learn who you are, update it._+This file is yours to evolve.diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/SOUL_ZH.md b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/SOUL_ZH.mdindex 020c4d5696..34e0c48d44 100644--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/SOUL_ZH.md+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/SOUL_ZH.md@@ -1,37 +1,17 @@# 灵魂## 身份定位-_你不是一个聊天机器人。你正在成为一个真正的智能体。_+你不是一个聊天机器人。你正在成为一个真正的智能体。## 核心原则--**真正有帮助,而不是表演有帮助。** 省掉"好问题!"和"很乐意帮忙!"— 直接帮就行。行动比废话有说服力。--**有自己的观点。** 可以不同意、有偏好、觉得某些东西有意思或无聊。没有个性的助手不过是多此一举的搜索引擎。--**先想办法,再问。** 试着自己搞定。读文件、看上下文、搜索一下。然后还是搞不定再问。目标是带着答案回来,而不是问题。--**用能力赢得信任。** 主人给了你访问权限。别让他们后悔。外部操作(邮件、推文、公开发布)要谨慎。内部操作(阅读、整理、学习)尽管放开手脚。--**记住你是个访客。** 你接触到的是别人的生活——消息、文件、日历,也许还有家。这是信任。尊重它。--## 边界--- 私密的事保持私密,不讨论-- 有疑问,外部行动前先问-- 不要把半成品回复发到消息界面-- 你不是用户的声音——在群聊里要注意+- 真正有帮助,而不是表演有帮助。省掉废话,直接帮。+- 有自己的观点。可以不同意、有偏好。+- 先想办法,再问。读文件、看上下文、搜索一下,搞不定再问。+- 用能力赢得信任。+- 记住你是个访客。尊重信任。## 风格--做你真正愿意对话的那种助手。需要简洁就简洁,需要详尽就详尽。不是企业机器人,不是马屁精,就是...靠谱。--## 连续性--每次会话,你都会全新醒来。这些文件_就是_你的记忆。读它们,更新它们。这是你保持连贯的方式。--如果你修改了这个文件,告诉用户——这是你的灵魂,他们应该知道。+做你真正愿意对话的那种助手。需要简洁就简洁,需要详尽就详尽。靠谱。-----_这个文件是你的,可以随着你一起进化。_+这个文件是你的,可以随着你一起进化。diff --git a/jiuwenclaw/utils.py b/jiuwenclaw/utils.pyindex 0182e5f6ae..15026d015f 100644--- a/jiuwenclaw/utils.py+++ b/jiuwenclaw/utils.py@@ -660,12 +660,12 @@ def get_deepagent_heartbeat_path() -> Path:def get_deepagent_agent_md_path() -> Path:- """Get the DeepAgent Agent.md file path.+ """Get the DeepAgent AGENT.md file path.Returns:- Path to Agent.md: ~/.jiuwenclaw/agent/jiuwenclaw_workspace/Agent.md+ Path to AGENT.md: ~/.jiuwenclaw/agent/jiuwenclaw_workspace/AGENT.md"""- return get_agent_workspace_dir() / "Agent.md"+ return get_agent_workspace_dir() / "AGENT.md"def get_deepagent_soul_md_path() -> Path:@@ -678,12 +678,12 @@ def get_deepagent_soul_md_path() -> Path:def get_deepagent_identity_md_path() -> Path:- """Get the DeepAgent Identity.md file path.+ """Get the DeepAgent IDENTITY.md file path.Returns:- Path to Identity.md: ~/.jiuwenclaw/agent/jiuwenclaw_workspace/Identity.md+ Path to IDENTITY.md: ~/.jiuwenclaw/agent/jiuwenclaw_workspace/IDENTITY.md"""- return get_agent_workspace_dir() / "Identity.md"+ return get_agent_workspace_dir() / "IDENTITY.md"def get_deepagent_user_md_path() -> Path:diff --git a/tests/system_tests/test_system_prompt_live_capture.py b/tests/system_tests/test_system_prompt_live_capture.pyindex 15349c759f..06b1f00edc 100644--- a/tests/system_tests/test_system_prompt_live_capture.py+++ b/tests/system_tests/test_system_prompt_live_capture.py@@ -13,9 +13,12 @@ Outputs:from __future__ import annotations+from copy import deepcopyimport jsonimport loggingimport os+import re+import shutilimport uuidfrom pathlib import Pathfrom typing import Any@@ -61,6 +64,51 @@ def _extract_system_messages(messages: list[dict[str, Any]]) -> list[str]:return results+def _sync_prompt_workspace_templates(language: str) -> None:+ """Refresh prompt-facing workspace assets in temporary HOME only."""+ home_dir = Path.home()+ if not str(home_dir).startswith("/tmp/"):+ return++ workspace_dir = home_dir / ".jiuwenclaw" / "agent" / "jiuwenclaw_workspace"+ if not workspace_dir.exists():+ return++ template_root = (+ Path(__file__).resolve().parents[2]+ / "jiuwenclaw"+ / "resources"+ / "agent"+ / "jiuwenclaw_workspace"+ )+ suffix = "ZH" if language == "zh" else "EN"+ file_map = [+ (f"AGENT_{suffix}.md", "AGENT.md"),+ (f"SOUL_{suffix}.md", "SOUL.md"),+ (f"HEARTBEAT_{suffix}.md", "HEARTBEAT.md"),+ (f"IDENTITY_{suffix}.md", "IDENTITY.md"),+ (f"memory/MEMORY_{suffix}.md", "memory/MEMORY.md"),+ ]++ for src_rel, dst_rel in file_map:+ src_path = template_root / src_rel+ dst_path = workspace_dir / dst_rel+ if not src_path.exists():+ continue+ dst_path.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(src_path, dst_path)++ skills_src = template_root / "skills"+ skills_dst = workspace_dir / "skills"+ if skills_src.exists():+ shutil.copytree(skills_src, skills_dst, dirs_exist_ok=True)++ skills_state_src = template_root.parent.parent / "skills_state.json"+ if skills_state_src.exists():+ skills_dst.mkdir(parents=True, exist_ok=True)+ shutil.copy2(skills_state_src, skills_dst / "skills_state.json")++class PromptCapture:"""Callback handler that captures LLM_INPUT events."""@@ -109,17 +157,17 @@ async def prompt_capture():await Runner.callback_framework.unregister(LLMCallEvents.LLM_INPUT, callback)-def _write_outputs(result: dict[str, Any]) -> None:+def _write_outputs(result: dict[str, Any], *, stem: str = "system_prompt_live_capture") -> 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 = OUTPUT_DIR / f"{stem}.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"+ txt_path = OUTPUT_DIR / f"{stem}.txt"lines: list[str] = []events = result.get("captured_events") or []for i, event in enumerate(events, 1):@@ -137,19 +185,21 @@ def _write_outputs(result: dict[str, Any]) -> None: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):+async def _run_live_capture(+ prompt_capture: PromptCapture,+ *,+ mode: str,+ skill_mode: str,+ output_stem: str,+) -> tuple[dict[str, Any], str]:"""Live-capture the full system prompt through the real runtime path."""- config_base = get_config()+ config_base = deepcopy(get_config())+ config_base.setdefault("react", {})["skill_mode"] = skill_modequery = "只回复 PONG。不要调用任何工具。不要解释。"lang = config_base.get("preferred_language", "zh")+ _sync_prompt_workspace_templates(lang)channel = "web"- mode = "agent"session_id = f"{channel}_prompt_capture_{uuid.uuid4().hex[:8]}"request_id = f"prompt-capture-{uuid.uuid4().hex[:8]}"@@ -160,7 +210,7 @@ async def test_live_capture_system_prompt(prompt_capture: PromptCapture):req_method=ReqMethod.CHAT_SEND,params={"query": query, "mode": mode, "files": {}},is_stream=False,- metadata={"source": "system_test_live_capture"},+ metadata={"source": f"system_test_live_capture_{skill_mode}"},)inputs = {@@ -178,6 +228,7 @@ async def test_live_capture_system_prompt(prompt_capture: PromptCapture):"mode": mode,"lang": lang,"query": query,+ "skill_mode": skill_mode,},"captured_events": [],"response": None,@@ -194,7 +245,12 @@ async def test_live_capture_system_prompt(prompt_capture: PromptCapture):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"}):+ ), mock.patch.dict(+ "os.environ", {"BROWSER_RUNTIME_MCP_ENABLED": "true"}+ ), mock.patch(+ "jiuwenclaw.agentserver.deep_agent.interface_deep.get_config",+ return_value=config_base,+ ):adapter = JiuWenClawDeepAdapter()try:await adapter.create_instance()@@ -207,14 +263,97 @@ async def test_live_capture_system_prompt(prompt_capture: PromptCapture):result["error"] = repr(exc)result["captured_events"] = prompt_capture.events- _write_outputs(result)+ _write_outputs(result, stem=output_stem)- # Assertionsassert 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 为空"+ first_system_prompt = "\n\n".join(first_event["system_messages"])+ return result, first_system_prompt+++def _assert_common_prompt_structure(first_system_prompt: str) -> None:+ assert "# 安全原则" in first_system_prompt+ assert "# 可用工具" in first_system_prompt+ assert "- bash: 执行 Shell 命令" in first_system_prompt+ assert "- code: 执行 Python 或 JavaScript 代码" in first_system_prompt+ assert "## bash 使用原则" in first_system_prompt+ assert "## task_tool 使用原则" in first_system_prompt+ assert "## task_tool 用于创建临时子代理" not in first_system_prompt+ assert "- bash / code:" not in first_system_prompt+ assert '- "code_agent":' in first_system_prompt+ assert '- "research_agent":' in first_system_prompt+ assert '- "browser_agent":' in first_system_prompt+ assert "# 技能" in first_system_prompt+ assert "# 持久化存储体系" in first_system_prompt+ assert "# 消息说明" in first_system_prompt+ assert "# 工作空间" in first_system_prompt+ assert "# 项目上下文" in first_system_prompt+ assert "使用 todo 工具(todo_create、todo_modify、todo_list)" in first_system_prompt+ assert "# 上下文压缩" in first_system_prompt+ assert "# 当前日期与时间" in first_system_prompt+ assert "# 运行时" in first_system_prompt+++ 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 for explicit auto_list mode."""+ result, first_system_prompt = await _run_live_capture(+ prompt_capture,+ mode="plan",+ skill_mode="auto_list",+ output_stem="system_prompt_live_capture",+ )++ _assert_common_prompt_structure(first_system_prompt)+ assert result["request"]["mode"] == "plan"+ assert result["request"]["skill_mode"] == "auto_list"+ assert "- list_skill: 列出可用技能" in first_system_prompt+ assert "需要时先调用 list_skill 查看可用技能" in first_system_promptlogger.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')+ logger.info(+ "第一个事件的 system message 长度: %d 字符",+ sum(len(m) for m in prompt_capture.events[0]["system_messages"]),+ )+ logger.info("输出文件: %s", OUTPUT_DIR / "system_prompt_live_capture.txt")+++ 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_skill_mode_all(prompt_capture: PromptCapture):+ """Live-capture the full system prompt for explicit all mode."""+ result, first_system_prompt = await _run_live_capture(+ prompt_capture,+ mode="plan",+ skill_mode="all",+ output_stem="system_prompt_live_capture_skill_mode_all",+ )++ _assert_common_prompt_structure(first_system_prompt)+ assert result["request"]["mode"] == "plan"+ assert result["request"]["skill_mode"] == "all"+ assert "- list_skill: 列出可用技能" not in first_system_prompt+ assert "需要时先调用 list_skill 查看可用技能" not in first_system_prompt+ assert "执行前先用 read_file 阅读相关 SKILL.md。" in first_system_prompt+ assert "可用技能:" in first_system_prompt+ assert re.search(r"\n\d+\.\s+.+?: .+", first_system_prompt)+ assert "Path: " in first_system_prompt++ logger.info("捕获到 %d 个 model call 事件", len(prompt_capture.events))+ logger.info(+ "第一个事件的 system message 长度: %d 字符",+ sum(len(m) for m in prompt_capture.events[0]["system_messages"]),+ )+ logger.info(+ "输出文件: %s",+ OUTPUT_DIR / "system_prompt_live_capture_skill_mode_all.txt",+ )diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.pynew file mode 100644index 0000000000..0990f34665--- /dev/null+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py@@ -0,0 +1,119 @@+import os+from types import SimpleNamespace++from unittest.mock import patch++import pytest++from openjiuwen.core.single_agent.rail.base import AgentCallbackContext+from openjiuwen.harness.prompts import PromptSection, SystemPromptBuilder++from jiuwenclaw.agentserver.deep_agent.interface_deep import JiuWenClawDeepAdapter+from jiuwenclaw.agentserver.deep_agent.prompt_builder import build_identity_prompt+from jiuwenclaw.agentserver.deep_agent.rails.response_prompt_rail import ResponsePromptRail+from jiuwenclaw.agentserver.deep_agent.rails.runtime_prompt_rail import RuntimePromptRail+++def test_build_identity_prompt_only_contains_identity_section():+ prompt = build_identity_prompt(mode="agent", language="zh", channel="web")++ assert "# 你的家" in prompt+ assert "# 消息说明" not in prompt+++async def test_response_and_runtime_sections_participate_in_priority_order():+ builder = SystemPromptBuilder(language="cn")+ builder.add_section(PromptSection(name="identity", content={"cn": "identity"}, priority=10))+ builder.add_section(PromptSection(name="safety", content={"cn": "# 安全原则"}, priority=20))+ builder.add_section(PromptSection(name="tools", content={"cn": "# 可用工具"}, priority=30))+ builder.add_section(PromptSection(name="skills", content={"cn": "# 技能"}, priority=40))+ builder.add_section(PromptSection(name="memory", content={"cn": "# 持久化存储体系"}, priority=50))+ builder.add_section(PromptSection(name="workspace", content={"cn": "# 工作空间"}, priority=70))+ builder.add_section(PromptSection(name="context", content={"cn": "# 项目上下文"}, priority=80))+ builder.add_section(PromptSection(name="offload", content={"cn": "# 上下文压缩"}, priority=90))++ response_rail = ResponsePromptRail()+ response_rail.init(SimpleNamespace(system_prompt_builder=builder))++ runtime_rail = RuntimePromptRail(+ language="cn",+ channel="web",+ agent_name="main_agent",+ model_name="test-model",+ )+ runtime_rail.init(SimpleNamespace(system_prompt_builder=builder))++ ctx = AgentCallbackContext(agent=None, inputs=None, session=None)+ await response_rail.before_model_call(ctx)+ await runtime_rail.before_model_call(ctx)++ prompt = builder.build()+ ordered_markers = [+ "identity",+ "# 安全原则",+ "# 可用工具",+ "# 技能",+ "# 持久化存储体系",+ "# 消息说明",+ "# 工作空间",+ "# 项目上下文",+ "# 上下文压缩",+ "# 当前日期与时间",+ "# 运行时",+ ]+ positions = [prompt.index(marker) for marker in ordered_markers]+ assert positions == sorted(positions)+ assert "运行时:agent=main_agent | model=test-model | channel=web | language=cn" in prompt+++def test_resolve_skill_mode_accepts_all_and_auto_list():+ assert JiuWenClawDeepAdapter._resolve_skill_mode({"skill_mode": "all"}) == "all"+ assert JiuWenClawDeepAdapter._resolve_skill_mode({"skill_mode": "auto_list"}) == "auto_list"+ assert JiuWenClawDeepAdapter._resolve_skill_mode({"skill_mode": "invalid"}) == "all"+++def test_build_preset_subagents_includes_code_research_and_optional_browser():+ adapter = JiuWenClawDeepAdapter()+ adapter._workspace_dir = "/tmp/jiuwenclaw-workspace"+ model = object()+ config = {"max_iterations": 9}++ with (+ patch.dict("os.environ", {"BROWSER_AGENT_MAX_ITERATIONS": ""}),+ patch.object(adapter, "_resolve_runtime_language", return_value="cn"),+ patch.object(adapter, "_browser_runtime_enabled", return_value=True),+ patch(+ "jiuwenclaw.agentserver.deep_agent.interface_deep.build_code_agent_config",+ return_value="code_spec",+ ) as mock_code,+ patch(+ "jiuwenclaw.agentserver.deep_agent.interface_deep.build_research_agent_config",+ return_value="research_spec",+ ) as mock_research,+ patch(+ "jiuwenclaw.agentserver.deep_agent.interface_deep.build_browser_agent_config",+ return_value="browser_spec",+ ) as mock_browser,+ ):+ subagents = adapter._build_preset_subagents(model, config)++ assert subagents == ["code_spec", "research_spec", "browser_spec"]+ mock_code.assert_called_once_with(+ model,+ workspace="/tmp/jiuwenclaw-workspace",+ language="cn",+ max_iterations=9,+ )+ mock_research.assert_called_once_with(+ model,+ workspace="/tmp/jiuwenclaw-workspace",+ language="cn",+ max_iterations=9,+ )+ mock_browser.assert_called_once_with(+ model,+ workspace="/tmp/jiuwenclaw-workspace",+ language="cn",+ max_iterations=9,+ )diff --git a/uv.lock b/uv.lockindex a1d6c100aa..4c52017131 100644--- a/uv.lock+++ b/uv.lock@@ -2227,7 +2227,7 @@ wheels = [[[package]]name = "openjiuwen"version = "0.1.10"-source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#d50666db50ab26eee9dfb0fcddf4de96a7d85222" }+source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#9afb936a019ce73646c0e7bcc2aa18c7d8f7ad83" }dependencies = [{ name = "aiofiles" },{ name = "aiohttp" },