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(skill-evolution): align evolution outcomes and restore TUI rebuild command - Derive evolution watcher timeout from rail.evolution_total_timeout_secs instead of using the legacy fixed host timeout - Handle no-op outcome metadata so watcher emits start/end terminal status even without prior progress - Normalize agent/team evolution watcher cleanup paths
z2tng520cec0d01af
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/evolve.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/evolve.tsindex 9a89615dec..5db8f43ad6 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/evolve.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/evolve.ts@@ -116,7 +116,6 @@ export function createEvolveRebuildCommand(): SlashCommand {example: "/evolve_rebuild pptx improve error handling",kind: CommandKind.BUILT_IN,takesArgs: true,- hidden: true,action: (ctx, args) => {const parsedArgs = parseArgs(args);const skillName = parsedArgs[0];@@ -141,4 +140,3 @@ export function createEvolveRebuildCommand(): SlashCommand {},};}-diff --git a/jiuwenswarm/server/runtime/agent_adapter/evolution_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/evolution_helpers.pyindex 255793294a..51ef4de5ba 100644--- a/jiuwenswarm/server/runtime/agent_adapter/evolution_helpers.py+++ b/jiuwenswarm/server/runtime/agent_adapter/evolution_helpers.py@@ -5,6 +5,7 @@from __future__ import annotationsimport logging+import mathfrom dataclasses import dataclassfrom typing import Any, Callable@@ -12,6 +13,7 @@ logger = logging.getLogger(__name__)TEAM_EVOLUTION_IDLE_SLEEP_SEC = 1.0TEAM_EVOLUTION_EVENT_TIMEOUT_SEC = 900.0+TEAM_EVOLUTION_EVENT_TIMEOUT_GRACE_SEC = 5.0TEAM_EVOLUTION_START_STAGE = "collecting"TEAM_EVOLUTION_START_MESSAGE = "Running team skill evolution analysis..."TEAM_EVOLUTION_NOOP_STAGE = "no_evolution_generated"@@ -111,6 +113,31 @@ def event_type(evt: Any) -> str:return payload_type if isinstance(payload_type, str) else ""+def resolve_evolution_event_timeout_sec(+ rail: Any,+ *,+ fallback_sec: float | None = None,+ grace_sec: float | None = None,+) -> float:+ """Resolve host watcher timeout from the SDK rail's background evolution timeout."""+ fallback = TEAM_EVOLUTION_EVENT_TIMEOUT_SEC if fallback_sec is None else fallback_sec+ grace = TEAM_EVOLUTION_EVENT_TIMEOUT_GRACE_SEC if grace_sec is None else grace_sec++ try:+ sdk_timeout = getattr(rail, "evolution_total_timeout_secs", None)+ except Exception as exc:+ logger.debug("Failed to read SDK evolution timeout from property: %s", exc)+ return fallback++ try:+ parsed_timeout = float(sdk_timeout)+ except (TypeError, ValueError):+ return fallback+ if not math.isfinite(parsed_timeout) or parsed_timeout <= 0:+ return fallback+ return parsed_timeout + max(grace, 0.0)++def is_evolution_approval_event(evt: Any) -> bool:if event_type(evt) == "chat.ask_user_question":return Truediff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 27d2d55e57..0143c83f1b 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -147,6 +147,7 @@ from jiuwenswarm.server.runtime.agent_adapter.evolution_helpers import (push_evolution_event,push_evolution_progress,push_evolution_status,+ resolve_evolution_event_timeout_sec,team_evolution_terminal_progress,terminal_stage,visible_evolution_progress_from_events,@@ -4300,12 +4301,6 @@ class JiuWenClawDeepAdapter:"""stripped = query.strip()- if stripped.startswith("/evolve_rewrite"):- return {- "output": "`/evolve_rewrite` 已删除,请使用 `/evolve_rebuild <skill_name> [user_intent]`。",- "result_type": "error",- }-if stripped.startswith("/evolve_simplify"):err = self._ensure_evolution_rail_for_slash(mode)if err:@@ -5738,7 +5733,7 @@ class JiuWenClawDeepAdapter:build_server_push_message,)- async def _cleanup_rail() -> None:+ async def _cleanup_evolution_rail() -> None:if self._skill_evolution_rail is None:returntry:@@ -5760,6 +5755,10 @@ class JiuWenClawDeepAdapter:active = Falselast_event_at = time.monotonic()+ event_timeout_sec = resolve_evolution_event_timeout_sec(+ self._skill_evolution_rail,+ fallback_sec=TEAM_EVOLUTION_EVENT_TIMEOUT_SEC,+ )while True:if self._skill_evolution_rail is None:@@ -5767,13 +5766,13 @@ class JiuWenClawDeepAdapter:if not getattr(self._skill_evolution_rail, "auto_scan", True):if active:await _push_status("end", "hidden", "")- await _cleanup_rail()+ await _cleanup_evolution_rail()returnevents = await self._skill_evolution_rail.drain_pending_approval_events(wait=False) or []if not events:idle_for = time.monotonic() - last_event_at- if idle_for >= TEAM_EVOLUTION_EVENT_TIMEOUT_SEC:+ if idle_for >= event_timeout_sec:logger.warning("[JiuWenClawDeepAdapter] evolution watcher timed out: ""request_id=%s session_id=%s idle_for=%.1fs",@@ -5784,10 +5783,10 @@ class JiuWenClawDeepAdapter:if active:message = (f"Evolution analysis timed out after "- f"{TEAM_EVOLUTION_EVENT_TIMEOUT_SEC:.0f}s without host events"+ f"{event_timeout_sec:.0f}s without host events")await _push_status("end", "hidden", message)- await _cleanup_rail()+ await _cleanup_evolution_rail()returnawait asyncio.sleep(TEAM_EVOLUTION_IDLE_SLEEP_SEC)continue@@ -5828,7 +5827,7 @@ class JiuWenClawDeepAdapter:for evt in approval_events:await _push_approval(evt)await _push_status("end", "approval_required", "")- await _cleanup_rail()+ await _cleanup_evolution_rail()returnoutcomes = [@@ -5837,21 +5836,25 @@ class JiuWenClawDeepAdapter:if is_evolution_outcome_event(evt)]if outcomes:- if not active:- await _cleanup_rail()- returnoutcome = outcomes[-1]stage = str(outcome.get("status") or "completed").strip().lower()message = str(outcome.get("message") or "")- if stage in {"failed", "timed_out"}:- await _push_status("end", "hidden", message)+ if stage in TEAM_EVOLUTION_HIDDEN_TERMINAL_STAGES:+ end_stage = "hidden"else:- await _push_status(- "end",- stage or "completed",- message or "Evolution analysis completed",- )- await _cleanup_rail()+ end_stage = stage or "completed"+ if not active and end_stage == "hidden":+ await _cleanup_evolution_rail()+ return+ if not active:+ await _push_status("start", end_stage, message)+ active = True+ await _push_status(+ "end",+ end_stage,+ message or "Evolution analysis completed",+ )+ await _cleanup_evolution_rail()returnterminal_progress = [@@ -5865,7 +5868,7 @@ class JiuWenClawDeepAdapter:if end_stage in TEAM_EVOLUTION_HIDDEN_TERMINAL_STAGES:end_stage = "hidden"if not active and end_stage == "hidden":- await _cleanup_rail()+ await _cleanup_evolution_rail()returnif not active:await _push_status(@@ -5879,11 +5882,11 @@ class JiuWenClawDeepAdapter:end_stage,str(terminal.get("message") or ""),)- await _cleanup_rail()+ await _cleanup_evolution_rail()returnexcept asyncio.CancelledError:try:- await _cleanup_rail()+ await _cleanup_evolution_rail()finally:raiseexcept Exception as exc:diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.pyindex 84779be182..4bfcedb1ff 100644--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py@@ -49,6 +49,7 @@ from jiuwenswarm.server.runtime.agent_adapter.evolution_helpers import (progress_for_request,push_evolution_event,push_evolution_status,+ resolve_evolution_event_timeout_sec,team_evolution_end_update,terminal_progress_from_events,terminal_stage,@@ -1115,7 +1116,7 @@ async def _watch_team_evolution_and_push(fallback_cycle_index = 0active_cycle_request_id: str | None = None- async def _cleanup_rail() -> None:+ async def _cleanup_evolution_rail() -> None:cleanup = getattr(rail, "cleanup_background_tasks", None)if cleanup is None:return@@ -1156,6 +1157,10 @@ async def _watch_team_evolution_and_push(try:last_event_at = time.monotonic()+ event_timeout_sec = resolve_evolution_event_timeout_sec(+ rail,+ fallback_sec=TEAM_EVOLUTION_EVENT_TIMEOUT_SEC,+ )while True:if not getattr(rail, "auto_scan", True):if active_cycle_request_id is not None:@@ -1169,14 +1174,14 @@ async def _watch_team_evolution_and_push(),build_server_push_message,)- await _cleanup_rail()+ await _cleanup_evolution_rail()returnevents = await rail.drain_pending_approval_events(wait=False) or []if not events:if active_cycle_request_id is not None:idle_for = time.monotonic() - last_event_at- if idle_for >= TEAM_EVOLUTION_EVENT_TIMEOUT_SEC:+ if idle_for >= event_timeout_sec:logger.warning("[TeamHelpers] evolution monitor timed out: session_id=%s ""request_id=%s idle_for=%.1fs",@@ -1192,12 +1197,12 @@ async def _watch_team_evolution_and_push(stage=TEAM_EVOLUTION_HIDDEN_STAGE,message=("Team skill evolution analysis timed out after "- f"{TEAM_EVOLUTION_EVENT_TIMEOUT_SEC:.0f}s without host events"+ f"{event_timeout_sec:.0f}s without host events"),),build_server_push_message,)- await _cleanup_rail()+ await _cleanup_evolution_rail()returnawait asyncio.sleep(TEAM_EVOLUTION_IDLE_SLEEP_SEC)continuediff --git a/tests/unit_tests/agentserver/test_evolution_helpers.py b/tests/unit_tests/agentserver/test_evolution_helpers.pyindex 0215de9d46..cdb62d535a 100644--- a/tests/unit_tests/agentserver/test_evolution_helpers.py+++ b/tests/unit_tests/agentserver/test_evolution_helpers.py@@ -32,6 +32,43 @@ def test_evolution_helpers_parse_approval_and_outcome_events():assert evolution_helpers.extract_evolution_request_id(approval) == "team_skill_evolve_req1"+def test_evolution_helpers_parse_noop_outcome_status_from_sdk_metadata():+ outcome = SimpleNamespace(+ type="llm_reasoning",+ payload={+ "_evolution_meta": {+ "event_kind": "outcome",+ "rail_kind": "regular",+ "status": "no_evolution_no_records",+ "stage": "completed",+ "skill_name": "powerpoint-pptx",+ "source": "experience_updater",+ },+ "content": "[Evolution] no applied updates for skill=powerpoint-pptx\n",+ },+ )++ assert evolution_helpers.evolution_outcome_from_event(outcome) == {+ "status": "no_evolution_no_records",+ "message": "[Evolution] no applied updates for skill=powerpoint-pptx\n",+ }+++ ("rail", "expected"),+ [+ (SimpleNamespace(evolution_total_timeout_secs=600), 605),+ (object(), 900),+ ],+)+def test_resolve_evolution_event_timeout_matches_sdk_budget(rail, expected):+ assert evolution_helpers.resolve_evolution_event_timeout_sec(+ rail,+ fallback_sec=900,+ grace_sec=5,+ ) == expected++def test_evolution_helpers_extract_request_id_from_evolution_meta():progress = SimpleNamespace(type="llm_reasoning",diff --git a/tests/unit_tests/agentserver/test_evolution_push_delivery.py b/tests/unit_tests/agentserver/test_evolution_push_delivery.pyindex f1f61b55ef..18927995b3 100644--- a/tests/unit_tests/agentserver/test_evolution_push_delivery.py+++ b/tests/unit_tests/agentserver/test_evolution_push_delivery.py@@ -2,10 +2,12 @@from __future__ import annotations+import asynciofrom types import SimpleNamespaceimport pytest+from jiuwenswarm.server.runtime.agent_adapter import evolution_helpersfrom jiuwenswarm.server.runtime.agent_adapter import interface_deep as interface_deep_modulefrom jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenClawDeepAdapter@@ -37,6 +39,23 @@ def _outcome_event(status: str, message: str) -> SimpleNamespace:)+def _sdk_noop_outcome_event(skill_name: str = "powerpoint-pptx") -> SimpleNamespace:+ return SimpleNamespace(+ type="llm_reasoning",+ payload={+ "_evolution_meta": {+ "event_kind": "outcome",+ "rail_kind": "regular",+ "status": "no_evolution_no_records",+ "stage": "completed",+ "skill_name": skill_name,+ "source": "experience_updater",+ },+ "content": f"[Evolution] no applied updates for skill={skill_name}\n",+ },+ )++def _progress_event(content: str, *, stage: str | None = None) -> SimpleNamespace:payload = {"content": content}if stage is not None:@@ -165,6 +184,39 @@ async def test_normal_evolution_watcher_does_not_push_status_without_sdk_events(assert rail.cleanup_calls == 1+async def test_normal_evolution_watcher_uses_sdk_timeout_before_legacy_fallback(monkeypatch):+ class _SdkTimeoutRail(_FakeEvolutionRail):+ @property+ def evolution_total_timeout_secs(self) -> float:+ return 0.01++ _FakeTransport.pushes = []+ rail = _SdkTimeoutRail([[_progress_event("generating", stage="generating_updates")]])+ adapter = _TestAdapter.build_with_rail(rail)++ monkeypatch.setattr(+ "jiuwenswarm.server.gateway_push.WebSocketGatewayPushTransport",+ _FakeTransport,+ )+ monkeypatch.setattr(interface_deep_module, "TEAM_EVOLUTION_IDLE_SLEEP_SEC", 0.001)+ monkeypatch.setattr(interface_deep_module, "TEAM_EVOLUTION_EVENT_TIMEOUT_SEC", 100.0)+ monkeypatch.setattr(evolution_helpers, "TEAM_EVOLUTION_EVENT_TIMEOUT_GRACE_SEC", 0.001)++ await asyncio.wait_for(+ adapter.watch_evolution_and_push("stream-rid", "web", "sess-sdk-timeout"),+ timeout=0.2,+ )++ status_pushes = [+ push for push in _FakeTransport.pushes+ if push["payload"]["event_type"] == "chat.evolution_status"+ ]+ assert [push["payload"]["status"] for push in status_pushes] == ["start", "end"]+ assert status_pushes[-1]["payload"]["stage"] == "hidden"+ assert rail.cleanup_calls == 1++@pytest.mark.asyncioasync def test_normal_evolution_watcher_maps_sdk_progress_stages(monkeypatch):_FakeTransport.pushes = []@@ -269,6 +321,31 @@ async def test_normal_evolution_watcher_reads_outcome_status_from_metadata(monkeassert status_pushes == []+async def test_normal_evolution_watcher_ends_on_sdk_noop_outcome_without_prior_progress(monkeypatch):+ _FakeTransport.pushes = []+ rail = _FakeEvolutionRail([[_sdk_noop_outcome_event()]])+ adapter = _TestAdapter.build_with_rail(rail)++ monkeypatch.setattr(+ "jiuwenswarm.server.gateway_push.WebSocketGatewayPushTransport",+ _FakeTransport,+ )++ await adapter.watch_evolution_and_push("stream-rid", "web", "sess-sdk-noop-only")++ status_pushes = [+ push for push in _FakeTransport.pushes+ if push["payload"]["event_type"] == "chat.evolution_status"+ ]+ assert [push["payload"]["status"] for push in status_pushes] == ["start", "end"]+ assert [push["payload"]["stage"] for push in status_pushes] == [+ "no_evolution_no_records",+ "no_evolution_no_records",+ ]+ assert rail.cleanup_calls == 1++@pytest.mark.asyncioasync def test_normal_evolution_watcher_pushes_passive_progress_before_approval(monkeypatch):_FakeTransport.pushes = []diff --git a/tests/unit_tests/agentserver/test_team_helpers.py b/tests/unit_tests/agentserver/test_team_helpers.pyindex 873a8f29c6..f45627873f 100644--- a/tests/unit_tests/agentserver/test_team_helpers.py+++ b/tests/unit_tests/agentserver/test_team_helpers.py@@ -11,6 +11,7 @@ import pytestfrom openjiuwen.agent_teams.schema.team import TeamRolefrom jiuwenswarm.agents.harness.team import TeamMonitorHandler+from jiuwenswarm.server.runtime.agent_adapter import evolution_helpersfrom jiuwenswarm.server.runtime.agent_adapter import team_helpers@@ -699,6 +700,38 @@ async def test_team_evolution_monitor_times_out_after_idle_progress(monkeypatch)assert rail.cleanup_calls == 1+async def test_team_evolution_monitor_uses_sdk_timeout_before_legacy_fallback(monkeypatch):+ class _SdkTimeoutProgressRail(_FakeProgressOnlyRail):+ @property+ def evolution_total_timeout_secs(self) -> float:+ return 0.01++ _FakeTransport.pushes = []+ rail = _SdkTimeoutProgressRail()++ monkeypatch.setattr(+ "jiuwenswarm.server.gateway_push.WebSocketGatewayPushTransport",+ _FakeTransport,+ )+ monkeypatch.setattr(team_helpers, "TEAM_EVOLUTION_IDLE_SLEEP_SEC", 0.001)+ monkeypatch.setattr(team_helpers, "TEAM_EVOLUTION_EVENT_TIMEOUT_SEC", 100.0)+ monkeypatch.setattr(evolution_helpers, "TEAM_EVOLUTION_EVENT_TIMEOUT_GRACE_SEC", 0.001)++ await asyncio.wait_for(+ _TeamHelpersTestApi.watch_team_evolution_and_push("web", "sess-sdk-timeout", rail),+ timeout=0.2,+ )++ status_pushes = [+ push for push in _FakeTransport.pushes+ if push["payload"]["event_type"] == "chat.evolution_status"+ ]+ assert [push["payload"]["status"] for push in status_pushes] == ["start", "end"]+ assert status_pushes[-1]["payload"]["stage"] == "hidden"+ assert rail.cleanup_calls == 1++@pytest.mark.anyioasync def test_ensure_team_evolution_watcher_starts_without_reasoning_gate(monkeypatch):registered: dict[str, asyncio.Task] = {}diff --git a/uv.lock b/uv.lockindex 6f2bd1494e..ab020665f2 100644--- a/uv.lock+++ b/uv.lock@@ -2379,7 +2379,7 @@ wheels = [[[package]]name = "openjiuwen"version = "0.1.13"-source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#2bfd4ded2c56e52fbe8be6a3d3e04feb01ac77b3" }+source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#a218490d3dd1ada14e5f462d4df03e3a7f4494d1" }dependencies = [{ name = "aiofiles" },{ name = "aiohttp" },