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
fix: isolate runtime_state.yaml per session
cycong_17bc9655349fc
diff --git a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.pyindex 57c25f97bf..e22896a860 100644--- a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py@@ -22,7 +22,7 @@ from openjiuwen.harness.prompts.prompt_attachment_manager import (from openjiuwen.harness.rails.base import DeepAgentRailfrom jiuwenswarm.agents.harness.common.prompt.shell_environment import build_shell_environment_prompt-from jiuwenswarm.common.utils import get_config_dir, logger+from jiuwenswarm.common.utils import get_runtime_state_path, loggerfrom jiuwenswarm.common.utils import get_agent_workspace_dir@@ -52,6 +52,7 @@ class RuntimePromptRail(DeepAgentRail):self._project_dir: str | None = Noneself._model_name: str = ""self._mode: str = ""+ self._session_id: str | None = Noneself._force_english: bool = Falsedef init(self, agent) -> None:@@ -100,6 +101,14 @@ class RuntimePromptRail(DeepAgentRail):"""per-request 更新运行模式,作为文件读取失败时的兜底。"""self._mode = mode or ""+ def set_session_id(self, session_id: str | None) -> None:+ """per-request 更新 session id,用于读取按 session 隔离的 runtime_state 文件。"""+ self._session_id = (+ session_id.strip()+ if isinstance(session_id, str) and session_id.strip()+ else None+ )+def set_force_english(self, force: bool) -> None:"""Force English-only injected sections regardless of language (code mode)."""self._force_english = force@@ -166,13 +175,14 @@ class RuntimePromptRail(DeepAgentRail):# ── runtime ──runtime_state: dict[str, Any] = {}+ state_path = get_runtime_state_path(self._session_id)try:- with open(get_config_dir() / "runtime_state.yaml", encoding="utf-8") as f:+ with open(state_path, encoding="utf-8") as f:runtime_state = yaml.safe_load(f) or {}except FileNotFoundError:passexcept Exception as e:- logger.warning("Failed to read runtime_state.yaml: %s", e)+ logger.warning("Failed to read runtime state file %s: %s", state_path, e)model = (runtime_state.get("model") or self._model_name or "unknown").strip()mode = (runtime_state.get("mode") or self._mode or "unknown").strip()diff --git a/jiuwenswarm/common/utils.py b/jiuwenswarm/common/utils.pyindex 03aca9bd6f..d25f65e77c 100644--- a/jiuwenswarm/common/utils.py+++ b/jiuwenswarm/common/utils.py@@ -1402,6 +1402,16 @@ def get_config_dir() -> Path:return _config_dir+def get_runtime_state_path(session_id: str | None = None) -> Path:+ """Per-session runtime_state.yaml path under config dir.++ 每个 session 独占一份文件,避免心跳/定时/并发 session 共用单文件互相覆盖+ channel/mode/model/git 等字段。session_id 为空时回退到 ``default``。+ """+ sid = re.sub(r"[^A-Za-z0-9_.-]", "_", (session_id or "").strip())[:128] or "default"+ return get_config_dir() / "runtime_state" / f"{sid}.yaml"++def get_workspace_dir() -> Path:"""Get the workspace directory path."""_resolve_paths()diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex 3eda8b2fee..b27a76cdec 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -1182,6 +1182,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):cwd=runtime_config.cwd,project_dir=runtime_config.project_dir or self._project_dir,)+ self._runtime_prompt_rail.set_session_id(runtime_config.session_id)# PermissionInterruptRail: per-request trusted_dirs 注入,使 external_directory# 检查将这些子树视为 internal 而跳过 ask/deny(与 RuntimePromptRail 对齐)。# 用 getattr 兼容绕过 __init__ 的测试构造(_permission_rail 仅在 rail 构建流程赋值)。@@ -1198,6 +1199,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):mode=runtime_config.mode,language=self._resolve_output_language(),channel=resolved_channel,+ session_id=runtime_config.session_id,project_dir=runtime_config.project_diror runtime_config.cwdor self._project_dirdiff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 55bf1a1141..3c21cc0770 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -271,6 +271,7 @@ from jiuwenswarm.common.utils import (get_config_dir,get_env_file,get_prompt_attachment_dir,+ get_runtime_state_path,get_user_workspace_dir,reset_free_search_runtime_flags,)@@ -733,6 +734,13 @@ class JiuWenSwarmDeepAdapter:self._session_adapters.pop(sid, None)self._session_adapter_locks.pop(sid, None)self._session_adapter_last_used.pop(sid, None)+ try:+ get_runtime_state_path(sid).unlink(missing_ok=True)+ except Exception:+ logger.debug(+ "[JiuWenSwarmDeepAdapter] remove runtime_state failed: session_id=%s",+ sid, exc_info=True,+ )evicted += 1async def _get_or_create_session_adapter(self, session_id: str | None) -> "JiuWenSwarmDeepAdapter":@@ -1157,9 +1165,10 @@ class JiuWenSwarmDeepAdapter:language: str,channel: str,*,+ session_id: str | None = None,project_dir: str | None = None,) -> None:- """将当前运行时状态写入 config 目录下的 runtime_state.yaml。"""+ """将当前运行时状态写入 config 目录下按 session 隔离的 runtime_state 文件。"""try:git_branch = "N/A"git_main_branch = ""@@ -1212,7 +1221,8 @@ class JiuWenSwarmDeepAdapter:"git_recent_commits": git_recent_commits,"git_user": git_user,}- path = get_config_dir() / "runtime_state.yaml"+ path = get_runtime_state_path(session_id)+ path.parent.mkdir(parents=True, exist_ok=True)with open(path, "w", encoding="utf-8") as f:yaml.safe_dump(state, f, allow_unicode=True, sort_keys=False)except Exception as exc:@@ -4299,6 +4309,7 @@ class JiuWenSwarmDeepAdapter:)self._runtime_prompt_rail.set_model_name(self._resolve_model_name())self._runtime_prompt_rail.set_mode(runtime_config.mode)+ self._runtime_prompt_rail.set_session_id(runtime_config.session_id)if self._response_prompt_rail:self._response_prompt_rail.set_channel(resolved_channel)# PermissionInterruptRail: per-request trusted_dirs 注入,使 external_directory@@ -4320,6 +4331,7 @@ class JiuWenSwarmDeepAdapter:mode=runtime_config.mode,language=resolved_language,channel=resolved_channel,+ session_id=runtime_config.session_id,project_dir=runtime_config.project_diror runtime_config.cwdor self._project_dir@@ -5475,7 +5487,7 @@ class JiuWenSwarmDeepAdapter:try:await self._update_runtime_config(self._RuntimeConfig(- session_id=request.session_id,+ session_id=session_id,mode=mode,request_id=request.request_id,channel_id=request.channel_id,@@ -5567,11 +5579,16 @@ class JiuWenSwarmDeepAdapter:if self._runtime_prompt_rail:self._runtime_prompt_rail.set_model_name(self._resolve_model_name())self._runtime_prompt_rail.set_mode(mode)+ self._runtime_prompt_rail.set_session_id(session_id)self._write_runtime_state(mode=mode,language=resolved_language,channel=resolved_channel,- project_dir=inputs.get("project_dir") or self._project_dir or self._workspace_dir,+ session_id=session_id,+ project_dir=inputs.get("project_dir")+ or inputs.get("cwd")+ or self._project_dir+ or self._workspace_dir,)async for chunk in process_team_message_stream(request, inputs, self._instance):@@ -5588,7 +5605,7 @@ class JiuWenSwarmDeepAdapter:await self._update_runtime_config(self._RuntimeConfig(- session_id=request.session_id,+ session_id=session_id,mode=mode,request_id=request.request_id,channel_id=request.channel_id,@@ -5711,7 +5728,7 @@ class JiuWenSwarmDeepAdapter:try:await self._update_runtime_config(self._RuntimeConfig(- session_id=request.session_id,+ session_id=session_id,mode=mode,request_id=request.request_id,channel_id=request.channel_id,diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.pyindex 0b7678d47c..ba7ba3b08c 100644--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py@@ -11,10 +11,10 @@ from openjiuwen.harness.prompts.prompt_attachment_manager import ()from openjiuwen.harness.prompts import PromptSection, SystemPromptBuilder+from jiuwenswarm.common import utils as _utils_modfrom jiuwenswarm.server.runtime.agent_adapter import interface_deep as interface_modulefrom jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapterfrom jiuwenswarm.agents.harness.common.prompt.prompt_builder import build_agent_identity_prompt-from jiuwenswarm.agents.harness.common.rails import runtime_prompt_rail as _runtime_modfrom jiuwenswarm.agents.harness.common.rails import skill_retrieval_prompt_rail as _skill_retrieval_prompt_modfrom jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail import RuntimePromptRailfrom jiuwenswarm.agents.harness.common.rails.skill_retrieval_prompt_rail import SkillRetrievalPromptRail@@ -236,7 +236,7 @@ async def test_runtime_time_section_participates_in_priority_order():@pytest.mark.asyncioasync def test_runtime_dynamic_sections_go_to_prompt_attachment_when_manager_available(tmp_path, monkeypatch):- monkeypatch.setattr(_runtime_mod, "get_config_dir", lambda: tmp_path)+ monkeypatch.setattr(_utils_mod, "get_config_dir", lambda: tmp_path)builder = SystemPromptBuilder(language="en")agent = _FakeAgent(builder)runtime_rail = RuntimePromptRail(language="en", channel="web")@@ -281,8 +281,9 @@ async def test_runtime_dynamic_sections_go_to_prompt_attachment_when_manager_ava@pytest.mark.asyncioasync def test_runtime_git_status_attachment_clears_when_git_context_disappears(tmp_path, monkeypatch):- monkeypatch.setattr(_runtime_mod, "get_config_dir", lambda: tmp_path)- runtime_state = tmp_path / "runtime_state.yaml"+ monkeypatch.setattr(_utils_mod, "get_config_dir", lambda: tmp_path)+ runtime_state = tmp_path / "runtime_state" / "default.yaml"+ runtime_state.parent.mkdir(parents=True, exist_ok=True)runtime_state.write_text("git_branch: feature/test\n""git_status: M file.py\n"@@ -354,11 +355,13 @@ async def test_runtime_prompt_language_output_prefers_rail_language_over_runtime):config_dir = tmp_path / "config"config_dir.mkdir()- (config_dir / "runtime_state.yaml").write_text(+ state_dir = config_dir / "runtime_state"+ state_dir.mkdir()+ (state_dir / "default.yaml").write_text("model: test-model\nmode: team.plan\nlanguage: en\nchannel: tui\n",encoding="utf-8",)- monkeypatch.setattr(_runtime_mod, "get_config_dir", lambda: config_dir)+ monkeypatch.setattr(_utils_mod, "get_config_dir", lambda: config_dir)builder = SystemPromptBuilder(language="cn")agent = _FakeAgent(builder)