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: 运行时状态写入runtime_state.yaml,模型按需读取

cycong_16510288de254
diff --git a/jiuwenclaw/agentserver/deep_agent/interface_deep.py b/jiuwenclaw/agentserver/deep_agent/interface_deep.py
index 68a2ae72ac..21e5ed6008 100644
--- a/jiuwenclaw/agentserver/deep_agent/interface_deep.py
+++ b/jiuwenclaw/agentserver/deep_agent/interface_deep.py
@@ -11,10 +11,14 @@ from __future__ import annotations
import asyncio
import logging
import os
+import platform
+import subprocess
from contextvars import ContextVar, Token
from dataclasses import dataclass
+from shutil import which
from typing import Any, AsyncIterator, Callable, List, Tuple
+import yaml
from dotenv import load_dotenv
from openjiuwen.core.context_engine.schema.config import ContextEngineConfig
from openjiuwen.core.foundation.llm import ModelRequestConfig, ModelClientConfig, Model
@@ -161,6 +165,7 @@ from jiuwenclaw.utils import (
get_agent_skills_dir,
get_agent_workspace_dir,
get_checkpoint_dir,
+ get_config_dir,
get_env_file,
reset_free_search_runtime_flags,
)
@@ -280,6 +285,13 @@ def _build_context_processor_rail(config: dict[str, Any]) -> ContextProcessorRai
return None
+_MODE_DISPLAY_MAP: dict[str, dict[str, str]] = {
+ "agent.plan": {"cn": "规划模式", "en": "Planning Mode"},
+ "agent.fast": {"cn": "性能模式", "en": "Performance Mode"},
+ "team": {"cn": "集群模式", "en": "Cluster Mode"},
+}
+
+
class _RuntimeCronToolContext:
"""Stable cron tool context proxy backed by per-task contextvars."""
@@ -416,10 +428,45 @@ class JiuWenClawDeepAdapter:
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"
+ if self._model_request_config and hasattr(self._model_request_config, 'model_name'):
+ return self._model_request_config.model_name or "unknown"
return "unknown"
+ def _write_runtime_state(self, mode: str, language: str, channel: str) -> None:
+ """将当前运行时状态写入 config 目录下的 runtime_state.yaml。"""
+ try:
+ git_branch = "N/A"
+ git_bin = which("git")
+ if git_bin:
+ try:
+ r = subprocess.run(
+ [git_bin, "rev-parse", "--abbrev-ref", "HEAD"],
+ capture_output=True, text=True, timeout=5,
+ cwd=os.path.dirname(__file__),
+ )
+ if r.returncode == 0 and r.stdout.strip():
+ git_branch = r.stdout.strip()
+ except Exception:
+ pass
+
+ mode_display = _MODE_DISPLAY_MAP.get(mode, {}).get(language, mode)
+
+ state = {
+ "model": self._resolve_model_name(),
+ "mode": mode_display,
+ "language": language,
+ "channel": channel,
+ "agent": self._agent_name,
+ "platform": f"{platform.system()} {platform.machine()}",
+ "python": platform.python_version(),
+ "git_branch": git_branch,
+ }
+ path = get_config_dir() / "runtime_state.yaml"
+ with open(path, "w", encoding="utf-8") as f:
+ yaml.safe_dump(state, f, allow_unicode=True, sort_keys=False)
+ except Exception as exc:
+ logger.debug("[JiuWenClawDeepAdapter] write runtime_state failed: %s", exc)
+
@staticmethod
def _browser_runtime_enabled() -> bool:
"""Whether browser runtime support is enabled for DeepAgent subagent wiring."""
@@ -969,6 +1016,7 @@ class JiuWenClawDeepAdapter:
config.model_name = model.model_config.model_name
config.model_client_config = model.model_client_config
config.model_config_obj = model.model_config
+ self._model_request_config = model.model_config
@staticmethod
def _resolve_skill_mode(config: dict[str, Any]) -> str:
@@ -1232,8 +1280,6 @@ 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:
@@ -2049,11 +2095,13 @@ class JiuWenClawDeepAdapter:
raise RuntimeError("JiuWenClawDeepAdapter 未初始化,请先调用 create_instance()")
resolved_language = self._resolve_runtime_language()
+ resolved_channel = str(runtime_config.channel_id or
+ self._resolve_prompt_channel(runtime_config.session_id) or "web").strip() or "web"
if self._runtime_prompt_rail:
self._runtime_prompt_rail.set_language(resolved_language)
- resolved_channel = str(runtime_config.channel_id or self._resolve_prompt_channel(runtime_config.session_id) or "web").strip() or "web"
self._runtime_prompt_rail.set_channel(resolved_channel)
self._runtime_prompt_rail.set_trusted_dirs(runtime_config.trusted_dirs)
+ self._write_runtime_state(mode=runtime_config.mode, language=resolved_language, channel=resolved_channel)
await self._update_rails_for_mode(runtime_config.mode)
await self._update_tools_for_mode(runtime_config.mode, runtime_config.session_id, runtime_config.request_id)
diff --git a/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py b/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py
index 68d4273f1b..5faa9dc094 100644
--- a/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py
+++ b/jiuwenclaw/agentserver/deep_agent/rails/runtime_prompt_rail.py
@@ -1,26 +1,25 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
-"""RuntimePromptRail — Inject dynamic time/channel/runtime info per model call.
+"""RuntimePromptRail — Inject dynamic time/runtime info per 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().
+Time is injected fresh on every model call. Static runtime properties
+(model, mode, language, platform, etc.) are maintained in runtime_state.yaml
+and the model is instructed to read that file when the user asks about them.
"""
from __future__ import annotations
-import platform
-import subprocess
-from shutil import which
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
+from jiuwenclaw.utils import get_config_dir
_CN_WEEKDAYS = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
class RuntimePromptRail(DeepAgentRail):
- """在 before_model_call 中注入运行时动态 section(时间、运行时信息)。"""
+ """在 before_model_call 中注入时间及运行时状态文件路径。"""
priority = 5 # 高优先级,确保早于其他 rail 执行
@@ -29,16 +28,12 @@ class RuntimePromptRail(DeepAgentRail):
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 = None
self._language = language
self._channel = channel
self._tz = timezone(timedelta(hours=timezone_offset))
- self._agent_name = agent_name
- self._model_name = model_name
self._trusted_dirs: list[str] | None = None
def init(self, agent) -> None:
@@ -66,29 +61,7 @@ class RuntimePromptRail(DeepAgentRail):
"""per-request 更新可信目录。"""
self._trusted_dirs = trusted_dirs
- @staticmethod
- def _get_git_branch() -> str:
- """获取当前 git 分支名,失败时返回 N/A。"""
- git_bin = which("git")
- if not git_bin:
- return "N/A"
-
- try:
- result = subprocess.run(
- [git_bin, "rev-parse", "--abbrev-ref", "HEAD"],
- capture_output=True,
- text=True,
- timeout=5,
- )
- except (subprocess.SubprocessError, OSError):
- return "N/A"
-
- if result.returncode == 0 and result.stdout.strip():
- return result.stdout.strip()
- return "N/A"
-
async def before_model_call(self, ctx: AgentCallbackContext) -> None:
- """每次 model call 注入最新的时间和运行时信息。"""
if not self.system_prompt_builder:
return
@@ -120,31 +93,22 @@ class RuntimePromptRail(DeepAgentRail):
priority=92,
))
- plat = f"{platform.system()} {platform.machine()}"
- python_ver = platform.python_version()
- git_branch = self._get_git_branch()
-
+ runtime_state_path = str(get_config_dir() / "runtime_state.yaml")
if self._language == "cn":
runtime_content = (
"# 运行时\n\n"
- f"- 平台:{plat}\n"
- f"- Python:{python_ver}\n"
- f"- 模型:{self._model_name}\n"
- f"- Git 分支:{git_branch}\n"
- f"- Agent:{self._agent_name}\n"
- f"- 频道:{self._channel}\n"
- f"- 语言:{self._language}"
+ f"- 运行时状态文件:{runtime_state_path}\n"
+ "- 每次用户询问当前模型、模式、语言等运行时属性时,"
+ "必须重新调用 read_file 工具读取该文件获取最新值,"
+ "只用一句话回答用户问的那个字段,不要列出其他内容"
)
else:
runtime_content = (
"# Runtime\n\n"
- f"- Platform: {plat}\n"
- f"- Python: {python_ver}\n"
- f"- Model: {self._model_name}\n"
- f"- Git branch: {git_branch}\n"
- f"- Agent: {self._agent_name}\n"
- f"- Channel: {self._channel}\n"
- f"- Language: {self._language}"
+ f"- Runtime state file: {runtime_state_path}\n"
+ "- Every time the user asks about the current model, mode, language, "
+ "or other runtime properties, you MUST re-invoke the read_file tool to get the latest value. "
+ "Only answer the field the user asked about in one sentence, do not list all file contents."
)
self.system_prompt_builder.add_section(PromptSection(
diff --git a/jiuwenclaw/agentserver/team/team_manager.py b/jiuwenclaw/agentserver/team/team_manager.py
index 45813ef2e1..115c1cf7e2 100644
--- a/jiuwenclaw/agentserver/team/team_manager.py
+++ b/jiuwenclaw/agentserver/team/team_manager.py
@@ -377,8 +377,6 @@ class TeamManager:
skills_dir=str(member_skills_dir),
language="cn",
channel=resolved_channel,
- agent_name=getattr(agent.card, "name", "team_member"),
- model_name=resolved_model_name,
)
for rail in member_rails:
if type(rail).__name__ in RAIL_WHITELIST:
diff --git a/jiuwenclaw/agentserver/team/team_runtime_inheritance.py b/jiuwenclaw/agentserver/team/team_runtime_inheritance.py
index 026d037227..3468c8b064 100644
--- a/jiuwenclaw/agentserver/team/team_runtime_inheritance.py
+++ b/jiuwenclaw/agentserver/team/team_runtime_inheritance.py
@@ -80,8 +80,6 @@ def build_member_rails(
skills_dir: str,
language: str = "cn",
channel: str = "default",
- agent_name: str = "team_member",
- model_name: str = "gpt-4",
) -> list[Any]:
"""为 Team 成员创建 rails 列表.
@@ -89,8 +87,6 @@ def build_member_rails(
skills_dir: 兼容保留参数,当前不参与 skill rail 构造
language: 语言设置
channel: 渠道设置(使用真实 channel_id)
- agent_name: 成员名称
- model_name: 模型名称
Returns:
rail 实例列表
@@ -101,8 +97,6 @@ def build_member_rails(
rail = RuntimePromptRail(
language=language,
channel=channel,
- agent_name=agent_name,
- model_name=model_name,
)
rails_list.append(rail)
logger.info("[TeamRuntime] RuntimePromptRail created: channel=%s", channel)
diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
index 91f9f95397..f2e5e8ef2d 100644
--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py
+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
@@ -41,9 +41,7 @@ async def test_runtime_time_section_participates_in_priority_order():
runtime_rail = RuntimePromptRail(
language="cn",
- channel="web",
- agent_name="main_agent",
- model_name="test-model",
+ channel="web"
)
runtime_rail.init(SimpleNamespace(system_prompt_builder=builder))
@@ -60,7 +58,7 @@ async def test_runtime_time_section_participates_in_priority_order():
]
positions = [prompt.index(marker) for marker in ordered_markers]
assert positions == sorted(positions)
- assert "频道:web" in prompt
+ assert "runtime_state.yaml" in prompt
def test_resolve_skill_mode_accepts_all_and_auto_list():