pi-web-ui 0.113.1 → 0.114.1

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 (280) hide show
  1. package/CHANGELOG.md +71 -1
  2. package/README.md +187 -316
  3. package/README.zh-CN.md +227 -299
  4. package/README.zh-TW.md +227 -299
  5. package/bin/device-hub-cli.mjs +577 -0
  6. package/bin/frp-manager.mjs +1573 -1573
  7. package/bin/pi-device-hub.mjs +9 -0
  8. package/bin/pi-web-ui.mjs +4081 -4041
  9. package/deploy/nginx-subpath.conf +100 -100
  10. package/deploy/pi-web-ui.service +36 -36
  11. package/dist/server/agent-service-daemon.js +102 -24
  12. package/dist/server/agent-service.js +2419 -1174
  13. package/dist/server/approval-rules.js +29 -3
  14. package/dist/server/ask-user-question-tool.js +8 -8
  15. package/dist/server/atomic-file.js +35 -14
  16. package/dist/server/attachment-store.js +71 -35
  17. package/dist/server/attachments.js +69 -13
  18. package/dist/server/canvas/canvas-agent-tool.js +68 -18
  19. package/dist/server/canvas/canvas-cards.js +1 -1
  20. package/dist/server/canvas/canvas-dispatch.js +61 -20
  21. package/dist/server/canvas/canvas-orchestrator.js +519 -202
  22. package/dist/server/canvas/canvas-scheduled-task.js +45 -0
  23. package/dist/server/canvas/canvas-scheduler.js +99 -0
  24. package/dist/server/canvas/canvas-store.js +107 -54
  25. package/dist/server/canvas/canvas-validation.js +131 -0
  26. package/dist/server/canvas/canvas-workspace.js +284 -0
  27. package/dist/server/client-id-utils.js +8 -0
  28. package/dist/server/client-state.js +110 -24
  29. package/dist/server/communicate-tool.js +76 -0
  30. package/dist/server/compact-context-tool.js +2 -3
  31. package/dist/server/compaction-instructions.js +75 -0
  32. package/dist/server/compaction-markers.js +7 -2
  33. package/dist/server/compaction-state.js +84 -0
  34. package/dist/server/composer-drafts.js +43 -40
  35. package/dist/server/context-evidence.js +346 -0
  36. package/dist/server/conversation-communication.js +368 -0
  37. package/dist/server/conversation-read-tool.js +3 -4
  38. package/dist/server/conversation-tool-names.js +14 -0
  39. package/dist/server/conversation-tool.js +57 -0
  40. package/dist/server/delegate-mode.js +17 -4
  41. package/dist/server/device-center/bot-catalog.js +88 -0
  42. package/dist/server/device-center/bot-execution.js +106 -0
  43. package/dist/server/device-center/bots.js +170 -0
  44. package/dist/server/device-center/collab-service.js +153 -0
  45. package/dist/server/device-center/collab-tool.js +184 -0
  46. package/dist/server/device-center/connector.js +351 -0
  47. package/dist/server/device-center/desktop-linux.js +372 -0
  48. package/dist/server/device-center/desktop-native.js +413 -0
  49. package/dist/server/device-center/desktop-page.js +232 -0
  50. package/dist/server/device-center/desktop-setup.js +30 -0
  51. package/dist/server/device-center/desktop.js +387 -0
  52. package/dist/server/device-center/device-portals.js +241 -0
  53. package/dist/server/device-center/execution-failure.js +70 -0
  54. package/dist/server/device-center/executor.js +371 -0
  55. package/dist/server/device-center/file-sync.js +493 -0
  56. package/dist/server/device-center/hub-auth.js +69 -0
  57. package/dist/server/device-center/hub-page.js +68 -0
  58. package/dist/server/device-center/hub-setup.js +214 -0
  59. package/dist/server/device-center/hub.js +830 -0
  60. package/dist/server/device-center/local-hub.js +92 -0
  61. package/dist/server/device-center/local.js +529 -0
  62. package/dist/server/device-center/main.js +118 -0
  63. package/dist/server/device-center/native-desktop/macos.js +192 -0
  64. package/dist/server/device-center/native-desktop/windows.js +118 -0
  65. package/dist/server/device-center/path-portal.js +120 -0
  66. package/dist/server/device-center/relay.js +996 -0
  67. package/dist/server/device-center/runtime.js +253 -0
  68. package/dist/server/device-center/store.js +122 -0
  69. package/dist/server/device-center/task-error.js +14 -0
  70. package/dist/server/device-center/transfers.js +293 -0
  71. package/dist/server/device-center/workspaces.js +45 -0
  72. package/dist/server/dispatch-domain-handlers.js +84 -27
  73. package/dist/server/dsh/dsh-agent-service.js +282 -159
  74. package/dist/server/dsh/dsh-client.js +12 -2
  75. package/dist/server/dsh/runtime/cordis.yml +1 -1
  76. package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
  77. package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
  78. package/dist/server/dsh/runtime/launcher.mjs +235 -235
  79. package/dist/server/dsh/runtime/override.patch.yml +89 -89
  80. package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
  81. package/dist/server/durable/durable-agent-service.js +1 -1
  82. package/dist/server/engine-probe.js +36 -6
  83. package/dist/server/eval-tool.js +135 -135
  84. package/dist/server/evidence-tool-hooks.js +49 -0
  85. package/dist/server/file-save.js +95 -0
  86. package/dist/server/file-transfer-routes.js +97 -47
  87. package/dist/server/files-service.js +38 -26
  88. package/dist/server/global-loader.js +40 -2
  89. package/dist/server/goal-review-gate.js +16 -6
  90. package/dist/server/goal-service.js +54 -30
  91. package/dist/server/http-proxy.js +120 -0
  92. package/dist/server/index.js +285 -255
  93. package/dist/server/load-timing.js +31 -0
  94. package/dist/server/mcp-bridge.js +219 -94
  95. package/dist/server/mcp-hot-reload.js +31 -5
  96. package/dist/server/mcp-manager.js +192 -93
  97. package/dist/server/mcp-oauth-login.js +169 -0
  98. package/dist/server/mcp-oauth-ui.js +137 -0
  99. package/dist/server/mcp-oauth.js +395 -0
  100. package/dist/server/mcp-project-runtime.js +207 -0
  101. package/dist/server/message-window.js +74 -21
  102. package/dist/server/net-guard.js +122 -20
  103. package/dist/server/patch-bash-process.js +125 -0
  104. package/dist/server/patch-tool.js +9 -9
  105. package/dist/server/patch-turn-end-boundary.js +3 -3
  106. package/dist/server/payload-limits.js +17 -0
  107. package/dist/server/pending-question.js +82 -0
  108. package/dist/server/persona-chain.js +8 -8
  109. package/dist/server/plan-mode.js +338 -137
  110. package/dist/server/plugin-assets.js +8 -4
  111. package/dist/server/plugin-chat-attachments.js +48 -0
  112. package/dist/server/plugin-facilities.js +67 -220
  113. package/dist/server/plugin-installer.js +2 -1
  114. package/dist/server/plugin-removal.js +49 -0
  115. package/dist/server/plugin-secrets.js +179 -0
  116. package/dist/server/plugins.js +288 -94
  117. package/dist/server/preset-fields.js +56 -0
  118. package/dist/server/preset-plugin-dependencies.js +57 -0
  119. package/dist/server/preset-share.js +113 -72
  120. package/dist/server/prompt-templates.js +106 -0
  121. package/dist/server/protocol-version.js +1 -1
  122. package/dist/server/queue-modes.js +10 -0
  123. package/dist/server/remote-ssh-service.js +199 -106
  124. package/dist/server/request-context.js +164 -0
  125. package/dist/server/resolve-global-sdk.js +2 -0
  126. package/dist/server/sandbox-data.js +655 -0
  127. package/dist/server/sandbox-engines.js +7 -0
  128. package/dist/server/sandbox-runtime-gate.js +41 -0
  129. package/dist/server/sandbox-service.js +139 -698
  130. package/dist/server/sandbox-tool.js +21 -4
  131. package/dist/server/schedule-agent-tool.js +39 -21
  132. package/dist/server/scheduler-tasks.js +106 -55
  133. package/dist/server/scm-commitmsg.js +10 -10
  134. package/dist/server/serialize.js +48 -19
  135. package/dist/server/session-branch.js +25 -3
  136. package/dist/server/session-parser.js +28 -18
  137. package/dist/server/session-scan.js +130 -0
  138. package/dist/server/session-search.js +51 -37
  139. package/dist/server/settings-service.js +273 -111
  140. package/dist/server/setup-config.js +58 -0
  141. package/dist/server/setup-page.js +620 -620
  142. package/dist/server/skill-maintenance.js +112 -24
  143. package/dist/server/subagent-helpers.js +4 -1
  144. package/dist/server/subagent-notify.js +4 -1
  145. package/dist/server/subagent-security-gate.js +52 -11
  146. package/dist/server/subagent-task.js +27 -0
  147. package/dist/server/subagents.js +217 -46
  148. package/dist/server/tabs.js +9 -1
  149. package/dist/server/terminals.js +467 -363
  150. package/dist/server/text-quote.js +9 -0
  151. package/dist/server/tool-guards.js +42 -6
  152. package/dist/server/tool-manager.js +48 -20
  153. package/dist/server/tool-overrides.js +13 -11
  154. package/dist/server/tool-prompt-overrides.js +32 -2
  155. package/dist/server/tool-prompts.js +1 -1
  156. package/dist/server/turn-timing.js +11 -0
  157. package/dist/server/universal/drivers/claude-code.js +5 -0
  158. package/dist/server/universal/drivers/codex.js +336 -0
  159. package/dist/server/universal/index.js +1 -0
  160. package/dist/server/universal/session-store.js +48 -6
  161. package/dist/server/universal/universal-attachments.js +24 -1
  162. package/dist/server/universal/universal-service.js +1 -1
  163. package/dist/server/universal/universal-session.js +357 -231
  164. package/dist/server/uploads.js +64 -5
  165. package/dist/server/vision-bridge.js +18 -18
  166. package/dist/server/worktree-service.js +32 -24
  167. package/dist/server/ws-pending-queue.js +73 -27
  168. package/docs/device-center.md +148 -0
  169. package/docs/device-desktop.md +48 -0
  170. package/docs/dsh-engine.md +493 -493
  171. package/extensions/webui.ts +335 -335
  172. package/package.json +5 -2
  173. package/plugin-sdk/README.md +174 -174
  174. package/plugin-sdk/client-utils.mjs +279 -279
  175. package/plugin-sdk/import-check.mjs +210 -210
  176. package/plugin-sdk/index.d.ts +698 -676
  177. package/plugin-sdk/index.mjs +696 -696
  178. package/plugin-sdk/package.json +13 -13
  179. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  180. package/plugins/catalog.json +11 -1
  181. package/themes/aetheris.css +501 -607
  182. package/themes/ayu-light.css +116 -140
  183. package/themes/bases/flow-base.css +1357 -1363
  184. package/themes/bases/obsidian-base.css +895 -895
  185. package/themes/bases/statusbar-flat-base.css +112 -0
  186. package/themes/bases/zhujian-base.css +688 -687
  187. package/themes/bases/zhupi-base.css +660 -659
  188. package/themes/catppuccin-latte.css +119 -142
  189. package/themes/catppuccin.css +116 -147
  190. package/themes/claude-code-dark.css +147 -146
  191. package/themes/codex.css +114 -138
  192. package/themes/cyberpunk.css +50 -108
  193. package/themes/dark-teal.css +264 -265
  194. package/themes/dazzle.css +38 -108
  195. package/themes/everforest-light.css +115 -138
  196. package/themes/flow-light.css +164 -164
  197. package/themes/flow.css +161 -161
  198. package/themes/geist.css +114 -138
  199. package/themes/gruvbox-light.css +115 -138
  200. package/themes/kanagawa-lotus.css +115 -138
  201. package/themes/md-preview.css +24 -234
  202. package/themes/mist.css +166 -186
  203. package/themes/nord.css +107 -138
  204. package/themes/one-dark.css +106 -139
  205. package/themes/paper.css +174 -186
  206. package/themes/rose-pine-dawn.css +114 -138
  207. package/themes/sakura.css +166 -186
  208. package/themes/solarized-light.css +114 -137
  209. package/themes/tokyo-night.css +115 -146
  210. package/themes/translucent.css +85 -85
  211. package/themes/transparent.css +116 -116
  212. package/themes/vs-code-dark.css +147 -147
  213. package/themes/wallpaper-flow.css +382 -382
  214. package/themes/wallpaper-obsidian.css +74 -74
  215. package/themes/white.css +164 -186
  216. package/themes/zhujian-dark.css +115 -114
  217. package/themes/zhujian.css +114 -114
  218. package/themes/zhupi-dark.css +115 -114
  219. package/themes/zhupi.css +114 -114
  220. package/web/dist/.build-assets.json +1 -0
  221. package/web/dist/assets/BgTasksModal-BcXJ20RO.js +1 -0
  222. package/web/dist/assets/BgTasksModal-DjQmiKnE.js +1 -0
  223. package/web/dist/assets/CanvasStudio-PI9pid0Y.js +1579 -0
  224. package/web/dist/assets/CanvasStudio-nf5-HxLM.js +1579 -0
  225. package/web/dist/assets/DeviceCenter-CYttJw2a.js +3 -0
  226. package/web/dist/assets/DeviceCenter-DPe4sz74.js +3 -0
  227. package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
  228. package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
  229. package/web/dist/assets/FilePreview-C9Ut4Lq6.js +2 -0
  230. package/web/dist/assets/FilePreview-CvK3ZzX5.js +2 -0
  231. package/web/dist/assets/GlobalSearchModal-C5e-OCw2.js +1 -0
  232. package/web/dist/assets/GlobalSearchModal-H7pFK2UC.js +1 -0
  233. package/web/dist/assets/GroupConversation-C2wNM0dQ.js +1 -0
  234. package/web/dist/assets/GroupConversation-ChN3TWQK.js +1 -0
  235. package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
  236. package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
  237. package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
  238. package/web/dist/assets/SCMPanel-buTGziDB.js +2 -0
  239. package/web/dist/assets/SCMPanel-kx-SCL2s.js +2 -0
  240. package/web/dist/assets/SettingsModal-BsUF8jqr.js +20 -0
  241. package/web/dist/assets/SettingsModal-D357Ky7P.js +20 -0
  242. package/web/dist/assets/TerminalPanel-BBuM_Sez.js +3 -0
  243. package/web/dist/assets/TerminalPanel-D6x6xz8Q.js +3 -0
  244. package/web/dist/assets/TuiOverlayModal-CdbGV3Za.js +1 -0
  245. package/web/dist/assets/TuiOverlayModal-d6x9u25n.js +1 -0
  246. package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
  247. package/web/dist/assets/desktop-YguLbrX1.js +1 -0
  248. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  249. package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
  250. package/web/dist/assets/index-BPvpea8t.js +85 -0
  251. package/web/dist/assets/index-D6u8xH0o.js +85 -0
  252. package/web/dist/assets/index-DDZMv6LO.css +1 -0
  253. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  254. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  255. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  256. package/web/dist/assets/math-BorAY7qD.css +1 -0
  257. package/web/dist/assets/plugin-host-BRBg6zmQ.js +1 -0
  258. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  259. package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
  260. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  261. package/web/dist/index.html +42 -35
  262. package/web/dist/sw.js +179 -179
  263. package/web/public/sw.js +179 -179
  264. package/dist/gh-comment-781.md +0 -5
  265. package/dist/server/durable/durable-capabilities.js +0 -11
  266. package/dist/server/markers/builtins/services.js +0 -123
  267. package/dist/server/markers/builtins/todo.js +0 -189
  268. package/dist/server/markers-list-tool.js +0 -34
  269. package/dist/server/orchestrator.js +0 -109
  270. package/dist/server/system-prompt-soul.js +0 -41
  271. package/dist/server/univer-service.js +0 -448
  272. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  273. package/dist/test-artifact.md +0 -9
  274. package/dist/test-preview-modal.md +0 -11
  275. package/dist/test-report.html +0 -20
  276. package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
  277. package/web/dist/assets/index-ByiO9f-N.js +0 -2008
  278. package/web/dist/assets/index-ycGLh4a4.css +0 -1
  279. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  280. 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,10 +1,25 @@
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
- import { saveUpload, uploadsRoot } from "./uploads.js";
4
+ import { resolveDataDir, saveUpload, uploadsRoot } from "./uploads.js";
5
+ import { isSafeGraphId, loadCanvasGraph } from "./canvas/canvas-store.js";
6
+ import { existsSync } from "node:fs";
7
+ import { join } from "node:path";
4
8
  import { isAbsoluteWirePath, wireToAbs } from "./files-service.js";
5
9
  import { buildVisionBridgePrompt, findVisionModels, transcribeImages } from "./vision-bridge.js";
6
10
  import { saveAttachment } from "./attachment-store.js";
7
11
  import { getGlobalRemoteSshService, isRemoteWorkspaceUri, parseRemoteWorkspaceUri, resolveRemoteWorkspacePath, } from "./remote-ssh-service.js";
12
+ /** Resolve reference metadata without creating the store's implicit default graph. */
13
+ export function getCanvasReference(graphId) {
14
+ const dataDir = resolveDataDir();
15
+ if (!isSafeGraphId(graphId) || !existsSync(join(dataDir, "canvas", `${graphId}.json`))) {
16
+ throw new Error("Invalid or missing canvas reference");
17
+ }
18
+ const graph = loadCanvasGraph(dataDir, graphId);
19
+ if (graph.id !== graphId)
20
+ throw new Error("Canvas graph id mismatch");
21
+ return { id: graphId, title: graph.name || graphId };
22
+ }
8
23
  /** 跨快照的视觉转写缓存:批次 hash(名称 + base64 头 + 提示词)→ 转写文本。
9
24
  * 编辑重问重发相同图片不再重复耗视觉 token。进程级共享即可。
10
25
  * 长驻进程下无界 Map 会随图片种类缓慢吃内存(单条转写可达数十 KB),
@@ -137,7 +152,7 @@ export async function buildAttachmentMessages(ctx, attachments) {
137
152
  }
138
153
  continue;
139
154
  }
140
- if (att.fileData || !att.path)
155
+ if (att.mode === "canvas" || att.fileData || !att.path)
141
156
  continue;
142
157
  const ext = extname(att.path).toLowerCase();
143
158
  if (!IMAGE_EXT.has(ext) || ext === ".svg")
@@ -306,7 +321,7 @@ export async function buildAttachmentMessages(ctx, attachments) {
306
321
  // `path` is unused — the reference travels in conversationId (running
307
322
  // conversation, incl. subagents) or sessionPath (history transcript).
308
323
  // 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.
324
+ // the model fetches it on demand with the conversation tool.
310
325
  if (att.mode === "conversation") {
311
326
  const convId = att.conversationId;
312
327
  const sessPath = att.sessionPath;
@@ -324,15 +339,15 @@ export async function buildAttachmentMessages(ctx, attachments) {
324
339
  }
325
340
  const ref = id ? `id="${attr(id)}"` : `path="${attr(sp)}"`;
326
341
  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.`;
342
+ ? `Use the conversation tool with action="read", id="${attr(id)}" to read its messages.`
343
+ : `Use the conversation tool with action="read", path="${attr(sp)}" to read its transcript.`;
329
344
  out.push({
330
345
  message: {
331
346
  customType: "file",
332
347
  content: [
333
348
  {
334
349
  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>`,
350
+ 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
351
  },
337
352
  ],
338
353
  display: true,
@@ -341,6 +356,38 @@ export async function buildAttachmentMessages(ctx, attachments) {
341
356
  });
342
357
  continue;
343
358
  }
359
+ // Canvas identifiers are not filesystem paths. Resolve only through the canvas store.
360
+ if (att.mode === "canvas") {
361
+ const graphId = att.path;
362
+ try {
363
+ const { title } = getCanvasReference(graphId);
364
+ out.push({
365
+ message: {
366
+ customType: "file",
367
+ content: [
368
+ {
369
+ type: "text",
370
+ text: `
371
+ <canvas-ref id="${attr(graphId)}" title="${attr(title)}">
372
+ The user referenced this canvas. First use canvas(action="get", graphId="${attr(graphId)}") to inspect its topology and status. Only when the user requests execution, use canvas(action="run_all", graphId="${attr(graphId)}", prompt="the user requirements"); prompt supplies the run initialPrompt. Use canvas(action="get_log", graphId="${attr(graphId)}") for logs, and action="get" for status. This reference alone does not authorize or start a run.
373
+ </canvas-ref>`,
374
+ },
375
+ ],
376
+ display: true,
377
+ details: { mode: "canvas", path: graphId, name: title, title },
378
+ },
379
+ });
380
+ }
381
+ catch {
382
+ ctx.emit({
383
+ type: "notice",
384
+ level: "warning",
385
+ text: `画布引用无效或不存在,已跳过:${graphId}`,
386
+ textEn: `Invalid or missing canvas reference, skipped: ${graphId}`,
387
+ });
388
+ }
389
+ continue;
390
+ }
344
391
  // Granted web page (page-picker extension): `path` is the page origin,
345
392
  // NOT a workspace path — never stat/read it. The model gets the exact
346
393
  // browser_page target plus the fact that this page is already granted,
@@ -471,8 +518,17 @@ export async function buildAttachmentMessages(ctx, attachments) {
471
518
  // them on demand with its read tool (absolute path, no traversal guard
472
519
  // needed — the path is server-generated). Always a path reference.
473
520
  if (att.fileData) {
521
+ const maxBytes = uploadLimitBytes(ctx.settings, "chat");
522
+ if (isUploadDataTooLong(att.fileData.length, maxBytes)) {
523
+ ctx.emit({
524
+ type: "notice",
525
+ level: "warning",
526
+ text: `文件过大已跳过(>${maxBytes / 1024 / 1024}MB):${att.name ?? "上传文件"}`,
527
+ textEn: `File too large, skipped (>${maxBytes / 1024 / 1024}MB): ${att.name ?? "uploaded file"}`,
528
+ });
529
+ continue;
530
+ }
474
531
  const buf = Buffer.from(att.fileData, "base64");
475
- const MAX_UPLOAD_BYTES = 20 * 1024 * 1024;
476
532
  if (buf.length === 0) {
477
533
  ctx.emit({
478
534
  type: "notice",
@@ -482,12 +538,12 @@ export async function buildAttachmentMessages(ctx, attachments) {
482
538
  });
483
539
  continue;
484
540
  }
485
- if (buf.length > MAX_UPLOAD_BYTES) {
541
+ if (buf.length > maxBytes) {
486
542
  ctx.emit({
487
543
  type: "notice",
488
544
  level: "warning",
489
- text: `文件过大已跳过(>20MB):${att.name ?? "上传文件"}`,
490
- textEn: `File too large, skipped (>20MB): ${att.name ?? "uploaded file"}`,
545
+ text: `文件过大已跳过(>${maxBytes / 1024 / 1024}MB):${att.name ?? "上传文件"}`,
546
+ textEn: `File too large, skipped (>${maxBytes / 1024 / 1024}MB): ${att.name ?? "uploaded file"}`,
491
547
  });
492
548
  continue;
493
549
  }
@@ -653,9 +709,9 @@ export async function buildAttachmentMessages(ctx, attachments) {
653
709
  content: [
654
710
  {
655
711
  type: "text",
656
- text: `
657
- <vision-bridge>
658
- ${transcript}
712
+ text: `
713
+ <vision-bridge>
714
+ ${transcript}
659
715
  </vision-bridge>`,
660
716
  },
661
717
  ...(pathImg