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

feat(evolution): async approval push with drain/wait and event_type routing

z2tng04ccc4d144c4
diff --git a/jiuwenclaw/agentserver/deep_agent/interface_deep.py b/jiuwenclaw/agentserver/deep_agent/interface_deep.py
index d191122c29..7cc28f0de3 100644
--- a/jiuwenclaw/agentserver/deep_agent/interface_deep.py
+++ b/jiuwenclaw/agentserver/deep_agent/interface_deep.py
@@ -384,6 +384,7 @@ class JiuWenClawDeepAdapter:
self._permission_rail: Any = None
self._avatar_rail: Any = None
self._tool_cards = None
+ self._evolution_watcher_tasks: set[asyncio.Task] = set()
self._sys_operation = None
self._vision_model_config: VisionModelConfig | None = None
self._audio_model_config: AudioModelConfig | None = None
@@ -1398,10 +1399,11 @@ class JiuWenClawDeepAdapter:
evolution_auto_scan: bool = _env_auto_scan.lower() in ("true", "1", "yes")
else:
evolution_auto_scan = config.get("evolution", {}).get("auto_scan", False)
+ model_name = self._default_model_name or config.get("model_name", "gpt-4")
skill_evolution_rail = SkillEvolutionRail(
skills_dir=str(get_agent_skills_dir()),
llm=self._model,
- model=config.get("model_name", "gpt-4"),
+ model=model_name,
auto_scan=evolution_auto_scan,
auto_save=False,
)
@@ -1681,7 +1683,7 @@ class JiuWenClawDeepAdapter:
"""
# Apply in-place updates to skill_evolution_rail (no re-init needed).
if self._skill_evolution_rail is not None:
- self._skill_evolution_rail.update_llm(self._model, config.get("model_name", "gpt-4"))
+ self._skill_evolution_rail.update_llm(self._model, self._default_model_name)
_env_auto_scan = os.getenv("EVOLUTION_AUTO_SCAN")
if _env_auto_scan is not None:
self._skill_evolution_rail.auto_scan = _env_auto_scan.lower() in (
@@ -2689,8 +2691,17 @@ class JiuWenClawDeepAdapter:
request.params.get("request_id", "") if isinstance(request.params, dict) else ""
)
answers = request.params.get("answers", []) if isinstance(request.params, dict) else []
+ session_id = request.session_id
resolved = False
- if request_id.startswith("skill_evolve_"):
+ if request_id.startswith("team_skill_create_"):
+ resolved = await self._handle_team_skill_create_approval(request_id, answers, session_id)
+ elif request_id.startswith("team_skill_evolve_"):
+ resolved = await self._handle_team_skill_evolve_approval(request_id, answers, session_id)
+ elif request_id.startswith("evolve_simplify_"):
+ resolved = await self._handle_governance_approval(request_id, answers, "simplify")
+ elif request_id.startswith("evolve_rebuild_"):
+ resolved = await self._handle_governance_approval(request_id, answers, "rebuild")
+ elif request_id.startswith("skill_evolve_"):
resolved = await self._handle_evolution_approval(request_id, answers)
elif request_id.startswith("skill_create_"):
resolved = await self._handle_skill_create_approval(request_id, answers)
@@ -2774,6 +2785,96 @@ class JiuWenClawDeepAdapter:
return True
+ # ------------------------------------------------------------------
+ # Team Skill approval handlers
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def _find_team_skill_rail(request_id: str):
+ """Find TeamSkillRail that owns the given pending request_id."""
+ try:
+ from jiuwenclaw.agentserver.team import get_team_manager
+ return get_team_manager().find_team_skill_rail_for_request(request_id)
+ except Exception:
+ return None
+
+ @staticmethod
+ def _option_matches(answers: list, accept_labels: tuple[str, ...]) -> bool:
+ """Check whether any answer's selected_options matches accept labels.
+
+ Tolerates both Chinese and English labels (case-insensitive) so the
+ agent-core layer can keep neutral English labels while jiuwenclaw UI
+ may localize them.
+ """
+ normalized_accept = {s.strip().lower() for s in accept_labels}
+ for ans in answers:
+ if not isinstance(ans, dict):
+ continue
+ for opt in ans.get("selected_options", []) or []:
+ if isinstance(opt, str) and opt.strip().lower() in normalized_accept:
+ return True
+ return False
+
+ async def _handle_team_skill_create_approval(
+ self, request_id: str, answers: list, session_id: str | None = None,
+ ) -> bool:
+ rail = JiuWenClawDeepAdapter._find_team_skill_rail(request_id)
+ if rail is None:
+ logger.warning("[JiuWenClaw] team skill create approval failed: no TeamSkillRail")
+ return False
+
+ accepted = self._option_matches(answers, ("create", "创建"))
+
+ logger.info(
+ "[JiuWenClaw] team skill create approval: request_id=%s, answers=%s, accepted=%s",
+ request_id, answers, accepted,
+ )
+
+ if accepted:
+ await rail.on_approve_team_skill(request_id)
+ # Sync newly created team skill from workspace to global team_skills dir.
+ try:
+ from jiuwenclaw.agentserver.team import get_team_manager
+ get_team_manager().sync_team_skills(session_id or "")
+ except Exception as exc:
+ logger.warning("[JiuWenClaw] team skill sync after create failed: %s", exc)
+ logger.info("[JiuWenClaw] team skill create accepted: request_id=%s", request_id)
+ else:
+ await rail.on_reject_team_skill(request_id)
+ logger.info("[JiuWenClaw] team skill create rejected: request_id=%s", request_id)
+
+ return True
+
+ async def _handle_team_skill_evolve_approval(
+ self, request_id: str, answers: list, session_id: str | None = None,
+ ) -> bool:
+ rail = JiuWenClawDeepAdapter._find_team_skill_rail(request_id)
+ if rail is None:
+ logger.warning("[JiuWenClaw] team skill evolve approval failed: no TeamSkillRail")
+ return False
+
+ accepted = self._option_matches(answers, ("accept", "接收", "接受"))
+
+ logger.info(
+ "[JiuWenClaw] team skill evolve approval: request_id=%s, answers=%s, accepted=%s",
+ request_id, answers, accepted,
+ )
+
+ if accepted:
+ await rail.on_approve_patch(request_id)
+ # Sync updated team skill from workspace to global team_skills dir.
+ try:
+ from jiuwenclaw.agentserver.team import get_team_manager
+ get_team_manager().sync_team_skills(session_id or "")
+ except Exception as exc:
+ logger.warning("[JiuWenClaw] team skill sync after patch failed: %s", exc)
+ logger.info("[JiuWenClaw] team skill evolve accepted: request_id=%s", request_id)
+ else:
+ await rail.on_reject_patch(request_id)
+ logger.info("[JiuWenClaw] team skill evolve rejected: request_id=%s", request_id)
+
+ return True
+
# ------------------------------------------------------------------
# /evolve, /evolve_list, /evolve_simplify & /solidify command handlers
# ------------------------------------------------------------------
@@ -2877,7 +2978,7 @@ class JiuWenClawDeepAdapter:
}
# 5) Drain the buffered approval event
- events = rail.drain_pending_approval_events()
+ events = await rail.drain_pending_approval_events()
if not events:
return {
"output": "演进经验生成失败:无法创建审批事件。",
@@ -3095,19 +3196,18 @@ class JiuWenClawDeepAdapter:
}
async def _handle_evolve_simplify_command(self, query: str) -> dict[str, Any]:
- """/evolve_simplify <skill_name> [--dry-run] — LLM-based experience cleanup."""
+ """/evolve_simplify <skill_name> [user_intent] — LLM-based experience cleanup with approval."""
rail = self._skill_evolution_rail
assert rail is not None
store = rail.store
- scorer = rail.scorer
- parts = query.split()
+ parts = query.split(maxsplit=2)
skill_name = parts[1] if len(parts) > 1 else ""
- dry_run = "--dry-run" in parts
+ user_intent = parts[2] if len(parts) > 2 else None
- if not skill_name or skill_name.startswith("--"):
+ if not skill_name:
return {
- "output": "请指定 Skill 名称:`/evolve_simplify <skill_name> [--dry-run]`",
+ "output": "请指定 Skill 名称:`/evolve_simplify <skill_name> [user_intent]`",
"result_type": "error",
}
@@ -3118,54 +3218,185 @@ class JiuWenClawDeepAdapter:
"result_type": "error",
}
- records = await store.get_records_by_score(skill_name)
- if not records:
+ try:
+ request_id = await rail.request_simplify(skill_name, user_intent)
+ except Exception as exc:
+ logger.warning("[JiuWenClaw] evolve_simplify failed: %s", exc)
+ return {"output": f"智能整理分析失败:{exc}", "result_type": "error"}
+
+ if not request_id:
return {
- "output": f"Skill '{skill_name}' 暂无演进经验,无需整理。",
+ "output": f"Skill '{skill_name}' 经验库状态良好,无需整理。",
"result_type": "answer",
}
- skill_summary = await store.read_skill_content(skill_name)
+ approval_chunks = await rail.drain_pending_approval_events()
+ return {
+ "output": f"Skill '{skill_name}' 精简方案已生成,请在审批弹框中确认。",
+ "result_type": "answer",
+ "approval_chunks": approval_chunks,
+ }
+
+ async def _handle_evolve_rebuild_command(self, query: str) -> dict[str, Any]:
+ """/evolve_rebuild <skill_name> [user_intent] — Rebuild skill body with approval."""
+ rail = self._skill_evolution_rail
+ assert rail is not None
+ store = rail.store
+
+ parts = query.split(maxsplit=2)
+ skill_name = parts[1] if len(parts) > 1 else ""
+ user_intent = parts[2] if len(parts) > 2 else None
+
+ if not skill_name:
+ return {
+ "output": "请指定 Skill 名称:`/evolve_rebuild <skill_name> [user_intent]`",
+ "result_type": "error",
+ }
+
+ if not store.skill_exists(skill_name):
+ available = "、".join(store.list_skill_names()) or "(无可用 Skill)"
+ return {
+ "output": f"未找到 Skill '{skill_name}'。当前可用:{available}",
+ "result_type": "error",
+ }
+
try:
- actions = await scorer.simplify(skill_name, skill_summary, records)
+ request_id = await rail.request_rebuild(skill_name, user_intent)
except Exception as exc:
- logger.warning("[JiuWenClaw] evolve_simplify failed: %s", exc)
+ logger.warning("[JiuWenClaw] evolve_rebuild failed: %s", exc)
+ return {"output": f"重建分析失败:{exc}", "result_type": "error"}
+
+ if not request_id:
return {
- "output": f"智能整理分析失败:{exc}",
+ "output": f"Skill '{skill_name}' 重建生成失败(LLM 未输出有效内容)。",
"result_type": "error",
}
- if not actions:
+ approval_chunks = await rail.drain_pending_approval_events()
+ return {
+ "output": f"Skill '{skill_name}' 重建方案已生成,请在审批弹框中确认。",
+ "result_type": "answer",
+ "approval_chunks": approval_chunks,
+ }
+
+ async def _handle_evolve_rollback_command(self, query: str) -> dict[str, Any]:
+ """/evolve_rollback <skill_name> [version] — Rollback skill to archived version."""
+ rail = self._skill_evolution_rail
+ assert rail is not None
+ store = rail.store
+
+ parts = query.split(maxsplit=2)
+ skill_name = parts[1] if len(parts) > 1 else ""
+ version = parts[2].strip() if len(parts) > 2 else None
+
+ if not skill_name:
+ archives_hint = ""
+ for name in store.list_skill_names():
+ archives = store.list_archives(name)
+ if archives:
+ body_versions = [a for a in archives if a.startswith("SKILL.v")]
+ archives_hint += f"\n - **{name}**: {len(body_versions)} 个版本"
return {
- "output": f"Skill '{skill_name}' 经验库状态良好,无需整理。",
- "result_type": "answer",
+ "output": (
+ "请指定 Skill 名称:`/evolve_rollback <skill_name> [version]`"
+ + (f"\n\n可回滚的 Skill:{archives_hint}" if archives_hint else "")
+ ),
+ "result_type": "error",
}
- summary_lines = []
- for action in actions:
- op = action.get("action", "KEEP")
- ids = action.get("target_ids", [])
- reason = action.get("reason", "")
- summary_lines.append(f"- **{op}** {', '.join(ids)}: {reason}")
+ if not store.skill_exists(skill_name):
+ available = "、".join(store.list_skill_names()) or "(无可用 Skill)"
+ return {
+ "output": f"未找到 Skill '{skill_name}'。当前可用:{available}",
+ "result_type": "error",
+ }
- if dry_run:
+ archives = store.list_archives(skill_name)
+ body_versions = [a for a in archives if a.startswith("SKILL.v")]
+ if not body_versions:
+ return {
+ "output": f"Skill '{skill_name}' 没有归档版本可回滚。",
+ "result_type": "error",
+ }
+
+ # No version specified → list available versions for user to pick
+ if not version:
+ lines = [f"**Skill '{skill_name}' 可用归档版本(最新在前):**\n"]
+ for i, v in enumerate(body_versions):
+ ts = v.replace("SKILL.v", "").replace(".md", "")
+ if len(ts) >= 15:
+ display_ts = f"{ts[:4]}-{ts[4:6]}-{ts[6:8]} {ts[9:11]}:{ts[11:13]}:{ts[13:15]} UTC"
+ else:
+ display_ts = ts
+ marker = " ← 最近" if i == 0 else ""
+ lines.append(f" {i+1}. `{v}` ({display_ts}){marker}")
+ lines.append(f"\n用法:`/evolve_rollback {skill_name} SKILL.v<时间戳>.md`")
+ lines.append(f"快捷回滚到最近版本:`/evolve_rollback {skill_name} latest`")
+ return {"output": "\n".join(lines), "result_type": "answer"}
+
+ # "latest" shorthand → pick newest
+ if version == "latest":
+ version = body_versions[0]
+
+ if version not in body_versions:
+ hint = "、".join(f"`{v}`" for v in body_versions[:5])
+ return {
+ "output": f"版本 `{version}` 不存在。可用版本:{hint}",
+ "result_type": "error",
+ }
+
+ try:
+ success = await rail.rollback_skill(skill_name, version)
+ except Exception as exc:
+ logger.warning("[JiuWenClaw] evolve_rollback failed: %s", exc)
+ return {"output": f"回滚失败:{exc}", "result_type": "error"}
+
+ if success:
return {
"output": (
- f"**Skill '{skill_name}' 整理预览(dry-run,未执行):**\n\n"
- + "\n".join(summary_lines)
+ f"Skill '{skill_name}' 已成功回滚到 `{version}`。\n\n"
+ f"(当前状态已自动归档,可再次回滚恢复。)"
),
"result_type": "answer",
}
-
- result_text = await scorer.execute_simplify_actions(store, skill_name, actions)
return {
- "output": (
- f"**Skill '{skill_name}' 整理完成:** {result_text}\n\n"
- f"**操作详情:**\n" + "\n".join(summary_lines)
- ),
- "result_type": "answer",
+ "output": f"Skill '{skill_name}' 回滚失败,请检查归档版本是否有效。",
+ "result_type": "error",
}
+ async def _handle_governance_approval(
+ self, request_id: str, answers: list, kind: str
+ ) -> bool:
+ """Unified handler for simplify/rebuild governance approvals."""
+ rail = self._skill_evolution_rail
+ if rail is None:
+ logger.warning("[JiuWenClaw] governance approval failed: no SkillEvolutionRail")
+ return False
+
+ accept_labels = {"执行", "重建"} if kind in ("simplify", "rebuild") else set()
+ accepted = any(
+ isinstance(ans, dict)
+ and bool(accept_labels & set(ans.get("selected_options", [])))
+ for ans in answers
+ )
+
+ if kind == "simplify":
+ if accepted:
+ await rail.on_approve_simplify(request_id)
+ else:
+ await rail.on_reject_simplify(request_id)
+ elif kind == "rebuild":
+ if accepted:
+ await rail.on_approve_rebuild(request_id)
+ else:
+ await rail.on_reject_rebuild(request_id)
+
+ logger.info(
+ "[JiuWenClaw] governance %s %s: request_id=%s",
+ kind, "accepted" if accepted else "rejected", request_id,
+ )
+ return True
+
def _ensure_evolution_rail_for_slash(self, mode: str) -> str | None:
"""Check evolution availability for slash commands; lazily init rail if needed.
@@ -3207,6 +3438,18 @@ class JiuWenClawDeepAdapter:
return {"output": err, "result_type": "error"}
return await self._handle_evolve_simplify_command(stripped)
+ if stripped.startswith("/evolve_rebuild"):
+ err = self._ensure_evolution_rail_for_slash(mode)
+ if err:
+ return {"output": err, "result_type": "error"}
+ return await self._handle_evolve_rebuild_command(stripped)
+
+ if stripped.startswith("/evolve_rollback"):
+ err = self._ensure_evolution_rail_for_slash(mode)
+ if err:
+ return {"output": err, "result_type": "error"}
+ return await self._handle_evolve_rollback_command(stripped)
+
if stripped.startswith("/evolve_list"):
err = self._ensure_evolution_rail_for_slash(mode)
if err:
@@ -3441,8 +3684,6 @@ class JiuWenClawDeepAdapter:
has_streamed_content = False
accumulated_text = ""
accumulated_reasoning = ""
- evolution_status_started = False
- evolution_status_ended = False
usage_accumulator = {
"input_tokens": 0,
"output_tokens": 0,
@@ -3574,19 +3815,6 @@ class JiuWenClawDeepAdapter:
continue
if chunk_type == "answer":
- if (
- not evolution_status_started
- and self._skill_evolution_rail is not None
- and request.params.get("mode", "agent.plan") == "agent.plan"
- ):
- # Mark evolution phase start before after_invoke auto-evolution runs.
- yield AgentResponseChunk(
- request_id=rid,
- channel_id=cid,
- payload={"event_type": "chat.evolution_status", "status": "start"},
- is_complete=False,
- )
- evolution_status_started = True
if accumulated_text:
yield AgentResponseChunk(
request_id=rid,
@@ -3666,10 +3894,9 @@ class JiuWenClawDeepAdapter:
is_complete=False,
)
- # after_invoke 在流关闭后触发,其中缓存的审批事件无法通过
- # session.write_stream 传递,需手动注入到 stream 输出
if self._skill_evolution_rail is not None:
- for evt in self._skill_evolution_rail.drain_pending_approval_events():
+ drained_events = await self._skill_evolution_rail.drain_pending_approval_events(wait=False)
+ for evt in drained_events:
parsed = self._parse_stream_chunk(evt)
if parsed is not None:
yield AgentResponseChunk(
@@ -3678,15 +3905,11 @@ class JiuWenClawDeepAdapter:
payload=parsed,
is_complete=False,
)
-
- if evolution_status_started and not evolution_status_ended:
- yield AgentResponseChunk(
- request_id=rid,
- channel_id=cid,
- payload={"event_type": "chat.evolution_status", "status": "end"},
- is_complete=False,
+ task = asyncio.create_task(
+ self._watch_evolution_and_push(rid, cid, session_id)
)
- evolution_status_ended = True
+ task.add_done_callback(self._on_evolution_watcher_done)
+ self._evolution_watcher_tasks.add(task)
except asyncio.CancelledError:
logger.info(
"[JiuWenClawDeepAdapter] 流式任务被取消: request_id=%s session_id=%s",
@@ -3696,14 +3919,6 @@ class JiuWenClawDeepAdapter:
raise
except Exception as exc:
logger.exception("[JiuWenClawDeepAdapter] 流式任务异常: %s", exc)
- if evolution_status_started and not evolution_status_ended:
- yield AgentResponseChunk(
- request_id=rid,
- channel_id=cid,
- payload={"event_type": "chat.evolution_status", "status": "end"},
- is_complete=False,
- )
- evolution_status_ended = True
yield AgentResponseChunk(
request_id=rid,
channel_id=cid,
@@ -4072,3 +4287,91 @@ class JiuWenClawDeepAdapter:
}
return response
+
+ async def _watch_evolution_and_push(self, rid: str, cid: str, session_id: str) -> None:
+ """等待演进后台 task 完成,通过 send_push 推送审批事件。
+
+ 审批事件必须先于 evolution_status:end 推送,否则 Gateway 在清除
+ evolution_in_progress 和标记 pending_approval 之间存在竞争窗口。
+ """
+ from jiuwenclaw.agentserver.gateway_push import WebSocketGatewayPushTransport
+
+ transport = WebSocketGatewayPushTransport()
+
+ async def _push_status(status: str, stage: str, message: str = "") -> None:
+ await transport.send_push({
+ "request_id": rid,
+ "channel_id": cid,
+ "session_id": session_id,
+ "payload": {
+ "event_type": "chat.evolution_status",
+ "status": status,
+ "stage": stage,
+ "message": message,
+ },
+ })
+
+ async def _push_approval(evt) -> None:
+ raw_payload = evt.payload if hasattr(evt, "payload") and isinstance(evt.payload, dict) else evt
+ # Inject event_type from OutputSchema.type so Gateway routes it correctly.
+ payload = dict(raw_payload)
+ evt_type = getattr(evt, "type", None)
+ if evt_type and "event_type" not in payload:
+ payload["event_type"] = evt_type
+ await transport.send_push({
+ "request_id": rid,
+ "channel_id": cid,
+ "session_id": session_id,
+ "payload": payload,
+ })
+
+ timed_out = False
+ try:
+ await _push_status("start", "collecting", "Running evolution analysis...")
+
+ if self._skill_evolution_rail is not None:
+ events = await self._skill_evolution_rail.drain_pending_approval_events(
+ wait=True, timeout=300
+ )
+ await self._skill_evolution_rail.cleanup_background_tasks()
+ else:
+ events = []
+
+ if not events:
+ timed_out = True
+
+ for evt in events:
+ if self._is_approval_event(evt):
+ await _push_approval(evt)
+
+ if timed_out:
+ await _push_status("end", "timed_out", "Evolution analysis timed out")
+ else:
+ await _push_status("end", "completed", "Evolution analysis completed")
+ except Exception as exc:
+ logger.warning("[JiuWenClawDeepAdapter] evolution watcher failed: %s", exc)
+ try:
+ await _push_status("end", "failed", f"Evolution analysis failed: {exc}")
+ except Exception:
+ pass
+
+ def _on_evolution_watcher_done(self, task: asyncio.Task) -> None:
+ """Callback when an evolution watcher task completes.
+
+ Discards the task from the tracking set and logs any exception.
+ """
+ self._evolution_watcher_tasks.discard(task)
+ try:
+ task.result()
+ except Exception as exc:
+ logger.warning("[JiuWenClawDeepAdapter] evolution watcher task exception: %s", exc)
+
+ @staticmethod
+ def _is_approval_event(evt) -> bool:
+ """Check whether an OutputSchema event is an approval request."""
+ evt_type = getattr(evt, "type", "")
+ if evt_type == "chat.ask_user_question":
+ return True
+ if hasattr(evt, "payload") and isinstance(evt.payload, dict):
+ return evt.payload.get("event_type") == "chat.ask_user_question"
+ return False
diff --git a/jiuwenclaw/agentserver/deep_agent/team_helpers.py b/jiuwenclaw/agentserver/deep_agent/team_helpers.py
index 2dc8c03965..d3ccf5e751 100644
--- a/jiuwenclaw/agentserver/deep_agent/team_helpers.py
+++ b/jiuwenclaw/agentserver/deep_agent/team_helpers.py
@@ -29,7 +29,24 @@ def _waiter_key(channel_id: str | None, session_id: str) -> tuple[str, str]:
return _resolve_channel_id(channel_id), session_id
-def _broadcast_event(channel_id: str | None, session_id: str, event: dict[str, Any]) -> None:
+async def _drain_team_skill_approval_events(
+ channel_id: str | None,
+ session_id: str,
+) -> None:
+ """Drain buffered TeamSkillRail approval events and broadcast them."""
+ try:
+ tm = get_team_manager()
+ for evt in await tm.drain_team_skill_events(session_id):
+ parsed = parse_stream_chunk(evt)
+ if parsed is not None:
+ _broadcast_event(channel_id, session_id, parsed)
+ except Exception as exc:
+ logger.warning("[TeamHelpers] drain team skill events failed: %s", exc)
+
+
+def _broadcast_event(
+ channel_id: str | None, session_id: str, event: dict[str, Any]
+) -> None:
"""Broadcast an event to all request queues waiting on the same channel/session."""
waiter_key = _waiter_key(channel_id, session_id)
waiters = _pending_waiters.get(waiter_key, [])
@@ -111,7 +128,9 @@ async def process_team_message_stream(
session_id,
)
except Exception as exc:
- logger.warning("[TeamHelpers] Monitor start failed, continue without it: %s", exc)
+ logger.warning(
+ "[TeamHelpers] Monitor start failed, continue without it: %s", exc
+ )
stream_task = asyncio.create_task(
_consume_stream_with_query(
@@ -143,7 +162,10 @@ async def process_team_message_stream(
yield AgentResponseChunk(
request_id=rid,
channel_id=channel_id,
- payload={"event_type": "chat.error", "error": "interact failed"},
+ payload={
+ "event_type": "chat.error",
+ "error": "interact failed",
+ },
is_complete=False,
)
yield AgentResponseChunk(
@@ -180,7 +202,10 @@ async def process_team_message_stream(
payload=event,
is_complete=False,
)
- if isinstance(event, dict) and event.get("event_type") == "team.error":
+ if (
+ isinstance(event, dict)
+ and event.get("event_type") == "team.error"
+ ):
break
except asyncio.TimeoutError:
if not team_manager.has_stream_task(session_id):
@@ -230,6 +255,22 @@ async def process_team_message_stream(
)
+_DRAIN_INTERVAL_SEC = 5
+
+
+async def _periodic_drain(
+ channel_id: str | None,
+ session_id: str,
+) -> None:
+ """Periodically drain buffered approval events in the background."""
+ while True:
+ await asyncio.sleep(_DRAIN_INTERVAL_SEC)
+ try:
+ await _drain_team_skill_approval_events(channel_id, session_id)
+ except Exception as exc:
+ logger.debug("[TeamHelpers] periodic drain failed: %s", exc)
+
+
async def _consume_stream_with_query(
channel_id: str | None,
session_id: str,
@@ -237,6 +278,10 @@ async def _consume_stream_with_query(
initial_query: str,
) -> None:
"""Consume the team stream in the background and broadcast parsed events."""
+ drain_task = asyncio.create_task(
+ _periodic_drain(channel_id, session_id),
+ name=f"periodic_drain_{session_id}",
+ )
try:
logger.info(
"[TeamHelpers] stream started: channel_id=%s session_id=%s",
@@ -251,6 +296,7 @@ async def _consume_stream_with_query(
parsed = parse_stream_chunk(chunk)
if parsed is not None:
_broadcast_event(channel_id, session_id, parsed)
+ await _drain_team_skill_approval_events(channel_id, session_id)
logger.warning(
"[TeamHelpers] stream ended unexpectedly: channel_id=%s session_id=%s",
@@ -281,8 +327,38 @@ async def _consume_stream_with_query(
},
)
finally:
- team_manager = get_team_manager(channel_id)
- team_manager.pop_stream_task(session_id)
+ drain_task.cancel()
+ try:
+ await drain_task
+ except asyncio.CancelledError:
+ pass
+
+ # Final drain for any events buffered right before stream exit.
+ try:
+ await _drain_team_skill_approval_events(channel_id, session_id)
+ except Exception as exc:
+ logger.warning("[TeamHelpers] final drain failed: %s", exc)
+
+ # Launch watcher task to await evolution completion and push approval.
+ tm = get_team_manager(channel_id)
+ rail = tm.get_team_skill_rail(session_id)
+ if rail is not None:
+ logger.info(
+ "[TeamHelpers] launching evolution watcher: channel_id=%s session_id=%s",
+ channel_id,
+ session_id,
+ )
+ task = asyncio.create_task(
+ _watch_team_evolution_and_push(channel_id, session_id, rail)
+ )
+ task.add_done_callback(_on_team_watcher_done)
+ else:
+ logger.warning(
+ "[TeamHelpers] no TeamSkillRail found, evolution watcher not launched: session_id=%s",
+ session_id,
+ )
+
+ tm.pop_stream_task(session_id)
async def _consume_monitor_events(
@@ -321,3 +397,95 @@ async def _consume_monitor_events(
)
+def _on_team_watcher_done(task: asyncio.Task) -> None:
+ """Callback when a team evolution watcher task completes."""
+ exc = task.exception()
+ if exc is not None:
+ logger.warning("[TeamHelpers] evolution watcher task exception: %s", exc)
+
+
+async def _watch_team_evolution_and_push(
+ channel_id: str | None,
+ session_id: str,
+ rail: Any,
+) -> None:
+ """Wait for TeamSkillRail background evolution to complete, push approval via send_push."""
+ from jiuwenclaw.agentserver.gateway_push import WebSocketGatewayPushTransport
+
+ transport = WebSocketGatewayPushTransport()
+ rid = f"team_evolve_{session_id}"
+
+ async def _push_status(status: str, stage: str, message: str = "") -> None:
+ await transport.send_push(
+ {
+ "request_id": rid,
+ "channel_id": channel_id or "default",
+ "session_id": session_id,
+ "payload": {
+ "event_type": "chat.evolution_status",
+ "status": status,
+ "stage": stage,
+ "message": message,
+ },
+ }
+ )
+
+ async def _push_approval(evt) -> None:
+ raw_payload = (
+ evt.payload
+ if hasattr(evt, "payload") and isinstance(evt.payload, dict)
+ else evt
+ )
+ # Inject event_type from OutputSchema.type so Gateway routes it correctly.
+ payload = dict(raw_payload)
+ evt_type = getattr(evt, "type", None)
+ if evt_type and "event_type" not in payload:
+ payload["event_type"] = evt_type
+ await transport.send_push(
+ {
+ "request_id": rid,
+ "channel_id": channel_id or "default",
+ "session_id": session_id,
+ "payload": payload,
+ }
+ )
+
+ def _is_approval(evt) -> bool:
+ evt_type = getattr(evt, "type", "")
+ if evt_type == "chat.ask_user_question":
+ return True
+ if hasattr(evt, "payload") and isinstance(evt.payload, dict):
+ return evt.payload.get("event_type") == "chat.ask_user_question"
+ return False
+
+ try:
+ # 1. Push evolution start status.
+ await _push_status(
+ "start", "collecting", "Running team skill evolution analysis..."
+ )
+
+ # 2. Wait for SDK background evolution task to complete and retrieve approval events.
+ events = await rail.drain_pending_approval_events(wait=True, timeout=300)
+
+ # 3. Push approval events first (filter out llm_reasoning progress events).
+ for evt in events:
+ if _is_approval(evt):
+ try:
+ await _push_approval(evt)
+ except Exception as exc:
+ logger.warning(
+ "[TeamHelpers] push approval failed for event type=%s: %s",
+ getattr(evt, "type", "unknown"),
+ exc,
+ )
+
+ # 4. Push evolution end status last.
+ await _push_status(
+ "end", "completed", "Team skill evolution analysis completed"
+ )
+ except Exception as exc:
+ logger.warning("[TeamHelpers] evolution watcher failed: %s", exc)
+ try:
+ await _push_status("end", "failed", f"团队技能演进分析失败: {exc}")
+ except Exception as push_exc:
+ logger.warning("[TeamHelpers] push status notification failed: %s", push_exc)
diff --git a/jiuwenclaw/agentserver/stream_utils.py b/jiuwenclaw/agentserver/stream_utils.py
index 913a0b5718..95bdf1989a 100644
--- a/jiuwenclaw/agentserver/stream_utils.py
+++ b/jiuwenclaw/agentserver/stream_utils.py
@@ -103,6 +103,15 @@ def _parse_typed_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Any
chunk_type = getattr(chunk, "type", "")
payload = getattr(chunk, "payload", {})
+ if isinstance(chunk_type, str) and "." in chunk_type:
+ if isinstance(payload, dict):
+ return {
+ "event_type": chunk_type,
+ **{k: _serialize_chunk_recursive(v) if isinstance(v, (dict, list)) else _serialize_value(v)
+ for k, v in payload.items()},
+ }
+ return {"event_type": chunk_type, "content": str(payload)}
+
if chunk_type == "controller_output" and payload is not None:
inner_t = getattr(payload, "type", None)
inner_val = (
diff --git a/jiuwenclaw/agentserver/team/config_loader.py b/jiuwenclaw/agentserver/team/config_loader.py
index 4d99eacd82..8f431984f4 100644
--- a/jiuwenclaw/agentserver/team/config_loader.py
+++ b/jiuwenclaw/agentserver/team/config_loader.py
@@ -87,7 +87,7 @@ def resolve_team_sqlite_db_path(config_base: dict[str, Any] | None = None) -> Pa
def _build_default_model_dict(config_base: dict[str, Any]) -> dict[str, Any]:
model_config = config_base.get("models", {}).get("default", {})
- model_client_config = model_config.get("model_client_config", {})
+ model_client_config = dict(model_config.get("model_client_config", {}))
model_request_config = dict(model_config.get("model_config_obj", {}))
model_name = model_client_config.get("model_name", "")
diff --git a/jiuwenclaw/agentserver/team/team_manager.py b/jiuwenclaw/agentserver/team/team_manager.py
index 070ef7a45f..a1d497221e 100644
--- a/jiuwenclaw/agentserver/team/team_manager.py
+++ b/jiuwenclaw/agentserver/team/team_manager.py
@@ -49,6 +49,7 @@ from jiuwenclaw.agentserver.team.team_runtime_inheritance import (
filter_inheritable_ability_cards,
get_default_model_name,
)
+from jiuwenclaw.utils import get_agent_skills_dir
logger = logging.getLogger(__name__)
@@ -62,6 +63,29 @@ _PG_POST_START_READY_BACKOFF = 1.45
_PG_POST_START_LOG_EVERY_SEC = 5.0
+def _sync_skills_dir(source: Path, target: Path) -> None:
+ """Copy every valid skill directory from *source* into *target*.
+
+ A valid skill is a sub-directory containing a ``SKILL.md`` file.
+ Existing skills in *target* are overwritten so the latest version
+ always wins.
+ """
+ if not source.is_dir():
+ return
+ target.mkdir(parents=True, exist_ok=True)
+ synced = 0
+ for skill_dir in source.iterdir():
+ if not skill_dir.is_dir() or not (skill_dir / "SKILL.md").is_file():
+ continue
+ dest = target / skill_dir.name
+ if dest.exists():
+ shutil.rmtree(dest)
+ shutil.copytree(skill_dir, dest)
+ synced += 1
+ if synced:
+ logger.info("[TeamManager] synced %d skills: %s -> %s", synced, source, target)
+
+
async def cleanup_team_runtime_state_once() -> tuple[list[str], list[str]]:
"""Clear leftover shared team runtime state once during AgentServer startup."""
from openjiuwen.agent_teams.paths import get_agent_teams_home
@@ -87,6 +111,10 @@ class TeamManager:
self._team_monitors: dict[str, TeamMonitorHandler] = {}
self._stream_tasks: dict[str, asyncio.Task] = {}
self._lock = asyncio.Lock()
+ # session_id → TeamSkillRail instance (set by customizer, used for drain/approval)
+ self._team_skill_rails: dict[str, Any] = {}
+ # session_id → (workspace_skills_dir, global_team_skills_dir)
+ self._team_skill_sync_targets: dict[str, tuple[Path, Path]] = {}
def has_stream_task(self, session_id: str) -> bool:
return session_id in self._stream_tasks
@@ -247,13 +275,20 @@ class TeamManager:
)
from jiuwenclaw.agentserver.skill_manager import SkillManager
from jiuwenclaw.agentserver.extensions.rail_manager import get_rail_manager
- from jiuwenclaw.utils import get_agent_skills_dir
global_skills_dir = get_agent_skills_dir()
global_skills_state_path = global_skills_dir / "skills_state.json"
resolved_channel = channel_id or "default"
resolved_model_name = get_default_model_name()
+ # Resolve team shared workspace skills directory for TeamSkillRail.
+ ws_config = spec.workspace
+ team_ws_root = (
+ ws_config.root_path if ws_config and ws_config.root_path
+ else str(team_home(spec.team_name) / "team-workspace")
+ )
+ team_ws_skills_dir = Path(team_ws_root) / "skills"
+
def resolve_member_spec(
member_name: str | None,
role: str | None,
@@ -434,8 +469,10 @@ class TeamManager:
)
member_workspace = agent.deep_config.workspace if agent.deep_config else None
+ member_skills_dir_resolved: Path | None = None
if member_workspace and member_workspace.root_path:
member_skills_dir = Path(member_workspace.root_path) / "skills"
+ member_skills_dir_resolved = member_skills_dir
skills_configured, selected_skills = resolve_member_skills(member_name, role)
# Copy member-configured skills to member's own skills directory
@@ -464,20 +501,43 @@ class TeamManager:
except Exception as exc:
logger.warning("[TeamManager] MemberSkillToolkitRail setup failed: %s", exc)
- try:
- member_rails = build_member_rails(
- skills_dir=str(member_skills_dir),
- language="cn",
- channel=resolved_channel,
+ # Build all member rails (common + skill rails via role).
+ try:
+ member_rails = build_member_rails(
+ skills_dir=str(member_skills_dir_resolved) if member_skills_dir_resolved else "",
+ language="cn",
+ channel=resolved_channel,
+ agent_name=getattr(agent.card, "name", "team_member"),
+ model_name=resolved_model_name,
+ role=role,
+ team_ws_skills_dir=str(team_ws_skills_dir),
+ )
+ from openjiuwen.harness.rails.team_skill_rail import TeamSkillRail
+ team_skill_rail: Any | None = None
+ for rail in member_rails:
+ if type(rail).__name__ in RAIL_WHITELIST:
+ agent.add_rail(rail)
+ else:
+ logger.debug("[TeamManager] Skipping non-whitelisted rail: %s", type(rail).__name__)
+ if isinstance(rail, TeamSkillRail):
+ team_skill_rail = rail
+ logger.info("[TeamManager] Added %d rails for team member", len(member_rails))
+ # Register TeamSkillRail with TeamManager for approval/sync.
+ if team_skill_rail is not None:
+ tm = get_team_manager()
+ tm.register_team_skill_rail(session_id, team_skill_rail)
+ tm.register_team_skill_sync_target(
+ session_id,
+ team_ws_skills_dir,
+ get_agent_skills_dir(),
)
- for rail in member_rails:
- if type(rail).__name__ in RAIL_WHITELIST:
- agent.add_rail(rail)
- else:
- logger.debug("[TeamManager] Skipping non-whitelisted rail: %s", type(rail).__name__)
- logger.info("[TeamManager] Added %d rails for team member", len(member_rails))
- except Exception as exc:
- logger.warning("[TeamManager] build_member_rails failed: %s", exc)
+ logger.info(
+ "[TeamManager] TeamSkillRail mounted on leader "
+ "(skills_dir=%s, sync_target=%s)",
+ team_ws_skills_dir, get_agent_skills_dir(),
+ )
+ except Exception as exc:
+ logger.warning("[TeamManager] build_member_rails failed: %s", exc)
rail_manager = get_rail_manager()
for rail_name in rail_manager.get_registered_rail_names():
@@ -531,8 +591,6 @@ class TeamManager:
@staticmethod
def _copy_global_skills_to_team_shared_dir(spec: TeamAgentSpec) -> None:
"""Copy global skills to team shared directory (executed once after team build)."""
- from jiuwenclaw.utils import get_agent_skills_dir
-
global_skills_dir = get_agent_skills_dir()
if not global_skills_dir.exists():
logger.warning("[TeamManager] global_skills_dir does not exist: %s", global_skills_dir)
@@ -671,6 +729,48 @@ class TeamManager:
logger.error("[TeamManager] interact failed: session_id=%s, error=%s", session_id, exc)
return False
+ # ── TeamSkillRail accessor ──────────────────────────────────
+
+ def get_team_skill_rail(self, session_id: str) -> Any | None:
+ return self._team_skill_rails.get(session_id)
+
+ def find_team_skill_rail_for_request(self, request_id: str) -> Any | None:
+ """Find the TeamSkillRail that owns a pending proposal/patch with this request_id."""
+ for rail in self._team_skill_rails.values():
+ if request_id in getattr(rail, "_pending_skill_proposals", {}):
+ return rail
+ if request_id in getattr(rail, "_pending_patch_snapshots", {}):
+ return rail
+ return None
+
+ async def drain_team_skill_events(self, session_id: str) -> list[dict]:
+ """Drain buffered approval events from this session's TeamSkillRail."""
+ rail = self._team_skill_rails.get(session_id)
+ if rail is None:
+ return []
+ return await rail.drain_pending_approval_events()
+
+ def register_team_skill_rail(self, session_id: str, rail: Any) -> None:
+ """Register a TeamSkillRail instance for the given session."""
+ self._team_skill_rails[session_id] = rail
+
+ def register_team_skill_sync_target(
+ self, session_id: str, source: Path, target: Path,
+ ) -> None:
+ """Register skill sync directories for the given session."""
+ self._team_skill_sync_targets[session_id] = (source, target)
+
+ # ── Skill sync helpers ──────────────────────────────────────
+
+ def sync_team_skills(self, session_id: str) -> None:
+ """Sync team skills from workspace dir to global team_skills dir after approval."""
+ sync_info = self._team_skill_sync_targets.get(session_id)
+ if sync_info is None:
+ logger.debug("[TeamManager] no sync target for session_id=%s", session_id)
+ return
+ source, target = sync_info
+ _sync_skills_dir(source, target)
+
async def destroy_team(self, session_id: str) -> bool:
async with self._lock:
return await self._destroy_team(session_id)
@@ -706,6 +806,10 @@ class TeamManager:
exc,
)
+ # Clean up sync state for the team skill rail.
+ self._team_skill_rails.pop(session_id, None)
+ self._team_skill_sync_targets.pop(session_id, None)
+
team_agent = self._team_agents.pop(session_id, None)
cleaned = False
try:
diff --git a/jiuwenclaw/agentserver/team/team_runtime_inheritance.py b/jiuwenclaw/agentserver/team/team_runtime_inheritance.py
index 3468c8b064..e35a0e4287 100644
--- a/jiuwenclaw/agentserver/team/team_runtime_inheritance.py
+++ b/jiuwenclaw/agentserver/team/team_runtime_inheritance.py
@@ -8,13 +8,17 @@ TeamMember 专用 Rail、Ability 继承逻辑,不依赖主 agent adapter。
from __future__ import annotations
import logging
+import os
+from pathlib import Path
from typing import Any
from openjiuwen.core.foundation.tool import ToolCard
from openjiuwen.harness.rails.filesystem_rail import FileSystemRail
from openjiuwen.harness.rails.heartbeat_rail import HeartbeatRail
from openjiuwen.harness.rails.security_rail import SecurityRail
+from openjiuwen.harness.rails.skill_evolution_rail import SkillEvolutionRail
from openjiuwen.harness.rails.task_planning_rail import TaskPlanningRail
+from openjiuwen.harness.rails.team_skill_rail import TeamSkillRail
from jiuwenclaw.agentserver.deep_agent.rails.avatar_rail import AvatarPromptRail
from jiuwenclaw.agentserver.deep_agent.rails.response_prompt_rail import ResponsePromptRail
@@ -32,6 +36,8 @@ RAIL_WHITELIST = frozenset({
"HeartbeatRail",
"AvatarPromptRail",
"FileSystemRail",
+ "TeamSkillRail",
+ "SkillEvolutionRail",
})
TOOL_WHITELIST = frozenset({
@@ -80,13 +86,17 @@ def build_member_rails(
skills_dir: str,
language: str = "cn",
channel: str = "default",
+ role: str | None = None,
+ team_ws_skills_dir: str | None = None,
) -> list[Any]:
"""为 Team 成员创建 rails 列表.
Args:
- skills_dir: 兼容保留参数,当前不参与 skill rail 构造
+ skills_dir: 成员 skills 目录路径,非 leader 时用于 SkillEvolutionRail
language: 语言设置
channel: 渠道设置(使用真实 channel_id)
+ role: 成员角色,"leader" 时创建 TeamSkillRail
+ team_ws_skills_dir: 团队共享 workspace skills 目录,leader 角色时使用
Returns:
rail 实例列表
@@ -152,6 +162,32 @@ def build_member_rails(
except Exception as exc:
logger.warning("[TeamRuntime] AvatarPromptRail failed: %s", exc)
+ # Leader-only: TeamSkillRail for team skill evolution.
+ if role == "leader" and team_ws_skills_dir:
+ try:
+ Path(team_ws_skills_dir).mkdir(parents=True, exist_ok=True)
+ llm_model, actual_model_name = build_evolution_llm()
+ team_skill_rail = TeamSkillRail(
+ skills_dir=team_ws_skills_dir,
+ llm=llm_model,
+ model=actual_model_name,
+ language=language,
+ auto_save=False,
+ )
+ rails_list.append(team_skill_rail)
+ logger.info(
+ "[TeamRuntime] TeamSkillRail created: skills_dir=%s, model=%s",
+ team_ws_skills_dir, actual_model_name,
+ )
+ except Exception as exc:
+ logger.warning("[TeamRuntime] TeamSkillRail failed: %s", exc, exc_info=True)
+
+ # Non-leader: SkillEvolutionRail for member skill self-evolution.
+ if role != "leader" and skills_dir:
+ evo_rail = build_skill_evolution_rail(skills_dir=skills_dir)
+ if evo_rail is not None:
+ rails_list.append(evo_rail)
+
logger.info("[TeamRuntime] Total rails built: %d", len(rails_list))
return rails_list
@@ -211,3 +247,103 @@ def get_default_model_name(config: dict[str, Any] | None = None) -> str:
logger.warning("[TeamRuntime] Failed to resolve default model name: %s", exc)
return "gpt-4"
+
+
+def resolve_model_config(
+ config: dict[str, Any],
+) -> tuple[dict[str, Any], dict[str, Any], str]:
+ """从配置字典解析 model 相关参数.
+
+ Args:
+ config: 配置字典.
+
+ Returns:
+ (model_client_config dict, model_config_obj dict, model_name str).
+ """
+ model_configs = config.get("models", {}).copy()
+ default_model_config = model_configs.get("default", {}).copy()
+ react_config = config.get("react", {}).copy()
+
+ model_client_config = default_model_config.get("model_client_config") or {}
+ if not model_client_config:
+ model_client_config = react_config.get("model_client_config") or {}
+
+ model_name = (
+ model_client_config.get("model_name")
+ or react_config.get("model_name")
+ or "gpt-4"
+ )
+
+ model_config_obj = default_model_config.get("model_config_obj") or {}
+ if not model_config_obj:
+ model_config_obj = react_config.get("model_config_obj") or {}
+
+ return model_client_config, model_config_obj, model_name
+
+
+def build_evolution_llm(
+ config: dict[str, Any] | None = None,
+) -> tuple[Any, str]:
+ """从配置构造 evolution 使用的 LLM Model 实例.
+
+ Args:
+ config: 可选配置字典,为 None 时自动加载.
+
+ Returns:
+ (Model 实例, model_name 字符串) 元组.
+ """
+ from openjiuwen.core.foundation.llm import (
+ Model, ModelClientConfig, ModelRequestConfig,
+ )
+
+ if config is None:
+ from jiuwenclaw.config import get_config
+ config = get_config()
+
+ model_client_config, model_config_obj, model_name = resolve_model_config(config)
+
+ request_config = ModelRequestConfig(
+ model=model_name,
+ temperature=model_config_obj.get("temperature", 0.95),
+ )
+ client_config = ModelClientConfig(**model_client_config)
+ return Model(model_client_config=client_config, model_config=request_config), model_name
+
+
+def build_skill_evolution_rail(
+ skills_dir: str,
+ config: dict[str, Any] | None = None,
+) -> Any | None:
+ """为 Team member 构造 SkillEvolutionRail.
+
+ Args:
+ skills_dir: 技能目录路径.
+ config: 可选配置字典.
+
+ Returns:
+ SkillEvolutionRail 实例,失败返回 None.
+ """
+ try:
+ llm, model_name = build_evolution_llm(config)
+ _env_auto_scan = os.getenv("EVOLUTION_AUTO_SCAN")
+ if _env_auto_scan is not None:
+ evolution_auto_scan: bool = _env_auto_scan.lower() in ("true", "1", "yes")
+ else:
+ evolution_auto_scan = (config or {}).get("evolution", {}).get("auto_scan", False)
+
+ rail = SkillEvolutionRail(
+ skills_dir=skills_dir,
+ llm=llm,
+ model=model_name,
+ auto_scan=evolution_auto_scan,
+ auto_save=True,
+ )
+ logger.info(
+ "[TeamRuntime] SkillEvolutionRail created: model=%s, auto_scan=%s",
+ model_name,
+ evolution_auto_scan,
+ )
+ return rail
+ except Exception as exc:
+ logger.warning("[TeamRuntime] SkillEvolutionRail creation failed: %s", exc, exc_info=True)
+ return None
diff --git a/jiuwenclaw/config.py b/jiuwenclaw/config.py
index 6cc0e09890..ee25bb1ed5 100644
--- a/jiuwenclaw/config.py
+++ b/jiuwenclaw/config.py
@@ -76,10 +76,32 @@ def resolve_env_vars(value: Any) -> Any:
return value
+def _normalize_config(config: dict[str, Any]) -> None:
+ """后处理配置,将需要结构化的字符串字段解析为原生类型。
+
+ 例如 custom_headers 在 YAML 中通过环境变量传入时是 JSON 字符串,
+ 需要统一解析为 dict。
+ """
+ models = config.get("models", {})
+ if isinstance(models, dict):
+ for entry in models.values():
+ if isinstance(entry, dict):
+ mcc = entry.get("model_client_config")
+ if isinstance(mcc, dict) and "custom_headers" in mcc:
+ mcc["custom_headers"] = _parse_custom_headers(mcc["custom_headers"])
+
+ react = config.get("react", {})
+ if isinstance(react, dict):
+ mcc = react.get("model_client_config")
+ if isinstance(mcc, dict) and "custom_headers" in mcc:
+ mcc["custom_headers"] = _parse_custom_headers(mcc["custom_headers"])
+
+
def get_config():
with open(get_config_file(), "r", encoding="utf-8") as f:
config_base = yaml.safe_load(f)
config_base = resolve_env_vars(config_base)
+ _normalize_config(config_base)
return config_base
diff --git a/jiuwenclaw/gateway/message_handler.py b/jiuwenclaw/gateway/message_handler.py
index 559cc91da8..17ce8b8409 100644
--- a/jiuwenclaw/gateway/message_handler.py
+++ b/jiuwenclaw/gateway/message_handler.py
@@ -1237,6 +1237,9 @@ class MessageHandler(ABC):
)
return
+ # Track evolution state on the server_push path as well.
+ self._handle_evolution_chunk(chunk, session_id)
+
out = self._chunk_to_message(
chunk, session_id=session_id, metadata=bus_metadata
)
@@ -1459,10 +1462,13 @@ class MessageHandler(ABC):
@staticmethod
def _is_evolution_approval_request_id(request_id: Any) -> bool:
- # Support skill evolution (skill_evolve_*) and new skill creation (skill_create*)
+ # Support skill evolution (skill_evolve_*), new skill creation (skill_create_*),
+ # and team skill evolution/creation (team_skill_evolve_*, team_skill_create_*).
return isinstance(request_id, str) and (
request_id.startswith("skill_evolve_") or
- request_id.startswith("skill_create_")
+ request_id.startswith("skill_create_") or
+ request_id.startswith("team_skill_evolve_") or
+ request_id.startswith("team_skill_create_")
)
def _queue_supplement_input(
@@ -1507,6 +1513,44 @@ class MessageHandler(ABC):
def _is_session_evolution_in_progress(self, session_id: str | None) -> bool:
return isinstance(session_id, str) and session_id in self._session_evolution_in_progress
+ def _handle_evolution_chunk(self, chunk, session_id: str | None) -> None:
+ """处理 chunk 中的演进状态和审批事件,更新 Gateway 状态机。
+
+ 在 process_stream 和 _handle_agent_server_push 两条路径中复用。
+ """
+ if not isinstance(chunk.payload, dict):
+ return
+ event_type = chunk.payload.get("event_type")
+ if event_type == "chat.evolution_status":
+ status = str(chunk.payload.get("status", "")).strip().lower()
+ if status == "start":
+ self._mark_session_evolution_in_progress(session_id)
+ rid = getattr(chunk, "request_id", "")
+ logger.info(
+ "[MessageHandler] evolution status start: session_id=%s request_id=%s",
+ session_id,
+ rid,
+ )
+ elif status == "end":
+ self._clear_session_evolution_in_progress(session_id)
+ rid = getattr(chunk, "request_id", "")
+ logger.info(
+ "[MessageHandler] evolution status end: session_id=%s request_id=%s",
+ session_id,
+ rid,
+ )
+ approval_request_id = chunk.payload.get("request_id")
+ if (
+ event_type == "chat.ask_user_question"
+ and self._is_evolution_approval_request_id(approval_request_id)
+ ):
+ self._mark_pending_evolution_approval(session_id, approval_request_id)
+ logger.info(
+ "[MessageHandler] evolution approval detected: session_id=%s request_id=%s",
+ session_id,
+ approval_request_id,
+ )
+
def _clear_session_evolution_states(self, session_id: str | None) -> None:
self._clear_session_evolution_in_progress(session_id)
self._clear_pending_evolution_approval(session_id)
@@ -1540,7 +1584,7 @@ class MessageHandler(ABC):
is_stream=True,
)
- async def _process_non_stream_request(self, msg: "Message", env: "E2AEnvelope") -> None:
+ async def _process_non_stream_request(self, msg: "Message", env: "E2AEnvelope") -> Any:
"""执行单次非流式 Agent 请求并将结果写入 robot_messages(供串行或后台任务复用)。"""
try:
resp = await self._agent_client.send_request(env)
@@ -1555,6 +1599,7 @@ class MessageHandler(ABC):
resp.request_id,
resp.channel_id,
)
+ return resp
except Exception as e:
logger.exception("AgentServer send_request failed for %s: %s", msg.id, e)
err_msg = self._build_error_out_message(msg, e)
@@ -1564,6 +1609,7 @@ class MessageHandler(ABC):
msg.id,
msg.channel_id,
)
+ return None
# ---------- 入队 -> AgentServer -> 出队 转发循环 ----------
@@ -1593,28 +1639,41 @@ class MessageHandler(ABC):
# 检查是否是中断请求
if msg.req_method == ReqMethod.CHAT_ANSWER:
- # 先正常转发用户审批答案,再按会话自动派发排队的新输入
agent_msg = await self._prepare_agent_dispatch_message(msg)
env = self.message_to_e2a(agent_msg)
- await self._process_non_stream_request(msg, env)
+ resp = await self._process_non_stream_request(msg, env)
answer_request_id = (msg.params or {}).get("request_id")
if self._is_evolution_approval_request_id(answer_request_id):
- self._clear_pending_evolution_approval(msg.session_id)
- self._clear_session_evolution_in_progress(msg.session_id)
- queued_payload = self._pop_queued_supplement_input(msg.session_id)
- queued_input = str((queued_payload or {}).get("new_input") or "").strip()
- queued_attachments = (queued_payload or {}).get("attachments")
- if queued_input:
- queued_msg = self._build_queued_chat_send_message(
- msg,
- queued_input,
- queued_attachments if isinstance(queued_attachments, list) else None,
- )
- self._user_messages.put_nowait(queued_msg)
+ # Check whether the response indicates the approval was actually resolved.
+ resolved = False
+ if resp is not None and hasattr(resp, "payload") and isinstance(resp.payload, dict):
+ resolved = resp.payload.get("resolved", False) is True
+ if resolved:
+ self._clear_pending_evolution_approval(msg.session_id)
+ self._clear_session_evolution_in_progress(msg.session_id)
+ queued_payload = self._pop_queued_supplement_input(msg.session_id)
+ queued_input = str((queued_payload or {}).get("new_input") or "").strip()
+ queued_attachments = (queued_payload or {}).get("attachments")
+ if queued_input:
+ queued_msg = self._build_queued_chat_send_message(
+ msg,
+ queued_input,
+ queued_attachments if isinstance(queued_attachments, list) else None,
+ )
+ self._user_messages.put_nowait(queued_msg)
+ logger.info(
+ "[MessageHandler] evolution approval answered (resolved), "
+ "queued supplement dispatched: id=%s session_id=%s",
+ queued_msg.id,
+ msg.session_id,
+ )
+ else:
logger.info(
- "[MessageHandler] evolution approval answered, queued supplement dispatched: id=%s session_id=%s",
- queued_msg.id,
+ "[MessageHandler] evolution approval answered but not resolved: "
+ "id=%s session_id=%s request_id=%s",
+ msg.id,
msg.session_id,
+ answer_request_id,
)
continue
@@ -1873,35 +1932,7 @@ class MessageHandler(ABC):
chunk.request_id,
)
continue
- if isinstance(chunk.payload, dict):
- event_type = chunk.payload.get("event_type")
- if event_type == "chat.evolution_status":
- status = str(chunk.payload.get("status", "")).strip().lower()
- if status == "start":
- self._mark_session_evolution_in_progress(session_id)
- logger.info(
- "[MessageHandler] evolution status start: session_id=%s request_id=%s",
- session_id,
- rid,
- )
- elif status == "end":
- self._clear_session_evolution_in_progress(session_id)
- logger.info(
- "[MessageHandler] evolution status end: session_id=%s request_id=%s",
- session_id,
- rid,
- )
- approval_request_id = chunk.payload.get("request_id")
- if (
- event_type == "chat.ask_user_question"
- and self._is_evolution_approval_request_id(approval_request_id)
- ):
- self._mark_pending_evolution_approval(session_id, approval_request_id)
- logger.info(
- "[MessageHandler] evolution approval detected: session_id=%s request_id=%s",
- session_id,
- approval_request_id,
- )
+ self._handle_evolution_chunk(chunk, session_id)
# 携带 request metadata,供 Feishu/Xiaoyi 用平台身份回发
# 检查是否是 processing_status=false 事件
payload = chunk.payload or {}
diff --git a/tests/unit_tests/agentserver/test_team_manager_skill_state.py b/tests/unit_tests/agentserver/test_team_manager_skill_state.py
index 0e353273ea..9e406c5097 100644
--- a/tests/unit_tests/agentserver/test_team_manager_skill_state.py
+++ b/tests/unit_tests/agentserver/test_team_manager_skill_state.py
@@ -37,7 +37,7 @@ def test_member_skill_state_inherits_marketplaces_and_rebuilds_installed_skills(
)
monkeypatch.setattr(
- "jiuwenclaw.utils.get_agent_skills_dir",
+ "jiuwenclaw.agentserver.team.team_manager.get_agent_skills_dir",
lambda: global_skills_dir,
)
monkeypatch.setattr(
diff --git a/tests/unit_tests/agentserver/test_team_runtime_inheritance.py b/tests/unit_tests/agentserver/test_team_runtime_inheritance.py
index 8ff0950801..3fb45fe159 100644
--- a/tests/unit_tests/agentserver/test_team_runtime_inheritance.py
+++ b/tests/unit_tests/agentserver/test_team_runtime_inheritance.py
@@ -3,11 +3,15 @@
"""Unit tests for team runtime inheritance helpers."""
from types import SimpleNamespace
+from unittest.mock import patch
from openjiuwen.core.foundation.tool import ToolCard
from jiuwenclaw.agentserver.team.team_runtime_inheritance import (
+ build_evolution_llm,
+ build_skill_evolution_rail,
filter_inheritable_ability_cards,
+ resolve_model_config,
)
@@ -51,3 +55,107 @@ def test_filter_inheritable_ability_cards_includes_extended_claw_tools():
assert "user_todos" in inherited_names
assert "task_tool" in inherited_names
assert "send_file_to_user" not in inherited_names
+
+
+# -- resolve_model_config tests --
+
+def test_resolve_model_config_from_default():
+ config = {
+ "models": {
+ "default": {
+ "model_client_config": {"model_name": "test-model", "api_key": "k1"},
+ "model_config_obj": {"temperature": 0.5},
+ }
+ },
+ "react": {},
+ }
+ client_cfg, model_cfg_obj, model_name = resolve_model_config(config)
+ assert client_cfg == {"model_name": "test-model", "api_key": "k1"}
+ assert model_cfg_obj == {"temperature": 0.5}
+ assert model_name == "test-model"
+
+
+def test_resolve_model_config_fallback_to_react():
+ config = {
+ "models": {"default": {}},
+ "react": {
+ "model_client_config": {"model_name": "react-model"},
+ "model_config_obj": {"temperature": 0.3},
+ },
+ }
+ client_cfg, model_cfg_obj, model_name = resolve_model_config(config)
+ assert client_cfg == {"model_name": "react-model"}
+ assert model_cfg_obj == {"temperature": 0.3}
+ assert model_name == "react-model"
+
+
+def test_resolve_model_config_default_name():
+ config = {"models": {"default": {}}, "react": {}}
+ client_cfg, model_cfg_obj, model_name = resolve_model_config(config)
+ assert client_cfg == {}
+ assert model_cfg_obj == {}
+ assert model_name == "gpt-4"
+
+
+# -- build_evolution_llm tests --
+
+def test_build_evolution_llm_from_config():
+ config = {
+ "models": {
+ "default": {
+ "model_client_config": {"model_name": "test-model"},
+ "model_config_obj": {"temperature": 0.5},
+ }
+ },
+ "react": {},
+ }
+ fake_model = object()
+ with patch("openjiuwen.core.foundation.llm.ModelClientConfig", return_value=None), \
+ patch("openjiuwen.core.foundation.llm.ModelRequestConfig"), \
+ patch("openjiuwen.core.foundation.llm.Model", return_value=fake_model):
+ model, model_name = build_evolution_llm(config)
+
+ assert model_name == "test-model"
+ assert model is fake_model
+
+
+def test_build_evolution_llm_fallback_to_react_config():
+ config = {
+ "models": {"default": {}},
+ "react": {
+ "model_client_config": {"model_name": "react-model"},
+ },
+ }
+ fake_model = object()
+ with patch("openjiuwen.core.foundation.llm.ModelClientConfig", return_value=None), \
+ patch("openjiuwen.core.foundation.llm.ModelRequestConfig"), \
+ patch("openjiuwen.core.foundation.llm.Model", return_value=fake_model):
+ model, model_name = build_evolution_llm(config)
+
+ assert model_name == "react-model"
+
+
+def test_build_evolution_llm_default_model_name():
+ config = {"models": {"default": {}}, "react": {}}
+ fake_model = object()
+ with patch("openjiuwen.core.foundation.llm.ModelClientConfig", return_value=None), \
+ patch("openjiuwen.core.foundation.llm.ModelRequestConfig"), \
+ patch("openjiuwen.core.foundation.llm.Model", return_value=fake_model):
+ model, model_name = build_evolution_llm(config)
+
+ assert model_name == "gpt-4"
+
+
+# -- build_skill_evolution_rail tests --
+
+def test_build_skill_evolution_rail_returns_none_on_invalid_config(tmp_path):
+ """When config is invalid for Model construction, should return None."""
+ result = build_skill_evolution_rail(
+ skills_dir=str(tmp_path / "nonexistent"),
+ config={
+ "models": {"default": {}},
+ "react": {},
+ },
+ )
+ # Will fail due to empty model_client_config, returning None
+ assert result is None
diff --git a/tests/unit_tests/agentserver/test_team_shared_skills.py b/tests/unit_tests/agentserver/test_team_shared_skills.py
index 7953dea8ee..35e7dbd41d 100644
--- a/tests/unit_tests/agentserver/test_team_shared_skills.py
+++ b/tests/unit_tests/agentserver/test_team_shared_skills.py
@@ -33,7 +33,7 @@ def test_copy_global_skills_to_team_shared_dir(tmp_path, monkeypatch):
)
monkeypatch.setattr(
- "jiuwenclaw.utils.get_agent_skills_dir",
+ "jiuwenclaw.agentserver.team.team_manager.get_agent_skills_dir",
lambda: global_skills_dir,
)
@@ -81,7 +81,7 @@ def test_copy_global_skills_not_copied_twice(tmp_path, monkeypatch):
(global_skills_dir / "skills_state.json").write_text("{}", encoding="utf-8")
monkeypatch.setattr(
- "jiuwenclaw.utils.get_agent_skills_dir",
+ "jiuwenclaw.agentserver.team.team_manager.get_agent_skills_dir",
lambda: global_skills_dir,
)
@@ -125,7 +125,7 @@ def test_member_configured_skills_copied_to_own_dir(tmp_path, monkeypatch):
)
monkeypatch.setattr(
- "jiuwenclaw.utils.get_agent_skills_dir",
+ "jiuwenclaw.agentserver.team.team_manager.get_agent_skills_dir",
lambda: global_skills_dir,
)
monkeypatch.setattr(
@@ -222,7 +222,7 @@ def test_member_no_configured_skills_has_state_file(tmp_path, monkeypatch):
)
monkeypatch.setattr(
- "jiuwenclaw.utils.get_agent_skills_dir",
+ "jiuwenclaw.agentserver.team.team_manager.get_agent_skills_dir",
lambda: global_skills_dir,
)
monkeypatch.setattr(
diff --git a/uv.lock b/uv.lock
index ee2582d5d6..2833ed85f7 100644
--- a/uv.lock
+++ b/uv.lock
@@ -2328,7 +2328,7 @@ wheels = [
[[package]]
name = "openjiuwen"
version = "0.1.11"
-source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#ebba9da59c3b818e855edfa75d03cb2aa9f56f47" }
+source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#cd52db103c1500f47a2b01a9e8f47904a2aacbde" }
dependencies = [
{ name = "a2a-sdk" },
{ name = "aiofiles" },