@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,83 @@
1
+ /**
2
+ * THE CONTINUATION ORDER: what a session is told when its answer was cut off by the output limit.
3
+ *
4
+ * WHY THIS IS ITS OWN MODULE. Three places have to agree on it: the orchestrator that sends it,
5
+ * the prompt builder that tells the model who is speaking, and the browser that renders the row it
6
+ * becomes. When those three each held their own copy of the wording, a change to one of them left
7
+ * the other two describing a message that was no longer being sent.
8
+ *
9
+ * WHY THE ORDER EXISTS AT ALL. A model that filled its single-response output budget did not fail -
10
+ * it answered, and the answer was cut short. The work it was doing is not over. So the session is
11
+ * asked to carry on, in the SAME conversation, where its own partial answer is already in its
12
+ * context. That is what lets the model resume at the sentence it stopped on instead of starting
13
+ * the answer again.
14
+ *
15
+ * WHY IT IS AN ORDER AND NOT A USER MESSAGE. The person never typed it, and a row under their name
16
+ * saying words they never said is the exact bug this ordering was built to avoid.
17
+ */
18
+ /**
19
+ * THE ENVELOPE A CONTINUATION ORDER TRAVELS IN.
20
+ *
21
+ * The browser renders a `tool` row by looking at the content, and it tells a delivered result
22
+ * (`<task ...>`) from an order (no envelope) by the same inspection. A continuation is neither: it
23
+ * is the system telling the session to keep writing, and it needs a third label - 「续写」 - because
24
+ * calling it a 「智能体下发」 order would say the system sent a task, which is not what happened.
25
+ */
26
+ export declare const LENGTH_CONTINUATION_ENVELOPE = "continue_output";
27
+ /**
28
+ * Maximum number of automatic continuations allowed per task/turn before requiring manual intervention.
29
+ */
30
+ export declare const MAX_LENGTH_CONTINUATIONS = 3;
31
+ /**
32
+ * THE TEXT THE MODEL IS GIVEN.
33
+ *
34
+ * It says two things, and both are needed. "Continue" alone invites a model to start the answer
35
+ * again from the top, because the model cannot tell that the earlier text was already accepted;
36
+ * "do not repeat what you have written" is what makes the continuation an extension rather than a
37
+ * second attempt.
38
+ */
39
+ export declare const LENGTH_CONTINUATION_TEXT = "\u4E0A\u4E00\u6761\u56DE\u7B54\u56E0\u4E3A\u8FBE\u5230\u5355\u6B21\u8F93\u51FA\u7684\u957F\u5EA6\u4E0A\u9650\u88AB\u622A\u65AD\u4E86\u3002\u8BF7\u76F4\u63A5\u4ECE\u88AB\u622A\u65AD\u7684\u5730\u65B9\u63A5\u7740\u5199\u5B8C\uFF0C\u4E0D\u8981\u91CD\u590D\u5DF2\u7ECF\u5199\u8FC7\u7684\u5185\u5BB9\u3002";
40
+ /**
41
+ * THE WHOLE ORDER, ENCLOSED.
42
+ *
43
+ * The envelope is what makes the row recognisable, and it wraps the text so the browser can show
44
+ * the instruction rather than the markup.
45
+ */
46
+ export declare const LENGTH_CONTINUATION_PROMPT = "<continue_output>\u4E0A\u4E00\u6761\u56DE\u7B54\u56E0\u4E3A\u8FBE\u5230\u5355\u6B21\u8F93\u51FA\u7684\u957F\u5EA6\u4E0A\u9650\u88AB\u622A\u65AD\u4E86\u3002\u8BF7\u76F4\u63A5\u4ECE\u88AB\u622A\u65AD\u7684\u5730\u65B9\u63A5\u7740\u5199\u5B8C\uFF0C\u4E0D\u8981\u91CD\u590D\u5DF2\u7ECF\u5199\u8FC7\u7684\u5185\u5BB9\u3002</continue_output>";
47
+ /**
48
+ * Extracts the tail anchor text from truncated assistant content.
49
+ */
50
+ export declare function extractContinuationAnchor(text: string, maxLen?: number): string;
51
+ /**
52
+ * Checks whether text ends inside an unclosed code block (odd number of ```).
53
+ */
54
+ export declare function hasUnclosedCodeBlock(text: string): boolean;
55
+ /**
56
+ * Checks whether text ends inside an unclosed thinking block (<think> without </think>).
57
+ */
58
+ export declare function hasUnclosedThinking(text: string): boolean;
59
+ /**
60
+ * Constructs an intelligent continuation order tailored to the truncation context.
61
+ *
62
+ * When an anchor is available, pointing at the exact cut-off text gives the model an attention
63
+ * anchor and prevents it from freezing or emitting a single polite word.
64
+ */
65
+ export declare function buildLengthContinuationText(assistant?: {
66
+ content?: unknown;
67
+ toolCalls?: unknown[];
68
+ }): string;
69
+ /**
70
+ * Builds the full enclosed continuation prompt with envelope.
71
+ */
72
+ export declare function buildLengthContinuationPrompt(assistant?: {
73
+ content?: unknown;
74
+ toolCalls?: unknown[];
75
+ }): string;
76
+ /**
77
+ * Whether this content is a continuation order.
78
+ */
79
+ export declare function isLengthContinuation(content: string): boolean;
80
+ /**
81
+ * THE TEXT INSIDE THE ENVELOPE, or the content itself when it carries no envelope.
82
+ */
83
+ export declare function lengthContinuationText(content: string): string;
@@ -0,0 +1,118 @@
1
+ /**
2
+ * THE CONTINUATION ORDER: what a session is told when its answer was cut off by the output limit.
3
+ *
4
+ * WHY THIS IS ITS OWN MODULE. Three places have to agree on it: the orchestrator that sends it,
5
+ * the prompt builder that tells the model who is speaking, and the browser that renders the row it
6
+ * becomes. When those three each held their own copy of the wording, a change to one of them left
7
+ * the other two describing a message that was no longer being sent.
8
+ *
9
+ * WHY THE ORDER EXISTS AT ALL. A model that filled its single-response output budget did not fail -
10
+ * it answered, and the answer was cut short. The work it was doing is not over. So the session is
11
+ * asked to carry on, in the SAME conversation, where its own partial answer is already in its
12
+ * context. That is what lets the model resume at the sentence it stopped on instead of starting
13
+ * the answer again.
14
+ *
15
+ * WHY IT IS AN ORDER AND NOT A USER MESSAGE. The person never typed it, and a row under their name
16
+ * saying words they never said is the exact bug this ordering was built to avoid.
17
+ */
18
+ /**
19
+ * THE ENVELOPE A CONTINUATION ORDER TRAVELS IN.
20
+ *
21
+ * The browser renders a `tool` row by looking at the content, and it tells a delivered result
22
+ * (`<task ...>`) from an order (no envelope) by the same inspection. A continuation is neither: it
23
+ * is the system telling the session to keep writing, and it needs a third label - 「续写」 - because
24
+ * calling it a 「智能体下发」 order would say the system sent a task, which is not what happened.
25
+ */
26
+ export const LENGTH_CONTINUATION_ENVELOPE = "continue_output";
27
+ /**
28
+ * Maximum number of automatic continuations allowed per task/turn before requiring manual intervention.
29
+ */
30
+ export const MAX_LENGTH_CONTINUATIONS = 3;
31
+ /**
32
+ * THE TEXT THE MODEL IS GIVEN.
33
+ *
34
+ * It says two things, and both are needed. "Continue" alone invites a model to start the answer
35
+ * again from the top, because the model cannot tell that the earlier text was already accepted;
36
+ * "do not repeat what you have written" is what makes the continuation an extension rather than a
37
+ * second attempt.
38
+ */
39
+ export const LENGTH_CONTINUATION_TEXT = "上一条回答因为达到单次输出的长度上限被截断了。请直接从被截断的地方接着写完,不要重复已经写过的内容。";
40
+ /**
41
+ * THE WHOLE ORDER, ENCLOSED.
42
+ *
43
+ * The envelope is what makes the row recognisable, and it wraps the text so the browser can show
44
+ * the instruction rather than the markup.
45
+ */
46
+ export const LENGTH_CONTINUATION_PROMPT = `<${LENGTH_CONTINUATION_ENVELOPE}>${LENGTH_CONTINUATION_TEXT}</${LENGTH_CONTINUATION_ENVELOPE}>`;
47
+ /**
48
+ * Extracts the tail anchor text from truncated assistant content.
49
+ */
50
+ export function extractContinuationAnchor(text, maxLen = 60) {
51
+ const clean = text.trimEnd();
52
+ if (!clean)
53
+ return "";
54
+ if (clean.length <= maxLen)
55
+ return clean;
56
+ return clean.slice(-maxLen).trimStart();
57
+ }
58
+ /**
59
+ * Checks whether text ends inside an unclosed code block (odd number of ```).
60
+ */
61
+ export function hasUnclosedCodeBlock(text) {
62
+ const matches = text.match(/```/g);
63
+ return Boolean(matches && matches.length % 2 === 1);
64
+ }
65
+ /**
66
+ * Checks whether text ends inside an unclosed thinking block (<think> without </think>).
67
+ */
68
+ export function hasUnclosedThinking(text) {
69
+ const opens = (text.match(/<think>/g) || []).length;
70
+ const closes = (text.match(/<\/think>/g) || []).length;
71
+ return opens > closes;
72
+ }
73
+ /**
74
+ * Constructs an intelligent continuation order tailored to the truncation context.
75
+ *
76
+ * When an anchor is available, pointing at the exact cut-off text gives the model an attention
77
+ * anchor and prevents it from freezing or emitting a single polite word.
78
+ */
79
+ export function buildLengthContinuationText(assistant) {
80
+ if (!assistant)
81
+ return LENGTH_CONTINUATION_TEXT;
82
+ // Case 1: truncation happened inside tool call arguments
83
+ if (Array.isArray(assistant.toolCalls) && assistant.toolCalls.length > 0) {
84
+ const rawContent = typeof assistant.content === "string" ? assistant.content.trim() : "";
85
+ if (!rawContent || rawContent.length < 20) {
86
+ return "上一次工具调用因参数超出单次长度上限未完整执行。请将写入或修改操作拆分为更小的批次(如使用分块写入或局部编辑模式)重新发起调用。";
87
+ }
88
+ }
89
+ // Case 2: textual output
90
+ const content = typeof assistant.content === "string" ? assistant.content : "";
91
+ const anchor = extractContinuationAnchor(content);
92
+ if (!anchor)
93
+ return LENGTH_CONTINUATION_TEXT;
94
+ if (hasUnclosedCodeBlock(content)) {
95
+ return `上一条代码因为达到单次输出上限在以下断点处被截断:\n\`\`\`\n${anchor}\n\`\`\`\n请直接紧接上述断点继续写完后续代码并闭合代码块,严禁寒暄,不要重复断点之前已经写过的代码。`;
96
+ }
97
+ return `上一条回答因为达到单次输出上限在以下内容处被截断:\n"${anchor}"\n请直接紧接上述断点继续写完,严禁客套寒暄,不要重复断点之前的内容。`;
98
+ }
99
+ /**
100
+ * Builds the full enclosed continuation prompt with envelope.
101
+ */
102
+ export function buildLengthContinuationPrompt(assistant) {
103
+ const text = buildLengthContinuationText(assistant);
104
+ return `<${LENGTH_CONTINUATION_ENVELOPE}>${text}</${LENGTH_CONTINUATION_ENVELOPE}>`;
105
+ }
106
+ /**
107
+ * Whether this content is a continuation order.
108
+ */
109
+ export function isLengthContinuation(content) {
110
+ return content.includes(`<${LENGTH_CONTINUATION_ENVELOPE}>`);
111
+ }
112
+ /**
113
+ * THE TEXT INSIDE THE ENVELOPE, or the content itself when it carries no envelope.
114
+ */
115
+ export function lengthContinuationText(content) {
116
+ const match = new RegExp(`<${LENGTH_CONTINUATION_ENVELOPE}>([\\s\\S]*?)</${LENGTH_CONTINUATION_ENVELOPE}>`).exec(content);
117
+ return match ? match[1].trim() : content.trim();
118
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * THE SERVER'S OWN LOG FILE.
3
+ *
4
+ * Super Pi is started DETACHED, with its standard streams thrown away (`stdio: "ignore"`), because
5
+ * the person who started it is usually gone by the time it matters - the panel runs in a browser tab
6
+ * and the server lives on behind it. The cost of that decision was that when the server DIED, it
7
+ * died silently: the browser sat there saying "connecting" and nobody could say why. A log file is
8
+ * the cheapest possible answer to "how did it die".
9
+ *
10
+ * Two properties matter more than volume here:
11
+ *
12
+ * - EVERY LINE IS WRITTEN SYNCHRONOUSLY. A buffered stream loses exactly the lines you want - the
13
+ * ones written a millisecond before the crash - because the buffer is still in memory when the
14
+ * process dies. `appendFileSync` costs a syscall per line, which is nothing at this volume, and
15
+ * it costs the line that matters.
16
+ * - THE CRASH IS LOGGED BEFORE THE PROCESS LEAVES. `uncaughtException` and `unhandledRejection` are
17
+ * the two ways a Node process dies without saying anything, and both are turned into a stack trace
18
+ * in the log file.
19
+ */
20
+ export declare const SERVER_LOG_NAME = "server.log";
21
+ export interface ServerLogging {
22
+ /** Absolute path of the log file this server writes to. */
23
+ readonly logFile: string;
24
+ /** Absolute path of the liveness file; its timestamp says when the server was last alive. */
25
+ readonly heartbeatFile: string;
26
+ /** Append one line to the log file, independently of the console. */
27
+ write(level: string, message: string): void;
28
+ }
29
+ /**
30
+ * Install the file logger. Returns the handle so the caller can write lines the console never sees.
31
+ */
32
+ export declare function installServerLogging(dataDir: string): ServerLogging;
@@ -0,0 +1,185 @@
1
+ import { appendFileSync, existsSync, mkdirSync, renameSync, statSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ /**
4
+ * THE SERVER'S OWN LOG FILE.
5
+ *
6
+ * Super Pi is started DETACHED, with its standard streams thrown away (`stdio: "ignore"`), because
7
+ * the person who started it is usually gone by the time it matters - the panel runs in a browser tab
8
+ * and the server lives on behind it. The cost of that decision was that when the server DIED, it
9
+ * died silently: the browser sat there saying "connecting" and nobody could say why. A log file is
10
+ * the cheapest possible answer to "how did it die".
11
+ *
12
+ * Two properties matter more than volume here:
13
+ *
14
+ * - EVERY LINE IS WRITTEN SYNCHRONOUSLY. A buffered stream loses exactly the lines you want - the
15
+ * ones written a millisecond before the crash - because the buffer is still in memory when the
16
+ * process dies. `appendFileSync` costs a syscall per line, which is nothing at this volume, and
17
+ * it costs the line that matters.
18
+ * - THE CRASH IS LOGGED BEFORE THE PROCESS LEAVES. `uncaughtException` and `unhandledRejection` are
19
+ * the two ways a Node process dies without saying anything, and both are turned into a stack trace
20
+ * in the log file.
21
+ */
22
+ export const SERVER_LOG_NAME = "server.log";
23
+ /** Kept small enough to open by eye; the previous file is kept as `server.log.1`. */
24
+ const MAX_LOG_BYTES = 8 * 1024 * 1024;
25
+ function format(level, message) {
26
+ const time = new Date().toISOString();
27
+ // A multi-line message (a stack trace) stays one entry per line, each carrying the same stamp, so
28
+ // that a `tail` still shows where it started.
29
+ return message
30
+ .split("\n")
31
+ .map((line) => `[${time}] [${level}] ${line}`)
32
+ .join("\n");
33
+ }
34
+ function rotateIfLarge(logFile) {
35
+ try {
36
+ if (!existsSync(logFile))
37
+ return;
38
+ if (statSync(logFile).size < MAX_LOG_BYTES)
39
+ return;
40
+ const previous = `${logFile}.1`;
41
+ try {
42
+ renameSync(previous, `${previous}.old`);
43
+ }
44
+ catch { /* no previous file: fine */ }
45
+ renameSync(logFile, previous);
46
+ }
47
+ catch {
48
+ // Rotation is best-effort: a log file that cannot be rotated must not stop the server from
49
+ // starting, and must not stop it from logging.
50
+ }
51
+ }
52
+ /**
53
+ * Install the file logger. Returns the handle so the caller can write lines the console never sees.
54
+ */
55
+ export function installServerLogging(dataDir) {
56
+ const logDir = join(dataDir, "logs");
57
+ try {
58
+ mkdirSync(logDir, { recursive: true });
59
+ }
60
+ catch { /* the write below will report the real problem */ }
61
+ const logFile = join(logDir, SERVER_LOG_NAME);
62
+ rotateIfLarge(logFile);
63
+ /**
64
+ * THE LIVENESS FILE.
65
+ *
66
+ * A log file says what the server said; it cannot say when the server STOPPED, because the lines
67
+ * it would have written to say that are exactly the ones a crash takes away. A native crash (the
68
+ * kind that comes from a terminal being killed) never runs a JavaScript handler at all, so the
69
+ * server cannot even write "I died". This file answers the other half of the question: it is
70
+ * touched every minute while the server lives, so its timestamp says "the server was alive until
71
+ * this moment" - which is how a silent death gets a time on it.
72
+ *
73
+ * IT ALSO CARRIES THE MEMORY FINGERPRINT, because "the server died without a word" has two very
74
+ * different causes and they need different answers. A server killed by the operating system's OOM
75
+ * killer leaves a log that ends mid-sentence and nothing else - the kernel does not run JavaScript,
76
+ * and the message Node prints about a heap it could not grow goes to a standard error stream this
77
+ * process was started without. The last heartbeat before the silence is the only record of how much
78
+ * memory the process was holding when it went, so it says: the resident size, the heap in use and
79
+ * the heap that had been reserved. A death at 2 GB of resident size is a memory story; a death at
80
+ * 90 MB is something else.
81
+ */
82
+ const heartbeatFile = join(logDir, "heartbeat.txt");
83
+ const touch = () => {
84
+ try {
85
+ const memory = process.memoryUsage();
86
+ const mb = (bytes) => Math.round(bytes / 1_048_576);
87
+ writeFileSync(heartbeatFile, `${Date.now()} rss=${mb(memory.rss)}MB heapUsed=${mb(memory.heapUsed)}MB heapTotal=${mb(memory.heapTotal)}MB external=${mb(memory.external)}MB\n`, "utf8");
88
+ }
89
+ catch { /* best effort */ }
90
+ };
91
+ touch();
92
+ const heartbeat = setInterval(touch, 60_000);
93
+ // The heartbeat must not be the reason the process stays alive.
94
+ heartbeat.unref?.();
95
+ const write = (level, message) => {
96
+ try {
97
+ appendFileSync(logFile, `${format(level, message)}\n`, "utf8");
98
+ }
99
+ catch { /* never let logging crash the server */ }
100
+ };
101
+ // CONSOLE OUTPUT IS TEED INTO THE FILE, NOT REPLACED BY IT.
102
+ //
103
+ // Everything the server already prints (the banner, warnings from the services, the shutdown
104
+ // notice) is worth keeping, and the cheapest way to keep it is to keep printing it and copy it.
105
+ // A service that logs through `console.warn` gets into the file for free.
106
+ const levels = ["log", "info", "warn", "error", "debug"];
107
+ const originals = new Map();
108
+ for (const level of levels) {
109
+ const original = console[level];
110
+ originals.set(level, original);
111
+ console[level] = (...args) => {
112
+ original.apply(console, args);
113
+ write(level === "log" ? "info" : level, args.map((arg) => (typeof arg === "string" ? arg : safeStringify(arg))).join(" "));
114
+ };
115
+ }
116
+ /**
117
+ * THE TWO WAYS A NODE PROCESS DIES WITHOUT A WORD.
118
+ *
119
+ * `uncaughtException` is a throw nobody caught; `unhandledRejection` is a promise nobody awaited.
120
+ * Both used to take the server down silently. Both now write the stack and then end the process -
121
+ * for `uncaughtException` continuing is not safe, because the process state after an uncaught
122
+ * exception is undefined.
123
+ */
124
+ process.on("uncaughtException", (error) => {
125
+ write("fatal", `uncaughtException: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`);
126
+ process.exit(1);
127
+ });
128
+ /**
129
+ * AN UNHANDLED REJECTION IS NOT FATAL, AND THE WORD MATTERS.
130
+ *
131
+ * Node hands an unhandled rejection to this hook and KEEPS RUNNING - the process does not die here.
132
+ * It was logged as `fatal` anyway, which made every one of them read like a crash report. One user
133
+ * report of "Super Pi crashed" turned out to be exactly this: a promise nobody was awaiting,
134
+ * refusing a path, once per agent write - and the log's `fatal` line is what made it look like the
135
+ * server had died.
136
+ *
137
+ * The line stays loud, because an unhandled rejection IS a bug - a promise that rejected with nobody
138
+ * listening - but it now says what actually happened, so the next reader is not sent looking for a
139
+ * dead process that is still alive.
140
+ */
141
+ process.on("unhandledRejection", (reason) => {
142
+ write("error", `unhandledRejection (the process is still running; a promise rejected with nobody listening): ${reason instanceof Error ? (reason.stack ?? reason.message) : String(reason)}`);
143
+ });
144
+ process.on("exit", (code) => {
145
+ write("info", `server process exiting with code ${code}`);
146
+ });
147
+ return { logFile, heartbeatFile, write };
148
+ }
149
+ function safeStringify(value) {
150
+ // JSON.stringify(new Error("boom")) is `{}` because Error's useful fields are
151
+ // non-enumerable. That used to erase the only clue in a detached server's log
152
+ // whenever a service did `console.error(error)`. Keep the diagnostic shape
153
+ // explicit and handle the other values that commonly make logging itself throw
154
+ // (cycles and BigInt).
155
+ if (value instanceof Error)
156
+ return value.stack ?? `${value.name}: ${value.message}`;
157
+ if (value === undefined)
158
+ return "undefined";
159
+ if (value === null)
160
+ return "null";
161
+ if (typeof value === "string")
162
+ return value;
163
+ if (typeof value === "bigint")
164
+ return `${value}n`;
165
+ try {
166
+ const seen = new WeakSet();
167
+ const text = JSON.stringify(value, (_key, nested) => {
168
+ if (nested instanceof Error) {
169
+ return { name: nested.name, message: nested.message, stack: nested.stack, cause: nested.cause };
170
+ }
171
+ if (typeof nested === "bigint")
172
+ return `${nested}n`;
173
+ if (nested && typeof nested === "object") {
174
+ if (seen.has(nested))
175
+ return "[Circular]";
176
+ seen.add(nested);
177
+ }
178
+ return nested;
179
+ });
180
+ return text ?? String(value);
181
+ }
182
+ catch {
183
+ return String(value);
184
+ }
185
+ }
@@ -0,0 +1,6 @@
1
+ import { type IncomingMessage, type ServerResponse } from "node:http";
2
+ import type { Duplex } from "node:stream";
3
+ import type { Client } from "ssh2";
4
+ export declare function tunnelJson(client: Client, port: number, path: string, key: string, method?: string): Promise<any>;
5
+ export declare function proxyThroughSsh(client: Client, port: number, key: string, path: string, request: IncomingMessage, response: ServerResponse, basePath?: string): void;
6
+ export declare function proxyWebSocketThroughSsh(client: Client, port: number, key: string, path: string, request: IncomingMessage, socket: Duplex, head: Buffer): Promise<void>;
@@ -0,0 +1,85 @@
1
+ import { request as httpRequest, Agent } from "node:http";
2
+ import { sshForward } from "./managed-ssh.js";
3
+ function headers(input, port, key) {
4
+ const next = { ...input, host: `127.0.0.1:${port}`, authorization: `Bearer ${key}` };
5
+ delete next.cookie;
6
+ // Only an upstream owner credential travels through the private SSH channel.
7
+ delete next["sec-websocket-protocol"];
8
+ return next;
9
+ }
10
+ function agentFor(client, port) {
11
+ const agent = new Agent({ keepAlive: false });
12
+ agent.createConnection = ((_options, callback) => {
13
+ void sshForward(client, port).then(channel => {
14
+ const socket = channel;
15
+ for (const method of ["setKeepAlive", "setNoDelay", "setTimeout", "ref", "unref"])
16
+ socket[method] = () => channel;
17
+ socket.destroySoon = channel.destroy.bind(channel);
18
+ callback(null, channel);
19
+ }, error => callback(error));
20
+ return undefined;
21
+ });
22
+ return agent;
23
+ }
24
+ export async function tunnelJson(client, port, path, key, method = "GET") {
25
+ return new Promise((resolve, reject) => {
26
+ const agent = agentFor(client, port);
27
+ const request = httpRequest({ hostname: "127.0.0.1", port, path, method, agent, headers: { authorization: `Bearer ${key}` } }, response => {
28
+ let text = "";
29
+ response.setEncoding("utf8");
30
+ response.on("data", chunk => { text += chunk; if (text.length > 8 * 1024 * 1024)
31
+ request.destroy(); });
32
+ response.once("end", () => { agent.destroy(); try {
33
+ if ((response.statusCode ?? 500) >= 400)
34
+ throw new Error();
35
+ resolve(JSON.parse(text));
36
+ }
37
+ catch {
38
+ reject(new Error(`远端服务未返回有效状态(${response.statusCode})`));
39
+ } });
40
+ });
41
+ const timeout = setTimeout(() => request.destroy(new Error("远端服务响应超时")), 12_000);
42
+ request.once("close", () => clearTimeout(timeout));
43
+ request.once("error", () => { agent.destroy(); reject(new Error("SSH 已连接,但远端 Super Pi 服务不可达")); });
44
+ request.end();
45
+ });
46
+ }
47
+ export function proxyThroughSsh(client, port, key, path, request, response, basePath = "") {
48
+ const agent = agentFor(client, port);
49
+ const upstream = httpRequest({ hostname: "127.0.0.1", port, method: request.method, path, headers: headers(request.headers, port, key), agent }, result => {
50
+ const outgoing = { ...result.headers };
51
+ delete outgoing["set-cookie"];
52
+ // The trusted artifact wrapper uses an origin-root URL; keep its inner frame on this backend.
53
+ if (basePath && path.startsWith("/api/message-artifact?") && new URL(path, "http://localhost").searchParams.has("frame") && String(outgoing["content-type"]).startsWith("text/html")) {
54
+ delete outgoing["content-length"];
55
+ let html = "";
56
+ result.setEncoding("utf8");
57
+ result.on("data", chunk => { html += chunk; if (html.length > 1024 * 1024)
58
+ result.destroy(); });
59
+ result.once("end", () => { response.writeHead(result.statusCode ?? 502, outgoing).end(html.replaceAll('src="/api/message-artifact', `src="${basePath}/api/message-artifact`)); agent.destroy(); });
60
+ return;
61
+ }
62
+ response.writeHead(result.statusCode ?? 502, outgoing);
63
+ result.pipe(response);
64
+ result.once("end", () => agent.destroy());
65
+ });
66
+ upstream.once("error", () => { agent.destroy(); if (!response.headersSent)
67
+ response.writeHead(502, { "content-type": "application/json" }).end(JSON.stringify({ error: "SSH 隧道暂不可用,正在恢复连接" }));
68
+ else
69
+ response.destroy(); });
70
+ response.once("close", () => { upstream.destroy(); agent.destroy(); });
71
+ request.pipe(upstream);
72
+ }
73
+ export async function proxyWebSocketThroughSsh(client, port, key, path, request, socket, head) {
74
+ const channel = await sshForward(client, port);
75
+ const outgoing = headers(request.headers, port, key);
76
+ channel.write(`GET ${path} HTTP/1.1\r\n${Object.entries(outgoing).filter(([, value]) => value !== undefined).map(([name, value]) => `${name}: ${Array.isArray(value) ? value.join(", ") : value}`).join("\r\n")}\r\n\r\n`);
77
+ if (head.length)
78
+ channel.write(head);
79
+ channel.pipe(socket);
80
+ socket.pipe(channel);
81
+ socket.once("close", () => channel.close());
82
+ channel.once("close", () => socket.destroy());
83
+ channel.once("error", () => socket.destroy());
84
+ socket.once("error", () => channel.close());
85
+ }
@@ -0,0 +1,4 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import type { ServerContext } from "./server-context.js";
3
+ /** A model-channel token is deliberately never accepted by these management routes. */
4
+ export declare function handleManagedHttp(context: ServerContext, request: IncomingMessage, response: ServerResponse, url: URL): Promise<boolean>;
@@ -0,0 +1,85 @@
1
+ import { isBrowserAuthorized } from "./browser-access.js";
2
+ import { isLoopbackAddress } from "./http-server.js";
3
+ /** A model-channel token is deliberately never accepted by these management routes. */
4
+ export async function handleManagedHttp(context, request, response, url) {
5
+ const route = url.pathname === "/api/managed-servers";
6
+ const proxy = /^\/managed\/([a-f0-9-]+)(\/.*)$/.exec(url.pathname);
7
+ if (!route && !proxy && url.pathname !== "/api/managed-model/reload")
8
+ return false;
9
+ const json = (status, value) => { response.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }).end(JSON.stringify(value)); };
10
+ if (url.pathname === "/api/managed-model/reload") {
11
+ if (!process.env.SUPER_PI_MANAGED_CONFIG) {
12
+ json(404, { error: "当前服务未由本地入口托管" });
13
+ return true;
14
+ }
15
+ if (!isBrowserAuthorized(request) || request.method !== "POST") {
16
+ json(403, { error: "需要托管服务的管理授权" });
17
+ return true;
18
+ }
19
+ context.runtime.invalidateCatalog?.();
20
+ context.runtime.bumpModelEpoch?.();
21
+ await context.catalogService.broadcastAllCatalog();
22
+ for (const conversation of context.store.snapshot().conversations)
23
+ if (!conversation.archivedAt)
24
+ await context.catalogService.broadcastCatalog(conversation.model, conversation.id);
25
+ json(200, { ok: true });
26
+ return true;
27
+ }
28
+ if (!context.managedServers) {
29
+ json(404, { available: false, error: "此纯服务安装不提供 SSH 管理,请在完整包的本地入口中配置" });
30
+ return true;
31
+ }
32
+ if (!isBrowserAuthorized(request) && (!isLoopbackAddress(request.socket.remoteAddress) || (request.headers.origin && request.headers.origin !== url.origin))) {
33
+ json(403, { error: "SSH 托管设置仅允许本地入口或已授权的管理浏览器访问" });
34
+ return true;
35
+ }
36
+ if (proxy) {
37
+ const path = proxy[2] + url.search;
38
+ if (!path.startsWith("/api/") && !path.startsWith("/tools/")) {
39
+ json(404, { error: "不支持的托管资源路径" });
40
+ return true;
41
+ }
42
+ context.managedServers.proxy(proxy[1], path, request, response);
43
+ return true;
44
+ }
45
+ const status = () => ({ available: true, profiles: context.managedServers.list(), connections: context.managedServers.connectionProfiles(), modelSource: "entry" });
46
+ if (request.method === "GET") {
47
+ json(200, status());
48
+ return true;
49
+ }
50
+ if (request.method !== "POST") {
51
+ json(405, { error: "仅支持 GET/POST" });
52
+ return true;
53
+ }
54
+ let text = "";
55
+ for await (const chunk of request) {
56
+ text += chunk;
57
+ if (text.length > 1024 * 1024) {
58
+ json(413, { error: "SSH 配置过大" });
59
+ return true;
60
+ }
61
+ }
62
+ try {
63
+ const body = JSON.parse(text);
64
+ if (body.action === "save") {
65
+ await context.managedServers.save(body.profile);
66
+ }
67
+ else if (body.action === "trust")
68
+ await context.managedServers.trust(body.id, body.fingerprint);
69
+ else if (body.action === "syncAll") {
70
+ for (const profile of context.managedServers.list())
71
+ if (profile.enabled && profile.service === "online")
72
+ await context.managedServers.action(profile.id, "sync");
73
+ }
74
+ else {
75
+ if (typeof body.id !== "string")
76
+ throw new Error("请选择服务器");
77
+ await context.managedServers.action(body.id, body.action);
78
+ }
79
+ json(200, status());
80
+ }
81
+ catch (cause) {
82
+ json(400, { ...status(), error: cause instanceof Error ? cause.message : "服务器托管操作失败" });
83
+ }
84
+ return true;
85
+ }
@@ -0,0 +1,17 @@
1
+ import type { Model } from "@earendil-works/pi-ai";
2
+ export interface ManagedModelConfig {
3
+ endpoint: string;
4
+ token: string;
5
+ models: Model<string>[];
6
+ defaultModel?: {
7
+ provider: string;
8
+ modelId: string;
9
+ };
10
+ }
11
+ export declare function readManagedModelConfig(): Promise<ManagedModelConfig | undefined>;
12
+ /** Both embedded sessions and isolated Pi processes register the same transport-only providers. */
13
+ export declare function managedProviderDefinitions(config: ManagedModelConfig): Promise<{
14
+ id: string;
15
+ provider: import("@earendil-works/pi-ai").Provider<string>;
16
+ }[]>;
17
+ export declare function installManagedModels(runtime: unknown): Promise<void>;