@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,3286 @@
1
+ import { spawn } from "node:child_process";
2
+ import { RpcChannel } from "./rpc-channel.js";
3
+ export { RpcChannel } from "./rpc-channel.js";
4
+ import { randomUUID } from "node:crypto";
5
+ import { KNOWLEDGE_IMPORT_TOOL_NAME, KNOWLEDGE_TOOL_NAME } from "./knowledge.js";
6
+ import { DOCUMENT_READ_TOOL_NAME, DOCUMENT_WRITE_TOOL_NAME } from "./documents.js";
7
+ import { FEISHU_READ_TOOL_NAME, FEISHU_WRITE_TOOL_NAME } from "./feishu-cli.js";
8
+ import { WEB_FETCH_TOOL_NAME, WEB_SEARCH_TOOL_NAME } from "./web.js";
9
+ import { existsSync } from "node:fs";
10
+ import { ConversationUsageCollector } from "./conversation-usage.js";
11
+ import { defaultAgentDir, piCacheWarmingMode } from "./pi-session.js";
12
+ import { isPiCacheWarmingMode } from "../shared/pi-cache-warming.js";
13
+ import { readProviderProxyEnv } from "./provider-proxy.js";
14
+ import { withArbitratedWindows } from "./model-context-window.js";
15
+ import { mkdir, stat } from "node:fs/promises";
16
+ import { forkSessionFile, truncateSessionFile } from "./session-repository.js";
17
+ export { forkSessionFile, truncateSessionFile } from "./session-repository.js";
18
+ import { resolve, join, basename } from "node:path";
19
+ import { agentSpawnArgs, readAgents, toolSelection, writeAgentPrompt } from "./agents.js";
20
+ import { TASK_CAPABILITY_ENV, mintCapability, releaseCapability } from "./capability.js";
21
+ import { resolvePiCommand, shellQuote } from "./pi-command.js";
22
+ import { PiSessionPool, repositoryRootFrom } from "./pi-session-pool.js";
23
+ import { nativeToolArgs, nativeToolEnv, nativeToolPolicy, nativeToolSettingsPath, nativeToolExtensionPath, readNativeToolSettings } from "./native-tool-settings.js";
24
+ import { describeDeliveredUserMessage, describePiQueue, handleSessionEvent, TurnQueue } from "./pi-session-events.js";
25
+ import { LengthExceededError } from "./turn-failure.js";
26
+ import { CONVERSATION_TITLE_CONTEXT_MAX_CHARS, CONVERSATION_TITLE_TIMEOUT_MS } from "../shared/conversation-title.js";
27
+ // The queue/steer recognisers live in pi-session-events.ts, where the SESSION path's bridge can use
28
+ // them; the one-shot drain loop below reads the same records through the same two functions, so both
29
+ // paths recognise a delivery identically. Re-exported because they were part of this module's surface.
30
+ export { describeDeliveredUserMessage, describePiQueue } from "./pi-session-events.js";
31
+ import { createPiSession, createSdkCatalog, piSdkAvailable, resolveTranscriptFile, superPiExtensionPaths } from "./pi-session.js";
32
+ import { TASK_CONVERSATION_ENV, PARENT_CONVERSATION_ENV, TASK_DEPTH_ENV, TASK_ENDPOINT_ENV, TASK_EXEC_ENDPOINT_ENV, TASK_ROSTER_ENV, TASK_TOOL_NAME, TODO_ENDPOINT_ENV, TODO_TOOL_NAME, PROJECT_TOOL_NAME, PROJECT_ENDPOINT_ENV, SCHEDULED_TASK_ENDPOINT_ENV, SCHEDULED_TASK_TOOL_NAME, WORKFLOW_ENDPOINT_ENV, WORKFLOW_TOOL_NAME, RUN_ASYNC_TOOL_NAME, ORCHESTRATOR_ENDPOINT_ENV, ORCHESTRATOR_WORKSPACE_ENV, WORKTREE_TOOL_NAME, SESSION_SPAWN_TOOL_NAME, SESSION_STATUS_TOOL_NAME, SESSION_DISPATCH_TOOL_NAME, SESSION_STOP_TOOL_NAME, SESSION_REPORT_TOOL_NAME, SESSION_STOP_SUBTREE_TOOL_NAME, SESSION_REMOVE_TOOL_NAME, SESSION_REMINDER_TOOL_NAME, rosterPayload, } from "./task-tool.js";
33
+ import { BLOCKING_UI_METHODS, EXTENSION_UI_METHODS, } from "./types.js";
34
+ import { loadConversationImages } from "./upload.js";
35
+ import { describeToolCall, describeToolCallArgs, describeToolCallInProgress, extractPartialResultText, extractToolResultText, readQuestionCall } from "./tool-calls.js";
36
+ import { InlineThinkingSplitter, stripInlineThinking } from "./inline-thinking.js";
37
+ import { toolTargetPath } from "./file-changes.js";
38
+ import { offeredThinkingLevels, readThinkingLevelMap } from "../shared/thinking-levels.js";
39
+ const traceLatency = (conversationId, phase, startedAt, extra = "") => {
40
+ if (process.env.SUPER_PI_TRACE_LATENCY !== "1")
41
+ return;
42
+ console.warn(`[super-pi latency] conversation=${conversationId} phase=${phase} elapsedMs=${Math.round(performance.now() - startedAt)}${extra ? ` ${extra}` : ""}`);
43
+ };
44
+ /** A steer that provably never reached Pi; the caller may safely use the next turn instead. */
45
+ export class SteerUnavailableError extends Error {
46
+ }
47
+ /** Deterministic offline runtime used by tests and local UI development. */
48
+ export class WelcomeRuntime {
49
+ async *answer({ prompt, signal }) {
50
+ const response = `\u5df2\u6536\u5230\uff1a${prompt}\n\nSuper Pi \u7684 Web \u57fa\u5ea7\u5df2\u7ecf\u8fd0\u884c\u3002\u5f53\u524d\u4f1a\u8bdd\u3001\u6d41\u5f0f\u8f93\u51fa\u3001\u505c\u6b62\u4efb\u52a1\u4e0e\u672c\u5730\u6301\u4e45\u5316\u5747\u53ef\u7528\u3002\n\nPi \u8fd0\u884c\u65f6\u9002\u914d\u5668\u5df2\u51c6\u5907\u5c31\u7eea\uff1a\u914d\u7f6e\u597d Pi \u7684\u6a21\u578b\u8ba4\u8bc1\u540e\uff0cWeb \u754c\u9762\u4f1a\u901a\u8fc7 JSONL RPC \u9a71\u52a8\u771f\u5b9e agent\u3002`;
51
+ for (const chunk of response.match(/.{1,16}/gsu) ?? []) {
52
+ if (signal.aborted)
53
+ return;
54
+ await new Promise((resolve) => setTimeout(resolve, 20));
55
+ yield chunk;
56
+ }
57
+ }
58
+ async stop() { }
59
+ /**
60
+ * No Pi, so no models. `source` is what turns the picker into a visibly disabled control instead
61
+ * of an empty list, which would read as "you have no models".
62
+ */
63
+ async catalog() {
64
+ return { source: "unavailable", models: [], levels: [], fetchedAt: new Date().toISOString(), error: "Welcome runtime has no Pi session to ask" };
65
+ }
66
+ }
67
+ const NOTIFY_TYPES = new Set(["info", "warning", "error"]);
68
+ const PLACEMENTS = new Set(["aboveEditor", "belowEditor"]);
69
+ const text = (value) => (typeof value === "string" ? value : undefined);
70
+ /** Keeps only real strings, so a malformed `options` cannot put objects into the browser's DOM. */
71
+ const textList = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : undefined;
72
+ /**
73
+ * Normalizes one `extension_ui_request` record, or returns undefined when the record is not something
74
+ * Pi's union can produce (wrong `type`, missing `id`, or a method outside the nine). Exports so the
75
+ * mapping can be tested without spawning Pi.
76
+ */
77
+ export function describeExtensionUiRequest(record) {
78
+ if (record.type !== "extension_ui_request" || typeof record.id !== "string" || record.id === "")
79
+ return undefined;
80
+ if (typeof record.method !== "string" || !EXTENSION_UI_METHODS.includes(record.method))
81
+ return undefined;
82
+ const method = record.method;
83
+ const request = { requestId: record.id, method, blocking: BLOCKING_UI_METHODS.has(method), title: text(record.title) ?? "" };
84
+ switch (method) {
85
+ case "select":
86
+ request.options = textList(record.options) ?? [];
87
+ break;
88
+ case "confirm":
89
+ request.message = text(record.message) ?? "";
90
+ break;
91
+ case "input":
92
+ request.placeholder = text(record.placeholder);
93
+ break;
94
+ case "editor":
95
+ request.prefill = text(record.prefill);
96
+ break;
97
+ // notify reuses `message`; there is no separate notifyTitle in Pi's union.
98
+ case "notify":
99
+ request.message = text(record.message) ?? "";
100
+ request.notifyType = (NOTIFY_TYPES.has(record.notifyType ?? "") ? record.notifyType : "info");
101
+ break;
102
+ case "setStatus":
103
+ request.statusKey = text(record.statusKey) ?? "";
104
+ request.statusText = text(record.statusText);
105
+ break;
106
+ case "setWidget":
107
+ request.widgetKey = text(record.widgetKey) ?? "";
108
+ request.widgetLines = textList(record.widgetLines);
109
+ request.widgetPlacement = (PLACEMENTS.has(record.widgetPlacement ?? "") ? record.widgetPlacement : undefined);
110
+ break;
111
+ case "setTitle": break;
112
+ case "set_editor_text":
113
+ request.text = text(record.text) ?? "";
114
+ break;
115
+ }
116
+ // Only Pi's blocking methods carry a deadline, and `editor` never does - which is exactly why an
117
+ // unanswered editor is allowed to wait indefinitely rather than being expired by this host.
118
+ if (request.blocking && typeof record.timeout === "number" && Number.isFinite(record.timeout) && record.timeout > 0)
119
+ request.timeoutMs = record.timeout;
120
+ return request;
121
+ }
122
+ /**
123
+ * Maps a human's answer onto the one response shape Pi's method accepts. The method decides the shape
124
+ * rather than the answer, so a client that sends `confirmed` for a `select` (or `value` for a `confirm`)
125
+ * cannot produce a response Pi would read as a missing field.
126
+ */
127
+ export function buildExtensionUiResponse(request, answer) {
128
+ if (answer.cancelled)
129
+ return { type: "extension_ui_response", id: request.requestId, cancelled: true };
130
+ if (request.method === "confirm")
131
+ return { type: "extension_ui_response", id: request.requestId, confirmed: answer.confirmed === true };
132
+ return { type: "extension_ui_response", id: request.requestId, value: answer.value ?? "" };
133
+ }
134
+ /**
135
+ * The commands a freshly spawned Pi must be told before it runs a conversation's turn.
136
+ *
137
+ * This is the whole mechanism behind the picker: PiRpcRuntime spawns one Pi process per turn and
138
+ * kills it afterwards, so there is no long-lived session to poke. Writing these commands onto that
139
+ * process's stdin before the prompt is what makes a selection REAL - Pi answers `set_model` with
140
+ * the model it switched to, and the prompt that follows runs on it.
141
+ *
142
+ * Model BEFORE level, and the order is load-bearing: `AgentSession.setModel` re-derives the thinking
143
+ * level for the new model (agent-session.ts:2493), so applying the level first would have Pi undo it
144
+ * on the very next line.
145
+ *
146
+ * A conversation with neither selection produces NO commands, which is what keeps every
147
+ * pre-picker conversation on Pi's own defaults.
148
+ */
149
+ export function sessionCommands(conversation) {
150
+ const commands = [];
151
+ const model = conversation.model;
152
+ if (model?.provider && model.modelId)
153
+ commands.push({ id: "set_model", type: "set_model", ...{ provider: model.provider, modelId: model.modelId } });
154
+ if (conversation.thinkingLevel)
155
+ commands.push({ id: "set_thinking_level", type: "set_thinking_level", ...{ level: conversation.thinkingLevel } });
156
+ return commands;
157
+ }
158
+ /**
159
+ * Kills a whole process tree on Windows. Pi is launched through a .cmd shim (spawn with shell:true),
160
+ * so the spawned process is cmd.exe and the real Pi is its grandchild: killing the shim alone leaks
161
+ * Pi, which keeps holding its working directory and the RPC pipes. No-op on a pid that already died.
162
+ *
163
+ * Exported rather than reimplemented per spawner: a second copy is how one of the two ends up killing
164
+ * only the shim, which is the exact failure this function exists to prevent.
165
+ */
166
+ export function killTree(pid) {
167
+ return new Promise((resolve) => {
168
+ const killer = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore" });
169
+ killer.once("exit", () => resolve());
170
+ killer.once("error", () => resolve());
171
+ });
172
+ }
173
+ /** Let Pi flush its extension shutdown hooks before using the process-tree backstop. */
174
+ export async function closePiWorker(child) {
175
+ const exited = () => child.exitCode !== null || child.signalCode !== null;
176
+ if (exited())
177
+ return;
178
+ const wait = (ms) => new Promise(resolve => {
179
+ const finish = () => { clearTimeout(timer); child.off("exit", finish); resolve(); };
180
+ const timer = setTimeout(finish, ms);
181
+ child.once("exit", finish);
182
+ if (exited())
183
+ finish();
184
+ });
185
+ child.stdin.end();
186
+ await wait(2000);
187
+ if (!exited() && child.pid !== undefined) {
188
+ if (process.platform === "win32")
189
+ await killTree(child.pid);
190
+ else {
191
+ try {
192
+ process.kill(-child.pid, "SIGKILL");
193
+ }
194
+ catch {
195
+ child.kill("SIGKILL");
196
+ }
197
+ }
198
+ await wait(2000);
199
+ }
200
+ }
201
+ // Session-file mutation and validation live behind this boundary; runtime only locates Pi sessions.
202
+ /** How long one command may take before the turn is failed rather than left hanging. */
203
+ const SESSION_COMMAND_TIMEOUT_MS = 10_000;
204
+ /** `get_state`/`get_entries` on an idle Pi. Generous, because it only has to answer a question. */
205
+ const LOOKUP_COMMAND_TIMEOUT_MS = 30_000;
206
+ /**
207
+ * How long a `steer` may go unanswered before the caller is told the outcome is unknown.
208
+ *
209
+ * The same budget as any other single Pi command, for the same reason: this is one round-trip to a
210
+ * local child that is already busy running a turn. It is generous because the child is mid-turn and may
211
+ * not read stdin promptly - too short a budget would report "unknown" for steers Pi simply had not got
212
+ * to yet, which is exactly the ambiguity this whole path exists to avoid.
213
+ */
214
+ const STEER_COMMAND_TIMEOUT_MS = 10_000;
215
+ /**
216
+ * Reads Pi's `steer` disposition out of its response payload.
217
+ *
218
+ * Unknown and missing both become `queued`, which is the CONSERVATIVE default and not a convenience: a
219
+ * steer Pi could not categorise may or may not already be in the model's context, so it must keep being
220
+ * treated as "not yet delivered" until a `queue_update` says otherwise. Guessing `handled` would let the
221
+ * caller drop the message from the dock on the strength of a payload shape we did not recognise.
222
+ */
223
+ export function describeSteerDisposition(data) {
224
+ const disposition = data?.disposition;
225
+ return disposition === "handled" || disposition === "queued" ? disposition : "queued";
226
+ }
227
+ /**
228
+ * How long a catalog answer is reused. Pi's model list changes when the user edits its config, never
229
+ * on a timer, so this only trades freshness for the ~400-840ms a probe Pi costs - measured here at
230
+ * 394ms for all three commands written at once. Ten minutes is long enough that reopening a picker
231
+ * twice in a session never pays for a second spawn, and short enough that a `pi models add` shows up
232
+ * the same afternoon.
233
+ */
234
+ const CATALOG_TTL_MS = 10 * 60_000;
235
+ /** A FAILED catalog is cached for far less time, so one broken Pi cannot be retried on every keystroke of a model switch. */
236
+ const CATALOG_FAILURE_TTL_MS = 30_000;
237
+ const CATALOG_COMMAND_TIMEOUT_MS = 15_000;
238
+ /**
239
+ * Keys Pi's model answers by. Exported so the store and the tests agree with the runtime.
240
+ *
241
+ * THE MODEL LIST IS SHARED. The list of models Pi offers is the same answer whichever model a
242
+ * conversation has selected - it is not the list of models one conversation may use. So the list has
243
+ * ONE key, and every conversation shares it.
244
+ *
245
+ * THE THINKING LEVELS BELONG TO THE MODEL IN USE, so they get a key PER MODEL. This used to be one
246
+ * "levels" key for every model, on the assumption that the level list is the same whichever model is
247
+ * selected - and that assumption is wrong: Pi computes the levels from the model itself
248
+ * (`getSupportedThinkingLevels`: a model that cannot reason offers only "off", and a model whose
249
+ * thinking map says so offers fewer). Measured with one key: after reading the levels for a reasoning
250
+ * model, a NON-reasoning model was offered the reasoning model's levels, and the other way round - so
251
+ * the picker offered levels the model in force does not have, and hid the ones it does. Super Pi
252
+ * cannot compute the levels itself instead: Pi's rule is not exported, and a second implementation of
253
+ * it would drift from Pi's.
254
+ *
255
+ * THE COST OF A KEY PER MODEL, and why it is not what it used to be. An earlier version of this
256
+ * comment said that keying on the model "meant a cache miss for every model a person ever picked, and
257
+ * every miss was a process start - so the picker went grey again after every model change". That was
258
+ * true when the catalog ALWAYS answered by spawning a Pi, which is no longer how the ordinary path
259
+ * works: the SDK path reads the levels out of a session (measured ~30ms, no process at all) and caches
260
+ * them per model. The one-shot path - a Pi the person named explicitly - does pay a spawn for a model
261
+ * it has not read yet, and that is the price of asking Pi rather than guessing at its rule.
262
+ */
263
+ export const catalogKey = (selection) => (selection?.provider && selection.modelId ? `levels:${selection.provider}/${selection.modelId}` : "list");
264
+ /**
265
+ * Where the `task` extension lives, as an ABSOLUTE path.
266
+ *
267
+ * Absolute because Pi requires it: `--extension` takes the path verbatim and resolves it against Pi's
268
+ * own working directory, which is the CONVERSATION's workspace, not this repository. A relative path
269
+ * would therefore resolve differently for every conversation and fail for all of them except the one
270
+ * whose workspace happens to be this repo.
271
+ *
272
+ * `import.meta.dirname` is the one thing stable across both ways this code runs - `dist/server/` after
273
+ * `tsc -b`, `src/server/` under `tsx watch` - so two `..` segments reach the repository root either way.
274
+ *
275
+ * Returned as a FUNCTION rather than a module constant so a test can assert on the resolution without
276
+ * this module's import-time filesystem state deciding it, and so the "does it exist" check below is a
277
+ * warning on a path that is genuinely optional rather than a startup crash on a build that skipped it.
278
+ */
279
+ export function taskExtensionPath(from = import.meta.dirname) {
280
+ return resolve(from, "../../agents/super-pi-task/index.ts");
281
+ }
282
+ /**
283
+ * The document extension's file, resolved the same way the task extension's is: two `..` segments
284
+ * from `import.meta.dirname` reach the repository root both after `tsc -b` and under `tsx watch`.
285
+ */
286
+ export function documentExtensionPath(from = import.meta.dirname) {
287
+ return resolve(from, "../../agents/super-pi-documents/index.ts");
288
+ }
289
+ /**
290
+ * The Feishu extension's file, resolved the same way the document extension's is.
291
+ *
292
+ * Named on both sides of the wire rather than imported by the extension, for the reason every one
293
+ * of these names is written out twice: `agents/` is loaded by Pi's module loader and `src/` by
294
+ * tsc, so a relative import across the two would resolve differently under each.
295
+ */
296
+ export function feishuExtensionPath(from = import.meta.dirname) {
297
+ return resolve(from, "../../agents/super-pi-feishu/index.ts");
298
+ }
299
+ /** Bridges a Pi session to Super Pi through Pi's documented JSONL RPC protocol. */
300
+ /**
301
+ * The tool's name as far as the stream has revealed it so far, or an empty string while the model is
302
+ * still on the first token. Deliberately NOT a placeholder: a block labelled 「工具」 tells the reader
303
+ * nothing they cannot already see, whereas one labelled 'edit' one second early is the whole point.
304
+ *
305
+ * THE EVENT IS READ BEFORE `partial`, and that order is the whole fix. This used to look only at
306
+ * `partial` - the half-built assistant message - which is where the Anthropic and pi-messages converters
307
+ * put the toolCall block. Real Pi does NOT send it: a live RPC probe against Pi itself returns
308
+ * `toolcall_start {"contentIndex":1,"id":"call_…","toolName":"read","hasPartial":false}`, the name on the
309
+ * event and no `partial` at all. So this returned "" for every call the user ever made, every placeholder
310
+ * row was filed under an empty name, and the name-based lookup that pairs a call with the row the reader
311
+ * is already looking at could never match - see `onToolCall` in application/run-service.ts, which then
312
+ * fell back to recency and put the calls on each other's rows. Reading `toolName` first is what makes the
313
+ * pairing work at all; `partial` stays as the fallback for a Pi that only fills the message.
314
+ */
315
+ function toolNameOf(event) {
316
+ const direct = event?.toolName;
317
+ if (typeof direct === "string" && direct)
318
+ return direct;
319
+ const content = event?.partial?.content;
320
+ const block = Array.isArray(content) ? content.find((item) => item?.type === "toolCall") : undefined;
321
+ return typeof block?.name === "string" ? block.name : "";
322
+ }
323
+ export class PiRpcRuntime {
324
+ sessionDir;
325
+ agents;
326
+ options;
327
+ memory;
328
+ setMemory(memory) { this.memory = memory; }
329
+ /**
330
+ * The memory and knowledge credentials minted for each LIVE session, so they can be released when
331
+ * the session goes. A credential whose session is gone must not keep working - that is exactly the
332
+ * shape of a secret with no owner.
333
+ */
334
+ sessionExtensionTokens = new Map();
335
+ knowledge;
336
+ setKnowledge(knowledge) { this.knowledge = knowledge; }
337
+ runs = new Map();
338
+ /**
339
+ * THE LIVE SESSIONS, one per conversation, alive across turns.
340
+ *
341
+ * `runs` is the OLD registry - a child that exists only while a turn is running - and it still
342
+ * describes the one-shot paths (memory review, knowledge rerank, catalog probe), which keep their
343
+ * own throwaway children. The main conversation path does NOT use it: a conversation's session lives
344
+ * in the pool, and a turn is a run ON that session rather than a process OF its own.
345
+ */
346
+ sessionPool;
347
+ /** Where Super Pi itself is installed, which is also where its own extensions are found. */
348
+ repositoryRoot;
349
+ /**
350
+ * The turn currently running on each conversation's session.
351
+ *
352
+ * This is the piece the old design did not need, because a turn WAS a process and the process
353
+ * registry said everything. With a session that outlives its turns, the host has to know which turn
354
+ * is on the session RIGHT NOW - that is what an abort targets, and what a steer is delivered into.
355
+ */
356
+ activeTurns = new Map();
357
+ /**
358
+ * THE CURRENT TURN'S EXTENSION-UI HOST, per conversation.
359
+ *
360
+ * Pi's blocking UI questions (`select`/`confirm`/`input`/`editor`) are answered by a host, and the
361
+ * host is a per-TURN thing - `run-service` builds one per `answer()` call - while the UI context the
362
+ * session's extensions talk to is bound ONCE per session. This map is the bridge between the two
363
+ * lifetimes: a turn registers its host here for exactly its own duration, and the session's bound
364
+ * context reads through it at call time. A question asked while no turn is registered gets the honest
365
+ * answer - `cancelled` - never a default, which is the same rule the RPC path's no-host branch follows.
366
+ */
367
+ sessionHosts = new Map();
368
+ /** The sessions whose extension runner already has the UI bridge bound. */
369
+ uiBoundSessions = new WeakSet();
370
+ backgroundUsageObservers = new Map();
371
+ backgroundUsageWrites = Promise.resolve();
372
+ cacheWarmingWrites = Promise.resolve();
373
+ cacheWarmingOverride;
374
+ cacheWarmingEpoch = 0;
375
+ /**
376
+ * The session-file path last reported for a conversation, so `onSessionFile` fires when it CHANGES
377
+ * rather than once per turn. The path is stable for the life of a session; what changes it is a
378
+ * rebuild (a revert, an eviction, a fingerprint change), which is exactly when the cached locator
379
+ * needs refreshing.
380
+ */
381
+ reportedSessionFiles = new Map();
382
+ /**
383
+ * `steer` commands written to a child and not yet answered by Pi, keyed by the command id.
384
+ *
385
+ * A steer has to be correlated to a promise rather than fire-and-forget, because Pi's `steer` response
386
+ * carries a `disposition` that decides whether the message is already in the model's context or still
387
+ * waiting (`handled` vs `queued`, `rpc-mode.ts:416-419`). Without that answer Super Pi would have to
388
+ * guess, and both guesses are wrong: reporting a delivered steer as waiting would leave a message
389
+ * stranded in the dock forever, and reporting a waiting one as delivered would let the user cancel a
390
+ * message the model is about to act on.
391
+ */
392
+ pendingSteers = new Map();
393
+ /** Distinguishes steer command ids. Never reused, so a late response cannot settle a later steer. */
394
+ steerSeq = 0;
395
+ catalogs = new Map();
396
+ /**
397
+ * In-flight reads, so N clients asking at once cost ONE read rather than N.
398
+ *
399
+ * "One read", not "one Pi spawn": the catalog is answered out of Pi's SDK and no process is started
400
+ * at all. The wording here used to promise a shared spawn, which is what the old implementation did.
401
+ */
402
+ pendingCatalogs = new Map();
403
+ /**
404
+ * Pi's SDK catalog reader, built once and reused.
405
+ *
406
+ * The ModelRuntime and SettingsManager it holds read the auth store and the model store from disk, so
407
+ * building a new one per call would put back the I/O this exists to avoid. They are read-mostly
408
+ * views of files that change rarely, and Pi's own long-lived session holds the same objects for its
409
+ * whole life.
410
+ *
411
+ * A FAILED build is remembered as a failure rather than retried per call: a broken SDK would
412
+ * otherwise be re-imported on every picker open.
413
+ */
414
+ sdkCatalogPromise;
415
+ /**
416
+ * Bumped whenever the set of models Pi knows about changes.
417
+ *
418
+ * A live session holds its own `ModelRuntime`, built when the session was built, and that runtime
419
+ * does not know about a provider added afterwards. Pi's refusal to switch to a model its runtime
420
+ * does not have is swallowed by the session pool into a warning, so the turn would go on running
421
+ * the OLD model while the picker said the new one - a control that lies. The sessions are made
422
+ * STALE by this counter instead: each one is rebuilt at its next turn, which is a moment when
423
+ * throwing a session away costs nothing, and the new one is built with a runtime that knows.
424
+ */
425
+ modelEpoch = 0;
426
+ /** Latches the "no extension on disk" warning, so it is said once rather than once per turn. */
427
+ warnedMissingExtension = false;
428
+ /** Latches the "the document extension is missing" warning, for the same reason. */
429
+ warnedMissingDocumentExtension = false;
430
+ /** Latches the "the Feishu extension is missing" warning, for the same reason. */
431
+ warnedMissingFeishuExtension = false;
432
+ /** Latches the "Pi's SDK is not installed" warning, for the same reason. */
433
+ warnedMissingSdk = false;
434
+ /**
435
+ * How a CONVERSATION runs: on a persistent SDK session, or by spawning a Pi for every turn.
436
+ *
437
+ * is the slower one, and it exists for the test suite: those suites drive a fake Pi that
438
+ * speaks the RPC protocol over a pipe, and a program is not a library - the session path cannot run
439
+ * it. It is an explicit request rather than something inferred from which Pi happens to be named,
440
+ * because inferring it is what made the Pi extension start conversations on the slow path without
441
+ * saying why.
442
+ */
443
+ sessionMode;
444
+ /**
445
+ * Agent definitions are read from disk, never cached. A file is cheap to parse, and re-reading it
446
+ * per turn is the whole point: editing an agent's prompt or tool allowlist changes the NEXT message
447
+ * with no re-selection and no restart, which a cache would silently prevent.
448
+ *
449
+ * `command` is an override for tests and for a Pi installed somewhere unusual; with none given, Pi is
450
+ * resolved through `resolvePiCommand()` (override -> PATH -> npm's global bin directory), the same
451
+ * function scripts/probe-agent-real-pi.mjs uses. Resolved ONCE here because it is a filesystem
452
+ * lookup, and a resolution that could change mid-run would make a turn's spawn line depend on when
453
+ * it was started.
454
+ */
455
+ pi;
456
+ /**
457
+ * HOW MANY LIVE SESSIONS THIS CONVERSATION HAS, and whether it has one at all.
458
+ *
459
+ * A reader of this number learns whether a conversation's context is still in Pi's memory. That is
460
+ * the fact a revert has to change: it rewrites the transcript on disk, and a live session keeps the
461
+ * OLD context in memory, so a session that outlived the revert is a model that answers from
462
+ * history the person withdrew - with nothing saying so.
463
+ *
464
+ * It is here because that failure is invisible from the outside: the file is shorter, the state is
465
+ * clean, and only the model knows something the reader cannot see.
466
+ */
467
+ liveSessionCount(conversationId) {
468
+ return this.sessionPool.has(conversationId) ? 1 : 0;
469
+ }
470
+ canSteer(conversationId) {
471
+ // A steer is only meaningful while a turn is RUNNING. A live session with nothing running is not a
472
+ // steer target: there is no current answer for the message to be inserted into, and the transcript's
473
+ // split-on-delivery model would have nothing to split. So this asks about the TURN, not about the
474
+ // process - which is the change the persistent session forces, and the reason it is stated here
475
+ // rather than left to a caller that used to infer it from a live child.
476
+ if (this.activeTurns.has(conversationId))
477
+ return true;
478
+ const run = this.runs.get(conversationId);
479
+ return Boolean(run && run.child.exitCode === null && !run.child.killed && !run.child.stdin.destroyed);
480
+ }
481
+ constructor(sessionDir, command,
482
+ /**
483
+ * Where agent definitions are read from and where their prompt bodies are written. A THIRD positional
484
+ * parameter rather than part of the second one, so every existing `new PiRpcRuntime(dir, launcher)`
485
+ * call site keeps its meaning - moving the agent directory into that slot would have silently fed a
486
+ * launcher's file path in as a directory of agent definitions.
487
+ */
488
+ agents = { dir: join(sessionDir, "agents"), promptDir: join(sessionDir, "agent-prompts") },
489
+ /**
490
+ * How the `task` extension reaches this server. A FOURTH positional parameter for the same reason as
491
+ * the third: an options bag in one of the earlier slots would silently change what an existing
492
+ * `new PiRpcRuntime(dir, launcher, { dir, promptDir })` call site means.
493
+ *
494
+ * `endpoint` is this server's own listening URL, supplied rather than derived. It is the fix for
495
+ * hardcoding a port: `SUPER_PI_PORT` is honoured by `index.ts` and by every test that boots on
496
+ * `freePort()`, so an extension that dialled a fixed number would reach nothing at all. When it is
497
+ * absent the extension is simply not mounted, and the reason is logged once per turn rather than
498
+ * swallowed - a task tool that is mysteriously missing is the single hardest failure here to
499
+ * diagnose from the outside.
500
+ *
501
+ * `todoEndpoint` is the `todowrite` endpoint, supplied the same way and for the same reason, and it
502
+ * is a SEPARATE field rather than a path derived from `endpoint`: the two tools are allowed to be
503
+ * available independently (a harness that only exercises dispatch does not want a todo writer, and an
504
+ * older checkout has no todo endpoint at all), and a derived path could not tell "not configured"
505
+ * from "configured wrong". When it is absent the tool still registers and the extension refuses in
506
+ * words, which is what `refuseTodo` in core.ts is for.
507
+ *
508
+ * `sessionFactory` is the TEST SEAM for the session path: the pool builds sessions through it instead
509
+ * of `createPiSession`, so a test can drive `answer()` against a fake `PiSessionLike` and assert on
510
+ * what the turn did with it - the same role the factory parameter plays in `PiSessionPool` itself.
511
+ */
512
+ options = {}) {
513
+ this.sessionDir = sessionDir;
514
+ this.agents = agents;
515
+ this.options = options;
516
+ this.pi = resolvePiCommand({ command });
517
+ if (!this.pi.found)
518
+ console.warn(`PiRpcRuntime: ${this.pi.reason}`);
519
+ this.sessionMode = this.options.sessionMode
520
+ ?? (process.env.SUPER_PI_SESSION_MODE === "oneshot" ? "oneshot" : "sdk");
521
+ this.repositoryRoot = repositoryRootFrom();
522
+ this.sessionPool = new PiSessionPool(sessionDir, this.repositoryRoot, undefined, (conversationId) => {
523
+ // A session's credential dies with the session. The session is what HELD the token - its
524
+ // extension read it out of the environment when it was loaded - so a session that is gone must
525
+ // not leave a usable token behind.
526
+ releaseCapability(conversationId);
527
+ // The session also held this conversation's UI bridge and session-file cache; both are facts
528
+ // ABOUT that session and stop being true with it.
529
+ this.sessionHosts.delete(conversationId);
530
+ this.reportedSessionFiles.delete(conversationId);
531
+ this.backgroundUsageObservers.get(conversationId)?.();
532
+ this.backgroundUsageObservers.delete(conversationId);
533
+ // The session held these credentials too, so they die with it.
534
+ const tokens = this.sessionExtensionTokens.get(conversationId);
535
+ if (tokens) {
536
+ if (tokens.memoryToken)
537
+ this.memory?.release(tokens.memoryToken);
538
+ if (tokens.knowledgeToken)
539
+ this.knowledge?.release(tokens.knowledgeToken);
540
+ this.sessionExtensionTokens.delete(conversationId);
541
+ }
542
+ }, options.sessionFactory ?? createPiSession, (conversationId) => mintCapability(conversationId), () => this.modelEpoch, (conversationId) => this.mintSessionExtensionTokens(conversationId));
543
+ }
544
+ /**
545
+ * The configuration of the session that was built for a conversation, for tests to inspect.
546
+ *
547
+ * WHY THIS EXISTS. The permission boundary - an agent's tool allowlist, its prompt file, the
548
+ * extensions it mounts - used to be proved by reading the ARGV of a spawned child. A session is not
549
+ * a child and has no argv, so the evidence moved: this is what the session was actually BUILT with,
550
+ * which is the same fact stated in the new architecture's terms.
551
+ *
552
+ * It is a RECORD, not a control channel: nothing in the runtime reads it back, and a test that
553
+ * asserts on it is asserting on the real decision the real code made.
554
+ */
555
+ builtSessions = new Map();
556
+ /** The configuration a conversation's session was built with, if one was built. */
557
+ builtSessionConfig(conversationId) {
558
+ return this.builtSessions.get(conversationId);
559
+ }
560
+ /**
561
+ * Which path a CONVERSATION on this runtime takes.
562
+ *
563
+ * Exposed so a test can assert it. The bug this exists to prevent was invisible from the outside:
564
+ * the version number said 0.1.95 while every conversation was still spawning a process per turn,
565
+ * and nothing said why. A test that can ask "would a conversation here spawn a Pi?" can catch that.
566
+ */
567
+ get conversationPath() {
568
+ return this.sessionMode;
569
+ }
570
+ /**
571
+ * Whether the SDK-backed session layer can be used at all.
572
+ *
573
+ * The SDK is a LIBRARY and it is optional: Super Pi also supports running against a Pi installed as a
574
+ * COMMAND, and a server that cannot load the library still has a working one-shot path for the
575
+ * conversations it can serve. The answer is reported rather than thrown, so the caller can say what is
576
+ * missing instead of failing a turn with a stack trace.
577
+ */
578
+ async sessionSupport() {
579
+ return piSdkAvailable();
580
+ }
581
+ /**
582
+ * Throws away every live session.
583
+ *
584
+ * Called at shutdown, and after a `revert` - the transcript on disk changed, and a session holding
585
+ * the old context in memory would keep answering from history the user has withdrawn.
586
+ */
587
+ async disposeSessions(conversationId) {
588
+ if (conversationId)
589
+ await this.sessionPool.evict(conversationId);
590
+ else
591
+ await this.sessionPool.disposeAll();
592
+ await this.backgroundUsageWrites;
593
+ }
594
+ async cacheWarmingSettings() {
595
+ const mode = await piCacheWarmingMode();
596
+ const sessions = this.sessionPool.conversationIds.map(id => this.sessionPool.get(id)).filter(Boolean);
597
+ return { mode, liveSessions: sessions.length,
598
+ scheduled: sessions.filter(session => session?.cacheWarmingStatus?.state === "scheduled").length,
599
+ refreshing: sessions.filter(session => session?.cacheWarmingStatus?.state === "refreshing").length };
600
+ }
601
+ reloadNativeTools() { this.modelEpoch++; }
602
+ async setCacheWarming(mode) {
603
+ if (!isPiCacheWarmingMode(mode))
604
+ throw new Error("请选择有效的缓存预热模式。");
605
+ const update = this.cacheWarmingWrites.then(async () => {
606
+ await piCacheWarmingMode(mode);
607
+ this.cacheWarmingOverride = mode;
608
+ this.cacheWarmingEpoch++;
609
+ for (const id of this.sessionPool.conversationIds) {
610
+ const session = this.sessionPool.get(id);
611
+ session?.setCacheWarmingMode?.(mode);
612
+ await session?.settingsManager?.flush();
613
+ if (session?.settingsManager?.drainErrors?.().length)
614
+ throw new Error("Pi 会话缓存设置同步失败,请检查服务端目录权限。");
615
+ }
616
+ return this.cacheWarmingSettings();
617
+ });
618
+ this.cacheWarmingWrites = update.catch(() => undefined);
619
+ return update;
620
+ }
621
+ observeBackgroundUsage(conversationId, session) {
622
+ if (!this.options.onBackgroundUsage || this.backgroundUsageObservers.has(conversationId))
623
+ return;
624
+ const record = (value) => {
625
+ if (!value || typeof value !== "object")
626
+ return;
627
+ const entry = value;
628
+ if (entry.type !== "usage" || entry.kind !== "cache_warm" || !entry.id)
629
+ return;
630
+ const collector = new ConversationUsageCollector();
631
+ collector.add(entry.usage, false);
632
+ const readout = { ...collector.readout(undefined, session.model, defaultAgentDir()), sourceEntryId: entry.id };
633
+ if (!readout.usage)
634
+ return;
635
+ this.backgroundUsageWrites = this.backgroundUsageWrites.then(() => this.options.onBackgroundUsage(conversationId, readout))
636
+ .catch(() => { console.warn(`PiRpcRuntime: could not persist cache-warming usage for conversation ${conversationId}. It will be retried when the transcript is reopened.`); });
637
+ };
638
+ this.backgroundUsageObservers.set(conversationId, session.subscribe(event => {
639
+ const item = event;
640
+ if (item?.type === "entry_appended")
641
+ record(item.entry);
642
+ }));
643
+ // Reconcile persisted entries after restart or eviction. The store deduplicates by entry id.
644
+ for (const entry of session.sessionManager?.getEntries?.() ?? [])
645
+ record(entry);
646
+ }
647
+ /** Throws away the sessions that have been idle for a while. */
648
+ async evictIdleSessions() {
649
+ await this.sessionPool.evictIdle();
650
+ }
651
+ /**
652
+ * The agent a conversation runs as, or undefined for Pi's own defaults.
653
+ *
654
+ * A selected role must remain valid. Missing or invalid definitions are refused before
655
+ * spawning Pi so their prompt and tool restrictions cannot silently disappear.
656
+ */
657
+ async agentFor(conversation) {
658
+ if (!conversation.agentId)
659
+ return undefined;
660
+ const { agents } = await readAgents(this.agents.dir);
661
+ const agent = agents.find((item) => item.id === conversation.agentId);
662
+ if (agent)
663
+ return agent;
664
+ const dirLabel = Array.isArray(this.agents.dir) ? this.agents.dir.join(", ") : this.agents.dir;
665
+ throw new Error(`Agent ${JSON.stringify(conversation.agentId)} 已失效或不是可用的 primary agent(目录:${dirLabel})。请重新选择 Agent,或选择“跟随 Pi 默认”后重试。`);
666
+ }
667
+ modelValidator;
668
+ setModelValidator(validator) { this.modelValidator = validator; }
669
+ setAgentsDir(dir) {
670
+ this.agents.dir = dir;
671
+ }
672
+ /**
673
+ * The `--extension` argv for this turn, or `[]` when the task tool is not available.
674
+ *
675
+ * Empty in TWO different situations, and both are deliberate rather than merged:
676
+ *
677
+ * - No endpoint was configured, so there is nowhere for the extension to dispatch to. Mounting it
678
+ * anyway would give the model a tool whose every call fails with a network error.
679
+ * - The extension file is not on disk. That is a build or checkout problem, and it is warned about
680
+ * ONCE rather than every turn, because "your primary agent cannot delegate anything" is worth
681
+ * knowing and worth not repeating on every keystroke.
682
+ */
683
+ async taskExtensionArgs() {
684
+ if (!this.options.endpoint)
685
+ return [];
686
+ const path = taskExtensionPath();
687
+ if (!existsSync(path)) {
688
+ if (!this.warnedMissingExtension) {
689
+ this.warnedMissingExtension = true;
690
+ console.warn(`PiRpcRuntime: ${path} does not exist, so the primary agent cannot delegate to sub-agents. The task tool is off for every conversation until it is restored.`);
691
+ }
692
+ return [];
693
+ }
694
+ return ["--extension", path];
695
+ }
696
+ /**
697
+ * The document extension's spawn argument.
698
+ *
699
+ * IT IS MOUNTED UNCONDITIONALLY, unlike the knowledge extension. The knowledge extension is only
700
+ * worth mounting when the workspace HAS documents, because its tool returns nothing otherwise; the
701
+ * document tools are about the files in the workspace, and a workspace with no PDF in it is exactly
702
+ * the workspace where an agent might be asked to WRITE one.
703
+ *
704
+ * The endpoint is the gate: without it the extension returns without registering anything, so a
705
+ * runtime with no document endpoint mounts nothing rather than a tool whose every call fails.
706
+ */
707
+ documentExtensionArgs() {
708
+ if (!this.options.documentsEndpoint)
709
+ return [];
710
+ const path = documentExtensionPath();
711
+ if (!existsSync(path)) {
712
+ if (!this.warnedMissingDocumentExtension) {
713
+ this.warnedMissingDocumentExtension = true;
714
+ console.warn(`PiRpcRuntime: ${path} does not exist, so the primary agent cannot read or write PDF, Word and Excel files.`);
715
+ }
716
+ return [];
717
+ }
718
+ return ["--extension", path];
719
+ }
720
+ /**
721
+ * The Feishu extension's spawn argument.
722
+ *
723
+ * MOUNTED UNCONDITIONALLY, for the same reason the document tools are: the endpoint is the gate,
724
+ * and the extension registers nothing without it. The credential is NOT the gate - a user who
725
+ * has not configured an application yet still gets the tools, because the error those tools
726
+ * return is the one that tells the user what to do, and a tool that is simply absent cannot say
727
+ * anything at all.
728
+ */
729
+ feishuExtensionArgs() {
730
+ if (!process.env.SUPER_PI_FEISHU_ENDPOINT)
731
+ return [];
732
+ const path = feishuExtensionPath();
733
+ if (!existsSync(path)) {
734
+ if (!this.warnedMissingFeishuExtension) {
735
+ this.warnedMissingFeishuExtension = true;
736
+ console.warn(`PiRpcRuntime: ${path} does not exist, so the primary agent cannot read or write Feishu cloud documents.`);
737
+ }
738
+ return [];
739
+ }
740
+ return ["--extension", path];
741
+ }
742
+ /**
743
+ * The five values the extension reads out of its own environment. See `task-tool.ts` for why they are
744
+ * written out on both sides rather than imported.
745
+ *
746
+ * The ROSTER is read here, per turn, from the same `readAgents` the picker and the supervisor use -
747
+ * never from a list written into this file. A sub-agent added while the server is running is therefore
748
+ * dispatchable on the next message with no restart, which is the same freshness rule `agentFor`
749
+ * follows for agent files and for the same reason: a human edits those files while the server runs.
750
+ *
751
+ * `depth` is `0`, hardcoded, and that is not an oversight: this is the PRIMARY agent's spawn, so it is
752
+ * definitionally at the top of the tree. `SubagentSupervisor` never passes this function, which is why
753
+ * no sub-agent process is ever given this environment at all.
754
+ *
755
+ * The TODO ENDPOINT is the one value here that is NOT per-turn derived from disk: it is this server's
756
+ * own address, so it is the same string on every turn and is read once from the constructor's options.
757
+ */
758
+ /**
759
+ * THE MEMORY AND KNOWLEDGE CREDENTIALS FOR A NEW SESSION.
760
+ *
761
+ * Both extensions read their environment ONCE, when they are loaded, so these are minted where the
762
+ * session is born - the same place, and for the same reason, as the session's capability. The
763
+ * one-shot path has always minted them (per turn); the session path minted none, so the memory and
764
+ * knowledge extensions returned before registering a tool or injecting a prompt, and both features
765
+ * were missing in production - the SDK session path is the DEFAULT backend, and only the test
766
+ * scripts take the one-shot path (ledger TEST-039).
767
+ *
768
+ * The endpoints are published as global environment variables (index.ts), and they are repeated
769
+ * here so the extension's contract is stated in one place: an endpoint and a credential travel
770
+ * together, and the credential is what proves the caller.
771
+ */
772
+ async mintSessionExtensionTokens(conversationId) {
773
+ const minted = {};
774
+ const env = {};
775
+ if (this.memory && (await this.memory.configuration()).enabled) {
776
+ minted.memoryToken = this.memory.issue(conversationId);
777
+ env.SUPER_PI_MEMORY_TOKEN = minted.memoryToken;
778
+ env.SUPER_PI_MEMORY_ENDPOINT = process.env.SUPER_PI_MEMORY_ENDPOINT ?? "";
779
+ }
780
+ if (this.knowledge && this.knowledge.enabled()) {
781
+ minted.knowledgeToken = this.knowledge.issue(conversationId);
782
+ env.SUPER_PI_KNOWLEDGE_TOKEN = minted.knowledgeToken;
783
+ env.SUPER_PI_KNOWLEDGE_ENDPOINT = process.env.SUPER_PI_KNOWLEDGE_ENDPOINT ?? "";
784
+ }
785
+ if (minted.memoryToken || minted.knowledgeToken)
786
+ this.sessionExtensionTokens.set(conversationId, minted);
787
+ return env;
788
+ }
789
+ /**
790
+ * The environment Super Pi's extensions read when they are loaded.
791
+ *
792
+ * IT DOES NOT INCLUDE THE CREDENTIAL. The credential is minted by the session pool, when the session
793
+ * is created, and added there - because the credential belongs to the SESSION (the extension reads
794
+ * its environment once, when it is loaded) and a token minted per turn would be replaced before the
795
+ * second turn of the conversation, leaving the extension holding a value the server had forgotten.
796
+ */
797
+ async taskExtensionEnv(conversationId, workspaceId, parentConversationId) {
798
+ const { agents, problems } = await readAgents(this.agents.dir, { mode: "subagent" });
799
+ for (const problem of problems)
800
+ console.warn(`PiRpcRuntime: ${problem.file} is not a usable sub-agent - ${problem.message}`);
801
+ return {
802
+ [TASK_ENDPOINT_ENV]: this.options.endpoint ?? "",
803
+ [TASK_EXEC_ENDPOINT_ENV]: this.options.execEndpoint ?? "",
804
+ [TASK_ROSTER_ENV]: rosterPayload(agents),
805
+ [TASK_CONVERSATION_ENV]: conversationId,
806
+ [PARENT_CONVERSATION_ENV]: parentConversationId ?? "",
807
+ [TASK_DEPTH_ENV]: "0",
808
+ [TODO_ENDPOINT_ENV]: this.options.todoEndpoint ?? "",
809
+ [PROJECT_ENDPOINT_ENV]: this.options.orchestratorEndpoint?.replace(/\/api\/orchestrator$/, "/api/projects/tool") ?? "",
810
+ [SCHEDULED_TASK_ENDPOINT_ENV]: this.options.scheduledTaskEndpoint ?? "",
811
+ [WORKFLOW_ENDPOINT_ENV]: this.options.workflowEndpoint ?? "",
812
+ [ORCHESTRATOR_ENDPOINT_ENV]: this.options.orchestratorEndpoint ?? "",
813
+ [ORCHESTRATOR_WORKSPACE_ENV]: workspaceId,
814
+ SUPER_PI_ORCHESTRATOR_CONVERSATION: conversationId,
815
+ SUPER_PI_QUESTION_ENDPOINT: this.options.questionEndpoint ?? "",
816
+ SUPER_PI_TOOLS_ENDPOINT: this.options.toolsEndpoint ?? "",
817
+ // The document tools' endpoint and the conversation they act for. The CREDENTIAL is not here:
818
+ // it is the session's own capability, which the session pool adds to this environment when the
819
+ // session is born, and the document extension reads that same value. Minting a second
820
+ // credential for the same session would be a second thing to rotate and a second thing to
821
+ // forget to release.
822
+ SUPER_PI_DOCUMENTS_ENDPOINT: this.options.documentsEndpoint ?? "",
823
+ SUPER_PI_DOCUMENTS_CONVERSATION: conversationId,
824
+ SUPER_PI_WEB_ENDPOINT: process.env.SUPER_PI_WEB_ENABLED === "1" ? process.env.SUPER_PI_WEB_ENDPOINT ?? "" : "",
825
+ // The Feishu tools' endpoint and the conversation they act for. The CREDENTIAL is not here:
826
+ // it is the session's own capability, the same value the task dispatch uses, because a
827
+ // second credential for one session would be a second thing to rotate and to release.
828
+ SUPER_PI_FEISHU_ENDPOINT: process.env.SUPER_PI_FEISHU_ENDPOINT ?? "",
829
+ SUPER_PI_FEISHU_CONVERSATION: conversationId,
830
+ };
831
+ }
832
+ /**
833
+ * The environment for a ONE-SHOT child, which is the same as the session's except that it carries
834
+ * the credential.
835
+ *
836
+ * THE DIFFERENCE IS THE LIFETIME. A one-shot child lives for one turn, so its credential is minted
837
+ * for that turn and dies with the child - which is the original rule, and it is still exactly right
838
+ * here. A session lives for many turns, so its credential is minted when the session is created (see
839
+ * `PiSessionPool.acquire`) and the server separately requires a running turn for it to be usable.
840
+ */
841
+ async oneShotExtensionEnv(conversationId, workspaceId, capability, parentConversationId) {
842
+ return {
843
+ ...(await this.taskExtensionEnv(conversationId, workspaceId, parentConversationId)),
844
+ [TASK_CAPABILITY_ENV]: capability,
845
+ SUPER_PI_TOOLS_CAPABILITY: capability,
846
+ };
847
+ }
848
+ /**
849
+ * RUNS A TURN ON A PERSISTENT SESSION.
850
+ *
851
+ * This is the path every conversation takes now, and it is where the latency win comes from. There is
852
+ * no process to spawn and none to kill: the conversation's session already exists, its context is
853
+ * already in memory, and a turn is a `prompt()` on it. An interrupt is `abort()` on the same session -
854
+ * which is why an interrupt no longer costs a process teardown and a process startup.
855
+ *
856
+ * THE EVENT ROUTING. Pi pushes events through a subscription; this method pulls them, one at a time,
857
+ * through a queue. The generator yields text deltas to its caller, and every non-text event is
858
+ * delivered to the turn's callbacks as it arrives, so the transcript shows tool calls and reasoning
859
+ * WHILE the model is producing them rather than after the turn ends.
860
+ *
861
+ * THE ABORT. The caller's `signal` is the turn's abort. When it fires, the session is aborted - Pi
862
+ * stops the current operation and waits for the session to go idle - and the turn ends. The session
863
+ * ITSELF survives: it is the next turn's session, and it is the reason the next turn costs no startup.
864
+ */
865
+ /**
866
+ * The configuration a conversation's session is built with.
867
+ *
868
+ * SEPARATED FROM THE BUILD ON PURPOSE, because this is a decision and the build is its consequence.
869
+ * Everything that decides what Pi is allowed to do for a conversation - the agent's allowlist, its
870
+ * prompt file, the extensions it mounts, the model it runs on - is decided HERE, in one place, and
871
+ * the session is then built from it.
872
+ *
873
+ * Two things want that separation. The FIRST is the fingerprint: the decision is what the session is
874
+ * compared against, so a changed decision means the session is stale. The SECOND is the tests: the
875
+ * permission boundary is the most important thing this runtime does, and asserting on the decision
876
+ * is a DIRECT way to check it - a test that has to start a real Pi to learn what Pi was told is a
877
+ * test that only runs on a machine with a Pi.
878
+ */
879
+ async sessionConfiguration(conversation, cwd) {
880
+ // The agent definition, read from disk EVERY turn. That freshness is the whole point of the
881
+ // fingerprint: an edited agent file changes the configuration, the session is replaced, and the
882
+ // edit takes effect on the next message with no restart and no re-selection.
883
+ const agent = await this.agentFor(conversation);
884
+ // The SDK path has no RPC `get_state` round trip before its first prompt. Preserve the old guard at
885
+ // the equivalent boundary: before a session is created. In particular, an unspecified conversation
886
+ // model means "the catalog's Pi default", which still has to pass the workspace policy.
887
+ if (agent?.model)
888
+ await this.modelValidator?.(conversation.id, { ...agent.model, label: agent.model.modelId });
889
+ await this.modelValidator?.(conversation.id, conversation.model);
890
+ // The tool selection and the prompt file are the SAME DECISION the spawn line used to carry, in the
891
+ // form the SDK takes. `toolSelection` is the shared translation, so an agent that declares
892
+ // `tools: {"*": false, "read": true}` gets exactly the same tools here as it used to get on the
893
+ // command line - including the empty allowlist that means "this agent talks and does not act".
894
+ const selection = nativeToolPolicy(agent
895
+ ? toolSelection(agent.tools, { extraAllowedTools: this.extensionToolNames() })
896
+ : {}, readNativeToolSettings(nativeToolSettingsPath(this.sessionDir)));
897
+ const systemPromptFile = agent ? await writeAgentPrompt(this.agents.promptDir, agent) : undefined;
898
+ return {
899
+ ...(selection.tools ? { tools: selection.tools } : {}),
900
+ ...(selection.excludeTools ? { excludeTools: selection.excludeTools } : {}),
901
+ ...(systemPromptFile ? { systemPromptFile } : {}),
902
+ ...(agent?.promptMode ? { systemPromptMode: agent.promptMode } : {}),
903
+ extensionPaths: superPiExtensionPaths(repositoryRootFrom()),
904
+ extensionEnv: await this.taskExtensionEnv(conversation.id, conversation.workspaceId, conversation.parentConversationId),
905
+ ...(conversation.model ? { model: { provider: conversation.model.provider, modelId: conversation.model.modelId } } : {}),
906
+ ...(conversation.thinkingLevel ? { thinkingLevel: conversation.thinkingLevel } : {}),
907
+ };
908
+ }
909
+ async *answerOnSession(input) {
910
+ const { conversation, prompt, signal, cwd, images } = input;
911
+ const latencyStartedAt = performance.now();
912
+ traceLatency(conversation.id, "session.begin", latencyStartedAt);
913
+ const configuration = await this.sessionConfiguration(conversation, cwd);
914
+ // The record of what this session is built with. Written BEFORE the session is acquired, so it
915
+ // exists even when the build fails - a test that wants to know what Super Pi INTENDED to give Pi
916
+ // must be able to ask after a failure too.
917
+ this.builtSessions.set(conversation.id, configuration);
918
+ const cacheWarmingEpoch = this.cacheWarmingEpoch;
919
+ const session = await this.sessionPool.acquire({
920
+ conversationId: conversation.id,
921
+ cwd: resolve(cwd),
922
+ ...(conversation.piSessionFile ? { sessionFile: conversation.piSessionFile } : {}),
923
+ agentId: conversation.agentId ?? null,
924
+ extensionEnv: configuration.extensionEnv,
925
+ ...(configuration.tools ? { tools: configuration.tools } : {}),
926
+ ...(configuration.excludeTools ? { excludeTools: configuration.excludeTools } : {}),
927
+ ...(configuration.systemPromptFile ? { systemPromptFile: configuration.systemPromptFile } : {}),
928
+ ...(configuration.systemPromptMode ? { systemPromptMode: configuration.systemPromptMode } : {}),
929
+ ...(configuration.model ? { model: configuration.model } : {}),
930
+ ...(configuration.thinkingLevel ? { thinkingLevel: configuration.thinkingLevel } : {}),
931
+ });
932
+ traceLatency(conversation.id, "session.acquired", latencyStartedAt);
933
+ // A session may finish building while a settings update is visiting the pool.
934
+ if (this.cacheWarmingOverride && cacheWarmingEpoch !== this.cacheWarmingEpoch)
935
+ session.setCacheWarmingMode?.(this.cacheWarmingOverride);
936
+ this.observeBackgroundUsage(conversation.id, session);
937
+ // THE SESSION-FILE LOCATOR. `revert` and `fork` open the conversation's transcript by PATH, and the
938
+ // path is a fact the session already knows: its SessionManager resolves it at creation, before any
939
+ // byte is written. Reported when it CHANGES rather than once per turn - the path is stable for the
940
+ // life of a session, and a rebuild (revert, eviction, fingerprint change) is exactly when the cached
941
+ // locator needs refreshing. Best-effort, like the RPC path's get_state read: a failed report must not
942
+ // fail the turn, it only means the next revert pays for the spawn fallback.
943
+ if (input.onSessionFile && typeof session.sessionFile === "string" && session.sessionFile
944
+ && this.reportedSessionFiles.get(conversation.id) !== session.sessionFile) {
945
+ try {
946
+ await input.onSessionFile(session.sessionFile);
947
+ this.reportedSessionFiles.set(conversation.id, session.sessionFile);
948
+ }
949
+ catch (error) {
950
+ console.warn(`PiRpcRuntime: could not record the session file of conversation ${conversation.id} (${error instanceof Error ? error.message : "unknown error"}) - the next revert will locate it the slow way.`);
951
+ }
952
+ }
953
+ // THE EXTENSION-UI BRIDGE, bound ONCE per session. Pi's extensions ask their blocking questions
954
+ // through the session's UI context, which starts life as a no-op that silently answers
955
+ // `undefined`/`false` - and for `confirm` a silent `false` is a fabricated "no" the user never gave.
956
+ // The bridge forwards to the host of whichever turn is running RIGHT NOW (registered below), and
957
+ // answers `cancelled` when there is none - the same rule the RPC path's no-host branch follows.
958
+ if (input.host)
959
+ this.sessionHosts.set(conversation.id, input.host);
960
+ // WHERE THIS TURN STARTS in Pi's own transcript, captured BEFORE the prompt. The one-shot path asked
961
+ // Pi over RPC (`get_entries` for the leaf, then `get_entries(since: leaf)` after the turn); a live
962
+ // session holds the same entries in memory, so the same two reads are synchronous. `null` is a real
963
+ // answer - an empty session, so the whole branch is this turn's; `undefined` means the session has no
964
+ // transcript to read (a test double), and nothing is recorded.
965
+ const transcript = session.sessionManager;
966
+ let turnStartLeaf;
967
+ if (input.onUserEntry && transcript) {
968
+ try {
969
+ turnStartLeaf = transcript.getLeafId();
970
+ }
971
+ catch (error) {
972
+ console.warn(`PiRpcRuntime: could not read the leaf before the turn of conversation ${conversation.id} (${error instanceof Error ? error.message : "unknown error"}) - this turn's message may not become a revert boundary.`);
973
+ }
974
+ }
975
+ const queue = new TurnQueue();
976
+ const deferred = (handler) => (...args) => { if (handler)
977
+ queue.push({ kind: "callback", run: () => handler(...args) }); };
978
+ const handlers = {
979
+ onToolCall: deferred(input.onToolCall),
980
+ onFileWrite: input.onFileWrite,
981
+ onToolUpdate: deferred(input.onToolUpdate),
982
+ onToolPreparing: deferred(input.onToolPreparing),
983
+ onToolEnd: deferred(input.onToolEnd),
984
+ onThinking: deferred(input.onThinking),
985
+ onThinkingEnd: deferred(input.onThinkingEnd),
986
+ onSteerDelivered: deferred(input.onSteerDelivered),
987
+ onPiQueue: input.onPiQueue,
988
+ };
989
+ const announced = new Set();
990
+ const report = (key) => {
991
+ if (announced.has(key))
992
+ return;
993
+ announced.add(key);
994
+ console.warn(`PiRpcRuntime: unhandled Pi session event ${key} - consumed without action.`);
995
+ };
996
+ // THE FAILURE THE TURN ENDED ON, if it ended on one. Held here rather than thrown on the spot,
997
+ // because Pi retries on its own and only the LAST assistant message of a turn decides whether the
998
+ // turn failed. The bridge clears it when a new assistant message starts, and raises it when Pi
999
+ // settles.
1000
+ const failure = { current: undefined };
1001
+ const usage = new ConversationUsageCollector();
1002
+ const unsubscribe = session.subscribe((event) => {
1003
+ try {
1004
+ const record = event;
1005
+ if (record?.type === "entry_appended")
1006
+ return; // Persisted background usage has its own lifecycle observer.
1007
+ if (record?.type === "message_end" && record.message?.role === "assistant")
1008
+ usage.add(record.message.usage);
1009
+ handleSessionEvent(event, queue, handlers, report, failure);
1010
+ }
1011
+ catch (error) {
1012
+ console.warn(`PiRpcRuntime: the session event handler threw: ${error instanceof Error ? error.message : "unknown error"}`);
1013
+ }
1014
+ });
1015
+ // The abort. The caller's signal is the turn's, and aborting the session is what makes the model
1016
+ // stop. The session is NOT destroyed: it is the next turn's session.
1017
+ //
1018
+ // The turn has its OWN controller, and the caller's signal aborts it. A run can span several turns
1019
+ // on one session, so "the caller wants this run to stop" and "Pi has to be told about the turn in
1020
+ // flight" are two different facts, and only the second one is Pi's business.
1021
+ const turnController = new AbortController();
1022
+ let abortDone = Promise.resolve();
1023
+ const abortSession = () => {
1024
+ abortDone = session.abort().catch((error) => {
1025
+ console.warn(`PiRpcRuntime: aborting the session of ${conversation.id} threw: ${error instanceof Error ? error.message : "unknown error"}`);
1026
+ });
1027
+ };
1028
+ const abortTurn = () => {
1029
+ if (turnController.signal.aborted)
1030
+ return;
1031
+ turnController.abort();
1032
+ abortSession();
1033
+ };
1034
+ const onAbort = () => { abortTurn(); };
1035
+ if (signal.aborted)
1036
+ abortTurn();
1037
+ else
1038
+ signal.addEventListener("abort", onAbort, { once: true });
1039
+ // HOW BIG IS THE PROMPT WE ARE ABOUT TO SEND. The time to first token is a function of
1040
+ // this, not of anything Super Pi does, and it is the number that explains a slow first turn: the
1041
+ // model's provider has to RECEIVE the whole thing before it can answer, so a big prompt on a slow
1042
+ // link is seconds before the first word.
1043
+ //
1044
+ // It is traced rather than computed, because the system prompt is what Pi builds from the agent
1045
+ // directory, the skills, the extensions and the context files - none of which Super Pi controls,
1046
+ // and all of which the person who installed them controls.
1047
+ const promptSize = () => {
1048
+ try {
1049
+ const system = typeof session.systemPrompt === "string" ? session.systemPrompt : "";
1050
+ return `systemPrompt=${Buffer.byteLength(system, "utf8")}B`;
1051
+ }
1052
+ catch {
1053
+ return "systemPrompt=?";
1054
+ }
1055
+ };
1056
+ let firstTextSeen = false;
1057
+ let markPromptFinished;
1058
+ const promptFinished = new Promise((resolvePromise) => { markPromptFinished = resolvePromise; });
1059
+ const finished = (async () => {
1060
+ try {
1061
+ if (!this.uiBoundSessions.has(session)) {
1062
+ const uiContext = this.extensionUiBridge(conversation.id);
1063
+ if (session.bindExtensions) {
1064
+ let binding = true;
1065
+ let startupFailure;
1066
+ try {
1067
+ await session.bindExtensions({ uiContext, mode: "rpc", onError: error => {
1068
+ const failure = new Error(`Pi 扩展 ${basename(error.extensionPath)} 在 ${error.event} 中执行失败,请检查扩展配置。`);
1069
+ console.warn(failure.message);
1070
+ if (binding) {
1071
+ startupFailure = failure;
1072
+ return;
1073
+ }
1074
+ if (this.sessionPool.get(conversation.id) !== session)
1075
+ return;
1076
+ this.activeTurns.get(conversation.id)?.queue.fail(failure);
1077
+ void session.abort().catch(() => undefined);
1078
+ } });
1079
+ if (startupFailure)
1080
+ throw startupFailure;
1081
+ }
1082
+ catch (error) {
1083
+ await this.disposeSessions(conversation.id);
1084
+ throw error;
1085
+ }
1086
+ finally {
1087
+ binding = false;
1088
+ }
1089
+ }
1090
+ else
1091
+ session.extensionRunner?.setUIContext(uiContext, "rpc");
1092
+ this.uiBoundSessions.add(session);
1093
+ }
1094
+ let preflight;
1095
+ const imagePayloads = this.options.uploadsDir && images?.length
1096
+ ? await loadConversationImages(this.options.uploadsDir, conversation.id, images)
1097
+ : undefined;
1098
+ const promptOptions = {
1099
+ ...(imagePayloads?.length ? { images: imagePayloads } : {}),
1100
+ preflightResult: (result) => {
1101
+ preflight = result;
1102
+ if (result !== "started")
1103
+ return;
1104
+ traceLatency(conversation.id, "session.prompt.accepted", latencyStartedAt, promptSize());
1105
+ // Pi calls this hook immediately BEFORE _runAgentPrompt synchronously marks the run
1106
+ // active. An abort during before_agent_start can have returned while Pi was idle. Repeat
1107
+ // it in the next microtask, after the active flag and the agent's controller exist. Waiting
1108
+ // for prompt() would wait for the entire answer and make the cancellation ineffective.
1109
+ if (turnController.signal.aborted)
1110
+ queueMicrotask(() => {
1111
+ if (!queue.isSettled)
1112
+ abortSession();
1113
+ });
1114
+ },
1115
+ };
1116
+ // A STOP THAT ARRIVED WHILE THIS SESSION WAS BEING BUILT MUST NOT SEND THE PROMPT.
1117
+ //
1118
+ // The window between "the person pressed stop" and "the prompt goes out" is the whole session
1119
+ // build: Pi's resource loader, the extensions, the transcript, the model lookup - seconds, on a
1120
+ // cold session. The abort listener above already noticed the cancellation, but `session.abort()`
1121
+ // on a session that has not started running is a no-op, so nothing stopped the prompt that was
1122
+ // about to be sent: the model was asked a question the person had already cancelled, and it
1123
+ // answered it - which is why pressing stop looked like it "took effect" only once the reply was
1124
+ // over.
1125
+ //
1126
+ // So the cancellation is checked HERE, at the last moment before the prompt goes out, and a
1127
+ // cancelled turn ends with no question asked at all.
1128
+ //
1129
+ // `turnController.signal.aborted` is the OTHER half of the same fact: the turn's own controller
1130
+ // is what `abortTurn()` trips, and it is tripped by the very same cancellation. Both are checked
1131
+ // because they are tripped by different readers - one by the person, one by Pi's abort.
1132
+ if (signal.aborted || turnController.signal.aborted) {
1133
+ queue.push({ kind: "end" });
1134
+ return;
1135
+ }
1136
+ await session.prompt(prompt, promptOptions);
1137
+ markPromptFinished();
1138
+ // Pi's prompt() awaits the whole agent run. Input hooks and extension commands can also
1139
+ // handle it without starting a run, in which case no agent_settled event is emitted. Pi's idle
1140
+ // flag distinguishes that legitimate completion from an asynchronous session adapter whose
1141
+ // prompt promise returns before its stream finishes.
1142
+ if ((preflight === "handled" || (preflight === "started" && session.isIdle === true)) && !queue.isSettled)
1143
+ queue.push({ kind: "end" });
1144
+ // Drain every queued callback and delta before releasing this turn, even if Pi already went
1145
+ // idle. An adapter that returns early must still provide the authoritative settled event.
1146
+ await queue.settledSignal;
1147
+ traceLatency(conversation.id, "session.settled", latencyStartedAt);
1148
+ // THE REVERT BOUNDARY, recorded at the same moment the one-shot path records it: the turn has
1149
+ // settled, so every entry this turn wrote - the user message included - is in the transcript.
1150
+ // Recorded on abort too, on purpose: an aborted turn still PERSISTED the user message, and a
1151
+ // message in the transcript with no recorded id is a message the user can see but never revert
1152
+ // to. A prompt that was never accepted wrote nothing, so there is nothing to find.
1153
+ if (transcript && turnStartLeaf !== undefined && input.onUserEntry) {
1154
+ await this.recordSessionTurnEntryId(transcript, turnStartLeaf, conversation.id, input.onUserEntry);
1155
+ }
1156
+ }
1157
+ catch (error) {
1158
+ queue.fail(error instanceof Error ? error : new Error(String(error)));
1159
+ }
1160
+ finally {
1161
+ // Also release preparation failures and a turn cancelled before prompt() was called.
1162
+ markPromptFinished();
1163
+ }
1164
+ })();
1165
+ this.activeTurns.set(conversation.id, { queue, unsubscribe, finished, promptFinished, abort: abortTurn, get abortDone() { return abortDone; } });
1166
+ try {
1167
+ // THE SPLITTER LIVES HERE, INSIDE THE LOOP THAT DRAINS THE QUEUE, and its thinking events are
1168
+ // applied IN LINE rather than deferred. Two producers write into this one queue - Pi's session
1169
+ // events (text deltas, tool calls) and the splitter's reading of the text - and the deferred way
1170
+ // was to announce the second producer's findings at the END of the queue, which put "the thinking
1171
+ // ended" BEHIND the tool call that Pi had announced after the very text that ended it. The tool
1172
+ // callback then ran while the turn still thought it was thinking, and the call was filed inside
1173
+ // the thinking block (UX-008). In line, the thinking lifecycle happens where its text sits, so
1174
+ // the order Pi announced is the order the turn sees.
1175
+ const splitter = new InlineThinkingSplitter();
1176
+ for (;;) {
1177
+ const item = await queue.next();
1178
+ if (item.kind === "text") {
1179
+ if (!firstTextSeen) {
1180
+ firstTextSeen = true;
1181
+ traceLatency(conversation.id, "session.first-text", latencyStartedAt);
1182
+ }
1183
+ for (const segment of splitter.push(item.delta)) {
1184
+ if (segment.kind === "text") {
1185
+ yield segment.text;
1186
+ }
1187
+ else if (segment.kind === "thinking") {
1188
+ await input.onThinking?.(segment.text);
1189
+ }
1190
+ else {
1191
+ input.onThinkingEnd?.();
1192
+ }
1193
+ }
1194
+ continue;
1195
+ }
1196
+ if (item.kind === "callback") {
1197
+ await item.run();
1198
+ continue;
1199
+ }
1200
+ if (item.kind === "error")
1201
+ throw item.error;
1202
+ // THE END OF THE TURN. A model that was still thinking when the turn ended leaves an unclosed
1203
+ // region behind, and it belongs in the block rather than in the answer.
1204
+ for (const segment of splitter.flush()) {
1205
+ if (segment.kind === "text") {
1206
+ yield segment.text;
1207
+ }
1208
+ else if (segment.kind === "thinking") {
1209
+ await input.onThinking?.(segment.text);
1210
+ }
1211
+ else {
1212
+ input.onThinkingEnd?.();
1213
+ }
1214
+ }
1215
+ break;
1216
+ }
1217
+ }
1218
+ finally {
1219
+ signal.removeEventListener("abort", onAbort);
1220
+ unsubscribe();
1221
+ this.activeTurns.delete(conversation.id);
1222
+ // The host registration belongs to THIS turn: an extension question that arrives after it ends
1223
+ // finds no host and is answered `cancelled`, which is the honest answer to "nobody is being asked".
1224
+ if (input.host)
1225
+ this.sessionHosts.delete(conversation.id);
1226
+ await finished.catch(() => undefined);
1227
+ if (input.onUsage) {
1228
+ let context;
1229
+ try {
1230
+ context = session.getContextUsage?.();
1231
+ }
1232
+ catch { /* Unavailable context must not discard usage or keep a stale occupancy. */ }
1233
+ await input.onUsage(usage.readout(context, session.model, defaultAgentDir()));
1234
+ }
1235
+ }
1236
+ }
1237
+ /**
1238
+ * The Extension UI context a session's extensions talk to, bridged to the host of the turn that is
1239
+ * running right now.
1240
+ *
1241
+ * THE SHAPES MIRROR PI'S OWN RPC UI CONTEXT (rpc-mode.ts), method for method, because the extensions
1242
+ * were written against that contract: `select`/`input`/`editor` resolve to the chosen text or
1243
+ * `undefined` on cancel, `confirm` resolves to a boolean with cancel reading as `false` (Pi's own
1244
+ * mapping, not an invention), and the one-way methods are fire-and-forget. The TUI-only methods
1245
+ * (`setWorkingMessage`, footers, headers, `custom`, ...) are the same no-ops they are in RPC mode.
1246
+ *
1247
+ * A BLOCKING CALL WITH NO HOST IS CANCELLED, NEVER DEFAULTED. The no-op context Pi starts with answers
1248
+ * `confirm` with `false`, which is indistinguishable from the user clicking "no" - the exact failure
1249
+ * the "cancelled, never a default" rule exists to prevent. So an idle session (no turn, no host) and a
1250
+ * failed host both answer `cancelled`, and the reason is logged.
1251
+ */
1252
+ extensionUiBridge(conversationId) {
1253
+ const ask = async (request) => {
1254
+ const host = this.sessionHosts.get(conversationId);
1255
+ if (!host) {
1256
+ console.warn(`PiRpcRuntime: an extension asked ${request.method} on conversation ${conversationId} with no turn running - cancelled rather than answering on the user's behalf.`);
1257
+ return { cancelled: true };
1258
+ }
1259
+ try {
1260
+ return await host.ask({ ...request, requestId: randomUUID(), blocking: true });
1261
+ }
1262
+ catch (error) {
1263
+ console.warn(`PiRpcRuntime: the UI host failed a ${request.method} for conversation ${conversationId} (${error instanceof Error ? error.message : "unknown error"}) - cancelled.`);
1264
+ return { cancelled: true };
1265
+ }
1266
+ };
1267
+ const notify = (request) => {
1268
+ try {
1269
+ this.sessionHosts.get(conversationId)?.notify({ ...request, requestId: randomUUID(), blocking: false });
1270
+ }
1271
+ catch (error) {
1272
+ console.warn(`PiRpcRuntime: the UI host threw on a ${request.method} notification for conversation ${conversationId}: ${error instanceof Error ? error.message : "unknown error"}`);
1273
+ }
1274
+ };
1275
+ /** Pi passes its dialog timeout straight through; `ExtensionUiRequest.timeoutMs` is the same number. */
1276
+ const timeoutOf = (opts) => {
1277
+ const timeout = opts?.timeout;
1278
+ return typeof timeout === "number" && Number.isFinite(timeout) && timeout > 0 ? { timeoutMs: timeout } : {};
1279
+ };
1280
+ return {
1281
+ select: async (title, options, opts) => {
1282
+ const answer = await ask({ method: "select", title: typeof title === "string" ? title : "", options: Array.isArray(options) ? options.filter((item) => typeof item === "string") : [], ...timeoutOf(opts) });
1283
+ return answer.cancelled ? undefined : answer.value;
1284
+ },
1285
+ confirm: async (title, message, opts) => {
1286
+ const answer = await ask({ method: "confirm", title: typeof title === "string" ? title : "", message: typeof message === "string" ? message : "", ...timeoutOf(opts) });
1287
+ return answer.cancelled ? false : answer.confirmed === true;
1288
+ },
1289
+ input: async (title, placeholder, opts) => {
1290
+ const answer = await ask({ method: "input", title: typeof title === "string" ? title : "", ...(typeof placeholder === "string" ? { placeholder } : {}), ...timeoutOf(opts) });
1291
+ return answer.cancelled ? undefined : answer.value;
1292
+ },
1293
+ editor: async (title, prefill) => {
1294
+ const answer = await ask({ method: "editor", title: typeof title === "string" ? title : "", ...(typeof prefill === "string" ? { prefill } : {}) });
1295
+ return answer.cancelled ? undefined : answer.value;
1296
+ },
1297
+ notify: (message, type) => notify({ method: "notify", title: "", message: typeof message === "string" ? message : "", notifyType: (type === "warning" || type === "error" ? type : "info") }),
1298
+ onTerminalInput: () => () => { },
1299
+ setStatus: (key, text) => notify({ method: "setStatus", title: "", statusKey: typeof key === "string" ? key : "", ...(typeof text === "string" ? { statusText: text } : {}) }),
1300
+ setWidget: (key, content, options) => {
1301
+ if (content !== undefined && !Array.isArray(content))
1302
+ return; // component factories need the TUI
1303
+ const placement = options?.placement;
1304
+ notify({ method: "setWidget", title: "", widgetKey: typeof key === "string" ? key : "", ...(Array.isArray(content) ? { widgetLines: content.filter((line) => typeof line === "string") } : {}), ...(placement === "aboveEditor" || placement === "belowEditor" ? { widgetPlacement: placement } : {}) });
1305
+ },
1306
+ setTitle: (title) => notify({ method: "setTitle", title: typeof title === "string" ? title : "" }),
1307
+ setEditorText: (text) => notify({ method: "set_editor_text", title: "", ...(typeof text === "string" ? { text } : {}) }),
1308
+ pasteToEditor: (text) => notify({ method: "set_editor_text", title: "", ...(typeof text === "string" ? { text } : {}) }),
1309
+ // The rest need the TUI or have no web meaning; they are the same no-ops RPC mode provides.
1310
+ setWorkingMessage: () => { },
1311
+ setWorkingVisible: () => { },
1312
+ setWorkingIndicator: () => { },
1313
+ setHiddenThinkingLabel: () => { },
1314
+ setFooter: () => { },
1315
+ setHeader: () => { },
1316
+ custom: async () => undefined,
1317
+ getEditorText: () => "",
1318
+ addAutocompleteProvider: () => { },
1319
+ setEditorComponent: () => { },
1320
+ getEditorComponent: () => undefined,
1321
+ };
1322
+ }
1323
+ /**
1324
+ * Records the id of the user message this turn wrote, read from the live session's own transcript.
1325
+ *
1326
+ * THE SAME CONTRACT AS `recordTurnEntryId` ON THE ONE-SHOT PATH, over memory instead of RPC: the
1327
+ * captured pre-turn leaf is what makes the read exact, because the entries written after it belong to
1328
+ * THIS turn, and the first USER message among them is the one Super Pi just pushed. The three outcomes
1329
+ * are the same three:
1330
+ *
1331
+ * - leaf `null` - the session was empty, so the whole branch is this turn's.
1332
+ * - leaf found in the branch - everything after it is this turn's.
1333
+ * - leaf NOT found - the transcript moved underneath us (a compaction rewrite, a branch switch), so
1334
+ * nothing can be attributed to this turn with certainty and nothing is recorded. Guessing here would
1335
+ * hand back an EARLIER turn's id, and a revert to it would silently cut more than the user asked for.
1336
+ *
1337
+ * Every failure is a warning, never a throw: the answer has already streamed by this point, and "this
1338
+ * message cannot be a revert boundary" is not "your message failed".
1339
+ */
1340
+ async recordSessionTurnEntryId(transcript, leaf, conversationId, onUserEntry) {
1341
+ try {
1342
+ const branch = transcript.getBranch();
1343
+ let startIndex = 0;
1344
+ if (leaf !== null) {
1345
+ const at = branch.findIndex((entry) => entry?.id === leaf);
1346
+ if (at === -1) {
1347
+ console.warn(`PiRpcRuntime: the entry this turn started from is no longer in the transcript of conversation ${conversationId}, so its message was not recorded and cannot be used as a revert boundary.`);
1348
+ return;
1349
+ }
1350
+ startIndex = at + 1;
1351
+ }
1352
+ const firstUser = branch.slice(startIndex).find((entry) => {
1353
+ const candidate = entry;
1354
+ return candidate?.type === "message" && candidate.message?.role === "user" && typeof candidate.id === "string";
1355
+ });
1356
+ if (!firstUser) {
1357
+ console.warn(`PiRpcRuntime: the entries this turn of conversation ${conversationId} wrote contain no user message, so nothing was recorded as a revert boundary.`);
1358
+ return;
1359
+ }
1360
+ await onUserEntry(firstUser.id);
1361
+ }
1362
+ catch (error) {
1363
+ console.warn(`PiRpcRuntime: could not record this turn's Pi entry id for conversation ${conversationId} (${error instanceof Error ? error.message : "unknown error"}) - its message cannot be used as a revert boundary.`);
1364
+ }
1365
+ }
1366
+ /**
1367
+ * The tool names Super Pi's own extensions contribute, for the agent's allowlist.
1368
+ *
1369
+ * The same list the spawn line used to carry, so an agent that declares `tools: {"*": false, "read":
1370
+ * true}` gets exactly the same tools it used to get - and an agent that says `task: false` still wins,
1371
+ * because `toolFlags` treats an explicit false as outranking a host extra.
1372
+ */
1373
+ extensionToolNames() {
1374
+ const names = [TASK_TOOL_NAME, TODO_TOOL_NAME, WORKFLOW_TOOL_NAME, RUN_ASYNC_TOOL_NAME, SCHEDULED_TASK_TOOL_NAME, "question", "tool_register"];
1375
+ if (this.memory)
1376
+ names.push("memory", "skill_manage", "session_search");
1377
+ if (this.knowledge)
1378
+ names.push(KNOWLEDGE_TOOL_NAME, KNOWLEDGE_IMPORT_TOOL_NAME);
1379
+ if (process.env.SUPER_PI_WEB_ENDPOINT && process.env.SUPER_PI_WEB_ENABLED === "1")
1380
+ names.push(WEB_SEARCH_TOOL_NAME, WEB_FETCH_TOOL_NAME);
1381
+ // The document tools are named whenever the endpoint is configured, because that is what decides
1382
+ // whether the extension registers them. An agent that declares `tools: {"*": false, read: true}`
1383
+ // would otherwise get a loaded-but-undeclared tool - broken with no error to explain it.
1384
+ if (this.options.documentsEndpoint)
1385
+ names.push(DOCUMENT_READ_TOOL_NAME, DOCUMENT_WRITE_TOOL_NAME);
1386
+ // The Feishu tools are named whenever the endpoint is configured, for the same reason the
1387
+ // document tools are: the endpoint is what decides whether the extension registers them, and
1388
+ // an agent that declares `tools: {"*": false, read: true}` would otherwise get a
1389
+ // loaded-but-undeclared tool - broken with no error to explain it.
1390
+ if (process.env.SUPER_PI_FEISHU_ENDPOINT)
1391
+ names.push(FEISHU_READ_TOOL_NAME, FEISHU_WRITE_TOOL_NAME);
1392
+ if (this.options.orchestratorEndpoint)
1393
+ names.push(PROJECT_TOOL_NAME);
1394
+ if (this.options.orchestratorEndpoint)
1395
+ names.push(WORKTREE_TOOL_NAME, SESSION_SPAWN_TOOL_NAME, SESSION_STATUS_TOOL_NAME, SESSION_DISPATCH_TOOL_NAME, SESSION_STOP_TOOL_NAME, SESSION_REPORT_TOOL_NAME, SESSION_STOP_SUBTREE_TOOL_NAME, SESSION_REMOVE_TOOL_NAME);
1396
+ // THE REMINDER TOOL IS A SESSION TOOL, SO IT IS NAMED WHERE THE OTHER SESSION TOOLS ARE
1397
+ // NAMED - on its own line, because the line above is a pinned list and this one belongs to it.
1398
+ if (this.options.orchestratorEndpoint)
1399
+ names.push(SESSION_REMINDER_TOOL_NAME);
1400
+ return names;
1401
+ }
1402
+ /**
1403
+ * A TURN, WITH THE REASONING TAKEN OUT OF THE ANSWER.
1404
+ *
1405
+ * This is the ONE place every turn passes through, whichever path it runs on - the persistent
1406
+ * session or a one-shot process - so it is where the model's own text is read once and read
1407
+ * properly.
1408
+ *
1409
+ * WHAT IT DOES. A model that has no reasoning channel answers in one stream of text and marks its
1410
+ * thinking up inside it with `<think>…</think>`. Pi's adapter passes that through as ordinary
1411
+ * text, because Pi only knows the four reasoning FIELDS a provider can use and a tag is not one
1412
+ * of them. Left alone, the reasoning would be drawn as part of the answer, unlabelled, with the
1413
+ * tags in it.
1414
+ *
1415
+ * WHY IT IS HERE AND NOT IN THE USER'S `models.json`. The alternative is to tell every reader to
1416
+ * go and set a vendor-specific switch in a file Super Pi owns but Pi reads. A user who never
1417
+ * hears of it sees a broken transcript and has no way to find out why. Super Pi reads the tags
1418
+ * itself, for every provider, so the transcript reads the same way whichever endpoint is behind
1419
+ * it - and the reasoning goes where the reasoning goes: into a thinking block, over the same
1420
+ * channel Pi's own reasoning events use, so the fold, the live indicator and the persisted
1421
+ * transcript all work without knowing where the reasoning came from.
1422
+ */
1423
+ async *answer(input) {
1424
+ // THE SPLITTING HAPPENS INSIDE `answerTurn`, NOT HERE - and the reason is ORDER.
1425
+ //
1426
+ // The reasoning of an inline-thinking model is a `<think>…</think>` region INSIDE the answer text,
1427
+ // so "the thinking ended" is a fact that only exists once the text carrying the closing tag has
1428
+ // been read. When that fact was produced out here - one layer ABOVE the queue that carries Pi's
1429
+ // events - it was announced by DEFERRED, and a deferred announcement lands at the END of the
1430
+ // queue: BEHIND the tool call that Pi had already announced. So the tool callback ran while the
1431
+ // turn still believed it was thinking, and the call was filed INSIDE the thinking block - a
1432
+ // question that came after the answer was drawn inside the fold above it (UX-008).
1433
+ //
1434
+ // Splitting inside the queue's consumer keeps the two producers in ONE order: the thinking
1435
+ // lifecycle derived from a piece of text happens where that text sits, and a tool call Pi
1436
+ // announced after that text is announced after it too.
1437
+ yield* this.answerTurn(input);
1438
+ }
1439
+ /**
1440
+ * THE TURN ITSELF, on whichever path it runs. See `answer`, which is the seam the reasoning is
1441
+ * separated at.
1442
+ */
1443
+ async *answerTurn(input) {
1444
+ // The one-shot paths keep their own child process, and they are NOT the same thing as a conversation
1445
+ // turn: a memory review and a knowledge reranker have their own ids, their own tool sets and their own
1446
+ // lifetimes, and folding them into a conversation's session would give them that conversation's
1447
+ // context. They are identified by the flags that describe exactly that.
1448
+ if (input.memoryReview || input.knowledgeRerank) {
1449
+ yield* this.answerOneShotWithInlineThinking(input);
1450
+ return;
1451
+ }
1452
+ // WHICH PATH A CONVERSATION RUNS ON, and why it is NOT decided by which Pi was named.
1453
+ //
1454
+ // The session path does not use a Pi COMMAND at all: it imports Pi as a library, and the library it
1455
+ // imports is the one installed next to Super Pi. A named command is a PROGRAM, and the session path
1456
+ // cannot run a program as itself.
1457
+ //
1458
+ // So the two are different questions, and they are asked of different variables:
1459
+ //
1460
+ // - `SUPER_PI_HOST_PI` - the Pi that is hosting Super Pi, set by the Pi extension. It steers the
1461
+ // ONE-SHOT work (the sub-agents spawn a Pi) and nothing else. It does NOT redirect conversations.
1462
+ // - `SUPER_PI_SESSION_MODE=oneshot` - the explicit request to run conversations by spawning a Pi
1463
+ // instead of by using the SDK. It is slower, and it is here for the test suite, which drives a fake
1464
+ // Pi that speaks the RPC protocol - a program, not a library.
1465
+ //
1466
+ // THE BUG THIS FIXES. The extension used to set `SUPER_PI_PI_COMMAND`, and an explicitly named Pi
1467
+ // used to mean the one-shot path - so every conversation started from inside Pi spawned a process for
1468
+ // every turn. That is the exact architecture this refactor replaced, and it was still running for
1469
+ // anyone who started Super Pi the way most people do. The version number said 0.1.95; the speed said
1470
+ // 0.1.84.
1471
+ if (this.sessionMode === "oneshot") {
1472
+ yield* this.answerOneShotWithInlineThinking(input);
1473
+ return;
1474
+ }
1475
+ // The main path: a persistent session, reused across turns. When the SDK cannot be loaded the turn
1476
+ // falls back to the one-shot path rather than failing, and the reason is reported once - a server
1477
+ // that cannot use the SDK still serves conversations, just at the old speed.
1478
+ const support = await this.sessionSupport();
1479
+ if (!support.available) {
1480
+ if (!this.warnedMissingSdk) {
1481
+ this.warnedMissingSdk = true;
1482
+ console.warn(`PiRpcRuntime: ${support.reason} Falling back to one-shot Pi processes for conversations.`);
1483
+ }
1484
+ yield* this.answerOneShotWithInlineThinking(input);
1485
+ return;
1486
+ }
1487
+ yield* this.answerOnSession(input);
1488
+ }
1489
+ /**
1490
+ * THE ONE-SHOT PATH, WITH THE INLINE THINKING SPLIT OUT OF IT.
1491
+ *
1492
+ * WHY THIS IS A SEPARATE FUNCTION AND NOT A LINE IN `answerTurn`. The reasoning of an inline-thinking
1493
+ * model is a `<think>…</think>` region INSIDE the answer text, so splitting it is not a formatting
1494
+ * step - it is a reading of the text, and the facts it produces ("the thinking started", "the thinking
1495
+ * ended") belong where the text is read.
1496
+ *
1497
+ * WHEN IT WAS FORGOTTEN, IT COST THE PRODUCT A BUG. The splitter used to live one layer up, in
1498
+ * `answer()`, where it covered EVERY path. It was moved down into the SDK session path to fix the
1499
+ * ordering of "the thinking ended" against a tool call (UX-008), and in that move the ONE-SHOT
1500
+ * CONVERSATION path - the path a server without the Pi SDK falls back to, and the path the whole test
1501
+ * suite drives - lost the splitting altogether: the `<think>` tags reached the answer verbatim.
1502
+ * `scripts/inline-thinking.test.mjs` caught it; the SDK path was fine, which is why it took a test
1503
+ * suite running the other path to notice.
1504
+ *
1505
+ * SO EVERY ONE-SHOT PATH GOES THROUGH HERE, and the session path keeps its own splitter inside the
1506
+ * queue's consumer, where the ORDER of "thinking ended" and a tool call is decided.
1507
+ */
1508
+ async *answerOneShotWithInlineThinking(input) {
1509
+ const splitter = new InlineThinkingSplitter();
1510
+ for await (const chunk of this.answerOneShot(input)) {
1511
+ for (const segment of splitter.push(chunk)) {
1512
+ if (segment.kind === "text")
1513
+ yield segment.text;
1514
+ else if (segment.kind === "thinking")
1515
+ await input.onThinking?.(segment.text);
1516
+ else
1517
+ await input.onThinkingEnd?.();
1518
+ }
1519
+ }
1520
+ // THE END OF THE TURN. A model that was still thinking when the turn ended leaves an unclosed region
1521
+ // behind, and it belongs in the block rather than in the answer.
1522
+ for (const segment of splitter.flush()) {
1523
+ if (segment.kind === "text")
1524
+ yield segment.text;
1525
+ else if (segment.kind === "thinking")
1526
+ await input.onThinking?.(segment.text);
1527
+ else
1528
+ await input.onThinkingEnd?.();
1529
+ }
1530
+ }
1531
+ /**
1532
+ * The one-shot path: a fresh child process for a single turn.
1533
+ *
1534
+ * Still used for the memory review, the knowledge reranker, and as the fallback when Pi's SDK is not
1535
+ * installed. The main conversation path does NOT come here - see `answer`.
1536
+ */
1537
+ async *answerOneShot({ conversation, prompt, signal, cwd, host, onPiQueue, onSteerDelivered, onUserEntry, onSessionFile, onToolCall, onFileWrite, onToolUpdate, onToolPreparing, onToolEnd, onThinking, onThinkingEnd, images, memoryReview, memorySourceConversationId, knowledgeRerank }) {
1538
+ const latencyStartedAt = performance.now();
1539
+ traceLatency(conversation.id, "answer.begin", latencyStartedAt);
1540
+ await mkdir(this.sessionDir, { recursive: true });
1541
+ // Normalize first: the picker can hand over forward slashes or a trailing separator, and `resolve`
1542
+ // turns both into one absolute native path. The directory must exist on disk before spawn - a
1543
+ // deleted workspace directory is a visible failure, never a reason to run somewhere else.
1544
+ const childCwd = resolve(cwd);
1545
+ const info = await stat(childCwd).catch(() => undefined);
1546
+ if (!info?.isDirectory())
1547
+ throw new Error(`Workspace directory for conversation ${conversation.id} does not exist or is not a directory: ${childCwd}. Refusing to run Pi in any other directory.`);
1548
+ // The agent's flags go on the SPAWN line, not the wire, because that is the only place Pi reads
1549
+ // them: its RPC command union (rpc-types.ts:20-74) has no prompt and no tools command, so there is
1550
+ // nothing to send after the process is already running. Fetched before the spawn so a definition
1551
+ // error fails the turn loudly instead of starting a Pi that silently ignores it.
1552
+ const agent = memoryReview || knowledgeRerank ? undefined : await this.agentFor(conversation);
1553
+ const validationId = memorySourceConversationId ?? conversation.id;
1554
+ if (agent?.model)
1555
+ await this.modelValidator?.(validationId, { ...agent.model, label: agent.model.modelId });
1556
+ await this.modelValidator?.(validationId, conversation.model);
1557
+ // Whether the `task` tool EXISTS is decided first, because that is what decides whether it belongs
1558
+ // on the allowlist. Naming a tool Pi has not registered is meaningless, and doing it anyway would
1559
+ // change the spawn line of a runtime that has no task tool - which is what
1560
+ // `PiRpcRuntime(dir, launcher)` without an endpoint is, and what `agent-mechanism.test.mjs` asserts
1561
+ // a byte-identical spawn line for.
1562
+ //
1563
+ // Why it has to be added at all: Pi filters its registry through `--tools` and only activates a tool
1564
+ // the allowlist allows (agent-session.ts:3567-3574), so a primary agent declaring
1565
+ // `tools: {"*": false, read: true}` would otherwise get an extension tool that is loaded and never
1566
+ // declared - broken with no error. An agent that says `task: false` still wins: `toolFlags` treats an
1567
+ // explicit false as outranking a host extra, which is what makes "this agent does not delegate" true
1568
+ // rather than advisory.
1569
+ const extensionArgs = memoryReview || knowledgeRerank ? [] : await this.taskExtensionArgs();
1570
+ // A reranker gets no memory capability at all. `memoryReview` mints one deliberately, because a
1571
+ // review is supposed to write memory; a reranker must not be able to, so the token is simply
1572
+ // never issued rather than issued with a flag.
1573
+ const memoryEnabled = !knowledgeRerank && this.memory ? (await this.memory.configuration()).enabled : false;
1574
+ const memoryToken = memoryEnabled ? this.memory.issue(validationId, { review: memoryReview }) : undefined;
1575
+ const memoryExtension = resolve(import.meta.dirname, "../../agents/super-pi-memory/index.ts");
1576
+ const memoryArgs = memoryEnabled ? ["--extension", memoryExtension] : [];
1577
+ // Mounted on EVERY primary turn, empty base or not. The old condition (hasDocuments) saved a
1578
+ // catalogue round trip and a tool slot when there was nothing to find, but it also made the one
1579
+ // workspace where a user most plausibly says 「把这些文件加入知识库」 the one workspace whose
1580
+ // agent had no import tool. knowledge_search on an empty base answers no hits and costs nothing;
1581
+ // knowledge_import has to exist before the first document does. Review turns never mount it: a
1582
+ // background reflection has no business reading or writing documents, and its `--tools` line is a
1583
+ // closed list. A reranker never mounts it either - it must not be able to call what it ranks.
1584
+ const knowledgeEnabled = !memoryReview && !knowledgeRerank && !!this.knowledge && this.knowledge.enabled();
1585
+ const knowledgeToken = knowledgeEnabled ? this.knowledge.issue(conversation.id) : undefined;
1586
+ const knowledgeExtension = resolve(import.meta.dirname, "../../agents/super-pi-knowledge/index.ts");
1587
+ const knowledgeArgs = knowledgeEnabled ? ["--extension", knowledgeExtension] : [];
1588
+ const webExtension = resolve(import.meta.dirname, "../../agents/super-pi-web/index.ts");
1589
+ const webEnabled = !memoryReview && !knowledgeRerank && existsSync(webExtension) && !!process.env.SUPER_PI_WEB_ENDPOINT && process.env.SUPER_PI_WEB_ENABLED === "1";
1590
+ const webArgs = webEnabled ? ["--extension", webExtension] : [];
1591
+ // The Feishu tools are mounted for every ordinary turn, and NOT for a review or a rerank: a
1592
+ // background reflection has no business reading a company's cloud documents, and a reranker
1593
+ // must not be able to reach the tools it is ranking.
1594
+ const feishuEnabled = !memoryReview && !knowledgeRerank && this.feishuExtensionArgs().length > 0;
1595
+ const feishuArgs = feishuEnabled ? this.feishuExtensionArgs() : [];
1596
+ // The document tools are mounted for every ordinary turn, and NOT for a review or a rerank: a
1597
+ // background reflection has no business reading a PDF it was not asked about, and a reranker
1598
+ // must not be able to reach the tools it is ranking.
1599
+ const documentsEnabled = !memoryReview && !knowledgeRerank && this.documentExtensionArgs().length > 0;
1600
+ const documentArgs = documentsEnabled ? this.documentExtensionArgs() : [];
1601
+ // THE ONE-SHOT CHILD'S CREDENTIAL, MINTED ONCE. The server holds ONE capability per
1602
+ // conversation, so minting a second one for the same conversation would replace the first and
1603
+ // leave the task dispatch holding a token the server has already forgotten. Both the task
1604
+ // extension and the document extension therefore share this one value.
1605
+ const oneShotCapability = (extensionArgs.length || documentsEnabled || webEnabled || feishuEnabled) ? mintCapability(conversation.id) : undefined;
1606
+ // BOTH extension tools, or neither. Naming one while the other goes unmentioned would be a lie in a
1607
+ // different direction: Pi filters its registry through `--tools`, so an agent that declares
1608
+ // `tools: {"*": false, read: true}` gets whichever of the two is on this line and silently not the
1609
+ // other. They also share the extension's existence - `extensionArgs` is non-empty exactly when
1610
+ // `index.ts` is on disk and an endpoint was configured - so there is no case where one is mounted and
1611
+ // the other is not.
1612
+ // A RERANK SPAWNS WITH NOTHING ATTACHED BUT Pi ITSELF. No extensions, no skills, no MCP, no agent
1613
+ // definition, no session-scoped tools - it has one job, which is to turn a list of passages into a
1614
+ // list of indices. Note that Pi's BUILT-IN tools are not removed here: `--tools` needs a real
1615
+ // allowlist and naming a tool Pi has not registered would change the spawn line for every other
1616
+ // mode. The prompt asks for a bare JSON array and nothing else; if the model spends a turn on a
1617
+ // tool call anyway the reranker times out and falls back to the lexical order.
1618
+ const agentArgs = memoryReview ? ["--no-extensions", "--no-skills", "--no-mcp", "--no-context-files", "--no-prompt-templates", "--tools", "memory,skill_manage,session_search"] : knowledgeRerank ? ["--no-extensions", "--no-skills", "--no-mcp", "--no-context-files", "--no-prompt-templates"] : await agentSpawnArgs(this.agents.promptDir, agent, { extraAllowedTools: [...(extensionArgs.length ? [TASK_TOOL_NAME, TODO_TOOL_NAME, PROJECT_TOOL_NAME, WORKFLOW_TOOL_NAME, RUN_ASYNC_TOOL_NAME, SCHEDULED_TASK_TOOL_NAME, "question", "tool_register", "tool_shortcut", "tool_remove", ...(this.options.orchestratorEndpoint ? [WORKTREE_TOOL_NAME, SESSION_SPAWN_TOOL_NAME, SESSION_STATUS_TOOL_NAME, SESSION_DISPATCH_TOOL_NAME, SESSION_STOP_TOOL_NAME, SESSION_REPORT_TOOL_NAME, SESSION_STOP_SUBTREE_TOOL_NAME, SESSION_REMOVE_TOOL_NAME, SESSION_REMINDER_TOOL_NAME] : [])] : []), ...(memoryEnabled ? ["memory", "skill_manage", "session_search"] : []), ...(knowledgeEnabled ? [KNOWLEDGE_TOOL_NAME, KNOWLEDGE_IMPORT_TOOL_NAME] : []), ...(documentsEnabled ? [DOCUMENT_READ_TOOL_NAME, DOCUMENT_WRITE_TOOL_NAME] : []), ...(webEnabled ? [WEB_SEARCH_TOOL_NAME, WEB_FETCH_TOOL_NAME] : []), ...(feishuEnabled ? [FEISHU_READ_TOOL_NAME, FEISHU_WRITE_TOOL_NAME] : [])] });
1619
+ // Refused here, with the reason, rather than handed to the spawn: an ENOENT from `spawn` reads as
1620
+ // "the app is broken" and hides the one fact that matters, which is where it looked for Pi.
1621
+ if (!this.pi.found)
1622
+ throw new Error(this.pi.reason);
1623
+ // npm exposes global CLIs as .cmd shims on Windows; Node requires a shell to launch those shims.
1624
+ const nativePolicy = nativeToolPolicy(toolSelection(agent?.tools), readNativeToolSettings(nativeToolSettingsPath(this.sessionDir)));
1625
+ const useNativeTools = !memoryReview && !knowledgeRerank;
1626
+ if (useNativeTools && nativePolicy.excludeTools?.length)
1627
+ agentArgs.push("--exclude-tools", nativePolicy.excludeTools.join(","));
1628
+ const providerProxyEnv = { ...await readProviderProxyEnv(defaultAgentDir(), conversation.model?.provider), ...(useNativeTools ? nativeToolEnv(this.sessionDir, nativePolicy) : {}) };
1629
+ const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--session-dir", this.sessionDir, "--session-id", conversation.id, ...(useNativeTools ? ["--no-mcp", "--extension", nativeToolExtensionPath()] : []), ...extensionArgs, ...memoryArgs, ...knowledgeArgs, ...documentArgs, ...webArgs, ...feishuArgs, ...agentArgs], {
1630
+ cwd: childCwd,
1631
+ detached: process.platform !== "win32",
1632
+ stdio: ["pipe", "pipe", "pipe"],
1633
+ shell: process.platform === "win32",
1634
+ // `env` is passed ONLY when the extension is mounted, because passing `{ ...process.env }` on
1635
+ // every turn would silently replace the child's environment with whatever THIS process has at
1636
+ // spawn time. Inheriting is what an omitted `env` already does, so the two paths differ in nothing
1637
+ // but the four documented additions.
1638
+ ...((Object.keys(providerProxyEnv).length || extensionArgs.length || memoryEnabled || knowledgeEnabled || documentsEnabled || webEnabled || feishuEnabled) ? { env: { ...process.env, ...providerProxyEnv, ...(oneShotCapability ? await this.oneShotExtensionEnv(conversation.id, conversation.workspaceId, oneShotCapability, conversation.parentConversationId) : {}), ...(memoryEnabled ? {
1639
+ SUPER_PI_MEMORY_ENDPOINT: process.env.SUPER_PI_MEMORY_ENDPOINT,
1640
+ SUPER_PI_MEMORY_TOKEN: memoryToken,
1641
+ SUPER_PI_MEMORY_REVIEW: memoryReview ? "1" : "0",
1642
+ } : {}), ...(knowledgeEnabled ? {
1643
+ SUPER_PI_KNOWLEDGE_ENDPOINT: process.env.SUPER_PI_KNOWLEDGE_ENDPOINT,
1644
+ SUPER_PI_KNOWLEDGE_TOKEN: knowledgeToken,
1645
+ } : {}), ...(documentsEnabled ? {
1646
+ SUPER_PI_DOCUMENTS_ENDPOINT: this.options.documentsEndpoint ?? "",
1647
+ // The document tools carry the SESSION's capability, the same credential the task dispatch
1648
+ // uses: it proves which conversation is asking, and the server checks that the turn is
1649
+ // running. The conversation id travels with it, because the workspace is derived from the
1650
+ // conversation and never from the request.
1651
+ //
1652
+ // IT IS THE SAME VALUE THE TASK EXTENSION GETS. A one-shot child has no session to borrow a
1653
+ // credential from, so the token is minted for the turn - and minted ONCE, because the server
1654
+ // holds one capability per conversation and a second mint would replace the first in the
1655
+ // map, leaving the task dispatch holding a token the server had already forgotten.
1656
+ SUPER_PI_DOCUMENTS_TOKEN: oneShotCapability ?? "",
1657
+ SUPER_PI_DOCUMENTS_CONVERSATION: conversation.id,
1658
+ } : {}) } } : {}),
1659
+ });
1660
+ const channel = new RpcChannel(child);
1661
+ this.runs.set(conversation.id, { child, channel });
1662
+ traceLatency(conversation.id, "pi.spawned", latencyStartedAt, `pid=${child.pid ?? "unknown"}`);
1663
+ // Same guard as subagents.ts: a destroyed stdin throws synchronously on write, and an abort
1664
+ // listener that throws inside a listener would surface as an unhandled error instead of a cancel.
1665
+ const abort = () => {
1666
+ if (child.exitCode === null && !child.killed && !child.stdin.destroyed) {
1667
+ try {
1668
+ child.stdin.write(`${JSON.stringify({ id: "abort", type: "abort" })}\n`);
1669
+ }
1670
+ catch { /* the child died between the check and the write; the abort is moot */ }
1671
+ }
1672
+ };
1673
+ signal.addEventListener("abort", abort, { once: true });
1674
+ // A blocking request is awaited inside the drain loop, so the loop cannot observe an abort or a
1675
+ // dead child on its own. Both are raced into the wait so a pending question can never outlive the run.
1676
+ const ui = { seen: new Set(), aborted: new Promise((resolve) => { if (signal.aborted)
1677
+ resolve(undefined);
1678
+ else
1679
+ signal.addEventListener("abort", () => resolve(undefined), { once: true }); }), exited: new Promise((resolve) => child.once("exit", () => resolve(undefined))) };
1680
+ try {
1681
+ // The leaf this turn starts from, read from Pi BEFORE anything is written this turn.
1682
+ //
1683
+ // Written, not awaited: Pi queues commands, so this line costs no wall-clock time - it is answered
1684
+ // while the model is thinking, and collected at the end of the turn. Awaiting it here would add a
1685
+ // round trip to every message in exchange for information nothing needs until the turn is over.
1686
+ //
1687
+ // The FIRST turn has no file and no leaf at all, which is why `leafId` may be null: Pi reports it
1688
+ // that way until something has been appended, and the `since` lookup below simply reads everything.
1689
+ let turnStart;
1690
+ if (onUserEntry) {
1691
+ channel.write({ id: "turn_head", type: "get_entries" });
1692
+ // Swallowed HERE rather than awaited below: a Pi that cannot answer this has not failed the turn,
1693
+ // and the alternative - propagating - would turn "this message cannot be a revert boundary" into
1694
+ // "your message failed to send", which is both false and far more alarming.
1695
+ turnStart = channel.waitFor("turn_head", SESSION_COMMAND_TIMEOUT_MS, "get_entries").catch((error) => {
1696
+ console.warn(`PiRpcRuntime: could not read the leaf before the turn (${error instanceof Error ? error.message : "unknown error"}) - this turn's message may not become a revert boundary.`);
1697
+ return undefined;
1698
+ });
1699
+ }
1700
+ // The conversation's picker selection, applied to THIS Pi before it sees the prompt. A refusal
1701
+ // is thrown, never downgraded to a warning: a run on some other model than the button says is
1702
+ // exactly the decorative picker this must not be.
1703
+ for (const command of sessionCommands(conversation)) {
1704
+ const response = await channel.request(command, SESSION_COMMAND_TIMEOUT_MS);
1705
+ if (response.success === false)
1706
+ throw new Error(`Pi rejected ${command.type}: ${response.error ?? "no reason given"}`);
1707
+ }
1708
+ // Resumed Pi sessions can carry a different model than the global default.
1709
+ // Check the real get_state result as well, before any prompt reaches the model.
1710
+ if (this.modelValidator || onSessionFile) {
1711
+ const actual = await channel.request({ id: "policy_state", type: "get_state" }, SESSION_COMMAND_TIMEOUT_MS);
1712
+ const model = actual.data?.model;
1713
+ await this.modelValidator?.(validationId, model?.provider && model.id ? { provider: model.provider, modelId: model.id, label: model.name ?? model.id } : undefined);
1714
+ const sessionFile = actual.data?.sessionFile;
1715
+ if (typeof sessionFile === "string" && sessionFile)
1716
+ await onSessionFile?.(sessionFile);
1717
+ }
1718
+ const imagePayloads = this.options.uploadsDir && images?.length
1719
+ ? await loadConversationImages(this.options.uploadsDir, conversation.id, images)
1720
+ : undefined;
1721
+ // A STOP THAT ARRIVED WHILE THE CHILD WAS STARTING MUST NOT SEND THE PROMPT.
1722
+ //
1723
+ // The same gap the session path has, and the same reason: `abort` above writes an `abort`
1724
+ // command to a child that has not been given anything yet, so it does nothing - and the prompt
1725
+ // went out anyway, and the model answered a question the person had already cancelled.
1726
+ if (signal.aborted)
1727
+ return;
1728
+ channel.write({ id: "prompt", type: "prompt", message: prompt, ...(imagePayloads?.length ? { images: imagePayloads } : {}) });
1729
+ traceLatency(conversation.id, "prompt.sent", latencyStartedAt);
1730
+ let settled = false;
1731
+ let finalAgentOutcome;
1732
+ let finalDoneOutcome;
1733
+ const terminalOutcome = (message, reason) => {
1734
+ if (!message?.stopReason && !message?.errorMessage && !reason)
1735
+ return undefined;
1736
+ return { reason, stopReason: message?.stopReason, errorMessage: message?.errorMessage };
1737
+ };
1738
+ const throwIfTerminalFailure = () => {
1739
+ if (signal.aborted)
1740
+ return;
1741
+ const outcome = finalAgentOutcome ?? finalDoneOutcome;
1742
+ if (!outcome)
1743
+ throw new Error("Pi 已结束本轮运行,但没有报告最终结果。");
1744
+ const reason = outcome.stopReason ?? outcome.reason;
1745
+ if (reason === "error")
1746
+ throw new Error(outcome.errorMessage || "Pi 报告模型或服务提供方错误。");
1747
+ if (reason === "aborted")
1748
+ throw new Error(outcome.errorMessage || "Pi 意外中止了本轮回答。");
1749
+ if (reason === "length")
1750
+ throw new LengthExceededError(outcome.errorMessage || "模型输出达到本轮长度上限,回答未完成。");
1751
+ };
1752
+ let firstPiRecord = true;
1753
+ // Nothing may be dropped without a trace. Pi emits a wide, open-ended family of agent
1754
+ // session events (tool_call, thinking, compaction_*, auto_retry_*, ...), so an unhandled
1755
+ // record is announced once per distinct type and then tallied instead of logging per event.
1756
+ const announced = new Set();
1757
+ const repeats = new Map();
1758
+ /**
1759
+ * THE ARGUMENT TEXT EACH CALL HAS PRODUCED SO FAR, keyed by the contentIndex `toolcall_start` named.
1760
+ *
1761
+ * Held per TURN and cleared with it, so a second turn writing a different call to the same index
1762
+ * starts from an empty string rather than from the previous call's file path. The fragments are
1763
+ * still handed on one at a time as `delta`; this is only what a line naming the call is read out of,
1764
+ * and a block that could show 「正在生成参数…」 instead of the file it is about to open was telling
1765
+ * the reader less than the record already knew.
1766
+ */
1767
+ const argumentText = new Map();
1768
+ /** The tool name `toolcall_start` announced for each index, so a later fragment can still name it. */
1769
+ const toolNames = new Map();
1770
+ const noteUnhandled = (key) => {
1771
+ if (announced.has(key))
1772
+ repeats.set(key, (repeats.get(key) ?? 0) + 1);
1773
+ else {
1774
+ announced.add(key);
1775
+ console.warn(`PiRpcRuntime: unhandled Pi RPC record ${key} - consumed without action.`);
1776
+ }
1777
+ };
1778
+ while (!settled) {
1779
+ for (;;) {
1780
+ const record = await channel.next(100);
1781
+ if (!record)
1782
+ break;
1783
+ if (firstPiRecord) {
1784
+ firstPiRecord = false;
1785
+ traceLatency(conversation.id, "pi.first-record", latencyStartedAt, `type=${record.type}`);
1786
+ }
1787
+ if (record.type === "response" && record.id === "prompt" && record.success === false)
1788
+ throw new Error(record.error ?? "Pi rejected the prompt");
1789
+ // A `steer` written while this turn was running, answered here because this loop is the only
1790
+ // thing reading the child's stdout. Settled rather than ignored: the caller is holding a
1791
+ // promise on this exact id to learn whether the message is already in the model's context.
1792
+ //
1793
+ // THIS CHECK HAS TO COME BEFORE THE STASH, and it used not to. An earlier version stashed every
1794
+ // non-`prompt` response and continued, one line ABOVE this block, which made it unreachable:
1795
+ // a response that got past that line had `id === "prompt"` and fails this block's condition,
1796
+ // and a response with a steer id never got here at all. Nothing else settles a pending steer,
1797
+ // so every steer fell through to STEER_COMMAND_TIMEOUT_MS and the user was told Pi had not
1798
+ // acknowledged it - a lie, because Pi had answered and the answer was sitting in the stash.
1799
+ if (record.type === "response" && record.id !== "prompt") {
1800
+ const pending = typeof record.id === "string" ? this.pendingSteers.get(record.id) : undefined;
1801
+ if (pending) {
1802
+ this.pendingSteers.delete(record.id);
1803
+ if (record.success === false)
1804
+ pending.reject(new Error(`Pi rejected the steer: ${record.error ?? "no reason given"}`));
1805
+ else
1806
+ pending.resolve(describeSteerDisposition(record.data) ?? "queued");
1807
+ continue;
1808
+ }
1809
+ // A response the loop does not itself consume is not garbage - it is the answer to a command
1810
+ // somebody wrote on this channel and is waiting for (`get_entries`, and in `readCatalog` the
1811
+ // model list). Handed to the stash rather than dropped, which is what stopped the loop from
1812
+ // eating the per-turn entry-id read and leaving this turn's message unrecordable.
1813
+ channel.stash(record);
1814
+ continue;
1815
+ }
1816
+ // Pi's own queue, pushed as a full snapshot whenever it changes. READ, not dropped: this used
1817
+ // to fall through to `noteUnhandled` and be logged once as an unhandled record type, which is
1818
+ // the "looks wired up but nothing happens" failure - it is the only signal that a steer was
1819
+ // really picked up, and Pi emits it before the delivered message on the same stdout stream.
1820
+ const piQueue = describePiQueue(record);
1821
+ if (piQueue) {
1822
+ try {
1823
+ onPiQueue?.(piQueue);
1824
+ }
1825
+ catch (error) {
1826
+ console.warn(`PiRpcRuntime: the pi queue handler threw: ${error instanceof Error ? error.message : "unknown error"}`);
1827
+ }
1828
+ continue;
1829
+ }
1830
+ // A STEER THIS TURN DELIVERED. Pi announces the moment it stops waiting and starts being
1831
+ // answered by emitting `message_start` with the user message it picked up
1832
+ // (`agent-session.ts:1116-1136`) - on the same stdout stream, immediately after the
1833
+ // `queue_update` above that shows the entry gone.
1834
+ //
1835
+ // READ, not dropped, and this is the fix rather than a nicety. It used to fall through to
1836
+ // `noteUnhandled`, which is why a steered message reached the model and never reached the
1837
+ // transcript: nothing here told the host that a new user message had begun, so the answer to
1838
+ // it was appended to the assistant message that was already streaming and the user's own words
1839
+ // were never written anywhere they could be read. A host can now split the turn at this
1840
+ // boundary and put the answer under the message it answers.
1841
+ //
1842
+ // It is consumed silently and NOT announced as unhandled, because `message_start` for a user
1843
+ // role is a delivery notice, not something a reader needs to be told about in a log.
1844
+ const steeredText = describeDeliveredUserMessage(record);
1845
+ if (steeredText !== undefined) {
1846
+ try {
1847
+ await onSteerDelivered?.(steeredText);
1848
+ }
1849
+ catch (error) {
1850
+ console.warn(`PiRpcRuntime: the steer delivery handler threw: ${error instanceof Error ? error.message : "unknown error"}`);
1851
+ }
1852
+ continue;
1853
+ }
1854
+ // THE PRIMARY AGENT'S TOOL CALLS. Consumed, not announced - the same routing the sub-agent
1855
+ // supervisor already does for its child (subagents.ts:532-559), on the same two records.
1856
+ //
1857
+ // These two used to reach `noteUnhandled` and be logged once each per turn, which is the
1858
+ // "looks wired up but nothing happens" failure twice over: the warning said the host did not
1859
+ // understand them, and the host genuinely did not, so a `read` and a two-minute `bash` were the
1860
+ // same silence on the transcript. Consumed here because they now carry data - which is the
1861
+ // difference between routing and silencing.
1862
+ //
1863
+ // WHAT IS *NOT* CHANGED. Every other record type keeps its existing report, including the inner
1864
+ // `message_update` events below: a `thinking_delta` still announces itself, because that is a
1865
+ // documented decision about an event shape rather than an oversight this branch is here to
1866
+ // repair. Only the two tool records move.
1867
+ if (record.type === "tool_execution_update") {
1868
+ // THE THIRD TOOL RECORD, AND THE ONE THAT WAS MISSING.
1869
+ //
1870
+ // `tool_execution_start` announces a call and `tool_execution_end` reports how it went, which
1871
+ // left the whole span between them silent. For a `bash` that runs a minute or an `edit` whose
1872
+ // replacement text is large, that span is the entire execution, and the block sat there with
1873
+ // no status, no output and nothing changing - which on screen is indistinguishable from a
1874
+ // frozen agent. Pi has been sending this record the whole time, with the arguments as they
1875
+ // stand and whatever output has arrived so far.
1876
+ //
1877
+ // It updates the EXISTING row rather than announcing a new one, so `args` is re-derived on
1878
+ // every update (it grows as a tool is prepared) and `live` carries the running output. The
1879
+ // reduction is the same one the final result goes through, so a preview can never be bigger
1880
+ // than the answer it precedes.
1881
+ const id = record.toolCallId ?? "";
1882
+ if (id) {
1883
+ const name = record.toolName ?? "unknown";
1884
+ const live = extractPartialResultText(record.partialResult);
1885
+ try {
1886
+ onToolUpdate?.({ id, name, detail: describeToolCall(name, record.args), args: describeToolCallArgs(record.args), ...(live ? { live } : {}) });
1887
+ }
1888
+ catch (error) {
1889
+ console.warn(`PiRpcRuntime: the tool update handler threw: ${error instanceof Error ? error.message : "unknown error"}`);
1890
+ }
1891
+ }
1892
+ continue;
1893
+ }
1894
+ if (record.type === "tool_execution_start") {
1895
+ // The `args` are READ and summarised, never carried: `describeToolCallArgs` turns an
1896
+ // arbitrary object into at most six capped strings and a non-string becomes a bare type
1897
+ // word, because an `edit`'s arguments routinely hold a whole file's replacement text. See
1898
+ // tool-calls.ts for the argument-vs-transcript line.
1899
+ const name = record.toolName ?? "unknown";
1900
+ // A `question` CALL is read here, at `tool_execution_start`, rather than assembled somewhere
1901
+ // else when the answer arrives - so the card on screen is the tool call the model is actually
1902
+ // blocked in, with the same identity, the same `at`, and the same lifecycle. `args` stays the
1903
+ // display reduction; this is the one call whose arguments are also the transcript's data.
1904
+ try {
1905
+ onToolCall?.({ id: record.toolCallId ?? "", name, detail: describeToolCall(name, record.args), args: describeToolCallArgs(record.args), ...(() => { const question = readQuestionCall(name, record.args); return question ? { question } : {}; })() });
1906
+ }
1907
+ catch (error) {
1908
+ console.warn(`PiRpcRuntime: the tool call handler threw: ${error instanceof Error ? error.message : "unknown error"}`);
1909
+ }
1910
+ // THE FILE-WRITING CALL, announced before it runs. This is the ONLY moment the old content
1911
+ // is still on the disk, so this is where a baseline has to be taken - and it is taken by a
1912
+ // listener that does its own I/O, off the drain loop's path, because a disk read between
1913
+ // yields would stall the stream.
1914
+ const writePath = toolTargetPath(name, record.args);
1915
+ if (writePath) {
1916
+ try {
1917
+ onFileWrite?.(writePath, name, record.toolCallId ?? undefined);
1918
+ }
1919
+ catch (error) {
1920
+ console.warn(`PiRpcRuntime: the file-write handler threw: ${error instanceof Error ? error.message : "unknown error"}`);
1921
+ }
1922
+ }
1923
+ continue;
1924
+ }
1925
+ if (record.type === "tool_execution_end") {
1926
+ // The other half of the same call, and the half that lets a block say whether it finished.
1927
+ // ONLY `isError` AND `durationMs` CROSS OVER. `result` is never read - `RpcRecord` does not
1928
+ // even declare it, because for a `read` it is the file's contents and `ToolCallNotice` is
1929
+ // persisted into `state.json`.
1930
+ //
1931
+ // The handler is wrapped for the same reason the queue handler is: a listener that throws
1932
+ // must cost one tool row, not the whole turn's drain loop.
1933
+ try {
1934
+ onToolEnd?.({
1935
+ id: record.toolCallId ?? "",
1936
+ name: record.toolName ?? "unknown",
1937
+ status: record.isError === true ? "error" : "ok",
1938
+ // Reduced ONCE, here, and the raw record.result is dropped here. Anything that reaches a
1939
+ // store from this point is the bounded summary, never what Pi sent.
1940
+ ...(() => { const summary = extractToolResultText(record.result); return summary ? { result: summary } : {}; })(),
1941
+ ...(typeof record.durationMs === "number" && Number.isFinite(record.durationMs) ? { durationMs: Math.max(0, Math.round(record.durationMs)) } : {}),
1942
+ });
1943
+ }
1944
+ catch (error) {
1945
+ console.warn(`PiRpcRuntime: the tool end handler threw: ${error instanceof Error ? error.message : "unknown error"}`);
1946
+ }
1947
+ continue;
1948
+ }
1949
+ if (record.type === "message_update") {
1950
+ const event = record.assistantMessageEvent;
1951
+ if (event?.type === "done") {
1952
+ finalDoneOutcome = terminalOutcome(event.message, event.reason);
1953
+ }
1954
+ // text_delta is what drives the visible answer, and toolcall_start/delta/end are what make a
1955
+ // call VISIBLE WHILE IT IS BEING WRITTEN.
1956
+ //
1957
+ // Those two used to be dropped here by a comment that named them - "the rest (thinking, tool
1958
+ // calls, message_start/end) are consumed here". Consuming them was the bug, not the design: an
1959
+ // `edit` call's arguments ARE the old text and the new text, so the model spends many seconds
1960
+ // and thousands of tokens emitting them, and for every one of those seconds the screen showed
1961
+ // nothing at all. A frozen transcript and a slow one look identical from the outside; a block
1962
+ // that appears the instant the model starts writing its arguments is the difference.
1963
+ //
1964
+ // The text is what arrives - `toolcall_delta` is a raw JSON fragment, and parsing it early
1965
+ // would mean guessing at a document that is not finished. It is handed on as it comes.
1966
+ if (event?.type === "text_delta")
1967
+ yield event.delta ?? "";
1968
+ else if (event?.type === "toolcall_start" && typeof event.contentIndex === "number") {
1969
+ // A fresh index means a fresh call, so anything the PREVIOUS call at this index wrote is
1970
+ // dropped here rather than carried into this one's first fragment.
1971
+ argumentText.delete(event.contentIndex);
1972
+ const name = toolNameOf(event);
1973
+ toolNames.set(event.contentIndex, name);
1974
+ onToolPreparing?.({ contentIndex: event.contentIndex, name });
1975
+ }
1976
+ else if (event?.type === "toolcall_delta" && typeof event.contentIndex === "number") {
1977
+ const delta = typeof event.delta === "string" ? event.delta : "";
1978
+ // THE NAME IS CARRIED FORWARD because the line naming the call needs it: `toolcall_start`
1979
+ // is the only event that carries one, and by the second fragment the mapping has to choose
1980
+ // between a `read`'s path and a `bash`'s command.
1981
+ const name = toolNames.get(event.contentIndex) ?? "";
1982
+ argumentText.set(event.contentIndex, `${argumentText.get(event.contentIndex) ?? ""}${delta}`);
1983
+ // WHAT ARRIVES IS A FRAGMENT; WHAT IS HANDED ON IS THE TEXT SO FAR. The same field on the
1984
+ // caller's side receives `tool_execution_update`'s output, and Pi sends THAT already
1985
+ // accumulated - so a caller storing both verbatim would have to append one kind of text and
1986
+ // replace the other. Accumulating here, where the fragments already are, gives it one kind.
1987
+ const text = argumentText.get(event.contentIndex) ?? "";
1988
+ const detail = describeToolCallInProgress(name, text);
1989
+ onToolPreparing?.({ contentIndex: event.contentIndex, name, ...(text ? { live: text } : {}), ...(detail ? { detail } : {}) });
1990
+ }
1991
+ // `toolcall_end` IS THE ARGUMENTS, FINISHED - and this branch is what stops a call that Pi
1992
+ // announced but never ran from rendering as a call with no parameters at all.
1993
+ //
1994
+ // Until `tool_execution_start`, a row's parameters exist only as the JSON text streaming past
1995
+ // in `live`, which the transcript deliberately does not show as parameters. So a call the turn
1996
+ // cut off mid-flight - an abort, a cancelled turn, an upstream error - reached the reader as
1997
+ // 「正在生成参数…」 above 「(这次调用没有可显示的参数)」, the two halves of which are the same fact: the
1998
+ // parameters were known and were not shown. Pi puts the completed object on this event, so the
1999
+ // row gets its real parameters from here instead.
2000
+ //
2001
+ // Reduced exactly as everywhere else (`describeToolCallArgs`), so this is the same bounded
2002
+ // derivation and not the arguments themselves, and the raw object stops at this line.
2003
+ else if (event?.type === "toolcall_end" && typeof event.contentIndex === "number") {
2004
+ const toolCall = event.toolCall;
2005
+ const name = typeof toolCall?.name === "string" && toolCall.name ? toolCall.name : (toolNames.get(event.contentIndex) ?? "");
2006
+ // The name this event carries is the authoritative one, so a row filed under an empty name
2007
+ // by a start that carried none can still be paired with its execution.
2008
+ if (name)
2009
+ toolNames.set(event.contentIndex, name);
2010
+ const args = describeToolCallArgs(toolCall?.arguments);
2011
+ const text = argumentText.get(event.contentIndex) ?? "";
2012
+ // `detail` GOES OUT ONLY WHEN NOTHING HAS DERIVED ONE. The delta path reads the same target
2013
+ // out of the same text a fragment earlier, so re-sending it would be a patch that changes
2014
+ // nothing - and a patch that changes nothing still publishes a frame, which is one more
2015
+ // `message.tools` broadcast per call for no reader-visible change. The one case it earns its
2016
+ // place in is a call whose fragments never became readable, where this is the last moment
2017
+ // the parameters are available to name the target from.
2018
+ const detail = describeToolCall(name, toolCall?.arguments);
2019
+ onToolPreparing?.({ contentIndex: event.contentIndex, name, final: true, ...(args ? { args } : {}), ...(!describeToolCallInProgress(name, text) && detail ? { detail } : {}) });
2020
+ }
2021
+ // Pi's reasoning lifecycle is three events, not one flag: `thinking_delta` means the model is
2022
+ // STILL THINKING RIGHT NOW, and `thinking_end` is the only thing that says it stopped. There is
2023
+ // deliberately no `active` field read here - every `thinking_delta` in Pi's wire shape carries
2024
+ // `{ type, contentIndex, delta, partial }` and nothing else, so a delta is itself the evidence.
2025
+ else if (event?.type === "thinking_delta")
2026
+ onThinking?.(typeof event.delta === "string" ? event.delta : "");
2027
+ else if (event?.type === "thinking_end")
2028
+ onThinkingEnd?.();
2029
+ else {
2030
+ noteUnhandled(`message_update:${JSON.stringify(event?.type ?? "(missing)")}`);
2031
+ }
2032
+ continue;
2033
+ }
2034
+ if (record.type === "agent_end") {
2035
+ const message = [...(record.messages ?? [])].reverse().find((item) => item.role === "assistant");
2036
+ const outcome = terminalOutcome(message);
2037
+ // Pi emits `agent_end` for every attempt. A retryable error is deliberately only observed
2038
+ // here; Pi owns the retry and will replace this with the final attempt before it settles.
2039
+ if (record.willRetry !== true && outcome)
2040
+ finalAgentOutcome = outcome;
2041
+ continue;
2042
+ }
2043
+ if (record.type === "extension_ui_request") {
2044
+ await this.handleExtensionUi(record, child, host, ui);
2045
+ continue;
2046
+ }
2047
+ // Pi already caught this error inside the extension host, so it will never reach us as a
2048
+ // thrown failure. Every answer spawns its own Pi process, so any extension_error seen while
2049
+ // draining belongs to the prompt in flight - surface it as a real failure instead of
2050
+ // letting the turn finish as if nothing happened.
2051
+ if (record.type === "extension_error") {
2052
+ console.warn(`PiRpcRuntime: extension_error path=${record.extensionPath ?? "unknown"} event=${record.event ?? "unknown"} error=${record.error ?? "unknown"}`);
2053
+ throw new Error(`Pi extension error in ${record.extensionPath ?? "unknown path"} (${record.event ?? "unknown event"}): ${record.error ?? "unknown error"}`);
2054
+ }
2055
+ if (record.type === "agent_settled") {
2056
+ traceLatency(conversation.id, "pi.settled", latencyStartedAt);
2057
+ // Only now is it safe to inspect a provider error: before this point Pi may still be
2058
+ // automatically retrying a 429, timeout, or temporary upstream failure.
2059
+ throwIfTerminalFailure();
2060
+ settled = true;
2061
+ continue;
2062
+ }
2063
+ noteUnhandled(`type ${JSON.stringify(record.type ?? "(missing type)")}`);
2064
+ }
2065
+ if (!settled && channel.closed)
2066
+ throw new Error(`Pi RPC exited before settling (code ${child.exitCode}). ${channel.stderr.trim()}`);
2067
+ }
2068
+ for (const [key, count] of repeats)
2069
+ console.warn(`PiRpcRuntime: ${count} further unhandled record(s) of ${key}.`);
2070
+ // This turn's own slice of Pi's transcript, taken now because after the `finally` below the child is
2071
+ // gone and `answer()` will never be able to ask again.
2072
+ //
2073
+ // `since` is what makes this exact rather than approximate: the entries written after the pre-turn
2074
+ // leaf belong to THIS turn, and the first USER message among them is the one Super Pi just pushed.
2075
+ // Counting messages instead would be wrong the moment a compaction or a `model_change` lands in the
2076
+ // slice - which is exactly research §5 pitfall 6.
2077
+ if (onUserEntry) {
2078
+ await this.recordTurnEntryId(channel, await turnStart, conversation.id, onUserEntry);
2079
+ }
2080
+ }
2081
+ finally {
2082
+ signal.removeEventListener("abort", abort);
2083
+ this.runs.delete(conversation.id);
2084
+ // The capability dies with the CHILD that was given it. In this `finally`, so it happens on every
2085
+ // exit - a turn that answered, a turn that threw, and a turn whose child was killed - because a
2086
+ // credential whose process has ended is a credential with no owner. The one-shot path is the only
2087
+ // place this still holds literally: on the session path the child does not die with the turn.
2088
+ releaseCapability(conversation.id);
2089
+ if (memoryToken)
2090
+ this.memory?.release(memoryToken);
2091
+ if (knowledgeToken)
2092
+ this.knowledge?.release(knowledgeToken);
2093
+ // A steer still unanswered when the turn ends is REJECTED, not left pending. The drain loop above
2094
+ // is the only reader of this child's stdout and it has stopped, so nothing would ever settle that
2095
+ // promise: the caller would wait for a timeout to learn something this process already knows. The
2096
+ // message itself is not lost - Pi drains steering before its loop can end, so anything unanswered
2097
+ // at this point was in practice not delivered, and the caller returns it to its queue.
2098
+ if (!memoryReview && this.pendingSteers.size) {
2099
+ for (const [id, pending] of [...this.pendingSteers]) {
2100
+ this.pendingSteers.delete(id);
2101
+ pending.reject(new Error(`Pi never answered the steer: the turn ended first.`));
2102
+ }
2103
+ }
2104
+ // The run is not over until the child is actually gone: a process that is still tearing down
2105
+ // still holds a lock on its working directory, so a caller that removes that directory the
2106
+ // moment answer() returns would hit EBUSY on Windows. Kill, then wait for the exit.
2107
+ //
2108
+ // The 5s backstop is load-bearing and matches the two other waits in this file: the kill
2109
+ // precedes the `exit` subscription, so an exit that lands between them is dropped and the promise
2110
+ // never settles. Unbounded, that hangs the turn that asked for it. See readCatalog() for the
2111
+ // measurement.
2112
+ await closePiWorker(child);
2113
+ }
2114
+ }
2115
+ /**
2116
+ * Reads back the id of the user message this turn just created, and hands it to the caller.
2117
+ *
2118
+ * `head` is the already-answered pre-turn `get_entries`, whose `leafId` is what makes the second read
2119
+ * exact. Its three possible outcomes are handled differently ON PURPOSE, because they mean different
2120
+ * things and two of them must not produce an id:
2121
+ *
2122
+ * - `leafId: null` - the session was empty, so this IS the first turn and the whole entry list is this
2123
+ * turn's. Safe to take the first user message from it.
2124
+ * - `leafId: "..."` - read only what came after it. Safe, and the only correct answer for turn two onward.
2125
+ * - no usable answer - Pi never told us where the turn began, so NOTHING in the transcript can be
2126
+ * attributed to it. Reading everything and taking "the first user message" here would hand back a
2127
+ * PREVIOUS turn's id, and a revert to that id would silently cut more than the user asked for. So this
2128
+ * case records nothing and says why.
2129
+ *
2130
+ * Every failure is a warning, never a throw: the turn's answer has already streamed by this point, and
2131
+ * "this message cannot be a revert boundary" is not "your message failed".
2132
+ */
2133
+ async recordTurnEntryId(channel, head, conversationId, onUserEntry) {
2134
+ const before = head?.data;
2135
+ const leaf = before?.leafId;
2136
+ if (leaf !== null && typeof leaf !== "string") {
2137
+ console.warn(`PiRpcRuntime: Pi did not report where turn of conversation ${conversationId} started, so its message was not recorded and cannot be used as a revert boundary.`);
2138
+ return;
2139
+ }
2140
+ try {
2141
+ const id = `turn_tail_${Math.random().toString(36).slice(2, 10)}`;
2142
+ // `since` is omitted, not sent as null, on the first turn: Pi's handler tests
2143
+ // `command.since !== undefined` (`rpc-mode.ts:638`), and an explicit null would be a lookup for an
2144
+ // entry named "null" that fails with an error instead of reading everything.
2145
+ channel.write({ id, type: "get_entries", ...(typeof leaf === "string" ? { since: leaf } : {}) });
2146
+ const tail = await channel.waitFor(id, SESSION_COMMAND_TIMEOUT_MS, "get_entries");
2147
+ if (tail.success === false)
2148
+ throw new Error(tail.error ?? "Pi rejected get_entries");
2149
+ const entries = tail.data?.entries;
2150
+ if (!Array.isArray(entries))
2151
+ throw new Error("get_entries returned no entry list");
2152
+ const firstUser = entries.find((entry) => {
2153
+ const candidate = entry;
2154
+ return candidate?.type === "message" && candidate.message?.role === "user" && typeof candidate.id === "string";
2155
+ });
2156
+ if (typeof firstUser?.id !== "string") {
2157
+ console.warn(`PiRpcRuntime: the entries Pi added for this turn contain no user message, so nothing was recorded as a revert boundary for conversation ${conversationId}.`);
2158
+ return;
2159
+ }
2160
+ await onUserEntry(firstUser.id);
2161
+ }
2162
+ catch (error) {
2163
+ console.warn(`PiRpcRuntime: could not record this turn's Pi entry id for conversation ${conversationId} (${error instanceof Error ? error.message : "unknown error"}) - its message cannot be used as a revert boundary.`);
2164
+ }
2165
+ }
2166
+ /**
2167
+ * Reverts Pi's own transcript to the state right after `boundaryEntryId`.
2168
+ *
2169
+ * ============================ WHAT THIS DESTROYS ============================
2170
+ * Every Pi entry after that boundary, permanently - including tool calls, compaction records, model and
2171
+ * thinking-level markers, and usage accounting, not just the messages Super Pi shows. A copy of the file
2172
+ * as it was is left beside it as `<file>.super-pi-revert-backup`, which Pi never lists because it does
2173
+ * not end in `.jsonl`. There is no undo in the application.
2174
+ *
2175
+ * No workspace file is read, written or restored. That is the whole point of not reaching for OpenCode's
2176
+ * `snapshot/` machinery: its revert rolls the working tree back (`snapshot/index.ts:382-406`), this one
2177
+ * must not, and Super Pi has no reason to build a second git shadow repository to do damage.
2178
+ * =============================================================================
2179
+ *
2180
+ * WHY PI IS ASKED WHICH FILE TO OPEN, rather than this code scanning the session directory.
2181
+ *
2182
+ * The obvious implementation - read the directory, find the `*.jsonl` whose header id matches - is
2183
+ * exactly the one that fails silently, and probe B measured why:
2184
+ *
2185
+ * 1. When Pi cannot find the requested id it does NOT fail. It prints a warning to stderr and opens a
2186
+ * brand-new session under that same id (`main.ts:436-448`), so a wrong lookup becomes "the history
2187
+ * has vanished" with no error anywhere in the UI. Measured:
2188
+ * `Warning: No project session found with id '...'; creating a new session with that id.`
2189
+ * 2. Pi's lookup is not "match the id". With an explicit `--session-dir` it ALSO requires the session's
2190
+ * recorded `cwd` to equal the one it was asked from (`session-manager.ts:1874-1891`), and probe B
2191
+ * measured the same id resolving to two different files from two different working directories -
2192
+ * one of which did not exist on disk.
2193
+ *
2194
+ * So the file is taken from Pi's own `get_state.sessionFile` (`rpc-mode.ts:448-464`), which is the
2195
+ * lookup Pi performed for a real spawn, and then THREE things are checked before a byte is written:
2196
+ * the file exists, its header is the session header, and that header's id is the conversation being
2197
+ * reverted. A miss on any of them refuses, in words, rather than truncating something it is not sure of.
2198
+ *
2199
+ * The cost is one extra Pi spawn, which is why this is a deliberate trade rather than an oversight:
2200
+ * revert is a rare, deliberate act, and a second Pi answers in well under a second. It buys the
2201
+ * elimination of an entire class of "we truncated the wrong file and nothing said so" failures.
2202
+ */
2203
+ /**
2204
+ * THE LIVE SESSION MUST GO WHEN A REVERT REWRITES THE TRANSCRIPT.
2205
+ *
2206
+ * A revert rewrites Pi's transcript on disk. A live Pi session holds the OLD context in memory, and
2207
+ * nothing in Pi would notice the difference: the model would keep answering from history the user
2208
+ * has just withdrawn, while `state.json` and the file on disk both said it was gone. Three views of
2209
+ * the conversation, two of them wrong, and no error anywhere. So the session is destroyed and the
2210
+ * next turn rebuilds it from the truncated file.
2211
+ *
2212
+ * THIS IS A CORRECTNESS REQUIREMENT, NOT AN OPTIMIZATION, and it is why it lives in one place
2213
+ * called by EVERY branch of `revert`. It used to be inline in two of the three, and the third -
2214
+ * the one taken when the transcript path was not cached - missed it, so a session reverted before
2215
+ * its path was ever learned kept talking about the withdrawn turn with nothing saying so.
2216
+ */
2217
+ async evictAfterRevert(conversationId) {
2218
+ await this.sessionPool.evict(conversationId);
2219
+ }
2220
+ async revert({ conversation, cwd, boundaryEntryId, beforeBoundary }) {
2221
+ if (this.runs.has(conversation.id) || this.activeTurns.has(conversation.id))
2222
+ throw new Error("这个会话还有一轮任务在跑,先停止它再回退");
2223
+ // Stop idle cache writes and finish accounting before rewriting the transcript.
2224
+ await this.disposeSessions(conversation.id);
2225
+ if (!this.pi.found)
2226
+ throw new Error(this.pi.reason);
2227
+ // Normal path: this exact worker already asked Pi for get_state before its prompt was sent, so reuse
2228
+ // that locator. `truncateSessionFile` below still proves the header belongs to this conversation and
2229
+ // validates the requested boundary and parent chain before a byte is changed. The cache removes an
2230
+ // otherwise pointless second Pi startup from every ordinary revert.
2231
+ const cached = conversation.piSessionFile;
2232
+ if (cached) {
2233
+ const exists = await stat(cached).catch(() => undefined);
2234
+ if (exists?.isFile()) {
2235
+ const result = await truncateSessionFile(cached, boundaryEntryId, conversation.id, beforeBoundary);
2236
+ await this.evictAfterRevert(conversation.id);
2237
+ return { sessionFile: cached, linesKept: result.linesKept, entriesDropped: result.entriesDropped };
2238
+ }
2239
+ }
2240
+ // Compatibility fallback for conversations created before the live-worker locator existed, or a
2241
+ // transcript that was moved since the last turn. This retains Pi's authoritative lookup rather than
2242
+ // guessing from filenames.
2243
+ const childCwd = resolve(cwd);
2244
+ const info = await stat(childCwd).catch(() => undefined);
2245
+ if (!info?.isDirectory())
2246
+ throw new Error(`工作区目录不存在或不是目录,无法在其中找到这个会话的 Pi 记录:${childCwd}`);
2247
+ await mkdir(this.sessionDir, { recursive: true });
2248
+ // THE SDK ANSWERS THIS, AND ANSWERING IT WITH A PROCESS IS WHAT USED TO MAKE REVERT SLOW.
2249
+ //
2250
+ // Pi looks a session up by id AND by working directory, and the SDK's session manager resolves the
2251
+ // same thing the RPC command would have - so the library is asked first, and a process is started
2252
+ // only when there is no library to ask. The verification below is unchanged and still decides
2253
+ // whether the file may be written: `truncateSessionFile` proves the header belongs to this
2254
+ // conversation and validates the boundary, so a wrong answer from either source still cannot
2255
+ // truncate somebody else's history.
2256
+ const resolved = await this.resolveTranscriptFileWithoutSpawn(childCwd, conversation.id);
2257
+ if (resolved !== undefined) {
2258
+ const found = await stat(resolved).catch(() => undefined);
2259
+ if (!found?.isFile())
2260
+ throw new Error(`Pi 还没有为这个会话建立记录文件(${resolved}),没有可以回退的历史。`);
2261
+ const result = await truncateSessionFile(resolved, boundaryEntryId, conversation.id, beforeBoundary);
2262
+ await this.evictAfterRevert(conversation.id);
2263
+ return { sessionFile: resolved, linesKept: result.linesKept, entriesDropped: result.entriesDropped };
2264
+ }
2265
+ // NO agent flags and NO extension on this spawn. It sends no prompt and must leave nothing behind:
2266
+ // `SessionManager._persist` only creates a file once a session holds a message
2267
+ // (`session-manager.ts:1160-1170`), so an answer to `get_state` cannot write anything. Adding the
2268
+ // task extension here would mount a tool whose every call fails, since no endpoint is wired up.
2269
+ const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--no-tools", "--no-extensions", "--no-mcp", "--no-skills", "--no-context-files", "--no-prompt-templates", "--session-dir", this.sessionDir, "--session-id", conversation.id], {
2270
+ cwd: childCwd,
2271
+ stdio: ["pipe", "pipe", "pipe"],
2272
+ shell: process.platform === "win32",
2273
+ });
2274
+ let sessionFile;
2275
+ try {
2276
+ const channel = new RpcChannel(child);
2277
+ const state = await channel.request({ id: "revert_state", type: "get_state" }, LOOKUP_COMMAND_TIMEOUT_MS);
2278
+ if (state.success === false)
2279
+ throw new Error(`Pi 没有回答会话状态:${state.error ?? "未说明原因"}`);
2280
+ const data = state.data;
2281
+ // Pi echoes the id back even when it has just INVENTED a session for it, so this catches a Pi that
2282
+ // did something else entirely rather than the ordinary "no history yet" case below.
2283
+ if (typeof data?.sessionId === "string" && data.sessionId !== conversation.id)
2284
+ throw new Error(`Pi 打开的会话是 ${JSON.stringify(data.sessionId)},不是要回退的 ${JSON.stringify(conversation.id)}。已放弃,没有改动任何文件。`);
2285
+ if (typeof data?.sessionFile === "string" && data.sessionFile)
2286
+ sessionFile = data.sessionFile;
2287
+ if (channel.stderr.trim())
2288
+ console.warn(`PiRpcRuntime: Pi said this while locating conversation ${conversation.id}: ${channel.stderr.trim()}`);
2289
+ }
2290
+ catch (error) {
2291
+ if (child.exitCode === null && child.pid !== undefined)
2292
+ await killTree(child.pid);
2293
+ // taskkill has already terminated the process tree; do not add a five-second UI stall waiting for
2294
+ // Node's exit event bookkeeping on Windows.
2295
+ throw error instanceof Error ? error : new Error(`无法向 Pi 询问会话文件:${String(error)}`);
2296
+ }
2297
+ // The lookup Pi is holding open is finished; it is killed BEFORE the file is touched, for the same
2298
+ // reason `answer()` kills before returning: a process still tearing down can still be appending.
2299
+ if (child.exitCode === null && child.pid !== undefined)
2300
+ await killTree(child.pid);
2301
+ // The process tree is dead after killTree; copying can proceed without waiting for a delayed exit event.
2302
+ if (!sessionFile)
2303
+ throw new Error("Pi 没有报告这个会话的记录文件,已放弃,没有改动任何文件。");
2304
+ const exists = await stat(sessionFile).catch(() => undefined);
2305
+ // Measured, not guessed: Pi answers `get_state` with the path it WOULD use even for a session it has
2306
+ // just created, and that path does not exist until a message has been sent
2307
+ // (`session-manager.ts:1160-1170`). So "reported but absent" is the ordinary reading of "this
2308
+ // conversation has no Pi history yet", and truncating nothing is the correct outcome - but it is
2309
+ // reported, because the alternative is a revert that appears to work and changes nothing.
2310
+ if (!exists?.isFile())
2311
+ throw new Error(`Pi 还没有为这个会话建立记录文件(${sessionFile}),没有可以回退的历史。`);
2312
+ const result = await truncateSessionFile(sessionFile, boundaryEntryId, conversation.id, beforeBoundary);
2313
+ await this.evictAfterRevert(conversation.id);
2314
+ return { sessionFile, linesKept: result.linesKept, entriesDropped: result.entriesDropped };
2315
+ }
2316
+ /**
2317
+ * Copies Pi's own transcript for one conversation into a second, independent file under a new id.
2318
+ *
2319
+ * THE SAME THREE STEPS AS REVERT, IN THE SAME ORDER, AND FOR THE SAME REASONS: refuse a live turn, ask Pi
2320
+ * which file it uses rather than scanning the directory (probe B measured that a directory scan resolves
2321
+ * the wrong file or a nonexistent one with no error, and that Pi invents an empty session under an id it
2322
+ * cannot find), kill that Pi BEFORE touching anything on disk, and check the file's header against the
2323
+ * conversation being forked before a byte is written. Every one of those paragraphs above still applies
2324
+ * here word for word, because it is the same machinery pointed the other way: revert cuts a file in
2325
+ * place, fork copies a file beside it.
2326
+ *
2327
+ * ============================ WHAT A FORK COPIES ============================
2328
+ * The file, byte for byte, with two header fields changed (`id`, `parentSession` - see `forkSessionFile`).
2329
+ * Entry ids are NOT renumbered, so every message recorded on the source keeps a `piEntryId` that is valid
2330
+ * in the fork too, which is what keeps REVERT working inside a forked conversation.
2331
+ * =============================================================================
2332
+ *
2333
+ * WHAT A FORK DOES NOT COPY, and both omissions are deliberate:
2334
+ *
2335
+ * - **Sub-agent runs.** `SubagentRun.conversationId` points at the conversation that dispatched it, and
2336
+ * research pitfall 7 is that truncating or duplicating a transcript leaves those records orphaned. A
2337
+ * forked conversation shows the messages but no child cards from before the fork: the children belong to
2338
+ * the conversation that started them, they are not listed anywhere once their parent has copied their
2339
+ * words, and a card in the fork that could not be stopped from the fork would be worse than no card.
2340
+ * - **Queued messages.** Same argument, and narrower: a waiting message belongs to the run in progress,
2341
+ * and a run is not copied.
2342
+ *
2343
+ * THE EMPTY-CONVERSATION CASE IS NOT AN ERROR. A conversation with no messages has no Pi file at all -
2344
+ * `SessionManager._persist` only creates one once a session holds a message (`:1160-1170`) - so there is
2345
+ * nothing to copy and the fork is a copy of `state.json` alone. That is checked BEFORE any Pi is spawned,
2346
+ * so forking a fresh conversation costs nothing and cannot fail. The converse is refused rather than
2347
+ * tolerated: messages in `state.json` with no Pi file means the two histories were ALREADY out of step,
2348
+ * and copying that into a second conversation would make the disagreement permanent and multiply it.
2349
+ */
2350
+ async fork({ conversation, cwd, forkedConversationId }) {
2351
+ if (this.runs.has(conversation.id) || this.activeTurns.has(conversation.id))
2352
+ throw new Error("这个会话还有一轮任务在跑,先停止它再分叉");
2353
+ await this.disposeSessions(conversation.id);
2354
+ if (!conversation.messages.length)
2355
+ return { entriesCopied: 0 };
2356
+ if (!this.pi.found)
2357
+ throw new Error(this.pi.reason);
2358
+ const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
2359
+ const target = join(this.sessionDir, `${stamp}_${forkedConversationId}.jsonl`);
2360
+ const cached = conversation.piSessionFile;
2361
+ if (cached && (await stat(cached).catch(() => undefined))?.isFile()) {
2362
+ const result = await forkSessionFile(cached, target, conversation.id, forkedConversationId);
2363
+ return { sessionFile: target, ...result };
2364
+ }
2365
+ const childCwd = resolve(cwd);
2366
+ const info = await stat(childCwd).catch(() => undefined);
2367
+ if (!info?.isDirectory())
2368
+ throw new Error(`工作区目录不存在或不是目录,无法在其中找到这个会话的 Pi 记录:${childCwd}`);
2369
+ await mkdir(this.sessionDir, { recursive: true });
2370
+ // THE SAME SDK LOOKUP AS REVERT, FOR THE SAME REASON: a process would be started only to be told
2371
+ // which file Pi uses, and Pi's own session manager answers that without a process.
2372
+ const resolved = await this.resolveTranscriptFileWithoutSpawn(childCwd, conversation.id);
2373
+ if (resolved !== undefined) {
2374
+ const found = await stat(resolved).catch(() => undefined);
2375
+ if (!found?.isFile())
2376
+ return { entriesCopied: 0 };
2377
+ const copied = await forkSessionFile(resolved, target, conversation.id, forkedConversationId);
2378
+ return { sessionFile: target, ...copied };
2379
+ }
2380
+ // The same lookup spawn as `revert`, and the same reason for leaving the agent flags off: this child
2381
+ // sends no prompt and must leave nothing behind.
2382
+ const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--no-tools", "--no-extensions", "--no-mcp", "--no-skills", "--no-context-files", "--no-prompt-templates", "--session-dir", this.sessionDir, "--session-id", conversation.id], {
2383
+ cwd: childCwd,
2384
+ stdio: ["pipe", "pipe", "pipe"],
2385
+ shell: process.platform === "win32",
2386
+ });
2387
+ let sessionFile;
2388
+ try {
2389
+ const channel = new RpcChannel(child);
2390
+ const state = await channel.request({ id: "fork_state", type: "get_state" }, LOOKUP_COMMAND_TIMEOUT_MS);
2391
+ if (state.success === false)
2392
+ throw new Error(`Pi 没有回答会话状态:${state.error ?? "未说明原因"}`);
2393
+ const data = state.data;
2394
+ if (typeof data?.sessionId === "string" && data.sessionId !== conversation.id)
2395
+ throw new Error(`Pi 打开的会话是 ${JSON.stringify(data.sessionId)},不是要分叉的 ${JSON.stringify(conversation.id)}。已放弃,没有复制任何文件。`);
2396
+ if (typeof data?.sessionFile === "string" && data.sessionFile)
2397
+ sessionFile = data.sessionFile;
2398
+ if (channel.stderr.trim())
2399
+ console.warn(`PiRpcRuntime: Pi said this while locating conversation ${conversation.id} for a fork: ${channel.stderr.trim()}`);
2400
+ }
2401
+ catch (error) {
2402
+ if (child.exitCode === null && child.pid !== undefined)
2403
+ await killTree(child.pid);
2404
+ // killTree waits for taskkill; waiting again for Node's exit event can miss the event and add 5s.
2405
+ throw error instanceof Error ? error : new Error(`无法向 Pi 询问会话文件:${String(error)}`);
2406
+ }
2407
+ if (child.exitCode === null && child.pid !== undefined)
2408
+ await killTree(child.pid);
2409
+ // killTree waits for taskkill; do not wait for a possibly already-delivered exit event.
2410
+ if (!sessionFile)
2411
+ throw new Error("Pi 没有报告这个会话的记录文件,已放弃,没有复制任何文件。");
2412
+ const exists = await stat(sessionFile).catch(() => undefined);
2413
+ // Reached only when `state.json` HAS messages, so "reported but absent" cannot be the ordinary
2414
+ // no-history-yet reading here - it means the two files have already diverged, and the refusal says so.
2415
+ if (!exists?.isFile())
2416
+ throw new Error(`这个会话在 Super Pi 里有 ${conversation.messages.length} 条消息,但 Pi 的记录文件不存在(${sessionFile})。两份记录已经不一致,拒绝分叉——否则新会话会带着一份对不上的历史出生。`);
2417
+ // Named after the new id, exactly the way Pi names its own (`${timestamp}_${sessionId}.jsonl`,
2418
+ // `session-manager.ts:1673`), so a directory listing sorts and reads the way Pi's would. The timestamp
2419
+ // is the fork's, not the source's: the file header keeps the SOURCE timestamp verbatim (it is history),
2420
+ // while the filename carries when this copy was made, which is what makes the ordering of a directory
2421
+ // full of forks mean anything.
2422
+ const result = await forkSessionFile(sessionFile, target, conversation.id, forkedConversationId);
2423
+ return { sessionFile: target, ...result };
2424
+ }
2425
+ /**
2426
+ * Delivers one Extension UI request. One-way methods are pushed to the host and never replied to
2427
+ * (Pi holds no pending entry, so a response would resolve nothing). Blocking methods are handed to
2428
+ * the host and this call is awaited, so Pi stays blocked exactly as long as the human takes.
2429
+ */
2430
+ async handleExtensionUi(record, child, host, run) {
2431
+ const request = describeExtensionUiRequest(record);
2432
+ if (!request) {
2433
+ console.warn(`PiRpcRuntime: extension_ui_request method=${JSON.stringify(record.method ?? null)} id=${JSON.stringify(record.id ?? null)} is not one of Pi's nine Extension UI methods - consumed without reply.`);
2434
+ return;
2435
+ }
2436
+ const reply = (response) => {
2437
+ if (child.exitCode === null && !child.killed && !child.stdin.destroyed) {
2438
+ try {
2439
+ child.stdin.write(`${JSON.stringify(response)}\n`);
2440
+ }
2441
+ catch { /* the child died between the check and the write; the reply is moot */ }
2442
+ }
2443
+ };
2444
+ if (!request.blocking) {
2445
+ // Deliberately not awaited: these five are fire-and-forget in Pi, and awaiting would stall the
2446
+ // drain loop on a UI that already told us it wants no reply.
2447
+ try {
2448
+ host?.notify(request);
2449
+ }
2450
+ catch (error) {
2451
+ console.warn(`PiRpcRuntime: extension_ui notify for ${request.method} id=${request.requestId} threw in the host: ${error instanceof Error ? error.message : "unknown error"}`);
2452
+ }
2453
+ return;
2454
+ }
2455
+ if (run.seen.has(request.requestId)) {
2456
+ console.warn(`PiRpcRuntime: extension_ui_request method=${request.method} id=${request.requestId} arrived twice - second copy consumed without reply.`);
2457
+ return;
2458
+ }
2459
+ run.seen.add(request.requestId);
2460
+ if (!host) {
2461
+ // No human can be asked, so the honest reply is "cancelled". Auto-answering with options[0] or
2462
+ // confirmed:false would look to Pi exactly like a decision, and the user would never learn a
2463
+ // question was asked of them.
2464
+ console.warn(`PiRpcRuntime: extension_ui_request method=${request.method} id=${request.requestId} has no UI host, so nobody can answer it - cancelled rather than answering on the user's behalf.`);
2465
+ reply({ type: "extension_ui_response", id: request.requestId, cancelled: true });
2466
+ return;
2467
+ }
2468
+ const cancelled = { cancelled: true };
2469
+ let answer;
2470
+ try {
2471
+ answer = await Promise.race([host.ask(request), run.aborted.then(() => cancelled), run.exited.then(() => cancelled)]);
2472
+ }
2473
+ catch (error) {
2474
+ console.warn(`PiRpcRuntime: extension_ui_request method=${request.method} id=${request.requestId} host failed (${error instanceof Error ? error.message : "unknown error"}) - cancelled.`);
2475
+ answer = cancelled;
2476
+ }
2477
+ reply(buildExtensionUiResponse(request, answer));
2478
+ }
2479
+ async stop(conversationId) {
2480
+ // A turn on a persistent session is stopped by aborting THAT SESSION, and the session survives - it
2481
+ // is the next turn's session. This is the whole reason an interrupt no longer costs a process
2482
+ // teardown and a process startup: there is no process to tear down.
2483
+ const turn = this.activeTurns.get(conversationId);
2484
+ if (turn) {
2485
+ turn.abort();
2486
+ // abort() can resolve during prompt preflight, before any agent exists. Await the prompt call
2487
+ // as well, which includes that preflight and the actual run in Pi 0.86. For adapters returning
2488
+ // earlier, abortDone still waits for idle. Do not wait for the caller to drain the event queue:
2489
+ // a caller may stop while paused at a yielded delta. A deadline bounds only this request;
2490
+ // RunService retains the real run slot until the reader ends.
2491
+ let stopDeadline;
2492
+ try {
2493
+ await Promise.race([Promise.all([turn.promptFinished, turn.abortDone]), new Promise((resolvePromise) => {
2494
+ stopDeadline = setTimeout(resolvePromise, 5_000);
2495
+ })]);
2496
+ }
2497
+ finally {
2498
+ if (stopDeadline !== undefined)
2499
+ clearTimeout(stopDeadline);
2500
+ }
2501
+ return;
2502
+ }
2503
+ // The one-shot path: a child process that has to be told to abort over its stdin.
2504
+ const run = this.runs.get(conversationId);
2505
+ if (!run)
2506
+ return;
2507
+ // Same guard as the abort listener in `answer`: a destroyed stdin throws synchronously on write.
2508
+ if (run.child.exitCode === null && !run.child.killed && !run.child.stdin.destroyed) {
2509
+ try {
2510
+ run.child.stdin.write(`${JSON.stringify({ id: "abort", type: "abort" })}\n`);
2511
+ }
2512
+ catch { /* the child died between the check and the write; the abort is moot */ }
2513
+ }
2514
+ }
2515
+ /**
2516
+ * Injects one message into the Pi process that is running right now, at its next turn boundary.
2517
+ *
2518
+ * `steer` and NOT `follow_up`, and NOT `prompt` with a `streamingBehavior`. The three are not
2519
+ * interchangeable and the difference is the whole feature:
2520
+ *
2521
+ * - `steer` is drained at `agent-loop.ts:295`, after `turn_end` and therefore after the current
2522
+ * assistant message's WHOLE tool-call batch has finished, before the next LLM request. The agent
2523
+ * stops doing what it was doing at the next boundary instead of at the end of the task. That is
2524
+ * "插队", and its granularity is a tool BATCH - a long single tool call is not interruptible,
2525
+ * because Pi offers no preemption.
2526
+ * - `follow_up` is drained at `agent-loop.ts:302`, only once the agent has stopped on its own.
2527
+ * - `prompt` would start a turn, which is the thing that must NOT happen here: this conversation
2528
+ * already has a turn in flight, and starting a second one is the two-writers-one-session bug.
2529
+ *
2530
+ * NO `set_follow_up_mode` / `set_steering_mode` IS EVER SENT, and that is a hard rule rather than a
2531
+ * default. Both go through `AgentSession.set*Mode`, which mutates `SettingsManager`'s global scope and
2532
+ * calls `save()` (`settings-manager.ts:857-871`), writing to the user's Pi `settings.json`. A host that
2533
+ * merely wanted a different queue depth would permanently rewrite the user's Pi configuration. Pi's
2534
+ * default is already `one-at-a-time` (`agent.ts:247-248`), which is the semantics this wants: one
2535
+ * queued message consumed per boundary.
2536
+ *
2537
+ * REJECTS rather than reporting success when there is no live child, and when Pi does not answer in
2538
+ * time. The caller keeps the message cancellable in the first case because it provably reached no
2539
+ * model; in the second the outcome is genuinely unknown and a `sending` state says so.
2540
+ */
2541
+ async summarizeConversation(conversation, cwd, signal) {
2542
+ if (!this.pi.found)
2543
+ throw new Error(this.pi.reason);
2544
+ const TIMEOUT_MS = CONVERSATION_TITLE_TIMEOUT_MS;
2545
+ // Session names live in a narrow sidebar row. Keep the model's budget well below the storage
2546
+ // limit so the result remains a concise label instead of becoming a sentence.
2547
+ const MAX_TITLE_CHARS = 18;
2548
+ // A throwaway session id, not the conversation's: this child reads nothing else and its history must
2549
+ // not be filed under the conversation whose title it is producing.
2550
+ // The selected model is carried over, but the current conversation transcript and its live cache are
2551
+ // deliberately not: title generation is an isolated, bounded one-shot request.
2552
+ const selectedModel = conversation.model;
2553
+ const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--no-session", "--no-tools", "--no-extensions", "--no-mcp", "--no-skills", "--no-context-files", "--no-prompt-templates"], {
2554
+ cwd: resolve(cwd),
2555
+ env: { ...process.env, ...await readProviderProxyEnv(defaultAgentDir(), selectedModel?.provider) },
2556
+ stdio: ["pipe", "pipe", "pipe"],
2557
+ shell: process.platform === "win32",
2558
+ });
2559
+ const channel = new RpcChannel(child);
2560
+ const deadline = Date.now() + TIMEOUT_MS;
2561
+ try {
2562
+ const messages = conversation.messages
2563
+ .filter(message => (message.role === "user" || message.role === "assistant" || message.source === "session-reminder") && message.content.trim())
2564
+ .map(message => ({
2565
+ label: message.source === "session-reminder" ? "定时提醒" : message.role === "user" ? "User" : "Assistant",
2566
+ content: message.content.trim(),
2567
+ }));
2568
+ const firstUser = messages.find(message => message.label === "User");
2569
+ const recent = messages.slice(-10);
2570
+ const selected = firstUser && !recent.includes(firstUser) ? [firstUser, ...recent] : recent;
2571
+ const excerpts = selected.map(message => {
2572
+ const content = message.content.length > 1_500
2573
+ ? `${message.content.slice(0, 1_100)}\n[…中间内容省略…]\n${message.content.slice(-300)}`
2574
+ : message.content;
2575
+ return `${message.label}: ${content}`;
2576
+ });
2577
+ let transcript = excerpts.join("\n\n");
2578
+ if (transcript.length > CONVERSATION_TITLE_CONTEXT_MAX_CHARS) {
2579
+ const headSize = 2_500;
2580
+ transcript = `${transcript.slice(0, headSize)}\n\n[…较早对话省略…]\n\n${transcript.slice(-(CONVERSATION_TITLE_CONTEXT_MAX_CHARS - headSize - 32))}`;
2581
+ }
2582
+ if (!transcript)
2583
+ throw new Error("这个会话还没有内容,无法据此生成标题");
2584
+ if (selectedModel?.provider && selectedModel.modelId) {
2585
+ const modelResponse = await channel.request({ id: "autotitle_model", type: "set_model", provider: selectedModel.provider, modelId: selectedModel.modelId }, Math.max(1, Math.min(30_000, deadline - Date.now())));
2586
+ if (modelResponse.success !== true)
2587
+ throw new Error(modelResponse.error || `Pi 无法使用当前会话模型 ${selectedModel.provider}/${selectedModel.modelId}`);
2588
+ }
2589
+ // Reasoning adds latency without improving a short session label. Keep this one-shot call fast
2590
+ // even when the user's normal default thinking level is high.
2591
+ const thinkingResponse = await channel.request({ id: "autotitle_thinking", type: "set_thinking_level", level: "off" }, Math.max(1, Math.min(30_000, deadline - Date.now())));
2592
+ if (thinkingResponse.success !== true)
2593
+ throw new Error(thinkingResponse.error || "Pi 未能关闭标题生成的思考等级");
2594
+ channel.write({
2595
+ id: "autotitle_prompt",
2596
+ type: "prompt",
2597
+ message: [
2598
+ "为下面这段对话起一个简短标题,用作会话列表里的一行字。直接命名,不需要展开分析或推理。",
2599
+ "只输出标题本身:不要引号、句末标点、「标题:」前缀、解释或换行。",
2600
+ `只生成一个简短的会话标签,长度严格不超过 ${MAX_TITLE_CHARS} 个字符(中文按一个字计数)。优先控制在 8-12 个字符;不要写成完整句子,不要使用副标题、解释、列表或多个候选标题。用与对话内容相同的语言。`,
2601
+ "",
2602
+ transcript,
2603
+ ].join("\n"),
2604
+ });
2605
+ let settled = false, text = "";
2606
+ while (!settled && Date.now() < deadline) {
2607
+ if (signal?.aborted)
2608
+ throw new Error("已取消");
2609
+ const record = await channel.next(100);
2610
+ if (!record)
2611
+ continue;
2612
+ if (record.type === "message_update" && record.assistantMessageEvent?.type === "text_delta")
2613
+ text += record.assistantMessageEvent.delta ?? "";
2614
+ if (record.type === "agent_settled")
2615
+ settled = true;
2616
+ if (record.type === "response" && record.id === "autotitle_prompt" && record.success === false)
2617
+ throw new Error(record.error ?? "Pi 拒绝了这次请求");
2618
+ if (child.exitCode !== null)
2619
+ throw new Error("生成标题的进程意外退出");
2620
+ }
2621
+ if (!settled)
2622
+ throw new Error(`模型在 ${TIMEOUT_MS / 1000} 秒内没有返回标题`);
2623
+ // A model asked for "only the title" still wraps it now and then. Stripping the wrappers is not
2624
+ // cosmetic: without it a leading quote or a `Title:` prefix becomes the first characters of every
2625
+ // title in the sidebar.
2626
+ //
2627
+ // AND THE MODEL'S OWN REASONING IS STRIPPED FIRST, because a model that thinks inside its
2628
+ // answer puts the thinking in front of the title: the title would then start with `<think>`,
2629
+ // and the sidebar would show the markup of a reasoning trace where a label belongs.
2630
+ const title = stripInlineThinking(text)
2631
+ .replace(/^\s*(?:title|标题)\s*[::]\s*/iu, "")
2632
+ .replace(/^[`"'“”‘’「『]+/u, "")
2633
+ .replace(/[`"'“”‘’」』]+$/u, "")
2634
+ .replace(/[。.!!,,、;;\s]+$/u, "")
2635
+ .trim()
2636
+ .slice(0, MAX_TITLE_CHARS);
2637
+ if (!title) {
2638
+ const fallback = conversation.messages.find((message) => message.role === "user" && message.content.trim())?.content.trim();
2639
+ return (fallback || "新会话").slice(0, MAX_TITLE_CHARS);
2640
+ }
2641
+ return title;
2642
+ }
2643
+ finally {
2644
+ // The child is this method's alone, so leaving it running would leak one Pi process per rename.
2645
+ if (child.exitCode === null && child.pid !== undefined)
2646
+ await killTree(child.pid);
2647
+ }
2648
+ }
2649
+ /**
2650
+ * A single completion for a mounted tool. See `AgentRuntime.askOnce` for why it is its own child,
2651
+ * why nothing is attached but Pi, and why it picks no model.
2652
+ */
2653
+ async askOnce(input) {
2654
+ if (!this.pi.found)
2655
+ throw new Error(this.pi.reason);
2656
+ const args = ["--mode", "rpc", "--no-session", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-mcp"];
2657
+ let nativeEnv = {};
2658
+ if (input.agent && input.onToolStart) {
2659
+ const selection = nativeToolPolicy(toolSelection(input.agent.tools), readNativeToolSettings(nativeToolSettingsPath(this.sessionDir)));
2660
+ args.push("--extension", nativeToolExtensionPath(), ...nativeToolArgs(selection));
2661
+ nativeEnv = nativeToolEnv(this.sessionDir, selection);
2662
+ }
2663
+ else
2664
+ args.push("--no-tools", "--no-context-files");
2665
+ if (input.agent)
2666
+ args.push(input.agent.promptMode === "replace" ? "--system-prompt" : "--append-system-prompt", await writeAgentPrompt(this.agents.promptDir, input.agent));
2667
+ const proxyEnv = await readProviderProxyEnv(defaultAgentDir(), input.model?.provider);
2668
+ input.signal?.throwIfAborted();
2669
+ const child = spawn(shellQuote(this.pi.command), args.map(arg => shellQuote(arg)), {
2670
+ cwd: resolve(input.cwd),
2671
+ env: { ...process.env, ...proxyEnv, ...nativeEnv },
2672
+ stdio: ["pipe", "pipe", "pipe"],
2673
+ shell: process.platform === "win32",
2674
+ detached: process.platform !== "win32",
2675
+ });
2676
+ const channel = new RpcChannel(child);
2677
+ const deadline = Date.now() + input.timeoutMs;
2678
+ try {
2679
+ if (input.model) {
2680
+ const response = await channel.request({ id: "isolated_model", type: "set_model", provider: input.model.provider, modelId: input.model.modelId }, Math.min(input.timeoutMs, 8_000));
2681
+ if (response.success !== true)
2682
+ throw new Error(response.error || "Pi 无法选择指定模型");
2683
+ }
2684
+ input.signal?.throwIfAborted();
2685
+ channel.write({ id: "tool_llm", type: "prompt", message: input.prompt });
2686
+ let settled = false, text = "";
2687
+ let failure;
2688
+ const splitter = new InlineThinkingSplitter();
2689
+ const append = (parts) => {
2690
+ for (const part of parts) {
2691
+ if (part.kind === "thinking")
2692
+ input.onExecution?.({ kind: "thinking", phase: "delta", delta: part.text });
2693
+ else if (part.kind === "thinking-end")
2694
+ input.onExecution?.({ kind: "thinking", phase: "end" });
2695
+ }
2696
+ const delta = parts.filter(part => part.kind === "text").map(part => part.text).join("");
2697
+ if (!delta)
2698
+ return;
2699
+ text += delta;
2700
+ input.onText?.(delta);
2701
+ };
2702
+ const noteOutcome = (message, reason) => {
2703
+ const stop = message?.stopReason ?? reason;
2704
+ if (stop)
2705
+ failure = ["error", "aborted", "length"].includes(stop) ? message?.errorMessage || `模型未完成回答(${stop})` : undefined;
2706
+ };
2707
+ while (!settled && Date.now() < deadline) {
2708
+ if (input.signal?.aborted)
2709
+ throw new Error("已取消");
2710
+ const record = await channel.next(100);
2711
+ if (!record)
2712
+ continue;
2713
+ if (record.type === "tool_execution_start")
2714
+ input.onToolStart?.();
2715
+ if (input.onExecution && record.toolCallId && (record.type === "tool_execution_start" || record.type === "tool_execution_update" || record.type === "tool_execution_end")) {
2716
+ const phase = record.type === "tool_execution_start" ? "start" : record.type === "tool_execution_update" ? "update" : "end";
2717
+ const name = (record.toolName ?? "tool").slice(0, 64);
2718
+ // Keep file targets and simple executable names. Command arguments and tool output stay in Pi.
2719
+ const detail = ["read", "write", "edit", "grep", "find", "ls"].includes(name)
2720
+ ? describeToolCall("read", record.args)
2721
+ : name === "bash" || name === "powershell" ? describeToolCall(name, record.args)?.match(/^[a-z][a-z\d_.-]{0,31}(?=\s|$)/i)?.[0] : undefined;
2722
+ input.onExecution({ kind: "tool", phase, call: {
2723
+ id: record.toolCallId.slice(0, 160), name, detail,
2724
+ status: phase === "end" ? record.isError === true ? "error" : "ok" : undefined,
2725
+ durationMs: typeof record.durationMs === "number" && Number.isFinite(record.durationMs) ? Math.max(0, Math.round(record.durationMs)) : undefined,
2726
+ } });
2727
+ }
2728
+ if (record.type === "message_update") {
2729
+ const event = record.assistantMessageEvent;
2730
+ if (event?.type === "text_delta")
2731
+ append(splitter.push(event.delta ?? ""));
2732
+ else if (event?.type === "thinking_start")
2733
+ input.onExecution?.({ kind: "thinking", phase: "start" });
2734
+ else if (event?.type === "thinking_delta")
2735
+ input.onExecution?.({ kind: "thinking", phase: "delta", delta: event.delta });
2736
+ else if (event?.type === "thinking_end")
2737
+ input.onExecution?.({ kind: "thinking", phase: "end" });
2738
+ if (event?.type === "done" || event?.type === "error")
2739
+ noteOutcome(event.message, event.type === "error" ? "error" : event.reason);
2740
+ }
2741
+ if (record.type === "agent_end" && !record.willRetry && record.messages)
2742
+ noteOutcome([...record.messages].reverse().find(message => message.role === "assistant"));
2743
+ if (record.type === "agent_settled")
2744
+ settled = true;
2745
+ if (record.type === "response" && record.id === "tool_llm" && record.success === false)
2746
+ throw new Error(record.error ?? "Pi 拒绝了这次请求");
2747
+ if (!settled && child.exitCode !== null)
2748
+ throw new Error("模型进程意外退出");
2749
+ }
2750
+ if (!settled)
2751
+ throw new Error(`模型在 ${Math.round(input.timeoutMs / 1000)} 秒内没有返回`);
2752
+ // THE MODEL'S OWN REASONING IS NOT THE TOOL'S OUTPUT. A model that thinks inside its answer
2753
+ // would otherwise hand the caller a `<think>`-prefixed string, and the caller - a tool, a
2754
+ // title, a card - would store the reasoning trace as its result.
2755
+ append(splitter.flush());
2756
+ if (failure)
2757
+ throw new Error(failure);
2758
+ if (!text.trim())
2759
+ throw new Error("模型没有返回任何内容");
2760
+ return text;
2761
+ }
2762
+ finally {
2763
+ await closePiWorker(child);
2764
+ }
2765
+ }
2766
+ /**
2767
+ * The live session for a conversation, if there is one.
2768
+ *
2769
+ * Throws when there is none, because every caller wants a session it can act on - a steer that has
2770
+ * nowhere to go is a refusal the caller turns into "this message could not be delivered", not a
2771
+ * silent success.
2772
+ */
2773
+ async sessionFor(conversationId) {
2774
+ const session = this.sessionPool.get(conversationId);
2775
+ if (!session)
2776
+ throw new SteerUnavailableError(`会话 ${conversationId} 还没有可用的 Pi 会话`);
2777
+ return session;
2778
+ }
2779
+ /**
2780
+ * Hands a message to Pi's FOLLOW-UP queue, to be answered when the current run finishes its work.
2781
+ *
2782
+ * WHY THIS EXISTS ALONGSIDE A STEER. Both put a message into a queue Pi drains inside the running
2783
+ * turn, and neither of them re-runs `_prepareRun` - so neither re-emits `before_agent_start`, and
2784
+ * neither pays for the memory search and the system-prompt patch that hook does. A queued message
2785
+ * that answered itself with a fresh `prompt()` paid for both, once per message, and the prompt it
2786
+ * sent was larger than the one before it.
2787
+ *
2788
+ * The difference between the two is WHEN Pi delivers the message: a steer lands at the next turn
2789
+ * boundary (in the middle of the answer, which is what 「插队」 means), and a follow-up lands when
2790
+ * the agent would otherwise stop (after the answer, which is what a message typed while the agent
2791
+ * was busy means).
2792
+ */
2793
+ async followUp(conversationId, message, images) {
2794
+ // THE SESSION PATH. `session.followUp` is Pi's own follow-up queue, so the message joins the run
2795
+ // that is already going and is delivered by the agent loop when that run has nothing left to do.
2796
+ if (this.activeTurns.has(conversationId)) {
2797
+ const session = await this.sessionFor(conversationId);
2798
+ const imagePayloads = this.options.uploadsDir && images?.length
2799
+ ? await loadConversationImages(this.options.uploadsDir, conversationId, images)
2800
+ : undefined;
2801
+ if (!session.followUp)
2802
+ throw new SteerUnavailableError(`会话 ${conversationId} 的 Pi 不支持排队消息`);
2803
+ const disposition = await session.followUp(message, imagePayloads?.length ? imagePayloads : undefined);
2804
+ return disposition === "handled" ? "handled" : "queued";
2805
+ }
2806
+ // NO TURN TO FOLLOW. A follow-up is only meaningful while something is running - with nothing
2807
+ // running, Pi would hold the message until the NEXT run, which is the same answer arriving much
2808
+ // later than a prompt would have given it.
2809
+ //
2810
+ // THE ONE-SHOT PATH IS THIS CASE TOO, and it is not an accident: that path runs each turn in a
2811
+ // short-lived child that is killed when the turn ends, so a follow-up queue would die with it. The
2812
+ // message falls back to being answered by a turn of its own, which is the only thing that path can
2813
+ // do anyway.
2814
+ throw new SteerUnavailableError(`会话 ${conversationId} 当前没有可以接手的 Pi 会话,无法排队`);
2815
+ }
2816
+ async sendCustomMessage(conversationId, message) {
2817
+ const session = await this.sessionFor(conversationId);
2818
+ if (!session.sendCustomMessage)
2819
+ throw new SteerUnavailableError(`会话 ${conversationId} 的 Pi 不支持 custom message`);
2820
+ await session.sendCustomMessage(message, { triggerTurn: true, deliverAs: "followUp" });
2821
+ }
2822
+ /**
2823
+ * Empties Pi's steering and follow-up queues and returns what was in them.
2824
+ *
2825
+ * The session path asks Pi directly (`session.clearQueue`). The one-shot path writes Pi's
2826
+ * `clear_queue` command, which answers with the text it removed.
2827
+ */
2828
+ async clearQueues(conversationId) {
2829
+ const empty = { steering: [], followUp: [] };
2830
+ // A session and its queues outlive the active turn, including the abort hand-off window.
2831
+ const session = this.sessionPool.get(conversationId);
2832
+ if (session) {
2833
+ if (!session.clearQueue)
2834
+ return empty;
2835
+ try {
2836
+ const cleared = session.clearQueue();
2837
+ return { steering: [...(cleared?.steering ?? [])], followUp: [...(cleared?.followUp ?? [])] };
2838
+ }
2839
+ catch (error) {
2840
+ console.warn(`PiRpcRuntime: clearing the queues of ${conversationId} threw: ${error instanceof Error ? error.message : "unknown error"}`);
2841
+ return empty;
2842
+ }
2843
+ }
2844
+ const run = this.runs.get(conversationId);
2845
+ if (!run || !this.canSteer(conversationId))
2846
+ return empty;
2847
+ // THE ONE-SHOT PATH NEEDS NO CLEAR, and the reason is structural rather than convenient: that path
2848
+ // runs each turn in a short-lived child that is KILLED when the turn ends (`answerOneShot`'s
2849
+ // finally), and the child's queues die with it. A message Pi was holding in that child is gone the
2850
+ // moment the turn is over, so there is nothing to clear and nothing to wait for. Clearing it
2851
+ // anyway would cost a round trip to a child that is about to be killed, on the path between a turn
2852
+ // ending and the next one starting.
2853
+ void run;
2854
+ return empty;
2855
+ }
2856
+ async steer(conversationId, message, images) {
2857
+ // THE SESSION PATH. A steer on a persistent session is a `prompt` with `streamingBehavior:
2858
+ // "steer"` - the same queueing semantics Pi's RPC `steer` command has, expressed the way the SDK
2859
+ // takes it. The session is NOT aborted and NOT given a second writer: the message joins the turn
2860
+ // that is already running, and Pi delivers it at the next turn boundary.
2861
+ //
2862
+ // THE DISPOSITION. The SDK does not answer a steer with a disposition the way the RPC command does,
2863
+ // so it is derived from what the SDK can tell us: a steer accepted while a turn is running is
2864
+ // `queued` (Pi will deliver it at the next boundary), and one accepted with nothing running is
2865
+ // `handled`. The distinction is the one the caller needs: a queued message is still cancellable
2866
+ // and has NOT yet reached the model.
2867
+ if (this.activeTurns.has(conversationId)) {
2868
+ const session = await this.sessionFor(conversationId);
2869
+ const imagePayloads = this.options.uploadsDir && images?.length
2870
+ ? await loadConversationImages(this.options.uploadsDir, conversationId, images)
2871
+ : undefined;
2872
+ try {
2873
+ await session.prompt(message, { ...(imagePayloads?.length ? { images: imagePayloads } : {}), streamingBehavior: "steer" });
2874
+ }
2875
+ catch (error) {
2876
+ throw error instanceof Error ? error : new Error(String(error));
2877
+ }
2878
+ return "queued";
2879
+ }
2880
+ const run = this.runs.get(conversationId);
2881
+ if (!run || !this.canSteer(conversationId))
2882
+ throw new SteerUnavailableError(`会话 ${conversationId} 的 Pi 进程已结束`);
2883
+ const id = `steer_${++this.steerSeq}`;
2884
+ const imagePayloads = this.options.uploadsDir && images?.length
2885
+ ? await loadConversationImages(this.options.uploadsDir, conversationId, images)
2886
+ : undefined;
2887
+ const answer = new Promise((resolve, reject) => {
2888
+ const timer = setTimeout(() => {
2889
+ this.pendingSteers.delete(id);
2890
+ // NOT rolled back to `queued` here, and the distinction matters. The text is already in Pi's
2891
+ // stdin; Pi may well deliver it at the next boundary, and reporting it as never sent would make
2892
+ // the user see a message they can cancel - and then watch the model act on it anyway.
2893
+ reject(new Error(`Pi 在 ${STEER_COMMAND_TIMEOUT_MS}ms 内没有确认这条插队消息,它可能仍会在下一个工具调用结束时送达;请等这一轮结束再看。`));
2894
+ }, STEER_COMMAND_TIMEOUT_MS);
2895
+ timer.unref();
2896
+ this.pendingSteers.set(id, {
2897
+ resolve: (disposition) => { clearTimeout(timer); resolve(disposition); },
2898
+ reject: (error) => { clearTimeout(timer); reject(error); },
2899
+ });
2900
+ });
2901
+ try {
2902
+ run.channel.write({ id, type: "steer", message, ...(imagePayloads?.length ? { images: imagePayloads } : {}) });
2903
+ }
2904
+ catch (error) {
2905
+ // `write` throws when the pipe is already gone. Settle and unregister here rather than letting a
2906
+ // timeout report a broken stdin ten seconds later as an unexplained silence.
2907
+ const pending = this.pendingSteers.get(id);
2908
+ this.pendingSteers.delete(id);
2909
+ pending?.reject(error instanceof Error ? error : new Error(String(error)));
2910
+ }
2911
+ return answer;
2912
+ }
2913
+ /**
2914
+ * Throws away every cached answer about the models Pi offers.
2915
+ *
2916
+ * Called when the model list itself changes - which today means a person added a provider
2917
+ * through the settings window. The caches are three deep and all three have to go: the TTL map
2918
+ * (ten minutes), the in-flight map (a read that is already running would answer with the old
2919
+ * list), and the SDK catalog, which is remembered for the life of the process because it holds
2920
+ * objects that read the auth store and the model store from disk - and those files are exactly
2921
+ * what just changed.
2922
+ */
2923
+ invalidateCatalog() {
2924
+ this.catalogs.clear();
2925
+ this.pendingCatalogs.clear();
2926
+ this.sdkCatalogPromise = undefined;
2927
+ }
2928
+ async oauthProviders() { return (await this.sdkCatalog())?.oauthProviders() ?? []; }
2929
+ async loginOAuth(providerId, interaction) {
2930
+ const catalog = await this.sdkCatalog();
2931
+ if (!catalog)
2932
+ throw new Error("Pi 的供应商登录功能不可用。");
2933
+ await catalog.loginOAuth(providerId, interaction);
2934
+ }
2935
+ async logoutOAuth(providerId) {
2936
+ const catalog = await this.sdkCatalog();
2937
+ if (!catalog)
2938
+ throw new Error("Pi 的供应商登录功能不可用。");
2939
+ await catalog.logoutOAuth(providerId);
2940
+ }
2941
+ /**
2942
+ * Makes every live session stale, so the next turn builds one that knows the current models.
2943
+ *
2944
+ * WHY A COUNTER AND NOT A REBUILD. Rebuilding a session means throwing it away and reading its
2945
+ * transcript back, and a turn may be RUNNING right now. The counter is read by the session pool
2946
+ * as part of the fingerprint, so each session notices at its next acquire - between turns, where
2947
+ * a rebuild is free.
2948
+ */
2949
+ bumpModelEpoch() {
2950
+ this.modelEpoch += 1;
2951
+ }
2952
+ /**
2953
+ * The model/thinking catalog, from Pi, cached.
2954
+ *
2955
+ * Three layers, because a picker opens far more often than Pi can be asked: a TTL cache keyed by
2956
+ * the selection (10 minutes for a good answer, 30 seconds for a failure), an in-flight map so
2957
+ * concurrent callers share one spawn, and - because each read spawns a short-lived Pi that is
2958
+ * killed as soon as it has answered - no long-lived process to keep warm.
2959
+ */
2960
+ async catalog(selection) {
2961
+ const key = catalogKey(selection);
2962
+ const cached = this.catalogs.get(key);
2963
+ const ttl = cached?.value.source === "pi" ? CATALOG_TTL_MS : CATALOG_FAILURE_TTL_MS;
2964
+ if (cached && Date.now() - cached.at < ttl) {
2965
+ if (process.env.SUPER_PI_TRACE_LATENCY === "1")
2966
+ console.warn(`[super-pi latency] catalog key=${key} phase=catalog.cache-hit`);
2967
+ return this.withRealWindows(cached.value);
2968
+ }
2969
+ const inFlight = this.pendingCatalogs.get(key);
2970
+ if (inFlight) {
2971
+ if (process.env.SUPER_PI_TRACE_LATENCY === "1")
2972
+ console.warn(`[super-pi latency] catalog key=${key} phase=catalog.inflight-join`);
2973
+ return inFlight;
2974
+ }
2975
+ if (process.env.SUPER_PI_TRACE_LATENCY === "1")
2976
+ console.warn(`[super-pi latency] catalog key=${key} phase=catalog.read-begin`);
2977
+ const pending = this.readCatalog(selection, key)
2978
+ .then((catalog) => this.withRealWindows(catalog))
2979
+ .finally(() => this.pendingCatalogs.delete(key));
2980
+ this.pendingCatalogs.set(key, pending);
2981
+ return pending;
2982
+ }
2983
+ /**
2984
+ * THE CATALOG, WITH THE WINDOW EACH MODEL REALLY HAS.
2985
+ *
2986
+ * WHY THIS IS HERE AND NOT IN THE READ. There are two ways Super Pi can read the model list: Pi's
2987
+ * SDK hands over whole model objects (window included), while a spawned Pi in RPC mode answers
2988
+ * with a reduced list that has no window on it at all. So whether the reader is shown a model's
2989
+ * window depends on WHICH PATH the machine took - and the path that drops it is the one this
2990
+ * machine takes. The window is filled in here, on the way out, so both paths end up answering the
2991
+ * same way.
2992
+ *
2993
+ * The number is the one a session will really run on, because it comes from the same arbitration
2994
+ * the session's own resolver uses (`model-context-window.ts` explains the rule).
2995
+ */
2996
+ withRealWindows(catalog) {
2997
+ if (!catalog.models.length)
2998
+ return catalog;
2999
+ const filled = withArbitratedWindows(catalog.models, defaultAgentDir());
3000
+ // THE CATALOG ITSELF WHEN NOTHING CHANGED. A cached catalog is handed out by reference, and
3001
+ // a caller that compares two reads of the same cache entry is asking "did the answer change",
3002
+ // not "did the plumbing allocate". `scripts/pi-model-switch.test.mjs` pins this.
3003
+ if (filled.every((model, index) => model === catalog.models[index]))
3004
+ return catalog;
3005
+ return { ...catalog, models: filled };
3006
+ }
3007
+ /**
3008
+ * Reads the model catalog WITHOUT starting a Pi process, and falls back to a spawned Pi only when
3009
+ * the SDK is not available.
3010
+ *
3011
+ * WHY THIS IS THE DEFAULT. The picker used to be answered by starting a `pi --mode rpc` child,
3012
+ * asking it three questions and killing it: a process start, measured at 866ms on a fast machine and
3013
+ * seconds on a slow one. And the cache key is the SELECTED MODEL, so it started again for every model
3014
+ * a person picked - which is why "the picker stays grey for ten seconds" followed choosing a model,
3015
+ * and not only the first time.
3016
+ *
3017
+ * Pi's SDK is the same code Pi's RPC mode is built on, so the answers are the same, and the two are
3018
+ * compared field by field in `scripts/probe-catalog-equivalence.mjs`.
3019
+ */
3020
+ async readCatalog(selection, key) {
3021
+ const unavailable = (error) => {
3022
+ console.warn(`PiRpcRuntime: catalog for ${key} could not be read: ${error}`);
3023
+ return { source: "unavailable", models: [], levels: [], fetchedAt: new Date().toISOString(), error };
3024
+ };
3025
+ // AN EXPLICITLY NAMED PI IS THE ONE THAT WILL RUN THE CONVERSATION, SO IT IS THE ONE THAT GETS
3026
+ // ASKED. Naming a Pi is a statement about which Pi runs a turn, and the model list a person sees
3027
+ // has to be THAT Pi's list - otherwise the picker offers a model that no turn could ever use, and a
3028
+ // test harness driving its own Pi is refused models its Pi actually has.
3029
+ //
3030
+ // The SDK's list is the right answer only when the SDK IS the thing that will run the conversation,
3031
+ // which is the ordinary case: Super Pi depends on that package, so the SDK and the conversation
3032
+ // are the same Pi. It is the wrong answer the moment something else is - and then that something
3033
+ // else is asked, at the cost this change was made to remove.
3034
+ // NOT `this.pi.found &&`: a NAMED command that does not exist is still a named command, and the
3035
+ // honest answer to "this Pi cannot be asked" is still "unavailable" rather than a list from some
3036
+ // other Pi. `found: false` is exactly the case that must NOT be answered from elsewhere.
3037
+ const namedPiIsInCharge = this.pi.explicit === true || this.sessionMode === "oneshot";
3038
+ if (namedPiIsInCharge) {
3039
+ if (process.env.SUPER_PI_TRACE_LATENCY === "1")
3040
+ console.warn(`[super-pi latency] catalog key=${key} phase=catalog.asks-named-pi explicit=${this.pi.explicit ?? "not-found"} mode=${this.sessionMode}`);
3041
+ return this.readCatalogBySpawningPi(selection, key, unavailable);
3042
+ }
3043
+ const sdkRead = await this.readCatalogFromSdk(selection, unavailable);
3044
+ if (sdkRead) {
3045
+ this.catalogs.set(key, { at: Date.now(), value: sdkRead });
3046
+ return sdkRead;
3047
+ }
3048
+ return this.readCatalogBySpawningPi(selection, key, unavailable);
3049
+ }
3050
+ /**
3051
+ * The transcript file for a conversation, out of Pi's SDK, or undefined when the SDK cannot answer.
3052
+ *
3053
+ * Undefined means "ask someone else", not "no such file": a missing SDK and a missing transcript
3054
+ * are different facts, and only the first one should send the caller to the spawning path.
3055
+ *
3056
+ * For the same reason as the catalog, a NAMED Pi is not asked here: when something else will run the
3057
+ * conversation, it is also the only one that knows which file that conversation's transcript is in.
3058
+ */
3059
+ async resolveTranscriptFileWithoutSpawn(cwd, conversationId) {
3060
+ if (!this.pi.found || this.pi.explicit || this.sessionMode === "oneshot")
3061
+ return undefined;
3062
+ const support = await this.sessionSupport();
3063
+ if (!support.available)
3064
+ return undefined;
3065
+ try {
3066
+ return await resolveTranscriptFile(cwd, conversationId, this.sessionDir);
3067
+ }
3068
+ catch (error) {
3069
+ console.warn(`PiRpcRuntime: Pi's SDK could not locate the transcript of ${conversationId}: ${error instanceof Error ? error.message : String(error)}. Falling back to asking a Pi process, which is slower but the same answer.`);
3070
+ return undefined;
3071
+ }
3072
+ }
3073
+ async sdkCatalog() {
3074
+ if (!this.sdkCatalogPromise) {
3075
+ this.sdkCatalogPromise = createSdkCatalog(this.repositoryRoot).catch((error) => {
3076
+ console.warn(`PiRpcRuntime: Pi's SDK could not be used for the catalog: ${error instanceof Error ? error.message : String(error)}`);
3077
+ return undefined;
3078
+ });
3079
+ }
3080
+ return this.sdkCatalogPromise;
3081
+ }
3082
+ /**
3083
+ * The catalog, out of Pi's SDK. Returns undefined when the SDK is not available, which is the only
3084
+ * case in which the spawning path is reached.
3085
+ */
3086
+ async readCatalogFromSdk(selection, unavailable) {
3087
+ const support = await this.sessionSupport();
3088
+ if (!support.available)
3089
+ return undefined;
3090
+ try {
3091
+ const reader = await this.sdkCatalog();
3092
+ if (!reader)
3093
+ return undefined;
3094
+ const models = describeModels(reader.models);
3095
+ if (!models.length)
3096
+ return unavailable("Pi's SDK reported no usable models");
3097
+ const pick = (model) => (model ? { provider: model.provider, modelId: model.modelId, label: model.label } : undefined);
3098
+ // Unknown levels do not invalidate the SDK model list or imply an external Pi.
3099
+ // Keep the catalog usable without spawning a process or borrowing another model's levels.
3100
+ //
3101
+ // THE MODEL IN FORCE IS PI'S ANSWER. With no selection the conversation runs on the model Pi
3102
+ // resolved for itself - not on the pair Pi's settings happen to name, which may be missing,
3103
+ // stale, or unauthenticated. Asking for THAT model's levels is what puts a real list on screen
3104
+ // instead of an empty one.
3105
+ const forModel = selection ?? reader.defaultModel;
3106
+ const thinking = forModel ? await reader.thinkingLevelsFor(forModel) : undefined;
3107
+ const levelNames = thinking?.levels ?? [];
3108
+ // THE DEFAULT MODEL, TAKEN FROM THE LIST RATHER THAN REBUILT. The list carries Pi's own fields
3109
+ // - the window, the output limit, whether the model reasons - and a pair rebuilt from a
3110
+ // provider and an id would carry none of them.
3111
+ const wanted = reader.defaultModel;
3112
+ const defaultOption = wanted
3113
+ ? models.find((model) => model.provider === wanted.provider && model.modelId === wanted.modelId)
3114
+ ?? describeModel({ provider: wanted.provider, id: wanted.modelId, name: wanted.modelId })
3115
+ : undefined;
3116
+ const value = {
3117
+ source: "pi",
3118
+ models,
3119
+ levels: levelNames,
3120
+ // PI'S OWN VERDICT ON ITS OWN CONFIGURATION. It belongs on the catalog because the catalog is
3121
+ // what the picker shows, and a picker that is missing a provider without saying why is the
3122
+ // hardest kind of missing: Pi rejects a whole models.json over one bad field, so EVERY
3123
+ // custom provider disappears at once and the only explanation is somewhere else entirely.
3124
+ ...(reader.configError?.() ? { configError: reader.configError() } : {}),
3125
+ defaultModel: pick(defaultOption),
3126
+ // THE LEVEL IN FORCE, AS PI RESOLVED IT FOR THIS MODEL. It is already clamped to the level
3127
+ // list above, so the button on screen always names a level the model actually has.
3128
+ defaultThinkingLevel: thinking?.level ?? levelNames[0],
3129
+ fetchedAt: new Date().toISOString(),
3130
+ };
3131
+ return value;
3132
+ }
3133
+ catch (error) {
3134
+ // A failure here is a REASON TO WARN, not a reason to start a process: falling back to the spawn
3135
+ // would put the cost back exactly when the machine is already in trouble.
3136
+ console.warn(`PiRpcRuntime: the SDK catalog read failed, and this catalog will be empty rather than slow: ${error instanceof Error ? error.message : String(error)}`);
3137
+ return unavailable(`Pi's SDK could not answer: ${error instanceof Error ? error.message : String(error)}`);
3138
+ }
3139
+ }
3140
+ /**
3141
+ * Asks one throwaway Pi for its model list, its thinking levels and its own current selection.
3142
+ *
3143
+ * Only reached when Pi's SDK is not available - which is a broken installation, not a normal one.
3144
+ *
3145
+ * The three commands are written back to back and only then awaited, so Pi works on them in
3146
+ * parallel - measured at 394ms for all three, against 714ms for the slowest one alone. A Pi
3147
+ * scoped to one conversation's model needs `set_model` FIRST and alone, because thinking levels are
3148
+ * a property of the selected model, not of Pi's default.
3149
+ */
3150
+ async readCatalogBySpawningPi(selection, key, unavailable) {
3151
+ // Catalog probes get their OWN session directory and a fixed session id: they must never write
3152
+ // into a conversation's transcript, and a fixed id means a refresh reuses one file instead of
3153
+ // leaving a new one behind on every model switch.
3154
+ const directory = join(this.sessionDir, "catalog");
3155
+ await mkdir(directory, { recursive: true });
3156
+ // Same resolution, same refusal, one reason: a picker that cannot be filled because Pi is not
3157
+ // installed must say so in the picker's own error, not report the spawn's ENOENT as Pi's answer.
3158
+ if (!this.pi.found)
3159
+ return unavailable(this.pi.reason);
3160
+ let child;
3161
+ try {
3162
+ child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--no-tools", "--no-extensions", "--no-mcp", "--no-skills", "--no-context-files", "--no-prompt-templates", "--session-dir", directory, "--session-id", "catalog"], { cwd: directory, stdio: ["pipe", "pipe", "pipe"], shell: process.platform === "win32" });
3163
+ if (process.env.SUPER_PI_TRACE_LATENCY === "1")
3164
+ console.warn(`[super-pi latency] catalog key=${key} phase=catalog.spawned pid=${child.pid ?? "unknown"}`);
3165
+ }
3166
+ catch (error) {
3167
+ return unavailable(`could not spawn Pi: ${error instanceof Error ? error.message : "unknown error"}`);
3168
+ }
3169
+ try {
3170
+ const channel = new RpcChannel(child);
3171
+ if (selection?.provider && selection.modelId) {
3172
+ const applied = await channel.request({ id: "catalog_set_model", type: "set_model", provider: selection.provider, modelId: selection.modelId }, CATALOG_COMMAND_TIMEOUT_MS);
3173
+ // A MODEL PI NO LONGER OFFERS IS NOT A REASON TO FAIL THE READ. `set_model` only scopes the
3174
+ // level list to the model in force; the MODEL LIST itself is what the picker needs, and it
3175
+ // does not depend on the selection. Throwing here made a removed model - the model a person
3176
+ // is most likely to have just deleted - produce an empty picker with "Model not found" as
3177
+ // the only explanation. Pi keeps its current model when `set_model` is rejected, so the
3178
+ // levels below are the levels of the model that actually runs.
3179
+ if (applied.success === false) {
3180
+ console.warn(`PiRpcRuntime: catalog for ${key} could not select ${selection.provider}/${selection.modelId} (${applied.error ?? "unknown error"}); listing the models without it`);
3181
+ }
3182
+ }
3183
+ channel.write({ id: "catalog_models", type: "get_available_models" });
3184
+ channel.write({ id: "catalog_levels", type: "get_available_thinking_levels" });
3185
+ channel.write({ id: "catalog_state", type: "get_state" });
3186
+ const models = await channel.waitFor("catalog_models", CATALOG_COMMAND_TIMEOUT_MS, "get_available_models");
3187
+ const levels = await channel.waitFor("catalog_levels", CATALOG_COMMAND_TIMEOUT_MS, "get_available_thinking_levels");
3188
+ const state = await channel.waitFor("catalog_state", CATALOG_COMMAND_TIMEOUT_MS, "get_state");
3189
+ if (models.success === false)
3190
+ throw new Error(models.error ?? "Pi rejected get_available_models");
3191
+ if (levels.success === false)
3192
+ throw new Error(levels.error ?? "Pi rejected get_available_thinking_levels");
3193
+ const options = describeModels(models.data?.models);
3194
+ const levelNames = textList(levels.data?.levels) ?? [];
3195
+ const current = describeModel(state.data?.model);
3196
+ // Narrowed to the three fields ModelSelection declares, because a default is only ever read back
3197
+ // as a button label - the per-model capability fields belong to the list entries, not here.
3198
+ const pick = (model) => (model ? { provider: model.provider, modelId: model.modelId, label: model.label } : undefined);
3199
+ const value = {
3200
+ source: "pi",
3201
+ models: options,
3202
+ levels: levelNames,
3203
+ // Only get_state identifies Pi's default. Catalog order must never invent a default.
3204
+ defaultModel: pick(current),
3205
+ defaultThinkingLevel: text(state.data?.thinkingLevel) ?? levelNames[0],
3206
+ fetchedAt: new Date().toISOString(),
3207
+ };
3208
+ if (!value.models.length)
3209
+ return unavailable(`Pi returned no usable models: ${JSON.stringify(models.data?.models)?.slice(0, 200)}`);
3210
+ this.catalogs.set(key, { at: Date.now(), value });
3211
+ return value;
3212
+ }
3213
+ catch (error) {
3214
+ const message = error instanceof Error ? error.message : "unknown error";
3215
+ const failed = unavailable(message);
3216
+ this.catalogs.set(key, { at: Date.now(), value: failed });
3217
+ return failed;
3218
+ }
3219
+ finally {
3220
+ // Same rule as answer(): the child is not gone until it is actually gone, because a process
3221
+ // still tearing down still holds a lock on this directory.
3222
+ //
3223
+ // THE 5s BACKSTOP IS NOT OPTIONAL, and the same one already appears twice in this file. The kill
3224
+ // happens first and the `exit` subscription second, so an `exit` that fires in that window is
3225
+ // emitted to nobody and dropped by the EventEmitter - `exitCode` is then updated, but the promise
3226
+ // below never settles. Without the timer that hangs the whole catalog read, so `catalog()` never
3227
+ // returns, so the `workspace.settings` handler never reaches its persist: the 保存 dialog closes
3228
+ // and the setting is silently lost, with no error frame and nothing in the server log. Observed
3229
+ // under load in scripts/workspace-settings-browser.test.mjs, which timed out at 60s with an
3230
+ // accepted command, an empty error channel and an untouched state.json.
3231
+ if (child.exitCode === null && child.pid !== undefined) {
3232
+ const killedAt = performance.now();
3233
+ if (process.env.SUPER_PI_TRACE_LATENCY === "1")
3234
+ console.warn(`[super-pi latency] catalog key=${key} phase=catalog.kill.begin pid=${child.pid}`);
3235
+ if (!child.killed) {
3236
+ if (process.platform === "win32")
3237
+ await killTree(child.pid);
3238
+ else
3239
+ child.kill();
3240
+ }
3241
+ if (child.exitCode === null)
3242
+ await new Promise((resolve) => { child.once("exit", resolve); setTimeout(resolve, 5000); });
3243
+ if (process.env.SUPER_PI_TRACE_LATENCY === "1")
3244
+ console.warn(`[super-pi latency] catalog key=${key} phase=catalog.kill.end elapsedMs=${Math.round(performance.now() - killedAt)}`);
3245
+ }
3246
+ }
3247
+ }
3248
+ }
3249
+ /**
3250
+ * Normalizes Pi's `Model[]`, keeping only entries that can actually be sent back as a `set_model`.
3251
+ * Exported so the mapping is testable without a Pi process.
3252
+ *
3253
+ * `imageInput` reads Pi's `input` array, which is where image support is actually declared -
3254
+ * `BaseModel.input: ("text" | "image")[]` at packages/ai/src/types.ts:1124, and Pi's own CLI prints
3255
+ * the very same test as its "images" column (cli/list-models.ts:71, `m.input.includes("image")`).
3256
+ * Copying Pi's predicate rather than inventing one is the point: if Pi ever renames the value or
3257
+ * adds a third modality, Pi's column and this badge change together.
3258
+ *
3259
+ * A MISSING OR MALFORMED `input` READS AS FALSE, and that direction is deliberate. The field's
3260
+ * failure mode is a silent one in both directions - Pi's RPC reader does no schema validation
3261
+ * (rpc-mode.ts:750-783) - so a model with no `input` at all could be a Pi too old to have the
3262
+ * concept, and answering "supports images" for it would invite a picture the model cannot see.
3263
+ * Announcing a capability that turns out to be absent costs the user a confusing turn; declining to
3264
+ * announce one that is present costs them an unlabelled model. Only the first is worth guessing on.
3265
+ */
3266
+ export function describeModel(value) {
3267
+ if (!value || typeof value !== "object")
3268
+ return undefined;
3269
+ const model = value;
3270
+ if (typeof model.provider !== "string" || model.provider === "" || typeof model.id !== "string" || model.id === "")
3271
+ return undefined;
3272
+ const label = typeof model.name === "string" && model.name !== "" ? model.name : model.id;
3273
+ // Anything that is not an array of strings is treated as absent rather than searched with
3274
+ // `.includes`, which would throw on a string. Pi's own union makes this unreachable today; the
3275
+ // check is here because this runs against a field read off the wire from a process that does no
3276
+ // validation of its own.
3277
+ const input = Array.isArray(model.input) ? model.input.filter((value) => typeof value === "string") : [];
3278
+ const thinkingLevelMap = readThinkingLevelMap(model.thinkingLevelMap);
3279
+ const thinkingLevels = thinkingLevelMap ? offeredThinkingLevels(thinkingLevelMap) : undefined;
3280
+ return { provider: model.provider, modelId: model.id, label, detail: `${model.provider}/${model.id}`, reasoning: model.reasoning === true, contextWindow: typeof model.contextWindow === "number" ? model.contextWindow : 0, maxTokens: typeof model.maxTokens === "number" ? model.maxTokens : 0, imageInput: input.includes("image"), ...(thinkingLevels ? { thinkingLevels } : {}) };
3281
+ }
3282
+ export function describeModels(value) {
3283
+ if (!Array.isArray(value))
3284
+ return [];
3285
+ return value.map(describeModel).filter((model) => model !== undefined);
3286
+ }