schedule_task:改op分派get/create/update/delete,生命周期对AI开放;update对齐PATCH(仅改cron才重算next);撞车/扑空报错回显op并指路update/create,废"会话页删除"死路;prompt上限20000入create/update;delete不落scheduler_note;schema仅required op,条件必填代码校验
This commit is contained in:
+43
-3
@@ -15,6 +15,7 @@ const log = require('./log');
|
||||
const TZ = 'Asia/Shanghai'; // 与容器 TZ(docker-compose)一致;显式传入,不依赖进程隐式时区
|
||||
const TICK_MS = 30000; // 轮询周期:相对 1h 最小间隔足够密,无调优需求,不进 config.yml
|
||||
const MIN_INTERVAL_MS = 3600000; // cron 最小间隔 1 小时:防 AI 排出分钟级任务反复烧模型池
|
||||
const PROMPT_MAX_LEN = 20000; // prompt 长度上限,与 routes/sessions.js PATCH 口径一致
|
||||
|
||||
let eng = null; // engine 引用(start 注入)
|
||||
let timer = null;
|
||||
@@ -50,9 +51,10 @@ function validateCron(cronExpr) {
|
||||
// sessionId 由调用方从工具 ctx 取(AI 无法指定别的会话)。校验顺序:
|
||||
// validateCron → 本会话尚无任务 → INSERT(主键冲突兜底)。
|
||||
function createTask(db, sessionId, cronExpr, prompt) {
|
||||
if (prompt.length > PROMPT_MAX_LEN) throw new Error('prompt 过长(上限 ' + PROMPT_MAX_LEN + ' 字符)');
|
||||
const first = validateCron(cronExpr);
|
||||
const exist = db.prepare('SELECT cron_expr FROM scheduled_tasks WHERE session_id = ?').get(sessionId);
|
||||
if (exist) throw new Error('本会话已有定时任务(' + exist.cron_expr + '),请先在会话页删除');
|
||||
if (exist) throw new Error('本会话已有定时任务(' + exist.cron_expr + ')。改频次或提示词用 op=update;确要换新任务先 op=delete 再 op=create');
|
||||
try {
|
||||
db.prepare(
|
||||
'INSERT INTO scheduled_tasks (session_id, cron_expr, prompt, next_run_at, created_at) VALUES (?,?,?,?,?)'
|
||||
@@ -60,12 +62,50 @@ function createTask(db, sessionId, cronExpr, prompt) {
|
||||
} catch (_) {
|
||||
// 单进程同步 API 下正常到不了这里(上一步已查重),仅作主键约束重复报错的兜底
|
||||
const ex = db.prepare('SELECT cron_expr FROM scheduled_tasks WHERE session_id = ?').get(sessionId);
|
||||
throw new Error('本会话已有定时任务(' + (ex ? ex.cron_expr : cronExpr) + '),请先在会话页删除');
|
||||
throw new Error('本会话已有定时任务(' + (ex ? ex.cron_expr : cronExpr) + ')。改频次或提示词用 op=update;确要换新任务先 op=delete 再 op=create');
|
||||
}
|
||||
log.info('scheduler', sessionId + ' 创建定时任务 ' + cronExpr);
|
||||
return { cron_expr: cronExpr, next_run_at: first, next_text: fmtTime(first) };
|
||||
}
|
||||
|
||||
// ---------- 工具侧 get/update/delete(tools/executor.js 调) ----------
|
||||
// 表主键 session_id → 每会话至多一条,资源即「本会话的任务」,无 id 参数。
|
||||
// 语义与 routes/sessions.js 的 PATCH/DELETE 对齐,但不落 scheduler_note:
|
||||
// AI 路径的返回文本本身已进会话记录,不再重复留痕。update 允许只改其一,
|
||||
// 仅当改了 cron 才重算 next_run_at。不校验 running 状态(update 天然安全,
|
||||
// delete 也不打断正在跑的回合)。
|
||||
|
||||
function getTask(db, sessionId) {
|
||||
return db.prepare(
|
||||
'SELECT cron_expr, prompt, next_run_at, last_run_at, last_status, last_note FROM scheduled_tasks WHERE session_id = ?'
|
||||
).get(sessionId) || null;
|
||||
}
|
||||
|
||||
function updateTask(db, sessionId, patch) {
|
||||
const row = db.prepare('SELECT cron_expr, next_run_at FROM scheduled_tasks WHERE session_id = ?').get(sessionId);
|
||||
if (!row) throw new Error('本会话没有定时任务,先用 op=create 创建');
|
||||
let cron = row.cron_expr;
|
||||
let next = row.next_run_at;
|
||||
if (patch.cronExpr && patch.cronExpr !== row.cron_expr) {
|
||||
next = validateCron(patch.cronExpr);
|
||||
cron = patch.cronExpr;
|
||||
}
|
||||
const prompt = patch.prompt != null ? String(patch.prompt) : null;
|
||||
if (prompt !== null && prompt.length > PROMPT_MAX_LEN) throw new Error('prompt 过长(上限 ' + PROMPT_MAX_LEN + ' 字符)');
|
||||
db.prepare('UPDATE scheduled_tasks SET prompt = COALESCE(?, prompt), cron_expr = ?, next_run_at = ? WHERE session_id = ?')
|
||||
.run(prompt, cron, next, sessionId);
|
||||
log.info('scheduler', sessionId + ' 定时任务改为 ' + cron + '(原 ' + row.cron_expr + ')');
|
||||
return { cron_expr: cron, next_run_at: next, next_text: fmtTime(next) };
|
||||
}
|
||||
|
||||
function deleteTask(db, sessionId) {
|
||||
const row = db.prepare('SELECT cron_expr FROM scheduled_tasks WHERE session_id = ?').get(sessionId);
|
||||
if (!row) throw new Error('本会话没有定时任务,无需 op=delete');
|
||||
db.prepare('DELETE FROM scheduled_tasks WHERE session_id = ?').run(sessionId);
|
||||
log.info('scheduler', sessionId + ' 删除定时任务 ' + row.cron_expr);
|
||||
return row.cron_expr;
|
||||
}
|
||||
|
||||
// ---------- 投递 ----------
|
||||
// 触发前把会话全部消息标为 archived:buildMessages 遇 type='archived' 直接跳过(llm.js),
|
||||
// UI 照常展示全量(历次执行记录用户仍可见),AI 侧等价全新会话。
|
||||
@@ -150,4 +190,4 @@ function start(engine) {
|
||||
if (timer.unref) timer.unref(); // 不阻止进程退出
|
||||
}
|
||||
|
||||
module.exports = { start, createTask, computeNext, validateCron };
|
||||
module.exports = { start, createTask, getTask, updateTask, deleteTask, computeNext, validateCron, fmtTime };
|
||||
|
||||
@@ -103,18 +103,23 @@
|
||||
"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. Schedule times are interpreted in Asia/Shanghai (UTC+8). Call this ONLY when the user explicitly asks for something to run periodically or at a specific time.",
|
||||
"description": "Manage the recurring scheduled task bound to the CURRENT session. At most one task per session; it is deleted together with the session. At each trigger, the prompt is sent to this session as a new user message. Schedule times are interpreted in Asia/Shanghai (UTC+8). Call this ONLY when the user explicitly asks for something to run periodically or at a specific time.\n\nop=get No arguments.\nop=create Requires cron_expr and prompt.\nop=update Requires at least one of cron_expr, prompt; only the given fields change.\nop=delete No arguments.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"required": ["cron_expr", "prompt"],
|
||||
"required": ["op"],
|
||||
"properties": {
|
||||
"op": {
|
||||
"type": "string",
|
||||
"enum": ["get", "create", "update", "delete"],
|
||||
"description": "Operation to perform on the current session's scheduled task."
|
||||
},
|
||||
"cron_expr": {
|
||||
"type": "string",
|
||||
"description": "Standard 5-field cron expression in Asia/Shanghai (UTC+8), e.g. '0 9 * * *' for 09:00 Beijing time every day. The interval between two consecutive runs must be at least 1 hour."
|
||||
"description": "Standard 5-field cron expression in Asia/Shanghai (UTC+8), e.g. '0 9 * * *' for 09:00 Beijing time every day. The interval between two consecutive runs must be at least 1 hour. Required with op=create; optional with op=update (next run time is recomputed)."
|
||||
},
|
||||
"prompt": {
|
||||
"type": "string",
|
||||
"description": "The message to send to this session at each trigger. Write it as a self-contained instruction: previous conversation history is archived before each run, so this prompt is the only input the model will see. The output stays in this session for the user to view; if it must reach the user proactively, state how in the prompt (e.g. via a skill or webhook)."
|
||||
"description": "The message to send to this session at each trigger. Write it as a self-contained instruction: previous conversation history is archived before each run, so this prompt is the only input the model will see. The output stays in this session for the user to view; if it must reach the user proactively, state how in the prompt (e.g. via a skill or webhook). Required with op=create; optional with op=update."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -756,18 +756,48 @@ async function toolMintPublicLink(ctx, args) {
|
||||
return pl.base_url + '/p/' + id;
|
||||
}
|
||||
|
||||
// schedule_task:为当前会话创建定时任务。sessionId 取自 ctx(AI 无法指定别的会话);
|
||||
// 参数与会话唯一性校验均在 scheduler.createTask,失败抛中文 Error 回给 AI 自行纠正。
|
||||
// 生命周期:只能由 AI 创建,用户端只读 + 删除(改 = 删后让 AI 重建),故无修改/删除入口。
|
||||
// schedule_task:当前会话定时任务的完整生命周期(op 分派,规范见 docs/tool-design.md)。
|
||||
// sessionId 取自 ctx(AI 无法指定别的会话);表主键 session_id → 每会话至多一条,
|
||||
// 资源即「本会话的任务」,无 id 参数。条件必填在代码里校验(schema 只 required op),
|
||||
// 错误回显 op 与缺失字段;delete 不落 scheduler_note(返回文本本身已进会话记录)。
|
||||
function toolScheduleTask(ctx, args) {
|
||||
const op = String(args.op || '').trim().toLowerCase();
|
||||
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 db = ctx.db;
|
||||
switch (op) {
|
||||
case 'get': {
|
||||
const t = scheduler.getTask(db, ctx.sessionId);
|
||||
if (!t) return '本会话当前没有定时任务。要创建用 op=create。';
|
||||
const last = t.last_run_at
|
||||
? scheduler.fmtTime(t.last_run_at) + '(状态 ' + (t.last_status || '-') + (t.last_note ? ',' + t.last_note : '') + ')'
|
||||
: '尚未执行';
|
||||
return '本会话定时任务:cron=' + t.cron_expr + '(Asia/Shanghai),下次执行 ' +
|
||||
scheduler.fmtTime(t.next_run_at) + ',上次执行 ' + last + '。提示词:' + t.prompt;
|
||||
}
|
||||
case 'create': {
|
||||
if (!cronExpr) throw new Error('op=create 缺少必填参数 cron_expr');
|
||||
if (!prompt) throw new Error('op=create 缺少必填参数 prompt');
|
||||
const t = scheduler.createTask(db, ctx.sessionId, cronExpr, prompt);
|
||||
return '定时任务已创建:' + t.cron_expr + ',下次执行 ' + t.next_text + '(Asia/Shanghai)。' +
|
||||
'注意:每次触发前本会话的历史消息会被存档(AI 只看到任务 prompt),因此 prompt 需自包含;' +
|
||||
'后续改动用 op=update,取消用 op=delete。';
|
||||
}
|
||||
case 'update': {
|
||||
if (!cronExpr && !prompt) throw new Error('op=update 需要 cron_expr 和 prompt 至少提供一个');
|
||||
const t = scheduler.updateTask(db, ctx.sessionId, {
|
||||
cronExpr: cronExpr || null,
|
||||
prompt: prompt || null,
|
||||
});
|
||||
return '定时任务已更新:' + t.cron_expr + ',下次执行 ' + t.next_text + '(Asia/Shanghai)。';
|
||||
}
|
||||
case 'delete': {
|
||||
const old = scheduler.deleteTask(db, ctx.sessionId);
|
||||
return '定时任务已删除(原定 ' + old + ')。要建新任务用 op=create。';
|
||||
}
|
||||
default:
|
||||
throw new Error('未知的 op:"' + op + '"。可用:get / create(需 cron_expr、prompt)/ update(需 cron_expr、prompt 至少一个)/ delete');
|
||||
}
|
||||
}
|
||||
|
||||
const HANDLERS = {
|
||||
|
||||
Reference in New Issue
Block a user