@fitchmultz/pi-subagents 0.0.0-stage → 0.44.5

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 (347) hide show
  1. package/CHANGELOG.md +1654 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1533 -2
  4. package/agents/context-builder.md +97 -0
  5. package/agents/debugger.md +51 -0
  6. package/agents/delegate.md +13 -0
  7. package/agents/fixer.md +37 -0
  8. package/agents/oracle.md +71 -0
  9. package/agents/planner.md +72 -0
  10. package/agents/researcher.md +51 -0
  11. package/agents/reviewer-claude.md +69 -0
  12. package/agents/reviewer-gpt.md +68 -0
  13. package/agents/reviewer-ponytail.md +82 -0
  14. package/agents/reviewer-security.md +81 -0
  15. package/agents/reviewer.md +69 -0
  16. package/agents/scout.md +66 -0
  17. package/agents/ui-designer.md +51 -0
  18. package/agents/watcher.md +26 -0
  19. package/agents/worker.md +46 -0
  20. package/agents/writer.md +36 -0
  21. package/dist/agents/agent-management.js +923 -0
  22. package/dist/agents/agent-scope.js +7 -0
  23. package/dist/agents/agent-selection.js +20 -0
  24. package/dist/agents/agent-serializer.js +100 -0
  25. package/dist/agents/agents.js +752 -0
  26. package/dist/agents/chain-serializer.js +367 -0
  27. package/dist/agents/frontmatter.js +21 -0
  28. package/dist/agents/identity.js +29 -0
  29. package/dist/agents/skills.js +570 -0
  30. package/dist/extension/build-info.js +1 -0
  31. package/dist/extension/compact-tools.js +112 -0
  32. package/dist/extension/config.js +22 -0
  33. package/dist/extension/control-notices.js +29 -0
  34. package/dist/extension/doctor.js +143 -0
  35. package/dist/extension/fanout-child.js +326 -0
  36. package/dist/extension/index.js +577 -0
  37. package/dist/extension/schemas.js +416 -0
  38. package/dist/extension/tool-input.js +20 -0
  39. package/dist/extension/tool-result.js +14 -0
  40. package/dist/history/canonical-result.js +81 -0
  41. package/dist/history/database.js +72 -0
  42. package/dist/history/index.js +199 -0
  43. package/dist/history/ingest.js +468 -0
  44. package/dist/history/queries.js +350 -0
  45. package/dist/history/store.js +216 -0
  46. package/dist/history/types.js +4 -0
  47. package/dist/history/worker.js +466 -0
  48. package/dist/intercom/intercom-bridge.js +112 -0
  49. package/dist/intercom/live-intercom.js +94 -0
  50. package/dist/intercom/result-intercom.js +373 -0
  51. package/dist/pi-intercom/agent-dir.js +10 -0
  52. package/dist/pi-intercom/bridge.js +750 -0
  53. package/dist/pi-intercom/broker/broker.js +426 -0
  54. package/dist/pi-intercom/broker/client.js +492 -0
  55. package/dist/pi-intercom/broker/framing.js +65 -0
  56. package/dist/pi-intercom/broker/paths.js +42 -0
  57. package/dist/pi-intercom/broker/pid.js +66 -0
  58. package/dist/pi-intercom/broker/spawn.js +221 -0
  59. package/dist/pi-intercom/config.js +102 -0
  60. package/dist/pi-intercom/index.js +2942 -0
  61. package/dist/pi-intercom/reply-tracker.js +182 -0
  62. package/dist/pi-intercom/session-targets.js +128 -0
  63. package/dist/pi-intercom/subagent-live-events.js +132 -0
  64. package/dist/pi-intercom/topics.js +157 -0
  65. package/dist/pi-intercom/types.js +163 -0
  66. package/dist/pi-intercom/ui/compose.js +269 -0
  67. package/dist/pi-intercom/ui/inline-message.js +80 -0
  68. package/dist/pi-intercom/ui/session-list.js +124 -0
  69. package/dist/runs/background/async-control.js +95 -0
  70. package/dist/runs/background/async-execution.js +676 -0
  71. package/dist/runs/background/async-job-tracker.js +383 -0
  72. package/dist/runs/background/async-result-file.js +58 -0
  73. package/dist/runs/background/async-resume.js +305 -0
  74. package/dist/runs/background/async-status.js +442 -0
  75. package/dist/runs/background/completion-dedupe.js +69 -0
  76. package/dist/runs/background/completion-delivery.js +245 -0
  77. package/dist/runs/background/notify.js +71 -0
  78. package/dist/runs/background/parallel-groups.js +55 -0
  79. package/dist/runs/background/result-watcher.js +426 -0
  80. package/dist/runs/background/run-id-resolver.js +64 -0
  81. package/dist/runs/background/run-status.js +382 -0
  82. package/dist/runs/background/stale-run-reconciler.js +335 -0
  83. package/dist/runs/background/subagent-runner-launcher.js +55 -0
  84. package/dist/runs/background/subagent-runner.js +1872 -0
  85. package/dist/runs/background/top-level-async.js +5 -0
  86. package/dist/runs/foreground/chain-clarify.js +1152 -0
  87. package/dist/runs/foreground/clarify-invocation.js +72 -0
  88. package/dist/runs/foreground/execution-input.js +423 -0
  89. package/dist/runs/foreground/foreground-control.js +817 -0
  90. package/dist/runs/foreground/question-control.js +88 -0
  91. package/dist/runs/foreground/run-async-path.js +205 -0
  92. package/dist/runs/foreground/subagent-executor.js +442 -0
  93. package/dist/runs/foreground/subagent-params.js +165 -0
  94. package/dist/runs/foreground/wait-run.js +141 -0
  95. package/dist/runs/shared/acceptance-contract.js +253 -0
  96. package/dist/runs/shared/acceptance-evaluation.js +256 -0
  97. package/dist/runs/shared/acceptance-finalization.js +280 -0
  98. package/dist/runs/shared/acceptance-reports.js +147 -0
  99. package/dist/runs/shared/acceptance.js +4 -0
  100. package/dist/runs/shared/chain-outputs.js +110 -0
  101. package/dist/runs/shared/child-attempt.js +693 -0
  102. package/dist/runs/shared/child-execution-cwd.js +96 -0
  103. package/dist/runs/shared/child-observations.js +114 -0
  104. package/dist/runs/shared/claude-code.js +199 -0
  105. package/dist/runs/shared/completion-guard.js +31 -0
  106. package/dist/runs/shared/dynamic-fanout.js +274 -0
  107. package/dist/runs/shared/history-index.js +72 -0
  108. package/dist/runs/shared/mcp-direct-tool-allowlist.js +334 -0
  109. package/dist/runs/shared/model-fallback.js +185 -0
  110. package/dist/runs/shared/mutating-tool-guard.js +170 -0
  111. package/dist/runs/shared/native-finalization.js +101 -0
  112. package/dist/runs/shared/native-usage.js +153 -0
  113. package/dist/runs/shared/nested-events.js +700 -0
  114. package/dist/runs/shared/nested-path.js +48 -0
  115. package/dist/runs/shared/nested-render.js +108 -0
  116. package/dist/runs/shared/parallel-utils.js +61 -0
  117. package/dist/runs/shared/parent-receipts.js +68 -0
  118. package/dist/runs/shared/parent-usage.js +121 -0
  119. package/dist/runs/shared/pi-args.js +310 -0
  120. package/dist/runs/shared/pi-spawn.js +52 -0
  121. package/dist/runs/shared/run-history-queries.js +45 -0
  122. package/dist/runs/shared/run-history.js +110 -0
  123. package/dist/runs/shared/run-id-ambiguity.js +4 -0
  124. package/dist/runs/shared/run-records.js +679 -0
  125. package/dist/runs/shared/session-cwd-preload.js +33 -0
  126. package/dist/runs/shared/single-output.js +222 -0
  127. package/dist/runs/shared/streaming-text.js +15 -0
  128. package/dist/runs/shared/structured-output.js +55 -0
  129. package/dist/runs/shared/subagent-control.js +179 -0
  130. package/dist/runs/shared/subagent-prompt-runtime.js +197 -0
  131. package/dist/runs/shared/subagent-tool-loop-guard.js +66 -0
  132. package/dist/runs/shared/supervisor-questions.js +350 -0
  133. package/dist/runs/shared/workflow-graph.js +214 -0
  134. package/dist/runs/shared/workflow-policy.js +84 -0
  135. package/dist/runs/shared/worktree.js +525 -0
  136. package/dist/shared/agent-context-policy.js +126 -0
  137. package/dist/shared/artifacts.js +96 -0
  138. package/dist/shared/atomic-json.js +13 -0
  139. package/dist/shared/cooperative.js +20 -0
  140. package/dist/shared/execution-cwd.js +14 -0
  141. package/dist/shared/file-coalescer.js +21 -0
  142. package/dist/shared/fork-context.js +49 -0
  143. package/dist/shared/formatters.js +85 -0
  144. package/dist/shared/journal-reader.js +407 -0
  145. package/dist/shared/lazy-tools.js +32 -0
  146. package/dist/shared/model-info.js +68 -0
  147. package/dist/shared/native-session.js +15 -0
  148. package/dist/shared/native-tui.js +18 -0
  149. package/dist/shared/native-typebox.js +20 -0
  150. package/dist/shared/post-exit-stdio-guard.js +197 -0
  151. package/dist/shared/prompt-sections.js +8 -0
  152. package/dist/shared/session-entries.js +52 -0
  153. package/dist/shared/session-identity.js +14 -0
  154. package/dist/shared/settings.js +254 -0
  155. package/dist/shared/status-format.js +111 -0
  156. package/dist/shared/temp-root.js +114 -0
  157. package/dist/shared/types.js +207 -0
  158. package/dist/shared/ui-mode.js +3 -0
  159. package/dist/shared/utils.js +334 -0
  160. package/dist/slash/prompt-template-bridge.js +298 -0
  161. package/dist/slash/slash-bridge.js +116 -0
  162. package/dist/slash/slash-commands.js +607 -0
  163. package/dist/slash/slash-live-state.js +246 -0
  164. package/dist/tui/action-hints.js +75 -0
  165. package/dist/tui/agent-history.js +197 -0
  166. package/dist/tui/agent-view.js +1656 -0
  167. package/dist/tui/render.js +1515 -0
  168. package/docs/intercom-bridge.md +212 -0
  169. package/docs/intercom.md +581 -0
  170. package/docs/performance.md +121 -0
  171. package/package.json +102 -4
  172. package/prompts/gather-context-and-clarify.md +14 -0
  173. package/prompts/parallel-cleanup.md +62 -0
  174. package/prompts/parallel-context-build.md +56 -0
  175. package/prompts/parallel-handoff-plan.md +62 -0
  176. package/prompts/parallel-research.md +51 -0
  177. package/prompts/parallel-review.md +59 -0
  178. package/prompts/review-loop.md +42 -0
  179. package/scripts/build.mjs +134 -0
  180. package/scripts/check-compat.mjs +48 -0
  181. package/scripts/compat-host.mjs +19 -0
  182. package/scripts/intercom-bridge-credentials.mjs +143 -0
  183. package/scripts/intercom-remote.mjs +103 -0
  184. package/scripts/linux-smoke.sh +51 -0
  185. package/scripts/local-install-smoke.mjs +66 -0
  186. package/scripts/native-package-smoke.mjs +82 -0
  187. package/scripts/package-smoke.mjs +209 -0
  188. package/scripts/prepare.mjs +67 -0
  189. package/scripts/real-pi-smoke.mjs +415 -0
  190. package/scripts/run-tests.mjs +149 -0
  191. package/skills/pi-intercom/SKILL.md +113 -0
  192. package/skills/pi-intercom/evals/evals.json +29 -0
  193. package/skills/pi-intercom/evals/trigger-evals.json +47 -0
  194. package/skills/pi-intercom/references/peer-sessions.md +69 -0
  195. package/skills/pi-subagents/SKILL.md +76 -0
  196. package/skills/pi-subagents/evals/evals.json +29 -0
  197. package/skills/pi-subagents/evals/trigger-evals.json +42 -0
  198. package/skills/pi-subagents/references/full-orchestration-guide.md +863 -0
  199. package/src/agents/agent-management.ts +813 -0
  200. package/src/agents/agent-scope.ts +7 -0
  201. package/src/agents/agent-selection.ts +23 -0
  202. package/src/agents/agent-serializer.ts +99 -0
  203. package/src/agents/agents.ts +916 -0
  204. package/src/agents/chain-serializer.ts +329 -0
  205. package/src/agents/frontmatter.ts +21 -0
  206. package/src/agents/identity.ts +30 -0
  207. package/src/agents/skills.ts +637 -0
  208. package/src/extension/build-info.ts +2 -0
  209. package/src/extension/compact-tools.ts +114 -0
  210. package/src/extension/config.ts +23 -0
  211. package/src/extension/control-notices.ts +47 -0
  212. package/src/extension/doctor.ts +171 -0
  213. package/src/extension/fanout-child.ts +312 -0
  214. package/src/extension/index.ts +649 -0
  215. package/src/extension/schemas.ts +444 -0
  216. package/src/extension/tool-input.ts +19 -0
  217. package/src/extension/tool-result.ts +16 -0
  218. package/src/history/canonical-result.ts +62 -0
  219. package/src/history/database.ts +59 -0
  220. package/src/history/index.ts +156 -0
  221. package/src/history/ingest.ts +349 -0
  222. package/src/history/queries.ts +241 -0
  223. package/src/history/store.ts +203 -0
  224. package/src/history/types.ts +166 -0
  225. package/src/history/worker.ts +321 -0
  226. package/src/intercom/intercom-bridge.ts +123 -0
  227. package/src/intercom/live-intercom.ts +104 -0
  228. package/src/intercom/result-intercom.ts +429 -0
  229. package/src/pi-intercom/agent-dir.ts +9 -0
  230. package/src/pi-intercom/bridge.ts +668 -0
  231. package/src/pi-intercom/broker/broker.ts +463 -0
  232. package/src/pi-intercom/broker/client.ts +558 -0
  233. package/src/pi-intercom/broker/framing.ts +77 -0
  234. package/src/pi-intercom/broker/paths.ts +47 -0
  235. package/src/pi-intercom/broker/pid.ts +59 -0
  236. package/src/pi-intercom/broker/spawn.ts +248 -0
  237. package/src/pi-intercom/config.ts +142 -0
  238. package/src/pi-intercom/index.ts +2929 -0
  239. package/src/pi-intercom/reply-tracker.ts +211 -0
  240. package/src/pi-intercom/session-targets.ts +172 -0
  241. package/src/pi-intercom/subagent-live-events.ts +133 -0
  242. package/src/pi-intercom/topics.ts +125 -0
  243. package/src/pi-intercom/types.ts +271 -0
  244. package/src/pi-intercom/ui/compose.ts +289 -0
  245. package/src/pi-intercom/ui/inline-message.ts +92 -0
  246. package/src/pi-intercom/ui/session-list.ts +139 -0
  247. package/src/runs/background/async-control.ts +89 -0
  248. package/src/runs/background/async-execution.ts +850 -0
  249. package/src/runs/background/async-job-tracker.ts +385 -0
  250. package/src/runs/background/async-result-file.ts +62 -0
  251. package/src/runs/background/async-resume.ts +333 -0
  252. package/src/runs/background/async-status.ts +481 -0
  253. package/src/runs/background/completion-dedupe.ts +79 -0
  254. package/src/runs/background/completion-delivery.ts +195 -0
  255. package/src/runs/background/notify.ts +123 -0
  256. package/src/runs/background/parallel-groups.ts +53 -0
  257. package/src/runs/background/result-watcher.ts +423 -0
  258. package/src/runs/background/run-id-resolver.ts +69 -0
  259. package/src/runs/background/run-status.ts +384 -0
  260. package/src/runs/background/stale-run-reconciler.ts +369 -0
  261. package/src/runs/background/subagent-runner-launcher.ts +56 -0
  262. package/src/runs/background/subagent-runner.ts +2053 -0
  263. package/src/runs/background/top-level-async.ts +13 -0
  264. package/src/runs/foreground/chain-clarify.ts +1340 -0
  265. package/src/runs/foreground/clarify-invocation.ts +77 -0
  266. package/src/runs/foreground/execution-input.ts +467 -0
  267. package/src/runs/foreground/foreground-control.ts +821 -0
  268. package/src/runs/foreground/question-control.ts +82 -0
  269. package/src/runs/foreground/run-async-path.ts +243 -0
  270. package/src/runs/foreground/subagent-executor.ts +501 -0
  271. package/src/runs/foreground/subagent-params.ts +320 -0
  272. package/src/runs/foreground/wait-run.ts +124 -0
  273. package/src/runs/shared/acceptance-contract.ts +257 -0
  274. package/src/runs/shared/acceptance-evaluation.ts +275 -0
  275. package/src/runs/shared/acceptance-finalization.ts +353 -0
  276. package/src/runs/shared/acceptance-reports.ts +152 -0
  277. package/src/runs/shared/acceptance.ts +33 -0
  278. package/src/runs/shared/chain-outputs.ts +114 -0
  279. package/src/runs/shared/child-attempt.ts +623 -0
  280. package/src/runs/shared/child-execution-cwd.ts +91 -0
  281. package/src/runs/shared/child-observations.ts +99 -0
  282. package/src/runs/shared/claude-code.ts +243 -0
  283. package/src/runs/shared/completion-guard.ts +35 -0
  284. package/src/runs/shared/dynamic-fanout.ts +295 -0
  285. package/src/runs/shared/history-index.ts +69 -0
  286. package/src/runs/shared/mcp-direct-tool-allowlist.ts +376 -0
  287. package/src/runs/shared/model-fallback.ts +219 -0
  288. package/src/runs/shared/mutating-tool-guard.ts +194 -0
  289. package/src/runs/shared/native-finalization.ts +128 -0
  290. package/src/runs/shared/native-usage.ts +113 -0
  291. package/src/runs/shared/nested-events.ts +752 -0
  292. package/src/runs/shared/nested-path.ts +52 -0
  293. package/src/runs/shared/nested-render.ts +119 -0
  294. package/src/runs/shared/parallel-utils.ts +153 -0
  295. package/src/runs/shared/parent-receipts.ts +59 -0
  296. package/src/runs/shared/parent-usage.ts +121 -0
  297. package/src/runs/shared/pi-args.ts +350 -0
  298. package/src/runs/shared/pi-spawn.ts +52 -0
  299. package/src/runs/shared/run-history-queries.ts +44 -0
  300. package/src/runs/shared/run-history.ts +100 -0
  301. package/src/runs/shared/run-id-ambiguity.ts +4 -0
  302. package/src/runs/shared/run-records.ts +607 -0
  303. package/src/runs/shared/session-cwd-preload.ts +27 -0
  304. package/src/runs/shared/single-output.ts +267 -0
  305. package/src/runs/shared/streaming-text.ts +18 -0
  306. package/src/runs/shared/structured-output.ts +68 -0
  307. package/src/runs/shared/subagent-control.ts +219 -0
  308. package/src/runs/shared/subagent-prompt-runtime.ts +201 -0
  309. package/src/runs/shared/subagent-tool-loop-guard.ts +89 -0
  310. package/src/runs/shared/supervisor-questions.ts +415 -0
  311. package/src/runs/shared/workflow-graph.ts +220 -0
  312. package/src/runs/shared/workflow-policy.ts +125 -0
  313. package/src/runs/shared/worktree.ts +635 -0
  314. package/src/shared/agent-context-policy.ts +184 -0
  315. package/src/shared/artifacts.ts +95 -0
  316. package/src/shared/atomic-json.ts +16 -0
  317. package/src/shared/cooperative.ts +21 -0
  318. package/src/shared/execution-cwd.ts +14 -0
  319. package/src/shared/file-coalescer.ts +29 -0
  320. package/src/shared/fork-context.ts +68 -0
  321. package/src/shared/formatters.ts +84 -0
  322. package/src/shared/journal-reader.ts +333 -0
  323. package/src/shared/lazy-tools.ts +36 -0
  324. package/src/shared/model-info.ts +81 -0
  325. package/src/shared/native-session.ts +8 -0
  326. package/src/shared/native-tui.ts +10 -0
  327. package/src/shared/native-typebox.ts +14 -0
  328. package/src/shared/post-exit-stdio-guard.ts +204 -0
  329. package/src/shared/prompt-sections.ts +10 -0
  330. package/src/shared/session-entries.ts +49 -0
  331. package/src/shared/session-identity.ts +18 -0
  332. package/src/shared/settings.ts +384 -0
  333. package/src/shared/status-format.ts +123 -0
  334. package/src/shared/temp-root.ts +107 -0
  335. package/src/shared/types.ts +1260 -0
  336. package/src/shared/ui-mode.ts +5 -0
  337. package/src/shared/utils.ts +342 -0
  338. package/src/slash/prompt-template-bridge.ts +408 -0
  339. package/src/slash/slash-bridge.ts +178 -0
  340. package/src/slash/slash-commands.ts +617 -0
  341. package/src/slash/slash-live-state.ts +292 -0
  342. package/src/tui/action-hints.ts +69 -0
  343. package/src/tui/agent-history.ts +210 -0
  344. package/src/tui/agent-view.ts +1323 -0
  345. package/src/tui/render.ts +1550 -0
  346. package/tsconfig.build.json +12 -0
  347. package/tsconfig.json +19 -0
@@ -0,0 +1,813 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import {
5
+ type AgentConfig,
6
+ type AgentScope,
7
+ type AgentSource,
8
+ type ChainConfig,
9
+ type ChainStepConfig,
10
+ defaultInheritProjectContext,
11
+ defaultInheritSkills,
12
+ defaultSystemPromptMode,
13
+ discoverAgents,
14
+ discoverAgentsAll,
15
+ buildRuntimeName,
16
+ frontmatterNameForConfig,
17
+ parsePackageName,
18
+ } from "./agents.ts";
19
+ import { serializeAgent } from "./agent-serializer.ts";
20
+ import { serializeChain, serializeJsonChain } from "./chain-serializer.ts";
21
+ import { discoverAvailableSkills } from "./skills.ts";
22
+ import { isClaudeCodeModel } from "../runs/shared/claude-code.ts";
23
+ import type { SubagentExecutionResult } from "../shared/types.ts";
24
+ import { resolveEffectiveThinking } from "../shared/model-info.ts";
25
+
26
+ type ManagementAction = "list" | "get" | "create" | "update" | "delete";
27
+ type ManagementScope = "user" | "project";
28
+ type ManagementContext = Pick<ExtensionContext, "cwd" | "modelRegistry" | "isProjectTrusted">;
29
+
30
+ interface ManagementParams {
31
+ action?: string;
32
+ agent?: string;
33
+ chainName?: string;
34
+ agentScope?: string;
35
+ config?: unknown;
36
+ }
37
+
38
+ function result(text: string, isError = false): SubagentExecutionResult {
39
+ return { content: [{ type: "text", text }], isError, details: { mode: "management", results: [] } };
40
+ }
41
+
42
+ function parseCsv(value: string): string[] {
43
+ return [...new Set(value.split(",").map((v) => v.trim()).filter(Boolean))];
44
+ }
45
+
46
+ function configObject(config: unknown): { value?: Record<string, unknown>; error?: string } {
47
+ let val = config;
48
+ if (typeof val === "string") {
49
+ try {
50
+ val = JSON.parse(val);
51
+ } catch (error) {
52
+ const message = error instanceof Error ? error.message : String(error);
53
+ return { error: `config must be valid JSON: ${message}` };
54
+ }
55
+ }
56
+ if (!val || typeof val !== "object" || Array.isArray(val)) return {};
57
+ return { value: val as Record<string, unknown> };
58
+ }
59
+
60
+ function hasKey(obj: Record<string, unknown>, key: string): boolean {
61
+ return Object.prototype.hasOwnProperty.call(obj, key);
62
+ }
63
+
64
+ function asDisambiguationScope(scope: unknown): ManagementScope | undefined {
65
+ if (scope === "user" || scope === "project") return scope;
66
+ return undefined;
67
+ }
68
+
69
+ function normalizeListScope(scope: unknown): AgentScope | undefined {
70
+ if (scope === undefined) return "both";
71
+ if (scope === "user" || scope === "project" || scope === "both") return scope;
72
+ return undefined;
73
+ }
74
+
75
+ function sanitizeName(name: string): string {
76
+ return name.toLowerCase().trim().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
77
+ }
78
+
79
+ function parsePackageConfig(value: unknown): { packageName?: string; error?: string } {
80
+ return parsePackageName(value, "config.package");
81
+ }
82
+
83
+ function allAgents(d: { builtin: AgentConfig[]; package: AgentConfig[]; user: AgentConfig[]; project: AgentConfig[] }): AgentConfig[] {
84
+ return [...d.builtin, ...d.package, ...d.user, ...d.project];
85
+ }
86
+
87
+ function discoveryOptions(ctx: ManagementContext): { projectTrusted: boolean } {
88
+ return { projectTrusted: ctx.isProjectTrusted() };
89
+ }
90
+
91
+ function availableNames(ctx: ManagementContext, kind: "agent" | "chain", scope: AgentScope = "both"): string[] {
92
+ const d = discoverAgentsAll(ctx.cwd, discoveryOptions(ctx), scope);
93
+ const items = kind === "agent" ? allAgents(d) : d.chains;
94
+ return [...new Set(items.map((x) => x.name))].sort((a, b) => a.localeCompare(b));
95
+ }
96
+
97
+ function findAgents(name: string, ctx: ManagementContext, scope: AgentScope = "both"): AgentConfig[] {
98
+ const d = discoverAgentsAll(ctx.cwd, discoveryOptions(ctx), scope);
99
+ const raw = name.trim();
100
+ const sanitized = sanitizeName(raw);
101
+ return allAgents(d)
102
+ .filter((a) => (scope === "both" || a.source === scope) && (a.name === raw || a.name === sanitized))
103
+ .sort((a, b) => a.source.localeCompare(b.source));
104
+ }
105
+
106
+ function findChains(name: string, ctx: ManagementContext, scope: AgentScope = "both"): ChainConfig[] {
107
+ const raw = name.trim();
108
+ const sanitized = sanitizeName(raw);
109
+ return discoverAgentsAll(ctx.cwd, discoveryOptions(ctx), scope).chains
110
+ .filter((c) => (scope === "both" || c.source === scope) && (c.name === raw || c.name === sanitized))
111
+ .sort((a, b) => a.source.localeCompare(b.source));
112
+ }
113
+
114
+ function findEffectiveAgents(name: string, ctx: ManagementContext, scope: AgentScope = "both"): AgentConfig[] {
115
+ const raw = name.trim();
116
+ const sanitized = sanitizeName(raw);
117
+ return discoverAgents(ctx.cwd, scope, discoveryOptions(ctx)).agents
118
+ .filter((a) => a.name === raw || a.name === sanitized);
119
+ }
120
+
121
+ function nameExistsInScope(ctx: ManagementContext, scope: ManagementScope, name: string, excludePath?: string): boolean {
122
+ const d = discoverAgentsAll(ctx.cwd, discoveryOptions(ctx), scope);
123
+ for (const a of scope === "user" ? d.user : d.project) {
124
+ if (a.name === name && a.filePath !== excludePath) return true;
125
+ }
126
+ for (const c of d.chains) {
127
+ if (c.source === scope && c.name === name && c.filePath !== excludePath) return true;
128
+ }
129
+ return false;
130
+ }
131
+
132
+ function unknownChainAgents(ctx: ManagementContext, steps: ChainStepConfig[]): string[] {
133
+ const d = discoverAgentsAll(ctx.cwd, discoveryOptions(ctx));
134
+ const known = new Set(allAgents(d).map((a) => a.name));
135
+ return [...new Set(steps.map((s) => s.agent).filter((agent): agent is string => typeof agent === "string" && !known.has(agent)))].sort((a, b) => a.localeCompare(b));
136
+ }
137
+
138
+ function chainStepWarnings(ctx: ManagementContext, steps: ChainStepConfig[]): string[] {
139
+ const warnings: string[] = [];
140
+ const available = new Set(discoverAvailableSkills(ctx.cwd, discoveryOptions(ctx)).map((s) => s.name));
141
+ for (let i = 0; i < steps.length; i++) {
142
+ const s = steps[i]!;
143
+ if (s.model && !isClaudeCodeModel(s.model)) {
144
+ const found = ctx.modelRegistry.getAvailable().some((m) => `${m.provider}/${m.id}` === s.model || m.id === s.model);
145
+ if (!found) warnings.push(`Warning: step ${i + 1} (${s.agent}): model '${s.model}' is not in the current model registry.`);
146
+ }
147
+ if (Array.isArray(s.skills) && s.skills.length > 0) {
148
+ const missing = s.skills.filter((sk) => !available.has(sk));
149
+ if (missing.length) warnings.push(`Warning: step ${i + 1} (${s.agent}): skills not found: ${missing.join(", ")}.`);
150
+ }
151
+ }
152
+ return warnings;
153
+ }
154
+
155
+ function modelWarning(ctx: ManagementContext, model: string | undefined): string | undefined {
156
+ if (!model || isClaudeCodeModel(model)) return undefined;
157
+ const found = ctx.modelRegistry.getAvailable().some((m) => `${m.provider}/${m.id}` === model || m.id === model);
158
+ return found ? undefined : `Warning: model '${model}' is not in the current model registry.`;
159
+ }
160
+
161
+ function fallbackModelsWarning(ctx: ManagementContext, fallbackModels: string[] | undefined): string | undefined {
162
+ if (!fallbackModels || fallbackModels.length === 0) return undefined;
163
+ const available = new Set(ctx.modelRegistry.getAvailable().flatMap((m) => [`${m.provider}/${m.id}`, m.id]));
164
+ const missing = fallbackModels.filter((model) => !isClaudeCodeModel(model) && !available.has(model));
165
+ return missing.length ? `Warning: fallback models not in the current model registry: ${missing.join(", ")}.` : undefined;
166
+ }
167
+
168
+ function skillsWarning(ctx: ManagementContext, skills: string[] | undefined): string | undefined {
169
+ if (!skills || skills.length === 0) return undefined;
170
+ const available = new Set(discoverAvailableSkills(ctx.cwd, discoveryOptions(ctx)).map((s) => s.name));
171
+ const missing = skills.filter((s) => !available.has(s));
172
+ return missing.length ? `Warning: skills not found: ${missing.join(", ")}.` : undefined;
173
+ }
174
+
175
+ const SAVED_CHAIN_STEP_KEYS = new Set(["agent", "task", "phase", "label", "as", "outputSchema", "output", "outputMode", "reads", "model", "skills", "progress"]);
176
+
177
+ function parseStepList(raw: unknown): { steps?: ChainStepConfig[]; error?: string } {
178
+ if (!Array.isArray(raw)) return { error: "config.steps must be an array." };
179
+ if (raw.length === 0) return { error: "config.steps must include at least one step." };
180
+ const steps: ChainStepConfig[] = [];
181
+ for (let i = 0; i < raw.length; i++) {
182
+ const item = raw[i];
183
+ if (!item || typeof item !== "object" || Array.isArray(item)) return { error: `config.steps[${i}] must be an object.` };
184
+ const s = item as Record<string, unknown>;
185
+ if (hasKey(s, "skill")) return { error: `config.steps[${i}].skill is not supported; use skills.` };
186
+ const unknownKeys = Object.keys(s).filter((key) => !SAVED_CHAIN_STEP_KEYS.has(key));
187
+ if (unknownKeys.length) return { error: `config.steps[${i}] has unknown field${unknownKeys.length === 1 ? "" : "s"}: ${unknownKeys.join(", ")}.` };
188
+ if (typeof s.agent !== "string" || !s.agent.trim()) return { error: `config.steps[${i}].agent must be a non-empty string.` };
189
+ const step: ChainStepConfig = { agent: s.agent.trim(), task: typeof s.task === "string" ? s.task : "" };
190
+ if (hasKey(s, "phase")) {
191
+ if (typeof s.phase === "string") step.phase = s.phase;
192
+ else return { error: `config.steps[${i}].phase must be a string.` };
193
+ }
194
+ if (hasKey(s, "label")) {
195
+ if (typeof s.label === "string") step.label = s.label;
196
+ else return { error: `config.steps[${i}].label must be a string.` };
197
+ }
198
+ if (hasKey(s, "as")) {
199
+ if (typeof s.as === "string") step.as = s.as;
200
+ else return { error: `config.steps[${i}].as must be a string.` };
201
+ }
202
+ if (hasKey(s, "outputSchema")) {
203
+ if (typeof s.outputSchema === "string") step.outputSchema = s.outputSchema;
204
+ else return { error: `config.steps[${i}].outputSchema must be a schema file path string for saved chains.` };
205
+ }
206
+ if (hasKey(s, "output")) {
207
+ if (s.output === false) step.output = false;
208
+ else if (typeof s.output === "string") step.output = s.output;
209
+ else return { error: `config.steps[${i}].output must be a string or false.` };
210
+ }
211
+ if (hasKey(s, "outputMode")) {
212
+ if (s.outputMode === "inline" || s.outputMode === "file-only") step.outputMode = s.outputMode;
213
+ else return { error: `config.steps[${i}].outputMode must be 'inline' or 'file-only'.` };
214
+ }
215
+ if (hasKey(s, "reads")) {
216
+ if (s.reads === false) step.reads = false;
217
+ else if (Array.isArray(s.reads) && s.reads.every((value) => typeof value === "string")) step.reads = s.reads.map((value) => value.trim()).filter(Boolean);
218
+ else return { error: `config.steps[${i}].reads must be a string array or false.` };
219
+ }
220
+ if (hasKey(s, "model")) {
221
+ if (typeof s.model === "string") step.model = s.model;
222
+ else return { error: `config.steps[${i}].model must be a string.` };
223
+ }
224
+ if (hasKey(s, "skill")) {
225
+ return { error: `config.steps[${i}].skill is not supported for saved chains; use skills (array or false).` };
226
+ }
227
+ if (hasKey(s, "skills")) {
228
+ if (s.skills === false) step.skills = false;
229
+ else if (Array.isArray(s.skills) && s.skills.every((value) => typeof value === "string")) step.skills = s.skills.map((value) => value.trim()).filter(Boolean);
230
+ else return { error: `config.steps[${i}].skills must be a string array or false.` };
231
+ }
232
+ if (hasKey(s, "progress")) {
233
+ if (typeof s.progress === "boolean") step.progress = s.progress;
234
+ else return { error: `config.steps[${i}].progress must be a boolean.` };
235
+ }
236
+ steps.push(step);
237
+ }
238
+ return { steps };
239
+ }
240
+
241
+ function parseTools(raw: string): { tools?: string[]; mcpDirectTools?: string[] } {
242
+ const tools: string[] = [];
243
+ const mcpDirectTools: string[] = [];
244
+ for (const item of parseCsv(raw)) {
245
+ if (item.startsWith("mcp:")) {
246
+ const direct = item.slice(4).trim();
247
+ if (direct) mcpDirectTools.push(direct);
248
+ } else tools.push(item);
249
+ }
250
+ return { tools: tools.length ? tools : undefined, mcpDirectTools: mcpDirectTools.length ? mcpDirectTools : undefined };
251
+ }
252
+
253
+ const CHAIN_CONFIG_KEYS = new Set(["name", "package", "description", "scope", "steps"]);
254
+
255
+ function validateChainConfigKeys(cfg: Record<string, unknown>): string | undefined {
256
+ const unknownKeys = Object.keys(cfg).filter((key) => !CHAIN_CONFIG_KEYS.has(key));
257
+ return unknownKeys.length ? `config has unknown field${unknownKeys.length === 1 ? "" : "s"}: ${unknownKeys.join(", ")}.` : undefined;
258
+ }
259
+
260
+ const AGENT_CONFIG_KEYS = new Set([
261
+ "name", "package", "description", "scope", "systemPrompt", "model", "fallbackModels", "tools", "skills", "extensions", "thinking",
262
+ "systemPromptMode", "inheritProjectContext", "inheritSkills", "defaultContext", "output", "reads", "progress", "allowSubagents",
263
+ "maxSubagentDepth", "maxExecutionTimeMs", "maxTokens", "completionGuard",
264
+ ]);
265
+
266
+ function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): string | undefined {
267
+ const unknownKeys = Object.keys(cfg).filter((key) => !AGENT_CONFIG_KEYS.has(key));
268
+ if (unknownKeys.length) return `config has unknown field${unknownKeys.length === 1 ? "" : "s"}: ${unknownKeys.join(", ")}.`;
269
+ if (hasKey(cfg, "systemPrompt")) {
270
+ if (cfg.systemPrompt === false || cfg.systemPrompt === "") target.systemPrompt = "";
271
+ else if (typeof cfg.systemPrompt === "string") target.systemPrompt = cfg.systemPrompt;
272
+ else return "config.systemPrompt must be a string or false when provided.";
273
+ }
274
+ if (hasKey(cfg, "model")) {
275
+ if (cfg.model === false || cfg.model === "") target.model = undefined;
276
+ else if (typeof cfg.model === "string") target.model = cfg.model.trim() || undefined;
277
+ else return "config.model must be a string or false when provided.";
278
+ }
279
+ if (hasKey(cfg, "fallbackModels")) {
280
+ if (cfg.fallbackModels === false || cfg.fallbackModels === "") target.fallbackModels = undefined;
281
+ else if (typeof cfg.fallbackModels === "string") {
282
+ const models = parseCsv(cfg.fallbackModels);
283
+ target.fallbackModels = models.length ? models : undefined;
284
+ } else if (Array.isArray(cfg.fallbackModels)) {
285
+ const models = cfg.fallbackModels
286
+ .filter((value): value is string => typeof value === "string")
287
+ .map((value) => value.trim())
288
+ .filter(Boolean);
289
+ target.fallbackModels = models.length ? [...new Set(models)] : undefined;
290
+ } else return "config.fallbackModels must be a comma-separated string, string array, or false when provided.";
291
+ }
292
+ if (hasKey(cfg, "tools")) {
293
+ if (cfg.tools === false || cfg.tools === "") { target.tools = undefined; target.mcpDirectTools = undefined; }
294
+ else if (typeof cfg.tools === "string") { const parsed = parseTools(cfg.tools); target.tools = parsed.tools; target.mcpDirectTools = parsed.mcpDirectTools; }
295
+ else return "config.tools must be a comma-separated string or false when provided.";
296
+ }
297
+ if (hasKey(cfg, "skills")) {
298
+ if (cfg.skills === false || cfg.skills === "") target.skills = undefined;
299
+ else if (typeof cfg.skills === "string") { const skills = parseCsv(cfg.skills); target.skills = skills.length ? skills : undefined; }
300
+ else return "config.skills must be a comma-separated string or false when provided.";
301
+ }
302
+ if (hasKey(cfg, "extensions")) {
303
+ if (cfg.extensions === false) target.extensions = undefined;
304
+ else if (cfg.extensions === "") target.extensions = [];
305
+ else if (typeof cfg.extensions === "string") target.extensions = parseCsv(cfg.extensions);
306
+ else return "config.extensions must be a comma-separated string, empty string, or false when provided.";
307
+ }
308
+ if (hasKey(cfg, "thinking")) {
309
+ if (cfg.thinking === false || cfg.thinking === "") target.thinking = undefined;
310
+ else if (typeof cfg.thinking === "string") target.thinking = cfg.thinking.trim() || undefined;
311
+ else return "config.thinking must be a string or false when provided.";
312
+ }
313
+ if (hasKey(cfg, "systemPromptMode")) {
314
+ if (cfg.systemPromptMode === "append" || cfg.systemPromptMode === "replace") target.systemPromptMode = cfg.systemPromptMode;
315
+ else return "config.systemPromptMode must be 'append' or 'replace' when provided.";
316
+ }
317
+ if (hasKey(cfg, "inheritProjectContext")) {
318
+ if (typeof cfg.inheritProjectContext !== "boolean") return "config.inheritProjectContext must be a boolean when provided.";
319
+ target.inheritProjectContext = cfg.inheritProjectContext;
320
+ }
321
+ if (hasKey(cfg, "inheritSkills")) {
322
+ if (typeof cfg.inheritSkills !== "boolean") return "config.inheritSkills must be a boolean when provided.";
323
+ target.inheritSkills = cfg.inheritSkills;
324
+ }
325
+ if (hasKey(cfg, "defaultContext")) {
326
+ if (cfg.defaultContext === false || cfg.defaultContext === "") target.defaultContext = undefined;
327
+ else if (cfg.defaultContext === "fresh" || cfg.defaultContext === "fork") target.defaultContext = cfg.defaultContext;
328
+ else return "config.defaultContext must be 'fresh', 'fork', or false when provided.";
329
+ }
330
+ if (hasKey(cfg, "output")) {
331
+ if (cfg.output === false || cfg.output === "") target.output = undefined;
332
+ else if (typeof cfg.output === "string") target.output = cfg.output;
333
+ else return "config.output must be a string or false when provided.";
334
+ }
335
+ if (hasKey(cfg, "reads")) {
336
+ if (cfg.reads === false || cfg.reads === "") target.defaultReads = undefined;
337
+ else if (typeof cfg.reads === "string") {
338
+ const reads = parseCsv(cfg.reads);
339
+ target.defaultReads = reads.length ? reads : undefined;
340
+ } else return "config.reads must be a comma-separated string or false when provided.";
341
+ }
342
+ if (hasKey(cfg, "progress")) {
343
+ if (typeof cfg.progress !== "boolean") return "config.progress must be a boolean when provided.";
344
+ target.defaultProgress = cfg.progress;
345
+ }
346
+ if (hasKey(cfg, "allowSubagents")) {
347
+ if (typeof cfg.allowSubagents !== "boolean") return "config.allowSubagents must be a boolean when provided.";
348
+ target.allowSubagents = cfg.allowSubagents;
349
+ }
350
+ if (hasKey(cfg, "maxSubagentDepth")) {
351
+ if (cfg.maxSubagentDepth === false || cfg.maxSubagentDepth === "") target.maxSubagentDepth = undefined;
352
+ else if (typeof cfg.maxSubagentDepth === "number" && Number.isInteger(cfg.maxSubagentDepth) && cfg.maxSubagentDepth >= 0) {
353
+ target.maxSubagentDepth = cfg.maxSubagentDepth;
354
+ } else return "config.maxSubagentDepth must be an integer >= 0 or false when provided.";
355
+ }
356
+ if (hasKey(cfg, "maxExecutionTimeMs")) {
357
+ if (cfg.maxExecutionTimeMs === false || cfg.maxExecutionTimeMs === "") target.maxExecutionTimeMs = undefined;
358
+ else if (typeof cfg.maxExecutionTimeMs === "number" && Number.isInteger(cfg.maxExecutionTimeMs) && cfg.maxExecutionTimeMs >= 1) {
359
+ target.maxExecutionTimeMs = cfg.maxExecutionTimeMs;
360
+ } else return "config.maxExecutionTimeMs must be an integer >= 1 or false when provided.";
361
+ }
362
+ if (hasKey(cfg, "maxTokens")) {
363
+ if (cfg.maxTokens === false || cfg.maxTokens === "") target.maxTokens = undefined;
364
+ else if (typeof cfg.maxTokens === "number" && Number.isInteger(cfg.maxTokens) && cfg.maxTokens >= 1) {
365
+ target.maxTokens = cfg.maxTokens;
366
+ } else return "config.maxTokens must be an integer >= 1 or false when provided.";
367
+ }
368
+ if (hasKey(cfg, "completionGuard")) {
369
+ if (typeof cfg.completionGuard !== "boolean") return "config.completionGuard must be a boolean when provided.";
370
+ target.completionGuard = cfg.completionGuard;
371
+ }
372
+ return undefined;
373
+ }
374
+
375
+ type MutableTarget<T extends { source: AgentSource }> = T & { source: ManagementScope };
376
+
377
+ function isMutableTarget<T extends { source: AgentSource }>(target: T): target is MutableTarget<T> {
378
+ return target.source === "user" || target.source === "project";
379
+ }
380
+
381
+ function resolveTarget<T extends { source: AgentSource; filePath: string }>(
382
+ kind: "agent" | "chain",
383
+ name: string,
384
+ matches: T[],
385
+ ctx: ManagementContext,
386
+ scopeHint?: string,
387
+ ): MutableTarget<T> | SubagentExecutionResult {
388
+ const mutable = matches.filter(isMutableTarget);
389
+ if (mutable.length === 0) {
390
+ if (matches.length > 0) {
391
+ return result(`${kind === "agent" ? "Agent" : "Chain"} '${name}' is ${matches[0]!.source} and cannot be modified. Create a same-named ${kind} in user or project scope to override it.`, true);
392
+ }
393
+ const available = availableNames(ctx, kind);
394
+ return result(`${kind === "agent" ? "Agent" : "Chain"} '${name}' not found. Available: ${available.join(", ") || "none"}.`, true);
395
+ }
396
+ if (mutable.length === 1) return mutable[0]!;
397
+ const scope = asDisambiguationScope(scopeHint);
398
+ if (!scope) {
399
+ const paths = mutable.map((m) => `${m.source}: ${m.filePath}`).join("\n");
400
+ const sources = new Set(mutable.map((entry) => entry.source));
401
+ return sources.size === 1
402
+ ? result(`${kind === "agent" ? "Agent" : "Chain"} '${name}' has multiple definitions in ${mutable[0]!.source} scope and cannot be modified safely. Remove or rename one definition first.\n${paths}`, true)
403
+ : result(`${kind === "agent" ? "Agent" : "Chain"} '${name}' exists in both scopes. Specify agentScope: 'user' or 'project'.\n${paths}`, true);
404
+ }
405
+ const scoped = mutable.filter((m) => m.source === scope);
406
+ if (scoped.length === 0) return result(`${kind === "agent" ? "Agent" : "Chain"} '${name}' not found in scope '${scope}'.`, true);
407
+ if (scoped.length > 1) {
408
+ return result(`${kind === "agent" ? "Agent" : "Chain"} '${name}' has multiple definitions in scope '${scope}' and cannot be modified safely. Remove or rename one definition first:\n${scoped.map((entry) => entry.filePath).join("\n")}`, true);
409
+ }
410
+ return scoped[0]!;
411
+ }
412
+
413
+ function renamePath(
414
+ kind: "agent" | "chain",
415
+ currentPath: string,
416
+ newName: string,
417
+ scope: ManagementScope,
418
+ ctx: ManagementContext,
419
+ ): { filePath?: string; error?: string } {
420
+ if (nameExistsInScope(ctx, scope, newName, currentPath)) return { error: `Name '${newName}' already exists in ${scope} scope.` };
421
+ const ext = kind === "agent" ? ".md" : currentPath.endsWith(".chain.json") ? ".chain.json" : ".chain.md";
422
+ const filePath = path.join(path.dirname(currentPath), `${newName}${ext}`);
423
+ if (fs.existsSync(filePath) && filePath !== currentPath) {
424
+ return { error: `File already exists at ${filePath} but is not a valid ${kind} definition. Remove or rename it first.` };
425
+ }
426
+ fs.renameSync(currentPath, filePath);
427
+ return { filePath };
428
+ }
429
+
430
+ function formatModelDefaults(agent: AgentConfig): string[] {
431
+ const thinking = resolveEffectiveThinking(agent.model, agent.thinking) ?? agent.thinking;
432
+ const inherited = "inherited runtime default (unset)";
433
+ const fallbacks = agent.fallbackModels?.map((model) =>
434
+ `${model} (thinking: ${resolveEffectiveThinking(model, agent.thinking ?? thinking) ?? inherited})`);
435
+ return [
436
+ `Model: ${agent.model ?? "inherited from parent (resolved at launch)"}`,
437
+ `Thinking: ${thinking ?? inherited}`,
438
+ `Fallback models: ${fallbacks?.length ? fallbacks.join(", ") : "none configured"}`,
439
+ ];
440
+ }
441
+
442
+ function formatAgentDetail(agent: AgentConfig): string {
443
+ const tools = [...(agent.tools ?? []), ...(agent.mcpDirectTools ?? []).map((t) => `mcp:${t}`)];
444
+ const lines: string[] = [`Agent: ${agent.name} (${agent.source})`, `Path: ${agent.filePath}`, `Description: ${agent.description}`];
445
+ if (agent.packageName) {
446
+ lines.push(`Local name: ${frontmatterNameForConfig(agent)}`);
447
+ lines.push(`Package: ${agent.packageName}`);
448
+ }
449
+ lines.push(...formatModelDefaults(agent));
450
+ if (tools.length) lines.push(`Tools: ${tools.join(", ")}`);
451
+ if (agent.skills?.length) lines.push(`Skills: ${agent.skills.join(", ")}`);
452
+ lines.push(`System prompt mode: ${agent.systemPromptMode}`);
453
+ lines.push(`Inherit project context: ${agent.inheritProjectContext ? "true" : "false"}`);
454
+ lines.push(`Inherit skills: ${agent.inheritSkills ? "true" : "false"}`);
455
+ if (agent.defaultContext) lines.push(`Default context: ${agent.defaultContext}`);
456
+ if (agent.source === "builtin") lines.push(`Disabled: ${agent.disabled ? "true" : "false"}`);
457
+ if (agent.extensions !== undefined) lines.push(`Extensions: ${agent.extensions.length ? agent.extensions.join(", ") : "(none)"}`);
458
+ if (agent.output) lines.push(`Output: ${agent.output}`);
459
+ if (agent.defaultReads?.length) lines.push(`Reads: ${agent.defaultReads.join(", ")}`);
460
+ if (agent.defaultProgress) lines.push("Progress: true");
461
+ if (agent.allowSubagents) lines.push("Allow subagents: true");
462
+ if (agent.maxSubagentDepth !== undefined) lines.push(`Max subagent depth: ${agent.maxSubagentDepth}`);
463
+ if (agent.maxExecutionTimeMs !== undefined) lines.push(`Max execution time: ${agent.maxExecutionTimeMs}ms`);
464
+ if (agent.maxTokens !== undefined) lines.push(`Max tokens: ${agent.maxTokens}`);
465
+ if (agent.completionGuard !== undefined) lines.push(`Completion guard: ${agent.completionGuard}`);
466
+ if (agent.systemPrompt.trim()) lines.push("", "System Prompt:", agent.systemPrompt);
467
+ return lines.join("\n");
468
+ }
469
+
470
+ function formatChainStepDetail(step: ChainStepConfig, index: number): string[] {
471
+ const lines: string[] = [];
472
+ if (step.expand || step.collect) {
473
+ const parallel = step.parallel && !Array.isArray(step.parallel) && typeof step.parallel === "object" ? step.parallel as { agent?: unknown; task?: unknown; label?: unknown; outputSchema?: unknown } : undefined;
474
+ const expand = step.expand && typeof step.expand === "object" ? step.expand as { from?: { output?: unknown; path?: unknown }; item?: unknown; key?: unknown; maxItems?: unknown; onEmpty?: unknown } : undefined;
475
+ const collect = step.collect && typeof step.collect === "object" ? step.collect as { as?: unknown; outputSchema?: unknown } : undefined;
476
+ lines.push(`${index + 1}. Dynamic fanout${typeof collect?.as === "string" ? ` -> ${collect.as}` : ""}`);
477
+ if (expand?.from) lines.push(` Expand: ${String(expand.from.output ?? "?")}${String(expand.from.path ?? "")}`);
478
+ if (typeof expand?.item === "string") lines.push(` Item variable: ${expand.item}`);
479
+ if (typeof expand?.key === "string") lines.push(` Key: ${expand.key}`);
480
+ if (typeof expand?.maxItems === "number") lines.push(` Max items: ${expand.maxItems}`);
481
+ if (typeof expand?.onEmpty === "string") lines.push(` On empty: ${expand.onEmpty}`);
482
+ if (parallel?.agent) lines.push(` Agent: ${String(parallel.agent)}`);
483
+ if (typeof parallel?.label === "string") lines.push(` Label: ${parallel.label}`);
484
+ if (typeof parallel?.task === "string" && parallel.task.trim()) lines.push(` Task: ${parallel.task}`);
485
+ if (parallel?.outputSchema) lines.push(" Structured output: true");
486
+ if (collect?.outputSchema) lines.push(" Collect schema: true");
487
+ if (step.concurrency !== undefined) lines.push(` Concurrency: ${step.concurrency}`);
488
+ if (step.failFast !== undefined) lines.push(` Fail fast: ${step.failFast ? "true" : "false"}`);
489
+ return lines;
490
+ }
491
+ lines.push(`${index + 1}. ${step.agent}`);
492
+ if (step.task?.trim()) lines.push(` Task: ${step.task}`);
493
+ if (step.output === false) lines.push(" Output: false");
494
+ else if (step.output) lines.push(` Output: ${step.output}`);
495
+ if (step.outputMode) lines.push(` Output mode: ${step.outputMode}`);
496
+ if (step.reads === false) lines.push(" Reads: false");
497
+ else if (Array.isArray(step.reads) && step.reads.length > 0) lines.push(` Reads: ${step.reads.join(", ")}`);
498
+ if (step.model) lines.push(` Model: ${step.model}`);
499
+ if (step.skills === false) lines.push(" Skills: false");
500
+ else if (Array.isArray(step.skills) && step.skills.length > 0) lines.push(` Skills: ${step.skills.join(", ")}`);
501
+ if (step.progress !== undefined) lines.push(` Progress: ${step.progress ? "true" : "false"}`);
502
+ return lines;
503
+ }
504
+
505
+ function formatChainDetail(chain: ChainConfig): string {
506
+ const lines: string[] = [`Chain: ${chain.name} (${chain.source})`, `Path: ${chain.filePath}`, `Description: ${chain.description}`];
507
+ if (chain.packageName) {
508
+ lines.push(`Local name: ${frontmatterNameForConfig(chain)}`);
509
+ lines.push(`Package: ${chain.packageName}`);
510
+ }
511
+ lines.push("", "Steps:");
512
+ for (let i = 0; i < chain.steps.length; i++) {
513
+ lines.push(...formatChainStepDetail(chain.steps[i]!, i));
514
+ }
515
+ return lines.join("\n");
516
+ }
517
+
518
+ type AgentListRole = "Recon" | "Planning" | "Implementation" | "Review" | "Coordination" | "Specialized" | "Custom/other";
519
+
520
+ const AGENT_ROLE_HINTS: Record<AgentListRole, string> = {
521
+ Recon: "Use for read-only codebase mapping, grep/delta sweeps, and external facts.",
522
+ Planning: "Use when decomposition or an implementation handoff matters.",
523
+ Implementation: "Use for bounded code/doc changes after scope is clear.",
524
+ Review: "Use for independent validation, regressions, and drift checks.",
525
+ Coordination: "Use for generic delegation or high-context decision checks.",
526
+ Specialized: "Use only when the task matches the skill description.",
527
+ "Custom/other": "Project/user agents not classified by the builtins.",
528
+ };
529
+
530
+ function agentListRole(agent: AgentConfig): AgentListRole {
531
+ const name = agent.name.split(".").at(-1) ?? agent.name;
532
+ if (["scout", "context-builder", "researcher"].includes(name)) return "Recon";
533
+ if (name === "planner") return "Planning";
534
+ if (["worker", "fixer"].includes(name)) return "Implementation";
535
+ if (name === "reviewer" || name.includes("review")) return "Review";
536
+ if (["delegate", "oracle"].includes(name)) return "Coordination";
537
+ if (agent.source === "builtin") return "Specialized";
538
+ return "Custom/other";
539
+ }
540
+
541
+ function formatAgentListLine(a: AgentConfig): string {
542
+ return `- ${a.name} (${a.source}${a.defaultContext ? `, context: ${a.defaultContext}` : ""}): ${a.description}\n ${formatModelDefaults(a).join("; ")}`;
543
+ }
544
+
545
+ export function handleList(params: ManagementParams, ctx: ManagementContext): SubagentExecutionResult {
546
+ const scope = normalizeListScope(params.agentScope);
547
+ if (!scope) return result("agentScope must be 'user', 'project', or 'both'.", true);
548
+ const d = discoverAgentsAll(ctx.cwd, discoveryOptions(ctx), scope);
549
+ const agents = discoverAgents(ctx.cwd, scope, discoveryOptions(ctx)).agents
550
+ .sort((a, b) => a.name.localeCompare(b.name));
551
+ const chains = d.chains.filter((c) => scope === "both" || c.source === scope).sort((a, b) => a.name.localeCompare(b.name));
552
+ const diagnostics = [...d.agentDiagnostics, ...d.chainDiagnostics];
553
+ const roleOrder: AgentListRole[] = ["Recon", "Planning", "Implementation", "Review", "Coordination", "Specialized", "Custom/other"];
554
+ const lines: string[] = ["Executable agents (grouped by role):"];
555
+ if (!agents.length) {
556
+ lines.push("- (none)");
557
+ } else {
558
+ for (const role of roleOrder) {
559
+ const group = agents.filter((agent) => agentListRole(agent) === role);
560
+ if (!group.length) continue;
561
+ lines.push(``, `**${role}** — ${AGENT_ROLE_HINTS[role]}`, ...group.map(formatAgentListLine));
562
+ }
563
+ }
564
+ lines.push(
565
+ "",
566
+ "Chains:",
567
+ ...(chains.length ? chains.map((c) => `- ${c.name} (${c.source}): ${c.description}`) : ["- (none)"]),
568
+ ...(diagnostics.length ? ["", "Discovery diagnostics:", ...diagnostics.map((entry) => `- ${entry.filePath}: ${entry.error}`)] : []),
569
+ );
570
+ return result(lines.join("\n"));
571
+ }
572
+
573
+ function handleGet(params: ManagementParams, ctx: ManagementContext): SubagentExecutionResult {
574
+ if (!params.agent && !params.chainName) return result("Specify 'agent' or 'chainName' for get.", true);
575
+ const hasBoth = Boolean(params.agent && params.chainName);
576
+ const blocks: string[] = [];
577
+ let anyFound = false;
578
+ const scope = normalizeListScope(params.agentScope);
579
+ if (!scope) return result("agentScope must be 'user', 'project', or 'both'.", true);
580
+ if (params.agent) {
581
+ const matches = findEffectiveAgents(params.agent, ctx, scope);
582
+ if (!matches.length) {
583
+ const msg = `Agent '${params.agent}' not found. Available: ${availableNames(ctx, "agent", scope).join(", ") || "none"}.`;
584
+ if (!hasBoth) return result(msg, true);
585
+ blocks.push(msg);
586
+ } else {
587
+ anyFound = true;
588
+ blocks.push(...matches.map(formatAgentDetail));
589
+ }
590
+ }
591
+ if (params.chainName) {
592
+ const matches = findChains(params.chainName, ctx, scope);
593
+ if (!matches.length) {
594
+ const msg = `Chain '${params.chainName}' not found. Available: ${availableNames(ctx, "chain", scope).join(", ") || "none"}.`;
595
+ if (!hasBoth) return result(msg, true);
596
+ blocks.push(msg);
597
+ } else {
598
+ anyFound = true;
599
+ blocks.push(...matches.map(formatChainDetail));
600
+ }
601
+ }
602
+ return result(blocks.join("\n\n"), !anyFound);
603
+ }
604
+
605
+ export function handleCreate(params: ManagementParams, ctx: ManagementContext): SubagentExecutionResult {
606
+ const parsedConfig = configObject(params.config);
607
+ if (parsedConfig.error) return result(parsedConfig.error, true);
608
+ const cfg = parsedConfig.value;
609
+ if (!cfg) return result("config required for create.", true);
610
+ if (typeof cfg.name !== "string" || !cfg.name.trim()) return result("config.name is required and must be a non-empty string.", true);
611
+ if (typeof cfg.description !== "string" || !cfg.description.trim()) return result("config.description is required and must be a non-empty string.", true);
612
+ const name = sanitizeName(cfg.name);
613
+ if (!name) return result("config.name is invalid after sanitization. Use letters, numbers, spaces, or hyphens.", true);
614
+ const parsedPackage = parsePackageConfig(cfg.package);
615
+ if (parsedPackage.error) return result(parsedPackage.error, true);
616
+ const runtimeName = buildRuntimeName(name, parsedPackage.packageName);
617
+ const scopeRaw = cfg.scope ?? "user";
618
+ if (scopeRaw !== "user" && scopeRaw !== "project") return result("config.scope must be 'user' or 'project'.", true);
619
+ const scope = scopeRaw as ManagementScope;
620
+ const isChain = hasKey(cfg, "steps");
621
+ const options = discoveryOptions(ctx);
622
+ if (scope === "project" && options.projectTrusted === false) return result("Project scope is not available because this project is untrusted. Run from a trusted project or use scope: 'user'.", true);
623
+ const d = discoverAgentsAll(ctx.cwd, options);
624
+ const targetDir = isChain
625
+ ? scope === "user" ? d.userChainDir : d.projectChainDir ?? path.join(ctx.cwd, ".pi", "chains")
626
+ : scope === "user" ? d.userDir : d.projectDir ?? path.join(ctx.cwd, ".pi", "agents");
627
+ fs.mkdirSync(targetDir, { recursive: true });
628
+ if (nameExistsInScope(ctx, scope, runtimeName)) return result(`Name '${runtimeName}' already exists in ${scope} scope. Use update instead.`, true);
629
+ const targetPath = path.join(targetDir, isChain ? `${runtimeName}.chain.md` : `${runtimeName}.md`);
630
+ if (fs.existsSync(targetPath)) return result(`File already exists at ${targetPath} but is not a valid ${isChain ? "chain" : "agent"} definition. Remove or rename it first.`, true);
631
+ const warnings: string[] = [];
632
+ if (!isChain && d.builtin.some((a) => a.name === runtimeName)) warnings.push(`Note: this shadows the builtin agent '${runtimeName}'.`);
633
+ if (isChain) {
634
+ const keyError = validateChainConfigKeys(cfg);
635
+ if (keyError) return result(keyError, true);
636
+ const parsed = parseStepList(cfg.steps);
637
+ if (parsed.error) return result(parsed.error, true);
638
+ const chain: ChainConfig = { name: runtimeName, localName: name, packageName: parsedPackage.packageName, description: cfg.description.trim(), source: scope, filePath: targetPath, steps: parsed.steps! };
639
+ fs.writeFileSync(targetPath, serializeChain(chain), "utf-8");
640
+ const missing = unknownChainAgents(ctx, chain.steps);
641
+ if (missing.length) warnings.push(`Warning: chain steps reference unknown agents: ${missing.join(", ")}.`);
642
+ warnings.push(...chainStepWarnings(ctx, chain.steps));
643
+ return result([`Created chain '${runtimeName}' at ${targetPath}.`, ...warnings].join("\n"));
644
+ }
645
+ const agent: AgentConfig = {
646
+ name: runtimeName,
647
+ localName: name,
648
+ packageName: parsedPackage.packageName,
649
+ description: cfg.description.trim(),
650
+ source: scope,
651
+ filePath: targetPath,
652
+ systemPrompt: "",
653
+ systemPromptMode: defaultSystemPromptMode(name),
654
+ inheritProjectContext: defaultInheritProjectContext(name),
655
+ inheritSkills: defaultInheritSkills(),
656
+ maxSubagentDepth: 0,
657
+ };
658
+ const applyError = applyAgentConfig(agent, cfg);
659
+ if (applyError) return result(applyError, true);
660
+ const mw = modelWarning(ctx, agent.model);
661
+ if (mw) warnings.push(mw);
662
+ const fmw = fallbackModelsWarning(ctx, agent.fallbackModels);
663
+ if (fmw) warnings.push(fmw);
664
+ const sw = skillsWarning(ctx, agent.skills);
665
+ if (sw) warnings.push(sw);
666
+ fs.writeFileSync(targetPath, serializeAgent(agent), "utf-8");
667
+ return result([`Created agent '${runtimeName}' at ${targetPath}.`, ...warnings].join("\n"));
668
+ }
669
+
670
+ export function handleUpdate(params: ManagementParams, ctx: ManagementContext): SubagentExecutionResult {
671
+ if (!params.agent && !params.chainName) return result("Specify 'agent' or 'chainName' for update.", true);
672
+ if (params.agent && params.chainName) return result("Specify either 'agent' or 'chainName', not both.", true);
673
+ const parsedConfig = configObject(params.config);
674
+ if (parsedConfig.error) return result(parsedConfig.error, true);
675
+ const cfg = parsedConfig.value;
676
+ if (!cfg) return result("config required for update.", true);
677
+ const warnings: string[] = [];
678
+ if (params.agent) {
679
+ const scopeHint = asDisambiguationScope(params.agentScope);
680
+ const targetOrError = resolveTarget("agent", params.agent, findAgents(params.agent, ctx, scopeHint ?? "both"), ctx, params.agentScope);
681
+ if ("content" in targetOrError) return targetOrError;
682
+ const target = targetOrError;
683
+ const updated: AgentConfig = { ...target };
684
+ const oldName = target.name;
685
+ if (hasKey(cfg, "name") && (typeof cfg.name !== "string" || !cfg.name.trim())) return result("config.name must be a non-empty string when provided.", true);
686
+ if (hasKey(cfg, "description") && (typeof cfg.description !== "string" || !cfg.description.trim())) return result("config.description must be a non-empty string when provided.", true);
687
+ let newLocalName = target.localName ?? frontmatterNameForConfig(target);
688
+ if (hasKey(cfg, "name")) {
689
+ newLocalName = sanitizeName(cfg.name as string);
690
+ if (!newLocalName) return result("config.name is invalid after sanitization.", true);
691
+ }
692
+ let newPackageName = target.packageName;
693
+ if (hasKey(cfg, "package")) {
694
+ const parsedPackage = parsePackageConfig(cfg.package);
695
+ if (parsedPackage.error) return result(parsedPackage.error, true);
696
+ newPackageName = parsedPackage.packageName;
697
+ }
698
+ const applyError = applyAgentConfig(updated, cfg);
699
+ if (applyError) return result(applyError, true);
700
+ updated.localName = newLocalName;
701
+ updated.packageName = newPackageName;
702
+ updated.name = buildRuntimeName(newLocalName, newPackageName);
703
+ if (hasKey(cfg, "description")) updated.description = (cfg.description as string).trim();
704
+ if (hasKey(cfg, "model")) {
705
+ const mw = modelWarning(ctx, updated.model);
706
+ if (mw) warnings.push(mw);
707
+ }
708
+ if (hasKey(cfg, "fallbackModels")) {
709
+ const fmw = fallbackModelsWarning(ctx, updated.fallbackModels);
710
+ if (fmw) warnings.push(fmw);
711
+ }
712
+ if (hasKey(cfg, "skills")) {
713
+ const sw = skillsWarning(ctx, updated.skills);
714
+ if (sw) warnings.push(sw);
715
+ }
716
+ if (updated.name !== oldName) {
717
+ const renamed = renamePath("agent", target.filePath, updated.name, target.source, ctx);
718
+ if (renamed.error) return result(renamed.error, true);
719
+ updated.filePath = renamed.filePath!;
720
+ }
721
+ fs.writeFileSync(updated.filePath, serializeAgent(updated), "utf-8");
722
+ if (updated.name !== oldName) {
723
+ const refs = discoverAgentsAll(ctx.cwd, discoveryOptions(ctx)).chains.filter((c) => c.steps.some((s) => s.agent === oldName)).map((c) => `${c.name} (${c.source})`);
724
+ if (refs.length) warnings.push(`Warning: chains still reference '${oldName}': ${refs.join(", ")}.`);
725
+ }
726
+ const headline = updated.name === oldName
727
+ ? `Updated agent '${updated.name}' at ${updated.filePath}.`
728
+ : `Updated agent '${oldName}' to '${updated.name}' at ${updated.filePath}.`;
729
+ return result([headline, ...warnings].join("\n"));
730
+ }
731
+ const scopeHint = asDisambiguationScope(params.agentScope);
732
+ const targetOrError = resolveTarget("chain", params.chainName!, findChains(params.chainName!, ctx, scopeHint ?? "both"), ctx, params.agentScope);
733
+ if ("content" in targetOrError) return targetOrError;
734
+ const target = targetOrError;
735
+ const keyError = validateChainConfigKeys(cfg);
736
+ if (keyError) return result(keyError, true);
737
+ const updated: ChainConfig = { ...target, steps: [...target.steps] };
738
+ const oldName = target.name;
739
+ if (hasKey(cfg, "name") && (typeof cfg.name !== "string" || !cfg.name.trim())) return result("config.name must be a non-empty string when provided.", true);
740
+ if (hasKey(cfg, "description") && (typeof cfg.description !== "string" || !cfg.description.trim())) return result("config.description must be a non-empty string when provided.", true);
741
+ let newLocalName = target.localName ?? frontmatterNameForConfig(target);
742
+ if (hasKey(cfg, "name")) {
743
+ newLocalName = sanitizeName(cfg.name as string);
744
+ if (!newLocalName) return result("config.name is invalid after sanitization.", true);
745
+ }
746
+ let newPackageName = target.packageName;
747
+ if (hasKey(cfg, "package")) {
748
+ const parsedPackage = parsePackageConfig(cfg.package);
749
+ if (parsedPackage.error) return result(parsedPackage.error, true);
750
+ newPackageName = parsedPackage.packageName;
751
+ }
752
+ let parsedSteps: ChainStepConfig[] | undefined;
753
+ if (hasKey(cfg, "steps")) {
754
+ const parsed = parseStepList(cfg.steps);
755
+ if (parsed.error) return result(parsed.error, true);
756
+ parsedSteps = parsed.steps!;
757
+ }
758
+ updated.localName = newLocalName;
759
+ updated.packageName = newPackageName;
760
+ updated.name = buildRuntimeName(newLocalName, newPackageName);
761
+ if (hasKey(cfg, "description")) updated.description = (cfg.description as string).trim();
762
+ if (parsedSteps) {
763
+ updated.steps = parsedSteps;
764
+ const missing = unknownChainAgents(ctx, updated.steps);
765
+ if (missing.length) warnings.push(`Warning: chain steps reference unknown agents: ${missing.join(", ")}.`);
766
+ warnings.push(...chainStepWarnings(ctx, updated.steps));
767
+ }
768
+ if (updated.name !== oldName) {
769
+ const renamed = renamePath("chain", target.filePath, updated.name, target.source, ctx);
770
+ if (renamed.error) return result(renamed.error, true);
771
+ updated.filePath = renamed.filePath!;
772
+ }
773
+ fs.writeFileSync(updated.filePath, updated.filePath.endsWith(".chain.json") ? serializeJsonChain(updated) : serializeChain(updated), "utf-8");
774
+ const headline = updated.name === oldName
775
+ ? `Updated chain '${updated.name}' at ${updated.filePath}.`
776
+ : `Updated chain '${oldName}' to '${updated.name}' at ${updated.filePath}.`;
777
+ return result([headline, ...warnings].join("\n"));
778
+ }
779
+
780
+ function handleDelete(params: ManagementParams, ctx: ManagementContext): SubagentExecutionResult {
781
+ if (!params.agent && !params.chainName) return result("Specify 'agent' or 'chainName' for delete.", true);
782
+ if (params.agent && params.chainName) return result("Specify either 'agent' or 'chainName', not both.", true);
783
+ const scopeHint = asDisambiguationScope(params.agentScope);
784
+ if (params.agent) {
785
+ const targetOrError = resolveTarget("agent", params.agent, findAgents(params.agent, ctx, scopeHint ?? "both"), ctx, params.agentScope);
786
+ if ("content" in targetOrError) return targetOrError;
787
+ const target = targetOrError;
788
+ fs.unlinkSync(target.filePath);
789
+ const refs = discoverAgentsAll(ctx.cwd, discoveryOptions(ctx)).chains.filter((c) => c.steps.some((s) => s.agent === target.name)).map((c) => `${c.name} (${c.source})`);
790
+ const lines = [`Deleted agent '${target.name}' at ${target.filePath}.`];
791
+ if (refs.length) lines.push(`Warning: chains reference deleted agent '${target.name}': ${refs.join(", ")}.`);
792
+ return result(lines.join("\n"));
793
+ }
794
+ const targetOrError = resolveTarget("chain", params.chainName!, findChains(params.chainName!, ctx, scopeHint ?? "both"), ctx, params.agentScope);
795
+ if ("content" in targetOrError) return targetOrError;
796
+ const target = targetOrError;
797
+ fs.unlinkSync(target.filePath);
798
+ return result(`Deleted chain '${target.name}' at ${target.filePath}.`);
799
+ }
800
+
801
+ export function handleManagementAction(action: string, params: ManagementParams, ctx: ManagementContext): SubagentExecutionResult {
802
+ if (params.agentScope !== undefined && normalizeListScope(params.agentScope) === undefined) {
803
+ return result("agentScope must be 'user', 'project', or 'both'.", true);
804
+ }
805
+ switch (action as ManagementAction) {
806
+ case "list": return handleList(params, ctx);
807
+ case "get": return handleGet(params, ctx);
808
+ case "create": return handleCreate(params, ctx);
809
+ case "update": return handleUpdate(params, ctx);
810
+ case "delete": return handleDelete(params, ctx);
811
+ default: return result(`Unknown action: ${action}`, true);
812
+ }
813
+ }