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

feat:新增/cron定时任务命令

openJiuwen-botf3201b07cb39
diff --git a/docs/en/SlashCommands.md b/docs/en/SlashCommands.md
index da11ca48d0..007173d127 100644
--- a/docs/en/SlashCommands.md
+++ b/docs/en/SlashCommands.md
@@ -50,6 +50,7 @@ Identified by Gateway and forwarded to AgentServer and other backend capabilitie
| `/branch` | Create a branch session from current conversation point (see below) |
| `/rewind` | Rewind conversation to before a specific turn (see below) |
| `/memory` | Memory management (see below) |
+| `/cron` | Scheduled task (cron job) management (see below) |
---
@@ -268,6 +269,45 @@ Manages directories AI can access for file read, edit, and execute operations.
- `/memory toggle memory_enabled` — Toggle the master memory switch
- `/memory open` — View memory directory paths
+### `/cron` (Scheduled Task Management)
+
+Manage cron jobs via RPC calls to the backend `CronController`, sharing the same backend logic and data store with the Web UI.
+
+- Alias: `/crontab`
+- Subcommands:
+
+| Command | Description |
+|---|---|
+| `/cron` or `/cron list` | List all cron jobs |
+| `/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 run <job_id>` | Run a job immediately |
+| `/cron preview <job_id>` | Preview upcoming execution times for a job |
+
+- `add` parameters:
+
+| Parameter | Required | Description |
+|---|---|---|
+| `name` | Yes | Job name |
+| `cron_expr` | Yes | Cron expression (7-field Quartz format: sec min hour day month dow year) |
+| `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>` |
+| `timezone` | No | IANA timezone, default `Asia/Shanghai` |
+| `mode` | No | Execution mode: `agent` (default) or `plan` |
+| `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`
+
+- `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
+- `preview` display: wake_at and push_at timestamps for each upcoming execution
+
### `/skills` (Skills Management)
Manage skills lifecycle: listing, installing, uninstalling, and marketplace source management.
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 b91d69947a..651a2a92c2 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"
@@ -50,6 +50,7 @@
| `/branch` | 从当前对话点创建分支会话(见下文) |
| `/rewind` | 回退对话到指定轮次之前(见下文) |
| `/memory` | 记忆管理(见下文) |
+| `/cron` | 定时任务管理(见下文) |
---
@@ -290,6 +291,45 @@
- `/memory toggle memory_enabled` — 切换记忆总开关
- `/memory open` — 查看记忆目录路径
+### `/cron`(定时任务管理)
+
+管理定时任务(Cron Job),通过 RPC 调用后端 `CronController`,与 Web 端共用同一套后端逻辑和数据存储。
+
+- 别名:`/crontab`
+- 子命令:
+
+| 命令 | 说明 |
+|---|---|
+| `/cron` 或 `/cron list` | 列出所有定时任务 |
+| `/cron add name=<名称> cron_expr=<表达式> description=<描述> [其他参数]` | 新增定时任务 |
+| `/cron update <job_id> key=value ...` | 更新指定任务的部分字段 |
+| `/cron delete <job_id>` | 删除指定任务 |
+| `/cron toggle <job_id> on|off` | 启用或禁用指定任务 |
+| `/cron run <job_id>` | 立即执行指定任务 |
+| `/cron preview <job_id>` | 预览任务接下来几次执行时间 |
+
+- `add` 参数:
+
+| 参数 | 必填 | 说明 |
+|---|---|---|
+| `name` | 是 | 任务名称 |
+| `cron_expr` | 是 | Cron 表达式(7 字段 Quartz 格式:秒 分 时 日 月 周 年) |
+| `description` | 是 | 任务描述,即 Agent 执行时收到的输入指令 |
+| `targets` | 否 | 推送渠道,默认 `web`;可选:`web`、`feishu`、`whatsapp`、`wecom`、`xiaoyi`、`wechat` 或 `feishu_enterprise:<app_id>` |
+| `timezone` | 否 | IANA 时区,默认 `Asia/Shanghai` |
+| `mode` | 否 | 执行模式:`agent`(默认)或 `plan` |
+| `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`
+
+- `update` 用法:只需传入要修改的字段,如 `/cron update <id> name=新名称 enabled=false`
+- `list` 显示内容:序号、完整 job ID、名称、cron 表达式、启用状态、描述摘要
+- `preview` 显示内容:每次执行计划的唤醒时间和推送时间
+
### `/skills`(技能管理)
管理技能的完整生命周期:列表查看、安装、卸载以及市场源管理。
diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/cron.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/cron.ts
new file mode 100644
index 0000000000..e8614c20bb
--- /dev/null
+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/cron.ts
@@ -0,0 +1,451 @@
+import { addError, addInfo, parseArgs } from "../helpers.js";
+import { CommandKind, type SlashCommand, type CommandContext } from "../types.js";
+
+interface CronJobPayload {
+ id: string;
+ name: string;
+ enabled: boolean;
+ expired: boolean;
+ cron_expr: string;
+ timezone: string;
+ wake_offset_seconds: number;
+ description: string;
+ targets: string;
+ mode: string;
+ delete_after_run: boolean;
+ created_at: number | null;
+ updated_at: number | null;
+}
+
+interface CronJobListPayload {
+ jobs: CronJobPayload[];
+}
+
+const TARGET_CHANNELS = ["web", "feishu", "whatsapp", "wecom", "xiaoyi", "wechat"];
+const MODES = ["agent", "plan"];
+
+export function createCronCommand(): SlashCommand {
+ return {
+ name: "cron",
+ altNames: ["crontab"],
+ description: "管理定时任务(cron jobs)——到点让 Agent 帮你做事",
+ 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 update <id> description="新的任务内容"\n' +
+ "/cron delete <id>\n" +
+ "/cron toggle <id> on|off\n" +
+ "/cron run <id>\n" +
+ "/cron preview <id>",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ subCommands: [
+ {
+ name: "list",
+ description: "列出所有定时任务",
+ usage: "/cron list",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: false,
+ isSafeConcurrent: true,
+ action: async (ctx) => _handleList(ctx),
+ },
+ {
+ name: "add",
+ description: "创建定时任务",
+ usage: "/cron add name=... cron_expr=\"...\" description=\"...\"",
+ argGuide: "name=任务名 cron_expr=\"时间表达式\" description=\"让Agent做什么\" targets=web",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => _handleAdd(ctx, `add ${args}`),
+ },
+ {
+ name: "update",
+ description: "更新定时任务",
+ usage: "/cron update <id> key=value ...",
+ argGuide: "<id> description=\"新内容\" cron_expr=\"新时间\" ...",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => {
+ const parts = parseArgs(`update ${args}`);
+ await _handleUpdate(ctx, `update ${args}`, parts);
+ },
+ },
+ {
+ name: "delete",
+ description: "删除定时任务",
+ usage: "/cron delete <id>",
+ argGuide: "<job_id>",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => _handleDelete(ctx, parseArgs(`delete ${args}`)),
+ },
+ {
+ name: "toggle",
+ description: "开关定时任务",
+ usage: "/cron toggle <id> on|off",
+ argGuide: "<job_id> on|off",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => _handleToggle(ctx, parseArgs(`toggle ${args}`)),
+ },
+ {
+ name: "run",
+ description: "立即执行定时任务",
+ usage: "/cron run <id>",
+ argGuide: "<job_id>",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => _handleRun(ctx, parseArgs(`run ${args}`)),
+ },
+ {
+ name: "preview",
+ description: "预览定时任务下次执行时间",
+ usage: "/cron preview <id>",
+ argGuide: "<job_id> [次数]",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => _handlePreview(ctx, parseArgs(`preview ${args}`)),
+ },
+ ],
+ action: async (ctx: CommandContext, args: string) => {
+ const raw = args.trim();
+ const parts = parseArgs(raw);
+
+ if (parts.length === 0 || parts[0] === "list") {
+ await _handleList(ctx);
+ return;
+ }
+
+ const sub = parts[0];
+
+ switch (sub) {
+ case "add":
+ await _handleAdd(ctx, raw);
+ break;
+ case "update":
+ await _handleUpdate(ctx, raw, parts);
+ break;
+ case "delete":
+ await _handleDelete(ctx, parts);
+ break;
+ case "toggle":
+ await _handleToggle(ctx, parts);
+ break;
+ case "run":
+ await _handleRun(ctx, parts);
+ break;
+ case "preview":
+ await _handlePreview(ctx, parts);
+ break;
+ default:
+ ctx.addItem(
+ addError(
+ ctx.sessionId,
+ `Unknown sub-command: "${sub}". Use: list, add, update, delete, toggle, run, preview`,
+ ),
+ );
+ }
+ },
+ };
+}
+
+async function _handleList(ctx: CommandContext): Promise<void> {
+ try {
+ const payload = await ctx.request("cron.job.list", {}) as CronJobListPayload;
+ const jobs = payload.jobs ?? [];
+
+ if (jobs.length === 0) {
+ ctx.addItem(addInfo(ctx.sessionId, "No cron jobs configured", "clock"));
+ return;
+ }
+
+ const items = jobs.map((j: CronJobPayload, i: number) => {
+ const statusIcon = j.enabled ? "ON" : "OFF";
+ const expiredTag = j.expired ? " [expired]" : "";
+ const descSnippet = j.description ? (j.description.length > 30 ? j.description.slice(0, 30) + "..." : j.description) : "-";
+ return {
+ label: String(i + 1),
+ value: `${j.id} | ${j.name} | ${j.cron_expr} | ${statusIcon}${expiredTag} | ${descSnippet}`,
+ };
+ });
+
+ ctx.addItem(
+ addInfo(ctx.sessionId, `Cron Jobs (${jobs.length} total)`, "clock", {
+ view: "list",
+ title: "Cron Jobs",
+ items,
+ }),
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `Failed to list cron jobs: ${message}`));
+ }
+}
+
+async function _handleAdd(ctx: CommandContext, raw: string): Promise<void> {
+ const addPart = raw.replace(/^add\s+/, "");
+ const kvPairs: Record<string, string> = {};
+
+ // Handle quoted values like description="..." and cron_expr="0 9 * * *"
+ const quotedRegex = /(\w+)="([^"]+)"/g;
+ let m: RegExpExecArray | null;
+ while ((m = quotedRegex.exec(addPart)) !== null) {
+ kvPairs[m[1]] = m[2];
+ }
+ // Handle unquoted key=value pairs (skip ones already captured by quoted regex)
+ const unquotedRegex = /(\w+)=(\S+)/g;
+ while ((m = unquotedRegex.exec(addPart)) !== null) {
+ if (!kvPairs[m[1]]) {
+ kvPairs[m[1]] = m[2];
+ }
+ }
+
+ const requiredFields = ["name", "cron_expr", "description"];
+ const missing = requiredFields.filter((f) => !kvPairs[f]);
+ if (missing.length > 0) {
+ ctx.addItem(
+ addError(
+ ctx.sessionId,
+ `缺少必填字段: ${missing.join(", ")}。必填: name(任务名)、cron_expr(时间)、description(让Agent做什么)。示例: /cron add name=晨报 cron_expr="0 0 9 * * *" description="生成健康打卡提醒" targets=web`,
+ ),
+ );
+ return;
+ }
+
+ if (!kvPairs.targets) kvPairs.targets = "web";
+ if (!kvPairs.timezone) kvPairs.timezone = "Asia/Shanghai";
+ if (!kvPairs.mode) kvPairs.mode = "agent";
+
+ if (
+ !TARGET_CHANNELS.includes(kvPairs.targets.toLowerCase()) &&
+ !kvPairs.targets.startsWith("feishu_enterprise:")
+ ) {
+ ctx.addItem(
+ addError(
+ ctx.sessionId,
+ `Invalid target channel: "${kvPairs.targets}". Valid: ${TARGET_CHANNELS.join(", ")}, feishu_enterprise:<app_id>`,
+ ),
+ );
+ return;
+ }
+
+ if (!MODES.includes(kvPairs.mode.toLowerCase())) {
+ ctx.addItem(
+ addError(ctx.sessionId, `Invalid mode: "${kvPairs.mode}". Valid: ${MODES.join(", ")}`),
+ );
+ return;
+ }
+
+ try {
+ const payload = await ctx.request("cron.job.create", {
+ name: kvPairs.name,
+ cron_expr: kvPairs.cron_expr,
+ description: kvPairs.description,
+ targets: kvPairs.targets,
+ timezone: kvPairs.timezone,
+ mode: kvPairs.mode,
+ wake_offset_seconds: parseInt(kvPairs.wake_offset_seconds || "300", 10),
+ delete_after_run: kvPairs.delete_after_run === "true",
+ }) as { job: CronJobPayload };
+
+ const job = payload.job;
+ ctx.addItem(
+ addInfo(ctx.sessionId, `Created cron job: ${job.name}`, "clock", {
+ view: "kv",
+ title: "Cron Job Created",
+ items: [
+ { label: "id", value: job.id },
+ { label: "name", value: job.name },
+ { label: "cron_expr", value: job.cron_expr },
+ { label: "description", value: job.description },
+ { label: "timezone", value: job.timezone },
+ { label: "targets", value: job.targets },
+ { label: "mode", value: job.mode },
+ { label: "enabled", value: String(job.enabled) },
+ ],
+ }),
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `Failed to create cron job: ${message}`));
+ }
+}
+
+async function _handleDelete(ctx: CommandContext, parts: string[]): Promise<void> {
+ const jobId = parts[1];
+ if (!jobId) {
+ ctx.addItem(addError(ctx.sessionId, "Usage: /cron delete <job_id>"));
+ return;
+ }
+
+ try {
+ const payload = await ctx.request("cron.job.delete", { id: jobId }) as { deleted: boolean };
+ if (payload.deleted) {
+ ctx.addItem(addInfo(ctx.sessionId, `Deleted cron job: ${jobId}`, "clock"));
+ } else {
+ ctx.addItem(addError(ctx.sessionId, `Job not found: ${jobId}`));
+ }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `Failed to delete cron job: ${message}`));
+ }
+}
+
+async function _handleUpdate(ctx: CommandContext, raw: string, parts: string[]): Promise<void> {
+ const jobId = parts[1];
+ if (!jobId) {
+ ctx.addItem(addError(ctx.sessionId, "Usage: /cron update <job_id> key=value ... (只改你想改的字段)"));
+ return;
+ }
+
+ const updatePart = raw.replace(/^update\s+\S+\s+/, "");
+ if (!updatePart) {
+ ctx.addItem(addError(ctx.sessionId, "Usage: /cron update <job_id> key=value ... 例如: /cron update <id> description=\"新内容\" cron_expr=\"0 0 8 * * ? *\""));
+ return;
+ }
+
+ const patch: Record<string, unknown> = {};
+
+ // Handle quoted values like description="..."
+ const quotedRegex = /(\w+)="([^"]+)"/g;
+ let m: RegExpExecArray | null;
+ while ((m = quotedRegex.exec(updatePart)) !== null) {
+ patch[m[1]] = m[2];
+ }
+ // Handle unquoted key=value pairs
+ const unquotedRegex = /(\w+)=(\S+)/g;
+ while ((m = unquotedRegex.exec(updatePart)) !== null) {
+ if (!patch[m[1]]) {
+ patch[m[1]] = m[2];
+ }
+ }
+
+ if (Object.keys(patch).length === 0) {
+ ctx.addItem(addError(ctx.sessionId, "没有指定要更新的字段。用法: /cron update <id> key=value ..."));
+ return;
+ }
+
+ // Convert numeric fields
+ if ("wake_offset_seconds" in patch) {
+ patch.wake_offset_seconds = parseInt(String(patch.wake_offset_seconds), 10);
+ }
+ if ("delete_after_run" in patch) {
+ patch.delete_after_run = String(patch.delete_after_run).toLowerCase() === "true";
+ }
+
+ try {
+ const payload = await ctx.request("cron.job.update", { id: jobId, patch }) as { job: CronJobPayload };
+ const job = payload.job;
+ const updatedFields = Object.keys(patch);
+ ctx.addItem(
+ addInfo(ctx.sessionId, `Updated cron job: ${job.name} (修改了: ${updatedFields.join(", ")})`, "clock", {
+ view: "kv",
+ title: "Cron Job Updated",
+ items: updatedFields.map((k) => ({
+ label: k,
+ value: String(job[k as keyof CronJobPayload] ?? patch[k]),
+ })),
+ }),
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `Failed to update cron job: ${message}`));
+ }
+}
+
+async function _handleToggle(ctx: CommandContext, parts: string[]): Promise<void> {
+ const jobId = parts[1];
+ const onOff = parts[2];
+
+ if (!jobId || !onOff) {
+ ctx.addItem(addError(ctx.sessionId, "Usage: /cron toggle <job_id> on|off"));
+ return;
+ }
+
+ const enabled = onOff.toLowerCase() === "on" || onOff.toLowerCase() === "true";
+
+ try {
+ const payload = await ctx.request("cron.job.toggle", {
+ id: jobId,
+ enabled,
+ }) as { job: CronJobPayload };
+ const job = payload.job;
+ ctx.addItem(
+ addInfo(ctx.sessionId, `Toggled cron job "${job.name}" to ${job.enabled ? "ON" : "OFF"}`, "clock", {
+ view: "kv",
+ title: "Cron Job Toggle",
+ items: [
+ { label: "id", value: job.id },
+ { label: "name", value: job.name },
+ { label: "enabled", value: String(job.enabled) },
+ ],
+ }),
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `Failed to toggle cron job: ${message}`));
+ }
+}
+
+async function _handleRun(ctx: CommandContext, parts: string[]): Promise<void> {
+ const jobId = parts[1];
+ if (!jobId) {
+ ctx.addItem(addError(ctx.sessionId, "Usage: /cron run <job_id>"));
+ return;
+ }
+
+ try {
+ const payload = await ctx.request("cron.job.run_now", { id: jobId }) as { run_id: string };
+ ctx.addItem(
+ addInfo(ctx.sessionId, `Triggered cron job: ${jobId} (run_id: ${payload.run_id})`, "clock"),
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `Failed to run cron job: ${message}`));
+ }
+}
+
+async function _handlePreview(ctx: CommandContext, parts: string[]): Promise<void> {
+ const jobId = parts[1];
+ if (!jobId) {
+ ctx.addItem(addError(ctx.sessionId, "Usage: /cron preview <job_id>"));
+ return;
+ }
+
+ const count = parseInt(parts[2] || "5", 10);
+
+ try {
+ const payload = await ctx.request("cron.job.preview", {
+ id: jobId,
+ count,
+ }) as { next: Array<{ wake_at: string; push_at: string } | string> };
+ const nextRuns = payload.next ?? [];
+
+ if (nextRuns.length === 0) {
+ ctx.addItem(addInfo(ctx.sessionId, `No upcoming runs for job ${jobId} (may be expired or disabled)`, "clock"));
+ return;
+ }
+
+ const items = nextRuns.map((item: { wake_at: string; push_at: string } | string, i: number) => {
+ if (typeof item === "string") {
+ return { label: String(i + 1), value: item };
+ }
+ return {
+ label: String(i + 1),
+ value: `唤醒: ${item.wake_at} 推送: ${item.push_at}`,
+ };
+ });
+
+ ctx.addItem(
+ addInfo(ctx.sessionId, `Next ${nextRuns.length} runs for job ${jobId}`, "clock", {
+ view: "list",
+ title: "Cron Job Preview",
+ items,
+ }),
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `Failed to preview cron job: ${message}`));
+ }
+}
\ No newline at end of file
diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts
index 566aabe2ae..c6e06129e8 100644
--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts
+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts
@@ -6,6 +6,7 @@ import { createColorCommand } from "./builtins/color.js";
import { createCompactCommand } from "./builtins/compact.js";
import { createConfigCommand } from "./builtins/config.js";
import { createContextCommand } from "./builtins/context.js";
+import { createCronCommand } from "./builtins/cron.js";
import { createCopyCommand } from "./builtins/copy.js";
import { createRecapCommand } from "./builtins/recap.js";
import { createDiffCommand } from "./builtins/diff.js";
@@ -48,6 +49,7 @@ export function createBuiltinCommands(): SlashCommand[] {
createCompactCommand(),
createConfigCommand(),
createContextCommand(),
+ createCronCommand(),
createRecapCommand(),
createCopyCommand(),
createDiffCommand(),
diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts
index fa71181c6c..614c091c46 100644
--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts
+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts
@@ -98,6 +98,13 @@ export interface SlashCommand {
description: string;
usage?: string;
example?: string;
+ /**
+ * Inline hint shown after the cursor when the user has typed this command
+ * (or sub-command) with no further arguments. For commands that accept
+ * key=value fields, this should list the available keys with brief labels,
+ * e.g. "name=任务名 cron_expr=\"时间\" description=\"让Agent做什么\""
+ */
+ argGuide?: string;
hidden?: boolean;
isSafeConcurrent?: boolean;
kind: CommandKind;
diff --git a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts
index fb3b7e79c9..841306afa2 100644
--- a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts
+++ b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts
@@ -2765,17 +2765,88 @@ export class AppScreen implements Component, Focusable {
}
const parsed = parseSlashCommand(text, this.commands.getAll());
- if (!parsed.command || parsed.args.trim()) {
+ if (!parsed.command) {
return null;
}
- const usage = parsed.command.usage?.trim() ?? "";
- if (!usage.startsWith("/")) {
+ const args = parsed.args.trim();
+
+ // No args → show top-level usage hint (existing behavior)
+ if (!args) {
+ const usage = parsed.command.usage?.trim() ?? "";
+ if (!usage.startsWith("/")) {
+ return null;
+ }
+ const suffix = usage.replace(/^\/[^\s]+/, "").trim();
+ return suffix || null;
+ }
+
+ // Args present → check if they match a sub-command name
+ const subCommands = parsed.command.subCommands;
+ if (!subCommands?.length) {
+ // No sub-commands defined; if the command has an argGuide, show it
+ // only when the user hasn't started filling in key=value args yet.
+ const argGuide = parsed.command.argGuide;
+ if (argGuide && !args.includes("=")) {
+ return argGuide;
+ }
+ return null;
+ }
+
+ const argTokens = args.split(/\s+/);
+ const firstArg = argTokens[0]?.toLowerCase();
+
+ // Find matching sub-command
+ const matchedSub = subCommands.find(
+ (sub) => sub.name.toLowerCase() === firstArg
+ || sub.altNames?.some((alt) => alt.toLowerCase() === firstArg),
+ );
+
+ if (!matchedSub) {
+ // Partial match or no match
+ const partialMatch = firstArg
+ ? subCommands.filter((sub) => sub.name.toLowerCase().startsWith(firstArg))
+ : subCommands;
+ if (partialMatch.length === 1) {
+ // Unique partial match — show its argGuide directly
+ const unique = partialMatch[0];
+ if (unique.argGuide) {
+ return unique.argGuide;
+ }
+ const subUsage = unique.usage?.trim() ?? "";
+ if (subUsage.startsWith("/")) {
+ return subUsage.replace(/^\/[^\s]+/, "").trim() || null;
+ }
+ return unique.name;
+ }
+ if (partialMatch.length > 1 && partialMatch.length <= 6) {
+ return partialMatch.map((sub) => sub.name).join(" | ");
+ }
return null;
}
- const suffix = usage.replace(/^\/[^\s]+/, "").trim();
- return suffix || null;
+ // Sub-command matched, check remaining args after the sub-command name
+ const remainingArgs = argTokens.slice(1).join(" ").trim();
+
+ if (!remainingArgs) {
+ // User typed just "/cron add" — show argGuide or usage hint
+ if (matchedSub.argGuide) {
+ return matchedSub.argGuide;
+ }
+ const subUsage = matchedSub.usage?.trim() ?? "";
+ if (subUsage.startsWith("/")) {
+ const suffix = subUsage.replace(/^\/[^\s]+/, "").trim();
+ return suffix || null;
+ }
+ return matchedSub.description || null;
+ }
+
+ // User is typing key=value args after sub-command
+ if (matchedSub.argGuide && !remainingArgs.includes("=")) {
+ return matchedSub.argGuide;
+ }
+
+ return null;
}
/**
diff --git a/jiuwenclaw/gateway/app_gateway.py b/jiuwenclaw/gateway/app_gateway.py
index 7e382c4edf..d300c95942 100644
--- a/jiuwenclaw/gateway/app_gateway.py
+++ b/jiuwenclaw/gateway/app_gateway.py
@@ -997,6 +997,7 @@ async def _run(
on_config_saved=_on_config_saved,
path="/tui",
channel_id="tui",
+ cron_controller=cron_controller,
)
),
]
diff --git a/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py b/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py
index 20782ad706..b8efc62771 100644
--- a/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py
+++ b/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py
@@ -298,6 +298,7 @@ class CliHandlersBindParams:
message_handler: Any = None
on_config_saved: Any = None
path: str = "/tui"
+ cron_controller: Any = None
@dataclass
@@ -307,6 +308,7 @@ class CliRouteBindParams:
on_config_saved: Any = None
path: str = "/tui"
channel_id: str = "tui"
+ cron_controller: Any = None
_CLI_CONFIG_SET_ENV_MAP = {
@@ -549,6 +551,7 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
agent_client = bind.agent_client
on_config_saved = bind.on_config_saved
path = bind.path
+ cron_controller_ref = bind.cron_controller
async def _config_get(ws, req_id, params, session_id):
payload = {
@@ -1689,6 +1692,187 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
channel.register_local_handler(path, "memory.toggle", _memory_toggle)
channel.register_local_handler(path, "memory.open", _memory_open)
+ # ── Cron RPC handlers ────────────────────────────────────────────
+
+ def _get_cron():
+ """Resolve cron_controller from ref dict or direct instance."""
+ if isinstance(cron_controller_ref, dict):
+ return cron_controller_ref.get("value")
+ return cron_controller_ref
+
+ async def _cron_job_list(ws, req_id, params, session_id):
+ cc = _get_cron()
+ if cc is None:
+ await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
+ return
+ try:
+ jobs = await cc.list_jobs()
+ await channel.send_response(ws, req_id, ok=True, payload={"jobs": jobs})
+ except Exception as exc:
+ logger.warning("[cron.job.list] %s", exc)
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")
+
+ async def _cron_job_get(ws, req_id, params, session_id):
+ cc = _get_cron()
+ if cc is None:
+ await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ job_id = str(params.get("id") or "").strip()
+ if not job_id:
+ await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
+ return
+ try:
+ job = await cc.get_job(job_id)
+ if job is None:
+ await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
+ return
+ await channel.send_response(ws, req_id, ok=True, payload={"job": job})
+ except Exception as exc:
+ logger.warning("[cron.job.get] %s", exc)
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")
+
+ async def _cron_job_create(ws, req_id, params, session_id):
+ cc = _get_cron()
+ if cc is None:
+ await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ try:
+ job = await cc.create_job(params)
+ await channel.send_response(ws, req_id, ok=True, payload={"job": job})
+ except Exception as exc:
+ logger.warning("[cron.job.create] %s", exc)
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="BAD_REQUEST")
+
+ async def _cron_job_update(ws, req_id, params, session_id):
+ cc = _get_cron()
+ if cc is None:
+ await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ job_id = str(params.get("id") or "").strip()
+ patch = params.get("patch") or {}
+ if not job_id:
+ await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
+ return
+ if not isinstance(patch, dict):
+ await channel.send_response(ws, req_id, ok=False, error="patch must be object", code="BAD_REQUEST")
+ return
+ try:
+ job = await cc.update_job(job_id, patch)
+ await channel.send_response(ws, req_id, ok=True, payload={"job": job})
+ except KeyError:
+ await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
+ except Exception as exc:
+ logger.warning("[cron.job.update] %s", exc)
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="BAD_REQUEST")
+
+ async def _cron_job_delete(ws, req_id, params, session_id):
+ cc = _get_cron()
+ if cc is None:
+ await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ job_id = str(params.get("id") or "").strip()
+ if not job_id:
+ await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
+ return
+ try:
+ deleted = await cc.delete_job(job_id)
+ if not deleted:
+ await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
+ return
+ await channel.send_response(ws, req_id, ok=True, payload={"deleted": True})
+ except Exception as exc:
+ logger.warning("[cron.job.delete] %s", exc)
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")
+
+ async def _cron_job_toggle(ws, req_id, params, session_id):
+ cc = _get_cron()
+ if cc is None:
+ await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ job_id = str(params.get("id") or "").strip()
+ enabled = params.get("enabled", None)
+ if not job_id:
+ await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
+ return
+ if enabled is None:
+ await channel.send_response(ws, req_id, ok=False, error="enabled is required", code="BAD_REQUEST")
+ return
+ try:
+ job = await cc.toggle_job(job_id, bool(enabled))
+ await channel.send_response(ws, req_id, ok=True, payload={"job": job})
+ except KeyError:
+ await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
+ except Exception as exc:
+ logger.warning("[cron.job.toggle] %s", exc)
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")
+
+ async def _cron_job_preview(ws, req_id, params, session_id):
+ cc = _get_cron()
+ if cc is None:
+ await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ job_id = str(params.get("id") or "").strip()
+ count = params.get("count", 5)
+ if not job_id:
+ await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
+ return
+ try:
+ next_runs = await cc.preview_job(job_id, int(count) if count is not None else 5)
+ await channel.send_response(ws, req_id, ok=True, payload={"next": next_runs})
+ except KeyError:
+ await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
+ except Exception as exc:
+ logger.warning("[cron.job.preview] %s", exc)
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="BAD_REQUEST")
+
+ async def _cron_job_run_now(ws, req_id, params, session_id):
+ cc = _get_cron()
+ if cc is None:
+ await channel.send_response(ws, req_id, ok=False, error="cron not available", code="INTERNAL_ERROR")
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ job_id = str(params.get("id") or "").strip()
+ if not job_id:
+ await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")
+ return
+ try:
+ run_id = await cc.run_now(job_id)
+ await channel.send_response(ws, req_id, ok=True, payload={"run_id": run_id})
+ except KeyError:
+ await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
+ except Exception as exc:
+ logger.warning("[cron.job.run_now] %s", exc)
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")
+
+ channel.register_local_handler(path, "cron.job.list", _cron_job_list)
+ channel.register_local_handler(path, "cron.job.get", _cron_job_get)
+ channel.register_local_handler(path, "cron.job.create", _cron_job_create)
+ channel.register_local_handler(path, "cron.job.update", _cron_job_update)
+ channel.register_local_handler(path, "cron.job.delete", _cron_job_delete)
+ channel.register_local_handler(path, "cron.job.toggle", _cron_job_toggle)
+ channel.register_local_handler(path, "cron.job.preview", _cron_job_preview)
+ channel.register_local_handler(path, "cron.job.run_now", _cron_job_run_now)
+
def build_cli_route_binding(bind: CliRouteBindParams) -> GatewayRouteBinding:
def _install(channel: Any) -> None:
@@ -1699,6 +1883,7 @@ def build_cli_route_binding(bind: CliRouteBindParams) -> GatewayRouteBinding:
message_handler=bind.message_handler,
on_config_saved=bind.on_config_saved,
path=bind.path,
+ cron_controller=bind.cron_controller,
)
)