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: cron支持自然语言创建
Haowei_Duddabfb074334
diff --git a/jiuwenclaw/agentserver/react_agent.py b/jiuwenclaw/agentserver/react_agent.pyindex 6355ae423c..4188ecafec 100644--- a/jiuwenclaw/agentserver/react_agent.py+++ b/jiuwenclaw/agentserver/react_agent.py@@ -350,7 +350,7 @@ class JiuClawReActAgent(ReActAgent):await _pause_event.wait()logger.info(- "session s%, ReAct iteration %d/%d",+ "session %s, ReAct iteration %d/%d",session_id,iteration + 1,self._config.max_iterations,diff --git a/jiuwenclaw/gateway/cron/controller.py b/jiuwenclaw/gateway/cron/controller.pyindex aa7eff360e..1a51682792 100644--- a/jiuwenclaw/gateway/cron/controller.py+++ b/jiuwenclaw/gateway/cron/controller.py@@ -61,6 +61,22 @@ class CronController:base = datetime.now(tz=tz)_ = _cron_next_push_dt(cron_expr, base)+ _DESCRIPTION_TIME_KEYWORDS = ("每天", "每周", "每月", "上午", "下午", "早上", "晚上", "凌晨")++ @classmethod+ def _normalize_description(cls, description: str, name: str) -> str:+ """若 description 含时间/频率用语且 name 为纯任务,则只保留任务内容(用 name)。"""+ description = (description or "").strip()+ name = (name or "").strip()+ if not name:+ return description+ if not any(kw in description for kw in cls._DESCRIPTION_TIME_KEYWORDS):+ return description+ if name in description or description.endswith(name):+ return name+ return description++async def list_jobs(self) -> list[dict[str, Any]]:jobs = await self._store.list_jobs()return [j.to_dict() for j in jobs]@@ -72,13 +88,22 @@ class CronController:async def create_job(self, params: dict[str, Any]) -> dict[str, Any]:name = str(params.get("name") or "").strip()cron_expr = str(params.get("cron_expr") or "").strip()- timezone = str(params.get("timezone") or "").strip()+ timezone = str(params.get("timezone") or "Asia/Shanghai").strip() or "Asia/Shanghai"enabled = bool(params.get("enabled", True))description = str(params.get("description") or "")wake_offset_seconds = params.get("wake_offset_seconds", None)- targets = params.get("targets") or []+ targets = params.get("targets") or "web"++ # if not targets:+ # from jiuwenclaw.agentserver.request_context import get_current_request+ # req = get_current_request()+ # if req and (req.channel_id or req.session_id):+ # targets = [+ # {"channel_id": req.channel_id or "web", "session_id": req.session_id},+ # ]self._validate_schedule(cron_expr=cron_expr, timezone=timezone)+ description = self._normalize_description(description, name)job = await self._store.create_job(name=name,@@ -94,13 +119,16 @@ class CronController:async def update_job(self, job_id: str, patch: dict[str, Any]) -> dict[str, Any]:patch = dict(patch or {})+ existing = await self._store.get_job(job_id)+ if existing is None:+ raise KeyError("job not found")if "cron_expr" in patch or "timezone" in patch:- existing = await self._store.get_job(job_id)- if existing is None:- raise KeyError("job not found")cron_expr = str(patch.get("cron_expr") or existing.cron_expr).strip()timezone = str(patch.get("timezone") or existing.timezone).strip()self._validate_schedule(cron_expr=cron_expr, timezone=timezone)+ if "description" in patch:+ name = str(patch.get("name") or existing.name or "").strip()+ patch["description"] = self._normalize_description(str(patch.get("description") or ""), name)job = await self._store.update_job(job_id, patch)await self._scheduler.reload()@@ -142,7 +170,7 @@ class CronController:name: str,cron_expr: str,timezone: str,- targets: list[dict[str, Any]],+ targets: str,enabled: bool = True,description: str = "",wake_offset_seconds: int | None = None,@@ -151,7 +179,7 @@ class CronController:"name": name,"cron_expr": cron_expr,"timezone": timezone,- "targets": targets,+ "targets": targets or 'web',"enabled": enabled,"description": description,}@@ -230,50 +258,45 @@ class CronController:make_tool(name="cron_create_job",description=(- "Create a new cron job. Requires name, cron_expr (e.g. '0 9 * * 1-5'), "- "timezone (e.g. 'Asia/Shanghai'), and targets (list of {channel_id, session_id?}). "- "Optional: enabled, description, wake_offset_seconds."+ "创建定时任务。当用户说「每天/每周/每月某时间做某事」时使用。"+ "cron_expr 为 5 段:分 时 日 月 周。例:每天 9 点 = '0 9 * * *',每天 11 点 58 分 = '58 11 * * *',每周一 9 点 = '0 9 * * 1'。"+ "description 只填任务内容,不要包含时间、频率等,时间由 cron_expr 表达。"+ "timezone 默认 Asia/Shanghai。"),input_params={"type": "object","properties": {- "name": {"type": "string", "description": "Job name"},+ "name": {"type": "string", "description": "任务名称"},"cron_expr": {"type": "string",- "description": "Cron expression, e.g. '0 9 * * 1-5' for 9am weekdays",+ "description": "Cron 表达式,如每天9点10分用 '10 9 * * *'",},"timezone": {"type": "string",- "description": "Timezone, e.g. 'Asia/Shanghai'",+ "description": "时区,如 Asia/Shanghai",+ "default": "Asia/Shanghai",},"targets": {- "type": "array",- "items": {- "type": "object",- "properties": {- "channel_id": {"type": "string"},- "session_id": {"type": "string"},- },- "required": ["channel_id"],- },- "description": "List of push targets",+ "type": "string",+ "description": "推送频道,如网页用web, 飞书用feishu, 小艺用xiaoyi",+ "default": "web"},- "enabled": {+ "enabled": {"type": "boolean",- "description": "Whether job is enabled",+ "description": "是否启用","default": True,},"description": {"type": "string",- "description": "Optional job description",- "default": "",+ "description": "具体任务名称,到点执行时发给助手,不能为空。不要包含时间/频率,例如填「搜索美国总统年龄」而非「每天上午11点58分搜索美国总统年龄」",},"wake_offset_seconds": {"type": "integer",- "description": "Seconds before push time to wake (default 300)",+ "description": "提前多少秒执行,默认 300",+ "default": 300,},},- "required": ["name", "cron_expr", "timezone", "targets"],+ "required": ["name", "cron_expr", "timezone", "description"],},func=self._create_job_tool,),diff --git a/jiuwenclaw/gateway/cron/models.py b/jiuwenclaw/gateway/cron/models.pyindex c8ec6715b2..6e70ccdf95 100644--- a/jiuwenclaw/gateway/cron/models.py+++ b/jiuwenclaw/gateway/cron/models.py@@ -38,7 +38,9 @@ class CronJob:timezone: strwake_offset_seconds: int = 300description: str = ""- targets: list[CronTarget] = field(default_factory=list)+ # Target channel ID to push results to (e.g. "web").+ # JSON 字段名仍然叫 targets,用字符串保存频道 ID,兼容旧数据。+ targets: str = ""created_at: float | None = Noneupdated_at: float | None = None@@ -51,7 +53,7 @@ class CronJob:"timezone": self.timezone,"wake_offset_seconds": int(self.wake_offset_seconds),"description": self.description,- "targets": [t.to_dict() for t in self.targets],+ "targets": self.targets,"created_at": self.created_at,"updated_at": self.updated_at,}@@ -74,14 +76,19 @@ class CronJob:description = str(data.get("description") or "")- targets_raw = data.get("targets") or []- if not isinstance(targets_raw, list):- raise ValueError("targets must be list")- targets: list[CronTarget] = []- for item in targets_raw:- if not isinstance(item, dict):- continue- targets.append(CronTarget.from_dict(item))+ # targets 新格式是字符串;旧格式是 list[dict],此处做兼容。+ targets_raw = data.get("targets", "")+ targets_str = ""+ if isinstance(targets_raw, str):+ targets_str = targets_raw.strip()+ elif isinstance(targets_raw, list):+ # legacy: list of {channel_id, session_id?}+ for item in targets_raw:+ if isinstance(item, dict):+ ch = str(item.get("channel_id") or "").strip()+ if ch:+ targets_str = ch+ breakcreated_at = data.get("created_at", None)updated_at = data.get("updated_at", None)@@ -96,7 +103,7 @@ class CronJob:raise ValueError("cron_expr is required")if not timezone:raise ValueError("timezone is required")- if not targets:+ if not targets_str:raise ValueError("targets is required")return CronJob(@@ -107,7 +114,7 @@ class CronJob:timezone=timezone,wake_offset_seconds=wake_offset_seconds,description=description,- targets=targets,+ targets=targets_str,created_at=created_at_f,updated_at=updated_at_f,)@@ -127,5 +134,4 @@ class CronRunState:started_at: float | None = Nonefinished_at: float | None = Noneresult_text: str | None = None- error: str | None = None-+ error: str | None = None\ No newline at end of filediff --git a/jiuwenclaw/gateway/cron/scheduler.py b/jiuwenclaw/gateway/cron/scheduler.pyindex 4fe7fa95f1..ccdbcaa20d 100644--- a/jiuwenclaw/gateway/cron/scheduler.py+++ b/jiuwenclaw/gateway/cron/scheduler.py@@ -248,10 +248,11 @@ class CronSchedulerService:state.status = "running"state.started_at = self._now_fn()try:+ ts = format(int(time.time() * 1000), "x")req = AgentRequest(request_id=f"cron-{run_id}",channel_id="__cron__",- session_id=f"cron_{job.id}_{run_id.split(':')[-1]}",+ session_id=f"cron_{ts}_{job.id}",req_method=ReqMethod.CHAT_SEND,params={"content": job.description,@@ -350,17 +351,18 @@ class CronSchedulerService:"status": state.status,},}- for target in job.targets:- msg = Message(- id=f"cron-push-{state.run_id}-{target.channel_id}",- type="event",- channel_id=target.channel_id,- session_id=target.session_id,- params={},- timestamp=self._now_fn(),- ok=True,- payload=payload_extra,- event_type=EventType.CHAT_FINAL,- )- await self._message_handler.publish_robot_messages(msg)-+ channel_id = (job.targets or "").strip()+ if not channel_id:+ return+ msg = Message(+ id=f"cron-push-{state.run_id}-{channel_id}",+ type="event",+ channel_id=channel_id,+ session_id=None,+ params={},+ timestamp=self._now_fn(),+ ok=True,+ payload=payload_extra,+ event_type=EventType.CHAT_FINAL,+ )+ await self._message_handler.publish_robot_messages(msg)diff --git a/jiuwenclaw/gateway/cron/store.py b/jiuwenclaw/gateway/cron/store.pyindex 9ce2d69235..664f4b4dc2 100644--- a/jiuwenclaw/gateway/cron/store.py+++ b/jiuwenclaw/gateway/cron/store.py@@ -57,7 +57,7 @@ class CronJobStore:cron_expr: str,timezone: str,description: str,- targets: list[dict[str, Any]] | list[CronTarget],+ targets: str,enabled: bool = True,wake_offset_seconds: int | None = None,) -> CronJob:@@ -70,7 +70,7 @@ class CronJobStore:timezone=str(timezone or "").strip(),wake_offset_seconds=int(wake_offset_seconds) if wake_offset_seconds is not None else 300,description=str(description or ""),- targets=self._normalize_targets(targets),+ targets=str(targets or "").strip(),created_at=now,updated_at=now,)@@ -107,7 +107,7 @@ class CronJobStore:if "description" in patch:updated = replace(updated, description=str(patch.get("description") or ""))if "targets" in patch:- updated = replace(updated, targets=self._normalize_targets(patch.get("targets") or []))+ updated = replace(updated, targets=str(patch.get("targets") or "").strip())updated.updated_at = time.time()CronJob.from_dict(updated.to_dict())@@ -201,4 +201,3 @@ class CronJobStore:if not out:raise ValueError("targets is required")return out-