@evandu/super-pi-server 0.0.0-stage → 0.1.259

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 (370) hide show
  1. package/README.md +248 -3
  2. package/agents/code-auditor.md +64 -0
  3. package/agents/code-designer.md +64 -0
  4. package/agents/coder.md +24 -0
  5. package/agents/critic.md +24 -0
  6. package/agents/document-organizer.md +48 -0
  7. package/agents/patcher.md +27 -0
  8. package/agents/planner.md +30 -0
  9. package/agents/project-leader.md +28 -0
  10. package/agents/reviewer.md +27 -0
  11. package/agents/scout.md +27 -0
  12. package/agents/solution-designer.md +62 -0
  13. package/agents/super-pi-documents/index.ts +92 -0
  14. package/agents/super-pi-feishu/index.ts +88 -0
  15. package/agents/super-pi-knowledge/index.ts +70 -0
  16. package/agents/super-pi-managed-model/index.ts +9 -0
  17. package/agents/super-pi-memory/index.ts +75 -0
  18. package/agents/super-pi-native-tools/index.ts +1 -0
  19. package/agents/super-pi-task/core.ts +2262 -0
  20. package/agents/super-pi-task/index.ts +814 -0
  21. package/agents/super-pi-task/workflow-schema.ts +34 -0
  22. package/agents/super-pi-web/index.ts +32 -0
  23. package/agents/verifier.md +25 -0
  24. package/assets/fonts/LICENSE +92 -0
  25. package/assets/fonts/NotoSansSC-Bold.otf +0 -0
  26. package/assets/fonts/NotoSansSC-Regular.otf +0 -0
  27. package/assets/knowledge-model/README.md +37 -0
  28. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/config.json +31 -0
  29. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/onnx/model_quantized.onnx +0 -0
  30. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/special_tokens_map.json +7 -0
  31. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer.json +21278 -0
  32. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer_config.json +15 -0
  33. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/vocab.txt +21128 -0
  34. package/bin/npm-prefix.d.ts +1 -0
  35. package/bin/npm-prefix.js +10 -0
  36. package/bin/super-pi.js +349 -0
  37. package/dist/client/.super-pi-client-sources.json +82 -0
  38. package/dist/client/assets/CodeMirrorEditor-mi9rGUce.js +2 -0
  39. package/dist/client/assets/GitDiffEditor-CpoDDQrA.css +1 -0
  40. package/dist/client/assets/GitDiffEditor-FQBfGxOY.js +29 -0
  41. package/dist/client/assets/diff-ChtP43wD.js +1 -0
  42. package/dist/client/assets/dist-AW5lyI3I.js +1 -0
  43. package/dist/client/assets/dist-B3-a6uF0.js +7 -0
  44. package/dist/client/assets/dist-BGxkyh6e.js +1 -0
  45. package/dist/client/assets/dist-BJxfd7yb.js +11 -0
  46. package/dist/client/assets/dist-BRVQKlcp.js +1 -0
  47. package/dist/client/assets/dist-BV64A9Ji.js +1 -0
  48. package/dist/client/assets/dist-BXAOrsjq.js +1 -0
  49. package/dist/client/assets/dist-CKF2Jksy.js +1 -0
  50. package/dist/client/assets/dist-CX_Hm4GS.js +1 -0
  51. package/dist/client/assets/dist-Cus6_oaF.js +2 -0
  52. package/dist/client/assets/dist-Cx00EZKR.js +23 -0
  53. package/dist/client/assets/dist-D71y2EI1.js +1 -0
  54. package/dist/client/assets/dist-D978o95T.js +5 -0
  55. package/dist/client/assets/dist-Dc1MBGAG.js +1 -0
  56. package/dist/client/assets/dist-Dds-qLxY.js +9 -0
  57. package/dist/client/assets/dist-DeD9copn.js +1 -0
  58. package/dist/client/assets/dist-DuvGReu-.js +6 -0
  59. package/dist/client/assets/dist-Dvb0SqcK.js +2 -0
  60. package/dist/client/assets/dist-J6XWqRpB.js +3 -0
  61. package/dist/client/assets/dist-QzbOCAU6.js +1 -0
  62. package/dist/client/assets/dist-moiMRpw_.js +1 -0
  63. package/dist/client/assets/dist-scBkrwv-.js +2 -0
  64. package/dist/client/assets/dockerfile-BDePf5PZ.js +1 -0
  65. package/dist/client/assets/index-Cn7hdrDw.js +350 -0
  66. package/dist/client/assets/index-UfzqdECL.css +1 -0
  67. package/dist/client/assets/powershell-D8WpQPaX.js +1 -0
  68. package/dist/client/assets/properties-C357ku5U.js +1 -0
  69. package/dist/client/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  70. package/dist/client/assets/ruby-ChfNwlCY.js +1 -0
  71. package/dist/client/assets/shell-DwuoZtxw.js +1 -0
  72. package/dist/client/assets/swift-DKB6_1j6.js +1 -0
  73. package/dist/client/assets/toml-BPTmHmyx.js +1 -0
  74. package/dist/client/favicon.ico +0 -0
  75. package/dist/client/favicon.png +0 -0
  76. package/dist/client/favicon.svg +10 -0
  77. package/dist/client/index.html +18 -0
  78. package/dist/extension.d.ts +15 -0
  79. package/dist/extension.js +126 -0
  80. package/dist/server/active-memory.d.ts +247 -0
  81. package/dist/server/active-memory.js +669 -0
  82. package/dist/server/agents.d.ts +245 -0
  83. package/dist/server/agents.js +701 -0
  84. package/dist/server/application/catalog-service.d.ts +98 -0
  85. package/dist/server/application/catalog-service.js +245 -0
  86. package/dist/server/application/conversation-service.d.ts +245 -0
  87. package/dist/server/application/conversation-service.js +654 -0
  88. package/dist/server/application/document-service.d.ts +68 -0
  89. package/dist/server/application/document-service.js +120 -0
  90. package/dist/server/application/extension-ui-service.d.ts +44 -0
  91. package/dist/server/application/extension-ui-service.js +135 -0
  92. package/dist/server/application/feishu-service.d.ts +179 -0
  93. package/dist/server/application/feishu-service.js +358 -0
  94. package/dist/server/application/group-chat-service.d.ts +75 -0
  95. package/dist/server/application/group-chat-service.js +953 -0
  96. package/dist/server/application/group-execution.d.ts +15 -0
  97. package/dist/server/application/group-execution.js +77 -0
  98. package/dist/server/application/project-service.d.ts +464 -0
  99. package/dist/server/application/project-service.js +2523 -0
  100. package/dist/server/application/provider-service.d.ts +174 -0
  101. package/dist/server/application/provider-service.js +510 -0
  102. package/dist/server/application/run-service.d.ts +547 -0
  103. package/dist/server/application/run-service.js +2683 -0
  104. package/dist/server/application/scheduled-task-service.d.ts +184 -0
  105. package/dist/server/application/scheduled-task-service.js +391 -0
  106. package/dist/server/application/session-orchestrator-service.d.ts +388 -0
  107. package/dist/server/application/session-orchestrator-service.js +1146 -0
  108. package/dist/server/application/session-reminder-service.d.ts +59 -0
  109. package/dist/server/application/session-reminder-service.js +141 -0
  110. package/dist/server/application/session-watchdog.d.ts +171 -0
  111. package/dist/server/application/session-watchdog.js +284 -0
  112. package/dist/server/application/workspace-service.d.ts +52 -0
  113. package/dist/server/application/workspace-service.js +186 -0
  114. package/dist/server/application/worktree-service.d.ts +13 -0
  115. package/dist/server/application/worktree-service.js +76 -0
  116. package/dist/server/browser-access.d.ts +34 -0
  117. package/dist/server/browser-access.js +89 -0
  118. package/dist/server/capability.d.ts +105 -0
  119. package/dist/server/capability.js +170 -0
  120. package/dist/server/command-handler.d.ts +93 -0
  121. package/dist/server/command-handler.js +540 -0
  122. package/dist/server/content-search.d.ts +16 -0
  123. package/dist/server/content-search.js +235 -0
  124. package/dist/server/conversation-usage.d.ts +22 -0
  125. package/dist/server/conversation-usage.js +43 -0
  126. package/dist/server/documents.d.ts +152 -0
  127. package/dist/server/documents.js +998 -0
  128. package/dist/server/engineering-learning.d.ts +30 -0
  129. package/dist/server/engineering-learning.js +106 -0
  130. package/dist/server/exec-service.d.ts +45 -0
  131. package/dist/server/exec-service.js +167 -0
  132. package/dist/server/explicit-file-open.d.ts +34 -0
  133. package/dist/server/explicit-file-open.js +105 -0
  134. package/dist/server/failure-text.d.ts +18 -0
  135. package/dist/server/failure-text.js +44 -0
  136. package/dist/server/feishu-cli.d.ts +223 -0
  137. package/dist/server/feishu-cli.js +464 -0
  138. package/dist/server/file-changes.d.ts +119 -0
  139. package/dist/server/file-changes.js +280 -0
  140. package/dist/server/file-diff.d.ts +41 -0
  141. package/dist/server/file-diff.js +97 -0
  142. package/dist/server/file-index.d.ts +100 -0
  143. package/dist/server/file-index.js +296 -0
  144. package/dist/server/file-name-index.d.ts +160 -0
  145. package/dist/server/file-name-index.js +411 -0
  146. package/dist/server/files.d.ts +269 -0
  147. package/dist/server/files.js +748 -0
  148. package/dist/server/git.d.ts +245 -0
  149. package/dist/server/git.js +903 -0
  150. package/dist/server/http-server.d.ts +45 -0
  151. package/dist/server/http-server.js +3830 -0
  152. package/dist/server/index.d.ts +1 -0
  153. package/dist/server/index.js +485 -0
  154. package/dist/server/inline-thinking.d.ts +90 -0
  155. package/dist/server/inline-thinking.js +181 -0
  156. package/dist/server/json-comments.d.ts +14 -0
  157. package/dist/server/json-comments.js +71 -0
  158. package/dist/server/knowledge-embedding-worker.d.ts +1 -0
  159. package/dist/server/knowledge-embedding-worker.js +27 -0
  160. package/dist/server/knowledge-vectors.d.ts +150 -0
  161. package/dist/server/knowledge-vectors.js +385 -0
  162. package/dist/server/knowledge.d.ts +273 -0
  163. package/dist/server/knowledge.js +848 -0
  164. package/dist/server/length-continuation.d.ts +83 -0
  165. package/dist/server/length-continuation.js +118 -0
  166. package/dist/server/logging.d.ts +32 -0
  167. package/dist/server/logging.js +185 -0
  168. package/dist/server/managed-http-tunnel.d.ts +6 -0
  169. package/dist/server/managed-http-tunnel.js +85 -0
  170. package/dist/server/managed-http.d.ts +4 -0
  171. package/dist/server/managed-http.js +85 -0
  172. package/dist/server/managed-model-adapter.d.ts +17 -0
  173. package/dist/server/managed-model-adapter.js +75 -0
  174. package/dist/server/managed-model-gateway.d.ts +49 -0
  175. package/dist/server/managed-model-gateway.js +73 -0
  176. package/dist/server/managed-servers.d.ts +55 -0
  177. package/dist/server/managed-servers.js +392 -0
  178. package/dist/server/managed-ssh.d.ts +26 -0
  179. package/dist/server/managed-ssh.js +73 -0
  180. package/dist/server/manager-vault.d.ts +11 -0
  181. package/dist/server/manager-vault.js +67 -0
  182. package/dist/server/memory-recall.d.ts +25 -0
  183. package/dist/server/memory-recall.js +45 -0
  184. package/dist/server/memory.d.ts +67 -0
  185. package/dist/server/memory.js +216 -0
  186. package/dist/server/message-media.d.ts +7 -0
  187. package/dist/server/message-media.js +54 -0
  188. package/dist/server/model-context-window.d.ts +186 -0
  189. package/dist/server/model-context-window.js +444 -0
  190. package/dist/server/model-filter.d.ts +23 -0
  191. package/dist/server/model-filter.js +48 -0
  192. package/dist/server/models-store.d.ts +36 -0
  193. package/dist/server/models-store.js +132 -0
  194. package/dist/server/native-tool-settings.d.ts +25 -0
  195. package/dist/server/native-tool-settings.js +41 -0
  196. package/dist/server/native-tools-extension.d.ts +2 -0
  197. package/dist/server/native-tools-extension.js +39 -0
  198. package/dist/server/native-tools-service.d.ts +39 -0
  199. package/dist/server/native-tools-service.js +240 -0
  200. package/dist/server/persistence/app-state-repository.d.ts +65 -0
  201. package/dist/server/persistence/app-state-repository.js +1 -0
  202. package/dist/server/persistence/json-state-repository.d.ts +14 -0
  203. package/dist/server/persistence/json-state-repository.js +43 -0
  204. package/dist/server/persistence/open-state-store.d.ts +3 -0
  205. package/dist/server/persistence/open-state-store.js +35 -0
  206. package/dist/server/persistence/rename.d.ts +22 -0
  207. package/dist/server/persistence/rename.js +44 -0
  208. package/dist/server/persistence/sqlite-state-repository.d.ts +12 -0
  209. package/dist/server/persistence/sqlite-state-repository.js +264 -0
  210. package/dist/server/pi-command.d.ts +94 -0
  211. package/dist/server/pi-command.js +265 -0
  212. package/dist/server/pi-native.d.ts +12 -0
  213. package/dist/server/pi-native.js +16 -0
  214. package/dist/server/pi-session-events.d.ts +158 -0
  215. package/dist/server/pi-session-events.js +373 -0
  216. package/dist/server/pi-session-pool.d.ts +233 -0
  217. package/dist/server/pi-session-pool.js +382 -0
  218. package/dist/server/pi-session.d.ts +642 -0
  219. package/dist/server/pi-session.js +655 -0
  220. package/dist/server/presentations/schema.d.ts +120 -0
  221. package/dist/server/presentations/schema.js +128 -0
  222. package/dist/server/provider-network.d.ts +16 -0
  223. package/dist/server/provider-network.js +106 -0
  224. package/dist/server/provider-proxy.d.ts +18 -0
  225. package/dist/server/provider-proxy.js +200 -0
  226. package/dist/server/providers.d.ts +333 -0
  227. package/dist/server/providers.js +989 -0
  228. package/dist/server/remote-bootstrap.d.ts +17 -0
  229. package/dist/server/remote-bootstrap.js +119 -0
  230. package/dist/server/rpc-channel.d.ts +131 -0
  231. package/dist/server/rpc-channel.js +135 -0
  232. package/dist/server/runtime.d.ts +1393 -0
  233. package/dist/server/runtime.js +3286 -0
  234. package/dist/server/scheduled-tasks.d.ts +101 -0
  235. package/dist/server/scheduled-tasks.js +138 -0
  236. package/dist/server/server-context.d.ts +119 -0
  237. package/dist/server/server-context.js +1 -0
  238. package/dist/server/session-cwd.d.ts +19 -0
  239. package/dist/server/session-cwd.js +58 -0
  240. package/dist/server/session-ledger.d.ts +67 -0
  241. package/dist/server/session-ledger.js +76 -0
  242. package/dist/server/session-memory-scope.d.ts +4 -0
  243. package/dist/server/session-memory-scope.js +30 -0
  244. package/dist/server/session-repository.d.ts +100 -0
  245. package/dist/server/session-repository.js +246 -0
  246. package/dist/server/session-tree-scope.d.ts +125 -0
  247. package/dist/server/session-tree-scope.js +337 -0
  248. package/dist/server/skills.d.ts +23 -0
  249. package/dist/server/skills.js +190 -0
  250. package/dist/server/store.d.ts +1062 -0
  251. package/dist/server/store.js +3305 -0
  252. package/dist/server/subagent-runs.d.ts +185 -0
  253. package/dist/server/subagent-runs.js +383 -0
  254. package/dist/server/subagents.d.ts +200 -0
  255. package/dist/server/subagents.js +619 -0
  256. package/dist/server/task-tool.d.ts +282 -0
  257. package/dist/server/task-tool.js +507 -0
  258. package/dist/server/tavily.d.ts +32 -0
  259. package/dist/server/tavily.js +136 -0
  260. package/dist/server/team-context.d.ts +12 -0
  261. package/dist/server/team-context.js +180 -0
  262. package/dist/server/terminal.d.ts +163 -0
  263. package/dist/server/terminal.js +557 -0
  264. package/dist/server/thinking-level-discovery.d.ts +38 -0
  265. package/dist/server/thinking-level-discovery.js +183 -0
  266. package/dist/server/time-zone.d.ts +20 -0
  267. package/dist/server/time-zone.js +32 -0
  268. package/dist/server/tool-calls.d.ts +130 -0
  269. package/dist/server/tool-calls.js +341 -0
  270. package/dist/server/tool-llm.d.ts +72 -0
  271. package/dist/server/tool-llm.js +146 -0
  272. package/dist/server/tool-registry.d.ts +129 -0
  273. package/dist/server/tool-registry.js +249 -0
  274. package/dist/server/tool-runner.d.ts +112 -0
  275. package/dist/server/tool-runner.js +306 -0
  276. package/dist/server/turn-failure.d.ts +48 -0
  277. package/dist/server/turn-failure.js +148 -0
  278. package/dist/server/types.d.ts +2315 -0
  279. package/dist/server/types.js +11 -0
  280. package/dist/server/update-status.d.ts +14 -0
  281. package/dist/server/update-status.js +69 -0
  282. package/dist/server/update.d.ts +46 -0
  283. package/dist/server/update.js +104 -0
  284. package/dist/server/upload.d.ts +35 -0
  285. package/dist/server/upload.js +177 -0
  286. package/dist/server/version.d.ts +33 -0
  287. package/dist/server/version.js +111 -0
  288. package/dist/server/web.d.ts +27 -0
  289. package/dist/server/web.js +183 -0
  290. package/dist/server/workflow-engine.d.ts +47 -0
  291. package/dist/server/workflow-engine.js +255 -0
  292. package/dist/server/workflow.d.ts +329 -0
  293. package/dist/server/workflow.js +469 -0
  294. package/dist/server/workspace-file-indexes.d.ts +2 -0
  295. package/dist/server/workspace-file-indexes.js +61 -0
  296. package/dist/server/workspace-file-operations.d.ts +36 -0
  297. package/dist/server/workspace-file-operations.js +281 -0
  298. package/dist/server/workspace-file-response.d.ts +7 -0
  299. package/dist/server/workspace-file-response.js +79 -0
  300. package/dist/server/ws-server.d.ts +149 -0
  301. package/dist/server/ws-server.js +640 -0
  302. package/dist/shared/agent-order.d.ts +44 -0
  303. package/dist/shared/agent-order.js +50 -0
  304. package/dist/shared/archive-decisions.d.ts +44 -0
  305. package/dist/shared/archive-decisions.js +98 -0
  306. package/dist/shared/background-task.d.ts +25 -0
  307. package/dist/shared/background-task.js +183 -0
  308. package/dist/shared/child-session-lock.d.ts +37 -0
  309. package/dist/shared/child-session-lock.js +59 -0
  310. package/dist/shared/content-search.d.ts +22 -0
  311. package/dist/shared/content-search.js +1 -0
  312. package/dist/shared/conversation-title.d.ts +4 -0
  313. package/dist/shared/conversation-title.js +4 -0
  314. package/dist/shared/file-mentions.d.ts +17 -0
  315. package/dist/shared/file-mentions.js +91 -0
  316. package/dist/shared/git-commit.d.ts +11 -0
  317. package/dist/shared/git-commit.js +1 -0
  318. package/dist/shared/git-graph.d.ts +42 -0
  319. package/dist/shared/git-graph.js +30 -0
  320. package/dist/shared/group-chat.d.ts +132 -0
  321. package/dist/shared/group-chat.js +6 -0
  322. package/dist/shared/managed-servers.d.ts +36 -0
  323. package/dist/shared/managed-servers.js +1 -0
  324. package/dist/shared/message-media.d.ts +12 -0
  325. package/dist/shared/message-media.js +27 -0
  326. package/dist/shared/model-window-label.d.ts +39 -0
  327. package/dist/shared/model-window-label.js +55 -0
  328. package/dist/shared/native-tools.d.ts +43 -0
  329. package/dist/shared/native-tools.js +1 -0
  330. package/dist/shared/pi-cache-warming.d.ts +9 -0
  331. package/dist/shared/pi-cache-warming.js +4 -0
  332. package/dist/shared/project-overview.d.ts +107 -0
  333. package/dist/shared/project-overview.js +92 -0
  334. package/dist/shared/project-presentation.d.ts +55 -0
  335. package/dist/shared/project-presentation.js +111 -0
  336. package/dist/shared/provider-network.d.ts +30 -0
  337. package/dist/shared/provider-network.js +1 -0
  338. package/dist/shared/session-reporting.d.ts +40 -0
  339. package/dist/shared/session-reporting.js +97 -0
  340. package/dist/shared/session-search.d.ts +14 -0
  341. package/dist/shared/session-search.js +1 -0
  342. package/dist/shared/team-context-view.d.ts +33 -0
  343. package/dist/shared/team-context-view.js +49 -0
  344. package/dist/shared/team-context.d.ts +59 -0
  345. package/dist/shared/team-context.js +3 -0
  346. package/dist/shared/terminal-protocol.d.ts +71 -0
  347. package/dist/shared/terminal-protocol.js +1 -0
  348. package/dist/shared/thinking-levels.d.ts +53 -0
  349. package/dist/shared/thinking-levels.js +85 -0
  350. package/dist/shared/tool-glyph.d.ts +7 -0
  351. package/dist/shared/tool-glyph.js +19 -0
  352. package/dist/shared/transcript-order.d.ts +7 -0
  353. package/dist/shared/transcript-order.js +12 -0
  354. package/dist/shared/update-status.d.ts +28 -0
  355. package/dist/shared/update-status.js +1 -0
  356. package/dist/shared/workspace-file-preview.d.ts +4 -0
  357. package/dist/shared/workspace-file-preview.js +28 -0
  358. package/package.json +448 -4
  359. package/scripts/diagnose.mjs +603 -0
  360. package/scripts/patch-brace-expansion.mjs +260 -0
  361. package/scripts/restart-server.mjs +104 -0
  362. package/skills/presentation/SKILL.md +30 -0
  363. package/skills/presentation/references/data.md +10 -0
  364. package/skills/presentation/references/quality.md +12 -0
  365. package/skills/presentation/references/story.md +12 -0
  366. package/skills/presentation/references/templates-and-editing.md +11 -0
  367. package/skills/presentation/references/visual-system.md +10 -0
  368. package/skills/super-pi-agent-development/SKILL.md +25 -0
  369. package/skills/super-pi-development/SKILL.md +31 -0
  370. package/skills/super-pi-tool-development/SKILL.md +39 -0
@@ -0,0 +1,748 @@
1
+ /**
2
+ * Workspace file browsing and editing.
3
+ *
4
+ * ONE RULE GOVERNS THIS FILE, and it is the reason the module exists rather than four functions inside
5
+ * `index.ts`: a path that arrives from a browser is UNTRUSTED, and the question "does this resolve to
6
+ * somewhere inside the workspace" has to be answered in exactly one place. Every read, every write,
7
+ * every directory listing and every search walks through `resolveInsideRoot`. A check that is written
8
+ * twice is a check that is correct once.
9
+ *
10
+ * WHAT THE WORKSPACE ROOT IS, because the requirement says to find this out rather than assume it: it is
11
+ * `Workspace.path`, the directory the user picked when they created the workspace (`store.ts`
12
+ * `createWorkspace` stores `path` verbatim; the left rail's directory picker reads `/api/fs/dirs`, which
13
+ * is why that endpoint exists and why it is deliberately NOT reused here - see the note on it below).
14
+ * It is the same directory Pi runs in (`index.ts` `turnContext` hands `workspace.path` to every turn as
15
+ * `cwd`), which is the property that makes "the Files tab shows me what the agent is working on" true
16
+ * rather than aspirational.
17
+ *
18
+ * `/api/fs/dirs` IS NOT A PREDECESSOR OF ANYTHING IN HERE. It resolves whatever absolute path it is
19
+ * handed, because picking a workspace directory requires naming a directory that does not exist yet -
20
+ * it is a file picker, not a file reader, and reusing it would import its deliberate absence of
21
+ * containment straight into the one surface that must have it.
22
+ *
23
+ * THE ROOT IS ALSO A SUBJECT OF THIS FILE. `Workspace.path` is a stored string, and a stored string can
24
+ * name a directory that is no longer there - deleted, renamed, on a drive that is no longer mounted. The
25
+ * picker cannot create that state (`/api/fs/dirs` only ever lists directories it has just `stat`ed), but
26
+ * time can. So "does the workspace root exist" is answered here, once, in `realpathOfRoot`, and it is
27
+ * answered before any question is asked about the path INSIDE it. That ordering is what makes a missing
28
+ * directory a 404 that names itself instead of a containment failure about a symlink that does not exist.
29
+ */
30
+ import { createHash } from "node:crypto";
31
+ import { mkdtemp, readFile, readdir, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
32
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
33
+ /**
34
+ * Above this a read is refused rather than served. 5MB is roughly a large source file or a long document,
35
+ * and it is deliberately far below the point where an editor tab stops being useful: this panel is for
36
+ * reading and editing code and markdown, and a file too big for that has not become more editable by
37
+ * being loaded whole. The size is checked from `stat` BEFORE the read, so an oversized file costs one
38
+ * `stat` rather than a full buffer.
39
+ */
40
+ export const MAX_FILE_BYTES = 5 * 1024 * 1024;
41
+ /** Cap on one directory listing, so a `node_modules` or a generated assets folder cannot produce a
42
+ * multi-megabyte response. The count is reported as `truncated` rather than applied silently. */
43
+ export const MAX_DIR_ENTRIES = 2000;
44
+ /** Cap on a recursive filename search, for the same reason: a scan of a large repository has to end
45
+ * somewhere. The UI says the list was cut rather than pretending it is complete. */
46
+ export const MAX_SEARCH_RESULTS = 500;
47
+ /** How deep the recursive search walks. Twelve levels is past any real source tree; the cap is what
48
+ * turns a pathologically deep dependency tree from a hang into a result. */
49
+ export const MAX_SEARCH_DEPTH = 12;
50
+ /** Directories the recursive search skips. The TREE does not skip them - a directory the user cannot
51
+ * browse is a directory they cannot inspect a file in, and the binary handling below is only reachable
52
+ * if `node_modules` is reachable. A recursive filename search, by contrast, returns thousands of matches
53
+ * from these and nothing a person searched for, so they are excluded from the scan and the exclusion is
54
+ * reported in the response rather than being invisible. */
55
+ /** Shared exclusion list for recursive search and the quick-open index. The directory tree intentionally
56
+ * does not use it: users may still browse dependencies on demand. */
57
+ export const SEARCH_SKIP_DIRS = new Set([".git", "node_modules", "dist", "build", ".super-pi", ".next", ".cache", "coverage", ".venv"]);
58
+ /**
59
+ * Extensions that are binary by definition, checked BEFORE any bytes are read.
60
+ *
61
+ * This is a fast path, not the real test: a `.ts` file containing PNG bytes still has to be caught, and
62
+ * it is caught by `looksBinary` below. What this set buys is refusing the obvious cases without opening
63
+ * them - and, more importantly, refusing them with a MESSAGE that names the reason rather than "invalid
64
+ * UTF-8", because the person clicking the file wants to know it is an image.
65
+ */
66
+ const BINARY_EXTENSIONS = new Set([
67
+ ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".webp", ".avif", ".tif", ".tiff", ".heic",
68
+ ".psd", ".ai", ".eps",
69
+ ".zip", ".tar", ".gz", ".tgz", ".bz2", ".xz", ".7z", ".rar", ".iso", ".dmg", ".jar", ".war", ".whl",
70
+ ".exe", ".dll", ".so", ".dylib", ".bin", ".o", ".obj", ".a", ".lib", ".class", ".wasm", ".node",
71
+ ".pyd", ".msi", ".apk", ".deb", ".rpm",
72
+ ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".odt", ".ods", ".odp",
73
+ ".woff", ".woff2", ".ttf", ".otf", ".eot",
74
+ ".mp3", ".wav", ".flac", ".ogg", ".mp4", ".mov", ".avi", ".mkv", ".webm",
75
+ ".sqlite", ".sqlite3", ".db", ".pyc", ".pyo", ".pack", ".idx",
76
+ ]);
77
+ /**
78
+ * Extensions this panel OPENS without needing a sniff. It is a hint used only to label a file in the tree
79
+ * before it is read, and never as a permission: a `.png` is refused by name even if a sniffing pass would
80
+ * have liked it, and a `.txt` holding PNG bytes is still refused by the sniff.
81
+ */
82
+ export const TEXT_EXTENSIONS = new Set([
83
+ ".md", ".markdown", ".mdx", ".txt", ".text", ".log",
84
+ ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts",
85
+ ".json", ".jsonc", ".json5", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf",
86
+ ".css", ".scss", ".less", ".html", ".htm", ".xml", ".svg", ".vue", ".svelte", ".astro",
87
+ ".py", ".rb", ".go", ".rs", ".java", ".kt", ".kts", ".c", ".h", ".cc", ".cpp", ".hpp", ".cs", ".swift",
88
+ ".sh", ".bash", ".zsh", ".fish", ".ps1", ".bat", ".cmd",
89
+ ".sql", ".graphql", ".gql", ".proto", ".tf", ".tfvars", ".lua", ".r", ".jl", ".ex", ".exs", ".erl",
90
+ ".diff", ".patch", ".csv", ".tsv", ".lock",
91
+ ]);
92
+ /** The HTTP failure, carried as a status so the route can render it without a second switch. `details` is
93
+ * for the cases where the CLIENT can act on more than the sentence - today that is a conflict, where the
94
+ * current etag is what lets the UI offer a deliberate "overwrite anyway" instead of a blind one. */
95
+ export class FilesError extends Error {
96
+ status;
97
+ code;
98
+ details;
99
+ constructor(status, message, code, details) {
100
+ super(message);
101
+ this.status = status;
102
+ this.code = code;
103
+ this.details = details;
104
+ this.name = "FilesError";
105
+ }
106
+ }
107
+ /**
108
+ * Whether `candidate` is `root` itself or something under it.
109
+ *
110
+ * THE COMPARISON IS NOT `startsWith(root)`, because that is the traversal bug this whole file exists to
111
+ * avoid: with root `/home/u/proj`, the string `/home/u/proj-secrets` also starts with `/home/u/proj`.
112
+ * `relative()` asks the question in the form that can be answered exactly - it returns a path RELATIVE to
113
+ * the root, so "escaped" becomes "the relative path begins by going up", which is true for
114
+ * `/home/u/proj/../etc` and false for `/home/u/proj/etc`. `isAbsolute(relative)` catches the case
115
+ * `relative` cannot express: two different Windows drives, where there is no relative path between them
116
+ * and it hands back an absolute one.
117
+ */
118
+ export function contains(root, candidate) {
119
+ const rel = relative(root, candidate);
120
+ if (rel === "")
121
+ return true;
122
+ // Two drives on Windows, or a relative path that came back absolute. Either way there is no in-bounds
123
+ // answer, so it is a refusal rather than a comparison.
124
+ if (isAbsolute(rel))
125
+ return false;
126
+ return rel !== ".." && !rel.startsWith(`..${sep}`) && !rel.startsWith("../");
127
+ }
128
+ /**
129
+ * The syntactic half of the containment check: reject the SHAPES of a path that could escape, before
130
+ * anything is resolved.
131
+ *
132
+ * Every branch here is platform-independent on purpose. A server deployed on Linux must refuse `C:\...`
133
+ * and `\\server\share`, because a client is free to send them and a Linux build that only knows about `/`
134
+ * would happily `resolve` `C:\Windows` into a harmless-looking relative path under the root and answer
135
+ * 200 to a request that should be 403. The tests run on Windows and would not catch that.
136
+ *
137
+ * The backslash rewrite is the same decision, and it is a real trade rather than a free win: `\` is a
138
+ * legal CHARACTER in a POSIX filename, so a file literally named `a\b` is unreachable through this API.
139
+ * The alternative - honouring `\` only on Windows - buys that filename at the price of the same request
140
+ * meaning different things on two hosts, which is the more expensive of the two mistakes for a
141
+ * security check. Every escape form in the requirement is spelled with a backslash, and the check is
142
+ * worth more than the filename.
143
+ */
144
+ function rejectUnsafeShape(requested) {
145
+ // A NUL truncates the path inside every syscall it reaches - `readFile("a\0../../etc")` is `readFile("a")`
146
+ // as far as libuv is concerned, and the string this function validated is not the string the OS acts on.
147
+ // Refused before anything is normalised.
148
+ if (requested.includes("\0"))
149
+ throw new FilesError(400, "路径包含非法的空字符", "bad_path");
150
+ // UNC: `\\server\share\...` and its POSIX-spelled twin `//server/share`. Named explicitly because
151
+ // `isAbsolute` is true for the first on Windows and false for the second on Linux.
152
+ if (/^[\\/]{2}/.test(requested))
153
+ throw new FilesError(403, "拒绝 UNC 路径:请给出相对于工作区根目录的路径", "outside_workspace");
154
+ // A drive letter in EITHER position: `C:\x` is absolute, `C:x` is drive-relative and resolves against
155
+ // that drive's current directory, which is not a location the caller gets to choose. The colon is also
156
+ // how NTFS alternate data streams are addressed (`notes.md:hidden`), which is a second file hiding
157
+ // behind one path - handled by the segment check below.
158
+ if (/^[A-Za-z]:/.test(requested))
159
+ throw new FilesError(403, "拒绝 Windows 盘符路径:请给出相对于工作区根目录的路径", "outside_workspace");
160
+ // Rooted, POSIX or Windows: `/etc/passwd` and `\Windows`. Both are absolute, and the leading-slash
161
+ // forms are spelled out so the refusal does not depend on the host's own path parser agreeing.
162
+ if (requested.startsWith("/") || requested.startsWith("\\"))
163
+ throw new FilesError(403, "拒绝绝对路径:请给出相对于工作区根目录的路径", "outside_workspace");
164
+ return requested.replace(/\\/g, "/");
165
+ }
166
+ /**
167
+ * `realpath` of a workspace ROOT, where "does not exist" is a FINDING rather than a fallback.
168
+ *
169
+ * This function exists because of a measured failure, not a hypothetical one. With a workspace whose
170
+ * `path` does not exist, `nearestExistingAncestor` climbs to the nearest directory that DOES exist, gets
171
+ * handed back something above the root, and the containment test concludes - correctly, for what it was
172
+ * asked - that the target escaped. The route therefore answered:
173
+ *
174
+ * 403 {"error":"路径经符号链接后超出 workspace 范围,已拒绝:","code":"outside_workspace"}
175
+ *
176
+ * A security error, about a symlink that does not exist, naming NO PATH, for a workspace whose directory
177
+ * is simply not there. The user cannot act on that sentence, and the trailing colon shows the other half
178
+ * of the bug: the root is requested as `""`, so the message interpolates an empty string. A missing
179
+ * directory is a 404 that says which directory, and it is decided HERE - once, before the symlink half -
180
+ * so every read, write, listing and search says the same true thing about the same root.
181
+ *
182
+ * `realpath` rather than `stat` because the canonical form is needed anyway one line later, and a second
183
+ * syscall to learn something the first one already told us would be a race. `EACCES`/`EPERM` are named
184
+ * separately: a directory that exists but cannot be entered is a different mistake from one that was
185
+ * deleted, and the user needs to be able to tell them apart.
186
+ */
187
+ async function realpathOfRoot(base) {
188
+ try {
189
+ return await realpath(base);
190
+ }
191
+ catch (error) {
192
+ const code = error.code;
193
+ if (code === "ENOENT" || code === "ENOTDIR")
194
+ throw new FilesError(404, `工作区路径不存在:${base}`, "workspace_missing", { path: base });
195
+ if (code === "EACCES" || code === "EPERM")
196
+ throw new FilesError(403, `工作区路径无法访问(权限不足):${base}`, "denied", { path: base });
197
+ throw error;
198
+ }
199
+ }
200
+ /**
201
+ * The nearest ANCESTOR of `target` that exists on disk, canonically.
202
+ *
203
+ * Needed because a WRITE targets a file that may legitimately not exist yet, and the symlink half of the
204
+ * check still has to run on it. Climbing is safe to stop at: by the time the walk has climbed, every
205
+ * segment below the one it stopped on has been shown not to exist, and a segment that does not exist
206
+ * cannot itself be a symlink out of the tree.
207
+ */
208
+ async function nearestExistingAncestor(target) {
209
+ let current = target;
210
+ for (;;) {
211
+ try {
212
+ return await realpath(current);
213
+ }
214
+ catch (error) {
215
+ const code = error.code;
216
+ // ENOENT and ENOTDIR are the only two that mean "climb". EACCES and ELOOP are real problems and are
217
+ // allowed to surface as themselves rather than being turned into a climb that hides them.
218
+ if (code !== "ENOENT" && code !== "ENOTDIR")
219
+ throw error;
220
+ const parent = dirname(current);
221
+ if (parent === current)
222
+ throw error;
223
+ current = parent;
224
+ }
225
+ }
226
+ }
227
+ /** A guard bound to one workspace root. `resolveInsideRoot` is the one-shot form and is what callers are
228
+ * meant to use; the factory exists for the two places that check many paths against the SAME root in one
229
+ * request, so the canonical form of the root is resolved once instead of once per entry. */
230
+ export function createRootGuard(root) {
231
+ const base = resolve(root);
232
+ let realBase;
233
+ return async (requested) => {
234
+ const raw = (requested ?? "").trim();
235
+ // Empty means "the workspace itself", which is what the tree's root row and a listing of the top
236
+ // level both send. It is not an error and it is not a wildcard.
237
+ const target = raw === "" ? base : resolve(base, rejectUnsafeShape(raw));
238
+ // (1) LEXICAL, on the literal string. Catches `../`, `..\`, `/etc/passwd`, `C:\Windows`,
239
+ // `\\host\share` and anything else the caller SHAPED to escape, before any syscall touches the disk.
240
+ if (!contains(base, target))
241
+ throw new FilesError(403, `路径超出 workspace 范围,已拒绝:${raw}`, "outside_workspace");
242
+ // NTFS alternate data streams address a SECOND file behind one path. Windows only, because that is
243
+ // the only platform where the syntax means anything - a POSIX filename may legally contain a colon,
244
+ // and this check would refuse files that exist and are perfectly safe to read.
245
+ if (process.platform === "win32") {
246
+ const inside = target.slice(base.length);
247
+ if (inside.split(/[\\/]/).some((segment) => segment.includes(":"))) {
248
+ throw new FilesError(403, `拒绝 NTFS 数据流路径:${raw}`, "outside_workspace");
249
+ }
250
+ }
251
+ // (2) SYMLINK, on the resolved path. Catches a link INSIDE the workspace that points OUT of it - the
252
+ // one escape that is invisible to the string, because `workspace/link/etc/passwd` is a perfectly
253
+ // in-bounds spelling of a file somewhere else entirely. Both sides are canonicalised with `realpath`
254
+ // before comparison, because the root itself is very often reached through a link (on macOS
255
+ // `/var` -> `/private/var`, and a Windows worktree or junction is routine), so comparing a canonical
256
+ // target against an uncanonical root would reject every legitimate path.
257
+ // THE ROOT IS DECIDED FIRST, BEFORE ANY WORK ON THE TARGET, and both halves of that are deliberate.
258
+ //
259
+ // `realpathOfRoot` throws 404 `workspace_missing` for a workspace whose directory is gone, so the
260
+ // climb below can only ever be asked about a directory that exists - which is what makes the
261
+ // comparison after it mean "this path left the workspace" instead of "the workspace is not there".
262
+ //
263
+ // AWAITING IT BEFORE `nearestExistingAncestor` IS ALSO LOAD-BEARING. The first version asked for the
264
+ // target's canonical form first, and a workspace on a drive letter that does not exist (`Z:\nope`)
265
+ // then died inside the climb - it reaches the drive root, finds `dirname` unchanged, and rethrows the
266
+ // raw Node error. That surfaced as `500 {"error":"ENOENT: no such file or directory, realpath 'Z:\\'"}`:
267
+ // a missing workspace reported as an internal fault, leaking a libuv message. Resolving the root
268
+ // first means the 404 is always the answer, because the root is always known before the climb starts.
269
+ //
270
+ // THE `.catch(() => {})` IS LOAD-BEARING TOO, and it is there because that same first version CRASHED
271
+ // THE PROCESS on the ordinary missing-directory case. `realBase` is a PROMISE, and creating it and
272
+ // then awaiting anything else hands the event loop a turn with a rejected promise that has no handler
273
+ // yet; Node's default for an unhandled rejection is to terminate, so the server died with an uncaught
274
+ // `FilesError` instead of answering the 404. This attaches a handler at creation time and discards
275
+ // nothing - the original promise still rejects, and `await` below still receives it.
276
+ if (realBase === undefined) {
277
+ const pending = realpathOfRoot(base);
278
+ pending.catch(() => { });
279
+ realBase = pending;
280
+ }
281
+ const canonicalRoot = await realBase;
282
+ const realTarget = await nearestExistingAncestor(target);
283
+ if (!contains(canonicalRoot, realTarget))
284
+ throw new FilesError(403, `路径经符号链接后超出 workspace 范围,已拒绝:${raw}`, "outside_workspace");
285
+ return target;
286
+ };
287
+ }
288
+ /**
289
+ * THE CONTAINMENT CHECK. Every read, write, listing and search in this file goes through it, and the
290
+ * route layer is not allowed to do its own path arithmetic.
291
+ *
292
+ * `requested` arrives already percent-decoded, because `URLSearchParams` decodes once when the query is
293
+ * parsed. That is the right number of decodes: `%2e%2e%2f` is `../` by the time it gets here and is
294
+ * refused by the lexical test, while decoding a SECOND time would turn the harmless literal `%2e%2e%2f`
295
+ * into a live traversal - inventing an attack the URL parser does not actually have. The route decodes
296
+ * nothing further and never passes the raw query string down.
297
+ */
298
+ export function resolveInsideRoot(root, requested) {
299
+ return createRootGuard(root)(requested);
300
+ }
301
+ /**
302
+ * The identity of a file's CURRENT bytes, as far as a filesystem can cheaply say.
303
+ *
304
+ * Built from size and the nanosecond modification time rather than a content hash: hashing every file on
305
+ * every read would make opening a tab cost a full pass over the file, and the two fields together already
306
+ * change on any edit a human would call an edit. `bigint: true` is what makes this exact - the
307
+ * millisecond float `stat` reports by default rounds two edits inside the same millisecond into one
308
+ * value, and an external-change check that misses a change is worse than no check at all, because the
309
+ * user has been told it is safe to save.
310
+ */
311
+ export async function fileEtag(path) {
312
+ return fileMetaFromStat(await stat(path, { bigint: true })).etag;
313
+ }
314
+ export async function fileMeta(path) {
315
+ return fileMetaFromStat(await stat(path, { bigint: true }));
316
+ }
317
+ export function fileMetaFromStat(info) {
318
+ const etag = createHash("sha1").update(`${info.size}:${info.mtimeNs}:${info.ino}`).digest("hex").slice(0, 20);
319
+ return { etag, size: Number(info.size), modifiedAt: info.mtime.toISOString() };
320
+ }
321
+ /**
322
+ * Whether these bytes are text.
323
+ *
324
+ * The NUL test is the one that matters and it is the same one git uses for its "binary file" heuristic: a
325
+ * NUL byte cannot appear in valid UTF-8 text, while every common binary container has one within the
326
+ * first block. The sample is bounded so classifying a large file does not turn into reading all of it.
327
+ */
328
+ const BINARY_SNIFF_BYTES = 4096;
329
+ export function looksBinary(sample) {
330
+ const limit = Math.min(sample.length, BINARY_SNIFF_BYTES);
331
+ for (let i = 0; i < limit; i++)
332
+ if (sample[i] === 0)
333
+ return true;
334
+ return false;
335
+ }
336
+ /**
337
+ * Whether the NAME alone says this is binary.
338
+ *
339
+ * `endsWith` is the whole test, and the dot is what makes it a suffix test rather than a substring one:
340
+ * `"tool.bin".endsWith(".bin")` is true and `"foobin".endsWith(".bin")` is false, because the dot has to be
341
+ * one of the characters being matched. An earlier version added a "the character before the suffix must be
342
+ * a dot" guard on top of this, which was wrong - it compared the index of the dot AGAINST ITSELF minus
343
+ * one, so `"photo.png"` was checked at the `o` and came back false. Every binary file was therefore
344
+ * reaching the byte sniff instead of being refused by name, and the tests only ever passed because the
345
+ * fixture binaries also contained NUL bytes. A check that is dead code while a second check quietly does
346
+ * its job is exactly the kind of thing that survives review, which is why `files-api.test.mjs` asserts
347
+ * the extension path with a fixture whose CONTENT is text.
348
+ */
349
+ export function hasBinaryExtension(name) {
350
+ const lower = basename(name).toLowerCase();
351
+ for (const binary of BINARY_EXTENSIONS) {
352
+ if (lower.endsWith(binary))
353
+ return true;
354
+ }
355
+ return false;
356
+ }
357
+ /**
358
+ * The extensions of the documents the parsing layer can read.
359
+ *
360
+ * WHY THE LIST LIVES HERE AND NOT IN `documents.ts`. This module has no relative imports, and that is
361
+ * load-bearing: `scripts/files-api.test.mjs` copies this file ALONE into a temp directory and
362
+ * compiles it there, to prove that a broken containment check really does leak. An import of a
363
+ * sibling module would not resolve in that scratch directory, so the mutation would fail to compile
364
+ * - which the test would read as "the guard still refuses the escape", the exact opposite of what it
365
+ * is checking.
366
+ *
367
+ * The parsing layer holds the same list, and the two are checked against each other by
368
+ * `scripts/documents.test.mjs`, so the tree cannot offer a file the parser cannot read.
369
+ */
370
+ export const DOCUMENT_EXTENSIONS = new Set([".pdf", ".docx", ".xlsx", ".pptx", ".ppt"]);
371
+ /** Whether a file is worth putting in an editor tab at all, decided from its NAME alone, for the tree's
372
+ * own labelling. The authoritative answer comes from `readWorkspaceFile`, which reads bytes. */
373
+ export function isTextName(name) {
374
+ if (hasBinaryExtension(name))
375
+ return false;
376
+ const lower = basename(name).toLowerCase();
377
+ if (lower === "dockerfile" || lower === "makefile" || lower === "license" || lower === "readme")
378
+ return true;
379
+ const dot = lower.lastIndexOf(".");
380
+ if (dot <= 0)
381
+ return true; // extensionless files are usually source or config; the sniff decides
382
+ return TEXT_EXTENSIONS.has(lower.slice(dot));
383
+ }
384
+ /**
385
+ * Whether a file is a DOCUMENT the parsing layer can read, decided from its name.
386
+ *
387
+ * The same list the knowledge base and the document tools use, so a picker that offers a file and a
388
+ * server that accepts it cannot disagree about which files those are.
389
+ */
390
+ export function isDocumentName(name) {
391
+ const lower = basename(name).toLowerCase();
392
+ const dot = lower.lastIndexOf(".");
393
+ if (dot <= 0)
394
+ return false;
395
+ return DOCUMENT_EXTENSIONS.has(lower.slice(dot));
396
+ }
397
+ /** The `/`-separated relative form used on the wire and in every comparison. */
398
+ export function toRelative(root, absolute) {
399
+ return relative(root, absolute).split(sep).join("/");
400
+ }
401
+ /**
402
+ * A PATH A MODEL WROTE, AS THE WORKSPACE SPELLS IT.
403
+ *
404
+ * WHO SPELLS PATHS THIS WAY. Pi's `write`/`edit` tools carry whatever path the MODEL produced, and a
405
+ * model that has been told where the workspace is writes an absolute path: `/home/me/project/src/a.ts`
406
+ * is the same file as `src/a.ts`. The model is not trying to escape anything - it is repeating the
407
+ * workspace root it was given.
408
+ *
409
+ * WHY THIS IS HERE AND NOT IN THE CALLER. Two layers need the same translation and neither may own
410
+ * it: the file-change tracker (which records what the agent wrote) and the file index (which refreshes
411
+ * what the agent wrote). Before this function existed, the index refused an absolute path outright -
412
+ * and because the refusal was thrown out of a promise nobody was awaiting, one absolute-path write
413
+ * produced one `[fatal] unhandledRejection` in the server log and left the Files panel showing a file
414
+ * the agent had just written as if it had never been touched.
415
+ *
416
+ * AN ABSOLUTE PATH OUTSIDE THE WORKSPACE IS REFUSED, EXACTLY AS `../` IS REFUSED. The containment rule
417
+ * belongs to this module and has exactly one owner; this function does not get a second, weaker copy of
418
+ * it. It translates a spelling and then hands the result to the guard, which is what actually decides
419
+ * containment - including the symlink case, which a string comparison can never see.
420
+ */
421
+ export function toWorkspaceRelative(root, requested) {
422
+ const raw = requested.trim();
423
+ // A RELATIVE PATH IS ALREADY THE WORKSPACE'S SPELLING. It is passed through untouched so that the
424
+ // guard sees exactly what the caller asked for - including `../`, which the guard is there to refuse.
425
+ if (!isAbsolute(raw))
426
+ return raw;
427
+ const base = resolve(root);
428
+ const rel = relative(base, resolve(raw));
429
+ if (rel === "")
430
+ return "";
431
+ // `relative` answers "what is left to walk from base to target". When the target is on another drive
432
+ // (Windows) or outside the root (anywhere), the answer is an absolute path or a chain of `..`, and
433
+ // both mean the same thing: this path is not inside the workspace.
434
+ if (isAbsolute(rel) || rel === ".." || rel.startsWith(`..${sep}`) || rel.startsWith("../")) {
435
+ throw new FilesError(403, "拒绝绝对路径:请给出相对于工作区根目录的路径", "outside_workspace");
436
+ }
437
+ return rel.split(sep).join("/");
438
+ }
439
+ /** One directory's contents. Directories sort before files, then case-insensitively by name with numeric
440
+ * ordering, so `src2` lands between `src` and `src10` rather than after every `srcN`. */
441
+ export async function listDirectory(root, requested) {
442
+ const guard = createRootGuard(root);
443
+ const target = await guard(requested);
444
+ const info = await stat(target).catch((error) => {
445
+ const code = error?.code;
446
+ if (code === "ENOENT" || code === "ENOTDIR")
447
+ throw new FilesError(404, `目录不存在:${toRelative(root, target) || "/"}`, "not_found");
448
+ if (code === "EACCES" || code === "EPERM")
449
+ throw new FilesError(403, `权限不足:${toRelative(root, target) || "/"}`, "denied");
450
+ throw error;
451
+ });
452
+ if (!info.isDirectory())
453
+ throw new FilesError(400, `不是目录:${toRelative(root, target)}`, "not_a_directory");
454
+ const dirents = await readdir(target, { withFileTypes: true });
455
+ const entries = [];
456
+ for (const dirent of dirents) {
457
+ const absolute = resolve(target, dirent.name);
458
+ const isLink = dirent.isSymbolicLink();
459
+ // ONLY a link can leave the workspace. A regular file or directory reached through a path whose
460
+ // ancestors have all already been resolved cannot be anywhere else - there is no other way to get out
461
+ // - so running the symlink half of the guard on every entry of a 2000-file directory would be a few
462
+ // thousand `realpath` calls to re-derive what `isDirectory()` just said. A link is the exception, and
463
+ // it is the one worth a syscall.
464
+ let outside = false;
465
+ if (isLink) {
466
+ try {
467
+ await guard(toRelative(root, absolute));
468
+ }
469
+ catch {
470
+ outside = true;
471
+ }
472
+ }
473
+ const linked = isLink ? await stat(absolute).catch(() => undefined) : undefined;
474
+ const isDir = dirent.isDirectory() || (!outside && linked?.isDirectory() === true);
475
+ entries.push({
476
+ path: toRelative(root, absolute),
477
+ name: dirent.name,
478
+ kind: outside ? "symlink" : isDir ? "directory" : "file",
479
+ text: isDir ? null : !outside && isTextName(dirent.name),
480
+ ...(isDir ? {} : { document: !outside && isDocumentName(dirent.name) }),
481
+ ...(isLink ? { symlink: true } : {}),
482
+ ...(outside ? { outside: true } : {}),
483
+ ...(linked?.isFile() ? { openLink: true } : {}),
484
+ });
485
+ }
486
+ entries.sort((a, b) => {
487
+ const aFile = a.kind === "file" ? 1 : 0;
488
+ const bFile = b.kind === "file" ? 1 : 0;
489
+ if (aFile !== bFile)
490
+ return aFile - bFile;
491
+ return a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" });
492
+ });
493
+ const relativePath = toRelative(root, target);
494
+ const truncated = entries.length > MAX_DIR_ENTRIES;
495
+ return {
496
+ path: relativePath,
497
+ parent: relativePath === "" ? null : relativePath.split("/").slice(0, -1).join("/"),
498
+ entries: truncated ? entries.slice(0, MAX_DIR_ENTRIES) : entries,
499
+ truncated,
500
+ };
501
+ }
502
+ /**
503
+ * A recursive FILENAME search. Filename only, on purpose: content search is a different feature with
504
+ * different costs - it reads every candidate file, honours the size cap on each one, and it is the thing
505
+ * that turns a panel into a hang - and the requirement is explicit that this round does not need it.
506
+ *
507
+ * Every directory it descends into goes through the SAME guard as every other path here, so the search
508
+ * cannot be walked out of the workspace by a link, and it stops at `MAX_SEARCH_DEPTH` and
509
+ * `MAX_SEARCH_RESULTS` so a repository with a vendored dependency tree returns a truncated answer rather
510
+ * than never returning.
511
+ */
512
+ export async function searchByName(root, query) {
513
+ const needle = query.trim().toLowerCase();
514
+ if (!needle)
515
+ return { hits: [], truncated: false, skipped: [] };
516
+ const guard = createRootGuard(root);
517
+ const hits = [];
518
+ const skipped = [];
519
+ let truncated = false;
520
+ const walk = async (directory, depth) => {
521
+ if (truncated)
522
+ return;
523
+ if (depth > MAX_SEARCH_DEPTH) {
524
+ truncated = true;
525
+ return;
526
+ }
527
+ let listing;
528
+ try {
529
+ listing = await listDirectory(root, directory);
530
+ }
531
+ catch (error) {
532
+ // THE ROOT IS NOT ONE OF THE SKIPPABLE DIRECTORIES. Skipping a subdirectory that cannot be read is
533
+ // honest - the response says `skipped: [...]` - but skipping the workspace itself produced
534
+ // `200 {"mode":"search","hits":[],"skipped":["/"]}`, which is byte-for-byte the response for
535
+ // "I searched and nothing matched". Measured, on a workspace whose path did not exist. A workspace
536
+ // that is not there is therefore rethrown as the 404 it is: the whole point of reporting `skipped`
537
+ // is that the client can tell "no matches" from "I could not see everything", and a missing root
538
+ // is the case where neither is true.
539
+ if (!directory && error instanceof FilesError)
540
+ throw error;
541
+ // An unreadable directory is skipped and REPORTED, not swallowed: a search that silently skips half
542
+ // a repository and reports "no matches" is worse than one that says where it could not look.
543
+ if (error instanceof FilesError && (error.status === 403 || error.status === 404)) {
544
+ skipped.push(directory || "/");
545
+ return;
546
+ }
547
+ throw error;
548
+ }
549
+ // listDirectory intentionally caps UI listings; search must inspect the complete directory.
550
+ const fullEntries = listing.truncated
551
+ ? (await readdir(await guard(directory), { withFileTypes: true })).map((dirent) => {
552
+ const absolute = resolve(root, directory, dirent.name);
553
+ return { path: toRelative(root, absolute), name: dirent.name, kind: dirent.isDirectory() ? "directory" : dirent.isSymbolicLink() ? "symlink" : "file", text: null };
554
+ })
555
+ : listing.entries;
556
+ for (const entry of fullEntries) {
557
+ if (truncated)
558
+ return;
559
+ if (entry.kind === "file") {
560
+ if (entry.name.toLowerCase().includes(needle)) {
561
+ hits.push({ path: entry.path, name: entry.name, directory: entry.path.split("/").slice(0, -1).join("/") });
562
+ if (hits.length >= MAX_SEARCH_RESULTS) {
563
+ truncated = true;
564
+ return;
565
+ }
566
+ }
567
+ continue;
568
+ }
569
+ // A link is never descended: following one is how a search becomes an infinite walk, and the tree
570
+ // already refuses to expand it.
571
+ if (entry.kind === "symlink")
572
+ continue;
573
+ if (SEARCH_SKIP_DIRS.has(entry.name)) {
574
+ skipped.push(entry.path);
575
+ continue;
576
+ }
577
+ await walk(entry.path, depth + 1);
578
+ }
579
+ };
580
+ await walk("", 0);
581
+ hits.sort((a, b) => a.path.localeCompare(b.path, undefined, { numeric: true, sensitivity: "base" }));
582
+ return { hits, truncated, skipped };
583
+ }
584
+ /**
585
+ * Read one file, or refuse it with a reason a person can act on.
586
+ *
587
+ * ORDER MATTERS and is the whole reason the refusals are trustworthy: extension, then SIZE from `stat`,
588
+ * then a sniff, then a fatal decode. The size check precedes the read so an oversized file costs a `stat`
589
+ * rather than a buffer, and the sniff precedes the decode so binary bytes are never handed to
590
+ * `TextDecoder` as if they were text - a decode that "succeeds" on binary produces U+FFFD throughout,
591
+ * which is mojibake, and mojibake that then gets SAVED is how a text editor destroys a binary file.
592
+ */
593
+ export async function readWorkspaceFile(root, requested) {
594
+ const target = await resolveInsideRoot(root, requested);
595
+ const info = await stat(target).catch((error) => {
596
+ const code = error?.code;
597
+ if (code === "ENOENT" || code === "ENOTDIR")
598
+ throw new FilesError(404, `文件不存在:${requested}`, "not_found");
599
+ if (code === "EACCES" || code === "EPERM")
600
+ throw new FilesError(403, `权限不足:${requested}`, "denied");
601
+ throw error;
602
+ });
603
+ if (info.isDirectory())
604
+ throw new FilesError(400, `这是一个目录,不是文件:${requested}`, "not_a_file");
605
+ if (hasBinaryExtension(target))
606
+ throw new FilesError(415, `不支持的文件类型(二进制):${requested}`, "binary");
607
+ const meta = await fileMeta(target);
608
+ if (meta.size > MAX_FILE_BYTES) {
609
+ throw new FilesError(413, `文件过大(${(meta.size / 1024 / 1024).toFixed(1)}MB),上限 ${MAX_FILE_BYTES / 1024 / 1024}MB:${requested}`, "too_large");
610
+ }
611
+ return { path: toRelative(root, target), meta, ...decodeWorkspaceText(await readFile(target), requested) };
612
+ }
613
+ export function decodeWorkspaceText(raw, requested) {
614
+ if (looksBinary(raw))
615
+ throw new FilesError(415, `不支持的文件类型(二进制内容):${requested}`, "binary");
616
+ // `fatal: true` so a truncated multi-byte sequence - a file written by something that cut a UTF-8
617
+ // character in half - throws here instead of decoding to U+FFFD and being written back on save.
618
+ const bom = raw.length >= 3 && raw[0] === 0xef && raw[1] === 0xbb && raw[2] === 0xbf;
619
+ let content;
620
+ try {
621
+ content = new TextDecoder("utf-8", { fatal: true }).decode(raw);
622
+ }
623
+ catch {
624
+ throw new FilesError(415, `不是有效的 UTF-8 文本,不支持编辑:${requested}`, "binary");
625
+ }
626
+ return { content, bom, eol: content.includes("\r\n") ? "\r\n" : "\n" };
627
+ }
628
+ const writeLocks = new Map();
629
+ /**
630
+ * Write one EXISTING text file. No creation, no deletion, no rename, no directories.
631
+ *
632
+ * THE SCOPE CALL, with its reasoning, because it is a decision and not an omission:
633
+ *
634
+ * This panel's stated job is to BROWSE and EDIT what is in the workspace. Creation is refused even though
635
+ * the brief leaves it open, because creation is the operation where a mistake has no undo: a bad `path`
636
+ * parameter or a bug that loses one character writes a file the user never asked for and never has to
637
+ * clean up, whereas a refused write leaves nothing behind. Deletion is deferred by the brief and is
638
+ * deferred here for the same reason plus the one that matters more - it is irreversible.
639
+ *
640
+ * The symmetry is deliberate: create and delete are the two ends of the same axis, and shipping one
641
+ * without the other is how a "conservative, no surprises" surface becomes a half-built file manager.
642
+ *
643
+ * What IS refused regardless: a write to a file that does not exist (428), a write with no `baseEtag` at
644
+ * all (428 - without one the server cannot tell a save from a blind overwrite, and "may I overwrite" is
645
+ * not a question this endpoint is allowed to skip), a write whose `baseEtag` no longer matches the file
646
+ * on disk (409 `stale`), and a write that would push the file past the size cap.
647
+ *
648
+ * The write itself is a whole-file replace through a temporary file in the SAME directory and a rename,
649
+ * so an interrupted save cannot leave a half-written file where a whole one used to be. The temporary name
650
+ * is derived from the target's OWN name rather than living in the system temp directory, because a rename
651
+ * across filesystems is not atomic and would silently become a copy.
652
+ */
653
+ export async function writeWorkspaceFile(root, requested, content, baseEtag) {
654
+ const target = await resolveInsideRoot(root, requested);
655
+ const previous = writeLocks.get(target) ?? Promise.resolve();
656
+ let release;
657
+ const currentLock = new Promise((resolve) => { release = resolve; });
658
+ const queued = previous.then(() => currentLock);
659
+ writeLocks.set(target, queued);
660
+ await previous;
661
+ try {
662
+ const info = await stat(target).catch((error) => {
663
+ const code = error?.code;
664
+ if (code === "ENOENT" || code === "ENOTDIR")
665
+ throw new FilesError(428, `文件不存在,本面板只允许写入已存在的文件:${requested}`, "missing_target");
666
+ if (code === "EACCES" || code === "EPERM")
667
+ throw new FilesError(403, `权限不足:${requested}`, "denied");
668
+ throw error;
669
+ });
670
+ if (info.isDirectory())
671
+ throw new FilesError(400, `这是一个目录,不能写入:${requested}`, "not_a_file");
672
+ if (hasBinaryExtension(target))
673
+ throw new FilesError(415, `拒绝写入二进制文件:${requested}`, "binary");
674
+ const current = await fileMeta(target);
675
+ if (!baseEtag)
676
+ throw new FilesError(428, "缺少 baseEtag:保存必须带上打开时读到的版本标识,否则无法判断文件是否被改动过", "etag_required");
677
+ if (baseEtag !== current.etag) {
678
+ // The CURRENT etag travels with the refusal, and that is what makes an informed overwrite possible:
679
+ // the UI can offer "仍然覆盖" which re-sends THIS etag, rather than a blind write that would succeed
680
+ // only because the check was skipped once. The refusal is not a dead end - it is a question.
681
+ throw new FilesError(409, `文件在磁盘上已被其他程序修改,未保存:${requested}`, "stale", {
682
+ path: toRelative(root, target),
683
+ current,
684
+ yourEtag: baseEtag,
685
+ });
686
+ }
687
+ const bytes = Buffer.byteLength(content, "utf8");
688
+ if (bytes > MAX_FILE_BYTES)
689
+ throw new FilesError(413, `写入内容过大(${(bytes / 1024 / 1024).toFixed(1)}MB),上限 ${MAX_FILE_BYTES / 1024 / 1024}MB`, "too_large");
690
+ // A save must not turn a text file into a binary one, so the sniff that guards the read guards the
691
+ // write: a NUL arriving through a paste would otherwise be written to disk and make the file unreadable
692
+ // to this panel ever after.
693
+ if (looksBinary(Buffer.from(content, "utf8")))
694
+ throw new FilesError(415, "拒绝写入:内容包含二进制字节(\\0)", "binary");
695
+ const original = await readFile(target);
696
+ const hadBom = original.length >= 3 && original[0] === 0xef && original[1] === 0xbb && original[2] === 0xbf;
697
+ // THE LINE ENDINGS THE FILE HAD, NOT THE ONES THE EDITOR NORMALIZED.
698
+ //
699
+ // CodeMirror's document is always LF (it splits lines on `/\r\n?|\n/`), so a CRLF file comes back
700
+ // from the editor as LF text - and writing that back is how one edited character turns into a
701
+ // whole-file diff, on Windows, in every repository with `core.autocrlf=true`. The contract in this
702
+ // file already says it ("a CRLF file is saved back as CRLF instead of silently rewritten to LF");
703
+ // it just was not implemented HERE: the BOM's byte-level convention was honoured two lines above
704
+ // and the EOL's was dropped.
705
+ const eol = original.includes("\r\n") ? "\r\n" : "\n";
706
+ const body = eol === "\r\n" ? content.replace(/\r?\n/g, "\r\n") : content.replace(/\r\n/g, "\n");
707
+ const output = hadBom ? `\uFEFF${body}` : body;
708
+ const temporary = await mkdtemp(`${target}.super-pi-${process.pid}-`);
709
+ const temporaryFile = join(temporary, basename(target));
710
+ try {
711
+ await writeFile(temporaryFile, output, "utf8");
712
+ await rename(temporaryFile, target);
713
+ }
714
+ catch (error) {
715
+ // The temporary file is the ONLY thing this function can leave behind, and it is the one thing that
716
+ // must never survive a failed save.
717
+ await unlink(temporaryFile).catch(() => { });
718
+ throw error;
719
+ }
720
+ finally {
721
+ await import("node:fs/promises").then(({ rm }) => rm(temporary, { recursive: true, force: true })).catch(() => { });
722
+ release();
723
+ if (writeLocks.get(target) === queued)
724
+ writeLocks.delete(target);
725
+ }
726
+ return { path: toRelative(root, target), meta: await fileMeta(target), created: false };
727
+ }
728
+ catch (error) {
729
+ release();
730
+ throw error;
731
+ }
732
+ }
733
+ /** Every `FilesError` carries the status it should be rendered with; anything else is a real fault and
734
+ * becomes a 500 rather than being dressed up as a refusal the user is asked to understand. */
735
+ export function describe(error) {
736
+ if (error instanceof FilesError)
737
+ return { status: error.status, body: { error: error.message, code: error.code, ...(error.details ? { details: error.details } : {}) } };
738
+ const code = error?.code;
739
+ if (code === "EEXIST" || code === "ENOTEMPTY")
740
+ return { status: 409, body: { error: "目标名称已存在。", code: "already_exists" } };
741
+ if (code === "EXDEV")
742
+ return { status: 409, body: { error: "这个位置位于另一文件系统,无法移动。", code: "different_filesystem" } };
743
+ if (code === "EACCES" || code === "EPERM")
744
+ return { status: 403, body: { error: "权限不足,无法访问该路径", code: "denied" } };
745
+ if (code === "ELOOP")
746
+ return { status: 403, body: { error: "符号链接循环,已拒绝", code: "outside_workspace" } };
747
+ return { status: 500, body: { error: error instanceof Error ? error.message : "文件操作失败", code: "internal" } };
748
+ }