pi-web-ui 0.113.0 → 0.114.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 (228) hide show
  1. package/CHANGELOG.md +69 -1
  2. package/README.md +117 -252
  3. package/README.zh-CN.md +145 -223
  4. package/README.zh-TW.md +145 -223
  5. package/bin/device-hub-cli.mjs +577 -0
  6. package/bin/pi-device-hub.mjs +9 -0
  7. package/bin/pi-web-ui.mjs +145 -20
  8. package/dist/gh-comment-781.md +5 -0
  9. package/dist/server/agent-service-daemon.js +102 -24
  10. package/dist/server/agent-service.js +2296 -1121
  11. package/dist/server/approval-rules.js +29 -3
  12. package/dist/server/ask-user-question-tool.js +8 -8
  13. package/dist/server/atomic-file.js +35 -14
  14. package/dist/server/attachment-store.js +71 -35
  15. package/dist/server/attachments.js +18 -8
  16. package/dist/server/canvas/canvas-agent-tool.js +65 -15
  17. package/dist/server/canvas/canvas-dispatch.js +61 -20
  18. package/dist/server/canvas/canvas-orchestrator.js +516 -199
  19. package/dist/server/canvas/canvas-scheduler.js +99 -0
  20. package/dist/server/canvas/canvas-store.js +107 -54
  21. package/dist/server/canvas/canvas-validation.js +131 -0
  22. package/dist/server/canvas/canvas-workspace.js +284 -0
  23. package/dist/server/client-id-utils.js +8 -0
  24. package/dist/server/client-state.js +104 -22
  25. package/dist/server/communicate-tool.js +76 -0
  26. package/dist/server/compact-context-tool.js +2 -3
  27. package/dist/server/compaction-instructions.js +75 -0
  28. package/dist/server/compaction-markers.js +7 -2
  29. package/dist/server/compaction-state.js +84 -0
  30. package/dist/server/composer-drafts.js +43 -40
  31. package/dist/server/context-evidence.js +346 -0
  32. package/dist/server/control-socket.js +6 -2
  33. package/dist/server/conversation-communication.js +368 -0
  34. package/dist/server/conversation-read-tool.js +3 -4
  35. package/dist/server/conversation-tool-names.js +14 -0
  36. package/dist/server/conversation-tool.js +57 -0
  37. package/dist/server/delegate-mode.js +17 -4
  38. package/dist/server/device-center/bot-catalog.js +88 -0
  39. package/dist/server/device-center/bot-execution.js +106 -0
  40. package/dist/server/device-center/bots.js +170 -0
  41. package/dist/server/device-center/collab-service.js +153 -0
  42. package/dist/server/device-center/collab-tool.js +184 -0
  43. package/dist/server/device-center/connector.js +332 -0
  44. package/dist/server/device-center/desktop-linux.js +372 -0
  45. package/dist/server/device-center/desktop-native.js +413 -0
  46. package/dist/server/device-center/desktop-page.js +232 -0
  47. package/dist/server/device-center/desktop-setup.js +30 -0
  48. package/dist/server/device-center/desktop.js +387 -0
  49. package/dist/server/device-center/device-portals.js +241 -0
  50. package/dist/server/device-center/execution-failure.js +70 -0
  51. package/dist/server/device-center/executor.js +371 -0
  52. package/dist/server/device-center/file-sync.js +493 -0
  53. package/dist/server/device-center/hub-auth.js +69 -0
  54. package/dist/server/device-center/hub-page.js +68 -0
  55. package/dist/server/device-center/hub-setup.js +214 -0
  56. package/dist/server/device-center/hub.js +829 -0
  57. package/dist/server/device-center/local-page.js +17 -0
  58. package/dist/server/device-center/local.js +476 -0
  59. package/dist/server/device-center/main.js +118 -0
  60. package/dist/server/device-center/native-desktop/macos.js +192 -0
  61. package/dist/server/device-center/native-desktop/windows.js +118 -0
  62. package/dist/server/device-center/path-portal.js +120 -0
  63. package/dist/server/device-center/relay.js +959 -0
  64. package/dist/server/device-center/runtime.js +253 -0
  65. package/dist/server/device-center/smoke-preview.js +3 -0
  66. package/dist/server/device-center/store.js +122 -0
  67. package/dist/server/device-center/task-error.js +14 -0
  68. package/dist/server/device-center/transfers.js +293 -0
  69. package/dist/server/device-center/workspaces.js +45 -0
  70. package/dist/server/dispatch-domain-handlers.js +83 -27
  71. package/dist/server/dsh/dsh-agent-service.js +277 -158
  72. package/dist/server/dsh/dsh-client.js +12 -2
  73. package/dist/server/durable/durable-agent-service.js +1 -1
  74. package/dist/server/evidence-tool-hooks.js +49 -0
  75. package/dist/server/file-save.js +95 -0
  76. package/dist/server/file-transfer-routes.js +97 -47
  77. package/dist/server/files-service.js +110 -34
  78. package/dist/server/goal-review-gate.js +16 -6
  79. package/dist/server/goal-service.js +54 -30
  80. package/dist/server/http-proxy.js +120 -0
  81. package/dist/server/index.js +236 -232
  82. package/dist/server/load-timing.js +31 -0
  83. package/dist/server/mcp-bridge.js +219 -94
  84. package/dist/server/mcp-hot-reload.js +31 -5
  85. package/dist/server/mcp-manager.js +192 -93
  86. package/dist/server/mcp-oauth-login.js +169 -0
  87. package/dist/server/mcp-oauth-ui.js +137 -0
  88. package/dist/server/mcp-oauth.js +395 -0
  89. package/dist/server/mcp-project-runtime.js +207 -0
  90. package/dist/server/message-window.js +74 -21
  91. package/dist/server/net-guard.js +122 -20
  92. package/dist/server/payload-limits.js +17 -0
  93. package/dist/server/pending-question.js +82 -0
  94. package/dist/server/plan-mode.js +338 -137
  95. package/dist/server/plugin-assets.js +8 -4
  96. package/dist/server/plugin-chat-attachments.js +48 -0
  97. package/dist/server/plugin-facilities.js +67 -220
  98. package/dist/server/plugin-installer.js +2 -1
  99. package/dist/server/plugin-removal.js +49 -0
  100. package/dist/server/plugin-secrets.js +179 -0
  101. package/dist/server/plugins.js +262 -92
  102. package/dist/server/preset-fields.js +49 -0
  103. package/dist/server/preset-plugin-dependencies.js +57 -0
  104. package/dist/server/preset-share.js +112 -72
  105. package/dist/server/protocol-version.js +1 -1
  106. package/dist/server/queue-modes.js +10 -0
  107. package/dist/server/remote-ssh-service.js +160 -67
  108. package/dist/server/request-context.js +164 -0
  109. package/dist/server/sandbox-data.js +655 -0
  110. package/dist/server/sandbox-engines.js +7 -0
  111. package/dist/server/sandbox-runtime-gate.js +41 -0
  112. package/dist/server/sandbox-service.js +139 -698
  113. package/dist/server/sandbox-tool.js +21 -4
  114. package/dist/server/scheduler-tasks.js +63 -48
  115. package/dist/server/serialize.js +48 -19
  116. package/dist/server/session-branch.js +25 -3
  117. package/dist/server/session-parser.js +28 -18
  118. package/dist/server/session-scan.js +130 -0
  119. package/dist/server/session-search.js +51 -37
  120. package/dist/server/settings-service.js +267 -111
  121. package/dist/server/setup-config.js +58 -0
  122. package/dist/server/skill-maintenance.js +112 -24
  123. package/dist/server/subagent-helpers.js +4 -1
  124. package/dist/server/subagent-notify.js +4 -1
  125. package/dist/server/subagent-security-gate.js +52 -11
  126. package/dist/server/subagent-task.js +27 -0
  127. package/dist/server/subagents.js +217 -46
  128. package/dist/server/tabs.js +9 -1
  129. package/dist/server/terminals.js +467 -363
  130. package/dist/server/tool-guards.js +42 -6
  131. package/dist/server/tool-manager.js +47 -20
  132. package/dist/server/tool-overrides.js +13 -11
  133. package/dist/server/tool-prompt-overrides.js +32 -2
  134. package/dist/server/tool-prompts.js +1 -1
  135. package/dist/server/turn-timing.js +11 -0
  136. package/dist/server/universal/session-store.js +48 -6
  137. package/dist/server/universal/universal-service.js +1 -1
  138. package/dist/server/universal/universal-session.js +334 -231
  139. package/dist/server/uploads.js +64 -5
  140. package/dist/server/webui-context.js +6 -6
  141. package/dist/server/worktree-service.js +32 -24
  142. package/dist/server/ws-pending-queue.js +73 -27
  143. package/dist/test-artifact.md +9 -0
  144. package/dist/test-preview-modal.md +11 -0
  145. package/dist/test-report.html +20 -0
  146. package/docs/device-center.md +142 -0
  147. package/docs/device-desktop.md +48 -0
  148. package/package.json +4 -1
  149. package/plugin-sdk/index.d.ts +45 -9
  150. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  151. package/plugins/catalog.json +1 -1
  152. package/themes/aetheris.css +1 -107
  153. package/themes/ayu-light.css +5 -29
  154. package/themes/bases/flow-base.css +0 -6
  155. package/themes/bases/statusbar-flat-base.css +112 -0
  156. package/themes/bases/zhujian-base.css +1 -0
  157. package/themes/bases/zhupi-base.css +1 -0
  158. package/themes/catppuccin-latte.css +4 -27
  159. package/themes/catppuccin.css +4 -35
  160. package/themes/claude-code-dark.css +1 -0
  161. package/themes/codex.css +4 -28
  162. package/themes/cyberpunk.css +3 -61
  163. package/themes/dark-teal.css +0 -1
  164. package/themes/dazzle.css +3 -73
  165. package/themes/everforest-light.css +4 -27
  166. package/themes/geist.css +4 -28
  167. package/themes/gruvbox-light.css +4 -27
  168. package/themes/kanagawa-lotus.css +4 -27
  169. package/themes/md-preview.css +3 -213
  170. package/themes/mist.css +4 -24
  171. package/themes/nord.css +4 -35
  172. package/themes/one-dark.css +4 -37
  173. package/themes/paper.css +4 -16
  174. package/themes/rose-pine-dawn.css +4 -28
  175. package/themes/sakura.css +4 -24
  176. package/themes/solarized-light.css +4 -27
  177. package/themes/tokyo-night.css +3 -34
  178. package/themes/white.css +4 -26
  179. package/themes/zhujian-dark.css +1 -0
  180. package/themes/zhupi-dark.css +1 -0
  181. package/web/dist/.build-assets.json +1 -0
  182. package/web/dist/assets/BgTasksModal-CS7UNzcw.js +1 -0
  183. package/web/dist/assets/BgTasksModal-Dk-tp78W.js +1 -0
  184. package/web/dist/assets/CanvasStudio-BEJZE5BI.js +1579 -0
  185. package/web/dist/assets/CanvasStudio-CgUNHqos.js +1579 -0
  186. package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +3 -0
  187. package/web/dist/assets/DeviceCenter-CVblvhNX.js +3 -0
  188. package/web/dist/assets/Dropdown-Oug0DDte.js +1 -0
  189. package/web/dist/assets/FilePreview-CvdX6nr6.js +2 -0
  190. package/web/dist/assets/FilePreview-kCZhfBAF.js +2 -0
  191. package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +1 -0
  192. package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +1 -0
  193. package/web/dist/assets/GroupConversation-Cgo4xbpa.js +1 -0
  194. package/web/dist/assets/GroupConversation-DZ71jEi8.js +1 -0
  195. package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +2 -0
  196. package/web/dist/assets/PiSetupModal-mkWPSxMj.js +1 -0
  197. package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +1 -0
  198. package/web/dist/assets/SCMPanel-BP1TUT-V.js +2 -0
  199. package/web/dist/assets/SCMPanel-BscPm9kf.js +2 -0
  200. package/web/dist/assets/SettingsModal-C8UgMjVM.js +20 -0
  201. package/web/dist/assets/SettingsModal-VynB7jNb.js +20 -0
  202. package/web/dist/assets/TerminalPanel-D6cPRFei.js +3 -0
  203. package/web/dist/assets/TerminalPanel-DL20uKgU.js +3 -0
  204. package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +1 -0
  205. package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +1 -0
  206. package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +1 -0
  207. package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +1 -0
  208. package/web/dist/assets/app-globals-CnO6KlEM.js +325 -0
  209. package/web/dist/assets/desktop-DPyTy4M3.js +1 -0
  210. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  211. package/web/dist/assets/index-CPgAH5q7.js +83 -0
  212. package/web/dist/assets/index-Cje8iugL.js +83 -0
  213. package/web/dist/assets/index-DnKeiDbj.css +1 -0
  214. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  215. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  216. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  217. package/web/dist/assets/math-BorAY7qD.css +1 -0
  218. package/web/dist/assets/plugin-host-CqA4yW6w.js +1 -0
  219. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  220. package/web/dist/assets/theme-BqdAjEjF.js +1 -0
  221. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  222. package/web/dist/index.html +15 -9
  223. package/web/dist/sw.js +1 -1
  224. package/web/dist/assets/TerminalPanel-3wojLfLk.js +0 -3
  225. package/web/dist/assets/index-A8YXwnpZ.js +0 -2008
  226. package/web/dist/assets/index-BwL7qBh6.css +0 -1
  227. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  228. package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
@@ -33,6 +33,8 @@ import { existsSync, readFileSync, statSync } from "node:fs";
33
33
  import { isAbsolute, relative, resolve, sep } from "node:path";
34
34
  import { writeJsonAtomicSync } from "./atomic-file.js";
35
35
  import { DEFAULT_APPROVAL_RULES } from "./approval-default-rules.js";
36
+ import { LEGACY_TERMINAL_TOOL_NAMES } from "./tool-manager.js";
37
+ import { conversationToolAllowed } from "./conversation-tool-names.js";
36
38
  export { DEFAULT_APPROVAL_RULES };
37
39
  /**
38
40
  * 检测命令字符串中是否包含 Shell 复合操作符或子命令执行结构(分号、逻辑与/或、管道、反引号、换行、$())。
@@ -135,11 +137,27 @@ export function extractRuleFieldValue(field, toolName, params) {
135
137
  * 匹配成功时返回匹配区间信息 { index, length, text },否则返回 null。
136
138
  */
137
139
  /** 单条规则在一段字段文本里的全部命中区间(issue #578)。regex 规则逐次扫描、不只取首个。 */
140
+ /** Keep persisted per-action rules scoped to exactly the corresponding merged action. */
141
+ function legacyTerminalRuleCall(rule, toolName, params) {
142
+ if (toolName.trim().toLowerCase() !== "terminal" || !params || typeof params !== "object")
143
+ return null;
144
+ const { action, ...legacyParams } = params;
145
+ const legacyName = `terminal_${String(action ?? "")}`;
146
+ const names = rule.tools.map((name) => name.trim().toLowerCase());
147
+ if (names.includes("terminal") || names.includes("*"))
148
+ return null;
149
+ if (!LEGACY_TERMINAL_TOOL_NAMES.includes(legacyName) || !names.includes(legacyName))
150
+ return null;
151
+ return { toolName: legacyName, params: legacyParams };
152
+ }
138
153
  export function matchApprovalRuleDetails(rule, toolName, params, cwd, workspaceRoots = []) {
154
+ const legacy = legacyTerminalRuleCall(rule, toolName, params);
155
+ if (legacy)
156
+ return matchApprovalRuleDetails(rule, legacy.toolName, legacy.params, cwd, workspaceRoots);
139
157
  if (!rule.enabled)
140
158
  return [];
141
159
  const targetTools = rule.tools.map((t) => t.trim().toLowerCase());
142
- const toolMatches = targetTools.includes("*") || targetTools.includes(toolName.trim().toLowerCase());
160
+ const toolMatches = targetTools.includes("*") || conversationToolAllowed(new Set(targetTools), toolName.trim().toLowerCase());
143
161
  if (!toolMatches)
144
162
  return [];
145
163
  if (rule.match === "regex") {
@@ -171,11 +189,14 @@ export function matchApprovalRuleDetails(rule, toolName, params, cwd, workspaceR
171
189
  return single ? [single] : [];
172
190
  }
173
191
  export function matchApprovalRuleDetail(rule, toolName, params, cwd, workspaceRoots = []) {
192
+ const legacy = legacyTerminalRuleCall(rule, toolName, params);
193
+ if (legacy)
194
+ return matchApprovalRuleDetail(rule, legacy.toolName, legacy.params, cwd, workspaceRoots);
174
195
  if (!rule.enabled)
175
196
  return null;
176
197
  // 1. 工具名匹配
177
198
  const targetTools = rule.tools.map((t) => t.trim().toLowerCase());
178
- const toolMatches = targetTools.includes("*") || targetTools.includes(toolName.trim().toLowerCase());
199
+ const toolMatches = targetTools.includes("*") || conversationToolAllowed(new Set(targetTools), toolName.trim().toLowerCase());
179
200
  if (!toolMatches)
180
201
  return null;
181
202
  // 2. 特殊匹配方式:outside_workspace(工作区外路径)
@@ -282,7 +303,12 @@ export function evaluateApprovalRules(rules, toolName, params, cwd, workspaceRoo
282
303
  for (const rule of rules) {
283
304
  // 同一规则可在一段命令里出现多次(如 `git reset --hard && git clean -fd`),全部列出(#578)。
284
305
  for (const detail of matchApprovalRuleDetails(rule, toolName, params, cwd, workspaceRoots)) {
285
- if (!primary) {
306
+ // A migrated allow must never preempt a new terminal deny/ask rule.
307
+ if (!primary ||
308
+ (primary.action === "allow" &&
309
+ legacyTerminalRuleCall(primary.matchedRule, toolName, params) &&
310
+ !legacyTerminalRuleCall(rule, toolName, params) &&
311
+ rule.action !== "allow")) {
286
312
  primary = {
287
313
  action: rule.action,
288
314
  matchedRule: rule,
@@ -5,11 +5,7 @@
5
5
  * 从 agent-service.ts 抽出为独立模块。
6
6
  */
7
7
  import { Type } from "typebox";
8
- /**
9
- * askUser 签名带 {aborted} 快照而非完整 AbortSignal:customTool 的 execute 信号
10
- * 服务于整个 agent 生命周期,这里按「已中止即拒绝」的最小语义处理,避免与其它
11
- * 工具的取消逻辑纠缠。
12
- */
8
+ /** Forward the live signal so cancellation also settles an already pending request. */
13
9
  export function makeAskUserQuestionTool(clientSession,
14
10
  /** 本 runtime 所属会话:提问跟着对话走,快照只把当前对话的问卷推给客户端。 */
15
11
  ownerId) {
@@ -71,9 +67,13 @@ ownerId) {
71
67
  if (qs.length > 3) {
72
68
  throw new Error("ask_user_question allows at most 3 questions per call to prevent question fatigue (单次提问最多不得超过 3 个问题)");
73
69
  }
74
- const res = await clientSession.askUser(qs, {
75
- aborted: signal?.aborted,
76
- }, ownerId);
70
+ const res = await clientSession.askUser(qs, signal ?? new AbortController().signal, ownerId);
71
+ if (res && !Array.isArray(res) && "timed_out" in res) {
72
+ return {
73
+ content: [{ type: "text", text: "Question timed out. No answer was selected; do not infer user consent." }],
74
+ details: res,
75
+ };
76
+ }
77
77
  if (res === null) {
78
78
  throw new Error("User cancelled the question.\n用户取消了提问。");
79
79
  }
@@ -1,25 +1,46 @@
1
- import { mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
1
+ import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
2
2
  import { dirname } from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
- /**
5
- * 跨平台安全原子写文件:先写临时文件再 renameSync,进程崩溃不留半截文件。
6
- * - tmp 文件位于目标文件同目录下(保证处于同物理卷,rename 为原子操作);
7
- * - tmp 文件名携带 pid + 时间戳 + 随机串,防止同机多进程互踩;
8
- * - Windows 下目标文件若被外部临时占用(杀软/文本编辑器锁),rename 失败后退回原地写兜底;
9
- * - 确保无论成功失败,临时文件在 finally 中及时清理,杜绝残留 .tmp 垃圾文件。
10
- */
11
- export function writeAtomicSync(file, data) {
4
+ export function writeAtomicSync(file, data, options = {}) {
12
5
  const dir = dirname(file);
13
6
  mkdirSync(dir, { recursive: true });
14
7
  const suffix = `${process.pid}.${Date.now()}.${randomUUID().slice(0, 8)}.tmp`;
15
8
  const tmp = `${file}.${suffix}`;
16
9
  try {
17
- writeFileSync(tmp, data);
18
- try {
19
- renameSync(tmp, file);
10
+ if (options.mode !== undefined || options.fsync) {
11
+ let mode = options.mode;
12
+ if (mode !== undefined) {
13
+ try {
14
+ mode = statSync(file).mode & 0o777;
15
+ }
16
+ catch (error) {
17
+ if (error.code !== "ENOENT")
18
+ throw error;
19
+ }
20
+ }
21
+ const fd = openSync(tmp, "wx", mode);
22
+ try {
23
+ writeFileSync(fd, data);
24
+ if (options.fsync)
25
+ fsyncSync(fd);
26
+ }
27
+ finally {
28
+ closeSync(fd);
29
+ }
20
30
  }
21
- catch {
22
- writeFileSync(file, data);
31
+ else {
32
+ writeFileSync(tmp, data);
33
+ }
34
+ for (let attempt = 0;; attempt++) {
35
+ try {
36
+ renameSync(tmp, file);
37
+ break;
38
+ }
39
+ catch (error) {
40
+ const code = error.code;
41
+ if (attempt >= 2 || !["EPERM", "EACCES", "EBUSY"].includes(code ?? ""))
42
+ throw error;
43
+ }
23
44
  }
24
45
  }
25
46
  finally {
@@ -8,18 +8,41 @@
8
8
  * - 避免快照和消息列表随会话进行出现数兆字节 base64 的膨胀。
9
9
  */
10
10
  import { createHash, randomUUID } from "node:crypto";
11
- import { mkdirSync, existsSync, readdirSync } from "node:fs";
12
- import { readFile, rename, rm, writeFile, stat } from "node:fs/promises";
11
+ import { mkdirSync, existsSync } from "node:fs";
12
+ import { readFile, readdir, rename, rm, writeFile, stat } from "node:fs/promises";
13
13
  import { join, extname } from "node:path";
14
14
  import { writeAtomicSync } from "./atomic-file.js";
15
- let storeDir = "";
15
+ let store;
16
+ function indexFile(target, fileName) {
17
+ // Accept legacy hash.ext names, but never unfinished atomic writes.
18
+ const match = /^([a-f0-9]{64})\..+$/i.exec(fileName);
19
+ if (!match || fileName.endsWith(".tmp"))
20
+ return;
21
+ let files = target.files.get(match[1]);
22
+ if (!files)
23
+ target.files.set(match[1], (files = new Set()));
24
+ files.add(fileName);
25
+ }
26
+ function ensureIndex(target) {
27
+ return (target.ready ??= readdir(target.dir, { withFileTypes: true })
28
+ .then((entries) => {
29
+ for (const entry of entries) {
30
+ if (entry.isFile())
31
+ indexFile(target, entry.name);
32
+ }
33
+ })
34
+ .catch((error) => {
35
+ target.ready = undefined;
36
+ throw error;
37
+ }));
38
+ }
16
39
  /** 初始化附件存储目录(服务启动时调用)。 */
17
40
  export function initAttachmentStore(dataDir) {
18
- storeDir = join(dataDir, "attachments");
19
- if (!existsSync(storeDir)) {
20
- mkdirSync(storeDir, { recursive: true });
21
- }
22
- return storeDir;
41
+ const dir = join(dataDir, "attachments");
42
+ if (!existsSync(dir))
43
+ mkdirSync(dir, { recursive: true });
44
+ store = { dir, files: new Map() };
45
+ return dir;
23
46
  }
24
47
  const MIME_EXT_MAP = {
25
48
  "image/png": ".png",
@@ -46,13 +69,14 @@ const EXT_MIME_MAP = {
46
69
  * 已存在同哈希文件则直接返回元数据,不重复写盘。
47
70
  */
48
71
  export async function saveAttachment(buffer, mimeType = "application/octet-stream", preferredExt) {
49
- if (!storeDir) {
72
+ if (!store) {
50
73
  throw new Error("AttachmentStore has not been initialized with initAttachmentStore(dataDir)");
51
74
  }
52
75
  const hash = createHash("sha256").update(buffer).digest("hex");
53
76
  const ext = preferredExt || MIME_EXT_MAP[mimeType] || ".bin";
54
77
  const fileName = `${hash}${ext}`;
55
- const filePath = join(storeDir, fileName);
78
+ const target = store;
79
+ const filePath = join(target.dir, fileName);
56
80
  if (!existsSync(filePath)) {
57
81
  // 原地 writeFile 有两个问题:a) 同 hash 并发写时两个 writeFileSync
58
82
  // 交错会留下半个文件;b) 读方(/api/attachment/:hash)可能在写完前就命中。
@@ -67,10 +91,11 @@ export async function saveAttachment(buffer, mimeType = "application/octet-strea
67
91
  catch (err) {
68
92
  await rm(tmpPath, { force: true }).catch(() => { });
69
93
  const code = err.code;
70
- if (code !== "EEXIST" && code !== "EPERM")
94
+ if ((code !== "EEXIST" && code !== "EPERM") || !existsSync(filePath))
71
95
  throw err;
72
96
  }
73
97
  }
98
+ indexFile(target, fileName);
74
99
  return {
75
100
  hash,
76
101
  size: buffer.length,
@@ -85,13 +110,14 @@ export async function saveAttachment(buffer, mimeType = "application/octet-strea
85
110
  * 已存在同哈希文件则直接返回元数据,不重复写盘。
86
111
  */
87
112
  export function saveAttachmentSync(buffer, mimeType = "application/octet-stream", preferredExt) {
88
- if (!storeDir) {
113
+ if (!store) {
89
114
  throw new Error("AttachmentStore has not been initialized with initAttachmentStore(dataDir)");
90
115
  }
91
116
  const hash = createHash("sha256").update(buffer).digest("hex");
92
117
  const ext = preferredExt || MIME_EXT_MAP[mimeType] || ".bin";
93
118
  const fileName = `${hash}${ext}`;
94
- const filePath = join(storeDir, fileName);
119
+ const target = store;
120
+ const filePath = join(target.dir, fileName);
95
121
  if (!existsSync(filePath)) {
96
122
  try {
97
123
  writeAtomicSync(filePath, buffer);
@@ -116,6 +142,7 @@ export function saveAttachmentSync(buffer, mimeType = "application/octet-stream"
116
142
  throw err;
117
143
  }
118
144
  }
145
+ indexFile(target, fileName);
119
146
  return {
120
147
  hash,
121
148
  size: buffer.length,
@@ -126,37 +153,46 @@ export function saveAttachmentSync(buffer, mimeType = "application/octet-stream"
126
153
  };
127
154
  }
128
155
  /**
129
- * 根据哈希查找已存储的附件文件路径及元数据。
156
+ * 根据哈希定位附件;filePath、size、mimeType 可直接用于 HTTP 流式发送。
157
+ * 首次有效查询惰性异步扫描旧目录,并发查询共享扫描;后续查询只访问索引。
158
+ * 保存成功会增量更新索引。外部导入文件后需重新 initAttachmentStore。
130
159
  */
131
160
  export async function findAttachment(hash) {
132
- if (!storeDir || !existsSync(storeDir))
133
- return null;
134
- // 校验 hash 必须是 64 位十六进制字符串(防止目录遍历)
135
- if (!/^[a-f0-9]{64}$/i.test(hash))
161
+ const target = store;
162
+ if (!target || !/^[a-f0-9]{64}$/i.test(hash))
136
163
  return null;
137
164
  try {
138
- const files = readdirSync(storeDir);
139
- // 跳过原子写(tmp + rename)崩溃时可能残留的 .tmp —— 前缀同为 hash,
140
- // 若被命中会拿到错误的后缀与 MIME。
141
- const match = files.find((f) => f.startsWith(hash) && !f.endsWith(".tmp"));
142
- if (!match)
165
+ await ensureIndex(target);
166
+ const files = target.files.get(hash);
167
+ if (!files)
143
168
  return null;
144
- const filePath = join(storeDir, match);
145
- const st = await stat(filePath);
146
- const ext = extname(match).toLowerCase();
147
- const mimeType = EXT_MIME_MAP[ext] || "application/octet-stream";
148
- return {
149
- hash,
150
- size: st.size,
151
- mimeType,
152
- ext,
153
- url: `/api/attachment/${hash}`,
154
- filePath,
155
- };
169
+ for (const fileName of [...files].sort()) {
170
+ const filePath = join(target.dir, fileName);
171
+ try {
172
+ const st = await stat(filePath);
173
+ if (!st.isFile())
174
+ continue;
175
+ const ext = extname(fileName).toLowerCase();
176
+ return {
177
+ hash,
178
+ size: st.size,
179
+ mimeType: EXT_MIME_MAP[ext] || "application/octet-stream",
180
+ ext,
181
+ url: `/api/attachment/${hash}`,
182
+ filePath,
183
+ };
184
+ }
185
+ catch (error) {
186
+ const code = error.code;
187
+ if (code === "ENOENT" || code === "ENOTDIR")
188
+ files.delete(fileName);
189
+ }
190
+ }
156
191
  }
157
192
  catch {
158
193
  return null;
159
194
  }
195
+ return null;
160
196
  }
161
197
  /**
162
198
  * 读取附件二进制数据。
@@ -1,3 +1,4 @@
1
+ import { uploadLimitBytes, isUploadDataTooLong } from "./payload-limits.js";
1
2
  import { formatTextQuote, readTextQuote } from "./text-quote.js";
2
3
  import { sniffImageMime } from "./text-sniff.js";
3
4
  import { saveUpload, uploadsRoot } from "./uploads.js";
@@ -306,7 +307,7 @@ export async function buildAttachmentMessages(ctx, attachments) {
306
307
  // `path` is unused — the reference travels in conversationId (running
307
308
  // conversation, incl. subagents) or sessionPath (history transcript).
308
309
  // The transcript is NOT inlined here (it can be huge and goes stale);
309
- // the model fetches it on demand with the conversation_read tool.
310
+ // the model fetches it on demand with the conversation tool.
310
311
  if (att.mode === "conversation") {
311
312
  const convId = att.conversationId;
312
313
  const sessPath = att.sessionPath;
@@ -324,15 +325,15 @@ export async function buildAttachmentMessages(ctx, attachments) {
324
325
  }
325
326
  const ref = id ? `id="${attr(id)}"` : `path="${attr(sp)}"`;
326
327
  const how = id
327
- ? `Use the conversation_read tool with id="${attr(id)}" to read its messages.`
328
- : `Use the conversation_read tool with path="${attr(sp)}" to read its transcript.`;
328
+ ? `Use the conversation tool with action="read", id="${attr(id)}" to read its messages.`
329
+ : `Use the conversation tool with action="read", path="${attr(sp)}" to read its transcript.`;
329
330
  out.push({
330
331
  message: {
331
332
  customType: "file",
332
333
  content: [
333
334
  {
334
335
  type: "text",
335
- text: `\n<conversation-ref ${ref} title="${attr(title)}">\nThe user quoted another conversation "${attr(title)}". ${how} Do not guess its contents.\n用户引用了另一个对话,别猜它的内容,用 conversation_read 去读。\n</conversation-ref>`,
336
+ text: `\n<conversation-ref ${ref} title="${attr(title)}">\nThe user quoted another conversation "${attr(title)}". ${how} Do not guess its contents.\n用户引用了另一个对话,别猜它的内容,用 conversation 去读。\n</conversation-ref>`,
336
337
  },
337
338
  ],
338
339
  display: true,
@@ -471,8 +472,17 @@ export async function buildAttachmentMessages(ctx, attachments) {
471
472
  // them on demand with its read tool (absolute path, no traversal guard
472
473
  // needed — the path is server-generated). Always a path reference.
473
474
  if (att.fileData) {
475
+ const maxBytes = uploadLimitBytes(ctx.settings, "chat");
476
+ if (isUploadDataTooLong(att.fileData.length, maxBytes)) {
477
+ ctx.emit({
478
+ type: "notice",
479
+ level: "warning",
480
+ text: `文件过大已跳过(>${maxBytes / 1024 / 1024}MB):${att.name ?? "上传文件"}`,
481
+ textEn: `File too large, skipped (>${maxBytes / 1024 / 1024}MB): ${att.name ?? "uploaded file"}`,
482
+ });
483
+ continue;
484
+ }
474
485
  const buf = Buffer.from(att.fileData, "base64");
475
- const MAX_UPLOAD_BYTES = 20 * 1024 * 1024;
476
486
  if (buf.length === 0) {
477
487
  ctx.emit({
478
488
  type: "notice",
@@ -482,12 +492,12 @@ export async function buildAttachmentMessages(ctx, attachments) {
482
492
  });
483
493
  continue;
484
494
  }
485
- if (buf.length > MAX_UPLOAD_BYTES) {
495
+ if (buf.length > maxBytes) {
486
496
  ctx.emit({
487
497
  type: "notice",
488
498
  level: "warning",
489
- text: `文件过大已跳过(>20MB):${att.name ?? "上传文件"}`,
490
- textEn: `File too large, skipped (>20MB): ${att.name ?? "uploaded file"}`,
499
+ text: `文件过大已跳过(>${maxBytes / 1024 / 1024}MB):${att.name ?? "上传文件"}`,
500
+ textEn: `File too large, skipped (>${maxBytes / 1024 / 1024}MB): ${att.name ?? "uploaded file"}`,
491
501
  });
492
502
  continue;
493
503
  }
@@ -3,9 +3,8 @@
3
3
  *
4
4
  * 动作:list(工程摘要)/ get(整图 JSON)/ create_graph(新建工程)/ delete_graph(删除工程)/
5
5
  * add_node / update_node / delete_node / add_edge / delete_edge / apply_dag(整图节点边替换,角色白名单+环检测)。
6
- * 运行与调试(run_all/run_node/stop/steer/review/get_log)暂不在 AI 工具内:运行态活在 CanvasOrchestrator
7
- * 内存里,工具 host 只有 dataDir,够不着;前端 Canvas Studio 已有全套运行/日志/审查 UI,见 canvas-dispatch.ts。
8
- * 直接读写 canvas-store 落盘文件;前端画布下次 load 即见,聊天里即时回执。
6
+ * 运行与调试通过注入的 CanvasOrchestrator;编辑走版本检查与严格校验,成功后广播。
7
+ * 运行失败广播明确错误,状态与证据由调度器统一持久化。
9
8
  */
10
9
  import { Type } from "typebox";
11
10
  import { defineTool } from "@earendil-works/pi-coding-agent";
@@ -13,6 +12,7 @@ import { pick } from "../i18n.js";
13
12
  import { CANVAS_TOOL_NAME } from "../tool-manager.js";
14
13
  import { deleteCanvasGraph, listCanvasGraphs, loadCanvasGraph, saveCanvasGraph } from "./canvas-store.js";
15
14
  import { addCustomCard, deleteCustomCard, listCustomCards, updateCustomCard } from "./canvas-cards.js";
15
+ import { assertCanvasGraph } from "./canvas-validation.js";
16
16
  /** 新节点 cwd:显式参数 > 当前项目 > 服务启动目录(".") */
17
17
  function defaultNodeCwd(host, p) {
18
18
  const explicit = typeof p.cwd === "string" ? p.cwd.trim().slice(0, 256) : "";
@@ -48,7 +48,10 @@ function pushCards(dataDir) {
48
48
  }
49
49
  }
50
50
  function saveAndPush(dataDir, graph) {
51
- saveCanvasGraph(dataDir, graph);
51
+ assertCanvasGraph(graph);
52
+ const result = saveCanvasGraph(dataDir, graph, { expectedRev: graph.rev ?? 0 });
53
+ if (result.conflict)
54
+ throw new Error("Canvas changed; get the latest graph before editing again");
52
55
  try {
53
56
  canvasBroadcaster?.({ type: "canvas_graph_state", graph });
54
57
  }
@@ -156,10 +159,16 @@ function hasCycle(n, edges) {
156
159
  }
157
160
  export function makeCanvasTool(host, lang) {
158
161
  const getLang = lang ?? host.lang ?? (() => "en");
159
- const text = (t, details = {}) => ({
160
- content: [{ type: "text", text: t }],
161
- details,
162
- });
162
+ const text = (t, details = {}) => {
163
+ const encoded = JSON.stringify(details);
164
+ const oversized = Buffer.byteLength(encoded, "utf8") > 60_000;
165
+ return {
166
+ content: [{ type: "text", text: oversized ? `${t}\n${encoded}` : t }],
167
+ details: oversized
168
+ ? { truncated: true, note: "Full graph is included in text; details exceeded the UI budget" }
169
+ : details,
170
+ };
171
+ };
163
172
  return defineTool({
164
173
  name: CANVAS_TOOL_NAME,
165
174
  label: "Canvas pipeline",
@@ -278,7 +287,7 @@ export function makeCanvasTool(host, lang) {
278
287
  return text(pick(getLang(), "缺少 graphId,先用 action=list 查看工程。", "Missing graphId; call action=list first.", "canvas.missing.id", {}), { ok: false });
279
288
  if (graphId === "default")
280
289
  return text(pick(getLang(), "默认工程不可删。", "The default graph cannot be deleted.", "canvas.graph.protected", {}), { ok: false });
281
- const ok = deleteCanvasGraph(dataDir, graphId);
290
+ const ok = canvasRuntime ? canvasRuntime.deleteGraph(graphId) : deleteCanvasGraph(dataDir, graphId);
282
291
  if (ok) {
283
292
  try {
284
293
  canvasBroadcaster?.({ type: "canvas_list_result", graphs: listCanvasGraphs(dataDir) });
@@ -362,7 +371,22 @@ export function makeCanvasTool(host, lang) {
362
371
  return text(pick(getLang(), `节点不存在:${nodeId}`, `Node not found: ${nodeId}`, "canvas.node.missing", {}), { ok: false });
363
372
  const patch = (p.patch ?? {});
364
373
  for (const [k, v] of Object.entries(patch)) {
365
- if (["id", "status", "activeConvId"].includes(k))
374
+ if (![
375
+ "title",
376
+ "role",
377
+ "x",
378
+ "y",
379
+ "width",
380
+ "height",
381
+ "engine",
382
+ "model",
383
+ "thinkingLevel",
384
+ "cwd",
385
+ "useWorktree",
386
+ "systemPromptOverride",
387
+ "instruction",
388
+ "config",
389
+ ].includes(k))
366
390
  continue;
367
391
  if (k === "role" && typeof v === "string" && !VALID_ROLES.has(v))
368
392
  continue;
@@ -423,7 +447,11 @@ export function makeCanvasTool(host, lang) {
423
447
  }
424
448
  }
425
449
  const idx = rawNodes.map((_, i) => i);
426
- const normEdges = rawEdges.map((e) => ({ from: Number(e.from ?? e.source), to: Number(e.to ?? e.target) }));
450
+ const normEdges = rawEdges.map((e) => ({
451
+ ...e,
452
+ from: Number(e.from ?? e.source),
453
+ to: Number(e.to ?? e.target),
454
+ }));
427
455
  for (const e of normEdges) {
428
456
  if (!idx.includes(e.from) || !idx.includes(e.to) || e.from === e.to) {
429
457
  return text(pick(getLang(), "边下标非法。", "Invalid edge indices.", "canvas.dag.edge", {}), {
@@ -449,12 +477,16 @@ export function makeCanvasTool(host, lang) {
449
477
  useWorktree: false,
450
478
  status: "idle",
451
479
  ...(typeof n.instruction === "string" && n.instruction ? { instruction: n.instruction } : {}),
480
+ ...(n.config && typeof n.config === "object" ? { config: n.config } : {}),
452
481
  }));
453
482
  const edges = normEdges.map((e, i) => ({
454
483
  id: `e_${now}_${i}`,
455
484
  sourceNodeId: nodes[e.from].id,
456
485
  targetNodeId: nodes[e.to].id,
457
- type: "handoff",
486
+ type: (e.type ?? "handoff"),
487
+ ...(typeof e.sourcePort === "string" ? { sourcePort: e.sourcePort } : {}),
488
+ ...(typeof e.targetPort === "string" ? { targetPort: e.targetPort } : {}),
489
+ ...(typeof e.label === "string" ? { label: e.label } : {}),
458
490
  }));
459
491
  const next = { ...graph, nodes, edges, updatedAt: now };
460
492
  saveAndPush(dataDir, next);
@@ -477,7 +509,16 @@ export function makeCanvasTool(host, lang) {
477
509
  return text(pick(getLang(), "运行态未就绪(服务刚启动/未注入),请稍后重试或在 Canvas Studio 里操作。", "Canvas runtime not ready; retry later or use Canvas Studio.", "canvas.runtime.missing", {}), { ok: false });
478
510
  const nodeId = typeof p.nodeId === "string" ? p.nodeId : "";
479
511
  if (action === "run_all") {
480
- void canvasRuntime.runAll(graph, typeof p.prompt === "string" ? p.prompt : undefined, host.getCwd?.());
512
+ void canvasRuntime
513
+ .runAll(graph, typeof p.prompt === "string" ? p.prompt : undefined, host.getCwd?.())
514
+ .catch((error) => {
515
+ canvasBroadcaster?.({
516
+ type: "canvas_error",
517
+ code: "execution_error",
518
+ graphId,
519
+ message: error.message,
520
+ });
521
+ });
481
522
  return text(pick(getLang(), `已启动整图运行:${graph.name},进度在 Canvas Studio 看直播。`, `Started run-all for ${graph.name}; watch progress in Canvas Studio.`, "canvas.run.started", {}), { ok: true, graphId });
482
523
  }
483
524
  if (action === "run_node") {
@@ -485,7 +526,16 @@ export function makeCanvasTool(host, lang) {
485
526
  return text(pick(getLang(), "缺少 nodeId。", "Missing nodeId.", "canvas.node.missing", {}), {
486
527
  ok: false,
487
528
  });
488
- void canvasRuntime.runNode(graph, nodeId, typeof p.prompt === "string" ? p.prompt : undefined, host.getCwd?.());
529
+ void canvasRuntime
530
+ .runNode(graph, nodeId, typeof p.prompt === "string" ? p.prompt : undefined, host.getCwd?.())
531
+ .catch((error) => {
532
+ canvasBroadcaster?.({
533
+ type: "canvas_error",
534
+ code: "execution_error",
535
+ graphId,
536
+ message: error.message,
537
+ });
538
+ });
489
539
  return text(pick(getLang(), `已启动节点 ${nodeId},日志可用 get_log 查看。`, `Started node ${nodeId}; use get_log to inspect.`, "canvas.node.started", {}), { ok: true, graphId, nodeId });
490
540
  }
491
541
  if (action === "stop_node") {
@@ -502,7 +552,7 @@ export function makeCanvasTool(host, lang) {
502
552
  const message = typeof p.message === "string" ? p.message : "";
503
553
  if (!nodeId || !message)
504
554
  return text(pick(getLang(), "steer 需要 nodeId + message。", "steer needs nodeId + message.", "canvas.steer.bad", {}), { ok: false });
505
- canvasRuntime.steerNode(graphId, nodeId, message);
555
+ await canvasRuntime.steerNode(graphId, nodeId, message);
506
556
  return text(pick(getLang(), `已向节点 ${nodeId} 追问/转向。`, `Steered node ${nodeId}.`, "canvas.steered", {}), { ok: true });
507
557
  }
508
558
  if (action === "review_node") {