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(proactive recommendation):add proactive recommendation ability to remind user of the schedule, recommend skills to help user solve problems, or explore implicit needs.
Haowei_Dub9bfa4fc49c3
diff --git a/jiuwenswarm/agents/harness/common/recommendation/__init__.py b/jiuwenswarm/agents/harness/common/recommendation/__init__.pynew file mode 100644index 0000000000..1bd49238a4--- /dev/null+++ b/jiuwenswarm/agents/harness/common/recommendation/__init__.py@@ -0,0 +1,27 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Proactive recommendation system — background engine for profile extraction,+pain-point reasoning, task reminder, need exploration, and skill matching.++Modules:+- profile_extractor.py — UserProfile data model + persistence+- proactive_engine.py — Background tick loop (ProactiveEngine)+- proactive_actions.py — LLM prompts, decision types, skill discovery, push+- situation_report.py — Multi-session context aggregation for LLM+"""++from jiuwenswarm.agents.harness.common.recommendation.profile_extractor import (+ UserProfile,+ load_user_profile,+ save_user_profile,+)+from jiuwenswarm.agents.harness.common.recommendation.proactive_engine import (+ ProactiveEngine,+)++__all__ = [+ "UserProfile",+ "load_user_profile",+ "save_user_profile",+ "ProactiveEngine",+]diff --git a/jiuwenswarm/agents/harness/common/recommendation/calendar_source.py b/jiuwenswarm/agents/harness/common/recommendation/calendar_source.pynew file mode 100644index 0000000000..7677e8b4ed--- /dev/null+++ b/jiuwenswarm/agents/harness/common/recommendation/calendar_source.py@@ -0,0 +1,198 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Calendar data source for the proactive recommendation engine.++Pulls upcoming calendar events from a user-configured MCP calendar server+(declared under ``mcp.servers`` in config.yaml with a name containing+"calendar"). The engine calls :func:`fetch_calendar_events` each tick to+enrich the situation report with real schedule context.++Design notes:+- Pure data source; never raises. Any failure (no calendar server, MCP+ server not registered, transport error, unexpected payload) logs at debug+ and returns ``[]`` so the tick continues with conversation-only context.+- Does not hardcode a specific MCP calendar server's tool schema: it probes+ the server's tools for a known event-listing tool name and parses the+ result loosely.+- Runs against ``Runner.resource_mgr`` (the same singleton the AgentServer+ initializes at startup), so MCP servers registered from config are+ available here without extra wiring.+"""++from __future__ import annotations++import json+import logging+from datetime import datetime, timedelta, timezone+from typing import Any++logger = logging.getLogger(__name__)+++# Candidate MCP tool names that list calendar events, ordered by preference.+# Different calendar MCP servers name this tool differently; we probe each.+_EVENT_TOOL_CANDIDATES: tuple[str, ...] = (+ "list_events",+ "get_events",+ "search_events",+ "list_calendars", # some servers expose per-calendar listing+)++# Fields we try to extract from each event object (best-effort).+_EVENT_TITLE_KEYS = ("title", "summary", "subject", "name")+_EVENT_START_KEYS = ("start", "start_time", "dtStart", "startTime", "begin")+_EVENT_END_KEYS = ("end", "end_time", "dtEnd", "endTime", "finish")+_EVENT_LOCATION_KEYS = ("location", "place", "where")+++def _find_calendar_server_entry() -> dict[str, Any] | None:+ """Return the first enabled ``mcp.servers`` entry whose name contains 'calendar'."""+ from jiuwenswarm.common.config import get_mcp_servers++ for entry in get_mcp_servers():+ name = str(entry.get("name", "")).lower()+ if "calendar" in name and bool(entry.get("enabled", True)):+ return entry+ return None+++async def fetch_calendar_events(max_events: int = 10, lookahead_hours: int = 24) -> list[dict[str, Any]]:+ """Fetch upcoming calendar events from the configured MCP calendar server.++ Args:+ max_events: Cap on the number of events returned.+ lookahead_hours: Time window from now into the future to query.++ Returns:+ A list of normalized event dicts (keys: title, start, end, location).+ Empty list on any failure — never raises.+ """+ try:+ entry = _find_calendar_server_entry()+ if entry is None:+ logger.debug("[CalendarSource] no enabled calendar MCP server configured")+ return []+ server_name = str(entry.get("name", "")).strip()+ if not server_name:+ return []++ from openjiuwen.core.runner import Runner++ # Resolve the MCP tool: probe candidate names until one resolves.+ tool = await _resolve_event_tool(server_name)+ if tool is None:+ logger.debug(+ "[CalendarSource] no event-listing tool found on server '%s' "+ "(tried %s)", server_name, _EVENT_TOOL_CANDIDATES,+ )+ return []++ # Build the time window. Many calendar MCP servers accept ISO 8601.+ now = datetime.now(timezone.utc)+ start_iso = now.isoformat()+ end_iso = (now + timedelta(hours=lookahead_hours)).isoformat()++ out = await tool.invoke({"start": start_iso, "end": end_iso})+ events = _extract_events(out)+ if not events:+ logger.debug(+ "[CalendarSource] server '%s' returned no events for %s..%s",+ server_name, start_iso, end_iso,+ )+ return []++ normalized = [_normalize_event(ev) for ev in events]+ normalized = [e for e in normalized if e.get("title")]+ return normalized[:max_events]++ except Exception as exc:+ # Silent skip — the tick must not break because of a calendar hiccup.+ logger.debug("[CalendarSource] fetch failed (skipping): %s", exc, exc_info=True)+ return []+++async def _resolve_event_tool(server_name: str) -> Any | None:+ """Probe candidate tool names on the named MCP server; return the first MCPTool found."""+ from openjiuwen.core.runner import Runner++ resource_mgr = Runner.resource_mgr+ for candidate in _EVENT_TOOL_CANDIDATES:+ try:+ tool = await resource_mgr.get_mcp_tool(name=candidate, server_name=server_name)+ except Exception as exc:+ logger.debug("[CalendarSource] get_mcp_tool('%s') raised: %s", candidate, exc)+ continue+ # get_mcp_tool with string args returns a list[Tool]; take the first.+ if isinstance(tool, list):+ tool = tool[0] if tool else None+ if tool is not None:+ return tool+ return None+++def _extract_events(out: Any) -> list[Any]:+ """Loosely extract an events list from an MCP tool invoke() result.++ MCPTool.invoke returns ``{"result": <...>}`` where ``<...>`` may be a+ JSON string, a dict, or a list depending on the server. We normalize to+ a list of event dicts.+ """+ if not isinstance(out, dict):+ return []++ result = out.get("result", out)++ # result is often a JSON string (FastMCP returns content as text).+ if isinstance(result, str):+ try:+ result = json.loads(result)+ except (ValueError, TypeError):+ return []+ if isinstance(result, str): # double-encoded+ try:+ result = json.loads(result)+ except (ValueError, TypeError):+ return []++ # Unwrap common envelopes: {"events": [...]} / {"items": [...]} / raw list.+ if isinstance(result, dict):+ for key in ("events", "items", "data", "result"):+ val = result.get(key)+ if isinstance(val, list):+ return val+ # Single event object?+ if any(k in result for k in _EVENT_TITLE_KEYS):+ return [result]+ return []+ if isinstance(result, list):+ return result+ return []+++def _normalize_event(ev: Any) -> dict[str, Any]:+ """Pick the first present key from each candidate set into a flat dict."""+ if not isinstance(ev, dict):+ return {}+ return {+ "title": _first_present(ev, _EVENT_TITLE_KEYS) or "",+ "start": _first_present(ev, _EVENT_START_KEYS) or "",+ "end": _first_present(ev, _EVENT_END_KEYS) or "",+ "location": _first_present(ev, _EVENT_LOCATION_KEYS) or "",+ }+++def _first_present(d: dict[str, Any], keys: tuple[str, ...]) -> str | None:+ for k in keys:+ val = d.get(k)+ if val is None:+ continue+ # datetime objects / nested {dateTime: ...} envelopes+ if isinstance(val, dict):+ for sub in ("dateTime", "date", "value"):+ if val.get(sub):+ return str(val[sub])+ if isinstance(val, (list, tuple)) and val:+ return str(val[0])+ if val != "":+ return str(val)+ return Nonediff --git a/jiuwenswarm/agents/harness/common/recommendation/proactive_actions.py b/jiuwenswarm/agents/harness/common/recommendation/proactive_actions.pynew file mode 100644index 0000000000..9c645e9c04--- /dev/null+++ b/jiuwenswarm/agents/harness/common/recommendation/proactive_actions.py@@ -0,0 +1,408 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Proactive recommendation — decision types, skill discovery, rate limiting,+and LLM analysis helpers.++Prompts are in ``proactive_prompts.py``; the tick loop is in+``proactive_engine.py``; situation report in ``situation_report.py``;+agent build/trigger/init in ``proactive_adapter.py``. This file provides+the building blocks those modules call.+"""++from __future__ import annotations++import json+import logging+import re+import time+import threading+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++logger = logging.getLogger(__name__)++# ── Rate limiting ────────────────────────────────────────────────++# Note: max_recommend_per_day is configured in config.yaml, not hardcoded here+_daily_counts_lock = threading.Lock()+_daily_counts: dict[str, int] = {}+++def _today_key() -> str:+ from datetime import datetime, timezone+ return datetime.now(timezone.utc).strftime("%Y-%m-%d")+++def _today_recommend_count() -> int:+ with _daily_counts_lock:+ return _daily_counts.get(_today_key(), 0)+++def _increment_daily_count() -> int:+ with _daily_counts_lock:+ key = _today_key()+ _daily_counts[key] = _daily_counts.get(key, 0) + 1+ return _daily_counts[key]+++def _prune_daily_counts() -> None:+ """Remove entries older than 2 days."""+ from datetime import datetime, timedelta, timezone+ cutoff = (datetime.now(timezone.utc) - timedelta(days=2)).strftime("%Y-%m-%d")+ with _daily_counts_lock:+ keys_to_remove = [k for k in _daily_counts if k < cutoff]+ for k in keys_to_remove:+ _daily_counts.pop(k, None)+++# ── Cooldown ─────────────────────────────────────────────────────++_COOLDOWN_HOURS = 24+_COOLDOWN_SECONDS = _COOLDOWN_HOURS * 3600+++def _is_cooled_down(target: str, profile: Any, hours: int = _COOLDOWN_HOURS) -> bool:+ """Check if target is cooled down, using persisted cooldown records from profile."""+ cooldown_records = getattr(profile, "cooldown_records", {})+ last = cooldown_records.get(target, 0.0)+ return (time.time() - last) >= hours * 3600 # hours*3600 而非 _COOLDOWN_SECONDS:保留 hours 参数可被外部覆盖+++def _mark_recommended(target: str, profile: Any) -> None:+ """Mark target as recommended, persisting to profile's cooldown records."""+ if not hasattr(profile, "cooldown_records"):+ profile.cooldown_records = {}+ profile.cooldown_records[target] = time.time()+++def _prune_cooldown_records(profile: Any) -> None:+ """Remove entries past their cooldown window from profile."""+ if not hasattr(profile, "cooldown_records"):+ return+ cutoff = time.time() - _COOLDOWN_SECONDS+ keys_to_remove = [k for k, v in profile.cooldown_records.items() if v < cutoff]+ for k in keys_to_remove:+ profile.cooldown_records.pop(k, None)+++# ── Recommendation decision ──────────────────────────────────────++def _safe_urgency(value: Any, default: float = 0.5) -> float:+ """Parse urgency to float in [0,1]; return default on failure.++ LLM may output urgency as string ("0.8") or non-numeric; bare float() would+ raise ValueError and discard the whole decision (type/target/reason lost).+ """+ try:+ f = float(value)+ except (TypeError, ValueError):+ return default+ if f != f or f < 0.0: # NaN or negative+ return default+ return min(f, 1.0)+++@dataclass+class RecommendationDecision:+ """What the engine decided to proactively tell the user."""++ type: str # "skill_recommend" | "task_reminder" | "need_exploration"+ target: str # skill name, task description, or exploration direction+ reason: str # internal reason (for LLM message generation)+ urgency: float = 0.5 # 0.0..1.0+++# ── Skill discovery ─────────────────────────────────────────────++def _parse_skill_md(path: Path) -> dict[str, Any] | None:+ try:+ text = path.read_text(encoding="utf-8")+ except Exception:+ return None+ meta: dict[str, Any] = {}+ fm_match = re.match(r"^---\s*\n(.*?)\n---\s*\n?(.*)", text, re.DOTALL)+ if fm_match:+ body = fm_match.group(2).strip()+ try:+ import yaml+ loaded = yaml.safe_load(fm_match.group(1))+ if isinstance(loaded, dict):+ meta = {str(k): v for k, v in loaded.items()}+ except Exception as exc:+ logger.debug("[ProactiveEngine] skill %s frontmatter parse failed: %s", path, exc)+ if not meta:+ for line in fm_match.group(1).splitlines():+ line = line.strip()+ if not line or line.startswith("#"):+ continue+ m = re.match(r"^(\w[\w_-]*)\s*:\s*(.*)", line)+ if m:+ meta[m.group(1)] = m.group(2).strip().strip("'\"")+ if "name" not in meta:+ meta["name"] = path.stem+ meta.setdefault("description", body[:500])+ else:+ meta["name"] = path.stem+ meta["description"] = text[:500]+ return meta+++def _get_all_skills() -> tuple[set[str], list[dict[str, Any]]]:+ """Discover all available skills (local + builtin) by scanning disk."""+ try:+ from jiuwenswarm.common.utils import get_agent_skills_dir, get_builtin_skills_dir+ skills_dir = get_agent_skills_dir()+ builtin_dir = get_builtin_skills_dir()+ skills: list[dict[str, Any]] = []+ installed_names: set[str] = set()+ seen: set[str] = set()+ for child_dir, source, is_installed in [+ (skills_dir, "local", True), (builtin_dir, "builtin", False),+ ]:+ if not child_dir or not child_dir.exists():+ continue+ for child in child_dir.iterdir():+ if not child.is_dir() or child.name.startswith("_"):+ continue+ md_path = child / "SKILL.md"+ if not md_path.exists():+ continue+ meta = _parse_skill_md(md_path)+ if meta is None or meta.get("name") in seen:+ continue+ seen.add(meta["name"])+ meta.setdefault("name", child.name)+ meta["installed"] = is_installed+ meta.setdefault("source", source)+ meta.setdefault("description", meta.get("body", ""))+ meta.pop("body", None)+ skills.append(meta)+ if is_installed:+ installed_names.add(meta["name"])+ return installed_names, skills+ except Exception as exc:+ logger.warning("[ProactiveEngine] skill list load failed: %s", exc)+ return set(), []+++# ── LLM helpers ──────────────────────────────────────────────────+++def _extract_output_text(invoke_result: Any) -> str:+ """Extract the model's text output from a DeepAgent.invoke result.++ ``invoke`` returns a Dict like ``{"output": <str>, "result_type": ...}``.+ Strictly reads ``output``; returns "" when absent/wrong type so the caller+ treats it as "no decision" instead of misreading ``result_type`` ("answer")+ as the output (which would fail JSON parsing).+ """+ if invoke_result is None:+ return ""+ if isinstance(invoke_result, str):+ return invoke_result+ if isinstance(invoke_result, dict):+ out = invoke_result.get("output")+ if isinstance(out, str):+ return out+ if isinstance(out, list):+ return "\n".join(s for s in out if isinstance(s, str))+ # 不兜底扫其他值——result_type 也是 str,误取会解析失败。output 缺失返回空。+ return ""+ return ""+++def _extract_json_from_response(text: str) -> str:+ fence_match = re.search(r"```(?:json)?\s*\n(.*?)\n```", text, re.DOTALL)+ if fence_match:+ return fence_match.group(1).strip()+ brace_match = re.search(r"\{.*\}", text, re.DOTALL)+ if brace_match:+ return brace_match.group(0).strip()+ return ""+++def _get_model(temperature: float = 0.0) -> Any:+ try:+ from jiuwenswarm.common.config import get_default_models+ from openjiuwen.core.foundation.llm import (+ Model, ModelClientConfig, ModelRequestConfig,+ )+ except ImportError:+ return None+ entries = get_default_models()+ if not entries:+ return None+ entry = entries[0]+ mcc = entry.get("model_client_config", {})+ model_name = mcc.get("model_name", "")+ mcc_fields = {k: v for k, v in mcc.items() if k != "model_name"}+ try:+ return Model(+ model_client_config=ModelClientConfig(**mcc_fields),+ model_config=ModelRequestConfig(model=model_name, temperature=temperature),+ )+ except Exception:+ return None+++# ── Unified analysis prompt ──────────────────────────────────────+# prompt 模板拆到 proactive_prompts.py,便于独立维护话术。++from jiuwenswarm.agents.harness.common.recommendation.proactive_prompts import (+ UNIFIED_ANALYSIS_PROMPT,+ DIRECTIVE_PROMPT,+)+++@dataclass+class AnalysisResult:+ """Output from the unified LLM analysis call."""+ profile_delta: dict[str, Any] = field(default_factory=dict)+ decision: RecommendationDecision | None = None+++async def _analyze_and_decide(+ report_text: str,+ profile: Any,+ skills: list[dict[str, Any]],+ proactive_agent: Any,+) -> AnalysisResult:+ """Single call via the proactive agent: update profile + decide whether to recommend.++ ``proactive_agent`` is a lightweight DeepAgent (no tools, no task_loop,+ single-round) built by app_agentserver. It replaces the old bare+ ``model.invoke([SystemMessage, UserMessage])`` — going through the agent+ framework's invoke chain (rails, model selection, observation) instead of+ hand-rolling Model/SystemMessage/UserMessage.++ ``report_text`` is the fully rendered situation report (from+ ``SituationReport.render_for_llm``) and already contains the user profile,+ conversation summary, recommendation history, pending commitments,+ calendar events, and candidate skills. The prompt therefore takes only+ ``conversation_summary`` — re-formatting those sections here would+ duplicate them in the LLM context.+ """+ prompt = UNIFIED_ANALYSIS_PROMPT.format(+ conversation_summary=report_text[:60000],+ )++ # conversation_id 每次 tick 用唯一值——若用固定 id,DeepAgent 的 context+ # engine 会累积历次 tick 的 prompt+response 进同一 context(实测累积到+ # 2904 条消息),导致决策极慢/超时/无响应。每次独立 session 避免累积。+ import time as _time+ conv_id = f"proactive_analysis_{int(_time.time() * 1000)}"++ try:+ # 专用 agent 单轮 invoke:query 进、{"output": <文本>} 出。+ # system prompt("你是用户洞察与推荐助手。严格输出 JSON 对象。")+ # 在建实例时已配好,这里只传 query。+ result = await proactive_agent.invoke({+ "query": prompt,+ "conversation_id": conv_id,+ })+ content = _extract_output_text(result)+ json_str = _extract_json_from_response(content)+ if not json_str:+ return AnalysisResult()++ delta = json.loads(json_str)+ if not isinstance(delta, dict):+ return AnalysisResult()++ # Extract profile delta (only fields the LLM is allowed to change)+ profile_delta: dict[str, Any] = {}+ profile_keys = ("preferences", "goals", "interests", "commitments")+ for key in profile_keys:+ if key in delta and isinstance(delta[key], list):+ profile_delta[key] = delta[key]++ # Extract decision+ decision = None+ raw_decision = delta.get("decision")+ if isinstance(raw_decision, dict) and raw_decision.get("type") and raw_decision.get("target"):+ dec_type = raw_decision["type"]+ dec_target = raw_decision["target"]+ # Validate: skill_recommend must target an actually-existing skill.+ # LLM may recommend a skill mentioned in chat history but no longer+ # installed; reject such decisions so we don't push a non-existent skill.+ if dec_type == "skill_recommend":+ valid_skill_names = {s.get("name") for s in skills if s.get("name")}+ if dec_target not in valid_skill_names:+ logger.warning(+ "[ProactiveEngine] decision rejected: skill_recommend target '%s' not in available skills %s",+ dec_target, sorted(valid_skill_names)[:10],+ )+ decision = None+ else:+ decision = RecommendationDecision(+ type=dec_type,+ target=dec_target,+ reason=raw_decision.get("reason", ""),+ urgency=_safe_urgency(raw_decision.get("urgency", 0.5)),+ )+ else:+ decision = RecommendationDecision(+ type=dec_type,+ target=dec_target,+ reason=raw_decision.get("reason", ""),+ urgency=_safe_urgency(raw_decision.get("urgency", 0.5)),+ )++ logger.info(+ "[ProactiveEngine] analysis: delta_keys=%s, decision=%s",+ list(profile_delta.keys()),+ f"{decision.type}:{decision.target}" if decision else "null",+ )++ return AnalysisResult(+ profile_delta=profile_delta,+ decision=decision,+ )+ except Exception as exc:+ logger.warning("[ProactiveEngine] LLM analysis failed: %s", exc)+ return AnalysisResult()+ finally:+ # 决策是一次性的——本次 invoke 完立即释放 checkpointer 持久化的 session+ # 记录,避免孤儿数据无限累积(每次 tick 一条,不清会持续增长)。+ # proactive_agent 是无状态单次决策,不需要跨 tick 保留 context。+ try:+ from openjiuwen.core.session.checkpointer import CheckpointerFactory+ await CheckpointerFactory.get_checkpointer().release(conv_id)+ except Exception as exc:+ logger.debug("[ProactiveEngine] checkpoint release failed: %s", exc)+++async def _trigger_main_agent(+ session_id: str,+ channel_id: str | None,+ decision: RecommendationDecision,+ trigger_callback: Any,+) -> bool:+ """Trigger the main agent to run one round and generate the recommendation message.++ Constructs a directive-style query containing the decision (type/target/reason)+ and hands it to ``trigger_callback`` (injected by app_agentserver), which drives+ ``adapter.process_message_stream`` on the target session. The main agent then:++ - generates the recommendation message in its own voice → enters its context+ engine (``save_contexts`` persists it, so future dialogue sees it)+ - streams the output to the frontend via the normal E2A push path++ 避让:trigger_callback 内部检查 ``is_deep_agent_executing_for_session``,+ 目标 session 正忙时返回 False(跳过本次 tick,下个 tick 再来)。++ Returns:+ True if the main agent was triggered, False if the session was busy+ or delivery failed.+ """+ query = DIRECTIVE_PROMPT.format(+ rec_type=decision.type,+ target=decision.target,+ reason=decision.reason,+ )+ try:+ return bool(await trigger_callback(session_id, channel_id, query, decision))+ except Exception as exc:+ logger.warning("[ProactiveEngine] trigger_main_agent failed: %s", exc, exc_info=True)+ return False\ No newline at end of filediff --git a/jiuwenswarm/agents/harness/common/recommendation/proactive_engine.py b/jiuwenswarm/agents/harness/common/recommendation/proactive_engine.pynew file mode 100644index 0000000000..c0f42ccd3c--- /dev/null+++ b/jiuwenswarm/agents/harness/common/recommendation/proactive_engine.py@@ -0,0 +1,313 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Proactive engine — service that scans user conversations, updates the user+profile, and decides whether to proactively reach out with a skill recommendation,+task reminder, or need exploration message.++This is a pure service class that responds to external calls (from CronScheduler+or manual triggers). It does NOT run its own background tick loop.++Runs in AgentServer process. Decision is made by a proactive lightweight agent+(``set_proactive_agent``); the recommendation message is generated by the main+agent — tick triggers it via ``set_trigger_main_agent_callback``, so the message+naturally enters the main agent's context engine and streams to the frontend.++Usage:+- ``engine = ProactiveEngine(config)``+- ``engine.set_proactive_agent(proactive_agent)``+- ``engine.set_trigger_main_agent_callback(callback)``+- ``await engine.tick_now()`` — trigger a recommendation tick+"""++from __future__ import annotations++import logging+import time++from typing import Any++logger = logging.getLogger(__name__)+++class ProactiveEngine:+ """Proactive recommendation engine service.++ Each tick:+ 1. Build a situation report from multi-session history + profile+ 2. Single LLM call (via proactive agent): update profile + decide recommendation type+ 3. If a decision is made: trigger main agent to generate message → streams to frontend+ (message naturally enters the main agent's context engine)++ This class does NOT run its own background loop. It is triggered by:+ - CronScheduler (via proactive.tick WebSocket request from Gateway),+ including the "run now" button in the Cron panel (also goes through+ proactive.tick — no separate manual-trigger endpoint).+ """++ def __init__(self, config: dict[str, Any] | None = None) -> None:+ config = config or {}+ self._max_per_day: int = int(config.get("max_recommend_per_day", 5))+ self._max_sessions: int = int(config.get("max_sessions_per_tick", 10))+ # 默认 False,与 config.yaml 的 proactive_recommendation.enabled 默认值一致,+ # 防御性默认=关闭,避免配置段缺失时引擎被误启用。+ self._enabled: bool = config.get("enabled", False)+ self._last_tick_at: float = 0.0+ # 推荐专用 agent:只做决策(无 session、无 tools、单轮、输出 JSON),+ # 替代 proactive_actions._analyze_and_decide 里的裸 model.invoke。+ self._proactive_agent: Any = None+ # 触发主 agent 跑一轮生成话术的回调。+ # 话术交给主 agent 生成 → 自然进其 context engine(save_contexts 持久化)+ # → stream 输出推前端。撤掉旧的 push/inject 回调。+ self._trigger_main_agent_callback: Any = None++ def set_proactive_agent(self, agent: Any) -> None:+ """Set the proactive lightweight agent used for recommendation decision.++ Args:+ agent: A DeepAgent instance (no tools, no task_loop, single-round).+ Built by app_agentserver via create_deep_agent.+ """+ self._proactive_agent = agent++ @property+ def last_tick_at(self) -> float:+ """Last tick timestamp (public read accessor for ``_last_tick_at``)."""+ return self._last_tick_at++ def rebuild_proactive_agent(self, builder: Any) -> None:+ """Rebuild the proactive agent (e.g. after model config changed).++ The proactive agent is built once at AgentServer startup with the then-+ current model config. When the user changes models (frontend config+ save → agent.reload_config), the main agents hot-reload, but the+ proactive agent would keep the stale model. Call this to rebuild it+ with the latest model config.++ Args:+ builder: Callable ``() -> DeepAgent | None`` (the proactive_adapter+ ``build_proactive_agent``), re-reads model config at call.+ """+ try:+ new_agent = builder()+ if new_agent is not None:+ self._proactive_agent = new_agent+ logger.info("[ProactiveEngine] proactive agent rebuilt (model config refreshed)")+ except Exception as exc:+ logger.warning("[ProactiveEngine] proactive agent rebuild failed: %s", exc)++ def set_trigger_main_agent_callback(self, callback: Any) -> None:+ """Set the callback that triggers the main agent to run one round.++ Args:+ callback: Async function ``(session_id, channel_id, query, decision) -> bool``.+ Constructs an AgentRequest with the directive-style query and+ drives ``adapter.process_message_stream`` so the main agent+ generates the recommendation message naturally (entering its+ own context engine + streaming to the frontend). Returns False+ when the session is busy (避让) or delivery fails.+ """+ self._trigger_main_agent_callback = callback++ def reload_config(self, config: dict[str, Any]) -> None:+ """Hot-reload configuration without restarting the process."""+ new_enabled = bool(config.get("enabled", False))+ new_max_per_day = int(config.get("max_recommend_per_day", self._max_per_day))+ new_max_sessions = int(config.get("max_sessions_per_tick", self._max_sessions))++ self._max_per_day = new_max_per_day+ self._max_sessions = new_max_sessions+ self._enabled = new_enabled+ logger.info("[ProactiveEngine] config reloaded (enabled=%s, max_per_day=%d)",+ new_enabled, new_max_per_day)++ async def tick_now(self, target_channel: str | None = None) -> bool:+ """Trigger a recommendation tick.++ This is the main API for external callers (CronScheduler, manual triggers).++ Args:+ target_channel: Optional channel ID to deliver the recommendation to.+ If None, uses the most recently active session.++ Returns:+ True if a recommendation was made, False otherwise.+ """+ if not self._enabled:+ logger.debug("[ProactiveEngine] engine disabled, skipping tick")+ return False++ logger.info("[ProactiveEngine] tick_now called (target_channel=%s)", target_channel)+ try:+ pushed = await self._tick(target_channel=target_channel)+ return bool(pushed)+ except Exception as exc:+ logger.warning("[ProactiveEngine] tick_now failed: %s", exc, exc_info=True)+ return False++ async def _tick(self, target_channel: str | None = None) -> bool:+ """Single tick: build situation → analyze → push.++ Args:+ target_channel: Optional channel ID to deliver the recommendation to.+ If None, uses the most recently active session.++ Returns:+ True if a recommendation was actually pushed to the channel,+ False if the tick was skipped for any reason (daily limit reached,+ empty situation, no model, no decision, cooldown, no delivery+ target). Callers (CronScheduler / manual trigger) should use this+ to report an accurate status instead of assuming "sent".+ """+ from jiuwenswarm.agents.harness.common.recommendation.proactive_actions import (+ _today_recommend_count,+ _increment_daily_count,+ _is_cooled_down,+ _mark_recommended,+ _get_all_skills,+ _analyze_and_decide,+ _trigger_main_agent,+ )+ from jiuwenswarm.agents.harness.common.recommendation.profile_extractor import (+ load_user_profile,+ save_user_profile,+ )+ from jiuwenswarm.agents.harness.common.recommendation.situation_report import (+ build_situation_report,+ )++ # 每次 tick 顺手清理过期数据(daily_counts 老日期 key、cooldown_records 过期项)。+ # 这些数据只增不减,不清理会长期累积(user_profile.json 越来越大)。+ try:+ self.run_maintenance()+ except Exception as exc:+ logger.debug("[ProactiveEngine] maintenance failed: %s", exc)++ # Gate: daily budget (skip for manual triggers)+ if _today_recommend_count() >= self._max_per_day:+ logger.debug("[ProactiveEngine] daily limit reached, skipping tick")+ self._last_tick_at = time.time()+ return False++ # ── Step 1: Build situation report ─────────────────────+ # build_situation_report 默认只扫 agent 类会话(mode_prefix="agent"),+ # 避免 code/team 会话的技术语境污染推荐决策。+ _, available_skills = _get_all_skills()+ report = await build_situation_report(+ max_sessions=self._max_sessions,+ skills=available_skills,+ )++ if report.is_empty():+ logger.debug("[ProactiveEngine] situation report empty, skipping tick")+ self._last_tick_at = time.time()+ return False++ report_text = report.render_for_llm()++ # ── Step 2: LLM analysis + decision ────────────────────+ # 决策由专用 agent 生成(替代裸 model.invoke),无 session、单轮、输出 JSON。+ profile = load_user_profile()+ if self._proactive_agent is None:+ logger.debug("[ProactiveEngine] no proactive agent available, skipping tick")+ self._last_tick_at = time.time()+ return False++ result = await _analyze_and_decide(+ report_text, profile, available_skills, self._proactive_agent,+ )++ # ── Step 3: Update profile ─────────────────────────────+ if result.profile_delta:+ profile.merge(result.profile_delta)+ save_user_profile(profile)++ # ── Step 4: Check if we have a recommendation ───────────+ decision = result.decision+ if not decision:+ logger.debug("[ProactiveEngine] no recommendation this tick")+ self._last_tick_at = time.time()+ return False++ # ── Step 5: Cooldown check ─────────────────────────────+ if not _is_cooled_down(decision.target, profile):+ logger.debug("[ProactiveEngine] '%s' still in cooldown, skipping", decision.target)+ self._last_tick_at = time.time()+ return False++ # ── Step 6: Pick delivery target ───────────────────────+ if target_channel:+ target_session = report.find_session_for_channel(target_channel)+ if not target_session:+ logger.debug("[ProactiveEngine] no session found for channel '%s'", target_channel)+ self._last_tick_at = time.time()+ return False+ else:+ target_session = report.most_recent_active_session()+ if not target_session:+ logger.debug("[ProactiveEngine] no active session for delivery")+ self._last_tick_at = time.time()+ return False++ # ── Step 7: Trigger main agent to generate & deliver ────+ # 把决策包成指令式 query 触发主 agent 跑一轮,主 agent 自己生成话术+ # → 进其 context engine(save_contexts 持久化)→ stream 输出推前端。+ # 避让:目标 session 正忙则跳过本次 tick。+ if self._trigger_main_agent_callback is None:+ logger.warning("[ProactiveEngine] no trigger_main_agent_callback, skipping")+ self._last_tick_at = time.time()+ return False++ delivered = await _trigger_main_agent(+ session_id=target_session.session_id,+ channel_id=target_channel,+ decision=decision,+ trigger_callback=self._trigger_main_agent_callback,+ )+ if not delivered:+ logger.info("[ProactiveEngine] not delivered (session busy or trigger failed), skipping")+ self._last_tick_at = time.time()+ return False++ # ── Step 8: Update state ────────────────────────────────+ _increment_daily_count()+ _mark_recommended(decision.target, profile)+ profile.add_recommendation({+ "type": decision.type,+ "target": decision.target,+ "reason": decision.reason,+ "urgency": decision.urgency,+ "tick_at": time.time(),+ "session_id": target_session.session_id,+ })++ save_user_profile(profile)+ self._last_tick_at = time.time()++ logger.info("[ProactiveEngine] delivered '%s' (type=%s, urgency=%.2f, session=%s)",+ decision.target, decision.type, decision.urgency,+ target_session.session_id[:20])+ return True++ # ── Maintenance helpers (called by Cron or manually) ─────────++ @staticmethod+ def run_maintenance() -> None:+ """Prune stale data from daily counts and cooldown records.++ This should be called periodically (e.g., by Cron) to keep the+ recommendation state clean.+ """+ from jiuwenswarm.agents.harness.common.recommendation.proactive_actions import (+ _prune_daily_counts,+ _prune_cooldown_records,+ )+ from jiuwenswarm.agents.harness.common.recommendation.profile_extractor import (+ load_user_profile,+ save_user_profile,+ )++ _prune_daily_counts()+ profile = load_user_profile()+ _prune_cooldown_records(profile)+ save_user_profile(profile)+ logger.debug("[ProactiveEngine] maintenance completed")diff --git a/jiuwenswarm/agents/harness/common/recommendation/proactive_prompts.py b/jiuwenswarm/agents/harness/common/recommendation/proactive_prompts.pynew file mode 100644index 0000000000..64820c0a43--- /dev/null+++ b/jiuwenswarm/agents/harness/common/recommendation/proactive_prompts.py@@ -0,0 +1,101 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Proactive recommendation LLM prompt templates.++拆出 proactive_actions,便于独立维护话术——改 prompt 不碰逻辑代码。+"""++from __future__ import annotations++# ── 决策 prompt:画像更新 + 推荐决策 ──────────────────────────────++UNIFIED_ANALYSIS_PROMPT = """\+你是用户洞察与推荐助手。以下是用户的综合情境信息(含画像、对话摘要、历史推荐、待办、日程与候选 skill)。++{conversation_summary}++请完成以下任务,输出 JSON:++1. 更新用户画像(增量更新,只输出需要变更的字段,未变更的字段可以省略或保持原样):++ ⚠️⚠️⚠️ 画像提取铁律(违反会严重污染用户画像,务必严格遵守):++ 【来源限制】画像**只能从对话摘要中 `[User]:` 开头的消息**提取,且必须是用户**字面明确陈述**的事实。+ - `[Assistant]:` 是系统/助手的回复(含主动推荐话术、skill 介绍、建议),**绝对不是用户意图**+ - 「候选 Skill」列表是系统安装的工具清单,**绝对不是用户兴趣**——禁止把 skill 名(如 gaode-taxi、taobao-shopping-assistant)当用户 interests+ - 「历史推荐记录」是系统推送过的推荐,**不是用户意图**+ - 日程事件只用于决策提醒,不算用户表达的 goals++ 【禁止推理】禁止从用户行为/问题**推理/引申/联想**出画像:+ - 用户问天气 ≠ 用户要去旅游,禁止推断"旅游规划/行程/行李/打车/购物"为 goals/interests+ - 用户问代码 ≠ 用户要学 CI/CD,禁止推断+ - 只记录用户**字面说的**事实(如"我是Python开发者"→preferences;"明天要交房租"→commitments)+ - 用户没明确说的,一律不提取,宁可画像为空也不要推理填空++ 【commitments 严格要求】必须是用户原话表达的"我要去做X"意图,禁止把 assistant 的建议/提议(如"要不要试试")当用户承诺。++ 【撤销意图】用户明确表示"不想X了""不要X了""取消了"时,必须从 goals/commitments/interests+ 中删掉对应条目(在本次输出中不输出该条目即可)。用户改变主意后不应继续推已撤销的意图。++ 【清理既有误提取】现有画像可能含历史误提取条目(从 assistant/skill/推荐推理的),+ 发现无 `[User]:` 字面依据的,应在本次输出中删掉(不输出该条目即可)。++ 字段说明:+ - preferences: 长期偏好(技术栈、工作习惯、沟通风格),只保留反复出现的模式或用户明确表达的偏好+ - goals: 用户明确说的当前短期任务,已完成或过期的删掉+ - interests: 用户主动提及想了解的方向(非推理)+ - commitments: 用户明确说"我要去做X"但还没做的++2. 推荐决策:根据画像、对话、日程和历史推荐记录,决定是否需要主动与用户对话。++ 优先级(从高到低):+ a. 用户明确表达未完成的事 → "task_reminder"+ 另:若「即将到来的日程」中有近期事件(如会议、约会),可用 "task_reminder" 提醒,target 为事件标题。+ b. 场景化 skill 推荐:结合用户对话、画像和「即将到来的日程」,判断是否有+ 已安装的候选 Skill 能帮用户应对当前或即将到来的场景。+ - 综合分析日程事件(标题/地点/时间)+ 候选 Skill 列表,判断哪个 skill 与场景相关+ - reason 必须说明场景依据(引用日程事件或 [User]: 对话内容)+ → "skill_recommend"+ c. 从用户明确表达的兴趣推理潜在方向 → "need_exploration"+ (target 是探索方向,非 skill 名;必须有用户明确表达的兴趣为依据,禁止凭空联想)++ ⚠️ 约束:+ - decision.type 为 "skill_recommend" 时,decision.target 必须是上方「候选 Skill」列表里实际存在的 skill 名称。+ - 若没有完全匹配的已存在 skill,改用 "need_exploration" 或返回 null,不要编造不存在的 skill。+ - 「候选 Skill」列表仅供 skill_recommend 选 target 用,不作为用户兴趣来源。+ - 「历史推荐记录」仅用于避免重复推荐同类内容,不作为用户意图来源。+ - 如当前无合适推荐,decision 返回 null。++输出 JSON 格式:+{{+ "preferences": ["..."],+ "goals": ["..."],+ "interests": ["..."],+ "commitments": ["..."],+ "decision": {{+ "type": "skill_recommend|task_reminder|need_exploration",+ "target": "skill名称/待办事项/探索方向",+ "reason": "推荐原因(引用 [User]: 对话内容或日程事件,禁止引用 [Assistant]: 或候选 skill)",+ "urgency": 0.0-1.0+ }} | null+}}"""+++# ── 指令 prompt:把决策包成消息发给主 agent 生成话术 ─────────────++DIRECTIVE_PROMPT = """\+[主动推荐指令]+推荐类型:{rec_type}+推荐内容:{target}+推荐原因:{reason}++请基于以上信息,以助手身份自然地向用户发起这条推荐。要求:+- 2-3句话,口语化,不像广告+- 不要直接说"这是系统推荐",自然融入对话+- 给出行动引导(如"要不要现在试试" / "需要我帮你开始吗")+- 语气按推荐类型调整:+ · task_reminder:关切提醒,像贴心的助手+ · skill_recommend:从用户痛点切入,自然引出工具+ · need_exploration:像同事间的建议,让用户觉得这个方向有意思+输出纯文本话术,不要 JSON,不要标题。+"""diff --git a/jiuwenswarm/agents/harness/common/recommendation/profile_extractor.py b/jiuwenswarm/agents/harness/common/recommendation/profile_extractor.pynew file mode 100644index 0000000000..f5831b1080--- /dev/null+++ b/jiuwenswarm/agents/harness/common/recommendation/profile_extractor.py@@ -0,0 +1,143 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""User profile data model and persistence for the proactive recommendation engine.++The profile captures what the LLM has learned about the user from their+conversations across all channels. It is updated incrementally by the+proactive engine on each tick.++Storage: ``~/.jiuwenswarm/agent/workspace/user_profile.json``+"""++from __future__ import annotations++import json+import logging+from dataclasses import asdict, dataclass, field+from datetime import datetime, timezone+from pathlib import Path+from typing import Any++logger = logging.getLogger(__name__)+++# ── UserProfile ──────────────────────────────────────────────────+++@dataclass+class UserProfile:+ """Persistent user profile maintained by the proactive engine.++ Fields are grouped by who manages them:++ * **LLM-managed** (updated via ``merge()`` from LLM output):+ ``preferences``, ``goals``, ``interests``, ``commitments``++ * **Engine-managed** (updated by the engine itself, never by LLM):+ ``recommendation_history``+ """++ # ── LLM-managed fields ──────────────────────────────────────++ preferences: list[str] = field(default_factory=list)+ """Long-term preferences: tech stack, work habits, communication style."""++ goals: list[str] = field(default_factory=list)+ """Short-term goals: tasks the user is actively working on (days-scale)."""++ interests: list[str] = field(default_factory=list)+ """Interest boundaries: areas the user might want to explore but hasn't yet."""++ commitments: list[str] = field(default_factory=list)+ """Pending tasks: things the user said they'd do but haven't done yet."""++ # ── Engine-managed fields ───────────────────────────────────++ recommendation_history: list[dict[str, Any]] = field(default_factory=list)+ """Past recommendations with type, target, reason, timestamp (max 20)."""++ cooldown_records: dict[str, float] = field(default_factory=dict)+ """Cooldown records: target -> last recommended timestamp. Persisted to survive restarts."""++ last_updated: str = ""++ # ── Merge ───────────────────────────────────────────────────++ def merge(self, delta: dict[str, Any]) -> None:+ """Apply an incremental update from the LLM.++ The LLM outputs the *complete* list for each field it wants to change.+ Fields absent from ``delta`` are left untouched. Engine-managed fields+ (``recommendation_history``) are never modified here.+ """+ replace_fields = ("preferences", "goals", "interests", "commitments")+ for key in replace_fields:+ new_val = delta.get(key)+ if isinstance(new_val, list):+ setattr(self, key, [v for v in new_val if v])++ self.last_updated = datetime.now(timezone.utc).isoformat()++ def add_recommendation(self, rec: dict[str, Any]) -> None:+ """Append a recommendation record and cap at 20 entries."""+ self.recommendation_history.append(rec)+ if len(self.recommendation_history) > 20:+ self.recommendation_history = self.recommendation_history[-20:]+++# ── File helpers ──────────────────────────────────────────────────+++def _default_profile_path() -> Path:+ from jiuwenswarm.common.utils import get_agent_workspace_dir+ return get_agent_workspace_dir() / "user_profile.json"+++def load_user_profile(path: Path | None = None) -> UserProfile:+ """Load profile from disk, returning an empty profile on missing/corrupt file."""+ profile_path = path or _default_profile_path()+ if not profile_path.exists() or profile_path.stat().st_size == 0:+ # Missing or empty file = fresh state, not an error.+ return UserProfile()+ try:+ data = json.loads(profile_path.read_text(encoding="utf-8"))+ if not isinstance(data, dict):+ return UserProfile()++ return UserProfile(+ preferences=_safe_list(data, "preferences"),+ goals=_safe_list(data, "goals"),+ interests=_safe_list(data, "interests"),+ commitments=_safe_list(data, "commitments"),+ recommendation_history=_safe_list(data, "recommendation_history"),+ cooldown_records=_safe_dict(data, "cooldown_records"),+ last_updated=data.get("last_updated", ""),+ )+ except Exception as exc:+ logger.warning("[UserProfile] load failed: %s", exc)+ return UserProfile()+++def _safe_list(data: dict, key: str) -> list:+ """Extract a list from JSON data, returning [] on missing/wrong type."""+ val = data.get(key, [])+ return val if isinstance(val, list) else []+++def _safe_dict(data: dict, key: str) -> dict:+ """Extract a dict from JSON data, returning {} on missing/wrong type."""+ val = data.get(key, {})+ return val if isinstance(val, dict) else {}+++def save_user_profile(profile: UserProfile, path: Path | None = None) -> None:+ """Persist profile to disk."""+ profile_path = path or _default_profile_path()+ profile_path.parent.mkdir(parents=True, exist_ok=True)+ try:+ profile_path.write_text(+ json.dumps(asdict(profile), ensure_ascii=False, indent=2),+ encoding="utf-8",+ )+ except Exception as exc:+ logger.warning("[UserProfile] save failed: %s", exc)diff --git a/jiuwenswarm/agents/harness/common/recommendation/situation_report.py b/jiuwenswarm/agents/harness/common/recommendation/situation_report.pynew file mode 100644index 0000000000..a6d5ac37bf--- /dev/null+++ b/jiuwenswarm/agents/harness/common/recommendation/situation_report.py@@ -0,0 +1,479 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Situation report builder — aggregates multi-session history, user profile,+recommendation history, and pending commitments into a single LLM-ready context.+"""++from __future__ import annotations++import json+import logging+import re+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++from jiuwenswarm.common.utils import get_agent_sessions_dir++logger = logging.getLogger(__name__)++# ── Data structures ──────────────────────────────────────────────+++@dataclass+class SessionSummary:+ """Summary of a single session for the situation report."""++ session_id: str+ channel_id: str = "default"+ title: str = ""+ last_message_at: float = 0.0+ message_count: int = 0+ compressed_history: str = ""+ delivery_context: dict[str, Any] | None = None+++@dataclass+class SituationReport:+ """Aggregated context for the proactive engine's LLM tick."""++ sessions: list[SessionSummary] = field(default_factory=list)+ profile_summary: str = ""+ recommendation_history_summary: str = ""+ pending_commitments: list[str] = field(default_factory=list)+ skills_summary: str = ""+ calendar_events: list[dict[str, Any]] = field(default_factory=list)++ def is_empty(self) -> bool:+ """True when there is no conversation content to analyze."""+ return all(not s.compressed_history for s in self.sessions)++ def most_recent_active_session(self) -> SessionSummary | None:+ """Return the session with the latest activity for push delivery."""+ active = [s for s in self.sessions if s.compressed_history]+ if not active:+ return None+ return max(active, key=lambda s: s.last_message_at)++ def find_session_for_channel(self, channel: str | None) -> SessionSummary | None:+ """Return the most recent active session on the given channel.++ Used when the caller specifies a target channel (e.g. cron passes+ ``target_channel="web"``); we deliver the recommendation to a session+ on that channel. Falls back to the channel-id string comparison.+ Returns ``None`` if no session on that channel has content.+ """+ if not channel:+ return self.most_recent_active_session()+ target = channel.strip().lower()+ active = [+ s for s in self.sessions+ if s.compressed_history and (s.channel_id or "").strip().lower() == target+ ]+ if not active:+ return None+ return max(active, key=lambda s: s.last_message_at)++ def render_for_llm(self) -> str:+ """Render the full report as LLM-readable markdown."""+ parts: list[str] = []++ parts.append("## 用户画像")+ parts.append(self.profile_summary or "(尚无画像)")+ parts.append("")++ if self.sessions:+ parts.append("## 最近对话摘要")+ for s in self.sessions:+ if not s.compressed_history:+ continue+ channel_label = s.channel_id or "default"+ parts.append(f"### 会话: {s.title or s.session_id[:16]} (channel: {channel_label})")+ # Cap each session's contribution to avoid overwhelming the LLM.+ # 截最后 8000 字符——最新消息(含用户撤销意图等关键信息)比早期+ # 上下文更重要,从头截会丢失末尾的最新 user 消息。+ # 8000 字符约 2-3 轮完整对话,够 LLM 理解最新意图。+ hist = s.compressed_history+ parts.append(hist[-8000:] if len(hist) > 8000 else hist)+ parts.append("")++ parts.append("## 历史推荐记录(系统生成,非用户表达,禁止提取进画像)")+ parts.append(self.recommendation_history_summary or "(无推荐历史)")++ if self.pending_commitments:+ parts.append("")+ parts.append("## 用户待办/承诺")+ for c in self.pending_commitments:+ parts.append(f"- {c}")++ if self.calendar_events:+ parts.append("")+ parts.append("## 即将到来的日程")+ for ev in self.calendar_events:+ title = ev.get("title", "")+ start = ev.get("start", "")+ end = ev.get("end", "")+ location = ev.get("location", "")+ line = f"- {start} ~ {end} {title}".rstrip()+ if location:+ line += f" @ {location}"+ parts.append(line)++ if self.skills_summary:+ parts.append("")+ parts.append("## 候选 Skill")+ parts.append(self.skills_summary)++ return "\n".join(parts)+++# ── Session scanning ─────────────────────────────────────────────+++def _match_session_mode(meta: dict[str, Any], mode_prefix: str | None) -> bool:+ """Filter sessions by their ``mode`` field (prefix match), mirroring the+ dreaming sweeper's ``_match_session_mode``.++ 主动推荐面向 agent 类会话(推 skill/待办/需求探索),code/team 会话的+ 技术语境与推荐语义不匹配,混扫会污染 situation report。故默认只扫+ ``mode`` 以 ``agent`` 开头的会话。传 ``None`` 表示不过滤(扫全部)。++ 与 sweeper 不同处:sweeper 对无 mode 字段的会话直接跳过(return False),+ 这里同样如此——无 mode 的会话无法判断类型,按"不属 agent 类"处理。+ """+ if mode_prefix is None:+ return True+ session_mode = str(meta.get("mode", "")).strip()+ if not session_mode:+ return False+ return session_mode.startswith(mode_prefix)+++def _scan_sessions(+ max_sessions: int = 10,+ mode_prefix: str | None = "agent",+) -> list[SessionSummary]:+ """Scan the sessions directory and build summaries for recent active sessions.++ ``mode_prefix`` 按 metadata.json 的 ``mode`` 字段做前缀过滤,默认 ``"agent"``+ 只扫 agent 类会话(含 agent-plan 等)。传 ``None`` 扫全部会话。+ """+ sessions_dir = get_agent_sessions_dir()+ if not sessions_dir.exists():+ return []++ summaries: list[SessionSummary] = []++ for session_dir in sessions_dir.iterdir():+ if not session_dir.is_dir() or session_dir.name.startswith("heartbeat"):+ continue++ meta_path = session_dir / "metadata.json"+ if not meta_path.exists():+ continue++ session_id = session_dir.name+ # 历史文件可能是 history.jsonl(新)或 history.json(旧),+ # 用 session_history 的统一 reader,不要硬编码文件名 —— 否则+ # 在 jsonl 模式下所有 session 都会被跳过,situation report 恒为空,+ # 主动推荐永远不出内容。+ from jiuwenswarm.server.runtime.session.session_history import (+ get_read_history_path,+ )+ history_path = get_read_history_path(session_id)+ if not history_path.exists():+ continue++ try:+ meta = json.loads(meta_path.read_text(encoding="utf-8"))+ except (json.JSONDecodeError, OSError):+ continue++ if not isinstance(meta, dict):+ continue++ # Filter by session mode (agent / code / team ...) — 默认只扫 agent 类会话+ if not _match_session_mode(meta, mode_prefix):+ continue++ # Filter: only sessions with recent activity+ last_msg_at = meta.get("last_message_at", 0)+ try:+ last_ts = float(last_msg_at) if last_msg_at else 0.0+ except (TypeError, ValueError):+ last_ts = 0.0++ # Skip sessions with no activity at all+ if last_ts <= 0:+ continue++ compressed = _compress_history_for_profile(session_id, max_rounds=10)+ if not compressed:+ continue++ delivery_ctx = meta.get("delivery_context")+ if isinstance(delivery_ctx, dict):+ # Only keep routing-relevant fields+ delivery_ctx = {+ k: delivery_ctx[k]+ for k in ("channel_id", "route_metadata", "session_id")+ if k in delivery_ctx+ }+ else:+ delivery_ctx = None++ summaries.append(SessionSummary(+ session_id=session_dir.name,+ channel_id=meta.get("channel_id", "default"),+ title=meta.get("title", ""),+ last_message_at=last_ts,+ message_count=meta.get("message_count", 0),+ compressed_history=compressed,+ delivery_context=delivery_ctx,+ ))++ # Sort by most recent activity, keep top N+ summaries.sort(key=lambda s: s.last_message_at, reverse=True)+ return summaries[:max_sessions]+++# ── History compression ──────────────────────────────────────────+++def _compress_history_for_profile(+ session_id: str,+ max_rounds: int = 10,+) -> str:+ """Read a session's history and compress into [User]/[Assistant] rounds.++ Includes ``proactive_recommendation`` events so the LLM can see what was+ previously recommended. Uses ``load_history_records`` so both+ ``history.jsonl`` (current) and legacy ``history.json`` are handled.+ """+ from jiuwenswarm.server.runtime.session.session_history import (+ history_exists,+ load_history_records,+ )++ if not history_exists(session_id):+ return ""+ try:+ data = load_history_records(session_id)+ if not isinstance(data, list):+ return ""+ except Exception:+ return ""++ def _extract_text(content: Any) -> str:+ if isinstance(content, str):+ return content+ if isinstance(content, list):+ return " ".join(str(c) for c in content if isinstance(c, str))+ return ""++ rounds: list[tuple[str, str]] = []+ current_user: str | None = None+ assistant_buffer: list[str] = []++ _accepted_event_types = ("chat.delta", "chat.final")++ for entry in data:+ role = entry.get("role", "")+ event_type = entry.get("event_type", "")+ if role == "user":+ if current_user is not None and assistant_buffer:+ rounds.append((current_user, "".join(assistant_buffer)))+ current_user = _extract_text(entry.get("content", ""))+ assistant_buffer = []+ elif role == "assistant" and event_type in _accepted_event_types:+ text = _extract_text(entry.get("content", "")).strip()+ if text:+ assistant_buffer.append(text)++ if current_user is not None and assistant_buffer:+ rounds.append((current_user, "".join(assistant_buffer)))++ if len(rounds) > max_rounds:+ rounds = rounds[-max_rounds:]++ parts: list[str] = []+ for user_text, assistant_text in rounds:+ parts.append(f"[User]: {user_text[:1000]}")+ parts.append(f"[Assistant]: {assistant_text[:3000]}")+ return "\n\n".join(parts)+++# ── Commitment extraction (heuristic) ───────────────────────────+++_COMMITMENT_CUES: list[str] = [+ "我要去做", "我要去", "帮我记住", "帮我记",+ "提醒我", "别忘了", "待办", "我打算",+ "我计划", "明天要", "下周要", "我需要完成",+ "我需要做", "我还没做完", "还没完成",+ "i need to", "i will", "i plan to",+ "remind me", "don't forget", "i should",+ "i have to", "i'm going to",+]++_COMMITMENT_SPLIT_RE = re.compile(r"[.!?;。\n]")+++def _extract_commitments_from_text(text: str) -> list[str]:+ """Extract sentences that contain commitment cues from a text block."""+ if not text:+ return []+ sentences = _COMMITMENT_SPLIT_RE.split(text)+ commitments: list[str] = []+ for s in sentences:+ s = s.strip()+ if len(s) < 8:+ continue+ lower = s.lower()+ for cue in _COMMITMENT_CUES:+ if cue in lower:+ commitments.append(s)+ break+ return commitments+++def _extract_commitments(sessions: list[SessionSummary]) -> list[str]:+ """Extract pending commitments from recent session histories."""+ all_commitments: list[str] = []+ for s in sessions:+ if s.compressed_history:+ all_commitments.extend(_extract_commitments_from_text(s.compressed_history))+ # Deduplicate (case-insensitive)+ seen: set[str] = set()+ unique: list[str] = []+ for c in all_commitments:+ key = c.lower().strip()+ if key not in seen:+ seen.add(key)+ unique.append(c)+ return unique[:10]+++# ── Profile formatting ──────────────────────────────────────────+++def _format_existing_profile(profile: Any) -> str:+ """Render UserProfile fields as readable text for LLM context."""+ if not any([+ getattr(profile, "preferences", []),+ getattr(profile, "goals", []),+ getattr(profile, "interests", []),+ getattr(profile, "commitments", []),+ ]):+ return "(尚无画像)"++ parts: list[str] = []+ prefs = getattr(profile, "preferences", [])+ if prefs:+ parts.append("偏好: " + ", ".join(prefs))+ goals = getattr(profile, "goals", [])+ if goals:+ parts.append("短期目标: " + ", ".join(goals))+ interests = getattr(profile, "interests", [])+ if interests:+ parts.append("兴趣边界: " + ", ".join(interests))+ commitments = getattr(profile, "commitments", [])+ if commitments:+ parts.append("待办: " + ", ".join(commitments))+ return "\n".join(parts)+++# ── Skills formatting ───────────────────────────────────────────+++def _format_skills_for_llm(skills: list[dict[str, Any]]) -> str:+ """Render skill list for LLM context.++ 精简渲染——只给 skill 名 + 一句话描述(80 字符)+ 安装状态。+ tags 省略(LLM 不需要标签来选 skill,靠名字+描述即可)。+ """+ lines: list[str] = []+ for s in skills:+ name = s.get("name", "")+ desc = (s.get("description", "") or "")[:80]+ installed = " [已安装]" if s.get("installed") else ""+ lines.append(f"- {name} | {desc}{installed}")+ return "\n".join(lines) if lines else "(无候选 skill)"+++# ── Recommendation history formatting ───────────────────────────+++def _format_recommendation_history(history: list[dict[str, Any]]) -> str:+ """Render recommendation history for LLM context.++ 只保留 type/target——LLM 用它避免重复推荐同类内容。+ reason 不展示(LLM 不需要知道之前推过的理由)。+ 用户对推荐的反馈在对话历史里,LLM 自己能看到,不需要在这里重复。+ """+ if not history:+ return "(无推荐历史)"+ lines: list[str] = []+ for r in history[-10:]:+ rtype = r.get("type", "?")+ target = r.get("target", "?")+ lines.append(f"- [{rtype}] {target}")+ return "\n".join(lines)+++# ── Build ───────────────────────────────────────────────────────+++async def build_situation_report(+ max_sessions: int = 10,+ skills: list[dict[str, Any]] | None = None,+ mode_prefix: str | None = "agent",+) -> SituationReport:+ """Build a SituationReport from the current state of sessions and profile.++ ``async`` because calendar events are pulled from an MCP calendar server+ (a network/subprocess round-trip). Failures there are swallowed inside+ :func:`fetch_calendar_events` and yield an empty list, so this function+ never blocks the tick on calendar availability.++ ``mode_prefix`` 透传给 :func:`_scan_sessions`,按会话 mode 前缀过滤。+ 默认 ``"agent"`` 只扫 agent 类会话,避免 code/team 会话的技术语境污染+ 推荐决策。传 ``None`` 扫全部会话。+ """+ from jiuwenswarm.agents.harness.common.recommendation.profile_extractor import (+ load_user_profile,+ )+ from jiuwenswarm.agents.harness.common.recommendation.calendar_source import (+ fetch_calendar_events,+ )++ # 1. Scan sessions+ sessions = _scan_sessions(max_sessions=max_sessions, mode_prefix=mode_prefix)++ # 2. Load profile+ profile = load_user_profile()+ profile_summary = _format_existing_profile(profile)++ # 3. Recommendation history+ rec_history = getattr(profile, "recommendation_history", [])+ rec_summary = _format_recommendation_history(rec_history)++ # 4. Commitments(每 tick 从最近会话重新提取;跨 tick 保留由 LLM 画像的+ # commitments 字段承担——profile 持久化,引擎不另存一套)。+ commitments = _extract_commitments(sessions)+ commitments = commitments[:10]++ # 5. Skills+ skills_summary = _format_skills_for_llm(skills) if skills else ""++ # 6. Calendar events (MCP calendar server; [] if unconfigured/unreachable)+ calendar_events = await fetch_calendar_events()++ return SituationReport(+ sessions=sessions,+ profile_summary=profile_summary,+ recommendation_history_summary=rec_summary,+ pending_commitments=commitments,+ skills_summary=skills_summary,+ calendar_events=calendar_events,+ )diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsxindex b3589a4cfe..a61f33f982 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx@@ -30,6 +30,7 @@ import clsx from 'clsx';import { MarkdownRenderer } from '../../components/MarkdownRenderer';import { isTeamP2PMessageToUser, parseTeamEventMessage } from './teamEventUtils';import { TeamMemberAvatar } from '../TeamMemberAvatar';+import { ProactiveRecommendationCard } from './ProactiveRecommendationCard';export function MarkdownMessageBody({content,@@ -320,6 +321,11 @@ export function MessageItem({});}, [stopGeneratedAudio, stop]);+ // 主动推荐消息 - 使用特殊卡片样式+ if (message.isProactiveRecommendation) {+ return <ProactiveRecommendationCard message={message} />;+ }+// 工具调用/结果消息if (role === 'tool') {return (diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ProactiveRecommendationCard.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ProactiveRecommendationCard.tsxnew file mode 100644index 0000000000..8793d1519c--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ProactiveRecommendationCard.tsx@@ -0,0 +1,77 @@+/**+ * ProactiveRecommendationCard component+ *+ * Displays proactive recommendations with gradient styling based on type.+ * - skill_recommend: Blue-purple gradient+ * - task_reminder: Amber-orange gradient+ * - need_exploration: Green-cyan gradient+ */++import React from 'react';+import { useTranslation } from 'react-i18next';+import { Sparkles, Clock, Compass } from 'lucide-react';+import ReactMarkdown from 'react-markdown';+import type { Message } from '../../types';+import { formatTimestamp } from '../../utils';++interface ProactiveRecommendationCardProps {+ message: Message;+}++const typeConfig = {+ skill_recommend: {+ icon: Sparkles,+ gradient: 'from-indigo-500/20 via-purple-500/15 to-pink-500/20',+ border: 'border-indigo-400/40',+ iconColor: 'text-indigo-400',+ labelColor: 'text-indigo-300 dark:text-indigo-300',+ },+ task_reminder: {+ icon: Clock,+ gradient: 'from-orange-500/20 via-amber-500/15 to-yellow-500/20',+ border: 'border-orange-400/40',+ iconColor: 'text-orange-400',+ labelColor: 'text-orange-300 dark:text-orange-300',+ },+ need_exploration: {+ icon: Compass,+ gradient: 'from-emerald-500/20 via-teal-500/15 to-cyan-500/20',+ border: 'border-emerald-400/40',+ iconColor: 'text-emerald-400',+ labelColor: 'text-emerald-300 dark:text-emerald-300',+ },+};++export const ProactiveRecommendationCard: React.FC<ProactiveRecommendationCardProps> = ({ message }) => {+ const { t } = useTranslation();+ const proactiveType = message.proactiveType || 'skill_recommend';+ const config = typeConfig[proactiveType] || typeConfig.skill_recommend;+ const Icon = config.icon;+ const label = t(`config.proactive.typeLabel.${proactiveType}`, { defaultValue: t('config.proactive.typeLabel.skill_recommend') });++ return (+ <div className="proactive-recommendation-card animate-fade-in">+ <div className={`proactive-card bg-gradient-to-br ${config.gradient} border ${config.border} rounded-lg p-4`}>+ {/* Header with icon and label */}+ <div className="flex items-center gap-2 mb-3">+ <Icon className={`w-5 h-5 ${config.iconColor}`} strokeWidth={2} />+ <span className={`text-sm font-semibold ${config.labelColor}`}>+ {label}+ </span>+ </div>++ {/* Content */}+ <div className="proactive-card-content prose prose-sm max-w-none dark:prose-invert">+ <ReactMarkdown>{message.content}</ReactMarkdown>+ </div>++ {/* Timestamp */}+ {message.timestamp && (+ <div className="flex items-center gap-3 text-sm mt-2 text-text-muted">+ <span>{formatTimestamp(message.timestamp)}</span>+ </div>+ )}+ </div>+ </div>+ );+};diff --git a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsxindex 7cc02e657b..11382724e4 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx@@ -327,6 +327,15 @@ const SYMPHONY_KEYS = new Set([...SYMPHONY_BOOLEAN_KEYS,...SKILL_RETRIEVAL_KEYS,]);+const PROACTIVE_BOOLEAN_KEYS = new Set(["proactive_recommendation_enabled"]);+const PROACTIVE_KEYS = new Set([+ ...PROACTIVE_BOOLEAN_KEYS,+ "proactive_recommendation_max_recommend_per_day",+ "proactive_recommendation_max_sessions_per_tick",+]);+// 调度频率已交给定时任务面板,ConfigPanel 不再暴露 tick_interval。+// 即便后端残留下发,也在比较/提交时跳过,避免误提交空值。+const PROACTIVE_HIDDEN_FROM_UI_KEYS = new Set(["proactive_recommendation_tick_interval_minutes"]);function classifyKey(key: string): string {if (MODEL_DEFAULT_KEYS.has(key)) return "model_default";@@ -343,6 +352,7 @@ function classifyKey(key: string): string {if (MEMORY_KEYS.has(key)) return "memory";if (A2UI_KEYS.has(key)) return "a2ui";if (SYMPHONY_KEYS.has(key)) return "symphony";+ if (PROACTIVE_KEYS.has(key)) return "proactive";if (key === "context_engine_enabled" || key === "kv_cache_affinity_enabled") return "context_engine";if (key === "permissions_enabled") return "permissions";if (key.startsWith("feishu")) return "feishu";@@ -457,6 +467,13 @@ function getGroupIcon(tag: string) {</svg>);}+ if (tag === "proactive") {+ return (+ <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.8}>+ <path strokeLinecap="round" strokeLinejoin="round" d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.454 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0" />+ </svg>+ );+ }return (<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.8}><path strokeLinecap="round" strokeLinejoin="round" d="M11.25 6h9m-9 6h9m-9 6h9M3.75 6h.008v.008H3.75V6zm0 6h.008v.008H3.75V12zm0 6h.008v.008H3.75V18z" />@@ -481,6 +498,7 @@ function getGroupToneClass(tag: string): string {if (tag === "a2ui") return "text-fuchsia-500 bg-fuchsia-500/10 border-fuchsia-500/20";if (tag === "symphony") return "text-amber-500 bg-amber-500/10 border-amber-500/20";if (tag === "skill_retrieval") return "text-emerald-500 bg-emerald-500/10 border-emerald-500/20";+ if (tag === "proactive") return "text-sky-500 bg-sky-500/10 border-sky-500/20";if (tag === "email") return "text-emerald-500 bg-emerald-500/10 border-emerald-500/20";return "text-text-muted bg-secondary/70 border-border";}@@ -506,7 +524,8 @@ function isBooleanKey(key: string): boolean {key === "memory_forbidden_enabled" ||key === "a2ui_enabled" ||SYMPHONY_BOOLEAN_KEYS.has(key) ||- SKILL_RETRIEVAL_BOOLEAN_KEYS.has(key)+ SKILL_RETRIEVAL_BOOLEAN_KEYS.has(key) ||+ PROACTIVE_BOOLEAN_KEYS.has(key));}@@ -527,6 +546,7 @@ function getBooleanKeyLabel(key: string, t: (key: string) => string): string {a2ui_enabled: t('config.booleanLabels.enabled'),symphony_enabled: t('config.booleanLabels.enabled'),skill_retrieval_enabled: t('config.booleanLabels.enabled'),+ proactive_recommendation_enabled: t('config.booleanLabels.enabled'),};return labels[key] ?? key;}@@ -575,6 +595,7 @@ function getGroupMeta(t: (key: string) => string): Record<string, { label: strina2ui: { label: t('config.groups.a2ui.label'), order: 10, hint: t('config.groups.a2ui.hint') },symphony: { label: t('config.groups.symphony.label'), order: 10.4, hint: t('config.groups.symphony.hint') },skill_retrieval: { label: t('config.groups.skillRetrieval.label'), order: 10.5, hint: t('config.groups.skillRetrieval.hint') },+ proactive: { label: t('config.groups.proactive.label'), order: 10.6, hint: t('config.groups.proactive.hint') },memory: { label: t('config.groups.memory.label'), order: 11, hint: t('config.groups.memory.hint') },email: { label: t('config.groups.email.label'), order: 12, hint: t('config.groups.email.hint') },other: { label: t('config.groups.other.label'), order: 13, hint: t('config.groups.other.hint') },@@ -615,6 +636,9 @@ const KEY_DISPLAY_I18N: Record<string, string> = {skill_retrieval_retrieve_compact_codes_enabled: "config.keys.skillRetrievalCompactCodes",skill_retrieval_retrieve_flatten_tree: "config.keys.skillRetrievalFlattenTree",skill_retrieval_retrieve_max_exposure_depth: "config.keys.skillRetrievalMaxExposureDepth",+ proactive_recommendation_enabled: "config.keys.proactiveEnabled",+ proactive_recommendation_max_recommend_per_day: "config.keys.proactiveMaxPerDay",+ proactive_recommendation_max_sessions_per_tick: "config.keys.proactiveMaxSessions",};const KEY_PLACEHOLDER_I18N: Record<string, string> = {memory_forbidden_description: "config.keys.memoryForbiddenDescriptionPlaceholder",@@ -633,6 +657,9 @@ const KEY_SORT_PRIORITY: Record<string, number> = {free_search_bing_enabled: 1,symphony_enabled: 0,skill_retrieval_enabled: 1,+ proactive_recommendation_enabled: 0,+ proactive_recommendation_max_recommend_per_day: 2,+ proactive_recommendation_max_sessions_per_tick: 3,skill_retrieval_retrieve_max_exposure_depth: 10,skill_retrieval_build_max_depth: 20,skill_retrieval_build_max_workers: 21,@@ -2834,11 +2861,12 @@ export function ConfigPanel({const topLevelGroupCount = groups.length;const hasConfigChanges = useMemo(() => {const keys = Object.keys(normalizedConfig);- return keys.some((key) => (draftValues[key] ?? "") !== normalizedConfig[key]);+ return keys.some((key) => !PROACTIVE_HIDDEN_FROM_UI_KEYS.has(key) && (draftValues[key] ?? "") !== normalizedConfig[key]);}, [draftValues, normalizedConfig]);const configUpdates = useMemo(() => {const updates: Record<string, string> = {};for (const key of Object.keys(normalizedConfig)) {+ if (PROACTIVE_HIDDEN_FROM_UI_KEYS.has(key)) continue;const draftValue = draftValues[key] ?? "";if (draftValue !== normalizedConfig[key]) {updates[key] = draftValue;diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsxindex c9d56443c3..b0a677fc49 100644--- a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx@@ -11,6 +11,10 @@ import { useSessionStore } from '../../stores/sessionStore';const DEFAULT_CRON_TIMEZONE = 'Asia/Shanghai';const DEFAULT_CRON_TARGET = 'web';+// 由主动推荐配置自动维护的 job id(与后端 proactive_cron_sync.PROACTIVE_JOB_ID 一致)。+// 该 job 的调度表达式随 proactive_recommendation.tick_interval_minutes 变化,+// 面板上对其禁用编辑/删除,频率调整走设置→主动推荐。+const PROACTIVE_AUTO_JOB_ID = 'proactive-tick-auto';interface CronJob {id: string;@@ -514,9 +518,20 @@ export default function CronPanel({ sessionId }: CronPanelProps) {}try {+ const patch = buildLegacyJobInput(editJob, mode);+ // proactive 自动维护 job 的 enabled 由 ConfigPanel 开关驱动,+ // 面板编辑提交时不带 enabled,避免与配置侧开关冲突。+ // 同样不带 mode——proactive.tick 的 mode 必须保持 proactive.tick,+ // 否则会被会话 mode(agent.plan)覆盖,导致走普通 cron 流程而非引擎。+ // 不带 wake_offset_seconds——proactive.tick 到点就执行,偏移由后端强制 0。+ if (jobId === PROACTIVE_AUTO_JOB_ID) {+ delete patch['enabled'];+ delete patch['mode'];+ delete patch['wake_offset_seconds'];+ }const updateData: Record<string, unknown> = {id: editJob.id,- patch: buildLegacyJobInput(editJob, mode),+ patch,};await webRequest<{ job: CronJob }>('cron.job.update', {@@ -774,11 +789,12 @@ export default function CronPanel({ sessionId }: CronPanelProps) {<div className="flex items-center"><span className="text-sm mr-2">{editJob.enabled ? t('cron.status.enabled') : t('cron.status.disabled')}</span><div- className="relative inline-block w-10 h-6 align-middle select-none rounded-full cursor-pointer"- onClick={() => setEditingJobs((prev) => ({+ className={`relative inline-block w-10 h-6 align-middle select-none rounded-full ${job.id === PROACTIVE_AUTO_JOB_ID ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}+ onClick={job.id === PROACTIVE_AUTO_JOB_ID ? undefined : () => setEditingJobs((prev) => ({...prev,[job.id]: { ...prev[job.id], enabled: !prev[job.id].enabled },}))}+ title={job.id === PROACTIVE_AUTO_JOB_ID ? t('cron.autoManagedToggleDisabled') : undefined}style={{ backgroundColor: editJob.enabled ? '#10b981' : '#d1d5db' }}><div@@ -803,12 +819,13 @@ export default function CronPanel({ sessionId }: CronPanelProps) {<td className="px-4 py-3"><inputtype="number"- value={editJob.wake_offset_seconds}+ value={job.id === PROACTIVE_AUTO_JOB_ID ? 0 : editJob.wake_offset_seconds}onChange={(e) => setEditingJobs((prev) => ({...prev,[job.id]: { ...prev[job.id], wake_offset_seconds: parseInt(e.target.value, 10) || 0 },}))}- className="w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent"+ disabled={job.id === PROACTIVE_AUTO_JOB_ID}+ className={`w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent ${job.id === PROACTIVE_AUTO_JOB_ID ? 'opacity-50 cursor-not-allowed' : ''}`}placeholder={t('cron.placeholders.wakeOffset')}/></td>@@ -874,8 +891,18 @@ export default function CronPanel({ sessionId }: CronPanelProps) {data-cron-name={job.name}><td className="px-4 py-3 text-sm">- <div className="max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap" title={job.name}>- {job.name}+ <div className="flex items-center gap-1">+ <div className="max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap" title={job.name}>+ {job.name}+ </div>+ {job.id === PROACTIVE_AUTO_JOB_ID && (+ <span+ className="shrink-0 inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-sky-100 text-sky-700"+ title={t('cron.autoManagedHint')}+ >+ {t('cron.autoManaged')}+ </span>+ )}</div></td><td className="px-4 py-3 text-sm mono" data-testid={`cron-schedule-${job.id}`}>@@ -935,26 +962,46 @@ export default function CronPanel({ sessionId }: CronPanelProps) {>{t('cron.previewAction')}</span>- <span- onClick={() => handleToggleJob(job.id, job.enabled, job.expired)}- className={`cursor-pointer text-sm ${job.enabled ? 'text-danger' : 'text-accent'}`}- data-testid={`cron-toggle-${job.id}`}- >- {job.enabled ? t('cron.disable') : t('cron.enable')}- </span>+ {job.id === PROACTIVE_AUTO_JOB_ID ? (+ <span+ className="text-sm text-text-muted/50 cursor-not-allowed select-none"+ title={t('cron.autoManagedToggleDisabled')}+ data-testid={`cron-toggle-${job.id}`}+ >+ {job.enabled ? t('cron.disable') : t('cron.enable')}+ </span>+ ) : (+ <span+ onClick={() => handleToggleJob(job.id, job.enabled, job.expired)}+ className={`cursor-pointer text-sm ${job.enabled ? 'text-danger' : 'text-accent'}`}+ data-testid={`cron-toggle-${job.id}`}+ >+ {job.enabled ? t('cron.disable') : t('cron.enable')}+ </span>+ )}<spanonClick={() => handleUpdateJob(job.id)}className="cursor-pointer text-sm text-accent">{t('cron.update')}</span>- <span- onClick={() => handleDeleteJob(job.id)}- className="cursor-pointer text-sm text-accent"- data-testid={`cron-delete-${job.id}`}- >- {t('cron.delete')}- </span>+ {job.id === PROACTIVE_AUTO_JOB_ID ? (+ <span+ className="text-sm text-text-muted/50 cursor-not-allowed select-none"+ title={t('cron.autoManagedToggleDisabled')}+ data-testid={`cron-delete-${job.id}`}+ >+ {t('cron.delete')}+ </span>+ ) : (+ <span+ onClick={() => handleDeleteJob(job.id)}+ className="cursor-pointer text-sm text-accent"+ data-testid={`cron-delete-${job.id}`}+ >+ {t('cron.delete')}+ </span>+ )}</div></td></tr>diff --git a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.tsindex a95cbef69e..907305910f 100644--- a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts@@ -342,9 +342,23 @@ function parseHistoryTimelineEntry(},};}+ // 主动推荐消息:从历史记录还原 source/proactive_type,使刷新后仍按+ // ProactiveRecommendationCard 渲染(否则会退化为普通白色气泡)。+ const histSource = typeof payload.source === 'string' ? payload.source : '';+ const isProactiveRecommendation = histSource === 'proactive_recommendation';+ const histProactiveType = typeof payload.proactive_type === 'string' ? payload.proactive_type : '';return {kind: 'message',- message: { id, role: 'assistant', content, timestamp: at },+ message: {+ id,+ role: 'assistant',+ content,+ timestamp: at,+ ...(isProactiveRecommendation ? { isProactiveRecommendation } : {}),+ ...(isProactiveRecommendation && histProactiveType+ ? { proactiveType: histProactiveType as 'skill_recommend' | 'task_reminder' | 'need_exploration' }+ : {}),+ },};}diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.tsindex fa09611467..1fffa9e800 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts@@ -1588,13 +1588,20 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {const { currentStreamId, messages } = useChatStore.getState();const payloadSessionId =typeof payload.session_id === 'string' ? payload.session_id.trim() : '';++ // 检查是否为主动推荐消息+ const source = typeof payload.source === 'string' ? payload.source : '';+ const isProactiveRecommendation = source === 'proactive_recommendation';+ const proactiveType = typeof payload.proactive_type === 'string' ? payload.proactive_type : '';+// 仅当有明确会话绑定时才把 final 合并进当前流式气泡。- // 定时任务等广播的 session_id 为空/null,若仍走 currentStreamId 会写到错误气泡甚至“无可见更新”。+ // 定时任务等广播的 session_id 为空/null,若仍走 currentStreamId 会写到错误气泡甚至”无可见更新”。const streamId = currentStreamId;if (streamId && payloadSessionId) {updateMessage(streamId, {...(content ? { content } : {}),isStreaming: false,+ ...(isProactiveRecommendation ? { isProactiveRecommendation, ...(proactiveType ? { proactiveType: proactiveType as 'skill_recommend' | 'task_reminder' | 'need_exploration' } : {}) } : {}),});stopStreaming();if (content && !content.includes('MEDIA:')) {@@ -1664,11 +1671,19 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {if (last?.role === 'assistant' && last.content === content) {return;}++ // 检查是否为主动推荐消息+ const source = typeof payload.source === 'string' ? payload.source : '';+ const isProactiveRecommendation = source === 'proactive_recommendation';+ const proactiveType = typeof payload.proactive_type === 'string' ? payload.proactive_type : '';+addMessage({id: messageId,role: 'assistant',content,timestamp: new Date().toISOString(),+ isProactiveRecommendation,+ ...(proactiveType ? { proactiveType: proactiveType as 'skill_recommend' | 'task_reminder' | 'need_exploration' } : {}),});if (!content.includes('MEDIA:')) {handleTtsPlayback(messageId, content);@@ -2268,6 +2283,31 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {};addToolResult(sessionResult);}),+ webClient.on('proactive_recommendation', ({ payload }) => {+ if (!shouldHandleSessionEvent(payload)) return;+ const content = typeof payload.content === 'string' ? payload.content : '';+ if (!content) return;++ const proactiveType = typeof payload.proactive_type === 'string' ? payload.proactive_type : '';+ const proactiveTarget = typeof payload.proactive_target === 'string' ? payload.proactive_target : '';+ const proactiveReason = typeof payload.proactive_reason === 'string' ? payload.proactive_reason : '';++ const messageId = `proactive-${Date.now()}`;+ addMessage({+ id: messageId,+ role: 'assistant',+ content,+ timestamp: new Date().toISOString(),+ isProactiveRecommendation: true,+ proactiveType: (proactiveType as 'skill_recommend' | 'task_reminder' | 'need_exploration') || undefined,+ });++ console.debug('[ws] proactive_recommendation', {+ type: proactiveType,+ target: proactiveTarget,+ reason: proactiveReason,+ });+ }),webClient.on('team.event', ({ payload }) => {if (shouldDropDuplicatedEvent('team.event', payload)) {return;diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex c3317ee03c..5ab2171ea2 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -720,7 +720,11 @@"skillRetrievalBuildEquivalenceEnabled": "Enable equivalent branch merge","skillRetrievalCompactCodes": "Compact code mode","skillRetrievalFlattenTree": "Flatten retrieval tree",- "skillRetrievalMaxExposureDepth": "Exposure depth per call"+ "skillRetrievalMaxExposureDepth": "Exposure depth per call",+ "proactiveEnabled": "Enable proactive recommendation",+ "proactiveTickInterval": "Check interval (minutes)",+ "proactiveMaxPerDay": "Daily recommendation limit",+ "proactiveMaxSessions": "Max sessions per check"},"keyHelp": {"skillCreate": "Install `skill-creator` and `teamskill-creator` before enabling",@@ -816,7 +820,8 @@"skillRetrieval": { "label": "Skill Symphony", "hint": "Control Skill Symphony" },"memory": { "label": "Memory Sensitive Info Filter", "hint": "Configure sensitive content types forbidden from memory" },"email": { "label": "Email Settings", "hint": "Email account and token settings" },- "other": { "label": "Other Settings", "hint": "Unclassified extended parameters" }+ "other": { "label": "Other Settings", "hint": "Unclassified extended parameters" },+ "proactive": { "label": "Proactive Recommendation", "hint": "Automatically analyze user needs and proactively offer suggestions; adjust the schedule in the Cron panel" }},"booleanLabels": {"evolutionAutoScan": "Auto-detect evolution signals",@@ -850,6 +855,23 @@"loadFailed": "Failed to load tool permissions","saveFailed": "Save failed"},+ "proactive": {+ "title": "Proactive Recommendation",+ "description": "Automatically analyze user needs and proactively offer suggestions based on conversation context.",+ "tickInterval": "Check Interval",+ "tickIntervalDesc": "How often the engine scans for proactive opportunities",+ "maxPerDay": "Daily Limit",+ "maxPerDayDesc": "Maximum proactive recommendations per day",+ "maxSessions": "Sessions per Tick",+ "maxSessionsDesc": "Maximum sessions analyzed per check cycle",+ "notConnected": "Please connect to the server first.",+ "disabledHint": "Enable proactive recommendation first to use this feature.",+ "typeLabel": {+ "skill_recommend": "Skill Recommend",+ "task_reminder": "Task Reminder",+ "need_exploration": "Explore"+ }+ },"errors": {"requiredModelFields": "These model fields are required: {{fields}}. Complete them before saving and restarting.","saveFailed": "Save failed, please try again later",@@ -871,6 +893,9 @@"loading": "Loading scheduled tasks...","empty": "No scheduled tasks","deleteConfirm": "Are you sure you want to delete this task?",+ "autoManaged": "Auto-managed",+ "autoManagedHint": "This task is auto-created/deleted by the proactive recommendation toggle (Settings → Proactive Recommendation). Schedule, offset, timezone and target channel can be edited here; to remove it, turn off the toggle in Settings.",+ "autoManagedToggleDisabled": "The toggle of an auto-managed task is controlled by Settings → Proactive Recommendation and cannot be switched here.","status": {"enabled": "Enabled","disabled": "Disabled",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex fb5093e358..3012fa49d7 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -719,7 +719,11 @@"skillRetrievalBuildEquivalenceEnabled": "启用等价分支合并","skillRetrievalCompactCodes": "紧凑编码模式","skillRetrievalFlattenTree": "平铺检索树",- "skillRetrievalMaxExposureDepth": "单次披露深度"+ "skillRetrievalMaxExposureDepth": "单次披露深度",+ "proactiveEnabled": "启用主动推荐",+ "proactiveTickInterval": "检查间隔(分钟)",+ "proactiveMaxPerDay": "每日推荐上限",+ "proactiveMaxSessions": "每次检查会话数"},"keyHelp": {"skillCreate": "建议先安装 `skill-creator` 和 `teamskill-creator`,再开启",@@ -815,7 +819,8 @@"skillRetrieval": { "label": "技能交响乐", "hint": "控制技能交响乐" },"memory": { "label": "记忆系统敏感信息过滤", "hint": "配置禁止写入记忆的敏感信息类型" },"email": { "label": "邮箱配置", "hint": "邮件账号与令牌参数" },- "other": { "label": "其他配置", "hint": "未归类的扩展参数" }+ "other": { "label": "其他配置", "hint": "未归类的扩展参数" },+ "proactive": { "label": "主动推荐", "hint": "自动分析用户需求,主动提供建议;调度频率请在定时任务面板调整" }},"booleanLabels": {"evolutionAutoScan": "自动检测可演进信号",@@ -849,6 +854,23 @@"loadFailed": "加载工具权限失败","saveFailed": "保存失败"},+ "proactive": {+ "title": "主动推荐",+ "description": "自动分析用户需求,根据对话上下文主动提供建议。",+ "tickInterval": "检查间隔",+ "tickIntervalDesc": "引擎扫描主动推荐机会的频率",+ "maxPerDay": "每日上限",+ "maxPerDayDesc": "每日主动推荐次数上限",+ "maxSessions": "每次检查会话数",+ "maxSessionsDesc": "每轮检查最多分析的会话数",+ "notConnected": "请先连接服务器。",+ "disabledHint": "请先启用主动推荐,再使用此功能。",+ "typeLabel": {+ "skill_recommend": "技能推荐",+ "task_reminder": "任务提醒",+ "need_exploration": "探索发现"+ }+ },"errors": {"requiredModelFields": "模型配置为必填:{{fields}}。请完整填写后再保存并重启。","saveFailed": "保存失败,请稍后重试",@@ -870,6 +892,9 @@"loading": "正在加载任务列表...","empty": "暂无定时任务","deleteConfirm": "确定要删除这个任务吗?",+ "autoManaged": "自动维护",+ "autoManagedHint": "此任务由主动推荐开关自动创建/删除;开关在设置→主动推荐。调度频率、偏移、时区、推送频道可在此面板编辑,删除请到设置关闭开关。",+ "autoManagedToggleDisabled": "自动维护任务的开关由设置→主动推荐控制,不可在此切换。","status": {"enabled": "启用","disabled": "禁用",diff --git a/jiuwenswarm/channels/web/frontend/src/index.css b/jiuwenswarm/channels/web/frontend/src/index.cssindex 7bd1301c22..9653e4d8bb 100644--- a/jiuwenswarm/channels/web/frontend/src/index.css+++ b/jiuwenswarm/channels/web/frontend/src/index.css@@ -893,6 +893,36 @@ select {line-height: 1.7142857;}+ /* Proactive Recommendation Card */+ .proactive-recommendation-card {+ margin: 0.75rem 0;+ max-width: 85%;+ }++ .proactive-card {+ position: relative;+ overflow: hidden;+ transition: all 0.2s ease;+ }++ .proactive-card:hover {+ transform: translateY(-2px);+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);+ }++ .proactive-card-content {+ color: var(--text);+ line-height: 1.6;+ }++ .proactive-card-content p {+ margin: 0;+ }++ .proactive-card-content p + p {+ margin-top: 0.5rem;+ }+.context-compression-running-text {display: inline-block;color: var(--text);diff --git a/jiuwenswarm/channels/web/frontend/src/services/webClient.ts b/jiuwenswarm/channels/web/frontend/src/services/webClient.tsindex e1bb220b99..42dab4c95d 100644--- a/jiuwenswarm/channels/web/frontend/src/services/webClient.ts+++ b/jiuwenswarm/channels/web/frontend/src/services/webClient.ts@@ -522,4 +522,9 @@ export async function webRequest<T = unknown>(return webClient.request<T>(method, params, options);}+// Expose webClient to window for debugging in development+if (import.meta.env.DEV) {+ (window as any).webClient = webClient;+}+export type { WsEvent, WebMessage };diff --git a/jiuwenswarm/channels/web/frontend/src/types/message.ts b/jiuwenswarm/channels/web/frontend/src/types/message.tsindex bc30601c3d..65cc4d0437 100644--- a/jiuwenswarm/channels/web/frontend/src/types/message.ts+++ b/jiuwenswarm/channels/web/frontend/src/types/message.ts@@ -66,6 +66,9 @@ export interface Message {usageSummary?: UsageSummary;// Harness message flag for special stylingisHarnessMessage?: boolean;+ // 主动推荐消息标记+ isProactiveRecommendation?: boolean;+ proactiveType?: 'skill_recommend' | 'task_reminder' | 'need_exploration';}export interface ToolCall {diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.pyindex a059e7749d..1f1467e7f4 100644--- a/jiuwenswarm/common/config.py+++ b/jiuwenswarm/common/config.py@@ -386,6 +386,16 @@ def update_auto_recap_enabled_in_config(value: bool) -> None:dump_yaml_round_trip(CONFIG_YAML_PATH, data)+def update_proactive_recommendation_in_config(updates: dict[str, Any]) -> None:+ """更新 proactive_recommendation 配置段并写回。"""+ data = load_yaml_round_trip(CONFIG_YAML_PATH)+ if "proactive_recommendation" not in data or data["proactive_recommendation"] is None:+ data["proactive_recommendation"] = {}+ section = data["proactive_recommendation"]+ _merge_config_dict(section, updates)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)++def update_updater_in_config(updates: dict[str, Any]) -> None:"""只更新 updater 段并写回。"""data = load_yaml_round_trip(CONFIG_YAML_PATH)diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.pyindex de4f1f7a5e..b1f478cc70 100644--- a/jiuwenswarm/common/schema/message.py+++ b/jiuwenswarm/common/schema/message.py@@ -61,7 +61,9 @@ class ReqMethod(Enum):AGENT_RELOAD_CONFIG = "agent.reload_config"MEMORY_COMPUTE = "memory.compute"-++ PROACTIVE_TICK = "proactive.tick" # Trigger proactive recommendation tick (from Cron)+FILES_LIST = "files.list"FILES_GET = "files.get"TTS_SYNTHESIZE = "tts.synthesize"@@ -230,6 +232,7 @@ class EventType(Enum):WORKFLOW_UPDATED = "workflow.updated"HEARTBEAT_RELAY = "heartbeat.relay"HISTORY_GET = "history.message"+ PROACTIVE_RECOMMENDATION = "proactive_recommendation"class Mode(Enum):diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.pyindex ca0abcf4ee..7e5234b5a9 100644--- a/jiuwenswarm/gateway/app_gateway.py+++ b/jiuwenswarm/gateway/app_gateway.py@@ -47,6 +47,8 @@ from jiuwenswarm.common.utils import (prepare_workspace,reset_free_search_runtime_flags,)+from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields+from jiuwenswarm.common.schema.message import ReqMethod, Message, Mode# Ensure workspace initialized_workspace_dir = get_user_workspace_dir()@@ -90,7 +92,6 @@ def _build_event_frame(msg) -> dict[str, Any]:def _normalize_gateway_message(msg):- from jiuwenswarm.common.schema.message import Message, ReqMethodreq_method = getattr(msg, "req_method", None) or ReqMethod.CHAT_SENDparams = dict(msg.params or {})@@ -811,7 +812,6 @@ class GatewayServer:await self._promote_pending_session_client(route, session_key)async def _handle_raw_message(self, ws: Any, raw: str, request_path: str, route: RouteConfig) -> None:- from jiuwenswarm.common.schema.message import Message, Mode, ReqMethodtry:data = json.loads(raw)@@ -1083,7 +1083,6 @@ async def _run()from jiuwenswarm.extensions.manager import ExtensionManagerfrom jiuwenswarm.extensions.registry import ExtensionRegistry- from jiuwenswarm.common.schema.message import Messagefrom jiuwenswarm.common.updater import UpdaterServicefrom openjiuwen.core.runner import Runner@@ -1227,9 +1226,6 @@ async def _run(env=dict(env_updates or {}),)- from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields- from jiuwenswarm.common.schema.message import ReqMethod-reload_env = e2a_from_agent_fields(request_id=f"agent-reload-{uuid_module.uuid4().hex[:8]}",channel_id="",@@ -1263,6 +1259,17 @@ async def _run(req_method=ReqMethod.BROWSER_RUNTIME_RESTART,)await client.send_request(restart_env)++ # 主动推荐:enabled 变更时同步 proactive.tick job(创建/删除)+ proactive_keys = {+ "proactive_recommendation_enabled",+ }+ if updated_env_keys and (proactive_keys & set(updated_env_keys)):+ try:+ from jiuwenswarm.gateway.cron.proactive_cron_sync import sync_proactive_tick_job+ await sync_proactive_tick_job(cron_controller, config_payload)+ except Exception as e: # noqa: BLE001 # 兜底:proactive 同步失败不阻断配置保存+ logger.warning("[App] proactive.tick sync on config save failed: %s", e)return Trueexcept Exception as e: # noqa: BLE001logger.warning("[App] hot config reload failed, scheduling restart: %s", e)@@ -1272,6 +1279,7 @@ async def _run(web_channel = Noneweb_config = WebChannelConfig(enabled=True, host=web_host, port=web_port, path=web_path)web_channel = WebChannel(web_config, _DummyBus())+_register_web_handlers(WebHandlersBindParams(channel=web_channel,@@ -1895,6 +1903,12 @@ async def _run(await channel_manager.start_dispatch()await cron_scheduler.start()+ # 主动推荐:按 config 自动注册/删除 proactive.tick 定时 job+ try:+ from jiuwenswarm.gateway.cron.proactive_cron_sync import sync_proactive_tick_job+ await sync_proactive_tick_job(cron_controller, get_config())+ except Exception as e: # noqa: BLE001 # 兜底:启动时 proactive job 注册失败不阻断 Gateway 启动+ logger.warning("[App] proactive.tick auto-register failed (non-fatal): %s", e)# 先同步完成监听绑定,避免 IDE/ACP 子进程在端口尚未就绪时连接导致多次重试。await gateway_server.start()gateway_server_task = asyncio.create_task(diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 8570e2e31f..81884298d1 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -42,6 +42,7 @@ from jiuwenswarm.common.config import (update_memory_forbidden_description_in_config,update_a2ui_in_config,update_updater_in_config,+ update_proactive_recommendation_in_config,)from jiuwenswarm.server.runtime.a2ui.integration import (get_a2ui_config_payload,@@ -446,6 +447,9 @@ _CONFIG_YAML_KEYS = frozenset({"memory_forbidden_enabled","memory_forbidden_description","a2ui_enabled",+ "proactive_recommendation_enabled",+ "proactive_recommendation_max_recommend_per_day",+ "proactive_recommendation_max_sessions_per_tick",})_SYMPHONY_CONFIG_SPECS: dict[str, tuple[tuple[str, ...], str, Any]] = {@@ -846,6 +850,14 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:if not payload.get("free_search_bing_enabled"):payload["free_search_bing_enabled"] = "false"payload.update(_flatten_modes_team_for_config_panel(raw))+ # Proactive recommendation — use resolved config (env vars expanded)+ resolved = get_config()+ proactive_cfg = resolved.get("proactive_recommendation") or {}+ payload["proactive_recommendation_enabled"] = "true" if proactive_cfg.get("enabled", False) else "false"+ payload["proactive_recommendation_max_recommend_per_day"] = str(+ proactive_cfg.get("max_recommend_per_day", 5))+ payload["proactive_recommendation_max_sessions_per_tick"] = str(+ proactive_cfg.get("max_sessions_per_tick", 10))except Exception: # noqa: BLE001payload.setdefault("context_engine_enabled", "false")payload.setdefault("kv_cache_affinity_enabled", "false")@@ -869,6 +881,9 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:payload.setdefault(key, default_text)payload.setdefault("free_search_ddg_enabled", "false")payload.setdefault("free_search_bing_enabled", "false")+ payload.setdefault("proactive_recommendation_enabled", "false")+ payload.setdefault("proactive_recommendation_max_recommend_per_day", "5")+ payload.setdefault("proactive_recommendation_max_sessions_per_tick", "10")await channel.send_response(ws, req_id, ok=True, payload=payload)def _persist_env_updates(updates: dict[str, str]) -> None:@@ -970,6 +985,12 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:if not ok:raise _ConfigBadRequest(error or "invalid A2UI config")update_a2ui_in_config(update)+ elif param_key == "proactive_recommendation_enabled":+ update_proactive_recommendation_in_config({"enabled": parsed})+ elif param_key == "proactive_recommendation_max_recommend_per_day":+ update_proactive_recommendation_in_config({"max_recommend_per_day": int(str(val).strip())})+ elif param_key == "proactive_recommendation_max_sessions_per_tick":+ update_proactive_recommendation_in_config({"max_sessions_per_tick": int(str(val).strip())})yaml_updated.append(param_key)except Exception as e: # noqa: BLE001logger.warning("[config.set] 写回 config.yaml 失败 %s: %s", param_key, e)diff --git a/jiuwenswarm/gateway/channel_manager/web/web_connect.py b/jiuwenswarm/gateway/channel_manager/web/web_connect.pyindex 2b4c3f2fce..3aeac91135 100644--- a/jiuwenswarm/gateway/channel_manager/web/web_connect.py+++ b/jiuwenswarm/gateway/channel_manager/web/web_connect.py@@ -404,7 +404,8 @@ class WebChannel(BaseChannel):"history.message","chat.session_result", "chat.usage_metadata","chat.usage_summary", "chat.file",- "chat.retract", "security.alert") \+ "chat.retract", "security.alert",+ "proactive_recommendation") \or event_name.startswith("team.") \or event_name.startswith("harness."):# 传递完整 payload,保留所有字段@@ -431,6 +432,20 @@ class WebChannel(BaseChannel):cron_extra = msg.payload.get("cron")if isinstance(cron_extra, dict):payload["cron"] = cron_extra+ # 保留 source 字段,供前端识别消息来源(如主动推荐)+ source = msg.payload.get("source")+ if source:+ payload["source"] = source+ # 保留 proactive_type,供前端选对卡片样式(技能推荐/任务提醒/探索发现)+ ptype = msg.payload.get("proactive_type")+ if ptype:+ payload["proactive_type"] = ptype+ if source == "proactive_recommendation":+ logger.info(+ "[WebChannel] proactive push frame: source=%s proactive_type=%s "+ "content_len=%d payload_keys=%s",+ source, ptype, len(str(payload.get("content", ""))), list(payload.keys()),+ )else:# payload 不是 dict,尝试从 params 提取content = str((msg.params or {}).get("content", "") or "")diff --git a/jiuwenswarm/gateway/cron/models.py b/jiuwenswarm/gateway/cron/models.pyindex d587406327..ade4578999 100644--- a/jiuwenswarm/gateway/cron/models.py+++ b/jiuwenswarm/gateway/cron/models.py@@ -72,6 +72,9 @@ CRON_JOB_MODES: frozenset[str] = frozenset("agent.fast","team.plan","code.team",+ # 不走 chat.send,scheduler 消费时直接发 PROACTIVE_TICK WS 请求+ # 触发 AgentServer ProactiveEngine.tick_now()。由 proactive_cron_sync 自动注册。+ "proactive.tick",})diff --git a/jiuwenswarm/gateway/cron/proactive_cron_sync.py b/jiuwenswarm/gateway/cron/proactive_cron_sync.pynew file mode 100644index 0000000000..98ec966464--- /dev/null+++ b/jiuwenswarm/gateway/cron/proactive_cron_sync.py@@ -0,0 +1,133 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Auto-register the proactive-recommendation tick cron job.++``ProactiveEngine`` does not run its own loop — it relies on an external caller+to invoke ``tick_now()``. The scheduler already knows how to handle a job+with ``mode == "proactive.tick"`` (it sends a ``PROACTIVE_TICK`` WS request to+the AgentServer, which calls ``tick_now()``), but nothing was creating such a+job. This module reconciles the cron store with the+``proactive_recommendation`` config:++* ``enabled == true`` → ensure a ``proactive.tick`` job exists (created if+ missing with a default schedule; left untouched if already present, so the+ schedule edited in the Cron panel is preserved).+* ``enabled == false`` → delete the job if it exists.++The schedule (cron expression / offset / timezone / target channel) is owned+by the Cron panel once the job exists — this module only seeds the initial+defaults on first creation and never overwrites them afterwards.++Called from two places:+ 1. Gateway startup, after the cron scheduler is started.+ 2. ``_on_config_saved``, when the proactive ``enabled`` key changes.++Idempotent: the job uses a fixed id (``PROACTIVE_JOB_ID``) so repeated calls+never produce duplicates.+"""++from __future__ import annotations++import logging+from typing import Any++logger = logging.getLogger(__name__)++PROACTIVE_JOB_ID = "proactive-tick-auto"+PROACTIVE_JOB_NAME = "主动推荐定时检查"+# 首次创建时使用的默认调度:每 1 小时一次(每小时第 0 分 20 秒),秒字段 20 错峰。+# 仅用于 seed;job 创建后由 Cron 面板接管,此处不再覆盖。+DEFAULT_CRON_EXPR = "20 0 * * * * *"+# 推荐推送到哪个通道。scheduler 消费 proactive.tick 时把 job.targets 当作+# target_channel 传给 ProactiveEngine.tick_now()。web 是最常见的展示通道;+# 用户若主要用 TUI/IM,可在 cron 面板手动改为对应 channel。+DEFAULT_TARGET_CHANNEL = "web"+++def _get_proactive_cfg(config_payload: dict[str, Any] | None) -> dict[str, Any]:+ if not isinstance(config_payload, dict):+ return {}+ cfg = config_payload.get("proactive_recommendation")+ return cfg if isinstance(cfg, dict) else {}+++async def sync_proactive_tick_job(+ cron_controller: Any,+ config_payload: dict[str, Any] | None,+) -> None:+ """根据 config 同步 proactive.tick job(创建/删除)。幂等。++ 只看 ``enabled``:开则确保 job 存在(缺失才创建,已存在不动以保留面板编辑),+ 关则删除。调度表达式不再由 config 驱动。+ """+ if cron_controller is None:+ logger.debug("[ProactiveAutoReg] cron_controller is None, skip")+ return++ try:+ cfg = _get_proactive_cfg(config_payload)+ enabled = bool(cfg.get("enabled", False))++ if not enabled:+ await _ensure_deleted(cron_controller)+ return++ await _ensure_present(cron_controller)+ except Exception as exc: # noqa: BLE001+ # 不影响 config 保存主流程+ logger.warning("[ProactiveAutoReg] sync failed (non-fatal): %s", exc, exc_info=True)+++async def _ensure_present(cron_controller: Any) -> None:+ """确保 proactive.tick job 存在。++ 缺失则用默认调度创建;已存在则完全不动 —— 调度表达式 / 偏移 / 时区 /+ 推送频道均由 Cron 面板接管,避免覆盖用户的编辑。+ """+ existing = await _find_job(cron_controller)+ if existing is None:+ params = {+ "id": PROACTIVE_JOB_ID,+ "name": PROACTIVE_JOB_NAME,+ "cron_expr": DEFAULT_CRON_EXPR,+ "timezone": "Asia/Shanghai",+ "enabled": True,+ "description": "由主动推荐开关自动创建/删除;调度表达式可在定时任务面板编辑",+ "targets": DEFAULT_TARGET_CHANNEL,+ "mode": "proactive.tick",+ # wake_offset=0:proactive.tick 到点就执行,不提前 wake。+ # 否则 wake_dt 在过去会导致循环触发。+ "wake_offset_seconds": 0,+ }+ await cron_controller.create_job(params)+ logger.info("[ProactiveAutoReg] created proactive.tick job (cron=%s)", DEFAULT_CRON_EXPR)+ return++ logger.debug("[ProactiveAutoReg] job already exists, leaving schedule untouched (cron=%s)",+ (existing.get("cron_expr") or "").strip())+++async def _ensure_deleted(cron_controller: Any) -> None:+ existing = await _find_job(cron_controller)+ if existing is None:+ return+ await cron_controller.delete_job(PROACTIVE_JOB_ID)+ logger.info("[ProactiveAutoReg] deleted proactive.tick job (disabled in config)")+++async def _find_job(cron_controller: Any) -> dict[str, Any] | None:+ """Return the auto-managed proactive job dict if it exists in the store."""+ try:+ job = await cron_controller.get_job(PROACTIVE_JOB_ID)+ except Exception:+ job = None+ if job is not None:+ return job+ # get_job may return None for some controllers; fall back to listing.+ try:+ for j in await cron_controller.list_jobs():+ if isinstance(j, dict) and j.get("id") == PROACTIVE_JOB_ID:+ return j+ except Exception as exc:+ logger.debug("[ProactiveAutoReg] list_jobs fallback failed: %s", exc)+ return Nonediff --git a/jiuwenswarm/gateway/cron/scheduler.py b/jiuwenswarm/gateway/cron/scheduler.pyindex fd126ddff1..38b069176a 100644--- a/jiuwenswarm/gateway/cron/scheduler.py+++ b/jiuwenswarm/gateway/cron/scheduler.py@@ -463,7 +463,14 @@ class CronSchedulerService:tz = ZoneInfo(job.timezone)base = datetime.fromtimestamp(now_ts, tz=tz)push_dt = _cron_next_push_dt(job.cron_expr, base)- wake_dt = push_dt - timedelta(seconds=max(0, int(job.wake_offset_seconds or 0)))+ # proactive.tick 无视 wake_offset——到点就执行,不提前 wake。+ # 否则 wake_dt = push_dt - offset 可能在过去,导致 reschedule 后立刻+ # 触发 → 每 6 秒循环(实测 14:26-14:28 反复 triggering 同一 run_id)。+ if getattr(job, "mode", "") == "proactive.tick":+ offset = 0+ else:+ offset = max(0, int(job.wake_offset_seconds or 0))+ wake_dt = push_dt - timedelta(seconds=offset)run_id = f"{job.id}:{int(push_dt.timestamp())}"return push_dt, wake_dt, run_id@@ -520,6 +527,77 @@ class CronSchedulerService:async def _handle_event(self, ev: _Event) -> None:job = self._jobs.get(ev.job_id)++ # Handle proactive.tick mode: send WebSocket request to AgentServer+ if job is not None and job.mode == "proactive.tick" and ev.kind == "wake":+ logger.info("[Cron] triggering proactive.tick for job=%s run_id=%s", job.id, ev.run_id)+ try:+ # Create run state for tracking+ tz = ZoneInfo(job.timezone)+ push_ts = int(ev.run_id.split(":")[-1])+ push_dt = datetime.fromtimestamp(push_ts, tz=tz)+ wake_dt = push_dt - timedelta(seconds=max(0, int(job.wake_offset_seconds or 0)))+ state = CronRunState(+ run_id=ev.run_id,+ job_id=job.id,+ wake_at_iso=wake_dt.isoformat(),+ push_at_iso=push_dt.isoformat(),+ job_name=job.name,+ targets=job.targets,+ session_id=job.session_id,+ chat_type=job.chat_type,+ timezone=job.timezone,+ )+ self._runs[ev.run_id] = state+ state.status = "running"+ state.started_at = self._now_fn()++ # Send proactive.tick request to AgentServer via WebSocket+ envelope = e2a_from_agent_fields(+ request_id=f"proactive-tick-{ev.run_id}",+ channel_id="__cron__",+ session_id=f"cron_{job.id}",+ req_method=ReqMethod.PROACTIVE_TICK,+ params={"target_channel": job.targets or None},+ is_stream=False,+ timestamp=self._now_fn(),+ metadata={"cron": {"job_id": job.id, "run_id": ev.run_id}},+ )+ resp = await self._agent_client.send_request(envelope)++ state.finished_at = self._now_fn()+ if resp.ok:+ success = resp.payload.get("success", False) if resp.payload else False+ state.status = "succeeded" if success else "skipped"+ # success 现在表示"是否真的推送了推荐"(cooldown/无新内容/配额已满均为 False)。+ # 文案与实际一致:不再出现"已发送"但实际没内容的情况。+ state.result_text = "推荐已发送" if success else "本次无需推荐(冷却中或无新内容)"+ logger.info("[Cron] proactive.tick completed job=%s success=%s", job.id, success)+ else:+ state.status = "failed"+ state.error = resp.payload.get("error", "unknown") if resp.payload else "unknown"+ logger.warning("[Cron] proactive.tick failed job=%s: %s", job.id, state.error)+ except Exception as exc:+ logger.warning("[Cron] proactive.tick failed job=%s: %s", job.id, exc, exc_info=True)+ # proactive.tick 走专属分支提前 return,跳过下方 643 通用 reschedule。+ # 必须显式排下一次 wake,否则只在 reload 时才排,期间漏跑+ # (实测:19:56 tick 完,20:00 整点不触发,因为没 reload)。+ try:+ push_dt, wake_dt, next_run_id = self._compute_next_run(job, now_ts=self._now_fn())+ self._schedule_event(wake_dt, "wake", job.id, next_run_id)+ self._schedule_event(push_dt, "push", job.id, next_run_id)+ except Exception as exc: # noqa: BLE001 # 兜底:reschedule 失败不阻断本次 tick 结果(下个 reload 会重排)+ if self._is_croniter_no_next_date(exc):+ try:+ job.enabled = False+ job.expired = True+ await self._store.update_job(job.id, {"enabled": False, "expired": True})+ except Exception as update_exc: # noqa: BLE001 # 兜底:标记过期失败仅告警,不影响主流程+ logger.warning("[Cron] mark expired after proactive.tick failed job=%s: %s", job.id, update_exc)+ else:+ logger.warning("[Cron] reschedule after proactive.tick failed job=%s: %s", job.id, exc)+ return+if job is None and ev.kind != "push_update":return# For wake/push/push_update events: if the job no longer exists in the@@ -586,6 +664,13 @@ class CronSchedulerService:except Exception as update_exc:logger.warning("[Cron] mark expired after push failed job=%s: %s", job.id, update_exc)return+ # proactive.tick 的 wake 分支(525)已处理执行 + reschedule,push 事件+ # 在此仅 _on_push(已 return,不做推送)。若 push 也 reschedule,会和+ # wake 的 reschedule 重复排 wake 事件,形成 push→reschedule→wake→+ # reschedule→push 循环(实测每 6 秒反复 triggering 同一 run_id)。+ # proactive.tick 跳过 push 的 reschedule,由 wake 分支统一管调度。+ if getattr(job, "mode", "") == "proactive.tick":+ returntry:push_dt, wake_dt, next_run_id = self._compute_next_run(job, now_ts=self._now_fn())self._schedule_event(wake_dt, "wake", job.id, next_run_id)@@ -923,6 +1008,12 @@ class CronSchedulerService:raiseasync def _on_push(self, job: CronJob, run_id: str) -> None:+ # proactive.tick 的结果在 wake 分支已同步产出:有推荐时由+ # trigger_main_agent → send_push 直接推送内容;无推荐时静默。+ # push 事件不再推 result_text 或"正在执行中"占位,避免 wake 的+ # tick_now 还在跑(LLM 耗时)时误推占位消息。+ if getattr(job, "mode", None) == "proactive.tick":+ returnstate = self._runs.get(run_id)if state is None:tz = ZoneInfo(job.timezone)diff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.pyindex eb0ab09374..e189426fb6 100644--- a/jiuwenswarm/gateway/message_handler/message_handler.py+++ b/jiuwenswarm/gateway/message_handler/message_handler.py@@ -323,6 +323,9 @@ class MessageHandler(ABC):@classmethoddef _should_cancel_existing_stream_before_chat_send(cls, msg: "Message") -> bool:+ # 主动推荐消息不取消现有流式任务,避免干扰用户当前对话+ if isinstance(msg.params, dict) and msg.params.get("source") == "proactive_recommendation":+ return Falsereturn (cls._is_chat_send_message(msg)and not cls._is_team_chat_send(msg)diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex 45cb8de3d8..b375bd9110 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -187,6 +187,12 @@ memory:base_id: ${LAKEBASE_MEM_BASE_ID:-}database_id: ${LAKEBASE_DATABASE_ID:-}++proactive_recommendation:+ enabled: ${PROACTIVE_RECOMMENDATION_ENABLED:-false} # 总开关+ max_recommend_per_day: ${MAX_RECOMMEND_PER_DAY:-5} # 每天最多推荐次数+ max_sessions_per_tick: ${MAX_SESSIONS_PER_TICK:-10} # 每次 Tick 扫描最多几个会话+models:defaults:- model_client_config:@@ -935,6 +941,7 @@ mcp:# Authorization: Bearer ${MCP_TOKEN}# timeout_s: 30+modes:# 一级模式 agent / code / teamagent:diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex 900eefeef2..9c6bfc2b12 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -892,10 +892,16 @@ class AgentWebSocketServer:self._default_model: Optional[Any] = None# 本地 jiuwenbox 子进程管理器 (lazy 启动, 在 /sandbox enable 时 ensure_running)self._jiuwenbox_runner = JiuwenBoxRunner.instance()+ # Proactive recommendation engine (set by app_agentserver for debug trigger)+ self._proactive_engine: Any = Noneget_acp_output_manager().set_send_push_callback(lambda msg: asyncio.create_task(self.send_push(msg)))+ def set_proactive_engine(self, engine: Any) -> None:+ """Store the proactive engine instance for debug trigger interface."""+ self._proactive_engine = engine+@staticmethoddef _ws_capabilities_key(ws: Any) -> int:return id(ws)@@ -1393,6 +1399,9 @@ class AgentWebSocketServer:if request.req_method == ReqMethod.TEAM_SNAPSHOT:await self._handle_team_snapshot(ws, request, send_lock)return+ if request.req_method == ReqMethod.PROACTIVE_TICK:+ await self._handle_proactive_tick(ws, request, send_lock)+ returnif request.req_method == ReqMethod.COMMAND_WORKFLOWS:await self._handle_command_workflows(ws, request, send_lock)return@@ -2896,6 +2905,52 @@ class AgentWebSocketServer:async with send_lock:await ws.send(json.dumps(wire, ensure_ascii=False))++ async def _handle_proactive_tick(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:+ """Handle proactive.tick request from CronScheduler.++ This is called by Gateway's CronScheduler to trigger a recommendation tick.+ Respects cooldown and daily limits.+ """+ if self._proactive_engine is None:+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": "ProactiveEngine not initialized"},+ )+ else:+ try:+ # Extract target_channel from params+ params = request.params or {}+ target_channel = params.get("target_channel")++ # Run the tick (respects cooldown and daily limits)+ success = await self._proactive_engine.tick_now(target_channel=target_channel)++ status = "tick_executed" if success else "no_recommendation"+ last_tick = self._proactive_engine.last_tick_at+ if last_tick > 0:+ status = f"{status} (last_tick_at={last_tick:.0f})"++ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload={"status": status, "success": success},+ )+ except Exception as e:+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": str(e)},+ )++ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)+ async with send_lock:+ await ws.send(json.dumps(wire, ensure_ascii=False))+async def _handle_team_snapshot(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:from jiuwenswarm.agents.harness.team import get_team_manager@@ -4905,6 +4960,11 @@ class AgentWebSocketServer:return agentreturn None+ @staticmethod+ def resolve_adapter(agent: Any) -> Any:+ """Public wrapper for :meth:`_resolve_adapter` (避开 protected-access)."""+ return AgentWebSocketServer._resolve_adapter(agent)+@staticmethoddef _parse_sandbox_host_port(url: str) -> tuple[str, int]:"""从 sandbox url 解析 host:port; 默认 127.0.0.1:8321."""@@ -5633,6 +5693,21 @@ class AgentWebSocketServer:env_overrides,**reload_kwargs,)++ # Hot-reload ProactiveEngine config if available+ if self._proactive_engine is not None:+ cfg = get_config()+ proactive_cfg = cfg.get("proactive_recommendation", {})+ self._proactive_engine.reload_config(proactive_cfg)+ # 重建 proactive agent——它启动时建一次,模型配置固化在实例里。+ # 用户改模型后主 agent 会热更新,但 proactive agent 不在主 agent+ # 链路里,不重建会继续用旧模型(可能已失效/欠费)。+ try:+ from jiuwenswarm.server.runtime.proactive_adapter import build_proactive_agent+ self._proactive_engine.rebuild_proactive_agent(build_proactive_agent)+ except Exception as exc: # noqa: BLE001+ logger.warning("[AgentWebSocketServer] proactive agent rebuild failed: %s", exc)+resp = AgentResponse(request_id=request.request_id,channel_id=request.channel_id,diff --git a/jiuwenswarm/server/app_agentserver.py b/jiuwenswarm/server/app_agentserver.pyindex 921dcfabdd..b68bef17ca 100644--- a/jiuwenswarm/server/app_agentserver.py+++ b/jiuwenswarm/server/app_agentserver.py@@ -129,12 +129,14 @@ from jiuwenswarm.llm_sse_patch import apply_openai_sse_invoke_patchapply_openai_sse_invoke_patch()+async def _run(host: str, port: int) -> None:from openjiuwen.core.runner import Runnerfrom jiuwenswarm.server.agent_ws_server import AgentWebSocketServerfrom jiuwenswarm.agents.harness.team.remote_member_bootstrap import run_teammate_bootstrap_daemonfrom jiuwenswarm.extensions.manager import ExtensionManagerfrom jiuwenswarm.extensions.registry import ExtensionRegistry+ from jiuwenswarm.common.config import get_configlogger.info("[AgentServer] starting: ws://%s:%s", host, port)@@ -157,6 +159,14 @@ async def _run(host: str, port: int) -> None:)await server.start()+ # ---------- ProactiveEngine 初始化 ----------+ # 适配逻辑(建专用 agent + 触发主 agent 回调)封装在 proactive_adapter,+ # app_agentserver 只调 init_proactive_engine。+ from jiuwenswarm.server.runtime.proactive_adapter import init_proactive_engine+ full_cfg = get_config()+ proactive_config = full_cfg.get("proactive_recommendation", {}) if isinstance(full_cfg, dict) else {}+ await init_proactive_engine(server, proactive_config)+logger.info("[AgentServer] ready: ws://%s:%s Ctrl+C to stop", host, port)stop_event = asyncio.Event()@@ -254,3 +264,4 @@ def main() -> None:if __name__ == "__main__":main()+diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex f816410cf8..1fa71c9f20 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -1532,7 +1532,10 @@ class JiuWenSwarm:session_id = self._session_manager.get_session_id(request.session_id)query = request.params.get("query", "")- if not is_interrupt_resume_payload(request.params):+ # proactive_recommendation 是系统触发的推荐指令(不是用户说的话),不写 user+ # history——否则刷新页面会显示"[主动推荐指令] xxx"这种用户没说过的消息。+ if not is_interrupt_resume_payload(request.params) \+ and str(request.params.get("source") or "") != "proactive_recommendation":append_history_record(session_id=session_id,request_id=request.request_id,@@ -1699,7 +1702,10 @@ class JiuWenSwarm:and isinstance(request.params.get("activate_response"), dict))- if not is_interrupt_resume_payload(request.params):+ # proactive_recommendation 是系统触发的推荐指令(不是用户说的话),不写 user+ # history——否则刷新页面会显示"[主动推荐指令] xxx"这种用户没说过的消息。+ if not is_interrupt_resume_payload(request.params) \+ and str(request.params.get("source") or "") != "proactive_recommendation":append_history_record(session_id=session_id,request_id=request.request_id,diff --git a/jiuwenswarm/server/runtime/proactive_adapter.py b/jiuwenswarm/server/runtime/proactive_adapter.pynew file mode 100644index 0000000000..2e10f58cc2--- /dev/null+++ b/jiuwenswarm/server/runtime/proactive_adapter.py@@ -0,0 +1,172 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""ProactiveEngine 初始化与适配层。++把主动推荐的适配逻辑从 app_agentserver 抽出,集中管理:+- build_proactive_agent: 建专用决策 agent(无 tools、单轮、输出 JSON)+- trigger_main_agent: 触发主 agent 跑一轮生成话术 → stream 推前端+- init_proactive_engine: 组装 ProactiveEngine + 注入 agent + callback++app_agentserver 只需调 init_proactive_engine(server, config)。+"""++from __future__ import annotations++import logging+import time+from typing import Any++logger = logging.getLogger(__name__)+++def build_proactive_agent():+ """Build the lightweight proactive agent for proactive recommendation decisions.++ 无 tools、无 task_loop、单轮、输出 JSON。复用 _get_model 的模型选择逻辑。+ 替代 proactive_actions._analyze_and_decide 里的裸 model.invoke —— 走 agent+ 框架的 invoke 链路(rails / 模型选择 / 观测),不再手搓 Model/SystemMessage。+ """+ try:+ from jiuwenswarm.agents.harness.common.recommendation.proactive_actions import _get_model+ from openjiuwen.harness.factory import create_deep_agent+ from openjiuwen.core.single_agent import AgentCard+ except ImportError as exc:+ logger.warning("[AgentServer] proactive agent imports failed: %s", exc)+ return None++ model = _get_model(temperature=0.0)+ if model is None:+ logger.warning("[AgentServer] proactive agent: no model configured")+ return None+ try:+ return create_deep_agent(+ model=model,+ card=AgentCard(name="proactive_agent", id="proactive_agent"),+ system_prompt="你是用户洞察与推荐助手。严格输出 JSON 对象。",+ tools=[],+ rails=[],+ enable_task_loop=False,+ max_iterations=1,+ add_general_purpose_agent=False,+ )+ except Exception as exc:+ logger.warning("[AgentServer] proactive agent build failed: %s", exc)+ return None+++async def trigger_main_agent(server, session_id: str, channel_id: str | None,+ query: str, decision: Any) -> bool:+ """Drive the main agent to run one round with the directive-style query.++ 避让:目标 session 正在跑 stream 时跳过(同 session 不支持并发 stream)。+ 触发后主 agent 自己生成话术 → 进 context engine → stream 推前端。+ Returns True on triggered, False on busy/missing adapter/failure.+ """+ try:+ from jiuwenswarm.common.schema.agent import AgentRequest+ except ImportError as exc:+ logger.warning("[AgentServer] trigger_main_agent import failed: %s", exc)+ return False++ cid = channel_id or "web"+ # 用外层 agent(JiuWenSwarm)调 process_message_stream——它做 session 管理、+ # history 落盘、mode 解析等前置后委托给内层 adapter 的 process_message_stream_impl。+ # 内层 adapter 只有 impl 方法,直接调会 AttributeError。+ #+ # 用 get_agent_nowait(不自动创建):tick 不应替用户建 agent——自动建时 cache_key+ # (mode:sub_mode:project_dir)和用户对话实际用的可能不一致(用户对话带 project_dir/+ # sub_mode),会建出第二个 agent,导致推荐进的不是用户对话用的 context。+ # agent 不在内存 = 用户尚未在该 channel 发过消息(无活跃 context 可投递)→ 跳过本次 tick,+ # 等用户用过一次、agent 建好后下个 tick 自然拿到。+ agent = server.get_agent_manager().get_agent_nowait(cid)+ if agent is None or not hasattr(agent, "process_message_stream"):+ logger.info("[ProactiveEngine] trigger: no agent for channel=%s "+ "(user hasn't used this channel yet), skipping", cid)+ return False+ # 内层 adapter 用于避让检查(is_deep_agent_executing_for_session 在 adapter 上)+ # 用公开 resolve_adapter 避开 protected-access+ from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer+ adapter = AgentWebSocketServer.resolve_adapter(agent)++ # 避让:目标 session 正忙 → 跳过本次 tick+ if adapter is not None and hasattr(adapter, "is_deep_agent_executing_for_session"):+ try:+ if adapter.is_deep_agent_executing_for_session(session_id):+ logger.info("[ProactiveEngine] trigger: session %s busy, skipping", str(session_id)[:20])+ return False+ except Exception as exc:+ logger.debug("[ProactiveEngine] is_deep_agent_executing_for_session check failed: %s", exc)++ request = AgentRequest(+ request_id=f"proactive_{decision.type}_{int(time.time() * 1000)}",+ channel_id=cid,+ session_id=session_id,+ # source=proactive_recommendation 标记这是系统触发的推荐指令,不是用户说的话。+ # process_message_stream 写 user history 时据此跳过——否则刷新页面会看到+ # "[主动推荐指令] xxx" 这条用户没说过的消息。+ # proactive_type/target 给 assistant 写 history 时透传用(待通用流程支持)。+ params={+ "query": query,+ "mode": "agent.plan",+ "source": "proactive_recommendation",+ "proactive_type": decision.type,+ "proactive_target": decision.target,+ },+ is_stream=True,+ )+ try:+ async for chunk in agent.process_message_stream(request):+ # chunk 经 server.send_push 推 Gateway。send_push 内部已用+ # _current_send_lock 串行化 ws 发送,且 build_server_push_wire 走+ # chunk 分支(无 response_kind)正确编码——这里只需带齐 chunk 的+ # request_id / payload / is_complete,Gateway 才能按 request_id 路由。+ #+ # 注入 source/proactive_type:主 agent 的 chunk 是普通对话格式,+ # 不带主动推荐标记。前端靠 payload.source==='proactive_recommendation'+ # 识别卡片、payload.proactive_type 选颜色,缺这俩会退化成普通白色气泡。+ # decision.type 在手上,给每个 chunk 的 payload 补上。+ try:+ chunk_payload = dict(getattr(chunk, "payload", None) or {})+ chunk_payload.setdefault("source", "proactive_recommendation")+ chunk_payload.setdefault("proactive_type", decision.type)+ chunk_payload.setdefault("proactive_target", decision.target)+ await server.send_push({+ "request_id": getattr(chunk, "request_id", "") or request.request_id,+ "channel_id": cid,+ "session_id": session_id,+ "payload": chunk_payload,+ "is_complete": bool(getattr(chunk, "is_complete", False)),+ })+ except Exception as exc:+ logger.debug("[ProactiveEngine] send_push chunk failed: %s", exc)+ return True+ except Exception as exc:+ logger.warning("[ProactiveEngine] trigger: process_message_stream failed: %s", exc, exc_info=True)+ return False+++async def init_proactive_engine(server, config: dict[str, Any] | None = None) -> None:+ """组装 ProactiveEngine + 注入专用 agent + 触发回调,挂到 server 上。++ app_agentserver 启动时调用,把所有 proactive 适配逻辑集中在此。+ """+ from jiuwenswarm.agents.harness.common.recommendation.proactive_engine import ProactiveEngine++ try:+ proactive_config = config or {}+ proactive_engine = ProactiveEngine(proactive_config)++ # 专用 agent:只做决策(无 tools、无 task_loop、单轮、输出 JSON),+ # 替代 proactive_actions._analyze_and_decide 里的裸 model.invoke。+ proactive_agent = build_proactive_agent()+ proactive_engine.set_proactive_agent(proactive_agent)++ # 触发主 agent 回调:tick 决策后,把决策包成指令式 query 触发主 agent+ # 跑一轮,主 agent 自己生成话术 → 进 context engine → stream 推前端。+ async def _trigger_cb(session_id, channel_id, query, decision):+ return await trigger_main_agent(server, session_id, channel_id, query, decision)++ proactive_engine.set_trigger_main_agent_callback(_trigger_cb)+ server.set_proactive_engine(proactive_engine)+ except Exception as exc:+ logger.warning("[AgentServer] ProactiveEngine initialization failed: %s", exc)diff --git a/tests/symphony/test_proactive_recommendation_flow.py b/tests/symphony/test_proactive_recommendation_flow.pynew file mode 100644index 0000000000..6d734faee6--- /dev/null+++ b/tests/symphony/test_proactive_recommendation_flow.py@@ -0,0 +1,480 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""End-to-end integration tests for the proactive recommendation engine.++These tests mock out the LLM, WebSocket push, and session scanning to+verify the full Tick 1 → 2 → 3 flow:+ Tick 1: LLM discovers pain point → plans multi-stage path → pushes stage-1+ Tick 2: User accepted → path status="continue" → pushes stage-2+ Tick 3: User rejected → path status="rejected" → path deleted+"""++from __future__ import annotations++import json+import tempfile+import time+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest++# ── Fixtures ─────────────────────────────────────────────────────────++SAMPLE_SKILLS = [+ {"name": "auto-test-runner", "description": "监听文件变化自动跑测试", "tags": ["testing"], "installed": False},+ {"name": "test-coverage", "description": "生成测试覆盖率报告", "tags": ["testing"], "installed": False},+ {"name": "ci-pipeline", "description": "CI/CD 流水线配置生成器", "tags": ["ci"], "installed": False},+ {"name": "debug-helper", "description": "智能调试助手", "tags": ["debug"], "installed": False},+]++_PATCH_TARGETS = {+ "situation_report": "jiuwenswarm.agents.harness.common.recommendation.situation_report",+ "actions": "jiuwenswarm.agents.harness.common.recommendation.proactive_actions",+ "utils": "jiuwenswarm.common.utils",+}+++def _fake_session_summary() -> MagicMock:+ s = MagicMock()+ s.session_id = "test-session-001"+ s.channel_id = "default"+ s.title = "Test Session"+ s.last_message_at = time.time()+ s.message_count = 5+ s.compressed_history = "[User]: 每次改完代码都要手动跑测试,好麻烦\n[Assistant]: 理解你的痛点。"+ s.delivery_context = {"channel_id": "default", "route_metadata": {}, "session_id": "test-session-001"}+ return s+++def _fake_report() -> MagicMock:+ report = MagicMock()+ report.is_empty.return_value = False+ report.most_recent_active_session.return_value = _fake_session_summary()+ report.render_for_llm.return_value = "对话摘要:用户手动跑测试多次"+ report.sessions = [_fake_session_summary()]+ return report+++def _write_profile(ws_dir: Path, profile_data: dict) -> Path:+ """Write user_profile.json into the workspace dir (where the engine reads/writes)."""+ profile_path = ws_dir / "user_profile.json"+ profile_path.write_text(json.dumps(profile_data, ensure_ascii=False, indent=2), encoding="utf-8")+ return profile_path+++def _read_profile(ws_dir: Path) -> dict:+ return json.loads((ws_dir / "user_profile.json").read_text(encoding="utf-8"))+++class _MockProactiveAgent:+ """Mock dedicated agent: invoke() returns {"output": <JSON string>}."""++ def __init__(self, tick_responses: list[dict]):+ self._responses = tick_responses+ self._call_index = 0++ async def invoke(self, inputs, session=None):+ if self._call_index < len(self._responses):+ result = self._responses[self._call_index]+ else:+ result = None+ self._call_index += 1+ output = json.dumps(result, ensure_ascii=False) if result else ""+ return {"output": output, "result_type": "answer"}+++def _make_proactive_agent(tick_responses: list[dict]):+ return _MockProactiveAgent(tick_responses)+++# Capture _trigger_main_agent calls (session_id, channel_id, query, decision)+def _capture_trigger(triggered_list):+ async def _trigger(session_id, channel_id, query, decision):+ triggered_list.append({+ "session_id": session_id,+ "channel_id": channel_id,+ "query": query,+ "decision": decision,+ })+ return True+ return _trigger+++# ── Tick 1: Discover pain point → push recommendation ────────++async def test_tick1_recommend_skill():+ """Tick 1: LLM discovers pain point → recommends skill → saves to history."""+ emitted = []++ tick1_llm = {+ "preferences": ["使用 pytest 做测试"],+ "goals": ["搭建测试自动化"],+ "interests": ["CI/CD 自动化"],+ "commitments": [],+ "decision": {+ "type": "need_exploration",+ "target": "auto-test-runner",+ "reason": "用户多次手动跑测试,痛点明确",+ "urgency": 0.8,+ },+ }++ dedicated = _make_proactive_agent([tick1_llm])++ with tempfile.TemporaryDirectory() as ws:+ ws_path = Path(ws)+ _write_profile(ws_path, {+ "preferences": ["使用 pytest 做测试"],+ "goals": ["搭建测试自动化"],+ "interests": [],+ "commitments": [],+ "recommendation_history": [],+ "last_updated": "",+ })++ with patch(f"{_PATCH_TARGETS['utils']}.get_agent_workspace_dir", return_value=ws_path), \+ patch(f"{_PATCH_TARGETS['situation_report']}.build_situation_report", return_value=_fake_report()), \+ patch(f"{_PATCH_TARGETS['actions']}._today_recommend_count", return_value=0), \+ patch(f"{_PATCH_TARGETS['actions']}._is_cooled_down", return_value=True), \+ patch(f"{_PATCH_TARGETS['actions']}._get_all_skills", return_value=(set(), SAMPLE_SKILLS)):++ from jiuwenswarm.agents.harness.common.recommendation.proactive_engine import ProactiveEngine++ engine = ProactiveEngine({"enabled": True})+ engine.set_proactive_agent(dedicated)+ engine.set_trigger_main_agent_callback(_capture_trigger(emitted))+ await engine.tick_now()++ # Verify main agent was triggered+ assert len(emitted) == 1, f"Should trigger 1 recommendation, got {len(emitted)}"++ # Verify profile was updated+ profile_data = _read_profile(ws_path)+ assert len(profile_data["recommendation_history"]) == 1+++# ── Tick 2: Continue recommending different skill ──────++async def test_tick2_recommend_different_skill():+ """Tick 2: LLM recommends a different skill after first recommendation was accepted."""+ emitted = []++ with tempfile.TemporaryDirectory() as ws:+ ws_path = Path(ws)+ _write_profile(ws_path, {+ "preferences": ["使用 pytest 做测试"],+ "goals": ["搭建测试自动化"],+ "interests": ["CI/CD 自动化"],+ "commitments": [],+ "recommendation_history": [{+ "type": "need_exploration",+ "target": "auto-test-runner",+ "reason": "用户多次手动跑测试",+ "urgency": 0.8,+ "tick_at": time.time() - 3600,+ "session_id": "test-session-001",+ }],+ "last_updated": "",+ })++ tick2_llm = {+ "preferences": ["使用 pytest 做测试"],+ "goals": ["搭建测试自动化"],+ "interests": ["CI/CD 自动化"],+ "commitments": [],+ "decision": {+ "type": "need_exploration",+ "target": "test-coverage",+ "reason": "用户已接受 auto-test-runner,继续推荐 test-coverage",+ "urgency": 0.6,+ },+ }++ dedicated = _make_proactive_agent([tick2_llm])++ with patch(f"{_PATCH_TARGETS['utils']}.get_agent_workspace_dir", return_value=ws_path), \+ patch(f"{_PATCH_TARGETS['situation_report']}.build_situation_report", return_value=_fake_report()), \+ patch(f"{_PATCH_TARGETS['actions']}._today_recommend_count", return_value=0), \+ patch(f"{_PATCH_TARGETS['actions']}._is_cooled_down", return_value=True), \+ patch(f"{_PATCH_TARGETS['actions']}._get_all_skills", return_value=(set(), SAMPLE_SKILLS)):++ from jiuwenswarm.agents.harness.common.recommendation.proactive_engine import ProactiveEngine++ engine = ProactiveEngine({"enabled": True})+ engine.set_proactive_agent(dedicated)+ engine.set_trigger_main_agent_callback(_capture_trigger(emitted))+ await engine.tick_now()++ # Verify main agent was triggered+ assert len(emitted) == 1, f"Should trigger 1 recommendation, got {len(emitted)}"++ # Verify profile was updated with new recommendation+ profile_data = _read_profile(ws_path)+ assert len(profile_data["recommendation_history"]) == 2+++# ── Tick 3: No recommendation when cooldown active ─────++async def test_tick3_cooldown_blocks_recommendation():+ """Tick 3: When target is in cooldown, no recommendation is emitted."""+ emitted = []++ with tempfile.TemporaryDirectory() as ws:+ ws_path = Path(ws)+ _write_profile(ws_path, {+ "preferences": ["使用 pytest 做测试"],+ "goals": ["搭建测试自动化"],+ "interests": [],+ "commitments": [],+ "recommendation_history": [{+ "type": "need_exploration",+ "target": "auto-test-runner",+ "reason": "用户多次手动跑测试",+ "urgency": 0.8,+ "tick_at": time.time() - 7200,+ "session_id": "test-session-001",+ }],+ "cooldown_records": {+ "auto-test-runner": time.time() - 3600 # 1 hour ago, still in cooldown+ },+ "last_updated": "",+ })++ tick3_llm = {+ "preferences": ["使用 pytest 做测试"],+ "goals": ["搭建测试自动化"],+ "interests": [],+ "commitments": [],+ "decision": {+ "type": "skill_recommend",+ "target": "auto-test-runner",+ "reason": "再次推荐",+ "urgency": 0.4,+ },+ }++ dedicated = _make_proactive_agent([tick3_llm])++ with patch(f"{_PATCH_TARGETS['utils']}.get_agent_workspace_dir", return_value=ws_path), \+ patch(f"{_PATCH_TARGETS['situation_report']}.build_situation_report", return_value=_fake_report()), \+ patch(f"{_PATCH_TARGETS['actions']}._today_recommend_count", return_value=0), \+ patch(f"{_PATCH_TARGETS['actions']}._is_cooled_down", return_value=False), \+ patch(f"{_PATCH_TARGETS['actions']}._get_all_skills", return_value=(set(), SAMPLE_SKILLS)):++ from jiuwenswarm.agents.harness.common.recommendation.proactive_engine import ProactiveEngine++ engine = ProactiveEngine({"enabled": True})+ engine.set_proactive_agent(dedicated)+ engine.set_trigger_main_agent_callback(_capture_trigger(emitted))+ await engine.tick_now()++ # No recommendation triggered (target in cooldown)+ assert len(emitted) == 0+++# ── No recommendation when decision is null ───────++async def test_no_recommendation_when_decision_null():+ """When LLM decides not to recommend, no recommendation is emitted."""+ emitted = []++ with tempfile.TemporaryDirectory() as ws:+ ws_path = Path(ws)+ _write_profile(ws_path, {+ "preferences": [],+ "goals": [],+ "interests": [],+ "commitments": [],+ "recommendation_history": [{+ "type": "need_exploration",+ "target": "auto-test-runner",+ "reason": "痛点",+ "urgency": 0.8,+ "tick_at": time.time() - 7200,+ "session_id": "test-session-001",+ }],+ "last_updated": "",+ })++ tick_llm = {+ "preferences": [],+ "goals": [],+ "interests": [],+ "commitments": [],+ "decision": None, # No recommendation+ }++ dedicated = _make_proactive_agent([tick_llm])++ with patch(f"{_PATCH_TARGETS['utils']}.get_agent_workspace_dir", return_value=ws_path), \+ patch(f"{_PATCH_TARGETS['situation_report']}.build_situation_report", return_value=_fake_report()), \+ patch(f"{_PATCH_TARGETS['actions']}._today_recommend_count", return_value=0), \+ patch(f"{_PATCH_TARGETS['actions']}._is_cooled_down", return_value=True), \+ patch(f"{_PATCH_TARGETS['actions']}._get_all_skills", return_value=(set(), SAMPLE_SKILLS)):++ from jiuwenswarm.agents.harness.common.recommendation.proactive_engine import ProactiveEngine++ engine = ProactiveEngine({"enabled": True})+ engine.set_proactive_agent(dedicated)+ engine.set_trigger_main_agent_callback(_capture_trigger(emitted))+ await engine.tick_now()++ # No recommendation triggered (decision was null)+ assert len(emitted) == 0+++# ── Daily limit gate ───────────────────────────────────────────────++async def test_daily_limit_blocks_tick():+ """When daily limit is reached, tick should skip without calling the dedicated agent."""+ call_counts = {"analyze": 0}++ class _CountingProactive:+ async def invoke(self, inputs, session=None):+ call_counts["analyze"] += 1+ return {"output": "{}", "result_type": "answer"}++ dedicated = _CountingProactive()++ with tempfile.TemporaryDirectory() as ws:+ ws_path = Path(ws)+ _write_profile(ws_path, {+ "preferences": [],+ "goals": [],+ "interests": [],+ "commitments": [],+ "recommendation_history": [],+ "last_updated": "",+ })++ with patch(f"{_PATCH_TARGETS['utils']}.get_agent_workspace_dir", return_value=ws_path), \+ patch(f"{_PATCH_TARGETS['situation_report']}.build_situation_report", return_value=_fake_report()), \+ patch(f"{_PATCH_TARGETS['actions']}._today_recommend_count", return_value=5), \+ patch(f"{_PATCH_TARGETS['actions']}._is_cooled_down", return_value=True), \+ patch(f"{_PATCH_TARGETS['actions']}._get_all_skills", return_value=(set(), SAMPLE_SKILLS)):++ from jiuwenswarm.agents.harness.common.recommendation.proactive_engine import ProactiveEngine++ engine = ProactiveEngine({+ "enabled": True,+ "max_recommend_per_day": 5,+ })+ engine.set_proactive_agent(dedicated)+ engine.set_trigger_main_agent_callback(_capture_trigger([]))+ await engine.tick_now()++ assert call_counts["analyze"] == 0, "dedicated agent should not be called when daily limit reached"+++# ── 避让:目标 session 正忙时跳过 ──────────────────────────────++async def test_skip_when_main_agent_busy():+ """trigger_callback 返回 False(session 正忙)时,引擎应跳过、不记冷却/计数。"""+ from jiuwenswarm.agents.harness.common.recommendation.proactive_actions import (+ RecommendationDecision,+ )++ tick_llm = {+ "preferences": [], "goals": [],+ "interests": [], "commitments": [],+ "decision": {+ "type": "task_reminder", "target": "项目周会",+ "reason": "时间临近", "urgency": 0.9,+ },+ }+ dedicated = _make_proactive_agent([tick_llm])++ triggered = []++ async def _busy_trigger(session_id, channel_id, query, decision):+ triggered.append((session_id, channel_id, decision))+ return False # session 正忙++ with tempfile.TemporaryDirectory() as ws:+ ws_path = Path(ws)+ _write_profile(ws_path, {+ "preferences": [], "goals": [],+ "interests": [], "commitments": [],+ "recommendation_history": [], "last_updated": "",+ })++ with patch(f"{_PATCH_TARGETS['utils']}.get_agent_workspace_dir", return_value=ws_path), \+ patch(f"{_PATCH_TARGETS['situation_report']}.build_situation_report", return_value=_fake_report()), \+ patch(f"{_PATCH_TARGETS['actions']}._today_recommend_count", return_value=0), \+ patch(f"{_PATCH_TARGETS['actions']}._is_cooled_down", return_value=True), \+ patch(f"{_PATCH_TARGETS['actions']}._get_all_skills", return_value=(set(), SAMPLE_SKILLS)):++ from jiuwenswarm.agents.harness.common.recommendation.proactive_engine import ProactiveEngine+ engine = ProactiveEngine({"enabled": True})+ engine.set_proactive_agent(dedicated)+ engine.set_trigger_main_agent_callback(_busy_trigger)+ result = await engine.tick_now()++ # 触发被调用一次但返回 False → 引擎跳过+ assert len(triggered) == 1+ assert result is False++ # 不应记冷却/推荐历史(因为没真正投递)+ profile_data = _read_profile(ws_path)+ assert len(profile_data["recommendation_history"]) == 0+++# ── 专用 agent JSON 解析 ───────────────────────────────────────++async def test_proactive_agent_output_parsed_to_decision():+ """专用 agent invoke 返回的 JSON 字符串应被解析为 decision + profile_delta。"""+ from jiuwenswarm.agents.harness.common.recommendation.proactive_actions import (+ _analyze_and_decide, RecommendationDecision,+ )+ tick_llm = {+ "preferences": ["Python 异步"],+ "goals": ["认证模块重构"],+ "interests": ["CI/CD"],+ "commitments": ["编写单元测试"],+ "decision": {+ "type": "skill_recommend", "target": "auto-test-runner",+ "reason": "手动测试繁琐", "urgency": 0.7,+ },+ }+ dedicated = _make_proactive_agent([tick_llm])+ profile = MagicMock(+ preferences=[], goals=[],+ interests=[], commitments=[],+ )++ result = await _analyze_and_decide("report text", profile, SAMPLE_SKILLS, dedicated)++ assert result.decision is not None+ assert result.decision.type == "skill_recommend"+ assert result.decision.target == "auto-test-runner"+ assert result.decision.urgency == 0.7+ assert "preferences" in result.profile_delta+ assert result.profile_delta["preferences"] == ["Python 异步"]+++async def test_proactive_agent_invalid_json_returns_empty():+ """专用 agent 返回非 JSON 时,应安全返回空 AnalysisResult。"""+ from jiuwenswarm.agents.harness.common.recommendation.proactive_actions import (+ _analyze_and_decide,+ )++ class _BadAgent:+ async def invoke(self, inputs, session=None):+ return {"output": "这不是JSON", "result_type": "answer"}++ profile = MagicMock(+ preferences=[], goals=[],+ interests=[], commitments=[],+ )+ result = await _analyze_and_decide("report", profile, SAMPLE_SKILLS, _BadAgent())+ assert result.decision is None+ assert result.profile_delta == {}