@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,100 @@
1
+ /**
2
+ * Cuts a Pi session file down to the header plus everything up to and including `boundaryEntryId`.
3
+ *
4
+ * ============================ WHAT THIS DESTROYS ============================
5
+ * **Every entry written after the boundary is gone from disk, permanently, and there is no way to
6
+ * reconstruct it from this file.** That includes not only the messages a person can see but also Pi's
7
+ * `tool_call` records, `compaction` summaries, `model_change` and `thinking_level_change` markers, usage
8
+ * accounting, and anything a future Pi version adds. This is the step the whole revert design is built
9
+ * around (research §4.2) and the step that cannot be undone by the application - Super Pi has no undo,
10
+ * and adding one was explicitly left out of scope.
11
+ *
12
+ * It does NOT touch the workspace. No file the agent read or wrote is read, written or reverted here.
13
+ * =============================================================================
14
+ *
15
+ * WHY TRUNCATE RATHER THAN ASK PI. Pi's `SessionManager` is append-only by design
16
+ * (`session-manager.ts:1516-1519`: "Entries cannot be modified or deleted"), and its in-session rewind -
17
+ * `branch()`, `navigateTree()` - is IN-MEMORY ONLY (`:1573-1584`): `_buildIndex()` re-reads the whole
18
+ * file on every `open()` and sets the leaf to the last line unconditionally (`:1103-1122`). Super Pi
19
+ * spawns one Pi per turn and kills it afterwards, so a leaf pointer set in one turn is gone before the
20
+ * next one starts - a "call `branch()` once" solution would look correct for a turn and then silently
21
+ * forget (research §5 pitfall 2). Truncating the file is the only version of this that is a durable state
22
+ * change rather than per-turn bookkeeping that can be skipped exactly once.
23
+ *
24
+ * WHY THE FORMAT IS ASSUMED RATHER THAN GUESSED. The shape this relies on - line 0 is the one and only
25
+ * `type: "session"` header, every other line is one self-contained JSON entry, every entry's `parentId`
26
+ * already appears earlier in the file, no blank lines, and a trailing newline - was measured against
27
+ * real Pi by scripts/probe-revert-session-format.mjs, which also proves the `parentId` property that
28
+ * makes a prefix a VALID session rather than a fragment. That probe is the reason this function may
29
+ * index by line at all; every one of those claims is re-checked here before anything is written, so a
30
+ * Pi that changed the format fails loudly instead of producing a file Pi cannot open.
31
+ *
32
+ * WHY THE WRITE IS TEMP-THEN-RENAME. Pi appends with a bare `appendFileSync`
33
+ * (`session-manager.ts:1187`) and makes no atomicity guarantee of its own. Writing the truncated copy
34
+ * under a different name and renaming it over the original means a reader never observes a half-written
35
+ * file, and a failure before the rename leaves the original untouched.
36
+ *
37
+ * WHY A BACKUP IS KEPT. `.super-pi-revert-backup` is written next to the session file, deliberately not
38
+ * named `*.jsonl` so Pi's own discovery (`readdirSync` filtered on that suffix,
39
+ * `session-manager.ts:1881`) never lists it, and deliberately NOT surfaced anywhere as a feature:
40
+ * Super Pi has no undo and does not pretend to. It exists so that an irreversible, unrecoverable-by-code
41
+ * operation on a person's conversation history is at least recoverable by hand.
42
+ *
43
+ * EXPORTED so it can be tested against a fabricated session file in a temp directory, without Pi and
44
+ * without touching anybody's real transcript.
45
+ */
46
+ export declare function truncateSessionFile(path: string, boundaryEntryId: string, expectedSessionId: string, beforeBoundary?: boolean): Promise<{
47
+ linesKept: number;
48
+ entriesDropped: number;
49
+ }>;
50
+ /**
51
+ * Writes a second Pi session file that begins as an EXACT copy of one, under a different session id.
52
+ *
53
+ * ============================ WHAT THIS DOES TO THE ORIGINAL ============================
54
+ * **Nothing.** The source file is read and never written, never truncated, never renamed. This is the
55
+ * whole difference from `truncateSessionFile`, and it is the reason a fork is the safe half of this pair
56
+ * of operations: a revert destroys entries permanently and keeps a hand-recovery backup, while a fork
57
+ * leaves both files whole and keeps no backup because there is nothing to recover.
58
+ * ========================================================================================
59
+ *
60
+ * WHY A COPY AND NOT PI'S `fork()`. Covered at length on `ClientCommand`'s `conversation.fork`: Pi's fork
61
+ * always tears down the runtime and switches to the new session (`agent-session-runtime.ts:299-307`), and
62
+ * Super Pi has no runtime to switch - it spawns one Pi per turn and kills it. The file is the only durable
63
+ * thing a fork has to produce here, so the file is what gets produced.
64
+ *
65
+ * ============================ WHAT THIS DOES TO PI's ENTRY IDS ============================
66
+ * **Nothing either, and this is a deliberate divergence from Pi's own `createBranchedSession`, which
67
+ * RENUMBERS `parentId` (`:1655-1666`).** Keeping every id verbatim means every cross-reference already
68
+ * inside the file stays valid, and research pitfall 6 is exactly why that matters: a Pi entry may point
69
+ * at other entries by id in ways this code has never enumerated - a `compaction` record carries a
70
+ * `firstKeptEntryId`, `branch_summary` carries the branch point - and renumbering ids means rewriting every
71
+ * one of those references correctly, with no way to find them all. Copying the bytes cannot break a
72
+ * reference because it changes nothing a reference points at. The cost is that the same entry id now
73
+ * exists in two files; that is safe because `_buildIndex` builds its `byId` map per file (`:1103-1122`),
74
+ * and Super Pi only ever opens one file per process.
75
+ *
76
+ * WHAT THE HEADER CHANGES, and it is two fields. `id` becomes the new conversation's id, because that is
77
+ * what Pi's lookup matches (`findLocalSessionByExactId` reads the header, probe B) and therefore what makes
78
+ * `--session-id <forked>` open THIS file rather than silently inventing an empty session with that id
79
+ * (`main.ts:436-448`, measured: `Warning: No project session found with id '...'`). And `parentSession`
80
+ * records the file this one came from, which is the same one-line lineage pointer Pi itself writes
81
+ * (`:1675-1682`) and is not a link - the files share nothing. `cwd`, `version` and `timestamp` are copied
82
+ * verbatim: `cwd` MUST be identical, because Pi's lookup requires the recorded cwd to equal the one it is
83
+ * asked from, and the fork always lives in the same workspace as its source.
84
+ *
85
+ * THE SAME FORMAT CHECKS AS TRUNCATE, AND FOR THE SAME REASON. Probe A measured this file's shape against
86
+ * real Pi (`scripts/probe-revert-session-format.mjs`); a Pi upgrade can invalidate any of those claims, so
87
+ * every one is re-checked before a byte is written and a failure names the shape actually found. Here the
88
+ * `parentId` property is checked across the WHOLE file rather than across a kept prefix, because the whole
89
+ * file is what is being copied.
90
+ *
91
+ * TEMP-THEN-RENAME, because Pi appends with a bare `appendFileSync` (`:1187`) and the target must never be
92
+ * observed half-written - a half-written file under the forked id is precisely the "Pi opens an empty
93
+ * session and the history has vanished with no error anywhere" outcome probe B was about.
94
+ *
95
+ * EXPORTED so it can be tested against fabricated session files in a temp directory, without Pi.
96
+ */
97
+ export declare function forkSessionFile(sourcePath: string, targetPath: string, expectedSessionId: string, targetSessionId: string): Promise<{
98
+ entriesCopied: number;
99
+ inheritedUsageEntryIds?: string[];
100
+ }>;
@@ -0,0 +1,246 @@
1
+ import { readFile, rename, writeFile } from "node:fs/promises";
2
+ /**
3
+ * Cuts a Pi session file down to the header plus everything up to and including `boundaryEntryId`.
4
+ *
5
+ * ============================ WHAT THIS DESTROYS ============================
6
+ * **Every entry written after the boundary is gone from disk, permanently, and there is no way to
7
+ * reconstruct it from this file.** That includes not only the messages a person can see but also Pi's
8
+ * `tool_call` records, `compaction` summaries, `model_change` and `thinking_level_change` markers, usage
9
+ * accounting, and anything a future Pi version adds. This is the step the whole revert design is built
10
+ * around (research §4.2) and the step that cannot be undone by the application - Super Pi has no undo,
11
+ * and adding one was explicitly left out of scope.
12
+ *
13
+ * It does NOT touch the workspace. No file the agent read or wrote is read, written or reverted here.
14
+ * =============================================================================
15
+ *
16
+ * WHY TRUNCATE RATHER THAN ASK PI. Pi's `SessionManager` is append-only by design
17
+ * (`session-manager.ts:1516-1519`: "Entries cannot be modified or deleted"), and its in-session rewind -
18
+ * `branch()`, `navigateTree()` - is IN-MEMORY ONLY (`:1573-1584`): `_buildIndex()` re-reads the whole
19
+ * file on every `open()` and sets the leaf to the last line unconditionally (`:1103-1122`). Super Pi
20
+ * spawns one Pi per turn and kills it afterwards, so a leaf pointer set in one turn is gone before the
21
+ * next one starts - a "call `branch()` once" solution would look correct for a turn and then silently
22
+ * forget (research §5 pitfall 2). Truncating the file is the only version of this that is a durable state
23
+ * change rather than per-turn bookkeeping that can be skipped exactly once.
24
+ *
25
+ * WHY THE FORMAT IS ASSUMED RATHER THAN GUESSED. The shape this relies on - line 0 is the one and only
26
+ * `type: "session"` header, every other line is one self-contained JSON entry, every entry's `parentId`
27
+ * already appears earlier in the file, no blank lines, and a trailing newline - was measured against
28
+ * real Pi by scripts/probe-revert-session-format.mjs, which also proves the `parentId` property that
29
+ * makes a prefix a VALID session rather than a fragment. That probe is the reason this function may
30
+ * index by line at all; every one of those claims is re-checked here before anything is written, so a
31
+ * Pi that changed the format fails loudly instead of producing a file Pi cannot open.
32
+ *
33
+ * WHY THE WRITE IS TEMP-THEN-RENAME. Pi appends with a bare `appendFileSync`
34
+ * (`session-manager.ts:1187`) and makes no atomicity guarantee of its own. Writing the truncated copy
35
+ * under a different name and renaming it over the original means a reader never observes a half-written
36
+ * file, and a failure before the rename leaves the original untouched.
37
+ *
38
+ * WHY A BACKUP IS KEPT. `.super-pi-revert-backup` is written next to the session file, deliberately not
39
+ * named `*.jsonl` so Pi's own discovery (`readdirSync` filtered on that suffix,
40
+ * `session-manager.ts:1881`) never lists it, and deliberately NOT surfaced anywhere as a feature:
41
+ * Super Pi has no undo and does not pretend to. It exists so that an irreversible, unrecoverable-by-code
42
+ * operation on a person's conversation history is at least recoverable by hand.
43
+ *
44
+ * EXPORTED so it can be tested against a fabricated session file in a temp directory, without Pi and
45
+ * without touching anybody's real transcript.
46
+ */
47
+ export async function truncateSessionFile(path, boundaryEntryId, expectedSessionId, beforeBoundary = false) {
48
+ const raw = await readFile(path, "utf8");
49
+ // Split, then drop the empty segment a trailing newline leaves behind. Probe A measured that the file
50
+ // DOES end with a newline, so `split` yields one empty tail element; keeping it would append a blank
51
+ // line to the rewritten file and undo the property the probe just established.
52
+ const lines = raw.split("\n");
53
+ if (lines.at(-1) === "")
54
+ lines.pop();
55
+ if (!lines.length)
56
+ throw new Error(`Pi 的会话文件是空的,拒绝回退:${path}`);
57
+ const parsed = lines.map((line) => {
58
+ try {
59
+ return JSON.parse(line);
60
+ }
61
+ catch {
62
+ return undefined;
63
+ }
64
+ });
65
+ // Every claim probe A made, re-checked here because a Pi upgrade may invalidate any of them. Each
66
+ // failure names the shape that was actually found, because "revert failed" alone sends the reader
67
+ // looking for their own data instead of at the version mismatch that caused it.
68
+ // Checked BEFORE the JSON check, so the refusal names the actual defect: a blank line reads as "this
69
+ // file has a shape my line arithmetic cannot trust", which is what it is, and a bare "not valid JSON"
70
+ // would send the reader looking for a corrupted file instead.
71
+ const blank = lines.findIndex((line) => line.trim() === "");
72
+ if (blank >= 0)
73
+ throw new Error(`Pi 的会话文件第 ${blank} 行是空行,行号与 entry 号不再一一对应,拒绝回退:${path}`);
74
+ const unparseable = parsed.findIndex((entry) => entry === undefined);
75
+ if (unparseable >= 0)
76
+ throw new Error(`Pi 的会话文件第 ${unparseable} 行不是合法 JSON,这个文件的格式已经变了,拒绝回退以免损坏它:${path}`);
77
+ const headerLines = parsed.filter((entry) => entry?.type === "session");
78
+ if (headerLines.length !== 1)
79
+ throw new Error(`Pi 的会话文件里有 ${headerLines.length} 个 header(应为 1 个),格式已经变了,拒绝回退:${path}`);
80
+ if (parsed[0]?.type !== "session")
81
+ throw new Error(`Pi 的会话文件第一行不是 header(实际 type=${JSON.stringify(parsed[0]?.type ?? null)}),格式已经变了,拒绝回退:${path}`);
82
+ if (parsed[0]?.id !== expectedSessionId)
83
+ throw new Error(`Pi 的会话文件属于会话 ${JSON.stringify(parsed[0]?.id ?? null)},不是要回退的会话 ${JSON.stringify(expectedSessionId)}。拒绝截断别人的会话。`);
84
+ if (!raw.endsWith("\n"))
85
+ throw new Error(`Pi 的会话文件末尾没有换行,格式已经变了,拒绝回退:${path}`);
86
+ let boundary = boundaryEntryId === "" ? 0 : parsed.findIndex((entry, index) => index > 0 && entry?.id === boundaryEntryId);
87
+ if (boundary < 0)
88
+ throw new Error(`在这份 Pi 会话记录里找不到要保留的那条消息(entry ${JSON.stringify(boundaryEntryId)})。这条消息可能是更早的版本写的,Super Pi 当时没有记下它对应 Pi 的哪一条。`);
89
+ const expectedLastId = beforeBoundary ? parsed[boundary - 1]?.id : parsed[boundary]?.id;
90
+ if (beforeBoundary)
91
+ boundary -= 1;
92
+ // Fail closed: a boundary of -1 here means "revert to before the FIRST entry", which would write an
93
+ // empty session file. The verification below would pass vacuously (0 !== 0 is false), so the refusal
94
+ // must happen here rather than be trusted to a check that cannot fire.
95
+ if (boundary < 0)
96
+ throw new Error(`回退点在第一条消息之前,截断会得到一个空会话文件,拒绝回退:${path}`);
97
+ // The `parentId` property probe A measured, enforced at the boundary that matters: every entry still
98
+ // being KEPT must point at something also being kept. A prefix that violates this is not a session,
99
+ // and writing it would produce a file Pi either rejects or silently misreads.
100
+ const kept = new Set();
101
+ for (let index = 0; index <= boundary; index += 1) {
102
+ const parent = parsed[index]?.parentId;
103
+ if (parent !== undefined && parent !== null && !kept.has(parent))
104
+ throw new Error(`要保留的部分不是自洽的:第 ${index} 行引用了不在保留范围内的 ${JSON.stringify(parent)},拒绝回退以免产出 Pi 打不开的会话。`);
105
+ kept.add(parsed[index]?.id);
106
+ }
107
+ const rewritten = `${lines.slice(0, boundary + 1).join("\n")}\n`;
108
+ const backupPath = `${path}.super-pi-revert-backup`;
109
+ const temporaryPath = `${path}.super-pi-revert-tmp`;
110
+ await writeFile(backupPath, raw, "utf8");
111
+ await writeFile(temporaryPath, rewritten, "utf8");
112
+ await rename(temporaryPath, path);
113
+ // Re-read rather than trust the write. The claim this whole mechanism rests on is "the file's last
114
+ // line is now the boundary entry", and `_buildIndex` derives the leaf from exactly that line - so if
115
+ // the write did not land, nothing downstream would say so until a turn produced wrong context.
116
+ const verified = (await readFile(path, "utf8")).split("\n").filter((line) => line !== "");
117
+ const last = verified[verified.length - 1];
118
+ let lastEntry;
119
+ try {
120
+ lastEntry = JSON.parse(last);
121
+ }
122
+ catch {
123
+ lastEntry = undefined;
124
+ }
125
+ if (verified.length !== boundary + 1 || lastEntry?.id !== expectedLastId || boundary + 1 < 1) {
126
+ throw new Error(`截断后的 Pi 会话文件没有以要保留的那条消息结尾(写到 ${verified.length} 行,期望 ${boundary + 1} 行,末行 id=${JSON.stringify(lastEntry?.id ?? null)})。原始文件仍在 ${backupPath}。`);
127
+ }
128
+ return { linesKept: boundary + 1, entriesDropped: lines.length - (boundary + 1) };
129
+ }
130
+ /**
131
+ * Writes a second Pi session file that begins as an EXACT copy of one, under a different session id.
132
+ *
133
+ * ============================ WHAT THIS DOES TO THE ORIGINAL ============================
134
+ * **Nothing.** The source file is read and never written, never truncated, never renamed. This is the
135
+ * whole difference from `truncateSessionFile`, and it is the reason a fork is the safe half of this pair
136
+ * of operations: a revert destroys entries permanently and keeps a hand-recovery backup, while a fork
137
+ * leaves both files whole and keeps no backup because there is nothing to recover.
138
+ * ========================================================================================
139
+ *
140
+ * WHY A COPY AND NOT PI'S `fork()`. Covered at length on `ClientCommand`'s `conversation.fork`: Pi's fork
141
+ * always tears down the runtime and switches to the new session (`agent-session-runtime.ts:299-307`), and
142
+ * Super Pi has no runtime to switch - it spawns one Pi per turn and kills it. The file is the only durable
143
+ * thing a fork has to produce here, so the file is what gets produced.
144
+ *
145
+ * ============================ WHAT THIS DOES TO PI's ENTRY IDS ============================
146
+ * **Nothing either, and this is a deliberate divergence from Pi's own `createBranchedSession`, which
147
+ * RENUMBERS `parentId` (`:1655-1666`).** Keeping every id verbatim means every cross-reference already
148
+ * inside the file stays valid, and research pitfall 6 is exactly why that matters: a Pi entry may point
149
+ * at other entries by id in ways this code has never enumerated - a `compaction` record carries a
150
+ * `firstKeptEntryId`, `branch_summary` carries the branch point - and renumbering ids means rewriting every
151
+ * one of those references correctly, with no way to find them all. Copying the bytes cannot break a
152
+ * reference because it changes nothing a reference points at. The cost is that the same entry id now
153
+ * exists in two files; that is safe because `_buildIndex` builds its `byId` map per file (`:1103-1122`),
154
+ * and Super Pi only ever opens one file per process.
155
+ *
156
+ * WHAT THE HEADER CHANGES, and it is two fields. `id` becomes the new conversation's id, because that is
157
+ * what Pi's lookup matches (`findLocalSessionByExactId` reads the header, probe B) and therefore what makes
158
+ * `--session-id <forked>` open THIS file rather than silently inventing an empty session with that id
159
+ * (`main.ts:436-448`, measured: `Warning: No project session found with id '...'`). And `parentSession`
160
+ * records the file this one came from, which is the same one-line lineage pointer Pi itself writes
161
+ * (`:1675-1682`) and is not a link - the files share nothing. `cwd`, `version` and `timestamp` are copied
162
+ * verbatim: `cwd` MUST be identical, because Pi's lookup requires the recorded cwd to equal the one it is
163
+ * asked from, and the fork always lives in the same workspace as its source.
164
+ *
165
+ * THE SAME FORMAT CHECKS AS TRUNCATE, AND FOR THE SAME REASON. Probe A measured this file's shape against
166
+ * real Pi (`scripts/probe-revert-session-format.mjs`); a Pi upgrade can invalidate any of those claims, so
167
+ * every one is re-checked before a byte is written and a failure names the shape actually found. Here the
168
+ * `parentId` property is checked across the WHOLE file rather than across a kept prefix, because the whole
169
+ * file is what is being copied.
170
+ *
171
+ * TEMP-THEN-RENAME, because Pi appends with a bare `appendFileSync` (`:1187`) and the target must never be
172
+ * observed half-written - a half-written file under the forked id is precisely the "Pi opens an empty
173
+ * session and the history has vanished with no error anywhere" outcome probe B was about.
174
+ *
175
+ * EXPORTED so it can be tested against fabricated session files in a temp directory, without Pi.
176
+ */
177
+ export async function forkSessionFile(sourcePath, targetPath, expectedSessionId, targetSessionId) {
178
+ const raw = await readFile(sourcePath, "utf8");
179
+ const lines = raw.split("\n");
180
+ if (lines.at(-1) === "")
181
+ lines.pop();
182
+ if (!lines.length)
183
+ throw new Error(`Pi 的会话文件是空的,拒绝分叉:${sourcePath}`);
184
+ const parsed = lines.map((line) => {
185
+ try {
186
+ return JSON.parse(line);
187
+ }
188
+ catch {
189
+ return undefined;
190
+ }
191
+ });
192
+ // The refusal messages name the shape actually found, and say "拒绝分叉" rather than reusing the revert
193
+ // wording: the reader is looking at a fork button, and a message about 回退 would send them to look for a
194
+ // control they did not press.
195
+ const blank = lines.findIndex((line) => line.trim() === "");
196
+ if (blank >= 0)
197
+ throw new Error(`Pi 的会话文件第 ${blank} 行是空行,无法安全复制,拒绝分叉:${sourcePath}`);
198
+ const unparseable = parsed.findIndex((entry) => entry === undefined);
199
+ if (unparseable >= 0)
200
+ throw new Error(`Pi 的会话文件第 ${unparseable} 行不是合法 JSON,这个文件的格式已经变了,拒绝分叉以免复制出一个 Pi 打不开的会话:${sourcePath}`);
201
+ const headerLines = parsed.filter((entry) => entry?.type === "session");
202
+ if (headerLines.length !== 1)
203
+ throw new Error(`Pi 的会话文件里有 ${headerLines.length} 个 header(应为 1 个),格式已经变了,拒绝分叉:${sourcePath}`);
204
+ if (parsed[0]?.type !== "session")
205
+ throw new Error(`Pi 的会话文件第一行不是 header(实际 type=${JSON.stringify(parsed[0]?.type ?? null)}),格式已经变了,拒绝分叉:${sourcePath}`);
206
+ // The one that matters most. Copying the wrong file would put one person's conversation into another's
207
+ // session, and unlike a wrong truncation it would be written as a brand-new file rather than destroying
208
+ // something - so this check is what stops a fork from being a disclosure.
209
+ if (parsed[0]?.id !== expectedSessionId)
210
+ throw new Error(`Pi 的会话文件属于会话 ${JSON.stringify(parsed[0]?.id ?? null)},不是要分叉的会话 ${JSON.stringify(expectedSessionId)}。拒绝复制别人的会话。`);
211
+ if (!raw.endsWith("\n"))
212
+ throw new Error(`Pi 的会话文件末尾没有换行,格式已经变了,拒绝分叉:${sourcePath}`);
213
+ // Every kept entry must point at another kept entry. The whole file is being copied, so "kept" is all of
214
+ // it - and a file that violates this is not a session Pi can open.
215
+ const known = new Set();
216
+ for (let index = 0; index < parsed.length; index += 1) {
217
+ const parent = parsed[index]?.parentId;
218
+ if (parent !== undefined && parent !== null && !known.has(parent))
219
+ throw new Error(`这个 Pi 会话记录不自洽:第 ${index} 行引用了不存在的 ${JSON.stringify(parent)},拒绝分叉以免复制出一个 Pi 打不开的会话:${sourcePath}`);
220
+ known.add(parsed[index]?.id);
221
+ }
222
+ // The header is REBUILT rather than string-patched, so the two changed fields are structural and
223
+ // everything else - including any field a future Pi adds - is carried across untouched. A regex over the
224
+ // first line would silently drop a field it did not recognise.
225
+ const header = { ...parsed[0], id: targetSessionId, parentSession: sourcePath };
226
+ const rewritten = [JSON.stringify(header), ...lines.slice(1)].join("\n") + "\n";
227
+ const temporaryPath = `${targetPath}.super-pi-fork-tmp`;
228
+ await writeFile(temporaryPath, rewritten, "utf8");
229
+ await rename(temporaryPath, targetPath);
230
+ // Re-read rather than trust the write. The claim this rests on is "a Pi spawned with the new id will
231
+ // open THIS file and find the whole history in it", and nothing downstream would report a failed write -
232
+ // the fork would simply appear to work and the model would start from nothing.
233
+ const verified = (await readFile(targetPath, "utf8")).split("\n").filter((line) => line !== "");
234
+ let verifiedHeader;
235
+ try {
236
+ verifiedHeader = JSON.parse(verified[0]);
237
+ }
238
+ catch {
239
+ verifiedHeader = undefined;
240
+ }
241
+ if (verified.length !== lines.length || verifiedHeader?.id !== targetSessionId) {
242
+ throw new Error(`写入后的 Pi 会话文件不是预期的样子(写到 ${verified.length} 行,期望 ${lines.length} 行,header id=${JSON.stringify(verifiedHeader?.id ?? null)},期望 ${JSON.stringify(targetSessionId)})。已放弃,没有创建任何会话。`);
243
+ }
244
+ const inheritedUsageEntryIds = parsed.flatMap(entry => entry?.type === "usage" && entry.kind === "cache_warm" && typeof entry.id === "string" ? [entry.id] : []);
245
+ return { entriesCopied: lines.length - 1, ...(inheritedUsageEntryIds.length ? { inheritedUsageEntryIds } : {}) };
246
+ }
@@ -0,0 +1,125 @@
1
+ import type { Store } from "./store.js";
2
+ /**
3
+ * THE SESSION TREE'S SCOPE RULE.
4
+ *
5
+ * A session may only manage its DIRECT children: the sessions whose `parentConversationId` is
6
+ * exactly its own id. Nothing else. A grandchild is a level away, a peer sits in somebody else's
7
+ * branch, an ancestor is above - none of them is this session's subordinate, so none of them may be
8
+ * dispatched to, read, stopped or resumed by it. A workspace is NOT an organisation chart: two
9
+ * supervisors can sit in the same workspace without being each other's subordinates.
10
+ *
11
+ * WHY THE RULE IS ONE LINE. The tree edge is written on the conversation itself at birth
12
+ * (`parentConversationId`), so "is this session my child?" is a comparison, not a walk. The walk up
13
+ * the chain exists for ONE purpose only: writing a refusal that says WHY, so the reader knows
14
+ * whether it asked for a peer, a grandchild or somebody else's department. The walk NEVER decides
15
+ * anything - a refusal is a refusal because the parent is not the caller, never because the walk
16
+ * came back empty.
17
+ *
18
+ * WHY THIS MATTERS AT ALL. The result callback of a dispatched session goes back to the session that
19
+ * OWNS it - the one whose id is the target's `parentConversationId`. If a session could dispatch to
20
+ * a session it does not own, that session's result would report to somebody else, and the tree the
21
+ * user sees in the sidebar would stop being the tree the work actually flows through. Making the
22
+ * target's parent be the caller is what keeps "who gave the order is who gets the report" true by
23
+ * construction.
24
+ */
25
+ /** How the caller and the target relate in the session tree. Computed for the MESSAGE only. */
26
+ export type SessionRelation = "self" | "direct-child" | "descendant" | "ancestor" | "peer" | "other-root" | "unrelated";
27
+ /** The outcome of a scope check: allowed, or a refusal with the status code and the reason. */
28
+ export type ScopeVerdict = {
29
+ ok: true;
30
+ } | {
31
+ ok: false;
32
+ status: number;
33
+ error: string;
34
+ };
35
+ /** The verb a refusal is about, so the message reads like the action that was refused. */
36
+ export type ScopeVerb = "调度" | "读取" | "停止" | "恢复" | "列出" | "看护" | "移出";
37
+ /** What the caller was trying to reach: a session to manage, a session's children, or a parent to claim. */
38
+ export type ScopeSubject = "manage" | "list-children" | "declare-parent";
39
+ /** The narrow slice of the store this file needs. */
40
+ type ConversationReader = Pick<Store, "conversation">;
41
+ /**
42
+ * The relation between two sessions, in the tree.
43
+ *
44
+ * READ ONLY. This classifies a pair for the sake of the refusal message; it never grants access.
45
+ */
46
+ export declare const classifySessionRelation: (store: ConversationReader, callerConversationId: string, targetConversationId: string) => SessionRelation;
47
+ /**
48
+ * Writes the refusal for a pair that is not allowed to be reached.
49
+ *
50
+ * The three shapes, because the three failures are different failures:
51
+ * - managing a session -> 「不能调度/读取/停止/恢复会话 X」
52
+ * - listing a session's kids -> 「不能列出会话 X 的下属」
53
+ * - claiming a parent -> 「不能把会话 X 声明为自己的下属」
54
+ */
55
+ export declare const describeScopeRefusal: (options: {
56
+ store: ConversationReader;
57
+ callerConversationId: string;
58
+ targetConversationId: string;
59
+ verb: ScopeVerb;
60
+ subject: ScopeSubject;
61
+ }) => string;
62
+ /**
63
+ * Checks that the caller may manage the target: the target must be the caller's DIRECT child.
64
+ *
65
+ * The workspace check is NOT part of this rule and is NOT removed by it - a conversation has to be
66
+ * in the caller's workspace AND in the caller's own subtree. The workspace refusal comes first
67
+ * because it is the older, coarser boundary, and its message names the two workspaces.
68
+ */
69
+ export declare const verifyDirectChildScope: (options: {
70
+ store: ConversationReader;
71
+ callerConversationId: string;
72
+ targetConversationId: string;
73
+ verb?: ScopeVerb;
74
+ }) => ScopeVerdict;
75
+ /**
76
+ * Checks that the caller may list a parent's children.
77
+ *
78
+ * The rule is EQUALITY, not parenthood: the parent whose children are listed must be the caller
79
+ * itself, so the only sessions on the list are the caller's own direct children. Listing the
80
+ * children of the caller's own child would be listing grandchildren, which is the cross-level reach
81
+ * this whole rule exists to refuse.
82
+ */
83
+ export declare const verifyListParentScope: (options: {
84
+ store: ConversationReader;
85
+ callerConversationId: string;
86
+ requestedParentId?: string;
87
+ }) => ScopeVerdict;
88
+ /**
89
+ * Checks that the caller may REPORT to the target: the target must be the caller's DIRECT PARENT.
90
+ *
91
+ * THE REPORTING LINE IS THE TREE EDGE, READ BACKWARDS. Every other rule in this file asks "may this
92
+ * session manage that one?" - and the answer is always about a session's subordinates. A report is the
93
+ * one message that travels UP, so the rule is inverted: a child reports to the session that owns it,
94
+ * the one whose id is the child's `parentConversationId`, and to nobody else.
95
+ *
96
+ * WHY THE INVERSION IS NOT A LOOPHOLE. A peer is somebody else's child, an ancestor is above the
97
+ * caller's own parent, a grandchild is below the caller, and a session in another workspace is another
98
+ * department. Every one of them would put one branch's news into another branch's inbox, and the inbox
99
+ * is where a parent's NEXT ACTION is decided - so a report that crossed a branch would be a stranger's
100
+ * news steering the wrong supervisor.
101
+ *
102
+ * THE RECIPIENT IS DERIVED, NOT CHOSEN. This check exists for the case where a caller NAMES a
103
+ * recipient at all: the server derives the parent from the tree and this refuses anything else, so a
104
+ * model cannot redirect its own report up or sideways.
105
+ */
106
+ export declare const verifyReportTargetScope: (options: {
107
+ store: ConversationReader;
108
+ callerConversationId: string;
109
+ targetConversationId: string;
110
+ }) => ScopeVerdict;
111
+ /**
112
+ * Checks the parent a new session is created under.
113
+ *
114
+ * The parent edge is written onto the new conversation at birth, and the result callback follows
115
+ * that edge home. A caller that names somebody ELSE as the parent would therefore rewrite that
116
+ * session's reporting line - putting the victim's result into the caller's inbox - so the parent
117
+ * must be the caller. An empty parent means a top-level session, which is what the user's own "+"
118
+ * creates and what a session with no owner legitimately is.
119
+ */
120
+ export declare const verifySpawnParentScope: (options: {
121
+ store: ConversationReader;
122
+ callerConversationId: string;
123
+ requestedParentId?: string;
124
+ }) => ScopeVerdict;
125
+ export {};