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: Agent 添加定时任务工具
douran8368b9793aff
diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.pyindex 9b94c99255..1e3a61d88b 100644--- a/jiuwenclaw/agentserver/interface.py+++ b/jiuwenclaw/agentserver/interface.py@@ -14,6 +14,8 @@ from dotenv import load_dotenvfrom openjiuwen.core.runner import Runnerfrom openjiuwen.core.single_agent import AgentCard, ReActAgentConfigfrom openjiuwen.core.sys_operation import SysOperationCard, OperationMode, LocalWorkConfig++from jiuwenclaw.gateway.cron import CronControllerfrom jiuwenclaw.utils import _get_config_module, get_root_dir, logger, USER_WORKSPACE_DIR_config_module = _get_config_module()@@ -302,6 +304,14 @@ class JiuWenClaw:except Exception as exc:logger.warning("[JiuWenClaw] browser MCP registration skipped: %s", exc)+ # add cron tools+ try:+ cron_controller = CronController.get_instance()+ for cron_tool in cron_controller.get_tools():+ Runner.resource_mgr.add_tool(cron_tool)+ self._instance.ability_manager.add(cron_tool.card)+ except Exception as exc:+ logger.error("[JiuWenClaw] 定时工具加载失败, reason=%s", exc)logger.info("[JiuWenClaw] 初始化完成: agent_name=%s", self._agent_name)def reload_agent_config(self) -> None:diff --git a/jiuwenclaw/app.py b/jiuwenclaw/app.pyindex 67ca9a8eaa..909e50b8b8 100644--- a/jiuwenclaw/app.py+++ b/jiuwenclaw/app.py@@ -907,7 +907,7 @@ async def _run() -> None:# ---------- 一次启动所有服务 ----------agent = JiuWenClaw()- await agent.create_instance()+server = AgentWebSocketServer(agent, host="127.0.0.1", port=agent_port,ping_interval=20.0, ping_timeout=20.0,@@ -923,7 +923,10 @@ async def _run() -> None:cron_store = CronJobStore()cron_scheduler = CronSchedulerService(store=cron_store, agent_client=client, message_handler=message_handler)- cron_controller = CronController(store=cron_store, scheduler=cron_scheduler)+ cron_controller = CronController.get_instance(store=cron_store, scheduler=cron_scheduler)++ # agent实例化需要在定时任务后+ await agent.create_instance()# 探活:周期性向 AgentServer 发送心跳,便于检测连接与 Agent 可用性# 优先从 config/config.yaml 的 heartbeat 段读取配置,其次回退到环境变量/默认值diff --git a/jiuwenclaw/gateway/cron/controller.py b/jiuwenclaw/gateway/cron/controller.pyindex 8a17e42a5d..aa7eff360e 100644--- a/jiuwenclaw/gateway/cron/controller.py+++ b/jiuwenclaw/gateway/cron/controller.py@@ -1,7 +1,9 @@from __future__ import annotationsfrom datetime import datetime, timedelta-from typing import Any+from typing import Any, ClassVar, List++from openjiuwen.core.foundation.tool import LocalFunction, Tool, ToolCardfrom zoneinfo import ZoneInfofrom jiuwenclaw.gateway.cron.scheduler import CronSchedulerService, _cron_next_push_dt@@ -9,12 +11,50 @@ from jiuwenclaw.gateway.cron.store import CronJobStoreclass CronController:- """High-level cron API used by WebChannel handlers."""+ """High-level cron API used by WebChannel handlers. Singleton."""++ _instance: ClassVar[CronController | None] = Nonedef __init__(self, *, store: CronJobStore, scheduler: CronSchedulerService) -> None:self._store = storeself._scheduler = scheduler+ @classmethod+ def get_instance(+ cls,+ *,+ store: CronJobStore | None = None,+ scheduler: CronSchedulerService | None = None,+ ) -> CronController:+ """Return the singleton instance.++ On first call, store and scheduler are required to create the instance.+ On subsequent calls, both can be omitted to get the existing instance.++ Args:+ store: Required only on first call.+ scheduler: Required only on first call.++ Returns:+ The singleton CronController.++ Raises:+ RuntimeError: If instance not yet initialized and store/scheduler not provided.+ """+ if cls._instance is not None:+ return cls._instance+ if store is None or scheduler is None:+ raise RuntimeError(+ "CronController not initialized. Call get_instance(store=..., scheduler=...) first."+ )+ cls._instance = cls(store=store, scheduler=scheduler)+ return cls._instance++ @classmethod+ def reset_instance(cls) -> None:+ """Reset the singleton. For testing only."""+ cls._instance = None+@staticmethoddef _validate_schedule(*, cron_expr: str, timezone: str) -> None:tz = ZoneInfo(timezone)@@ -97,3 +137,205 @@ class CronController:run_id = await self._scheduler.trigger_run_now(job_id)return run_id+ async def _create_job_tool(+ self,+ name: str,+ cron_expr: str,+ timezone: str,+ targets: list[dict[str, Any]],+ enabled: bool = True,+ description: str = "",+ wake_offset_seconds: int | None = None,+ ) -> dict[str, Any]:+ params: dict[str, Any] = {+ "name": name,+ "cron_expr": cron_expr,+ "timezone": timezone,+ "targets": targets,+ "enabled": enabled,+ "description": description,+ }+ if wake_offset_seconds is not None:+ params["wake_offset_seconds"] = wake_offset_seconds+ return await self.create_job(params)++ async def _update_job_tool(+ self, job_id: str, patch: dict[str, Any]+ ) -> dict[str, Any]:+ return await self.update_job(job_id, patch)++ async def _preview_job_tool(+ self, job_id: str, count: int = 5+ ) -> list[dict[str, Any]]:+ return await self.preview_job(job_id, count)++ def get_tools(self) -> List[Tool]:+ """Return cron job tools for registration in the openJiuwen Runner.+ Tools to be returned:+ list_jobs+ get_job+ create_job+ update_job+ delete_job+ toggle_job+ preview_job++ Usage:+ toolkit = CronController(xxxxxx)+ tools = toolkit.get_tools()+ Runner.resource_mgr.add_tool(tools)+ for t in tools:+ agent.ability_manager.add(t.card)++ Returns:+ List of Tool instances (LocalFunction) ready for Runner/agent registration.+ """++ def make_tool(+ name: str,+ description: str,+ input_params: dict,+ func,+ ) -> Tool:+ card = ToolCard(+ id=f"cron_{name}",+ name=name,+ description=description,+ input_params=input_params,+ )+ return LocalFunction(card=card, func=func)++ return [+ make_tool(+ name="cron_list_jobs",+ description="List all cron jobs. Returns a list of job objects with id, name, cron_expr, timezone, enabled, etc.",+ input_params={"type": "object", "properties": {}},+ func=self.list_jobs,+ ),+ make_tool(+ name="cron_get_job",+ description="Get a single cron job by id. Returns job details or None if not found.",+ input_params={+ "type": "object",+ "properties": {+ "job_id": {+ "type": "string",+ "description": "The job id to look up",+ }+ },+ "required": ["job_id"],+ },+ func=self.get_job,+ ),+ 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."+ ),+ input_params={+ "type": "object",+ "properties": {+ "name": {"type": "string", "description": "Job name"},+ "cron_expr": {+ "type": "string",+ "description": "Cron expression, e.g. '0 9 * * 1-5' for 9am weekdays",+ },+ "timezone": {+ "type": "string",+ "description": "Timezone, e.g. '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",+ },+ "enabled": {+ "type": "boolean",+ "description": "Whether job is enabled",+ "default": True,+ },+ "description": {+ "type": "string",+ "description": "Optional job description",+ "default": "",+ },+ "wake_offset_seconds": {+ "type": "integer",+ "description": "Seconds before push time to wake (default 300)",+ },+ },+ "required": ["name", "cron_expr", "timezone", "targets"],+ },+ func=self._create_job_tool,+ ),+ make_tool(+ name="cron_update_job",+ description="Update an existing cron job. Pass job_id and a patch dict with fields to update (name, enabled, cron_expr, timezone, description, wake_offset_seconds, targets).",+ input_params={+ "type": "object",+ "properties": {+ "job_id": {"type": "string", "description": "Job id to update"},+ "patch": {+ "type": "object",+ "description": "Fields to update (name, enabled, cron_expr, timezone, description, wake_offset_seconds, targets)",+ },+ },+ "required": ["job_id", "patch"],+ },+ func=self._update_job_tool,+ ),+ make_tool(+ name="cron_delete_job",+ description="Delete a cron job by id. Returns True if deleted, False if not found.",+ input_params={+ "type": "object",+ "properties": {+ "job_id": {"type": "string", "description": "Job id to delete"},+ },+ "required": ["job_id"],+ },+ func=self.delete_job,+ ),+ make_tool(+ name="cron_toggle_job",+ description="Enable or disable a cron job. Pass job_id and enabled (true/false).",+ input_params={+ "type": "object",+ "properties": {+ "job_id": {"type": "string", "description": "Job id"},+ "enabled": {+ "type": "boolean",+ "description": "Whether to enable the job",+ },+ },+ "required": ["job_id", "enabled"],+ },+ func=self.toggle_job,+ ),+ make_tool(+ name="cron_preview_job",+ description="Preview next N scheduled run times for a job. Returns list of {wake_at, push_at} timestamps.",+ input_params={+ "type": "object",+ "properties": {+ "job_id": {"type": "string", "description": "Job id"},+ "count": {+ "type": "integer",+ "description": "Number of runs to preview (1-50, default 5)",+ "default": 5,+ },+ },+ "required": ["job_id"],+ },+ func=self._preview_job_tool,+ ),+ ]\ No newline at end of filediff --git a/jiuwenclaw/gateway/cron/store.py b/jiuwenclaw/gateway/cron/store.pyindex b79972839e..9ce2d69235 100644--- a/jiuwenclaw/gateway/cron/store.py+++ b/jiuwenclaw/gateway/cron/store.py@@ -9,7 +9,7 @@ from pathlib import Pathfrom typing import Anyfrom jiuwenclaw.gateway.cron.models import CronJob, CronTarget-from jiuwenclaw.paths import get_root_dir+from jiuwenclaw.utils import get_root_dirclass CronJobStore:diff --git a/jiuwenclaw/resources/cron_test.py b/jiuwenclaw/resources/cron_test.pyindex 65d9a5d0a0..299ac908c0 100644--- a/jiuwenclaw/resources/cron_test.py+++ b/jiuwenclaw/resources/cron_test.py@@ -76,9 +76,10 @@ async def main() -> None:sink = TestMessageSink()# 2. 初始化 cron 组件+ CronController.reset_instance()store = CronJobStore()scheduler = CronSchedulerService(store=store, agent_client=client, message_handler=sink)- controller = CronController(store=store, scheduler=scheduler)+ controller = CronController.get_instance(store=store, scheduler=scheduler)# 3. 创建一个立即执行的 cron 任务(通过 run_now 触发,无需等待真实 cron 时间)params = {