@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,306 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { randomUUID } from "node:crypto";
5
+ import { join } from "node:path";
6
+ const MAX_LOG_BYTES = 512_000;
7
+ const MAX_TIMEOUT_MS = 10 * 60_000;
8
+ /** The environment build gets its OWN budget: a cold `pip install` must not eat the tool's timeout. */
9
+ const MAX_ENV_TIMEOUT_MS = 10 * 60_000;
10
+ const isWindows = process.platform === "win32";
11
+ /** Keep OS architecture fallback data without exposing unrelated host configuration to Python. */
12
+ function pythonEnvironment() {
13
+ return {
14
+ PATH: process.env.PATH, SystemRoot: process.env.SystemRoot, TEMP: process.env.TEMP, TMP: process.env.TMP,
15
+ PROCESSOR_ARCHITECTURE: process.env.PROCESSOR_ARCHITECTURE,
16
+ PROCESSOR_ARCHITEW6432: process.env.PROCESSOR_ARCHITEW6432,
17
+ PYTHONIOENCODING: "utf-8", PYTHONNOUSERSITE: "1",
18
+ };
19
+ }
20
+ /** Runs a registered Python entrypoint without a shell. It intentionally accepts no command string. */
21
+ export class ToolRunner {
22
+ dataDir;
23
+ runs = new Map();
24
+ /** Optional so the existing unit tests can build a runner with no data dir; a tool that needs no venv never touches it. */
25
+ constructor(dataDir) {
26
+ this.dataDir = dataDir;
27
+ }
28
+ /**
29
+ * THE RESOLUTION ORDER, IN ONE PLACE, AND IT IS AN ORDER ON PURPOSE.
30
+ *
31
+ * 1. the tool's own venv - a tool's dependencies belong to that tool and to nothing else;
32
+ * 2. `SUPER_PI_PYTHON_COMMAND` - the user's explicit choice, already honoured before this existed;
33
+ * 3. the system interpreter - today's behaviour;
34
+ * 4. nothing usable, which is REPORTED as a sentence rather than discovered as an ENOENT.
35
+ *
36
+ * Bundling an interpreter later is a fourth rung on this chain, which is why nothing in a tool's
37
+ * files has to know about it.
38
+ */
39
+ resolvePython(toolId, needsVenv) {
40
+ if (needsVenv && this.dataDir) {
41
+ const envPython = this.envPython(toolId);
42
+ if (existsSync(envPython))
43
+ return { path: envPython, kind: "tool-env" };
44
+ }
45
+ const override = process.env.SUPER_PI_PYTHON_COMMAND?.trim();
46
+ if (override)
47
+ return { path: override, kind: "override" };
48
+ return { path: isWindows ? "python.exe" : "python3", kind: "system" };
49
+ }
50
+ /** The venv lives BESIDE the tools, not inside one: export walks the tool directory, and the mount route serves everything under it. */
51
+ envDir(toolId) { return join(this.dataDir ?? ".", "tool-envs", toolId); }
52
+ envPython(toolId) { return join(this.envDir(toolId), ".venv", isWindows ? "Scripts" : "bin", isWindows ? "python.exe" : "python"); }
53
+ /** MEASURE this machine's Python. One spawn; the answer is what every fingerprint is compared to. */
54
+ async describeLocalPython() {
55
+ const choice = this.resolvePython("", false);
56
+ const probe = await runCapture(choice.path, ["-I", "-c", "import json,platform,sys;print(json.dumps({'python':sys.version.split()[0],'platform':platform.system().lower()+'-'+platform.machine()}))"], 10_000);
57
+ if (!probe.ok)
58
+ return undefined;
59
+ try {
60
+ const parsed = JSON.parse(probe.stdout);
61
+ if (typeof parsed?.python !== "string")
62
+ return undefined;
63
+ return { ...choice, python: parsed.python, platform: parsed.platform };
64
+ }
65
+ catch {
66
+ return undefined;
67
+ }
68
+ }
69
+ async environmentState(tool) {
70
+ const environment = tool.environment;
71
+ const requires = environment?.requires ?? [];
72
+ const wants = requires.length > 0 || Boolean(environment?.requiresPython);
73
+ const local = await this.describeLocalPython();
74
+ const base = { python: local?.python, platform: local?.platform, requires };
75
+ if (!wants)
76
+ return { ...base, state: "zero-deps" };
77
+ if (!local)
78
+ return { ...base, state: "needs-python", detail: "这台机器上找不到可用的 Python 解释器。" };
79
+ if (environment?.requiresPython && !satisfiesRange(local.python ?? "", environment.requiresPython))
80
+ return { ...base, state: "needs-python", detail: `这个工具需要 Python ${environment.requiresPython},本机是 ${local.python}。` };
81
+ if (requires.length > 0 && this.dataDir && !existsSync(this.envPython(tool.id)))
82
+ return { ...base, state: "needs-env", detail: "首次运行这个工具时会自动安装这些依赖。" };
83
+ const known = environment?.fingerprint;
84
+ if (known?.python && known.platform && (majorMinor(known.python) !== majorMinor(local.python ?? "") || known.platform !== local.platform))
85
+ return { ...base, state: "differs", detail: `导出方是 Python ${known.python} / ${known.platform},本机是 ${local.python} / ${local.platform}。` };
86
+ return { ...base, state: "ready" };
87
+ }
88
+ /**
89
+ * Starts a run. It RETURNS SYNCHRONOUSLY - so bad parameters still throw at the call site, exactly
90
+ * as before - while the interpreter and, if the tool needs one, its virtual environment are prepared
91
+ * in the background. The run is already `running` at that point and the build's output lands in the
92
+ * run's own `logs`, which is why the tool's existing dialog shows the progress without knowing
93
+ * anything about environments.
94
+ */
95
+ start(input) {
96
+ validateParams(input.definition.parameters ?? {}, input.params);
97
+ const id = `toolrun_${randomUUID()}`;
98
+ const run = { id, toolId: input.toolId, status: "running", startedAt: new Date().toISOString(), logs: "" };
99
+ const timer = setTimeout(() => this.finish(id, "timed_out", `准备运行环境超过 ${MAX_ENV_TIMEOUT_MS}ms 时限`), MAX_ENV_TIMEOUT_MS);
100
+ timer.unref();
101
+ const active = { run, ownerId: input.ownerId, stdout: "", cancelled: false, timer };
102
+ this.runs.set(id, active);
103
+ void this.prepare(id, active, input);
104
+ return copy(run);
105
+ }
106
+ async prepare(id, active, input) {
107
+ try {
108
+ const requires = input.environment?.requires ?? [];
109
+ let python = this.resolvePython(input.toolId, false);
110
+ if (requires.length > 0) {
111
+ const built = await this.ensureEnvironment(input.toolId, python, requires, active);
112
+ if (!built.ok) {
113
+ this.finish(id, "failed", built.error);
114
+ return;
115
+ }
116
+ python = { path: this.envPython(input.toolId), kind: "tool-env" };
117
+ }
118
+ if (active.cancelled)
119
+ return;
120
+ if (active.timer)
121
+ clearTimeout(active.timer);
122
+ const scriptTimer = setTimeout(() => this.finish(id, "timed_out", `脚本超过 ${boundedTimeout(input.definition.timeoutMs)}ms 时限`), boundedTimeout(input.definition.timeoutMs));
123
+ scriptTimer.unref();
124
+ active.timer = scriptTimer;
125
+ this.launch(id, active, python, input);
126
+ }
127
+ catch (error) {
128
+ this.finish(id, "failed", error instanceof Error ? error.message : "tool environment could not be prepared");
129
+ }
130
+ }
131
+ /**
132
+ * THE VENV IS PYTHON'S OWN, ON PURPOSE. `python -m venv` finds its site-packages through the
133
+ * pyvenv.cfg next to the interpreter, which is why it survives the `-I` a tool runs under - a
134
+ * PYTHONPATH-based vendor directory does not (verified: `-I` implies `-E`, so PYTHONPATH is
135
+ * ignored, and dropping `-I` would give up the isolation that keeps a hostile PYTHON* environment
136
+ * from influencing a shared tool's script).
137
+ */
138
+ async ensureEnvironment(toolId, base, requires, active) {
139
+ if (!this.dataDir)
140
+ return { ok: false, error: "这个工具需要依赖,但没有可用的数据目录来存放它的虚拟环境。" };
141
+ const envDir = this.envDir(toolId), envPython = this.envPython(toolId);
142
+ const recorded = await readFile(join(envDir, "installed.json"), "utf8").then((text) => { try {
143
+ return JSON.parse(text);
144
+ }
145
+ catch {
146
+ return undefined;
147
+ } }).catch(() => undefined);
148
+ if (existsSync(envPython) && Array.isArray(recorded?.requires) && recorded.requires.length === requires.length && recorded.requires.every((item, index) => item === requires[index]))
149
+ return { ok: true };
150
+ await rm(envDir, { recursive: true, force: true });
151
+ await mkdir(envDir, { recursive: true });
152
+ const requirements = join(envDir, "requirements.txt");
153
+ await writeFile(requirements, `${requires.join("\n")}\n`, "utf8");
154
+ logLine(active, `正在准备 Python 虚拟环境(${requires.join("、")})…\n`);
155
+ const created = await runCapture(base.path, ["-m", "venv", join(envDir, ".venv")], MAX_ENV_TIMEOUT_MS, (text) => logLine(active, text));
156
+ if (!created.ok)
157
+ return { ok: false, error: `创建 Python 虚拟环境失败:${created.error || `解释器 ${base.path} 不可用`}` };
158
+ const installed = await runCapture(envPython, ["-m", "pip", "install", "--disable-pip-version-check", "--no-input", "-r", requirements], MAX_ENV_TIMEOUT_MS, (text) => logLine(active, text));
159
+ if (!installed.ok)
160
+ return { ok: false, error: `安装工具依赖失败:${installed.error || `pip 退出码 ${installed.code}`}(依赖:${requires.join("、")})` };
161
+ await writeFile(join(envDir, "installed.json"), JSON.stringify({ requires, python: base.path, builtAt: new Date().toISOString() }, null, 2), "utf8");
162
+ return { ok: true };
163
+ }
164
+ launch(id, active, python, input) {
165
+ // -I ignores user Python configuration and user site packages. No shell means params never become code.
166
+ const child = spawn(python.path, ["-I", "-u", input.script], { cwd: input.cwd, shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"], env: { ...pythonEnvironment(), SUPER_PI_TOOL_ID: input.toolId } });
167
+ active.child = child;
168
+ // A PIPE CARRIES BYTES, AND A READ BOUNDARY CAN LAND INSIDE A CHARACTER. A Chinese character is
169
+ // three bytes, so decoding one chunk at a time turns every character that straddles a boundary
170
+ // into U+FFFD - the same output comes out damaged on one machine and whole on another. The
171
+ // stream decodes instead, and Node keeps an incomplete character until the rest of its bytes
172
+ // arrive.
173
+ child.stdout.setEncoding("utf8");
174
+ child.stderr.setEncoding("utf8");
175
+ child.stdout.on("data", (text) => { active.stdout = clipped(`${active.stdout}${text}`); });
176
+ child.stderr.on("data", (text) => logLine(active, text));
177
+ child.once("error", (error) => this.finish(id, "failed", error.message));
178
+ child.once("close", (code) => {
179
+ if (active.run.status !== "running")
180
+ return;
181
+ if (code !== 0) {
182
+ this.finish(id, "failed", `Python exited with code ${code ?? "unknown"}`);
183
+ return;
184
+ }
185
+ try {
186
+ const parsed = JSON.parse(active.stdout);
187
+ if (!parsed || Array.isArray(parsed) || typeof parsed !== "object")
188
+ throw new Error("stdout must be a JSON object");
189
+ active.run.result = parsed;
190
+ this.finish(id, "succeeded");
191
+ }
192
+ catch (error) {
193
+ this.finish(id, "failed", `脚本没有输出一个 JSON 对象:${error instanceof Error ? error.message : "invalid output"}`);
194
+ }
195
+ });
196
+ child.stdin.end(JSON.stringify(input.params));
197
+ }
198
+ list(toolId, ownerId) {
199
+ return [...this.runs.values()].reverse()
200
+ .filter(entry => entry.run.toolId === toolId && entry.ownerId === ownerId)
201
+ .sort((a, b) => Number(b.run.status === "running") - Number(a.run.status === "running"))
202
+ .slice(0, 16)
203
+ .map(({ run: { id, status, startedAt, finishedAt } }) => ({ id, status, startedAt, finishedAt }));
204
+ }
205
+ get(id, toolId) { const active = this.runs.get(id); return active?.run.toolId === toolId ? copy(active.run) : undefined; }
206
+ cancel(id, toolId) { const active = this.runs.get(id); if (!active || active.run.toolId !== toolId)
207
+ return undefined; if (active.run.status === "running") {
208
+ active.cancelled = true;
209
+ this.finish(id, "cancelled");
210
+ } return copy(active.run); }
211
+ finish(id, status, error) { const active = this.runs.get(id); if (!active || active.run.status !== "running")
212
+ return; if (active.timer)
213
+ clearTimeout(active.timer); if (status !== "succeeded" && active.stdout)
214
+ active.run.logs = clipped(`${active.run.logs}${active.stdout}`); active.run.status = status; active.run.finishedAt = new Date().toISOString(); if (error)
215
+ active.run.error = error; if (active.child && !active.child.killed) {
216
+ try {
217
+ active.child.kill();
218
+ }
219
+ catch { }
220
+ } }
221
+ }
222
+ /**
223
+ * Runs a Python process with NO SHELL - the same rule as a tool run, because what is being installed
224
+ * is code too. There is no command string anywhere on this path, only an argv.
225
+ */
226
+ function runCapture(python, args, timeoutMs, onOutput) {
227
+ return new Promise((resolve) => {
228
+ let stdout = "", stderr = "", settled = false;
229
+ const child = spawn(python, args, { shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: pythonEnvironment() });
230
+ const timer = setTimeout(() => { if (settled)
231
+ return; settled = true; try {
232
+ child.kill();
233
+ }
234
+ catch { } resolve({ ok: false, code: null, stdout, error: `timed out after ${timeoutMs}ms` }); }, timeoutMs);
235
+ timer.unref();
236
+ child.stdout.setEncoding("utf8");
237
+ child.stderr.setEncoding("utf8");
238
+ child.stdout.on("data", (text) => { stdout += text; onOutput?.(text); });
239
+ child.stderr.on("data", (text) => { stderr += text; onOutput?.(text); });
240
+ child.once("error", (error) => { if (settled)
241
+ return; settled = true; clearTimeout(timer); resolve({ ok: false, code: null, stdout, error: error.message }); });
242
+ child.once("close", (code) => { if (settled)
243
+ return; settled = true; clearTimeout(timer); if (code === 0)
244
+ resolve({ ok: true, stdout, code });
245
+ else
246
+ resolve({ ok: false, code, stdout, error: stderr.split("\n").filter((line) => line.trim()).slice(-4).join("\n") }); });
247
+ });
248
+ }
249
+ /**
250
+ * A SMALL, DELIBERATELY SMALL PEP 440 READER: `>=`, `>`, `<=`, `<`, `==`, comma-separated. Anything it
251
+ * cannot parse counts as NOT satisfied, because a version check that guesses is worse than one that
252
+ * refuses. A tool needing something exotic declares no range at all and relies on the venv, not here.
253
+ */
254
+ export function satisfiesRange(version, range) {
255
+ const actual = version.split(".").map((part) => Number.parseInt(part, 10));
256
+ if (actual.some((part) => Number.isNaN(part)))
257
+ return false;
258
+ for (const term of range.split(",")) {
259
+ const match = /^(>=|<=|==|>|<)?\s*(\d+(?:\.\d+)*)$/.exec(term.trim());
260
+ if (!match)
261
+ return false;
262
+ const comparison = compareVersions(actual, match[2].split(".").map((part) => Number.parseInt(part, 10)));
263
+ const operator = match[1] ?? "==";
264
+ if (operator === ">=" && comparison < 0)
265
+ return false;
266
+ if (operator === ">" && comparison <= 0)
267
+ return false;
268
+ if (operator === "<=" && comparison > 0)
269
+ return false;
270
+ if (operator === "<" && comparison >= 0)
271
+ return false;
272
+ if (operator === "==" && comparison !== 0)
273
+ return false;
274
+ }
275
+ return true;
276
+ }
277
+ function compareVersions(left, right) { for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
278
+ const a = left[index] ?? 0, b = right[index] ?? 0;
279
+ if (a !== b)
280
+ return a < b ? -1 : 1;
281
+ } return 0; }
282
+ function majorMinor(version) { return version.split(".").slice(0, 2).join("."); }
283
+ function boundedTimeout(value) { return Math.max(1_000, Math.min(MAX_TIMEOUT_MS, Number.isFinite(value) ? Math.floor(value) : 60_000)); }
284
+ function clipped(text) { return text.length > MAX_LOG_BYTES ? text.slice(-MAX_LOG_BYTES) : text; }
285
+ function logLine(active, text) { active.run.logs = clipped(`${active.run.logs}${text}`); }
286
+ function copy(run) { return { ...run, result: run.result ? { ...run.result } : undefined }; }
287
+ export function validateParams(schema, params) {
288
+ if (!params || Array.isArray(params) || typeof params !== "object")
289
+ throw new Error("params 必须是对象");
290
+ for (const key of Object.keys(params))
291
+ if (!schema[key])
292
+ throw new Error(`不允许的参数:${key}`);
293
+ for (const [key, rule] of Object.entries(schema)) {
294
+ const value = params[key];
295
+ if (value === undefined) {
296
+ if (rule.required)
297
+ throw new Error(`缺少参数:${key}`);
298
+ continue;
299
+ }
300
+ const actual = Array.isArray(value) ? "array" : value === null ? "null" : typeof value;
301
+ if (actual !== rule.type)
302
+ throw new Error(`参数 ${key} 必须是 ${rule.type}`);
303
+ if (rule.enum && !rule.enum.includes(value))
304
+ throw new Error(`参数 ${key} 不在允许值中`);
305
+ }
306
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Translates a thrown error from the turn loop into a sentence a person reads.
3
+ *
4
+ * The turn loop throws for very different reasons: a model-provider rate limit, a 5xx that Pi's RPC
5
+ * layer chose to surface as a child exit, an OOM that took the whole process down, a path that
6
+ * resolved to a directory the workspace contract forbids, an `imageInput: false` mismatch. The
7
+ * throw message carries the technical fact; what the reader needs is the action it implies - retry,
8
+ * change model, check the key, change workspace - and that is the level this function writes at.
9
+ *
10
+ * The reason the shape is match-on-substring rather than match-on-error-class is that the upstream
11
+ * error is whatever Pi wrote to its own log: a string, not an exception class, and the host has
12
+ * nothing to pattern-match against other than the message itself. The literals below are
13
+ * deliberately permissive on the LLM side ("quota", "rate limit", "usage limit", "too many requests",
14
+ * "5-hour", "5h") because the underlying model APIs name this limit in several ways, and the
15
+ * reader cares about the bucket, not the exact wording.
16
+ *
17
+ * THIS LIVES IN ITS OWN MODULE so the buckets can be tested without starting a run: the function is
18
+ * pure, and every branch below is a decision about what a person is told, which is worth a test that
19
+ * needs no server, socket or Pi process.
20
+ */
21
+ export declare function formatTurnFailure(error: unknown): string;
22
+ /**
23
+ * THE MODEL FILLED ITS OUTPUT BUDGET AND STOPPED MID-ANSWER.
24
+ *
25
+ * A length stop is NOT a crash. The provider answered, streamed real text, and stopped because it
26
+ * ran out of `max_tokens` - which is what happens every time an answer is longer than one output
27
+ * budget. Treating it as a failure is what made an orchestrated child session die: the run service
28
+ * stamped the conversation `failed`, the orchestrator reported a failure to the parent, and a task
29
+ * that was one sentence from done was thrown away.
30
+ *
31
+ * It carries a CLASS so the layers above can tell it apart from a provider error by identity rather
32
+ * than by matching a Chinese substring - the message is written for a reader, and a reader-facing
33
+ * sentence is not a reliable machine contract.
34
+ */
35
+ export declare class LengthExceededError extends Error {
36
+ readonly stopReason: "length";
37
+ constructor(message?: string);
38
+ }
39
+ /**
40
+ * Whether this failure is a length stop rather than a real failure.
41
+ *
42
+ * The class is the answer; the message match is the BACKSTOP for a throw site that never got to
43
+ * construct the class - an error that crossed a process boundary, or one that was rebuilt from its
44
+ * text somewhere along the way. Both are checked because a length stop that loses its class on the
45
+ * way up is exactly the case that used to kill a child session.
46
+ */
47
+ export declare function isLengthExceededError(error: unknown): boolean;
48
+ export declare function controllerAborted(error: unknown): boolean;
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Translates a thrown error from the turn loop into a sentence a person reads.
3
+ *
4
+ * The turn loop throws for very different reasons: a model-provider rate limit, a 5xx that Pi's RPC
5
+ * layer chose to surface as a child exit, an OOM that took the whole process down, a path that
6
+ * resolved to a directory the workspace contract forbids, an `imageInput: false` mismatch. The
7
+ * throw message carries the technical fact; what the reader needs is the action it implies - retry,
8
+ * change model, check the key, change workspace - and that is the level this function writes at.
9
+ *
10
+ * The reason the shape is match-on-substring rather than match-on-error-class is that the upstream
11
+ * error is whatever Pi wrote to its own log: a string, not an exception class, and the host has
12
+ * nothing to pattern-match against other than the message itself. The literals below are
13
+ * deliberately permissive on the LLM side ("quota", "rate limit", "usage limit", "too many requests",
14
+ * "5-hour", "5h") because the underlying model APIs name this limit in several ways, and the
15
+ * reader cares about the bucket, not the exact wording.
16
+ *
17
+ * THIS LIVES IN ITS OWN MODULE so the buckets can be tested without starting a run: the function is
18
+ * pure, and every branch below is a decision about what a person is told, which is worth a test that
19
+ * needs no server, socket or Pi process.
20
+ */
21
+ export function formatTurnFailure(error) {
22
+ if (controllerAborted(error))
23
+ return "本轮任务已停止。";
24
+ const raw = error instanceof Error ? error.message : typeof error === "string" ? error : "";
25
+ const lower = raw.toLowerCase();
26
+ // PROVIDER QUOTA / RATE LIMIT - the only reason the user is in this branch is because Pi was
27
+ // answering them a moment ago and now the model will not let it. The action is "wait or change
28
+ // model"; the wording has to make that obvious from the banner alone, without a tooltip.
29
+ if (/\b429\b|quota|rate limit|usage limit|too many requests|5-hour|5h|resource_exhausted|resourc exhaust|hit your limit|usage cap|usage restrict/.test(lower)) {
30
+ return "模型额度已用完(5 小时限额或类似上限),Pi 已停止回答。可以等待重置后重试,或在会话里换一个模型再发。";
31
+ }
32
+ // RPC CHANNEL DEAD - Pi died without producing a `settled` event. Anything in the turn is now
33
+ // unanswerable, but the deltas the user already saw are still on screen, so the message has to
34
+ // say "we noticed and stopped" rather than "your input was lost".
35
+ if (lower.includes("pi rpc channel closed") || lower.includes("agent rpc") || lower.includes("exited before settling")) {
36
+ return "Pi 进程异常退出,未完成本轮回答。已停止运行,可以直接重发任务继续。";
37
+ }
38
+ // NO PI - the launch path failed (binary missing, executable bit, Windows shim). The reader's
39
+ // best move is a `which pi` / reinstall, and the banner should point there.
40
+ if (lower.includes("could not find") && lower.includes("pi") || lower.includes("pi command") || lower.startsWith("pi ")) {
41
+ return `无法启动 Pi:${raw || "未知原因"}。请确认 Pi 已正确安装并可在命令行运行。`;
42
+ }
43
+ // WORKSPACE PATH - turn refused on directory the contract forbids. Refusal happens before
44
+ // anything is on screen, so the banner is also the only place the reason lives.
45
+ if (lower.includes("workspace directory") || lower.includes("does not exist or is not a directory")) {
46
+ const match = raw.match(/does not exist or is not a directory:\s*(.+?)(?:\.\s*Refusing|$)/);
47
+ const path = match?.[1]?.trim();
48
+ return `工作区目录不存在:${path || "未知路径"}`;
49
+ }
50
+ // PROVIDER UNREACHABLE - the request never reached the model. This is the branch a custom
51
+ // provider with a wrong Base URL lands in, and the person editing that URL needs to be told that
52
+ // the address or the network is the problem, not that "Pi failed".
53
+ if (/failed to fetch|fetch failed|econnrefused|econnreset|enotfound|eai_again|socket hang up|connection refused|connection reset|network\s*error/.test(lower)) {
54
+ return "连不上模型供应商:网络不可达或接口地址不对。请检查供应商的 Base URL 与网络连接,然后重发。";
55
+ }
56
+ // PROVIDER AUTH - the key is wrong, missing, or lacks access to this model. Pi reports this as a
57
+ // 401/403 from the provider; the actionable place is the supplier's key, not the conversation.
58
+ if (/\b401\b|\b403\b|unauthorized|forbidden|invalid api key|incorrect api key|authentication failed|insufficient permission/.test(lower)) {
59
+ return "模型供应商拒绝了这次请求:鉴权失败。请在设置里检查这个供应商的 API key,然后重发。";
60
+ }
61
+ // PROVIDER 5XX - their side is down. Retrying is the action, and saying so stops the reader from
62
+ // hunting for a configuration mistake on their own machine.
63
+ const status = /\bhttp\s*(?:status\s*)?[:=]?\s*(\d{3})\b|\bstatus(?:\s*code)?\s*[:=]\s*(\d{3})\b/.exec(lower);
64
+ const code = Number(status?.[1] ?? status?.[2] ?? 0);
65
+ if (code >= 500 && code <= 599 || /internal server error|bad gateway|service unavailable|gateway timeout/.test(lower)) {
66
+ return `模型供应商服务端出错了${code ? `(HTTP ${code})` : ""},通常稍后重试即可。`;
67
+ }
68
+ // CONTEXT OVERFLOW - the conversation outgrew the model's window.
69
+ //
70
+ // This is the branch a reader hits when the session stops working entirely, so it has to name the
71
+ // cause AND the way out. The upstream wording varies by provider, and the shapes that show up are
72
+ // "context length exceeded", "maximum context length", "too many tokens", "prompt is too long",
73
+ // "reduce the length of the messages", and the 400s some providers use for it.
74
+ //
75
+ // The action is the same in every case: the conversation is too long for one request, and the
76
+ // reader's choices are to start a new conversation or use a model with a bigger window. Saying
77
+ // "the model refused" would hide both.
78
+ if (/context[\s_]*(?:length|window|size)[\s_]*(?:exceeded|exceeds|too large|limit)|maximum context|context limit|too many tokens|prompt is too long|reduce the length of the messages|exceeds the maximum|上下文(?:超|过)限|上下文长度/.test(lower)) {
79
+ return "这一轮的内容超过了模型的上下文上限,模型没能读下整段对话。可以新开一个会话继续,或换一个上下文窗口更大的模型(Pi 会在超限前自动压缩,这轮没能完成压缩)。";
80
+ }
81
+ // IMAGE MISMATCH - explicit by the caller, no need to translate.
82
+ if (lower.includes("不支持图片输入")) {
83
+ return raw;
84
+ }
85
+ // LENGTH LIMIT - the model stopped because it filled the output budget, NOT because anything
86
+ // broke. The answer is incomplete, but everything that was said is still on screen, so the
87
+ // sentence has to offer the way out (say "continue") instead of calling it a failure.
88
+ //
89
+ // THE SENTENCE IS BUILT, NOT TAKEN FROM THE ERROR. The error's own message says the fact
90
+ // ("模型输出达到本轮长度上限,回答未完成") and stops there - which is a statement, not an action, and
91
+ // a reader who is told a thing stopped has no idea what to do next. What they need is the way
92
+ // out, so the sentence always carries it. Pi's own words are kept only when they add something
93
+ // the sentence does not already say.
94
+ if (isLengthExceededError(error)) {
95
+ const detail = raw && !/长度上限/.test(raw) ? `(${raw})` : "";
96
+ return `模型单次输出达到长度上限,回答没有写完${detail}。可以点「继续写完」或者自己发一句「继续」,模型会从被截断的地方接着写。`;
97
+ }
98
+ // GENERIC - the literal message is more useful than a paraphrase, but it has to be the LAST
99
+ // branch and the message has to be non-empty (a thrown `new Error()` is empty and renders
100
+ // nothing, which is exactly the silence this whole change exists to break).
101
+ return raw || "Pi 未能完成本轮回答,已标记为失败。可以重发任务继续。";
102
+ }
103
+ /**
104
+ * THE MODEL FILLED ITS OUTPUT BUDGET AND STOPPED MID-ANSWER.
105
+ *
106
+ * A length stop is NOT a crash. The provider answered, streamed real text, and stopped because it
107
+ * ran out of `max_tokens` - which is what happens every time an answer is longer than one output
108
+ * budget. Treating it as a failure is what made an orchestrated child session die: the run service
109
+ * stamped the conversation `failed`, the orchestrator reported a failure to the parent, and a task
110
+ * that was one sentence from done was thrown away.
111
+ *
112
+ * It carries a CLASS so the layers above can tell it apart from a provider error by identity rather
113
+ * than by matching a Chinese substring - the message is written for a reader, and a reader-facing
114
+ * sentence is not a reliable machine contract.
115
+ */
116
+ export class LengthExceededError extends Error {
117
+ stopReason = "length";
118
+ constructor(message) {
119
+ super(message || "模型输出达到本轮长度上限,回答未完成。");
120
+ this.name = "LengthExceededError";
121
+ }
122
+ }
123
+ /**
124
+ * Whether this failure is a length stop rather than a real failure.
125
+ *
126
+ * The class is the answer; the message match is the BACKSTOP for a throw site that never got to
127
+ * construct the class - an error that crossed a process boundary, or one that was rebuilt from its
128
+ * text somewhere along the way. Both are checked because a length stop that loses its class on the
129
+ * way up is exactly the case that used to kill a child session.
130
+ */
131
+ export function isLengthExceededError(error) {
132
+ if (!error)
133
+ return false;
134
+ if (error instanceof LengthExceededError)
135
+ return true;
136
+ if (error?.stopReason === "length")
137
+ return true;
138
+ const msg = error instanceof Error ? error.message : typeof error === "string" ? error : "";
139
+ return msg.includes("模型输出达到本轮长度上限") || msg.includes("达到本轮长度上限") || msg.includes("单次输出达到长度上限");
140
+ }
141
+ export function controllerAborted(error) {
142
+ if (!error)
143
+ return false;
144
+ if (error instanceof Error && error.name === "AbortError")
145
+ return true;
146
+ const msg = error instanceof Error ? error.message : typeof error === "string" ? error : "";
147
+ return /abort|cancel|aborted/i.test(msg);
148
+ }