@ilya-lesikov/pi-pi 0.1.0

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 (271) hide show
  1. package/3p/pi-ask-user/index.ts +1835 -0
  2. package/3p/pi-ask-user/package.json +50 -0
  3. package/3p/pi-ask-user/single-select-layout.ts +203 -0
  4. package/3p/pi-lsp/extensions/lsp/client.ts +542 -0
  5. package/3p/pi-lsp/extensions/lsp/config.ts +135 -0
  6. package/3p/pi-lsp/extensions/lsp/effects/command.ts +42 -0
  7. package/3p/pi-lsp/extensions/lsp/effects/filesystem.ts +50 -0
  8. package/3p/pi-lsp/extensions/lsp/effects/runtime.ts +21 -0
  9. package/3p/pi-lsp/extensions/lsp/errors.ts +113 -0
  10. package/3p/pi-lsp/extensions/lsp/formatting.ts +315 -0
  11. package/3p/pi-lsp/extensions/lsp/index.ts +231 -0
  12. package/3p/pi-lsp/extensions/lsp/protocol.ts +209 -0
  13. package/3p/pi-lsp/extensions/lsp/retry.ts +39 -0
  14. package/3p/pi-lsp/extensions/lsp/tools/programs.ts +293 -0
  15. package/3p/pi-lsp/extensions/lsp/tools.ts +89 -0
  16. package/3p/pi-lsp/extensions/lsp/types.ts +243 -0
  17. package/3p/pi-lsp/package.json +54 -0
  18. package/3p/pi-plannotator/AGENTS.md +583 -0
  19. package/3p/pi-plannotator/apps/pi-extension/README.md +228 -0
  20. package/3p/pi-plannotator/apps/pi-extension/assistant-message.ts +128 -0
  21. package/3p/pi-plannotator/apps/pi-extension/config.test.ts +166 -0
  22. package/3p/pi-plannotator/apps/pi-extension/config.ts +318 -0
  23. package/3p/pi-plannotator/apps/pi-extension/current-pi-session.ts +147 -0
  24. package/3p/pi-plannotator/apps/pi-extension/index.ts +1279 -0
  25. package/3p/pi-plannotator/apps/pi-extension/package.json +56 -0
  26. package/3p/pi-plannotator/apps/pi-extension/plannotator-browser.test.ts +13 -0
  27. package/3p/pi-plannotator/apps/pi-extension/plannotator-browser.ts +616 -0
  28. package/3p/pi-plannotator/apps/pi-extension/plannotator-events.ts +342 -0
  29. package/3p/pi-plannotator/apps/pi-extension/plannotator.json +12 -0
  30. package/3p/pi-plannotator/apps/pi-extension/server/agent-jobs.ts +515 -0
  31. package/3p/pi-plannotator/apps/pi-extension/server/ai-runtime.ts +169 -0
  32. package/3p/pi-plannotator/apps/pi-extension/server/annotations.ts +85 -0
  33. package/3p/pi-plannotator/apps/pi-extension/server/external-annotations.ts +189 -0
  34. package/3p/pi-plannotator/apps/pi-extension/server/handlers.ts +210 -0
  35. package/3p/pi-plannotator/apps/pi-extension/server/helpers.ts +78 -0
  36. package/3p/pi-plannotator/apps/pi-extension/server/ide.ts +46 -0
  37. package/3p/pi-plannotator/apps/pi-extension/server/integrations.ts +195 -0
  38. package/3p/pi-plannotator/apps/pi-extension/server/network.test.ts +158 -0
  39. package/3p/pi-plannotator/apps/pi-extension/server/network.ts +268 -0
  40. package/3p/pi-plannotator/apps/pi-extension/server/pr.ts +126 -0
  41. package/3p/pi-plannotator/apps/pi-extension/server/project.ts +64 -0
  42. package/3p/pi-plannotator/apps/pi-extension/server/reference.ts +362 -0
  43. package/3p/pi-plannotator/apps/pi-extension/server/serverAnnotate.ts +199 -0
  44. package/3p/pi-plannotator/apps/pi-extension/server/serverPlan.ts +505 -0
  45. package/3p/pi-plannotator/apps/pi-extension/server/serverReview.ts +1229 -0
  46. package/3p/pi-plannotator/apps/pi-extension/server/vcs.ts +121 -0
  47. package/3p/pi-plannotator/apps/pi-extension/server.test.ts +966 -0
  48. package/3p/pi-plannotator/apps/pi-extension/server.ts +44 -0
  49. package/3p/pi-plannotator/apps/pi-extension/tool-scope.test.ts +88 -0
  50. package/3p/pi-plannotator/apps/pi-extension/tool-scope.ts +39 -0
  51. package/3p/pi-plannotator/apps/pi-extension/tsconfig.json +16 -0
  52. package/3p/pi-plannotator/apps/pi-extension/vendor.sh +48 -0
  53. package/3p/pi-plannotator/package.json +53 -0
  54. package/3p/pi-plannotator/packages/ai/ai.test.ts +1407 -0
  55. package/3p/pi-plannotator/packages/ai/base-session.ts +94 -0
  56. package/3p/pi-plannotator/packages/ai/context.ts +250 -0
  57. package/3p/pi-plannotator/packages/ai/endpoints.ts +326 -0
  58. package/3p/pi-plannotator/packages/ai/index.ts +105 -0
  59. package/3p/pi-plannotator/packages/ai/package.json +21 -0
  60. package/3p/pi-plannotator/packages/ai/provider.ts +103 -0
  61. package/3p/pi-plannotator/packages/ai/providers/claude-agent-sdk.ts +447 -0
  62. package/3p/pi-plannotator/packages/ai/providers/codex-sdk.ts +430 -0
  63. package/3p/pi-plannotator/packages/ai/providers/command-path.ts +115 -0
  64. package/3p/pi-plannotator/packages/ai/providers/opencode-sdk.ts +546 -0
  65. package/3p/pi-plannotator/packages/ai/providers/pi-events.ts +110 -0
  66. package/3p/pi-plannotator/packages/ai/providers/pi-sdk-node.ts +425 -0
  67. package/3p/pi-plannotator/packages/ai/providers/pi-sdk.ts +469 -0
  68. package/3p/pi-plannotator/packages/ai/session-manager.ts +195 -0
  69. package/3p/pi-plannotator/packages/ai/tsconfig.json +15 -0
  70. package/3p/pi-plannotator/packages/ai/types.ts +379 -0
  71. package/3p/pi-plannotator/packages/server/agent-jobs.ts +538 -0
  72. package/3p/pi-plannotator/packages/server/agent-review-message.test.ts +135 -0
  73. package/3p/pi-plannotator/packages/server/agent-review-message.ts +243 -0
  74. package/3p/pi-plannotator/packages/server/ai-runtime.ts +108 -0
  75. package/3p/pi-plannotator/packages/server/annotate.ts +401 -0
  76. package/3p/pi-plannotator/packages/server/browser.test.ts +87 -0
  77. package/3p/pi-plannotator/packages/server/browser.ts +245 -0
  78. package/3p/pi-plannotator/packages/server/claude-review.ts +352 -0
  79. package/3p/pi-plannotator/packages/server/code-nav.ts +73 -0
  80. package/3p/pi-plannotator/packages/server/codex-review-schema.json +41 -0
  81. package/3p/pi-plannotator/packages/server/codex-review.ts +330 -0
  82. package/3p/pi-plannotator/packages/server/config.ts +8 -0
  83. package/3p/pi-plannotator/packages/server/draft.ts +1 -0
  84. package/3p/pi-plannotator/packages/server/editor-annotations.ts +76 -0
  85. package/3p/pi-plannotator/packages/server/external-annotations.test.ts +18 -0
  86. package/3p/pi-plannotator/packages/server/external-annotations.ts +207 -0
  87. package/3p/pi-plannotator/packages/server/git.ts +141 -0
  88. package/3p/pi-plannotator/packages/server/goal-setup.test.ts +55 -0
  89. package/3p/pi-plannotator/packages/server/goal-setup.ts +248 -0
  90. package/3p/pi-plannotator/packages/server/ide.ts +43 -0
  91. package/3p/pi-plannotator/packages/server/image.test.ts +63 -0
  92. package/3p/pi-plannotator/packages/server/image.ts +66 -0
  93. package/3p/pi-plannotator/packages/server/index.ts +648 -0
  94. package/3p/pi-plannotator/packages/server/integrations.test.ts +172 -0
  95. package/3p/pi-plannotator/packages/server/integrations.ts +214 -0
  96. package/3p/pi-plannotator/packages/server/jj.test.ts +69 -0
  97. package/3p/pi-plannotator/packages/server/jj.ts +86 -0
  98. package/3p/pi-plannotator/packages/server/p4.ts +417 -0
  99. package/3p/pi-plannotator/packages/server/package.json +40 -0
  100. package/3p/pi-plannotator/packages/server/path-utils.ts +18 -0
  101. package/3p/pi-plannotator/packages/server/pr.ts +146 -0
  102. package/3p/pi-plannotator/packages/server/project.test.ts +115 -0
  103. package/3p/pi-plannotator/packages/server/project.ts +45 -0
  104. package/3p/pi-plannotator/packages/server/reference-handlers.ts +404 -0
  105. package/3p/pi-plannotator/packages/server/remote.test.ts +150 -0
  106. package/3p/pi-plannotator/packages/server/remote.ts +74 -0
  107. package/3p/pi-plannotator/packages/server/repo.ts +80 -0
  108. package/3p/pi-plannotator/packages/server/resolve-file.test.ts +310 -0
  109. package/3p/pi-plannotator/packages/server/review-workspace.test.ts +1032 -0
  110. package/3p/pi-plannotator/packages/server/review-workspace.ts +48 -0
  111. package/3p/pi-plannotator/packages/server/review.ts +1318 -0
  112. package/3p/pi-plannotator/packages/server/sessions.ts +111 -0
  113. package/3p/pi-plannotator/packages/server/share-url.ts +53 -0
  114. package/3p/pi-plannotator/packages/server/shared-handlers.test.ts +43 -0
  115. package/3p/pi-plannotator/packages/server/shared-handlers.ts +177 -0
  116. package/3p/pi-plannotator/packages/server/storage.test.ts +176 -0
  117. package/3p/pi-plannotator/packages/server/storage.ts +17 -0
  118. package/3p/pi-plannotator/packages/server/tour/tour-review.test.ts +146 -0
  119. package/3p/pi-plannotator/packages/server/tour/tour-review.ts +604 -0
  120. package/3p/pi-plannotator/packages/server/tsconfig.json +15 -0
  121. package/3p/pi-plannotator/packages/server/vcs.test.ts +48 -0
  122. package/3p/pi-plannotator/packages/server/vcs.ts +80 -0
  123. package/3p/pi-plannotator/packages/shared/agent-jobs.ts +132 -0
  124. package/3p/pi-plannotator/packages/shared/agents.ts +53 -0
  125. package/3p/pi-plannotator/packages/shared/annotate-args.test.ts +386 -0
  126. package/3p/pi-plannotator/packages/shared/annotate-args.ts +107 -0
  127. package/3p/pi-plannotator/packages/shared/at-reference.test.ts +99 -0
  128. package/3p/pi-plannotator/packages/shared/at-reference.ts +52 -0
  129. package/3p/pi-plannotator/packages/shared/checklist.ts +52 -0
  130. package/3p/pi-plannotator/packages/shared/code-file.test.ts +112 -0
  131. package/3p/pi-plannotator/packages/shared/code-file.ts +41 -0
  132. package/3p/pi-plannotator/packages/shared/code-nav.test.ts +515 -0
  133. package/3p/pi-plannotator/packages/shared/code-nav.ts +436 -0
  134. package/3p/pi-plannotator/packages/shared/compress.ts +51 -0
  135. package/3p/pi-plannotator/packages/shared/config.ts +262 -0
  136. package/3p/pi-plannotator/packages/shared/crypto.test.ts +172 -0
  137. package/3p/pi-plannotator/packages/shared/crypto.ts +97 -0
  138. package/3p/pi-plannotator/packages/shared/data-dir.ts +42 -0
  139. package/3p/pi-plannotator/packages/shared/diff-paths.test.ts +30 -0
  140. package/3p/pi-plannotator/packages/shared/diff-paths.ts +137 -0
  141. package/3p/pi-plannotator/packages/shared/draft.ts +64 -0
  142. package/3p/pi-plannotator/packages/shared/external-annotation.ts +397 -0
  143. package/3p/pi-plannotator/packages/shared/extract-code-paths.test.ts +59 -0
  144. package/3p/pi-plannotator/packages/shared/extract-code-paths.ts +66 -0
  145. package/3p/pi-plannotator/packages/shared/favicon.ts +5 -0
  146. package/3p/pi-plannotator/packages/shared/feedback-templates.test.ts +65 -0
  147. package/3p/pi-plannotator/packages/shared/feedback-templates.ts +29 -0
  148. package/3p/pi-plannotator/packages/shared/goal-setup.test.ts +231 -0
  149. package/3p/pi-plannotator/packages/shared/goal-setup.ts +336 -0
  150. package/3p/pi-plannotator/packages/shared/html-to-markdown.test.ts +62 -0
  151. package/3p/pi-plannotator/packages/shared/html-to-markdown.ts +32 -0
  152. package/3p/pi-plannotator/packages/shared/improvement-hooks.test.ts +135 -0
  153. package/3p/pi-plannotator/packages/shared/improvement-hooks.ts +115 -0
  154. package/3p/pi-plannotator/packages/shared/integrations-common.ts +243 -0
  155. package/3p/pi-plannotator/packages/shared/jj-core.test.ts +236 -0
  156. package/3p/pi-plannotator/packages/shared/jj-core.ts +433 -0
  157. package/3p/pi-plannotator/packages/shared/package.json +55 -0
  158. package/3p/pi-plannotator/packages/shared/pfm-reminder.test.ts +88 -0
  159. package/3p/pi-plannotator/packages/shared/pfm-reminder.ts +80 -0
  160. package/3p/pi-plannotator/packages/shared/pr-github.ts +661 -0
  161. package/3p/pi-plannotator/packages/shared/pr-gitlab.test.ts +202 -0
  162. package/3p/pi-plannotator/packages/shared/pr-gitlab.ts +620 -0
  163. package/3p/pi-plannotator/packages/shared/pr-provider.test.ts +266 -0
  164. package/3p/pi-plannotator/packages/shared/pr-provider.ts +123 -0
  165. package/3p/pi-plannotator/packages/shared/pr-stack.test.ts +104 -0
  166. package/3p/pi-plannotator/packages/shared/pr-stack.ts +194 -0
  167. package/3p/pi-plannotator/packages/shared/pr-types.ts +326 -0
  168. package/3p/pi-plannotator/packages/shared/project.ts +71 -0
  169. package/3p/pi-plannotator/packages/shared/prompts-integration.test.ts +421 -0
  170. package/3p/pi-plannotator/packages/shared/prompts.test.ts +504 -0
  171. package/3p/pi-plannotator/packages/shared/prompts.ts +247 -0
  172. package/3p/pi-plannotator/packages/shared/reference-common.ts +87 -0
  173. package/3p/pi-plannotator/packages/shared/repo.ts +71 -0
  174. package/3p/pi-plannotator/packages/shared/resolve-file.test.ts +113 -0
  175. package/3p/pi-plannotator/packages/shared/resolve-file.ts +509 -0
  176. package/3p/pi-plannotator/packages/shared/review-args.test.ts +64 -0
  177. package/3p/pi-plannotator/packages/shared/review-args.ts +85 -0
  178. package/3p/pi-plannotator/packages/shared/review-core.test.ts +286 -0
  179. package/3p/pi-plannotator/packages/shared/review-core.ts +895 -0
  180. package/3p/pi-plannotator/packages/shared/review-workspace-node.ts +230 -0
  181. package/3p/pi-plannotator/packages/shared/review-workspace.ts +436 -0
  182. package/3p/pi-plannotator/packages/shared/semantic-diff-types.ts +76 -0
  183. package/3p/pi-plannotator/packages/shared/semantic-diff.test.ts +322 -0
  184. package/3p/pi-plannotator/packages/shared/semantic-diff.ts +520 -0
  185. package/3p/pi-plannotator/packages/shared/storage.ts +378 -0
  186. package/3p/pi-plannotator/packages/shared/tour.ts +61 -0
  187. package/3p/pi-plannotator/packages/shared/tsconfig.json +15 -0
  188. package/3p/pi-plannotator/packages/shared/types.ts +29 -0
  189. package/3p/pi-plannotator/packages/shared/url-to-markdown.test.ts +177 -0
  190. package/3p/pi-plannotator/packages/shared/url-to-markdown.ts +351 -0
  191. package/3p/pi-plannotator/packages/shared/vcs-core.test.ts +332 -0
  192. package/3p/pi-plannotator/packages/shared/vcs-core.ts +482 -0
  193. package/3p/pi-plannotator/packages/shared/worktree-pool.test.ts +162 -0
  194. package/3p/pi-plannotator/packages/shared/worktree-pool.ts +103 -0
  195. package/3p/pi-plannotator/packages/shared/worktree.ts +119 -0
  196. package/3p/pi-subagents/package.json +50 -0
  197. package/3p/pi-subagents/src/agent-manager.ts +413 -0
  198. package/3p/pi-subagents/src/agent-runner.ts +502 -0
  199. package/3p/pi-subagents/src/agent-types.ts +248 -0
  200. package/3p/pi-subagents/src/context.ts +58 -0
  201. package/3p/pi-subagents/src/cross-extension-rpc.ts +135 -0
  202. package/3p/pi-subagents/src/custom-agents.ts +137 -0
  203. package/3p/pi-subagents/src/default-agents.ts +144 -0
  204. package/3p/pi-subagents/src/env.ts +33 -0
  205. package/3p/pi-subagents/src/group-join.ts +141 -0
  206. package/3p/pi-subagents/src/index.ts +1811 -0
  207. package/3p/pi-subagents/src/invocation-config.ts +40 -0
  208. package/3p/pi-subagents/src/memory.ts +165 -0
  209. package/3p/pi-subagents/src/model-resolver.ts +81 -0
  210. package/3p/pi-subagents/src/output-file.ts +77 -0
  211. package/3p/pi-subagents/src/prompts.ts +85 -0
  212. package/3p/pi-subagents/src/skill-loader.ts +79 -0
  213. package/3p/pi-subagents/src/types.ts +111 -0
  214. package/3p/pi-subagents/src/ui/agent-widget.ts +496 -0
  215. package/3p/pi-subagents/src/ui/conversation-viewer.ts +250 -0
  216. package/3p/pi-subagents/src/worktree.ts +162 -0
  217. package/3p/pi-tasks/package.json +52 -0
  218. package/3p/pi-tasks/src/auto-clear.ts +91 -0
  219. package/3p/pi-tasks/src/index.ts +1150 -0
  220. package/3p/pi-tasks/src/process-tracker.ts +140 -0
  221. package/3p/pi-tasks/src/reminder-cadence.ts +90 -0
  222. package/3p/pi-tasks/src/task-store.ts +324 -0
  223. package/3p/pi-tasks/src/tasks-config.ts +27 -0
  224. package/3p/pi-tasks/src/types.ts +40 -0
  225. package/3p/pi-tasks/src/ui/settings-menu.ts +152 -0
  226. package/3p/pi-tasks/src/ui/task-widget.ts +296 -0
  227. package/AGENTS.md +28 -0
  228. package/LICENSE +201 -0
  229. package/extensions/orchestrator/agents/brainstorm-reviewer.ts +77 -0
  230. package/extensions/orchestrator/agents/code-reviewer.ts +89 -0
  231. package/extensions/orchestrator/agents/explore.ts +33 -0
  232. package/extensions/orchestrator/agents/librarian.ts +43 -0
  233. package/extensions/orchestrator/agents/plan-reviewer.ts +75 -0
  234. package/extensions/orchestrator/agents/planner.ts +61 -0
  235. package/extensions/orchestrator/agents/registry.ts +156 -0
  236. package/extensions/orchestrator/agents/task.ts +50 -0
  237. package/extensions/orchestrator/agents/tool-routing.ts +84 -0
  238. package/extensions/orchestrator/ast-search.ts +85 -0
  239. package/extensions/orchestrator/cbm.ts +330 -0
  240. package/extensions/orchestrator/command-handlers.test.ts +163 -0
  241. package/extensions/orchestrator/command-handlers.ts +116 -0
  242. package/extensions/orchestrator/commands.test.ts +81 -0
  243. package/extensions/orchestrator/commands.ts +75 -0
  244. package/extensions/orchestrator/config.test.ts +221 -0
  245. package/extensions/orchestrator/config.ts +230 -0
  246. package/extensions/orchestrator/context.test.ts +293 -0
  247. package/extensions/orchestrator/context.ts +206 -0
  248. package/extensions/orchestrator/event-handlers.test.ts +190 -0
  249. package/extensions/orchestrator/event-handlers.ts +1416 -0
  250. package/extensions/orchestrator/exa.ts +104 -0
  251. package/extensions/orchestrator/flant-infra.ts +486 -0
  252. package/extensions/orchestrator/index.ts +80 -0
  253. package/extensions/orchestrator/integration.test.ts +1214 -0
  254. package/extensions/orchestrator/orchestrator.test.ts +252 -0
  255. package/extensions/orchestrator/orchestrator.ts +538 -0
  256. package/extensions/orchestrator/phases/brainstorm.test.ts +15 -0
  257. package/extensions/orchestrator/phases/brainstorm.ts +273 -0
  258. package/extensions/orchestrator/phases/implementation.ts +40 -0
  259. package/extensions/orchestrator/phases/machine.test.ts +293 -0
  260. package/extensions/orchestrator/phases/machine.ts +209 -0
  261. package/extensions/orchestrator/phases/planning.ts +255 -0
  262. package/extensions/orchestrator/phases/review.ts +193 -0
  263. package/extensions/orchestrator/plannotator.ts +56 -0
  264. package/extensions/orchestrator/pp-menu.ts +866 -0
  265. package/extensions/orchestrator/state.test.ts +343 -0
  266. package/extensions/orchestrator/state.ts +237 -0
  267. package/extensions/orchestrator/validate-artifacts.test.ts +88 -0
  268. package/extensions/orchestrator/validate-artifacts.ts +272 -0
  269. package/extensions/orchestrator/vendor.d.ts +26 -0
  270. package/package.json +73 -0
  271. package/scripts/postinstall.sh +18 -0
@@ -0,0 +1,1811 @@
1
+ /**
2
+ * pi-agents — A pi extension providing Claude Code-style autonomous sub-agents.
3
+ *
4
+ * Tools:
5
+ * Agent — LLM-callable: spawn a sub-agent
6
+ * get_subagent_result — LLM-callable: check background agent status/result
7
+ * steer_subagent — LLM-callable: send a steering message to a running agent
8
+ *
9
+ * Commands:
10
+ * /agents — Interactive agent management menu
11
+ */
12
+
13
+ import { existsSync, mkdirSync, readFileSync, unlinkSync } from "node:fs";
14
+ import { homedir } from "node:os";
15
+ import { join } from "node:path";
16
+ import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
17
+ import { Text } from "@earendil-works/pi-tui";
18
+ import { Type } from "@sinclair/typebox";
19
+ import { AgentManager } from "./agent-manager.js";
20
+ import { getAgentConversation, getDefaultMaxTurns, getGraceTurns, normalizeMaxTurns, setDefaultMaxTurns, setGraceTurns, steerAgent } from "./agent-runner.js";
21
+ import { BUILTIN_TOOL_NAMES, getAgentConfig, getAllTypes, getAvailableTypes, getDefaultAgentNames, getUserAgentNames, registerAgents, registerExtensionAgents, unregisterExtensionAgents, unregisterExtensionAgentsByPrefix, clearExtensionAgents, setExtensionOnlyMode, resolveType } from "./agent-types.js";
22
+ import { registerRpcHandlers } from "./cross-extension-rpc.js";
23
+ import { loadCustomAgents } from "./custom-agents.js";
24
+ import { GroupJoinManager } from "./group-join.js";
25
+ import { resolveAgentInvocationConfig, resolveJoinMode } from "./invocation-config.js";
26
+ import { type ModelRegistry, resolveModel } from "./model-resolver.js";
27
+ import { createOutputFilePath, streamToOutputFile, writeInitialEntry } from "./output-file.js";
28
+ import { type AgentConfig, type AgentRecord, type JoinMode, type NotificationDetails, type SubagentType } from "./types.js";
29
+ import {
30
+ type AgentActivity,
31
+ type AgentDetails,
32
+ AgentWidget,
33
+ describeActivity,
34
+ formatDuration,
35
+ formatMs,
36
+ formatTokens,
37
+ formatTurns,
38
+ getDisplayName,
39
+ getPromptModeLabel,
40
+ SPINNER,
41
+ type UICtx,
42
+ } from "./ui/agent-widget.js";
43
+
44
+ // ---- Shared helpers ----
45
+
46
+ /** Tool execute return value for a text response. */
47
+ function textResult(msg: string, details?: AgentDetails) {
48
+ return { content: [{ type: "text" as const, text: msg }], details: details as any };
49
+ }
50
+
51
+ function appendParentFlowTrace(cwd: string | undefined, event: string, detail: Record<string, unknown>) {
52
+ if (!cwd) return;
53
+ try {
54
+ mkdirSync(join(cwd, ".pp"), { recursive: true });
55
+ const line = JSON.stringify({ timestamp: new Date().toISOString(), event, ...detail }) + "\n";
56
+ require("node:fs").appendFileSync(join(cwd, ".pp", "subagent-parent-flow-trace.jsonl"), line, "utf-8");
57
+ } catch {}
58
+ }
59
+
60
+ function appendSubagentDebugTrace(cwd: string | undefined, event: string, detail: Record<string, unknown>) {
61
+ if (!cwd) return;
62
+ try {
63
+ mkdirSync(join(cwd, ".pp"), { recursive: true });
64
+ const line = JSON.stringify({ timestamp: new Date().toISOString(), event, ...detail }) + "\n";
65
+ require("node:fs").appendFileSync(join(cwd, ".pp", "subagent-interactive-trace.jsonl"), line, "utf-8");
66
+ } catch {}
67
+ }
68
+
69
+ /** Safe token formatting — wraps session.getSessionStats() in try-catch. */
70
+ function safeFormatTokens(session: { getSessionStats(): { tokens: { total: number } } } | undefined): string {
71
+ if (!session) return "";
72
+ try { return formatTokens(session.getSessionStats().tokens.total); } catch { return ""; }
73
+ }
74
+
75
+ /**
76
+ * Create an AgentActivity state and spawn callbacks for tracking tool usage.
77
+ * Used by both foreground and background paths to avoid duplication.
78
+ */
79
+ function createActivityTracker(maxTurns?: number, onStreamUpdate?: () => void) {
80
+ const state: AgentActivity = { activeTools: new Map(), toolUses: 0, turnCount: 1, maxTurns, tokens: "", responseText: "", session: undefined };
81
+
82
+ const callbacks = {
83
+ onToolActivity: (activity: { type: "start" | "end"; toolName: string }) => {
84
+ if (activity.type === "start") {
85
+ state.activeTools.set(activity.toolName + "_" + Date.now(), activity.toolName);
86
+ } else {
87
+ for (const [key, name] of state.activeTools) {
88
+ if (name === activity.toolName) { state.activeTools.delete(key); break; }
89
+ }
90
+ state.toolUses++;
91
+ }
92
+ state.tokens = safeFormatTokens(state.session);
93
+ onStreamUpdate?.();
94
+ },
95
+ onTextDelta: (_delta: string, fullText: string) => {
96
+ state.responseText = fullText;
97
+ onStreamUpdate?.();
98
+ },
99
+ onTurnEnd: (turnCount: number) => {
100
+ state.turnCount = turnCount;
101
+ onStreamUpdate?.();
102
+ },
103
+ onSessionCreated: (session: any) => {
104
+ state.session = session;
105
+ },
106
+ };
107
+
108
+ return { state, callbacks };
109
+ }
110
+
111
+ /** Human-readable status label for agent completion. */
112
+ function getStatusLabel(status: string, error?: string): string {
113
+ switch (status) {
114
+ case "error": return `Error: ${error ?? "unknown"}`;
115
+ case "aborted": return "Aborted (max turns exceeded)";
116
+ case "steered": return "Wrapped up (turn limit)";
117
+ case "stopped": return "Stopped";
118
+ default: return "Done";
119
+ }
120
+ }
121
+
122
+ /** Parenthetical status note for completed agent result text. */
123
+ function getStatusNote(status: string): string {
124
+ switch (status) {
125
+ case "aborted": return " (aborted — max turns exceeded, output may be incomplete)";
126
+ case "steered": return " (wrapped up — reached turn limit)";
127
+ case "stopped": return " (stopped by user)";
128
+ default: return "";
129
+ }
130
+ }
131
+
132
+ /** Escape XML special characters to prevent injection in structured notifications. */
133
+ function escapeXml(s: string): string {
134
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
135
+ }
136
+
137
+ /** Format a structured task notification matching Claude Code's <task-notification> XML. */
138
+ function formatTaskNotification(record: AgentRecord, resultMaxLen: number): string {
139
+ const status = getStatusLabel(record.status, record.error);
140
+ const durationMs = record.completedAt ? record.completedAt - record.startedAt : 0;
141
+ let totalTokens = 0;
142
+ try {
143
+ if (record.session) {
144
+ const stats = record.session.getSessionStats();
145
+ totalTokens = stats.tokens?.total ?? 0;
146
+ }
147
+ } catch { /* session stats unavailable */ }
148
+
149
+ const resultPreview = record.result
150
+ ? record.result.length > resultMaxLen
151
+ ? record.result.slice(0, resultMaxLen) + "\n...(truncated, use get_subagent_result for full output)"
152
+ : record.result
153
+ : "No output.";
154
+
155
+ return [
156
+ `<task-notification>`,
157
+ `<task-id>${record.id}</task-id>`,
158
+ record.toolCallId ? `<tool-use-id>${escapeXml(record.toolCallId)}</tool-use-id>` : null,
159
+ record.outputFile ? `<output-file>${escapeXml(record.outputFile)}</output-file>` : null,
160
+ `<status>${escapeXml(status)}</status>`,
161
+ `<summary>Agent "${escapeXml(record.description)}" ${record.status}</summary>`,
162
+ `<result>${escapeXml(resultPreview)}</result>`,
163
+ `<usage><total_tokens>${totalTokens}</total_tokens><tool_uses>${record.toolUses}</tool_uses><duration_ms>${durationMs}</duration_ms></usage>`,
164
+ `</task-notification>`,
165
+ ].filter(Boolean).join('\n');
166
+ }
167
+
168
+ /** Build AgentDetails from a base + record-specific fields. */
169
+ function buildDetails(
170
+ base: Pick<AgentDetails, "displayName" | "description" | "subagentType" | "modelName" | "tags">,
171
+ record: { toolUses: number; startedAt: number; completedAt?: number; status: string; error?: string; id?: string; session?: any },
172
+ activity?: AgentActivity,
173
+ overrides?: Partial<AgentDetails>,
174
+ ): AgentDetails {
175
+ return {
176
+ ...base,
177
+ toolUses: record.toolUses,
178
+ tokens: safeFormatTokens(record.session),
179
+ turnCount: activity?.turnCount,
180
+ maxTurns: activity?.maxTurns,
181
+ durationMs: (record.completedAt ?? Date.now()) - record.startedAt,
182
+ status: record.status as AgentDetails["status"],
183
+ agentId: record.id,
184
+ error: record.error,
185
+ ...overrides,
186
+ };
187
+ }
188
+
189
+ /** Build notification details for the custom message renderer. */
190
+ function buildNotificationDetails(record: AgentRecord, resultMaxLen: number, activity?: AgentActivity): NotificationDetails {
191
+ let totalTokens = 0;
192
+ try {
193
+ if (record.session) totalTokens = record.session.getSessionStats().tokens?.total ?? 0;
194
+ } catch {}
195
+
196
+ return {
197
+ id: record.id,
198
+ description: record.description,
199
+ status: record.status,
200
+ toolUses: record.toolUses,
201
+ turnCount: activity?.turnCount ?? 0,
202
+ maxTurns: activity?.maxTurns,
203
+ totalTokens,
204
+ durationMs: record.completedAt ? record.completedAt - record.startedAt : 0,
205
+ outputFile: record.outputFile,
206
+ error: record.error,
207
+ resultPreview: record.result
208
+ ? record.result.length > resultMaxLen
209
+ ? record.result.slice(0, resultMaxLen) + "…"
210
+ : record.result
211
+ : "No output.",
212
+ };
213
+ }
214
+
215
+ export default function (pi: ExtensionAPI) {
216
+ // ---- Register custom notification renderer ----
217
+ pi.registerMessageRenderer<NotificationDetails>(
218
+ "subagent-notification",
219
+ (message, { expanded }, theme) => {
220
+ const d = message.details;
221
+ if (!d) return undefined;
222
+
223
+ function renderOne(d: NotificationDetails): string {
224
+ const isError = d.status === "error" || d.status === "stopped" || d.status === "aborted";
225
+ const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
226
+ const statusText = isError ? d.status
227
+ : d.status === "steered" ? "completed (steered)"
228
+ : "completed";
229
+
230
+ // Line 1: icon + agent description + status
231
+ let line = `${icon} ${theme.bold(d.description)} ${theme.fg("dim", statusText)}`;
232
+
233
+ // Line 2: stats
234
+ const parts: string[] = [];
235
+ if (d.turnCount > 0) parts.push(formatTurns(d.turnCount, d.maxTurns));
236
+ if (d.toolUses > 0) parts.push(`${d.toolUses} tool use${d.toolUses === 1 ? "" : "s"}`);
237
+ if (d.totalTokens > 0) parts.push(formatTokens(d.totalTokens));
238
+ if (d.durationMs > 0) parts.push(formatMs(d.durationMs));
239
+ if (parts.length) {
240
+ line += "\n " + parts.map(p => theme.fg("dim", p)).join(" " + theme.fg("dim", "·") + " ");
241
+ }
242
+
243
+ // Line 3: result preview (collapsed) or full (expanded)
244
+ if (expanded) {
245
+ const lines = d.resultPreview.split("\n").slice(0, 30);
246
+ for (const l of lines) line += "\n" + theme.fg("dim", ` ${l}`);
247
+ } else {
248
+ const preview = d.resultPreview.split("\n")[0]?.slice(0, 80) ?? "";
249
+ line += "\n " + theme.fg("dim", `⎿ ${preview}`);
250
+ }
251
+
252
+ // Line 4: output file link (if present)
253
+ if (d.outputFile) {
254
+ line += "\n " + theme.fg("muted", `transcript: ${d.outputFile}`);
255
+ }
256
+
257
+ return line;
258
+ }
259
+
260
+ const all = [d, ...(d.others ?? [])];
261
+ return new Text(all.map(renderOne).join("\n"), 0, 0);
262
+ }
263
+ );
264
+
265
+ let currentProjectCwd = process.cwd?.() ?? undefined;
266
+
267
+ /** Reload agents from .pi/agents/*.md and merge with defaults (called on init and each Agent invocation). */
268
+ const getProjectCwd = () => currentProjectCwd;
269
+
270
+ const reloadCustomAgents = () => {
271
+ const cwd = getProjectCwd();
272
+ if (!cwd) return;
273
+ const userAgents = loadCustomAgents(cwd);
274
+ registerAgents(userAgents);
275
+ };
276
+
277
+ // Initial load
278
+ reloadCustomAgents();
279
+
280
+ // ---- Agent activity tracking + widget ----
281
+ const agentActivity = new Map<string, AgentActivity>();
282
+
283
+ // ---- Cancellable pending notifications ----
284
+ // Holds notifications briefly so get_subagent_result can cancel them
285
+ // before they reach pi.sendMessage (fire-and-forget).
286
+ const pendingNudges = new Map<string, ReturnType<typeof setTimeout>>();
287
+ const NUDGE_HOLD_MS = 200;
288
+
289
+ function scheduleNudge(key: string, send: () => void, delay = NUDGE_HOLD_MS) {
290
+ cancelNudge(key);
291
+ pendingNudges.set(key, setTimeout(() => {
292
+ pendingNudges.delete(key);
293
+ send();
294
+ }, delay));
295
+ }
296
+
297
+ function cancelNudge(key: string) {
298
+ const timer = pendingNudges.get(key);
299
+ if (timer != null) {
300
+ clearTimeout(timer);
301
+ pendingNudges.delete(key);
302
+ }
303
+ }
304
+
305
+ // ---- Individual nudge helper (async join mode) ----
306
+ function emitIndividualNudge(record: AgentRecord) {
307
+ if (record.resultConsumed) return; // re-check at send time
308
+
309
+ const shouldTriggerTurn = !manager.hasRunning();
310
+ const notification = formatTaskNotification(record, 500);
311
+ const footer = record.outputFile ? `
312
+ Full transcript available at: ${record.outputFile}` : '';
313
+
314
+ pi.sendMessage<NotificationDetails>({
315
+ customType: "subagent-notification",
316
+ content: notification + footer,
317
+ display: true,
318
+ details: buildNotificationDetails(record, 500, agentActivity.get(record.id)),
319
+ }, { deliverAs: "followUp", triggerTurn: shouldTriggerTurn });
320
+ }
321
+
322
+ function sendIndividualNudge(record: AgentRecord) {
323
+ agentActivity.delete(record.id);
324
+ widget.markFinished(record.id);
325
+ scheduleNudge(record.id, () => emitIndividualNudge(record));
326
+ widget.update();
327
+ }
328
+
329
+ // ---- Group join manager ----
330
+ const groupJoin = new GroupJoinManager(
331
+ (records, partial) => {
332
+ for (const r of records) { agentActivity.delete(r.id); widget.markFinished(r.id); }
333
+
334
+ const groupKey = `group:${records.map(r => r.id).join(",")}`;
335
+ scheduleNudge(groupKey, () => {
336
+ // Re-check at send time
337
+ const unconsumed = records.filter(r => !r.resultConsumed);
338
+ if (unconsumed.length === 0) { widget.update(); return; }
339
+
340
+ const notifications = unconsumed.map(r => formatTaskNotification(r, 300)).join('\n\n');
341
+ const label = partial
342
+ ? `${unconsumed.length} agent(s) finished (partial — others still running)`
343
+ : `${unconsumed.length} agent(s) finished`;
344
+
345
+ const [first, ...rest] = unconsumed;
346
+ const details = buildNotificationDetails(first, 300, agentActivity.get(first.id));
347
+ if (rest.length > 0) {
348
+ details.others = rest.map(r => buildNotificationDetails(r, 300, agentActivity.get(r.id)));
349
+ }
350
+
351
+ const shouldTriggerTurn = !partial && !manager.hasRunning();
352
+ pi.sendMessage<NotificationDetails>({
353
+ customType: "subagent-notification",
354
+ content: `Background agent group completed: ${label}
355
+
356
+ ${notifications}
357
+
358
+ Use get_subagent_result for full output.`,
359
+ display: true,
360
+ details,
361
+ }, { deliverAs: "followUp", triggerTurn: shouldTriggerTurn });
362
+ });
363
+ widget.update();
364
+ },
365
+ 30_000,
366
+ );
367
+
368
+ /** Helper: build event data for lifecycle events from an AgentRecord. */
369
+ function buildEventData(record: AgentRecord) {
370
+ const durationMs = record.completedAt ? record.completedAt - record.startedAt : Date.now() - record.startedAt;
371
+ let tokens: { input: number; output: number; total: number } | undefined;
372
+ try {
373
+ if (record.session) {
374
+ const stats = record.session.getSessionStats();
375
+ tokens = {
376
+ input: stats.tokens?.input ?? 0,
377
+ output: stats.tokens?.output ?? 0,
378
+ total: stats.tokens?.total ?? 0,
379
+ };
380
+ }
381
+ } catch { /* session stats unavailable */ }
382
+ return {
383
+ id: record.id,
384
+ type: record.type,
385
+ description: record.description,
386
+ result: record.result,
387
+ error: record.error,
388
+ status: record.status,
389
+ toolUses: record.toolUses,
390
+ durationMs,
391
+ tokens,
392
+ };
393
+ }
394
+
395
+ // Background completion: route through group join or send individual nudge
396
+ const firstProgressSeen = new Set<string>();
397
+ const firstTurnSeen = new Set<string>();
398
+
399
+ const manager = new AgentManager((record) => {
400
+ firstProgressSeen.delete(record.id);
401
+ firstTurnSeen.delete(record.id);
402
+
403
+ let eventData: ReturnType<typeof buildEventData> | undefined;
404
+ try {
405
+ eventData = buildEventData(record);
406
+ } catch {}
407
+
408
+ if (eventData) {
409
+ const isError = record.status === "error" || record.status === "stopped" || record.status === "aborted";
410
+ try {
411
+ if (isError) {
412
+ pi.events.emit("subagents:failed", eventData);
413
+ } else {
414
+ pi.events.emit("subagents:completed", eventData);
415
+ }
416
+ } catch (error) {
417
+ }
418
+ }
419
+
420
+ try {
421
+ pi.appendEntry("subagents:record", {
422
+ id: record.id, type: record.type, description: record.description,
423
+ status: record.status, result: record.result, error: record.error,
424
+ startedAt: record.startedAt, completedAt: record.completedAt,
425
+ });
426
+ } catch (error) {
427
+ }
428
+
429
+ // Skip notification if result was already consumed via get_subagent_result
430
+ if (record.resultConsumed) {
431
+ agentActivity.delete(record.id);
432
+ widget.markFinished(record.id);
433
+ widget.update();
434
+ return;
435
+ }
436
+
437
+ // If this agent is pending batch finalization (debounce window still open),
438
+ // don't send an individual nudge — finalizeBatch will pick it up retroactively.
439
+ if (currentBatchAgents.some(a => a.id === record.id)) {
440
+ widget.update();
441
+ return;
442
+ }
443
+
444
+ const result = groupJoin.onAgentComplete(record);
445
+ if (result === 'pass') {
446
+ sendIndividualNudge(record);
447
+ }
448
+ // 'held' → do nothing, group will fire later
449
+ // 'delivered' → group callback already fired
450
+ widget.update();
451
+ }, undefined, (record) => {
452
+ // Emit started event when agent transitions to running (including from queue)
453
+ try {
454
+ pi.events.emit("subagents:started", {
455
+ id: record.id,
456
+ type: record.type,
457
+ description: record.description,
458
+ });
459
+ } catch {}
460
+ });
461
+
462
+ // Expose manager via Symbol.for() global registry for cross-package access.
463
+ // Standard Node.js pattern for cross-package singletons (used by OpenTelemetry, etc.).
464
+ const MANAGER_KEY = Symbol.for("pi-subagents:manager");
465
+ (globalThis as any)[MANAGER_KEY] = {
466
+ waitForAll: () => manager.waitForAll(),
467
+ hasRunning: () => manager.hasRunning(),
468
+ spawn: (piRef: any, ctx: any, type: string, prompt: string, options: any) =>
469
+ manager.spawn(piRef, ctx, type, prompt, options),
470
+ getRecord: (id: string) => manager.getRecord(id),
471
+ refreshWidget: (uiCtx?: any) => {
472
+ if (uiCtx) widget.setUICtx(uiCtx as UICtx);
473
+ widget.update();
474
+ },
475
+ };
476
+
477
+ // --- Cross-extension RPC via pi.events ---
478
+ let currentCtx: ExtensionContext | undefined;
479
+
480
+ // Capture ctx from session_start for RPC spawn handler
481
+ pi.on("session_start", async (_event, ctx) => {
482
+ currentCtx = ctx;
483
+ currentProjectCwd = ctx.cwd ?? currentProjectCwd;
484
+ if ((globalThis as any)[Symbol.for("pi-pi:subagent-session")]) {
485
+ pi.appendEntry("subagent-session", { active: true });
486
+ }
487
+ manager.clearCompleted(); // preserve existing behavior
488
+ });
489
+
490
+ let managedSession = false;
491
+ pi.events.on("subagents:set-managed", (data: any) => {
492
+ managedSession = data?.managed === true;
493
+ });
494
+
495
+ pi.on("session_switch", (event: any) => {
496
+ if (!managedSession) manager.clearCompleted();
497
+ });
498
+
499
+ const { unsubPing: unsubPingRpc, unsubSpawn: unsubSpawnRpc, unsubStop: unsubStopRpc } = registerRpcHandlers({
500
+ events: pi.events,
501
+ pi,
502
+ getCtx: () => currentCtx,
503
+ isSubagentSession: (ctx: unknown) => Boolean((ctx as any)?.sessionManager?.getEntries?.().some?.((entry: any) => entry?.type === "custom" && entry?.customType === "subagent-session")),
504
+ manager,
505
+ });
506
+
507
+ // Allow other extensions to take full control of agent registry
508
+ pi.events.on("subagents:set-extension-only", (data: any) => {
509
+ if (typeof data?.enabled === "boolean") {
510
+ setExtensionOnlyMode(data.enabled);
511
+ reloadCustomAgents();
512
+ }
513
+ });
514
+
515
+ // Allow other extensions to register in-memory agent types
516
+ pi.events.on("subagents:register-agents", (data: any) => {
517
+ if (data?.agents && data.agents instanceof Map) {
518
+ registerExtensionAgents(data.agents);
519
+ reloadCustomAgents();
520
+ }
521
+ });
522
+
523
+ pi.events.on("subagents:unregister-agents", (data: any) => {
524
+ if (data?.all === true) {
525
+ clearExtensionAgents();
526
+ reloadCustomAgents();
527
+ } else if (data?.names && Array.isArray(data.names)) {
528
+ unregisterExtensionAgents(data.names);
529
+ reloadCustomAgents();
530
+ } else if (data?.prefix && typeof data.prefix === "string") {
531
+ unregisterExtensionAgentsByPrefix(data.prefix);
532
+ reloadCustomAgents();
533
+ }
534
+ });
535
+
536
+ // Broadcast readiness so extensions loaded after us can discover us
537
+ pi.events.emit("subagents:ready", {});
538
+
539
+ // Interactive session transitions can emit session_shutdown while background
540
+ // agents are still alive. Keep the subagent manager alive across shutdown so
541
+ // background sessions can finish and still be surfaced in the next parent session.
542
+ pi.on("session_shutdown", async () => {
543
+ return;
544
+ });
545
+
546
+ // Live widget: show running agents above editor
547
+ const widget = new AgentWidget(manager, agentActivity);
548
+
549
+ // ---- Join mode configuration ----
550
+ let defaultJoinMode: JoinMode = 'smart';
551
+ function getDefaultJoinMode(): JoinMode { return defaultJoinMode; }
552
+ function setDefaultJoinMode(mode: JoinMode) { defaultJoinMode = mode; }
553
+
554
+ // ---- Batch tracking for smart join mode ----
555
+ // Collects background agent IDs spawned in the current turn for smart grouping.
556
+ // Uses a debounced timer: each new agent resets the 100ms window so that all
557
+ // parallel tool calls (which may be dispatched across multiple microtasks by the
558
+ // framework) are captured in the same batch.
559
+ let currentBatchAgents: { id: string; joinMode: JoinMode }[] = [];
560
+ let batchFinalizeTimer: ReturnType<typeof setTimeout> | undefined;
561
+ let batchCounter = 0;
562
+
563
+ /** Finalize the current batch: if 2+ smart-mode agents, register as a group. */
564
+ function finalizeBatch() {
565
+ batchFinalizeTimer = undefined;
566
+ const batchAgents = [...currentBatchAgents];
567
+ currentBatchAgents = [];
568
+
569
+ const smartAgents = batchAgents.filter(a => a.joinMode === 'smart' || a.joinMode === 'group');
570
+ if (smartAgents.length >= 2) {
571
+ const groupId = `batch-${++batchCounter}`;
572
+ const ids = smartAgents.map(a => a.id);
573
+ groupJoin.registerGroup(groupId, ids);
574
+ // Retroactively process agents that already completed during the debounce window.
575
+ // Their onComplete fired but was deferred (agent was in currentBatchAgents),
576
+ // so we feed them into the group now.
577
+ for (const id of ids) {
578
+ const record = manager.getRecord(id);
579
+ if (!record) continue;
580
+ record.groupId = groupId;
581
+ if (record.completedAt != null && !record.resultConsumed) {
582
+ groupJoin.onAgentComplete(record);
583
+ }
584
+ }
585
+ } else {
586
+ // No group formed — send individual nudges for any agents that completed
587
+ // during the debounce window and had their notification deferred.
588
+ for (const { id } of batchAgents) {
589
+ const record = manager.getRecord(id);
590
+ if (record?.completedAt != null && !record.resultConsumed) {
591
+ sendIndividualNudge(record);
592
+ }
593
+ }
594
+ }
595
+ }
596
+
597
+ // Grab UI context from first tool execution + clear lingering widget on new turn
598
+ pi.on("tool_execution_start", async (_event, ctx) => {
599
+ const hadUiCtx = Boolean((widget as any).uiCtx);
600
+ widget.setUICtx(ctx.ui as UICtx);
601
+ if (!hadUiCtx) widget.update();
602
+ widget.onTurnStart();
603
+ });
604
+
605
+ pi.on("before_agent_start", async (_event, ctx) => {
606
+ const hadUiCtx = Boolean((widget as any).uiCtx);
607
+ widget.setUICtx(ctx.ui as UICtx);
608
+ if (!hadUiCtx) widget.update();
609
+ });
610
+
611
+ /** Build the full type list text dynamically from the unified registry. */
612
+ const buildTypeListText = () => {
613
+ const defaultNames = getDefaultAgentNames();
614
+ const userNames = getUserAgentNames();
615
+
616
+ const defaultDescs = defaultNames.map((name) => {
617
+ const cfg = getAgentConfig(name);
618
+ const modelSuffix = cfg?.model ? ` (${getModelLabelFromConfig(cfg.model)})` : "";
619
+ return `- ${name}: ${cfg?.description ?? name}${modelSuffix}`;
620
+ });
621
+
622
+ const customDescs = userNames.map((name) => {
623
+ const cfg = getAgentConfig(name);
624
+ return `- ${name}: ${cfg?.description ?? name}`;
625
+ });
626
+
627
+ return [
628
+ "Default agents:",
629
+ ...defaultDescs,
630
+ ...(customDescs.length > 0 ? ["", "Custom agents:", ...customDescs] : []),
631
+ "",
632
+ "Custom agents can be defined in .pi/agents/<name>.md (project) or ~/.pi/agent/agents/<name>.md (global) — they are picked up automatically. Project-level agents override global ones. Creating a .md file with the same name as a default agent overrides it.",
633
+ ].join("\n");
634
+ };
635
+
636
+ /** Derive a short model label from a model string. */
637
+ function getModelLabelFromConfig(model: string): string {
638
+ // Strip provider prefix (e.g. "anthropic/claude-sonnet-4-6" → "claude-sonnet-4-6")
639
+ const name = model.includes("/") ? model.split("/").pop()! : model;
640
+ // Strip trailing date suffix (e.g. "claude-haiku-4-5-20251001" → "claude-haiku-4-5")
641
+ return name.replace(/-\d{8}$/, "");
642
+ }
643
+
644
+ const typeListText = buildTypeListText();
645
+
646
+ // ---- Agent tool ----
647
+
648
+ pi.registerTool<any, AgentDetails>({
649
+ name: "Agent",
650
+ label: "Agent",
651
+ description: `Launch a new agent to handle complex, multi-step tasks autonomously.
652
+
653
+ The Agent tool launches specialized agents that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
654
+
655
+ Available agent types:
656
+ ${typeListText}
657
+
658
+ Guidelines:
659
+ - For parallel work, use run_in_background: true on each agent. Foreground calls run sequentially — only one executes at a time.
660
+ - Use Explore for codebase searches and code understanding.
661
+ - Use Plan for architecture and implementation planning.
662
+ - Use general-purpose for complex tasks that need file editing.
663
+ - Provide clear, detailed prompts so the agent can work autonomously.
664
+ - Agent results are returned as text — summarize them for the user.
665
+ - Use run_in_background for work you don't need immediately. You will be notified when it completes.
666
+ - Use resume with an agent ID to continue a previous agent's work.
667
+ - Use steer_subagent to send mid-run messages to a running background agent.
668
+ - Use model to specify a different model (as "provider/modelId", or fuzzy e.g. "haiku", "sonnet").
669
+ - Use thinking to control extended thinking level.
670
+ - Use inherit_context if the agent needs the parent conversation history.
671
+ - Use isolation: "worktree" to run the agent in an isolated git worktree (safe parallel file modifications).`,
672
+ parameters: Type.Object({
673
+ prompt: Type.String({
674
+ description: "The task for the agent to perform.",
675
+ }),
676
+ description: Type.String({
677
+ description: "A short (3-5 word) description of the task (shown in UI).",
678
+ }),
679
+ subagent_type: Type.String({
680
+ description: `The type of specialized agent to use. Available types: ${getAvailableTypes().join(", ")}. Custom agents from .pi/agents/*.md (project) or ~/.pi/agent/agents/*.md (global) are also available.`,
681
+ }),
682
+ model: Type.Optional(
683
+ Type.String({
684
+ description:
685
+ 'Optional model override. Accepts "provider/modelId" or fuzzy name (e.g. "haiku", "sonnet"). Omit to use the agent type\'s default.',
686
+ }),
687
+ ),
688
+ thinking: Type.Optional(
689
+ Type.String({
690
+ description: "Thinking level: off, minimal, low, medium, high, xhigh. Overrides agent default.",
691
+ }),
692
+ ),
693
+ max_turns: Type.Optional(
694
+ Type.Number({
695
+ description: "Maximum number of agentic turns before stopping. Omit for unlimited (default).",
696
+ minimum: 1,
697
+ }),
698
+ ),
699
+ run_in_background: Type.Optional(
700
+ Type.Boolean({
701
+ description: "Set to true to run in background. Returns agent ID immediately. You will be notified on completion.",
702
+ }),
703
+ ),
704
+ resume: Type.Optional(
705
+ Type.String({
706
+ description: "Optional agent ID to resume from. Continues from previous context.",
707
+ }),
708
+ ),
709
+ isolated: Type.Optional(
710
+ Type.Boolean({
711
+ description: "If true, agent gets no extension/MCP tools — only built-in tools.",
712
+ }),
713
+ ),
714
+ inherit_context: Type.Optional(
715
+ Type.Boolean({
716
+ description: "If true, fork parent conversation into the agent. Default: false (fresh context).",
717
+ }),
718
+ ),
719
+ isolation: Type.Optional(
720
+ Type.Literal("worktree", {
721
+ description: 'Set to "worktree" to run the agent in a temporary git worktree (isolated copy of the repo). Changes are saved to a branch on completion.',
722
+ }),
723
+ ),
724
+ }),
725
+
726
+ // ---- Custom rendering: Claude Code style ----
727
+
728
+ renderCall(args, theme) {
729
+ const displayName = args.subagent_type ? getDisplayName(args.subagent_type) : "Agent";
730
+ const desc = args.description ?? "";
731
+ return new Text("▸ " + theme.fg("toolTitle", theme.bold(displayName)) + (desc ? " " + theme.fg("muted", desc) : ""), 0, 0);
732
+ },
733
+
734
+ renderResult(result, { expanded, isPartial }, theme) {
735
+ const details = result.details as AgentDetails | undefined;
736
+ if (!details) {
737
+ const text = result.content[0]?.type === "text" ? result.content[0].text : "";
738
+ return new Text(text, 0, 0);
739
+ }
740
+
741
+ // Helper: build "haiku · thinking: high · ⟳5≤30 · 3 tool uses · 33.8k tokens" stats string
742
+ const stats = (d: AgentDetails) => {
743
+ const parts: string[] = [];
744
+ if (d.modelName) parts.push(d.modelName);
745
+ if (d.tags) parts.push(...d.tags);
746
+ if (d.turnCount != null && d.turnCount > 0) {
747
+ parts.push(formatTurns(d.turnCount, d.maxTurns));
748
+ }
749
+ if (d.toolUses > 0) parts.push(`${d.toolUses} tool use${d.toolUses === 1 ? "" : "s"}`);
750
+ if (d.tokens) parts.push(d.tokens);
751
+ return parts.map(p => theme.fg("dim", p)).join(" " + theme.fg("dim", "·") + " ");
752
+ };
753
+
754
+ // ---- While running (streaming) ----
755
+ if (isPartial || details.status === "running") {
756
+ const frame = SPINNER[details.spinnerFrame ?? 0];
757
+ const s = stats(details);
758
+ let line = theme.fg("accent", frame) + (s ? " " + s : "");
759
+ line += "\n" + theme.fg("dim", ` ⎿ ${details.activity ?? "thinking…"}`);
760
+ return new Text(line, 0, 0);
761
+ }
762
+
763
+ // ---- Background agent launched ----
764
+ if (details.status === "background") {
765
+ return new Text(theme.fg("dim", ` ⎿ Running in background (ID: ${details.agentId})`), 0, 0);
766
+ }
767
+
768
+ // ---- Completed / Steered ----
769
+ if (details.status === "completed" || details.status === "steered") {
770
+ const duration = formatMs(details.durationMs);
771
+ const isSteered = details.status === "steered";
772
+ const icon = isSteered ? theme.fg("warning", "✓") : theme.fg("success", "✓");
773
+ const s = stats(details);
774
+ let line = icon + (s ? " " + s : "");
775
+ line += " " + theme.fg("dim", "·") + " " + theme.fg("dim", duration);
776
+
777
+ if (expanded) {
778
+ const resultText = result.content[0]?.type === "text" ? result.content[0].text : "";
779
+ if (resultText) {
780
+ const lines = resultText.split("\n").slice(0, 50);
781
+ for (const l of lines) {
782
+ line += "\n" + theme.fg("dim", ` ${l}`);
783
+ }
784
+ if (resultText.split("\n").length > 50) {
785
+ line += "\n" + theme.fg("muted", " ... (use get_subagent_result with verbose for full output)");
786
+ }
787
+ }
788
+ } else {
789
+ const doneText = isSteered ? "Wrapped up (turn limit)" : "Done";
790
+ line += "\n" + theme.fg("dim", ` ⎿ ${doneText}`);
791
+ }
792
+ return new Text(line, 0, 0);
793
+ }
794
+
795
+ // ---- Stopped (user-initiated abort) ----
796
+ if (details.status === "stopped") {
797
+ const s = stats(details);
798
+ let line = theme.fg("dim", "■") + (s ? " " + s : "");
799
+ line += "\n" + theme.fg("dim", " ⎿ Stopped");
800
+ return new Text(line, 0, 0);
801
+ }
802
+
803
+ // ---- Error / Aborted (hard max_turns) ----
804
+ const s = stats(details);
805
+ let line = theme.fg("error", "✗") + (s ? " " + s : "");
806
+
807
+ if (details.status === "error") {
808
+ line += "\n" + theme.fg("error", ` ⎿ Error: ${details.error ?? "unknown"}`);
809
+ } else {
810
+ line += "\n" + theme.fg("warning", " ⎿ Aborted (max turns exceeded)");
811
+ }
812
+
813
+ return new Text(line, 0, 0);
814
+ },
815
+
816
+ // ---- Execute ----
817
+
818
+ execute: async (toolCallId, params, signal, onUpdate, ctx) => {
819
+ // Ensure we have UI context for widget rendering
820
+ widget.setUICtx(ctx.ui as UICtx);
821
+
822
+ // Reload custom agents so new .pi/agents/*.md files are picked up without restart
823
+ reloadCustomAgents();
824
+
825
+ const rawType = params.subagent_type as SubagentType;
826
+ const resolved = resolveType(rawType);
827
+ const subagentType = resolved ?? "general-purpose";
828
+ const fellBack = resolved === undefined;
829
+
830
+ const displayName = getDisplayName(subagentType);
831
+
832
+ // Get agent config (if any)
833
+ const customConfig = getAgentConfig(subagentType);
834
+
835
+ const resolvedConfig = resolveAgentInvocationConfig(customConfig, params);
836
+
837
+ // Resolve model from agent config first; tool-call params only fill gaps.
838
+ let model = ctx.model;
839
+ if (resolvedConfig.modelInput) {
840
+ const resolved = resolveModel(resolvedConfig.modelInput, ctx.modelRegistry);
841
+ if (typeof resolved === "string") {
842
+ if (resolvedConfig.modelFromParams) return textResult(resolved);
843
+ // config-specified: silent fallback to parent
844
+ } else {
845
+ model = resolved;
846
+ }
847
+ }
848
+
849
+ const thinking = resolvedConfig.thinking;
850
+ const inheritContext = resolvedConfig.inheritContext;
851
+ const runInBackground = resolvedConfig.runInBackground;
852
+ const isolated = resolvedConfig.isolated;
853
+ const isolation = resolvedConfig.isolation;
854
+
855
+ // Build display tags for non-default config
856
+ const parentModelId = ctx.model?.id;
857
+ const effectiveModelId = model?.id;
858
+ const agentModelName = effectiveModelId && effectiveModelId !== parentModelId
859
+ ? (model?.name ?? effectiveModelId).replace(/^Claude\s+/i, "").toLowerCase()
860
+ : undefined;
861
+ const agentTags: string[] = [];
862
+ const modeLabel = getPromptModeLabel(subagentType);
863
+ if (modeLabel) agentTags.push(modeLabel);
864
+ if (thinking) agentTags.push(`thinking: ${thinking}`);
865
+ if (isolated) agentTags.push("isolated");
866
+ if (isolation === "worktree") agentTags.push("worktree");
867
+ const effectiveMaxTurns = normalizeMaxTurns(resolvedConfig.maxTurns ?? getDefaultMaxTurns());
868
+ // Shared base fields for all AgentDetails in this call
869
+ const detailBase = {
870
+ displayName,
871
+ description: params.description,
872
+ subagentType,
873
+ modelName: agentModelName,
874
+ tags: agentTags.length > 0 ? agentTags : undefined,
875
+ };
876
+
877
+ // Resume existing agent
878
+ if (params.resume) {
879
+ const existing = manager.getRecord(params.resume);
880
+ if (!existing) {
881
+ return textResult(`Agent not found: "${params.resume}". It may have been cleaned up.`);
882
+ }
883
+ if (!existing.session) {
884
+ return textResult(`Agent "${params.resume}" has no active session to resume.`);
885
+ }
886
+ const record = await manager.resume(params.resume, params.prompt, signal);
887
+ if (!record) {
888
+ return textResult(`Failed to resume agent "${params.resume}".`);
889
+ }
890
+ return textResult(
891
+ record.result?.trim() || record.error?.trim() || "No output.",
892
+ buildDetails(detailBase, record),
893
+ );
894
+ }
895
+
896
+ // Background execution
897
+ if (runInBackground) {
898
+ const { state: bgState, callbacks: bgCallbacks } = createActivityTracker(effectiveMaxTurns);
899
+
900
+ let id: string;
901
+ const emitFirstTool = (toolName: string) => {
902
+ if (firstProgressSeen.has(id)) return;
903
+ firstProgressSeen.add(id);
904
+ pi.events.emit("subagents:first_tool", {
905
+ id,
906
+ type: subagentType,
907
+ description: params.description,
908
+ toolName,
909
+ });
910
+ };
911
+ const emitFirstTurn = (turnCount: number) => {
912
+ if (firstTurnSeen.has(id)) return;
913
+ firstTurnSeen.add(id);
914
+ pi.events.emit("subagents:first_turn", {
915
+ id,
916
+ type: subagentType,
917
+ description: params.description,
918
+ turnCount,
919
+ });
920
+ };
921
+ const originalBgToolActivity = bgCallbacks.onToolActivity;
922
+ bgCallbacks.onToolActivity = (activity) => {
923
+ originalBgToolActivity(activity);
924
+ if (activity.type === "start") emitFirstTool(activity.toolName);
925
+ };
926
+ const originalBgTurnEnd = bgCallbacks.onTurnEnd;
927
+ bgCallbacks.onTurnEnd = (turnCount) => {
928
+ originalBgTurnEnd(turnCount);
929
+ emitFirstTurn(turnCount);
930
+ };
931
+
932
+ // Wrap onSessionCreated to wire output file streaming.
933
+ // The callback lazily reads record.outputFile (set right after spawn)
934
+ // rather than closing over a value that doesn't exist yet.
935
+ const origBgOnSession = bgCallbacks.onSessionCreated;
936
+ bgCallbacks.onSessionCreated = (session: any) => {
937
+ origBgOnSession(session);
938
+ firstProgressSeen.delete(id);
939
+ firstTurnSeen.delete(id);
940
+ const rec = manager.getRecord(id);
941
+ if (rec?.outputFile) {
942
+ rec.outputCleanup = streamToOutputFile(session, rec.outputFile, id, ctx.cwd);
943
+ }
944
+ };
945
+
946
+ id = manager.spawn(pi, ctx, subagentType, params.prompt, {
947
+ description: params.description,
948
+ model,
949
+ maxTurns: effectiveMaxTurns,
950
+ isolated,
951
+ inheritContext,
952
+ thinkingLevel: thinking,
953
+ isBackground: true,
954
+ isolation,
955
+ ...bgCallbacks,
956
+ });
957
+
958
+ pi.events.emit("subagents:created", {
959
+ id,
960
+ type: subagentType,
961
+ description: params.description,
962
+ isBackground: true,
963
+ });
964
+
965
+ // Set output file + join mode synchronously after spawn, before the
966
+ // event loop yields — onSessionCreated is async so this is safe.
967
+ const joinMode = resolveJoinMode(defaultJoinMode, true);
968
+ const record = manager.getRecord(id);
969
+ if (record && joinMode) {
970
+ record.joinMode = joinMode;
971
+ record.toolCallId = toolCallId;
972
+ const sessionId = ctx.sessionManager.getSessionId?.();
973
+ if (ctx.cwd && sessionId) {
974
+ record.outputFile = createOutputFilePath(ctx.cwd, id, sessionId);
975
+ writeInitialEntry(record.outputFile, id, params.prompt, ctx.cwd);
976
+ }
977
+ }
978
+
979
+ if (joinMode == null || joinMode === 'async') {
980
+ // Foreground/no join mode or explicit async — not part of any batch
981
+ } else {
982
+ // smart or group — add to current batch
983
+ currentBatchAgents.push({ id, joinMode });
984
+ // Debounce: reset timer on each new agent so parallel tool calls
985
+ // dispatched across multiple event loop ticks are captured together
986
+ if (batchFinalizeTimer) clearTimeout(batchFinalizeTimer);
987
+ batchFinalizeTimer = setTimeout(finalizeBatch, 100);
988
+ }
989
+
990
+ agentActivity.set(id, bgState);
991
+ widget.ensureTimer();
992
+ widget.update();
993
+
994
+ const isQueued = record?.status === "queued";
995
+ return textResult(
996
+ `Agent ${isQueued ? "queued" : "started"} in background.\n` +
997
+ `Agent ID: ${id}\n` +
998
+ `Type: ${displayName}\n` +
999
+ `Description: ${params.description}\n` +
1000
+ (record?.outputFile ? `Output file: ${record.outputFile}\n` : "") +
1001
+ (isQueued ? `Position: queued (max ${manager.getMaxConcurrent()} concurrent)\n` : "") +
1002
+ `\nYou will be notified when this agent completes.\n` +
1003
+ `Use get_subagent_result to retrieve full results, or steer_subagent to send it messages.\n` +
1004
+ `Do not duplicate this agent's work.`,
1005
+ { ...detailBase, toolUses: 0, tokens: "", durationMs: 0, status: "background" as const, agentId: id },
1006
+ );
1007
+ }
1008
+
1009
+ // Foreground (synchronous) execution — stream progress via onUpdate
1010
+ let spinnerFrame = 0;
1011
+ const startedAt = Date.now();
1012
+ let fgId: string | undefined;
1013
+
1014
+ const streamUpdate = () => {
1015
+ const details: AgentDetails = {
1016
+ ...detailBase,
1017
+ toolUses: fgState.toolUses,
1018
+ tokens: fgState.tokens,
1019
+ turnCount: fgState.turnCount,
1020
+ maxTurns: fgState.maxTurns,
1021
+ durationMs: Date.now() - startedAt,
1022
+ status: "running",
1023
+ activity: describeActivity(fgState.activeTools, fgState.responseText),
1024
+ spinnerFrame: spinnerFrame % SPINNER.length,
1025
+ };
1026
+ onUpdate?.({
1027
+ content: [{ type: "text", text: `${fgState.toolUses} tool uses...` }],
1028
+ details: details as any,
1029
+ });
1030
+ };
1031
+
1032
+ const { state: fgState, callbacks: fgCallbacks } = createActivityTracker(effectiveMaxTurns, streamUpdate);
1033
+
1034
+ // Wire session creation to register in widget
1035
+ const origOnSession = fgCallbacks.onSessionCreated;
1036
+ fgCallbacks.onSessionCreated = (session: any) => {
1037
+ origOnSession(session);
1038
+ for (const a of manager.listAgents()) {
1039
+ if (a.session === session) {
1040
+ fgId = a.id;
1041
+ agentActivity.set(a.id, fgState);
1042
+ widget.ensureTimer();
1043
+ break;
1044
+ }
1045
+ }
1046
+ };
1047
+
1048
+ // Animate spinner at ~80ms (smooth rotation through 10 braille frames)
1049
+ const spinnerInterval = setInterval(() => {
1050
+ spinnerFrame++;
1051
+ streamUpdate();
1052
+ }, 80);
1053
+
1054
+ streamUpdate();
1055
+
1056
+ const record = await manager.spawnAndWait(pi, ctx, subagentType, params.prompt, {
1057
+ description: params.description,
1058
+ model,
1059
+ maxTurns: effectiveMaxTurns,
1060
+ isolated,
1061
+ inheritContext,
1062
+ thinkingLevel: thinking,
1063
+ isolation,
1064
+ ...fgCallbacks,
1065
+ });
1066
+
1067
+ clearInterval(spinnerInterval);
1068
+
1069
+ // Clean up foreground agent from widget
1070
+ if (fgId) {
1071
+ agentActivity.delete(fgId);
1072
+ widget.markFinished(fgId);
1073
+ }
1074
+
1075
+ // Get final token count
1076
+ const tokenText = safeFormatTokens(fgState.session);
1077
+
1078
+ const details = buildDetails(detailBase, record, fgState, { tokens: tokenText });
1079
+
1080
+ const fallbackNote = fellBack
1081
+ ? `Note: Unknown agent type "${rawType}" — using general-purpose.\n\n`
1082
+ : "";
1083
+
1084
+ if (record.status === "error") {
1085
+ return textResult(`${fallbackNote}Agent failed: ${record.error}`, details);
1086
+ }
1087
+
1088
+ const durationMs = (record.completedAt ?? Date.now()) - record.startedAt;
1089
+ const statsParts = [`${record.toolUses} tool uses`];
1090
+ if (tokenText) statsParts.push(tokenText);
1091
+ return textResult(
1092
+ `${fallbackNote}Agent completed in ${formatMs(durationMs)} (${statsParts.join(", ")})${getStatusNote(record.status)}.\n\n` +
1093
+ (record.result?.trim() || "No output."),
1094
+ details,
1095
+ );
1096
+ },
1097
+ });
1098
+
1099
+ // ---- get_subagent_result tool ----
1100
+
1101
+ pi.registerTool({
1102
+ name: "get_subagent_result",
1103
+ label: "Get Agent Result",
1104
+ description:
1105
+ "Check status and retrieve results from a background agent. Use the agent ID returned by Agent with run_in_background.",
1106
+ parameters: Type.Object({
1107
+ agent_id: Type.String({
1108
+ description: "The agent ID to check.",
1109
+ }),
1110
+ wait: Type.Optional(
1111
+ Type.Boolean({
1112
+ description: "If true, wait for the agent to complete before returning. Default: false.",
1113
+ }),
1114
+ ),
1115
+ verbose: Type.Optional(
1116
+ Type.Boolean({
1117
+ description: "If true, include the agent's full conversation (messages + tool calls). Default: false.",
1118
+ }),
1119
+ ),
1120
+ }),
1121
+ execute: async (_toolCallId, params, _signal, _onUpdate, _ctx) => {
1122
+ const record = manager.getRecord(params.agent_id);
1123
+ if (!record) {
1124
+ return textResult(`Agent not found: "${params.agent_id}". It may have been cleaned up.`);
1125
+ }
1126
+
1127
+ // Wait for completion if requested.
1128
+ // Pre-mark resultConsumed BEFORE awaiting: onComplete fires inside .then()
1129
+ // (attached earlier at spawn time) and always runs before this await resumes.
1130
+ // Setting the flag here prevents a redundant follow-up notification.
1131
+ if (params.wait && record.status === "running" && record.promise) {
1132
+ record.resultConsumed = true;
1133
+ cancelNudge(params.agent_id);
1134
+ await record.promise;
1135
+ }
1136
+
1137
+ const displayName = getDisplayName(record.type);
1138
+ const duration = formatDuration(record.startedAt, record.completedAt);
1139
+ const tokens = safeFormatTokens(record.session);
1140
+ const toolStats = tokens ? `Tool uses: ${record.toolUses} | ${tokens}` : `Tool uses: ${record.toolUses}`;
1141
+
1142
+ let output =
1143
+ `Agent: ${record.id}\n` +
1144
+ `Type: ${displayName} | Status: ${record.status} | ${toolStats} | Duration: ${duration}\n` +
1145
+ `Description: ${record.description}\n\n`;
1146
+
1147
+ if (record.status === "running") {
1148
+ output += "Agent is still running. Use wait: true or check back later.";
1149
+ } else if (record.status === "error") {
1150
+ output += `Error: ${record.error}`;
1151
+ } else {
1152
+ output += record.result?.trim() || "No output.";
1153
+ }
1154
+
1155
+ // Mark result as consumed — suppresses the completion notification
1156
+ if (record.status !== "running" && record.status !== "queued") {
1157
+ record.resultConsumed = true;
1158
+ cancelNudge(params.agent_id);
1159
+ }
1160
+
1161
+ // Verbose: include full conversation
1162
+ if (params.verbose && record.session) {
1163
+ const conversation = getAgentConversation(record.session);
1164
+ if (conversation) {
1165
+ output += `\n\n--- Agent Conversation ---\n${conversation}`;
1166
+ }
1167
+ }
1168
+
1169
+ return textResult(output);
1170
+ },
1171
+ });
1172
+
1173
+ // ---- steer_subagent tool ----
1174
+
1175
+ pi.registerTool({
1176
+ name: "steer_subagent",
1177
+ label: "Steer Agent",
1178
+ description:
1179
+ "Send a steering message to a running agent. The message will interrupt the agent after its current tool execution " +
1180
+ "and be injected into its conversation, allowing you to redirect its work mid-run. Only works on running agents.",
1181
+ parameters: Type.Object({
1182
+ agent_id: Type.String({
1183
+ description: "The agent ID to steer (must be currently running).",
1184
+ }),
1185
+ message: Type.String({
1186
+ description: "The steering message to send. This will appear as a user message in the agent's conversation.",
1187
+ }),
1188
+ }),
1189
+ execute: async (_toolCallId, params, _signal, _onUpdate, _ctx) => {
1190
+ const record = manager.getRecord(params.agent_id);
1191
+ if (!record) {
1192
+ return textResult(`Agent not found: "${params.agent_id}". It may have been cleaned up.`);
1193
+ }
1194
+ if (record.status !== "running") {
1195
+ return textResult(`Agent "${params.agent_id}" is not running (status: ${record.status}). Cannot steer a non-running agent.`);
1196
+ }
1197
+ if (!record.session) {
1198
+ // Session not ready yet — queue the steer for delivery once initialized
1199
+ if (!record.pendingSteers) record.pendingSteers = [];
1200
+ record.pendingSteers.push(params.message);
1201
+ pi.events.emit("subagents:steered", { id: record.id, message: params.message });
1202
+ return textResult(`Steering message queued for agent ${record.id}. It will be delivered once the session initializes.`);
1203
+ }
1204
+
1205
+ try {
1206
+ await steerAgent(record.session, params.message);
1207
+ pi.events.emit("subagents:steered", { id: record.id, message: params.message });
1208
+ return textResult(`Steering message sent to agent ${record.id}. The agent will process it after its current tool execution.`);
1209
+ } catch (err) {
1210
+ return textResult(`Failed to steer agent: ${err instanceof Error ? err.message : String(err)}`);
1211
+ }
1212
+ },
1213
+ });
1214
+
1215
+ // ---- /agents interactive menu ----
1216
+
1217
+ const projectAgentsDir = () => {
1218
+ const cwd = getProjectCwd();
1219
+ return cwd ? join(cwd, ".pi", "agents") : undefined;
1220
+ };
1221
+ const personalAgentsDir = () => join(homedir(), ".pi", "agent", "agents");
1222
+
1223
+ /** Find the file path of a custom agent by name (project first, then global). */
1224
+ function findAgentFile(name: string): { path: string; location: "project" | "personal" } | undefined {
1225
+ const projectDir = projectAgentsDir();
1226
+ if (projectDir) {
1227
+ const projectPath = join(projectDir, `${name}.md`);
1228
+ if (existsSync(projectPath)) return { path: projectPath, location: "project" };
1229
+ }
1230
+ const personalPath = join(personalAgentsDir(), `${name}.md`);
1231
+ if (existsSync(personalPath)) return { path: personalPath, location: "personal" };
1232
+ return undefined;
1233
+ }
1234
+
1235
+ function getModelLabel(type: string, registry?: ModelRegistry): string {
1236
+ const cfg = getAgentConfig(type);
1237
+ if (!cfg?.model) return "inherit";
1238
+ // If registry provided, check if the model actually resolves
1239
+ if (registry) {
1240
+ const resolved = resolveModel(cfg.model, registry);
1241
+ if (typeof resolved === "string") return "inherit"; // model not available
1242
+ }
1243
+ return getModelLabelFromConfig(cfg.model);
1244
+ }
1245
+
1246
+ async function showAgentsMenu(ctx: ExtensionCommandContext) {
1247
+ reloadCustomAgents();
1248
+ const allNames = getAllTypes();
1249
+
1250
+ // Build select options
1251
+ const options: string[] = [];
1252
+
1253
+ // Running agents entry (only if there are active agents)
1254
+ const agents = manager.listAgents();
1255
+ if (agents.length > 0) {
1256
+ const running = agents.filter(a => a.status === "running" || a.status === "queued").length;
1257
+ const done = agents.filter(a => a.status === "completed" || a.status === "steered").length;
1258
+ options.push(`Running agents (${agents.length}) — ${running} running, ${done} done`);
1259
+ }
1260
+
1261
+ // Agent types list
1262
+ if (allNames.length > 0) {
1263
+ options.push(`Agent types (${allNames.length})`);
1264
+ }
1265
+
1266
+ // Actions
1267
+ options.push("Create new agent");
1268
+ options.push("Settings");
1269
+
1270
+ const noAgentsMsg = allNames.length === 0 && agents.length === 0
1271
+ ? "No agents found. Create specialized subagents that can be delegated to.\n\n" +
1272
+ "Each subagent has its own context window, custom system prompt, and specific tools.\n\n" +
1273
+ "Try creating: Code Reviewer, Security Auditor, Test Writer, or Documentation Writer.\n\n"
1274
+ : "";
1275
+
1276
+ if (noAgentsMsg) {
1277
+ ctx.ui.notify(noAgentsMsg, "info");
1278
+ }
1279
+
1280
+ const choice = await ctx.ui.select("Agents", options);
1281
+ if (!choice) return;
1282
+
1283
+ if (choice.startsWith("Running agents (")) {
1284
+ await showRunningAgents(ctx);
1285
+ await showAgentsMenu(ctx);
1286
+ } else if (choice.startsWith("Agent types (")) {
1287
+ await showAllAgentsList(ctx);
1288
+ await showAgentsMenu(ctx);
1289
+ } else if (choice === "Create new agent") {
1290
+ await showCreateWizard(ctx);
1291
+ } else if (choice === "Settings") {
1292
+ await showSettings(ctx);
1293
+ await showAgentsMenu(ctx);
1294
+ }
1295
+ }
1296
+
1297
+ async function showAllAgentsList(ctx: ExtensionCommandContext) {
1298
+ const allNames = getAllTypes();
1299
+ if (allNames.length === 0) {
1300
+ ctx.ui.notify("No agents.", "info");
1301
+ return;
1302
+ }
1303
+
1304
+ // Source indicators: defaults unmarked, custom agents get • (project) or ◦ (global)
1305
+ // Disabled agents get ✕ prefix
1306
+ const sourceIndicator = (cfg: AgentConfig | undefined) => {
1307
+ const disabled = cfg?.enabled === false;
1308
+ if (cfg?.source === "project") return disabled ? "✕• " : "• ";
1309
+ if (cfg?.source === "global") return disabled ? "✕◦ " : "◦ ";
1310
+ if (disabled) return "✕ ";
1311
+ return " ";
1312
+ };
1313
+
1314
+ const entries = allNames.map(name => {
1315
+ const cfg = getAgentConfig(name);
1316
+ const disabled = cfg?.enabled === false;
1317
+ const model = getModelLabel(name, ctx.modelRegistry);
1318
+ const indicator = sourceIndicator(cfg);
1319
+ const prefix = `${indicator}${name} · ${model}`;
1320
+ const desc = disabled ? "(disabled)" : (cfg?.description ?? name);
1321
+ return { name, prefix, desc };
1322
+ });
1323
+ const maxPrefix = Math.max(...entries.map(e => e.prefix.length));
1324
+
1325
+ const hasCustom = allNames.some(n => { const c = getAgentConfig(n); return c && !c.isDefault && c.enabled !== false; });
1326
+ const hasDisabled = allNames.some(n => getAgentConfig(n)?.enabled === false);
1327
+ const legendParts: string[] = [];
1328
+ if (hasCustom) legendParts.push("• = project ◦ = global");
1329
+ if (hasDisabled) legendParts.push("✕ = disabled");
1330
+ const legend = legendParts.length ? "\n" + legendParts.join(" ") : "";
1331
+
1332
+ const options = entries.map(({ prefix, desc }) =>
1333
+ `${prefix.padEnd(maxPrefix)} — ${desc}`,
1334
+ );
1335
+ if (legend) options.push(legend);
1336
+
1337
+ const choice = await ctx.ui.select("Agent types", options);
1338
+ if (!choice) return;
1339
+
1340
+ const agentName = choice.split(" · ")[0].replace(/^[•◦✕\s]+/, "").trim();
1341
+ if (getAgentConfig(agentName)) {
1342
+ await showAgentDetail(ctx, agentName);
1343
+ await showAllAgentsList(ctx);
1344
+ }
1345
+ }
1346
+
1347
+ async function showRunningAgents(ctx: ExtensionCommandContext) {
1348
+ const agents = manager.listAgents();
1349
+ if (agents.length === 0) {
1350
+ ctx.ui.notify("No agents.", "info");
1351
+ return;
1352
+ }
1353
+
1354
+ const options = agents.map(a => {
1355
+ const dn = getDisplayName(a.type);
1356
+ const dur = formatDuration(a.startedAt, a.completedAt);
1357
+ return `${dn} (${a.description}) · ${a.toolUses} tools · ${a.status} · ${dur}`;
1358
+ });
1359
+
1360
+ const choice = await ctx.ui.select("Running agents", options);
1361
+ if (!choice) return;
1362
+
1363
+ // Find the selected agent by matching the option index
1364
+ const idx = options.indexOf(choice);
1365
+ if (idx < 0) return;
1366
+ const record = agents[idx];
1367
+
1368
+ await viewAgentConversation(ctx, record);
1369
+ // Back-navigation: re-show the list
1370
+ await showRunningAgents(ctx);
1371
+ }
1372
+
1373
+ async function viewAgentConversation(ctx: ExtensionCommandContext, record: AgentRecord) {
1374
+ if (!record.session) {
1375
+ ctx.ui.notify(`Agent is ${record.status === "queued" ? "queued" : "expired"} — no session available.`, "info");
1376
+ return;
1377
+ }
1378
+
1379
+ const { ConversationViewer } = await import("./ui/conversation-viewer.js");
1380
+ const session = record.session;
1381
+ const activity = agentActivity.get(record.id);
1382
+
1383
+ await ctx.ui.custom<undefined>(
1384
+ (tui, theme, _keybindings, done) => {
1385
+ return new ConversationViewer(tui, session, record, activity, theme, done);
1386
+ },
1387
+ {
1388
+ overlay: true,
1389
+ overlayOptions: { anchor: "center", width: "90%" },
1390
+ },
1391
+ );
1392
+ }
1393
+
1394
+ async function showAgentDetail(ctx: ExtensionCommandContext, name: string) {
1395
+ const cfg = getAgentConfig(name);
1396
+ if (!cfg) {
1397
+ ctx.ui.notify(`Agent config not found for "${name}".`, "warning");
1398
+ return;
1399
+ }
1400
+
1401
+ const file = findAgentFile(name);
1402
+ const isDefault = cfg.isDefault === true;
1403
+ const disabled = cfg.enabled === false;
1404
+
1405
+ let menuOptions: string[];
1406
+ if (disabled && file) {
1407
+ // Disabled agent with a file — offer Enable
1408
+ menuOptions = isDefault
1409
+ ? ["Enable", "Edit", "Reset to default", "Delete", "Back"]
1410
+ : ["Enable", "Edit", "Delete", "Back"];
1411
+ } else if (isDefault && !file) {
1412
+ // Default agent with no .md override
1413
+ menuOptions = ["Eject (export as .md)", "Disable", "Back"];
1414
+ } else if (isDefault && file) {
1415
+ // Default agent with .md override (ejected)
1416
+ menuOptions = ["Edit", "Disable", "Reset to default", "Delete", "Back"];
1417
+ } else {
1418
+ // User-defined agent
1419
+ menuOptions = ["Edit", "Disable", "Delete", "Back"];
1420
+ }
1421
+
1422
+ const choice = await ctx.ui.select(name, menuOptions);
1423
+ if (!choice || choice === "Back") return;
1424
+
1425
+ if (choice === "Edit" && file) {
1426
+ const content = readFileSync(file.path, "utf-8");
1427
+ const edited = await ctx.ui.editor(`Edit ${name}`, content);
1428
+ if (edited !== undefined && edited !== content) {
1429
+ const { writeFileSync } = await import("node:fs");
1430
+ writeFileSync(file.path, edited, "utf-8");
1431
+ reloadCustomAgents();
1432
+ ctx.ui.notify(`Updated ${file.path}`, "info");
1433
+ }
1434
+ } else if (choice === "Delete") {
1435
+ if (file) {
1436
+ const confirmed = await ctx.ui.confirm("Delete agent", `Delete ${name} from ${file.location} (${file.path})?`);
1437
+ if (confirmed) {
1438
+ unlinkSync(file.path);
1439
+ reloadCustomAgents();
1440
+ ctx.ui.notify(`Deleted ${file.path}`, "info");
1441
+ }
1442
+ }
1443
+ } else if (choice === "Reset to default" && file) {
1444
+ const confirmed = await ctx.ui.confirm("Reset to default", `Delete override ${file.path} and restore embedded default?`);
1445
+ if (confirmed) {
1446
+ unlinkSync(file.path);
1447
+ reloadCustomAgents();
1448
+ ctx.ui.notify(`Restored default ${name}`, "info");
1449
+ }
1450
+ } else if (choice.startsWith("Eject")) {
1451
+ await ejectAgent(ctx, name, cfg);
1452
+ } else if (choice === "Disable") {
1453
+ await disableAgent(ctx, name);
1454
+ } else if (choice === "Enable") {
1455
+ await enableAgent(ctx, name);
1456
+ }
1457
+ }
1458
+
1459
+ /** Eject a default agent: write its embedded config as a .md file. */
1460
+ async function ejectAgent(ctx: ExtensionCommandContext, name: string, cfg: AgentConfig) {
1461
+ const location = await ctx.ui.select("Choose location", [
1462
+ "Project (.pi/agents/)",
1463
+ "Personal (~/.pi/agent/agents/)",
1464
+ ]);
1465
+ if (!location) return;
1466
+
1467
+ const targetDir = location.startsWith("Project") ? projectAgentsDir() : personalAgentsDir();
1468
+ mkdirSync(targetDir, { recursive: true });
1469
+
1470
+ const targetPath = join(targetDir, `${name}.md`);
1471
+ if (existsSync(targetPath)) {
1472
+ const overwrite = await ctx.ui.confirm("Overwrite", `${targetPath} already exists. Overwrite?`);
1473
+ if (!overwrite) return;
1474
+ }
1475
+
1476
+ // Build the .md file content
1477
+ const fmFields: string[] = [];
1478
+ fmFields.push(`description: ${cfg.description}`);
1479
+ if (cfg.displayName) fmFields.push(`display_name: ${cfg.displayName}`);
1480
+ fmFields.push(`tools: ${cfg.builtinToolNames?.join(", ") || "all"}`);
1481
+ if (cfg.model) fmFields.push(`model: ${cfg.model}`);
1482
+ if (cfg.thinking) fmFields.push(`thinking: ${cfg.thinking}`);
1483
+ if (cfg.maxTurns) fmFields.push(`max_turns: ${cfg.maxTurns}`);
1484
+ fmFields.push(`prompt_mode: ${cfg.promptMode}`);
1485
+ if (cfg.extensions === false) fmFields.push("extensions: false");
1486
+ else if (Array.isArray(cfg.extensions)) fmFields.push(`extensions: ${cfg.extensions.join(", ")}`);
1487
+ if (cfg.skills === false) fmFields.push("skills: false");
1488
+ else if (Array.isArray(cfg.skills)) fmFields.push(`skills: ${cfg.skills.join(", ")}`);
1489
+ if (cfg.disallowedTools?.length) fmFields.push(`disallowed_tools: ${cfg.disallowedTools.join(", ")}`);
1490
+ if (cfg.inheritContext) fmFields.push("inherit_context: true");
1491
+ if (cfg.runInBackground) fmFields.push("run_in_background: true");
1492
+ if (cfg.isolated) fmFields.push("isolated: true");
1493
+ if (cfg.memory) fmFields.push(`memory: ${cfg.memory}`);
1494
+ if (cfg.isolation) fmFields.push(`isolation: ${cfg.isolation}`);
1495
+
1496
+ const content = `---\n${fmFields.join("\n")}\n---\n\n${cfg.systemPrompt}\n`;
1497
+
1498
+ const { writeFileSync } = await import("node:fs");
1499
+ writeFileSync(targetPath, content, "utf-8");
1500
+ reloadCustomAgents();
1501
+ ctx.ui.notify(`Ejected ${name} to ${targetPath}`, "info");
1502
+ }
1503
+
1504
+ /** Disable an agent: set enabled: false in its .md file, or create a stub for built-in defaults. */
1505
+ async function disableAgent(ctx: ExtensionCommandContext, name: string) {
1506
+ const file = findAgentFile(name);
1507
+ if (file) {
1508
+ // Existing file — set enabled: false in frontmatter (idempotent)
1509
+ const content = readFileSync(file.path, "utf-8");
1510
+ if (content.includes("\nenabled: false\n")) {
1511
+ ctx.ui.notify(`${name} is already disabled.`, "info");
1512
+ return;
1513
+ }
1514
+ const updated = content.replace(/^---\n/, "---\nenabled: false\n");
1515
+ const { writeFileSync } = await import("node:fs");
1516
+ writeFileSync(file.path, updated, "utf-8");
1517
+ reloadCustomAgents();
1518
+ ctx.ui.notify(`Disabled ${name} (${file.path})`, "info");
1519
+ return;
1520
+ }
1521
+
1522
+ // No file (built-in default) — create a stub
1523
+ const location = await ctx.ui.select("Choose location", [
1524
+ "Project (.pi/agents/)",
1525
+ "Personal (~/.pi/agent/agents/)",
1526
+ ]);
1527
+ if (!location) return;
1528
+
1529
+ const targetDir = location.startsWith("Project") ? projectAgentsDir() : personalAgentsDir();
1530
+ mkdirSync(targetDir, { recursive: true });
1531
+
1532
+ const targetPath = join(targetDir, `${name}.md`);
1533
+ const { writeFileSync } = await import("node:fs");
1534
+ writeFileSync(targetPath, "---\nenabled: false\n---\n", "utf-8");
1535
+ reloadCustomAgents();
1536
+ ctx.ui.notify(`Disabled ${name} (${targetPath})`, "info");
1537
+ }
1538
+
1539
+ /** Enable a disabled agent by removing enabled: false from its frontmatter. */
1540
+ async function enableAgent(ctx: ExtensionCommandContext, name: string) {
1541
+ const file = findAgentFile(name);
1542
+ if (!file) return;
1543
+
1544
+ const content = readFileSync(file.path, "utf-8");
1545
+ const updated = content.replace(/^(---\n)enabled: false\n/, "$1");
1546
+ const { writeFileSync } = await import("node:fs");
1547
+
1548
+ // If the file was just a stub ("---\n---\n"), delete it to restore the built-in default
1549
+ if (updated.trim() === "---\n---" || updated.trim() === "---\n---\n") {
1550
+ unlinkSync(file.path);
1551
+ reloadCustomAgents();
1552
+ ctx.ui.notify(`Enabled ${name} (removed ${file.path})`, "info");
1553
+ } else {
1554
+ writeFileSync(file.path, updated, "utf-8");
1555
+ reloadCustomAgents();
1556
+ ctx.ui.notify(`Enabled ${name} (${file.path})`, "info");
1557
+ }
1558
+ }
1559
+
1560
+ async function showCreateWizard(ctx: ExtensionCommandContext) {
1561
+ const location = await ctx.ui.select("Choose location", [
1562
+ "Project (.pi/agents/)",
1563
+ "Personal (~/.pi/agent/agents/)",
1564
+ ]);
1565
+ if (!location) return;
1566
+
1567
+ const targetDir = location.startsWith("Project") ? projectAgentsDir() : personalAgentsDir();
1568
+
1569
+ const method = await ctx.ui.select("Creation method", [
1570
+ "Generate with Claude (recommended)",
1571
+ "Manual configuration",
1572
+ ]);
1573
+ if (!method) return;
1574
+
1575
+ if (method.startsWith("Generate")) {
1576
+ await showGenerateWizard(ctx, targetDir);
1577
+ } else {
1578
+ await showManualWizard(ctx, targetDir);
1579
+ }
1580
+ }
1581
+
1582
+ async function showGenerateWizard(ctx: ExtensionCommandContext, targetDir: string) {
1583
+ const description = await ctx.ui.input("Describe what this agent should do");
1584
+ if (!description) return;
1585
+
1586
+ const name = await ctx.ui.input("Agent name (filename, no spaces)");
1587
+ if (!name) return;
1588
+
1589
+ mkdirSync(targetDir, { recursive: true });
1590
+
1591
+ const targetPath = join(targetDir, `${name}.md`);
1592
+ if (existsSync(targetPath)) {
1593
+ const overwrite = await ctx.ui.confirm("Overwrite", `${targetPath} already exists. Overwrite?`);
1594
+ if (!overwrite) return;
1595
+ }
1596
+
1597
+ ctx.ui.notify("Generating agent definition...", "info");
1598
+
1599
+ const generatePrompt = `Create a custom pi sub-agent definition file based on this description: "${description}"
1600
+
1601
+ Write a markdown file to: ${targetPath}
1602
+
1603
+ The file format is a markdown file with YAML frontmatter and a system prompt body:
1604
+
1605
+ \`\`\`markdown
1606
+ ---
1607
+ description: <one-line description shown in UI>
1608
+ tools: <comma-separated built-in tools: read, bash, edit, write, grep, find, ls. Use "none" for no tools. Omit for all tools>
1609
+ model: <optional model as "provider/modelId", e.g. "anthropic/claude-haiku-4-5-20251001". Omit to inherit parent model>
1610
+ thinking: <optional thinking level: off, minimal, low, medium, high, xhigh. Omit to inherit>
1611
+ max_turns: <optional max agentic turns. 0 or omit for unlimited (default)>
1612
+ prompt_mode: <"replace" (body IS the full system prompt) or "append" (body is appended to default prompt). Default: replace>
1613
+ extensions: <true (inherit all MCP/extension tools), false (none), or comma-separated names. Default: true>
1614
+ skills: <true (inherit all), false (none), or comma-separated skill names to preload into prompt. Default: true>
1615
+ disallowed_tools: <comma-separated tool names to block, even if otherwise available. Omit for none>
1616
+ inherit_context: <true to fork parent conversation into agent so it sees chat history. Default: false>
1617
+ run_in_background: <true to run in background by default. Default: false>
1618
+ isolated: <true for no extension/MCP tools, only built-in tools. Default: false>
1619
+ memory: <"user" (global), "project" (per-project), or "local" (gitignored per-project) for persistent memory. Omit for none>
1620
+ isolation: <"worktree" to run in isolated git worktree. Omit for normal>
1621
+ ---
1622
+
1623
+ <system prompt body — instructions for the agent>
1624
+ \`\`\`
1625
+
1626
+ Guidelines for choosing settings:
1627
+ - For read-only tasks (review, analysis): tools: read, bash, grep, find, ls
1628
+ - For code modification tasks: include edit, write
1629
+ - Use prompt_mode: append if the agent should keep the default system prompt and add specialization on top
1630
+ - Use prompt_mode: replace for fully custom agents with their own personality/instructions
1631
+ - Set inherit_context: true if the agent needs to know what was discussed in the parent conversation
1632
+ - Set isolated: true if the agent should NOT have access to MCP servers or other extensions
1633
+ - Only include frontmatter fields that differ from defaults — omit fields where the default is fine
1634
+
1635
+ Write the file using the write tool. Only write the file, nothing else.`;
1636
+
1637
+ const record = await manager.spawnAndWait(pi, ctx, "general-purpose", generatePrompt, {
1638
+ description: `Generate ${name} agent`,
1639
+ maxTurns: 5,
1640
+ });
1641
+
1642
+ if (record.status === "error") {
1643
+ ctx.ui.notify(`Generation failed: ${record.error}`, "warning");
1644
+ return;
1645
+ }
1646
+
1647
+ reloadCustomAgents();
1648
+
1649
+ if (existsSync(targetPath)) {
1650
+ ctx.ui.notify(`Created ${targetPath}`, "info");
1651
+ } else {
1652
+ ctx.ui.notify("Agent generation completed but file was not created. Check the agent output.", "warning");
1653
+ }
1654
+ }
1655
+
1656
+ async function showManualWizard(ctx: ExtensionCommandContext, targetDir: string) {
1657
+ // 1. Name
1658
+ const name = await ctx.ui.input("Agent name (filename, no spaces)");
1659
+ if (!name) return;
1660
+
1661
+ // 2. Description
1662
+ const description = await ctx.ui.input("Description (one line)");
1663
+ if (!description) return;
1664
+
1665
+ // 3. Tools
1666
+ const toolChoice = await ctx.ui.select("Tools", ["all", "none", "read-only (read, bash, grep, find, ls)", "custom..."]);
1667
+ if (!toolChoice) return;
1668
+
1669
+ let tools: string;
1670
+ if (toolChoice === "all") {
1671
+ tools = BUILTIN_TOOL_NAMES.join(", ");
1672
+ } else if (toolChoice === "none") {
1673
+ tools = "none";
1674
+ } else if (toolChoice.startsWith("read-only")) {
1675
+ tools = "read, bash, grep, find, ls";
1676
+ } else {
1677
+ const customTools = await ctx.ui.input("Tools (comma-separated)", BUILTIN_TOOL_NAMES.join(", "));
1678
+ if (!customTools) return;
1679
+ tools = customTools;
1680
+ }
1681
+
1682
+ // 4. Model
1683
+ const modelChoice = await ctx.ui.select("Model", [
1684
+ "inherit (parent model)",
1685
+ "haiku",
1686
+ "sonnet",
1687
+ "opus",
1688
+ "custom...",
1689
+ ]);
1690
+ if (!modelChoice) return;
1691
+
1692
+ let modelLine = "";
1693
+ if (modelChoice === "haiku") modelLine = "\nmodel: anthropic/claude-haiku-4-5-20251001";
1694
+ else if (modelChoice === "sonnet") modelLine = "\nmodel: anthropic/claude-sonnet-4-6";
1695
+ else if (modelChoice === "opus") modelLine = "\nmodel: anthropic/claude-opus-4-6";
1696
+ else if (modelChoice === "custom...") {
1697
+ const customModel = await ctx.ui.input("Model (provider/modelId)");
1698
+ if (customModel) modelLine = `\nmodel: ${customModel}`;
1699
+ }
1700
+
1701
+ // 5. Thinking
1702
+ const thinkingChoice = await ctx.ui.select("Thinking level", [
1703
+ "inherit",
1704
+ "off",
1705
+ "minimal",
1706
+ "low",
1707
+ "medium",
1708
+ "high",
1709
+ "xhigh",
1710
+ ]);
1711
+ if (!thinkingChoice) return;
1712
+
1713
+ let thinkingLine = "";
1714
+ if (thinkingChoice !== "inherit") thinkingLine = `\nthinking: ${thinkingChoice}`;
1715
+
1716
+ // 6. System prompt
1717
+ const systemPrompt = await ctx.ui.editor("System prompt", "");
1718
+ if (systemPrompt === undefined) return;
1719
+
1720
+ // Build the file
1721
+ const content = `---
1722
+ description: ${description}
1723
+ tools: ${tools}${modelLine}${thinkingLine}
1724
+ prompt_mode: replace
1725
+ ---
1726
+
1727
+ ${systemPrompt}
1728
+ `;
1729
+
1730
+ mkdirSync(targetDir, { recursive: true });
1731
+ const targetPath = join(targetDir, `${name}.md`);
1732
+
1733
+ if (existsSync(targetPath)) {
1734
+ const overwrite = await ctx.ui.confirm("Overwrite", `${targetPath} already exists. Overwrite?`);
1735
+ if (!overwrite) return;
1736
+ }
1737
+
1738
+ const { writeFileSync } = await import("node:fs");
1739
+ writeFileSync(targetPath, content, "utf-8");
1740
+ reloadCustomAgents();
1741
+ ctx.ui.notify(`Created ${targetPath}`, "info");
1742
+ }
1743
+
1744
+ async function showSettings(ctx: ExtensionCommandContext) {
1745
+ const choice = await ctx.ui.select("Settings", [
1746
+ `Max concurrency (current: ${manager.getMaxConcurrent()})`,
1747
+ `Default max turns (current: ${getDefaultMaxTurns() ?? "unlimited"})`,
1748
+ `Grace turns (current: ${getGraceTurns()})`,
1749
+ `Join mode (current: ${getDefaultJoinMode()})`,
1750
+ ]);
1751
+ if (!choice) return;
1752
+
1753
+ if (choice.startsWith("Max concurrency")) {
1754
+ const val = await ctx.ui.input("Max concurrent background agents", String(manager.getMaxConcurrent()));
1755
+ if (val) {
1756
+ const n = parseInt(val, 10);
1757
+ if (n >= 1) {
1758
+ manager.setMaxConcurrent(n);
1759
+ ctx.ui.notify(`Max concurrency set to ${n}`, "info");
1760
+ } else {
1761
+ ctx.ui.notify("Must be a positive integer.", "warning");
1762
+ }
1763
+ }
1764
+ } else if (choice.startsWith("Default max turns")) {
1765
+ const val = await ctx.ui.input("Default max turns before wrap-up (0 = unlimited)", String(getDefaultMaxTurns() ?? 0));
1766
+ if (val) {
1767
+ const n = parseInt(val, 10);
1768
+ if (n === 0) {
1769
+ setDefaultMaxTurns(undefined);
1770
+ ctx.ui.notify("Default max turns set to unlimited", "info");
1771
+ } else if (n >= 1) {
1772
+ setDefaultMaxTurns(n);
1773
+ ctx.ui.notify(`Default max turns set to ${n}`, "info");
1774
+ } else {
1775
+ ctx.ui.notify("Must be 0 (unlimited) or a positive integer.", "warning");
1776
+ }
1777
+ }
1778
+ } else if (choice.startsWith("Grace turns")) {
1779
+ const val = await ctx.ui.input("Grace turns after wrap-up steer", String(getGraceTurns()));
1780
+ if (val) {
1781
+ const n = parseInt(val, 10);
1782
+ if (n >= 1) {
1783
+ setGraceTurns(n);
1784
+ ctx.ui.notify(`Grace turns set to ${n}`, "info");
1785
+ } else {
1786
+ ctx.ui.notify("Must be a positive integer.", "warning");
1787
+ }
1788
+ }
1789
+ } else if (choice.startsWith("Join mode")) {
1790
+ const val = await ctx.ui.select("Default join mode for background agents", [
1791
+ "smart — auto-group 2+ agents in same turn (default)",
1792
+ "async — always notify individually",
1793
+ "group — always group background agents",
1794
+ ]);
1795
+ if (val) {
1796
+ const mode = val.split(" ")[0] as JoinMode;
1797
+ setDefaultJoinMode(mode);
1798
+ ctx.ui.notify(`Default join mode set to ${mode}`, "info");
1799
+ }
1800
+ }
1801
+ }
1802
+
1803
+ pi.registerCommand("agents", {
1804
+ description: "Manage agents",
1805
+ handler: async (_args, ctx) => { await showAgentsMenu(ctx); },
1806
+ });
1807
+
1808
+ (globalThis as any)[Symbol.for("pi-subagents:menu")] = {
1809
+ showMenu: async (ctx: ExtensionCommandContext) => showAgentsMenu(ctx),
1810
+ };
1811
+ }