@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,30 @@
1
+ import type { Message } from "./types.js";
2
+ export declare const ENGINEERING_ROLE_IDS: Set<string>;
3
+ export declare const isEngineeringRole: (id: string | undefined) => boolean;
4
+ export declare const STANDARD_PREFIX = "\u4EE3\u7801\u89C4\u8303\uFF1A";
5
+ export declare const LESSON_PREFIX = "\u5DE5\u7A0B\u9A8C\u8BC1\u7ECF\u9A8C\uFF1A";
6
+ export declare const sensitiveMemoryText: (text: string) => boolean;
7
+ export declare function userProse(text: string): string;
8
+ export declare function isLearningCandidate(userText: string, engineeringRole: boolean): boolean;
9
+ type Check = {
10
+ id: string;
11
+ command: string;
12
+ output: string;
13
+ status: "ok" | "error";
14
+ };
15
+ export type RecoveryEvidence = {
16
+ failed: Check;
17
+ passed: Check;
18
+ };
19
+ export declare function recoveries(messages: Message[], finalAssistantId: string): RecoveryEvidence[];
20
+ export declare function learningResult(text: string, userText: string | undefined, evidence: RecoveryEvidence[]): {
21
+ standards: {
22
+ applicability?: string;
23
+ rule: string;
24
+ }[];
25
+ lesson: {
26
+ rule: string;
27
+ applicability: string;
28
+ } | undefined;
29
+ };
30
+ export {};
@@ -0,0 +1,106 @@
1
+ export const ENGINEERING_ROLE_IDS = new Set(["solution-designer", "code-designer", "code-auditor", "document-organizer"]);
2
+ const codingRoles = new Set([...ENGINEERING_ROLE_IDS, "coder", "planner", "reviewer", "project-leader", "verifier"]);
3
+ export const isEngineeringRole = (id) => id !== undefined && codingRoles.has(id);
4
+ export const STANDARD_PREFIX = "代码规范:";
5
+ export const LESSON_PREFIX = "工程验证经验:";
6
+ export const sensitiveMemoryText = (text) => /-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:\s*bearer\s+\S+|(?:api[_-]?key|password|[a-z_]*token)\s*=\s*["']?[^\s"']{8,}/iu.test(text);
7
+ const privateExperienceText = (text) => sensitiveMemoryText(text)
8
+ || /(?:\b[a-z]:[\\/]|\\\\[^\\\s]+\\|\/(?:home|Users|local-data|var|root|mnt|opt)\/|\b(?:https?|ssh):\/\/\S+|\b(?:sk-[A-Za-z0-9_-]{24,}|gh[pousr]_[A-Za-z0-9]{20,}))/iu.test(text);
9
+ const stableWording = /(?:以后|今后|下次|始终|一律|规范|约定|每次|别再|总是|不能再|长期|默认|always|never|from now on|going forward|convention)/iu;
10
+ const engineeringTopic = /(?:health|健康|代码|源码|接口|风格|验证|日志|测试|发布|工作区|文件|分支|目录|仓库|部署|刷新|行尾|crlf|bug|lint|test|build|repo|release|commit|style|naming)/iu;
11
+ const correctionWording = /(?:不要|不能|不应该|你这里|应该用|统一用|这里用|must|should use|do not|instead)/iu;
12
+ const temporaryWording = /(?:这一次|这次先|这次不用|本次先|临时|仅本次|暂时|现在先|先不用|for this (?:task|change|run)|for now|temporarily)/iu;
13
+ const globalWording = /(?:全局|所有(?:工作区|仓库|项目)|任何(?:工作区|仓库|项目)|跨(?:工作区|仓库|项目)|globally|across all (?:workspaces|repos|projects))/iu;
14
+ export function userProse(text) {
15
+ let fence;
16
+ return text.split(/\r?\n/u).filter(line => {
17
+ const marker = /^\s*(`{3,}|~{3,})(.*)$/u.exec(line);
18
+ if (marker) {
19
+ if (!fence)
20
+ fence = marker[1];
21
+ else if (marker[1].startsWith(fence) && !marker[2].trim())
22
+ fence = undefined;
23
+ return false;
24
+ }
25
+ return !fence && !/^\s*>/u.test(line);
26
+ }).join("\n");
27
+ }
28
+ export function isLearningCandidate(userText, engineeringRole) {
29
+ return Boolean(userText.trim()) && !sensitiveMemoryText(userText)
30
+ && (engineeringRole || (engineeringTopic.test(userText) && (stableWording.test(userText) || correctionWording.test(userText))));
31
+ }
32
+ function checkEvidence(messageId, tool, index) {
33
+ const command = tool.detail?.trim() ?? "";
34
+ const output = tool.result?.text.trim() ?? "";
35
+ if (!/^(bash|powershell|shell|command)$/iu.test(tool.label) || !tool.status || !command || !output
36
+ || sensitiveMemoryText(command) || sensitiveMemoryText(output))
37
+ return;
38
+ if (!/api\/health|healthcheck|server-ready|install-smoke|(?:\b(?:node --test|npm (?:run )?test|pytest|tsc|lint|typecheck|build)\b)/iu.test(command))
39
+ return;
40
+ if (tool.status === "ok") {
41
+ const healthResponse = /\b(?:curl|invoke-restmethod|invoke-webrequest|fetch|iwr)\b/iu.test(command)
42
+ && /["']status["']\s*:\s*["']ok["']/iu.test(output) && /["']service["']\s*:\s*["']super-pi["']/iu.test(output);
43
+ const verifiedCompletion = /(?:node --test|npm (?:run )?test|pytest|tsc|lint|typecheck|build|install-smoke)/iu.test(command)
44
+ && /(?:#\s*fail\s+0\b|(?:^|\s)\d+\s+passed\b|BUILD SUCCESS|INSTALL SMOKE PASSED)/imu.test(output);
45
+ if (!healthResponse && !verifiedCompletion)
46
+ return;
47
+ }
48
+ return { id: messageId + ":" + index, command: command.slice(0, 400), output: output.slice(-650), status: tool.status };
49
+ }
50
+ function verificationFamily(command) {
51
+ if (/install-smoke|server-ready/iu.test(command))
52
+ return command.replace(/\s+/gu, " ");
53
+ if (/api\/health/iu.test(command) && /\b(?:curl|invoke-restmethod|invoke-webrequest|fetch|iwr)\b/iu.test(command))
54
+ return "http-health";
55
+ return command.replace(/\s+/gu, " ");
56
+ }
57
+ export function recoveries(messages, finalAssistantId) {
58
+ const finalIndex = messages.findIndex(message => message.id === finalAssistantId && message.role === "assistant");
59
+ if (finalIndex < 0)
60
+ return [];
61
+ const stages = messages.slice(0, finalIndex + 1).filter(message => message.role === "assistant").slice(-3);
62
+ const recentFailures = new Map();
63
+ const confirmed = [];
64
+ for (const message of stages)
65
+ for (const [index, tool] of (message.toolCalls ?? []).entries()) {
66
+ const check = checkEvidence(message.id, tool, index);
67
+ if (!check)
68
+ continue;
69
+ const family = verificationFamily(check.command);
70
+ if (check.status === "error")
71
+ recentFailures.set(family, check);
72
+ else {
73
+ const failed = recentFailures.get(family);
74
+ if (failed && message.id === finalAssistantId)
75
+ confirmed.push({ failed, passed: check });
76
+ recentFailures.delete(family);
77
+ }
78
+ }
79
+ return confirmed.slice(-3);
80
+ }
81
+ export function learningResult(text, userText, evidence) {
82
+ const result = JSON.parse(text.trim().replace(/^```(?:json)?\s*|\s*```$/giu, ""));
83
+ const standards = [];
84
+ if (userText && Array.isArray(result?.standards))
85
+ for (const item of result.standards.slice(0, 4)) {
86
+ const quote = typeof item?.quote === "string" ? item.quote.trim() : "";
87
+ if (!quote || quote.length > 600 || !userText.includes(quote) || privateExperienceText(quote) || temporaryWording.test(quote))
88
+ continue;
89
+ const originalLine = userText.split(/\r?\n/u).find(line => line.includes(quote));
90
+ if (originalLine && temporaryWording.test(originalLine))
91
+ continue;
92
+ const condition = typeof item.conditionQuote === "string" ? item.conditionQuote.trim() : "";
93
+ const validCondition = condition && condition.length <= 240 && userText.includes(condition)
94
+ && !privateExperienceText(condition) && !temporaryWording.test(condition);
95
+ const applicability = validCondition ? condition : globalWording.test(originalLine ?? quote) ? "用户明确要求跨项目遵守" : undefined;
96
+ standards.push({ applicability, rule: STANDARD_PREFIX + quote });
97
+ }
98
+ const suggestion = result?.lesson;
99
+ const pair = evidence.find(item => item.failed.id === suggestion?.failedId && item.passed.id === suggestion?.passedId);
100
+ const lesson = typeof suggestion?.text === "string" ? suggestion.text.trim() : "";
101
+ const condition = typeof suggestion?.applicability === "string" ? suggestion.applicability.trim() : "";
102
+ return { standards, lesson: pair && lesson && lesson.length <= 650 && !privateExperienceText(lesson) ? {
103
+ rule: LESSON_PREFIX + lesson + "\n实测来源:" + pair.failed.id + " → " + pair.passed.id,
104
+ applicability: condition && condition.length <= 240 && !privateExperienceText(condition) ? condition : "已有相同故障现象和验收条件的任务",
105
+ } : undefined };
106
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Lightweight background command execution using node-pty.
3
+ *
4
+ * This module is entirely independent from subagents.ts. It spawns a PTY, runs one command to completion,
5
+ * collects its output, and fires an onComplete callback. It exists so the pi-task tool can run background
6
+ * bash commands without going through the subagent dispatch machinery.
7
+ */
8
+ import type { AppState, ExecEvent } from "./types.js";
9
+ export interface ExecSession {
10
+ id: string;
11
+ pid: number;
12
+ cmd: string;
13
+ cwd: string;
14
+ startTime: Date;
15
+ exitCode: number | null;
16
+ killed: boolean;
17
+ }
18
+ /** Callback fired when an exec session ends, with the final result. */
19
+ export type ExecCompletion = {
20
+ status: "exited" | "cancelled" | "interrupted";
21
+ signal?: number;
22
+ offset: number;
23
+ };
24
+ export type ExecCompleteHandler = (sessionId: string, exitCode: number, stdout: string, stderr: string, completion: ExecCompletion) => void;
25
+ type ExecCheckpoint = (id: string, output: string, offset: number) => Promise<void>;
26
+ export declare class ExecService {
27
+ private readonly onCheckpoint?;
28
+ private readonly sessions;
29
+ private readonly broadcast;
30
+ private readonly onComplete;
31
+ constructor(broadcast: (event: ExecEvent) => void, onComplete: ExecCompleteHandler, onCheckpoint?: ExecCheckpoint | undefined);
32
+ get status(): {
33
+ enabled: boolean;
34
+ reason?: string;
35
+ };
36
+ spawn(id: string, cmd: string, cwd: string, conversationId?: string): ExecSession;
37
+ outputSnapshots(state: Pick<AppState, "conversations" | "backgroundTasks">, scope?: {
38
+ conversationId?: string;
39
+ }): ExecEvent[];
40
+ kill(id: string, cancellation?: "cancelled" | "interrupted"): void;
41
+ stop(id: string, cancellation?: "cancelled" | "interrupted"): Promise<boolean>;
42
+ closeAll(): Promise<void>;
43
+ private finish;
44
+ }
45
+ export {};
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Lightweight background command execution using node-pty.
3
+ *
4
+ * This module is entirely independent from subagents.ts. It spawns a PTY, runs one command to completion,
5
+ * collects its output, and fires an onComplete callback. It exists so the pi-task tool can run background
6
+ * bash commands without going through the subagent dispatch machinery.
7
+ */
8
+ import { createRequire } from "node:module";
9
+ import { BACKGROUND_LOG_LIMIT } from "../shared/background-task.js";
10
+ let ptyModule;
11
+ let ptyLoadFailure;
12
+ function loadPty() {
13
+ if (ptyModule)
14
+ return ptyModule;
15
+ if (ptyLoadFailure)
16
+ return undefined;
17
+ try {
18
+ const require = createRequire(import.meta.url);
19
+ ptyModule = require("node-pty");
20
+ return ptyModule;
21
+ }
22
+ catch (error) {
23
+ ptyLoadFailure = error instanceof Error ? error.message : String(error);
24
+ return undefined;
25
+ }
26
+ }
27
+ function ptyLoadError() {
28
+ loadPty(); // ensure the failure is populated
29
+ return ptyLoadFailure;
30
+ }
31
+ const CHECKPOINT_INTERVAL_MS = 500;
32
+ const STOP_TIMEOUT_MS = 2000;
33
+ export class ExecService {
34
+ onCheckpoint;
35
+ sessions = new Map();
36
+ broadcast;
37
+ onComplete;
38
+ constructor(broadcast, onComplete, onCheckpoint) {
39
+ this.onCheckpoint = onCheckpoint;
40
+ this.broadcast = broadcast;
41
+ this.onComplete = onComplete;
42
+ }
43
+ get status() {
44
+ const pty = loadPty();
45
+ if (!pty)
46
+ return { enabled: false, reason: ptyLoadError() };
47
+ return { enabled: true };
48
+ }
49
+ spawn(id, cmd, cwd, conversationId) {
50
+ const pty = loadPty();
51
+ if (!pty)
52
+ throw new Error("node-pty is not available");
53
+ // Determine shell to run the command.
54
+ const shell = defaultShell();
55
+ let resolveEnd;
56
+ const ended = new Promise(resolve => { resolveEnd = resolve; });
57
+ const active = {
58
+ conversationId,
59
+ pty: pty.spawn(shell.file, [...shell.args, "-c", cmd], {
60
+ name: "xterm-256color",
61
+ cols: 80,
62
+ rows: 24,
63
+ cwd,
64
+ env: { ...process.env, TERM: "xterm-256color" },
65
+ }),
66
+ output: "",
67
+ offset: 0,
68
+ checkpoint: undefined,
69
+ ended,
70
+ resolveEnd,
71
+ };
72
+ this.sessions.set(id, active);
73
+ active.pty.onData((data) => {
74
+ if (this.sessions.get(id) !== active)
75
+ return;
76
+ active.offset += data.length;
77
+ active.output = (active.output + data).slice(-BACKGROUND_LOG_LIMIT);
78
+ this.broadcast({ type: "exec.output", sessionId: id, conversationId, data, offset: active.offset, truncated: active.offset > active.output.length });
79
+ if (this.onCheckpoint && !active.checkpoint) {
80
+ active.checkpoint = setTimeout(() => {
81
+ active.checkpoint = undefined;
82
+ void this.onCheckpoint?.(id, active.output, active.offset).catch(error => {
83
+ console.warn("Super Pi: could not checkpoint background output:", error);
84
+ });
85
+ }, CHECKPOINT_INTERVAL_MS);
86
+ active.checkpoint.unref();
87
+ }
88
+ });
89
+ active.pty.onExit(({ exitCode, signal }) => this.finish(id, active, exitCode ?? 1, signal));
90
+ return {
91
+ id,
92
+ pid: active.pty.pid,
93
+ cmd,
94
+ cwd,
95
+ startTime: new Date(),
96
+ exitCode: null,
97
+ killed: false,
98
+ };
99
+ }
100
+ outputSnapshots(state, scope) {
101
+ const visible = new Set(state.conversations.map(conversation => conversation.id));
102
+ const ids = state.backgroundTasks.filter(task => visible.has(task.conversationId) && (!scope || task.conversationId === scope.conversationId)).map(task => task.id);
103
+ const maxPerTask = Math.min(BACKGROUND_LOG_LIMIT, Math.max(1, Math.floor(512_000 / Math.max(ids.length, 1))));
104
+ return ids.flatMap(id => {
105
+ const session = this.sessions.get(id);
106
+ if (!session)
107
+ return [];
108
+ const data = session.output.slice(-maxPerTask);
109
+ return [{ type: "exec.output", sessionId: id, conversationId: session.conversationId, data, replace: true, offset: session.offset, truncated: session.offset > data.length }];
110
+ });
111
+ }
112
+ kill(id, cancellation = "cancelled") {
113
+ const session = this.sessions.get(id);
114
+ if (!session)
115
+ return;
116
+ session.cancellation ??= cancellation;
117
+ try {
118
+ session.pty.kill();
119
+ }
120
+ catch { /* already gone */ }
121
+ }
122
+ async stop(id, cancellation = "cancelled") {
123
+ const session = this.sessions.get(id);
124
+ if (!session)
125
+ return false;
126
+ this.kill(id, cancellation);
127
+ let timer;
128
+ await Promise.race([session.ended, new Promise(resolve => { timer = setTimeout(resolve, STOP_TIMEOUT_MS); })]);
129
+ clearTimeout(timer);
130
+ if (this.sessions.get(id) === session)
131
+ throw new Error("后台命令尚未退出,可以重试终止。");
132
+ return true;
133
+ }
134
+ async closeAll() {
135
+ const results = await Promise.allSettled([...this.sessions.keys()].map(id => this.stop(id, "interrupted")));
136
+ for (const result of results) {
137
+ if (result.status === "rejected")
138
+ console.warn("Super Pi: a background command did not exit at shutdown:", result.reason);
139
+ }
140
+ }
141
+ finish(id, session, exitCode, signal) {
142
+ if (this.sessions.get(id) !== session)
143
+ return;
144
+ this.sessions.delete(id);
145
+ clearTimeout(session.checkpoint);
146
+ // A PTY delivers one stream, including error diagnostics.
147
+ try {
148
+ this.onComplete(id, exitCode, session.output, "", { status: session.cancellation ?? "exited", signal, offset: session.offset });
149
+ }
150
+ finally {
151
+ session.resolveEnd();
152
+ }
153
+ }
154
+ }
155
+ function defaultShell() {
156
+ const override = process.env.SUPER_PI_TERMINAL_SHELL?.trim();
157
+ if (override) {
158
+ const parts = override.match(/"[^"]+"|\S+/g) ?? [];
159
+ const file = (parts.shift() ?? "").replace(/^"|"$/g, "");
160
+ if (file)
161
+ return { file, args: parts };
162
+ }
163
+ if (process.platform === "win32") {
164
+ return { file: process.env.COMSPEC?.toLowerCase().includes("pwsh") ? "pwsh.exe" : "powershell.exe", args: [] };
165
+ }
166
+ return { file: process.env.SHELL || "/bin/sh", args: ["-l"] };
167
+ }
@@ -0,0 +1,34 @@
1
+ export declare function createExplicitFileOpen(): {
2
+ open(workspaceId: string, workspace: string, root: string, input: string): Promise<{
3
+ meta: import("./files.js").FileMeta;
4
+ text: boolean;
5
+ path: string;
6
+ name: string;
7
+ } | {
8
+ content: string;
9
+ eol: "\n" | "\r\n";
10
+ bom: boolean;
11
+ meta: import("./files.js").FileMeta;
12
+ text: boolean;
13
+ path: string;
14
+ name: string;
15
+ } | {
16
+ meta: import("./files.js").FileMeta;
17
+ text: boolean;
18
+ path: string;
19
+ name: string;
20
+ targetName?: string | undefined;
21
+ ticket: `${string}-${string}-${string}-${string}-${string}`;
22
+ } | {
23
+ content: string;
24
+ eol: "\n" | "\r\n";
25
+ bom: boolean;
26
+ meta: import("./files.js").FileMeta;
27
+ text: boolean;
28
+ path: string;
29
+ name: string;
30
+ targetName?: string | undefined;
31
+ ticket: `${string}-${string}-${string}-${string}-${string}`;
32
+ }>;
33
+ target(workspaceId: string, root: string, ticket: string): Promise<string>;
34
+ };
@@ -0,0 +1,105 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { lstat, open, realpath } from "node:fs/promises";
4
+ import { basename, isAbsolute, posix, resolve } from "node:path";
5
+ import { contains, decodeWorkspaceText, fileMetaFromStat, FilesError, hasBinaryExtension, MAX_FILE_BYTES, toRelative } from "./files.js";
6
+ import { explorerInternalPath, explorerPath } from "./workspace-file-operations.js";
7
+ const MAX_OPEN_TICKETS = 256;
8
+ function localAbsolute(path) {
9
+ return process.platform === "win32" ? /^[a-z]:[\\/]/i.test(path) : path.startsWith("/") && !path.startsWith("//");
10
+ }
11
+ async function selectedFile(workspace, root, input) {
12
+ if (input.includes("\0"))
13
+ throw new FilesError(400, "文件路径包含非法字符。", "bad_path");
14
+ if (process.platform === "win32" && input.slice(localAbsolute(input) ? 2 : 0).includes(":")) {
15
+ throw new FilesError(400, "请输入完整的本机文件路径。", "bad_path");
16
+ }
17
+ if (localAbsolute(input))
18
+ return resolve(input);
19
+ if (isAbsolute(input) || /^[\\/]|^[a-z]:/i.test(input)) {
20
+ throw new FilesError(400, "请输入完整的本机文件路径。", "bad_path");
21
+ }
22
+ const relative = input.replaceAll("\\", "/");
23
+ const name = posix.basename(relative);
24
+ if (!name || name === "." || name === "..")
25
+ throw new FilesError(400, "请选择一个文件。", "not_a_file");
26
+ const parent = await explorerPath(workspace, root, posix.dirname(relative), true);
27
+ const file = resolve(parent, name);
28
+ if (explorerInternalPath(toRelative(workspace, file))) {
29
+ throw new FilesError(403, "不能直接访问应用的回收目录。", "protected_path");
30
+ }
31
+ if (!(await lstat(file)).isSymbolicLink())
32
+ await explorerPath(workspace, root, relative);
33
+ return file;
34
+ }
35
+ async function readOpenedFile(path) {
36
+ if (!(await lstat(path)).isFile())
37
+ throw new FilesError(400, "请选择一个普通文件。", "not_a_file");
38
+ const handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK | (constants.O_NOFOLLOW ?? 0));
39
+ try {
40
+ const info = await handle.stat({ bigint: true });
41
+ if (!info.isFile())
42
+ throw new FilesError(400, "请选择一个普通文件。", "not_a_file");
43
+ const meta = fileMetaFromStat(info);
44
+ if (meta.size > MAX_FILE_BYTES || hasBinaryExtension(path))
45
+ return { meta, text: false };
46
+ const buffer = Buffer.alloc(meta.size + 1);
47
+ let read = 0;
48
+ while (read < buffer.length) {
49
+ const { bytesRead } = await handle.read(buffer, read, buffer.length - read, read);
50
+ if (!bytesRead)
51
+ break;
52
+ read += bytesRead;
53
+ }
54
+ if (read !== meta.size)
55
+ throw new FilesError(409, "读取时文件发生变化,请重新打开。", "stale");
56
+ try {
57
+ return { meta, text: true, ...decodeWorkspaceText(buffer.subarray(0, read), path) };
58
+ }
59
+ catch (error) {
60
+ if (error instanceof FilesError && error.code === "binary")
61
+ return { meta, text: false };
62
+ throw error;
63
+ }
64
+ }
65
+ finally {
66
+ await handle.close();
67
+ }
68
+ }
69
+ export function createExplicitFileOpen() {
70
+ const tickets = new Map();
71
+ return {
72
+ async open(workspaceId, workspace, root, input) {
73
+ const selected = await selectedFile(workspace, root, input);
74
+ const [path, canonicalRoot, canonicalWorkspace] = await Promise.all([realpath(selected), realpath(root), realpath(workspace)]);
75
+ if (contains(canonicalWorkspace, path) && explorerInternalPath(toRelative(canonicalWorkspace, path))) {
76
+ throw new FilesError(403, "不能直接访问应用的回收目录。", "protected_path");
77
+ }
78
+ if (contains(canonicalRoot, path)) {
79
+ const scoped = toRelative(canonicalRoot, path);
80
+ await explorerPath(workspace, root, scoped);
81
+ return { path: scoped, name: basename(path), ...await readOpenedFile(path) };
82
+ }
83
+ const contents = await readOpenedFile(path);
84
+ const ticket = randomUUID();
85
+ if (tickets.size === MAX_OPEN_TICKETS)
86
+ tickets.delete(tickets.keys().next().value);
87
+ tickets.set(ticket, { workspaceId, root: canonicalRoot, path });
88
+ const name = basename(selected);
89
+ const targetName = basename(path);
90
+ return { path: input, name, ...(targetName !== name ? { targetName } : {}), ticket, ...contents };
91
+ },
92
+ async target(workspaceId, root, ticket) {
93
+ const entry = tickets.get(ticket);
94
+ if (!entry || entry.workspaceId !== workspaceId || entry.root !== await realpath(root)) {
95
+ throw new FilesError(404, "请重新打开这个外部文件。", "missing_open_file");
96
+ }
97
+ if (entry.path !== await realpath(entry.path)) {
98
+ throw new FilesError(404, "文件目标已改变,请重新打开。", "missing_open_file");
99
+ }
100
+ tickets.delete(ticket);
101
+ tickets.set(ticket, entry);
102
+ return entry.path;
103
+ },
104
+ };
105
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * THE TEXT OF A FAILURE.
3
+ *
4
+ * A server failure reaches the browser as a sentence, and the reader is entitled to know what
5
+ * actually went wrong. The trouble is that what was thrown is not always an `Error`: it can be a
6
+ * string, a plain object, a rejected promise with no reason at all. The old code answered
7
+ * `command failed` in those cases - the one sentence that says nothing about anything - so a real
8
+ * cause that had reached the server was replaced by a sentence with no cause in it.
9
+ *
10
+ * This module is the one place that decides what a thrown value turns into. It never invents
11
+ * text: an `Error` gives its message, a string gives itself, an object gives its `message` or its
12
+ * JSON, and a value that carries no information at all gives an EMPTY STRING - which the client
13
+ * reads as "no reason was given", and says so out loud instead of pretending.
14
+ */
15
+ /** The failure as a person should read it. Empty when the thrown value carries no information. */
16
+ export declare function describeThrown(error: unknown): string;
17
+ /** The failure with its stack, for the log file. */
18
+ export declare function describeThrownWithStack(error: unknown): string;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * THE TEXT OF A FAILURE.
3
+ *
4
+ * A server failure reaches the browser as a sentence, and the reader is entitled to know what
5
+ * actually went wrong. The trouble is that what was thrown is not always an `Error`: it can be a
6
+ * string, a plain object, a rejected promise with no reason at all. The old code answered
7
+ * `command failed` in those cases - the one sentence that says nothing about anything - so a real
8
+ * cause that had reached the server was replaced by a sentence with no cause in it.
9
+ *
10
+ * This module is the one place that decides what a thrown value turns into. It never invents
11
+ * text: an `Error` gives its message, a string gives itself, an object gives its `message` or its
12
+ * JSON, and a value that carries no information at all gives an EMPTY STRING - which the client
13
+ * reads as "no reason was given", and says so out loud instead of pretending.
14
+ */
15
+ /** The failure as a person should read it. Empty when the thrown value carries no information. */
16
+ export function describeThrown(error) {
17
+ if (error instanceof Error)
18
+ return error.message || error.name;
19
+ if (typeof error === "string")
20
+ return error;
21
+ if (error === null || error === undefined)
22
+ return "";
23
+ if (typeof error === "object") {
24
+ const message = error.message;
25
+ if (typeof message === "string" && message.trim())
26
+ return message;
27
+ try {
28
+ const text = JSON.stringify(error);
29
+ if (text && text !== "{}")
30
+ return text;
31
+ }
32
+ catch {
33
+ // Circular or otherwise unserializable: there is nothing better to say than "no reason".
34
+ }
35
+ return "";
36
+ }
37
+ return String(error);
38
+ }
39
+ /** The failure with its stack, for the log file. */
40
+ export function describeThrownWithStack(error) {
41
+ if (error instanceof Error && error.stack)
42
+ return error.stack;
43
+ return describeThrown(error);
44
+ }