pi-web-ui 0.98.0 → 0.100.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +85 -5
  2. package/README.md +2 -1
  3. package/README.zh-CN.md +2 -1
  4. package/bin/pi-web-ui.mjs +174 -36
  5. package/dist/server/agent-service.js +1169 -152
  6. package/dist/server/approval-rules.js +95 -23
  7. package/dist/server/attachments.js +55 -0
  8. package/dist/server/bg-servers.js +82 -2
  9. package/dist/server/claim-files-tool.js +4 -4
  10. package/dist/server/client-state.js +41 -0
  11. package/dist/server/compact-context-tool.js +10 -9
  12. package/dist/server/conversation-read-tool.js +7 -8
  13. package/dist/server/conversation-touches.js +19 -0
  14. package/dist/server/delegate-task.js +10 -14
  15. package/dist/server/dsh/dsh-agent-service.js +116 -12
  16. package/dist/server/edit-soft-tool.js +10 -12
  17. package/dist/server/eval-tool.js +26 -6
  18. package/dist/server/goal-evidence.js +173 -0
  19. package/dist/server/goal-service.js +78 -15
  20. package/dist/server/hashline-engine.js +198 -31
  21. package/dist/server/index.js +55 -9
  22. package/dist/server/load-tools-tool.js +100 -0
  23. package/dist/server/lsp-tool.js +10 -16
  24. package/dist/server/marker-service.js +53 -12
  25. package/dist/server/markers/builtins/action.js +108 -0
  26. package/dist/server/markers/index.js +4 -1
  27. package/dist/server/model-enrich.js +2 -0
  28. package/dist/server/patch-remote-catalog.js +28 -10
  29. package/dist/server/patch-tool.js +74 -38
  30. package/dist/server/plan-manager.js +71 -30
  31. package/dist/server/plan-mode.js +7 -6
  32. package/dist/server/plugin-api-catalog.js +10 -3
  33. package/dist/server/plugin-conversation-view.js +47 -0
  34. package/dist/server/plugins.js +113 -26
  35. package/dist/server/present-files-tool.js +10 -11
  36. package/dist/server/preset-fields.js +693 -0
  37. package/dist/server/preset-share.js +1178 -0
  38. package/dist/server/prompt-composer.js +23 -9
  39. package/dist/server/protocol-version.js +1 -1
  40. package/dist/server/read-tool.js +8 -10
  41. package/dist/server/resolve-global-sdk.js +80 -18
  42. package/dist/server/schedule-agent-tool.js +147 -146
  43. package/dist/server/sdk-origin.js +125 -37
  44. package/dist/server/settings-service.js +103 -84
  45. package/dist/server/skill-tool.js +3 -4
  46. package/dist/server/subagents.js +15 -22
  47. package/dist/server/terminals.js +29 -39
  48. package/dist/server/tool-approval.js +3 -1
  49. package/dist/server/tool-manager.js +63 -27
  50. package/dist/server/tool-prompt-overrides.js +158 -0
  51. package/dist/server/tool-prompts.js +42 -0
  52. package/dist/server/tool-signature.js +104 -0
  53. package/dist/server/update-check.js +0 -15
  54. package/dist/server/workspace-snapshot.js +42 -11
  55. package/package.json +5 -3
  56. package/plugin-sdk/README.md +8 -4
  57. package/plugin-sdk/import-check.mjs +210 -0
  58. package/plugin-sdk/index.d.ts +4 -1
  59. package/plugin-sdk/index.mjs +1 -0
  60. package/plugins/catalog.json +33 -2
  61. package/themes/zhupi-dark.css +1 -1
  62. package/themes/zhupi.css +1 -1
  63. package/web/dist/assets/{TerminalPanel-C88r3r3Q.js → TerminalPanel-C3I1Mc-C.js} +2 -2
  64. package/web/dist/assets/index-B-E2EM_0.css +1 -0
  65. package/web/dist/assets/index-BYumAaGi.js +379 -0
  66. package/web/dist/index.html +2 -2
  67. package/web/dist/sw.js +1 -1
  68. package/web/dist/assets/index-2jDtjHvW.css +0 -1
  69. package/web/dist/assets/index-BjdK7s1M.js +0 -368
@@ -184,14 +184,28 @@ function buildContextText(files, lang = "en") {
184
184
  "</project_context>",
185
185
  ].join("\n");
186
186
  }
187
- /** 工具列表块:工具列表 + "In addition…" 句。 */
188
- function buildToolsText(inputs) {
189
- const visible = inputs.selectedTools.filter((n) => !!inputs.toolSnippets[n]);
190
- const toolsList = visible.length > 0 ? visible.map((n) => `- ${n}: ${inputs.toolSnippets[n]}`).join("\n") : "(none)";
191
- return [
192
- `Available tools:\n${toolsList}`,
193
- "In addition to the tools above, you may have access to other custom tools depending on the project.",
194
- ].join("\n\n");
187
+ /** 工具列表块:工具列表(延迟加载时列完整目录)+ 恒定提示 + "In addition…" 句。
188
+ *
189
+ * 延迟加载下这里**只依赖目录本身**(不依赖「哪些已加载」):系统提示词是供应商
190
+ * 前缀缓存的第一段,只要它不变,加载工具造成的只是 tools 数组的追加(前缀不变的
191
+ * 增量),缓存才不会被我们自已打坏。 */
192
+ function buildToolsText(inputs, lang) {
193
+ const listed = inputs.lazy ? (inputs.catalogTools ?? inputs.selectedTools) : inputs.selectedTools;
194
+ const visible = listed.filter((n) => !!inputs.toolSnippets[n]);
195
+ const toolsList = visible.length > 0
196
+ ? visible
197
+ .map((n) => {
198
+ const sig = inputs.toolSignatures?.[n] ? ` ${inputs.toolSignatures[n]}` : "";
199
+ return `- ${n}:${sig} ${inputs.toolSnippets[n]}`;
200
+ })
201
+ .join("\n")
202
+ : "(none)";
203
+ const parts = [`Available tools:\n${toolsList}`];
204
+ if (inputs.lazy) {
205
+ parts.push(pick(lang, "上表里有一部分工具的**参数 schema 尚未附加**;调用前先用 `load_tools` 把它们的名字传进来,即可拿到完整参数(本对话后续轮次都能继续用)。尚不在你工具列表里的,一律先 load_tools。", "Some tools above do NOT have their parameter schema attached yet. Before calling one, pass its name to `load_tools` to attach the full schema for the rest of this conversation. Anything not in your function list must be loaded first.", "prompt.tools.lazy"));
206
+ }
207
+ parts.push("In addition to the tools above, you may have access to other custom tools depending on the project.");
208
+ return parts.join("\n\n");
195
209
  }
196
210
  /** 工具 schema 只读文本(设置面板「查看当前完整提示词」里展示发给模型的完整
197
211
  * 工具定义:name + description + parameters JSON Schema)。 */
@@ -220,7 +234,7 @@ export function resolveSectionTexts(inputs) {
220
234
  soul = getServerBlock(lang, "prompt.soul", BUILTIN_SOUL_ZH.split("\n"), BUILTIN_SOUL.split("\n")).join("\n");
221
235
  return {
222
236
  soul,
223
- tools: buildToolsText(inputs),
237
+ tools: buildToolsText(inputs, lang),
224
238
  guidelines: buildGuidelinesText(inputs),
225
239
  pi_docs: buildPiDocsText(inputs.piReadme, inputs.piDocs, inputs.piExamples, lang),
226
240
  append: inputs.appendFiles.join("\n\n"),
@@ -8,4 +8,4 @@
8
8
  * its own copy in web/src/protocol-version.ts; scripts/check-protocol-sync.mjs
9
9
  * verifies the two never drift.
10
10
  */
11
- export const PROTOCOL_VERSION = 22;
11
+ export const PROTOCOL_VERSION = 26;
@@ -29,7 +29,7 @@
29
29
  import { stat } from "node:fs/promises";
30
30
  import { homedir } from "node:os";
31
31
  import { isAbsolute, join, resolve as nodeResolve } from "node:path";
32
- import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, createLsToolDefinition, createReadToolDefinition, defineTool, } from "@earendil-works/pi-coding-agent";
32
+ import { createLsToolDefinition, createReadToolDefinition, defineTool, } from "@earendil-works/pi-coding-agent";
33
33
  import { Type } from "typebox";
34
34
  import { pick } from "./i18n.js";
35
35
  const UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;
@@ -87,8 +87,10 @@ export function prepareReadArguments(raw) {
87
87
  return args;
88
88
  }
89
89
  /** Directory support note appended to any read definition (definitions are English-only). */
90
- const DIR_DESCRIPTION_NOTE = "Also accepts a directory path: its entries are then listed instead of file contents (one entry per line, directories suffixed with '/'); in that case `limit` caps the number of entries and `offset` is ignored.";
91
- const DIR_GUIDELINE = "Use read on a directory to list its entries — no need to shell out to `ls`";
90
+ const DIR_DESCRIPTION_NOTE = "Also accepts a directory path: its entries are listed instead of contents (one per line, directories suffixed with '/'); `limit` then caps entries and `offset` is ignored.";
91
+ /** 内置基底专用:`file_path` 别名只在没有扩展同名工具时由本模块提供。 */
92
+ const FILE_PATH_ALIAS_NOTE = "Also accepts `file_path` as an alias of `path`.";
93
+ const DIR_GUIDELINE = "No need to shell out to `ls`: read lists a directory's entries";
92
94
  /**
93
95
  * 两条路(内置基底 / 扩展基底)共用的执行体:先判「路径是不是目录」—— 是就复用 SDK 的
94
96
  * ls 列条目(排序/`/` 后缀/截断提示口径一致),否则把请求转发给基底实现。
@@ -147,13 +149,9 @@ export function makeReadDirTool(fallbackCwd, options = {}) {
147
149
  const getLang = options.getLang ?? (() => "en");
148
150
  return defineTool({
149
151
  ...base,
150
- description: `${base.description} Also accepts \`file_path\` as an alias of \`path\`. ` +
151
- "If the path is a directory, its entries are listed instead (one per line, directories suffixed with '/'); `limit` caps the entries and `offset` is ignored.",
152
- promptSnippet: "Read file contents (a directory path lists its entries)",
153
- promptGuidelines: [
154
- ...(base.promptGuidelines ?? []),
155
- "Use read on a directory to list its entries — no need to shell out to `ls`",
156
- ],
152
+ description: `${base.description} ${FILE_PATH_ALIAS_NOTE} ${DIR_DESCRIPTION_NOTE}`,
153
+ promptSnippet: "file contents by path (a directory lists its entries)",
154
+ promptGuidelines: [...(base.promptGuidelines ?? []), DIR_GUIDELINE],
157
155
  parameters: readDirSchema,
158
156
  prepareArguments: prepareReadArguments,
159
157
  async execute(toolCallId, params, signal, onUpdate, ctx) {
@@ -25,33 +25,79 @@
25
25
  * 让服务起不来。它必须在任何 SDK 静态 import **之前**被加载(`--import <本文件>`,
26
26
  * 或前台启动时在 import 服务入口之前先 import 它)。
27
27
  */
28
+ import { existsSync, readFileSync } from "node:fs";
28
29
  import { registerHooks } from "node:module";
29
- import { dirname } from "node:path";
30
- import { pathToFileURL } from "node:url";
30
+ import { dirname, join } from "node:path";
31
+ import { fileURLToPath, pathToFileURL } from "node:url";
31
32
  import { compareVersions, sdkCopies } from "./sdk-origin.js";
32
33
  const PKG = "@earendil-works/pi-coding-agent";
33
34
  /** 显式强制自带副本的取值(旧默认;可复现、CI 覆盖的那份)。 */
34
35
  const BUNDLED_MODES = new Set(["bundled", "0", "off", "false", "no"]);
36
+ /**
37
+ * 找出传入副本列表中的随包自带副本(如果有的话)。
38
+ * 自带副本必须位于 pi-web-ui 自身包根下的 node_modules/@earendil-works/pi-coding-agent/package.json。
39
+ */
40
+ export function findBundledCopy(copies, fromFile = import.meta.url) {
41
+ const filePath = fromFile.startsWith("file:") ? fileURLToPath(fromFile) : fromFile;
42
+ let cur = dirname(filePath);
43
+ let pkgRoot = null;
44
+ for (let i = 0; i < 5; i++) {
45
+ const pj = join(cur, "package.json");
46
+ if (existsSync(pj)) {
47
+ try {
48
+ const info = JSON.parse(readFileSync(pj, "utf8"));
49
+ if (info?.name === "pi-web-ui") {
50
+ pkgRoot = cur;
51
+ break;
52
+ }
53
+ }
54
+ catch { }
55
+ }
56
+ const p = dirname(cur);
57
+ if (p === cur)
58
+ break;
59
+ cur = p;
60
+ }
61
+ if (!pkgRoot) {
62
+ return copies[0] ?? null;
63
+ }
64
+ const expectedBundledPath = join(pkgRoot, "node_modules", PKG, "package.json").replace(/\\/g, "/");
65
+ return copies.find((c) => c.path.replace(/\\/g, "/") === expectedBundledPath) ?? null;
66
+ }
35
67
  /**
36
68
  * 该用哪一份对外解析(纯函数,便于单测)。
37
- * `copies` 按 Node 的解析顺序([0] = 自带的、无钩子时实际会被用到的),
69
+ * `copies` 按 Node 的解析顺序,`bundledCopy` 为识别到的随包自带副本(null = 无自带副本)。
38
70
  * 返回 null = 保持默认(用自带副本兜底)。
39
71
  */
40
- export function pickGlobalSdk(copies, mode) {
72
+ export function pickGlobalSdk(copies, mode, bundledCopy = copies[0] ?? null) {
41
73
  if (BUNDLED_MODES.has((mode ?? "global").trim().toLowerCase()))
42
74
  return null;
43
- const bundled = copies[0];
44
75
  // 显式透传的宿主 SDK 路径(如 extensions/webui.ts 宿主传递,issue #482):若不降级优先选用
45
76
  if (process.env.PI_WEB_SDK_DIR) {
46
77
  const hostCopy = copies.find((c) => dirname(c.path) === process.env.PI_WEB_SDK_DIR);
47
- if (hostCopy && (!bundled || compareVersions(hostCopy.version, bundled.version) >= 0)) {
78
+ if (hostCopy && (!bundledCopy || compareVersions(hostCopy.version, bundledCopy.version) >= 0)) {
48
79
  return hostCopy;
49
80
  }
50
81
  }
51
- // 只考虑祖先链上**严格更新**的副本,多份取版本最高的(旧的/同版本的都不折腾)。
82
+ // 如果没有随包自带副本(例如 pnpm 隔离安装未包含可选依赖,或轻量部署,issue #562):
83
+ // 机器上只要发现可用副本就必须选用,否则 Node 无法导入 SDK 会报错崩溃。
84
+ if (!bundledCopy) {
85
+ if (copies.length === 0)
86
+ return null;
87
+ let best = copies[0];
88
+ for (const copy of copies.slice(1)) {
89
+ if (compareVersions(copy.version, best.version) > 0) {
90
+ best = copy;
91
+ }
92
+ }
93
+ return best;
94
+ }
95
+ // 存在自带副本:只考虑比自带副本**严格更新**的外部副本,多份取版本最高的(旧的/同版本的都不折腾)。
52
96
  let best = null;
53
- for (const copy of copies.slice(1)) {
54
- if ((!bundled || compareVersions(copy.version, bundled.version) > 0) &&
97
+ for (const copy of copies) {
98
+ if (copy.path === bundledCopy.path)
99
+ continue;
100
+ if (compareVersions(copy.version, bundledCopy.version) > 0 &&
55
101
  (!best || compareVersions(copy.version, best.version) > 0)) {
56
102
  best = copy;
57
103
  }
@@ -62,21 +108,37 @@ export function pickGlobalSdk(copies, mode) {
62
108
  export function registerGlobalSdkPreference(mode = process.env.PI_WEB_SDK, fromFile = import.meta.url) {
63
109
  try {
64
110
  const copies = sdkCopies(fromFile);
65
- const chosen = pickGlobalSdk(copies, mode);
111
+ const bundled = findBundledCopy(copies, fromFile);
112
+ const chosen = pickGlobalSdk(copies, mode, bundled);
66
113
  if (!chosen)
67
114
  return null;
68
115
  registerHooks({
69
116
  resolve(specifier, context, nextResolve) {
70
- if (specifier !== PKG)
71
- return nextResolve(specifier, context);
72
- // 以目标副本的 package.json 为父重新解析:Node 从那里往上找,
73
- // 第一个命中的就是它自己 —— 等价于「从那个包内部 import 自己」。
74
- try {
75
- return nextResolve(specifier, { ...context, parentURL: pathToFileURL(chosen.path).href });
117
+ if (specifier === PKG) {
118
+ // 以目标副本的 package.json 为父重新解析:Node 从那里往上找,
119
+ // 第一个命中的就是它自己 —— 等价于「从那个包内部 import 自己」。
120
+ try {
121
+ return nextResolve(specifier, { ...context, parentURL: pathToFileURL(chosen.path).href });
122
+ }
123
+ catch {
124
+ return nextResolve(specifier, context);
125
+ }
76
126
  }
77
- catch {
78
- return nextResolve(specifier, context);
127
+ if (specifier === "typebox") {
128
+ try {
129
+ return nextResolve(specifier, context);
130
+ }
131
+ catch {
132
+ // 本地缺少 typebox(如 pnpm 隔离安装)时,从已选中的 pi SDK 目录解析(issue #562)
133
+ try {
134
+ return nextResolve(specifier, { ...context, parentURL: pathToFileURL(chosen.path).href });
135
+ }
136
+ catch {
137
+ return nextResolve(specifier, context);
138
+ }
139
+ }
79
140
  }
141
+ return nextResolve(specifier, context);
80
142
  },
81
143
  });
82
144
  return chosen;
@@ -6,10 +6,12 @@
6
6
  // AI 被用户要求“每小时检查一次”“半小时后提醒我”时手里没有工具,只能用
7
7
  // sleep 死循环假装答应(休眠的会话根本推不回消息)。
8
8
  //
9
- // 本文件注册三个标准 pi 引擎 customTool(DSH 引擎无 customTool 注册面,不接):
10
- // schedule_task → 建任务(默认绑定发起对话+单次,用熟即删);
11
- // schedule_list → 看全部任务(含下次触发/上次结果);
12
- // schedule_cancel → 按 id 删任务。
9
+ // 本文件注册一个标准 pi 引擎 customTool(DSH 引擎无 customTool 注册面,不接):
10
+ // schedule(action="create") → 建任务(默认绑定发起对话+单次,用熟即删);
11
+ // schedule(action="list") → 看全部任务(含下次触发/上次结果);
12
+ // schedule(action="cancel") → 按 id 删任务。
13
+ // (历史上是 schedule_task / schedule_list / schedule_cancel 三个独立工具,已合并为
14
+ // 单 action 工具以减少工具条目与上下文开销;旧工具名仍在持久化配置迁移里兼容。)
13
15
  // 到期执行走 index.ts 的 executor:目标对话还在 → steer 语义唤醒它(不切用户
14
16
  // 当前对话);不在了(关闭/重启)→ 回落原有无头执行;单次任务触发后自动删除。
15
17
  //
@@ -19,7 +21,7 @@
19
21
  import { defineTool } from "@earendil-works/pi-coding-agent";
20
22
  import { Type } from "typebox";
21
23
  import { pick } from "./i18n.js";
22
- import { SCHEDULE_CANCEL_TOOL_NAME, SCHEDULE_LIST_TOOL_NAME, SCHEDULE_TASK_TOOL_NAME } from "./tool-manager.js";
24
+ import { SCHEDULE_TOOL_NAME } from "./tool-manager.js";
23
25
  import { computeNextFire, describeIntervalMs, SCHEDULER_MIN_INTERVAL_MS, SchedulerValidationError, } from "./scheduler-tasks.js";
24
26
  import { parseCronSpec } from "./plugin-schedule.js";
25
27
  /** 用户写法 → 调度规格。纯函数,可单测。
@@ -97,163 +99,162 @@ function taskLine(t, lang) {
97
99
  : "";
98
100
  return `• ${t.id} · ${t.name} · ${when} · ${state}${once}${target} · ${lang === "zh" ? "下次" : "next"} ${fmtTime(t.nextFire, lang)}${last}`;
99
101
  }
100
- export function makeScheduleTools(host, ownerConversationId, lang) {
102
+ export const SCHEDULE_ACTIONS = ["create", "list", "cancel"];
103
+ export function makeScheduleTool(host, ownerConversationId, lang) {
101
104
  const getLang = lang ?? (() => "en");
102
105
  const text = (t, details = {}) => ({
103
106
  content: [{ type: "text", text: t }],
104
107
  details,
105
108
  });
106
109
  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: "Create a scheduled wake-up in the CURRENT conversation: at the cron time or after the delay, your prompt is delivered back into this conversation so you continue and report. " +
111
- "Use for periodic checks, delayed reminders, scheduled summaries — never sleep loops (they cannot push messages back). " +
112
- 'schedule: 5-field cron ("0 * * * *" hourly) or delay ("in 30m"); minimum 60s. One-shot by default; recurring=true repeats. ' +
113
- "Re-binds to the same session after compaction/restart; if the conversation is gone it falls back to the project's active conversation (visibly reported), headless only when none exists. " +
114
- "Manage with schedule_list / schedule_cancel.",
115
- promptSnippet: "schedule a wake-up in this conversation (cron or delay), auto-report on fire",
110
+ return defineTool({
111
+ name: SCHEDULE_TOOL_NAME,
112
+ label: "Manage scheduled wake-ups",
113
+ description: "Create, list, or cancel built-in scheduled wake-ups in the CURRENT conversation: on create your prompt is delivered " +
114
+ "back into this conversation at the cron time or after the delay you give, so you continue and report. One-shot by default; recurring=true repeats. " +
115
+ "Survives compaction/restart; if the conversation is gone it falls back to the project's active conversation when one exists, headless otherwise.",
116
+ promptSnippet: "create/list/cancel scheduled wake-ups",
117
+ promptGuidelines: [
118
+ "Use action=create for periodic checks, delayed reminders, and scheduled summaries — never sleep loops (they cannot push messages back)",
119
+ "Use action=list to inspect existing tasks and action=cancel to stop one by id",
120
+ ],
116
121
  parameters: Type.Object({
117
- schedule: Type.String({
118
- description: 'When to fire: 5-field cron ("0 * * * *" hourly) or relative delay ("in 30m", "in 1h", "30m"). Minimum 60s.',
122
+ action: Type.Unsafe({
123
+ type: "string",
124
+ enum: [...SCHEDULE_ACTIONS],
125
+ description: "The schedule action to perform.",
119
126
  }),
120
- prompt: Type.String({
121
- description: "Instruction delivered into this conversation on fire (e.g. what to check and report). Max 8000 chars.",
122
- }),
123
- label: Type.Optional(Type.String({ description: "Short name shown in the background-tasks panel. Defaults to the prompt head." })),
124
- recurring: Type.Optional(Type.Boolean({ description: "Repeat on schedule (default false = one-shot, auto-deleted after firing)." })),
127
+ schedule: Type.Optional(Type.String({
128
+ description: 'create: when to fire — 5-field cron ("0 * * * *" hourly) or relative delay ("in 30m", "in 1h", "30m"). Minimum 60s.',
129
+ })),
130
+ prompt: Type.Optional(Type.String({
131
+ description: "create: instruction delivered into this conversation on fire (e.g. what to check and report). Max 8000 chars.",
132
+ })),
133
+ label: Type.Optional(Type.String({
134
+ description: "create: short name shown in the background-tasks panel. Defaults to the prompt head.",
135
+ })),
136
+ recurring: Type.Optional(Type.Boolean({
137
+ description: "create: repeat on schedule (default false = one-shot, auto-deleted after firing).",
138
+ })),
139
+ id: Type.Optional(Type.String({ description: "cancel: task id from action=list." })),
125
140
  }),
126
141
  execute: async (_id, p) => {
142
+ const action = (p.action ?? "").trim().toLowerCase();
143
+ if (!action) {
144
+ return text(pick(getLang(), "schedule 工具缺少 action 参数(可选:create, list, cancel)。", "schedule tool requires an action parameter (one of: create, list, cancel).", "sched.action.missing"));
145
+ }
127
146
  const store = host.store();
128
147
  if (!store)
129
148
  return noStore();
130
- let parsed;
131
- try {
132
- parsed = parseScheduleSpec(p.schedule);
133
- }
134
- catch (err) {
135
- 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 ?? "") }));
136
- }
137
- if (parsed.kind === "interval" && Number(parsed.spec) < SCHEDULER_MIN_INTERVAL_MS) {
138
- return text(pick(getLang(), `间隔太短(最短 60s,防 token 烧穿)。`, `Interval too short (minimum 60s, prevents token burn).`, "sched.task.interval.too.short"));
139
- }
140
- const prompt = String(p.prompt ?? "").trim();
141
- if (!prompt) {
142
- return text(pick(getLang(), "触发指令(prompt)不能为空:写清楚触发时要检查什么、汇报什么。", "Prompt must not be empty: say what to check and report on fire.", "sched.task.empty.prompt"));
143
- }
144
- const cwd = String(host.cwd() ?? "").trim();
145
- if (!cwd) {
146
- return text(pick(getLang(), "当前没有工作目录,无法创建定时任务。", "No working directory, cannot create the scheduled task.", "sched.task.no.cwd"));
147
- }
148
- const labelRaw = typeof p.label === "string" ? p.label.trim().slice(0, 80) : "";
149
- const name = labelRaw || prompt.split("\n")[0].slice(0, 40) || "定时任务";
150
- const convId = (ownerConversationId ?? "").trim() || String(host.activeConversationId() ?? "").trim();
151
- // 稳定绑定(issue #231):owner 对话的落盘会话文件 —— 压缩/重启后靠它重认同一会话,
152
- // 内存对话 id(c1/c2…)只做首选唤醒键。宿主没实现 conversationInfo 时按原来只绑 id。
153
- let bindCwd = cwd;
154
- let bindSessionFile = "";
155
- try {
156
- const info = host.conversationInfo?.((ownerConversationId ?? "").trim() || convId || undefined);
157
- if (info) {
158
- if (String(info.cwd ?? "").trim())
159
- bindCwd = String(info.cwd).trim();
160
- bindSessionFile = String(info.sessionFile ?? "")
161
- .trim()
162
- .slice(0, 1024);
149
+ switch (action) {
150
+ case "create": {
151
+ let parsed;
152
+ try {
153
+ parsed = parseScheduleSpec(p.schedule);
154
+ }
155
+ catch (err) {
156
+ 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 ?? "") }));
157
+ }
158
+ if (parsed.kind === "interval" && Number(parsed.spec) < SCHEDULER_MIN_INTERVAL_MS) {
159
+ return text(pick(getLang(), `间隔太短(最短 60s,防 token 烧穿)。`, `Interval too short (minimum 60s, prevents token burn).`, "sched.task.interval.too.short"));
160
+ }
161
+ const prompt = String(p.prompt ?? "").trim();
162
+ if (!prompt) {
163
+ return text(pick(getLang(), "触发指令(prompt)不能为空:写清楚触发时要检查什么、汇报什么。", "Prompt must not be empty: say what to check and report on fire.", "sched.task.empty.prompt"));
164
+ }
165
+ const cwd = String(host.cwd() ?? "").trim();
166
+ if (!cwd) {
167
+ return text(pick(getLang(), "当前没有工作目录,无法创建定时任务。", "No working directory, cannot create the scheduled task.", "sched.task.no.cwd"));
168
+ }
169
+ const labelRaw = typeof p.label === "string" ? p.label.trim().slice(0, 80) : "";
170
+ const name = labelRaw || prompt.split("\n")[0].slice(0, 40) || "定时任务";
171
+ const convId = (ownerConversationId ?? "").trim() || String(host.activeConversationId() ?? "").trim();
172
+ // 稳定绑定(issue #231):owner 对话的落盘会话文件 —— 压缩/重启后靠它重认同一会话,
173
+ // 内存对话 id(c1/c2…)只做首选唤醒键。宿主没实现 conversationInfo 时按原来只绑 id。
174
+ let bindCwd = cwd;
175
+ let bindSessionFile = "";
176
+ try {
177
+ const info = host.conversationInfo?.((ownerConversationId ?? "").trim() || convId || undefined);
178
+ if (info) {
179
+ if (String(info.cwd ?? "").trim())
180
+ bindCwd = String(info.cwd).trim();
181
+ bindSessionFile = String(info.sessionFile ?? "")
182
+ .trim()
183
+ .slice(0, 1024);
184
+ }
185
+ }
186
+ catch {
187
+ /* 绑定快照尽力而为:拿不到稳定键就按原来的 id 绑定触发 */
188
+ }
189
+ const recurring = p.recurring === true;
190
+ let task;
191
+ try {
192
+ task = store.upsert({
193
+ name,
194
+ cwd: bindCwd,
195
+ kind: parsed.kind,
196
+ spec: parsed.spec,
197
+ prompt,
198
+ conversationId: convId,
199
+ sessionFile: bindSessionFile,
200
+ oneShot: !recurring,
201
+ });
202
+ }
203
+ catch (err) {
204
+ const L = getLang();
205
+ if (err instanceof SchedulerValidationError) {
206
+ return text(L === "zh" ? err.messageZh : err.messageEn);
207
+ }
208
+ return text(String(err?.message ?? err));
209
+ }
210
+ const L = getLang();
211
+ const next = computeNextFire(task, Date.now());
212
+ const head = L === "zh"
213
+ ? `定时任务已创建:${task.id}(${task.name})`
214
+ : `Scheduled task created: ${task.id} (${task.name})`;
215
+ const whenLine = L === "zh"
216
+ ? `触发:${parsed.kind === "cron" ? `cron ${parsed.spec}` : describeIntervalMs(Number(parsed.spec))},下次 ${fmtTime(next, L)}${recurring ? "(周期)" : "(单次,触发后自动删除)"}`
217
+ : `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)"}`;
218
+ const targetLine = convId
219
+ ? L === "zh"
220
+ ? `汇报:触发时自动唤醒本对话(${convId});压缩/重启后按会话文件自动重绑,原对话不在时先回落同项目活跃对话(明确提示),无存活对话才无头执行。`
221
+ : `Reports: wakes this conversation (${convId}) on fire; re-binds by session file after compaction/restart, falls back to the project's active conversation (with a visible note), headless only with no live conversation.`
222
+ : L === "zh"
223
+ ? "汇报:无头执行,报告进调度面板历史(创建时没拿到对话 id)。"
224
+ : "Reports: headless run, report in panel history (no conversation id captured at creation).";
225
+ const tail = L === "zh"
226
+ ? `取消:schedule(action="cancel", id="${task.id}"),或后台任务面板手动取消;查看:schedule(action="list")。`
227
+ : `Cancel: schedule(action="cancel", id="${task.id}"), or from the background-tasks panel; inspect: schedule(action="list").`;
228
+ return text(`${head}\n${whenLine}\n${targetLine}\n${tail}`, { task });
163
229
  }
164
- }
165
- catch {
166
- /* 绑定快照尽力而为:拿不到稳定键就按原来的 id 绑定触发 */
167
- }
168
- const recurring = p.recurring === true;
169
- let task;
170
- try {
171
- task = store.upsert({
172
- name,
173
- cwd: bindCwd,
174
- kind: parsed.kind,
175
- spec: parsed.spec,
176
- prompt,
177
- conversationId: convId,
178
- sessionFile: bindSessionFile,
179
- oneShot: !recurring,
180
- });
181
- }
182
- catch (err) {
183
- const L = getLang();
184
- if (err instanceof SchedulerValidationError) {
185
- return text(L === "zh" ? err.messageZh : err.messageEn);
230
+ case "list": {
231
+ const L = getLang();
232
+ const tasks = store.list();
233
+ if (tasks.length === 0) {
234
+ return text(pick(getLang(), '当前没有定时任务。用 schedule(action="create") 创建(cron 或 in 30m 这类延迟,最短 60s)。', 'No scheduled tasks. Create one with schedule(action="create") (cron or a delay like in 30m, minimum 60s).', "sched.list.empty"), { tasks: [] });
235
+ }
236
+ const lines = tasks.slice(0, 50).map((t) => taskLine(t, L));
237
+ const more = tasks.length > 50
238
+ ? L === "zh"
239
+ ? `\n…还有 ${tasks.length - 50} 条没列(去后台任务面板看全量)。`
240
+ : `\n…${tasks.length - 50} more not shown (see the background-tasks panel).`
241
+ : "";
242
+ const head = L === "zh" ? `定时任务(${tasks.length}):` : `Scheduled tasks (${tasks.length}):`;
243
+ return text(`${head}\n${lines.join("\n")}${more}`, { tasks });
186
244
  }
187
- return text(String(err?.message ?? err));
188
- }
189
- const L = getLang();
190
- const next = computeNextFire(task, Date.now());
191
- const head = L === "zh" ? `定时任务已创建:${task.id}(${task.name})` : `Scheduled task created: ${task.id} (${task.name})`;
192
- const whenLine = L === "zh"
193
- ? `触发:${parsed.kind === "cron" ? `cron ${parsed.spec}` : describeIntervalMs(Number(parsed.spec))},下次 ${fmtTime(next, L)}${recurring ? "(周期)" : "(单次,触发后自动删除)"}`
194
- : `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)"}`;
195
- const targetLine = convId
196
- ? L === "zh"
197
- ? `汇报:触发时自动唤醒本对话(${convId});压缩/重启后按会话文件自动重绑,原对话不在时先回落同项目活跃对话(明确提示),无存活对话才无头执行。`
198
- : `Reports: wakes this conversation (${convId}) on fire; re-binds by session file after compaction/restart, falls back to the project's active conversation (with a visible note), headless only with no live conversation.`
199
- : L === "zh"
200
- ? "汇报:无头执行,报告进调度面板历史(创建时没拿到对话 id)。"
201
- : "Reports: headless run, report in panel history (no conversation id captured at creation).";
202
- const tail = L === "zh"
203
- ? `取消:schedule_cancel(id="${task.id}"),或后台任务面板手动取消;查看:schedule_list。`
204
- : `Cancel: schedule_cancel(id="${task.id}"), or from the background-tasks panel; inspect: schedule_list.`;
205
- return text(`${head}\n${whenLine}\n${targetLine}\n${tail}`, { task });
206
- },
207
- });
208
- const listTool = defineTool({
209
- name: SCHEDULE_LIST_TOOL_NAME,
210
- label: "List scheduled tasks",
211
- description: "List all built-in scheduled tasks (all projects): " +
212
- "id, name, cron/interval, on/paused, one-shot, target conversation, next fire, last run. " +
213
- "Use it to inspect before cancelling, or to answer the user about what is scheduled.",
214
- promptSnippet: "list scheduled wake-up tasks",
215
- parameters: Type.Object({}),
216
- execute: async () => {
217
- const store = host.store();
218
- if (!store)
219
- return noStore();
220
- const L = getLang();
221
- const tasks = store.list();
222
- if (tasks.length === 0) {
223
- 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: [] });
224
- }
225
- const lines = tasks.slice(0, 50).map((t) => taskLine(t, L));
226
- const more = tasks.length > 50
227
- ? L === "zh"
228
- ? `\n…还有 ${tasks.length - 50} 条没列(去后台任务面板看全量)。`
229
- : `\n…${tasks.length - 50} more not shown (see the background-tasks panel).`
230
- : "";
231
- const head = L === "zh" ? `定时任务(${tasks.length}):` : `Scheduled tasks (${tasks.length}):`;
232
- return text(`${head}\n${lines.join("\n")}${more}`, { tasks });
233
- },
234
- });
235
- const cancelTool = defineTool({
236
- name: SCHEDULE_CANCEL_TOOL_NAME,
237
- label: "Cancel a scheduled task",
238
- description: "Delete a scheduled task by id (see schedule_list). " +
239
- "Deleting stops all future fires; use it when the user says the schedule is no longer needed.",
240
- promptSnippet: "cancel a scheduled task by id",
241
- parameters: Type.Object({
242
- id: Type.String({ description: "Task id from schedule_list." }),
243
- }),
244
- execute: async (_id, p) => {
245
- const store = host.store();
246
- if (!store)
247
- return noStore();
248
- const id = String(p.id ?? "").trim();
249
- if (!id) {
250
- return text(pick(getLang(), "要删哪个任务?给 id(先 schedule_list 查)。", "Which task? Give its id (see schedule_list first).", "sched.cancel.empty.id"));
251
- }
252
- if (!store.remove(id)) {
253
- 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 }));
245
+ case "cancel": {
246
+ const id = String(p.id ?? "").trim();
247
+ if (!id) {
248
+ return text(pick(getLang(), '要删哪个任务?给 id(先 schedule(action="list") 查)。', 'Which task? Give its id (see schedule(action="list") first).', "sched.cancel.empty.id"));
249
+ }
250
+ if (!store.remove(id)) {
251
+ return text(pick(getLang(), `没有 id=${id} 的任务(可能已触发自删或被删过,用 schedule(action="list") 看现有的)。`, `No task id=${id} (may have fired-and-deleted or been removed; see schedule(action="list")).`, "sched.cancel.not.found", { id }));
252
+ }
253
+ return text(pick(getLang(), `定时任务 ${id} 已删除,不再触发。`, `Scheduled task ${id} deleted, will not fire again.`, "sched.cancel.ok", { id }), { id });
254
+ }
255
+ default:
256
+ return text(pick(getLang(), `未知 action:${action}。支持的 action:create, list, cancel。`, `Unknown action: ${action}. Supported actions: create, list, cancel.`, "sched.action.unknown", { action }));
254
257
  }
255
- return text(pick(getLang(), `定时任务 ${id} 已删除,不再触发。`, `Scheduled task ${id} deleted, will not fire again.`, "sched.cancel.ok", { id }), { id });
256
258
  },
257
259
  });
258
- return [taskTool, listTool, cancelTool];
259
260
  }