@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,469 @@
1
+ import { randomUUID } from "node:crypto";
2
+ /**
3
+ * The workflow PLAN: a tree of steps, bounded loops and primary-supplied foreach iterations. The server
4
+ * executes the tree; it never asks a sub-agent to choose the control flow. Step outputs are still carried
5
+ * into later prompts, and every rule in this file remains pure so validation and conclusion matching can
6
+ * be tested without spawning a process.
7
+ *
8
+ * The dispatch and persistence seams are the existing ones: `task-tool.ts` supplies the roster,
9
+ * `SubagentRunRecorder.dispatch` settles every child, and `WorkflowAttempt` is the append-only artefact.
10
+ * There is deliberately no graph, expression language, server-side item discovery, or second artefact store.
11
+ */
12
+ /**
13
+ * The id an orchestrated plan answers to.
14
+ *
15
+ * Prefixed and uuid-shaped for the same reason run ids are: the string is a lookup key in `state.json`
16
+ * and appears in `data-*` attributes in the browser, and a shape a person can recognise in a log is worth
17
+ * more than a bare uuid. `engine.ts` validates caller-supplied ids against this prefix the way
18
+ * `subagents.ts:358` validates run ids, because the same string becomes a reconciliation key at startup.
19
+ */
20
+ export const newWorkflowRunId = () => `wf_${randomUUID()}`;
21
+ /** Matches the shape `newWorkflowRunId` produces, for validating a caller-supplied id. */
22
+ export const WORKFLOW_ID_PATTERN = /^wf_[A-Za-z0-9_-]{1,120}$/;
23
+ /**
24
+ * How many steps one plan may hold.
25
+ *
26
+ * A bound, because every step is a real Pi process that runs for minutes and every step's output is
27
+ * carried forward: the cost of a plan grows with both its length and the size of what it accumulates.
28
+ * Eight steps is more than the pipelines this install's four sub-agents are built for (`scout` to
29
+ * `patcher` to `verifier`, maybe twice), so the bound is one a real request would not reach rather than
30
+ * one it would hit by accident.
31
+ */
32
+ export const WORKFLOW_MAX_STEPS = 8;
33
+ /** A loop always has a finite bound. The primary may lower it or explicitly raise it to this hard cap. */
34
+ export const WORKFLOW_DEFAULT_LOOP_MAX = 8;
35
+ export const WORKFLOW_MAX_LOOP_ROUNDS = 100;
36
+ /** Every accepted policy, in the order the refusal message lists them for a model that guesses wrong. */
37
+ export const WORKFLOW_FAILURE_POLICIES = ["stop", "skip", "retry:1", "retry:2", "retry:3"];
38
+ /**
39
+ * Reads a failure policy, or `undefined` for anything that is not one.
40
+ *
41
+ * `retry` alone normalizes to `retry:1`: a model that reaches for retry almost always means "try it
42
+ * again once", and refusing over a missing count would cost a retry of the plan itself. Everything else
43
+ * is refused rather than coerced, because guessing `stop` for a model that asked for `parallel` would
44
+ * silently run a different plan than the one it wrote.
45
+ */
46
+ export function parseFailurePolicy(raw) {
47
+ if (typeof raw !== "string")
48
+ return undefined;
49
+ const text = raw.trim().toLowerCase();
50
+ if (text === "retry")
51
+ return "retry:1";
52
+ return WORKFLOW_FAILURE_POLICIES.find((policy) => policy === text);
53
+ }
54
+ /** How many times a policy re-runs a failing step. `stop` and `skip` both run it zero further times. */
55
+ export function retriesFor(policy) {
56
+ const match = /^retry:([123])$/.exec(policy);
57
+ return match ? Number.parseInt(match[1], 10) : 0;
58
+ }
59
+ /**
60
+ * Caps a block of text from the FRONT, and says in the surviving text that something was dropped.
61
+ *
62
+ * THE TAIL IS WHAT SURVIVES, and that is not an arbitrary choice. Every sub-agent in `agents/` is written
63
+ * to put its conclusion last - `verifier.md` says its last line is `通过`/`失败`/`无法验证` and nothing
64
+ * else - so keeping the end of a report keeps the part the next step and the human both need. Cutting
65
+ * from the end would keep the preamble and discard the verdict, which is the one line that matters.
66
+ */
67
+ export function capText(text, budget, what) {
68
+ if (budget <= 0)
69
+ return { text: "", truncated: text.length > 0, droppedChars: text.length };
70
+ if (text.length <= budget)
71
+ return { text, truncated: false, droppedChars: 0 };
72
+ const dropped = text.length - budget;
73
+ return {
74
+ text: `…(前面 ${dropped} 个字符的${what}已省略,完整内容在 Super Pi 的运行记录里)\n${text.slice(text.length - budget)}`,
75
+ truncated: true,
76
+ droppedChars: dropped,
77
+ };
78
+ }
79
+ /** The word a PERSON reads beside a status. Colour is never the only signal, so this is not optional decoration. */
80
+ const STEP_STATUS_WORD = {
81
+ pending: "未开始",
82
+ running: "运行中",
83
+ completed: "已完成",
84
+ failed: "失败",
85
+ skipped: "已跳过",
86
+ stopped: "已停止",
87
+ };
88
+ /** As above, for a whole plan. `failed` and `stopped` differ: one ran out of steps, the other was halted. */
89
+ const WORKFLOW_STATUS_WORD = {
90
+ running: "运行中",
91
+ completed: "全部完成",
92
+ failed: "中途失败",
93
+ stopped: "已停止",
94
+ };
95
+ export const stepStatusWord = (status) => STEP_STATUS_WORD[status] ?? status;
96
+ export const workflowStatusWord = (status) => WORKFLOW_STATUS_WORD[status] ?? status;
97
+ /**
98
+ * Per-step cap on how much of one prior output is carried into the next step's prompt.
99
+ *
100
+ * Eight KB is roughly two thousand tokens of Chinese prose or a little more of code, which is enough for
101
+ * the conclusion-plus-evidence shape every sub-agent in `agents/` is instructed to produce, and small
102
+ * enough that eight of them plus the plan itself stay inside a normal model's working context.
103
+ */
104
+ export const STEP_OUTPUT_BUDGET = 8_000;
105
+ /**
106
+ * Total cap across all carried-forward output in one step's prompt.
107
+ *
108
+ * Separate from the per-step cap because the per-step one alone does not bound anything: eight steps
109
+ * carrying 8 KB each is 64 KB, which is larger than the whole context most sub-agents run with. The
110
+ * budget is spent newest-first, so the immediately preceding step - the one whose conclusion the current
111
+ * step is most likely acting on - is never the one that loses characters.
112
+ */
113
+ export const WORKFLOW_CONTEXT_BUDGET = 32_000;
114
+ /** The token that hands a step exactly the previous step's output, with nothing prepended. */
115
+ export const PREVIOUS_TOKEN = "{{previous}}";
116
+ /** The token that hands a step every prior step's output, with nothing prepended. */
117
+ export const HISTORY_TOKEN = "{{history}}";
118
+ export const ITEM_TOKEN = "{{item}}";
119
+ export const LAST_TOKEN = "{{last}}";
120
+ /** Single-pass replacement: token-looking text inside an item or prior output is data, not another expression. */
121
+ export function substituteWorkflowVariables(prompt, variables) {
122
+ return prompt.replace(/\{\{(item|last)\}\}/g, (_token, name) => variables[name] ?? "");
123
+ }
124
+ /** Exact whole-line matching against the final line. Empty or missing output is false, never an error. */
125
+ export function workflowUntilMet(output, until) {
126
+ const text = output?.trim();
127
+ if (!text)
128
+ return false;
129
+ return (text.split(/\r?\n/).at(-1)?.trim() ?? "") === until;
130
+ }
131
+ /**
132
+ * Renders one prior step as a block, or as a sentence when it has no output to hand on.
133
+ *
134
+ * A SKIPPED STEP IS SPOKEN, NOT OMITTED. Silence about a step that never ran would leave the next
135
+ * sub-agent - which has a fresh context and cannot see the plan - working from a gap it has no way to
136
+ * know about. So a skipped step contributes a line saying it was skipped, and contributes no output.
137
+ */
138
+ function renderPriorStep(step, output) {
139
+ const heading = `### 第 ${step.index + 1} 步 · ${step.label?.trim() || step.agentId}(${step.agentId})— ${stepStatusWord(step.status)}`;
140
+ if (step.status === "skipped")
141
+ return `${heading}\n(这一步按编排声明的失败策略被跳过了,没有产出。)`;
142
+ if (!output?.trim())
143
+ return `${heading}\n(这一步没有留下文字输出。)`;
144
+ return `${heading}\n${output}`;
145
+ }
146
+ /**
147
+ * Composes the prompt one step actually runs with, carrying earlier results into it.
148
+ *
149
+ * THE DEFAULT IS THE HANDOFF BLOCK, and the two tokens are the opt-outs. A model that does nothing
150
+ * special gets every prior step's output prepended, because "did the model remember to copy the last
151
+ * result forward" is not a property worth trusting a multi-step plan to. A model that WANTS control -
152
+ * wants the last output and nothing else, or wants the whole history verbatim - says so with a token,
153
+ * and in exchange the automatic block is suppressed entirely rather than being added alongside. Both
154
+ * spellings keep one rule intact: whatever this returns is the complete prompt, never a prefix that
155
+ * hides some of the instruction.
156
+ *
157
+ * AN EMPTY FIRST STEP IS THE PROMPT, VERBATIM. Composing a handoff header onto step one would tell a
158
+ * sub-agent about previous steps that do not exist, and would spend its attention on the header.
159
+ */
160
+ export function composeStepPrompt(prompt, prior) {
161
+ const own = prompt.trim();
162
+ // Steps that ran, oldest first. A pending or running step is not a result yet, and neither is a step
163
+ // beyond the one being composed - the caller passes a slice, but the filter makes the contract local.
164
+ const ran = prior.filter((step) => step.status !== "pending");
165
+ if (own.includes(HISTORY_TOKEN)) {
166
+ const filled = fillHistoryToken(own, ran);
167
+ return { prompt: filled.text, handedOff: filled.used, truncated: filled.truncated };
168
+ }
169
+ if (own.includes(PREVIOUS_TOKEN)) {
170
+ const filled = fillPreviousToken(own, ran);
171
+ return { prompt: filled.text, handedOff: filled.used, truncated: filled.truncated };
172
+ }
173
+ if (!ran.length)
174
+ return { prompt: own, handedOff: 0, truncated: false };
175
+ const { blocks, used, truncated } = budgetPrior(ran);
176
+ // Gated on BLOCKS, NOT ON OUTPUT. A skipped step contributes no output at all, so an output count of
177
+ // zero does not mean there is nothing to say - it means the one thing that must be said is that the step
178
+ // was skipped. Gating on the count would drop exactly the message a fresh-context sub-agent most needs,
179
+ // since it has no other way to learn a step was walked past. This is the bug the skip test caught.
180
+ if (!blocks.length)
181
+ return { prompt: own, handedOff: 0, truncated: false };
182
+ // Blocks are joined with a BLANK line, not a newline: each one starts with a `###` heading, and a
183
+ // heading flush against the paragraph above it does not render as a heading under most Markdown
184
+ // parsers - so the report of the step before would be swallowed into the heading. The same blank line
185
+ // after the rule keeps the model's own task from being read as part of the handoff.
186
+ const header = [
187
+ "编排上下文:下面是这个编排里前面已经跑过的步骤和它们的结论。你自己是一个全新上下文的子 agent,看不到编排本身,所以这段是你唯一的前序信息。最后才是这次派给你的活。",
188
+ "",
189
+ blocks.join("\n\n"),
190
+ "",
191
+ "--- 以下是你这次的任务 ---",
192
+ "",
193
+ "",
194
+ ].join("\n");
195
+ return { prompt: `${header}${own}`, handedOff: used, truncated };
196
+ }
197
+ /** The output a step hands forward: its LAST attempt's, because that is the one a retry corrected. */
198
+ function lastOutputOf(step) {
199
+ for (let index = step.attempts.length - 1; index >= 0; index -= 1) {
200
+ const output = step.attempts[index]?.output;
201
+ if (output?.trim())
202
+ return output;
203
+ }
204
+ return undefined;
205
+ }
206
+ /**
207
+ * Spends the context budget across prior steps, newest first, and renders the survivors oldest-first.
208
+ *
209
+ * NEWEST FIRST IS THE ALLOCATION ORDER, and it is also why a long plan degrades gracefully rather than
210
+ * dropping its most recent context. A plan whose earlier steps produced large reports keeps its tail
211
+ * intact and loses its preamble, which is the right thing to lose: step seven acting on step six's
212
+ * conclusion does not need step one's full output, and step two acting on step one already happened
213
+ * while the budget still had room.
214
+ */
215
+ function budgetPrior(ran) {
216
+ let remaining = WORKFLOW_CONTEXT_BUDGET;
217
+ const chosen = new Map();
218
+ let used = 0;
219
+ let truncated = false;
220
+ for (let index = ran.length - 1; index >= 0 && remaining > 0; index -= 1) {
221
+ const step = ran[index];
222
+ const output = lastOutputOf(step);
223
+ if (!output?.trim()) {
224
+ // Still renders - as the "no output" or "was skipped" line - but spends no budget, because a line
225
+ // that says nothing took nothing.
226
+ chosen.set(index, { output: "", truncated: false });
227
+ continue;
228
+ }
229
+ const capped = capText(output, Math.min(STEP_OUTPUT_BUDGET, remaining), "前序输出");
230
+ if (!capped.text.trim())
231
+ continue;
232
+ truncated ||= capped.truncated;
233
+ chosen.set(index, { output: capped.text, truncated: capped.truncated });
234
+ remaining -= capped.text.length;
235
+ used += 1;
236
+ }
237
+ const blocks = [];
238
+ for (let index = 0; index < ran.length; index += 1) {
239
+ const entry = chosen.get(index);
240
+ // A step whose output did not fit the budget is dropped from the rendered block entirely rather
241
+ // than rendered with nothing in it, which would read as "this step produced no conclusion".
242
+ if (entry === undefined) {
243
+ truncated = true;
244
+ continue;
245
+ }
246
+ blocks.push(renderPriorStep(ran[index], entry.output || undefined));
247
+ }
248
+ return { blocks, used, truncated };
249
+ }
250
+ /**
251
+ * Replaces `{{previous}}` with the output of the single nearest preceding step that produced any.
252
+ *
253
+ * NEAREST, NOT ALL, because the token's name is a promise: a model that wrote `{{previous}}` asked for the
254
+ * last result, and quietly handing it the whole plan instead would be the same surprise as prepending a
255
+ * block it declined. A skipped step does not count as the previous step for this purpose - it has no
256
+ * output - so the search walks back to the nearest step that has one, and the rendered header still says
257
+ * which step it was, so the gap in the numbering is visible rather than inferred.
258
+ *
259
+ * The token is REPLACED EVEN WHEN THERE IS NOTHING TO REPLACE IT WITH. Leaving a literal `{{previous}}`
260
+ * in front of a sub-agent would read as an instruction it cannot satisfy; saying plainly that the first
261
+ * step has nothing before it is the honest version of the same fact.
262
+ */
263
+ function fillPreviousToken(prompt, ran) {
264
+ const nearest = [...ran].reverse().find((step) => Boolean(lastOutputOf(step)?.trim()));
265
+ if (!nearest) {
266
+ return { text: prompt.split(PREVIOUS_TOKEN).join("(这是编排的第一步,前面还没有上一步的产出。)"), used: 0, truncated: false };
267
+ }
268
+ const output = lastOutputOf(nearest) ?? "";
269
+ const capped = capText(output, STEP_OUTPUT_BUDGET, "上一步输出");
270
+ return { text: prompt.split(PREVIOUS_TOKEN).join(renderPriorStep(nearest, capped.text)), used: 1, truncated: capped.truncated };
271
+ }
272
+ /**
273
+ * Replaces `{{history}}` with every prior step, under the same budget the default block uses.
274
+ *
275
+ * Shares `budgetPrior` with the default path on purpose: the two spellings of "hand me what came before"
276
+ * must not be able to disagree about what fits, or a model that chose the explicit token would get a
277
+ * different conversation than one that took the default for the same plan.
278
+ */
279
+ function fillHistoryToken(prompt, ran) {
280
+ const { blocks, used, truncated } = budgetPrior(ran);
281
+ const replacement = blocks.join("\n\n");
282
+ return { text: replacement ? prompt.split(HISTORY_TOKEN).join(replacement) : prompt.split(HISTORY_TOKEN).join("(这是编排的第一步,前面还没有任何产出。)"), used, truncated };
283
+ }
284
+ /** Validates the complete tree before the engine can allocate even its first pending execution row. */
285
+ function validateRecursivePlan(body, roster) {
286
+ const ids = roster.map((entry) => entry.id);
287
+ const available = ids.length ? ids.join(", ") : "(none)";
288
+ const onFailure = body.onFailure === undefined ? "stop" : parseFailurePolicy(body.onFailure);
289
+ if (!onFailure)
290
+ return { refusal: `workflow.onFailure must be one of ${WORKFLOW_FAILURE_POLICIES.join(", ")}, or "retry" on its own for a single retry. Got ${JSON.stringify(body.onFailure)}. "stop" is used when you leave it out.` };
291
+ if (!Array.isArray(body.nodes))
292
+ return { refusal: `workflow.nodes must be an array of at least one step, loop or foreach node. Got ${body.nodes === undefined ? "nothing" : typeof body.nodes}.` };
293
+ if (!body.nodes.length)
294
+ return { refusal: "workflow.nodes was empty. A workflow needs at least one node; for a single sub-agent, call the task tool instead." };
295
+ const steps = [];
296
+ const visit = (raw, where) => {
297
+ if (typeof raw !== "object" || raw === null)
298
+ return { refusal: `${where} must be a step, loop or foreach object. Got ${raw === null ? "null" : typeof raw}.` };
299
+ const entry = raw;
300
+ if (entry.kind === "step") {
301
+ const agentId = typeof entry.agentId === "string" ? entry.agentId.trim() : "";
302
+ if (!agentId)
303
+ return { refusal: `${where}.agentId is required. Dispatchable sub-agents: ${available}.` };
304
+ if (!ids.includes(agentId))
305
+ return { refusal: `${JSON.stringify(agentId)} is not a dispatchable sub-agent (${where}.agentId). Dispatchable sub-agents: ${available}. Pick one of those, or call the task tool directly for a single delegation.` };
306
+ const prompt = typeof entry.prompt === "string" ? entry.prompt.trim() : "";
307
+ if (!prompt)
308
+ return { refusal: `${where}.prompt is required and must not be empty: the sub-agent starts with a fresh context, so this is everything it will know about the work.` };
309
+ const label = typeof entry.label === "string" ? entry.label.trim() : "";
310
+ steps.push({ agentId, prompt, ...(label ? { label } : {}) });
311
+ return { node: { kind: "step", agentId, prompt, ...(label ? { label } : {}) } };
312
+ }
313
+ if (entry.kind === "loop") {
314
+ const until = typeof entry.until === "string" ? entry.until.trim() : "";
315
+ if (!until)
316
+ return { refusal: `${where}.until is required: write the exact conclusion line the server should match, for example "通过".` };
317
+ const max = entry.max === undefined ? WORKFLOW_DEFAULT_LOOP_MAX : entry.max;
318
+ if (typeof max !== "number" || !Number.isInteger(max) || max < 1 || max > WORKFLOW_MAX_LOOP_ROUNDS) {
319
+ return { refusal: `${where}.max must be an integer from 1 to ${WORKFLOW_MAX_LOOP_ROUNDS}. Leave it out for the default of ${WORKFLOW_DEFAULT_LOOP_MAX}.` };
320
+ }
321
+ if (!Array.isArray(entry.do) || !entry.do.length)
322
+ return { refusal: `${where}.do must be a non-empty array of nodes; a loop body may contain several steps, loops or foreaches.` };
323
+ const children = [];
324
+ for (let index = 0; index < entry.do.length; index += 1) {
325
+ const child = visit(entry.do[index], `${where}.do[${index}]`);
326
+ if (!child.node)
327
+ return { refusal: child.refusal ?? `${where} is invalid.` };
328
+ children.push(child.node);
329
+ }
330
+ return { node: { kind: "loop", until, max, do: children } };
331
+ }
332
+ if (entry.kind === "foreach") {
333
+ if (!Array.isArray(entry.items) || !entry.items.length) {
334
+ return { refusal: `${where}.items must be a non-empty string array supplied by the primary agent. The server never discovers a foreach list; a foreach without items is refused.` };
335
+ }
336
+ const items = [];
337
+ for (let index = 0; index < entry.items.length; index += 1) {
338
+ const item = entry.items[index];
339
+ if (typeof item !== "string" || !item.trim())
340
+ return { refusal: `${where}.items[${index}] must be a non-empty string explicitly supplied by the primary agent.` };
341
+ items.push(item);
342
+ }
343
+ if (!Array.isArray(entry.do) || !entry.do.length)
344
+ return { refusal: `${where}.do must be a non-empty array of nodes to run once for each primary-supplied item.` };
345
+ const children = [];
346
+ for (let index = 0; index < entry.do.length; index += 1) {
347
+ const child = visit(entry.do[index], `${where}.do[${index}]`);
348
+ if (!child.node)
349
+ return { refusal: child.refusal ?? `${where} is invalid.` };
350
+ children.push(child.node);
351
+ }
352
+ return { node: { kind: "foreach", items, do: children } };
353
+ }
354
+ return { refusal: `${where}.kind must be exactly "step", "loop" or "foreach". Got ${JSON.stringify(entry.kind)}.` };
355
+ };
356
+ const nodes = [];
357
+ for (let index = 0; index < body.nodes.length; index += 1) {
358
+ const result = visit(body.nodes[index], `workflow.nodes[${index}]`);
359
+ if (!result.node)
360
+ return { refusal: result.refusal ?? `workflow.nodes[${index}] is invalid.` };
361
+ nodes.push(result.node);
362
+ if (steps.length > WORKFLOW_MAX_STEPS)
363
+ return { refusal: `workflow.nodes declares more than ${WORKFLOW_MAX_STEPS} step nodes and the limit is ${WORKFLOW_MAX_STEPS}. Shorten the plan, or split it into two workflows.` };
364
+ }
365
+ const summary = typeof body.summary === "string" && body.summary.trim() ? body.summary.trim().slice(0, 200) : `${steps.length} 步编排`;
366
+ return { plan: { summary, onFailure, steps, nodes } };
367
+ }
368
+ /**
369
+ * Checks an untrusted plan body against the roster that may actually be dispatched.
370
+ *
371
+ * VALIDATES, NEVER REWRITES, THE AGENT LIST. `agentId` is matched against the roster rather than
372
+ * defaulted, because defaulting would run a different sub-agent than the model asked for - a plan that
373
+ * silently substituted `patcher` for a misspelled `patchre` would edit files on a read-only request.
374
+ * The roster arrives already filtered to `mode: subagent` and non-hidden (`task-tool.ts:88`), so a
375
+ * primary agent's id is refused here by the same rule that refuses it at dispatch time
376
+ * (`subagents.ts:368`) - one lock, consulted twice, rather than a second list that could drift.
377
+ */
378
+ export function validateWorkflowPlan(raw, roster) {
379
+ const ids = roster.map((entry) => entry.id);
380
+ const available = ids.length ? ids.join(", ") : "(none)";
381
+ if (typeof raw !== "object" || raw === null)
382
+ return { refusal: `A workflow must be an object with "summary", "onFailure" and "steps". Got ${raw === null ? "null" : typeof raw}.` };
383
+ const body = raw;
384
+ if (body.nodes !== undefined) {
385
+ if (body.steps !== undefined)
386
+ return { refusal: "workflow accepts either legacy `steps` or recursive `nodes`, not both. Send one plan shape so there is only one execution order." };
387
+ return validateRecursivePlan(body, roster);
388
+ }
389
+ const rawSteps = body.steps;
390
+ if (!Array.isArray(rawSteps))
391
+ return { refusal: `workflow.steps must be an array of at least 1 and at most ${WORKFLOW_MAX_STEPS} steps. Got ${rawSteps === undefined ? "nothing" : typeof rawSteps}.` };
392
+ if (rawSteps.length < 1)
393
+ return { refusal: "workflow.steps was empty. A workflow needs at least one step; for a single sub-agent, call the task tool instead." };
394
+ if (rawSteps.length > WORKFLOW_MAX_STEPS)
395
+ return { refusal: `workflow.steps holds ${rawSteps.length} steps and the limit is ${WORKFLOW_MAX_STEPS}. Shorten the plan, or split it into two workflows and use background dispatch for the parts that are independent.` };
396
+ const onFailure = body.onFailure === undefined ? "stop" : parseFailurePolicy(body.onFailure);
397
+ if (!onFailure)
398
+ return { refusal: `workflow.onFailure must be one of ${WORKFLOW_FAILURE_POLICIES.join(", ")}, or "retry" on its own for a single retry. Got ${JSON.stringify(body.onFailure)}. "stop" is used when you leave it out.` };
399
+ const steps = [];
400
+ for (let index = 0; index < rawSteps.length; index += 1) {
401
+ const entry = rawSteps[index];
402
+ const where = `workflow.steps[${index}]`;
403
+ if (typeof entry !== "object" || entry === null)
404
+ return { refusal: `${where} must be an object with "agentId" and "prompt". Got ${entry === null ? "null" : typeof entry}.` };
405
+ const step = entry;
406
+ const agentId = typeof step.agentId === "string" ? step.agentId.trim() : "";
407
+ if (!agentId)
408
+ return { refusal: `${where}.agentId is required. Dispatchable sub-agents: ${available}.` };
409
+ if (!ids.includes(agentId))
410
+ return { refusal: `${JSON.stringify(agentId)} is not a dispatchable sub-agent (${where}.agentId). Dispatchable sub-agents: ${available}. Pick one of those, or call the task tool directly for a single delegation.` };
411
+ const prompt = typeof step.prompt === "string" ? step.prompt.trim() : "";
412
+ if (!prompt)
413
+ return { refusal: `${where}.prompt is required and must not be empty: the sub-agent starts with a fresh context, so this is everything it will know about the work.` };
414
+ const label = typeof step.label === "string" ? step.label.trim() : "";
415
+ steps.push({ agentId, prompt, ...(label ? { label } : {}) });
416
+ }
417
+ // Defaulted rather than refused. The summary is a heading for a human, and a model that wrote three
418
+ // good steps but no summary has still written a runnable plan; refusing would spend a whole retry on
419
+ // a field that exists to be pretty.
420
+ const summary = typeof body.summary === "string" && body.summary.trim() ? body.summary.trim().slice(0, 200) : `${steps.length} 步编排`;
421
+ return { plan: { summary, onFailure, steps } };
422
+ }
423
+ /**
424
+ * Reduces a persisted plan to what the primary agent is told when the workflow returns.
425
+ *
426
+ * ONE ATTEMPT PER STEP, THE LAST ONE. The earlier attempts stay in the run records and on the timeline,
427
+ * which is where a person debugging a retried plan looks; putting all of them in the envelope would make
428
+ * the model re-read a failure it has already acted on.
429
+ */
430
+ export function workflowSummary(plan) {
431
+ return {
432
+ id: plan.id,
433
+ summary: plan.summary,
434
+ status: plan.status,
435
+ onFailure: plan.onFailure,
436
+ steps: plan.steps.map((step) => {
437
+ const last = step.attempts[step.attempts.length - 1];
438
+ return {
439
+ n: step.index + 1,
440
+ agentId: step.agentId,
441
+ ...(step.label ? { label: step.label } : {}),
442
+ status: step.status,
443
+ attempts: step.attempts.length,
444
+ ...(last?.output !== undefined ? { output: last.output, ...(last.outputTruncated ? { outputTruncated: true } : {}) } : {}),
445
+ ...(last?.error ? { error: last.error } : {}),
446
+ };
447
+ }),
448
+ ...(plan.finishedAt ? { finishedAt: plan.finishedAt } : {}),
449
+ };
450
+ }
451
+ /**
452
+ * The step a settled run became, as an attempt record.
453
+ *
454
+ * The narrow seam between the run recorder and this engine: everything about spawning, streaming and
455
+ * process teardown is the recorder's, and the only thing that crosses here is the settled record it
456
+ * always resolves with (`subagent-runs.ts:159`). `output` is copied rather than referenced because the
457
+ * store hands out clones, and a plan that kept a live reference would read whatever the run wrote next.
458
+ */
459
+ export function attemptFromRun(run, n) {
460
+ return {
461
+ n,
462
+ runId: run.id,
463
+ status: run.status === "completed" ? "completed" : run.status === "stopped" ? "stopped" : "failed",
464
+ ...(run.output !== undefined ? { output: run.output, ...(run.outputTruncated ? { outputTruncated: true } : {}) } : {}),
465
+ startedAt: run.startedAt,
466
+ ...(run.finishedAt ? { finishedAt: run.finishedAt } : {}),
467
+ ...(run.error ? { error: run.error } : {}),
468
+ };
469
+ }
@@ -0,0 +1,2 @@
1
+ import type { ServerContext } from "./server-context.js";
2
+ export declare function updateExplorerIndexes(context: Pick<ServerContext, "fileIndexes" | "nameIndexes">, workspaceId: string, workspaceRoot: string, path: string, previousPath: string | undefined, directory: boolean, removed: boolean): Promise<void>;
@@ -0,0 +1,61 @@
1
+ import { readdir } from "node:fs/promises";
2
+ import { belowPath, inScope } from "./file-index.js";
3
+ import { createRootGuard } from "./files.js";
4
+ import { explorerInternalPath } from "./workspace-file-operations.js";
5
+ export async function updateExplorerIndexes(context, workspaceId, workspaceRoot, path, previousPath, directory, removed) {
6
+ const files = [...(context.fileIndexes?.values() ?? [])].filter(index => index.workspaceId === workspaceId);
7
+ const names = [...(context.nameIndexes?.values() ?? [])].filter(index => index.workspaceId === workspaceId);
8
+ if (!files.length && !names.length)
9
+ return;
10
+ if (previousPath !== undefined) {
11
+ for (const index of [...files, ...names]) {
12
+ const scoped = inScope(workspaceRoot, index.cwd, previousPath);
13
+ if (scoped !== undefined)
14
+ index.removeTree(scoped);
15
+ else if (belowPath(index.cwd, previousPath))
16
+ index.removeTree("");
17
+ }
18
+ }
19
+ if (removed)
20
+ return;
21
+ if (!directory) {
22
+ for (const index of names) {
23
+ const scoped = inScope(workspaceRoot, index.cwd, path);
24
+ if (scoped)
25
+ index.upsert(scoped);
26
+ }
27
+ await Promise.all(files.map(index => {
28
+ const scoped = inScope(workspaceRoot, index.cwd, path);
29
+ return scoped ? index.refresh(scoped) : undefined;
30
+ }));
31
+ return;
32
+ }
33
+ const guard = createRootGuard(workspaceRoot);
34
+ const folders = [path];
35
+ const entries = [{ path, kind: "directory" }];
36
+ for (let cursor = 0; cursor < folders.length && cursor < 4000 && entries.length < 30000; cursor += 1) {
37
+ const folder = folders[cursor];
38
+ const children = await guard(folder).then(absolute => readdir(absolute, { withFileTypes: true })).catch(() => []);
39
+ for (const child of children) {
40
+ const childPath = `${folder}/${child.name}`;
41
+ if (explorerInternalPath(childPath) || (!child.isDirectory() && !child.isFile()))
42
+ continue;
43
+ entries.push({ path: childPath, kind: child.isDirectory() ? "directory" : "file" });
44
+ if (child.isDirectory())
45
+ folders.push(childPath);
46
+ if (entries.length >= 30000)
47
+ break;
48
+ }
49
+ }
50
+ for (const index of names)
51
+ for (const entry of entries) {
52
+ const scoped = inScope(workspaceRoot, index.cwd, entry.path);
53
+ if (scoped)
54
+ index.upsert(scoped, entry.kind);
55
+ }
56
+ for (const index of files)
57
+ index.recordEntries(entries.flatMap(entry => {
58
+ const scoped = inScope(workspaceRoot, index.cwd, entry.path);
59
+ return scoped ? [{ ...entry, path: scoped }] : [];
60
+ }));
61
+ }
@@ -0,0 +1,36 @@
1
+ declare const MAX_INITIAL_CONTENT: number;
2
+ export declare function serializeWorkspaceWrite<T>(workspace: string, work: () => Promise<T>): Promise<T>;
3
+ export type FileTreeMutation = {
4
+ path: string;
5
+ previousPath?: string;
6
+ removed?: boolean;
7
+ directory?: boolean;
8
+ text?: boolean;
9
+ trashId?: string;
10
+ };
11
+ export declare function explorerInternalPath(path: string): boolean;
12
+ export declare function explorerPath(workspace: string, root: string, path: string, allowRoot?: boolean): Promise<string>;
13
+ export declare function listWorkspaceTrash(workspace: string, root: string): Promise<{
14
+ deletedAt: string;
15
+ directory: boolean;
16
+ id: string;
17
+ path: string;
18
+ }[]>;
19
+ export declare function mutateWorkspaceTree(workspace: string, root: string, body: Record<string, unknown>): Promise<FileTreeMutation>;
20
+ export declare function inspectWorkspaceUpload(workspace: string, root: string, parent: string, name: string): Promise<{
21
+ exists: boolean;
22
+ replaceable?: undefined;
23
+ meta?: undefined;
24
+ } | {
25
+ exists: boolean;
26
+ replaceable: boolean;
27
+ meta?: undefined;
28
+ } | {
29
+ exists: boolean;
30
+ replaceable: boolean;
31
+ meta: import("./files.js").FileMeta;
32
+ }>;
33
+ export declare function uploadWorkspaceFile(workspace: string, root: string, parent: string, name: string, bytes: Buffer, baseEtag?: string): Promise<{
34
+ path: string;
35
+ }>;
36
+ export { MAX_INITIAL_CONTENT as MAX_WORKSPACE_UPLOAD_BYTES };