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

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 +250 -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 +396 -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 +450 -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,603 @@
1
+ // `super_pi diagnose`: local runtime probe, or --url read-only network probe from THIS machine.
2
+ // Each report names what was observed. A loopback span cannot exonerate a remote transport, a
3
+ // process count cannot assign latency, and stored JSON is not compressed wire traffic.
4
+ import { spawn } from "node:child_process";
5
+ import { mkdtempSync, rmSync, existsSync, statSync, readFileSync } from "node:fs";
6
+ import { homedir, tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { pathToFileURL } from "node:url";
9
+ import { createRequire } from "node:module";
10
+ import { request as httpRequest } from "node:http";
11
+ import { request as httpsRequest } from "node:https";
12
+ import { hostname } from "node:os";
13
+ import { gunzipSync, inflateSync, brotliDecompressSync } from "node:zlib";
14
+
15
+ /** Compatibility requirement, not evidence of the cause of any measured delay. */
16
+ const PI_NODE_REQUIREMENT = "22.19.0";
17
+
18
+ export function parseDiagnoseArgs(args) {
19
+ const result = {};
20
+ for (let i = 0; i < args.length; i++) {
21
+ const arg = args[i];
22
+ if (/^\d+$/.test(arg) && result.turns === undefined) { result.turns = Number(arg); continue; }
23
+ const [name, ...inline] = arg.split("=");
24
+ const key = { "--url": "url", "--workspace": "workspaceId", "--conversation": "conversationId" }[name];
25
+ if (!key) throw new Error(`Unknown diagnose option: ${name}`);
26
+ const value = inline.length ? inline.join("=") : args[++i];
27
+ if (!value || value.startsWith("--")) throw new Error(`Missing value for ${name}`);
28
+ result[key] = value;
29
+ }
30
+ if (!result.url && (result.workspaceId || result.conversationId)) throw new Error("--workspace/--conversation require --url");
31
+ return result;
32
+ }
33
+
34
+ /** Raw encoded HTTP body bytes: fetch() transparently decompresses and cannot measure this. */
35
+ function measureHttp(url, headers, timeoutMs) {
36
+ return new Promise((resolve, reject) => {
37
+ const start = performance.now();
38
+ const req = (url.protocol === "https:" ? httpsRequest : httpRequest)(url, { headers, agent: false }, response => {
39
+ const headersMs = performance.now() - start;
40
+ const chunks = [];
41
+ let encodedBodyBytes = 0;
42
+ response.on("data", chunk => {
43
+ encodedBodyBytes += chunk.length;
44
+ if (encodedBodyBytes > 64 * 1024 * 1024) req.destroy(new Error("HTTP sample exceeds 64 MiB"));
45
+ else chunks.push(chunk);
46
+ });
47
+ response.on("error", reject);
48
+ response.on("end", () => {
49
+ try {
50
+ const completeMs = performance.now() - start;
51
+ const encoded = Buffer.concat(chunks);
52
+ const encoding = response.headers["content-encoding"] ?? "identity";
53
+ const opts = { maxOutputLength: 64 * 1024 * 1024 };
54
+ const body = encoding === "gzip" ? gunzipSync(encoded, opts) : encoding === "deflate" ? inflateSync(encoded, opts)
55
+ : encoding === "br" ? brotliDecompressSync(encoded, opts) : encoded;
56
+ if (response.statusCode !== 200) throw new Error(`HTTP ${response.statusCode}; redirects are not followed`);
57
+ resolve({ headersMs, bodyMs: completeMs - headersMs, completeMs, encodedBodyBytes, decodedBodyBytes: body.length, encoding, body: JSON.parse(body.toString()) });
58
+ } catch (error) { reject(error); }
59
+ });
60
+ });
61
+ const timer = setTimeout(() => req.destroy(new Error("HTTP probe deadline exceeded")), timeoutMs);
62
+ req.on("close", () => clearTimeout(timer));
63
+ req.on("error", reject);
64
+ req.end();
65
+ });
66
+ }
67
+
68
+ /** Read-only probe from THIS computer to an existing server. Never sends application commands. */
69
+ export async function diagnoseRemote({ url, workspaceId, conversationId, token = process.env.SUPER_PI_ACCESS_TOKEN, timeoutMs = 15000 } = {}) {
70
+ const target = new URL(url);
71
+ if (!["http:", "https:"].includes(target.protocol) || target.username || target.password || target.search || target.hash || target.pathname !== "/") {
72
+ throw new Error("--url must be an http(s) origin without credentials, path, query or fragment");
73
+ }
74
+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(target.hostname);
75
+ const result = { mode: "remote", origin: `${hostname()} (${process.platform})`, target: target.origin, loopback };
76
+ const headers = { "accept-encoding": "gzip", ...(token ? { authorization: `Bearer ${token}` } : {}) };
77
+ try {
78
+ const { body: health, ...measurement } = await measureHttp(new URL("/api/health", target), headers, timeoutMs);
79
+ if (health.service !== "super-pi") throw new Error("Target is not a Super Pi health endpoint");
80
+ result.health = measurement;
81
+ const { WebSocket } = await import("ws");
82
+ const endpoint = new URL("/ws", target);
83
+ endpoint.protocol = target.protocol === "https:" ? "wss:" : "ws:";
84
+ endpoint.searchParams.set("state", "focused");
85
+ if (conversationId) endpoint.searchParams.set("conversationId", conversationId);
86
+ result.websocket = await new Promise((resolve, reject) => {
87
+ const started = performance.now();
88
+ const socket = new WebSocket(endpoint, { headers, handshakeTimeout: timeoutMs, maxPayload: 64 * 1024 * 1024 });
89
+ const sample = { decodedMessageBytes: 0, messages: 0, pingRttMs: [] };
90
+ let first = false, pingStart;
91
+ const timer = setTimeout(() => fail(new Error("WebSocket probe deadline exceeded")), timeoutMs);
92
+ function fail(error) { clearTimeout(timer); socket.terminate(); reject(error); }
93
+ socket.on("error", fail);
94
+ socket.once("close", () => { if (sample.pingRttMs.length !== 3) fail(new Error("WebSocket closed before probe completed")); });
95
+ socket.on("open", () => { sample.upgradeMs = performance.now() - started; sample.compression = socket.extensions || "none"; });
96
+ socket.on("message", raw => {
97
+ sample.messages++;
98
+ sample.decodedMessageBytes += raw.length;
99
+ try {
100
+ const event = JSON.parse(raw.toString());
101
+ if (!first && event.type === "state") {
102
+ first = true;
103
+ sample.firstStateMs = performance.now() - started;
104
+ sample.stateJsonBytes = raw.length;
105
+ pingStart = performance.now(); socket.ping("diagnose-0");
106
+ }
107
+ } catch (error) { fail(error); }
108
+ });
109
+ socket.on("pong", raw => {
110
+ if (raw.toString() !== `diagnose-${sample.pingRttMs.length}`) return;
111
+ sample.pingRttMs.push(performance.now() - pingStart);
112
+ if (sample.pingRttMs.length < 3) { pingStart = performance.now(); socket.ping(`diagnose-${sample.pingRttMs.length}`); return; }
113
+ // Includes HTTP upgrade, WS headers, catalogues and pongs, before closing. This is NOT an
114
+ // individual state frame size, nor Ethernet/TCP/TLS overhead. Label the counter honestly.
115
+ sample.socketInputBytes = socket._socket.bytesRead;
116
+ sample.sampleMs = performance.now() - started;
117
+ clearTimeout(timer); socket.terminate(); resolve(sample);
118
+ });
119
+ });
120
+ if (workspaceId) {
121
+ const indexUrl = new URL("/api/files/index", target);
122
+ indexUrl.searchParams.set("workspaceId", workspaceId);
123
+ const { body: _index, ...index } = await measureHttp(indexUrl, headers, timeoutMs);
124
+ result.fileIndex = index;
125
+ }
126
+ } catch (error) { result.error = error instanceof Error ? error.message : String(error); }
127
+ return result;
128
+ }
129
+
130
+ function renderRemoteReport(result) {
131
+ const lines = ["Super Pi 远程链路诊断(只读)", ` 探针位置:${result.origin}`, ` 目标:${result.target}`,
132
+ ` 路径:${result.loopback ? "回环地址,未覆盖其他电脑的访问路径" : "此电脑到目标;请在发生问题的客户端电脑执行"}`];
133
+ const http = (name, sample) => {
134
+ if (!sample) return;
135
+ lines.push(` ${name}: 收到响应头 ${sample.headersMs.toFixed(1)}ms,响应体传输 ${sample.bodyMs.toFixed(1)}ms,总计 ${sample.completeMs.toFixed(1)}ms`);
136
+ lines.push(` 编码后响应体 ${sample.encodedBodyBytes} B,解码后 ${sample.decodedBodyBytes} B,编码 ${sample.encoding}`);
137
+ };
138
+ http("health", result.health);
139
+ if (result.websocket) {
140
+ const ws = result.websocket;
141
+ lines.push(` WS: upgrade ${ws.upgradeMs.toFixed(1)}ms,首个 focused state ${ws.firstStateMs.toFixed(1)}ms,state JSON ${ws.stateJsonBytes} B`);
142
+ lines.push(` socket 输入 ${ws.socketInputBytes} B,解码后消息合计 ${ws.decodedMessageBytes} B,压缩 ${ws.compression}`);
143
+ lines.push(` Ping RTT: ${ws.pingRttMs.map(n => n.toFixed(1) + "ms").join(", ")}`);
144
+ }
145
+ http("文件索引(显式指定 workspace)", result.fileIndex);
146
+ if (result.error) lines.push(` 失败:${result.error}`);
147
+ lines.push(" 范围:响应头等待包含网络与服务端处理,不能当作纯服务端耗时。socket 输入含 upgrade/WS 帧,未计 IP/TCP/TLS 开销。");
148
+ lines.push(" 未测:浏览器点击/解析/绘制、创建/停止/撤回、模型调用;未创建会话或发送业务命令。小样本不能推算链路带宽。");
149
+ return lines.join("\n");
150
+ }
151
+
152
+ /**
153
+ * Compares two dotted versions.
154
+ *
155
+ * `localeCompare` would do this lexically and get "22.9.0" > "22.19.0" wrong - 9 sorts after 19 as
156
+ * characters - and a person whose Node is 22.9 would be told they satisfy a requirement they do not.
157
+ */
158
+ function atLeast(actual, required) {
159
+ const left = String(actual).split(".").map((part) => Number.parseInt(part, 10) || 0);
160
+ const right = String(required).split(".").map((part) => Number.parseInt(part, 10) || 0);
161
+ for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
162
+ const difference = (left[index] ?? 0) - (right[index] ?? 0);
163
+ if (difference !== 0) return difference >= 0;
164
+ }
165
+ return true;
166
+ }
167
+
168
+ /**
169
+ * Read-only storage context. A fresh throwaway server cannot reveal real history size. Rebuild
170
+ * logical state via the repository layout, but never label that JSON as actual browser traffic:
171
+ * focused projection, per-message compression and transport overhead produce different sizes.
172
+ */
173
+ function measureRealState(dataDir) {
174
+ const result = { path: "", bytes: 0, fileBytes: 0, conversations: 0, messages: 0, fullWriteMs: undefined };
175
+ for (const name of ["state.sqlite", "state.json"]) {
176
+ const path = join(dataDir, name);
177
+ if (!existsSync(path)) continue;
178
+ result.path = path;
179
+ try {
180
+ result.fileBytes = statSync(path).size;
181
+ if (name === "state.json") {
182
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
183
+ result.conversations = parsed.conversations?.length ?? 0;
184
+ result.messages = (parsed.conversations ?? []).reduce((sum, c) => sum + (c.messages?.length ?? 0), 0);
185
+ // Logical storage state, not a focused projection or compressed network measurement.
186
+ result.bytes = Buffer.byteLength(JSON.stringify(parsed), "utf8");
187
+ } else {
188
+ // THE SQLITE STATE, REBUILT AND MEASURED. The repository's own loader is the authority on what
189
+ // the state IS, so the report does not guess at it: the database is opened READ-ONLY, the
190
+ // overlays are folded onto the base snapshot the way `load()` folds them, and the result is
191
+ // measured as JSON. The browser's scoped projection and compression are separate measurements.
192
+ const measured = measureSqliteState(path);
193
+ if (measured.bytes > 0) {
194
+ result.bytes = measured.bytes;
195
+ result.conversations = measured.conversations;
196
+ result.messages = measured.messages;
197
+ }
198
+ }
199
+ } catch { /* unreadable is not a fact worth reporting */ }
200
+ break;
201
+ }
202
+ return result;
203
+ }
204
+
205
+ /**
206
+ * The size of the state a SQLite store holds, measured as the JSON a broadcast would carry.
207
+ *
208
+ * READ-ONLY, and it opens its OWN connection rather than the server's: a report must not disturb the
209
+ * session someone is in the middle of, and a second read-only connection sees a consistent snapshot
210
+ * without taking any lock the server needs.
211
+ */
212
+ function measureSqliteState(path) {
213
+ let db;
214
+ const empty = { bytes: 0, conversations: 0, messages: 0 };
215
+ try {
216
+ const require = createRequire(import.meta.url);
217
+ const { DatabaseSync } = require("node:sqlite");
218
+ db = new DatabaseSync(path, { readOnly: true });
219
+ const row = db.prepare("SELECT json FROM state WHERE id=1").get();
220
+ if (!row) return empty;
221
+ const state = JSON.parse(String(row.json));
222
+ if (!Array.isArray(state.conversations)) state.conversations = [];
223
+ // THE OVERLAYS, folded the way `load()` folds them: a conversation's metadata replaces its fields
224
+ // except its messages, and its messages are the union of the base array and the overlay rows - with
225
+ // the authoritative order rows winning when they are there.
226
+ const metadata = db.prepare("SELECT conversation,json FROM metadata").all();
227
+ const overrides = db.prepare("SELECT conversation,id,json FROM messages").all();
228
+ const ordered = db.prepare("SELECT conversation,id,position,json FROM message_order").all();
229
+ const byConversation = new Map();
230
+ for (const item of overrides) {
231
+ const list = byConversation.get(String(item.conversation)) ?? new Map();
232
+ list.set(String(item.id), JSON.parse(String(item.json)));
233
+ byConversation.set(String(item.conversation), list);
234
+ }
235
+ const orderByConversation = new Map();
236
+ for (const item of ordered) {
237
+ const list = orderByConversation.get(String(item.conversation)) ?? [];
238
+ list.push({ position: Number(item.position), message: JSON.parse(String(item.json)) });
239
+ orderByConversation.set(String(item.conversation), list);
240
+ }
241
+ for (const item of metadata) {
242
+ const conversation = state.conversations.find((entry) => entry.id === String(item.conversation));
243
+ if (!conversation) continue;
244
+ const messages = conversation.messages;
245
+ for (const key of Object.keys(conversation)) Reflect.deleteProperty(conversation, key);
246
+ Object.assign(conversation, JSON.parse(String(item.json)), { messages });
247
+ }
248
+ for (const conversation of state.conversations) {
249
+ const map = byConversation.get(conversation.id) ?? new Map();
250
+ const order = orderByConversation.get(conversation.id) ?? [];
251
+ if (order.length) {
252
+ conversation.messages = order.sort((a, b) => a.position - b.position).map((entry) => entry.message);
253
+ } else if (Array.isArray(conversation.messages)) {
254
+ conversation.messages = conversation.messages.map((message) => map.get(message.id) ?? message);
255
+ } else {
256
+ conversation.messages = [];
257
+ }
258
+ }
259
+ return {
260
+ bytes: Buffer.byteLength(JSON.stringify(state), "utf8"),
261
+ conversations: state.conversations.length,
262
+ messages: state.conversations.reduce((sum, conversation) => sum + (conversation.messages?.length ?? 0), 0),
263
+ };
264
+ } catch {
265
+ return empty;
266
+ } finally {
267
+ try { db?.close(); } catch { /* already closed */ }
268
+ }
269
+ }
270
+
271
+ /**
272
+ * Runs the diagnosis against a throwaway server and returns what it measured.
273
+ *
274
+ * A THROWAWAY SERVER, not the running one: it starts its own on a private port with its own data
275
+ * directory, so this never disturbs a session someone is in the middle of, and never writes into
276
+ * their real conversations. It also means the numbers describe a COLD machine's first conversation,
277
+ * which is the case being complained about.
278
+ */
279
+ export async function diagnose({ repositoryRoot, turns = 2, onProgress = () => {} } = {}) {
280
+ const dataDir = mkdtempSync(join(tmpdir(), "super-pi-diagnose-"));
281
+ const port = 35000 + Math.floor(Math.random() * 4000);
282
+ const server = spawn(process.execPath, [join(repositoryRoot, "dist/server/index.js")], {
283
+ cwd: repositoryRoot,
284
+ env: {
285
+ ...process.env,
286
+ SUPER_PI_PORT: String(port),
287
+ SUPER_PI_HOST: "127.0.0.1",
288
+ SUPER_PI_RUNTIME: "pi",
289
+ SUPER_PI_DATA_DIR: dataDir,
290
+ SUPER_PI_PERSISTENCE: "json",
291
+ // The latency trace is what turns "it was slow" into "this step was slow".
292
+ SUPER_PI_TRACE_LATENCY: "1",
293
+ },
294
+ stdio: ["ignore", "pipe", "pipe"],
295
+ });
296
+ let log = "";
297
+ server.stdout.on("data", (chunk) => { log += chunk.toString(); });
298
+ server.stderr.on("data", (chunk) => { log += chunk.toString(); });
299
+ const stop = () => { try { server.kill(); } catch { /* already gone */ } };
300
+
301
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
302
+ const realDataDir = process.env.SUPER_PI_DATA_DIR ?? join(homedir(), ".super-pi");
303
+ const result = {
304
+ realState: measureRealState(realDataDir),
305
+ node: process.versions.node,
306
+ nodeOk: atLeast(process.versions.node, PI_NODE_REQUIREMENT),
307
+ required: PI_NODE_REQUIREMENT,
308
+ };
309
+ try {
310
+ onProgress("starting a throwaway server...");
311
+ const bootStart = Date.now();
312
+ let healthy = false;
313
+ for (let attempt = 0; attempt < 600; attempt += 1) {
314
+ try { if ((await fetch(`http://127.0.0.1:${port}/api/health`)).ok) { healthy = true; break; } } catch { /* not up yet */ }
315
+ await sleep(50);
316
+ }
317
+ result.bootMs = Date.now() - bootStart;
318
+ if (!healthy) {
319
+ result.error = "the server did not become healthy";
320
+ result.log = log.slice(-2000);
321
+ return result;
322
+ }
323
+
324
+ const { WebSocket } = await import("ws");
325
+ const socket = new WebSocket(`ws://127.0.0.1:${port}/ws`);
326
+ await new Promise((resolve, reject) => { socket.once("open", resolve); socket.once("error", reject); });
327
+ const events = [];
328
+ socket.on("message", (raw) => { try { events.push(JSON.parse(raw.toString())); } catch { /* not json */ } });
329
+ const send = (command) => socket.send(JSON.stringify(command));
330
+ const waitFor = async (predicate, label, timeoutMs = 240000) => {
331
+ const deadline = Date.now() + timeoutMs;
332
+ while (Date.now() < deadline) {
333
+ const hit = events.find(predicate);
334
+ if (hit) return hit;
335
+ await sleep(15);
336
+ }
337
+ throw new Error(`timed out waiting for ${label}`);
338
+ };
339
+
340
+ // A fresh store starts with no workspace, so the diagnosis creates the one it measures against -
341
+ // before any measured span, so workspace setup never lands inside a number.
342
+ send({ type: "workspace.create", name: "diagnose", path: process.cwd() });
343
+ const workspaceId = (await waitFor((e) => e.type === "state" && e.state.workspaces.some((w) => w.name === "diagnose"), "the diagnose workspace")).state.workspaces.find((w) => w.name === "diagnose").id;
344
+
345
+ onProgress("creating a conversation...");
346
+ send({ type: "conversation.create", workspaceId });
347
+ await waitFor((e) => e.type === "state" && e.state.conversations.length > 0, "a conversation");
348
+ const conversation = events.filter((e) => e.type === "state").at(-1).state.conversations[0];
349
+
350
+ // Span 1: the picker.
351
+ const pickerStart = Date.now();
352
+ send({ type: "catalog.fetch", conversationId: conversation.id });
353
+ const catalog = await waitFor((e) => e.type === "model.catalog", "the model catalog");
354
+ result.pickerMs = Date.now() - pickerStart;
355
+ result.catalogSource = catalog.catalog?.source ?? catalog.source ?? "unknown";
356
+ result.models = (catalog.catalog?.models ?? catalog.models ?? []).length;
357
+
358
+ // Span 1b: THE PICKER AFTER A WORKSPACE DEFAULT IS SET.
359
+ //
360
+ // THIS IS THE PATH THE FIRST MEASUREMENT MISSED, and it is the one most people are actually on.
361
+ // `createConversation` copies the workspace's default model onto the new conversation, and it
362
+ // VALIDATES that default against the catalog first - so creating a conversation with a default
363
+ // model READS THE CATALOG, and a picker opened afterwards asks for the LEVELS of that model, which
364
+ // is a different catalog key. A measurement that never sets a default model never sees any of it.
365
+ //
366
+ // The report says which path it measured, because a number for a path nobody is on is worse than
367
+ // no number at all.
368
+ const defaultModel = (catalog.catalog?.models ?? catalog.models ?? []).find((m) => m.modelId)
369
+ ?? (catalog.catalog?.defaultModel ?? catalog.defaultModel);
370
+ if (defaultModel) {
371
+ onProgress("setting a workspace default model, then creating a conversation...");
372
+ send({
373
+ type: "workspace.settings",
374
+ workspaceId,
375
+ model: { provider: defaultModel.provider, modelId: defaultModel.modelId },
376
+ thinkingLevel: null,
377
+ });
378
+ await sleep(400);
379
+ const withDefaultStart = Date.now();
380
+ send({ type: "conversation.create", workspaceId });
381
+ const withDefault = await waitFor((e) => e.type === "state"
382
+ && e.state.conversations.length >= 2, "a conversation with the workspace default");
383
+ result.conversationWithDefaultMs = Date.now() - withDefaultStart;
384
+ const withDefaultConversation = events.filter((e) => e.type === "state").at(-1).state.conversations[0];
385
+ // And the picker for THAT conversation, which is the one a person actually opens.
386
+ const defaultPickerStart = Date.now();
387
+ send({ type: "catalog.fetch", conversationId: withDefaultConversation.id });
388
+ // The conversation id is a SIBLING of the catalog, not inside it - `broadcastCatalog` sends
389
+ // `{ type, catalog, conversationId }` - and reading it from the wrong place times out on a
390
+ // catalog that has already arrived.
391
+ await waitFor((e) => e.type === "model.catalog" && e.conversationId === withDefaultConversation.id,
392
+ "the catalog for the conversation with a default model");
393
+ result.pickerWithDefaultMs = Date.now() - defaultPickerStart;
394
+ }
395
+
396
+ // Spans 2 and 3, per turn.
397
+ result.turns = [];
398
+ for (let turn = 1; turn <= turns; turn += 1) {
399
+ onProgress(`sending turn ${turn} of ${turns}...`);
400
+ const mark = events.length;
401
+ const logMark = log.length;
402
+ const sent = Date.now();
403
+ send({ type: "message.send", conversationId: conversation.id, content: `第${turn}问:请简短回答。` });
404
+ await waitFor((e, i) => i >= mark && e.type === "state"
405
+ && e.state.conversations.find((c) => c.id === conversation.id)?.status === "waiting", `turn ${turn} to report waiting`);
406
+ const waiting = Date.now();
407
+ await waitFor((e, i) => i >= mark && e.type === "message.delta" && e.conversationId === conversation.id, `turn ${turn}'s first character`);
408
+ const text = Date.now();
409
+ // Let the turn finish so the next one is a new turn rather than a queued one.
410
+ while (Date.now() < text + 120000) {
411
+ const done = events.slice(mark).some((e) => e.type === "state"
412
+ && e.state.conversations.find((c) => c.id === conversation.id)?.status === "completed");
413
+ if (done) break;
414
+ await sleep(30);
415
+ }
416
+ await sleep(250);
417
+ const added = log.slice(logMark);
418
+ const promptSize = /systemPrompt=(\d+)B/.exec(added)?.[1];
419
+ if (promptSize) result.systemPromptBytes = Number(promptSize);
420
+ result.turns.push({
421
+ turn,
422
+ toWaitingMs: waiting - sent,
423
+ toTextMs: text - sent,
424
+ modelMs: text - waiting,
425
+ spawned: (added.match(/phase=pi\.spawned/g) ?? []).length,
426
+ built: (added.match(/phase=session\.build\.begin/g) ?? []).length,
427
+ reused: (added.match(/phase=session\.reused/g) ?? []).length,
428
+ });
429
+ }
430
+ // Span 4: THE INTERRUPT.
431
+ //
432
+ // The second thing people report is "打断并回答 → 开始回答还要好十秒", and it is a DIFFERENT
433
+ // chain from sending a message: it waits for the running turn to unwind, waits for its slot, and
434
+ // only then asks the model. Those first two waits are Super Pi's, and they are the ones that can
435
+ // be slow; the model's share is the same as any other turn.
436
+ //
437
+ // So it is measured as its own span, with a tool running so there is something to interrupt.
438
+ onProgress("measuring the interrupt...");
439
+ const interruptMark = events.length;
440
+ const interruptLogMark = log.length;
441
+ send({
442
+ type: "message.send",
443
+ conversationId: conversation.id,
444
+ content: '用 bash 运行:node -e "setTimeout(()=>{},20000)"。等它跑完再回复。',
445
+ });
446
+ let toolStarted = false;
447
+ const toolDeadline = Date.now() + 60000;
448
+ while (!toolStarted && Date.now() < toolDeadline) {
449
+ toolStarted = events.slice(interruptMark).some((e) => e.type === "message.tools");
450
+ if (!toolStarted) await sleep(30);
451
+ }
452
+ if (toolStarted) {
453
+ // Queue the message that the interrupt will answer.
454
+ send({ type: "message.send", conversationId: conversation.id, content: "被打断的那条:只回答「第二」两个字。" });
455
+ let queued = null;
456
+ const queueDeadline = Date.now() + 60000;
457
+ while (!queued && Date.now() < queueDeadline) {
458
+ queued = events.filter((e) => e.type === "state").at(-1)?.state?.conversations
459
+ ?.find((c) => c.id === conversation.id)?.messages
460
+ ?.find((m) => m.content?.includes("被打断的那条") && m.delivery === "waiting");
461
+ if (!queued) await sleep(30);
462
+ }
463
+ if (queued) {
464
+ await sleep(800);
465
+ const clicked = Date.now();
466
+ send({ type: "message.interrupt", conversationId: conversation.id, messageId: queued.id });
467
+ let interruptWaiting = 0;
468
+ try {
469
+ await waitFor((e, i) => i >= interruptMark && e.type === "state"
470
+ && e.state.conversations.find((c) => c.id === conversation.id)?.status === "waiting"
471
+ && Date.now() > clicked, "the interrupted turn to report waiting", 60000);
472
+ interruptWaiting = Date.now() - clicked;
473
+ await waitFor((e, i) => i >= interruptMark && e.type === "message.delta" && e.conversationId === conversation.id
474
+ && Date.now() > clicked + 50, "the interrupted turn's first character", 180000);
475
+ } catch { /* reported as not measured below */ }
476
+ const interruptText = Date.now() - clicked;
477
+ const interruptLog = log.slice(interruptLogMark);
478
+ // The whole trace of the interrupt, in order. It is kept because the interrupt is the one path
479
+ // whose cost has turned out to be surprising, and a number without the phases around it cannot
480
+ // say which phase the number belongs to.
481
+ result.interruptTrace = interruptLog
482
+ .split("\n")
483
+ .filter((line) => line.includes("[super-pi latency]"))
484
+ .map((line) => line.replace(/.*\[super-pi latency\] /, "").trim())
485
+ .slice(0, 24);
486
+ result.interrupt = {
487
+ toWaitingMs: interruptWaiting || undefined,
488
+ toTextMs: interruptText,
489
+ modelMs: interruptText - (interruptWaiting || 0),
490
+ spawned: (interruptLog.match(/phase=pi\.spawned/g) ?? []).length,
491
+ built: (interruptLog.match(/phase=session\.build\.begin/g) ?? []).length,
492
+ reused: (interruptLog.match(/phase=session\.reused/g) ?? []).length,
493
+ };
494
+ }
495
+ }
496
+
497
+ socket.close();
498
+ } catch (error) {
499
+ result.error = error instanceof Error ? error.message : String(error);
500
+ result.log = log.slice(-2000);
501
+ } finally {
502
+ stop();
503
+ await sleep(200);
504
+ rmSync(dataDir, { recursive: true, force: true });
505
+ }
506
+ return result;
507
+ }
508
+
509
+ /** Renders a diagnosis as the report a person reads. */
510
+ export function renderReport(result) {
511
+ if (result.mode === "remote") return renderRemoteReport(result);
512
+ const lines = [];
513
+ const ms = (value) => (typeof value === "number" ? `${String(value).padStart(6)}ms` : " ?");
514
+
515
+ lines.push(`Super Pi 延迟诊断 — ${new Date().toISOString()}`);
516
+ lines.push(" 测量范围:本机临时 server + 回环连接;未测用户电脑到云服务器的网络,也未测浏览器点击/绘制。");
517
+ lines.push(" 远程访问请在客户端电脑运行:super_pi diagnose --url http://SERVER:3080");
518
+ lines.push("");
519
+ lines.push(` Node ${result.node} (Pi 要求 >= ${result.required}:${result.nodeOk ? "满足" : "过低"})`);
520
+ lines.push(` server 就绪耗时 ${ms(result.bootMs)}`);
521
+
522
+ if (result.error) {
523
+ lines.push("");
524
+ lines.push(` 失败:${result.error}`);
525
+ if (result.log) lines.push(result.log.split("\n").map((l) => ` | ${l}`).join("\n"));
526
+ return lines.join("\n");
527
+ }
528
+
529
+ lines.push("");
530
+ lines.push(" 每一段耗时 耗时 归属");
531
+ lines.push(` 1. picker 有数据 ${ms(result.pickerMs)} Super Pi (catalog 读取)`);
532
+ if (typeof result.conversationWithDefaultMs === "number") {
533
+ lines.push(` 1b. 建会话(工作区有默认模型) ${ms(result.conversationWithDefaultMs)} Super Pi (建会话要校验默认模型,会再读一次 catalog)`);
534
+ lines.push(` 1c. 该会话的 picker ${ms(result.pickerWithDefaultMs)} Super Pi (带默认模型时读的是另一份 catalog)`);
535
+ } else {
536
+ lines.push(" 1b/1c. 未测:这次没有可用的模型来设工作区默认模型");
537
+ }
538
+ for (const turn of result.turns ?? []) {
539
+ lines.push(` 第${turn.turn}轮 发送 -> 等待中 ${ms(turn.toWaitingMs)} Super Pi (建会话 + 首个 prompt)`);
540
+ lines.push(` 第${turn.turn}轮 等待中 -> 出字 ${ms(turn.modelMs)} 首字等待 (包含 runtime、供应商及传输,未单独归因)`);
541
+ }
542
+ if (result.interrupt) {
543
+ if (Array.isArray(result.interruptTrace) && result.interruptTrace.length) {
544
+ lines.push(" 打断时的完整阶段(按顺序):");
545
+ for (const entry of result.interruptTrace) lines.push(` ${entry}`);
546
+ }
547
+
548
+ lines.push("");
549
+ lines.push(" 打断(点「打断并回答」之后):");
550
+ lines.push(` 点击 -> 新一轮报等待中 ${ms(result.interrupt.toWaitingMs)} Super Pi (等旧轮退完 + 等槽位)`);
551
+ lines.push(` 点击 -> 出字 ${ms(result.interrupt.toTextMs)} 整条链`);
552
+ lines.push(` 其中首字等待 ${ms(result.interrupt.modelMs)} runtime/供应商/传输,未单独归因`);
553
+ lines.push(` 打断后启动的 Pi 进程数: ${result.interrupt.spawned}`);
554
+ } else {
555
+ lines.push("");
556
+ lines.push(" 打断:未测(需要一次正在跑工具的轮次)");
557
+ }
558
+ lines.push("");
559
+ lines.push(` catalog: ${result.catalogSource},${result.models} 个模型`);
560
+
561
+ const spawned = (result.turns ?? []).reduce((sum, t) => sum + t.spawned, 0);
562
+ const built = (result.turns ?? []).reduce((sum, t) => sum + t.built, 0);
563
+ const reused = (result.turns ?? []).reduce((sum, t) => sum + t.reused, 0);
564
+ lines.push("");
565
+ lines.push(" 结构计数 —— 快机器和慢机器上一样的那部分:");
566
+ lines.push(` 启动的 Pi 进程数: ${spawned}`);
567
+ lines.push(` 建立的会话数: ${built}`);
568
+ lines.push(` 复用的会话数: ${reused}`);
569
+
570
+ if (result.systemPromptBytes) {
571
+ lines.push("");
572
+ lines.push(` 发给模型的系统提示:${(result.systemPromptBytes / 1024).toFixed(1)}KB`);
573
+ lines.push(" 这是逻辑提示体积;供应商协议、压缩、缓存和网络吞吐未在此测量,不能据此换算首字延迟。");
574
+ }
575
+
576
+ const real = result.realState;
577
+ if (real && real.path) {
578
+ lines.push("");
579
+ lines.push(" 你真实的 state(上面那些数字是在一个全新的空目录上量的,看不到它):");
580
+ lines.push(` ${real.path}`);
581
+ const megabytes = real.bytes ? (real.bytes / 1024 / 1024).toFixed(2) : "未测";
582
+ const shape = real.conversations ? `,${real.conversations} 个会话,${real.messages} 条消息` : "";
583
+ lines.push(` 存储状态重建后的 JSON:${real.bytes ? megabytes + "MB" : megabytes}${shape}(不是浏览器传输量)`);
584
+ if (real.fileBytes && real.fileBytes !== real.bytes) {
585
+ lines.push(` 数据库文件本身:${(real.fileBytes / 1024 / 1024).toFixed(2)}MB`);
586
+ lines.push(" (数据库含基础快照和增量表;磁盘体积、重建 JSON、focused JSON 与压缩传输量必须分开。)");
587
+ }
588
+ if (real.bytes > 1024 * 1024) {
589
+ lines.push(" 全量状态很大时,应检查克隆/持久化成本;现代 focused 客户端只收摘要与选中详情,不能据全库大小断言远程耗时。");
590
+ }
591
+ }
592
+
593
+
594
+ lines.push("");
595
+ if (!result.nodeOk) {
596
+ lines.push(` Node 版本低于 Pi 的要求(>= ${result.required})。请升级 Node 以满足兼容要求;版本不匹配本身不能证明延迟根因。`);
597
+ lines.push("");
598
+ }
599
+ lines.push(" 怎么看这份报告:");
600
+ lines.push(" - 进程数与会话构建/复用数说明执行结构,零进程不代表零开销或已经复用。");
601
+ lines.push(" - 各阶段是本机探针观察值;未结合跨机器传输和浏览器 trace 时,不能排除 Super Pi 或网络。");
602
+ return lines.join("\n");
603
+ }