scheduler: AI 侧与管理面——schedule_task 工具(sessionId 取自 ctx,校验在 createTask)+ 会话详情 schedule 字段 + DELETE /:id/schedule(只落 scheduler_note 通知,不触发 AI)

This commit is contained in:
2026-09-19 22:24:40 +08:00
parent 4403256fa9
commit f1687ab7ce
3 changed files with 61 additions and 0 deletions
+24
View File
@@ -201,10 +201,16 @@ router.get('/:id', wrap((req, res) => {
}
const taskDir = engine.taskDirOf(session.id);
// 定时任务状态(scheduler.js / schedule_task 工具;每会话至多一行,无则 null)。
// 列表接口故意不带此字段,避免 N+1;前端进会话详情时才拉。
const schedule = db.prepare(
'SELECT cron_expr, next_run_at, last_run_at, last_status, last_note FROM scheduled_tasks WHERE session_id = ?'
).get(session.id) || null;
res.json({
session,
messages,
files: listTaskFiles(taskDir),
schedule,
queue_pos: session.status === 'queued' ? engine.queuePosition(session.id) : null,
running: !!(engine.getRun(session.id) || {}).looping,
has_more: hasMore, // 分页模式下:是否还有更早的历史
@@ -229,5 +235,23 @@ router.delete('/:id', wrap((req, res) => {
res.json(engine.deleteSession(req.params.id, delDir));
}));
// 手动删除定时任务(用户端唯一入口;创建只经 AI 工具,改 = 删后让 AI 重建)。
// 通知消息只 saveMessage 落库,不走 postUserMessage:不触发 AI 运行,
// 下一次自然对话时 AI 自会看到(type='scheduler_note' 对 buildMessages 是未知型,按普通 user 消息发)。
// 删会话无需此处:scheduled_tasks 随 sessions 行 ON DELETE CASCADE 自动清理。
router.delete('/:id/schedule', wrap((req, res) => {
const db = engine.getDb();
const t = db.prepare('SELECT cron_expr FROM scheduled_tasks WHERE session_id = ?').get(req.params.id);
if (!t) throw Object.assign(new Error('本会话没有定时任务'), { status_code: 404 });
db.prepare('DELETE FROM scheduled_tasks WHERE session_id = ?').run(req.params.id);
engine.saveMessage(req.params.id, {
role: 'user',
content: '[系统] 定时任务已删除(原定 ' + t.cron_expr + ')',
type: 'scheduler_note',
});
log.info('scheduler', req.params.id + ' 删除定时任务 ' + t.cron_expr);
res.json({ ok: true });
}));
module.exports = router;
module.exports.listTaskFiles = listTaskFiles;
+21
View File
@@ -247,6 +247,27 @@
}
}
},
{
"type": "function",
"function": {
"name": "schedule_task",
"description": "Create a recurring scheduled task for the CURRENT session. At each trigger, the given prompt is sent to this session as a new user message. Only one task per session is allowed; if one already exists the call fails and the user must delete it first in the session view. Call this ONLY when the user explicitly asks for something to run periodically or at a specific time.",
"parameters": {
"type": "object",
"required": ["cron_expr", "prompt"],
"properties": {
"cron_expr": {
"type": "string",
"description": "Standard 5-field cron expression, e.g. '0 9 * * *' for 09:00 every day. Minimum interval is 1 hour."
},
"prompt": {
"type": "string",
"description": "The message to send to this session at each trigger. Write it as a self-contained instruction, because previous conversation history is archived before each run."
}
}
}
}
},
{
"type": "function",
"function": {
+16
View File
@@ -9,6 +9,7 @@ const mcp = require('../mcp');
const skills = require('./skills');
const rexec = require('../remote-exec');
const publicFiles = require('../public-files');
const scheduler = require('../scheduler'); // 只依赖 log/cron-parser,不成环(engine→executor→scheduler 单向)
function makeMatcher(pattern, opts) {
const mm = new Minimatch(pattern, opts || {});
@@ -718,6 +719,20 @@ async function toolMintPublicLink(ctx, args) {
return pl.base_url + '/p/' + id;
}
// schedule_task:为当前会话创建定时任务。sessionId 取自 ctx(AI 无法指定别的会话);
// 参数与会话唯一性校验均在 scheduler.createTask,失败抛中文 Error 回给 AI 自行纠正。
// 生命周期:只能由 AI 创建,用户端只读 + 删除(改 = 删后让 AI 重建),故无修改/删除入口。
function toolScheduleTask(ctx, args) {
const cronExpr = String(args.cron_expr || '').trim();
const prompt = String(args.prompt || '').trim();
if (!cronExpr) throw new Error('cron_expr 不能为空');
if (!prompt) throw new Error('prompt 不能为空');
const t = scheduler.createTask(ctx.db, ctx.sessionId, cronExpr, prompt);
return '定时任务已创建:' + t.cron_expr + ',下次执行 ' + t.next_text + '(Asia/Shanghai)。' +
'注意:每次触发前本会话的历史消息会被存档(AI 只看到任务 prompt),因此 prompt 需自包含;' +
'如需修改或删除,请让用户在会话页操作。';
}
const HANDLERS = {
read_file: toolReadFile,
write_file: toolWriteFile,
@@ -732,6 +747,7 @@ const HANDLERS = {
grep: toolGrep,
terminal: toolTerminal,
fetch: toolFetch,
schedule_task: toolScheduleTask,
list_skills: async (ctx, args) => JSON.stringify(await skills.listSkills(ctx), null, 2),
get_skill_info: (ctx, args) => skills.getSkillInfo(ctx, args.skill_name),
run_skill: (ctx, args) => skills.runSkill(ctx, args.skill_name, args.input_args),