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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (370) hide show
  1. package/README.md +250 -3
  2. package/agents/code-auditor.md +64 -0
  3. package/agents/code-designer.md +64 -0
  4. package/agents/coder.md +24 -0
  5. package/agents/critic.md +24 -0
  6. package/agents/document-organizer.md +48 -0
  7. package/agents/patcher.md +27 -0
  8. package/agents/planner.md +30 -0
  9. package/agents/project-leader.md +28 -0
  10. package/agents/reviewer.md +27 -0
  11. package/agents/scout.md +27 -0
  12. package/agents/solution-designer.md +62 -0
  13. package/agents/super-pi-documents/index.ts +92 -0
  14. package/agents/super-pi-feishu/index.ts +88 -0
  15. package/agents/super-pi-knowledge/index.ts +70 -0
  16. package/agents/super-pi-managed-model/index.ts +9 -0
  17. package/agents/super-pi-memory/index.ts +75 -0
  18. package/agents/super-pi-native-tools/index.ts +1 -0
  19. package/agents/super-pi-task/core.ts +2262 -0
  20. package/agents/super-pi-task/index.ts +814 -0
  21. package/agents/super-pi-task/workflow-schema.ts +34 -0
  22. package/agents/super-pi-web/index.ts +32 -0
  23. package/agents/verifier.md +25 -0
  24. package/assets/fonts/LICENSE +92 -0
  25. package/assets/fonts/NotoSansSC-Bold.otf +0 -0
  26. package/assets/fonts/NotoSansSC-Regular.otf +0 -0
  27. package/assets/knowledge-model/README.md +37 -0
  28. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/config.json +31 -0
  29. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/onnx/model_quantized.onnx +0 -0
  30. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/special_tokens_map.json +7 -0
  31. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer.json +21278 -0
  32. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer_config.json +15 -0
  33. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/vocab.txt +21128 -0
  34. package/bin/npm-prefix.d.ts +1 -0
  35. package/bin/npm-prefix.js +10 -0
  36. package/bin/super-pi.js +349 -0
  37. package/dist/client/.super-pi-client-sources.json +82 -0
  38. package/dist/client/assets/CodeMirrorEditor-mi9rGUce.js +2 -0
  39. package/dist/client/assets/GitDiffEditor-CpoDDQrA.css +1 -0
  40. package/dist/client/assets/GitDiffEditor-FQBfGxOY.js +29 -0
  41. package/dist/client/assets/diff-ChtP43wD.js +1 -0
  42. package/dist/client/assets/dist-AW5lyI3I.js +1 -0
  43. package/dist/client/assets/dist-B3-a6uF0.js +7 -0
  44. package/dist/client/assets/dist-BGxkyh6e.js +1 -0
  45. package/dist/client/assets/dist-BJxfd7yb.js +11 -0
  46. package/dist/client/assets/dist-BRVQKlcp.js +1 -0
  47. package/dist/client/assets/dist-BV64A9Ji.js +1 -0
  48. package/dist/client/assets/dist-BXAOrsjq.js +1 -0
  49. package/dist/client/assets/dist-CKF2Jksy.js +1 -0
  50. package/dist/client/assets/dist-CX_Hm4GS.js +1 -0
  51. package/dist/client/assets/dist-Cus6_oaF.js +2 -0
  52. package/dist/client/assets/dist-Cx00EZKR.js +23 -0
  53. package/dist/client/assets/dist-D71y2EI1.js +1 -0
  54. package/dist/client/assets/dist-D978o95T.js +5 -0
  55. package/dist/client/assets/dist-Dc1MBGAG.js +1 -0
  56. package/dist/client/assets/dist-Dds-qLxY.js +9 -0
  57. package/dist/client/assets/dist-DeD9copn.js +1 -0
  58. package/dist/client/assets/dist-DuvGReu-.js +6 -0
  59. package/dist/client/assets/dist-Dvb0SqcK.js +2 -0
  60. package/dist/client/assets/dist-J6XWqRpB.js +3 -0
  61. package/dist/client/assets/dist-QzbOCAU6.js +1 -0
  62. package/dist/client/assets/dist-moiMRpw_.js +1 -0
  63. package/dist/client/assets/dist-scBkrwv-.js +2 -0
  64. package/dist/client/assets/dockerfile-BDePf5PZ.js +1 -0
  65. package/dist/client/assets/index-Cn7hdrDw.js +350 -0
  66. package/dist/client/assets/index-UfzqdECL.css +1 -0
  67. package/dist/client/assets/powershell-D8WpQPaX.js +1 -0
  68. package/dist/client/assets/properties-C357ku5U.js +1 -0
  69. package/dist/client/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  70. package/dist/client/assets/ruby-ChfNwlCY.js +1 -0
  71. package/dist/client/assets/shell-DwuoZtxw.js +1 -0
  72. package/dist/client/assets/swift-DKB6_1j6.js +1 -0
  73. package/dist/client/assets/toml-BPTmHmyx.js +1 -0
  74. package/dist/client/favicon.ico +0 -0
  75. package/dist/client/favicon.png +0 -0
  76. package/dist/client/favicon.svg +10 -0
  77. package/dist/client/index.html +18 -0
  78. package/dist/extension.d.ts +15 -0
  79. package/dist/extension.js +126 -0
  80. package/dist/server/active-memory.d.ts +247 -0
  81. package/dist/server/active-memory.js +669 -0
  82. package/dist/server/agents.d.ts +245 -0
  83. package/dist/server/agents.js +701 -0
  84. package/dist/server/application/catalog-service.d.ts +98 -0
  85. package/dist/server/application/catalog-service.js +245 -0
  86. package/dist/server/application/conversation-service.d.ts +245 -0
  87. package/dist/server/application/conversation-service.js +654 -0
  88. package/dist/server/application/document-service.d.ts +68 -0
  89. package/dist/server/application/document-service.js +120 -0
  90. package/dist/server/application/extension-ui-service.d.ts +44 -0
  91. package/dist/server/application/extension-ui-service.js +135 -0
  92. package/dist/server/application/feishu-service.d.ts +179 -0
  93. package/dist/server/application/feishu-service.js +358 -0
  94. package/dist/server/application/group-chat-service.d.ts +75 -0
  95. package/dist/server/application/group-chat-service.js +953 -0
  96. package/dist/server/application/group-execution.d.ts +15 -0
  97. package/dist/server/application/group-execution.js +77 -0
  98. package/dist/server/application/project-service.d.ts +464 -0
  99. package/dist/server/application/project-service.js +2523 -0
  100. package/dist/server/application/provider-service.d.ts +174 -0
  101. package/dist/server/application/provider-service.js +510 -0
  102. package/dist/server/application/run-service.d.ts +547 -0
  103. package/dist/server/application/run-service.js +2683 -0
  104. package/dist/server/application/scheduled-task-service.d.ts +184 -0
  105. package/dist/server/application/scheduled-task-service.js +391 -0
  106. package/dist/server/application/session-orchestrator-service.d.ts +388 -0
  107. package/dist/server/application/session-orchestrator-service.js +1146 -0
  108. package/dist/server/application/session-reminder-service.d.ts +59 -0
  109. package/dist/server/application/session-reminder-service.js +141 -0
  110. package/dist/server/application/session-watchdog.d.ts +171 -0
  111. package/dist/server/application/session-watchdog.js +284 -0
  112. package/dist/server/application/workspace-service.d.ts +52 -0
  113. package/dist/server/application/workspace-service.js +186 -0
  114. package/dist/server/application/worktree-service.d.ts +13 -0
  115. package/dist/server/application/worktree-service.js +76 -0
  116. package/dist/server/browser-access.d.ts +34 -0
  117. package/dist/server/browser-access.js +89 -0
  118. package/dist/server/capability.d.ts +105 -0
  119. package/dist/server/capability.js +170 -0
  120. package/dist/server/command-handler.d.ts +93 -0
  121. package/dist/server/command-handler.js +540 -0
  122. package/dist/server/content-search.d.ts +16 -0
  123. package/dist/server/content-search.js +235 -0
  124. package/dist/server/conversation-usage.d.ts +22 -0
  125. package/dist/server/conversation-usage.js +43 -0
  126. package/dist/server/documents.d.ts +152 -0
  127. package/dist/server/documents.js +998 -0
  128. package/dist/server/engineering-learning.d.ts +30 -0
  129. package/dist/server/engineering-learning.js +106 -0
  130. package/dist/server/exec-service.d.ts +45 -0
  131. package/dist/server/exec-service.js +167 -0
  132. package/dist/server/explicit-file-open.d.ts +34 -0
  133. package/dist/server/explicit-file-open.js +105 -0
  134. package/dist/server/failure-text.d.ts +18 -0
  135. package/dist/server/failure-text.js +44 -0
  136. package/dist/server/feishu-cli.d.ts +223 -0
  137. package/dist/server/feishu-cli.js +464 -0
  138. package/dist/server/file-changes.d.ts +119 -0
  139. package/dist/server/file-changes.js +280 -0
  140. package/dist/server/file-diff.d.ts +41 -0
  141. package/dist/server/file-diff.js +97 -0
  142. package/dist/server/file-index.d.ts +100 -0
  143. package/dist/server/file-index.js +296 -0
  144. package/dist/server/file-name-index.d.ts +160 -0
  145. package/dist/server/file-name-index.js +411 -0
  146. package/dist/server/files.d.ts +269 -0
  147. package/dist/server/files.js +748 -0
  148. package/dist/server/git.d.ts +245 -0
  149. package/dist/server/git.js +903 -0
  150. package/dist/server/http-server.d.ts +45 -0
  151. package/dist/server/http-server.js +3830 -0
  152. package/dist/server/index.d.ts +1 -0
  153. package/dist/server/index.js +485 -0
  154. package/dist/server/inline-thinking.d.ts +90 -0
  155. package/dist/server/inline-thinking.js +181 -0
  156. package/dist/server/json-comments.d.ts +14 -0
  157. package/dist/server/json-comments.js +71 -0
  158. package/dist/server/knowledge-embedding-worker.d.ts +1 -0
  159. package/dist/server/knowledge-embedding-worker.js +27 -0
  160. package/dist/server/knowledge-vectors.d.ts +150 -0
  161. package/dist/server/knowledge-vectors.js +385 -0
  162. package/dist/server/knowledge.d.ts +273 -0
  163. package/dist/server/knowledge.js +848 -0
  164. package/dist/server/length-continuation.d.ts +83 -0
  165. package/dist/server/length-continuation.js +118 -0
  166. package/dist/server/logging.d.ts +32 -0
  167. package/dist/server/logging.js +185 -0
  168. package/dist/server/managed-http-tunnel.d.ts +6 -0
  169. package/dist/server/managed-http-tunnel.js +85 -0
  170. package/dist/server/managed-http.d.ts +4 -0
  171. package/dist/server/managed-http.js +85 -0
  172. package/dist/server/managed-model-adapter.d.ts +17 -0
  173. package/dist/server/managed-model-adapter.js +75 -0
  174. package/dist/server/managed-model-gateway.d.ts +49 -0
  175. package/dist/server/managed-model-gateway.js +73 -0
  176. package/dist/server/managed-servers.d.ts +55 -0
  177. package/dist/server/managed-servers.js +396 -0
  178. package/dist/server/managed-ssh.d.ts +26 -0
  179. package/dist/server/managed-ssh.js +73 -0
  180. package/dist/server/manager-vault.d.ts +11 -0
  181. package/dist/server/manager-vault.js +67 -0
  182. package/dist/server/memory-recall.d.ts +25 -0
  183. package/dist/server/memory-recall.js +45 -0
  184. package/dist/server/memory.d.ts +67 -0
  185. package/dist/server/memory.js +216 -0
  186. package/dist/server/message-media.d.ts +7 -0
  187. package/dist/server/message-media.js +54 -0
  188. package/dist/server/model-context-window.d.ts +186 -0
  189. package/dist/server/model-context-window.js +444 -0
  190. package/dist/server/model-filter.d.ts +23 -0
  191. package/dist/server/model-filter.js +48 -0
  192. package/dist/server/models-store.d.ts +36 -0
  193. package/dist/server/models-store.js +132 -0
  194. package/dist/server/native-tool-settings.d.ts +25 -0
  195. package/dist/server/native-tool-settings.js +41 -0
  196. package/dist/server/native-tools-extension.d.ts +2 -0
  197. package/dist/server/native-tools-extension.js +39 -0
  198. package/dist/server/native-tools-service.d.ts +39 -0
  199. package/dist/server/native-tools-service.js +240 -0
  200. package/dist/server/persistence/app-state-repository.d.ts +65 -0
  201. package/dist/server/persistence/app-state-repository.js +1 -0
  202. package/dist/server/persistence/json-state-repository.d.ts +14 -0
  203. package/dist/server/persistence/json-state-repository.js +43 -0
  204. package/dist/server/persistence/open-state-store.d.ts +3 -0
  205. package/dist/server/persistence/open-state-store.js +35 -0
  206. package/dist/server/persistence/rename.d.ts +22 -0
  207. package/dist/server/persistence/rename.js +44 -0
  208. package/dist/server/persistence/sqlite-state-repository.d.ts +12 -0
  209. package/dist/server/persistence/sqlite-state-repository.js +264 -0
  210. package/dist/server/pi-command.d.ts +94 -0
  211. package/dist/server/pi-command.js +265 -0
  212. package/dist/server/pi-native.d.ts +12 -0
  213. package/dist/server/pi-native.js +16 -0
  214. package/dist/server/pi-session-events.d.ts +158 -0
  215. package/dist/server/pi-session-events.js +373 -0
  216. package/dist/server/pi-session-pool.d.ts +233 -0
  217. package/dist/server/pi-session-pool.js +382 -0
  218. package/dist/server/pi-session.d.ts +642 -0
  219. package/dist/server/pi-session.js +655 -0
  220. package/dist/server/presentations/schema.d.ts +120 -0
  221. package/dist/server/presentations/schema.js +128 -0
  222. package/dist/server/provider-network.d.ts +16 -0
  223. package/dist/server/provider-network.js +106 -0
  224. package/dist/server/provider-proxy.d.ts +18 -0
  225. package/dist/server/provider-proxy.js +200 -0
  226. package/dist/server/providers.d.ts +333 -0
  227. package/dist/server/providers.js +989 -0
  228. package/dist/server/remote-bootstrap.d.ts +17 -0
  229. package/dist/server/remote-bootstrap.js +119 -0
  230. package/dist/server/rpc-channel.d.ts +131 -0
  231. package/dist/server/rpc-channel.js +135 -0
  232. package/dist/server/runtime.d.ts +1393 -0
  233. package/dist/server/runtime.js +3286 -0
  234. package/dist/server/scheduled-tasks.d.ts +101 -0
  235. package/dist/server/scheduled-tasks.js +138 -0
  236. package/dist/server/server-context.d.ts +119 -0
  237. package/dist/server/server-context.js +1 -0
  238. package/dist/server/session-cwd.d.ts +19 -0
  239. package/dist/server/session-cwd.js +58 -0
  240. package/dist/server/session-ledger.d.ts +67 -0
  241. package/dist/server/session-ledger.js +76 -0
  242. package/dist/server/session-memory-scope.d.ts +4 -0
  243. package/dist/server/session-memory-scope.js +30 -0
  244. package/dist/server/session-repository.d.ts +100 -0
  245. package/dist/server/session-repository.js +246 -0
  246. package/dist/server/session-tree-scope.d.ts +125 -0
  247. package/dist/server/session-tree-scope.js +337 -0
  248. package/dist/server/skills.d.ts +23 -0
  249. package/dist/server/skills.js +190 -0
  250. package/dist/server/store.d.ts +1062 -0
  251. package/dist/server/store.js +3305 -0
  252. package/dist/server/subagent-runs.d.ts +185 -0
  253. package/dist/server/subagent-runs.js +383 -0
  254. package/dist/server/subagents.d.ts +200 -0
  255. package/dist/server/subagents.js +619 -0
  256. package/dist/server/task-tool.d.ts +282 -0
  257. package/dist/server/task-tool.js +507 -0
  258. package/dist/server/tavily.d.ts +32 -0
  259. package/dist/server/tavily.js +136 -0
  260. package/dist/server/team-context.d.ts +12 -0
  261. package/dist/server/team-context.js +180 -0
  262. package/dist/server/terminal.d.ts +163 -0
  263. package/dist/server/terminal.js +557 -0
  264. package/dist/server/thinking-level-discovery.d.ts +38 -0
  265. package/dist/server/thinking-level-discovery.js +183 -0
  266. package/dist/server/time-zone.d.ts +20 -0
  267. package/dist/server/time-zone.js +32 -0
  268. package/dist/server/tool-calls.d.ts +130 -0
  269. package/dist/server/tool-calls.js +341 -0
  270. package/dist/server/tool-llm.d.ts +72 -0
  271. package/dist/server/tool-llm.js +146 -0
  272. package/dist/server/tool-registry.d.ts +129 -0
  273. package/dist/server/tool-registry.js +249 -0
  274. package/dist/server/tool-runner.d.ts +112 -0
  275. package/dist/server/tool-runner.js +306 -0
  276. package/dist/server/turn-failure.d.ts +48 -0
  277. package/dist/server/turn-failure.js +148 -0
  278. package/dist/server/types.d.ts +2315 -0
  279. package/dist/server/types.js +11 -0
  280. package/dist/server/update-status.d.ts +14 -0
  281. package/dist/server/update-status.js +69 -0
  282. package/dist/server/update.d.ts +46 -0
  283. package/dist/server/update.js +104 -0
  284. package/dist/server/upload.d.ts +35 -0
  285. package/dist/server/upload.js +177 -0
  286. package/dist/server/version.d.ts +33 -0
  287. package/dist/server/version.js +111 -0
  288. package/dist/server/web.d.ts +27 -0
  289. package/dist/server/web.js +183 -0
  290. package/dist/server/workflow-engine.d.ts +47 -0
  291. package/dist/server/workflow-engine.js +255 -0
  292. package/dist/server/workflow.d.ts +329 -0
  293. package/dist/server/workflow.js +469 -0
  294. package/dist/server/workspace-file-indexes.d.ts +2 -0
  295. package/dist/server/workspace-file-indexes.js +61 -0
  296. package/dist/server/workspace-file-operations.d.ts +36 -0
  297. package/dist/server/workspace-file-operations.js +281 -0
  298. package/dist/server/workspace-file-response.d.ts +7 -0
  299. package/dist/server/workspace-file-response.js +79 -0
  300. package/dist/server/ws-server.d.ts +149 -0
  301. package/dist/server/ws-server.js +640 -0
  302. package/dist/shared/agent-order.d.ts +44 -0
  303. package/dist/shared/agent-order.js +50 -0
  304. package/dist/shared/archive-decisions.d.ts +44 -0
  305. package/dist/shared/archive-decisions.js +98 -0
  306. package/dist/shared/background-task.d.ts +25 -0
  307. package/dist/shared/background-task.js +183 -0
  308. package/dist/shared/child-session-lock.d.ts +37 -0
  309. package/dist/shared/child-session-lock.js +59 -0
  310. package/dist/shared/content-search.d.ts +22 -0
  311. package/dist/shared/content-search.js +1 -0
  312. package/dist/shared/conversation-title.d.ts +4 -0
  313. package/dist/shared/conversation-title.js +4 -0
  314. package/dist/shared/file-mentions.d.ts +17 -0
  315. package/dist/shared/file-mentions.js +91 -0
  316. package/dist/shared/git-commit.d.ts +11 -0
  317. package/dist/shared/git-commit.js +1 -0
  318. package/dist/shared/git-graph.d.ts +42 -0
  319. package/dist/shared/git-graph.js +30 -0
  320. package/dist/shared/group-chat.d.ts +132 -0
  321. package/dist/shared/group-chat.js +6 -0
  322. package/dist/shared/managed-servers.d.ts +36 -0
  323. package/dist/shared/managed-servers.js +1 -0
  324. package/dist/shared/message-media.d.ts +12 -0
  325. package/dist/shared/message-media.js +27 -0
  326. package/dist/shared/model-window-label.d.ts +39 -0
  327. package/dist/shared/model-window-label.js +55 -0
  328. package/dist/shared/native-tools.d.ts +43 -0
  329. package/dist/shared/native-tools.js +1 -0
  330. package/dist/shared/pi-cache-warming.d.ts +9 -0
  331. package/dist/shared/pi-cache-warming.js +4 -0
  332. package/dist/shared/project-overview.d.ts +107 -0
  333. package/dist/shared/project-overview.js +92 -0
  334. package/dist/shared/project-presentation.d.ts +55 -0
  335. package/dist/shared/project-presentation.js +111 -0
  336. package/dist/shared/provider-network.d.ts +30 -0
  337. package/dist/shared/provider-network.js +1 -0
  338. package/dist/shared/session-reporting.d.ts +40 -0
  339. package/dist/shared/session-reporting.js +97 -0
  340. package/dist/shared/session-search.d.ts +14 -0
  341. package/dist/shared/session-search.js +1 -0
  342. package/dist/shared/team-context-view.d.ts +33 -0
  343. package/dist/shared/team-context-view.js +49 -0
  344. package/dist/shared/team-context.d.ts +59 -0
  345. package/dist/shared/team-context.js +3 -0
  346. package/dist/shared/terminal-protocol.d.ts +71 -0
  347. package/dist/shared/terminal-protocol.js +1 -0
  348. package/dist/shared/thinking-levels.d.ts +53 -0
  349. package/dist/shared/thinking-levels.js +85 -0
  350. package/dist/shared/tool-glyph.d.ts +7 -0
  351. package/dist/shared/tool-glyph.js +19 -0
  352. package/dist/shared/transcript-order.d.ts +7 -0
  353. package/dist/shared/transcript-order.js +12 -0
  354. package/dist/shared/update-status.d.ts +28 -0
  355. package/dist/shared/update-status.js +1 -0
  356. package/dist/shared/workspace-file-preview.d.ts +4 -0
  357. package/dist/shared/workspace-file-preview.js +28 -0
  358. package/package.json +450 -4
  359. package/scripts/diagnose.mjs +603 -0
  360. package/scripts/patch-brace-expansion.mjs +260 -0
  361. package/scripts/restart-server.mjs +104 -0
  362. package/skills/presentation/SKILL.md +30 -0
  363. package/skills/presentation/references/data.md +10 -0
  364. package/skills/presentation/references/quality.md +12 -0
  365. package/skills/presentation/references/story.md +12 -0
  366. package/skills/presentation/references/templates-and-editing.md +11 -0
  367. package/skills/presentation/references/visual-system.md +10 -0
  368. package/skills/super-pi-agent-development/SKILL.md +25 -0
  369. package/skills/super-pi-development/SKILL.md +31 -0
  370. package/skills/super-pi-tool-development/SKILL.md +39 -0
@@ -0,0 +1,1062 @@
1
+ import { type SessionSearchResult } from "../shared/session-search.js";
2
+ import type { AppStateRepository } from "./persistence/app-state-repository.js";
3
+ import { defaultJsonStatePath } from "./persistence/json-state-repository.js";
4
+ import type { ScheduledTask } from "./scheduled-tasks.js";
5
+ import type { WorkflowRun } from "./workflow.js";
6
+ import type { AppState, BackgroundTaskSummary, Conversation, Message, MessageDelivery, MessageImage, ModelSelection, Project, SubagentRun, SubagentRunUpdate, TodoItem, ToolCallQuestion, ToolCallArg, ToolCallBlock, ToolResultSummary, Workspace } from "./types.js";
7
+ import { type BackgroundCompletion } from "../shared/background-task.js";
8
+ import type { TurnUsageReadout } from "./conversation-usage.js";
9
+ /** Mints the id a forked conversation will have, BEFORE its Pi transcript exists.
10
+ *
11
+ * Exported because the ordering demands it and no other arrangement provides it. Pi's copied file's header
12
+ * `id` has to BE the new conversation's id (it is what `findLocalSessionByExactId` matches), so the id has
13
+ * to be decided before the file is written; and the conversation must not exist until the file is safely on
14
+ * disk, or a failed write would leave a conversation whose model context is silently empty. The runtime is
15
+ * therefore handed the id and the store is handed the same one back. See `ForkRequest.forkedConversationId`. */
16
+ export declare function newConversationId(): string;
17
+ /**
18
+ * ONE FOLDER, ONE KEY.
19
+ *
20
+ * The same directory reaches the app spelled several ways - `F:\code\app` and `F:/code/app/` and
21
+ * `f:\code\app` are one folder - and two workspaces for one folder are one project split in half.
22
+ * The key folds the separators and the trailing slash away, and folds case away only where the
23
+ * filesystem folds it too: Windows and macOS treat `F:\Code` and `f:\code` as one directory, Linux
24
+ * does not, and pretending otherwise would merge two real projects into one.
25
+ */
26
+ export declare function workspacePathKey(path: string): string;
27
+ /**
28
+ * How many SETTLED sub-agent runs `state.json` keeps, so the file cannot grow without bound.
29
+ *
30
+ * WHY A BOUND IS NEEDED AT ALL. `beginSubagentRun` unshifts and nothing ever removes a run, so a long
31
+ * session that dispatches sub-agents - which is exactly what this feature encourages - would otherwise
32
+ * accumulate records forever. The file is not a log on disk that costs nothing to grow: it is rewritten
33
+ * in full on EVERY text delta of EVERY running child (see `SubagentRunRecorder.publish`), cloned into
34
+ * the browser on every `state` broadcast, and read at startup. A run record is bounded but not small -
35
+ * `output` is the last assistant message, up to the 50 KB cap of §6, plus the task text and one label
36
+ * per tool call - so an unbounded array makes every one of those operations slower for everybody.
37
+ *
38
+ * WHY 100. It has to be big enough that a person can scroll back through a working day without a card
39
+ * going missing, and small enough that the worst case stays in the range a JSON file and a browser
40
+ * snapshot handle comfortably. At 100 settled runs, and a deliberately pessimistic 50 KB per output,
41
+ * the array is ~5 MB; at 1000 it would be ~50 MB, which is enough to be felt as the app hanging on
42
+ * every broadcast. 100 is roughly a day's worth of sub-agent work for a person using this as a tool
43
+ * rather than as a load generator, and a run older than that is still recoverable in full through Pi -
44
+ * the record carries `sessionId`, and `switch_session` or `export_html` reads the real transcript. So
45
+ * what the bound costs is a scrollback affordance, not history.
46
+ *
47
+ * Exported so a test can assert the bound against the same number the store uses rather than
48
+ * re-deriving it.
49
+ */
50
+ export declare const SUBAGENT_RUN_RETENTION = 100;
51
+ /**
52
+ * How many orchestrated plans are kept.
53
+ *
54
+ * SMALLER THAN THE RUN RETENTION, and deliberately so. A plan does not duplicate the runs it executed -
55
+ * it holds one row per STEP - so fifty plans point at runs that are themselves evicted at 100. Keeping
56
+ * more plans than runs would leave timelines whose cards have all been trimmed away, which is a worse
57
+ * outcome than forgetting the plan: an empty timeline reads as "nothing ran" rather than as "the details
58
+ * aged out". Fifty is also well past what one working day of orchestration produces, since a plan is a
59
+ * request that needed several specialists rather than a unit of work.
60
+ */
61
+ export declare const WORKFLOW_RETENTION = 50;
62
+ /**
63
+ * How many scheduled tasks are kept.
64
+ *
65
+ * A task is a standing arrangement, not a record of something that happened, so the bound here is much
66
+ * looser than the run retention: a person who keeps a daily task for a year has one task, and the
67
+ * hundredth is already a sign that the list is being used as a log rather than as a list of intentions.
68
+ */
69
+ export declare const SCHEDULED_TASK_RETENTION = 100;
70
+ /**
71
+ * Everything a revert decided, before anything is changed.
72
+ *
73
+ * TWO CALLERS NEED IT, and they must agree exactly: the server has to know which sub-agent children to
74
+ * STOP before it cuts the history out from under them, and the store has to know which records to delete
75
+ * afterwards. Two independently written answers to "what does this revert remove" would eventually
76
+ * disagree, and the shape of that disagreement is the worst one available - a stopped child whose record
77
+ * survives, or a deleted record for a child that is still running and still streaming into a store it is
78
+ * no longer in. So both read this one function, which touches nothing.
79
+ */
80
+ export type RevertPlan = {
81
+ /** Index of the message that SURVIVES. Everything from `boundaryIndex + 1` is removed. */
82
+ boundaryIndex: number;
83
+ /** Pi's entry id of the surviving message - the line Pi's file is cut at. */
84
+ boundaryEntryId: string;
85
+ /** The messages that go away, oldest first. */
86
+ removedMessageIds: string[];
87
+ /**
88
+ * Sub-agent runs dispatched by a turn that is being removed, so their records point at a transcript
89
+ * that no longer exists (research §5 pitfall 7). Runs from surviving turns are deliberately NOT here:
90
+ * `trimSubagentRuns` refuses to drop a live conversation's settled runs (`store.ts:183-195`), so a
91
+ * revert has to drop these explicitly or they become permanent orphans.
92
+ */
93
+ doomedRunIds: string[];
94
+ };
95
+ export declare class Store {
96
+ private readonly repository;
97
+ private state;
98
+ private constructor();
99
+ static open(filePath: string): Promise<Store>;
100
+ /** Opens an injected repository, retaining domain reconciliation here. */
101
+ static openRepository(repository: AppStateRepository): Promise<Store>;
102
+ /**
103
+ * THE MODEL FILTER RULES, WITHOUT CLONING THE STATE TO READ THEM.
104
+ *
105
+ * `snapshot()` deep-clones the WHOLE application - every workspace, every conversation, every
106
+ * message of every conversation - and the model filter check needs ONE small array. Reading that
107
+ * array through a full clone is the difference between a few hundred bytes and the entire
108
+ * transcript of the app, on the path that runs every time a message is sent.
109
+ *
110
+ * So the rules get their own narrow reader. It returns a COPY of the array (the caller may keep
111
+ * it, and the store's own state must not change under it), and the individual rules are treated
112
+ * as read-only - which is what the filter does with them.
113
+ */
114
+ modelFilterRules(): import("./types.js").ModelFilterRule[];
115
+ /**
116
+ * THE WORKSPACE A CONVERSATION BELONGS TO, WITHOUT CLONING THE STATE TO FIND ONE ROW.
117
+ *
118
+ * The same argument as the rules above: the filter needs to know WHICH workspace the conversation
119
+ * is in (the rules are per workspace), and the only way to know that today is to clone everything
120
+ * and look. This returns a shallow copy of the one workspace - cheap, and detached enough that a
121
+ * caller cannot reach into the store's state through it.
122
+ */
123
+ workspaceForConversation(conversationId: string): Workspace | undefined;
124
+ workspace(workspaceId: string): Workspace | undefined;
125
+ /** Read every workspace as detached shallow copies. */
126
+ workspaces(): Workspace[];
127
+ /** Read the app-wide default without cloning conversations or transcripts. */
128
+ defaultModel(): ModelSelection | undefined;
129
+ /** Read one detached conversation for lifecycle operations. */
130
+ conversation(conversationId: string): Conversation | undefined;
131
+ /** Return every pending question in one conversation without cloning unrelated history. */
132
+ pendingQuestions(conversationId: string): Array<{
133
+ messageId: string;
134
+ index: number;
135
+ question: ToolCallQuestion;
136
+ }>;
137
+ /**
138
+ * THE SCHEDULED TASKS, WITHOUT CLONING THE STATE TO FIND THEM.
139
+ *
140
+ * The same argument as the readers above, with a sharper edge: the scheduled-task clock sweeps
141
+ * every fifteen seconds and used to read its three-to-zero tasks through `snapshot()` - a deep
142
+ * clone of the whole application, every fifteen seconds, whether the user has any scheduled task or
143
+ * not. On a server holding a long transcript that is a full copy of the app four times a minute,
144
+ * produced for a list that is usually empty.
145
+ *
146
+ * The tasks are returned as a shallow copy of the array: the sweep reads `enabled` and
147
+ * `nextRunAt` and then hands the whole task back to the store, which owns the real one.
148
+ */
149
+ scheduledTasks(): ScheduledTask[];
150
+ projects(): Project[];
151
+ project(projectId: string): Project | undefined;
152
+ /** Conversation IDs that currently have an unresolved escalation requested. */
153
+ openEscalationConversationIds(): Set<string>;
154
+ /**
155
+ * 每条未决例外该谁拍板,按发起会话归拢。
156
+ *
157
+ * `supervisor` = 团队内部的事(会话在等自己的直属上级),`boss` = 到了顶层。
158
+ * 一个会话同时开着内部和顶层两条时,顶层那条赢:那是唯一需要用户听见的一条。
159
+ * 旧的子会话记录在加载时归回父会话,此处仅聚合规范化后的受众。
160
+ */
161
+ openEscalationAudiences(): Map<string, "supervisor" | "boss">;
162
+ /** Child conversation IDs whose enqueued session result is still waiting or sending on a non-archived parent. */
163
+ pendingResultConversationIds(): Set<string>;
164
+ setProject(project: Project): Promise<Project>;
165
+ removeProject(projectId: string): Promise<void>;
166
+ /** Small detached rows used when refreshing each conversation's scoped model catalog. */
167
+ catalogConversationTargets(): Array<Pick<Conversation, "id" | "archivedAt" | "model">>;
168
+ /** Clone only one workspace's transcripts, never unrelated workspaces or app state. */
169
+ conversationsForWorkspace(workspaceId: string): Conversation[];
170
+ setModelFilterRules(rules: import("./types.js").ModelFilterRule[]): Promise<void>;
171
+ /**
172
+ * Sets (or clears) the app-wide default model.
173
+ *
174
+ * `undefined` DELETES the key, for the same reason the workspace defaults do it that way: "follow
175
+ * Pi" has to be the ABSENCE of a value, not a frozen copy of whatever Pi's default was when the
176
+ * setting was saved. A stored copy would keep answering with a model the user had already
177
+ * removed, and Pi's own default may have changed underneath us in the meantime.
178
+ *
179
+ * The pair is written field by field, never as a spread, because the type declares exactly three
180
+ * fields and a spread would quietly start persisting whatever is added to `ModelSelection` next.
181
+ */
182
+ setDefaultModel(model?: ModelSelection): Promise<void>;
183
+ setTerminalShell(shell?: import("./types.js").TerminalShell): Promise<void>;
184
+ snapshot(): AppState;
185
+ /** Cheap scalar/entity reads for hot paths. Never expose the live mutable state object. */
186
+ hasWorkspace(workspaceId: string): boolean;
187
+ searchConversationMessages(workspaceId: string, query: string): SessionSearchResult;
188
+ conversationStatus(conversationId: string): Conversation["status"] | undefined;
189
+ question(conversationId: string, messageId: string, index: number): ToolCallQuestion | undefined;
190
+ pendingQuestion(conversationId: string): {
191
+ messageId: string;
192
+ index: number;
193
+ question: ToolCallQuestion;
194
+ } | undefined;
195
+ /**
196
+ * Whether a conversation already holds a message with this id.
197
+ *
198
+ * A LIVE read with no clone, because its one caller is the send path's duplicate check: a resend
199
+ * that arrives within milliseconds of the original must be answered without paying for a full
200
+ * copy of every conversation in the app. The answer is a boolean and the message is not handed
201
+ * out, so nothing can mutate the store through it.
202
+ */
203
+ hasMessage(conversationId: string, messageId: string): boolean;
204
+ hasAcceptedSend(conversationId: string, clientId: string): boolean;
205
+ /**
206
+ * One conversation and its workspace, as DETACHED copies, without cloning the whole state.
207
+ *
208
+ * The alternative - what the run path used to do - was two `snapshot()` calls, and `snapshot()`
209
+ * deep-clones every conversation, every message and every tool result in the app. That is the
210
+ * shape of the bug it fixes: reading one conversation's model cost O(entire state), and it sat on
211
+ * the path between a click on 发送 and the frame that tells the browser a turn has started.
212
+ *
213
+ * The two objects are still CLONES, because every caller of this is allowed to keep them after the
214
+ * store has moved on (a streamed turn holds its conversation for minutes), and handing out live
215
+ * references would turn the first such caller into a corruption bug that only shows up under load.
216
+ */
217
+ turnContext(conversationId: string): {
218
+ conversation: Conversation;
219
+ workspace: Workspace;
220
+ } | undefined;
221
+ /**
222
+ * THE PHYSICAL DIRECTORY IS THE WORKSPACE'S IDENTITY.
223
+ *
224
+ * A workspace is a folder, not a row in a table: two workspaces pointing at the same directory are
225
+ * the same project, and the app used to mint a fresh UUID for each one. That is what broke
226
+ * re-adding a workspace - the new id matched none of the conversations that belonged to that
227
+ * directory, so the history was unreachable (and, before the soft unmount, actually deleted).
228
+ *
229
+ * So the same folder always means the same workspace id, and the id is what the conversations
230
+ * point at.
231
+ */
232
+ createWorkspace(name: string, path?: string, project?: Workspace): Promise<Workspace>;
233
+ renameWorkspace(workspaceId: string, name: string): Promise<Workspace>;
234
+ /**
235
+ * Replaces the workspace's two defaults. `undefined` DELETES the key rather than storing Pi's
236
+ * default as this app's state - the same convention as setConversationThinking, and for the same
237
+ * reason: "follow Pi" must be the absence of a value, not a frozen copy of whatever Pi's default
238
+ * happened to be when the dialog was saved. Only conversations created AFTER this call ever see
239
+ * the new values; existing ones are not migrated, by design.
240
+ */
241
+ /**
242
+ * Replaces the workspace's defaults. `model`/`thinkingLevel` are ALWAYS sent whole (null clears one of
243
+ * them); `agentId` is tri-state, which is why it is not part of that pair: a string sets it, `null`
244
+ * clears it, and `undefined` leaves it alone. Bundling a tri-state field into an "absent means delete"
245
+ * pair would make any caller that only wanted to change the model silently drop the default agent.
246
+ *
247
+ * ONE persist for all three, deliberately. Two writes would publish an intermediate state - the pair
248
+ * saved but not the agent - and the window between them is observable: a client that reopens the
249
+ * settings dialog after seeing the first write on disk would mount from a broadcast that has not been
250
+ * sent yet, and its draft would then be frozen at the stale value. One write, one broadcast, no window.
251
+ */
252
+ setWorkspaceDefaults(workspaceId: string, defaults: {
253
+ model?: ModelSelection;
254
+ thinkingLevel?: string;
255
+ agentId?: string | null;
256
+ }): Promise<Workspace>;
257
+ /** Applies the shared model defaults to every mounted workspace and writes them together. */
258
+ setMountedWorkspaceDefaults(defaults: {
259
+ model?: ModelSelection;
260
+ thinkingLevel?: string;
261
+ }): Promise<number>;
262
+ /**
263
+ * TAKES A WORKSPACE OUT OF THE SIDEBAR. IT DOES NOT DELETE ANYTHING.
264
+ *
265
+ * This used to cascade: the workspace row AND every conversation that pointed at it were erased
266
+ * from the state, in one persist. That made the most natural thing a user could do - remove a
267
+ * workspace to tidy the sidebar, then add the same folder back - silently destroy the history of
268
+ * that project, and there was no way to get it back.
269
+ *
270
+ * So the removal is a SOFT UNMOUNT, the same shape as a session's archive: the workspace row
271
+ * stays (with `closedAt` on it), the conversations stay, the uploads stay, and nothing is
272
+ * broadcast for either (see `clientState`). Adding the same folder again re-opens the very same
273
+ * workspace - same id, same conversations - which is the whole point of the physical path being
274
+ * the workspace's identity.
275
+ *
276
+ * The returned list is the conversations that were STOPPED, not deleted: a turn that was still
277
+ * running under a workspace that just left the sidebar cannot keep burning a model session
278
+ * behind the user's back, and a pending question would otherwise wait for an answer that the
279
+ * sidebar can no longer reach.
280
+ */
281
+ deleteWorkspace(workspaceId: string): Promise<string[]>;
282
+ /**
283
+ * THE STATE THE CLIENT IS ALLOWED TO SEE.
284
+ *
285
+ * `snapshot()` is the truth of what the store HOLDS; this is the truth of what is ON SCREEN. The
286
+ * difference is the closed workspaces: one that was removed from the sidebar is still in the store
287
+ * - that is exactly why re-adding the folder brings its history back - but it is not part of the
288
+ * app any more, so neither it nor its conversations are broadcast.
289
+ *
290
+ * Filtering HERE, in one place, rather than in every reader, is what keeps the client dumb: the
291
+ * sidebar renders `state.workspaces` and never has to know that a closed workspace exists.
292
+ */
293
+ clientState(scope?: {
294
+ conversationId?: string;
295
+ }): AppState;
296
+ createConversation(workspaceId: string, configuration?: {
297
+ agentId?: string | null;
298
+ model?: ModelSelection | null;
299
+ thinkingLevel?: string | null;
300
+ modelNotice?: string;
301
+ agentNotice?: string;
302
+ cwd?: string;
303
+ parentConversationId?: string;
304
+ origin?: "user" | "orchestrator";
305
+ separateMemoryTree?: boolean;
306
+ }): Promise<Conversation>;
307
+ /**
308
+ * Records (or clears) one conversation as collapsed in the sidebar's session tree. The list is a
309
+ * SET in array clothing - order means nothing, duplicates must not accumulate - and it follows the
310
+ * assign -> persist -> rollback pattern `setTerminalShell` established: the in-memory value is the
311
+ * previous value again the moment persistence fails, so a rejected write can never leave the
312
+ * screen and the disk disagreeing.
313
+ */
314
+ setConversationCollapsed(conversationId: string, collapsed: boolean): Promise<void>;
315
+ /**
316
+ * Whether the reader has opened one child session's composer.
317
+ *
318
+ * THE SERVER OWNS THIS FACT. The browser keeps a copy per conversation (so the choice survives a
319
+ * reload), but the copy is a mirror: what the server says is what happens. A browser that owned
320
+ * it could unlock a session the server still refuses, and the reader would be told 「发送失败」
321
+ * for a message that was never allowed to be sent.
322
+ */
323
+ childLockUnlocked(conversationId: string): boolean;
324
+ listWarmSessions(workspaceId: string): NonNullable<AppState["warmSessions"]>;
325
+ isWarmSession(conversationId: string): boolean;
326
+ /**
327
+ * Opens (or re-closes) one child session's composer, and persists it.
328
+ *
329
+ * The assign -> persist -> rollback pattern `setConversationCollapsed` established: the in-memory
330
+ * value is the previous value again the moment persistence fails, so a rejected write can never
331
+ * leave the screen and the disk disagreeing about whether the door is open.
332
+ */
333
+ setChildLockUnlocked(conversationId: string, unlocked: boolean): Promise<void>;
334
+ /**
335
+ * THE CHILD-SESSION FACTS OF ONE CONVERSATION: its own parent edge, and the parent's row.
336
+ *
337
+ * Narrow on purpose: the send path asks this on EVERY message, and `store.conversation()` clones
338
+ * the whole transcript - a long conversation would pay for its entire history to answer one
339
+ * yes/no question. Two rows, read in place, and nothing copied.
340
+ */
341
+ childSessionFacts(conversationId: string): {
342
+ parentConversationId?: string;
343
+ parent?: {
344
+ id: string;
345
+ archivedAt?: string;
346
+ };
347
+ };
348
+ /**
349
+ * Copies a conversation into a NEW one, under an id the caller has already minted.
350
+ *
351
+ * THE ID IS A PARAMETER, and that is the whole reason this method does not simply mint one: the caller had
352
+ * to write Pi's copied transcript under that id first (see `ForkRequest.forkedConversationId`), so by the
353
+ * time this runs the id is already the one on disk. Minting here as well would produce a conversation whose
354
+ * Pi file belongs to a different, nonexistent conversation - the exact "Pi opens an empty session and the
355
+ * history has vanished with no error anywhere" failure probe B was about.
356
+ *
357
+ * WHAT IS COPIED, FIELD BY FIELD AND NEVER BY A SPREAD, for the same reason `createConversation` writes out
358
+ * three fields individually: the type declares exactly these, so a spread would quietly start persisting
359
+ * whatever the next person adds to `Conversation`. The workspace, the model, the thinking level and the
360
+ * agent are all copied, because a fork that came back on a different model or with no role would not be
361
+ * the conversation the user forked.
362
+ *
363
+ * `title` is copied VERBATIM, unchanged. Not a reason, not a suffix: the fork IS this conversation, and
364
+ * inventing a name is a product decision the request did not delegate. Renaming it is one click and always
365
+ * available, which is better than a label nobody chose.
366
+ *
367
+ * MESSAGES ARE COPIED WITH FRESH `id`s AND THE ORIGINAL `piEntryId`s. Both halves matter:
368
+ *
369
+ * - Fresh ids, because `Message.id` is this store's own handle (`beginAssistantMessage`,
370
+ * `appendToolCall` and `appendAssistantDelta` all find a message by it) and a forked conversation that
371
+ * answered to its source's ids would be one object wearing two names. Fork the same conversation twice
372
+ * and the two copies are distinct records.
373
+ * - The ORIGINAL `piEntryId`, because that is the whole reason the fork is a fork. Pi's copied file is
374
+ * byte-identical apart from two header fields (see `forkSessionFile`), so the source's entry ids are
375
+ * present and valid in the fork - and a copied message keeps the ability to be a REVERT boundary in the
376
+ * conversation it was copied into. Dropping the ids would produce a fork whose history cannot be
377
+ * reverted at all, which is a silent loss of a feature rather than an honest absence.
378
+ *
379
+ * `status` is `"idle"` unconditionally, even when the source is running, because the caller refuses a
380
+ * running source outright (`runtime.fork`) and a conversation that has never run a turn must not be born
381
+ * claiming to be in one. `error` is NOT copied: it describes a run, and this conversation has had none.
382
+ *
383
+ * NOT COPIED, and both omissions are deliberate and both are the same judgement - they belong to a RUN,
384
+ * and no run was copied: `subagentRuns` are filtered by `conversationId`, so a run dispatched by the source
385
+ * stays with the source; a run dispatched by the FORK will be filed under the fork's own id and work as
386
+ * usual. `queuedMessages` likewise, for the same reason (research pitfall 7): a message waiting for a turn
387
+ * that was never copied must not be re-sent into a different conversation.
388
+ *
389
+ * POSITION IS NOT CHOSEN HERE. `unshift` plus the client rendering the sidebar by `updatedAt`
390
+ * (`byRecency`) puts a fork at the TOP of its workspace group, because `updatedAt` is now - which is the
391
+ * same position a newly created conversation takes, and the same reason.
392
+ */
393
+ forkConversation(sourceConversationId: string, forkedConversationId: string, options?: {
394
+ parentConversationId?: string;
395
+ warmTitle?: string;
396
+ piSessionFile?: string;
397
+ inheritedUsageEntryIds?: string[];
398
+ }): Promise<Conversation>;
399
+ /**
400
+ * Archive is a marker, not a move: the conversation keeps its id, workspace, messages and position.
401
+ * `updatedAt` is deliberately NOT touched, because it drives the sidebar's live timestamp and recency -
402
+ * bumping it would teleport the row to the top of the list the instant it was archived.
403
+ *
404
+ * A running conversation is rejected rather than archived. An archived conversation cannot be opened,
405
+ * so allowing one would leave a run streaming into a pane the user can no longer reach, along with any
406
+ * Extension UI question it is blocked on. Refusing keeps the rule honest and leaves stop-then-archive
407
+ * to the user, which is a visible choice instead of a silent one.
408
+ */
409
+ archiveConversation(conversationId: string): Promise<void>;
410
+ /** Restoring deletes the key rather than setting it to null, so a fully restored conversation serializes
411
+ * byte-identically to one that was never archived. `delete` is legal here because the field is optional. */
412
+ unarchiveConversation(conversationId: string): Promise<void>;
413
+ /**
414
+ * Archives one whole tree as one state write. Only a conversation with no existing parent may
415
+ * start it; an archived parent is still a parent, so its active descendants cannot be archived
416
+ * independently. All running checks happen before the first mutation, making rejection all-or-none.
417
+ */
418
+ archiveConversationTree(conversationId: string): Promise<void>;
419
+ /** Restores one archived tree in one write; active descendants are already restored by definition. */
420
+ unarchiveConversationTree(conversationId: string): Promise<void>;
421
+ /**
422
+ * Lists the conversation IDs in a session's subtree (root first, pre-order).
423
+ * Returns `[]` when the conversation does not exist.
424
+ */
425
+ conversationSubtreeIds(conversationId: string): string[];
426
+ /**
427
+ * Permanently destroys a child conversation and its entire descendant subtree along with all
428
+ * conversation-scoped store records (messages, tool calls, sub-agent runs, background tasks,
429
+ * workflows, todos, UI locks/collapse markers, and open escalations raised by the destroyed
430
+ * sessions). Refuses top-level sessions and refuses if any session in the subtree is running.
431
+ */
432
+ deleteConversationSubtree(conversationId: string): Promise<{
433
+ destroyed: Array<{
434
+ id: string;
435
+ title: string;
436
+ workspaceId: string;
437
+ piSessionFile?: string;
438
+ messageIds: string[];
439
+ }>;
440
+ }>;
441
+ /** Pre-order traversal with cycle protection; archived nodes are traversed, not treated as leaves. */
442
+ private conversationSubtree;
443
+ /**
444
+ * Rename edits the title and NOTHING else. In particular `updatedAt` is deliberately not touched,
445
+ * for exactly the reason archive is: `updatedAt` is the sidebar's recency key, so bumping it would
446
+ * teleport the row to the top of the live list because someone retitled it. Renaming is not activity.
447
+ *
448
+ * There is no uniqueness check, and there is no status check on purpose. `createWorkspace` does not
449
+ * reject a duplicate name either, so rejecting one here would make the two paths disagree about the
450
+ * same question; two rows reading "notes" is a cosmetic problem the user can see and fix. And a
451
+ * RUNNING conversation stays renameable: the title is display-only, the run is unaffected, and
452
+ * refusing would mean a conversation could be permanently un-renameable while the agent works.
453
+ *
454
+ * Archived conversations are renameable too - archiving folds a row away, it does not delete it, and
455
+ * the Archived group renders the same name.
456
+ */
457
+ renameConversation(conversationId: string, name: string): Promise<Conversation>;
458
+ followConversationWorktree(conversationId: string, worktreeId: string): Promise<void>;
459
+ /**
460
+ * Writes ONE user message into the transcript - the single place a user utterance comes into being.
461
+ *
462
+ * Two callers exist and they differ only in `delivery`, because whether a send starts a turn or waits
463
+ * for one is decided by the RUN GUARD in `run-service`, not here. This method records the words and,
464
+ * if they are waiting, records that they are waiting. Deciding anything about turns would put a second,
465
+ * contradictory answer next to the guard's.
466
+ *
467
+ * `clientId` is the browser's own id for the message it has already drawn. When it is well formed and
468
+ * not already taken, the message IS that id - which is what lets the optimistic bubble and the stored
469
+ * message be the same object rather than two that have to be matched up by content afterwards. A
470
+ * collision falls back to a minted id rather than throwing: the browser is asking for its words to be
471
+ * kept, and refusing the whole send because an id was already in use would lose them.
472
+ *
473
+ * `delivery: "waiting"` ALSO SKIPS EVERY SIDE EFFECT BELOW - no `running`, no title, no `updatedAt`,
474
+ * no clearing of a failure reason. Those all describe a turn, and a message waiting for one has not
475
+ * started anything. It is why a conversation holding only waiting messages still reads as idle in the
476
+ * sidebar, and why the title comes from the first message that was actually asked rather than from
477
+ * whatever was typed into a box that was not listening yet. `openTurnOnMessage` applies them at the
478
+ * moment a turn genuinely begins.
479
+ */
480
+ /**
481
+ * Writes ONE INSTRUCTION INTO THE TRANSCRIPT AS SOMETHING THE SYSTEM SAID.
482
+ *
483
+ * `addUserMessage` above is the only way a person's words come into being, and everything written
484
+ * through it wears the reader's own name and the reader's bubble. That is right for a person and
485
+ * wrong for the orchestrator: when a primary agent dispatches a task to a child session, the
486
+ * child receives an ORDER, not something the reader typed - and the child transcript showed it
487
+ * under the reader's avatar, so the reader saw their own name on an instruction they never wrote.
488
+ *
489
+ * The role is `tool` for a reason that is not cosmetic: `tool` is already the product's word for
490
+ * "the system delivered this", it renders as the 系统 side of the transcript rather than as a
491
+ * person, and Pi's queue already knows how to hand a `tool` message to a model (see
492
+ * `composePrompt` in the run service). So the instruction reaches the model the same way, and the
493
+ * reader sees who spoke.
494
+ */
495
+ addAgentMessage(conversationId: string, content: string, options?: Pick<Message, "delivery" | "source">): Promise<Message>;
496
+ addUserMessage(conversationId: string, content: string, images?: MessageImage[], attachments?: import("./types.js").MessageAttachments, options?: {
497
+ clientId?: string;
498
+ delivery?: Message["delivery"];
499
+ }): Promise<Message>;
500
+ private persistIncomingTurn;
501
+ /**
502
+ * Takes the browser's id for its own optimistic message, when it is safe to.
503
+ *
504
+ * A client that names an id already in this conversation gets a minted one instead: two messages sharing
505
+ * an id would break `updateToolCall`, `revertMessage` and every per-message write that follows, so
506
+ * uniqueness within the conversation is worth more than the client getting its own id back in that case.
507
+ * The `message_` prefix is required so a folded legacy id (which is `q_`-prefixed) can never be adopted.
508
+ */
509
+ private claimClientMessageId;
510
+ /**
511
+ * Appends one background-result message to a conversation. The render column is the same as before
512
+ * (a `role: "tool"` row, never impersonating a user bubble) - what this method now ALSO supports is
513
+ * putting the message straight into the dock by passing `delivery: "waiting"`, which is what exec and
514
+ * sub-agent background completions do once a 后台回传 is treated as a queue item with steer priority
515
+ * rather than a one-way notice the model never gets to read.
516
+ *
517
+ * NO `turnContext` claim, NO `status: "running"`. The message sits in the transcript; with a delivery
518
+ * state it also enters `waitingMessages` and `runConversationTurns` will pick it up next.
519
+ */
520
+ addToolMessage(conversationId: string, content: string, options?: {
521
+ delivery?: MessageDelivery;
522
+ prioritizeWaiting?: boolean;
523
+ }): Promise<Message>;
524
+ /**
525
+ * Records the model a conversation runs on. `updatedAt` is deliberately NOT touched, for the same
526
+ * reason rename does not touch it: it is the sidebar's recency key, and switching model is not
527
+ * activity in the conversation. No status check either - changing the model of a RUNNING
528
+ * conversation is allowed, because the selection is read at the START of the next turn, so the
529
+ * turn in flight is unaffected and refusing would strand a conversation on a model the user can
530
+ * no longer change until it settles.
531
+ */
532
+ setConversationModel(conversationId: string, model: ModelSelection): Promise<Conversation>;
533
+ /**
534
+ * Forgets the model a conversation runs on, so it follows Pi's own default again.
535
+ *
536
+ * FOR A MODEL THAT NO LONGER EXISTS. A conversation's model is copied at birth and never re-read
537
+ * from the workspace - but the copied model can be removed from Pi, and leaving the field pointing
538
+ * at it is worse than clearing it: Pi does not fail such a turn, it runs it on its own default, so
539
+ * the picker names one model while another one answers. `undefined` DELETES the key rather than
540
+ * storing "Pi's default" as this app's state, the same as `setConversationThinking` above.
541
+ *
542
+ * THE THINKING LEVEL GOES WITH IT. A level is a property of a model (`max` on a model with one
543
+ * level means something different from `max` on another), so a level left behind by a model that
544
+ * is gone describes nothing.
545
+ */
546
+ clearConversationModel(conversationId: string): Promise<Conversation>;
547
+ /** Restoring Pi's own default deletes the key rather than storing Pi's default as this app's state. */
548
+ setConversationThinking(conversationId: string, level: string | undefined): Promise<Conversation>;
549
+ /**
550
+ * Records the agent a conversation runs as. Same three rules as `setConversationModel`: `undefined`
551
+ * DELETES the key rather than freezing "no agent" as a value, `updatedAt` is untouched because
552
+ * changing role is not activity in the conversation, and no status check - the agent is read at the
553
+ * START of the next turn, so the turn in flight is unaffected.
554
+ */
555
+ setConversationAgent(conversationId: string, agentId: string | undefined): Promise<Conversation>;
556
+ setConversationConfiguration(conversationId: string, settings: {
557
+ agentId?: string;
558
+ model?: ModelSelection;
559
+ thinkingLevel?: string;
560
+ }): Promise<Conversation>;
561
+ beginAssistantMessage(conversationId: string, agentIdentity?: Message["agentIdentity"]): Promise<Message>;
562
+ /**
563
+ * Applies a streamed delta to the authoritative in-memory transcript without touching disk.
564
+ *
565
+ * The runtime must be able to drain Pi and publish the token before a disk transaction finishes.
566
+ * `checkpointMessage` below makes the same object durable on a bounded cadence and at turn boundaries.
567
+ */
568
+ appendAssistantDeltaLive(conversationId: string, messageId: string, delta: string): void;
569
+ appendAssistantDelta(conversationId: string, messageId: string, delta: string): Promise<void>;
570
+ /**
571
+ * THE MODEL'S REASONING, APPENDED TO THE MESSAGE IT BELONGS TO.
572
+ *
573
+ * It used to be broadcast and nothing more: the server emitted `message.thinking` on every delta and no
574
+ * code anywhere read it, so the reasoning reached no one - not the screen while it streamed, and not
575
+ * the transcript afterwards. The field, the event and the stylesheet were all already there; the two
576
+ * halves that would have used them were missing, which is why a finished turn had no visible reasoning
577
+ * to go back to. Persisting here rather than only in the browser is the point of its living on the
578
+ * message: a reasoning stream that vanishes on reload was never a record of anything.
579
+ */
580
+ appendThinkingDeltaLive(conversationId: string, messageId: string, delta: string, at?: number, newBlock?: boolean): void;
581
+ setThinkingActiveLive(conversationId: string, messageId: string, active: boolean): void;
582
+ appendThinkingDelta(conversationId: string, messageId: string, delta: string): Promise<void>;
583
+ /** Persists the message exactly as it stands now, including any live text, thinking and tool updates. */
584
+ checkpointMessage(conversationId: string, messageId: string): Promise<void>;
585
+ /**
586
+ * Appends one tool call to the message it belongs to, and returns the message's whole `toolCalls`
587
+ * array so the caller can broadcast it as one snapshot.
588
+ *
589
+ * WHY AN APPEND AND NOT AN UPDATE, and why the returned array is the whole truth. A turn's calls arrive
590
+ * one at a time and each one REWRITES a field on a row it has already broadcast - `status` and
591
+ * `durationMs` land on `tool_execution_end`, minutes or seconds after the row was published by
592
+ * `tool_execution_start`. So the only thing that can be cheap and correct is: the store owns the array,
593
+ * the caller sends the array. Handing back the array rather than the one row is what stops the two from
594
+ * drifting - the caller has nothing to merge, so there is no merge to get wrong, and the event it sends
595
+ * is the same shape `state` carries on the next broadcast.
596
+ *
597
+ * PERSISTED ON EVERY CALL, for the same reason `appendAssistantDelta` is: a block that was on screen
598
+ * when the browser reloaded has to come back, and a reload that showed a `read` but not the `bash` that
599
+ * followed it would be worse than showing neither.
600
+ *
601
+ * `toolCalls` is CREATED LAZILY, so a message whose turn used no tools stores no empty array - which is
602
+ * what makes a `state.json` written before call blocks existed read as "this turn used no tools"
603
+ * instead of as a field it does not understand.
604
+ */
605
+ appendToolCall(conversationId: string, messageId: string, call: ToolCallBlock): Promise<ToolCallBlock[]>;
606
+ /**
607
+ * Fills in the outcome of the call at `index`, or returns the array UNCHANGED when there is no such
608
+ * index.
609
+ *
610
+ * ADDRESSED BY POSITION rather than by Pi's `toolCallId`, and that is the whole reason the caller has
611
+ * to hold a map. `toolCallId` is an identity only Pi can resolve - it is never persisted on
612
+ * `ToolCallBlock` - so the caller resolves each end back to the row it started, which is exactly what
613
+ * `SubagentRunRecorder` does for a card.
614
+ *
615
+ * A MISMATCH IS NOT AN ERROR. `tool_execution_end` with no matching start, or one that arrives after the
616
+ * turn ended, must not fail the turn: the alternative is a store method that throws inside a drain loop,
617
+ * and the reader would lose the whole turn's transcript over one unresolvable id. Returning the array
618
+ * unchanged keeps the caller broadcasting what it actually knows.
619
+ *
620
+ * Only `status` and `durationMs` are written, and only when they are present on the incoming block - a
621
+ * second end for a row that already has an outcome must not erase it with an absent field.
622
+ */
623
+ settleToolCall(conversationId: string, messageId: string, index: number, outcome: {
624
+ status?: "ok" | "error";
625
+ durationMs?: number;
626
+ result?: ToolResultSummary;
627
+ }): Promise<ToolCallBlock[]>;
628
+ /**
629
+ * REWRITE A CALL THAT IS STILL RUNNING - its arguments as they have grown, and whatever output has
630
+ * arrived so far. Separate from `settleToolCall` because "settle" is the wrong word for a turn that is
631
+ * still going: nothing here decides an outcome, and a method that could be mistaken for it is one a
632
+ * future caller reaches for by mistake.
633
+ *
634
+ * Every field is `undefined`-tested for the same reason `settleToolCall` does it: `""` and `[]` are
635
+ * values a tool can genuinely produce, and treating them as "not reported" would erase a real answer.
636
+ */
637
+ /**
638
+ * THE TOOL-CALL WRITES, PERSISTED AS ONE MESSAGE INSTEAD OF THE WHOLE APPLICATION.
639
+ *
640
+ * A tool call's lifecycle touches exactly ONE thing: the `toolCalls` array of ONE message. The
641
+ * write used to be `this.persist()`, which hands the ENTIRE state to the repository - every
642
+ * workspace, every conversation, every message of every conversation - to be serialized and
643
+ * written. A turn that calls five tools therefore wrote the whole application ten to fifteen
644
+ * times, and every one of those writes was proportional to the whole history rather than to the
645
+ * one row that changed (LAT-020).
646
+ *
647
+ * `message.replace` is the transaction that means 「this one message now reads like this」, and it
648
+ * is exactly the write this is: the row's content did not change, only its tool calls did.
649
+ */
650
+ private persistToolCallMessage;
651
+ updateToolCall(conversationId: string, messageId: string, index: number, patch: {
652
+ label?: string;
653
+ detail?: string;
654
+ args?: ToolCallArg[];
655
+ live?: string;
656
+ preparing?: boolean;
657
+ question?: ToolCallQuestion;
658
+ at?: number;
659
+ thinkingAt?: number;
660
+ thinkingBlock?: number | null;
661
+ backgroundTask?: ToolCallBlock["backgroundTask"];
662
+ }): Promise<ToolCallBlock[]>;
663
+ /**
664
+ * STOPS SEVERAL ROWS FROM CLAIMING THE MODEL IS STILL WRITING THEM, in one write.
665
+ *
666
+ * A row is created by `toolcall_start` and filled in by `tool_execution_start`, so a call the turn cut
667
+ * off between the two - an abort, a cancelled turn, an upstream error - kept `preparing` for the rest of
668
+ * time. A finished turn showing 「生成参数中…」 is the same expensive lie as a settled tool still saying
669
+ * 「正在生成参数…」: it says the agent is working on something it has already stopped doing, and it is
670
+ * what a reader sees on every such row for the rest of the conversation.
671
+ *
672
+ * WHAT IS *NOT* WRITTEN HERE, and the omissions are the point. No `status`: Pi reported no outcome for
673
+ * these calls, and `status` is the field that says an outcome was observed - writing `"error"` would
674
+ * claim the tool failed, which is a different fact from "it never ran". No `result`, for the same
675
+ * reason. `preparing: false` alone says exactly what is true, which is that the arguments stopped
676
+ * arriving.
677
+ *
678
+ * `live` IS CLEARED, because during preparation that field holds the ARGUMENT TEXT and the transcript
679
+ * would otherwise print a raw JSON fragment under a call that never ran. The parameters themselves are
680
+ * not lost: `args` carries them from `toolcall_end`, and `detail` has named the target since the first
681
+ * readable fragment.
682
+ *
683
+ * Addressed by position like every other row write, and one that is not there is skipped rather than
684
+ * failing the turn - the same tolerance `settleToolCall` has for an id it cannot resolve.
685
+ */
686
+ clearPreparingToolCalls(conversationId: string, messageId: string, rows: readonly number[]): Promise<ToolCallBlock[]>;
687
+ setStatus(conversationId: string, status: Conversation["status"]): Promise<void>;
688
+ /** Commit once at turn end; metadata transactions work for both JSON and SQLite repositories. */
689
+ recordConversationUsage(conversationId: string, readout: TurnUsageReadout): Promise<void>;
690
+ /**
691
+ * Records WHY a turn failed in a way the reader can see. `Conversation.error` is rendered as a red
692
+ * banner above the transcript (`App.tsx:conversation-error`), and it is the only field that survives
693
+ * a status flip and a navigation away and back - so it is the only place a "Pi died without saying
694
+ * anything" failure becomes visible to a person.
695
+ *
696
+ * Settled through `persistMetadata` rather than `persistState` so the message and tool deltas the
697
+ * turn had already written are not re-validated against a partial read; a previous build took the
698
+ * heavier path and an early failure mid-turn left the transcript rolled back to the last good
699
+ * checkpoint, hiding exactly the deltas the reader would have wanted to see.
700
+ *
701
+ * Set to `undefined` to clear, which the next `addUserMessage` does anyway - so callers only need
702
+ * this when they want the banner without a follow-up message (the turn did fail and the user is
703
+ * going to act on it without sending another prompt first).
704
+ */
705
+ setFailureReason(conversationId: string, reason: string | undefined): Promise<void>;
706
+ /**
707
+ * Records WHY THIS CONVERSATION'S LAST ANSWER IS INCOMPLETE, in a way the reader can see.
708
+ *
709
+ * `Conversation.warning` is a different fact from `Conversation.error`: the run did not break, the
710
+ * answer was cut short by the model's output budget. The reader's next move is different too - a
711
+ * failed turn asks them to retry, a truncated one asks them to let the model continue - so the two
712
+ * are kept apart rather than sharing one field and one colour.
713
+ *
714
+ * Set to `undefined` to clear, which the next `addUserMessage` does anyway.
715
+ */
716
+ setWarningReason(conversationId: string, reason: string | undefined): Promise<void>;
717
+ /** The plan a revert would carry out, without carrying it out. The server reads this to stop children first. */
718
+ planRevert(conversationId: string, messageId: string, withdraw?: boolean): RevertPlan;
719
+ /**
720
+ * Records which Pi entry a message became, as reported by Pi while it was still running.
721
+ *
722
+ * Only ever set, never cleared: a message that already has an id keeps the one Pi gave it for that
723
+ * turn, and a second report for the same message is ignored rather than allowed to move the boundary -
724
+ * a boundary that moved under a user who is looking at it is exactly the silent data loss revert must not
725
+ * be able to cause. An unknown message id is refused for the same reason `appendAssistantDelta` refuses
726
+ * one: it means the caller and the store disagree about the conversation, and guessing is worse.
727
+ */
728
+ setMessagePiEntryId(conversationId: string, messageId: string, piEntryId: string): Promise<void>;
729
+ /** Cache a locator Pi itself resolved while serving this conversation; never trust it as authorization. */
730
+ setConversationPiSessionFile(conversationId: string, path: string): Promise<void>;
731
+ /** Records that a child conversation has reported its result/progress to its parent. */
732
+ markConversationReported(conversationId: string, timestamp?: string): Promise<Conversation | undefined>;
733
+ /**
734
+ * Reverts the conversation to the state right after `messageId`, in `state.json` only.
735
+ *
736
+ * SCOPE, DELIBERATELY NARROW: this touches `messages` and `subagentRuns` and nothing else. It does not
737
+ * touch the workspace (that is not this process's to touch), it does not create or modify a conversation
738
+ * (the user's hard requirement: still the same session, same id, same row in the sidebar), and it does
739
+ * not record a "revert happened" marker - there is no undo to restore one for.
740
+ *
741
+ * NOT `updatedAt`. For the same reason rename and archive leave it alone: it is the sidebar's recency key,
742
+ * so bumping it would teleport the conversation to the top of the list as a side effect of editing its
743
+ * history. What a person did to a transcript is not activity IN the conversation, and the timestamps of
744
+ * the surviving messages are untouched, so the pane's own ordering does not move either.
745
+ *
746
+ * `planRevert` has already run by the time this is called (the server reads it to stop children), so the
747
+ * plan is recomputed here rather than passed in - two callers cannot disagree about what a message id
748
+ * means, and the recomputation is a pure scan of a small array.
749
+ */
750
+ revertMessages(conversationId: string, messageId: string, withdraw?: boolean): Promise<RevertPlan>;
751
+ private requireConversation;
752
+ /**
753
+ * This conversation's waiting messages, in the order they will be started.
754
+ *
755
+ * Cloned like every other value this store hands out, because the caller broadcasts it straight to
756
+ * browsers and the array is mutated in place by the very next send.
757
+ */
758
+ listWaitingMessages(conversationId: string): Message[];
759
+ /** The same list by reference, for callers that only read a field and must not pay for a clone.
760
+ *
761
+ * Includes `role: "tool"` messages now that a 后台回传 is a real queue item: same dock, same ordering,
762
+ * same delivery state machine, same steer/claim semantics - the only thing different is the render
763
+ * (kept as a 后台回传 block) and what the agent is told when its turn comes (see `composePrompt`). */
764
+ private waitingMessages;
765
+ private requireWaitingMessage;
766
+ private persistMessages;
767
+ /**
768
+ * Claims one waiting message for delivery to the live Pi process: `waiting` becomes `sending`, and the
769
+ * message STAYS WHERE IT IS - still on screen, still in the transcript, still at the same index.
770
+ *
771
+ * The read and the write are adjacent statements with no `await` between them, which is what makes the
772
+ * claim atomic here. This store has no mutex and does not need one: JavaScript runs this synchronous
773
+ * run-to-completion, so a second caller arriving in the same tick observes the write above and cannot
774
+ * claim the same message.
775
+ */
776
+ claimWaitingMessage(conversationId: string, messageId: string): Promise<Message>;
777
+ /**
778
+ * Puts ONE message into `waiting` when it has no delivery state at all.
779
+ *
780
+ * `releaseWaitingMessage` above moves `sending` BACK to `waiting`, which is a claim being taken back.
781
+ * This is the other direction: a message that was written as an ordinary sent message and has to join
782
+ * the queue after the fact. There are exactly two reasons it happens, and both are consequences of the
783
+ * decision being made before the write rather than after it (see `enqueueAndRun`):
784
+ *
785
+ * 1. Two sends raced. The second one read "idle", wrote itself as an ordinary message, and only then
786
+ * found the run slot taken. Its words are unanswered, so it is a waiting message after all.
787
+ * 2. The preflight that runs between the write and the turn refused (a model that cannot read images,
788
+ * an @-mention that could not be expanded). Nothing reached a model, so the words are still owed an
789
+ * answer and belong in the queue where the user can see them and send them again.
790
+ *
791
+ * Both are restorations of a state that was briefly wrong, never a way to re-queue a message Pi holds:
792
+ * a `sending` message is refused here, which keeps this from becoming a back door around the one-way
793
+ * door `claimWaitingMessage` puts up.
794
+ */
795
+ markMessageWaiting(conversationId: string, messageId: string): Promise<Message | undefined>;
796
+ /**
797
+ * Puts ONE `sending` message back to `waiting`, for the one case that proves Pi never took it.
798
+ *
799
+ * The one legal use, and it is narrow on purpose: this is called ONLY when we can prove the message
800
+ * never reached a model - the turn ended while Pi still held it, or the write to Pi's stdin failed
801
+ * before it left. Pi drains steering before its loop can end and announces the delivery before the turn
802
+ * settles, so a message still `sending` when the child is gone provably was not delivered, and
803
+ * returning it is a fact rather than a guess. It is deliberately NOT used for "Pi has not answered yet",
804
+ * where the outcome is genuinely unknown and the honest state is still `sending`.
805
+ */
806
+ releaseWaitingMessage(conversationId: string, messageId: string): Promise<void>;
807
+ /**
808
+ * Returns every `sending` message of this conversation to `waiting`, for the end of a turn.
809
+ *
810
+ * See `releaseWaitingMessage` for why this is a fact and not a guess. Called both when a turn ends and
811
+ * when the user stops it: in the stop case the child is killed mid-turn and a steer it was still holding
812
+ * was never delivered either, so putting it back is what lets the user decide what to do with it instead
813
+ * of silently dropping a message they typed - a message they can still see, because it never left the
814
+ * transcript in the first place.
815
+ */
816
+ releaseSendingMessages(conversationId: string): Promise<void>;
817
+ /**
818
+ * Withdraws one waiting message, by id. Returns it, or `undefined` when it is already gone.
819
+ *
820
+ * "Already gone" is a no-op rather than an error, and the reason is the same as `SubagentRun.stop`: the
821
+ * click that sent this was almost always triggered by a bubble the browser has not been told about
822
+ * yet, so an id that has already been answered or cancelled is the ordinary case and must not surface
823
+ * as a failure.
824
+ *
825
+ * A `sending` message REFUSES, because the text is already in a live Pi child's stdin and Pi has no way
826
+ * to forget one item (its only queue command is `clear_queue`, which clears every one of them,
827
+ * including follow-ups that have nothing to do with this click). Removing it here would not stop Pi from
828
+ * delivering it - it would make the model act on a message the user believed they had withdrawn, while
829
+ * their own transcript quietly lost the words.
830
+ */
831
+ cancelWaitingMessage(conversationId: string, messageId: string): Promise<Message | undefined>;
832
+ /**
833
+ * Rewrites the words of one waiting message. User sends only - a 后台回传 carries a `<task>` envelope
834
+ * the model parses for state, summary and body, and editing it would change a fact the agent has
835
+ * already started reasoning from. The client dock shows no 「改字」 button for `role: "tool"` rows.
836
+ */
837
+ editWaitingMessage(conversationId: string, messageId: string, content: string): Promise<Message>;
838
+ /**
839
+ * Moves one waiting message to a new position among the waiting messages.
840
+ *
841
+ * `toIndex` is counted over the WAITING messages only, so `0` is the next one the agent will start and
842
+ * the caller never has to know how many answered messages sit above it. Moving to the front and moving
843
+ * back are the same operation, which is the point: the old arrangement had a `priority` boolean for the
844
+ * first and no way at all to express the second, so undoing a priority meant cancelling the message and
845
+ * retyping it.
846
+ *
847
+ * NOTHING CAN GO IN FRONT OF A `sending` MESSAGE. It is already in Pi's stdin and Pi's steering queue
848
+ * is FIFO, so it will be delivered before anything this server could do about the order. Accepting the
849
+ * move and then delivering the other one first would be the UI promising an outcome the transport has
850
+ * already decided, so it is refused instead.
851
+ */
852
+ reorderWaitingMessage(conversationId: string, messageId: string, toIndex: number): Promise<Message>;
853
+ private moveWaitingMessage;
854
+ /**
855
+ * Open the reply to a Pi steer and clear its delivery state in one write.
856
+ * The text match and the FIFO fallback both require a claimed `sending` row.
857
+ */
858
+ deliverWaitingMessage(conversationId: string, agentIdentity?: Message["agentIdentity"], messageId?: string): Promise<{
859
+ user: Message;
860
+ assistant: Message;
861
+ } | undefined>;
862
+ /**
863
+ * Opens a turn on a message that is ALREADY IN THE TRANSCRIPT: clears its delivery state, applies every
864
+ * side effect that means "a turn started here", and splices the assistant placeholder in DIRECTLY AFTER
865
+ * IT.
866
+ *
867
+ * THE INSERT POSITION IS THE WHOLE DESIGN. `push` was the old behaviour and it is only correct when the
868
+ * message being answered is the last thing in the conversation. With two messages waiting, answering
869
+ * the first by appending puts its reply BELOW the second one, so the reader sees the answer to a
870
+ * question that is still waiting - a transcript lying about its own order. Splicing at
871
+ * `indexOf(user) + 1` keeps every waiting message below the reply that belongs to the one above it.
872
+ *
873
+ * The side effects - title, `updatedAt`, `status: "waiting"`, clearing a stale failure - all describe a
874
+ * TURN rather than a message, which is why `addUserMessage` skips them for a message that is only
875
+ * waiting. They belong here, at the moment the turn genuinely begins - the model still has not
876
+ * returned a token, and that is the shape the row carries until `streamTurn` sees the first delta.
877
+ */
878
+ openTurnOnMessage(conversationId: string, messageId: string, agentIdentity?: Message["agentIdentity"]): Promise<{
879
+ user: Message;
880
+ assistant: Message;
881
+ }>;
882
+ /**
883
+ * Takes the OLDEST still-`waiting` message of this conversation, clearing its delivery state, for the
884
+ * next turn to send as its prompt.
885
+ *
886
+ * Clearing the state and taking the message are the same write on purpose: it bounds the follow-up loop
887
+ * (every pass strictly shrinks the set of waiting messages, so the loop cannot run forever even if a turn
888
+ * succeeds without consuming anything) and it is what makes the crash honest - a server that dies
889
+ * mid-turn has already taken the message out of the waiting set, so startup does not put it back, because
890
+ * it may well have been delivered.
891
+ */
892
+ takeNextWaitingMessage(conversationId: string): Promise<Message | undefined>;
893
+ /** Takes one specific waiting message by id, so an explicit user action can start it as a new turn. */
894
+ takeWaitingMessage(conversationId: string, messageId: string): Promise<Message>;
895
+ /**
896
+ * Opens a turn for a message the user chose to be answered now, when the conversation is idle.
897
+ *
898
+ * The one place that both claims a specific message and opens its turn, so there is no window between
899
+ * "the message stopped waiting" and "the turn began" in which a crash would leave a message that is
900
+ * neither waiting nor answered.
901
+ */
902
+ openTurnOnSpecificMessage(conversationId: string, messageId: string, agentIdentity?: Message["agentIdentity"]): Promise<{
903
+ user: Message;
904
+ assistant: Message;
905
+ }>;
906
+ /**
907
+ * Records a sub-agent run as `running`, BEFORE the child is spawned.
908
+ *
909
+ * The ordering is the whole point of this method existing separately from the spawn. A record created
910
+ * after the child starts cannot survive the child failing to start, and one created only at the end
911
+ * leaves nothing behind when the SERVER dies - which is the orphan startup reconciliation exists to
912
+ * clean up. Writing the claim first is what makes that orphan possible, and therefore recoverable.
913
+ *
914
+ * `unshift`, like `createConversation`: the newest run is the one a reader is looking for.
915
+ *
916
+ * Trimmed HERE rather than at read time, because the array in memory and the file on disk have to
917
+ * be the same thing - a store that kept evicted rows until the next unrelated write would put them
918
+ * back on disk, and one that trimmed on read would show a browser a roster the file still holds.
919
+ */
920
+ beginSubagentRun(run: SubagentRun): Promise<SubagentRun>;
921
+ /**
922
+ * Writes a whole plan BEFORE step one runs, and persists it.
923
+ *
924
+ * THE ORDER THIS EXISTS TO ENFORCE. A plan recorded only as it executes leaves a reload showing
925
+ * nothing recoverable - which steps were intended, in what order, under which failure policy - because
926
+ * a transcript of the model asking for a plan is not the plan. Writing it whole first makes the record
927
+ * a CLAIM the engine then makes good, exactly the relationship a run has to its child process, and it
928
+ * means an engine that dies mid-plan leaves a document a person can read instead of a gap.
929
+ *
930
+ * Steps arrive already in their pending form with empty `attempts`, rather than being built as the
931
+ * engine reaches them, so what lands on disk before anything runs is the whole intention.
932
+ *
933
+ * `structuredClone` on the way out, like `beginSubagentRun`: the engine mutates its own copy on every
934
+ * transition, and a caller holding a live reference would watch the record change under itself.
935
+ */
936
+ beginWorkflow(plan: WorkflowRun): Promise<WorkflowRun>;
937
+ /**
938
+ * Replaces a plan wholesale, and persists it.
939
+ *
940
+ * THE WHOLE PLAN RATHER THAN A FIELD PATCH, and the reason is that a plan's live state is three moving
941
+ * parts at once - `currentIndex`, the status of one step, and an appended attempt - so a patch type
942
+ * narrow enough to be safe for all three is a shape nothing could be typechecked against. Writing the
943
+ * plan also cannot forget a field, which is the failure a hand-maintained patch list invites as the
944
+ * plan grows new parts.
945
+ *
946
+ * The whole array is cloned before the write, for the same reason the recorder keeps its own copy of a
947
+ * run (`subagent-runs.ts:170`): the caller mutates the object it is about to hand back here, and a store
948
+ * that persisted by reference would write out those edits before they were ever announced.
949
+ */
950
+ setWorkflow(plan: WorkflowRun): Promise<WorkflowRun>;
951
+ setBackgroundTask(summary: AppState["backgroundTasks"][number]): Promise<void>;
952
+ backgroundTask(id: string): BackgroundTaskSummary | undefined;
953
+ checkpointBackgroundOutput(id: string, output: string, offset: number): Promise<void>;
954
+ finishBackgroundTask(taskId: string, outcome: BackgroundCompletion, content: string, deliver: boolean): Promise<Message | undefined>;
955
+ removeBackgroundTask(id: string): Promise<void>;
956
+ clearBackgroundTasks(): Promise<void>;
957
+ /**
958
+ * Writes a scheduled task - new or changed - and persists it.
959
+ *
960
+ * ONE METHOD FOR BOTH, because the two are the same write. A task that has not run and a task that
961
+ * has run are the same kind of thing with different field values, and splitting them into
962
+ * "create" and "update" would leave the caller to decide which of two paths a given change takes -
963
+ * which is exactly the kind of decision that ends up made twice, differently, in two places.
964
+ *
965
+ * The value is cloned on the way in and on the way out, like every other store method that hands a
966
+ * record back: the caller mutates its own copy freely, and the copy on disk is the copy that was
967
+ * written.
968
+ */
969
+ setScheduledTask(task: ScheduledTask): Promise<ScheduledTask>;
970
+ /**
971
+ * Removes a scheduled task, and persists the removal.
972
+ *
973
+ * AN EMPTY LIST IS STORED AS ABSENCE, for the same reason `setTodos` stores an empty todo list as
974
+ * the absence of the key: a state file that says "scheduledTasks: []" claims the user considered a
975
+ * schedule and found none, and a fresh install has never considered anything.
976
+ */
977
+ removeScheduledTask(id: string): Promise<void>;
978
+ /**
979
+ * Applies the fields a run's life can change, and nothing else.
980
+ *
981
+ * `Object.assign` is safe HERE in a way it is not in `setConversationModel`, and the difference is the
982
+ * patch's own type: `SubagentRunUpdate` is a named list of six already-narrowed fields, so there is no
983
+ * wider object for a spread to smuggle extra keys in from. `undefined` means "no such value" and is
984
+ * dropped by JSON.stringify, which is how `output`/`error`/`outputTruncated` come to be absent rather
985
+ * than stored as an empty or null one.
986
+ *
987
+ * PERSISTED ON EVERY CALL, exactly as `appendAssistantDelta` is: the record a reader sees in a
988
+ * `state` broadcast and the record on disk are then never different, and a run that is in flight is
989
+ * as durable as the conversation it belongs to.
990
+ */
991
+ setSubagentRun(runId: string, changes: SubagentRunUpdate): Promise<SubagentRun>;
992
+ updateSubagentProgress(runId: string, changes: SubagentRunUpdate): void;
993
+ checkpointSubagentProgress(runId: string): Promise<void>;
994
+ /**
995
+ * Adds ONE settled run's usage to the ledger of the conversation that dispatched it.
996
+ *
997
+ * CALLED AT THE SETTLE, ONCE PER RUN, and the run's FINAL accumulated usage is what it reads - the
998
+ * run record already holds the total of every finished message the child produced, so nothing is
999
+ * re-derived here and no message is counted twice.
1000
+ *
1001
+ * THE FLAG AND THE LEDGER ENTRY ARE WRITTEN IN ONE WRITE, and that is the whole crash-safety
1002
+ * argument: `foldRunUsage` mutates both in the same synchronous block and this persists the state
1003
+ * once, so a server that dies here cannot leave the money counted twice (flag written, entry not)
1004
+ * or not at all (entry written, flag not). A run that was folded already is left alone, so calling
1005
+ * this twice is a no-op rather than a second bill.
1006
+ *
1007
+ * IT PERSISTS THE WHOLE STATE rather than the two rows, because the two rows ARE one fact: the
1008
+ * run's flag and the conversation's ledger entry have to become true together or not at all.
1009
+ */
1010
+ accountSubagentUsage(runId: string): Promise<boolean>;
1011
+ /**
1012
+ * Replaces the model's task list, and persists it.
1013
+ *
1014
+ * WHY IT IS A FILE AND NOT PI'S MEMORY, stated once here because it is the whole justification: Pi is
1015
+ * killed unconditionally at the end of every turn (`runtime.ts`) and never writes a tool result it was
1016
+ * given by an extension anywhere durable except the session JSONL, so a list held only in the child
1017
+ * would be gone before a person could look at it - and the sidebar would empty itself at every turn
1018
+ * boundary. The list is therefore part of `state.json` and rides the existing broadcast, which is also
1019
+ * why the browser needs no channel of its own: it already repaints from `state` on every text delta.
1020
+ *
1021
+ * THE PARAMETER IS RE-NORMALIZED HERE, not trusted because the endpoint normalized it. Those are two
1022
+ * different things: `/api/todos` validates a request that crossed a socket, and this validates a value
1023
+ * handed to `setTodos` by any future caller inside this process. A method whose own contract is "call me
1024
+ * with anything" is the only version of this that cannot be broken by the next call site.
1025
+ *
1026
+ * AN EMPTY LIST IS STORED AS ABSENCE, not as `[]`. `normalizeTodos` returns `[]` for a list the model
1027
+ * emptied deliberately, and the two must not be distinguishable: the browser renders `todos: []` and
1028
+ * `todos: undefined` as the same empty state on purpose, and persisting `[]` for a store that has never
1029
+ * seen the tool would make a fresh install claim the model had considered a plan and found none. So the
1030
+ * key is deleted, which also keeps `state.json` free of a field no build before this one wrote.
1031
+ */
1032
+ setTodos(conversationId: string, raw: unknown): Promise<{
1033
+ todos: TodoItem[];
1034
+ dropped: number;
1035
+ }>;
1036
+ /**
1037
+ * Updates user-configured custom agent discovery directories.
1038
+ * Empty/whitespace paths are ignored, and if no valid paths remain, the key is deleted
1039
+ * to keep state.json clean.
1040
+ */
1041
+ setCustomAgentDirs(dirs: string[]): Promise<string[]>;
1042
+ /**
1043
+ * Writes the whole state atomically: a temp file, then a rename over the real one.
1044
+ *
1045
+ * SERIALIZED, because two conversations can genuinely run at once (see workspace-cwd.test.mjs), and
1046
+ * this method was not safe for that: every write used the SAME `${filePath}.tmp`, so two overlapping
1047
+ * persists raced and the loser's rename failed with ENOENT on a file the winner had already moved.
1048
+ * A unique name per write would hide that ENOENT while leaving the real bug in place - whichever rename
1049
+ * landed last would win, and a rename of an OLDER snapshot last would silently discard a newer one.
1050
+ * Queueing keeps both properties: one writer at a time, and last write wins with the newest state.
1051
+ *
1052
+ * A rejected write must not poison the queue, or one failure would reject every later persist as well.
1053
+ */
1054
+ flush(): Promise<void>;
1055
+ /** Releases persistence resources after all accepted writes settle. */
1056
+ close(): Promise<void>;
1057
+ private persistTransaction;
1058
+ private persistCollections;
1059
+ private persistMetadata;
1060
+ private persist;
1061
+ }
1062
+ export declare const defaultStorePath: typeof defaultJsonStatePath;