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参数校验

openJiuwen-botbc96b6fbe486
diff --git a/docs/en/SlashCommands.md b/docs/en/SlashCommands.md
index b2bcfc1bbf..7581f25270 100644
--- a/docs/en/SlashCommands.md
+++ b/docs/en/SlashCommands.md
@@ -318,6 +318,7 @@ Manage cron jobs via RPC calls to the backend `CronController`, sharing the same
| Command | Description |
|---|---|
| `/cron` or `/cron list` | List all cron jobs |
+| `/cron show <job_id>` | Show detailed info for a specific job |
| `/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 |
@@ -332,7 +333,7 @@ Manage cron jobs via RPC calls to the backend `CronController`, sharing the same
| `name` | Yes | Job name |
| `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 `tui`; options: `tui`, `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`, `dingtalk`, or `feishu_enterprise:<app_id>` |
| `timezone` | No | IANA timezone, default `Asia/Shanghai` |
| `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 |
@@ -345,6 +346,7 @@ Manage cron jobs via RPC calls to the backend `CronController`, sharing the same
- `/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`
+- `show` display: full job details in key-value format (id, name, status, cron_expr, timezone, description, targets, mode, wake_offset_seconds, delete_after_run)
- `list` display: sequence number, full job ID, name, cron expression, enabled status, description snippet
- `preview` display: wake_at and push_at timestamps for each upcoming execution
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 fc4ed02799..be446987b9 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"
@@ -340,6 +340,7 @@
| 命令 | 说明 |
|---|---|
| `/cron` 或 `/cron list` | 列出所有定时任务 |
+| `/cron show <job_id>` | 查看指定任务的详细信息 |
| `/cron add name=<名称> cron_expr=<表达式> description=<描述> [其他参数]` | 新增定时任务 |
| `/cron update <job_id> key=value ...` | 更新指定任务的部分字段 |
| `/cron delete <job_id>` | 删除指定任务 |
@@ -354,7 +355,7 @@
| `name` | 是 | 任务名称 |
| `cron_expr` | 是 | Cron 表达式,支持两种格式:5 字段(分 时 日 月 周)或 7 字段 Quartz(秒 分 时 日 月 周 年)。5 字段会自动转换为 7 字段(补 second=0, year=*)。示例:每天 9 点 = `0 9 * * *`(5 字段)或 `0 0 9 * * ? *`(7 字段) |
| `description` | 是 | 任务描述,即 Agent 执行时收到的输入指令 |
-| `targets` | 否 | 推送渠道,默认 `tui`;可选:`tui`、`web`、`feishu`、`whatsapp`、`wecom`、`xiaoyi`、`wechat` 或 `feishu_enterprise:<app_id>` |
+| `targets` | 否 | 推送渠道,默认 `tui`;可选:`tui`、`web`、`feishu`、`whatsapp`、`wecom`、`xiaoyi`、`wechat`、`dingtalk` 或 `feishu_enterprise:<app_id>` |
| `timezone` | 否 | IANA 时区,默认 `Asia/Shanghai` |
| `mode` | 否 | 执行模式:`agent`(默认,适用于简单提醒类任务)或 `plan`(较复杂的推理任务,让Agent先规划步骤再执行) |
| `wake_offset_seconds` | 否 | 提前唤醒秒数,默认 300 |
@@ -367,6 +368,7 @@
- `/cron add name=每周一报 cron_expr="0 9 * * 1" description="生成本周周报" targets=web`
- `update` 用法:只需传入要修改的字段,如 `/cron update <id> name=新名称 enabled=false`
+- `show` 显示内容:以 key-value 格式展示任务全部字段(id、name、status、cron_expr、timezone、description、targets、mode、wake_offset_seconds、delete_after_run)
- `list` 显示内容:序号、完整 job ID、名称、cron 表达式、启用状态、描述摘要
- `preview` 显示内容:每次执行计划的唤醒时间和推送时间
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/cron.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/cron.ts
index f6d8be895f..c1b8c1e5a5 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/cron.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/cron.ts
@@ -21,17 +21,118 @@ interface CronJobListPayload {
jobs: CronJobPayload[];
}
-const TARGET_CHANNELS = ["tui", "web", "feishu", "whatsapp", "wecom", "xiaoyi", "wechat"];
+const TARGET_CHANNELS = ["tui", "web", "feishu", "whatsapp", "wecom", "xiaoyi", "wechat", "dingtalk"];
const MODES = ["agent", "plan"];
+// ── cron expression syntax validation ──
+
+interface CronFieldRange {
+ min: number;
+ max: number;
+ allowQuestion: boolean;
+}
+
+const CRON_5FIELD_RANGES: CronFieldRange[] = [
+ { min: 0, max: 59, allowQuestion: false }, // minute
+ { min: 0, max: 23, allowQuestion: false }, // hour
+ { min: 1, max: 31, allowQuestion: true }, // day
+ { min: 1, max: 12, allowQuestion: false }, // month
+ { min: 0, max: 7, allowQuestion: true }, // dow (0=Sun,7=Sun)
+];
+
+const CRON_7FIELD_RANGES: CronFieldRange[] = [
+ { min: 0, max: 59, allowQuestion: false }, // second
+ { min: 0, max: 59, allowQuestion: false }, // minute
+ { min: 0, max: 23, allowQuestion: false }, // hour
+ { min: 1, max: 31, allowQuestion: true }, // day
+ { min: 1, max: 12, allowQuestion: false }, // month
+ { min: 1, max: 7, allowQuestion: true }, // dow
+ // year handled separately
+];
+
+const FIELD_NAMES_5 = ["minute(0-59)", "hour(0-23)", "day(1-31)", "month(1-12)", "dow(0-7)"];
+const FIELD_NAMES_7 = ["second(0-59)", "minute(0-59)", "hour(0-23)", "day(1-31)", "month(1-12)", "dow(1-7)", "year"];
+
+function isValidCronValue(value: string, range: CronFieldRange): boolean {
+ if (value === "*") return true;
+ if (range.allowQuestion && value === "?") return true;
+
+ const parts = value.split(",");
+ for (const part of parts) {
+ if (part.includes("/")) {
+ const [rangePart, stepStr] = part.split("/");
+ const step = parseInt(stepStr, 10);
+ if (isNaN(step) || step <= 0) return false;
+ if (rangePart === "*") continue;
+ if (!isValidCronRange(rangePart, range.min, range.max)) return false;
+ } else if (part.includes("-")) {
+ if (!isValidCronRange(part, range.min, range.max)) return false;
+ } else {
+ const num = parseInt(part, 10);
+ if (isNaN(num)) return false;
+ if (range.min === 0 && range.max === 7 && (num < 0 || num > 7)) return false;
+ if (range.min !== 0 || range.max !== 7) {
+ if (num < range.min || num > range.max) return false;
+ }
+ }
+ }
+ return true;
+}
+
+function isValidCronRange(range: string, min: number, max: number): boolean {
+ const [startStr, endStr] = range.split("-");
+ if (!startStr || !endStr) return false;
+ const start = parseInt(startStr, 10);
+ const end = parseInt(endStr, 10);
+ if (isNaN(start) || isNaN(end)) return false;
+ if (min === 0 && max === 7) return start >= 0 && end <= 7 && start <= end;
+ return start >= min && end <= max && start <= end;
+}
+
+function validateCronExpr(expr: string): string | null {
+ const trimmed = expr.trim();
+ if (!trimmed) return "cron_expr 不能为空";
+
+ const fields = trimmed.split(/\s+/);
+ const fieldCount = fields.length;
+
+ if (fieldCount !== 5 && fieldCount !== 7) {
+ return `cron_expr 需要 5 字段(周期)或 7 字段(单次),当前有 ${fieldCount} 个字段`;
+ }
+
+ const ranges = fieldCount === 5 ? CRON_5FIELD_RANGES : CRON_7FIELD_RANGES;
+ const names = fieldCount === 5 ? FIELD_NAMES_5 : FIELD_NAMES_7;
+
+ for (let i = 0; i < fields.length; i++) {
+ // Year field (7-field, index 6) has special handling
+ if (fieldCount === 7 && i === 6) {
+ if (fields[i] === "*") continue;
+ const yearNum = parseInt(fields[i], 10);
+ if (isNaN(yearNum) || yearNum < 1970 || yearNum > 2099) {
+ return `${names[i]} 字段无效: year 需为 1970-2099 或 *`;
+ }
+ continue;
+ }
+
+ if (!isValidCronValue(fields[i], ranges[i])) {
+ return `${names[i]} 字段无效: "${fields[i]}"`;
+ }
+ }
+
+ return null; // valid
+}
+
+// ── end cron validation ──
+
export function createCronCommand(): SlashCommand {
return {
name: "cron",
altNames: ["crontab"],
description: "管理定时任务(cron jobs)——到点让 Agent 帮你做事",
- usage: "/cron [list|add|update|delete|toggle|run|preview]",
+ usage: "/cron [list|show|add|update|delete|toggle|run|preview]",
example:
'/cron list\n' +
+ '/cron show <id>\n' +
'/cron add name=晨报 cron_expr="0 9 * * *" description="生成简短的中文健康打卡提醒" targets=tui\n' +
'/cron update <id> description="新的任务内容"\n' +
"/cron delete <id>\n" +
@@ -50,6 +151,15 @@ export function createCronCommand(): SlashCommand {
isSafeConcurrent: true,
action: async (ctx) => _handleList(ctx),
},
+ {
+ name: "show",
+ description: "查看定时任务详情",
+ usage: "/cron show <job_id>",
+ argGuide: "<job_id>",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => _handleShow(ctx, parseArgs(`show ${args}`)),
+ },
{
name: "add",
description: "创建定时任务",
@@ -120,6 +230,9 @@ export function createCronCommand(): SlashCommand {
const sub = parts[0];
switch (sub) {
+ case "show":
+ await _handleShow(ctx, parts);
+ break;
case "add":
await _handleAdd(ctx, raw);
break;
@@ -142,7 +255,7 @@ export function createCronCommand(): SlashCommand {
ctx.addItem(
addError(
ctx.sessionId,
- `Unknown sub-command: "${sub}". Use: list, add, update, delete, toggle, run, preview`,
+ `Unknown sub-command: "${sub}". Use: list, show, add, update, delete, toggle, run, preview`,
),
);
}
@@ -183,6 +296,49 @@ async function _handleList(ctx: CommandContext): Promise<void> {
}
}
+async function _handleShow(ctx: CommandContext, parts: string[]): Promise<void> {
+ const jobId = parts[1];
+ if (!jobId) {
+ ctx.addItem(addError(ctx.sessionId, "Usage: /cron show <job_id>"));
+ return;
+ }
+
+ try {
+ const payload = await ctx.request("cron.job.get", { id: jobId }) as { job: CronJobPayload } | null;
+ if (!payload || !payload.job) {
+ ctx.addItem(addError(ctx.sessionId, `Job not found: ${jobId}`));
+ return;
+ }
+
+ const job = payload.job;
+ const statusTag = job.expired ? "EXPIRED" : job.enabled ? "ON" : "OFF";
+ const isOneShot = job.delete_after_run === true;
+ const taskType = isOneShot ? "单次任务" : "周期任务";
+
+ ctx.addItem(
+ addInfo(ctx.sessionId, `Cron Job: ${job.name}`, "clock", {
+ view: "kv",
+ title: `Cron Job Detail [${taskType}]`,
+ items: [
+ { label: "id", value: job.id },
+ { label: "name", value: job.name },
+ { label: "status", value: statusTag },
+ { label: "cron_expr", value: job.cron_expr },
+ { label: "timezone", value: job.timezone },
+ { label: "description", value: job.description || "-" },
+ { label: "targets", value: job.targets },
+ { label: "mode", value: job.mode || "agent" },
+ { label: "wake_offset_seconds", value: String(job.wake_offset_seconds ?? 300) },
+ { label: "delete_after_run", value: String(isOneShot) },
+ ],
+ }),
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `Failed to get cron job: ${message}`));
+ }
+}
+
async function _handleAdd(ctx: CommandContext, raw: string): Promise<void> {
const addPart = raw.replace(/^add\s+/, "");
const kvPairs: Record<string, string> = {};
@@ -218,6 +374,14 @@ async function _handleAdd(ctx: CommandContext, raw: string): Promise<void> {
if (!kvPairs.timezone) kvPairs.timezone = "Asia/Shanghai";
if (!kvPairs.mode) kvPairs.mode = "agent";
+ // cron_expr syntax validation
+ const cronError = validateCronExpr(kvPairs.cron_expr);
+ if (cronError) {
+ ctx.addItem(addError(ctx.sessionId, `cron_expr 语法错误: ${cronError}`));
+ return;
+ }
+
+ // targets validation
if (
!TARGET_CHANNELS.includes(kvPairs.targets.toLowerCase()) &&
!kvPairs.targets.startsWith("feishu_enterprise:")
@@ -245,6 +409,15 @@ async function _handleAdd(ctx: CommandContext, raw: string): Promise<void> {
return;
}
+ // wake_offset_seconds validation
+ if (kvPairs.wake_offset_seconds) {
+ const wos = parseInt(kvPairs.wake_offset_seconds, 10);
+ if (isNaN(wos) || wos < 0) {
+ ctx.addItem(addError(ctx.sessionId, `Invalid wake_offset_seconds: "${kvPairs.wake_offset_seconds}". Must be a non-negative integer`));
+ return;
+ }
+ }
+
try {
const payload = await ctx.request("cron.job.create", {
name: kvPairs.name,
@@ -335,12 +508,51 @@ async function _handleUpdate(ctx: CommandContext, raw: string, parts: string[]):
return;
}
- // Convert numeric fields
- if ("wake_offset_seconds" in patch) {
- patch.wake_offset_seconds = parseInt(String(patch.wake_offset_seconds), 10);
+ // Validate each field in the patch
+ if ("name" in patch && !String(patch.name).trim()) {
+ ctx.addItem(addError(ctx.sessionId, "name 不能为空"));
+ return;
+ }
+ if ("cron_expr" in patch) {
+ const cronError = validateCronExpr(String(patch.cron_expr));
+ if (cronError) {
+ ctx.addItem(addError(ctx.sessionId, `cron_expr 语法错误: ${cronError}`));
+ return;
+ }
+ }
+ if ("description" in patch && !String(patch.description).trim()) {
+ ctx.addItem(addError(ctx.sessionId, "description 不能为空"));
+ return;
+ }
+ if ("targets" in patch) {
+ const t = String(patch.targets).trim().toLowerCase();
+ if (!TARGET_CHANNELS.includes(t) && !String(patch.targets).startsWith("feishu_enterprise:")) {
+ ctx.addItem(addError(ctx.sessionId, `Invalid target channel: "${patch.targets}". Valid: ${TARGET_CHANNELS.join(", ")}, feishu_enterprise:<app_id>`));
+ return;
+ }
+ }
+ if ("mode" in patch) {
+ const m = String(patch.mode).trim().toLowerCase();
+ if (!MODES.includes(m)) {
+ ctx.addItem(addError(ctx.sessionId, `Invalid mode: "${patch.mode}". Valid: ${MODES.join(", ")}`));
+ return;
+ }
}
if ("delete_after_run" in patch) {
- patch.delete_after_run = String(patch.delete_after_run).toLowerCase() === "true";
+ const raw = String(patch.delete_after_run).toLowerCase();
+ if (raw !== "true" && raw !== "false") {
+ ctx.addItem(addError(ctx.sessionId, `Invalid delete_after_run: "${patch.delete_after_run}". Valid: "true" or "false"`));
+ return;
+ }
+ patch.delete_after_run = raw === "true";
+ }
+ if ("wake_offset_seconds" in patch) {
+ const wos = parseInt(String(patch.wake_offset_seconds), 10);
+ if (isNaN(wos) || wos < 0) {
+ ctx.addItem(addError(ctx.sessionId, `Invalid wake_offset_seconds: "${patch.wake_offset_seconds}". Must be a non-negative integer`));
+ return;
+ }
+ patch.wake_offset_seconds = wos;
}
try {
@@ -372,6 +584,12 @@ async function _handleToggle(ctx: CommandContext, parts: string[]): Promise<void
return;
}
+ const validOnOff = ["on", "off", "true", "false"];
+ if (!validOnOff.includes(onOff.toLowerCase())) {
+ ctx.addItem(addError(ctx.sessionId, `Invalid toggle value: "${onOff}". Must be "on" or "off"`));
+ return;
+ }
+
const enabled = onOff.toLowerCase() === "on" || onOff.toLowerCase() === "true";
try {
diff --git a/jiuwenswarm/gateway/cron/models.py b/jiuwenswarm/gateway/cron/models.py
index 2e6f927cec..7e0e4dbb83 100644
--- a/jiuwenswarm/gateway/cron/models.py
+++ b/jiuwenswarm/gateway/cron/models.py
@@ -4,6 +4,8 @@ from dataclasses import dataclass, field
from enum import Enum
from typing import Any
+from jiuwenswarm.gateway.cron.cron_expr import validate_cron_expression
+
class CronTargetChannel(str, Enum):
"""推送频道枚举。"""
@@ -151,7 +153,9 @@ class CronJob:
if wake_offset_seconds < 0:
wake_offset_seconds = 0
- description = str(data.get("description") or "")
+ description = str(data.get("description") or "").strip()
+ if not description:
+ raise ValueError("description is required")
# targets 新格式是字符串;旧格式是 list[dict],此处做兼容。
targets_raw = data.get("targets", "")
@@ -180,6 +184,7 @@ class CronJob:
raise ValueError("cron_expr is required")
if not timezone:
raise ValueError("timezone is required")
+ validate_cron_expression(cron_expr, timezone=timezone)
if not targets_str:
raise ValueError("targets is required")