pi-web-ui 0.99.0 → 0.101.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 (109) hide show
  1. package/CHANGELOG.md +90 -1
  2. package/README.md +48 -45
  3. package/README.zh-CN.md +43 -40
  4. package/bin/pi-web-ui.mjs +172 -40
  5. package/dist/server/agent-formatters.js +191 -0
  6. package/dist/server/agent-service-daemon.js +1266 -0
  7. package/dist/server/agent-service.js +9851 -11892
  8. package/dist/server/approval-default-rules.js +158 -0
  9. package/dist/server/approval-rules.js +130 -184
  10. package/dist/server/ask-user-question-tool.js +94 -0
  11. package/dist/server/attachment-store.js +38 -1
  12. package/dist/server/attachments.js +55 -0
  13. package/dist/server/bash-tool.js +83 -0
  14. package/dist/server/bg-servers.js +82 -2
  15. package/dist/server/browser-page-tool.js +207 -0
  16. package/dist/server/claim-files-tool.js +4 -4
  17. package/dist/server/client-id-utils.js +51 -0
  18. package/dist/server/client-state.js +63 -1
  19. package/dist/server/compact-context-tool.js +10 -9
  20. package/dist/server/compaction-markers.js +34 -1
  21. package/dist/server/context-budget-runner.js +43 -0
  22. package/dist/server/conversation-read-tool.js +7 -8
  23. package/dist/server/conversation-touches.js +19 -0
  24. package/dist/server/dangling-tools.js +18 -5
  25. package/dist/server/delegate-mode.js +1 -0
  26. package/dist/server/delegate-task.js +10 -14
  27. package/dist/server/dispatch-domain-handlers.js +631 -0
  28. package/dist/server/dispatch-plugin-handlers.js +300 -0
  29. package/dist/server/dsh/dsh-agent-service.js +125 -13
  30. package/dist/server/edit-soft-tool.js +10 -12
  31. package/dist/server/eval-tool.js +4 -5
  32. package/dist/server/goal-evidence.js +180 -0
  33. package/dist/server/goal-service.js +49 -9
  34. package/dist/server/hashline-engine.js +199 -32
  35. package/dist/server/index.js +212 -944
  36. package/dist/server/left-panel-running.js +115 -0
  37. package/dist/server/load-tools-tool.js +100 -0
  38. package/dist/server/lsp-tool.js +50 -28
  39. package/dist/server/marker-service.js +53 -12
  40. package/dist/server/markers/builtins/action.js +108 -0
  41. package/dist/server/markers/index.js +4 -1
  42. package/dist/server/markers-list-tool.js +34 -0
  43. package/dist/server/market-service.js +277 -0
  44. package/dist/server/mcp-bridge.js +137 -30
  45. package/dist/server/mcp-hot-reload.js +84 -27
  46. package/dist/server/mcp-manager.js +215 -0
  47. package/dist/server/message-entry-resolver.js +32 -0
  48. package/dist/server/orphan-manager.js +44 -0
  49. package/dist/server/patch-remote-catalog.js +28 -10
  50. package/dist/server/patch-tool.js +9 -8
  51. package/dist/server/persona-chain.js +63 -0
  52. package/dist/server/plan-mode.js +9 -6
  53. package/dist/server/plan-update-tool.js +96 -0
  54. package/dist/server/plugin-api-catalog.js +30 -3
  55. package/dist/server/plugin-conversation-view.js +47 -0
  56. package/dist/server/plugin-facilities.js +13 -3
  57. package/dist/server/plugin-ui-slots.js +39 -0
  58. package/dist/server/plugins.js +183 -63
  59. package/dist/server/present-files-tool.js +10 -11
  60. package/dist/server/preset-fields.js +700 -0
  61. package/dist/server/preset-share.js +1179 -0
  62. package/dist/server/process-utils.js +30 -0
  63. package/dist/server/prompt-assembler.js +80 -0
  64. package/dist/server/prompt-composer.js +23 -9
  65. package/dist/server/protocol-version.js +1 -1
  66. package/dist/server/read-tool.js +8 -10
  67. package/dist/server/resolve-global-sdk.js +80 -18
  68. package/dist/server/schedule-agent-tool.js +147 -146
  69. package/dist/server/scm-commitmsg.js +74 -0
  70. package/dist/server/sdk-origin.js +125 -37
  71. package/dist/server/serialize.js +97 -7
  72. package/dist/server/session-branch.js +367 -0
  73. package/dist/server/session-parser.js +235 -0
  74. package/dist/server/session-search.js +158 -0
  75. package/dist/server/settings-service.js +115 -84
  76. package/dist/server/skill-content-filler.js +33 -0
  77. package/dist/server/skill-tool.js +3 -4
  78. package/dist/server/subagent-handoff.js +18 -0
  79. package/dist/server/subagent-helpers.js +88 -0
  80. package/dist/server/subagents.js +15 -22
  81. package/dist/server/terminals.js +171 -91
  82. package/dist/server/tool-approval.js +3 -1
  83. package/dist/server/tool-guards.js +527 -0
  84. package/dist/server/tool-host-factories.js +217 -0
  85. package/dist/server/tool-manager.js +84 -23
  86. package/dist/server/tool-prompt-overrides.js +158 -0
  87. package/dist/server/tool-prompts.js +42 -0
  88. package/dist/server/tool-signature.js +104 -0
  89. package/dist/server/wait-subscription-scan.js +46 -1
  90. package/dist/server/workspace-snapshot.js +60 -11
  91. package/extensions/webui.ts +90 -24
  92. package/package.json +5 -3
  93. package/plugin-sdk/README.md +25 -4
  94. package/plugin-sdk/import-check.mjs +210 -0
  95. package/plugin-sdk/index.d.ts +21 -1
  96. package/plugin-sdk/index.mjs +6 -0
  97. package/plugins/catalog.json +53 -2
  98. package/themes/aetheris.css +3 -1
  99. package/themes/translucent.css +8 -1
  100. package/themes/transparent.css +9 -1
  101. package/themes/zhupi-dark.css +1 -1
  102. package/themes/zhupi.css +1 -1
  103. package/web/dist/assets/{TerminalPanel-NerrJlTS.js → TerminalPanel-DD7I5_aC.js} +2 -2
  104. package/web/dist/assets/index-CpjA1YdT.css +1 -0
  105. package/web/dist/assets/index-nKn87VuM.js +678 -0
  106. package/web/dist/index.html +2 -2
  107. package/web/dist/sw.js +1 -1
  108. package/web/dist/assets/index-BdMaGCcs.css +0 -1
  109. package/web/dist/assets/index-ByCBN4Kt.js +0 -368
@@ -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
  }
@@ -18,6 +18,10 @@
18
18
  * getting that). Only a repo with no commits yet falls back to the UI
19
19
  * language passed as fallbackLang.
20
20
  */
21
+ import { isNotRepoError, scmCommitContext } from "./scm.js";
22
+ import { pick } from "./i18n.js";
23
+ /** SCM AI 提交信息生成超时时间(毫秒) */
24
+ export const SCM_COMMITMSG_TIMEOUT_MS = 60_000;
21
25
  /** Hard cap for the generated subject — the commit input is single-line and
22
26
  * this keeps a chatty model from filling the whole header row. */
23
27
  export const MAX_COMMITMSG_LEN = 200;
@@ -138,3 +142,73 @@ export function sanitizeCommitMessage(raw) {
138
142
  out = `${out.slice(0, MAX_COMMITMSG_LEN - 1).trimEnd()}…`;
139
143
  return out;
140
144
  }
145
+ /**
146
+ * 完整的 SCM AI 提交信息生成逻辑封装:
147
+ * 提取 git 差异上下文 -> 组装 prompt -> 调用模型 completeSimple -> 结果清洗校验
148
+ */
149
+ export async function generateScmCommitMessage(opts) {
150
+ const { cwd, model, runtime, lang, promptMode = "append", customPrompt = "", timeoutMs = SCM_COMMITMSG_TIMEOUT_MS, } = opts;
151
+ try {
152
+ const ctx = await scmCommitContext(cwd, () => lang);
153
+ const input = buildCommitMsgInput(ctx, lang === "zh" ? "zh" : "en");
154
+ if (!input) {
155
+ return {
156
+ ok: false,
157
+ error: pick(lang, "没有可描述的更改(工作区干净)", "Nothing to describe (working tree clean)", "scm.commitmsg.no.changes"),
158
+ };
159
+ }
160
+ const ac = new AbortController();
161
+ const timer = setTimeout(() => ac.abort(), timeoutMs);
162
+ const systemPrompt = buildCommitMsgPrompt(promptMode, customPrompt);
163
+ let msg;
164
+ try {
165
+ msg = await runtime.completeSimple(model, {
166
+ systemPrompt,
167
+ messages: [
168
+ {
169
+ role: "user",
170
+ timestamp: Date.now(),
171
+ content: [{ type: "text", text: input }],
172
+ },
173
+ ],
174
+ }, { signal: ac.signal, maxTokens: 400 });
175
+ }
176
+ finally {
177
+ clearTimeout(timer);
178
+ }
179
+ if (msg.stopReason === "error" || msg.stopReason === "aborted") {
180
+ return {
181
+ ok: false,
182
+ error: msg.errorMessage ||
183
+ pick(lang, `模型异常终止(${msg.stopReason})`, `Model terminated abnormally (${msg.stopReason})`, "scm.commitmsg.model.terminated"),
184
+ };
185
+ }
186
+ const raw = msg.content
187
+ .filter((b) => b.type === "text")
188
+ .map((b) => b.text ?? "")
189
+ .join("\n");
190
+ const text = sanitizeCommitMessage(raw);
191
+ if (!text) {
192
+ return {
193
+ ok: false,
194
+ error: pick(lang, "模型返回了空的提交信息", "The model returned an empty commit message", "scm.commitmsg.empty"),
195
+ };
196
+ }
197
+ return { ok: true, text };
198
+ }
199
+ catch (err) {
200
+ if (isNotRepoError(err)) {
201
+ return {
202
+ ok: false,
203
+ error: pick(lang, "当前目录不是 Git 仓库", "Current directory is not a Git repository", "scm.commitmsg.not.repo"),
204
+ };
205
+ }
206
+ if (err instanceof Error && /abort/i.test(`${err.name} ${err.message}`)) {
207
+ return {
208
+ ok: false,
209
+ error: pick(lang, `生成提交信息超时(${Math.round(timeoutMs / 1000)} 秒)`, `Commit-message generation timed out (${Math.round(timeoutMs / 1000)}s)`, "scm.commitmsg.timeout"),
210
+ };
211
+ }
212
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
213
+ }
214
+ }
@@ -11,58 +11,143 @@
11
11
  *
12
12
  * 纯函数 + 零副作用,便于单测(见 tests/unit/sdk-origin.test.ts)。
13
13
  */
14
- import { existsSync, readFileSync } from "node:fs";
15
- import { dirname, join } from "node:path";
14
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
15
+ import { dirname, join, delimiter, isAbsolute } from "node:path";
16
16
  import { fileURLToPath } from "node:url";
17
17
  const PKG = "@earendil-works/pi-coding-agent";
18
- /** 从某个文件出发,逐级向上查找 `<dir>/node_modules/<pkg>/package.json`。
18
+ function addCopy(pjPath, out, requireName = false) {
19
+ if (!existsSync(pjPath))
20
+ return;
21
+ const norm = pjPath.replace(/\\/g, "/");
22
+ if (out.some((c) => c.path.replace(/\\/g, "/") === norm))
23
+ return;
24
+ try {
25
+ const raw = readFileSync(pjPath, "utf8");
26
+ const info = JSON.parse(raw);
27
+ if (requireName && info?.name !== PKG)
28
+ return;
29
+ if (typeof info?.version === "string" && info.version) {
30
+ out.push({ path: pjPath, version: info.version });
31
+ }
32
+ }
33
+ catch { }
34
+ }
35
+ /** 探测 PATH 上的 pi 可执行文件反推其包根(issue #559, #562)。 */
36
+ function scanPathForPi(out, env = process.env) {
37
+ const rawPath = env.PATH || "";
38
+ if (!rawPath)
39
+ return;
40
+ const dirs = rawPath.split(delimiter).filter(Boolean);
41
+ const isWin = process.platform === "win32";
42
+ const names = isWin ? ["pi.cmd", "pi.exe", "pi.ps1", "pi"] : ["pi"];
43
+ for (const dir of dirs) {
44
+ for (const name of names) {
45
+ const candidate = join(dir, name);
46
+ if (!existsSync(candidate))
47
+ continue;
48
+ // 1. 尝试 realpathSync 解析符号链接(Unix 下 npm/pnpm 全局 bin 标准布局)
49
+ try {
50
+ const real = realpathSync(candidate);
51
+ let cur = dirname(real);
52
+ for (let i = 0; i < 5; i++) {
53
+ const pj = join(cur, "package.json");
54
+ addCopy(pj, out, true);
55
+ const parent = dirname(cur);
56
+ if (parent === cur)
57
+ break;
58
+ cur = parent;
59
+ }
60
+ }
61
+ catch { }
62
+ // 2. 检查常见同级/相对 node_modules 目录(Windows npm 全局 bin 同级 node_modules 等)
63
+ addCopy(join(dir, "node_modules", PKG, "package.json"), out);
64
+ addCopy(join(dir, "..", "lib", "node_modules", PKG, "package.json"), out);
65
+ addCopy(join(dir, "..", "node_modules", PKG, "package.json"), out);
66
+ // 3. 脚本包装内容解析(Windows 下 .cmd / .ps1 或 Unix 下 shell 包装脚本)
67
+ try {
68
+ const head = readFileSync(candidate, "utf8").slice(0, 4096);
69
+ const m = head.match(/[^\r\n"']*@earendil-works[/\\]pi-coding-agent[^\r\n"']*/);
70
+ if (m) {
71
+ let matchedPath = m[0].trim().replace(/%~?dp0%?[/\\]/gi, "");
72
+ let targetDir = isAbsolute(matchedPath) ? matchedPath : join(dir, matchedPath);
73
+ for (let i = 0; i < 5; i++) {
74
+ const pj = join(targetDir, "package.json");
75
+ addCopy(pj, out, true);
76
+ const parent = dirname(targetDir);
77
+ if (parent === targetDir)
78
+ break;
79
+ targetDir = parent;
80
+ }
81
+ }
82
+ }
83
+ catch { }
84
+ }
85
+ }
86
+ }
87
+ /** 探测 npm / pnpm 全局 prefix 目录(issue #559)。 */
88
+ function scanGlobalPrefixes(out, env = process.env) {
89
+ const home = env.HOME || env.USERPROFILE || "";
90
+ // 1. npm_config_prefix / PREFIX
91
+ const prefix = env.npm_config_prefix || env.PREFIX;
92
+ if (prefix) {
93
+ addCopy(join(prefix, "lib", "node_modules", PKG, "package.json"), out);
94
+ addCopy(join(prefix, "node_modules", PKG, "package.json"), out);
95
+ }
96
+ // 2. 用户级 npm 全局 (~/.npm-global, %APPDATA%\npm)
97
+ if (home) {
98
+ addCopy(join(home, ".npm-global", "lib", "node_modules", PKG, "package.json"), out);
99
+ addCopy(join(home, ".npm-global", "node_modules", PKG, "package.json"), out);
100
+ }
101
+ if (env.APPDATA) {
102
+ addCopy(join(env.APPDATA, "npm", "node_modules", PKG, "package.json"), out);
103
+ }
104
+ // 3. POSIX 系统级 npm 全局
105
+ if (process.platform !== "win32") {
106
+ addCopy(join("/usr", "local", "lib", "node_modules", PKG, "package.json"), out);
107
+ addCopy(join("/usr", "lib", "node_modules", PKG, "package.json"), out);
108
+ }
109
+ // 4. pnpm 全局目录 (PNPM_HOME, ~/.local/share/pnpm/global, %LOCALAPPDATA%\pnpm\global)
110
+ if (env.PNPM_HOME) {
111
+ addCopy(join(env.PNPM_HOME, "node_modules", PKG, "package.json"), out);
112
+ addCopy(join(env.PNPM_HOME, "global", "node_modules", PKG, "package.json"), out);
113
+ }
114
+ if (home) {
115
+ addCopy(join(home, ".local", "share", "pnpm", "global", "node_modules", PKG, "package.json"), out);
116
+ }
117
+ if (env.LOCALAPPDATA) {
118
+ addCopy(join(env.LOCALAPPDATA, "pnpm", "global", "node_modules", PKG, "package.json"), out);
119
+ }
120
+ }
121
+ /** 从某个文件出发,逐级向上查找 `<dir>/node_modules/<pkg>/package.json`,
122
+ * 并探测系统/全局已安装的 pi SDK 副本(issue #260, #321, #559, #562)。
19
123
  * `fromFile` 收 URL(`import.meta.url`)或普通文件路径(便于单测)。 */
20
- export function sdkCopies(fromFile = import.meta.url) {
124
+ export function sdkCopies(fromFile = import.meta.url, options = {}) {
125
+ const env = options.env ?? process.env;
126
+ const includeGlobal = options.includeGlobal ?? (options.env ? true : !process.env.VITEST);
21
127
  const out = [];
22
128
  let dir = dirname(fromFile.startsWith("file:") ? fileURLToPath(fromFile) : fromFile);
23
129
  for (;;) {
24
130
  const pj = join(dir, "node_modules", PKG, "package.json");
25
- if (existsSync(pj)) {
26
- try {
27
- const version = JSON.parse(readFileSync(pj, "utf8")).version;
28
- if (typeof version === "string" && version)
29
- out.push({ path: pj, version });
30
- }
31
- catch {
32
- // 坏 JSON:跳过这一份,不影响其它候选(best-effort,同 process-utils 的口径)
33
- }
34
- }
131
+ addCopy(pj, out);
35
132
  const parent = dirname(dir);
36
133
  if (parent === dir)
37
134
  break;
38
135
  dir = parent;
39
136
  }
40
137
  // 显式透传的宿主 SDK 路径(如 extensions/webui.ts 宿主传递,issue #482)
41
- if (process.env.PI_WEB_SDK_DIR) {
42
- const pj = join(process.env.PI_WEB_SDK_DIR, "package.json");
43
- if (existsSync(pj) && !out.some((c) => c.path === pj)) {
44
- try {
45
- const version = JSON.parse(readFileSync(pj, "utf8")).version;
46
- if (typeof version === "string" && version) {
47
- out.push({ path: pj, version });
48
- }
49
- }
50
- catch { }
51
- }
138
+ if (env.PI_WEB_SDK_DIR) {
139
+ addCopy(join(env.PI_WEB_SDK_DIR, "package.json"), out);
52
140
  }
53
141
  // 宿主 Pi Node 路径探测(~/.local/share/pi-node/current/...,issue #482)
54
- const home = process.env.HOME || process.env.USERPROFILE;
142
+ const home = env.HOME || env.USERPROFILE;
55
143
  if (home) {
56
- const hostPj = join(home, ".local", "share", "pi-node", "current", "lib", "node_modules", PKG, "package.json");
57
- if (existsSync(hostPj) && !out.some((c) => c.path === hostPj)) {
58
- try {
59
- const version = JSON.parse(readFileSync(hostPj, "utf8")).version;
60
- if (typeof version === "string" && version) {
61
- out.push({ path: hostPj, version });
62
- }
63
- }
64
- catch { }
65
- }
144
+ addCopy(join(home, ".local", "share", "pi-node", "current", "lib", "node_modules", PKG, "package.json"), out);
145
+ }
146
+ if (includeGlobal) {
147
+ // PATH 上的 pi 可执行文件反推(issue #559)
148
+ scanPathForPi(out, env);
149
+ // npm / pnpm 全局 prefix 目录探测(issue #559)
150
+ scanGlobalPrefixes(out, env);
66
151
  }
67
152
  return out;
68
153
  }
@@ -85,7 +170,10 @@ export function compareVersions(a, b) {
85
170
  * (如部分桌面/容器布局)时按自带算 —— 那本来就是唯一能加载的份。
86
171
  * UI 用它决定是否亮「安装全局引擎并切换」入口(issue #321)。
87
172
  */
88
- export function isBundledInUse(copies, effectiveVersion) {
173
+ export function isBundledInUse(copies, effectiveVersion, bundledCopy) {
174
+ if (bundledCopy !== undefined) {
175
+ return bundledCopy !== null && effectiveVersion === bundledCopy.version;
176
+ }
89
177
  return copies.length === 0 || effectiveVersion === copies[0].version;
90
178
  }
91
179
  /**