fix: add random jitter to daily dream schedule

This commit is contained in:
zhayujie
2026-04-15 00:33:33 +08:00
parent ae20ba1148
commit cabd24605f
3 changed files with 26 additions and 10 deletions

View File

@@ -548,14 +548,17 @@ class AgentInitializer:
import threading import threading
def _daily_flush_loop(): def _daily_flush_loop():
import random
while True: while True:
try: try:
now = datetime.datetime.now() now = datetime.datetime.now()
target = now.replace(hour=23, minute=55, second=0, microsecond=0) jitter_min = random.randint(50, 55)
jitter_sec = random.randint(0, 59)
target = now.replace(hour=23, minute=jitter_min, second=jitter_sec, microsecond=0)
if target <= now: if target <= now:
target += datetime.timedelta(days=1) target += datetime.timedelta(days=1)
wait_seconds = (target - now).total_seconds() wait_seconds = (target - now).total_seconds()
logger.info(f"[DailyFlush] Next flush at {target.strftime('%Y-%m-%d %H:%M')} (in {wait_seconds/3600:.1f}h)") logger.info(f"[DailyFlush] Next flush at {target.strftime('%Y-%m-%d %H:%M:%S')} (in {wait_seconds/3600:.1f}h)")
time.sleep(wait_seconds) time.sleep(wait_seconds)
self._flush_all_agents() self._flush_all_agents()

View File

@@ -34,7 +34,7 @@ CowAgent 支持通过统一的 `install` 命令安装来自 **[Cow 技能广场]
## 从 LinkAI 安装 ## 从 LinkAI 安装
[LinkAI](https://link-ai.tech/console) 上的所有公开资源 (1w+个插件/应用/工作流) ,以及自己创建的资源 (应用/工作流/知识库/数据库/插件) 都可以通过命令一键安装: [LinkAI](https://link-ai.tech/console) 上的所有公开资源 (1w+个应用/工作流/插件) ,以及自己创建的资源 (应用/工作流/知识库/数据库/插件) 都可以通过命令一键安装:
```text ```text
/skill install linkai:<code> /skill install linkai:<code>

View File

@@ -174,7 +174,7 @@ class CowCliPlugin(Plugin):
# status # status
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def _cmd_status(self, args: str, e_context: EventContext, session_id: str = "") -> str: def _cmd_status(self, args: str, e_context: EventContext, session_id: str = "", **_) -> str:
from config import conf from config import conf
cfg = conf() cfg = conf()
@@ -256,7 +256,7 @@ class CowCliPlugin(Plugin):
# context # context
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def _cmd_context(self, args: str, e_context: EventContext, session_id: str = "") -> str: def _cmd_context(self, args: str, e_context: EventContext, session_id: str = "", **_) -> str:
session_id = self._get_session_id(e_context, fallback=session_id) session_id = self._get_session_id(e_context, fallback=session_id)
agent = self._get_agent(session_id) agent = self._get_agent(session_id)
@@ -885,7 +885,6 @@ class CowCliPlugin(Plugin):
if agent and agent.memory_manager: if agent and agent.memory_manager:
flush_mgr = agent.memory_manager.flush_manager flush_mgr = agent.memory_manager.flush_manager
# Fallback: construct a temporary MemoryFlushManager when agent is not yet initialized
if not flush_mgr: if not flush_mgr:
try: try:
flush_mgr = self._create_standalone_flush_manager() flush_mgr = self._create_standalone_flush_manager()
@@ -895,24 +894,38 @@ class CowCliPlugin(Plugin):
if not flush_mgr.llm_model: if not flush_mgr.llm_model:
return "⚠️ 未配置 LLM 模型,无法执行记忆蒸馏" return "⚠️ 未配置 LLM 模型,无法执行记忆蒸馏"
# SaaS (e_context is None): run synchronously, return full result
if e_context is None:
return self._memory_dream_sync(flush_mgr, days)
# Local channels: run in background, notify via channel.send()
is_web = self._is_web_channel(e_context) is_web = self._is_web_channel(e_context)
def _run(): def _run():
try: try:
result = flush_mgr.deep_dream(lookback_days=days, force=True) result = flush_mgr.deep_dream(lookback_days=days, force=True)
if result: if result:
msg = self._build_dream_result(flush_mgr, is_web) self._notify(e_context, self._build_dream_result(flush_mgr, is_web))
self._notify(e_context, msg)
else: else:
self._notify(e_context, "💤 记忆蒸馏跳过 — 没有新的记忆内容需要整理") self._notify(e_context, "💤 记忆蒸馏跳过 — 没有新的记忆内容需要整理")
except Exception as e: except Exception as e:
logger.warning(f"[CowCli] /memory dream failed: {e}") logger.warning(f"[CowCli] /memory dream failed: {e}")
self._notify(e_context, f"❌ 记忆蒸馏失败: {e}") self._notify(e_context, f"❌ 记忆蒸馏失败: {e}")
thread = threading.Thread(target=_run, daemon=True) threading.Thread(target=_run, daemon=True).start()
thread.start()
return f"🌙 记忆蒸馏已启动 (整理近 {days} 天的记忆)\n\n整理在后台执行,完成后会通知你。" return f"🌙 记忆蒸馏已启动 (整理近 {days} 天的记忆)\n\n整理在后台执行,完成后会通知你。"
def _memory_dream_sync(self, flush_mgr, days: int) -> str:
"""Run deep dream synchronously and return the full result."""
try:
result = flush_mgr.deep_dream(lookback_days=days, force=True)
if result:
return self._build_dream_result(flush_mgr, is_web=True)
return "💤 记忆蒸馏跳过 — 没有新的记忆内容需要整理"
except Exception as e:
logger.warning(f"[CowCli] /memory dream sync failed: {e}")
return f"❌ 记忆蒸馏失败: {e}"
@staticmethod @staticmethod
def _notify(e_context, text: str): def _notify(e_context, text: str):
"""Push a notification message back to the chat channel.""" """Push a notification message back to the chat channel."""