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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (370) hide show
  1. package/README.md +248 -3
  2. package/agents/code-auditor.md +64 -0
  3. package/agents/code-designer.md +64 -0
  4. package/agents/coder.md +24 -0
  5. package/agents/critic.md +24 -0
  6. package/agents/document-organizer.md +48 -0
  7. package/agents/patcher.md +27 -0
  8. package/agents/planner.md +30 -0
  9. package/agents/project-leader.md +28 -0
  10. package/agents/reviewer.md +27 -0
  11. package/agents/scout.md +27 -0
  12. package/agents/solution-designer.md +62 -0
  13. package/agents/super-pi-documents/index.ts +92 -0
  14. package/agents/super-pi-feishu/index.ts +88 -0
  15. package/agents/super-pi-knowledge/index.ts +70 -0
  16. package/agents/super-pi-managed-model/index.ts +9 -0
  17. package/agents/super-pi-memory/index.ts +75 -0
  18. package/agents/super-pi-native-tools/index.ts +1 -0
  19. package/agents/super-pi-task/core.ts +2262 -0
  20. package/agents/super-pi-task/index.ts +814 -0
  21. package/agents/super-pi-task/workflow-schema.ts +34 -0
  22. package/agents/super-pi-web/index.ts +32 -0
  23. package/agents/verifier.md +25 -0
  24. package/assets/fonts/LICENSE +92 -0
  25. package/assets/fonts/NotoSansSC-Bold.otf +0 -0
  26. package/assets/fonts/NotoSansSC-Regular.otf +0 -0
  27. package/assets/knowledge-model/README.md +37 -0
  28. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/config.json +31 -0
  29. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/onnx/model_quantized.onnx +0 -0
  30. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/special_tokens_map.json +7 -0
  31. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer.json +21278 -0
  32. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer_config.json +15 -0
  33. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/vocab.txt +21128 -0
  34. package/bin/npm-prefix.d.ts +1 -0
  35. package/bin/npm-prefix.js +10 -0
  36. package/bin/super-pi.js +349 -0
  37. package/dist/client/.super-pi-client-sources.json +82 -0
  38. package/dist/client/assets/CodeMirrorEditor-mi9rGUce.js +2 -0
  39. package/dist/client/assets/GitDiffEditor-CpoDDQrA.css +1 -0
  40. package/dist/client/assets/GitDiffEditor-FQBfGxOY.js +29 -0
  41. package/dist/client/assets/diff-ChtP43wD.js +1 -0
  42. package/dist/client/assets/dist-AW5lyI3I.js +1 -0
  43. package/dist/client/assets/dist-B3-a6uF0.js +7 -0
  44. package/dist/client/assets/dist-BGxkyh6e.js +1 -0
  45. package/dist/client/assets/dist-BJxfd7yb.js +11 -0
  46. package/dist/client/assets/dist-BRVQKlcp.js +1 -0
  47. package/dist/client/assets/dist-BV64A9Ji.js +1 -0
  48. package/dist/client/assets/dist-BXAOrsjq.js +1 -0
  49. package/dist/client/assets/dist-CKF2Jksy.js +1 -0
  50. package/dist/client/assets/dist-CX_Hm4GS.js +1 -0
  51. package/dist/client/assets/dist-Cus6_oaF.js +2 -0
  52. package/dist/client/assets/dist-Cx00EZKR.js +23 -0
  53. package/dist/client/assets/dist-D71y2EI1.js +1 -0
  54. package/dist/client/assets/dist-D978o95T.js +5 -0
  55. package/dist/client/assets/dist-Dc1MBGAG.js +1 -0
  56. package/dist/client/assets/dist-Dds-qLxY.js +9 -0
  57. package/dist/client/assets/dist-DeD9copn.js +1 -0
  58. package/dist/client/assets/dist-DuvGReu-.js +6 -0
  59. package/dist/client/assets/dist-Dvb0SqcK.js +2 -0
  60. package/dist/client/assets/dist-J6XWqRpB.js +3 -0
  61. package/dist/client/assets/dist-QzbOCAU6.js +1 -0
  62. package/dist/client/assets/dist-moiMRpw_.js +1 -0
  63. package/dist/client/assets/dist-scBkrwv-.js +2 -0
  64. package/dist/client/assets/dockerfile-BDePf5PZ.js +1 -0
  65. package/dist/client/assets/index-Cn7hdrDw.js +350 -0
  66. package/dist/client/assets/index-UfzqdECL.css +1 -0
  67. package/dist/client/assets/powershell-D8WpQPaX.js +1 -0
  68. package/dist/client/assets/properties-C357ku5U.js +1 -0
  69. package/dist/client/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  70. package/dist/client/assets/ruby-ChfNwlCY.js +1 -0
  71. package/dist/client/assets/shell-DwuoZtxw.js +1 -0
  72. package/dist/client/assets/swift-DKB6_1j6.js +1 -0
  73. package/dist/client/assets/toml-BPTmHmyx.js +1 -0
  74. package/dist/client/favicon.ico +0 -0
  75. package/dist/client/favicon.png +0 -0
  76. package/dist/client/favicon.svg +10 -0
  77. package/dist/client/index.html +18 -0
  78. package/dist/extension.d.ts +15 -0
  79. package/dist/extension.js +126 -0
  80. package/dist/server/active-memory.d.ts +247 -0
  81. package/dist/server/active-memory.js +669 -0
  82. package/dist/server/agents.d.ts +245 -0
  83. package/dist/server/agents.js +701 -0
  84. package/dist/server/application/catalog-service.d.ts +98 -0
  85. package/dist/server/application/catalog-service.js +245 -0
  86. package/dist/server/application/conversation-service.d.ts +245 -0
  87. package/dist/server/application/conversation-service.js +654 -0
  88. package/dist/server/application/document-service.d.ts +68 -0
  89. package/dist/server/application/document-service.js +120 -0
  90. package/dist/server/application/extension-ui-service.d.ts +44 -0
  91. package/dist/server/application/extension-ui-service.js +135 -0
  92. package/dist/server/application/feishu-service.d.ts +179 -0
  93. package/dist/server/application/feishu-service.js +358 -0
  94. package/dist/server/application/group-chat-service.d.ts +75 -0
  95. package/dist/server/application/group-chat-service.js +953 -0
  96. package/dist/server/application/group-execution.d.ts +15 -0
  97. package/dist/server/application/group-execution.js +77 -0
  98. package/dist/server/application/project-service.d.ts +464 -0
  99. package/dist/server/application/project-service.js +2523 -0
  100. package/dist/server/application/provider-service.d.ts +174 -0
  101. package/dist/server/application/provider-service.js +510 -0
  102. package/dist/server/application/run-service.d.ts +547 -0
  103. package/dist/server/application/run-service.js +2683 -0
  104. package/dist/server/application/scheduled-task-service.d.ts +184 -0
  105. package/dist/server/application/scheduled-task-service.js +391 -0
  106. package/dist/server/application/session-orchestrator-service.d.ts +388 -0
  107. package/dist/server/application/session-orchestrator-service.js +1146 -0
  108. package/dist/server/application/session-reminder-service.d.ts +59 -0
  109. package/dist/server/application/session-reminder-service.js +141 -0
  110. package/dist/server/application/session-watchdog.d.ts +171 -0
  111. package/dist/server/application/session-watchdog.js +284 -0
  112. package/dist/server/application/workspace-service.d.ts +52 -0
  113. package/dist/server/application/workspace-service.js +186 -0
  114. package/dist/server/application/worktree-service.d.ts +13 -0
  115. package/dist/server/application/worktree-service.js +76 -0
  116. package/dist/server/browser-access.d.ts +34 -0
  117. package/dist/server/browser-access.js +89 -0
  118. package/dist/server/capability.d.ts +105 -0
  119. package/dist/server/capability.js +170 -0
  120. package/dist/server/command-handler.d.ts +93 -0
  121. package/dist/server/command-handler.js +540 -0
  122. package/dist/server/content-search.d.ts +16 -0
  123. package/dist/server/content-search.js +235 -0
  124. package/dist/server/conversation-usage.d.ts +22 -0
  125. package/dist/server/conversation-usage.js +43 -0
  126. package/dist/server/documents.d.ts +152 -0
  127. package/dist/server/documents.js +998 -0
  128. package/dist/server/engineering-learning.d.ts +30 -0
  129. package/dist/server/engineering-learning.js +106 -0
  130. package/dist/server/exec-service.d.ts +45 -0
  131. package/dist/server/exec-service.js +167 -0
  132. package/dist/server/explicit-file-open.d.ts +34 -0
  133. package/dist/server/explicit-file-open.js +105 -0
  134. package/dist/server/failure-text.d.ts +18 -0
  135. package/dist/server/failure-text.js +44 -0
  136. package/dist/server/feishu-cli.d.ts +223 -0
  137. package/dist/server/feishu-cli.js +464 -0
  138. package/dist/server/file-changes.d.ts +119 -0
  139. package/dist/server/file-changes.js +280 -0
  140. package/dist/server/file-diff.d.ts +41 -0
  141. package/dist/server/file-diff.js +97 -0
  142. package/dist/server/file-index.d.ts +100 -0
  143. package/dist/server/file-index.js +296 -0
  144. package/dist/server/file-name-index.d.ts +160 -0
  145. package/dist/server/file-name-index.js +411 -0
  146. package/dist/server/files.d.ts +269 -0
  147. package/dist/server/files.js +748 -0
  148. package/dist/server/git.d.ts +245 -0
  149. package/dist/server/git.js +903 -0
  150. package/dist/server/http-server.d.ts +45 -0
  151. package/dist/server/http-server.js +3830 -0
  152. package/dist/server/index.d.ts +1 -0
  153. package/dist/server/index.js +485 -0
  154. package/dist/server/inline-thinking.d.ts +90 -0
  155. package/dist/server/inline-thinking.js +181 -0
  156. package/dist/server/json-comments.d.ts +14 -0
  157. package/dist/server/json-comments.js +71 -0
  158. package/dist/server/knowledge-embedding-worker.d.ts +1 -0
  159. package/dist/server/knowledge-embedding-worker.js +27 -0
  160. package/dist/server/knowledge-vectors.d.ts +150 -0
  161. package/dist/server/knowledge-vectors.js +385 -0
  162. package/dist/server/knowledge.d.ts +273 -0
  163. package/dist/server/knowledge.js +848 -0
  164. package/dist/server/length-continuation.d.ts +83 -0
  165. package/dist/server/length-continuation.js +118 -0
  166. package/dist/server/logging.d.ts +32 -0
  167. package/dist/server/logging.js +185 -0
  168. package/dist/server/managed-http-tunnel.d.ts +6 -0
  169. package/dist/server/managed-http-tunnel.js +85 -0
  170. package/dist/server/managed-http.d.ts +4 -0
  171. package/dist/server/managed-http.js +85 -0
  172. package/dist/server/managed-model-adapter.d.ts +17 -0
  173. package/dist/server/managed-model-adapter.js +75 -0
  174. package/dist/server/managed-model-gateway.d.ts +49 -0
  175. package/dist/server/managed-model-gateway.js +73 -0
  176. package/dist/server/managed-servers.d.ts +55 -0
  177. package/dist/server/managed-servers.js +392 -0
  178. package/dist/server/managed-ssh.d.ts +26 -0
  179. package/dist/server/managed-ssh.js +73 -0
  180. package/dist/server/manager-vault.d.ts +11 -0
  181. package/dist/server/manager-vault.js +67 -0
  182. package/dist/server/memory-recall.d.ts +25 -0
  183. package/dist/server/memory-recall.js +45 -0
  184. package/dist/server/memory.d.ts +67 -0
  185. package/dist/server/memory.js +216 -0
  186. package/dist/server/message-media.d.ts +7 -0
  187. package/dist/server/message-media.js +54 -0
  188. package/dist/server/model-context-window.d.ts +186 -0
  189. package/dist/server/model-context-window.js +444 -0
  190. package/dist/server/model-filter.d.ts +23 -0
  191. package/dist/server/model-filter.js +48 -0
  192. package/dist/server/models-store.d.ts +36 -0
  193. package/dist/server/models-store.js +132 -0
  194. package/dist/server/native-tool-settings.d.ts +25 -0
  195. package/dist/server/native-tool-settings.js +41 -0
  196. package/dist/server/native-tools-extension.d.ts +2 -0
  197. package/dist/server/native-tools-extension.js +39 -0
  198. package/dist/server/native-tools-service.d.ts +39 -0
  199. package/dist/server/native-tools-service.js +240 -0
  200. package/dist/server/persistence/app-state-repository.d.ts +65 -0
  201. package/dist/server/persistence/app-state-repository.js +1 -0
  202. package/dist/server/persistence/json-state-repository.d.ts +14 -0
  203. package/dist/server/persistence/json-state-repository.js +43 -0
  204. package/dist/server/persistence/open-state-store.d.ts +3 -0
  205. package/dist/server/persistence/open-state-store.js +35 -0
  206. package/dist/server/persistence/rename.d.ts +22 -0
  207. package/dist/server/persistence/rename.js +44 -0
  208. package/dist/server/persistence/sqlite-state-repository.d.ts +12 -0
  209. package/dist/server/persistence/sqlite-state-repository.js +264 -0
  210. package/dist/server/pi-command.d.ts +94 -0
  211. package/dist/server/pi-command.js +265 -0
  212. package/dist/server/pi-native.d.ts +12 -0
  213. package/dist/server/pi-native.js +16 -0
  214. package/dist/server/pi-session-events.d.ts +158 -0
  215. package/dist/server/pi-session-events.js +373 -0
  216. package/dist/server/pi-session-pool.d.ts +233 -0
  217. package/dist/server/pi-session-pool.js +382 -0
  218. package/dist/server/pi-session.d.ts +642 -0
  219. package/dist/server/pi-session.js +655 -0
  220. package/dist/server/presentations/schema.d.ts +120 -0
  221. package/dist/server/presentations/schema.js +128 -0
  222. package/dist/server/provider-network.d.ts +16 -0
  223. package/dist/server/provider-network.js +106 -0
  224. package/dist/server/provider-proxy.d.ts +18 -0
  225. package/dist/server/provider-proxy.js +200 -0
  226. package/dist/server/providers.d.ts +333 -0
  227. package/dist/server/providers.js +989 -0
  228. package/dist/server/remote-bootstrap.d.ts +17 -0
  229. package/dist/server/remote-bootstrap.js +119 -0
  230. package/dist/server/rpc-channel.d.ts +131 -0
  231. package/dist/server/rpc-channel.js +135 -0
  232. package/dist/server/runtime.d.ts +1393 -0
  233. package/dist/server/runtime.js +3286 -0
  234. package/dist/server/scheduled-tasks.d.ts +101 -0
  235. package/dist/server/scheduled-tasks.js +138 -0
  236. package/dist/server/server-context.d.ts +119 -0
  237. package/dist/server/server-context.js +1 -0
  238. package/dist/server/session-cwd.d.ts +19 -0
  239. package/dist/server/session-cwd.js +58 -0
  240. package/dist/server/session-ledger.d.ts +67 -0
  241. package/dist/server/session-ledger.js +76 -0
  242. package/dist/server/session-memory-scope.d.ts +4 -0
  243. package/dist/server/session-memory-scope.js +30 -0
  244. package/dist/server/session-repository.d.ts +100 -0
  245. package/dist/server/session-repository.js +246 -0
  246. package/dist/server/session-tree-scope.d.ts +125 -0
  247. package/dist/server/session-tree-scope.js +337 -0
  248. package/dist/server/skills.d.ts +23 -0
  249. package/dist/server/skills.js +190 -0
  250. package/dist/server/store.d.ts +1062 -0
  251. package/dist/server/store.js +3305 -0
  252. package/dist/server/subagent-runs.d.ts +185 -0
  253. package/dist/server/subagent-runs.js +383 -0
  254. package/dist/server/subagents.d.ts +200 -0
  255. package/dist/server/subagents.js +619 -0
  256. package/dist/server/task-tool.d.ts +282 -0
  257. package/dist/server/task-tool.js +507 -0
  258. package/dist/server/tavily.d.ts +32 -0
  259. package/dist/server/tavily.js +136 -0
  260. package/dist/server/team-context.d.ts +12 -0
  261. package/dist/server/team-context.js +180 -0
  262. package/dist/server/terminal.d.ts +163 -0
  263. package/dist/server/terminal.js +557 -0
  264. package/dist/server/thinking-level-discovery.d.ts +38 -0
  265. package/dist/server/thinking-level-discovery.js +183 -0
  266. package/dist/server/time-zone.d.ts +20 -0
  267. package/dist/server/time-zone.js +32 -0
  268. package/dist/server/tool-calls.d.ts +130 -0
  269. package/dist/server/tool-calls.js +341 -0
  270. package/dist/server/tool-llm.d.ts +72 -0
  271. package/dist/server/tool-llm.js +146 -0
  272. package/dist/server/tool-registry.d.ts +129 -0
  273. package/dist/server/tool-registry.js +249 -0
  274. package/dist/server/tool-runner.d.ts +112 -0
  275. package/dist/server/tool-runner.js +306 -0
  276. package/dist/server/turn-failure.d.ts +48 -0
  277. package/dist/server/turn-failure.js +148 -0
  278. package/dist/server/types.d.ts +2315 -0
  279. package/dist/server/types.js +11 -0
  280. package/dist/server/update-status.d.ts +14 -0
  281. package/dist/server/update-status.js +69 -0
  282. package/dist/server/update.d.ts +46 -0
  283. package/dist/server/update.js +104 -0
  284. package/dist/server/upload.d.ts +35 -0
  285. package/dist/server/upload.js +177 -0
  286. package/dist/server/version.d.ts +33 -0
  287. package/dist/server/version.js +111 -0
  288. package/dist/server/web.d.ts +27 -0
  289. package/dist/server/web.js +183 -0
  290. package/dist/server/workflow-engine.d.ts +47 -0
  291. package/dist/server/workflow-engine.js +255 -0
  292. package/dist/server/workflow.d.ts +329 -0
  293. package/dist/server/workflow.js +469 -0
  294. package/dist/server/workspace-file-indexes.d.ts +2 -0
  295. package/dist/server/workspace-file-indexes.js +61 -0
  296. package/dist/server/workspace-file-operations.d.ts +36 -0
  297. package/dist/server/workspace-file-operations.js +281 -0
  298. package/dist/server/workspace-file-response.d.ts +7 -0
  299. package/dist/server/workspace-file-response.js +79 -0
  300. package/dist/server/ws-server.d.ts +149 -0
  301. package/dist/server/ws-server.js +640 -0
  302. package/dist/shared/agent-order.d.ts +44 -0
  303. package/dist/shared/agent-order.js +50 -0
  304. package/dist/shared/archive-decisions.d.ts +44 -0
  305. package/dist/shared/archive-decisions.js +98 -0
  306. package/dist/shared/background-task.d.ts +25 -0
  307. package/dist/shared/background-task.js +183 -0
  308. package/dist/shared/child-session-lock.d.ts +37 -0
  309. package/dist/shared/child-session-lock.js +59 -0
  310. package/dist/shared/content-search.d.ts +22 -0
  311. package/dist/shared/content-search.js +1 -0
  312. package/dist/shared/conversation-title.d.ts +4 -0
  313. package/dist/shared/conversation-title.js +4 -0
  314. package/dist/shared/file-mentions.d.ts +17 -0
  315. package/dist/shared/file-mentions.js +91 -0
  316. package/dist/shared/git-commit.d.ts +11 -0
  317. package/dist/shared/git-commit.js +1 -0
  318. package/dist/shared/git-graph.d.ts +42 -0
  319. package/dist/shared/git-graph.js +30 -0
  320. package/dist/shared/group-chat.d.ts +132 -0
  321. package/dist/shared/group-chat.js +6 -0
  322. package/dist/shared/managed-servers.d.ts +36 -0
  323. package/dist/shared/managed-servers.js +1 -0
  324. package/dist/shared/message-media.d.ts +12 -0
  325. package/dist/shared/message-media.js +27 -0
  326. package/dist/shared/model-window-label.d.ts +39 -0
  327. package/dist/shared/model-window-label.js +55 -0
  328. package/dist/shared/native-tools.d.ts +43 -0
  329. package/dist/shared/native-tools.js +1 -0
  330. package/dist/shared/pi-cache-warming.d.ts +9 -0
  331. package/dist/shared/pi-cache-warming.js +4 -0
  332. package/dist/shared/project-overview.d.ts +107 -0
  333. package/dist/shared/project-overview.js +92 -0
  334. package/dist/shared/project-presentation.d.ts +55 -0
  335. package/dist/shared/project-presentation.js +111 -0
  336. package/dist/shared/provider-network.d.ts +30 -0
  337. package/dist/shared/provider-network.js +1 -0
  338. package/dist/shared/session-reporting.d.ts +40 -0
  339. package/dist/shared/session-reporting.js +97 -0
  340. package/dist/shared/session-search.d.ts +14 -0
  341. package/dist/shared/session-search.js +1 -0
  342. package/dist/shared/team-context-view.d.ts +33 -0
  343. package/dist/shared/team-context-view.js +49 -0
  344. package/dist/shared/team-context.d.ts +59 -0
  345. package/dist/shared/team-context.js +3 -0
  346. package/dist/shared/terminal-protocol.d.ts +71 -0
  347. package/dist/shared/terminal-protocol.js +1 -0
  348. package/dist/shared/thinking-levels.d.ts +53 -0
  349. package/dist/shared/thinking-levels.js +85 -0
  350. package/dist/shared/tool-glyph.d.ts +7 -0
  351. package/dist/shared/tool-glyph.js +19 -0
  352. package/dist/shared/transcript-order.d.ts +7 -0
  353. package/dist/shared/transcript-order.js +12 -0
  354. package/dist/shared/update-status.d.ts +28 -0
  355. package/dist/shared/update-status.js +1 -0
  356. package/dist/shared/workspace-file-preview.d.ts +4 -0
  357. package/dist/shared/workspace-file-preview.js +28 -0
  358. package/package.json +448 -4
  359. package/scripts/diagnose.mjs +603 -0
  360. package/scripts/patch-brace-expansion.mjs +260 -0
  361. package/scripts/restart-server.mjs +104 -0
  362. package/skills/presentation/SKILL.md +30 -0
  363. package/skills/presentation/references/data.md +10 -0
  364. package/skills/presentation/references/quality.md +12 -0
  365. package/skills/presentation/references/story.md +12 -0
  366. package/skills/presentation/references/templates-and-editing.md +11 -0
  367. package/skills/presentation/references/visual-system.md +10 -0
  368. package/skills/super-pi-agent-development/SKILL.md +25 -0
  369. package/skills/super-pi-development/SKILL.md +31 -0
  370. package/skills/super-pi-tool-development/SKILL.md +39 -0
@@ -0,0 +1,557 @@
1
+ /**
2
+ * The right rail's terminal, as a SERVER-SIDE SESSION MANAGER.
3
+ *
4
+ * ---------------------------------------------------------------------------------------------
5
+ * WHY THIS FILE EXISTS AT ALL, stated plainly because it is the most consequential file in the project
6
+ * ---------------------------------------------------------------------------------------------
7
+ *
8
+ * Everything else in Super Pi is a control plane for a MODEL. This file hands a browser a SHELL on the
9
+ * machine Super Pi runs on. That is categorically different in kind, not in degree: a chat message can
10
+ * at worst make the model write a file inside a workspace, whereas one keystroke here runs whatever the
11
+ * user typed, with the full privileges of the server process, with no workspace containment and no
12
+ * capability scope.
13
+ *
14
+ * The server binds `0.0.0.0` by default (see `index.ts`), which exists so a phone on the same Wi-Fi can
15
+ * reach Super Pi without an SSH tunnel. Combined with a shell, that turns "anyone on the LAN who can
16
+ * open a web page" into "anyone on the LAN who can open a web page has a root-or-you shell". The
17
+ * project already knows this shape of problem - `http-server.ts` guards file writes and uploads behind
18
+ * `isLocalOrPrivateAddress` for exactly this reason - but a file write is bounded by the workspace root
19
+ * and this is not.
20
+ *
21
+ * So the guards here are deliberately redundant, and each one closes a hole the others do not:
22
+ *
23
+ * 1. AVAILABLE BY DEFAULT. The terminal is a built-in local capability. Network scope, workspace
24
+ * resolution, and bounded sessions still protect every command.
25
+ * 2. NETWORK SCOPE. Even enabled, a command is refused unless the WebSocket arrived from loopback or
26
+ * an RFC 1918 / link-local / ULA address (`isLocalOrPrivateAddress`, the same predicate the file
27
+ * endpoints use). A request that arrives from a routed or proxied address is refused by name.
28
+ * 3. WORKSPACE SCOPE. The server resolves a workspace ID and validates the relative starting directory.
29
+ * 4. BOUNDED SESSIONS. Shells and retained output count toward fixed limits.
30
+ * 5. REATTACHMENT. Browser ownership scopes session discovery; only a subscribed socket may
31
+ * address a slot. Losing a subscription does not end the shell.
32
+ *
33
+ * What is NOT here is a per-command allowlist. A terminal that refuses `rm` or `curl` is not a terminal,
34
+ * and pretending otherwise would be worse than the honest version: with (1) and (2) the operator has
35
+ * chosen to expose a shell to their own LAN, and from there every command is the operator's own.
36
+ *
37
+ * ---------------------------------------------------------------------------------------------
38
+ * WHY `node-pty` AND NOT `child_process.spawn`
39
+ * ---------------------------------------------------------------------------------------------
40
+ *
41
+ * `spawn("bash", { stdio: "pipe" })` gives a program three pipes and no terminal. Programs that ask
42
+ * whether stdout is a TTY take the "I am being piped" branch and behave differently: no colours, no
43
+ * progress bars, and `vim` / `top` / `less` refuse outright with "not a terminal". A terminal panel
44
+ * that cannot run those is a command runner wearing a terminal's clothes.
45
+ *
46
+ * `node-pty` allocates a real pseudo-terminal (ConPTY on Windows, `forkpty` elsewhere), which is the
47
+ * only way to get them. The cost is a native module, and it is paid only by operators who set
48
+ */
49
+ import { createRequire } from "node:module";
50
+ import { randomUUID } from "node:crypto";
51
+ import { existsSync, accessSync, constants } from "node:fs";
52
+ import { delimiter, join } from "node:path";
53
+ import { MAX_TERMINAL_SLOTS } from "../shared/terminal-protocol.js";
54
+ import { resolveFileCwd } from "./session-cwd.js";
55
+ let ptyModule;
56
+ let ptyLoadFailure;
57
+ /**
58
+ * WHY THIS IS LAZY, AND WHY IT IS `createRequire` RATHER THAN `import`.
59
+ *
60
+ * `import("node-pty")` would be evaluated by the bundler/compiler as a real dynamic import of a package
61
+ * the project does not depend on by default, and its rejection is a load-time failure of the WHOLE
62
+ * server rather than of the terminal. A server can start without node-pty and report a useful error only
63
+ * when the terminal is used.
64
+ *
65
+ * `createRequire` sidesteps the module-resolution question entirely: this file is compiled to ESM by
66
+ * `tsconfig.server.json`, `node-pty` is CommonJS, and `require` is the one call that loads CJS from ESM
67
+ * without an interop wrapper. The result is cached in `ptyModule` so the native handle is resolved once.
68
+ *
69
+ * The failure is CACHED AS A STRING because a missing native module must produce the SAME refusal on
70
+ * every subsequent keystroke rather than a different native stack trace each time, and a missing
71
+ * terminal is a far better outcome than an unstable one.
72
+ */
73
+ function loadPty() {
74
+ if (ptyModule)
75
+ return ptyModule;
76
+ if (ptyLoadFailure)
77
+ return undefined;
78
+ try {
79
+ const require = createRequire(import.meta.url);
80
+ ptyModule = require("node-pty");
81
+ return ptyModule;
82
+ }
83
+ catch (error) {
84
+ ptyLoadFailure = error instanceof Error ? error.message : String(error);
85
+ console.warn(`Super Pi: 终端组件 node-pty 加载失败,右侧栏终端将不可用:${ptyLoadFailure}`);
86
+ return undefined;
87
+ }
88
+ }
89
+ /**
90
+ * The node-pty version this file is written against, and WHY IT IS NOT 1.1.0.
91
+ *
92
+ * node-pty 1.1.0's Windows `kill()` forks a helper process that calls `AttachConsole(shellPid)` in order
93
+ * to enumerate the console's process list so it can kill stragglers. When the console has already gone,
94
+ * `AttachConsole` fails, the helper throws an unhandled error, and - reproducibly, on Windows - the
95
+ * NODE PROCESS ITSELF dies with `STATUS_ENTRYPOINT_NOT_FOUND` (0xC0000139).
96
+ *
97
+ * That is not a recoverable bug in a server. A user clicking "close terminal" would take down every
98
+ * running conversation, every open WebSocket and the persistence handle with it. `scripts/
99
+ * terminal-pty.test.mjs` asserts the spawn/write/kill/respawn cycle end to end so a downgrade back to
100
+ * 1.1.0 fails a test instead of killing the server at runtime.
101
+ *
102
+ * 1.2.0-beta.15 replaces that kill path and survives it; the abnormal 0xC0000139 exit code it still
103
+ * reports for a KILLED shell is filtered in `onExit` below so it is never shown to a user as if it were
104
+ * a command's exit status.
105
+ */
106
+ const MINIMUM_PTY_VERSION = "1.2.0-beta.15";
107
+ /**
108
+ * WHICH SHELL, and why it is not `COMSPEC`.
109
+ *
110
+ * `process.env.COMSPEC` on Windows IS `cmd.exe`, which is what this function used to spawn - while the
111
+ * comment beside it claimed PowerShell. The mismatch was visible in practice: `cmd.exe` is a DOS-era
112
+ * console with a legacy code page, so a Chinese filename printed by `dir` arrives as mojibake and the
113
+ * prompt echoes the active code page. Super Pi's whole interface is Chinese, so a terminal that cannot
114
+ * print Chinese is not a working terminal for the people who would use it.
115
+ *
116
+ * PowerShell is therefore the default, chosen over `pwsh` by name because `powershell.exe` ships with
117
+ * every supported Windows version while `pwsh` is a separate install. `SUPER_PI_TERMINAL_SHELL` overrides
118
+ * it for anyone who wants `cmd.exe`, `pwsh`, or Git Bash.
119
+ *
120
+ * On Unix the user's own `$SHELL` is right and a login shell is requested, because the terminal should
121
+ * see the same PATH and aliases as the terminal they use elsewhere.
122
+ *
123
+ * The ARGS differ by family and are not an arbitrary detail: `-l` is a bash/sh login flag, and passing it
124
+ * to PowerShell would make the shell refuse to start.
125
+ */
126
+ export function parseShellCommand(command) {
127
+ const parts = command.match(/"[^"\\]*(?:\\.[^"\\]*)*"|'[^']*'|\S+/g) ?? [];
128
+ const file = (parts.shift() ?? "").replace(/^("|' )|("|' )$/g, "").replace(/^['"]|['"]$/g, "");
129
+ return file ? { file, args: parts.map((part) => part.replace(/^['"]|['"]$/g, "")) } : undefined;
130
+ }
131
+ function defaultPlatformShell(env = process.env) {
132
+ if (process.platform === "win32") {
133
+ return { file: env.COMSPEC?.toLowerCase().includes("pwsh") ? "pwsh.exe" : "powershell.exe", args: [] };
134
+ }
135
+ return { file: env.SHELL || "/bin/bash", args: ["-l"] };
136
+ }
137
+ export function defaultShell(env = process.env, configured) {
138
+ if (configured?.file)
139
+ return { file: configured.file, args: [...configured.args] };
140
+ const override = env.SUPER_PI_TERMINAL_SHELL?.trim();
141
+ if (override)
142
+ return parseShellCommand(override) ?? defaultPlatformShell(env);
143
+ return defaultPlatformShell(env);
144
+ }
145
+ export function shellSource(env = process.env, configured) {
146
+ return configured?.file ? "设置" : env.SUPER_PI_TERMINAL_SHELL?.trim() ? "环境变量" : "平台默认";
147
+ }
148
+ function commandOnPath(file, env) {
149
+ if (file.includes("/") || file.includes("\\"))
150
+ return existsSync(file);
151
+ for (const dir of (env.PATH ?? "").split(delimiter)) {
152
+ const names = process.platform === "win32" ? [file, ...(env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").map((ext) => file.endsWith(ext.toLowerCase()) ? file : file + ext.toLowerCase())] : [file];
153
+ if (names.some((name) => { try {
154
+ accessSync(join(dir, name), constants.X_OK);
155
+ return true;
156
+ }
157
+ catch {
158
+ return false;
159
+ } }))
160
+ return true;
161
+ }
162
+ return false;
163
+ }
164
+ export function validateShellCommand(command, env = process.env) {
165
+ const parsed = parseShellCommand(command);
166
+ if (!parsed)
167
+ return "请输入要启动的 shell 命令。";
168
+ if (!commandOnPath(parsed.file, env))
169
+ return `找不到 ${parsed.file}:既不在 PATH 上,也不是一个存在的路径`;
170
+ return undefined;
171
+ }
172
+ export function terminalShellCandidates(env = process.env) {
173
+ const items = [];
174
+ if (process.platform === "win32") {
175
+ items.push({ file: "powershell.exe", args: [], label: "PowerShell" }, { file: "cmd.exe", args: [], label: "命令提示符" });
176
+ const git = "C:\\Program Files\\Git\\bin\\bash.exe";
177
+ if (existsSync(git))
178
+ items.push({ file: git, args: [], label: "Git Bash" });
179
+ if (commandOnPath("wsl.exe", env))
180
+ items.push({ file: "wsl.exe", args: ["-e", "bash"], label: "WSL Bash" });
181
+ }
182
+ else {
183
+ for (const file of [env.SHELL, "bash", "zsh", "fish"])
184
+ if (file && commandOnPath(file, env) && !items.some((item) => item.file === file))
185
+ items.push({ file, args: ["-l"], label: file });
186
+ }
187
+ return items;
188
+ }
189
+ // ---------------------------------------------------------------------------------------------
190
+ // Bounds
191
+ // ---------------------------------------------------------------------------------------------
192
+ /**
193
+ * THE CEILING ON LIVE SHELLS.
194
+ *
195
+ * WHAT THIS COUNTS. Only the browser's terminal panel: `terminal.open` is the ONE place a shell is
196
+ * spawned, and it is a command the browser sends over its own WebSocket. An agent session, a
197
+ * sub-agent run, and the `exec` tool do NOT consume this budget - the exec tool spawns its own
198
+ * short-lived `shell -c` process through a different service.
199
+ *
200
+ * WHY THE COUNT ACCUMULATES. The client opens up to five terminals per session (`MAX_SLOTS` in
201
+ * TerminalPanel), and a shell is deliberately KEPT ALIVE across a session switch: the panel unmounts
202
+ * without closing it, so the work in that shell survives the switch. Every session in the tree is a
203
+ * conversation with its own panel - including a CHILD session the user can click into - and each of
204
+ * them can hold five shells, and all of them land in this one map. A tree multiplies: eight parents
205
+ * with four children each are forty sessions, and forty sessions at four terminals is a hundred and
206
+ * sixty shells.
207
+ *
208
+ * WHY 256. Every shell in this map was opened by the user on purpose, and what runs inside it is the
209
+ * user's own business - so this constant is NOT a memory governor and does not pretend to be one. Its
210
+ * whole job is to be generous enough never to stand in the way of real work, and loud enough that a
211
+ * client looping on `terminal.open` is stopped with a message instead of quietly filling the machine.
212
+ * (For the record, the platform's own overhead per shell is the shell: an idle Windows PowerShell is
213
+ * ~90MB and an idle bash ~8MB, so the cost of "many terminals" is the cost of the shells themselves.)
214
+ * Reconnect storms do not need this constant to be low: the socket-close cleanup already kills a
215
+ * connection's shells, and the 30-second heartbeat reaps the half-open connections that would
216
+ * otherwise leave them behind.
217
+ */
218
+ export const MAX_SESSIONS = 256;
219
+ /** Below the client panel's own minimum, and small enough that a `ls` cannot stall the socket. */
220
+ const MIN_COLS = 20;
221
+ const MIN_ROWS = 5;
222
+ const MAX_COLS = 500;
223
+ const MAX_ROWS = 200;
224
+ /**
225
+ * OUTPUT IS COALESCED, NOT SENT PER CHUNK.
226
+ *
227
+ * A `yes` or a fast build writes thousands of `onData` callbacks per second. Forwarding each one as its
228
+ * own WebSocket frame makes the browser the bottleneck and lets a single command saturate the server's
229
+ * event loop. Chunks are queued and flushed on a timer, with a byte ceiling per frame so one flush
230
+ * cannot build a megabyte-long string.
231
+ *
232
+ * The per-frame ceiling never DISCARDS data: a flush larger than MAX_CHUNK_BYTES sends its first
233
+ * MAX_CHUNK_BYTES and puts the remainder back at the FRONT of the queue - it is older than anything
234
+ * enqueued since - with the flush timer re-armed, so the split lands at the START of the next flush
235
+ * rather than mid-escape, where it could cut a partial ANSI escape sequence.
236
+ */
237
+ const FLUSH_INTERVAL_MS = 16;
238
+ const MAX_CHUNK_BYTES = 64 * 1024;
239
+ /** Maximum pending output and retained replay history, measured in UTF-16 code units. */
240
+ const MAX_BACKLOG_BYTES = 4 * 1024 * 1024;
241
+ const MAX_HISTORY = 256 * 1024;
242
+ /** The terminal is built in. Native PTY availability is checked on use. */
243
+ export function isTerminalEnabled(env = process.env) {
244
+ void env;
245
+ return true;
246
+ }
247
+ export function terminalDisabledReason(_env = process.env) {
248
+ if (ptyLoadFailure)
249
+ return "终端组件(node-pty)没有加载成功,请重新安装依赖或重启 Super Pi。";
250
+ return "";
251
+ }
252
+ export class TerminalService {
253
+ groups = new Map();
254
+ subscriptions = new Map();
255
+ closing = false;
256
+ workspaceFor;
257
+ isTrustedPeer;
258
+ configuredShell;
259
+ saveConfiguredShell;
260
+ constructor(options) {
261
+ this.workspaceFor = options.workspaceFor;
262
+ this.isTrustedPeer = options.isTrustedPeer;
263
+ this.configuredShell = options.configuredShell ?? (() => undefined);
264
+ this.saveConfiguredShell = options.saveConfiguredShell ?? (async () => { });
265
+ this.enabled = options.enabled ?? isTerminalEnabled();
266
+ }
267
+ enabled;
268
+ async setShell(command, remoteAddress, browserAuthorized = false) {
269
+ if (!this.enabled || (!browserAuthorized && !this.isTrustedPeer(remoteAddress)))
270
+ return false;
271
+ if (command === null) {
272
+ await this.saveConfiguredShell(undefined);
273
+ return true;
274
+ }
275
+ const error = validateShellCommand(command);
276
+ if (error)
277
+ throw new Error(error);
278
+ const shell = parseShellCommand(command);
279
+ if (!shell)
280
+ throw new Error("请输入要启动的 shell 命令。");
281
+ await this.saveConfiguredShell(shell);
282
+ return true;
283
+ }
284
+ assertUsable(remoteAddress, send, browserAuthorized) {
285
+ if (!browserAuthorized && !this.isTrustedPeer(remoteAddress)) {
286
+ send({ type: "terminal.error", message: "终端只接受来自本机或局域网地址的连接。" });
287
+ return false;
288
+ }
289
+ if (this.closing || !this.enabled || !loadPty()) {
290
+ send({ type: "terminal.status", enabled: false, reason: terminalDisabledReason() });
291
+ return false;
292
+ }
293
+ return true;
294
+ }
295
+ async handle(command, remoteAddress, send, browserAuthorized = false) {
296
+ if (command.type === "terminal.detach") {
297
+ this.detach(send);
298
+ return;
299
+ }
300
+ if (!this.assertUsable(remoteAddress, send, browserAuthorized))
301
+ return;
302
+ if (command.type === "terminal.sync") {
303
+ await this.sync(command, send);
304
+ return;
305
+ }
306
+ const subscription = this.subscriptions.get(send);
307
+ if (!subscription?.ready) {
308
+ if (command.type !== "terminal.resize")
309
+ send({ type: "terminal.error", message: "终端尚未连接,请刷新页面后重试。" });
310
+ return;
311
+ }
312
+ const { group } = subscription;
313
+ if (command.type === "terminal.open") {
314
+ try {
315
+ const activate = await this.open(group, subscription.cwd, command);
316
+ for (const [peer, view] of this.subscriptions) {
317
+ if (view.ready && view.group === group)
318
+ this.sendSessions(peer, group, false, peer === send ? activate : undefined);
319
+ }
320
+ }
321
+ catch (error) {
322
+ send({ type: "terminal.error", sessionId: command.sessionId, message: this.errorMessage(error) });
323
+ }
324
+ return;
325
+ }
326
+ const session = group.sessions.get(command.sessionId);
327
+ if (!session) {
328
+ if (command.type === "terminal.resize")
329
+ return;
330
+ send({ type: "terminal.error", sessionId: command.sessionId, message: "终端会话已关闭或不属于当前视图。" });
331
+ this.sendSessions(send, group, false);
332
+ return;
333
+ }
334
+ if (command.type === "terminal.close") {
335
+ while (session.pending)
336
+ this.flush(group, session);
337
+ group.sessions.delete(session.slot.id);
338
+ this.stop(session);
339
+ this.publish(group, { type: "terminal.exit", sessionId: session.slot.id, exitCode: 0 });
340
+ this.publish(group, { type: "terminal.sessions", ...group.scope, sessions: this.slots(group), replay: false });
341
+ return;
342
+ }
343
+ if (!session.pty)
344
+ return;
345
+ if (command.type === "terminal.input") {
346
+ if (typeof command.data === "string" && command.data.length <= 64 * 1024)
347
+ session.pty.write(command.data);
348
+ return;
349
+ }
350
+ const cols = clamp(command.cols, MIN_COLS, MAX_COLS, session.slot.cols);
351
+ const rows = clamp(command.rows, MIN_ROWS, MAX_ROWS, session.slot.rows);
352
+ if (cols === session.slot.cols && rows === session.slot.rows)
353
+ return;
354
+ try {
355
+ session.pty.resize(cols, rows);
356
+ Object.assign(session.slot, { cols, rows });
357
+ this.publish(group, { type: "terminal.size", sessionId: session.slot.id, cols, rows });
358
+ }
359
+ catch {
360
+ // The PTY can exit before a layout hint arrives.
361
+ }
362
+ }
363
+ async sync(command, send) {
364
+ const { ownerId, workspaceId, conversationId, cwd } = command;
365
+ this.detach(send);
366
+ if (typeof ownerId !== "string" || !/^[0-9a-f]{32}$/.test(ownerId)
367
+ || typeof workspaceId !== "string" || !this.workspaceFor(workspaceId)
368
+ || (conversationId !== undefined && (typeof conversationId !== "string" || conversationId.length > 200))) {
369
+ send({ type: "terminal.error", message: "终端的浏览器标识或工作区无效。" });
370
+ return;
371
+ }
372
+ const key = JSON.stringify([ownerId, workspaceId, conversationId]);
373
+ let group = this.groups.get(key);
374
+ if (!group) {
375
+ group = { key, scope: { workspaceId, conversationId }, initialized: false, creating: 0, sessions: new Map() };
376
+ this.groups.set(key, group);
377
+ }
378
+ const subscription = { group, cwd, ready: false };
379
+ this.subscriptions.set(send, subscription);
380
+ try {
381
+ if (command.initialize === false)
382
+ group.initialized = true;
383
+ if (!group.initialized)
384
+ await this.open(group, cwd, command, true);
385
+ }
386
+ catch (error) {
387
+ if (this.subscriptions.get(send) === subscription) {
388
+ this.detach(send);
389
+ send({ type: "terminal.error", message: this.errorMessage(error) });
390
+ }
391
+ return;
392
+ }
393
+ if (this.subscriptions.get(send) !== subscription)
394
+ return;
395
+ subscription.ready = true;
396
+ this.sendSessions(send, group, true);
397
+ // No await between the snapshot and replay. Live output starts after this baseline.
398
+ for (const session of group.sessions.values()) {
399
+ send({ type: "terminal.replay", sessionId: session.slot.id, data: session.history });
400
+ }
401
+ }
402
+ async open(group, cwd, size, initial = false) {
403
+ group.creating += 1;
404
+ try {
405
+ return await this.spawn(group, cwd, size, initial);
406
+ }
407
+ finally {
408
+ group.creating -= 1;
409
+ this.pruneEmptyGroup(group);
410
+ }
411
+ }
412
+ async spawn(group, cwd, size, initial) {
413
+ const workspace = this.workspaceFor(group.scope.workspaceId);
414
+ if (!workspace)
415
+ throw new Error("工作区不存在,无法打开终端。");
416
+ if (cwd !== undefined && typeof cwd !== "string")
417
+ throw new Error("会话目录无效。");
418
+ const directory = await resolveFileCwd(workspace.path, cwd);
419
+ if (this.closing || this.groups.get(group.key) !== group)
420
+ throw new Error("终端工作区已关闭,无法打开终端。");
421
+ if (!existsSync(directory))
422
+ throw new Error("会话工作目录不存在,无法打开终端。");
423
+ // Filesystem resolution yields to other sockets. Recheck creation and capacity before spawning.
424
+ if (initial && group.initialized)
425
+ return;
426
+ const previous = size.sessionId ? group.sessions.get(size.sessionId) : undefined;
427
+ if (size.sessionId && !previous)
428
+ throw new Error("终端会话已关闭。");
429
+ if (previous?.pty)
430
+ return previous.slot.id;
431
+ const count = [...this.groups.values()].reduce((total, item) => total + item.sessions.size, 0);
432
+ if (!previous && (group.sessions.size >= MAX_TERMINAL_SLOTS || count >= MAX_SESSIONS)) {
433
+ throw new Error(`终端数量已达上限(每个会话最多 ${MAX_TERMINAL_SLOTS} 个,服务端最多 ${MAX_SESSIONS} 个)。请关闭不用的终端后重试。`);
434
+ }
435
+ let title = 1;
436
+ const used = new Set([...group.sessions.values()].map(session => session.slot.title));
437
+ while (used.has(String(title)))
438
+ title += 1;
439
+ const slot = {
440
+ id: previous?.slot.id ?? randomUUID(),
441
+ title: previous?.slot.title ?? String(title),
442
+ cols: clamp(size.cols, MIN_COLS, MAX_COLS, 80),
443
+ rows: clamp(size.rows, MIN_ROWS, MAX_ROWS, 24),
444
+ };
445
+ const shell = defaultShell(process.env, this.configuredShell());
446
+ const child = loadPty().spawn(shell.file, shell.args, {
447
+ name: "xterm-256color", cols: slot.cols, rows: slot.rows, cwd: directory,
448
+ env: { ...process.env, TERM: "xterm-256color" },
449
+ });
450
+ const session = { slot, pty: child, history: "", pending: "" };
451
+ group.sessions.set(slot.id, session);
452
+ group.initialized = true;
453
+ child.onData(data => {
454
+ if (session.pty !== child)
455
+ return;
456
+ session.pending += data;
457
+ session.timer ??= setTimeout(() => this.flush(group, session), FLUSH_INTERVAL_MS);
458
+ });
459
+ child.onExit(({ exitCode }) => {
460
+ while (session.pending && session.pty === child)
461
+ this.flush(group, session);
462
+ if (session.pty !== child)
463
+ return;
464
+ session.pty = undefined;
465
+ this.recordExit(group, session, exitCode);
466
+ });
467
+ return slot.id;
468
+ }
469
+ slots(group) {
470
+ return [...group.sessions.values()].map(session => session.slot);
471
+ }
472
+ sendSessions(send, group, replay, activate) {
473
+ send({ type: "terminal.sessions", ...group.scope, sessions: this.slots(group), replay, activate });
474
+ }
475
+ publish(group, event) {
476
+ for (const [send, view] of this.subscriptions) {
477
+ if (view.ready && view.group === group)
478
+ send(event);
479
+ }
480
+ }
481
+ flush(group, session) {
482
+ clearTimeout(session.timer);
483
+ session.timer = undefined;
484
+ if (!session.pending)
485
+ return;
486
+ if (session.pending.length > MAX_BACKLOG_BYTES) {
487
+ this.stop(session);
488
+ this.recordExit(group, session, 1, "输出量过大,已停止该终端会话。");
489
+ return;
490
+ }
491
+ const data = session.pending.slice(0, MAX_CHUNK_BYTES);
492
+ session.pending = session.pending.slice(data.length);
493
+ if (session.pending)
494
+ session.timer = setTimeout(() => this.flush(group, session), FLUSH_INTERVAL_MS);
495
+ session.history = (session.history + data).slice(-MAX_HISTORY);
496
+ this.publish(group, { type: "terminal.output", sessionId: session.slot.id, data });
497
+ }
498
+ recordExit(group, session, exitCode, reason) {
499
+ Object.assign(session.slot, { exitCode, reason });
500
+ this.publish(group, { type: "terminal.exit", sessionId: session.slot.id, exitCode, reason });
501
+ }
502
+ stop(session) {
503
+ const child = session.pty;
504
+ session.pty = undefined;
505
+ session.pending = "";
506
+ clearTimeout(session.timer);
507
+ session.timer = undefined;
508
+ try {
509
+ child?.kill();
510
+ }
511
+ catch { /* The shell may already be gone. */ }
512
+ }
513
+ errorMessage(error) {
514
+ return error instanceof Error ? error.message : "无法打开终端。";
515
+ }
516
+ /** Losing a reader never changes a shell or its output history. */
517
+ detach(send) {
518
+ const view = this.subscriptions.get(send);
519
+ this.subscriptions.delete(send);
520
+ if (view)
521
+ this.pruneEmptyGroup(view.group);
522
+ }
523
+ pruneEmptyGroup(group) {
524
+ if (group.sessions.size || group.creating || this.groups.get(group.key) !== group)
525
+ return;
526
+ if ([...this.subscriptions.values()].some(view => view.group === group))
527
+ return;
528
+ this.groups.delete(group.key);
529
+ }
530
+ removeWorkspace(workspaceId) {
531
+ for (const [key, group] of this.groups) {
532
+ if (group.scope.workspaceId !== workspaceId)
533
+ continue;
534
+ this.groups.delete(key);
535
+ for (const session of group.sessions.values())
536
+ this.stop(session);
537
+ for (const [send, view] of this.subscriptions) {
538
+ if (view.group === group)
539
+ this.detach(send);
540
+ }
541
+ }
542
+ }
543
+ closeAll() {
544
+ this.closing = true;
545
+ for (const group of this.groups.values()) {
546
+ for (const session of group.sessions.values())
547
+ this.stop(session);
548
+ }
549
+ this.groups.clear();
550
+ this.subscriptions.clear();
551
+ }
552
+ }
553
+ function clamp(value, min, max, fallback) {
554
+ if (typeof value !== "number" || !Number.isFinite(value))
555
+ return fallback;
556
+ return Math.min(max, Math.max(min, Math.floor(value)));
557
+ }
@@ -0,0 +1,38 @@
1
+ import { type ThinkingLevelMap } from "../shared/thinking-levels.js";
2
+ /**
3
+ * WHICH THINKING LEVELS A MODEL REALLY OFFERS, and who is allowed to say.
4
+ *
5
+ * THE PROBLEM THIS SOLVES. A model that only does `low`/`medium`/`high` looks exactly like one that
6
+ * does everything, because Pi ENABLES the ordinary levels when nobody says otherwise. So the picker
7
+ * offers a level the provider does not have, the request carries a `reasoning_effort` the provider
8
+ * refuses, and the turn fails on a setting nobody chose.
9
+ *
10
+ * THE RULE THIS FILE ENFORCES. A level may only be written into a model when somebody SAID it, in
11
+ * a form that names the level. Three things do NOT count as saying it, and all three are refused
12
+ * here:
13
+ *
14
+ * 1. A model whose NAME looks like a reasoning model (`o3`, `deepseek-r1`, `thinking`).
15
+ * 2. A provider that only says it supports the PARAMETER (`supports_reasoning_effort: true`,
16
+ * `supported_parameters: ["reasoning_effort"]`). That says a field exists, not which values
17
+ * the model accepts.
18
+ * 3. `reasoning: true`, which says the model thinks, not how hard it can think.
19
+ *
20
+ * AND THE RULE ABOUT COPIES. A level belongs to ONE endpoint's answer about ONE model. A proxy that
21
+ * serves a model with the same name as somebody else's model does NOT get that model's levels, and
22
+ * an answer about one API is never carried over to another. That is why the only endpoint-specific
23
+ * rule below matches the OFFICIAL host exactly.
24
+ */
25
+ /** What the endpoint that answered is, so a rule can be about it and not about the model alone. */
26
+ export type ThinkingLevelContext = {
27
+ /** The endpoint, exactly as the person typed it. */
28
+ baseUrl: string;
29
+ /** The API that endpoint is spoken with. */
30
+ api?: string;
31
+ };
32
+ /**
33
+ * THE LEVELS A MODEL OFFERS, or `undefined` when nobody said.
34
+ *
35
+ * `undefined` is not "no levels" - it is "nobody said", and the caller keeps whatever behaviour it
36
+ * had. A model that nobody described keeps Pi's own defaults, exactly as before.
37
+ */
38
+ export declare function discoverThinkingLevels(entry: Record<string, unknown>, context: ThinkingLevelContext): ThinkingLevelMap | undefined;