@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,619 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdir, stat } from "node:fs/promises";
4
+ import { join, resolve } from "node:path";
5
+ import { agentSpawnArgs, readAgents, toolSelection } from "./agents.js";
6
+ import { nativeToolEnv, nativeToolPolicy, nativeToolSettingsPath, nativeToolExtensionPath, readNativeToolSettings } from "./native-tool-settings.js";
7
+ import { resolvePiCommand, shellQuote } from "./pi-command.js";
8
+ import { buildExtensionUiResponse, describeExtensionUiRequest, closePiWorker, } from "./runtime.js";
9
+ import { RpcChannel } from "./rpc-channel.js";
10
+ import { InlineThinkingSplitter, stripInlineThinking } from "./inline-thinking.js";
11
+ import { describeToolCall, extractPartialResultText, TOOL_DETAIL_CAP } from "./tool-calls.js";
12
+ /**
13
+ * The tool-call derivation now lives in `tool-calls.js`, because the primary agent's runtime needs the
14
+ * identical mapping and `subagents.ts` already imports `runtime.ts` - so the shared definition has to sit
15
+ * below both of them.
16
+ *
17
+ * RE-EXPORTED rather than moved silently. `scripts/agent-vis-records.test.mjs` imports both of these from
18
+ * this module, and a card that quietly lost its only derivation would still typecheck. Keeping the names
19
+ * exported here means that test keeps pointing at the one definition that also serves a call block.
20
+ */
21
+ export { describeToolCall, TOOL_DETAIL_CAP };
22
+ /**
23
+ * Spawning and draining ONE child Pi, per [docs/SUBAGENT-DESIGN.md](../docs/SUBAGENT-DESIGN.md) §4.
24
+ * No records, no events, no store: this file's whole job is that a `mode: subagent` definition becomes a
25
+ * real OS process whose text comes back as a stream and a final answer. What the browser does with that
26
+ * is a later step, and keeping it out is why `run()` returns a value instead of emitting one.
27
+ *
28
+ * The mechanism is the primary agent's, reused rather than reinvented: the same `readAgents` /
29
+ * `agentSpawnArgs`, the same `resolvePiCommand` / `shellQuote` resolution, the same `RpcChannel` and
30
+ * JSONL drain loop, the same `killTree`. A sub-agent is the same thing one layer down.
31
+ */
32
+ /** How long the drain loop waits for a record before re-checking the child and the caller's signal. */
33
+ const DRAIN_POLL_MS = 100;
34
+ /**
35
+ * The run id every dispatch gets unless a caller supplies one: `sub_<uuid>`, and Pi's `--session-id`
36
+ * alongside it. Exported so a caller that must know the id BEFORE the spawn - the recorder, which has to
37
+ * write a `running` row before the child exists - generates exactly the id this would have generated.
38
+ */
39
+ export const newSubagentRunId = () => `sub_${randomUUID()}`;
40
+ /** Token/cost usage for a run that produced no finished message. */
41
+ const NO_USAGE = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
42
+ /**
43
+ * Pi's session records that ARE part of one turn's lifecycle, so this supervisor has nothing to do with
44
+ * them, and so announcing them once per distinct type and then tallying the rest turns an ordinary run
45
+ * into a thousand warnings.
46
+ *
47
+ * THE CRITERION IS "WE KNOW EXACTLY WHAT THIS IS", not "it is noisy" and not "we are bored of it". Each
48
+ * name below is a member of Pi's own published `AgentSessionEvent` union, and every one of them arrives on
49
+ * every single run: `session.subscribe((event) => output(toJsonEvent(event)))` forwards the union
50
+ * unfiltered (modes/rpc/rpc-mode.ts:355-356), so a host that acts on a handful of them and treats the rest
51
+ * as silence is the only possible design here. Membership is therefore a CLAIM about Pi's protocol, and
52
+ * `scripts/subagent-noise.test.mjs` is what keeps the claim honest in both directions: a fake Pi emitting
53
+ * this whole set must produce no warning, and a fake Pi emitting a type that is NOT in it must still
54
+ * produce one. That second half is the point - the day Pi adds a record here, it lands in the tally
55
+ * instead of vanishing (the failure mode R2 §4.3/P1-1 records: a record dropped silently makes a protocol
56
+ * change look like it worked).
57
+ *
58
+ * What is deliberately NOT in this set, even though Pi documents all of it: `queue_update`,
59
+ * `compaction_start` / `compaction_end`, `auto_retry_start` / `auto_retry_end`, `summarization_retry_*`,
60
+ * `bash_execution_update`, `session_info_changed`, `thinking_level_changed`. Those are known too, but
61
+ * this supervisor has no answer for them - a compacted or retried run is a run whose answer a caller
62
+ * should distrust, and R2 P1-1 names `queue_update` as exactly the record a future feature must consume
63
+ * rather than have quietly swallowed. "We know what it is" is the necessary condition for exemption here;
64
+ * it is not sufficient, and these keep announcing until something actually handles them.
65
+ */
66
+ const KNOWN_LIFECYCLE_RECORDS = new Set([
67
+ // Pi's own framing of a run, one pair per child (packages/agent/src/types.ts:518-519). The bookends
68
+ // carry no information this supervisor can use, and `agent_end` carries every message in the transcript,
69
+ // which by contract Super Pi never reads - see `run()`'s "Pi owns the directory".
70
+ "agent_start",
71
+ "agent_end",
72
+ // The turn and message boundaries AROUND the records this loop does act on. `turn_end` is where Pi
73
+ // finishes a turn and `message_start` / `message_end` bracket every message; the loop needs none of
74
+ // them because it tracks the assistant message through the inner `start` / `done` events instead
75
+ // (modes/json-event.ts:40-44 says the same: "message_start provides the initial message, deltas build
76
+ // it, and message_end provides the final authoritative message").
77
+ "turn_start",
78
+ "turn_end",
79
+ "message_start",
80
+ "message_end",
81
+ // The rest of ONE tool call's lifecycle. `tool_execution_start` is handled and reported as the tool
82
+ // line; these two are the same call's progress and result, carrying `partialResult` / `result` payloads
83
+ // that `SubagentToolCall` deliberately drops because they can be large and can hold file contents. One
84
+ // line per call is the whole contract, so two more records per call is pure repetition.
85
+ "tool_execution_update",
86
+ "tool_execution_end",
87
+ // Pi telling us it appended an entry to the transcript it owns. Same contract as `agent_end`: Super Pi
88
+ // never reads Pi's transcript, so there is nothing to do with an entry-level receipt.
89
+ "entry_appended",
90
+ ]);
91
+ /**
92
+ * The inner events of a `message_update` that are part of an assistant message's construction, for the
93
+ * same reason and under the same criterion as `KNOWN_LIFECYCLE_RECORDS` - every name is a member of Pi's
94
+ * published `AssistantMessageEvent` union (packages/ai/src/types.ts:788-804) minus `partial`, and each one
95
+ * fires on every run. The union's members the loop DOES consume are `start`, `text_delta`, `done` and
96
+ * `error`; these are the rest.
97
+ */
98
+ const KNOWN_LIFECYCLE_EVENTS = new Set([
99
+ // The boundaries of the very `text_delta` stream this loop accumulates. Real Pi emits a `text_start` /
100
+ // `text_end` pair around EVERY text block, so a run with one paragraph per turn emits two of these per
101
+ // turn for output the loop already has.
102
+ "text_start",
103
+ "text_end",
104
+ // The model's reasoning stream, as a whole lifecycle rather than just its `thinking_delta` - one real
105
+ // run logged 1449 of them, which is one per token of thought. Nothing here is a bug or a protocol
106
+ // surprise; this supervisor's contract is `finalText`, not the model's private thinking.
107
+ // ROADMAP NOTE: if thinking ever becomes part of a sub-agent card, this is where it is plumbed in -
108
+ // accumulate the deltas and render them - and THAT change should move these three out of this set
109
+ // deliberately, at the same time as it teaches the UI to show them. Until then they are known and
110
+ // deliberately unused, which is different from unknown.
111
+ "thinking_start",
112
+ "thinking_delta",
113
+ "thinking_end",
114
+ // A tool call being assembled inside the message. The tool LINE this supervisor reports comes from the
115
+ // outer `tool_execution_start`, which carries the authoritative `toolCallId` and `toolName`; these three
116
+ // are the incremental JSON of arguments the loop deliberately does not keep.
117
+ "toolcall_start",
118
+ "toolcall_delta",
119
+ "toolcall_end",
120
+ ]);
121
+ /**
122
+ * A run that ended because the caller aborted it.
123
+ *
124
+ * A named error rather than a message a caller has to pattern-match, because "the user pressed stop" and
125
+ * "the child failed" are different outcomes for whoever reports this run later, and collapsing them into
126
+ * one rejected promise would force that decision back out of string matching.
127
+ */
128
+ export class SubagentCancelled extends Error {
129
+ runId;
130
+ constructor(runId) {
131
+ super(`sub-agent run ${runId} was cancelled before it settled`);
132
+ this.runId = runId;
133
+ this.name = "SubagentCancelled";
134
+ }
135
+ }
136
+ /**
137
+ * The text of one assistant message: its FIRST text block, exactly as the reference implementation reads
138
+ * it (examples/extensions/subagent/index.ts:170-180). A message whose only content is a tool call has no
139
+ * text, so "" is a real answer here rather than a failure.
140
+ */
141
+ const textOf = (part) => part !== null && typeof part === "object" && part.type === "text" && typeof part.text === "string"
142
+ ? part.text
143
+ : undefined;
144
+ const assistantText = (message) => {
145
+ const content = message?.content;
146
+ if (!Array.isArray(content))
147
+ return "";
148
+ for (const part of content) {
149
+ const text = textOf(part);
150
+ if (text !== undefined)
151
+ return text;
152
+ }
153
+ return "";
154
+ };
155
+ /**
156
+ * Adds one finished message's usage into the run total.
157
+ *
158
+ * Read ONLY on `done`, never on a delta: Pi repeats the same per-message usage on every update of that
159
+ * message (modes/json-event.ts:56), so summing per delta would count a message's tokens once per token
160
+ * in it. `cost` is `usage.cost.total`, the provider's own number rather than a re-derivation of it.
161
+ */
162
+ const addUsage = (total, usage) => {
163
+ total.input += usage?.input ?? 0;
164
+ total.output += usage?.output ?? 0;
165
+ total.cacheRead += usage?.cacheRead ?? 0;
166
+ total.cacheWrite += usage?.cacheWrite ?? 0;
167
+ total.cost += usage?.cost?.total ?? 0;
168
+ total.turns += 1;
169
+ };
170
+ /** Spawns sub-agent children Pi and drains their JSONL RPC streams. */
171
+ export class SubagentSupervisor {
172
+ sessionDir;
173
+ agents;
174
+ memory;
175
+ setMemory(memory) { this.memory = memory; }
176
+ pi;
177
+ /** Live children by run id, so a caller can name the process it means. Cleared in the run's `finally`. */
178
+ children = new Map();
179
+ /**
180
+ * `command` and `agents` are the same two override points `PiRpcRuntime` takes, and for the same
181
+ * reasons: a test needs to launch a fake peer, and a Pi installed somewhere unusual needs to be
182
+ * reachable. `Pi` is resolved once, because a resolution that could change mid-run would make one
183
+ * child's spawn line depend on when it was started.
184
+ */
185
+ modelValidator;
186
+ setModelValidator(validator) { this.modelValidator = validator; }
187
+ constructor(sessionDir, command, agents = { dir: join(sessionDir, "agents"), promptDir: join(sessionDir, "agent-prompts") }) {
188
+ this.sessionDir = sessionDir;
189
+ this.agents = agents;
190
+ this.pi = resolvePiCommand({ command });
191
+ if (!this.pi.found)
192
+ console.warn(`SubagentSupervisor: ${this.pi.reason}`);
193
+ }
194
+ /**
195
+ * Every child this supervisor still owns, optionally narrowed to one conversation.
196
+ *
197
+ * A live view rather than a returned handle, because the caller cannot have the id before the run:
198
+ * `run()` returns the RESULT, and a stop button needs the pid while the promise is still pending.
199
+ * Deleted as soon as the child is gone, so a caller that polls it sees the truth rather than a
200
+ * remembered one.
201
+ */
202
+ liveRuns(conversationId) {
203
+ return [...this.children].map(([id, run]) => ({ id, conversationId: run.conversationId, pid: run.child.pid }));
204
+ }
205
+ setAgentsDir(dir) {
206
+ this.agents.dir = dir;
207
+ }
208
+ /**
209
+ * Runs one sub-agent to completion and returns what it said.
210
+ *
211
+ * The three spawn-time decisions, all of which the design fixes rather than leaves open:
212
+ *
213
+ * - `--mode rpc`, NOT the reference implementation's `--mode json -p`. In print mode a child that
214
+ * wants to ask something has nowhere to ask and hangs; in RPC mode its questions arrive as
215
+ * `extension_ui_request` records on the channel Super Pi already owns. That is the whole reason this
216
+ * supervisor exists instead of shipping Pi's extension.
217
+ * - `--session-dir` shared by every child, `--session-id` unique per run, so Pi owns the directory and
218
+ * Super Pi never has to read a transcript it could only misread.
219
+ * - `agentSpawnArgs` verbatim, so a sub-agent's tool allowlist and prompt go through the one proven
220
+ * translation rather than a second hand-rolled one.
221
+ *
222
+ * The TASK goes over RPC stdin, never on argv. The reference passes it as a positional argument, which
223
+ * under `shell: true` on Windows is cmd.exe's to parse: an ampersand or a pipe in a model's own words
224
+ * becomes a command. `{ type: "prompt" }` is exactly how the primary agent is already prompted, so
225
+ * this costs nothing and removes the whole class of bug.
226
+ */
227
+ async run(input) {
228
+ const { conversationId, agentId, task, cwd, model, host, signal, onTextDelta, onToolCall, onToolUpdate, onToolEnd, onThinking, onStage } = input;
229
+ // Refused here, with the reason, rather than handed to the spawn: an ENOENT from `spawn` reads as
230
+ // "the app is broken" and hides the one fact that matters, which is where it looked for Pi.
231
+ if (!this.pi.found)
232
+ throw new Error(this.pi.reason);
233
+ if (!task.trim())
234
+ throw new Error(`sub-agent ${JSON.stringify(agentId)} was dispatched with an empty task`);
235
+ // The caller's id, or the one this would have made. Refused rather than sanitised: a mangled id
236
+ // would still spawn, still write a Pi transcript, and still be unreconcilable at the next startup.
237
+ const supplied = input.id;
238
+ if (supplied !== undefined && !/^sub_[A-Za-z0-9_-]{1,120}$/.test(supplied))
239
+ throw new Error(`A caller-supplied sub-agent run id must look like ${newSubagentRunId()}; got ${JSON.stringify(supplied)}.`);
240
+ const id = supplied ?? newSubagentRunId();
241
+ // Normalized first, and required to be a real directory: a deleted workspace is a visible failure,
242
+ // never a reason to run the child somewhere else.
243
+ const childCwd = resolve(cwd);
244
+ const info = await stat(childCwd).catch(() => undefined);
245
+ if (!info?.isDirectory())
246
+ throw new Error(`Workspace directory for conversation ${conversationId} does not exist or is not a directory: ${childCwd}. Refusing to run sub-agent ${JSON.stringify(agentId)} in any other directory.`);
247
+ // Fetched before the spawn, so a bad definition fails the run loudly instead of starting a Pi that
248
+ // silently ignores it - and so a PRIMARY agent cannot be dispatched as a sub-agent by accident.
249
+ const agent = await this.subagentDefinition(agentId);
250
+ // The child's own `tools:` map, minus whatever the dispatching agent denied. Never the parent's
251
+ // ALLOWLIST - see `SubagentRunInput.denyTools` for why that asymmetry is the reference's too.
252
+ const memoryEnabled = this.memory ? (await this.memory.configuration()).enabled : false;
253
+ const agentArgs = await agentSpawnArgs(this.agents.promptDir, agent, { denyTools: input.denyTools ?? [], extraAllowedTools: memoryEnabled ? ["memory", "skill_manage", "session_search"] : [] });
254
+ const nativePolicy = nativeToolPolicy(toolSelection(agent.tools, { denyTools: input.denyTools ?? [], extraAllowedTools: memoryEnabled ? ["memory", "skill_manage", "session_search"] : [] }), readNativeToolSettings(nativeToolSettingsPath(this.sessionDir)));
255
+ if (nativePolicy.excludeTools?.length)
256
+ agentArgs.push("--exclude-tools", nativePolicy.excludeTools.join(","));
257
+ const sessionDirectory = join(this.sessionDir, "subagents");
258
+ await mkdir(sessionDirectory, { recursive: true });
259
+ const memoryToken = memoryEnabled ? this.memory.issue(conversationId, { readOnly: true, agentId }) : undefined;
260
+ const args = ["--mode", "rpc", "--no-mcp", "--extension", nativeToolExtensionPath(), "--session-dir", sessionDirectory, "--session-id", id, ...(memoryToken ? ["--extension", resolve(import.meta.dirname, "../../agents/super-pi-memory/index.ts")] : []), ...agentArgs];
261
+ // Model inheritance: the definition wins, otherwise the parent's current model, otherwise Pi's own
262
+ // default. "Omit the model and get what the parent is running on" is the default worth having, and it
263
+ // is a spawn-time flag because there is no RPC command to change it later.
264
+ const chosen = agent.model ?? (model?.provider && model.modelId ? { provider: model.provider, modelId: model.modelId } : undefined);
265
+ if (model)
266
+ await this.modelValidator?.(conversationId, model);
267
+ await this.modelValidator?.(conversationId, chosen ? { ...chosen, label: chosen.modelId } : undefined);
268
+ if (chosen)
269
+ args.push("--provider", chosen.provider, "--model", chosen.modelId);
270
+ if (agent.thinkingLevel)
271
+ args.push("--thinking", agent.thinkingLevel);
272
+ // Cancellation may arrive during filesystem/config/model preparation, before the child or its
273
+ // abort listener exists. Refuse the spawn instead of starting work after the user pressed stop.
274
+ if (signal?.aborted) {
275
+ if (memoryToken)
276
+ this.memory?.release(memoryToken);
277
+ throw new SubagentCancelled(id);
278
+ }
279
+ // npm exposes global CLIs as .cmd shims on Windows; Node requires a shell to launch those shims.
280
+ const child = spawn(shellQuote(this.pi.command), args, { cwd: childCwd, detached: process.platform !== "win32", stdio: ["pipe", "pipe", "pipe"], shell: process.platform === "win32", env: { ...process.env, ...nativeToolEnv(this.sessionDir, nativePolicy), ...(memoryToken ? { SUPER_PI_MEMORY_ENDPOINT: process.env.SUPER_PI_MEMORY_ENDPOINT, SUPER_PI_MEMORY_TOKEN: memoryToken, SUPER_PI_MEMORY_READ_ONLY: "1" } : {}) } });
281
+ if (memoryToken)
282
+ child.once("close", () => this.memory?.release(memoryToken));
283
+ this.children.set(id, { conversationId, child });
284
+ const channel = new RpcChannel(child);
285
+ // Pi is asked to stop first and killed only if that is not enough, so a child that can unwind its own
286
+ // tools gets to. `channel.write` is deliberately not used: it throws on a closed pipe, and an abort
287
+ // handler that throws inside a listener would surface as an unhandled rejection instead of a cancel.
288
+ const abort = () => {
289
+ if (child.exitCode === null && !child.stdin.destroyed)
290
+ child.stdin.write(`${JSON.stringify({ id: "abort", type: "abort" })}\n`);
291
+ };
292
+ signal?.addEventListener("abort", abort, { once: true });
293
+ /** Every delta of the run, for a child that streams text but never sends a `done`. */
294
+ let streamed = "";
295
+ /** The current assistant message's text, reset by `start` and replaced by `done`. */
296
+ let current = "";
297
+ /** The last assistant message's text, which is the run's output. */
298
+ let finalText = "";
299
+ /**
300
+ * THE CHILD'S OWN REASONING, taken out of its answer.
301
+ *
302
+ * A model that has no reasoning channel writes its thinking into the answer, marked up with
303
+ * `<think>…</think>`. This supervisor's contract is `finalText` - the child's OUTPUT - and the
304
+ * reasoning is not part of it, so the tags and what they wrap never reach the card. The splitter
305
+ * is per child, because what it holds back belongs to one child's stream and to nothing else.
306
+ */
307
+ const inlineThinking = new InlineThinkingSplitter();
308
+ const usage = { ...NO_USAGE };
309
+ /** Set rather than thrown so a child's own failure is reported AFTER its output has been drained. */
310
+ let failed;
311
+ const noteOutcome = (message, reason) => {
312
+ const status = message?.stopReason ?? reason;
313
+ if (!status)
314
+ return;
315
+ failed = status === "error" || status === "aborted"
316
+ ? `sub-agent ${agentId} (${id}) stopped with reason ${status}: ${message?.errorMessage?.trim() || stripInlineThinking(assistantText(message)) || "no detail from Pi"}`
317
+ : undefined;
318
+ };
319
+ /**
320
+ * Which phase the child is in, for a caller that has to say where a run died.
321
+ *
322
+ * Changed ONLY at a record the drain loop actually consumed, so `onStage` cannot report a phase that
323
+ * never happened - which is what keeps a failure card's 「卡在哪」 an observation rather than a guess.
324
+ * Starts at `dispatch`, which covers every refusal above the spawn: an unknown agent, a deleted
325
+ * workspace, a Pi that is not installed. Those throw before a child exists, and "it never got as
326
+ * far as being asked anything" is the accurate thing to say about all of them.
327
+ */
328
+ let stage = "dispatch";
329
+ const enter = (next) => {
330
+ if (stage === next)
331
+ return;
332
+ stage = next;
333
+ onStage?.(next);
334
+ };
335
+ try {
336
+ channel.write({ id: "prompt", type: "prompt", message: task });
337
+ enter("prompt");
338
+ let settled = false;
339
+ // Nothing may be dropped without a trace. Pi emits a wide, open-ended family of session events, so
340
+ // an unhandled record is announced once per distinct type and then tallied instead of logged per event.
341
+ // "Unhandled" means "not in KNOWN_LIFECYCLE_RECORDS / KNOWN_LIFECYCLE_EVENTS and not consumed above",
342
+ // i.e. genuinely unrecognised - NOT merely frequent. The exemption sets are the whole reason an
343
+ // ordinary run is quiet while a protocol change is still loud; keep that ordering when editing them.
344
+ const announced = new Set();
345
+ const repeats = new Map();
346
+ const noteUnhandled = (key) => {
347
+ if (announced.has(key))
348
+ repeats.set(key, (repeats.get(key) ?? 0) + 1);
349
+ else {
350
+ announced.add(key);
351
+ console.warn(`SubagentSupervisor: unhandled child record ${key} - consumed without action.`);
352
+ }
353
+ };
354
+ // A child asking a question is exactly why RPC mode was chosen, and `host` is the other half of
355
+ // that choice: with one, the question reaches a human and Pi stays blocked for as long as they take.
356
+ // The host speaks the same protocol the primary agent's does (`describeExtensionUiRequest` /
357
+ // `buildExtensionUiResponse` are shared with `PiRpcRuntime`), so there is exactly one definition of
358
+ // "what Pi's nine methods mean" in the codebase rather than one per spawner.
359
+ //
360
+ // The reply always carries the record's OWN `requestId`, never the host's key for it: the host may
361
+ // scope that key per run or per conversation so two questions cannot settle each other, and leaking
362
+ // that prefix back into the child's protocol would make Pi wait forever on an id it never issued.
363
+ const ui = {
364
+ seen: new Set(),
365
+ aborted: new Promise((resolve) => { if (signal?.aborted)
366
+ resolve(undefined);
367
+ else
368
+ signal?.addEventListener("abort", () => resolve(undefined), { once: true }); }),
369
+ exited: new Promise((resolve) => child.once("exit", () => resolve(undefined))),
370
+ };
371
+ const handleExtensionUi = async (record) => {
372
+ const request = describeExtensionUiRequest(record);
373
+ if (!request) {
374
+ console.warn(`SubagentSupervisor: sub-agent ${agentId} (${id}) sent extension_ui_request method=${JSON.stringify(record.method ?? null)} id=${JSON.stringify(record.id ?? null)}, which is not one of Pi's nine Extension UI methods - consumed without reply.`);
375
+ return;
376
+ }
377
+ // `channel.write` is deliberately not used for the reply, for the same reason it is not used for
378
+ // the abort: it throws on a closed pipe, and a throw from inside a host callback would surface as
379
+ // an unhandled rejection rather than as the failure it actually is.
380
+ const reply = (response) => { if (child.exitCode === null && !child.stdin.destroyed)
381
+ child.stdin.write(`${JSON.stringify(response)}\n`); };
382
+ // The five one-way methods carry no question and Pi holds no pending entry for them, so a response
383
+ // would resolve nothing. Pushed to the host un-awaited; a host that throws is announced, not fatal.
384
+ if (!request.blocking) {
385
+ try {
386
+ host?.notify(request);
387
+ }
388
+ catch (error) {
389
+ console.warn(`SubagentSupervisor: extension_ui notify for ${request.method} id=${request.requestId} in sub-agent ${agentId} (${id}) threw in the host: ${error instanceof Error ? error.message : "unknown error"}`);
390
+ }
391
+ return;
392
+ }
393
+ // Pi parks one pending entry per request id, so a duplicate id is the same question twice. Answering
394
+ // it twice would write two responses into one slot.
395
+ if (ui.seen.has(request.requestId)) {
396
+ console.warn(`SubagentSupervisor: sub-agent ${agentId} (${id}) sent extension_ui_request ${request.method} id=${request.requestId} twice - second copy consumed without reply.`);
397
+ return;
398
+ }
399
+ ui.seen.add(request.requestId);
400
+ if (!host) {
401
+ // No human can be asked, so the honest reply is "cancelled". Auto-answering with options[0] or
402
+ // confirmed:false would look to Pi exactly like a decision, and the user would never learn a
403
+ // question was asked of them.
404
+ console.warn(`SubagentSupervisor: sub-agent ${agentId} (${id}) used ${request.method} id=${request.requestId}, and this run has no UI host to answer it - cancelled rather than answering on a human's behalf.`);
405
+ reply({ type: "extension_ui_response", id: request.requestId, cancelled: true });
406
+ return;
407
+ }
408
+ // Raced against abort and exit, because this `await` parks the drain loop and the loop cannot see
409
+ // either of them on its own: a question outliving its run would leave the child blocked forever on
410
+ // a reply that can no longer be written.
411
+ const cancelled = { cancelled: true };
412
+ let answer;
413
+ try {
414
+ answer = await Promise.race([host.ask(request), ui.aborted.then(() => cancelled), ui.exited.then(() => cancelled)]);
415
+ }
416
+ catch (error) {
417
+ console.warn(`SubagentSupervisor: sub-agent ${agentId} (${id}) got no answer for ${request.method} id=${request.requestId} (host failed: ${error instanceof Error ? error.message : "unknown error"}) - cancelled.`);
418
+ answer = cancelled;
419
+ }
420
+ reply(buildExtensionUiResponse(request, answer));
421
+ };
422
+ while (!settled) {
423
+ // Checked between polls rather than only on the abort event: a child that ignores `abort` must
424
+ // not be able to hold the run open, and the kill in `finally` is what actually ends it.
425
+ if (signal?.aborted)
426
+ throw new SubagentCancelled(id);
427
+ for (;;) {
428
+ let record;
429
+ try {
430
+ record = await channel.next(DRAIN_POLL_MS);
431
+ }
432
+ catch (error) {
433
+ // RpcChannel surfaces EOF immediately so a caller cannot mistake a dead Pi for an
434
+ // idle one. Preserve this supervisor's richer contract: the agent identity, phase
435
+ // and exit code are what make an unexpected child exit actionable to the user.
436
+ if (error?.code === "CHANNEL_CLOSED") {
437
+ throw new Error(`sub-agent ${agentId} (${id}) exited before settling (code ${child.exitCode}). ${channel.stderr.trim()}`);
438
+ }
439
+ throw error;
440
+ }
441
+ if (!record)
442
+ break;
443
+ // THE RECEIPT FOR OUR OWN PROMPT IS A KNOWN RECORD, NOT AN UNKNOWN ONE. Pi answers every
444
+ // command with `type:"response"`, so the successful receipt for the prompt we just wrote is
445
+ // part of the protocol - and treating it as unrecognised made every ordinary sub-agent run
446
+ // log a false alarm ("unhandled child record response - consumed without action"). A FAILED
447
+ // receipt is the run's failure and is thrown; a successful one is simply consumed.
448
+ if (record.type === "response" && record.id === "prompt") {
449
+ if (record.success === false)
450
+ throw new Error(`Pi rejected the sub-agent task: ${record.error ?? "no reason given"}`);
451
+ continue;
452
+ }
453
+ if (record.type === "message_update") {
454
+ const event = record.assistantMessageEvent;
455
+ // `text_delta` is the only inner event that is output. `start` and `done` are the boundaries
456
+ // that make "the last assistant message" knowable at all: without them a child that produced
457
+ // three messages would report all three concatenated as one answer.
458
+ if (event?.type === "text_delta") {
459
+ const delta = event.delta ?? "";
460
+ // THE REASONING COMES OUT FIRST. What the card shows is the child's answer, and a model
461
+ // that thinks inside its answer would otherwise hand it a string that opens with
462
+ // `<think>` - the markup of a reasoning trace where the child's result belongs.
463
+ const answer = inlineThinking.push(delta)
464
+ .filter((segment) => segment.kind === "text")
465
+ .map((segment) => segment.text)
466
+ .join("");
467
+ streamed += answer;
468
+ current += answer;
469
+ enter("turn");
470
+ if (answer)
471
+ onTextDelta?.(answer);
472
+ }
473
+ else if (event?.type === "start") {
474
+ current = "";
475
+ enter("turn");
476
+ }
477
+ else if (event?.type === "done") {
478
+ // `done` carries the AUTHORITATIVE message, so its text wins over what the deltas added up
479
+ // to; the accumulated text stays as the fallback for a child that streams without a `done`.
480
+ // The authoritative text is stripped the same way the deltas were: a child whose answer
481
+ // ends in a reasoning region must not turn that region into its result.
482
+ current = stripInlineThinking(assistantText(event.message)) || current;
483
+ finalText = current;
484
+ addUsage(usage, record.usage);
485
+ enter("turn");
486
+ noteOutcome(event.message, event.reason);
487
+ }
488
+ else if (event?.type === "error") {
489
+ noteOutcome(event.message, "error");
490
+ }
491
+ else if (event?.type === "thinking_delta") {
492
+ // CONSUMED, not discarded. A reasoning model spends the first seconds of every turn here,
493
+ // emitting no text at all, so this record is the only evidence the child is alive and
494
+ // working during exactly the window a card otherwise looks frozen. See `onThinking`.
495
+ enter("turn");
496
+ onThinking?.();
497
+ continue;
498
+ }
499
+ else if (KNOWN_LIFECYCLE_EVENTS.has(event?.type ?? "")) {
500
+ // Known, and this supervisor has no use for it - see the set's own comment for why each name
501
+ // qualifies. Deliberately NOT a blanket ignore: anything outside the set still falls through
502
+ // to `noteUnhandled`, which is what catches Pi adding an event shape.
503
+ }
504
+ else {
505
+ noteUnhandled(`message_update:${JSON.stringify(event?.type ?? "(missing)")}`);
506
+ }
507
+ continue;
508
+ }
509
+ if (record.type === "tool_execution_start") {
510
+ // The `args` on this record are exactly what used to be thrown away with the record itself.
511
+ // They are read, not copied: `describeToolCall` turns them into one bounded label and the
512
+ // object itself goes no further. See that function for the whole argument-vs-transcript line.
513
+ enter("tool");
514
+ onToolCall?.({ id: record.toolCallId ?? "", name: record.toolName ?? "unknown", detail: describeToolCall(record.toolName ?? "unknown", record.args) });
515
+ continue;
516
+ }
517
+ if (record.type === "tool_execution_update" || record.type === "tool_execution_end") {
518
+ const final = record.type === "tool_execution_end";
519
+ if (onToolUpdate && record.toolCallId && /^(bash|powershell|shell|command)$/i.test(record.toolName ?? "")) {
520
+ const output = extractPartialResultText(final ? record.result : record.partialResult);
521
+ if (output)
522
+ onToolUpdate(record.toolCallId, output, final);
523
+ }
524
+ if (!final)
525
+ continue;
526
+ // THE OTHER HALF OF THE SAME CALL, and the half that makes a row mean something. Until Pi
527
+ // started sending this, a `read` row could only ever say that a `read` happened: not whether
528
+ // it found the file, not how long a slow call had been running, and - for a card whose child
529
+ // is still working - not whether the row was even finished yet.
530
+ //
531
+ // Every tool reports timing and success. Only shell tools expose captured output.
532
+ enter("turn");
533
+ onToolEnd?.({
534
+ id: record.toolCallId ?? "",
535
+ name: record.toolName ?? "unknown",
536
+ status: record.isError === true ? "error" : "ok",
537
+ ...(typeof record.durationMs === "number" && Number.isFinite(record.durationMs) ? { durationMs: Math.max(0, Math.round(record.durationMs)) } : {}),
538
+ });
539
+ continue;
540
+ }
541
+ if (record.type === "extension_ui_request") {
542
+ await handleExtensionUi(record);
543
+ continue;
544
+ }
545
+ if (record.type === "agent_end") {
546
+ if (!record.willRetry) {
547
+ const message = record.messages && [...record.messages].reverse().find(item => item.role === "assistant");
548
+ if (message)
549
+ noteOutcome(message);
550
+ }
551
+ continue;
552
+ }
553
+ // Pi caught this inside its own extension host, so it never becomes a thrown failure there. Every
554
+ // run is a fresh process, so any extension_error seen while draining belongs to the task in
555
+ // flight - and a sub-agent whose extension failed has not really done the job.
556
+ if (record.type === "extension_error")
557
+ throw new Error(`Pi extension error in ${record.extensionPath ?? "unknown path"} (${record.event ?? "unknown event"}): ${record.error ?? "unknown error"}`);
558
+ if (record.type === "agent_settled") {
559
+ enter("settle");
560
+ settled = true;
561
+ continue;
562
+ }
563
+ // Known lifecycle, no action needed - see the set's own comment. Anything NOT in the set lands on
564
+ // `noteUnhandled` below, so a record type this build has never heard of is still announced.
565
+ if (KNOWN_LIFECYCLE_RECORDS.has(record.type ?? ""))
566
+ continue;
567
+ noteUnhandled(`type ${JSON.stringify(record.type ?? "(missing type)")}`);
568
+ }
569
+ // A dead child will never settle, so waiting out another poll would only delay the failure.
570
+ if (!settled && channel.closed)
571
+ throw new Error(`sub-agent ${agentId} (${id}) exited before settling (code ${child.exitCode}). ${channel.stderr.trim()}`);
572
+ }
573
+ for (const [key, count] of repeats)
574
+ console.warn(`SubagentSupervisor: ${count} further unhandled child record(s) of ${key}.`);
575
+ // Checked again after the loop, because the poll above can consume the very record `agent_settled`
576
+ // emits and the abort at the same time: a run the user stopped must not report success just because
577
+ // Pi happened to finish while it was being cancelled.
578
+ if (signal?.aborted)
579
+ throw new SubagentCancelled(id);
580
+ if (failed)
581
+ throw new Error(failed);
582
+ // No `done` at all is a child that streamed and vanished; the deltas are then the best answer there
583
+ // is, and returning them beats returning "" for work that demonstrably happened.
584
+ //
585
+ // THE SPLITTER IS RELEASED FIRST. It may still be holding back the beginning of a tag, and that
586
+ // text belongs to the child: a run that ended mid-word must not lose the word.
587
+ for (const segment of inlineThinking.flush()) {
588
+ if (segment.kind === "text")
589
+ streamed += segment.text;
590
+ }
591
+ return { id, sessionId: id, finalText: finalText || streamed, usage };
592
+ }
593
+ finally {
594
+ if (memoryToken)
595
+ this.memory?.release(memoryToken);
596
+ signal?.removeEventListener("abort", abort);
597
+ this.children.delete(id);
598
+ // The run is not over until the child is actually gone: a process still tearing down still holds a
599
+ // lock on its working directory, so a caller that removes that directory the moment run() settles
600
+ // would hit EBUSY on Windows.
601
+ await closePiWorker(child);
602
+ }
603
+ }
604
+ /**
605
+ * The definition this run will use, or the reason there is none.
606
+ *
607
+ * Read with `mode: "subagent"`, so a primary agent is not found by id at all rather than found and
608
+ * then judged: a sub-agent definition is the same `agents/*.md` file with a different `mode`, and this
609
+ * is the filter that keeps the two rosters from ever meeting.
610
+ */
611
+ async subagentDefinition(agentId) {
612
+ const { agents, problems } = await readAgents(this.agents.dir, { mode: "subagent" });
613
+ const agent = agents.find((item) => item.id === agentId);
614
+ if (agent)
615
+ return agent;
616
+ const dirLabel = Array.isArray(this.agents.dir) ? this.agents.dir.join(", ") : this.agents.dir;
617
+ throw new Error(`sub-agent ${JSON.stringify(agentId)} is not a subagent definition in ${dirLabel}${problems.length ? ` (${problems.length} file(s) there are not usable agents)` : ""}. A sub-agent is an agents/*.md file with \`mode: subagent\`; a primary agent is chosen by a human and is deliberately not dispatchable as one.`);
618
+ }
619
+ }