Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix:/cron定时命令支持tui

openJiuwen-bot8518abc5d1bf
diff --git a/docs/en/SlashCommands.md b/docs/en/SlashCommands.md
index a68b5844fd..f8cd65fd29 100644
--- a/docs/en/SlashCommands.md
+++ b/docs/en/SlashCommands.md
@@ -319,7 +319,7 @@ Manage cron jobs via RPC calls to the backend `CronController`, sharing the same
| `/cron add name=<name> cron_expr=<expression> description=<desc> [other params]` | Create a new cron job |
| `/cron update <job_id> key=value ...` | Update specific fields of a job |
| `/cron delete <job_id>` | Delete a job |
-| `/cron toggle <job_id> on|off` | Enable or disable a job |
+| `/cron toggle <job_id> <on or off>` | Enable or disable a job |
| `/cron run <job_id>` | Run a job immediately |
| `/cron preview <job_id>` | Preview upcoming execution times for a job |
@@ -328,18 +328,19 @@ Manage cron jobs via RPC calls to the backend `CronController`, sharing the same
| Parameter | Required | Description |
|---|---|---|
| `name` | Yes | Job name |
-| `cron_expr` | Yes | Cron expression (7-field Quartz format: sec min hour day month dow year) |
+| `cron_expr` | Yes | Cron expression, supports two formats: 5-field (min hour day month dow) or 7-field Quartz (sec min hour day month dow year). 5-field is auto-converted to 7-field (second=0, year=*). Examples: daily 9am = `0 9 * * *` (5-field) or `0 0 9 * * ? *` (7-field) |
| `description` | Yes | Job description — the input prompt the Agent receives when executing |
-| `targets` | No | Push channel, default `web`; options: `web`, `feishu`, `whatsapp`, `wecom`, `xiaoyi`, `wechat`, or `feishu_enterprise:<app_id>` |
+| `targets` | No | Push channel, default `tui`; options: `tui`, `web`, `feishu`, `whatsapp`, `wecom`, `xiaoyi`, `wechat`, or `feishu_enterprise:<app_id>` |
| `timezone` | No | IANA timezone, default `Asia/Shanghai` |
-| `mode` | No | Execution mode: `agent` (default) or `plan` |
+| `mode` | No | Execution mode: `agent` (default, suitable for simple reminder-type tasks) or `plan` (for more complex reasoning tasks, allowing the Agent to plan the steps first before executing) |
| `wake_offset_seconds` | No | Wake-up offset in seconds, default 300 |
| `delete_after_run` | No | Auto-delete after one run, default false |
- `add` examples:
- - `/cron add name=minute-test cron_expr="0 * * * * * *" description="Tell me the current time" targets=web`
- - `/cron add name=morning-brief cron_expr="0 0 9 * * * *" description="Generate today's morning briefing" targets=web mode=plan`
- - `/cron add name=reminder cron_expr="0 0 14 15 5 * *" description="Don't forget the meeting" targets=web delete_after_run=true`
+ - `/cron add name=minute-test cron_expr="0 * * * *" description="Tell me the current time" targets=tui`
+ - `/cron add name=morning-brief cron_expr="0 9 * * *" description="Generate today's morning briefing" targets=tui mode=plan`
+ - `/cron add name=reminder cron_expr="0 30 17 29 4 ? 2026" description="Don't forget the meeting" targets=tui delete_after_run=true`
+ - `/cron add name=weekly-report cron_expr="0 9 * * 1" description="Generate weekly report" targets=web`
- `update` usage: Only pass the fields you want to change, e.g., `/cron update <id> name=new-name enabled=false`
- `list` display: sequence number, full job ID, name, cron expression, enabled status, description snippet
diff --git "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md" "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"
index 6a1c82d423..7d8f3e06a9 100644
--- "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"
+++ "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"
@@ -341,7 +341,7 @@
| `/cron add name=<名称> cron_expr=<表达式> description=<描述> [其他参数]` | 新增定时任务 |
| `/cron update <job_id> key=value ...` | 更新指定任务的部分字段 |
| `/cron delete <job_id>` | 删除指定任务 |
-| `/cron toggle <job_id> on|off` | 启用或禁用指定任务 |
+| `/cron toggle <job_id> <on或off>` | 启用或禁用指定任务 |
| `/cron run <job_id>` | 立即执行指定任务 |
| `/cron preview <job_id>` | 预览任务接下来几次执行时间 |
@@ -350,18 +350,19 @@
| 参数 | 必填 | 说明 |
|---|---|---|
| `name` | 是 | 任务名称 |
-| `cron_expr` | 是 | Cron 表达式(7 字段 Quartz 格式:秒 分 时 日 月 周 年) |
+| `cron_expr` | 是 | Cron 表达式,支持两种格式:5 字段(分 时 日 月 周)或 7 字段 Quartz(秒 分 时 日 月 周 年)。5 字段会自动转换为 7 字段(补 second=0, year=*)。示例:每天 9 点 = `0 9 * * *`(5 字段)或 `0 0 9 * * ? *`(7 字段) |
| `description` | 是 | 任务描述,即 Agent 执行时收到的输入指令 |
-| `targets` | 否 | 推送渠道,默认 `web`;可选:`web`、`feishu`、`whatsapp`、`wecom`、`xiaoyi`、`wechat` 或 `feishu_enterprise:<app_id>` |
+| `targets` | 否 | 推送渠道,默认 `tui`;可选:`tui`、`web`、`feishu`、`whatsapp`、`wecom`、`xiaoyi`、`wechat` 或 `feishu_enterprise:<app_id>` |
| `timezone` | 否 | IANA 时区,默认 `Asia/Shanghai` |
-| `mode` | 否 | 执行模式:`agent`(默认)或 `plan` |
+| `mode` | 否 | 执行模式:`agent`(默认,适用于简单提醒类任务)或 `plan`(较复杂的推理任务,让Agent先规划步骤再执行) |
| `wake_offset_seconds` | 否 | 提前唤醒秒数,默认 300 |
| `delete_after_run` | 否 | 执行一次后自动删除,默认 false |
- `add` 示例:
- - `/cron add name=每分钟测试 cron_expr="0 * * * * * *" description="告诉我现在几点了" targets=web`
- - `/cron add name=晨报 cron_expr="0 0 9 * * * *" description="生成今日晨报摘要" targets=web mode=plan`
- - `/cron add name=提醒 cron_expr="0 0 14 15 5 * *" description="别忘了开会" targets=web delete_after_run=true`
+ - `/cron add name=每分钟测试 cron_expr="0 * * * *" description="告诉我现在几点了" targets=tui`
+ - `/cron add name=晨报 cron_expr="0 9 * * *" description="生成今日晨报摘要" targets=tui mode=plan`
+ - `/cron add name=提醒 cron_expr="0 30 17 29 4 ? 2026" description="别忘了开会" targets=tui delete_after_run=true`
+ - `/cron add name=每周一报 cron_expr="0 9 * * 1" description="生成本周周报" targets=web`
- `update` 用法:只需传入要修改的字段,如 `/cron update <id> name=新名称 enabled=false`
- `list` 显示内容:序号、完整 job ID、名称、cron 表达式、启用状态、描述摘要
diff --git a/jiuwenclaw/agents/harness/common/tools/cron/cron_tools.py b/jiuwenclaw/agents/harness/common/tools/cron/cron_tools.py
index 05fdcb4fe2..75781d532f 100644
--- a/jiuwenclaw/agents/harness/common/tools/cron/cron_tools.py
+++ b/jiuwenclaw/agents/harness/common/tools/cron/cron_tools.py
@@ -9,6 +9,7 @@ from typing import Any
from zoneinfo import ZoneInfo
from openjiuwen.core.foundation.tool import LocalFunction, Tool, ToolCard
+from jiuwenclaw.gateway.cron.cron_expr import normalize_cron_expr
from jiuwenclaw.gateway.cron.store import CronJobStore
from jiuwenclaw.gateway.cron.scheduler import _cron_next_push_dt, CronSchedulerService
from jiuwenclaw.gateway.cron.models import (
@@ -182,7 +183,9 @@ class CronTools:
return CronTargetChannel.WHATSAPP.value
if channel.startswith("wechat"):
return CronTargetChannel.WECHAT.value
-
+ if channel.startswith("tui"):
+ return CronTargetChannel.TUI.value
+
return CronTargetChannel.WEB.value
def _resolve_channel_id(self) -> str:
@@ -228,6 +231,7 @@ class CronTools:
normalized = dict(params or {})
normalized.pop("session_id", None)
normalized["targets"] = self._normalize_targets_param(normalized.get("targets"))
+ normalized["cron_expr"] = normalize_cron_expr(str(normalized.get("cron_expr") or "").strip())
targets_str = normalized["targets"]
logger.info(
"[CronTools] create_job: route(channel=%s session=%s request=%s) input.targets=%s normalized.targets=%s",
@@ -269,6 +273,8 @@ class CronTools:
async def update_job(self, job_id: str, patch: dict[str, Any]) -> Any:
normalized_patch = dict(patch or {})
normalized_patch.pop("session_id", None)
+ if "cron_expr" in normalized_patch:
+ normalized_patch["cron_expr"] = normalize_cron_expr(str(normalized_patch["cron_expr"]).strip())
if "targets" in normalized_patch:
normalized_patch["targets"] = self._normalize_targets_param(normalized_patch.get("targets"))
t = str(normalized_patch.get("targets") or "").strip()
diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/cron.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/cron.ts
index e8614c20bb..c0bd102e0b 100644
--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/cron.ts
+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/cron.ts
@@ -21,7 +21,7 @@ interface CronJobListPayload {
jobs: CronJobPayload[];
}
-const TARGET_CHANNELS = ["web", "feishu", "whatsapp", "wecom", "xiaoyi", "wechat"];
+const TARGET_CHANNELS = ["tui", "web", "feishu", "whatsapp", "wecom", "xiaoyi", "wechat"];
const MODES = ["agent", "plan"];
export function createCronCommand(): SlashCommand {
@@ -32,7 +32,7 @@ export function createCronCommand(): SlashCommand {
usage: "/cron [list|add|update|delete|toggle|run|preview]",
example:
'/cron list\n' +
- '/cron add name=晨报 cron_expr="0 0 9 * * * *" description="生成简短的中文健康打卡提醒" targets=web\n' +
+ '/cron add name=晨报 cron_expr="0 9 * * *" description="生成简短的中文健康打卡提醒" targets=tui\n' +
'/cron update <id> description="新的任务内容"\n' +
"/cron delete <id>\n" +
"/cron toggle <id> on|off\n" +
@@ -54,7 +54,7 @@ export function createCronCommand(): SlashCommand {
name: "add",
description: "创建定时任务",
usage: "/cron add name=... cron_expr=\"...\" description=\"...\"",
- argGuide: "name=任务名 cron_expr=\"时间表达式\" description=\"让Agent做什么\" targets=web",
+ argGuide: "name=任务名 cron_expr=\"时间表达式(5字段或7字段)\" description=\"让Agent做什么\" targets=tui",
kind: CommandKind.BUILT_IN,
takesArgs: true,
action: async (ctx, args) => _handleAdd(ctx, `add ${args}`),
@@ -207,13 +207,13 @@ async function _handleAdd(ctx: CommandContext, raw: string): Promise<void> {
ctx.addItem(
addError(
ctx.sessionId,
- `缺少必填字段: ${missing.join(", ")}。必填: name(任务名)、cron_expr(时间)、description(让Agent做什么)。示例: /cron add name=晨报 cron_expr="0 0 9 * * *" description="生成健康打卡提醒" targets=web`,
+ `缺少必填字段: ${missing.join(", ")}。必填: name(任务名)、cron_expr(时间)、description(让Agent做什么)。示例: /cron add name=晨报 cron_expr="0 9 * * *" description="生成健康打卡提醒" targets=tui`,
),
);
return;
}
- if (!kvPairs.targets) kvPairs.targets = "web";
+ if (!kvPairs.targets) kvPairs.targets = "tui";
if (!kvPairs.timezone) kvPairs.timezone = "Asia/Shanghai";
if (!kvPairs.mode) kvPairs.mode = "agent";
diff --git a/jiuwenclaw/channels/web/frontend/src/components/CronPanel/index.tsx b/jiuwenclaw/channels/web/frontend/src/components/CronPanel/index.tsx
index 0b2cb7f3c2..78c52f9a26 100644
--- a/jiuwenclaw/channels/web/frontend/src/components/CronPanel/index.tsx
+++ b/jiuwenclaw/channels/web/frontend/src/components/CronPanel/index.tsx
@@ -300,6 +300,7 @@ export default function CronPanel({ sessionId }: CronPanelProps) {
// 目标选项 - 动态根据启用状态
const targetOptions = useMemo(() => [
{ value: 'web', label: t('cron.targets.web'), disabled: !enabledChannels.has('web') },
+ { value: 'tui', label: t('cron.targets.tui'), disabled: !enabledChannels.has('tui') },
{ value: 'xiaoyi', label: t('cron.targets.xiaoyi'), disabled: !enabledChannels.has('xiaoyi') },
{ value: 'feishu', label: t('cron.targets.feishu'), disabled: !enabledChannels.has('feishu') },
{ value: 'whatsapp', label: t('cron.targets.whatsapp'), disabled: !enabledChannels.has('whatsapp') },
diff --git a/jiuwenclaw/channels/web/frontend/src/i18n/locales/en.json b/jiuwenclaw/channels/web/frontend/src/i18n/locales/en.json
index a0bf68a8e8..a0018931a4 100644
--- a/jiuwenclaw/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenclaw/channels/web/frontend/src/i18n/locales/en.json
@@ -694,6 +694,7 @@
},
"targets": {
"web": "Web (web)",
+ "tui": "Terminal (tui)",
"xiaoyi": "Xiaoyi (xiaoyi)",
"feishu": "Lark (feishu)",
"whatsapp": "WhatsApp (whatsapp)",
diff --git a/jiuwenclaw/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenclaw/channels/web/frontend/src/i18n/locales/zh.json
index de16935f83..28b3b5c1cc 100644
--- a/jiuwenclaw/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenclaw/channels/web/frontend/src/i18n/locales/zh.json
@@ -694,6 +694,7 @@
},
"targets": {
"web": "网页 (web)",
+ "tui": "终端 (tui)",
"xiaoyi": "小艺 (xiaoyi)",
"feishu": "飞书 (feishu)",
"whatsapp": "WhatsApp (whatsapp)",
diff --git a/jiuwenclaw/gateway/app_gateway.py b/jiuwenclaw/gateway/app_gateway.py
index 401bfc9433..2d3a22e51f 100644
--- a/jiuwenclaw/gateway/app_gateway.py
+++ b/jiuwenclaw/gateway/app_gateway.py
@@ -76,6 +76,18 @@ logger = logging.getLogger("jiuwenclaw.gateway")
_PROMPT_IDLE_FINALIZE_SECONDS = 3.0
+def _build_event_frame(msg) -> dict[str, Any]:
+ event_name = "chat.final"
+ if msg.event_type is not None:
+ event_name = msg.event_type.value
+ if isinstance(msg.payload, dict):
+ payload = {**msg.payload}
+ payload.setdefault("session_id", msg.session_id)
+ else:
+ payload = {"session_id": msg.session_id, "content": str(msg.payload or "")}
+ return {"type": "event", "event": event_name, "payload": payload}
+
+
def _normalize_gateway_message(msg):
from jiuwenclaw.common.schema.message import Message, ReqMethod
@@ -257,6 +269,12 @@ class GatewayServer:
return None
return channel, scope
+ def _find_channel_clients(self, channel_id: str) -> list[Any]:
+ return [
+ client_ws for key, client_ws in self._session_to_client.items()
+ if isinstance(key, tuple) and key[0] == channel_id and not getattr(client_ws, "closed", False)
+ ]
+
def on_message(self, callback) -> None:
self._on_message_cb = callback
@@ -405,6 +423,28 @@ class GatewayServer:
if ws is None:
ws = self._session_to_client.get(session_key[1])
if ws is None or bool(getattr(ws, "closed", False)):
+ if ws is None:
+ channel_id = getattr(msg, "channel_id", None)
+ if channel_id and channel_id != "acp" and msg.type != "res":
+ clients = self._find_channel_clients(channel_id)
+ if clients:
+ frame = _build_event_frame(msg)
+ data = json.dumps(frame, ensure_ascii=False)
+ logger.info(
+ "[GatewayServer] broadcast fallback: channel_id=%s clients=%d id=%s",
+ channel_id, len(clients), getattr(msg, "id", None),
+ )
+ await asyncio.gather(
+ *[c.send(data) for c in clients],
+ return_exceptions=True,
+ )
+ return
+ logger.warning(
+ "[GatewayServer] message dropped: no WebSocket client found for channel_id=%s session_id=%s id=%s",
+ getattr(msg, "channel_id", None),
+ getattr(msg, "session_id", None),
+ getattr(msg, "id", None),
+ )
return
if getattr(msg, "channel_id", None) == "acp":
diff --git a/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py b/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py
index 9af48feb92..a0c425c83a 100644
--- a/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py
+++ b/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py
@@ -1757,6 +1757,8 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
return
try:
+ if session_id:
+ params["session_id"] = session_id
job = await cc.create_job(params)
await channel.send_response(ws, req_id, ok=True, payload={"job": job})
except Exception as exc:
diff --git a/jiuwenclaw/gateway/cron/controller.py b/jiuwenclaw/gateway/cron/controller.py
index 1e6af8015f..81d66da7fa 100644
--- a/jiuwenclaw/gateway/cron/controller.py
+++ b/jiuwenclaw/gateway/cron/controller.py
@@ -6,6 +6,7 @@ from typing import Any, ClassVar, List
from openjiuwen.core.foundation.tool import LocalFunction, Tool, ToolCard
from zoneinfo import ZoneInfo
+from jiuwenclaw.gateway.cron.cron_expr import normalize_cron_expr
from jiuwenclaw.gateway.cron.models import (
CronTargetChannel,
is_valid_target_channel_id,
@@ -80,7 +81,10 @@ class CronController:
if not raw_s:
return normalize_target_channel_id(self._target_channel.value)
if not is_valid_target_channel_id(raw_s):
- raise ValueError("targets must be one of web/feishu/whatsapp/wecom/xiaoyi or feishu_enterprise:<app_id>")
+ raise ValueError(
+ "targets must be one of tui/web/feishu/whatsapp/wecom/xiaoyi"
+ " or feishu_enterprise:<app_id>"
+ )
return normalize_target_channel_id(raw_s)
@classmethod
@@ -97,19 +101,20 @@ class CronController:
return description
@staticmethod
- def _routing_session_id_for_enterprise(targets: str, raw: Any) -> str | None:
- """Only accept SessionMap-style ids (feishu::...) for feishu_enterprise targets."""
- if not str(targets or "").strip().startswith("feishu_enterprise:"):
- return None
- if not isinstance(raw, str):
- return None
- s = raw.strip()
- if not s or "::" not in s:
- return None
- parts = s.split("::")
- if len(parts) < 3 or parts[0] != "feishu":
+ def _routing_session_id(targets: str, raw: Any) -> str | None:
+ """Accept session_id for all channels; feishu_enterprise requires SessionMap format."""
+ targets_s = str(targets or "").strip()
+ raw_s = str(raw or "").strip() if isinstance(raw, str) else ""
+ if not raw_s:
return None
- return s
+ if targets_s.startswith("feishu_enterprise:"):
+ if "::" not in raw_s:
+ return None
+ parts = raw_s.split("::")
+ if len(parts) < 3 or parts[0] != "feishu":
+ return None
+ return raw_s
+ return raw_s
async def list_jobs(self) -> list[dict[str, Any]]:
jobs = await self._store.list_jobs()
@@ -121,7 +126,7 @@ 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()
+ cron_expr = normalize_cron_expr(str(params.get("cron_expr") 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 "")
@@ -133,7 +138,7 @@ class CronController:
self._validate_schedule(cron_expr=cron_expr, timezone=timezone)
description = self._normalize_description(description, name)
- routing_sid = self._routing_session_id_for_enterprise(targets, params.get("session_id"))
+ routing_sid = self._routing_session_id(targets, params.get("session_id"))
chat_type = params.get("chat_type")
delete_after_run = params.get("delete_after_run")
job = await self._store.create_job(
@@ -160,6 +165,8 @@ class CronController:
existing = await self._store.get_job(job_id)
if existing is None:
raise KeyError("job not found")
+ if "cron_expr" in patch:
+ patch["cron_expr"] = normalize_cron_expr(str(patch["cron_expr"]).strip())
if "cron_expr" in patch or "timezone" in patch:
cron_expr = str(patch.get("cron_expr") or existing.cron_expr).strip()
timezone = str(patch.get("timezone") or existing.timezone).strip()
@@ -170,14 +177,13 @@ class CronController:
final_targets = str(patch.get("targets") or existing.targets).strip()
if "session_id" in patch:
- if final_targets.startswith("feishu_enterprise:"):
- patch["session_id"] = self._routing_session_id_for_enterprise(
- final_targets, patch.get("session_id")
- )
- else:
- patch["session_id"] = None
- elif "targets" in patch and not final_targets.startswith("feishu_enterprise:"):
- patch["session_id"] = None
+ patch["session_id"] = self._routing_session_id(
+ final_targets, patch.get("session_id")
+ )
+ elif "targets" in patch:
+ patch["session_id"] = self._routing_session_id(
+ final_targets, existing.session_id
+ )
job = await self._store.update_job(job_id, patch)
await self._scheduler.reload()
@@ -355,7 +361,7 @@ class CronController:
"targets": {
"type": "string",
"enum": [e.value for e in CronTargetChannel],
- "description": "Delivery channel: web, feishu, whatsapp, wecom, xiaoyi. "
+ "description": "Delivery channel: tui, web, feishu, whatsapp, wecom, xiaoyi. "
"If omitted, use the current request source channel.",
},
"enabled": {
diff --git a/jiuwenclaw/gateway/cron/cron_expr.py b/jiuwenclaw/gateway/cron/cron_expr.py
index ff38dcd1ef..4ab00da95c 100644
--- a/jiuwenclaw/gateway/cron/cron_expr.py
+++ b/jiuwenclaw/gateway/cron/cron_expr.py
@@ -9,6 +9,26 @@ def cron_field_count(expr: str) -> int:
return len(str(expr or "").split())
+def normalize_cron_expr(raw: str) -> str:
+ """Normalize cron expression to 7-field Quartz format.
+
+ 5-field (minute hour day month dow) → prepend "0" (second) and append "*" (year).
+ 7-field is left unchanged.
+ Other field counts raise ValueError.
+ """
+ s = str(raw or "").strip()
+ n = cron_field_count(s)
+ if n == 5:
+ return f"0 {s} *"
+ if n == 7:
+ return s
+ raise ValueError(
+ f"cron_expr must have 5 or 7 fields, got {n} fields. "
+ "5-field: minute hour day month dow. "
+ "7-field (Quartz): second minute hour day month dow year."
+ )
+
+
def iso_to_seven_field_cron(at_iso: str, *, timezone: str) -> str:
"""Convert ISO8601 datetime into 7-field cron (Quartz format):
second minute hour day month dow year.
@@ -30,7 +50,10 @@ def iso_to_seven_field_cron(at_iso: str, *, timezone: str) -> str:
def validate_cron_expression(expr: str, *, timezone: str) -> None:
- """Validate cron expression format is 7 fields (Quartz format: second minute hour day month dow year).
+ """Validate cron expression (5-field or 7-field Quartz format).
+
+ 5-field (minute hour day month dow) is auto-normalized to 7-field by prepending
+ second=0 and appending year=*.
Note: for 7-field one-shot with a fixed past year, `croniter.get_next()`
can fail; we only validate syntax here.
@@ -41,13 +64,12 @@ def validate_cron_expression(expr: str, *, timezone: str) -> None:
if not raw:
raise ValueError("cron_expr is empty")
- n = cron_field_count(raw)
- if n != 7:
+ normalized = normalize_cron_expr(raw)
+
+ # Use second_at_beginning=True for Quartz 7-field format
+ if not croniter.is_valid(normalized, second_at_beginning=True):
raise ValueError(
- f"cron_expr must have 7 fields (second minute hour day month dow year), got {n} fields"
+ f"invalid cron expression: '{raw}'"
)
- # Use second_at_beginning=True for Quartz 7-field format
- if not croniter.is_valid(raw, second_at_beginning=True):
- raise ValueError("invalid cron expression")
_ = ZoneInfo(timezone)
- croniter(raw, datetime.now(tz=ZoneInfo(timezone)), second_at_beginning=True)
+ croniter(normalized, datetime.now(tz=ZoneInfo(timezone)), second_at_beginning=True)
diff --git a/jiuwenclaw/gateway/cron/models.py b/jiuwenclaw/gateway/cron/models.py
index a39ce34055..028bf3e0c1 100644
--- a/jiuwenclaw/gateway/cron/models.py
+++ b/jiuwenclaw/gateway/cron/models.py
@@ -9,6 +9,7 @@ class CronTargetChannel(str, Enum):
"""推送频道枚举。"""
WEB = "web"
+ TUI = "tui"
FEISHU = "feishu"
WHATSAPP = "whatsapp"
WECOM = "wecom"