pi-web-ui 0.88.0 → 0.90.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +80 -1
- package/dist/server/agent-service.js +464 -68
- package/dist/server/attachments.js +39 -0
- package/dist/server/auth-cookie.js +23 -0
- package/dist/server/client-state.js +35 -0
- package/dist/server/composer-drafts.js +20 -2
- package/dist/server/conversation-read-tool.js +325 -0
- package/dist/server/dsh/dsh-agent-service.js +46 -11
- package/dist/server/file-archives.js +258 -0
- package/dist/server/file-transfer-routes.js +113 -0
- package/dist/server/files-service.js +123 -1
- package/dist/server/index.js +361 -14
- package/dist/server/marker-service.js +3 -1
- package/dist/server/model-admin.js +285 -36
- package/dist/server/plugins.js +152 -5
- package/dist/server/queue-utils.js +16 -0
- package/dist/server/schedule-agent-tool.js +240 -0
- package/dist/server/scheduler-tasks.js +414 -0
- package/dist/server/settings-service.js +76 -2
- package/dist/server/terminals.js +14 -1
- package/dist/server/tool-manager.js +16 -1
- package/dist/server/update-check.js +253 -19
- package/dist/server/webui-context.js +4 -0
- package/dist/server/ws-unknown-types.js +44 -0
- package/extensions/webui.ts +9 -2
- package/package.json +7 -3
- package/plugin-sdk/index.d.ts +4 -0
- package/plugin-sdk/index.mjs +9 -0
- package/plugins/catalog.json +11 -2
- package/web/dist/assets/TerminalPanel-BDbdLhpT.js +6 -0
- package/web/dist/assets/index-1f_DP8S3.js +380 -0
- package/web/dist/assets/index-DeUwDA-C.css +10 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/TerminalPanel-CDH27dNP.js +0 -6
- package/web/dist/assets/index-CQg5A74_.js +0 -375
- package/web/dist/assets/index-DTEcxHWs.css +0 -10
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// schedule-agent-tool.ts — 把内置调度器暴露给 Agent(issue #193)
|
|
3
|
+
// ---------------------------------------------------------------------------
|
|
4
|
+
// 背景:pi-web-ui 早有完整调度基建(SchedulerStore:cron/间隔触发+持久化+
|
|
5
|
+
// 无头执行,见 scheduler-tasks.ts),但只停留在插件 API 与图形面板层面 ——
|
|
6
|
+
// AI 被用户要求“每小时检查一次”“半小时后提醒我”时手里没有工具,只能用
|
|
7
|
+
// sleep 死循环假装答应(休眠的会话根本推不回消息)。
|
|
8
|
+
//
|
|
9
|
+
// 本文件注册三个标准 pi 引擎 customTool(DSH 引擎无 customTool 注册面,不接):
|
|
10
|
+
// schedule_task → 建任务(默认绑定发起对话+单次,用熟即删);
|
|
11
|
+
// schedule_list → 看全部任务(含下次触发/上次结果);
|
|
12
|
+
// schedule_cancel → 按 id 删任务。
|
|
13
|
+
// 到期执行走 index.ts 的 executor:目标对话还在 → steer 语义唤醒它(不切用户
|
|
14
|
+
// 当前对话);不在了(关闭/重启)→ 回落原有无头执行;单次任务触发后自动删除。
|
|
15
|
+
//
|
|
16
|
+
// 双语约定(issue #91):definition 走 bilingual(en, zh) 内联双语;per-call
|
|
17
|
+
// 返回文本按 lang 取 pick(lang, zh, en, key, vars),缺表回落英文内联。
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
20
|
+
import { Type } from "typebox";
|
|
21
|
+
import { bilingual, pick } from "./i18n.js";
|
|
22
|
+
import { SCHEDULE_CANCEL_TOOL_NAME, SCHEDULE_LIST_TOOL_NAME, SCHEDULE_TASK_TOOL_NAME } from "./tool-manager.js";
|
|
23
|
+
import { computeNextFire, describeIntervalMs, SCHEDULER_MIN_INTERVAL_MS, } from "./scheduler-tasks.js";
|
|
24
|
+
import { parseCronSpec } from "./plugin-schedule.js";
|
|
25
|
+
/** 用户写法 → 调度规格。纯函数,可单测。
|
|
26
|
+
* 收:5 字段 cron("0 * * * *")、相对时间("in 30m" / "in 1h" / "in 2d")、
|
|
27
|
+
* 裸时长("30m" / "1h",裸数字按分钟)。单位 s/m/h/d/w(大小写不敏感)。 */
|
|
28
|
+
export function parseScheduleSpec(raw) {
|
|
29
|
+
const s = String(raw ?? "").trim();
|
|
30
|
+
if (!s)
|
|
31
|
+
throw new Error("empty");
|
|
32
|
+
const single = s.replace(/\s+/g, " ");
|
|
33
|
+
// 5 字段即按 cron 试("in 30m"是 2 段,不会误判)。
|
|
34
|
+
if (single.split(" ").length === 5 && parseCronSpec(single)) {
|
|
35
|
+
return { kind: "cron", spec: single };
|
|
36
|
+
}
|
|
37
|
+
const m = /^(?:in\s+)?(\d+(?:\.\d+)?)\s*(s|sec|secs|second|seconds|m|min|mins|minute|minutes|h|hour|hours|d|day|days|w|week|weeks)?$/i.exec(single);
|
|
38
|
+
if (!m) {
|
|
39
|
+
throw new Error(`无法解析的时间写法:${s}(要 5 字段 cron 如 "0 * * * *",或相对时间如 "in 30m" / "in 1h" / "30m")`);
|
|
40
|
+
}
|
|
41
|
+
const n = Number(m[1]);
|
|
42
|
+
const unit = (m[2] ?? "m").toLowerCase();
|
|
43
|
+
const mult = unit.startsWith("s")
|
|
44
|
+
? 1000
|
|
45
|
+
: unit.startsWith("m")
|
|
46
|
+
? 60_000
|
|
47
|
+
: unit.startsWith("h")
|
|
48
|
+
? 3_600_000
|
|
49
|
+
: unit.startsWith("d")
|
|
50
|
+
? 86_400_000
|
|
51
|
+
: 7 * 86_400_000; // w
|
|
52
|
+
const ms = Math.floor(n * mult);
|
|
53
|
+
if (!Number.isFinite(ms) || ms <= 0)
|
|
54
|
+
throw new Error(`时长非法:${s}`);
|
|
55
|
+
return { kind: "interval", spec: String(ms) };
|
|
56
|
+
}
|
|
57
|
+
function fmtTime(ms, lang) {
|
|
58
|
+
if (ms === null || !Number.isFinite(ms))
|
|
59
|
+
return lang === "zh" ? "(未知)" : "(unknown)";
|
|
60
|
+
try {
|
|
61
|
+
return new Date(ms).toLocaleString(lang === "zh" ? "zh-CN" : "en-US", { hour12: false });
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return new Date(ms).toISOString();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** 任务一行摘要(列表用;cron 显示原样,interval 中文用“每 X”,英文用秒数)。 */
|
|
68
|
+
function taskLine(t, lang) {
|
|
69
|
+
const when = t.kind === "cron"
|
|
70
|
+
? `cron ${t.spec}`
|
|
71
|
+
: lang === "zh"
|
|
72
|
+
? describeIntervalMs(Number(t.spec))
|
|
73
|
+
: `every ${Math.round(Number(t.spec) / 1000)}s`;
|
|
74
|
+
const state = !t.enabled
|
|
75
|
+
? lang === "zh"
|
|
76
|
+
? "已暂停"
|
|
77
|
+
: "paused"
|
|
78
|
+
: t.running
|
|
79
|
+
? lang === "zh"
|
|
80
|
+
? "执行中"
|
|
81
|
+
: "running"
|
|
82
|
+
: lang === "zh"
|
|
83
|
+
? "启用"
|
|
84
|
+
: "on";
|
|
85
|
+
const once = t.oneShot ? (lang === "zh" ? " · 单次" : " · one-shot") : "";
|
|
86
|
+
const target = t.conversationId
|
|
87
|
+
? lang === "zh"
|
|
88
|
+
? ` · 汇报→对话${t.conversationId}`
|
|
89
|
+
: ` · reports→${t.conversationId}`
|
|
90
|
+
: lang === "zh"
|
|
91
|
+
? " · 无头执行"
|
|
92
|
+
: " · headless";
|
|
93
|
+
const last = t.lastRun
|
|
94
|
+
? lang === "zh"
|
|
95
|
+
? ` · 上次${t.lastRun.ok ? "成功" : `失败(${t.lastRun.error ?? "未知错误"})`}`
|
|
96
|
+
: ` · last ${t.lastRun.ok ? "ok" : `failed (${t.lastRun.error ?? "unknown"})`}`
|
|
97
|
+
: "";
|
|
98
|
+
return `• ${t.id} · ${t.name} · ${when} · ${state}${once}${target} · ${lang === "zh" ? "下次" : "next"} ${fmtTime(t.nextFire, lang)}${last}`;
|
|
99
|
+
}
|
|
100
|
+
export function makeScheduleTools(host, ownerConversationId, lang) {
|
|
101
|
+
const getLang = lang ?? (() => "en");
|
|
102
|
+
const text = (t, details = {}) => ({
|
|
103
|
+
content: [{ type: "text", text: t }],
|
|
104
|
+
details,
|
|
105
|
+
});
|
|
106
|
+
const noStore = () => text(pick(getLang(), "当前引擎不支持定时任务(调度存储未接入)。", "Scheduled tasks are not wired for the current engine.", "sched.not.wired"));
|
|
107
|
+
const taskTool = defineTool({
|
|
108
|
+
name: SCHEDULE_TASK_TOOL_NAME,
|
|
109
|
+
label: "Schedule a wake-up in this conversation",
|
|
110
|
+
description: bilingual("Create a scheduled wake-up in the CURRENT conversation: at the given cron time or after the given delay, the scheduler automatically delivers your prompt back into this conversation so you continue the work and report to the user. " +
|
|
111
|
+
"Use it when the user asks for periodic checks, delayed reminders, or scheduled summaries — do NOT fake it with sleep loops (a sleeping script can never push a message back). " +
|
|
112
|
+
'Schedule accepts a 5-field cron ("0 * * * *" = hourly) or a relative delay ("in 30m", "in 1h", "30m"); minimum interval is 60s. ' +
|
|
113
|
+
"One-shot by default (recurring=false auto-deletes the task after it fires); pass recurring=true for repeats. " +
|
|
114
|
+
"If the conversation is gone when it fires (closed/restarted), the task runs headless in its project and the report stays in the scheduler panel history. " +
|
|
115
|
+
"Manage with schedule_list / schedule_cancel; the user can also cancel from the background-tasks panel.", "在**当前对话**里创建一个定时唤醒:到指定 cron 时间或延迟后,调度器自动把你的 prompt 投回本对话,你继续执行并向用户汇报。" +
|
|
116
|
+
"用户要求定时巡检、延时提醒、定时汇总时用它 —— 不要用 sleep 死循环假装答应(休眠的脚本推不回任何消息)。" +
|
|
117
|
+
"时间写法收 5 字段 cron(“0 * * * *”=每小时)或相对延迟(“in 30m”“in 1h”“30m”);最短间隔 60s。" +
|
|
118
|
+
"默认单次(recurring=false 触发后自动删除);传 recurring=true 做周期任务。" +
|
|
119
|
+
"触发时对话已不在(关闭/重启)则回落无头执行,报告留在调度面板历史里。" +
|
|
120
|
+
"用 schedule_list / schedule_cancel 管理;用户也可从后台任务面板取消。"),
|
|
121
|
+
promptSnippet: "schedule a wake-up in this conversation (cron or delay), auto-report on fire",
|
|
122
|
+
parameters: Type.Object({
|
|
123
|
+
schedule: Type.String({
|
|
124
|
+
description: 'When to fire: 5-field cron ("0 * * * *" hourly) or relative delay ("in 30m", "in 1h", "30m"). Minimum 60s.',
|
|
125
|
+
}),
|
|
126
|
+
prompt: Type.String({
|
|
127
|
+
description: "Instruction delivered into this conversation on fire (e.g. what to check and report). Max 8000 chars.",
|
|
128
|
+
}),
|
|
129
|
+
label: Type.Optional(Type.String({ description: "Short name shown in the background-tasks panel. Defaults to the prompt head." })),
|
|
130
|
+
recurring: Type.Optional(Type.Boolean({ description: "Repeat on schedule (default false = one-shot, auto-deleted after firing)." })),
|
|
131
|
+
}),
|
|
132
|
+
execute: async (_id, p) => {
|
|
133
|
+
const store = host.store();
|
|
134
|
+
if (!store)
|
|
135
|
+
return noStore();
|
|
136
|
+
let parsed;
|
|
137
|
+
try {
|
|
138
|
+
parsed = parseScheduleSpec(p.schedule);
|
|
139
|
+
}
|
|
140
|
+
catch (err) {
|
|
141
|
+
return text(pick(getLang(), `时间写法非法:${String(p.schedule ?? "")}(要 5 字段 cron 如 "0 * * * *" 或相对时间如 "in 30m"):${err.message}`, `Invalid schedule: ${String(p.schedule ?? "")} (want 5-field cron like "0 * * * *" or a delay like "in 30m"): ${err.message}`, "sched.task.bad.schedule", { schedule: String(p.schedule ?? "") }));
|
|
142
|
+
}
|
|
143
|
+
if (parsed.kind === "interval" && Number(parsed.spec) < SCHEDULER_MIN_INTERVAL_MS) {
|
|
144
|
+
return text(pick(getLang(), `间隔太短(最短 60s,防 token 烧穿)。`, `Interval too short (minimum 60s, prevents token burn).`, "sched.task.interval.too.short"));
|
|
145
|
+
}
|
|
146
|
+
const prompt = String(p.prompt ?? "").trim();
|
|
147
|
+
if (!prompt) {
|
|
148
|
+
return text(pick(getLang(), "触发指令(prompt)不能为空:写清楚触发时要检查什么、汇报什么。", "Prompt must not be empty: say what to check and report on fire.", "sched.task.empty.prompt"));
|
|
149
|
+
}
|
|
150
|
+
const cwd = String(host.cwd() ?? "").trim();
|
|
151
|
+
if (!cwd) {
|
|
152
|
+
return text(pick(getLang(), "当前没有工作目录,无法创建定时任务。", "No working directory, cannot create the scheduled task.", "sched.task.no.cwd"));
|
|
153
|
+
}
|
|
154
|
+
const labelRaw = typeof p.label === "string" ? p.label.trim().slice(0, 80) : "";
|
|
155
|
+
const name = labelRaw || prompt.split("\n")[0].slice(0, 40) || "定时任务";
|
|
156
|
+
const convId = (ownerConversationId ?? "").trim() || String(host.activeConversationId() ?? "").trim();
|
|
157
|
+
const recurring = p.recurring === true;
|
|
158
|
+
let task;
|
|
159
|
+
try {
|
|
160
|
+
task = store.upsert({
|
|
161
|
+
name,
|
|
162
|
+
cwd,
|
|
163
|
+
kind: parsed.kind,
|
|
164
|
+
spec: parsed.spec,
|
|
165
|
+
prompt,
|
|
166
|
+
conversationId: convId,
|
|
167
|
+
oneShot: !recurring,
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
catch (err) {
|
|
171
|
+
return text(String(err?.message ?? err));
|
|
172
|
+
}
|
|
173
|
+
const L = getLang();
|
|
174
|
+
const next = computeNextFire(task, Date.now());
|
|
175
|
+
const head = L === "zh" ? `定时任务已创建:${task.id}(${task.name})` : `Scheduled task created: ${task.id} (${task.name})`;
|
|
176
|
+
const whenLine = L === "zh"
|
|
177
|
+
? `触发:${parsed.kind === "cron" ? `cron ${parsed.spec}` : describeIntervalMs(Number(parsed.spec))},下次 ${fmtTime(next, L)}${recurring ? "(周期)" : "(单次,触发后自动删除)"}`
|
|
178
|
+
: `Fires: ${parsed.kind === "cron" ? `cron ${parsed.spec}` : `every ${Math.round(Number(parsed.spec) / 1000)}s`}, next ${fmtTime(next, L)}${recurring ? " (recurring)" : " (one-shot, auto-deleted after firing)"}`;
|
|
179
|
+
const targetLine = convId
|
|
180
|
+
? L === "zh"
|
|
181
|
+
? `汇报:触发时自动唤醒本对话(${convId});对话已不在则无头执行,报告进调度面板历史。`
|
|
182
|
+
: `Reports: wakes this conversation (${convId}) on fire; runs headless (report in panel history) if it is gone.`
|
|
183
|
+
: L === "zh"
|
|
184
|
+
? "汇报:无头执行,报告进调度面板历史(创建时没拿到对话 id)。"
|
|
185
|
+
: "Reports: headless run, report in panel history (no conversation id captured at creation).";
|
|
186
|
+
const tail = L === "zh"
|
|
187
|
+
? `取消:schedule_cancel(id="${task.id}"),或后台任务面板手动取消;查看:schedule_list。`
|
|
188
|
+
: `Cancel: schedule_cancel(id="${task.id}"), or from the background-tasks panel; inspect: schedule_list.`;
|
|
189
|
+
return text(`${head}\n${whenLine}\n${targetLine}\n${tail}`, { task });
|
|
190
|
+
},
|
|
191
|
+
});
|
|
192
|
+
const listTool = defineTool({
|
|
193
|
+
name: SCHEDULE_LIST_TOOL_NAME,
|
|
194
|
+
label: "List scheduled tasks",
|
|
195
|
+
description: bilingual("List all built-in scheduled tasks (all projects): id, name, cron/interval, on/paused, one-shot, target conversation, next fire, last run. Use it to inspect before cancelling, or to answer the user about what is scheduled.", "列出全部内置定时任务(跨项目):id、名称、cron/间隔、启用/暂停、单次、目标对话、下次触发、上次结果。取消前先看,或回答用户“排了什么”时用。"),
|
|
196
|
+
promptSnippet: "list scheduled wake-up tasks",
|
|
197
|
+
parameters: Type.Object({}),
|
|
198
|
+
execute: async () => {
|
|
199
|
+
const store = host.store();
|
|
200
|
+
if (!store)
|
|
201
|
+
return noStore();
|
|
202
|
+
const L = getLang();
|
|
203
|
+
const tasks = store.list();
|
|
204
|
+
if (tasks.length === 0) {
|
|
205
|
+
return text(pick(getLang(), "当前没有定时任务。用 schedule_task 创建(cron 或 in 30m 这类延迟,最短 60s)。", "No scheduled tasks. Create one with schedule_task (cron or a delay like in 30m, minimum 60s).", "sched.list.empty"), { tasks: [] });
|
|
206
|
+
}
|
|
207
|
+
const lines = tasks.slice(0, 50).map((t) => taskLine(t, L));
|
|
208
|
+
const more = tasks.length > 50
|
|
209
|
+
? L === "zh"
|
|
210
|
+
? `\n…还有 ${tasks.length - 50} 条没列(去后台任务面板看全量)。`
|
|
211
|
+
: `\n…${tasks.length - 50} more not shown (see the background-tasks panel).`
|
|
212
|
+
: "";
|
|
213
|
+
const head = L === "zh" ? `定时任务(${tasks.length}):` : `Scheduled tasks (${tasks.length}):`;
|
|
214
|
+
return text(`${head}\n${lines.join("\n")}${more}`, { tasks });
|
|
215
|
+
},
|
|
216
|
+
});
|
|
217
|
+
const cancelTool = defineTool({
|
|
218
|
+
name: SCHEDULE_CANCEL_TOOL_NAME,
|
|
219
|
+
label: "Cancel a scheduled task",
|
|
220
|
+
description: bilingual("Delete a scheduled task by id (see schedule_list). Deleting stops all future fires; use it when the user says the schedule is no longer needed.", "按 id 删除定时任务(id 见 schedule_list)。删除后不再触发;用户说不用排了时用它。"),
|
|
221
|
+
promptSnippet: "cancel a scheduled task by id",
|
|
222
|
+
parameters: Type.Object({
|
|
223
|
+
id: Type.String({ description: "Task id from schedule_list." }),
|
|
224
|
+
}),
|
|
225
|
+
execute: async (_id, p) => {
|
|
226
|
+
const store = host.store();
|
|
227
|
+
if (!store)
|
|
228
|
+
return noStore();
|
|
229
|
+
const id = String(p.id ?? "").trim();
|
|
230
|
+
if (!id) {
|
|
231
|
+
return text(pick(getLang(), "要删哪个任务?给 id(先 schedule_list 查)。", "Which task? Give its id (see schedule_list first).", "sched.cancel.empty.id"));
|
|
232
|
+
}
|
|
233
|
+
if (!store.remove(id)) {
|
|
234
|
+
return text(pick(getLang(), `没有 id=${id} 的任务(可能已触发自删或被删过,用 schedule_list 看现有的)。`, `No task id=${id} (may have fired-and-deleted or been removed; see schedule_list).`, "sched.cancel.not.found", { id }));
|
|
235
|
+
}
|
|
236
|
+
return text(pick(getLang(), `定时任务 ${id} 已删除,不再触发。`, `Scheduled task ${id} deleted, will not fire again.`, "sched.cancel.ok", { id }), { id });
|
|
237
|
+
},
|
|
238
|
+
});
|
|
239
|
+
return [taskTool, listTool, cancelTool];
|
|
240
|
+
}
|
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 内置定时任务调度(issue #184)。
|
|
3
|
+
*
|
|
4
|
+
* 面向普通用户的图形化调度器:任务 CRUD + cron/间隔触发 + 无头执行 +
|
|
5
|
+
* 执行历史 + 通知。底层 cron 解析复用 plugin-schedule.ts(parseCronSpec /
|
|
6
|
+
* nextCronFire),持久化走 <dataDir>/scheduler-tasks.json(全局共享,
|
|
7
|
+
* 与 client-state.json 同级),执行经调用方注入的 executor(index.ts 接
|
|
8
|
+
* AgentService.chatFromScheduler,无头伪客户端)。
|
|
9
|
+
*
|
|
10
|
+
* 定时策略:单个 10s ticker 检查到期任务(cron 下次触发 / 间隔毫秒),
|
|
11
|
+
* running 集合防重叠;catchUp "once" 在启动时补跑一次漏掉的触发。
|
|
12
|
+
*/
|
|
13
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
import { nextCronFire, parseCronSpec } from "./plugin-schedule.js";
|
|
16
|
+
export const SCHEDULER_FILE = "scheduler-tasks.json";
|
|
17
|
+
/** 持久间隔底线 60s(与 host.schedule 持久任务同口径,防 token 烧穿)。 */
|
|
18
|
+
export const SCHEDULER_MIN_INTERVAL_MS = 60_000;
|
|
19
|
+
export const SCHEDULER_MAX_INTERVAL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
20
|
+
export const SCHEDULER_HISTORY_MAX = 20;
|
|
21
|
+
const TICK_MS = 10_000;
|
|
22
|
+
export const SCHEDULER_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
23
|
+
export function schedulerFile(dataDir) {
|
|
24
|
+
return join(dataDir, SCHEDULER_FILE);
|
|
25
|
+
}
|
|
26
|
+
function randomTaskId() {
|
|
27
|
+
const abc = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
28
|
+
let s = "";
|
|
29
|
+
for (let i = 0; i < 6; i++)
|
|
30
|
+
s += abc[Math.floor(Math.random() * abc.length)];
|
|
31
|
+
return `task-${s}`;
|
|
32
|
+
}
|
|
33
|
+
/** 归一化 + 校验用户输入;非法抛 Error(中文信息,直接面向 UI)。纯函数,可单测。 */
|
|
34
|
+
export function normalizeSchedulerInput(input, now = Date.now()) {
|
|
35
|
+
const idRaw = String(input.id ?? "").trim();
|
|
36
|
+
const id = idRaw || randomTaskId();
|
|
37
|
+
if (!SCHEDULER_ID_RE.test(id))
|
|
38
|
+
throw new Error("任务 id 非法(只收字母/数字/下划线/连字符,≤64 字)");
|
|
39
|
+
const name = String(input.name ?? "")
|
|
40
|
+
.trim()
|
|
41
|
+
.slice(0, 80);
|
|
42
|
+
if (!name)
|
|
43
|
+
throw new Error("任务名称不能为空");
|
|
44
|
+
const description = String(input.description ?? "")
|
|
45
|
+
.trim()
|
|
46
|
+
.slice(0, 500);
|
|
47
|
+
const cwd = String(input.cwd ?? "").trim();
|
|
48
|
+
if (!cwd)
|
|
49
|
+
throw new Error("执行目标项目(cwd)不能为空");
|
|
50
|
+
const kind = input.kind === "interval" ? "interval" : "cron";
|
|
51
|
+
let spec;
|
|
52
|
+
if (kind === "cron") {
|
|
53
|
+
spec = String(input.spec ?? "")
|
|
54
|
+
.trim()
|
|
55
|
+
.replace(/\s+/g, " ");
|
|
56
|
+
if (!parseCronSpec(spec))
|
|
57
|
+
throw new Error("cron 表达式非法(要 5 字段:分 时 日 月 周,如 0 9 * * *)");
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
const ms = Math.floor(Number(input.spec));
|
|
61
|
+
if (!Number.isFinite(ms) || ms <= 0)
|
|
62
|
+
throw new Error("间隔毫秒数非法");
|
|
63
|
+
if (ms < SCHEDULER_MIN_INTERVAL_MS)
|
|
64
|
+
throw new Error(`间隔太短(最短 ${SCHEDULER_MIN_INTERVAL_MS / 1000}s,防 token 烧穿)`);
|
|
65
|
+
if (ms > SCHEDULER_MAX_INTERVAL_MS)
|
|
66
|
+
throw new Error("间隔太长(最长 30 天)");
|
|
67
|
+
spec = String(ms);
|
|
68
|
+
}
|
|
69
|
+
const prompt = String(input.prompt ?? "").trim();
|
|
70
|
+
if (!prompt)
|
|
71
|
+
throw new Error("触发指令(prompt)不能为空");
|
|
72
|
+
if (prompt.length > 8000)
|
|
73
|
+
throw new Error("触发指令超长(>8000 字),请裁剪后重试");
|
|
74
|
+
const model = String(input.model ?? "").trim();
|
|
75
|
+
if (model && !model.includes("/"))
|
|
76
|
+
throw new Error("模型格式非法(应为 provider/id)");
|
|
77
|
+
const thinkingLevel = String(input.thinkingLevel ?? "").trim();
|
|
78
|
+
const catchUp = input.catchUp === "once" ? "once" : "skip";
|
|
79
|
+
const conversationId = String(input.conversationId ?? "")
|
|
80
|
+
.trim()
|
|
81
|
+
.slice(0, 128);
|
|
82
|
+
return {
|
|
83
|
+
id,
|
|
84
|
+
name,
|
|
85
|
+
description,
|
|
86
|
+
cwd,
|
|
87
|
+
kind,
|
|
88
|
+
spec,
|
|
89
|
+
prompt,
|
|
90
|
+
enabled: input.enabled !== false,
|
|
91
|
+
model,
|
|
92
|
+
thinkingLevel,
|
|
93
|
+
catchUp,
|
|
94
|
+
conversationId,
|
|
95
|
+
oneShot: input.oneShot === true,
|
|
96
|
+
createdAt: now,
|
|
97
|
+
updatedAt: now,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/** 下次触发毫秒时间戳;非法/禁用回 null。纯函数,可单测。 */
|
|
101
|
+
export function computeNextFire(task, fromMs) {
|
|
102
|
+
try {
|
|
103
|
+
if (task.kind === "cron") {
|
|
104
|
+
const parts = parseCronSpec(task.spec);
|
|
105
|
+
if (!parts)
|
|
106
|
+
return null;
|
|
107
|
+
return nextCronFire(parts, fromMs);
|
|
108
|
+
}
|
|
109
|
+
const ms = Math.floor(Number(task.spec));
|
|
110
|
+
if (!Number.isFinite(ms) || ms <= 0)
|
|
111
|
+
return null;
|
|
112
|
+
return Math.floor(Number(fromMs)) + ms;
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/** 间隔任务的人类可读描述(面板显示用)。纯函数。 */
|
|
119
|
+
export function describeIntervalMs(ms) {
|
|
120
|
+
const s = Math.round(ms / 1000);
|
|
121
|
+
if (s < 60)
|
|
122
|
+
return `每 ${s} 秒`;
|
|
123
|
+
if (s < 3600) {
|
|
124
|
+
const m = Math.floor(s / 60);
|
|
125
|
+
return s % 60 === 0 ? `每 ${m} 分钟` : `每 ${m} 分 ${s % 60} 秒`;
|
|
126
|
+
}
|
|
127
|
+
if (s < 86400) {
|
|
128
|
+
const h = Math.floor(s / 3600);
|
|
129
|
+
return s % 3600 === 0 ? `每 ${h} 小时` : `每 ${h} 小时 ${Math.floor((s % 3600) / 60)} 分`;
|
|
130
|
+
}
|
|
131
|
+
const d = Math.floor(s / 86400);
|
|
132
|
+
return `每 ${d} 天`;
|
|
133
|
+
}
|
|
134
|
+
function sanitizeHistory(v) {
|
|
135
|
+
if (!Array.isArray(v))
|
|
136
|
+
return [];
|
|
137
|
+
const out = [];
|
|
138
|
+
for (const r of v) {
|
|
139
|
+
if (!r || typeof r !== "object")
|
|
140
|
+
continue;
|
|
141
|
+
const rec = r;
|
|
142
|
+
if (typeof rec.at !== "number" || !Number.isFinite(rec.at))
|
|
143
|
+
continue;
|
|
144
|
+
out.push({
|
|
145
|
+
at: rec.at,
|
|
146
|
+
ok: rec.ok === true,
|
|
147
|
+
durationMs: typeof rec.durationMs === "number" && Number.isFinite(rec.durationMs) ? rec.durationMs : 0,
|
|
148
|
+
...(typeof rec.conversationId === "string" && rec.conversationId ? { conversationId: rec.conversationId } : {}),
|
|
149
|
+
...(typeof rec.error === "string" && rec.error ? { error: rec.error.slice(0, 500) } : {}),
|
|
150
|
+
...(rec.manual === true ? { manual: true } : {}),
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
return out.sort((a, b) => b.at - a.at).slice(0, SCHEDULER_HISTORY_MAX);
|
|
154
|
+
}
|
|
155
|
+
export class SchedulerStore {
|
|
156
|
+
dataDir;
|
|
157
|
+
opts;
|
|
158
|
+
tasks = new Map();
|
|
159
|
+
nextFire = new Map();
|
|
160
|
+
running = new Set();
|
|
161
|
+
timer = null;
|
|
162
|
+
started = false;
|
|
163
|
+
constructor(dataDir, opts = {}) {
|
|
164
|
+
this.dataDir = dataDir;
|
|
165
|
+
this.opts = opts;
|
|
166
|
+
}
|
|
167
|
+
setExecutor(executor) {
|
|
168
|
+
this.opts.executor = executor;
|
|
169
|
+
}
|
|
170
|
+
/** 启动 ticker + catchUp 补跑(幂等)。 */
|
|
171
|
+
start() {
|
|
172
|
+
this.load();
|
|
173
|
+
if (this.started)
|
|
174
|
+
return;
|
|
175
|
+
this.started = true;
|
|
176
|
+
const now = Date.now();
|
|
177
|
+
for (const task of this.tasks.values()) {
|
|
178
|
+
if (!task.enabled)
|
|
179
|
+
continue;
|
|
180
|
+
const lastAt = task.history?.[0]?.at ?? task.updatedAt;
|
|
181
|
+
const next = computeNextFire(task, Math.max(lastAt, task.updatedAt));
|
|
182
|
+
if (next === null)
|
|
183
|
+
continue;
|
|
184
|
+
if (next <= now && task.catchUp === "once" && lastAt < now) {
|
|
185
|
+
// 重启发现漏跑:补一次,补完按这次重排。
|
|
186
|
+
this.nextFire.set(task.id, now + 5000);
|
|
187
|
+
void this.fire(task.id, false);
|
|
188
|
+
}
|
|
189
|
+
else if (next <= now) {
|
|
190
|
+
this.nextFire.set(task.id, computeNextFire(task, now) ?? now + TICK_MS);
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
this.nextFire.set(task.id, next);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
this.timer = setInterval(() => void this.tick(), TICK_MS);
|
|
197
|
+
this.timer.unref?.();
|
|
198
|
+
}
|
|
199
|
+
stop() {
|
|
200
|
+
if (this.timer) {
|
|
201
|
+
clearInterval(this.timer);
|
|
202
|
+
this.timer = null;
|
|
203
|
+
}
|
|
204
|
+
this.started = false;
|
|
205
|
+
}
|
|
206
|
+
/** 读盘;坏文件/形状不对当空表(读路径不回写)。 */
|
|
207
|
+
load() {
|
|
208
|
+
try {
|
|
209
|
+
const parsed = JSON.parse(readFileSync(schedulerFile(this.dataDir), "utf8"));
|
|
210
|
+
if (!parsed || typeof parsed !== "object" || !parsed.tasks || typeof parsed.tasks !== "object") {
|
|
211
|
+
this.tasks = new Map();
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
const next = new Map();
|
|
215
|
+
for (const [id, raw] of Object.entries(parsed.tasks)) {
|
|
216
|
+
if (!raw || typeof raw !== "object")
|
|
217
|
+
continue;
|
|
218
|
+
const r = raw;
|
|
219
|
+
try {
|
|
220
|
+
const task = normalizeSchedulerInput({
|
|
221
|
+
id,
|
|
222
|
+
name: r.name,
|
|
223
|
+
description: r.description,
|
|
224
|
+
cwd: r.cwd,
|
|
225
|
+
kind: r.kind,
|
|
226
|
+
spec: r.spec,
|
|
227
|
+
prompt: r.prompt,
|
|
228
|
+
enabled: r.enabled,
|
|
229
|
+
model: r.model,
|
|
230
|
+
thinkingLevel: r.thinkingLevel,
|
|
231
|
+
catchUp: r.catchUp,
|
|
232
|
+
conversationId: r.conversationId,
|
|
233
|
+
oneShot: r.oneShot,
|
|
234
|
+
});
|
|
235
|
+
task.createdAt = typeof r.createdAt === "number" && Number.isFinite(r.createdAt) ? r.createdAt : Date.now();
|
|
236
|
+
task.updatedAt =
|
|
237
|
+
typeof r.updatedAt === "number" && Number.isFinite(r.updatedAt) ? r.updatedAt : task.createdAt;
|
|
238
|
+
next.set(id, { ...task, history: sanitizeHistory(r.history) });
|
|
239
|
+
}
|
|
240
|
+
catch {
|
|
241
|
+
// 单条坏记录跳过,不影响其他任务
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
this.tasks = next;
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
this.tasks = new Map();
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
save() {
|
|
251
|
+
try {
|
|
252
|
+
mkdirSync(this.dataDir, { recursive: true });
|
|
253
|
+
const file = schedulerFile(this.dataDir);
|
|
254
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
255
|
+
const tasks = {};
|
|
256
|
+
for (const [id, t] of this.tasks)
|
|
257
|
+
tasks[id] = t;
|
|
258
|
+
writeFileSync(tmp, JSON.stringify({ v: 1, tasks }));
|
|
259
|
+
renameSync(tmp, file);
|
|
260
|
+
}
|
|
261
|
+
catch (err) {
|
|
262
|
+
console.error("[scheduler] persist failed:", err);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
changed() {
|
|
266
|
+
try {
|
|
267
|
+
this.opts.onChange?.();
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
/* 推送失败不影响调度 */
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
list() {
|
|
274
|
+
const now = Date.now();
|
|
275
|
+
return [...this.tasks.values()]
|
|
276
|
+
.map((t) => {
|
|
277
|
+
const history = sanitizeHistory(t.history);
|
|
278
|
+
return {
|
|
279
|
+
id: t.id,
|
|
280
|
+
name: t.name,
|
|
281
|
+
description: t.description,
|
|
282
|
+
cwd: t.cwd,
|
|
283
|
+
kind: t.kind,
|
|
284
|
+
spec: t.spec,
|
|
285
|
+
prompt: t.prompt,
|
|
286
|
+
enabled: t.enabled,
|
|
287
|
+
model: t.model,
|
|
288
|
+
thinkingLevel: t.thinkingLevel,
|
|
289
|
+
catchUp: t.catchUp,
|
|
290
|
+
conversationId: t.conversationId,
|
|
291
|
+
oneShot: t.oneShot,
|
|
292
|
+
createdAt: t.createdAt,
|
|
293
|
+
updatedAt: t.updatedAt,
|
|
294
|
+
nextFire: !t.enabled ? null : (this.nextFire.get(t.id) ?? computeNextFire(t, Math.max(now, t.updatedAt))),
|
|
295
|
+
lastRun: history[0] ?? null,
|
|
296
|
+
history,
|
|
297
|
+
running: this.running.has(t.id),
|
|
298
|
+
};
|
|
299
|
+
})
|
|
300
|
+
.sort((a, b) => a.name.localeCompare(b.name, "zh"));
|
|
301
|
+
}
|
|
302
|
+
/** 新建或全量更新(同名 id 覆盖);返回归一化后的任务。 */
|
|
303
|
+
upsert(input) {
|
|
304
|
+
const prev = this.tasks.get(String(input.id ?? "").trim());
|
|
305
|
+
const task = normalizeSchedulerInput(input);
|
|
306
|
+
if (prev) {
|
|
307
|
+
task.createdAt = prev.createdAt;
|
|
308
|
+
task.updatedAt = Date.now();
|
|
309
|
+
}
|
|
310
|
+
const history = prev?.history ? sanitizeHistory(prev.history) : [];
|
|
311
|
+
this.tasks.set(task.id, { ...task, history });
|
|
312
|
+
// spec/cwd/开关变了 → 按现在重排下次触发
|
|
313
|
+
this.nextFire.set(task.id, computeNextFire(task, Date.now()) ?? Date.now() + TICK_MS);
|
|
314
|
+
this.save();
|
|
315
|
+
this.changed();
|
|
316
|
+
return task;
|
|
317
|
+
}
|
|
318
|
+
remove(id) {
|
|
319
|
+
const ok = this.tasks.delete(id);
|
|
320
|
+
this.nextFire.delete(id);
|
|
321
|
+
if (ok) {
|
|
322
|
+
this.save();
|
|
323
|
+
this.changed();
|
|
324
|
+
}
|
|
325
|
+
return ok;
|
|
326
|
+
}
|
|
327
|
+
setEnabled(id, enabled) {
|
|
328
|
+
const t = this.tasks.get(id);
|
|
329
|
+
if (!t)
|
|
330
|
+
return null;
|
|
331
|
+
t.enabled = enabled;
|
|
332
|
+
t.updatedAt = Date.now();
|
|
333
|
+
this.nextFire.set(id, computeNextFire(t, Date.now()) ?? Date.now() + TICK_MS);
|
|
334
|
+
this.save();
|
|
335
|
+
this.changed();
|
|
336
|
+
return t;
|
|
337
|
+
}
|
|
338
|
+
async tick() {
|
|
339
|
+
const now = Date.now();
|
|
340
|
+
for (const task of this.tasks.values()) {
|
|
341
|
+
if (!task.enabled || this.running.has(task.id))
|
|
342
|
+
continue;
|
|
343
|
+
let next = this.nextFire.get(task.id);
|
|
344
|
+
if (next === undefined) {
|
|
345
|
+
next = computeNextFire(task, Math.max(now, task.updatedAt)) ?? now + TICK_MS;
|
|
346
|
+
this.nextFire.set(task.id, next);
|
|
347
|
+
}
|
|
348
|
+
if (next <= now)
|
|
349
|
+
await this.fire(task.id, false);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
/** 手动立即执行一次(面板 Run Now;调试用,不扰动下次触发)。 */
|
|
353
|
+
async runNow(id) {
|
|
354
|
+
const task = this.tasks.get(id);
|
|
355
|
+
if (!task)
|
|
356
|
+
return { ok: false, error: "任务不存在" };
|
|
357
|
+
if (this.running.has(id))
|
|
358
|
+
return { ok: false, error: "任务正在执行中" };
|
|
359
|
+
return this.fire(id, true);
|
|
360
|
+
}
|
|
361
|
+
async fire(id, manual) {
|
|
362
|
+
const task = this.tasks.get(id);
|
|
363
|
+
if (!task)
|
|
364
|
+
return { ok: false, error: "任务不存在" };
|
|
365
|
+
const executor = this.opts.executor;
|
|
366
|
+
if (!executor) {
|
|
367
|
+
const err = "调度器执行器未接入(当前引擎不支持定时任务)";
|
|
368
|
+
this.recordRun(id, { at: Date.now(), ok: false, durationMs: 0, error: err, ...(manual ? { manual } : {}) });
|
|
369
|
+
return { ok: false, error: err };
|
|
370
|
+
}
|
|
371
|
+
this.running.add(id);
|
|
372
|
+
this.changed();
|
|
373
|
+
const startedAt = Date.now();
|
|
374
|
+
let result;
|
|
375
|
+
try {
|
|
376
|
+
result = await executor({ ...task });
|
|
377
|
+
}
|
|
378
|
+
catch (err) {
|
|
379
|
+
result = { ok: false, error: err.message };
|
|
380
|
+
}
|
|
381
|
+
const durationMs = Date.now() - startedAt;
|
|
382
|
+
this.running.delete(id);
|
|
383
|
+
this.recordRun(id, {
|
|
384
|
+
at: Date.now(),
|
|
385
|
+
ok: result.ok,
|
|
386
|
+
durationMs,
|
|
387
|
+
...(result.conversationId ? { conversationId: result.conversationId } : {}),
|
|
388
|
+
...(result.error ? { error: result.error.slice(0, 500) } : {}),
|
|
389
|
+
...(manual ? { manual } : {}),
|
|
390
|
+
});
|
|
391
|
+
// 按这次完成时间重排下次触发(间隔任务从完成起算,避免长任务连击)。
|
|
392
|
+
const cur = this.tasks.get(id);
|
|
393
|
+
if (cur && cur.enabled && !manual) {
|
|
394
|
+
this.nextFire.set(id, computeNextFire(cur, Date.now()) ?? Date.now() + TICK_MS);
|
|
395
|
+
this.save();
|
|
396
|
+
}
|
|
397
|
+
const label = `⏰ ${task.name}`;
|
|
398
|
+
if (result.ok) {
|
|
399
|
+
this.opts.notify?.("info", `定时任务「${task.name}」${manual ? "手动" : "定时"}触发完成(${(durationMs / 1000).toFixed(0)}s)——${label}`, `Scheduled task "${task.name}" ${manual ? "manually" : "automatically"} finished (${Math.round(durationMs / 1000)}s) — ${label}`);
|
|
400
|
+
}
|
|
401
|
+
else {
|
|
402
|
+
this.opts.notify?.("warning", `定时任务「${task.name}」${manual ? "手动" : "定时"}触发失败:${result.error ?? "未知错误"}`, `Scheduled task "${task.name}" ${manual ? "manual" : "automatic"} run failed: ${result.error ?? "unknown error"}`);
|
|
403
|
+
}
|
|
404
|
+
this.changed();
|
|
405
|
+
return result;
|
|
406
|
+
}
|
|
407
|
+
recordRun(id, run) {
|
|
408
|
+
const t = this.tasks.get(id);
|
|
409
|
+
if (!t)
|
|
410
|
+
return;
|
|
411
|
+
t.history = [run, ...sanitizeHistory(t.history)].slice(0, SCHEDULER_HISTORY_MAX);
|
|
412
|
+
this.save();
|
|
413
|
+
}
|
|
414
|
+
}
|