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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (370) hide show
  1. package/README.md +248 -3
  2. package/agents/code-auditor.md +64 -0
  3. package/agents/code-designer.md +64 -0
  4. package/agents/coder.md +24 -0
  5. package/agents/critic.md +24 -0
  6. package/agents/document-organizer.md +48 -0
  7. package/agents/patcher.md +27 -0
  8. package/agents/planner.md +30 -0
  9. package/agents/project-leader.md +28 -0
  10. package/agents/reviewer.md +27 -0
  11. package/agents/scout.md +27 -0
  12. package/agents/solution-designer.md +62 -0
  13. package/agents/super-pi-documents/index.ts +92 -0
  14. package/agents/super-pi-feishu/index.ts +88 -0
  15. package/agents/super-pi-knowledge/index.ts +70 -0
  16. package/agents/super-pi-managed-model/index.ts +9 -0
  17. package/agents/super-pi-memory/index.ts +75 -0
  18. package/agents/super-pi-native-tools/index.ts +1 -0
  19. package/agents/super-pi-task/core.ts +2262 -0
  20. package/agents/super-pi-task/index.ts +814 -0
  21. package/agents/super-pi-task/workflow-schema.ts +34 -0
  22. package/agents/super-pi-web/index.ts +32 -0
  23. package/agents/verifier.md +25 -0
  24. package/assets/fonts/LICENSE +92 -0
  25. package/assets/fonts/NotoSansSC-Bold.otf +0 -0
  26. package/assets/fonts/NotoSansSC-Regular.otf +0 -0
  27. package/assets/knowledge-model/README.md +37 -0
  28. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/config.json +31 -0
  29. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/onnx/model_quantized.onnx +0 -0
  30. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/special_tokens_map.json +7 -0
  31. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer.json +21278 -0
  32. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer_config.json +15 -0
  33. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/vocab.txt +21128 -0
  34. package/bin/npm-prefix.d.ts +1 -0
  35. package/bin/npm-prefix.js +10 -0
  36. package/bin/super-pi.js +349 -0
  37. package/dist/client/.super-pi-client-sources.json +82 -0
  38. package/dist/client/assets/CodeMirrorEditor-mi9rGUce.js +2 -0
  39. package/dist/client/assets/GitDiffEditor-CpoDDQrA.css +1 -0
  40. package/dist/client/assets/GitDiffEditor-FQBfGxOY.js +29 -0
  41. package/dist/client/assets/diff-ChtP43wD.js +1 -0
  42. package/dist/client/assets/dist-AW5lyI3I.js +1 -0
  43. package/dist/client/assets/dist-B3-a6uF0.js +7 -0
  44. package/dist/client/assets/dist-BGxkyh6e.js +1 -0
  45. package/dist/client/assets/dist-BJxfd7yb.js +11 -0
  46. package/dist/client/assets/dist-BRVQKlcp.js +1 -0
  47. package/dist/client/assets/dist-BV64A9Ji.js +1 -0
  48. package/dist/client/assets/dist-BXAOrsjq.js +1 -0
  49. package/dist/client/assets/dist-CKF2Jksy.js +1 -0
  50. package/dist/client/assets/dist-CX_Hm4GS.js +1 -0
  51. package/dist/client/assets/dist-Cus6_oaF.js +2 -0
  52. package/dist/client/assets/dist-Cx00EZKR.js +23 -0
  53. package/dist/client/assets/dist-D71y2EI1.js +1 -0
  54. package/dist/client/assets/dist-D978o95T.js +5 -0
  55. package/dist/client/assets/dist-Dc1MBGAG.js +1 -0
  56. package/dist/client/assets/dist-Dds-qLxY.js +9 -0
  57. package/dist/client/assets/dist-DeD9copn.js +1 -0
  58. package/dist/client/assets/dist-DuvGReu-.js +6 -0
  59. package/dist/client/assets/dist-Dvb0SqcK.js +2 -0
  60. package/dist/client/assets/dist-J6XWqRpB.js +3 -0
  61. package/dist/client/assets/dist-QzbOCAU6.js +1 -0
  62. package/dist/client/assets/dist-moiMRpw_.js +1 -0
  63. package/dist/client/assets/dist-scBkrwv-.js +2 -0
  64. package/dist/client/assets/dockerfile-BDePf5PZ.js +1 -0
  65. package/dist/client/assets/index-Cn7hdrDw.js +350 -0
  66. package/dist/client/assets/index-UfzqdECL.css +1 -0
  67. package/dist/client/assets/powershell-D8WpQPaX.js +1 -0
  68. package/dist/client/assets/properties-C357ku5U.js +1 -0
  69. package/dist/client/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  70. package/dist/client/assets/ruby-ChfNwlCY.js +1 -0
  71. package/dist/client/assets/shell-DwuoZtxw.js +1 -0
  72. package/dist/client/assets/swift-DKB6_1j6.js +1 -0
  73. package/dist/client/assets/toml-BPTmHmyx.js +1 -0
  74. package/dist/client/favicon.ico +0 -0
  75. package/dist/client/favicon.png +0 -0
  76. package/dist/client/favicon.svg +10 -0
  77. package/dist/client/index.html +18 -0
  78. package/dist/extension.d.ts +15 -0
  79. package/dist/extension.js +126 -0
  80. package/dist/server/active-memory.d.ts +247 -0
  81. package/dist/server/active-memory.js +669 -0
  82. package/dist/server/agents.d.ts +245 -0
  83. package/dist/server/agents.js +701 -0
  84. package/dist/server/application/catalog-service.d.ts +98 -0
  85. package/dist/server/application/catalog-service.js +245 -0
  86. package/dist/server/application/conversation-service.d.ts +245 -0
  87. package/dist/server/application/conversation-service.js +654 -0
  88. package/dist/server/application/document-service.d.ts +68 -0
  89. package/dist/server/application/document-service.js +120 -0
  90. package/dist/server/application/extension-ui-service.d.ts +44 -0
  91. package/dist/server/application/extension-ui-service.js +135 -0
  92. package/dist/server/application/feishu-service.d.ts +179 -0
  93. package/dist/server/application/feishu-service.js +358 -0
  94. package/dist/server/application/group-chat-service.d.ts +75 -0
  95. package/dist/server/application/group-chat-service.js +953 -0
  96. package/dist/server/application/group-execution.d.ts +15 -0
  97. package/dist/server/application/group-execution.js +77 -0
  98. package/dist/server/application/project-service.d.ts +464 -0
  99. package/dist/server/application/project-service.js +2523 -0
  100. package/dist/server/application/provider-service.d.ts +174 -0
  101. package/dist/server/application/provider-service.js +510 -0
  102. package/dist/server/application/run-service.d.ts +547 -0
  103. package/dist/server/application/run-service.js +2683 -0
  104. package/dist/server/application/scheduled-task-service.d.ts +184 -0
  105. package/dist/server/application/scheduled-task-service.js +391 -0
  106. package/dist/server/application/session-orchestrator-service.d.ts +388 -0
  107. package/dist/server/application/session-orchestrator-service.js +1146 -0
  108. package/dist/server/application/session-reminder-service.d.ts +59 -0
  109. package/dist/server/application/session-reminder-service.js +141 -0
  110. package/dist/server/application/session-watchdog.d.ts +171 -0
  111. package/dist/server/application/session-watchdog.js +284 -0
  112. package/dist/server/application/workspace-service.d.ts +52 -0
  113. package/dist/server/application/workspace-service.js +186 -0
  114. package/dist/server/application/worktree-service.d.ts +13 -0
  115. package/dist/server/application/worktree-service.js +76 -0
  116. package/dist/server/browser-access.d.ts +34 -0
  117. package/dist/server/browser-access.js +89 -0
  118. package/dist/server/capability.d.ts +105 -0
  119. package/dist/server/capability.js +170 -0
  120. package/dist/server/command-handler.d.ts +93 -0
  121. package/dist/server/command-handler.js +540 -0
  122. package/dist/server/content-search.d.ts +16 -0
  123. package/dist/server/content-search.js +235 -0
  124. package/dist/server/conversation-usage.d.ts +22 -0
  125. package/dist/server/conversation-usage.js +43 -0
  126. package/dist/server/documents.d.ts +152 -0
  127. package/dist/server/documents.js +998 -0
  128. package/dist/server/engineering-learning.d.ts +30 -0
  129. package/dist/server/engineering-learning.js +106 -0
  130. package/dist/server/exec-service.d.ts +45 -0
  131. package/dist/server/exec-service.js +167 -0
  132. package/dist/server/explicit-file-open.d.ts +34 -0
  133. package/dist/server/explicit-file-open.js +105 -0
  134. package/dist/server/failure-text.d.ts +18 -0
  135. package/dist/server/failure-text.js +44 -0
  136. package/dist/server/feishu-cli.d.ts +223 -0
  137. package/dist/server/feishu-cli.js +464 -0
  138. package/dist/server/file-changes.d.ts +119 -0
  139. package/dist/server/file-changes.js +280 -0
  140. package/dist/server/file-diff.d.ts +41 -0
  141. package/dist/server/file-diff.js +97 -0
  142. package/dist/server/file-index.d.ts +100 -0
  143. package/dist/server/file-index.js +296 -0
  144. package/dist/server/file-name-index.d.ts +160 -0
  145. package/dist/server/file-name-index.js +411 -0
  146. package/dist/server/files.d.ts +269 -0
  147. package/dist/server/files.js +748 -0
  148. package/dist/server/git.d.ts +245 -0
  149. package/dist/server/git.js +903 -0
  150. package/dist/server/http-server.d.ts +45 -0
  151. package/dist/server/http-server.js +3830 -0
  152. package/dist/server/index.d.ts +1 -0
  153. package/dist/server/index.js +485 -0
  154. package/dist/server/inline-thinking.d.ts +90 -0
  155. package/dist/server/inline-thinking.js +181 -0
  156. package/dist/server/json-comments.d.ts +14 -0
  157. package/dist/server/json-comments.js +71 -0
  158. package/dist/server/knowledge-embedding-worker.d.ts +1 -0
  159. package/dist/server/knowledge-embedding-worker.js +27 -0
  160. package/dist/server/knowledge-vectors.d.ts +150 -0
  161. package/dist/server/knowledge-vectors.js +385 -0
  162. package/dist/server/knowledge.d.ts +273 -0
  163. package/dist/server/knowledge.js +848 -0
  164. package/dist/server/length-continuation.d.ts +83 -0
  165. package/dist/server/length-continuation.js +118 -0
  166. package/dist/server/logging.d.ts +32 -0
  167. package/dist/server/logging.js +185 -0
  168. package/dist/server/managed-http-tunnel.d.ts +6 -0
  169. package/dist/server/managed-http-tunnel.js +85 -0
  170. package/dist/server/managed-http.d.ts +4 -0
  171. package/dist/server/managed-http.js +85 -0
  172. package/dist/server/managed-model-adapter.d.ts +17 -0
  173. package/dist/server/managed-model-adapter.js +75 -0
  174. package/dist/server/managed-model-gateway.d.ts +49 -0
  175. package/dist/server/managed-model-gateway.js +73 -0
  176. package/dist/server/managed-servers.d.ts +55 -0
  177. package/dist/server/managed-servers.js +392 -0
  178. package/dist/server/managed-ssh.d.ts +26 -0
  179. package/dist/server/managed-ssh.js +73 -0
  180. package/dist/server/manager-vault.d.ts +11 -0
  181. package/dist/server/manager-vault.js +67 -0
  182. package/dist/server/memory-recall.d.ts +25 -0
  183. package/dist/server/memory-recall.js +45 -0
  184. package/dist/server/memory.d.ts +67 -0
  185. package/dist/server/memory.js +216 -0
  186. package/dist/server/message-media.d.ts +7 -0
  187. package/dist/server/message-media.js +54 -0
  188. package/dist/server/model-context-window.d.ts +186 -0
  189. package/dist/server/model-context-window.js +444 -0
  190. package/dist/server/model-filter.d.ts +23 -0
  191. package/dist/server/model-filter.js +48 -0
  192. package/dist/server/models-store.d.ts +36 -0
  193. package/dist/server/models-store.js +132 -0
  194. package/dist/server/native-tool-settings.d.ts +25 -0
  195. package/dist/server/native-tool-settings.js +41 -0
  196. package/dist/server/native-tools-extension.d.ts +2 -0
  197. package/dist/server/native-tools-extension.js +39 -0
  198. package/dist/server/native-tools-service.d.ts +39 -0
  199. package/dist/server/native-tools-service.js +240 -0
  200. package/dist/server/persistence/app-state-repository.d.ts +65 -0
  201. package/dist/server/persistence/app-state-repository.js +1 -0
  202. package/dist/server/persistence/json-state-repository.d.ts +14 -0
  203. package/dist/server/persistence/json-state-repository.js +43 -0
  204. package/dist/server/persistence/open-state-store.d.ts +3 -0
  205. package/dist/server/persistence/open-state-store.js +35 -0
  206. package/dist/server/persistence/rename.d.ts +22 -0
  207. package/dist/server/persistence/rename.js +44 -0
  208. package/dist/server/persistence/sqlite-state-repository.d.ts +12 -0
  209. package/dist/server/persistence/sqlite-state-repository.js +264 -0
  210. package/dist/server/pi-command.d.ts +94 -0
  211. package/dist/server/pi-command.js +265 -0
  212. package/dist/server/pi-native.d.ts +12 -0
  213. package/dist/server/pi-native.js +16 -0
  214. package/dist/server/pi-session-events.d.ts +158 -0
  215. package/dist/server/pi-session-events.js +373 -0
  216. package/dist/server/pi-session-pool.d.ts +233 -0
  217. package/dist/server/pi-session-pool.js +382 -0
  218. package/dist/server/pi-session.d.ts +642 -0
  219. package/dist/server/pi-session.js +655 -0
  220. package/dist/server/presentations/schema.d.ts +120 -0
  221. package/dist/server/presentations/schema.js +128 -0
  222. package/dist/server/provider-network.d.ts +16 -0
  223. package/dist/server/provider-network.js +106 -0
  224. package/dist/server/provider-proxy.d.ts +18 -0
  225. package/dist/server/provider-proxy.js +200 -0
  226. package/dist/server/providers.d.ts +333 -0
  227. package/dist/server/providers.js +989 -0
  228. package/dist/server/remote-bootstrap.d.ts +17 -0
  229. package/dist/server/remote-bootstrap.js +119 -0
  230. package/dist/server/rpc-channel.d.ts +131 -0
  231. package/dist/server/rpc-channel.js +135 -0
  232. package/dist/server/runtime.d.ts +1393 -0
  233. package/dist/server/runtime.js +3286 -0
  234. package/dist/server/scheduled-tasks.d.ts +101 -0
  235. package/dist/server/scheduled-tasks.js +138 -0
  236. package/dist/server/server-context.d.ts +119 -0
  237. package/dist/server/server-context.js +1 -0
  238. package/dist/server/session-cwd.d.ts +19 -0
  239. package/dist/server/session-cwd.js +58 -0
  240. package/dist/server/session-ledger.d.ts +67 -0
  241. package/dist/server/session-ledger.js +76 -0
  242. package/dist/server/session-memory-scope.d.ts +4 -0
  243. package/dist/server/session-memory-scope.js +30 -0
  244. package/dist/server/session-repository.d.ts +100 -0
  245. package/dist/server/session-repository.js +246 -0
  246. package/dist/server/session-tree-scope.d.ts +125 -0
  247. package/dist/server/session-tree-scope.js +337 -0
  248. package/dist/server/skills.d.ts +23 -0
  249. package/dist/server/skills.js +190 -0
  250. package/dist/server/store.d.ts +1062 -0
  251. package/dist/server/store.js +3305 -0
  252. package/dist/server/subagent-runs.d.ts +185 -0
  253. package/dist/server/subagent-runs.js +383 -0
  254. package/dist/server/subagents.d.ts +200 -0
  255. package/dist/server/subagents.js +619 -0
  256. package/dist/server/task-tool.d.ts +282 -0
  257. package/dist/server/task-tool.js +507 -0
  258. package/dist/server/tavily.d.ts +32 -0
  259. package/dist/server/tavily.js +136 -0
  260. package/dist/server/team-context.d.ts +12 -0
  261. package/dist/server/team-context.js +180 -0
  262. package/dist/server/terminal.d.ts +163 -0
  263. package/dist/server/terminal.js +557 -0
  264. package/dist/server/thinking-level-discovery.d.ts +38 -0
  265. package/dist/server/thinking-level-discovery.js +183 -0
  266. package/dist/server/time-zone.d.ts +20 -0
  267. package/dist/server/time-zone.js +32 -0
  268. package/dist/server/tool-calls.d.ts +130 -0
  269. package/dist/server/tool-calls.js +341 -0
  270. package/dist/server/tool-llm.d.ts +72 -0
  271. package/dist/server/tool-llm.js +146 -0
  272. package/dist/server/tool-registry.d.ts +129 -0
  273. package/dist/server/tool-registry.js +249 -0
  274. package/dist/server/tool-runner.d.ts +112 -0
  275. package/dist/server/tool-runner.js +306 -0
  276. package/dist/server/turn-failure.d.ts +48 -0
  277. package/dist/server/turn-failure.js +148 -0
  278. package/dist/server/types.d.ts +2315 -0
  279. package/dist/server/types.js +11 -0
  280. package/dist/server/update-status.d.ts +14 -0
  281. package/dist/server/update-status.js +69 -0
  282. package/dist/server/update.d.ts +46 -0
  283. package/dist/server/update.js +104 -0
  284. package/dist/server/upload.d.ts +35 -0
  285. package/dist/server/upload.js +177 -0
  286. package/dist/server/version.d.ts +33 -0
  287. package/dist/server/version.js +111 -0
  288. package/dist/server/web.d.ts +27 -0
  289. package/dist/server/web.js +183 -0
  290. package/dist/server/workflow-engine.d.ts +47 -0
  291. package/dist/server/workflow-engine.js +255 -0
  292. package/dist/server/workflow.d.ts +329 -0
  293. package/dist/server/workflow.js +469 -0
  294. package/dist/server/workspace-file-indexes.d.ts +2 -0
  295. package/dist/server/workspace-file-indexes.js +61 -0
  296. package/dist/server/workspace-file-operations.d.ts +36 -0
  297. package/dist/server/workspace-file-operations.js +281 -0
  298. package/dist/server/workspace-file-response.d.ts +7 -0
  299. package/dist/server/workspace-file-response.js +79 -0
  300. package/dist/server/ws-server.d.ts +149 -0
  301. package/dist/server/ws-server.js +640 -0
  302. package/dist/shared/agent-order.d.ts +44 -0
  303. package/dist/shared/agent-order.js +50 -0
  304. package/dist/shared/archive-decisions.d.ts +44 -0
  305. package/dist/shared/archive-decisions.js +98 -0
  306. package/dist/shared/background-task.d.ts +25 -0
  307. package/dist/shared/background-task.js +183 -0
  308. package/dist/shared/child-session-lock.d.ts +37 -0
  309. package/dist/shared/child-session-lock.js +59 -0
  310. package/dist/shared/content-search.d.ts +22 -0
  311. package/dist/shared/content-search.js +1 -0
  312. package/dist/shared/conversation-title.d.ts +4 -0
  313. package/dist/shared/conversation-title.js +4 -0
  314. package/dist/shared/file-mentions.d.ts +17 -0
  315. package/dist/shared/file-mentions.js +91 -0
  316. package/dist/shared/git-commit.d.ts +11 -0
  317. package/dist/shared/git-commit.js +1 -0
  318. package/dist/shared/git-graph.d.ts +42 -0
  319. package/dist/shared/git-graph.js +30 -0
  320. package/dist/shared/group-chat.d.ts +132 -0
  321. package/dist/shared/group-chat.js +6 -0
  322. package/dist/shared/managed-servers.d.ts +36 -0
  323. package/dist/shared/managed-servers.js +1 -0
  324. package/dist/shared/message-media.d.ts +12 -0
  325. package/dist/shared/message-media.js +27 -0
  326. package/dist/shared/model-window-label.d.ts +39 -0
  327. package/dist/shared/model-window-label.js +55 -0
  328. package/dist/shared/native-tools.d.ts +43 -0
  329. package/dist/shared/native-tools.js +1 -0
  330. package/dist/shared/pi-cache-warming.d.ts +9 -0
  331. package/dist/shared/pi-cache-warming.js +4 -0
  332. package/dist/shared/project-overview.d.ts +107 -0
  333. package/dist/shared/project-overview.js +92 -0
  334. package/dist/shared/project-presentation.d.ts +55 -0
  335. package/dist/shared/project-presentation.js +111 -0
  336. package/dist/shared/provider-network.d.ts +30 -0
  337. package/dist/shared/provider-network.js +1 -0
  338. package/dist/shared/session-reporting.d.ts +40 -0
  339. package/dist/shared/session-reporting.js +97 -0
  340. package/dist/shared/session-search.d.ts +14 -0
  341. package/dist/shared/session-search.js +1 -0
  342. package/dist/shared/team-context-view.d.ts +33 -0
  343. package/dist/shared/team-context-view.js +49 -0
  344. package/dist/shared/team-context.d.ts +59 -0
  345. package/dist/shared/team-context.js +3 -0
  346. package/dist/shared/terminal-protocol.d.ts +71 -0
  347. package/dist/shared/terminal-protocol.js +1 -0
  348. package/dist/shared/thinking-levels.d.ts +53 -0
  349. package/dist/shared/thinking-levels.js +85 -0
  350. package/dist/shared/tool-glyph.d.ts +7 -0
  351. package/dist/shared/tool-glyph.js +19 -0
  352. package/dist/shared/transcript-order.d.ts +7 -0
  353. package/dist/shared/transcript-order.js +12 -0
  354. package/dist/shared/update-status.d.ts +28 -0
  355. package/dist/shared/update-status.js +1 -0
  356. package/dist/shared/workspace-file-preview.d.ts +4 -0
  357. package/dist/shared/workspace-file-preview.js +28 -0
  358. package/package.json +448 -4
  359. package/scripts/diagnose.mjs +603 -0
  360. package/scripts/patch-brace-expansion.mjs +260 -0
  361. package/scripts/restart-server.mjs +104 -0
  362. package/skills/presentation/SKILL.md +30 -0
  363. package/skills/presentation/references/data.md +10 -0
  364. package/skills/presentation/references/quality.md +12 -0
  365. package/skills/presentation/references/story.md +12 -0
  366. package/skills/presentation/references/templates-and-editing.md +11 -0
  367. package/skills/presentation/references/visual-system.md +10 -0
  368. package/skills/super-pi-agent-development/SKILL.md +25 -0
  369. package/skills/super-pi-development/SKILL.md +31 -0
  370. package/skills/super-pi-tool-development/SKILL.md +39 -0
@@ -0,0 +1,654 @@
1
+ import { assertModelAllowed } from "../model-filter.js";
2
+ import { newConversationId } from "../store.js";
3
+ import { normalizeSessionCwd, resolveSessionCwd } from "../session-cwd.js";
4
+ import { isChildSession } from "../../shared/child-session-lock.js";
5
+ import { dismissArchivedOwnerDecisions } from "../../shared/archive-decisions.js";
6
+ import { rm } from "node:fs/promises";
7
+ import { copyForkUploads, deleteConversationUploads } from "../upload.js";
8
+ function isMissingPrimaryAgent(error, agentId) {
9
+ const message = error instanceof Error ? error.message : String(error);
10
+ const id = JSON.stringify(agentId);
11
+ return message.includes(`Agent ${id} 已失效或不是可用的 primary agent`)
12
+ || message.includes(`Agent ${id} 不存在或不是可用的 primary agent`);
13
+ }
14
+ /**
15
+ * Service managing conversation lifecycle: creation, selection, archiving,
16
+ * model/thinking/agent configuration, message reversion, and session forking.
17
+ */
18
+ export class ConversationService {
19
+ store;
20
+ runtime;
21
+ subagents;
22
+ broadcaster;
23
+ catalogService;
24
+ runService;
25
+ extensionUiService;
26
+ agentsDir;
27
+ uploadsDir;
28
+ /** Conversations whose Pi transcript is being cut RIGHT NOW. Read by the send path, below. */
29
+ // This is a reference count rather than a Set. A revert is claimed at socket arrival and claimed a
30
+ // second time when the service starts the cut. More than one socket can also click revert before the
31
+ // first one finishes. A Set lets the first owner release the entry while the second cut is still
32
+ // running, admitting a send onto a transcript that has not been cut yet.
33
+ reverting = new Map();
34
+ /** Reverts for one conversation must never truncate the same Pi file concurrently. */
35
+ revertOps = new Map();
36
+ /** The memory store, so a revert can undo what that conversation taught it. Set by `setMemory`. */
37
+ memory;
38
+ constructor(store, runtime, subagents, broadcaster, catalogService, runService, extensionUiService, agentsDir, uploadsDir) {
39
+ this.store = store;
40
+ this.runtime = runtime;
41
+ this.subagents = subagents;
42
+ this.broadcaster = broadcaster;
43
+ this.catalogService = catalogService;
44
+ this.runService = runService;
45
+ this.extensionUiService = extensionUiService;
46
+ this.agentsDir = agentsDir;
47
+ this.uploadsDir = uploadsDir;
48
+ }
49
+ setAgentsDir(dir) {
50
+ this.agentsDir = dir;
51
+ }
52
+ isWarmSession(conversationId) {
53
+ return this.store.isWarmSession(conversationId);
54
+ }
55
+ /**
56
+ * Creates a new conversation in a workspace.
57
+ *
58
+ * `parentage` is WHO OPENED THIS CONVERSATION, recorded at birth exactly once: the session
59
+ * tree's edge (`parentConversationId`) and its origin. Only the orchestrator passes it - the "+"
60
+ * button and every other caller create a top-level conversation by omission, which is the same
61
+ * "absence means top level" rule the pre-tree state.json files read under.
62
+ *
63
+ * `separateMemoryTree` says that this conversation is its own working context: it must not
64
+ * inherit the memory tree of the conversation it hangs under. A project leader is the case that
65
+ * needs it - it sits in the user's chat in the sidebar, and it shares nothing of that chat's
66
+ * tree-scoped memories with it.
67
+ */
68
+ async createConversation(workspaceId, parentage, cwd) {
69
+ const workspace = this.store.workspace(workspaceId);
70
+ if (!workspace)
71
+ throw new Error("找不到这个工作区。");
72
+ // Workspace defaults are copied at birth, but Pi's model list can change after the
73
+ // setting was saved (for example when a model is removed from Pi's config). Do not
74
+ // stamp a dead selection onto every new conversation: the scoped catalog probe would
75
+ // fail and leave the model/thinking controls unavailable. A missing or invalid default
76
+ // means "follow Pi's current default" for this newly-created conversation.
77
+ // THE PRECEDENCE AT BIRTH IS WORKSPACE > APP > Pi. The app-wide default is a FALLBACK, not an
78
+ // override: a workspace that has a default of its own keeps it, and only a workspace with none
79
+ // inherits the app-wide one. Both are copied onto the conversation and never consulted again,
80
+ // so changing either default never rewrites an existing conversation.
81
+ const appDefault = this.store.defaultModel();
82
+ let model = workspace.defaultModel ?? appDefault;
83
+ let thinkingLevel = workspace.defaultThinkingLevel;
84
+ // WHY A DEFAULT MODEL CAN BE DROPPED, IN WORDS. The two ways a default does not survive are
85
+ // both real and both the user's problem: Pi may no longer offer the model, and the workspace's
86
+ // model rules may forbid it. Either way the conversation starts on Pi's own default - and the
87
+ // user has to be TOLD, because the alternative is a conversation silently running on a model
88
+ // nobody chose (TEST-062). The note is carried on the conversation and read by the panel.
89
+ let modelNotice;
90
+ const catalog = model || thinkingLevel ? await this.runtime.catalog() : undefined;
91
+ if (catalog?.source === "pi" && model) {
92
+ const option = catalog.models.find(item => item.provider === model?.provider && item.modelId === model?.modelId);
93
+ if (!option) {
94
+ modelNotice = `你设的默认模型 ${model.label ?? `${model.provider}/${model.modelId}`} 现在不在 Pi 的模型列表里了,这个会话改用 Pi 自己的默认模型。`;
95
+ model = undefined;
96
+ thinkingLevel = undefined;
97
+ }
98
+ else {
99
+ model = { provider: option.provider, modelId: option.modelId, label: option.label };
100
+ if (thinkingLevel) {
101
+ const scoped = await this.runtime.catalog(model);
102
+ if (scoped.source === "pi" && !scoped.levels.includes(thinkingLevel))
103
+ thinkingLevel = undefined;
104
+ }
105
+ }
106
+ }
107
+ if (model) {
108
+ // THE MODEL RULES HOLD AT BIRTH, FOR EVERY DEFAULT. The check used to be guarded by
109
+ // `inheritsAppDefault` - that is, it only ran when the model came from the APP-wide default.
110
+ // A workspace with a default of its own skipped the check entirely, so the one default the
111
+ // user had chosen FOR THIS WORKSPACE was the one the workspace's own rules never applied to
112
+ // (TEST-061). The rules say 「this workspace only runs THIS model」; that is a statement about
113
+ // the workspace, so it holds for every model the workspace starts on.
114
+ //
115
+ // An app-wide default belongs to no workspace, so the workspace's model rules are checked HERE,
116
+ // at birth, where the workspace is finally known. A default the rules forbid is not stamped
117
+ // on: the conversation starts on Pi's own default instead, which is the same outcome as a
118
+ // workspace default that pointed at a model Pi no longer offers.
119
+ try {
120
+ assertModelAllowed(this.store.modelFilterRules(), workspace, model);
121
+ }
122
+ catch (error) {
123
+ modelNotice = `你设的默认模型 ${model.label ?? `${model.provider}/${model.modelId}`} 被这个工作区的模型规则拦下了(${String(error instanceof Error ? error.message : error)}),这个会话改用 Pi 自己的默认模型。`;
124
+ model = undefined;
125
+ thinkingLevel = undefined;
126
+ }
127
+ }
128
+ let agentNotice;
129
+ let resolved = { model, thinkingLevel };
130
+ if (workspace.defaultAgentId) {
131
+ try {
132
+ resolved = await this.resolveAgentConfiguration({ id: workspaceId, model, thinkingLevel }, workspace.defaultAgentId, workspaceId);
133
+ }
134
+ catch (error) {
135
+ // Only an absent definition is downgraded. A present agent whose model, thinking level or
136
+ // workspace rules are invalid must still refuse rather than silently dropping its configuration.
137
+ if (!isMissingPrimaryAgent(error, workspace.defaultAgentId))
138
+ throw error;
139
+ agentNotice = `你设的默认 Agent「${workspace.defaultAgentId}」已经不存在了,这个会话改用 Pi 默认 Agent。请在工作区设置里重新选择默认 Agent。`;
140
+ }
141
+ }
142
+ // `null` is intentional here: Store uses it to remove a workspace value that it
143
+ // would otherwise have copied before applying the resolved configuration.
144
+ const sessionCwd = await normalizeSessionCwd(workspace.path, cwd);
145
+ const defaults = { ...resolved, agentId: resolved.agentId ?? null, model: resolved.model ?? null, thinkingLevel: resolved.thinkingLevel ?? null, ...(sessionCwd ? { cwd: sessionCwd } : {}), ...(modelNotice ? { modelNotice } : {}), ...(agentNotice ? { agentNotice } : {}), ...(parentage ? { parentConversationId: parentage.parentConversationId, origin: parentage.origin } : {}), ...(parentage?.separateMemoryTree ? { separateMemoryTree: true } : {}) };
146
+ const created = await this.store.createConversation(workspaceId, defaults);
147
+ this.broadcaster.broadcastState();
148
+ return created.id;
149
+ }
150
+ /**
151
+ * Name a conversation from what was said in it. Returns the title; the CALLER applies it, because the
152
+ * rename is a second command with its own optimistic path and its own failure toast, and a service that
153
+ * renamed as a side effect of being asked for a name would make those two outcomes indistinguishable in
154
+ * a log and in a retry.
155
+ */
156
+ async autoRenameConversation(conversationId) {
157
+ const context = this.store.turnContext(conversationId);
158
+ const conversation = context?.conversation;
159
+ if (!conversation)
160
+ throw new Error("会话不存在");
161
+ if (conversation.archivedAt)
162
+ throw new Error("已归档的会话无法重命名,请先恢复会话");
163
+ const workspace = context.workspace;
164
+ if (!workspace)
165
+ throw new Error("会话所属的工作区不存在");
166
+ if (!this.runtime.summarizeConversation)
167
+ throw new Error("当前没有可用的 Pi 进程,无法生成标题");
168
+ return this.runtime.summarizeConversation(conversation, workspace.path);
169
+ }
170
+ /**
171
+ * THE LOCK STATE OF ONE CONVERSATION'S COMPOSER.
172
+ *
173
+ * "top" - a top-level session: the reader talks to it directly, and always could.
174
+ * "locked" - a child session whose parent is still alive. The reader may not talk to it
175
+ * directly; the reporting line runs upwards, one level at a time.
176
+ * "unlocked" - a child session the reader deliberately opened.
177
+ *
178
+ * THE ORPHAN IS "top". A conversation whose parent was archived and left behind has nobody
179
+ * above it to report to, so there is no reporting line for it to bypass - and locking it would
180
+ * lock a conversation that the rules do not cover.
181
+ *
182
+ * The judgement itself lives in `src/shared/child-session-lock.ts` because the browser draws
183
+ * the very same lock: two implementations of "what is a child session" would eventually
184
+ * disagree, and the two ways to disagree are both bad (a lock the server does not honour, and a
185
+ * refusal the interface never explained).
186
+ */
187
+ childLockState(conversationId) {
188
+ const facts = this.store.childSessionFacts(conversationId);
189
+ if (!isChildSession(facts.parentConversationId, facts.parent))
190
+ return "top";
191
+ return this.store.childLockUnlocked(conversationId) ? "unlocked" : "locked";
192
+ }
193
+ /**
194
+ * Opens (or re-closes) ONE child session's composer.
195
+ *
196
+ * The server owns this state, because the server is what refuses the message. The browser keeps
197
+ * a copy per conversation in localStorage so the choice survives a reload, but that copy is a
198
+ * mirror: the server's answer is the one that decides.
199
+ *
200
+ * Re-locking is a real door, not a one-way street: `unlocked: false` puts the lock back, and a
201
+ * lock that could only be opened would not be a lock.
202
+ */
203
+ async setChildLock(conversationId, unlocked) {
204
+ if (!this.store.conversation(conversationId))
205
+ throw new Error("找不到这个会话。");
206
+ await this.store.setChildLockUnlocked(conversationId, unlocked);
207
+ this.broadcaster.broadcastState();
208
+ }
209
+ /**
210
+ * The model a conversation has selected, or undefined when it follows Pi's default.
211
+ *
212
+ * THIS IS WHAT THE CATALOG'S THINKING LEVELS DEPEND ON. Pi computes the levels from the model
213
+ * itself, so the levels of the model in force are the levels that conversation gets. A catalog read
214
+ * without this is a catalog of whatever Pi would default to.
215
+ */
216
+ modelSelectionFor(conversationId) {
217
+ if (!conversationId)
218
+ return undefined;
219
+ const conversation = this.store.conversation(conversationId);
220
+ return conversation?.model;
221
+ }
222
+ /**
223
+ * Selects a conversation and broadcasts the catalog for that conversation's model.
224
+ */
225
+ async getConversationCatalog(conversationId) {
226
+ const conversation = this.store.conversation(conversationId);
227
+ if (!conversation)
228
+ throw new Error("找不到这个会话。");
229
+ const workspace = this.store.workspaceForConversation(conversationId);
230
+ if (!workspace)
231
+ throw new Error("找不到这个工作区。");
232
+ const catalog = await this.runtime.catalog();
233
+ assertModelAllowed(this.store.modelFilterRules(), workspace, conversation.model ?? catalog.defaultModel);
234
+ return this.catalogService.getCatalog(conversation.model, conversationId);
235
+ }
236
+ async selectConversation(conversationId) {
237
+ this.broadcaster.broadcast({ type: "model.catalog", conversationId, catalog: await this.getConversationCatalog(conversationId) });
238
+ }
239
+ /**
240
+ * Archives a conversation.
241
+ *
242
+ * An archive carries three things: the tree is archived, **the decisions the reader still owes
243
+ * go with it**, and the state is broadcast once.
244
+ *
245
+ * Why they go: the owner session is in the archive => nobody runs that project any more => the
246
+ * decisions it owed the reader are asked of nobody. The reader said it plainly: once the
247
+ * archive is decided, every pending decision is rubbish.
248
+ *
249
+ * A dismissal is a QUALIFICATION, not a deletion: the case stays in `p.escalations`, its
250
+ * `status` becomes `dismissed`, `decision` says why it went, `resolvedAt` says when -
251
+ * searchable, exportable. A supervisor-level case is left alone (that is the team's business),
252
+ * and so is another project's.
253
+ *
254
+ * The order matters: archive first, dismiss second. A refused archive (a running session)
255
+ * must change nothing at all.
256
+ */
257
+ async archiveConversation(conversationId) {
258
+ this.runService.reviewMemoryBoundary(conversationId);
259
+ const archivedIds = this.store.conversationSubtreeIds(conversationId);
260
+ await this.store.archiveConversationTree(conversationId);
261
+ await this.dismissDecisionsOfArchivedOwners(archivedIds);
262
+ this.broadcaster.broadcastState();
263
+ }
264
+ /**
265
+ * Dismisses the pending user-level cases of the projects whose OWNER session was archived.
266
+ * The record stays; only its status changes.
267
+ */
268
+ async dismissDecisionsOfArchivedOwners(conversationIds) {
269
+ if (!conversationIds.length)
270
+ return;
271
+ const projects = this.store.projects();
272
+ const updated = dismissArchivedOwnerDecisions(projects, conversationIds, new Date().toISOString());
273
+ for (const [index, project] of updated.entries()) {
274
+ if (project === projects[index])
275
+ continue;
276
+ await this.store.setProject(project);
277
+ }
278
+ }
279
+ /**
280
+ * Unarchives an archived tree root and every archived descendant. Descendants that are
281
+ * already active need no write; they are already in the live tree this restore rejoins.
282
+ */
283
+ async unarchiveConversation(conversationId) {
284
+ await this.store.unarchiveConversationTree(conversationId);
285
+ this.broadcaster.broadcastState();
286
+ }
287
+ /**
288
+ * Collapses or expands one conversation's subtree in the sidebar's session tree. The state is
289
+ * the store's, server-side; this method only adds the conversation-exists check and the
290
+ * broadcast every other write here performs.
291
+ */
292
+ async setCollapsed(conversationId, collapsed) {
293
+ if (!this.store.conversation(conversationId))
294
+ throw new Error("找不到这个会话。");
295
+ await this.store.setConversationCollapsed(conversationId, collapsed);
296
+ this.broadcaster.broadcastState();
297
+ }
298
+ /**
299
+ * Renames a conversation.
300
+ */
301
+ async renameConversation(conversationId, name) {
302
+ const conversation = this.store.conversation(conversationId);
303
+ if (conversation?.archivedAt)
304
+ throw new Error("已归档的会话无法重命名,请先恢复会话");
305
+ await this.store.renameConversation(conversationId, name);
306
+ this.broadcaster.broadcastState();
307
+ }
308
+ /**
309
+ * Sets the active model on a conversation, validating against Pi's catalog.
310
+ */
311
+ async setModel(conversationId, provider, modelId) {
312
+ const previous = this.store.conversation(conversationId);
313
+ const catalog = await this.runtime.catalog();
314
+ const option = catalog.source === "pi"
315
+ ? catalog.models.find((model) => model.provider === provider && model.modelId === modelId)
316
+ : undefined;
317
+ if (catalog.source === "pi" && !option) {
318
+ throw this.catalogService.notOffered(`模型 ${provider}/${modelId}`, catalog);
319
+ }
320
+ const selection = option
321
+ ? { provider: option.provider, modelId: option.modelId, label: option.label }
322
+ : { provider, modelId, label: modelId };
323
+ const workspace = this.store.workspaceForConversation(conversationId);
324
+ if (!workspace)
325
+ throw new Error("找不到这个工作区。");
326
+ assertModelAllowed(this.store.modelFilterRules(), workspace, selection);
327
+ await this.store.setConversationModel(conversationId, selection);
328
+ const thinking = await this.runtime.catalog(selection);
329
+ if (thinking.source === "pi" && previous?.thinkingLevel && !thinking.levels.includes(previous.thinkingLevel)) {
330
+ await this.store.setConversationThinking(conversationId, undefined);
331
+ }
332
+ this.broadcaster.broadcastState();
333
+ await this.catalogService.broadcastCatalog(selection, conversationId);
334
+ }
335
+ /**
336
+ * Sets the thinking level on a conversation, validating against the model's available levels.
337
+ */
338
+ async setThinking(conversationId, level) {
339
+ const conversation = this.store.conversation(conversationId);
340
+ const catalog = await this.runtime.catalog(conversation?.model);
341
+ if (catalog.source === "pi" && !catalog.levels.includes(level)) {
342
+ throw this.catalogService.notOffered(`思考等级 ${level}`, catalog);
343
+ }
344
+ await this.store.setConversationThinking(conversationId, level);
345
+ this.broadcaster.broadcastState();
346
+ }
347
+ /**
348
+ * Configures or clears the primary agent assigned to a conversation.
349
+ */
350
+ async setAgent(conversationId, agentId) {
351
+ const conversation = this.store.conversation(conversationId);
352
+ if (!conversation)
353
+ throw new Error("找不到这个会话。");
354
+ if (agentId === null) {
355
+ await this.store.setConversationAgent(conversationId, undefined);
356
+ this.broadcaster.broadcastState();
357
+ return;
358
+ }
359
+ const settings = await this.resolveAgentConfiguration(conversation, agentId);
360
+ await this.store.setConversationConfiguration(conversationId, settings);
361
+ this.broadcaster.broadcastState();
362
+ await this.catalogService.broadcastCatalog(this.store.conversation(conversationId)?.model, conversationId);
363
+ }
364
+ /**
365
+ * Resolves the agent's model/thinking defaults against the catalog and the workspace's model rules.
366
+ *
367
+ * `workspaceId` must be passed when `conversation` is a workspace-shaped placeholder (the
368
+ * createConversation path passes `{ id: workspaceId, ... }`), because matching a workspace by a
369
+ * CONVERSATION id would never hit. Real conversations omit it: their workspace is resolved through
370
+ * `workspaceForConversation`, which resolves `conversation.workspaceId` without copying messages.
371
+ */
372
+ async resolveAgentConfiguration(conversation, agentId, workspaceId) {
373
+ const agent = await this.runtime.agentFor?.({ id: conversation.id, agentId });
374
+ if (!agent) {
375
+ const dirsLabel = Array.isArray(this.agentsDir) ? this.agentsDir.join(", ") : this.agentsDir;
376
+ throw new Error(`Agent ${JSON.stringify(agentId)} 不存在或不是可用的 primary agent(目录:${dirsLabel})`);
377
+ }
378
+ let selection = conversation.model;
379
+ if (agent.model) {
380
+ const catalog = await this.runtime.catalog();
381
+ if (catalog.source === "pi" && !catalog.models.some((model) => model.provider === agent.model?.provider && model.modelId === agent.model?.modelId)) {
382
+ throw this.catalogService.notOffered(`Agent ${agent.name} 指定的模型 ${agent.model.provider}/${agent.model.modelId}`, catalog);
383
+ }
384
+ const option = catalog.models.find((model) => model.provider === agent.model?.provider && model.modelId === agent.model?.modelId);
385
+ selection = option
386
+ ? { provider: option.provider, modelId: option.modelId, label: option.label }
387
+ : { provider: agent.model.provider, modelId: agent.model.modelId, label: `${agent.model.provider}/${agent.model.modelId}` };
388
+ }
389
+ if (agent.thinkingLevel) {
390
+ const catalog = await this.runtime.catalog(selection);
391
+ if (catalog.source === "pi" && !catalog.levels.includes(agent.thinkingLevel)) {
392
+ throw this.catalogService.notOffered(`Agent ${agent.name} 指定的思考等级 ${agent.thinkingLevel}`, catalog);
393
+ }
394
+ }
395
+ const workspace = workspaceId
396
+ ? this.store.workspace(workspaceId)
397
+ : this.store.workspaceForConversation(conversation.id);
398
+ if (!workspace)
399
+ throw new Error("找不到这个工作区。");
400
+ assertModelAllowed(this.store.modelFilterRules(), workspace, selection ?? (await this.runtime.catalog()).defaultModel);
401
+ return { agentId: agent.id, model: selection, thinkingLevel: agent.thinkingLevel ?? conversation.thinkingLevel };
402
+ }
403
+ /**
404
+ * Reverts conversation history to a designated message boundary, truncating both
405
+ * Pi's transcript and state.json.
406
+ */
407
+ async revertMessage(conversationId, messageId, withdraw = false) {
408
+ // CLAIMED FOR THE WHOLE CUT, and released in a `finally` however this ends - a revert that threw
409
+ // halfway must not leave the conversation permanently unable to send. The per-conversation lane is
410
+ // separate from the WebSocket command queue: revert may start immediately, but two clicks against
411
+ // the same transcript still run strictly in order.
412
+ return this.serializeRevert(conversationId, async () => {
413
+ this.claimRevert(conversationId);
414
+ try {
415
+ return await this.cutTo(conversationId, messageId, withdraw);
416
+ }
417
+ finally {
418
+ this.releaseRevert(conversationId);
419
+ }
420
+ });
421
+ }
422
+ /**
423
+ * The memory store, injected rather than constructed: `ActiveMemory` is built once in `index.ts` and
424
+ * handed to every holder, and this is the third of those. The rewind reaches memory through here
425
+ * because a revert that only rewound the TRANSCRIPT would leave the app still telling the model what
426
+ * the withdrawn turn said.
427
+ */
428
+ setMemory(memory) {
429
+ this.memory = memory;
430
+ }
431
+ /** Whether a revert is currently cutting this conversation's history. The send path asks. */
432
+ isReverting(conversationId) {
433
+ return (this.reverting.get(conversationId) ?? 0) > 0;
434
+ }
435
+ /**
436
+ * CLAIM THE CUT AT THE MOMENT THE COMMAND ARRIVES, not at the moment it runs.
437
+ *
438
+ * `revertMessage` above takes the claim itself, but it only runs when the command is EXECUTED - and a
439
+ * `message.send` deliberately does not wait for this socket's command queue (ws-server runs it
440
+ * independently, so a follow-up can be admitted while a turn is streaming). So a send arriving in the
441
+ * same tick as a revert used to be handled FIRST, found `isReverting` false because the cut had not
442
+ * started yet, and was admitted onto a transcript the cut was about to remove. The guard existed and
443
+ * still could not see the case it was written for.
444
+ *
445
+ * The claim therefore moves to the arrival edge, and `releaseRevert` below gives it back. The claim is
446
+ * reference-counted: the service owns one count while the cut runs, and the socket owns one until the
447
+ * command finishes. This also remains safe when two browser tabs click revert before either cut ends.
448
+ *
449
+ * The cost is that a revert sitting behind a long queue refuses sends from the moment it ARRIVES
450
+ * rather than from the moment it STARTS. That is the direction to err in: a send admitted during the
451
+ * gap is appended to a history the model still reads in full, and the message the person just withdrew
452
+ * is in its context.
453
+ */
454
+ claimRevert(conversationId) {
455
+ this.reverting.set(conversationId, (this.reverting.get(conversationId) ?? 0) + 1);
456
+ this.runService.holdHistoryCut?.(conversationId);
457
+ }
458
+ /** Give the claim back once the command that took it has finished, however it ended. */
459
+ releaseRevert(conversationId) {
460
+ const count = this.reverting.get(conversationId) ?? 0;
461
+ if (count <= 1)
462
+ this.reverting.delete(conversationId);
463
+ else
464
+ this.reverting.set(conversationId, count - 1);
465
+ this.runService.releaseHistoryCut?.(conversationId);
466
+ }
467
+ /**
468
+ * Serializes destructive transcript cuts for one conversation while keeping different conversations
469
+ * independent. The lane is intentionally local to this service: the socket layer can dispatch a
470
+ * revert without waiting behind unrelated commands, and this lane is the ordering boundary that the
471
+ * Pi file actually requires.
472
+ */
473
+ serializeRevert(conversationId, work) {
474
+ const previous = this.revertOps.get(conversationId) ?? Promise.resolve();
475
+ const next = previous.catch(() => undefined).then(work);
476
+ const lane = next.then(() => undefined, () => undefined);
477
+ this.revertOps.set(conversationId, lane);
478
+ void lane.finally(() => {
479
+ if (this.revertOps.get(conversationId) === lane)
480
+ this.revertOps.delete(conversationId);
481
+ });
482
+ return next;
483
+ }
484
+ async cutTo(conversationId, messageId, withdraw) {
485
+ let plan = this.store.planRevert(conversationId, messageId, withdraw);
486
+ // Revert is already a heavy path (Pi transcript truncation and memory cleanup), but it should not
487
+ // pay for cloning every other conversation merely to obtain these two rows. `turnContext` returns
488
+ // detached copies of exactly this conversation and its workspace and keeps the full-state clone
489
+ // out of the click-to-result path. This matters most when the user has many long historical tabs.
490
+ let context = this.store.turnContext(conversationId);
491
+ let conversation = context?.conversation;
492
+ let workspace = context?.workspace;
493
+ if (!conversation)
494
+ throw new Error("会话不存在");
495
+ if (!workspace)
496
+ throw new Error(`会话所属的工作区 ${conversation.workspaceId} 已不存在,拒绝回退`);
497
+ if (!this.runtime.revert) {
498
+ throw new Error("当前运行时没有 Pi 会话,无法回退消息");
499
+ }
500
+ if (this.runService.isRunning(conversationId)) {
501
+ this.extensionUiService.cancelPendingUi(conversationId, "aborted");
502
+ await this.runService.stopRun(conversationId);
503
+ // The stopping turn may have recorded the user's Pi entry while it drained.
504
+ plan = this.store.planRevert(conversationId, messageId, withdraw);
505
+ context = this.store.turnContext(conversationId);
506
+ conversation = context?.conversation;
507
+ if (!conversation)
508
+ throw new Error("会话不存在");
509
+ }
510
+ for (const runId of plan.doomedRunIds) {
511
+ if (this.subagents.stop(runId)) {
512
+ console.log(`Super Pi: stopped sub-agent run ${runId}, whose turn was reverted away.`);
513
+ }
514
+ }
515
+ const outcome = await this.runtime.revert({
516
+ conversation,
517
+ cwd: await resolveSessionCwd(workspace.path, conversation.cwd),
518
+ boundaryEntryId: plan.boundaryEntryId,
519
+ beforeBoundary: withdraw && Boolean(conversation.messages.find(item => item.id === messageId)?.piEntryId),
520
+ });
521
+ // Capture both facts before Store splices the messages array. `store.conversation()` is a shallow
522
+ // copy, so reading them afterwards would read the already-shortened array and lose both the
523
+ // withdrawn message and the first memory timestamp that has to be removed (TEST-051).
524
+ const firstRemovedAt = conversation.messages[plan.boundaryIndex + (withdraw ? 0 : 1)]?.createdAt;
525
+ const withdrawn = conversation.messages.find(item => item.id === messageId);
526
+ const withdrawnContent = withdrawn ? { content: withdrawn.content, images: withdrawn.images } : undefined;
527
+ const applied = await this.store.revertMessages(conversationId, messageId, withdraw);
528
+ // THE RECALL INDEX MUST SEE THE TRUNCATED TRANSCRIPT. `conversation` above is the DETACHED COPY
529
+ // that `turnContext` took BEFORE the store spliced its live array, so it still holds the withdrawn
530
+ // turns - re-syncing from it would put the text the person just withdrew straight back into the
531
+ // index, which is the exact leak this path exists to close. The store's post-revert conversation is
532
+ // the truth, and this rare destructive path is where one clone of it is the right price.
533
+ this.memory?.syncConversation(this.store.conversation(conversationId) ?? conversation);
534
+ // THE MEMORY HALF OF THE REWIND, and the half that used to be missing. Everything above removes the
535
+ // turn from Pi's file and from state.json; the memory store is a second durable copy of what the turn
536
+ // said, and it is spliced into every later prompt. So the model kept being told about a turn the person
537
+ // had withdrawn - measured by scripts/revert-real-pi.test.mjs, which answers a question about the
538
+ // withdrawn turn correctly only with `SUPER_PI_MEMORY_ENABLED=0`.
539
+ //
540
+ // The cut is the FIRST REMOVED message's timestamp. Revert keeps the boundary; withdraw removes
541
+ // it too, including memory written before its assistant placeholder existed. `revertMessages` has already removed the rest,
542
+ // so this runs on data that is settled and cannot be racing the store's own writes.
543
+ const forgotten = firstRemovedAt ? await this.memory?.forgetAfter(conversationId, firstRemovedAt) ?? 0 : 0;
544
+ // The recall index is a cache of the store's messages, and the store just lost several: left alone it
545
+ // keeps answering the memory extension's searches with the withdrawn turns, so the model is told about
546
+ // history the person reverted away even though the transcript, Pi's file and the memory store all
547
+ // agree it is gone. The store's plan says exactly which message ids were dropped, so exactly those
548
+ // postings leave the index - the surviving conversations of this workspace stay indexed and the next
549
+ // search pays no rebuild.
550
+ this.memory?.removeFromIndex(applied.removedMessageIds);
551
+ console.log(`Super Pi: reverted conversation ${conversationId} to ${applied.boundaryIndex + 1} message(s): ` +
552
+ `${plan.removedMessageIds.length} message(s) and ${applied.doomedRunIds.length} sub-agent run(s) dropped from state.json; ` +
553
+ `Pi's file ${outcome.sessionFile} kept ${outcome.linesKept} line(s) and lost ${outcome.entriesDropped}; ` +
554
+ `${forgotten} memory entr${forgotten === 1 ? "y" : "ies"} withdrawn with the turn.`);
555
+ this.broadcaster.broadcastState();
556
+ return withdraw ? withdrawnContent : undefined;
557
+ }
558
+ /**
559
+ * Forks an existing conversation into a new parallel branch, cloning the Pi session.
560
+ */
561
+ async forkConversation(conversationId, options = {}) {
562
+ const conversation = this.store.conversation(conversationId);
563
+ if (!conversation) {
564
+ return { ok: false, message: "会话不存在" };
565
+ }
566
+ if (conversation.archivedAt && !(conversation.warmSession && options.parentConversationId && !options.warmTitle)) {
567
+ return { ok: false, message: "已归档的会话无法分叉,请先恢复会话" };
568
+ }
569
+ const workspace = this.store.workspaceForConversation(conversationId);
570
+ if (!workspace) {
571
+ return { ok: false, message: `会话所属的工作区 ${conversation.workspaceId} 已不存在,拒绝分叉` };
572
+ }
573
+ if (this.runService.isRunning(conversationId) || ["running", "waiting", "awaiting_background"].includes(conversation.status)) {
574
+ return { ok: false, message: "这个会话还有一轮任务在跑,等它结束(或先停止它)再分叉" };
575
+ }
576
+ if (!this.runtime.fork) {
577
+ return { ok: false, message: "当前运行时没有 Pi 会话,无法分叉(只能复制可见的历史)" };
578
+ }
579
+ let copiedFile;
580
+ let copiedUploads;
581
+ try {
582
+ const warmTitle = options.warmTitle?.trim();
583
+ if (options.warmTitle !== undefined && (!warmTitle || warmTitle.length > 100))
584
+ throw new Error("预热会话名称须为 1–100 个字符");
585
+ if (warmTitle && !conversation.messages.some((message) => message.role === "assistant" && !message.delivery)) {
586
+ throw new Error("预热会话需要已有的对话历史");
587
+ }
588
+ const parent = options.parentConversationId;
589
+ if (parent && !conversation.warmSession && parent !== conversation.parentConversationId)
590
+ throw new Error("只能从同一直属上级下的会话分叉");
591
+ const forkedId = newConversationId();
592
+ const outcome = await this.runtime.fork({ conversation, cwd: await resolveSessionCwd(workspace.path, conversation.cwd), forkedConversationId: forkedId });
593
+ copiedFile = outcome.sessionFile;
594
+ if ((parent || warmTitle) && conversation.messages.some((message) => !message.delivery) && !copiedFile) {
595
+ throw new Error("找不到来源会话的 Pi 记录,无法保留上下文分叉");
596
+ }
597
+ if (this.uploadsDir && (parent || warmTitle)) {
598
+ const images = conversation.messages.filter((message) => !message.delivery).flatMap((message) => message.images ?? []);
599
+ if (images.length) {
600
+ copiedUploads = forkedId;
601
+ await copyForkUploads(this.uploadsDir, conversationId, forkedId, images);
602
+ }
603
+ }
604
+ const latest = this.store.conversation(conversationId);
605
+ if (!latest || latest.updatedAt !== conversation.updatedAt || this.runService.isRunning(conversationId)
606
+ || latest.archivedAt !== conversation.archivedAt || JSON.stringify(latest.messages) !== JSON.stringify(conversation.messages)) {
607
+ throw new Error("来源会话在复制时发生变化,请等当前操作结束后重试");
608
+ }
609
+ const forked = await this.store.forkConversation(conversationId, forkedId, { parentConversationId: parent, warmTitle, piSessionFile: copiedFile, inheritedUsageEntryIds: outcome.inheritedUsageEntryIds });
610
+ copiedFile = undefined;
611
+ copiedUploads = undefined;
612
+ console.log(`Super Pi: forked conversation ${conversation.id} into ${forked.id}: ` +
613
+ `${forked.messages.length} message(s) copied in state.json` +
614
+ `${outcome.sessionFile ? `, ${outcome.entriesCopied} Pi entry/entries copied to ${outcome.sessionFile}` : ", and this conversation had no Pi transcript to copy (no messages)"}.`);
615
+ this.broadcaster.broadcastState();
616
+ return {
617
+ ok: true,
618
+ forkedId: forked.id,
619
+ title: forked.title,
620
+ messagesCopied: forked.messages.length,
621
+ piSessionFile: outcome.sessionFile,
622
+ };
623
+ }
624
+ catch (error) {
625
+ if (copiedFile)
626
+ await rm(copiedFile, { force: true }).catch(() => { });
627
+ if (copiedUploads && this.uploadsDir)
628
+ await deleteConversationUploads(this.uploadsDir, copiedUploads);
629
+ const message = error instanceof Error ? error.message : `分叉失败:${String(error)}`;
630
+ return { ok: false, message };
631
+ }
632
+ }
633
+ /**
634
+ * Cancels pending UI/sub-agent work and clears active memory notes for a conversation about to
635
+ * be permanently destroyed (runs while the conversation is still readable in the store).
636
+ */
637
+ async prepareDestroyConversation(conversationId) {
638
+ this.extensionUiService.cancelPendingUi(conversationId, "aborted");
639
+ for (const run of this.store.snapshot().subagentRuns) {
640
+ if (run.conversationId === conversationId && run.status === "running") {
641
+ this.subagents.stop(run.id);
642
+ }
643
+ }
644
+ await this.memory?.forgetAfter(conversationId, "1970-01-01T00:00:00.000Z");
645
+ }
646
+ /**
647
+ * Removes a destroyed conversation's messages from the recall index and disposes any cached Pi
648
+ * session held in runtime memory.
649
+ */
650
+ async cleanupDestroyedConversation(conversation) {
651
+ this.memory?.removeFromIndex(conversation.messageIds);
652
+ await this.runtime.disposeSessions?.(conversation.id);
653
+ }
654
+ }