@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,640 @@
1
+ import { isBrowserAuthorized } from "./browser-access.js";
2
+ import { WebSocket, WebSocketServer } from "ws";
3
+ import { isAuthorized, isLoopbackAddress } from "./http-server.js";
4
+ import { describeThrown, describeThrownWithStack } from "./failure-text.js";
5
+ /**
6
+ * A WebSocket is a live transport, not an unbounded queue. `ws.send()` only
7
+ * copies bytes into the socket's userland buffer; a browser that is frozen or
8
+ * a network peer that has disappeared can therefore make the buffer grow
9
+ * without throwing. Once this threshold is crossed we drop that connection
10
+ * and let the normal close path clean up its resources.
11
+ *
12
+ * AND YET DROPPING IT IS THE WRONG ANSWER FOR A BUSY SERVER. The threshold was
13
+ * written for a peer that has gone away - a frozen tab, a pulled cable. A server
14
+ * that is merely DELIVERING TOO MUCH hits the same number: a sub-agent that
15
+ * streams text emits one `subagent.event` per delta, each of which asks for a
16
+ * full state broadcast, and a browser that cannot parse frames as fast as they
17
+ * arrive lets the buffer grow past the threshold while it is perfectly alive.
18
+ * The browser then reports code 1006 and reconnects, only to be dropped again -
19
+ * "连接中 / 断连 / 连接中" forever - and the user's work is interrupted rather
20
+ * than slowed.
21
+ *
22
+ * So a frame that does not fit is DROPPED, not the connection: the next frame
23
+ * carries the same state, and a browser that is behind will catch up on the next
24
+ * one instead of being disconnected and losing its place. The connection is
25
+ * only terminated when the socket itself is gone (readyState is not OPEN).
26
+ */
27
+ export const MAX_WS_BUFFERED_BYTES = 8 * 1024 * 1024;
28
+ /** Maximum size of one inbound WebSocket message. Attachments are uploaded
29
+ * over HTTP and commands contain references, so multi-megabyte WS frames are
30
+ * almost certainly malformed or abusive. */
31
+ export const MAX_WS_PAYLOAD_BYTES = 4 * 1024 * 1024;
32
+ /**
33
+ * Send one frame without allowing a race with close/error to escape as an
34
+ * uncaught exception. The `ws` package can throw synchronously after the
35
+ * readyState check (for example when a close happens between the two calls),
36
+ * and an unhandled `error` event can otherwise terminate the Node process.
37
+ */
38
+ export function safeSend(socket, payload) {
39
+ if (socket.readyState !== WebSocket.OPEN)
40
+ return false;
41
+ const bufferedAmount = Number(socket.bufferedAmount ?? 0);
42
+ if (Number.isFinite(bufferedAmount) && bufferedAmount > MAX_WS_BUFFERED_BYTES) {
43
+ // DROP THE FRAME, KEEP THE CONNECTION. A peer that is merely behind is not
44
+ // a peer that is gone: the next broadcast carries the same state, so the
45
+ // browser catches up instead of being disconnected and losing its place.
46
+ // Terminating here is what produced "连接中 / 断连 / 连接中" forever on a
47
+ // server that was delivering sub-agent output faster than the browser could
48
+ // parse it - and the browser's own code 1006 was only the symptom.
49
+ return false;
50
+ }
51
+ try {
52
+ socket.send(payload);
53
+ return true;
54
+ }
55
+ catch (error) {
56
+ console.warn(`Super Pi: WebSocket send failed: ${error instanceof Error ? error.message : String(error)}`);
57
+ try {
58
+ socket.terminate();
59
+ }
60
+ catch { /* close races are already being cleaned up */ }
61
+ return false;
62
+ }
63
+ }
64
+ /**
65
+ * Concrete implementation of EventBroadcaster delivering server events
66
+ * across active WebSocket connections.
67
+ */
68
+ export class WsBroadcaster {
69
+ getState;
70
+ replay;
71
+ sockets = new Set();
72
+ // Undefined preserves the original full-state protocol. An object, including {}, opts into
73
+ // conversation-focused snapshots from the very first frame of the connection.
74
+ scopes = new Map();
75
+ fileIndexScopes = new Map();
76
+ coalescedSockets = new Set();
77
+ pendingStreams = new Map();
78
+ pendingRuntimeReplays = new Map();
79
+ /**
80
+ * DIAGNOSTIC ONLY - sends every requested state frame immediately instead of merging them.
81
+ *
82
+ * The legacy flood switch (`SUPER_PI_LEGACY_SUBAGENT_FLOOD=1`) restores the pre-fix WIRING: one
83
+ * full state broadcast per sub-agent event. But the 150ms merge window would still fold those
84
+ * broadcasts into one frame, so the "before" measurement would not actually be "before" - it
85
+ * would show a flood that the fixed server also survives, and the A/B comparison would prove
86
+ * nothing. This flag removes the window as well, so the probe can reproduce the real pre-fix
87
+ * wire shape: one frame per request, sent at once.
88
+ *
89
+ * Never set outside a probe or a regression test that is asserting the old behaviour.
90
+ */
91
+ sendStateImmediately = process.env.SUPER_PI_LEGACY_SUBAGENT_FLOOD === "1";
92
+ constructor(getState, replay) {
93
+ this.getState = getState;
94
+ this.replay = replay;
95
+ }
96
+ register(socket, scope) {
97
+ this.sockets.add(socket);
98
+ this.scopes.set(socket, scope);
99
+ }
100
+ unregister(socket) {
101
+ this.coalescedSockets.delete(socket);
102
+ const pending = this.pendingStreams.get(socket);
103
+ if (pending)
104
+ clearTimeout(pending.timer);
105
+ this.pendingStreams.delete(socket);
106
+ this.clearRuntimeReplay(socket);
107
+ this.scopes.delete(socket);
108
+ this.fileIndexScopes.delete(socket);
109
+ this.sockets.delete(socket);
110
+ }
111
+ subscribe(socket, conversationId) {
112
+ // Finish the old transcript before replacing it. A later delta then belongs to the new scope,
113
+ // and the authoritative snapshot reconstructs anything not streamed while it was unselected.
114
+ this.flushStreaming(socket);
115
+ this.scopes.set(socket, conversationId ? { conversationId } : {});
116
+ this.sendState(socket);
117
+ }
118
+ sendState(socket) {
119
+ if (socket.readyState !== WebSocket.OPEN)
120
+ return;
121
+ if (socket.bufferedAmount > MAX_WS_BUFFERED_BYTES) {
122
+ this.scheduleRuntimeReplay(socket);
123
+ return;
124
+ }
125
+ this.flushStreaming(socket);
126
+ const scope = this.scopes.get(socket);
127
+ const state = this.getState(scope);
128
+ this.clearRuntimeReplay(socket);
129
+ // Replay compact logs first so a large transcript cannot starve them on every retry.
130
+ for (const event of this.replay?.(state, scope) ?? []) {
131
+ if (!safeSend(socket, JSON.stringify(event)))
132
+ this.scheduleRuntimeReplay(socket);
133
+ }
134
+ if (!safeSend(socket, JSON.stringify({ type: "state", state }))) {
135
+ this.scheduleRuntimeReplay(socket);
136
+ }
137
+ }
138
+ scheduleRuntimeReplay(socket) {
139
+ if (this.pendingRuntimeReplays.has(socket) || socket.readyState !== WebSocket.OPEN)
140
+ return;
141
+ this.pendingRuntimeReplays.set(socket, setTimeout(() => {
142
+ this.pendingRuntimeReplays.delete(socket);
143
+ if (this.sockets.has(socket))
144
+ this.sendState(socket);
145
+ }, 100).unref());
146
+ }
147
+ clearRuntimeReplay(socket) {
148
+ const timer = this.pendingRuntimeReplays.get(socket);
149
+ if (timer)
150
+ clearTimeout(timer);
151
+ this.pendingRuntimeReplays.delete(socket);
152
+ }
153
+ subscribeFileIndex(socket, workspaceId, cwd = "") {
154
+ if (workspaceId)
155
+ this.fileIndexScopes.set(socket, { workspaceId, cwd });
156
+ else
157
+ this.fileIndexScopes.delete(socket);
158
+ }
159
+ receives(socket, event) {
160
+ const scope = this.scopes.get(socket);
161
+ if (!scope)
162
+ return true;
163
+ switch (event.type) {
164
+ case "files.index": {
165
+ const fileScope = this.fileIndexScopes.get(socket);
166
+ return fileScope?.workspaceId === event.workspaceId && fileScope.cwd === (event.cwd ?? "");
167
+ }
168
+ case "message.delta":
169
+ case "message.thinking":
170
+ case "message.tools":
171
+ return event.conversationId === scope.conversationId;
172
+ case "exec.output":
173
+ case "exec.exit":
174
+ return !event.conversationId || event.conversationId === scope.conversationId;
175
+ case "subagent.event":
176
+ return event.run.conversationId === scope.conversationId;
177
+ case "workflow.event":
178
+ return event.workflow.conversationId === scope.conversationId;
179
+ default:
180
+ // Lifecycle and summary changes still reach the sidebar for every conversation.
181
+ return true;
182
+ }
183
+ }
184
+ configureStreaming(socket, coalesce) {
185
+ if (coalesce)
186
+ this.coalescedSockets.add(socket);
187
+ else {
188
+ this.flushStreaming(socket);
189
+ this.coalescedSockets.delete(socket);
190
+ }
191
+ }
192
+ flushStreaming(socket) {
193
+ const pending = this.pendingStreams.get(socket);
194
+ if (!pending)
195
+ return;
196
+ clearTimeout(pending.timer);
197
+ this.pendingStreams.delete(socket);
198
+ for (const event of pending.events.values()) {
199
+ if (!safeSend(socket, JSON.stringify(event)) && event.type === "subagent.event") {
200
+ this.scheduleRuntimeReplay(socket);
201
+ }
202
+ }
203
+ }
204
+ enqueueStreaming(socket, event) {
205
+ let pending = this.pendingStreams.get(socket);
206
+ if (!pending) {
207
+ const events = [];
208
+ pending = { events, timer: setTimeout(() => this.flushStreaming(socket), 16) };
209
+ this.pendingStreams.set(socket, pending);
210
+ }
211
+ // A subagent.event is a whole-run SNAPSHOT whose output is the accumulated text so far: within one
212
+ // 16ms window the LATEST snapshot for a run supersedes every earlier one (they differ only by more
213
+ // text). Keeping the newest replaces a per-delta frame burst with at most one frame per run per
214
+ // window - the O(n²) burst the flood fix exists for - while the card still updates at ~60fps.
215
+ if (event.type === "subagent.event") {
216
+ const superseded = pending.events.findIndex((queued) => queued.type === "subagent.event" && queued.run.id === event.run.id);
217
+ if (superseded >= 0) {
218
+ pending.events[superseded] = event;
219
+ return;
220
+ }
221
+ pending.events.push(event);
222
+ return;
223
+ }
224
+ // Only adjacent fragments from the same stream can merge. A different kind,
225
+ // answer offset or lifecycle flag is an ordering boundary, even within 16ms.
226
+ const previous = pending.events.at(-1);
227
+ if (previous && previous.type === event.type && previous.conversationId === event.conversationId
228
+ && previous.messageId === event.messageId && (event.type !== "message.thinking"
229
+ || (previous.type === "message.thinking" && previous.at === event.at && previous.active === event.active && previous.blockIndex === event.blockIndex))) {
230
+ pending.events[pending.events.length - 1] = { ...event, delta: previous.delta + event.delta };
231
+ }
232
+ else
233
+ pending.events.push(event);
234
+ }
235
+ getSockets() {
236
+ return this.sockets;
237
+ }
238
+ broadcast(event) {
239
+ if (event.type === "state") {
240
+ this.broadcastState();
241
+ return;
242
+ }
243
+ const streaming = event.type === "message.delta" || event.type === "message.thinking" || event.type === "subagent.event";
244
+ // Serialize common events once, after finding a recipient. Coalesced text stays per socket;
245
+ // conversation snapshots are projected and serialized once per scope in broadcastState().
246
+ let payload;
247
+ for (const socket of this.sockets) {
248
+ if (socket.readyState !== WebSocket.OPEN || !this.receives(socket, event))
249
+ continue;
250
+ if (streaming && this.coalescedSockets.has(socket))
251
+ this.enqueueStreaming(socket, event);
252
+ else {
253
+ // A state/tool/lifecycle event is a transcript boundary. Flush its preceding text first.
254
+ this.flushStreaming(socket);
255
+ payload ??= JSON.stringify(event);
256
+ if (!safeSend(socket, payload) && (event.type === "exec.output" || event.type === "exec.exit" || event.type === "subagent.event")) {
257
+ this.scheduleRuntimeReplay(socket);
258
+ }
259
+ }
260
+ }
261
+ }
262
+ /**
263
+ * BROADCAST STATES IN A TIME WINDOW, NOT IN A MICROTASK.
264
+ *
265
+ * The microtask flag this replaces merged only the calls that arrived within the
266
+ * SAME tick. A sub-agent that streams text emits one `subagent.event` per delta,
267
+ * each asking for a full state broadcast, and those deltas arrive across many
268
+ * ticks - so a single sub-agent run could ask for HUNDREDS of full state
269
+ * broadcasts. On a machine whose state is large, that is a flood the browser
270
+ * cannot drain: its parse queue falls behind, the socket buffer grows, and the
271
+ * connection is dropped (the browser reports 1006).
272
+ *
273
+ * A window turns a burst into a handful of frames. The state a browser receives
274
+ * is the LATEST state - the intermediate ones carried nothing the last one did
275
+ * not - so nothing is lost by sending fewer of them. The only thing that
276
+ * changes is how promptly the browser sees a change, and 150ms is below the
277
+ * threshold at which a person notices.
278
+ */
279
+ stateFlushScheduled = false;
280
+ broadcastState() {
281
+ // DIAGNOSTIC PATH: the pre-fix wire shape, one frame per request, no merge window.
282
+ if (this.sendStateImmediately) {
283
+ this.flushState();
284
+ return;
285
+ }
286
+ if (this.stateFlushScheduled)
287
+ return;
288
+ this.stateFlushScheduled = true;
289
+ const now = Date.now();
290
+ // HOW MANY STATE FRAMES WENT OUT IN THE LAST SECOND.
291
+ //
292
+ // This is the flood detector, and it is a RATE, not a delay. A server that is behaving sends a
293
+ // handful of frames a second: one per user action, one per turn boundary. A server that is
294
+ // flooding sends hundreds - a sub-agent's delta used to ask for one full state frame each.
295
+ //
296
+ // The NORMAL path stays exactly as it always was: a microtask merge, so the frame goes out at the
297
+ // end of this tick. That matters for more than latency: "the user sent a message" and "the turn
298
+ // opened" are two broadcasts, and if they are merged into one frame the user's own message never
299
+ // appears on its own - it appears already accompanied by the assistant placeholder. A message
300
+ // that arrives half-written is a message the user does not believe they sent.
301
+ //
302
+ // The DEGRADED path is for a server that is genuinely flooding: requests are then merged into one
303
+ // frame per window, because a browser that cannot parse frames as fast as they arrive gets its
304
+ // connection dropped (the browser reports 1006) and the user sees "连接中 / 断连 / 连接中".
305
+ queueMicrotask(() => {
306
+ this.stateFlushScheduled = false;
307
+ this.flushState();
308
+ });
309
+ }
310
+ flushState() {
311
+ const groups = new Map();
312
+ for (const socket of this.sockets) {
313
+ if (socket.readyState !== WebSocket.OPEN)
314
+ continue;
315
+ const scope = this.scopes.get(socket);
316
+ const key = scope ? `focused:${JSON.stringify(scope.conversationId ?? null)}` : "legacy";
317
+ let group = groups.get(key);
318
+ if (!group) {
319
+ group = { scope, sockets: [] };
320
+ groups.set(key, group);
321
+ }
322
+ group.sockets.push(socket);
323
+ }
324
+ for (const { scope, sockets } of groups.values()) {
325
+ const snapshotStartedAt = performance.now();
326
+ const state = this.getState(scope);
327
+ const snapshotMs = performance.now() - snapshotStartedAt;
328
+ const serializeStartedAt = performance.now();
329
+ const cachedStatePayload = JSON.stringify({ type: "state", state });
330
+ const serializeMs = performance.now() - serializeStartedAt;
331
+ if (process.env.SUPER_PI_TRACE_LATENCY === "1") {
332
+ console.warn(`[super-pi latency] phase=state.snapshot.ready bytes=${Buffer.byteLength(cachedStatePayload, "utf8")} snapshotMs=${Math.round(snapshotMs)} serializeMs=${Math.round(serializeMs)} sockets=${sockets.length} scope=${scope ? "focused" : "legacy"}`);
333
+ }
334
+ for (const socket of sockets) {
335
+ this.flushStreaming(socket);
336
+ safeSend(socket, cachedStatePayload);
337
+ }
338
+ }
339
+ }
340
+ /**
341
+ * Releases the pending state window, so a shutting-down server does not hold the event loop
342
+ * open on a timer whose flush would send to sockets that are already closed.
343
+ */
344
+ dispose() {
345
+ this.stateFlushScheduled = false;
346
+ for (const socket of this.pendingRuntimeReplays.keys())
347
+ this.clearRuntimeReplay(socket);
348
+ }
349
+ getStateSnapshot(scope) {
350
+ return this.getState(scope);
351
+ }
352
+ }
353
+ import { checkDiskVersion } from "./version.js";
354
+ /**
355
+ * WebSocket transport manager handling upgrade, connection lifecycles, and command dispatch.
356
+ */
357
+ export class WsServer {
358
+ browserAccess;
359
+ managedServers;
360
+ websocketServer;
361
+ broadcaster;
362
+ commandHandler;
363
+ catalogService;
364
+ accessToken;
365
+ rootDir;
366
+ onSocketClose;
367
+ constructor(options) {
368
+ this.browserAccess = options.browserAccess;
369
+ this.managedServers = options.managedServers;
370
+ this.broadcaster = options.broadcaster;
371
+ this.commandHandler = options.commandHandler;
372
+ this.catalogService = options.catalogService;
373
+ this.accessToken = options.accessToken;
374
+ this.rootDir = options.rootDir;
375
+ this.onSocketClose = options.onSocketClose;
376
+ // Remote clients are commonly separated from the server by a high-latency link. State snapshots can
377
+ // contain a long transcript, so sending them uncompressed turns every lifecycle event into a multi-MB
378
+ // transfer. Per-message deflate keeps the protocol unchanged while making the wire cost proportional
379
+ // to the actual information in the snapshot. The threshold avoids spending CPU on token-sized events.
380
+ this.websocketServer = new WebSocketServer({ noServer: true, handleProtocols: protocols => protocols.has("super-pi") ? "super-pi" : false, maxPayload: MAX_WS_PAYLOAD_BYTES, perMessageDeflate: { threshold: 1024, serverNoContextTakeover: true } });
381
+ this.setupUpgrade(options.httpServer);
382
+ this.setupConnectionHandling();
383
+ }
384
+ setupUpgrade(httpServer) {
385
+ httpServer.on("upgrade", (request, socket, head) => {
386
+ const browserAuthorized = this.browserAccess?.authorize(request, true) ?? false;
387
+ const url = new URL(request.url ?? "/", `http://${request.headers.host ?? "localhost"}`);
388
+ const managed = /^\/managed\/([a-f0-9-]+)(\/ws)$/.exec(url.pathname);
389
+ if (managed) {
390
+ if (!this.managedServers || !isAuthorized(request, this.accessToken)
391
+ || (!browserAuthorized && (!isLoopbackAddress(request.socket.remoteAddress) || (request.headers.origin && request.headers.origin !== url.origin)))) {
392
+ socket.destroy();
393
+ return;
394
+ }
395
+ void this.managedServers.upgrade(managed[1], managed[2] + url.search, request, socket, head).catch(() => socket.destroy());
396
+ return;
397
+ }
398
+ if (!isAuthorized(request, this.accessToken) || new URL(request.url ?? "/", "http://localhost").pathname !== "/ws") {
399
+ socket.destroy();
400
+ return;
401
+ }
402
+ const origin = request.headers.origin;
403
+ if (origin) {
404
+ try {
405
+ const parsed = new URL(origin);
406
+ const host = request.headers.host;
407
+ if ((!browserAuthorized && (!host || parsed.host !== host)) || !["http:", "https:"].includes(parsed.protocol)) {
408
+ socket.destroy();
409
+ return;
410
+ }
411
+ }
412
+ catch {
413
+ socket.destroy();
414
+ return;
415
+ }
416
+ }
417
+ this.websocketServer.handleUpgrade(request, socket, head, (ws) => {
418
+ if (browserAuthorized) {
419
+ const release = this.browserAccess.onRevoke(() => ws.close(4003, "Browser authorization revoked"));
420
+ ws.once("close", release);
421
+ }
422
+ this.websocketServer.emit("connection", ws, request);
423
+ });
424
+ });
425
+ }
426
+ setupConnectionHandling() {
427
+ this.websocketServer.on("connection", (socket, request) => {
428
+ const url = new URL(request.url ?? "/ws", "http://localhost");
429
+ // HOW A CLIENT ASKS FOR A SCOPE, AND WHAT IT GETS WHEN IT DOES NOT ASK.
430
+ //
431
+ // `undefined` means the WHOLE application: every workspace, every conversation and every
432
+ // message. On a machine with a long history that is tens of megabytes in the FIRST FRAME.
433
+ //
434
+ // There are three cases, and they are NOT the same thing:
435
+ //
436
+ // ?state=focused -> the focused projection (sidebar + the selected transcript)
437
+ // ?conversationId=<id> -> the focused projection of that one conversation
438
+ // (neither) -> the legacy full state, exactly as before this change
439
+ //
440
+ // The middle case is what the current browser sends (it sends both). The third case is a
441
+ // client running an OLD bundle, and it MUST keep getting the full state: a focused frame
442
+ // with no conversationId carries NO transcripts at all, so an old client that never sends
443
+ // `state.subscribe` would connect and see an empty application. Dropping it silently is
444
+ // worse than a big first frame.
445
+ //
446
+ // And the big first frame is no longer FATAL: `safeSend` drops an oversized frame instead
447
+ // of terminating the connection, so a browser that cannot digest 42 MB at once is merely
448
+ // SLOW on that first frame - it is not disconnected, and it does not enter the
449
+ // "连接中 / 断连 / 连接中" loop. The disconnect is fixed at the buffer, not at the scope.
450
+ const wantsFocused = url.searchParams.get("state") === "focused";
451
+ const conversationId = url.searchParams.get("conversationId") || undefined;
452
+ const scope = wantsFocused || conversationId ? { conversationId } : undefined;
453
+ this.broadcaster.register(socket, scope);
454
+ socket.on("error", (error) => {
455
+ console.warn(`Super Pi: WebSocket error: ${error instanceof Error ? error.message : String(error)}`);
456
+ try {
457
+ socket.terminate();
458
+ }
459
+ catch { /* already closed */ }
460
+ });
461
+ /**
462
+ * The peer address, captured ONCE per connection rather than read per message.
463
+ *
464
+ * `socket._socket.remoteAddress` is the real TCP peer, but the terminal re-checks it on every
465
+ * command (`TerminalService.assertUsable`), so it has to be read where the underlying socket is
466
+ * still reachable. Reading it inside the message handler would reach for a private field on a
467
+ * `WebSocket` that may already be torn down, and the terminal is exactly the command family where
468
+ * a missing address must fail CLOSED rather than fall back to "allowed".
469
+ */
470
+ const remoteAddress = request.socket.remoteAddress;
471
+ const send = event => {
472
+ if (safeSend(socket, JSON.stringify(event)))
473
+ return;
474
+ // Dropping a terminal frame would corrupt the stream or leave its replay unfinished.
475
+ // Reconnecting restores the baseline without stopping the PTY.
476
+ if (event.type.startsWith("terminal.") && socket.readyState === WebSocket.OPEN)
477
+ socket.close(1013, "Terminal reconnect required");
478
+ };
479
+ this.broadcaster.sendState(socket);
480
+ if (this.rootDir) {
481
+ safeSend(socket, JSON.stringify({ type: "server.version", version: checkDiskVersion(this.rootDir) }));
482
+ }
483
+ void this.catalogService.agentCatalog().then((catalog) => {
484
+ if (socket.readyState === WebSocket.OPEN) {
485
+ safeSend(socket, JSON.stringify({ type: "agent.catalog", catalog }));
486
+ }
487
+ }).catch((error) => console.warn(`Super Pi: agent catalog for a new connection failed: ${error instanceof Error ? error.message : "unknown error"}`));
488
+ void this.catalogService.subagentCatalog().then((catalog) => {
489
+ if (socket.readyState === WebSocket.OPEN) {
490
+ safeSend(socket, JSON.stringify({ type: "subagent.catalog", catalog }));
491
+ }
492
+ }).catch((error) => console.warn(`Super Pi: sub-agent catalog for a new connection failed: ${error instanceof Error ? error.message : "unknown error"}`));
493
+ /**
494
+ * Liveness follows the standard ws pattern: every pong marks the peer alive, each heartbeat
495
+ * marks it unanswered and pings, and a peer that is STILL unanswered on the next heartbeat is
496
+ * terminated. Without this, a half-open connection (frozen tab, gone NAT entry, pulled cable)
497
+ * stays OPEN forever and every broadcast serializes full state to it.
498
+ */
499
+ let isAlive = true;
500
+ socket.on("pong", () => { isAlive = true; });
501
+ const heartbeat = setInterval(() => {
502
+ if (socket.readyState !== WebSocket.OPEN)
503
+ return;
504
+ if (!isAlive) {
505
+ // Fires 'close', which runs the per-socket cleanup below.
506
+ socket.terminate();
507
+ return;
508
+ }
509
+ isAlive = false;
510
+ socket.ping();
511
+ if (this.rootDir) {
512
+ const v = checkDiskVersion(this.rootDir);
513
+ if (v.needsRestart) {
514
+ safeSend(socket, JSON.stringify({ type: "server.version", version: v }));
515
+ }
516
+ }
517
+ }, 30_000);
518
+ socket.on("close", () => {
519
+ clearInterval(heartbeat);
520
+ this.broadcaster.unregister(socket);
521
+ this.onSocketClose?.(send);
522
+ });
523
+ /**
524
+ * Commands from ONE socket are SERIALIZED through a promise chain. `handleCommand` is async, so
525
+ * a bare `async` listener lets command N+1 start while command N is still awaiting inside the
526
+ * services, interleaving that defeats their check-then-act guards. Chaining each command off the
527
+ * previous one makes same-socket execution strictly in-order while different sockets keep their
528
+ * own independent chains. Error handling is unchanged: each command catches its own errors and
529
+ * reports them on the socket, and the chain-level catch only stops an unexpected rejection from
530
+ * poisoning every later command on the same socket.
531
+ */
532
+ let commandQueue = Promise.resolve();
533
+ socket.on("message", (raw) => {
534
+ if (isBrowserAuthorized(request) && !this.browserAccess?.authorize(request, true)) {
535
+ socket.close(4003, "Browser authorization revoked");
536
+ return;
537
+ }
538
+ let parsed;
539
+ try {
540
+ parsed = JSON.parse(raw.toString());
541
+ }
542
+ catch {
543
+ console.error("Super Pi command error: received a frame that is not valid JSON");
544
+ safeSend(socket, JSON.stringify({ type: "error", message: "收到一条无法解析的命令,已忽略。" }));
545
+ return;
546
+ }
547
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || typeof parsed.type !== "string") {
548
+ safeSend(socket, JSON.stringify({ type: "error", message: "收到一条格式无效的命令,已忽略。" }));
549
+ return;
550
+ }
551
+ if (parsed.type === "files.index.subscribe") {
552
+ this.broadcaster.subscribeFileIndex(socket, typeof parsed.workspaceId === "string" ? parsed.workspaceId : undefined, typeof parsed.cwd === "string" ? parsed.cwd : "");
553
+ return;
554
+ }
555
+ if (parsed.type === "stream.configure") {
556
+ this.broadcaster.configureStreaming(socket, parsed.coalesce);
557
+ return;
558
+ }
559
+ if (parsed.type === "state.subscribe") {
560
+ if (parsed.conversationId !== undefined && typeof parsed.conversationId !== "string") {
561
+ safeSend(socket, JSON.stringify({ type: "error", message: "会话订阅标识必须是字符串。" }));
562
+ return;
563
+ }
564
+ this.broadcaster.subscribe(socket, parsed.conversationId);
565
+ return;
566
+ }
567
+ // A send or selected queued turn is a streaming operation. It must leave the socket's command
568
+ // chain immediately: waiting for the model turn would block later priority/cancel commands and
569
+ // make a second send miss the durable queue. The service owns per-conversation run claims.
570
+ const runIndependently = parsed.type === "message.send" || parsed.type === "message.sendQueued"
571
+ || parsed.type === "message.interrupt" || parsed.type === "run.stop" || parsed.type === "message.revert";
572
+ // ...WHICH MEANS A SEND CAN OVERTAKE A REVERT SENT JUST BEFORE IT, because the revert below is
573
+ // queued behind whatever this socket was already doing. The service only learns it is cutting
574
+ // when the command EXECUTES, so a send handled in between would find the conversation open and
575
+ // be admitted onto a transcript the cut has not reached yet. Claiming here closes that gap: this
576
+ // is the arrival edge, and the only one early enough to be of use to a command that does not wait.
577
+ if (parsed.type === "message.revert")
578
+ this.commandHandler.claimRevert(parsed.conversationId);
579
+ const execute = async () => {
580
+ let command;
581
+ try {
582
+ command = parsed;
583
+ if (command.type.startsWith("terminal.") && socket.readyState !== WebSocket.OPEN)
584
+ return;
585
+ const entityId = await this.commandHandler.handleCommand(command, send, remoteAddress, isBrowserAuthorized(request));
586
+ // Void-returning configuration commands also need an ack to release optimistic UI state.
587
+ if (command.operationRequestId)
588
+ safeSend(socket, JSON.stringify({ type: "operation.result", requestId: command.operationRequestId, ok: true, entityId }));
589
+ }
590
+ catch (error) {
591
+ // A FAILED COMMAND WRITES ITSELF DOWN BEFORE IT ANSWERS.
592
+ //
593
+ // The server runs detached with its streams thrown away, so `console.error` here is not
594
+ // decoration: the logger tees it into `<dataDir>/logs/server.log`, which is the only place
595
+ // the stack survives. The browser gets the reason (never a stand-in phrase like
596
+ // `command failed`), because the reader is the one who has to act on it.
597
+ console.error("Super Pi command error:", describeThrownWithStack(error));
598
+ const reason = describeThrown(error);
599
+ if (command?.operationRequestId) {
600
+ safeSend(socket, JSON.stringify({ type: "operation.result", requestId: command.operationRequestId, ok: false, message: reason }));
601
+ return;
602
+ }
603
+ safeSend(socket, JSON.stringify({
604
+ type: "error",
605
+ message: reason || "服务端没有说明这次失败的原因。",
606
+ }));
607
+ }
608
+ finally {
609
+ // Hand the claim back whatever happened - including a revert that threw before it ever
610
+ // reached the service. Without this a refused or malformed revert would leave the
611
+ // conversation permanently unable to send, which is a worse failure than the one the claim
612
+ // was added to prevent.
613
+ if (parsed.type === "message.revert")
614
+ this.commandHandler.releaseRevert(parsed.conversationId);
615
+ }
616
+ };
617
+ if (runIndependently)
618
+ void execute().catch((error) => {
619
+ console.error("Super Pi command dispatch failed:", describeThrownWithStack(error));
620
+ });
621
+ else
622
+ commandQueue = commandQueue.then(execute).catch((error) => {
623
+ console.error("Super Pi command dispatch failed:", describeThrownWithStack(error));
624
+ });
625
+ });
626
+ });
627
+ }
628
+ /**
629
+ * Gracefully closes all active WebSocket connections and terminates the server.
630
+ */
631
+ close() {
632
+ // A pending state window must not outlive the server: the timer holds the event loop
633
+ // open, and a flush after the sockets are closed would send to a dead peer.
634
+ this.broadcaster.dispose();
635
+ for (const socket of this.broadcaster.getSockets()) {
636
+ socket.close(1001, "server-shutdown");
637
+ }
638
+ this.websocketServer.close();
639
+ }
640
+ }