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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (370) hide show
  1. package/README.md +248 -3
  2. package/agents/code-auditor.md +64 -0
  3. package/agents/code-designer.md +64 -0
  4. package/agents/coder.md +24 -0
  5. package/agents/critic.md +24 -0
  6. package/agents/document-organizer.md +48 -0
  7. package/agents/patcher.md +27 -0
  8. package/agents/planner.md +30 -0
  9. package/agents/project-leader.md +28 -0
  10. package/agents/reviewer.md +27 -0
  11. package/agents/scout.md +27 -0
  12. package/agents/solution-designer.md +62 -0
  13. package/agents/super-pi-documents/index.ts +92 -0
  14. package/agents/super-pi-feishu/index.ts +88 -0
  15. package/agents/super-pi-knowledge/index.ts +70 -0
  16. package/agents/super-pi-managed-model/index.ts +9 -0
  17. package/agents/super-pi-memory/index.ts +75 -0
  18. package/agents/super-pi-native-tools/index.ts +1 -0
  19. package/agents/super-pi-task/core.ts +2262 -0
  20. package/agents/super-pi-task/index.ts +814 -0
  21. package/agents/super-pi-task/workflow-schema.ts +34 -0
  22. package/agents/super-pi-web/index.ts +32 -0
  23. package/agents/verifier.md +25 -0
  24. package/assets/fonts/LICENSE +92 -0
  25. package/assets/fonts/NotoSansSC-Bold.otf +0 -0
  26. package/assets/fonts/NotoSansSC-Regular.otf +0 -0
  27. package/assets/knowledge-model/README.md +37 -0
  28. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/config.json +31 -0
  29. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/onnx/model_quantized.onnx +0 -0
  30. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/special_tokens_map.json +7 -0
  31. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer.json +21278 -0
  32. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer_config.json +15 -0
  33. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/vocab.txt +21128 -0
  34. package/bin/npm-prefix.d.ts +1 -0
  35. package/bin/npm-prefix.js +10 -0
  36. package/bin/super-pi.js +349 -0
  37. package/dist/client/.super-pi-client-sources.json +82 -0
  38. package/dist/client/assets/CodeMirrorEditor-mi9rGUce.js +2 -0
  39. package/dist/client/assets/GitDiffEditor-CpoDDQrA.css +1 -0
  40. package/dist/client/assets/GitDiffEditor-FQBfGxOY.js +29 -0
  41. package/dist/client/assets/diff-ChtP43wD.js +1 -0
  42. package/dist/client/assets/dist-AW5lyI3I.js +1 -0
  43. package/dist/client/assets/dist-B3-a6uF0.js +7 -0
  44. package/dist/client/assets/dist-BGxkyh6e.js +1 -0
  45. package/dist/client/assets/dist-BJxfd7yb.js +11 -0
  46. package/dist/client/assets/dist-BRVQKlcp.js +1 -0
  47. package/dist/client/assets/dist-BV64A9Ji.js +1 -0
  48. package/dist/client/assets/dist-BXAOrsjq.js +1 -0
  49. package/dist/client/assets/dist-CKF2Jksy.js +1 -0
  50. package/dist/client/assets/dist-CX_Hm4GS.js +1 -0
  51. package/dist/client/assets/dist-Cus6_oaF.js +2 -0
  52. package/dist/client/assets/dist-Cx00EZKR.js +23 -0
  53. package/dist/client/assets/dist-D71y2EI1.js +1 -0
  54. package/dist/client/assets/dist-D978o95T.js +5 -0
  55. package/dist/client/assets/dist-Dc1MBGAG.js +1 -0
  56. package/dist/client/assets/dist-Dds-qLxY.js +9 -0
  57. package/dist/client/assets/dist-DeD9copn.js +1 -0
  58. package/dist/client/assets/dist-DuvGReu-.js +6 -0
  59. package/dist/client/assets/dist-Dvb0SqcK.js +2 -0
  60. package/dist/client/assets/dist-J6XWqRpB.js +3 -0
  61. package/dist/client/assets/dist-QzbOCAU6.js +1 -0
  62. package/dist/client/assets/dist-moiMRpw_.js +1 -0
  63. package/dist/client/assets/dist-scBkrwv-.js +2 -0
  64. package/dist/client/assets/dockerfile-BDePf5PZ.js +1 -0
  65. package/dist/client/assets/index-Cn7hdrDw.js +350 -0
  66. package/dist/client/assets/index-UfzqdECL.css +1 -0
  67. package/dist/client/assets/powershell-D8WpQPaX.js +1 -0
  68. package/dist/client/assets/properties-C357ku5U.js +1 -0
  69. package/dist/client/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  70. package/dist/client/assets/ruby-ChfNwlCY.js +1 -0
  71. package/dist/client/assets/shell-DwuoZtxw.js +1 -0
  72. package/dist/client/assets/swift-DKB6_1j6.js +1 -0
  73. package/dist/client/assets/toml-BPTmHmyx.js +1 -0
  74. package/dist/client/favicon.ico +0 -0
  75. package/dist/client/favicon.png +0 -0
  76. package/dist/client/favicon.svg +10 -0
  77. package/dist/client/index.html +18 -0
  78. package/dist/extension.d.ts +15 -0
  79. package/dist/extension.js +126 -0
  80. package/dist/server/active-memory.d.ts +247 -0
  81. package/dist/server/active-memory.js +669 -0
  82. package/dist/server/agents.d.ts +245 -0
  83. package/dist/server/agents.js +701 -0
  84. package/dist/server/application/catalog-service.d.ts +98 -0
  85. package/dist/server/application/catalog-service.js +245 -0
  86. package/dist/server/application/conversation-service.d.ts +245 -0
  87. package/dist/server/application/conversation-service.js +654 -0
  88. package/dist/server/application/document-service.d.ts +68 -0
  89. package/dist/server/application/document-service.js +120 -0
  90. package/dist/server/application/extension-ui-service.d.ts +44 -0
  91. package/dist/server/application/extension-ui-service.js +135 -0
  92. package/dist/server/application/feishu-service.d.ts +179 -0
  93. package/dist/server/application/feishu-service.js +358 -0
  94. package/dist/server/application/group-chat-service.d.ts +75 -0
  95. package/dist/server/application/group-chat-service.js +953 -0
  96. package/dist/server/application/group-execution.d.ts +15 -0
  97. package/dist/server/application/group-execution.js +77 -0
  98. package/dist/server/application/project-service.d.ts +464 -0
  99. package/dist/server/application/project-service.js +2523 -0
  100. package/dist/server/application/provider-service.d.ts +174 -0
  101. package/dist/server/application/provider-service.js +510 -0
  102. package/dist/server/application/run-service.d.ts +547 -0
  103. package/dist/server/application/run-service.js +2683 -0
  104. package/dist/server/application/scheduled-task-service.d.ts +184 -0
  105. package/dist/server/application/scheduled-task-service.js +391 -0
  106. package/dist/server/application/session-orchestrator-service.d.ts +388 -0
  107. package/dist/server/application/session-orchestrator-service.js +1146 -0
  108. package/dist/server/application/session-reminder-service.d.ts +59 -0
  109. package/dist/server/application/session-reminder-service.js +141 -0
  110. package/dist/server/application/session-watchdog.d.ts +171 -0
  111. package/dist/server/application/session-watchdog.js +284 -0
  112. package/dist/server/application/workspace-service.d.ts +52 -0
  113. package/dist/server/application/workspace-service.js +186 -0
  114. package/dist/server/application/worktree-service.d.ts +13 -0
  115. package/dist/server/application/worktree-service.js +76 -0
  116. package/dist/server/browser-access.d.ts +34 -0
  117. package/dist/server/browser-access.js +89 -0
  118. package/dist/server/capability.d.ts +105 -0
  119. package/dist/server/capability.js +170 -0
  120. package/dist/server/command-handler.d.ts +93 -0
  121. package/dist/server/command-handler.js +540 -0
  122. package/dist/server/content-search.d.ts +16 -0
  123. package/dist/server/content-search.js +235 -0
  124. package/dist/server/conversation-usage.d.ts +22 -0
  125. package/dist/server/conversation-usage.js +43 -0
  126. package/dist/server/documents.d.ts +152 -0
  127. package/dist/server/documents.js +998 -0
  128. package/dist/server/engineering-learning.d.ts +30 -0
  129. package/dist/server/engineering-learning.js +106 -0
  130. package/dist/server/exec-service.d.ts +45 -0
  131. package/dist/server/exec-service.js +167 -0
  132. package/dist/server/explicit-file-open.d.ts +34 -0
  133. package/dist/server/explicit-file-open.js +105 -0
  134. package/dist/server/failure-text.d.ts +18 -0
  135. package/dist/server/failure-text.js +44 -0
  136. package/dist/server/feishu-cli.d.ts +223 -0
  137. package/dist/server/feishu-cli.js +464 -0
  138. package/dist/server/file-changes.d.ts +119 -0
  139. package/dist/server/file-changes.js +280 -0
  140. package/dist/server/file-diff.d.ts +41 -0
  141. package/dist/server/file-diff.js +97 -0
  142. package/dist/server/file-index.d.ts +100 -0
  143. package/dist/server/file-index.js +296 -0
  144. package/dist/server/file-name-index.d.ts +160 -0
  145. package/dist/server/file-name-index.js +411 -0
  146. package/dist/server/files.d.ts +269 -0
  147. package/dist/server/files.js +748 -0
  148. package/dist/server/git.d.ts +245 -0
  149. package/dist/server/git.js +903 -0
  150. package/dist/server/http-server.d.ts +45 -0
  151. package/dist/server/http-server.js +3830 -0
  152. package/dist/server/index.d.ts +1 -0
  153. package/dist/server/index.js +485 -0
  154. package/dist/server/inline-thinking.d.ts +90 -0
  155. package/dist/server/inline-thinking.js +181 -0
  156. package/dist/server/json-comments.d.ts +14 -0
  157. package/dist/server/json-comments.js +71 -0
  158. package/dist/server/knowledge-embedding-worker.d.ts +1 -0
  159. package/dist/server/knowledge-embedding-worker.js +27 -0
  160. package/dist/server/knowledge-vectors.d.ts +150 -0
  161. package/dist/server/knowledge-vectors.js +385 -0
  162. package/dist/server/knowledge.d.ts +273 -0
  163. package/dist/server/knowledge.js +848 -0
  164. package/dist/server/length-continuation.d.ts +83 -0
  165. package/dist/server/length-continuation.js +118 -0
  166. package/dist/server/logging.d.ts +32 -0
  167. package/dist/server/logging.js +185 -0
  168. package/dist/server/managed-http-tunnel.d.ts +6 -0
  169. package/dist/server/managed-http-tunnel.js +85 -0
  170. package/dist/server/managed-http.d.ts +4 -0
  171. package/dist/server/managed-http.js +85 -0
  172. package/dist/server/managed-model-adapter.d.ts +17 -0
  173. package/dist/server/managed-model-adapter.js +75 -0
  174. package/dist/server/managed-model-gateway.d.ts +49 -0
  175. package/dist/server/managed-model-gateway.js +73 -0
  176. package/dist/server/managed-servers.d.ts +55 -0
  177. package/dist/server/managed-servers.js +392 -0
  178. package/dist/server/managed-ssh.d.ts +26 -0
  179. package/dist/server/managed-ssh.js +73 -0
  180. package/dist/server/manager-vault.d.ts +11 -0
  181. package/dist/server/manager-vault.js +67 -0
  182. package/dist/server/memory-recall.d.ts +25 -0
  183. package/dist/server/memory-recall.js +45 -0
  184. package/dist/server/memory.d.ts +67 -0
  185. package/dist/server/memory.js +216 -0
  186. package/dist/server/message-media.d.ts +7 -0
  187. package/dist/server/message-media.js +54 -0
  188. package/dist/server/model-context-window.d.ts +186 -0
  189. package/dist/server/model-context-window.js +444 -0
  190. package/dist/server/model-filter.d.ts +23 -0
  191. package/dist/server/model-filter.js +48 -0
  192. package/dist/server/models-store.d.ts +36 -0
  193. package/dist/server/models-store.js +132 -0
  194. package/dist/server/native-tool-settings.d.ts +25 -0
  195. package/dist/server/native-tool-settings.js +41 -0
  196. package/dist/server/native-tools-extension.d.ts +2 -0
  197. package/dist/server/native-tools-extension.js +39 -0
  198. package/dist/server/native-tools-service.d.ts +39 -0
  199. package/dist/server/native-tools-service.js +240 -0
  200. package/dist/server/persistence/app-state-repository.d.ts +65 -0
  201. package/dist/server/persistence/app-state-repository.js +1 -0
  202. package/dist/server/persistence/json-state-repository.d.ts +14 -0
  203. package/dist/server/persistence/json-state-repository.js +43 -0
  204. package/dist/server/persistence/open-state-store.d.ts +3 -0
  205. package/dist/server/persistence/open-state-store.js +35 -0
  206. package/dist/server/persistence/rename.d.ts +22 -0
  207. package/dist/server/persistence/rename.js +44 -0
  208. package/dist/server/persistence/sqlite-state-repository.d.ts +12 -0
  209. package/dist/server/persistence/sqlite-state-repository.js +264 -0
  210. package/dist/server/pi-command.d.ts +94 -0
  211. package/dist/server/pi-command.js +265 -0
  212. package/dist/server/pi-native.d.ts +12 -0
  213. package/dist/server/pi-native.js +16 -0
  214. package/dist/server/pi-session-events.d.ts +158 -0
  215. package/dist/server/pi-session-events.js +373 -0
  216. package/dist/server/pi-session-pool.d.ts +233 -0
  217. package/dist/server/pi-session-pool.js +382 -0
  218. package/dist/server/pi-session.d.ts +642 -0
  219. package/dist/server/pi-session.js +655 -0
  220. package/dist/server/presentations/schema.d.ts +120 -0
  221. package/dist/server/presentations/schema.js +128 -0
  222. package/dist/server/provider-network.d.ts +16 -0
  223. package/dist/server/provider-network.js +106 -0
  224. package/dist/server/provider-proxy.d.ts +18 -0
  225. package/dist/server/provider-proxy.js +200 -0
  226. package/dist/server/providers.d.ts +333 -0
  227. package/dist/server/providers.js +989 -0
  228. package/dist/server/remote-bootstrap.d.ts +17 -0
  229. package/dist/server/remote-bootstrap.js +119 -0
  230. package/dist/server/rpc-channel.d.ts +131 -0
  231. package/dist/server/rpc-channel.js +135 -0
  232. package/dist/server/runtime.d.ts +1393 -0
  233. package/dist/server/runtime.js +3286 -0
  234. package/dist/server/scheduled-tasks.d.ts +101 -0
  235. package/dist/server/scheduled-tasks.js +138 -0
  236. package/dist/server/server-context.d.ts +119 -0
  237. package/dist/server/server-context.js +1 -0
  238. package/dist/server/session-cwd.d.ts +19 -0
  239. package/dist/server/session-cwd.js +58 -0
  240. package/dist/server/session-ledger.d.ts +67 -0
  241. package/dist/server/session-ledger.js +76 -0
  242. package/dist/server/session-memory-scope.d.ts +4 -0
  243. package/dist/server/session-memory-scope.js +30 -0
  244. package/dist/server/session-repository.d.ts +100 -0
  245. package/dist/server/session-repository.js +246 -0
  246. package/dist/server/session-tree-scope.d.ts +125 -0
  247. package/dist/server/session-tree-scope.js +337 -0
  248. package/dist/server/skills.d.ts +23 -0
  249. package/dist/server/skills.js +190 -0
  250. package/dist/server/store.d.ts +1062 -0
  251. package/dist/server/store.js +3305 -0
  252. package/dist/server/subagent-runs.d.ts +185 -0
  253. package/dist/server/subagent-runs.js +383 -0
  254. package/dist/server/subagents.d.ts +200 -0
  255. package/dist/server/subagents.js +619 -0
  256. package/dist/server/task-tool.d.ts +282 -0
  257. package/dist/server/task-tool.js +507 -0
  258. package/dist/server/tavily.d.ts +32 -0
  259. package/dist/server/tavily.js +136 -0
  260. package/dist/server/team-context.d.ts +12 -0
  261. package/dist/server/team-context.js +180 -0
  262. package/dist/server/terminal.d.ts +163 -0
  263. package/dist/server/terminal.js +557 -0
  264. package/dist/server/thinking-level-discovery.d.ts +38 -0
  265. package/dist/server/thinking-level-discovery.js +183 -0
  266. package/dist/server/time-zone.d.ts +20 -0
  267. package/dist/server/time-zone.js +32 -0
  268. package/dist/server/tool-calls.d.ts +130 -0
  269. package/dist/server/tool-calls.js +341 -0
  270. package/dist/server/tool-llm.d.ts +72 -0
  271. package/dist/server/tool-llm.js +146 -0
  272. package/dist/server/tool-registry.d.ts +129 -0
  273. package/dist/server/tool-registry.js +249 -0
  274. package/dist/server/tool-runner.d.ts +112 -0
  275. package/dist/server/tool-runner.js +306 -0
  276. package/dist/server/turn-failure.d.ts +48 -0
  277. package/dist/server/turn-failure.js +148 -0
  278. package/dist/server/types.d.ts +2315 -0
  279. package/dist/server/types.js +11 -0
  280. package/dist/server/update-status.d.ts +14 -0
  281. package/dist/server/update-status.js +69 -0
  282. package/dist/server/update.d.ts +46 -0
  283. package/dist/server/update.js +104 -0
  284. package/dist/server/upload.d.ts +35 -0
  285. package/dist/server/upload.js +177 -0
  286. package/dist/server/version.d.ts +33 -0
  287. package/dist/server/version.js +111 -0
  288. package/dist/server/web.d.ts +27 -0
  289. package/dist/server/web.js +183 -0
  290. package/dist/server/workflow-engine.d.ts +47 -0
  291. package/dist/server/workflow-engine.js +255 -0
  292. package/dist/server/workflow.d.ts +329 -0
  293. package/dist/server/workflow.js +469 -0
  294. package/dist/server/workspace-file-indexes.d.ts +2 -0
  295. package/dist/server/workspace-file-indexes.js +61 -0
  296. package/dist/server/workspace-file-operations.d.ts +36 -0
  297. package/dist/server/workspace-file-operations.js +281 -0
  298. package/dist/server/workspace-file-response.d.ts +7 -0
  299. package/dist/server/workspace-file-response.js +79 -0
  300. package/dist/server/ws-server.d.ts +149 -0
  301. package/dist/server/ws-server.js +640 -0
  302. package/dist/shared/agent-order.d.ts +44 -0
  303. package/dist/shared/agent-order.js +50 -0
  304. package/dist/shared/archive-decisions.d.ts +44 -0
  305. package/dist/shared/archive-decisions.js +98 -0
  306. package/dist/shared/background-task.d.ts +25 -0
  307. package/dist/shared/background-task.js +183 -0
  308. package/dist/shared/child-session-lock.d.ts +37 -0
  309. package/dist/shared/child-session-lock.js +59 -0
  310. package/dist/shared/content-search.d.ts +22 -0
  311. package/dist/shared/content-search.js +1 -0
  312. package/dist/shared/conversation-title.d.ts +4 -0
  313. package/dist/shared/conversation-title.js +4 -0
  314. package/dist/shared/file-mentions.d.ts +17 -0
  315. package/dist/shared/file-mentions.js +91 -0
  316. package/dist/shared/git-commit.d.ts +11 -0
  317. package/dist/shared/git-commit.js +1 -0
  318. package/dist/shared/git-graph.d.ts +42 -0
  319. package/dist/shared/git-graph.js +30 -0
  320. package/dist/shared/group-chat.d.ts +132 -0
  321. package/dist/shared/group-chat.js +6 -0
  322. package/dist/shared/managed-servers.d.ts +36 -0
  323. package/dist/shared/managed-servers.js +1 -0
  324. package/dist/shared/message-media.d.ts +12 -0
  325. package/dist/shared/message-media.js +27 -0
  326. package/dist/shared/model-window-label.d.ts +39 -0
  327. package/dist/shared/model-window-label.js +55 -0
  328. package/dist/shared/native-tools.d.ts +43 -0
  329. package/dist/shared/native-tools.js +1 -0
  330. package/dist/shared/pi-cache-warming.d.ts +9 -0
  331. package/dist/shared/pi-cache-warming.js +4 -0
  332. package/dist/shared/project-overview.d.ts +107 -0
  333. package/dist/shared/project-overview.js +92 -0
  334. package/dist/shared/project-presentation.d.ts +55 -0
  335. package/dist/shared/project-presentation.js +111 -0
  336. package/dist/shared/provider-network.d.ts +30 -0
  337. package/dist/shared/provider-network.js +1 -0
  338. package/dist/shared/session-reporting.d.ts +40 -0
  339. package/dist/shared/session-reporting.js +97 -0
  340. package/dist/shared/session-search.d.ts +14 -0
  341. package/dist/shared/session-search.js +1 -0
  342. package/dist/shared/team-context-view.d.ts +33 -0
  343. package/dist/shared/team-context-view.js +49 -0
  344. package/dist/shared/team-context.d.ts +59 -0
  345. package/dist/shared/team-context.js +3 -0
  346. package/dist/shared/terminal-protocol.d.ts +71 -0
  347. package/dist/shared/terminal-protocol.js +1 -0
  348. package/dist/shared/thinking-levels.d.ts +53 -0
  349. package/dist/shared/thinking-levels.js +85 -0
  350. package/dist/shared/tool-glyph.d.ts +7 -0
  351. package/dist/shared/tool-glyph.js +19 -0
  352. package/dist/shared/transcript-order.d.ts +7 -0
  353. package/dist/shared/transcript-order.js +12 -0
  354. package/dist/shared/update-status.d.ts +28 -0
  355. package/dist/shared/update-status.js +1 -0
  356. package/dist/shared/workspace-file-preview.d.ts +4 -0
  357. package/dist/shared/workspace-file-preview.js +28 -0
  358. package/package.json +448 -4
  359. package/scripts/diagnose.mjs +603 -0
  360. package/scripts/patch-brace-expansion.mjs +260 -0
  361. package/scripts/restart-server.mjs +104 -0
  362. package/skills/presentation/SKILL.md +30 -0
  363. package/skills/presentation/references/data.md +10 -0
  364. package/skills/presentation/references/quality.md +12 -0
  365. package/skills/presentation/references/story.md +12 -0
  366. package/skills/presentation/references/templates-and-editing.md +11 -0
  367. package/skills/presentation/references/visual-system.md +10 -0
  368. package/skills/super-pi-agent-development/SKILL.md +25 -0
  369. package/skills/super-pi-development/SKILL.md +31 -0
  370. package/skills/super-pi-tool-development/SKILL.md +39 -0
@@ -0,0 +1,814 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import { workflowNodeSchema } from "./workflow-schema.ts";
3
+ import { PROJECT_TOOL_NAME, PROJECT_DESCRIPTION, TEAM_COORDINATION_DESCRIPTION, TEAM_CONTEXT_SECTION_KEY, loadTeamContext, readProjectConfig, executeProject } from "./core.ts";
4
+ import {
5
+ SUPER_PI_CAPABILITIES_SECTION,
6
+ SUPER_PI_CAPABILITIES_SECTION_KEY,
7
+ TASK_TOOL_NAME,
8
+ describeTask,
9
+ executeTask,
10
+ readTaskConfig,
11
+ type TaskParams,
12
+ type TaskToolResult,
13
+ } from "./core.ts";
14
+ import {
15
+ WORKFLOW_DESCRIPTION,
16
+ WORKFLOW_TOOL_NAME,
17
+ executeWorkflow,
18
+ readWorkflowConfig,
19
+ type WorkflowParams,
20
+ } from "./core.ts";
21
+ import {
22
+ TODO_DESCRIPTION,
23
+ TODO_TOOL_NAME,
24
+ executeTodo,
25
+ readTodoConfig,
26
+ type TodoParams,
27
+ } from "./core.ts";
28
+ import {
29
+ RUN_ASYNC_DESCRIPTION,
30
+ RUN_ASYNC_TOOL_NAME,
31
+ executeAsync,
32
+ type RunAsyncParams,
33
+ } from "./core.ts";
34
+ import {
35
+ SCHEDULED_TASK_DESCRIPTION,
36
+ SCHEDULED_TASK_TOOL_NAME,
37
+ executeScheduledTask,
38
+ readScheduledTaskConfig,
39
+ type ScheduledTaskParams,
40
+ } from "./core.ts";
41
+ import {
42
+ SESSION_SPAWN_TOOL_NAME,
43
+ SESSION_STATUS_TOOL_NAME,
44
+ SESSION_DISPATCH_TOOL_NAME,
45
+ SESSION_STOP_TOOL_NAME,
46
+ SESSION_REPORT_TOOL_NAME,
47
+ SESSION_STOP_SUBTREE_TOOL_NAME,
48
+ SESSION_REMOVE_TOOL_NAME,
49
+ SESSION_REMINDER_TOOL_NAME,
50
+ WORKTREE_TOOL_NAME,
51
+ executeWorktree,
52
+ type WorktreeToolParams,
53
+ SESSION_SPAWN_DESCRIPTION,
54
+ SESSION_STATUS_DESCRIPTION,
55
+ SESSION_DISPATCH_DESCRIPTION,
56
+ SESSION_STOP_DESCRIPTION,
57
+ SESSION_REPORT_DESCRIPTION,
58
+ SESSION_STOP_SUBTREE_DESCRIPTION,
59
+ SESSION_REMOVE_DESCRIPTION,
60
+ SESSION_REMINDER_DESCRIPTION,
61
+ executeSessionSpawn,
62
+ executeSessionStatus,
63
+ executeSessionDispatch,
64
+ executeSessionStop,
65
+ executeSessionReport,
66
+ executeSessionStopSubtree,
67
+ executeSessionRemove,
68
+ executeSessionReminder,
69
+ readOrchestratorConfig,
70
+ type SessionSpawnParams,
71
+ type SessionStatusParams,
72
+ type SessionDispatchParams,
73
+ type SessionStopParams,
74
+ type SessionReportParams,
75
+ type SessionStopSubtreeParams,
76
+ type SessionRemoveParams,
77
+ type SessionReminderParams,
78
+ } from "./core.ts";
79
+
80
+ /**
81
+ * The Pi adapter for the `task` and `todowrite` tools. Everything with a decision in it is in
82
+ * `./core.ts`; this file is the mounting hardware and nothing else.
83
+ *
84
+ * `@sinclair/typebox` is Pi's VIRTUAL MODULE (packages/coding-agent/src/core/extensions/virtual-modules.ts),
85
+ * which is why importing it works here and would not work anywhere else in this repository: it is not in
86
+ * `package.json` and is not installed in `node_modules`. Nothing outside Pi may import this file for that
87
+ * reason - `scripts/task-tool.test.mjs` drives `core.ts` instead, and reads this file as TEXT for the
88
+ * things that cannot be executed outside Pi.
89
+ *
90
+ * The parameter schema is OpenCode's `task.ts:43-52` verbatim, including `task_id`. `task_id` is
91
+ * accepted and ignored in this step: resuming a sub-agent's session would mean keeping its Pi process
92
+ * and its transcript alive between calls, and `runtime.ts` kills the primary's Pi after every turn, so
93
+ * there is nothing for a session id to point at yet. It is kept in the schema because removing it would
94
+ * make this tool incompatible with a model that has been told the OpenCode shape, and because the next
95
+ * step is precisely the thing that gives it meaning.
96
+ */
97
+ const Parameters = Type.Object({
98
+ description: Type.String({ description: "A short (3-5 words) description of the task" }),
99
+ prompt: Type.String({ description: "The task for the agent to perform" }),
100
+ subagent_type: Type.String({ description: "The type of specialized agent to use for this task" }),
101
+ task_id: Type.Optional(Type.String({ description: "Resume a previous task when supported" })),
102
+ });
103
+ const QuestionParameters = Type.Object({ question: Type.String(), options: Type.Array(Type.String(), { minItems: 1 }), multiple: Type.Optional(Type.Boolean()), extraNote: Type.Optional(Type.Boolean()) });
104
+ const ToolRegisterParameters = Type.Object({ slug: Type.String({ description: "Lowercase global tool slug, e.g. json-viewer" }), name: Type.String({ description: "Human-readable tool name" }), glyph: Type.Optional(Type.String({ description: "Distinctive plain-text icon, 1-4 Unicode characters, e.g. {} or ∑" })), description: Type.Optional(Type.String()), dialogSize: Type.Optional(Type.Object({ width: Type.Number({ description: "Popup width in CSS pixels; clamped to 480-1800" }), height: Type.Number({ description: "Popup height in CSS pixels; clamped to 360-1400" }) })), entrypoint: Type.Optional(Type.String({ description: "HTML entrypoint, normally index.html" })), files: Type.Array(Type.Object({ path: Type.String({ description: "Tool-relative file path" }), content: Type.String({ description: "Complete UTF-8 text content" }) }), { minItems: 1, maxItems: 32 }), script: Type.Optional(Type.Object({ path: Type.String({ description: "Optional tool-relative Python .py entrypoint" }), timeoutMs: Type.Optional(Type.Number()), parameters: Type.Optional(Type.Record(Type.String(), Type.Object({ type: Type.Union([Type.Literal("string"), Type.Literal("number"), Type.Literal("boolean"), Type.Literal("object"), Type.Literal("array")]), required: Type.Optional(Type.Boolean()), enum: Type.Optional(Type.Array(Type.Union([Type.String(), Type.Number(), Type.Boolean()]))) }))) })) });
105
+ const ToolShortcutParameters = Type.Object({ slug: Type.String(), action: Type.Union([Type.Literal("get"), Type.Literal("set")]), shortcut: Type.Optional(Type.Union([Type.Null(), Type.Object({ key: Type.String(), ctrl: Type.Optional(Type.Boolean()), alt: Type.Optional(Type.Boolean()), shift: Type.Optional(Type.Boolean()), meta: Type.Optional(Type.Boolean()) })])) });
106
+ const ToolRemoveParameters = Type.Object({ slug: Type.String({ description: "The existing global tool slug to remove" }) });
107
+
108
+ /**
109
+ * The `todowrite` parameter schema, OpenCode's `tool/todo.ts:6-8` in the TypeBox dialect this adapter
110
+ * speaks. `todos` is the WHOLE list every time - it replaces the list rather than adding to it - which is
111
+ * stated in the per-property description, because a model that assumes it appends will send one item and
112
+ * watch the other forty disappear.
113
+ *
114
+ * `id` is absent from the schema on purpose and this is the ONE place Super Pi's copy differs from
115
+ * OpenCode's: OpenCode's `Todo.Info` carries only content/status/priority. Super Pi keeps those three and
116
+ * ADDS a stable id server-side (`normalizeTodos`), which the schema does not mention so the model is not
117
+ * invited to invent ids it will not control.
118
+ */
119
+ const TodoParameters = Type.Object({
120
+ todos: Type.Array(Type.Object({
121
+ content: Type.String({ description: "The task text, specific and actionable" }),
122
+ status: Type.Union([Type.Literal("pending"), Type.Literal("in_progress"), Type.Literal("completed")], { description: "pending = not started, in_progress = being worked on now (exactly one at a time), completed = finished successfully" }),
123
+ priority: Type.Optional(Type.Union([Type.Literal("high"), Type.Literal("medium"), Type.Literal("low")], { description: "How urgent this item is" })),
124
+ }), { description: "The COMPLETE updated todo list - this replaces the previous list entirely, so include every item you still want on screen" }),
125
+ });
126
+
127
+ /**
128
+ * The only structural type this file needs, declared locally.
129
+ *
130
+ * It was `import type { ExtensionFactory } from "F:/code/open_agents_repo/pi/..."` before, which is an
131
+ * absolute path into one machine's checkout: fine there, unresolvable on any other, and it made this
132
+ * file impossible to open without that checkout present. Pi is a runtime, not a build dependency of
133
+ * Super Pi, so there is no package to import its types from - declaring the two shapes this file uses is
134
+ * the honest alternative, and `npm run check` would not have caught the old one because `agents/` is
135
+ * outside every tsconfig.
136
+ */
137
+ type ExtensionToolDefinition = {
138
+ name: string;
139
+ label: string;
140
+ description: string;
141
+ parameters: unknown;
142
+ execute(toolCallId: string, params: unknown, signal: AbortSignal | undefined, onUpdate: unknown, context: { cwd: string }): Promise<unknown>;
143
+ prepareLoadout?(loadout: unknown): { descriptions?: Record<string, string> } | undefined;
144
+ };
145
+ /**
146
+ * The `workflow` parameter schema.
147
+ *
148
+ * `agentId` rather than `subagent_type`, and the difference is that it is REQUIRED here. A single
149
+ * dispatch can infer itself from its prompt - a model asking for one delegation is obvious about which
150
+ * agent it wants - but a plan of up to eight steps cannot: a step whose agent is unspecified would have to
151
+ * be guessed by the server, and a server that guesses which specialist to run is exactly the
152
+ * role-name branch this whole feature refuses to have.
153
+ *
154
+ * `onFailure` is a plain string rather than a TypeBox union so the SERVER owns the whitelist. A closed
155
+ * enum here would be a second list that could disagree with `parseFailurePolicy`, and the message a model
156
+ * gets for a bad value is better written by the side that knows the real options.
157
+ */
158
+ /**
159
+ * THE PROVIDER-FACING WORKFLOW NODE SCHEMA.
160
+ *
161
+ * Some OpenAI-compatible providers reject recursive `$ref` and object `anyOf` schemas before a
162
+ * request reaches the model. Keep this description provider-portable and leave strict recursive
163
+ * validation to the Super Pi workflow endpoint, which owns the actual runtime roster and limits.
164
+ * The nested `do` items stay open objects so loop and foreach bodies can still be recursive.
165
+ */
166
+ const WorkflowNodeParameters = Type.Unsafe(workflowNodeSchema());
167
+
168
+ const WorkflowParameters = Type.Object({
169
+ summary: Type.String({ description: "One line saying what this whole plan is for, shown to the user above the timeline" }),
170
+ onFailure: Type.Optional(Type.String({ description: "What to do when a step FAILS TO RUN: stop (default), skip, retry:1, retry:2 or retry:3" })),
171
+ steps: Type.Optional(Type.Array(Type.Object({
172
+ agentId: Type.String({ description: "The dispatchable sub-agent type to run, e.g. scout" }),
173
+ label: Type.Optional(Type.String({ description: "3-4 words saying what this step is FOR, shown to the user only" })),
174
+ prompt: Type.String({ description: "The instruction for THIS step alone. Earlier steps' output is added for you." }),
175
+ }), { minItems: 1, maxItems: 8, description: "Legacy flat steps, equivalent to step nodes" })),
176
+ nodes: Type.Optional(Type.Array(WorkflowNodeParameters, { minItems: 1, description: "Recursive step/loop/foreach plan; use this OR legacy steps, not both" })),
177
+ });
178
+
179
+ type ExtensionApi = { registerTool(tool: ExtensionToolDefinition): void; on(eventName: string, handler: (event: any) => unknown): void };
180
+
181
+ const extension = (pi: ExtensionApi): void => {
182
+ // THE CAPABILITIES SECTION, injected on every agent run of every primary conversation. The same
183
+ // Pi channel the knowledge extension uses for its document catalogue (`before_agent_start` +
184
+ // `systemPromptOptions.sections`, SDK-normalized so `sections` is always a Record), under its own
185
+ // key so the two never overwrite each other. It rides THIS extension because this is the one
186
+ // mounted on every primary panel conversation and on nothing else: sub-agent processes never load
187
+ // it, and the memory-review and rerank one-shots spawn with no extensions at all - exactly the
188
+ // audience that talks to a user and therefore needs to understand 「帮我开发一个 agent」.
189
+ pi.on("before_agent_start", (event: { systemPromptOptions: { sections: Record<string, string> } }) => {
190
+ event.systemPromptOptions.sections[SUPER_PI_CAPABILITIES_SECTION_KEY] = SUPER_PI_CAPABILITIES_SECTION;
191
+ return {};
192
+ });
193
+
194
+ // CAPTURED AT LOAD TIME, NOT READ PER CALL.
195
+ // In SDK session mode (`createPiSession`), `withEnvironment` injects the extension environment
196
+ // into `process.env` ONLY during `loader.reload()`. As soon as extensions finish loading, the
197
+ // environment variables are removed from `process.env`.
198
+ // Reading them inside `execute()` resulted in `endpoint` being undefined and failing with
199
+ // "The Super Pi tool registry is not available in this run."
200
+ // Capturing them here in closure variables guarantees they remain accessible for the session.
201
+ const toolsEndpoint = process.env.SUPER_PI_TOOLS_ENDPOINT;
202
+ const toolsCapability = process.env.SUPER_PI_TOOLS_CAPABILITY;
203
+ const questionEndpoint = process.env.SUPER_PI_QUESTION_ENDPOINT;
204
+ const taskConversationId = process.env.SUPER_PI_TASK_CONVERSATION;
205
+ const taskCapability = process.env.SUPER_PI_TASK_CAPABILITY;
206
+
207
+ // THE QUESTION TOOL. It blocks on an HTTP request until the person answers, and the answer comes back
208
+ // as the tool result, which is what keeps the run alive across the exchange - the model does not decide
209
+ // to continue, it cannot: the tool has not returned.
210
+ //
211
+ // IT RETURNS THE SHAPE EVERY OTHER TOOL HERE RETURNS, AND THAT IS NOT COSMETIC. `TaskToolResult` is
212
+ // `{content: [{type:"text", text}], details}` - `todo`, `task` and `workflow` all build it through the
213
+ // local `text()` helper. This tool used to `return` the parsed JSON object bare, which Pi does not read
214
+ // as a tool result at all: the model received an EMPTY result and said so - 「我无法复述你的答案,
215
+ // question 工具调用后返回了空结果」. The answer was in the store the whole time; it simply never arrived.
216
+ //
217
+ // A REFUSED QUESTION THROWS, and that is the whole of the dismissal semantics: a failed call is what
218
+ // stops the run. OpenCode is the reference and is explicit - rejecting a question fails the deferred
219
+ // and the tool dies (`packages/core/src/question.ts:128-141`). Nothing is invented to fill the gap, not
220
+ // `options[0]` and not an empty selection, which would look to the model exactly like a real choice.
221
+ pi.registerTool({ name: "question", label: "Question", description: "Ask the user a blocking single or multiple choice question with an optional extra note.", parameters: QuestionParameters, execute: async (_id, raw): Promise<TaskToolResult> => {
222
+ const endpoint = questionEndpoint;
223
+ const conversationId = taskConversationId;
224
+ const text = (body: string, isError?: boolean): TaskToolResult => ({ content: [{ type: "text", text: body }], details: undefined, ...(isError ? { isError: true } : {}) });
225
+ if (!endpoint || !conversationId) return text("This run cannot ask the user anything: the question endpoint is not available.", true);
226
+ const p = raw as { question: string; options: string[]; multiple?: boolean; extraNote?: boolean };
227
+ const capability = taskCapability;
228
+ const response = await fetch(endpoint, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ conversationId, ...p, capability }) });
229
+ const payload = await response.json() as { error?: string; answers?: { id: string; selected: string[]; note?: string }[]; summary?: string };
230
+ if (!response.ok || payload?.error) return text(payload?.error ?? `The question could not be delivered (HTTP ${response.status}).`, true);
231
+ // READABLE, NOT JUST PRESENT. The bare `{answers:[{id, selected}]}` carries a UUID and an array, and
232
+ // a model handed that has to guess what it means - which it did, describing a real answer as a
233
+ // cancellation. The text says what was asked and what was chosen, in words.
234
+ return text(JSON.stringify({ answers: (payload.answers ?? []).map((answer) => ({ question: p.question, selected: answer.selected, ...(answer.note ? { note: answer.note } : {}) })), ...(payload.summary ? { summary: payload.summary } : {}) }));
235
+ } });
236
+ pi.registerTool({ name: "tool_register", label: "Register Tool", description: "Register a global Super Pi sidebar tool. Use this when the user asks to create or add a right-sidebar tool. Send complete HTML/JS/CSS files directly; they are stored by Super Pi and work in every workspace. An optional registered Python script receives validated JSON on stdin and must print one JSON object to stdout. Declare environment.requiresPython/environment.requires (pinned exactly, pkg==version) for third-party Python packages - they are installed into this tool's own virtual environment on first run. If the tool needs the model (summarising, rewriting, extracting, classifying), call SuperPiTool.llm({prompt, system}) or SuperPiTool.llmText(...) from ./super-pi-tool.js instead of writing a client, and declare permissions: { llm: true } in this call or the server refuses it and the user is told on the import screen; Super Pi holds the credentials and chooses the model. In the HTML, load ./super-pi-tool.js and use SuperPiTool.run/get/wait/cancel for the tool's own Python jobs; do not call /api/exec, guess a tool id, or start another HTTP server.", promptSnippet: "register a newly created global right-sidebar tool with Super Pi", parameters: ToolRegisterParameters, execute: async (_id, raw, _signal, _update, _context): Promise<TaskToolResult> => {
237
+ const endpoint = toolsEndpoint;
238
+ const text = (body: string, isError?: boolean): TaskToolResult => ({ content: [{ type: "text", text: body }], details: undefined, ...(isError ? { isError: true } : {}) });
239
+ if (!endpoint) return text("The Super Pi tool registry is not available in this run.", true);
240
+ const p = raw as { slug: string; name: string; glyph?: string; description?: string; dialogSize?: { width: number; height: number }; entrypoint?: string; files: { path: string; content: string }[]; script?: unknown };
241
+ try {
242
+ const capability = toolsCapability;
243
+ const conversationId = taskConversationId;
244
+ if (!conversationId || !capability) return text("The Super Pi tool registry is not available in this run: missing session capability.", true);
245
+ const response = await fetch(endpoint, { method: "POST", headers: { "content-type": "application/json", ...(capability ? { "x-super-pi-capability": capability } : {}) }, body: JSON.stringify({ ...p, conversationId, capability }) });
246
+ const payload = await response.json() as { id?: string; error?: string };
247
+ if (!response.ok || payload.error) return text(payload.error ?? `Tool registration failed (HTTP ${response.status}).`, true);
248
+ return text(JSON.stringify({ registered: true, id: payload.id, url: `/tools/${payload.id}/`, runtime: "Load ./super-pi-tool.js; use SuperPiTool.run(params), SuperPiTool.get(runId), SuperPiTool.wait(runId), and SuperPiTool.cancel(runId). For the model use SuperPiTool.llm({prompt, system}) plus SuperPiTool.llmWait(id), or SuperPiTool.llmText({prompt, system}) to await the answer - never write your own model client." }));
249
+ } catch (error) { return text(`Tool registration could not reach Super Pi: ${error instanceof Error ? error.message : "unknown error"}`, true); }
250
+ } });
251
+ pi.registerTool({ name: "tool_shortcut", label: "Tool Shortcut", description: "Read or set the shortcut for a registered global sidebar tool by slug. A removed tool's shortcut is cleared; read it before removing a tool if it should be restored after re-registration. Setting a shortcut reports conflicts with other registered global tools.", parameters: ToolShortcutParameters, execute: async (_id, raw): Promise<TaskToolResult> => {
252
+ const text = (body: string, isError?: boolean): TaskToolResult => ({ content: [{ type: "text", text: body }], details: undefined, ...(isError ? { isError: true } : {}) });
253
+ const p = raw as { slug: string; action: "get" | "set"; shortcut?: { key: string; ctrl?: boolean; alt?: boolean; shift?: boolean; meta?: boolean } | null };
254
+ if (!toolsEndpoint || !toolsCapability || !taskConversationId) return text("The Super Pi tool registry is not available in this run.", true);
255
+ try {
256
+ const response = await fetch(toolsEndpoint.replace(/\/api\/tools$/, "/api/tools/agent"), { method: "POST", headers: { "content-type": "application/json", "x-super-pi-capability": toolsCapability }, body: JSON.stringify({ action: p.action === "get" ? "get-shortcut" : "set-shortcut", slug: p.slug, ...(p.action === "set" ? { shortcut: p.shortcut ?? null } : {}), conversationId: taskConversationId, capability: toolsCapability }) });
257
+ const payload = await response.json() as { shortcut?: unknown; error?: string };
258
+ if (!response.ok) return text(payload.error ?? `Shortcut operation failed (HTTP ${response.status}).`, true);
259
+ return text(JSON.stringify({ slug: p.slug, shortcut: payload.shortcut ?? null }));
260
+ } catch (error) { return text(`Shortcut operation could not reach Super Pi: ${error instanceof Error ? error.message : "unknown error"}`, true); }
261
+ } });
262
+ pi.registerTool({ name: "tool_remove", label: "Remove Tool", description: "Remove a registered global sidebar tool by slug. Its shortcut is cleared with the tool; call tool_shortcut first if the shortcut should be reassigned after re-registering.", parameters: ToolRemoveParameters, execute: async (_id, raw): Promise<TaskToolResult> => {
263
+ const text = (body: string, isError?: boolean): TaskToolResult => ({ content: [{ type: "text", text: body }], details: undefined, ...(isError ? { isError: true } : {}) });
264
+ const p = raw as { slug: string };
265
+ if (!toolsEndpoint || !toolsCapability || !taskConversationId) return text("The Super Pi tool registry is not available in this run.", true);
266
+ try {
267
+ const response = await fetch(toolsEndpoint.replace(/\/api\/tools$/, "/api/tools/agent"), { method: "POST", headers: { "content-type": "application/json", "x-super-pi-capability": toolsCapability }, body: JSON.stringify({ action: "remove", slug: p.slug, conversationId: taskConversationId, capability: toolsCapability }) });
268
+ const payload = await response.json() as { removed?: boolean; error?: string };
269
+ if (!response.ok || !payload.removed) return text(payload.error ?? "Tool removal failed.", true);
270
+ return text(JSON.stringify({ removed: true, slug: p.slug, shortcutCleared: true }));
271
+ } catch (error) { return text(`Tool removal could not reach Super Pi: ${error instanceof Error ? error.message : "unknown error"}`, true); }
272
+ } });
273
+ // Read ONCE at load, not per call: the environment cannot change under a running Pi, and `prepareLoadout`
274
+ // is synchronous - it cannot await a fetch for a roster - so the roster has to already be here.
275
+ const config = readTaskConfig(process.env);
276
+ // Same rule for the todo tool, and for a stronger reason: the todo endpoint is derived from the same
277
+ // listen address as the task endpoint, so reading it per call would mean re-reading an environment
278
+ // that cannot have changed since the process started.
279
+ const todoConfig = readTodoConfig(process.env);
280
+ // Same rule for the workflow tool: one read at load, because the environment cannot change under a
281
+ // running Pi. The capability it reads is minted for THIS turn and dies with it, so it is valid for
282
+ // exactly as long as this process is - which is the whole reason a sub-agent cannot present one.
283
+ const workflowConfig = readWorkflowConfig(process.env);
284
+ // Same rule for the scheduled-task tool: one read at load, because the environment cannot change
285
+ // under a running Pi, and the endpoint is supplied by the server rather than derived from anything
286
+ // in the process.
287
+ const scheduledTaskConfig = readScheduledTaskConfig(process.env);
288
+ const projectConfig = readProjectConfig(process.env);
289
+ pi.on("before_agent_start", async (event: { prompt?: string; systemPromptOptions: { sections: Record<string, string> } }, context?: { signal?: AbortSignal }) => {
290
+ try {
291
+ const notes = await loadTeamContext(projectConfig, context?.signal);
292
+ if (notes && !event.prompt?.includes(notes)) event.systemPromptOptions.sections[TEAM_CONTEXT_SECTION_KEY] = notes;
293
+ else delete event.systemPromptOptions.sections[TEAM_CONTEXT_SECTION_KEY];
294
+ } catch {
295
+ event.systemPromptOptions.sections[TEAM_CONTEXT_SECTION_KEY] = "项目共享上下文暂不可用;需要时调用 project get_context 获取,不要将历史快照当作最新结论。";
296
+ }
297
+ return {};
298
+ });
299
+ pi.registerTool({
300
+ name: PROJECT_TOOL_NAME, label: "Project", description: `${PROJECT_DESCRIPTION}\n${TEAM_COORDINATION_DESCRIPTION}\nFor parallel work from explored context, pass forkFromConversationId from an idle direct executor to dispatch taskIds. When the user selects a prepared context, use list_warm_sessions with projectId, then pass warmSessionId to dispatch. Use message to follow up with a direct task's retained session after acceptance.`,
301
+ parameters: Type.Object({
302
+ action: Type.Union(["create", "start", "get", "list", "list_warm_sessions", "add_task", "dispatch", "submit", "request_review", "review", "update_task", "report", "escalate", "resolve_escalation", "correct", "deliver", "cancel", "export", "share_context", "get_context", "message"].map((value) => Type.Literal(value))),
303
+ projectId: Type.Optional(Type.String()), taskId: Type.Optional(Type.String()),
304
+ taskIds: Type.Optional(Type.Array(Type.String(), { description: "For dispatch: independent ready task ids to start asynchronously; inspect both started and failed." })),
305
+ forkFromConversationId: Type.Optional(Type.String({ description: "For dispatch of new tasks: reuse the settled Pi history of an executor session in the same project that reports directly to you. Each task gets an independent fork under your supervision." })),
306
+ warmSessionId: Type.Optional(Type.String({ description: "For dispatch of new tasks: use an independent copy of a workspace snapshot explicitly saved by the user. Discover IDs with list_warm_sessions and the projectId. Cannot be combined with forkFromConversationId." })),
307
+ deliveryMode: Type.Optional(Type.Union([Type.Literal("queue"), Type.Literal("steer")], { description: "For message: queue behind current work, or steer at the next tool boundary without restarting the worker." })),
308
+ contextIds: Type.Optional(Type.Array(Type.String(), { description: "For get_context: exact shared entry ids to read without relevance filtering." })),
309
+ handoffNote: Type.Optional(Type.String({ description: "Task-specific discoveries, implementation guidance, known gaps and evidence; accepted by add_task/update_task/dispatch." })),
310
+ ownedPaths: Type.Optional(Type.Array(Type.String(), { description: "Workspace-relative files/directories this task will WRITE, no globs; declared active writers may not overlap." })),
311
+ readOnly: Type.Optional(Type.Boolean({ description: "Research/review task; do not modify files. May overlap active writers for inspection." })),
312
+ sharedContext: Type.Optional(Type.Array(Type.Object({
313
+ title: Type.String(), content: Type.String(),
314
+ kind: Type.Optional(Type.Union(["finding", "decision", "pitfall", "hypothesis"].map(value => Type.Literal(value)))),
315
+ evidenceRefs: Type.Optional(Type.Array(Type.String())), taskIds: Type.Optional(Type.Array(Type.String())), paths: Type.Optional(Type.Array(Type.String())),
316
+ id: Type.Optional(Type.String()), expectedRevision: Type.Optional(Type.Number()),
317
+ status: Type.Optional(Type.Union([Type.Literal("active"), Type.Literal("withdrawn")])),
318
+ }), { description: "Publish team discoveries in the same create/add_task/dispatch/submit/report call, or share_context; updates require id and expectedRevision." })),
319
+ parentTaskId: Type.Optional(Type.String()), role: Type.Optional(Type.Union([Type.Literal("leader"), Type.Literal("executor")])),
320
+ title: Type.Optional(Type.String({ description: "Required for action=\"create\" (and add_task): short project or task title. For action=\"create\" this and objective are the ONLY two fields you must send; every other field may be omitted." })),
321
+ objective: Type.Optional(Type.String({ description: "Required for action=\"create\" (and add_task): what the project or task should achieve. For action=\"create\" this and title are the ONLY two fields you must send." })),
322
+ deliverables: Type.Optional(Type.Array(Type.String(), { description: "Optional deliverables list. Omit if not needed; does not block starting." })),
323
+ acceptanceCriteria: Type.Optional(Type.Array(Type.String(), { description: "Optional acceptance criteria list. Omit if not needed; does not block starting." })),
324
+ constraints: Type.Optional(Type.Array(Type.String(), { description: "Optional constraints list. Omit if not needed; does not block starting." })),
325
+ dependencies: Type.Optional(Type.Array(Type.String())),
326
+ risk: Type.Optional(Type.String({ description: "Optional risk level (defaults to low; any value is accepted without error)." })),
327
+ mode: Type.Optional(Type.Union([Type.Literal("standard"), Type.Literal("lightweight")])),
328
+ priority: Type.Optional(Type.String()), status: Type.Optional(Type.String()), blockedReason: Type.Optional(Type.String()),
329
+ tasks: Type.Optional(Type.Array(Type.Object({
330
+ title: Type.String(), objective: Type.String(),
331
+ deliverables: Type.Optional(Type.Array(Type.String())), acceptanceCriteria: Type.Optional(Type.Array(Type.String())),
332
+ dependencies: Type.Optional(Type.Array(Type.String())), priority: Type.Optional(Type.String()),
333
+ handoffNote: Type.Optional(Type.String()), ownedPaths: Type.Optional(Type.Array(Type.String())), readOnly: Type.Optional(Type.Boolean()),
334
+ }), { description: "Optional initial top-level tasks. Omit to let the leader decompose and dispatch." })),
335
+ output: Type.Optional(Type.String()), evidenceRefs: Type.Optional(Type.Array(Type.String())), verdict: Type.Optional(Type.String()), summary: Type.Optional(Type.String()),
336
+ kind: Type.Optional(Type.String()), progress: Type.Optional(Type.String()), variance: Type.Optional(Type.String()), nextStep: Type.Optional(Type.String()),
337
+ risks: Type.Optional(Type.Array(Type.String())), decisionNeeded: Type.Optional(Type.String()), reason: Type.Optional(Type.String()), severity: Type.Optional(Type.String()),
338
+ escalationId: Type.Optional(Type.String({ description: "The id of the escalation to answer - take it from the escalations array that project(action=get) returns. Required for resolve_escalation" })),
339
+ decision: Type.Optional(Type.String({ description: "Your handling note on that escalation: what you decided and why. Required for resolve_escalation" })),
340
+ targetConversationId: Type.Optional(Type.String({ description: "For action=\"correct\": the project member session that receives the message. It must be inside this project's tree - a session outside it is refused." })),
341
+ content: Type.Optional(Type.String({ description: "For action=\"correct\": the one message sent to that member session, in its own words. Required for correct." })),
342
+ defaultLeaderProfile: Type.Optional(Type.Object({
343
+ agentId: Type.Optional(Type.String()), cwd: Type.Optional(Type.String()),
344
+ model: Type.Optional(Type.Object({ provider: Type.String(), modelId: Type.String() })),
345
+ thinkingLevel: Type.Optional(Type.String()), watchdogTimeoutSeconds: Type.Optional(Type.Number()),
346
+ })),
347
+ defaultExecutorProfile: Type.Optional(Type.Object({
348
+ agentId: Type.Optional(Type.String()), cwd: Type.Optional(Type.String()),
349
+ model: Type.Optional(Type.Object({ provider: Type.String(), modelId: Type.String() })),
350
+ thinkingLevel: Type.Optional(Type.String()), watchdogTimeoutSeconds: Type.Optional(Type.Number()),
351
+ })),
352
+ defaultReviewerProfile: Type.Optional(Type.Object({
353
+ agentId: Type.Optional(Type.String()), cwd: Type.Optional(Type.String()),
354
+ model: Type.Optional(Type.Object({ provider: Type.String(), modelId: Type.String() })),
355
+ thinkingLevel: Type.Optional(Type.String()), watchdogTimeoutSeconds: Type.Optional(Type.Number()),
356
+ })),
357
+ executorProfile: Type.Optional(Type.Object({
358
+ agentId: Type.Optional(Type.String()), cwd: Type.Optional(Type.String()),
359
+ model: Type.Optional(Type.Object({ provider: Type.String(), modelId: Type.String() })),
360
+ thinkingLevel: Type.Optional(Type.String()), watchdogTimeoutSeconds: Type.Optional(Type.Number()),
361
+ })),
362
+ reviewerProfile: Type.Optional(Type.Object({
363
+ agentId: Type.Optional(Type.String()), cwd: Type.Optional(Type.String()),
364
+ model: Type.Optional(Type.Object({ provider: Type.String(), modelId: Type.String() })),
365
+ thinkingLevel: Type.Optional(Type.String()), watchdogTimeoutSeconds: Type.Optional(Type.Number()),
366
+ })),
367
+ }),
368
+ execute: async (_toolCallId, params, signal) => executeProject(params as Record<string, unknown>, projectConfig, { signal: signal ?? undefined }),
369
+ });
370
+
371
+ pi.registerTool({
372
+ name: TASK_TOOL_NAME,
373
+ label: "Task",
374
+ // The fallback for the seconds between registration and the first `prepareLoadout`: the guidance with
375
+ // no roster, which is still true text rather than a placeholder.
376
+ description: describeTask(config.roster),
377
+ promptSnippet: "delegate substantial work to a specialized subagent",
378
+ parameters: Parameters,
379
+ /**
380
+ * Injects the roster into the description the model is shown, on every loadout.
381
+ *
382
+ * Pi's own mechanism for a tool that lists other tools, and the reason it is used rather than
383
+ * editing the system prompt: `ToolDefinition.prepareLoadout` is documented for exactly this
384
+ * (types.ts:620-622 - "Tools that orchestrate other tools use it"), it is called whenever the active
385
+ * tools change, and a description that Pi receives is a description that cannot drift from the tool
386
+ * set it belongs to. `describeTask()` in OpenCode does the same thing one layer up, inside
387
+ * `registry.ts`.
388
+ *
389
+ * Read from the environment the server filled at spawn time, never from a list written here, so a
390
+ * sub-agent added to `agents/*.md` while the server runs is dispatchable on the next message.
391
+ */
392
+ prepareLoadout: () => ({ descriptions: { [TASK_TOOL_NAME]: describeTask(config.roster) } }),
393
+ // `toolCallId` IS Pi's own id for this call, and it was being discarded as `_toolCallId`. It is what
394
+ // lets the server anchor the sub-agent's card to this row instead of sorting by a start time.
395
+ execute: async (toolCallId, params, signal, _onUpdate, context) =>
396
+ await executeTask(params as TaskParams, context, config, { signal: signal ?? undefined }, { toolCallId }),
397
+ });
398
+
399
+
400
+
401
+ /**
402
+ * `todowrite`, registered SECOND and for one reason: order in the tool list is the order a model reads
403
+ * them in, and a plan is worth more in front of the eye than a dispatcher is. Nothing depends on the
404
+ * order functionally - `runtime.ts` names both tools in its allowlist and Pi activates whichever of them
405
+ * the agent's own `tools:` map allows.
406
+ *
407
+ * NO `prepareLoadout`, and that is a decision rather than an omission. The task tool needs one because
408
+ * its description embeds the ROSTER, which changes on disk while the server runs; the todo description
409
+ * embeds nothing that changes, and the thing that does change - the current list - is the tool's own
410
+ * OUTPUT, which the model reads back from its own transcript on every subsequent turn. Re-injecting the
411
+ * list into the description would be a second source of truth for the same fact, and it would put a
412
+ * snapshot of the plan in front of the model that could disagree with the one its history already
413
+ * contains.
414
+ */
415
+ pi.registerTool({
416
+ name: TODO_TOOL_NAME,
417
+ label: "Todo",
418
+ description: TODO_DESCRIPTION,
419
+ promptSnippet: "track multi-step work as a live task list the user watches",
420
+ parameters: TodoParameters,
421
+ execute: async (_toolCallId, params, signal) =>
422
+ await executeTodo(params as TodoParams, todoConfig, { signal: signal ?? undefined }),
423
+ });
424
+
425
+ /**
426
+ * `workflow`, registered THIRD and last.
427
+ *
428
+ * Last on purpose: a tool list is read in order, and this is the one a model should reach for LAST. It
429
+ * is also the most expensive call available - it blocks a whole pipeline of sub-agent runs - so the
430
+ * entry before it in the list being `todowrite` (a plan, free) rather than `workflow` is doing real work:
431
+ * the cheap way to express a plan should be what a model sees first.
432
+ *
433
+ * NO `prepareLoadout`, unlike `task`, because unlike `task` its description embeds nothing that changes
434
+ * while the server runs. It does not list the roster: the ids it accepts are the same ones `task` lists
435
+ * one entry above, in the same loadout, so injecting them a second time would be the same fact in two
436
+ * places free to disagree - and its description points the model at that list rather than repeating it.
437
+ */
438
+ pi.registerTool({
439
+ name: WORKFLOW_TOOL_NAME,
440
+ label: "Workflow",
441
+ description: WORKFLOW_DESCRIPTION,
442
+ promptSnippet: "run recursive sub-agent steps, bounded loops and explicit foreach batches",
443
+ parameters: WorkflowParameters,
444
+ execute: async (_toolCallId, params, signal) =>
445
+ await executeWorkflow(params as WorkflowParams, workflowConfig, { signal: signal ?? undefined }),
446
+ });
447
+
448
+ /**
449
+ * `run_async` - asynchronous shell command execution. NOT a sub-agent dispatch.
450
+ *
451
+ * Registered LAST so a model scanning the tool list reads `task` (the more powerful delegation
452
+ * primitive) before the more specialised background-command tool. A model reaching for the wrong
453
+ * one is the failure this ordering tries to prevent.
454
+ *
455
+ * SHARES THE EXEC ENDPOINT with `task` when it had `background: true`, but is its OWN tool so the
456
+ * description can say "shell command" rather than "sub-agent with a flag" and refuse-task does not
457
+ * have to make the subagent_type optional in a way that confused a model reading the description.
458
+ */
459
+ const RunAsyncParameters = Type.Object({
460
+ command: Type.String({ description: "The shell command to run in the workspace. Runs under bash on Linux/macOS and PowerShell on Windows." }),
461
+ description: Type.Optional(Type.String({ description: "3-5 word label shown in the background tasks panel." })),
462
+ });
463
+ pi.registerTool({
464
+ name: RUN_ASYNC_TOOL_NAME,
465
+ label: "Run Async",
466
+ description: RUN_ASYNC_DESCRIPTION,
467
+ promptSnippet: "run a shell command in the background and deliver its output as a follow-up message",
468
+ parameters: RunAsyncParameters,
469
+ execute: async (toolCallId, params, signal, _onUpdate, context) =>
470
+ await executeAsync(params as RunAsyncParams, context, config, { signal: signal ?? undefined }, { toolCallId }),
471
+ });
472
+
473
+ /**
474
+ * `scheduled_task`, registered AFTER everything that acts on the PRESENT.
475
+ *
476
+ * The order is the reading order, and the tools above all act on THIS turn - `task` delegates,
477
+ * `todowrite` plans, `workflow` orchestrates, `run_async` runs a command. This one is the only one
478
+ * that acts on the FUTURE, and a model should reach for it last: after deciding what work matters,
479
+ * then deciding whether it should happen again without anyone around.
480
+ *
481
+ * NO `prepareLoadout`: the description embeds nothing that changes while the server runs.
482
+ */
483
+ const ScheduledTaskParameters = Type.Object({
484
+ action: Type.Union([
485
+ Type.Literal("create", { description: "Create a new scheduled task" }),
486
+ Type.Literal("list", { description: "List this workspace's scheduled tasks" }),
487
+ Type.Literal("update", { description: "Change an existing task - needs its id" }),
488
+ Type.Literal("delete", { description: "Delete a task - needs its id" }),
489
+ ]),
490
+ id: Type.Optional(Type.String({ description: "The task's id, required for update and delete - get it with list" })),
491
+ name: Type.Optional(Type.String({ description: "Short name shown in the panel; defaults to the prompt's first line" })),
492
+ prompt: Type.Optional(Type.String({ description: "The instruction sent VERBATIM when the task fires. Complete instructions only - no memory of this conversation is available at fire time" })),
493
+ schedule: Type.Optional(Type.Object({
494
+ kind: Type.Union([
495
+ Type.Literal("interval"),
496
+ Type.Literal("daily"),
497
+ Type.Literal("weekly"),
498
+ Type.Literal("once"),
499
+ ]),
500
+ everyMinutes: Type.Optional(Type.Number({ description: "For interval: the number of minutes between runs" })),
501
+ time: Type.Optional(Type.String({ description: "For daily/weekly: \"HH:MM\" local time, e.g. \"09:00\"" })),
502
+ weekdays: Type.Optional(Type.Array(Type.Number({ description: "For weekly: 0=Sunday, 1=Monday, ..., 6=Saturday" }), { description: "For weekly: the days it runs" })),
503
+ at: Type.Optional(Type.Number({ description: "For once: the epoch milliseconds of the single run" })),
504
+ }, { description: "WHEN it fires. interval needs everyMinutes; daily and weekly need time; weekly needs weekdays; once needs at" })),
505
+ model: Type.Optional(Type.Object({
506
+ provider: Type.String({ description: "The provider's id, e.g. \"openai\"" }),
507
+ modelId: Type.String({ description: "The model's id, e.g. \"gpt-4o\"" }),
508
+ }, { description: "The model to run the task with. Leave out to use the workspace default" })),
509
+ agentId: Type.Optional(Type.String({ description: "The primary agent to run the task with. Leave out to use the workspace default" })),
510
+ });
511
+ pi.registerTool({
512
+ name: SCHEDULED_TASK_TOOL_NAME,
513
+ label: "Scheduled Task",
514
+ description: SCHEDULED_TASK_DESCRIPTION,
515
+ promptSnippet: "create a task that runs on a schedule - daily, weekly, every N minutes, or once",
516
+ parameters: ScheduledTaskParameters,
517
+ execute: async (_toolCallId, params, signal) =>
518
+ await executeScheduledTask(params as ScheduledTaskParams, scheduledTaskConfig, { signal: signal ?? undefined }),
519
+ });
520
+
521
+ const orchestratorConfig = readOrchestratorConfig(process.env);
522
+
523
+ const SessionSpawnParameters = Type.Object({
524
+ handoffNote: Type.Optional(Type.String({ description: "Verified findings, decisions, relevant file locations, ruled-out approaches and known gaps for the child. Its private history starts fresh; the server also supplies a bounded navigation index. Same-workspace cwd inherits from the parent unless explicitly overridden." })),
525
+ task: Type.String({
526
+ description: "The high-level task or instructions to be performed by the new sibling session. This is sent as the initial prompt.",
527
+ }),
528
+ parentConversationId: Type.Optional(Type.String({
529
+ description: "The parent is always the calling session; pass the calling session's own id to repeat it. Any other session is refused and nothing is created.",
530
+ })),
531
+ title: Type.Optional(Type.String({
532
+ description: "An optional title for the new sibling conversation in the sidebar. If omitted, derived from task.",
533
+ })),
534
+ agentId: Type.Optional(Type.String({
535
+ description: "Optional agent definition to assign to the new session (e.g. 'coder', 'planner'). Defaults to the workspace default.",
536
+ })),
537
+ model: Type.Optional(Type.Object({
538
+ provider: Type.String({ description: "The provider half of the \"provider/modelId\" pair, e.g. \"anthropic\"." }),
539
+ modelId: Type.String({ description: "The model half of the \"provider/modelId\" pair, e.g. \"claude-...\"." }),
540
+ }, { description: "The model the NEW session runs on. BOTH halves are required - it is one \"provider/modelId\" pair, exactly as the model picker shows it. Leave it out to use the workspace default model." })),
541
+ thinkingLevel: Type.Optional(Type.String({
542
+ description: "Optional thinking level override ('off', 'low', 'medium', 'high'). Defaults to workspace setting.",
543
+ })),
544
+ wait: Type.Optional(Type.Boolean({
545
+ description: "Whether to await turn completion before returning (default: false, asynchronous).",
546
+ })),
547
+ cwd: Type.Optional(Type.String({
548
+ description: "Optional workspace-root-relative subdirectory (for example, packages/a). Absolute paths, '..' traversal, UNC paths, and escaping symlinks are rejected; omit it to use the workspace root.",
549
+ })),
550
+ watchdogTimeoutSeconds: Type.Optional(Type.Number({
551
+ description: "How long YOU are willing to wait for a report from the new session before you want to be reminded, in seconds (for example 300 for five minutes). A report from the child restarts the clock; the watchdog never stops the child. Omit it to run without a watchdog.",
552
+ })),
553
+ });
554
+
555
+ const SessionStatusParameters = Type.Object({
556
+ conversationId: Type.Optional(Type.String({
557
+ description: "The ID of the sibling conversation to inspect. Omit to list sibling conversations.",
558
+ })),
559
+ parentConversationId: Type.Optional(Type.String({
560
+ description: "When listing, only return sessions whose direct parent has this ID. Defaults to the calling session.",
561
+ })),
562
+ includeOutput: Type.Optional(Type.Boolean({
563
+ description: "For a single session, include its final output from the result file, capped to the last 64Ki characters with an explicit truncation notice.",
564
+ })),
565
+ });
566
+
567
+ const SessionDispatchParameters = Type.Object({
568
+ conversationId: Type.String({
569
+ description: "The ID of the target sibling conversation to send a message to.",
570
+ }),
571
+ content: Type.String({
572
+ description: "The text message or instructions to send to the sibling conversation.",
573
+ }),
574
+ wait: Type.Optional(Type.Boolean({
575
+ description: "Whether to await turn completion before returning (default: false, asynchronous).",
576
+ })),
577
+ mode: Type.Optional(Type.Union([
578
+ Type.Literal("queue", { description: "Wait for the active turn and earlier queued messages to finish (default)" }),
579
+ Type.Literal("steer", { description: "Deliver as steering guidance at the next tool/turn boundary without killing in-flight tools" }),
580
+ ], {
581
+ description: "Delivery mode when the sibling session is busy: 'queue' (default) or 'steer' (next turn boundary).",
582
+ })),
583
+ });
584
+
585
+ const SessionStopParameters = Type.Object({
586
+ conversationId: Type.String({
587
+ description: "The conversation ID of the sibling session to stop.",
588
+ }),
589
+ mode: Type.Optional(Type.Union([
590
+ Type.Literal("active", { description: "Interrupt current running turn only" }),
591
+ Type.Literal("queued", { description: "Cancel pending queued messages only" }),
592
+ Type.Literal("all", { description: "Stop active turn and cancel all queued messages (default)" }),
593
+ ], {
594
+ description: "Stop mode: 'active', 'queued', or 'all' (default).",
595
+ })),
596
+ messageId: Type.Optional(Type.String({
597
+ description: "Optional specific queued message ID to cancel or interrupt.",
598
+ })),
599
+ messageIds: Type.Optional(Type.Array(Type.String(), {
600
+ description: "Optional list of queued message IDs to selectively withdraw while keeping other queued/steered messages and the running turn.",
601
+ })),
602
+ });
603
+
604
+ /**
605
+ * The `session_stop_subtree` parameter schema.
606
+ *
607
+ * The same shape as `session_stop`, because the model fills in the same things: WHICH session, and
608
+ * HOW hard to stop it. The difference is in what the operation means, and that is the server's to
609
+ * decide - a second set of parameter names would only invite a model to wonder which spelling it
610
+ * should use.
611
+ */
612
+ const SessionStopSubtreeParameters = Type.Object({
613
+ conversationId: Type.String({
614
+ description: "The conversation ID of the sibling session whose whole subtree should be stopped.",
615
+ }),
616
+ mode: Type.Optional(Type.Union([
617
+ Type.Literal("active", { description: "Interrupt current running turn only" }),
618
+ Type.Literal("queued", { description: "Cancel pending queued messages only" }),
619
+ Type.Literal("all", { description: "Stop active turn and cancel all queued messages (default)" }),
620
+ ], {
621
+ description: "Stop mode: 'active', 'queued', or 'all' (default).",
622
+ })),
623
+ messageId: Type.Optional(Type.String({
624
+ description: "Optional specific queued message ID to cancel or interrupt.",
625
+ })),
626
+ });
627
+
628
+ /** The `session_remove` parameter schema. */
629
+ const SessionRemoveParameters = Type.Object({
630
+ conversationId: Type.String({
631
+ description: "The conversation ID of your direct child session to permanently destroy (along with any descendant sessions under it).",
632
+ }),
633
+ reason: Type.Optional(Type.String({
634
+ description: "Optional reason for destroying this child session (confirmed in the tool result).",
635
+ })),
636
+ });
637
+
638
+ /**
639
+ * The `session_report` parameter schema.
640
+ *
641
+ * `content` is required, because a report with nothing in it is a report that says nothing - and
642
+ * the parent reads it as if it had been told something. `status` is a closed union of the three
643
+ * words the server understands, so a model cannot invent a fourth one that arrives as an
644
+ * unintended interim update.
645
+ */
646
+ const SessionReportParameters = Type.Object({
647
+ content: Type.String({
648
+ description: "The text the parent receives. Write it for the parent: what is done, what is left, what you need.",
649
+ }),
650
+ status: Type.Optional(Type.Union([
651
+ Type.Literal("in_progress", { description: "An interim update; the task continues and the parent's watchdog clock restarts (default)" }),
652
+ Type.Literal("completed", { description: "The task is finished and this is the final report" }),
653
+ Type.Literal("failed", { description: "The task could not be finished; say why" }),
654
+ ], {
655
+ description: "What this report means: 'in_progress' (default), 'completed', or 'failed'.",
656
+ })),
657
+ });
658
+
659
+ /**
660
+ * The `session_reminder` parameter schema.
661
+ *
662
+ * `action` is optional and defaults to "create", because setting a reminder is what the tool is
663
+ * for and a model that only means "remind me later" should not have to spell the action out.
664
+ * `delaySeconds` and `seconds` are the same field under two spellings, and BOTH are accepted:
665
+ * a model that reaches for `seconds` is not wrong, and refusing it would only teach it to
666
+ * retry with a different word.
667
+ */
668
+ const SessionReminderParameters = Type.Object({
669
+ action: Type.Optional(Type.Union([
670
+ Type.Literal("create", { description: "Set a new reminder for this conversation (default)" }),
671
+ Type.Literal("cancel", { description: "Cancel a pending reminder - needs its reminderId" }),
672
+ Type.Literal("list", { description: "List this conversation's pending reminders" }),
673
+ ], {
674
+ description: "What to do: 'create' (default), 'cancel' or 'list'.",
675
+ })),
676
+ delaySeconds: Type.Optional(Type.Number({
677
+ description: "Seconds until the first wake-up, and between wake-ups when repeat is true. Must be positive.",
678
+ })),
679
+ seconds: Type.Optional(Type.Number({
680
+ description: "The same as delaySeconds - accepted because models spell it both ways.",
681
+ })),
682
+ note: Type.Optional(Type.String({
683
+ description: "Optional short text for a one-off reminder. Omit for a wake-up that reports only elapsed time.",
684
+ })),
685
+ repeat: Type.Optional(Type.Boolean({
686
+ description: "Wake this conversation repeatedly until cancelled. Each wake-up reports only elapsed time.",
687
+ })),
688
+ reminderId: Type.Optional(Type.String({
689
+ description: "The reminder's id, as returned by create or listed by list. Required for cancel.",
690
+ })),
691
+ });
692
+
693
+ if (orchestratorConfig.endpoint) {
694
+ pi.registerTool({
695
+ name: WORKTREE_TOOL_NAME,
696
+ label: "Git Worktree",
697
+ description: "When the user requests work in an isolated Git worktree, create it and let the current chat follow its Git changes. Use list to find existing worktrees and their IDs, create for a new managed checkout, follow to show an existing worktree in Git, and open for a new persistent chat on that checkout. Supply task only when the user wants implementation started in a new execution chat. Include the agreed approach and constraints. Leave task out to prepare or inspect. Use the returned workspaceRoot explicitly in the current turn.",
698
+ parameters: Type.Object({
699
+ action: Type.Union([Type.Literal("list"), Type.Literal("create"), Type.Literal("follow"), Type.Literal("open")]),
700
+ worktreeId: Type.Optional(Type.String({ description: "Verified worktree ID for follow or open" })),
701
+ branch: Type.Optional(Type.String({ description: "New branch name; omit for a detached checkout" })),
702
+ base: Type.Optional(Type.String({ description: "Local starting branch; omit to start at the current checkout's HEAD" })),
703
+ task: Type.Optional(Type.String({ description: "Implementation handoff for the new execution chat" })),
704
+ }),
705
+ execute: async (toolCallId, params, signal) => executeWorktree(params as WorktreeToolParams, orchestratorConfig, toolCallId, signal ?? undefined),
706
+ });
707
+
708
+ pi.registerTool({
709
+ name: SESSION_SPAWN_TOOL_NAME,
710
+ label: "Spawn Sibling Session",
711
+ description: SESSION_SPAWN_DESCRIPTION,
712
+ promptSnippet: "spawn a persistent sibling conversation for an independent work stream",
713
+ parameters: SessionSpawnParameters,
714
+ execute: async (_toolCallId, params, signal) =>
715
+ await executeSessionSpawn(params as SessionSpawnParams, orchestratorConfig, { signal: signal ?? undefined }),
716
+ });
717
+
718
+ pi.registerTool({
719
+ name: SESSION_STATUS_TOOL_NAME,
720
+ label: "Session Status",
721
+ description: SESSION_STATUS_DESCRIPTION,
722
+ promptSnippet: "check progress, turn count and activity of sibling sessions",
723
+ parameters: SessionStatusParameters,
724
+ execute: async (_toolCallId, params, signal) =>
725
+ await executeSessionStatus(params as SessionStatusParams, orchestratorConfig, { signal: signal ?? undefined }),
726
+ });
727
+
728
+ pi.registerTool({
729
+ name: SESSION_DISPATCH_TOOL_NAME,
730
+ label: "Dispatch to Session",
731
+ description: SESSION_DISPATCH_DESCRIPTION,
732
+ promptSnippet: "send a message or follow-up prompt to an existing sibling session",
733
+ parameters: SessionDispatchParameters,
734
+ execute: async (_toolCallId, params, signal) =>
735
+ await executeSessionDispatch(params as SessionDispatchParams, orchestratorConfig, { signal: signal ?? undefined }),
736
+ });
737
+
738
+ pi.registerTool({
739
+ name: SESSION_STOP_TOOL_NAME,
740
+ label: "Stop Session",
741
+ description: SESSION_STOP_DESCRIPTION,
742
+ promptSnippet: "interrupt an active turn or cancel queued messages in a sibling session",
743
+ parameters: SessionStopParameters,
744
+ execute: async (_toolCallId, params, signal) =>
745
+ await executeSessionStop(params as SessionStopParams, orchestratorConfig, { signal: signal ?? undefined }),
746
+ });
747
+
748
+ /**
749
+ * `session_report`, registered AFTER the four tools that act ON OTHER SESSIONS.
750
+ *
751
+ * The order is the reading order, and this one is the odd one out: the other four are a
752
+ * PARENT's tools - they reach out and manage somebody else's session - while this one is the
753
+ * CHILD's own voice. A model reading the list top to bottom meets the manager's instruments
754
+ * first and the worker's mouth last, which is the order the relationship actually has.
755
+ */
756
+ pi.registerTool({
757
+ name: SESSION_REPORT_TOOL_NAME,
758
+ label: "Report to Parent",
759
+ description: SESSION_REPORT_DESCRIPTION,
760
+ promptSnippet: "report progress or a blocker to the parent session that spawned this one",
761
+ parameters: SessionReportParameters,
762
+ execute: async (_toolCallId, params, signal) =>
763
+ await executeSessionReport(params as SessionReportParams, orchestratorConfig, { signal: signal ?? undefined }),
764
+ });
765
+
766
+ /**
767
+ * `session_stop_subtree`, registered after `session_stop`.
768
+ *
769
+ * The two sit next to each other on purpose, because the decision a model makes between them
770
+ * is the whole point: one stops a session, the other stops the branch. A model that reads them
771
+ * apart knows that leaving children running under a stopped parent is a choice, not an
772
+ * oversight.
773
+ */
774
+ pi.registerTool({
775
+ name: SESSION_STOP_SUBTREE_TOOL_NAME,
776
+ label: "Stop Session Tree",
777
+ description: SESSION_STOP_SUBTREE_DESCRIPTION,
778
+ promptSnippet: "stop a sibling session and every session underneath it, so nothing is left running under a dead parent",
779
+ parameters: SessionStopSubtreeParameters,
780
+ execute: async (_toolCallId, params, signal) =>
781
+ await executeSessionStopSubtree(params as SessionStopSubtreeParams, orchestratorConfig, { signal: signal ?? undefined }),
782
+ });
783
+
784
+ pi.registerTool({
785
+ name: SESSION_REMOVE_TOOL_NAME,
786
+ label: "Remove Child Session",
787
+ description: SESSION_REMOVE_DESCRIPTION,
788
+ promptSnippet: "remove a direct child session from the active working group (archive without deleting history)",
789
+ parameters: SessionRemoveParameters,
790
+ execute: async (_toolCallId, params, signal) =>
791
+ await executeSessionRemove(params as SessionRemoveParams, orchestratorConfig, { signal: signal ?? undefined }),
792
+ });
793
+
794
+ /**
795
+ * `session_reminder`, registered AFTER the tools that act on OTHER SESSIONS.
796
+ *
797
+ * The order is the reading order, and this one is the odd one out: every tool above it reaches
798
+ * OUT to somebody else's session, while this one turns the clock on THIS conversation. A model
799
+ * reading the list top to bottom meets the manager's instruments first and its own timer last,
800
+ * which is the order the relationship actually has.
801
+ */
802
+ pi.registerTool({
803
+ name: SESSION_REMINDER_TOOL_NAME,
804
+ label: "Session Reminder",
805
+ description: SESSION_REMINDER_DESCRIPTION,
806
+ promptSnippet: "set a timer that delivers a note back into THIS conversation when it fires",
807
+ parameters: SessionReminderParameters,
808
+ execute: async (_toolCallId, params, signal) =>
809
+ await executeSessionReminder(params as SessionReminderParams, orchestratorConfig, { signal: signal ?? undefined }),
810
+ });
811
+ }
812
+ };
813
+
814
+ export default extension;