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
[dev-stable] 回合 AgentServer Bugfix:默认关闭预热并停止修改项目 .gitignore
haowenzhong1e544efc4e5b7
diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.pyindex d0fbbaba2a..d591c528c2 100644--- a/jiuwenswarm/gateway/app_gateway.py+++ b/jiuwenswarm/gateway/app_gateway.py@@ -102,6 +102,13 @@ async def _start_gateway_a2a_ingress(a2a_manager: Any) -> None:_PROMPT_IDLE_FINALIZE_SECONDS = 3.0_AGENT_PREWARM_EXCLUDED_CHANNELS = frozenset({"acp", "a2a"})++def _agent_prewarm_enabled() -> bool:+ """Return whether background session prewarming is switched on."""+ from jiuwenswarm.server.runtime.agent_warm_pool import prewarm_enabled_by_env++ return prewarm_enabled_by_env()+# IM 平台官方 API 域名(仅作为 config.yaml 缺字段时的加载兜底,不在 Config 类里硬编码)_FEISHU_DEFAULT_API_BASE = "https://open.feishu.cn"_DINGTALK_DEFAULT_API_BASE = "https://api.dingtalk.com" # 新版 v1.0 接口域名@@ -1944,7 +1951,7 @@ async def _run_with_telemetry(prewarm_sync_task: asyncio.Task[None] | None = Noneasync def _sync_agent_prewarm_channels() -> None:- if is_enterprise():+ if is_enterprise() or not _agent_prewarm_enabled():returntry:prewarm_channels = {@@ -1977,7 +1984,7 @@ async def _run_with_telemetry(name: str, *, delay_seconds: float = 1.0) -> None:"""Coalesce startup/config/channel churn into one settled sync."""- if is_enterprise():+ if is_enterprise() or not _agent_prewarm_enabled():returnnonlocal prewarm_sync_debounce_taskprevious = prewarm_sync_debounce_task@@ -2916,7 +2923,7 @@ async def _run_with_telemetry("agent-prewarm-sync-after-startup",delay_seconds=3.0,)- if not is_enterprise():+ if not is_enterprise() and _agent_prewarm_enabled():prewarm_sync_task = asyncio.create_task(_periodic_agent_prewarm_sync(),name="agent-prewarm-periodic-sync",diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 6dfb84170c..bf03ab22dc 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -2249,6 +2249,10 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:"""Reconcile project-derived warm keys without delaying the Web RPC."""if is_enterprise():return+ from jiuwenswarm.server.runtime.agent_warm_pool import prewarm_enabled_by_env++ if not prewarm_enabled_by_env():+ returnasync def _sync() -> None:try:diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex 46aae486d8..e909477847 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -637,7 +637,6 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):initial_workspace = self._project_dir or str(get_default_project_session_workspace_dir())- self._ensure_project_gitignore_agent_history(initial_workspace)self._seed_runtime_cwd(initial_workspace, workspace=initial_workspace)setattr(self._instance, "_jiuwenswarm_adapter_mode", "code")diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex a83358afa1..38fb41d0f3 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -11463,10 +11463,6 @@ class JiuWenSwarmDeepAdapter:initial_runtime_workspace = self._project_dir or str(get_default_project_session_workspace_dir())- await asyncio.to_thread(- self._ensure_project_gitignore_agent_history,- initial_runtime_workspace,- )self._seed_runtime_cwd(initial_runtime_workspace, workspace=initial_runtime_workspace)setattr(self._instance, "_jiuwenswarm_project_dir", initial_runtime_workspace)@@ -11547,86 +11543,6 @@ class JiuWenSwarmDeepAdapter:"[JiuWenSwarmDeepAdapter] ExtensionRegistry unavailable, skip extension tools")- @staticmethod- def _ensure_project_gitignore_agent_history(project_dir: str | None) -> None:- """Ensure JiuwenSwarm's file operation logs stay out of project git diffs."""- if not project_dir:- return- try:- repo_probe = subprocess.run(- ["git", "rev-parse", "--show-toplevel"],- cwd=project_dir,- capture_output=True,- text=True,- timeout=5,- check=False,- )- except (OSError, subprocess.SubprocessError):- return- if repo_probe.returncode != 0:- return-- repo_root_text = repo_probe.stdout.strip()- if not repo_root_text:- return- gitignore_path = Path(repo_root_text) / ".gitignore"- try:- existing_bytes = gitignore_path.read_bytes() if gitignore_path.exists() else b""- except OSError as exc:- logger.warning(- "[JiuWenSwarmDeepAdapter] read .gitignore for agent history rule failed: %s",- exc,- )- return-- if JiuWenSwarmDeepAdapter._gitignore_covers_agent_history(existing_bytes):- return-- existing = existing_bytes.decode("utf-8", errors="replace")- prefix = "" if not existing else ("\n" if existing.endswith(("\n", "\r")) else "\n\n")- addition = (- f"{prefix}# JiuwenSwarm runtime file operation logs\n.agent_history/\n"- ).encode("utf-8")- try:- gitignore_path.write_bytes(existing_bytes + addition)- except OSError as exc:- logger.warning(- "[JiuWenSwarmDeepAdapter] ensure .agent_history gitignore failed: %s",- exc,- )-- @staticmethod- def _gitignore_covers_agent_history(content: bytes) -> bool:- """Return True if .gitignore content already ignores .agent_history/.-- Recognizes equivalent forms such as ``.agent_history``,- ``.agent_history/``, ``.agent_history/*``, ``.agent_history/**``,- ``.agent_history/**/*``, ``**/.agent_history`` and combinations- thereof, so that the rule is idempotent across pre-existing project- configurations.- """- text = content.decode("utf-8", errors="replace")- for raw_line in text.splitlines():- line = raw_line.strip()- if not line or line.startswith("#"):- continue- # Skip negation rules; they re-include paths rather than ignore- # the directory.- if line.startswith("!"):- continue- # Strip leading glob prefix like `**/`.- if line.startswith("**/"):- line = line[3:]- # Split into segments. The rule covers `.agent_history` if the- # first segment matches and any following segments are wildcards- # that target the directory contents.- segments = [seg for seg in line.split("/") if seg]- if not segments or segments[0] != ".agent_history":- continue- if all(seg in ("*", "**") for seg in segments[1:]):- return True- return False-async def load_user_rails(self) -> None:"""动态加载用户自定义的 Rail 扩展."""try:diff --git a/jiuwenswarm/server/runtime/agent_warm_pool.py b/jiuwenswarm/server/runtime/agent_warm_pool.pyindex 5a3f94ddf3..08b1c40cc7 100644--- a/jiuwenswarm/server/runtime/agent_warm_pool.py+++ b/jiuwenswarm/server/runtime/agent_warm_pool.py@@ -30,7 +30,7 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)-# Background prewarming is on by default and can be opted out of through the+# Background prewarming is off by default and is only activated through the# environment. Once off, sessions are allocated an id immediately and initialize# lazily on their first request._PREWARM_ENABLED_ENV_KEY = "JIUWENSWARM_AGENT_PREWARM"@@ -38,12 +38,12 @@ _PREWARM_ON_VALUES = frozenset({"1", "true", "yes", "on"})_PREWARM_OFF_VALUES = frozenset({"0", "false", "no", "off"})-def _prewarm_enabled_by_env() -> bool:+def prewarm_enabled_by_env() -> bool:"""Return whether background session prewarming is switched on.Returns:- The explicit environment choice, or True when the switch is unset or- carries an unrecognized value.+ True only when the environment explicitly opts in; False when the+ switch is unset or carries an unrecognized value.企业版模型依赖请求 ``metadata.routing``(含 ``bot_id``)。预热路径没有identity,会落到空 ``config.yaml`` 并打 ERROR;因此企业版强制关闭会话预热,@@ -52,15 +52,15 @@ def _prewarm_enabled_by_env() -> bool:if is_enterprise():return Falseraw = str(os.environ.get(_PREWARM_ENABLED_ENV_KEY, "") or "").strip().lower()- if raw in _PREWARM_OFF_VALUES:- return False- if raw not in _PREWARM_ON_VALUES and raw:+ if raw in _PREWARM_ON_VALUES:+ return True+ if raw and raw not in _PREWARM_OFF_VALUES:logger.warning(- "Ignoring unrecognized %s value %r; keeping prewarming enabled.",+ "Ignoring unrecognized %s value %r; keeping prewarming disabled.",_PREWARM_ENABLED_ENV_KEY,raw,)- return True+ return Falsedef _zero_stats() -> dict[str, int]:@@ -135,7 +135,7 @@ class AgentWarmPool:enabled: bool | None = None,) -> None:self._manager = manager- self._enabled = _prewarm_enabled_by_env() if enabled is None else bool(enabled)+ self._enabled = prewarm_enabled_by_env() if enabled is None else bool(enabled)self._boot_id = uuid.uuid4().hexself._sequence = 0self._revision = WarmRevision(self._boot_id, "", 0)@@ -469,6 +469,8 @@ class AgentWarmPool:async def begin_foreground(self) -> None:"""Preempt speculative preparation while a real chat is active."""+ if not self._enabled:+ returncancelled = 0async with self._lock:self._foreground_count += 1@@ -490,6 +492,8 @@ class AgentWarmPool:async def end_foreground(self) -> None:"""Resume lazy background preparation after the final chat completes."""+ if not self._enabled:+ returnasync with self._lock:self._foreground_count = max(0, self._foreground_count - 1)if self._foreground_count == 0:diff --git a/jiuwenswarm/server/runtime/tenant_agent_pool.py b/jiuwenswarm/server/runtime/tenant_agent_pool.pyindex 17f3a29325..7e8dcbf386 100644--- a/jiuwenswarm/server/runtime/tenant_agent_pool.py+++ b/jiuwenswarm/server/runtime/tenant_agent_pool.py@@ -1059,7 +1059,7 @@ class TenantAgentPool:"""[PERF 优化③] session.create 成功后后台预热该会话(租户池路径)。企业版 warm pool 因预热路径缺请求身份而被强制关闭(见- agent_warm_pool._prewarm_enabled_by_env),每个新会话首条 chat 仍全额+ agent_warm_pool.prewarm_enabled_by_env),每个新会话首条 chat 仍全额支付 agent 构建 + prepare_session(实测 ~10s)。本方法在 create 上下文(身份齐全)中按 process_message_stream 同款租户推导,后台完成同一套构建:**不含 LLM 轮次、不写对话历史**。get_agent 按 key 双检锁,与首条diff --git a/tests/unit_tests/agentserver/test_agent_warm_pool.py b/tests/unit_tests/agentserver/test_agent_warm_pool.pyindex 157ad5a601..3cd77b86e9 100644--- a/tests/unit_tests/agentserver/test_agent_warm_pool.py+++ b/tests/unit_tests/agentserver/test_agent_warm_pool.py@@ -83,14 +83,14 @@ def isolated_pool(monkeypatch, tmp_path: Path):)def factory(agent: _FakeRootAgent) -> AgentWarmPool:- # Prewarming is on by default; stay explicit so a developer environment- # that opts out cannot silently turn these cases into no-ops.+ # Prewarming is off by default; stay explicit so a developer environment+ # that opts in cannot silently turn these cases into no-ops.return AgentWarmPool(_FakeManager(agent), max_concurrency=4, enabled=True)yield factory-def test_prewarm_is_enabled_unless_the_environment_opts_out(+def test_prewarm_is_disabled_unless_the_environment_opts_in(monkeypatch, tmp_path: Path) -> None:monkeypatch.setattr(@@ -103,7 +103,7 @@ def test_prewarm_is_enabled_unless_the_environment_opts_out(return AgentWarmPool(_FakeManager(_FakeRootAgent()))monkeypatch.delenv("JIUWENSWARM_AGENT_PREWARM", raising=False)- assert build()._enabled is True+ assert build()._enabled is Falsemonkeypatch.setenv("JIUWENSWARM_AGENT_PREWARM", " OFF ")assert build()._enabled is False@@ -112,6 +112,25 @@ def test_prewarm_is_enabled_unless_the_environment_opts_out(assert build()._enabled is True+async def test_disabled_pool_skips_foreground_bookkeeping(+ monkeypatch, tmp_path: Path+) -> None:+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.agent_warm_pool.get_agent_sessions_dir",+ lambda: tmp_path,+ )+ pool = AgentWarmPool(_FakeManager(_FakeRootAgent()), enabled=False)++ await pool.begin_foreground()+ await pool.end_foreground()++ assert pool._foreground_count == 0+ assert pool._foreground_idle.is_set()+ assert pool._background_pump_task is None+ await pool.close()++def test_prewarm_disabled_on_enterprise_even_if_env_opts_in(monkeypatch, tmp_path: Path) -> None:diff --git a/tests/unit_tests/server/test_agent_history_gitignore.py b/tests/unit_tests/server/test_agent_history_gitignore.pyindex da736ff955..0ab1de07b2 100644--- a/tests/unit_tests/server/test_agent_history_gitignore.py+++ b/tests/unit_tests/server/test_agent_history_gitignore.py@@ -89,75 +89,6 @@ async def test_memory_reindex_is_singleflight_per_workspace_and_config(await asyncio.wait_for(first._memory_reindex_task, timeout=1)-def test_ensure_project_gitignore_agent_history_updates_repo_root(tmp_path):- repo = tmp_path / "repo"- subdir = repo / "pkg"- subdir.mkdir(parents=True)- _git(repo, "init")-- JiuWenSwarmDeepAdapter._ensure_project_gitignore_agent_history(str(subdir))- JiuWenSwarmDeepAdapter._ensure_project_gitignore_agent_history(str(subdir))-- gitignore = repo / ".gitignore"- assert gitignore.exists()- content = gitignore.read_text(encoding="utf-8")- assert content.count(".agent_history/") == 1--- "existing_rule",- [- ".agent_history",- ".agent_history/",- ".agent_history/*",- ".agent_history/**",- ".agent_history/**/*",- "**/.agent_history",- "**/.agent_history/",- "**/.agent_history/*",- ],-)-def test_ensure_project_gitignore_agent_history_idempotent_for_equivalent_rules(- tmp_path, existing_rule-):- repo = tmp_path / "repo"- repo.mkdir()- _git(repo, "init")-- gitignore = repo / ".gitignore"- gitignore.write_text(f"build/\n{existing_rule}\n", encoding="utf-8")-- before = gitignore.read_bytes()-- JiuWenSwarmDeepAdapter._ensure_project_gitignore_agent_history(str(repo))- JiuWenSwarmDeepAdapter._ensure_project_gitignore_agent_history(str(repo))-- after = gitignore.read_bytes()- assert before == after, (- f".gitignore should remain unchanged for equivalent rule {existing_rule!r}"- )---def test_ensure_project_gitignore_agent_history_preserves_crlf(tmp_path):- repo = tmp_path / "repo"- repo.mkdir()- _git(repo, "init")-- gitignore = repo / ".gitignore"- original = b"build/\r\ndist/\r\n"- gitignore.write_bytes(original)-- JiuWenSwarmDeepAdapter._ensure_project_gitignore_agent_history(str(repo))-- after = gitignore.read_bytes()- # Original CRLF lines must be preserved verbatim.- assert after.startswith(original)- # Appended rule uses LF (consistent with the rest of the addition) and is- # separated from existing content by exactly one blank line.- assert after.endswith(b"# JiuwenSwarm runtime file operation logs\n.agent_history/\n")- assert after.count(b".agent_history/") == 1--def test_git_diff_excludes_unignored_agent_history(tmp_path):repo = tmp_path / "repo"repo.mkdir()