@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 @@
1
+ export {};
@@ -0,0 +1,485 @@
1
+ import { validateConversationModel } from "./model-filter.js";
2
+ import { ActiveMemory } from "./active-memory.js";
3
+ import { KnowledgeBase } from "./knowledge.js";
4
+ import { VectorIndex } from "./knowledge-vectors.js";
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import { mkdir } from "node:fs/promises";
7
+ import { homedir } from "node:os";
8
+ import { join, resolve } from "node:path";
9
+ import { pathToFileURL } from "node:url";
10
+ import { isChildSession } from "../shared/child-session-lock.js";
11
+ import { sanitizeBackgroundOutput } from "../shared/background-task.js";
12
+ import { openStateStore } from "./persistence/open-state-store.js";
13
+ import { PiRpcRuntime, WelcomeRuntime } from "./runtime.js";
14
+ import { agentModeOf, resolveAgentDirectories } from "./agents.js";
15
+ import { releaseAllCapabilities } from "./capability.js";
16
+ import { SubagentSupervisor } from "./subagents.js";
17
+ import { SubagentRunRecorder } from "./subagent-runs.js";
18
+ import { WorkflowEngine } from "./workflow-engine.js";
19
+ import { ExtensionUiService } from "./application/extension-ui-service.js";
20
+ import { DocumentService } from "./application/document-service.js";
21
+ import { FeishuService } from "./application/feishu-service.js";
22
+ import { CatalogService } from "./application/catalog-service.js";
23
+ import { ProviderService } from "./application/provider-service.js";
24
+ import { ProviderRegistry } from "./providers.js";
25
+ import { RunService } from "./application/run-service.js";
26
+ import { GroupChatService } from "./application/group-chat-service.js";
27
+ import { FileChangeTracker } from "./file-changes.js";
28
+ import { ConversationService } from "./application/conversation-service.js";
29
+ import { ScheduledTaskService } from "./application/scheduled-task-service.js";
30
+ import { SessionLedger } from "./session-ledger.js";
31
+ import { SessionOrchestratorService } from "./application/session-orchestrator-service.js";
32
+ import { SessionReminderService } from "./application/session-reminder-service.js";
33
+ import { ProjectService } from "./application/project-service.js";
34
+ import { WorkspaceService } from "./application/workspace-service.js";
35
+ import { CommandHandler } from "./command-handler.js";
36
+ import { TerminalService, terminalDisabledReason } from "./terminal.js";
37
+ import { ExecService } from "./exec-service.js";
38
+ import { createHttpServer, getLanIps, isLocalOrPrivateAddress, parseServerArgs } from "./http-server.js";
39
+ import { WsBroadcaster, WsServer } from "./ws-server.js";
40
+ import { initRunningVersion } from "./version.js";
41
+ import { installServerLogging } from "./logging.js";
42
+ import { ToolRegistry } from "./tool-registry.js";
43
+ import { ToolRunner } from "./tool-runner.js";
44
+ import { ToolLlmService } from "./tool-llm.js";
45
+ import { WebService } from "./web.js";
46
+ import { TavilyService } from "./tavily.js";
47
+ // ------------------------------------------------------------- Environment & paths
48
+ const rootDir = resolve(import.meta.dirname, "../..");
49
+ initRunningVersion(rootDir);
50
+ // ------------------------------------------------------------- The log file
51
+ //
52
+ // THE SERVER IS STARTED DETACHED WITH ITS OUTPUT THROWN AWAY, so anything printed to the console
53
+ // is gone. A crash used to take the process down with no word at all, and the browser just sat there
54
+ // saying "connecting". The log file is installed BEFORE anything else can fail, so the first line in
55
+ // it is always "the server started" and the last line is always "the server stopped".
56
+ const defaultDataDir = !rootDir.includes("node_modules") && existsSync(join(rootDir, ".super-pi"))
57
+ ? join(rootDir, ".super-pi")
58
+ : join(homedir(), ".super-pi");
59
+ const dataDir = resolve(process.env.SUPER_PI_DATA_DIR ?? defaultDataDir);
60
+ const logging = installServerLogging(dataDir);
61
+ logging.write("info", `server starting: pid ${process.pid}, node ${process.versions.node}, data dir ${dataDir}`);
62
+ // THE SECURITY PATCH, APPLIED WHERE IT CANNOT BREAK AN INSTALL.
63
+ //
64
+ // Pi's package pins a vulnerable `brace-expansion` in its own shrinkwrapped tree, and npm will not let
65
+ // anything move it - not `overrides`, not `npm audit fix`. So Super Pi replaces that one copy with the
66
+ // patched release itself.
67
+ //
68
+ // It runs HERE, at startup, and not as a `postinstall` script, because a postinstall that fails fails
69
+ // the INSTALL - and on 2026-10-21 it did exactly that on somebody else's machine, leaving them unable
70
+ // to install Super Pi at all. An install must not be breakable by a security patch.
71
+ //
72
+ // It is also deliberately ASYNCHRONOUS and off the startup path: the server is already serving by the
73
+ // time this finishes, and a registry that is slow or unreachable must not delay the panel. The copy is
74
+ // vulnerable for the few seconds until the patch lands, and the patched version is what every later
75
+ // turn uses.
76
+ void (async () => {
77
+ try {
78
+ // The specifier is built at runtime so the compiler does not need the file to exist: it lives in
79
+ // `scripts/`, which is not part of the compiled output.
80
+ const modulePath = resolve(rootDir, "scripts", "patch-brace-expansion.mjs");
81
+ const { patchBraceExpansion } = await import(pathToFileURL(modulePath).href);
82
+ await patchBraceExpansion();
83
+ }
84
+ catch (error) {
85
+ console.warn(`[super-pi] the brace-expansion patch did not run: ${error instanceof Error ? error.message : String(error)}`);
86
+ }
87
+ })();
88
+ // PI'S SDK, LOADED WHILE THE SERVER IS STILL STARTING.
89
+ //
90
+ // Importing Pi's SDK costs about 1.5 seconds the first time and is free afterwards, and it was being
91
+ // paid by whichever user action happened to need it first - which, for most people, was opening the
92
+ // model picker and wondering why it stayed grey. Here it is paid during startup, in parallel with
93
+ // everything else the server does, so the first conversation does not pay for it.
94
+ //
95
+ // Warmup only: nothing here is required for the server to run, and a failure is one line.
96
+ void (async () => {
97
+ try {
98
+ const { warmPiSdk } = await import(pathToFileURL(resolve(rootDir, "dist", "server", "pi-session.js")).href);
99
+ await warmPiSdk();
100
+ }
101
+ catch (error) {
102
+ console.warn(`[super-pi] Pi's SDK did not load during warmup: ${error instanceof Error ? error.message : String(error)}`);
103
+ }
104
+ })();
105
+ const cliArgs = parseServerArgs(process.argv);
106
+ // THE PORT THE PERSON CHOSE, IN THE ORDER THEY CHOSE IT: the command line, then the
107
+ // environment, then the saved config, then the built-in default. `super-pi set port` writes the
108
+ // saved config, so a deployment that cannot pass a flag still gets the port it asked for.
109
+ const savedSettings = (() => {
110
+ try {
111
+ return JSON.parse(readFileSync(join(dataDir, "config.json"), "utf8")) ?? {};
112
+ }
113
+ catch {
114
+ return {};
115
+ }
116
+ })();
117
+ // A non-numeric SUPER_PI_PORT would parse to NaN and die later in `listen` with a confusing error;
118
+ // like the other environment variables here, an unusable value falls back to the next choice.
119
+ const savedPort = Number(savedSettings.port);
120
+ const savedHost = typeof savedSettings.host === "string" && savedSettings.host ? savedSettings.host : undefined;
121
+ const envPort = process.env.SUPER_PI_PORT === undefined ? undefined : Number.parseInt(process.env.SUPER_PI_PORT, 10);
122
+ const port = cliArgs.port ?? (envPort !== undefined && !Number.isNaN(envPort) ? envPort : (Number.isInteger(savedPort) && savedPort > 0 ? savedPort : 3080));
123
+ const host = cliArgs.host ?? process.env.SUPER_PI_HOST ?? savedHost ?? "0.0.0.0";
124
+ const internalHost = (host === "0.0.0.0" || host === "::" || !host) ? "127.0.0.1" : host;
125
+ const agentPromptDir = join(dataDir, "agent-prompts");
126
+ const clientDir = join(rootDir, "dist", "client");
127
+ const accessToken = process.env.SUPER_PI_ACCESS_TOKEN;
128
+ const uploadsDir = join(dataDir, "uploads");
129
+ try {
130
+ await mkdir(uploadsDir, { recursive: true });
131
+ }
132
+ catch (error) {
133
+ logging.write("warn", `uploads directory unavailable: ${error instanceof Error ? error.message : String(error)}`);
134
+ }
135
+ const taskEndpoint = `http://${internalHost}:${port}/api/subagent/dispatch`;
136
+ const execEndpoint = `http://${internalHost}:${port}/api/exec`;
137
+ const todoEndpoint = `http://${internalHost}:${port}/api/todos`;
138
+ const scheduledTaskEndpoint = `http://${internalHost}:${port}/api/scheduled-tasks`;
139
+ const workflowEndpoint = `http://${internalHost}:${port}/api/workflow/run`;
140
+ const questionEndpoint = `http://${internalHost}:${port}/api/question`;
141
+ const toolsEndpoint = `http://${internalHost}:${port}/api/tools`;
142
+ const documentsEndpoint = `http://${internalHost}:${port}/api/documents/tool`;
143
+ const orchestratorEndpoint = `http://${internalHost}:${port}/api/orchestrator`;
144
+ // ------------------------------------------------------------- Core singletons
145
+ const store = await openStateStore(dataDir, process.env.SUPER_PI_PERSISTENCE ?? "sqlite");
146
+ const toolRegistry = new ToolRegistry(dataDir);
147
+ // The data dir is what makes a per-tool virtual environment possible: it lives at
148
+ // `<dataDir>/tool-envs/<toolId>`, beside the tools rather than inside one.
149
+ const toolRunner = new ToolRunner(dataDir);
150
+ const initialAgentDirs = resolveAgentDirectories({
151
+ customDirs: store.snapshot().customAgentDirs,
152
+ rootDir,
153
+ });
154
+ const agentsDir = initialAgentDirs[0] ?? resolve(process.env.SUPER_PI_AGENTS_DIR ?? join(rootDir, "agents"));
155
+ const paths = {
156
+ dataDir,
157
+ rootDir,
158
+ agentsDir,
159
+ agentDirs: initialAgentDirs,
160
+ agentPromptDir,
161
+ uploadsDir,
162
+ clientDir,
163
+ };
164
+ const runtime = process.env.SUPER_PI_RUNTIME === "welcome"
165
+ ? new WelcomeRuntime()
166
+ : new PiRpcRuntime(join(dataDir, "pi-sessions"), undefined, { dir: initialAgentDirs, promptDir: agentPromptDir }, { endpoint: taskEndpoint, execEndpoint, todoEndpoint, workflowEndpoint, questionEndpoint, toolsEndpoint, documentsEndpoint, scheduledTaskEndpoint, orchestratorEndpoint, uploadsDir,
167
+ onBackgroundUsage: async (conversationId, readout) => {
168
+ if (!store.conversation(conversationId))
169
+ return;
170
+ await store.recordConversationUsage(conversationId, readout);
171
+ broadcaster.broadcastState();
172
+ },
173
+ });
174
+ // Closed workspaces stay in the store for reopening. Focused sockets receive all visible sidebar
175
+ // summaries and only their selected transcript; legacy sockets retain the complete visible state.
176
+ let projectRuntime = (state) => state;
177
+ let replayRuntime = (_state, _scope) => [];
178
+ const broadcaster = new WsBroadcaster(scope => projectRuntime(store.clientState(scope)), (state, scope) => replayRuntime(state, scope));
179
+ const memory = new ActiveMemory(join(dataDir, "memories"), store, runtime);
180
+ process.env.SUPER_PI_MEMORY_ENDPOINT = `http://${internalHost}:${port}/api/memory/tool`;
181
+ if (runtime instanceof PiRpcRuntime)
182
+ runtime.setMemory(memory);
183
+ // The model a mounted tool may ask. It IS Pi: `PiRpcRuntime.askOnce` spawns its own child with nothing
184
+ // attached but Pi, and a runtime without one reports itself unavailable rather than faking an answer.
185
+ const toolLlm = new ToolLlmService(runtime, rootDir);
186
+ const knowledge = new KnowledgeBase(join(dataDir, "knowledge"), store, runtime, new VectorIndex(join(dataDir, "knowledge")));
187
+ process.env.SUPER_PI_KNOWLEDGE_ENDPOINT = `http://${internalHost}:${port}/api/knowledge/tool`;
188
+ if (runtime instanceof PiRpcRuntime)
189
+ runtime.setKnowledge(knowledge);
190
+ // The document tools. The endpoint is published here, the same way the knowledge one is: the Pi
191
+ // process of a turn reads it out of its environment, and the endpoint verifies the session's
192
+ // capability on its own.
193
+ const documentService = new DocumentService(store);
194
+ process.env.SUPER_PI_DOCUMENTS_ENDPOINT = documentsEndpoint;
195
+ // The Feishu tools. The credential belongs to the OFFICIAL CLI, which keeps it in the OS keychain,
196
+ // so this service holds nothing but the CLI's address. The endpoint is published here the same way
197
+ // the document one is: the Pi process of a turn reads it out of its environment, and the endpoint
198
+ // verifies the session's capability on its own.
199
+ const feishu = new FeishuService();
200
+ process.env.SUPER_PI_FEISHU_ENDPOINT = `http://${internalHost}:${port}/api/feishu/tool`;
201
+ const tavily = new TavilyService(join(dataDir, "tavily.json"));
202
+ const web = new WebService(tavily);
203
+ process.env.SUPER_PI_WEB_ENDPOINT = `http://${internalHost}:${port}/api/web/tool`;
204
+ process.env.SUPER_PI_WEB_ENABLED = tavily.configured ? "1" : "0";
205
+ const extensionUiService = new ExtensionUiService(broadcaster, id => {
206
+ const { parentConversationId, parent } = store.childSessionFacts(id);
207
+ return !isChildSession(parentConversationId, parent);
208
+ });
209
+ const supervisor = new SubagentSupervisor(join(dataDir, "pi-sessions"), undefined, {
210
+ dir: initialAgentDirs,
211
+ promptDir: agentPromptDir,
212
+ });
213
+ supervisor.setMemory(memory);
214
+ const validateModel = (conversationId, selection) => validateConversationModel(store, runtime, conversationId, selection);
215
+ runtime.setModelValidator?.(validateModel);
216
+ supervisor.setModelValidator(validateModel);
217
+ /**
218
+ * DIAGNOSTIC ONLY - reproduces the pre-fix flood wire-for-wire (a full `state` broadcast per
219
+ * `subagent.event`, uncapped live output) so probes and regression tests can A/B the fix. Never set
220
+ * outside a probe; see docs/SUBAGENT-WS-FLOOD-FIX-2026-10-29.md.
221
+ */
222
+ const legacySubagentFlood = process.env.SUPER_PI_LEGACY_SUBAGENT_FLOOD === "1";
223
+ const subagents = new SubagentRunRecorder(supervisor, {
224
+ store,
225
+ broadcast: (event) => {
226
+ broadcaster.broadcast(event);
227
+ if (legacySubagentFlood && event.type === "subagent.event")
228
+ broadcaster.broadcastState();
229
+ },
230
+ // The full state broadcast moved from "every delta" to "on settle": a browser that reloads mid-run
231
+ // rebuilds the card from the current store snapshot; the settle frame puts the final
232
+ // record into `state` so a reload after the finish sees it too.
233
+ onSettled: legacySubagentFlood ? undefined : () => broadcaster.broadcastState(),
234
+ liveTailCap: legacySubagentFlood ? Number.POSITIVE_INFINITY : undefined,
235
+ host: (conversationId, runId) => extensionUiService.createHost(conversationId, runId),
236
+ closeHost: (conversationId, runId) => extensionUiService.cancelPendingUi(conversationId, "aborted", { runId }),
237
+ });
238
+ /**
239
+ * The orchestration engine: walks a whole plan the primary agent declared, dispatching each step through
240
+ * the recorder above and handing each step's output to the next.
241
+ *
242
+ * Broadcasts `workflow.event` AND the full state, exactly as the recorder does for `subagent.event`. The
243
+ * extra state frame is what puts a plan into `AppState.workflows`, so a browser that reloads mid-plan
244
+ * rebuilds the timeline from the file rather than from the events it happened to receive - the same reason
245
+ * a run's card survives a refresh. It costs nothing in practice because the engine publishes twice per
246
+ * step rather than per delta.
247
+ */
248
+ const workflows = new WorkflowEngine(subagents, {
249
+ store,
250
+ broadcast: (event) => {
251
+ broadcaster.broadcast(event);
252
+ if (event.type === "workflow.event")
253
+ broadcaster.broadcastState();
254
+ },
255
+ });
256
+ // ------------------------------------------------------------- Application services
257
+ const onDirsChanged = (dirs) => {
258
+ paths.agentDirs = dirs;
259
+ paths.agentsDir = dirs[0] ?? "";
260
+ runtime.setAgentsDir?.(dirs);
261
+ subagents.setAgentsDir(dirs);
262
+ runService.setAgentsDir(dirs);
263
+ conversationService.setAgentsDir(dirs);
264
+ workspaceService.setAgentsDir(dirs);
265
+ };
266
+ const catalogService = new CatalogService(runtime, broadcaster, initialAgentDirs, store, rootDir, onDirsChanged);
267
+ /**
268
+ * The providers a person added through the settings window.
269
+ *
270
+ * The registry lives in Super Pi's own data directory and holds the API keys; Pi's `models.json` and
271
+ * `auth.json` are written from it, so a provider added here is a provider Pi can use - in a session,
272
+ * in a spawned Pi, and in the terminal.
273
+ */
274
+ const providerRegistry = new ProviderRegistry(dataDir);
275
+ const providerService = new ProviderService(providerRegistry, runtime, broadcaster, catalogService, store);
276
+ const runService = new RunService(store, runtime, subagents, broadcaster, extensionUiService, initialAgentDirs, workflows);
277
+ runService.setMemory(memory);
278
+ /**
279
+ * WHAT THE AGENT CHANGED, and what each file looked like before.
280
+ *
281
+ * The tracker is created here rather than inside the service because it outlives one run: the changes a
282
+ * session produced are the session's record, and a tracker that died with the run would take the answer
283
+ * to "what did you just change" with it. It is handed to the run service as a setter, the same shape
284
+ * `memory` uses.
285
+ */
286
+ const fileChanges = new FileChangeTracker();
287
+ runService.setFileChanges(fileChanges);
288
+ const fileIndexes = new Map();
289
+ runService.setFileIndexes(fileIndexes);
290
+ /**
291
+ * THE NAME INDEXES, one per workspace, created eagerly.
292
+ *
293
+ * They are created here rather than on first use so that the agent's writes have somewhere to go from
294
+ * the first turn: the run service upserts into them, and the HTTP layer reads from them. A map that
295
+ * only appeared on the first search would be empty for every write that happened before it.
296
+ */
297
+ const nameIndexes = new Map();
298
+ runService.setNameIndexes(nameIndexes);
299
+ const conversationService = new ConversationService(store, runtime, subagents, broadcaster, catalogService, runService, extensionUiService, initialAgentDirs, uploadsDir);
300
+ conversationService.setMemory(memory);
301
+ const workspaceService = new WorkspaceService(store, runtime, broadcaster, catalogService, runService, extensionUiService, initialAgentDirs);
302
+ /**
303
+ * The terminal, constructed before `serverContext` because that object carries the two predicates
304
+ * `/api/terminal` answers with.
305
+ *
306
+ * Constructed UNCONDITIONALLY so the service exists to answer a refusal with a sentence, but it re-checks
307
+ * node-pty availability internally, so construction and `/api/terminal` cannot disagree. The workspace
308
+ * lookup goes through `store` rather than through the command body so that `terminal.open` has no path
309
+ * field to fill in, which is the structural half of the containment story documented in `terminal.ts`.
310
+ */
311
+ const terminalService = new TerminalService({
312
+ workspaceFor: (workspaceId) => store.snapshot().workspaces.find((workspace) => workspace.id === workspaceId),
313
+ isTrustedPeer: (remoteAddress) => isLocalOrPrivateAddress(remoteAddress),
314
+ configuredShell: () => store.snapshot().terminalShell,
315
+ saveConfiguredShell: async (shell) => { await store.setTerminalShell(shell); broadcaster.broadcastState(); },
316
+ });
317
+ /**
318
+ * Background command execution, independent from subagents. Uses node-pty to run shell commands
319
+ * and delivers results via WebSocket + injected conversation message.
320
+ */
321
+ const execService = new ExecService((event) => broadcaster.broadcast(event), (sessionId, exitCode, stdout, stderr, completion) => runService.enqueueExecResult(sessionId, exitCode, stdout, stderr, completion), (sessionId, output, offset) => store.checkpointBackgroundOutput(sessionId, sanitizeBackgroundOutput(output), offset));
322
+ runService.setExecService(execService, join(dataDir, "background-logs"));
323
+ replayRuntime = (state, scope) => execService.outputSnapshots(state, scope);
324
+ projectRuntime = state => {
325
+ const visible = new Set(state.conversations.map(conversation => conversation.id));
326
+ return {
327
+ ...state,
328
+ sendReceipts: true,
329
+ extensionUi: extensionUiService.snapshot(visible),
330
+ stoppingConversationIds: runService.stoppingConversationIds().filter(id => visible.has(id)),
331
+ };
332
+ };
333
+ /**
334
+ * THE SCHEDULED TASKS, and the clock that fires them.
335
+ *
336
+ * Constructed after the run service and the conversation service, because it drives both: a task that
337
+ * fires opens a conversation and sends a message into it, through exactly the path a person's own
338
+ * message takes.
339
+ */
340
+ const scheduledTaskService = new ScheduledTaskService(store, runService, conversationService, broadcaster);
341
+ const sessionLedger = new SessionLedger();
342
+ const sessionReminderService = new SessionReminderService(runService, store);
343
+ const sessionOrchestratorService = new SessionOrchestratorService(store, conversationService, runService, sessionLedger, broadcaster, undefined, uploadsDir);
344
+ /**
345
+ * THE PROJECT SERVICE IS TOLD HOW TO ASK WHAT AN AGENT IS.
346
+ *
347
+ * The employee rule of §1 - "a subagent cannot be a project employee" - is a fact about the agent
348
+ * DIRECTORY, and the directory is read through the same reader the picker and the runtime use
349
+ * (`readAgents`, through `agentModeOf`). The directories are asked of the catalogue service
350
+ * because THEY are the live ones: the user can add an agents directory at any time, and a guard
351
+ * that read a path captured at startup would answer about a directory that is no longer there.
352
+ */
353
+ const projectService = new ProjectService(store, sessionOrchestratorService, {
354
+ agentModeOf: (agentId) => agentModeOf(catalogService.getAgentDirs(), agentId),
355
+ });
356
+ void sessionOrchestratorService.restoreWatchdogs().catch((error) => {
357
+ console.warn("Super Pi: restoring watchdogs failed:", error instanceof Error ? error.message : String(error));
358
+ });
359
+ const groupChatService = await GroupChatService.open(join(dataDir, "group-chats.json"), store, runtime, memory, update => broadcaster.broadcast({ type: "group.activity", ...update }));
360
+ const serverContext = {
361
+ memory,
362
+ knowledge,
363
+ web,
364
+ tavily,
365
+ documentService,
366
+ feishu,
367
+ paths,
368
+ store,
369
+ runtime,
370
+ subagents,
371
+ broadcaster,
372
+ accessToken,
373
+ workspaceService,
374
+ conversationService,
375
+ runService,
376
+ extensionUiService,
377
+ catalogService,
378
+ providerService,
379
+ scheduledTaskService,
380
+ sessionLedger,
381
+ sessionReminderService,
382
+ sessionOrchestratorService,
383
+ projectService,
384
+ groupChatService,
385
+ execService,
386
+ toolRegistry,
387
+ toolRunner,
388
+ toolLlm,
389
+ fileChanges,
390
+ fileIndexes,
391
+ nameIndexes,
392
+ terminalEnabled: () => terminalService.enabled,
393
+ terminalDisabledReason: () => terminalDisabledReason(),
394
+ };
395
+ const commandHandler = new CommandHandler(workspaceService, conversationService, runService, extensionUiService, catalogService, terminalService, rootDir, providerService, scheduledTaskService, sessionOrchestratorService);
396
+ // ------------------------------------------------------------- Lifecycle & shutdown
397
+ let shutdownPromise;
398
+ async function closeHttpServer() {
399
+ await new Promise((resolve) => httpServer.close(() => resolve()));
400
+ }
401
+ async function shutdown(reason) {
402
+ if (shutdownPromise)
403
+ return shutdownPromise;
404
+ shutdownPromise = (async () => {
405
+ console.log(`Super Pi is shutting down (${reason}).`);
406
+ runService.beginShutdown();
407
+ // Stop accepting new connections first. Existing clients stay connected until
408
+ // their cancelled work has recorded its terminal state.
409
+ const httpClosed = closeHttpServer();
410
+ const nativeToolsClosed = httpServer.closeNativeTools();
411
+ // Kill every shell BEFORE the sockets close, so a PTY is never outlived by the server that owns it.
412
+ terminalService.closeAll();
413
+ const execClosed = execService.closeAll();
414
+ const groupsClosed = groupChatService.close();
415
+ runService.abortAll();
416
+ workflows.abortAll();
417
+ // The scheduler stops BEFORE the runs are waited for, so no new task starts while the server is
418
+ // closing. The runs already in flight are not aborted: a half-answered scheduled task is a real
419
+ // answer in a real conversation, and throwing it away to shut down faster would be the wrong trade.
420
+ await scheduledTaskService.stop();
421
+ for (const c of store.snapshot().conversations) {
422
+ extensionUiService.cancelPendingUi(c.id, "aborted");
423
+ }
424
+ await sessionOrchestratorService.watchdog.dispose();
425
+ await execClosed;
426
+ await Promise.all([runService.waitForIdle(), workflows.waitForIdle(), groupsClosed]);
427
+ // THE LIVE SESSIONS GO NEXT, AND THEY HAVE TO GO EXPLICITLY. `runService.abortAll()` stops the
428
+ // TURNS, and a stopped turn is not a stopped session: a session with nothing running on it is idle,
429
+ // it holds a model client and a session file, and nothing in the abort path would reach it. So
430
+ // without this the server would exit with a session per conversation still alive - and on Windows
431
+ // those sessions hold their working directory open, which is the lock that made a deleted workspace
432
+ // fail to go away.
433
+ await runtime.disposeSessions?.();
434
+ await serverContext.managedServers?.close();
435
+ // The capabilities die AFTER the sessions that carry them: a session that is still alive could
436
+ // otherwise use a credential the server has already forgotten about.
437
+ releaseAllCapabilities();
438
+ await store.flush();
439
+ wsServer.close();
440
+ httpServer.closeAllConnections();
441
+ await Promise.all([httpClosed, nativeToolsClosed]);
442
+ await store.close();
443
+ })();
444
+ return shutdownPromise;
445
+ }
446
+ process.on("SIGINT", () => { void shutdown("SIGINT").finally(() => process.exit(0)); });
447
+ process.on("SIGTERM", () => { void shutdown("SIGTERM").finally(() => process.exit(0)); });
448
+ // ------------------------------------------------------------- Transports & startup
449
+ const fullPackage = JSON.parse(readFileSync(join(rootDir, "package.json"), "utf8")).name !== "@evandu/super-pi-server";
450
+ if (fullPackage && !process.env.SUPER_PI_MANAGED_CONFIG && process.env.SUPER_PI_DISABLE_MANAGER !== "1") {
451
+ const { ManagedServers } = await import("./managed-servers.js");
452
+ serverContext.managedServers = new ManagedServers(join(dataDir, "manager"), rootDir, () => store.defaultModel());
453
+ await serverContext.managedServers.initialize();
454
+ }
455
+ const httpServer = createHttpServer({ context: serverContext, onShutdown: shutdown, port, host });
456
+ const wsServer = new WsServer({
457
+ httpServer,
458
+ broadcaster,
459
+ commandHandler,
460
+ catalogService,
461
+ accessToken,
462
+ rootDir,
463
+ onSocketClose: sender => terminalService.detach(sender),
464
+ browserAccess: serverContext.browserAccess,
465
+ managedServers: serverContext.managedServers,
466
+ });
467
+ httpServer.listen(port, host, () => {
468
+ const displayHost = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
469
+ console.log(`Super Pi is running at http://${displayHost}:${port}`);
470
+ logging.write("info", `listening on ${host}:${port} (pid ${process.pid})`);
471
+ // THE CLOCK STARTS WITH THE SERVER. A task whose moment passed while the server was down is fired
472
+ // once by the first sweep - the daily report the user asked for is still wanted when they come back,
473
+ // but seven of them are not.
474
+ scheduledTaskService.start();
475
+ if (host === "0.0.0.0" || host === "::") {
476
+ const lanIps = getLanIps();
477
+ for (const ip of lanIps) {
478
+ console.log(` - Network: http://${ip}:${port}`);
479
+ }
480
+ }
481
+ // Stated in the banner rather than left to be discovered, because the terminal is a SHELL and the
482
+ // operator should never have to read the source to find out one is exposed on this machine.
483
+ if (terminalService.enabled)
484
+ console.log(" - Terminal: enabled - the right rail's 终端 tab runs a real shell.");
485
+ });
@@ -0,0 +1,90 @@
1
+ /**
2
+ * THE REASONING A MODEL PUTS INSIDE ITS OWN ANSWER.
3
+ *
4
+ * Some models do not have a reasoning channel. They answer in one stream of text and put their
5
+ * thinking in it, marked up with `<think>…</think>` tags - MiniMax's M2 series is the one this
6
+ * file exists for, and every gateway that proxies it behaves the same way. The tags arrive as
7
+ * ordinary text, so nothing downstream can tell them from an answer.
8
+ *
9
+ * WHY THIS IS SUPER PI'S PROBLEM AND NOT THE USER'S. Pi's OpenAI-compatible adapter only treats
10
+ * `reasoning_content`, `reasoning`, `reasoning_text` and `reasoning_details` as reasoning; it
11
+ * never parses tags out of `content`. A provider that inlines its thinking therefore hands Pi one
12
+ * long text block, Pi hands Super Pi one long text block, and Super Pi would draw the reasoning as
13
+ * part of the answer - in the reader's face, unlabelled, with the tags still in it. The obvious
14
+ * "fix" is to tell the user to go and set a provider-specific switch in Pi's `models.json`, which
15
+ * is a private API of a program Super Pi ships, for a quirk of one vendor. A user who never
16
+ * hears of it sees a broken transcript and has no way to know why.
17
+ *
18
+ * SO THE SPLIT HAPPENS HERE, ON SUPER PI'S OWN SIDE, FOR EVERY PROVIDER. Whatever the endpoint
19
+ * does with its reasoning, the transcript reads the same way: the reasoning goes into a thinking
20
+ * block, the answer goes into the answer, and the tags are never shown to anyone.
21
+ *
22
+ * THE ORDER IS THE WHOLE TRICK. A tag can straddle two deltas - the model writes `</thi` and then
23
+ * `nk>` in the next one - so the splitter holds back the tail that might be the start of a tag
24
+ * until the next delta settles it. And a delta can hold an answer, a thought and another answer,
25
+ * so the splitter returns SEGMENTS IN ORDER rather than "the text" and "the thinking": the caller
26
+ * has to be able to put the answer that came before a thought after it, and has to be able to say
27
+ * where that thought began.
28
+ *
29
+ * THE RULES, because each of them has a case that would otherwise be a bug:
30
+ *
31
+ * - A PROPERLY CLOSED region is reasoning. It leaves the answer and enters the thinking block.
32
+ * - AN UNCLOSED region is reasoning too. The model said it was thinking and then the turn
33
+ * ended - an abort, a truncation, a provider that stopped mid-thought. The reasoning goes
34
+ * into the block, and the answer keeps whatever came before the tag. Nothing is thrown away
35
+ * either way: the fold is expandable, so the words are still there to be read.
36
+ * - A CLOSING TAG WITH NOTHING OPEN is dropped. The model wrote it by mistake, and showing it
37
+ * would be showing a fragment of markup as if it were content.
38
+ * - TEXT IS NEVER LOST. A `<` that turns out not to begin a tag is held for one delta and then
39
+ * released as text, so a comparison like `a < b` survives intact.
40
+ */
41
+ /**
42
+ * One piece of a turn's text, in the order the model wrote it.
43
+ *
44
+ * `thinking-end` is a segment of its own because the end of a reasoning region is a FACT the
45
+ * browser needs and not text: it is what closes the "正在思考" indicator and what tells the
46
+ * transcript that the next fold is a new one.
47
+ */
48
+ export type InlineThinkingSegment = {
49
+ kind: "text";
50
+ text: string;
51
+ } | {
52
+ kind: "thinking";
53
+ text: string;
54
+ } | {
55
+ kind: "thinking-end";
56
+ };
57
+ /**
58
+ * Splits a model's text into the answer and the reasoning the model wrote inside it.
59
+ *
60
+ * ONE SPLITTER PER TURN. The state it keeps - the held-back tail and whether the stream is
61
+ * inside a reasoning region - belongs to a turn and to nothing else, so a splitter is created
62
+ * when a turn starts and dropped when it ends.
63
+ */
64
+ export declare class InlineThinkingSplitter {
65
+ /** The tail that might be the start of a tag, held until the next delta settles it. */
66
+ private held;
67
+ /** True while the stream is inside a reasoning region. */
68
+ private inside;
69
+ /**
70
+ * Feeds one delta in and gets back the segments it produced, in order.
71
+ *
72
+ * A delta that carries nothing but text produces one text segment. A delta that opens a
73
+ * reasoning region produces the text before it, then the reasoning, then the end of the
74
+ * reasoning when the closing tag arrives - and the text after it, if there is any.
75
+ */
76
+ push(delta: string): InlineThinkingSegment[];
77
+ /**
78
+ * Closes the turn: whatever is still held is released, and a reasoning region that never
79
+ * closed is finished as one.
80
+ */
81
+ flush(): InlineThinkingSegment[];
82
+ }
83
+ /**
84
+ * The answer inside a model's text, with the reasoning taken out of it.
85
+ *
86
+ * For the paths that want a STRING rather than a stream of segments: the title generator, the
87
+ * tool LLM, a sub-agent's result. A title with a `<think>` prefix in it is not a title, and a
88
+ * sub-agent's card whose summary starts with markup reads as broken.
89
+ */
90
+ export declare function stripInlineThinking(text: string): string;