@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,701 @@
1
+ import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import { orderAgentsForDisplay } from "../shared/agent-order.js";
5
+ /**
6
+ * A guard rather than a cast: it is the only thing that lets `tools:` be checked once and then used as
7
+ * a map everywhere without the compiler complaining. It narrows to the index-signature shape that
8
+ * `object` cannot express on its own.
9
+ */
10
+ const isFrontmatter = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11
+ const FRONTMATTER_BLOCK = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
12
+ /**
13
+ * Every tool name Super Pi can know STATICALLY, read out of Pi's own source rather than from memory.
14
+ * Each entry carries the place it came from, because this list is the whole safety net behind
15
+ * `validateToolNames` and it has to be re-checked whenever Pi is upgraded.
16
+ *
17
+ * It is deliberately NOT the 8 built-ins alone. Pi's registry also holds:
18
+ *
19
+ * - `codemode` and `tool_search`, registered by the two built-in extensions
20
+ * (extensions/codemode/tool.ts:50, extensions/tool-search/tool.ts:20). Pi's own CLI help offers
21
+ * `--tools read,bash,codemode,'mcp__radius__*'` as an example (cli/args.ts:409), so treating
22
+ * these as unknown would reject configuration Pi documents.
23
+ * - the three MCP resource tools (core/mcp-servers.ts:31-37).
24
+ * - MCP server tools, named `mcp__<server>__<tool>` (core/mcp-servers.ts:38-41). The server list
25
+ * is runtime state, so those are recognised by PREFIX instead of by name - see `isKnownPiToolName`.
26
+ *
27
+ * Anything else Pi can hold - a third-party extension tool, an SDK-supplied tool
28
+ * (agent-session.ts:3503-3509) - has an arbitrary name that no static list can contain. Those names
29
+ * are indistinguishable from typos by construction, which is the limit of this check; see
30
+ * `validateToolNames` for what is rejected on that account and why.
31
+ */
32
+ export const PI_TOOL_NAMES = [
33
+ // core/tools/index.ts:95-105 - the ToolName union and the allToolNames set.
34
+ "read", "bash", "powershell", "edit", "write", "grep", "find", "ls",
35
+ // Registered by Pi's built-in extensions.
36
+ "codemode", "tool_search",
37
+ // core/mcp-servers.ts:31-37 - reachable on any server that exposes resources.
38
+ "list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource",
39
+ ];
40
+ /** Tools shipped by this package. Authors must be able to explicitly deny host extras. */
41
+ export const SUPER_PI_TOOL_NAMES = [
42
+ "task", "todowrite", "workflow", "run_async", "worktree", "scheduled_task", "project", "question", "tool_register", "tool_shortcut", "tool_remove",
43
+ "memory", "skill_manage", "session_search",
44
+ "session_spawn", "session_status", "session_dispatch", "session_stop", "session_report", "session_stop_subtree", "session_remove", "session_reminder",
45
+ "knowledge_search", "knowledge_import",
46
+ "document_read", "document_write", "web_search", "web_fetch", "feishu_doc_read", "feishu_doc_write",
47
+ ];
48
+ const KNOWN_TOOL_NAMES = [...PI_TOOL_NAMES, ...SUPER_PI_TOOL_NAMES];
49
+ const PI_TOOL_NAME_SET = new Set(KNOWN_TOOL_NAMES);
50
+ /**
51
+ * Whether a name can be a real Pi tool. A name is real if it is one of `PI_TOOL_NAMES`, an MCP
52
+ * server tool, or a PATTERN.
53
+ *
54
+ * Patterns are a real feature, not an escape hatch: Pi turns every `--tools` entry into a matcher
55
+ * that treats a `*` entry as a glob (core/mcp-servers.ts:21-25), and `--tools` is exactly what an
56
+ * agent's `tools` map becomes. Rejecting `mcp__radius__*` would reject Pi's documented syntax.
57
+ */
58
+ export function isKnownPiToolName(name) {
59
+ if (PI_TOOL_NAME_SET.has(name))
60
+ return true;
61
+ if (name.includes("*"))
62
+ return true;
63
+ return name.startsWith("mcp__");
64
+ }
65
+ function editDistance(left, right) {
66
+ const row = Array.from({ length: right.length + 1 }, (_, index) => index);
67
+ for (let i = 1; i <= left.length; i += 1) {
68
+ let diagonal = row[0];
69
+ row[0] = i;
70
+ for (let j = 1; j <= right.length; j += 1) {
71
+ const above = row[j];
72
+ row[j] = left[i - 1] === right[j - 1] ? diagonal : Math.min(diagonal + 1, above + 1, row[j - 1] + 1);
73
+ diagonal = above;
74
+ }
75
+ }
76
+ return row[right.length];
77
+ }
78
+ function closestToolName(name) {
79
+ const ranked = KNOWN_TOOL_NAMES.map((candidate) => ({ candidate, distance: editDistance(name, candidate) })).sort((a, b) => a.distance - b.distance);
80
+ return ranked[0]?.distance <= Math.max(2, Math.floor(name.length / 2)) ? ranked[0].candidate : undefined;
81
+ }
82
+ /**
83
+ * Reports every `tools` key that cannot be a Pi tool name, or undefined when they all can.
84
+ *
85
+ * WHY THIS CHECK EXISTS. Pi's own validator for a tool list (`getToolListError`,
86
+ * core/settings-manager.ts:227-234) only looks at `+name`/`-name` SYNTAX and never asks whether the
87
+ * tool exists. An allowlist naming one misspelled tool therefore passes Pi's validation and then
88
+ * matches nothing, so the agent is registered with NO tools at all and no warning is printed
89
+ * anywhere: the picker shows a working agent that cannot read, search or edit anything.
90
+ *
91
+ * WHAT IS REJECTED, AND WHAT THAT COSTS. A name that is neither statically known, nor `mcp__`-prefixed,
92
+ * nor a pattern is reported as a problem, which takes the whole definition out of the roster. The cost
93
+ * is a false positive on a third-party extension or SDK tool (agent-session.ts:3503-3509), whose names
94
+ * are arbitrary and unknowable from here. That direction is deliberate: a rejected agent is VISIBLE in
95
+ * the picker with the reason and the full known list attached, while an accepted typo is invisible and
96
+ * produces a silently useless agent - the exact failure this check exists to remove.
97
+ */
98
+ function validateToolNames(tools) {
99
+ if (!isFrontmatter(tools))
100
+ return undefined;
101
+ const unknown = Object.keys(tools).filter((name) => name !== "*" && !isKnownPiToolName(name));
102
+ if (!unknown.length)
103
+ return undefined;
104
+ const details = unknown.map((name) => {
105
+ const suggestion = closestToolName(name);
106
+ return `${JSON.stringify(name)}${suggestion ? ` (did you mean ${JSON.stringify(suggestion)}?)` : ""}`;
107
+ });
108
+ return `tools names ${details.join(", ")}, which Pi does not have. Statically known tools: ${KNOWN_TOOL_NAMES.join(", ")}; MCP tools are named mcp__<server>__<tool>, and a "*" in a name is a Pi glob.`;
109
+ }
110
+ /**
111
+ * Splits a definition file into frontmatter and body. The body is the system prompt, exactly as in
112
+ * OpenCode - a file with no frontmatter is not an agent definition, and is reported rather than
113
+ * silently treated as an empty-prompt agent.
114
+ */
115
+ export function splitDefinition(source) {
116
+ const match = FRONTMATTER_BLOCK.exec(source);
117
+ if (!match)
118
+ return undefined;
119
+ return { frontmatter: parseYaml(match[1]), body: source.slice(match[0].length) };
120
+ }
121
+ /**
122
+ * A deliberately small YAML reader: scalars, nested one-level maps, inline `[a, b]` lists and `- item`
123
+ * lists. That is the whole grammar OpenCode agent frontmatter uses (`tools:` is a map, `model:` and
124
+ * `color:` are scalars), and it keeps Super Pi free of a YAML dependency for four fields.
125
+ *
126
+ * Anything it cannot represent is DROPPED rather than guessed: a malformed agent file must fail its
127
+ * own parse and be reported, not load with a field the author thought they set.
128
+ */
129
+ export function parseYaml(text) {
130
+ const root = {};
131
+ const lines = text.split(/\r?\n/);
132
+ let index = 0;
133
+ const indentOf = (line) => line.length - line.trimStart().length;
134
+ /**
135
+ * Drops a trailing `# comment`, respecting quotes. Agent frontmatter carries explanatory comments -
136
+ * especially on the `tools` map, where `"*": false` is worth a line of prose - and without this a
137
+ * colour would come out as `"#4C9AFF" # the agent's brand colour`, which then fails the hex check
138
+ * and silently loses the colour. Quote-aware so a `#` inside a quoted value survives.
139
+ */
140
+ const stripComment = (value) => {
141
+ let quote;
142
+ for (let at = 0; at < value.length; at += 1) {
143
+ const character = value[at];
144
+ if (quote) {
145
+ if (character === quote)
146
+ quote = undefined;
147
+ continue;
148
+ }
149
+ if (character === '"' || character === "'") {
150
+ quote = character;
151
+ continue;
152
+ }
153
+ // Only a `#` preceded by whitespace starts a comment, so `color: #4C9AFF` still parses.
154
+ if (character === "#" && (at === 0 || /\s/.test(value[at - 1])))
155
+ return value.slice(0, at);
156
+ }
157
+ return value;
158
+ };
159
+ const valueAfter = (keyLine) => stripComment(keyLine.slice(keyLine.indexOf(":") + 1)).trim();
160
+ /**
161
+ * Reads whatever follows a key on the deeper-indented lines below it: either a `- item` block list or
162
+ * a nested map, and `undefined` when the next line is not deeper at all.
163
+ *
164
+ * This is the single place a block value is read, because the two shapes are easy to confuse and the
165
+ * failure is silent: treating a `- item` list as a map yields `{}`, and treating a map as a list
166
+ * yields `[]`. Both load as "an empty frontmatter field" rather than as an error.
167
+ */
168
+ const readDeeper = (parentIndent) => {
169
+ const next = lines[index];
170
+ if (next === undefined || next.trim() === "" || indentOf(next) <= parentIndent)
171
+ return undefined;
172
+ if (next.trim().startsWith("- ")) {
173
+ const items = [];
174
+ while (index < lines.length && lines[index].trim().startsWith("- ")) {
175
+ items.push(unquote(lines[index].trim().slice(2).trim()));
176
+ index += 1;
177
+ }
178
+ return items;
179
+ }
180
+ return readMap(parentIndent);
181
+ };
182
+ /** Reads the value belonging to `keyLine`, which the caller has ALREADY stepped past.
183
+ *
184
+ * `keyIndent` is the KEY's OWN indent, deliberately not its parent's. A block value must be indented
185
+ * deeper than the key that owns it; compared against the parent's indent instead, the first scalar in
186
+ * a map would swallow its next SIBLING - `tools:` -> `"*": false` -> `read: true` would parse the
187
+ * boolean as a map containing `read`, which loads as a permission map that reads back empty. */
188
+ const readValue = (keyLine, keyIndent) => {
189
+ const rest = valueAfter(keyLine);
190
+ if (rest.startsWith("["))
191
+ return parseInlineList(rest) ?? "";
192
+ const deeper = readDeeper(keyIndent);
193
+ return deeper === undefined ? parseScalar(rest) : deeper;
194
+ };
195
+ /** Reads `key:` followed by lines indented deeper than it, as a nested map. */
196
+ const readMap = (parentIndent) => {
197
+ const nested = {};
198
+ while (index < lines.length && lines[index].trim() !== "" && indentOf(lines[index]) > parentIndent) {
199
+ const child = lines[index];
200
+ const childColon = child.indexOf(":");
201
+ if (childColon < 0) {
202
+ index += 1;
203
+ continue;
204
+ }
205
+ const childKey = unquote(child.slice(0, childColon).trim());
206
+ index += 1;
207
+ nested[childKey] = readValue(child, indentOf(child));
208
+ }
209
+ return nested;
210
+ };
211
+ while (index < lines.length) {
212
+ const line = lines[index];
213
+ if (!line.trim() || line.trim().startsWith("#")) {
214
+ index += 1;
215
+ continue;
216
+ }
217
+ const colon = line.indexOf(":");
218
+ if (colon < 0) {
219
+ index += 1;
220
+ continue;
221
+ }
222
+ const key = unquote(line.slice(0, colon).trim());
223
+ const indent = indentOf(line);
224
+ // Stepped past the key's own line FIRST, so a block value is read from what actually follows it.
225
+ index += 1;
226
+ root[key] = readValue(line, indent);
227
+ }
228
+ return root;
229
+ }
230
+ const parseInlineList = (value) => {
231
+ if (!value.startsWith("[") || !value.endsWith("]"))
232
+ return undefined;
233
+ return value.slice(1, -1).split(",").map((item) => unquote(item.trim())).filter((item) => item !== "");
234
+ };
235
+ /** Booleans, numbers and quoted strings are the only scalar shapes agent frontmatter uses. */
236
+ function parseScalar(value) {
237
+ if (value === "" || value === "~" || value === "null")
238
+ return "";
239
+ if (value === "true")
240
+ return true;
241
+ if (value === "false")
242
+ return false;
243
+ if (/^-?\d+$/.test(value))
244
+ return Number.parseInt(value, 10);
245
+ return unquote(value);
246
+ }
247
+ function unquote(value) {
248
+ if ((value.startsWith('"') && value.endsWith('"') && value.length > 1) || (value.startsWith("'") && value.endsWith("'") && value.length > 1))
249
+ return value.slice(1, -1);
250
+ return value;
251
+ }
252
+ /**
253
+ * The Pi CLI flags an agent's `tools` map becomes. Returned flat so the caller can push them into the
254
+ * spawn argv in order, and so a test can assert on the exact list.
255
+ *
256
+ * THE TRANSLATION, from OpenCode's semantics (`tools` is a map whose `"*"` entry sets the default for
257
+ * every tool, and other keys override it) to Pi's three flags:
258
+ *
259
+ * tools: { "*": false, read: true } -> ["--tools", "read"] allowlist, everything else denied
260
+ * tools: { "*": false } -> ["--no-tools"] nothing at all
261
+ * tools: { bash: false } -> ["--exclude-tools","bash"] deny one, keep Pi's defaults
262
+ * tools: { "*": true, bash: false } -> ["--exclude-tools","bash"] same, stated explicitly
263
+ * no `tools` key -> [] Pi's own default tool set
264
+ *
265
+ * The allowlist form is a real permission boundary, not a courtesy: Pi filters the tool REGISTRY
266
+ * through the same allowlist (agent-session.ts:3536-3545), so a tool that is not on the list is never
267
+ * registered, never declared to the model, and therefore cannot be called - the model does not even
268
+ * see a schema for it. Naming a tool on the allowlist also activates it (agent-session.ts:3569-3574).
269
+ */
270
+ export function toolFlags(tools, options = {}) {
271
+ const denied = new Set((options.denyTools ?? []).filter((name) => name !== ""));
272
+ // An agent with no `tools:` map runs on Pi's own default set, so there is nothing to translate - but a
273
+ // DENY inherited from a parent still has to become an explicit exclusion, because there is no allowlist
274
+ // here to drop the name from.
275
+ if (!tools || typeof tools !== "object")
276
+ return denied.size ? ["--exclude-tools", [...denied].join(",")] : [];
277
+ const entries = Object.entries(tools).filter(([key]) => key !== "*");
278
+ // An absent `"*"` is OpenCode's default: every tool is allowed unless a key says otherwise.
279
+ const wildcard = tools["*"];
280
+ // An explicit `false` is the author's own refusal and outranks any extra the host is adding.
281
+ const explicit = new Map(entries);
282
+ const extra = (options.extraAllowedTools ?? []).filter((name) => name !== "" && explicit.get(name) !== false);
283
+ // An inherited deny is applied to the DECLARED list first, so `tools: {"read": true, "bash": true}` from
284
+ // a child whose parent denied `bash` becomes an allowlist of `read` - the intersection the child is
285
+ // entitled to, and the whole reason `denyTools` is applied here rather than at the call site.
286
+ const declared = entries.filter(([, on]) => on === true).map(([name]) => name).filter((name) => !denied.has(name));
287
+ const deny = entries.filter(([, on]) => on === false).map(([name]) => name)
288
+ .filter((name) => !declared.includes(name));
289
+ if (wildcard === false) {
290
+ // `{"*": false}` with nothing switched back on is the strongest statement an agent author can make -
291
+ // "this role talks, it does not act" - and an allowlist of nothing is where a host capability stops.
292
+ // Extending it would make `extraAllowedTools` an override of the author's intent rather than a
293
+ // completion of it, and the one agent that most clearly does not want a delegation tool is the one
294
+ // that has just said it wants no tools at all.
295
+ if (!declared.length)
296
+ return ["--no-tools"];
297
+ const allow = [...declared, ...extra.filter((name) => !declared.includes(name) && !denied.has(name))];
298
+ const excluded = [...new Set([...deny, ...denied])];
299
+ return ["--tools", allow.join(","), ...((allow.some(name => name.includes("*")) || excluded.some(name => name.includes("*"))) && excluded.length ? ["--exclude-tools", excluded.join(",")] : [])];
300
+ }
301
+ // A map with no allowlist is Pi's defaults, so a denied name has to become an explicit exclusion
302
+ // rather than being dropped - there is nothing to drop it FROM.
303
+ const excluded = [...new Set([...deny, ...[...denied].filter((name) => !deny.includes(name))])];
304
+ if (excluded.length)
305
+ return ["--exclude-tools", excluded.join(",")];
306
+ // `{"*": true}`, or an empty map, means "Pi's defaults" - the same as passing no flag at all.
307
+ return [];
308
+ }
309
+ /**
310
+ * Whether the map denies everything, which is `{"*": false}` with nothing switched back on. Split out
311
+ * of `toolFlags` because the picker needs to say "no tools" rather than render an empty allowlist.
312
+ */
313
+ export function deniesAllTools(tools) {
314
+ if (!isFrontmatter(tools))
315
+ return false;
316
+ return tools["*"] === false && !Object.entries(tools).some(([key, on]) => key !== "*" && on === true);
317
+ }
318
+ /**
319
+ * The same translation `toolFlags` performs, expressed as the SDK's two lists rather than as argv.
320
+ *
321
+ * WHY A SECOND TRANSLATION AND NOT A PARSER. The argv form is `--tools a,b,c` or `--exclude-tools x,y`
322
+ * or `--no-tools`, and parsing it back would be reading a serialization of a decision to recover the
323
+ * decision. Worse, `--no-tools` has no SDK equivalent that means the same thing: Pi's `noTools: "all"`
324
+ * disables the built-ins while leaving extension tools on, which is NOT what an agent that declared
325
+ * `{"*": false}` asked for - that agent asked for NO tools at all, and an extension tool left enabled
326
+ * would be a tool the author explicitly refused.
327
+ *
328
+ * So the DECISION is made once, here, in the same terms `toolFlags` uses, and each consumer takes the
329
+ * form it needs. The two must agree, and `scripts/agent-config-regression.test.mjs` asserts that they
330
+ * do for every shape of `tools:` map.
331
+ */
332
+ export function toolSelection(tools, options = {}) {
333
+ const denied = new Set((options.denyTools ?? []).filter((name) => name !== ""));
334
+ // No map at all is Pi's own default set. An inherited deny still has to become an exclusion, because
335
+ // there is no allowlist here to drop the name from.
336
+ if (!tools || typeof tools !== "object") {
337
+ return denied.size ? { excludeTools: [...denied] } : {};
338
+ }
339
+ const entries = Object.entries(tools).filter(([key]) => key !== "*");
340
+ const wildcard = tools["*"];
341
+ const explicit = new Map(entries);
342
+ const extra = (options.extraAllowedTools ?? []).filter((name) => name !== "" && explicit.get(name) !== false);
343
+ const declared = entries.filter(([, on]) => on === true).map(([name]) => name).filter((name) => !denied.has(name));
344
+ const deny = entries.filter(([, on]) => on === false).map(([name]) => name).filter((name) => !declared.includes(name));
345
+ if (wildcard === false) {
346
+ // An allowlist of nothing is an agent that talks and does not act. The SDK expresses that as an
347
+ // EMPTY allowlist - `tools: []` - which is different from omitting the option, and the difference
348
+ // matters: omitted means Pi's defaults, empty means none.
349
+ if (!declared.length)
350
+ return { tools: [] };
351
+ const allow = [...declared, ...extra.filter((name) => !declared.includes(name) && !denied.has(name))];
352
+ const excluded = [...new Set([...deny, ...denied])];
353
+ return { tools: allow, ...((allow.some(name => name.includes("*")) || excluded.some(name => name.includes("*"))) && excluded.length ? { excludeTools: excluded } : {}) };
354
+ }
355
+ const excluded = [...new Set([...deny, ...[...denied].filter((name) => !deny.includes(name))])];
356
+ return excluded.length ? { excludeTools: excluded } : {};
357
+ }
358
+ /** The tools an allowlist names, for display. Empty when the agent adds no allowlist of its own. */
359
+ export function allowedToolNames(tools) {
360
+ if (!isFrontmatter(tools) || tools["*"] !== false)
361
+ return [];
362
+ return Object.entries(tools).filter(([key, on]) => key !== "*" && on === true).map(([name]) => name);
363
+ }
364
+ /** `provider/modelId`, split into the two halves Pi's `set_model` and `--provider/--model` both need. */
365
+ export function parseAgentModel(model) {
366
+ if (typeof model !== "string")
367
+ return undefined;
368
+ // The slash is required: Pi rejects a model id with no provider (rpc-types.ts:33 needs both), and a
369
+ // bare string here would otherwise be stored as a provider with an empty modelId.
370
+ const slash = model.indexOf("/");
371
+ if (slash <= 0 || slash === model.length - 1)
372
+ return undefined;
373
+ return { provider: model.slice(0, slash), modelId: model.slice(slash + 1) };
374
+ }
375
+ /**
376
+ * Reads every `*.md` in `directory` as an agent definition. The file's base name is the agent id,
377
+ * matching OpenCode, so `agents/triage.md` is the agent `triage` and renaming the file renames it.
378
+ *
379
+ * A file that fails to parse is COLLECTED as a problem instead of throwing: one typo in one agent must
380
+ * not take down the picker and hide every other agent with it.
381
+ *
382
+ * `mode` picks WHICH half of one directory of definitions comes back, and defaults to `primary`. Both
383
+ * halves live in the same `agents/*.md` files - a sub-agent is the same format with `mode: subagent` -
384
+ * so the split is a filter on the parsed field, never a second directory or a second parser. A caller
385
+ * with no argument gets exactly what it always got.
386
+ */
387
+ /**
388
+ * Expands a leading tilde (`~` or `~/...` or `~\...`) to the user's home directory.
389
+ */
390
+ export function expandTilde(filepath) {
391
+ if (filepath === "~")
392
+ return homedir();
393
+ if (filepath.startsWith("~/") || filepath.startsWith("~\\")) {
394
+ return join(homedir(), filepath.slice(2));
395
+ }
396
+ return filepath;
397
+ }
398
+ /**
399
+ * The agents directory that ships WITH the package: the definitions Super Pi itself carries.
400
+ *
401
+ * WHY IT IS A FUNCTION AND NOT A CONSTANT. The package root is not the same directory in every
402
+ * layout - it is the repository root in a checkout and the installed package root in an npm install
403
+ * - so the path is derived from the same `rootDir` the discovery uses, and both sides of the
404
+ * "is this built-in?" question ask THIS function. If the two ever disagreed, a user agent could be
405
+ * filed as built-in and a built-in one as the user's, and the picker would sort them wrongly.
406
+ */
407
+ export function builtinAgentsDir(rootDir) {
408
+ return resolve(join(rootDir ?? resolve(import.meta.dirname, "../.."), "agents"));
409
+ }
410
+ /**
411
+ * Resolves the ordered list of directories to discover agents from:
412
+ * 1. Custom directories configured by the user in app settings (or options)
413
+ * 2. SUPER_PI_AGENTS_DIR environment variable if set
414
+ * 3. User global agent directories (~/.super_pi/agents, ~/.super-pi/agents, ~/.pi/agents)
415
+ * 4. Built-in repository/package agents directory (<rootDir>/agents)
416
+ *
417
+ * Duplicate paths are preserved in order of first appearance.
418
+ */
419
+ export function resolveAgentDirectories(options = {}) {
420
+ const dirs = [];
421
+ const add = (dir) => {
422
+ if (!dir)
423
+ return;
424
+ const trimmed = dir.trim();
425
+ if (!trimmed)
426
+ return;
427
+ const expanded = expandTilde(trimmed);
428
+ const resolved = resolve(expanded);
429
+ if (!dirs.includes(resolved)) {
430
+ dirs.push(resolved);
431
+ }
432
+ };
433
+ if (options.customDirs) {
434
+ for (const d of options.customDirs)
435
+ add(d);
436
+ }
437
+ const env = options.env ?? process.env;
438
+ if (env.SUPER_PI_AGENTS_DIR) {
439
+ add(env.SUPER_PI_AGENTS_DIR);
440
+ }
441
+ else {
442
+ try {
443
+ const home = homedir();
444
+ add(join(home, ".super_pi", "agents"));
445
+ add(join(home, ".super-pi", "agents"));
446
+ add(join(home, ".pi", "agents"));
447
+ }
448
+ catch {
449
+ // homedir() might throw in restricted sandbox environments
450
+ }
451
+ add(builtinAgentsDir(options.rootDir));
452
+ }
453
+ return dirs;
454
+ }
455
+ /**
456
+ * Whether two paths name the same directory.
457
+ *
458
+ * WHY THE COMPARISON IS NOT A PLAIN `===`. The paths that reach here were built by joining and
459
+ * resolving, so they are already absolute - but Windows paths are case-insensitive and a directory
460
+ * typed by hand (`d:\agents`) is the same directory as the one the app resolved itself
461
+ * (`D:\Agents`). Comparing them as strings would call the package's own agents directory "the user's"
462
+ * and put the built-in agents at the bottom of the picker, which is the defect this whole change is
463
+ * about.
464
+ */
465
+ function sameDirectory(left, right) {
466
+ const a = resolve(left);
467
+ const b = resolve(right);
468
+ return process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
469
+ }
470
+ export async function readAgents(directory, options = {}) {
471
+ const mode = options.mode ?? "primary";
472
+ const rawDirs = Array.isArray(directory) ? directory : [directory];
473
+ const dirs = rawDirs.filter(Boolean);
474
+ const agents = [];
475
+ const problems = [];
476
+ const seenIds = new Set();
477
+ // The directory whose definitions are the PACKAGE'S OWN. Everything else is the user's, and the
478
+ // two are listed separately so the package's agents can come first (see the sort at the end).
479
+ const builtinDir = options.builtinDir ?? builtinAgentsDir();
480
+ for (const dir of dirs) {
481
+ let entries;
482
+ try {
483
+ entries = await readdir(dir);
484
+ }
485
+ catch (error) {
486
+ if (error.code === "ENOENT")
487
+ continue;
488
+ throw error;
489
+ }
490
+ const isBuiltin = sameDirectory(dir, builtinDir);
491
+ for (const file of entries.filter((name) => name.toLowerCase().endsWith(".md")).sort()) {
492
+ // A FILE THAT CANNOT BE READ IS THE SAME KIND OF PROBLEM AS ONE THAT CANNOT BE PARSED.
493
+ //
494
+ // The function's own reason for existing says it plainly: "one typo in one agent must not take
495
+ // down the picker and hide every other agent with it". A file that cannot be READ is at least as
496
+ // ordinary as that - on Windows "another program has this file open" is a Tuesday, not an
497
+ // emergency - and it used to be the one unguarded step in this loop: the parse failure below is
498
+ // collected as a problem, while the read failure was thrown, so a single locked file emptied the
499
+ // whole directory. Four callers ate that: the main agent's own definition (the turn could not
500
+ // start), the roster handed to sub-agents on every turn, the roster used when dispatching one,
501
+ // and the picker (which came back with an empty agent list).
502
+ let source;
503
+ try {
504
+ source = await readFile(join(dir, file), "utf8");
505
+ }
506
+ catch (error) {
507
+ const fileId = file.replace(/\.md$/i, "");
508
+ if (!seenIds.has(fileId)) {
509
+ problems.push({ file, message: `读取失败:${error instanceof Error ? error.message : String(error)}` });
510
+ }
511
+ continue;
512
+ }
513
+ const parsed = parseDefinition(file, source);
514
+ if ("message" in parsed) {
515
+ const fileId = file.replace(/\.md$/i, "");
516
+ if (!seenIds.has(fileId)) {
517
+ problems.push({ file, message: parsed.message });
518
+ }
519
+ }
520
+ else {
521
+ if (!seenIds.has(parsed.id)) {
522
+ seenIds.add(parsed.id);
523
+ agents.push({ ...parsed, sourceDir: dir, builtin: isBuiltin });
524
+ }
525
+ }
526
+ }
527
+ }
528
+ // The half that was NOT asked for is filtered out here rather than marked in the UI: sub-agents are
529
+ // invoked BY an agent and never chosen by a human, so listing one in the picker would promise a role
530
+ // the runtime cannot honour.
531
+ //
532
+ // THE ORDER IS NOT DECIDED HERE. It is `orderAgentsForDisplay` - the one rule in
533
+ // `src/shared/agent-order.ts`, which the client applies too. The server orders the whole catalogue it
534
+ // read and hands out the half that was asked for, so what leaves the server is ALREADY in display
535
+ // order: the package's own agents first, the conversation roles before the delegated ones, and
536
+ // alphabetical by id inside each. Every surface that draws a server catalogue therefore inherits that
537
+ // order instead of guessing it, and the one place that MERGES two catalogues re-applies the same
538
+ // rule rather than inventing a second one.
539
+ //
540
+ // WHY THE GROUP ORDER DOES NOT TOUCH THE OVERRIDE RULE. The rule that decides WHICH definition of
541
+ // an id survives was applied above, while reading: the first directory to offer an id wins, and the
542
+ // user's directories are read before the package's own. Sorting here only reorders definitions that
543
+ // already survived that decision, so a user's copy of a built-in agent still wins - and it is then
544
+ // listed as the user's, because it IS the user's file.
545
+ return {
546
+ agents: orderAgentsForDisplay(agents).filter((agent) => agent.mode === mode),
547
+ problems,
548
+ };
549
+ }
550
+ /**
551
+ * WHAT KIND OF AGENT IS THIS ID?
552
+ *
553
+ * The catalogue is read in halves - the primaries and the subagents - and a question about ONE id
554
+ * has to be asked of both halves. The answer is the `mode:` frontmatter of the definition that
555
+ * WINS, which is the same override rule `readAgents` already applies: the first directory to offer
556
+ * an id owns it.
557
+ *
558
+ * `undefined` MEANS "NO SUCH AGENT IN THESE DIRECTORIES", and that is NOT the same as "not
559
+ * primary". An id nobody has heard of is a CUSTOM agent, and custom agents are legal - §3 keeps
560
+ * them legal on purpose, so that a project can name an agent the catalogue does not carry yet.
561
+ * Only an agent that EXISTS and is a subagent is a subagent.
562
+ *
563
+ * THE HIDDEN ONES COUNT. `hidden` decides whether a person is SHOWN an agent in a picker, not
564
+ * whether the agent exists, so a hidden subagent is still a subagent here. A guard that could be
565
+ * walked around by ticking one box in a frontmatter would not be a guard.
566
+ */
567
+ export async function agentModeOf(directories, agentId) {
568
+ const id = agentId.trim();
569
+ if (!id)
570
+ return undefined;
571
+ const dirs = Array.isArray(directories) ? [...directories] : [directories];
572
+ for (const mode of ["subagent", "primary"]) {
573
+ const scan = await readAgents(dirs, { mode });
574
+ if (scan.agents.some((agent) => agent.id === id))
575
+ return mode;
576
+ }
577
+ return undefined;
578
+ }
579
+ /** Only `#rgb` and `#rrggbb`. A `color:` frontmatter value is rendered as a CSS background, so it has to
580
+ * be a colour and nothing else - accepting an arbitrary string would put author-controlled text into a
581
+ * style declaration. Anything else is dropped rather than sanitised into something misleading. */
582
+ const HEX_COLOR = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
583
+ const color = (value) => (typeof value === "string" && HEX_COLOR.test(value.trim()) ? value.trim() : undefined);
584
+ /**
585
+ * The `task:` decision vocabulary, spelled the way OpenCode spells it in `agent.ts:165-167`, where the
586
+ * `plan` agent declares `task: { general: "deny" }`. `true`/`false` are accepted as the boolean
587
+ * equivalents so a definition can be written either way.
588
+ */
589
+ const TASK_DECISIONS = new Set(["allow", "deny", true, false]);
590
+ /**
591
+ * Reports a malformed `task:` value, or undefined when the map is usable.
592
+ *
593
+ * The same reasoning as `validateToolNames`, applied to the field one step along: `task:` is read by
594
+ * whatever implements dispatch, and a value outside this set cannot be acted on. `deny` is the safe
595
+ * direction, so the check exists to catch a typo (`allew`, `yes`) that would otherwise read as a
596
+ * misspelled permission and quietly mean nothing.
597
+ */
598
+ function validateTaskPolicy(taskPolicy) {
599
+ if (!isFrontmatter(taskPolicy))
600
+ return undefined;
601
+ const bad = Object.entries(taskPolicy).filter(([, decision]) => !TASK_DECISIONS.has(decision));
602
+ if (!bad.length)
603
+ return undefined;
604
+ return `task 的值只能是 allow 或 deny,收到 ${bad.map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(", ")}`;
605
+ }
606
+ /** Parses one definition file, or returns the reason it is not a usable agent. */
607
+ export function parseDefinition(file, source) {
608
+ const split = splitDefinition(source);
609
+ if (!split)
610
+ return { file, message: "缺少 YAML frontmatter(文件必须以 --- 开头)" };
611
+ const { frontmatter, body } = split;
612
+ const id = file.replace(/\.md$/i, "");
613
+ const mode = typeof frontmatter.mode === "string" ? frontmatter.mode.trim() : "primary";
614
+ if (mode !== "primary" && mode !== "subagent")
615
+ return { file, message: `mode 只能是 primary 或 subagent,收到 ${JSON.stringify(mode)}` };
616
+ const prompt = body.trim();
617
+ if (!prompt)
618
+ return { file, message: "正文为空:正文就是该 agent 的 system prompt" };
619
+ const tools = frontmatter.tools;
620
+ if (tools !== undefined && !isFrontmatter(tools))
621
+ return { file, message: "tools 必须是一个映射,例如 tools:\n \"*\": false\n read: true" };
622
+ const unknownTool = validateToolNames(tools);
623
+ if (unknownTool)
624
+ return { file, message: unknownTool };
625
+ const taskPolicy = frontmatter.task;
626
+ if (taskPolicy !== undefined && !isFrontmatter(taskPolicy))
627
+ return { file, message: "task 必须是一个映射,例如 task:\n \"*\": allow\n scout: deny" };
628
+ const badTaskDecision = validateTaskPolicy(taskPolicy);
629
+ if (badTaskDecision)
630
+ return { file, message: badTaskDecision };
631
+ const model = parseAgentModel(frontmatter.model);
632
+ if (frontmatter.model !== undefined && !model)
633
+ return { file, message: `model 必须是 provider/modelId 形式,收到 ${JSON.stringify(frontmatter.model)}` };
634
+ const promptMode = frontmatter.promptMode === undefined ? "append" : frontmatter.promptMode;
635
+ if (promptMode !== "append" && promptMode !== "replace")
636
+ return { file, message: `promptMode 只能是 append 或 replace,收到 ${JSON.stringify(promptMode)}` };
637
+ return {
638
+ id,
639
+ name: typeof frontmatter.name === "string" && frontmatter.name.trim() ? frontmatter.name.trim() : id,
640
+ mode,
641
+ description: typeof frontmatter.description === "string" ? frontmatter.description.trim() : "",
642
+ color: color(frontmatter.color),
643
+ hidden: frontmatter.hidden === true,
644
+ model,
645
+ thinkingLevel: typeof frontmatter.thinking === "string" && frontmatter.thinking.trim() ? frontmatter.thinking.trim() : undefined,
646
+ promptMode,
647
+ toolFlags: toolFlags(tools),
648
+ /** Which subagents this agent may dispatch, from the frontmatter `task:` map. Absent means no
649
+ * policy is expressed, NOT "allow everything" - the consuming dispatch code decides that, and
650
+ * this file deliberately does not implement the `task` tool itself. */
651
+ taskPolicy,
652
+ /** What the picker shows under the agent name. Empty means "Pi's own default tool set". */
653
+ toolNames: deniesAllTools(tools) ? [] : allowedToolNames(tools),
654
+ tools,
655
+ prompt,
656
+ };
657
+ }
658
+ /**
659
+ * Writes an agent's prompt body to `path` and returns that path, so it can be handed to Pi as
660
+ * `--append-system-prompt <file>` / `--system-prompt <file>`.
661
+ *
662
+ * A FILE, never the prompt text on the command line, and that is not a style choice. Pi resolves an
663
+ * existing path to its contents and anything else to literal text (resource-loader.ts:167-182), and
664
+ * Super Pi spawns Pi through `shell: true` on Windows because Pi is installed as a .cmd shim - so
665
+ * prompt text on argv would travel through cmd.exe, where a quote or an ampersand in an agent's
666
+ * instructions is a metacharacter. Writing the file also means the exact text Pi was given is a
667
+ * file on disk that can be read back as evidence.
668
+ */
669
+ export async function writeAgentPrompt(promptDir, agent) {
670
+ const path = join(promptDir, `${agent.id}.txt`);
671
+ // The directory is created here rather than assumed. `dataDir` exists at startup, but `agent-prompts`
672
+ // lives one level below it and nothing else creates it - and a missing directory would fail the very
673
+ // first turn of the very first conversation that selected an agent.
674
+ await mkdir(promptDir, { recursive: true });
675
+ await writeFile(path, agent.prompt, "utf8");
676
+ return path;
677
+ }
678
+ /**
679
+ * The spawn argv an agent adds, in the order Pi must receive it. Exported so the translation can be
680
+ * asserted without spawning anything, and so a probe can report exactly what was asked for.
681
+ *
682
+ * `options` are the caller's constraints on top of the definition's own `tools:` map - the two that
683
+ * exist are described on `ToolFlagOptions`. They are applied here rather than baked into
684
+ * `AgentDefinition.toolFlags` because they belong to the CALL: `PiRpcRuntime` adds `task` to the primary
685
+ * agent it is about to spawn, and the supervisor strips the parent's denies from the child it is about
686
+ * to spawn, and neither fact is a property of the definition file on disk.
687
+ */
688
+ export async function agentSpawnArgs(promptDir, agent, options = {}) {
689
+ if (!agent)
690
+ return [];
691
+ const args = [];
692
+ // Tools before the prompt: both are startup-time flags, and `--tools` also decides which tools the
693
+ // system prompt describes, so it has to be in effect before Pi builds the prompt at all.
694
+ args.push(...toolFlags(agent.tools, options));
695
+ const promptPath = await writeAgentPrompt(promptDir, agent);
696
+ // `append` keeps Pi's own coding-agent baseline (tool guidance, environment facts) and adds the
697
+ // role on top, which is what Pi's flag is for. `replace` is OpenCode's semantics - the agent's
698
+ // words are the whole system prompt - and is opt-in per agent because it strips that baseline.
699
+ args.push(agent.promptMode === "replace" ? "--system-prompt" : "--append-system-prompt", promptPath);
700
+ return args;
701
+ }