pi-web-ui 0.89.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.
@@ -30,7 +30,8 @@ import { WebSocket, WebSocketServer } from "ws";
30
30
  import { VERSION, getAgentDir } from "@earendil-works/pi-coding-agent";
31
31
  import { PROTOCOL_VERSION } from "./protocol-version.js";
32
32
  import { AgentService, workspacePath, QuiesceRejectedError } from "./agent-service.js";
33
- import { isAbsoluteWirePath, wireToAbs } from "./files-service.js";
33
+ import { WS_MAX_PAYLOAD_BYTES, isAbsoluteWirePath, wireToAbs } from "./files-service.js";
34
+ import { registerFileTransferRoutes } from "./file-transfer-routes.js";
34
35
  import { previewKind } from "./text-sniff.js";
35
36
  import { startControlServer } from "./control-socket.js";
36
37
  import { scheduleUploadCleanup } from "./uploads.js";
@@ -39,6 +40,7 @@ import { listThemes, resolveThemeFile } from "./themes.js";
39
40
  import { isManaged, managedRefusal } from "./managed.js";
40
41
  import { launchOrigin, toServiceInfo } from "./launch-origin.js";
41
42
  import { parseTabs, tabsRefusal } from "./tabs.js";
43
+ import { recordUnknownWsType } from "./ws-unknown-types.js";
42
44
  import { installPack, isKnownPack, listPacks, loadServerStrings, readPackFile, removePack, unloadServerStrings, } from "./locales.js";
43
45
  import { PluginManager, resolvePluginClientFile, } from "./plugins.js";
44
46
  import { PluginInstaller } from "./plugin-installer.js";
@@ -47,6 +49,7 @@ import { McpBridge } from "./mcp-bridge.js";
47
49
  import { createMcpHotReload } from "./mcp-hot-reload.js";
48
50
  import { createHostMetricsSampler } from "./host-metrics.js";
49
51
  import { SchedulerStore } from "./scheduler-tasks.js";
52
+ import { buildPiWebTokenCookie, isTlsRequest } from "./auth-cookie.js";
50
53
  /** Strip npm-injected env (`npm start` exports `npm_config_*` / `npm_package_*` /
51
54
  * `npm_lifecycle_*` into every child). Anything this server spawns — shells,
52
55
  * `pi update` — would otherwise inherit `npm_config_allow_scripts`, which npm
@@ -219,15 +222,19 @@ if (AUTH_TOKEN) {
219
222
  // 重要:只要请求携带着有效 token(query/header/cookie 任一匹配)就把 cookie 刷新为
220
223
  // 当前 AUTH_TOKEN——服务端重启改了 PI_WEB_TOKEN 后,旧 cookie 经一次正确的
221
224
  // ?token= 进入即被重新同步,无需用户清缓存(issue #71)。
225
+ // Secure 只在 TLS 连接上加:常加会让明文 HTTP(默认 loopback)收不到 cookie。
226
+ const secure = isTlsRequest(req);
222
227
  if (ok) {
223
228
  if (cookie !== encodeURIComponent(AUTH_TOKEN)) {
224
- res.setHeader("Set-Cookie", `pi_web_token=${encodeURIComponent(AUTH_TOKEN)}; Path=/; HttpOnly; SameSite=Strict; Max-Age=31536000`);
229
+ res.setHeader("Set-Cookie", buildPiWebTokenCookie(encodeURIComponent(AUTH_TOKEN), 31536000, secure));
225
230
  }
226
231
  }
227
232
  else if (cookie) {
228
233
  // 请求带的 cookie 已是失效旧值(服务端口令已更换)——立即让其过期,
229
234
  // 避免浏览器被残留 cookie 卡死一年(本来也不该再信任它鉴权)。
230
- res.setHeader("Set-Cookie", "pi_web_token=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0");
235
+ // Secure 与非 Secure 在浏览器里是两个独立 cookie:只清一种会因种植时的
236
+ // 协议不同而残留,所以两种属性组合各发一遍(HTTP 下 Secure 那条被忽略,无害)。
237
+ res.setHeader("Set-Cookie", [buildPiWebTokenCookie("", 0, false), buildPiWebTokenCookie("", 0, true)]);
231
238
  }
232
239
  if (req.path === "/api/health" || ok) {
233
240
  next();
@@ -253,6 +260,7 @@ const ORIGIN = launchOrigin();
253
260
  const SERVICE_INFO = toServiceInfo(ORIGIN);
254
261
  /** PI_WEB_TABS: the tabs this instance offers. null = all of them, as before. */
255
262
  const TABS = parseTabs();
263
+ registerFileTransferRoutes(app, (clientId) => service.get(clientId)?.cwd);
256
264
  app.get("/api/health", (_req, res) => {
257
265
  res.json({ ok: true, piVersion: VERSION, cwd: CWD, pid: process.pid, engine: ENGINE });
258
266
  });
@@ -352,6 +360,7 @@ app.get("/api/file", async (req, res) => {
352
360
  */
353
361
  app.get("/api/preview/*", async (req, res) => {
354
362
  try {
363
+ // SAFETY: Express wildcard captures are indexed string route parameters.
355
364
  const captured = String(req.params[0] ?? "");
356
365
  const ABS_MARKER = "__abs__/";
357
366
  const cid = typeof req.query.clientId === "string" ? req.query.clientId : "";
@@ -501,6 +510,7 @@ const PLUGINS_DIR = join(DATA_DIR, "plugins");
501
510
  // /plugins-api/<id>/inbox。PI_WEB_TOKEN 鉴权(上方 app.use)自动覆盖;
502
511
  // 响应已在前面过了 express.json。注意不要在此 catch-all 里消费 body。
503
512
  app.all(["/plugins-api/:id/*", "/plugins-api/:id"], (req, res) => {
513
+ // SAFETY: Express wildcard captures are strings indexed by 0.
504
514
  const rest = String(req.params[0] ?? "");
505
515
  pluginMgr.handleHttp(String(req.params.id ?? ""), req.method, rest, req, res);
506
516
  });
@@ -574,7 +584,7 @@ app.use((req, res, next) => {
574
584
  proxyHttp(hit, req, res);
575
585
  });
576
586
  app.get("/plugins/:id/client/*", (req, res) => {
577
- // express 4 的通配参数在运行时落在 params[0],但类型声明里没有 —— 显式取
587
+ // SAFETY: express 4 的通配参数在运行时落在 params[0],但类型声明里没有 -- 显式取
578
588
  const rest = String(req.params[0] ?? "");
579
589
  // 特权 DOM 门禁:声明了 dom 能力的插件,其 bundle 需用户逐个授权后才下发
580
590
  // (同源 bundle 技术上拦不住 DOM 访问,门只能放在这里;见 server/plugin-dom.ts)。
@@ -667,9 +677,10 @@ else if (process.env[RESTART_CHILD_ENV]) {
667
677
  const httpServer = createServer(app);
668
678
  const wss = new WebSocketServer({
669
679
  noServer: true,
670
- // 上调入站帧上限:右键上传走单帧 base64(100MB 文件 → ~133MB 帧),
671
- // ws 默认 maxPayload 只有 100MB,超限会直接断连。
672
- maxPayload: 256 * 1024 * 1024,
680
+ // 右键上传走单帧 base64(100MB 文件 → ~133MB 文本):上限与
681
+ // files-service 的上传 cap 对齐(base64 上限 + 1MB 包络余量),
682
+ // 超限帧由 ws 层直接拒收,不进 handler 再分配 Buffer。
683
+ maxPayload: WS_MAX_PAYLOAD_BYTES,
673
684
  // Per-message deflate: big-session snapshots serialize to multi-MB JSON
674
685
  // strings; wire-level compression cuts that several-fold. threshold keeps
675
686
  // tiny messages (notices/heartbeats) uncompressed to save CPU.
@@ -832,6 +843,8 @@ const heartbeatTimer = setInterval(() => {
832
843
  }
833
844
  }
834
845
  }, HEARTBEAT_INTERVAL_MS);
846
+ // Unref'd so it never blocks exit: heartbeat alone must not hold the event loop open.
847
+ heartbeatTimer.unref?.();
835
848
  // 引擎分发:PI_WEB_ENGINE=dsh 时使用 DeepSeek Harness 引擎(server/dsh/),
836
849
  // 默认 pi 引擎。同一 wire 协议,前端无感知(ready/health 携带 engine 字段)。
837
850
  import { DshAgentService } from "./dsh/dsh-agent-service.js";
@@ -953,25 +966,60 @@ pluginMgr.permissionRequester = (pluginId, req) => new Promise((resolve) => {
953
966
  });
954
967
  pluginMgr.onPermGrantsChanged = () => pushPluginPermissions();
955
968
  // 内置定时任务(issue #184):全局 <dataDir>/scheduler-tasks.json,TTL 与
956
- // client-state 同级;执行走标准 pi 引擎的无头伪客户端(chatFromScheduler),
957
- // DSH 引擎无该方法时 executor 回 not-supported(历史里记失败,不炸进程)。
969
+ // client-state 同级;Agent 工具建的任务优先唤醒发起对话(issue #193:
970
+ // wakeConversation steer 投递,不切用户当前对话),对话不在了再回落无头伪
971
+ // 客户端(chatFromScheduler);单次任务触发后自动删除。DSH 引擎无这俩方法时
972
+ // executor 回 not-supported(历史里记失败,不炸进程)。
958
973
  const scheduler = new SchedulerStore(DATA_DIR, {
959
974
  executor: async (task) => {
975
+ let result;
960
976
  try {
961
977
  const svc = service;
962
- if (typeof svc.chatFromScheduler !== "function")
963
- return { ok: false, error: "当前引擎不支持定时任务(仅标准 pi 引擎)" };
964
- return await svc.chatFromScheduler({
965
- id: task.id,
966
- cwd: task.cwd,
967
- prompt: task.prompt,
968
- model: task.model,
969
- thinkingLevel: task.thinkingLevel,
970
- });
978
+ if (typeof svc.chatFromScheduler !== "function" && typeof svc.wakeConversation !== "function") {
979
+ result = { ok: false, error: "当前引擎不支持定时任务(仅标准 pi 引擎)" };
980
+ }
981
+ else {
982
+ // 发起对话还在 → steer 唤醒它(报告直接落原对话);不在了 → 无头执行。
983
+ const target = String(task.conversationId ?? "").trim();
984
+ if (target && typeof svc.wakeConversation === "function") {
985
+ const w = await svc.wakeConversation(target, `[定时任务 ${task.name}] ${task.prompt}`);
986
+ if (w.ok) {
987
+ result = { ok: true, conversationId: w.conversationId };
988
+ }
989
+ else {
990
+ result = await svc.chatFromScheduler({
991
+ id: task.id,
992
+ cwd: task.cwd,
993
+ prompt: task.prompt,
994
+ model: task.model,
995
+ thinkingLevel: task.thinkingLevel,
996
+ });
997
+ }
998
+ }
999
+ else {
1000
+ result = await svc.chatFromScheduler({
1001
+ id: task.id,
1002
+ cwd: task.cwd,
1003
+ prompt: task.prompt,
1004
+ model: task.model,
1005
+ thinkingLevel: task.thinkingLevel,
1006
+ });
1007
+ }
1008
+ }
971
1009
  }
972
1010
  catch (err) {
973
- return { ok: false, error: err.message };
1011
+ result = { ok: false, error: err.message };
1012
+ }
1013
+ // 单次任务:触发一次后自动删除(历史随任务一起走,成败已由上面的 notify 播报)。
1014
+ if (task.oneShot) {
1015
+ try {
1016
+ scheduler.remove(task.id);
1017
+ }
1018
+ catch {
1019
+ // 删除失败不影响已记录的执行结果
1020
+ }
974
1021
  }
1022
+ return result;
975
1023
  },
976
1024
  onChange: () => pushSchedulerTasks(),
977
1025
  notify: (level, text, textEn) => pushNoticeToAll(level, text, textEn ?? text),
@@ -1052,6 +1100,11 @@ service.pluginCommandsProvider = () => pluginMgr.listCommands();
1052
1100
  pluginMgr.onBgTasksChanged = () => service.refreshBackgroundServers();
1053
1101
  service.pluginBgTasksProvider = () => pluginMgr.bgTasks();
1054
1102
  service.pluginStopBgTask = (taskId) => pluginMgr.stopPluginBgTask(taskId);
1103
+ // 定时任务 Agent 工具的数据源(schedule_task/list/cancel):标准 pi 引擎的
1104
+ // AgentService 才有 schedulerStore 字段,DSH service 没有 —— 有才设。
1105
+ if ("schedulerStore" in service) {
1106
+ service.schedulerStore = scheduler;
1107
+ }
1055
1108
  // ---------------------------------------------------------------------------
1056
1109
  // 插件扩展点 v2(并行任务在 server/plugins.ts 加 host.conversations/prompt/
1057
1110
  // steer/abortRun/chatWait/fs.watch/scm/bash/schedule/models/onStats/onStreaming/
@@ -1065,12 +1118,12 @@ service.pluginStopBgTask = (taskId) => pluginMgr.stopPluginBgTask(taskId);
1065
1118
  // {ok:false},绝不抛错炸进程。
1066
1119
  // ---------------------------------------------------------------------------
1067
1120
  {
1121
+ // SAFETY: This compatibility bridge only assigns optional plugin hooks; consumers test their presence.
1068
1122
  const pm = pluginMgr;
1069
1123
  /** 挑一个客户端会话:标准 pi 引擎走 service.pluginClient(),DSH/未知引擎无此方法即 undefined。 */
1070
1124
  const pickClient = () => {
1071
1125
  try {
1072
- const svc = service;
1073
- return typeof svc.pluginClient === "function" ? svc.pluginClient() : undefined;
1126
+ return service instanceof AgentService ? service.pluginClient() : undefined;
1074
1127
  }
1075
1128
  catch {
1076
1129
  return undefined;
@@ -1156,6 +1209,7 @@ service.pluginStopBgTask = (taskId) => pluginMgr.stopPluginBgTask(taskId);
1156
1209
  // 标准 pi 引擎走 service.completeForPlugins;DSH/未知引擎回 {ok:false},绝不抛错。
1157
1210
  pm.llmProvider = async (pluginId, req) => {
1158
1211
  try {
1212
+ // SAFETY: Only invoked after the optional method is checked; request fields are narrowed below.
1159
1213
  const svc = service;
1160
1214
  if (typeof svc.completeForPlugins !== "function")
1161
1215
  return { ok: false, error: "当前引擎不支持 LLM 直调(仅标准 pi 引擎)" };
@@ -1315,7 +1369,7 @@ wss.on("connection", (ws) => {
1315
1369
  void cs.prompt(msg.text, msg.attachments, msg.queue);
1316
1370
  break;
1317
1371
  case "queue_remove":
1318
- cs.removeQueued(msg.kind, msg.text);
1372
+ cs.removeQueued(msg.kind, msg.text, msg.index);
1319
1373
  break;
1320
1374
  case "draft_update":
1321
1375
  cs.saveDraft?.(msg.sessionId, msg.text, msg.ts);
@@ -1462,7 +1516,7 @@ wss.on("connection", (ws) => {
1462
1516
  void cs.completePath(msg.path);
1463
1517
  break;
1464
1518
  case "make_dir":
1465
- void cs.makeDir(msg.path);
1519
+ void cs.makeDir(msg.path, msg.setAsCwd === true);
1466
1520
  break;
1467
1521
  case "check_update":
1468
1522
  void cs.checkUpdate();
@@ -1633,6 +1687,7 @@ wss.on("connection", (ws) => {
1633
1687
  cs.pushSettings();
1634
1688
  break;
1635
1689
  case "set_settings":
1690
+ // SAFETY: Both dispatch engines validate the explicitly enumerated settings fields below.
1636
1691
  void cs.setSettings({
1637
1692
  promptMode: msg.promptMode,
1638
1693
  customSystemPrompt: msg.customSystemPrompt,
@@ -1943,8 +1998,16 @@ wss.on("connection", (ws) => {
1943
1998
  });
1944
1999
  }
1945
2000
  break;
1946
- default:
2001
+ default: {
2002
+ // 未知 type 只计数 + 节流 warn,不改变已知类型行为。
2003
+ // default 分支里 msg 已收窄成 never,type 需从宽化后取。
2004
+ const raw = msg.type;
2005
+ const name = typeof raw === "string" ? raw : String(raw);
2006
+ const r = recordUnknownWsType(name);
2007
+ if (r.warn)
2008
+ console.warn(`[ws] unknown message type "${name}" (x${r.count})`);
1947
2009
  break;
2010
+ }
1948
2011
  }
1949
2012
  };
1950
2013
  ws.on("message", (data) => {
@@ -2149,6 +2212,33 @@ async function shutdown(signal = "SIGINT") {
2149
2212
  }
2150
2213
  shuttingDown = true;
2151
2214
  console.log("\nshutting down…");
2215
+ // Windows ConPTY 兜底看门狗(PR #204 带入):主线程若死锁在 native
2216
+ // ClosePseudoConsole 里,事件循环冻结,上面的 forceExitTimer 永远触发不了 ——
2217
+ // 只能靠外部进程收尾。超时取 forceExit + 余量(只在进程内兜底失效时才开火);
2218
+ // 正常退出在 finally 里取消,避免误杀 + PID 复用竞态。
2219
+ // cmd.exe 是无 GUI 的控制台宿主,windowsHide 藏的是它一闪而过的黑窗口。
2220
+ let disarmKiller = null;
2221
+ if (process.platform === "win32") {
2222
+ try {
2223
+ const { spawn } = await import("node:child_process");
2224
+ const killer = spawn("cmd.exe", [
2225
+ "/c",
2226
+ `timeout /t ${Math.ceil((SHUTDOWN_FORCE_EXIT_MS + 5000) / 1000)} /nobreak >nul && taskkill /F /PID ${process.pid}`,
2227
+ ], { detached: true, stdio: "ignore", windowsHide: true });
2228
+ killer.unref();
2229
+ disarmKiller = () => {
2230
+ try {
2231
+ killer.kill();
2232
+ }
2233
+ catch {
2234
+ // 已退出/杀不掉:看门狗使命本来就是收尾,无需上报
2235
+ }
2236
+ };
2237
+ }
2238
+ catch {
2239
+ // 看门狗起不来:回落进程内 forceExitTimer,不阻断关机
2240
+ }
2241
+ }
2152
2242
  const forceExitTimer = setTimeout(() => {
2153
2243
  console.error("shutdown 超时仍未完成,强制退出…");
2154
2244
  process.exit(1);
@@ -2186,6 +2276,7 @@ async function shutdown(signal = "SIGINT") {
2186
2276
  }
2187
2277
  finally {
2188
2278
  clearTimeout(forceExitTimer);
2279
+ disarmKiller?.();
2189
2280
  process.exit(code);
2190
2281
  }
2191
2282
  }
@@ -105,7 +105,9 @@ export class MarkerService {
105
105
  return structuredClone(fromBranch);
106
106
  }
107
107
  }
108
- catch { }
108
+ catch {
109
+ // best-effort:分支不可读 → 回落 mem/init(快照损坏不阻断对话)。
110
+ }
109
111
  }
110
112
  const mem = this.memFor(convId, namespace);
111
113
  if (mem !== undefined)
@@ -872,7 +872,9 @@ export class PluginManager {
872
872
  try {
873
873
  this.onBgTasksChanged?.();
874
874
  }
875
- catch { }
875
+ catch {
876
+ // best-effort:可选 UI 刷新,失败忽略。
877
+ }
876
878
  return true;
877
879
  }
878
880
  return false;
@@ -1686,7 +1688,9 @@ export class PluginManager {
1686
1688
  try {
1687
1689
  t.stop?.();
1688
1690
  }
1689
- catch { }
1691
+ catch {
1692
+ // best-effort:反激活清理,单个任务失败不阻断。
1693
+ }
1690
1694
  }
1691
1695
  }
1692
1696
  this.pluginBgTasks.clear();
@@ -1875,7 +1879,9 @@ export class PluginManager {
1875
1879
  try {
1876
1880
  apiVersion = Number(JSON.parse(readFileSync(join(dir, "manifest.json"), "utf8")).apiVersion ?? 1) || 1;
1877
1881
  }
1878
- catch { }
1882
+ catch {
1883
+ // best-effort:无 manifest/JSON 坏 → 按 apiVersion 1 处理。
1884
+ }
1879
1885
  if (apiVersion > PLUGIN_API_VERSION) {
1880
1886
  const msg = pick(l, `插件要求宿主 API v${apiVersion},当前宿主 v${PLUGIN_API_VERSION} —— 请升级 pi-web-ui`, `Plugin requires host API v${apiVersion} but the host is v${PLUGIN_API_VERSION} — please upgrade pi-web-ui`, "plugins.host.api.mismatch", { apiVersion, PLUGIN_API_VERSION });
1881
1887
  console.error(`[plugin:${info.id}] ${msg}`);
@@ -2464,7 +2470,9 @@ export class PluginManager {
2464
2470
  try {
2465
2471
  this.onBgTasksChanged?.();
2466
2472
  }
2467
- catch { }
2473
+ catch {
2474
+ // best-effort:可选 UI 刷新,失败忽略。
2475
+ }
2468
2476
  };
2469
2477
  fire();
2470
2478
  return {
@@ -16,3 +16,19 @@ export function removeFirstOccurrence(list, text) {
16
16
  return [...list];
17
17
  return [...list.slice(0, index), ...list.slice(index + 1)];
18
18
  }
19
+ /**
20
+ * 按气泡下标移除一条排队消息(✕ 对应的是「第几个气泡」,不是「哪段文本」)。
21
+ * `index` 越界、非整数、或该位置文本与 `text` 对不上(点击与执行之间队列
22
+ * 已变化——有条消息刚送达或新入队)时,回落到 `removeFirstOccurrence` 的文本匹配,
23
+ * 保持旧客户端(只发 text)行为不变。不修改入参。
24
+ */
25
+ export function removeQueuedByIndexOrText(list, text, index) {
26
+ if (typeof index === "number" &&
27
+ Number.isInteger(index) &&
28
+ index >= 0 &&
29
+ index < list.length &&
30
+ list[index] === text) {
31
+ return [...list.slice(0, index), ...list.slice(index + 1)];
32
+ }
33
+ return removeFirstOccurrence(list, text);
34
+ }
@@ -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
+ }
@@ -76,6 +76,9 @@ export function normalizeSchedulerInput(input, now = Date.now()) {
76
76
  throw new Error("模型格式非法(应为 provider/id)");
77
77
  const thinkingLevel = String(input.thinkingLevel ?? "").trim();
78
78
  const catchUp = input.catchUp === "once" ? "once" : "skip";
79
+ const conversationId = String(input.conversationId ?? "")
80
+ .trim()
81
+ .slice(0, 128);
79
82
  return {
80
83
  id,
81
84
  name,
@@ -88,6 +91,8 @@ export function normalizeSchedulerInput(input, now = Date.now()) {
88
91
  model,
89
92
  thinkingLevel,
90
93
  catchUp,
94
+ conversationId,
95
+ oneShot: input.oneShot === true,
91
96
  createdAt: now,
92
97
  updatedAt: now,
93
98
  };
@@ -224,6 +229,8 @@ export class SchedulerStore {
224
229
  model: r.model,
225
230
  thinkingLevel: r.thinkingLevel,
226
231
  catchUp: r.catchUp,
232
+ conversationId: r.conversationId,
233
+ oneShot: r.oneShot,
227
234
  });
228
235
  task.createdAt = typeof r.createdAt === "number" && Number.isFinite(r.createdAt) ? r.createdAt : Date.now();
229
236
  task.updatedAt =
@@ -280,6 +287,8 @@ export class SchedulerStore {
280
287
  model: t.model,
281
288
  thinkingLevel: t.thinkingLevel,
282
289
  catchUp: t.catchUp,
290
+ conversationId: t.conversationId,
291
+ oneShot: t.oneShot,
283
292
  createdAt: t.createdAt,
284
293
  updatedAt: t.updatedAt,
285
294
  nextFire: !t.enabled ? null : (this.nextFire.get(t.id) ?? computeNextFire(t, Math.max(now, t.updatedAt))),