@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,570 @@
1
+ /**
2
+ * Skill resolution and caching for subagent extension
3
+ */
4
+ import { execSync } from "node:child_process";
5
+ import * as fs from "node:fs";
6
+ import * as os from "node:os";
7
+ import * as path from "node:path";
8
+ import { getAgentDir } from "../shared/utils.js";
9
+ const skillCache = new Map();
10
+ const MAX_CACHE_SIZE = 50;
11
+ let loadSkillsCache = null;
12
+ const LOAD_SKILLS_CACHE_TTL_MS = 5000;
13
+ const CONFIG_DIR = ".pi";
14
+ const SUBAGENT_ORCHESTRATION_SKILL = "pi-subagents";
15
+ const SOURCE_PRIORITY = {
16
+ project: 700,
17
+ "project-settings": 650,
18
+ "project-package": 600,
19
+ user: 300,
20
+ "user-settings": 250,
21
+ "user-package": 200,
22
+ extension: 150,
23
+ builtin: 100,
24
+ unknown: 0,
25
+ };
26
+ function stripSkillFrontmatter(content) {
27
+ const normalized = content.replace(/\r\n/g, "\n");
28
+ if (!normalized.startsWith("---"))
29
+ return normalized;
30
+ const endIndex = normalized.indexOf("\n---", 3);
31
+ if (endIndex === -1)
32
+ return normalized;
33
+ return normalized.slice(endIndex + 4).trim();
34
+ }
35
+ function isWithinPath(filePath, dir) {
36
+ const relative = path.relative(dir, filePath);
37
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
38
+ }
39
+ function readOptionalJsonFile(filePath, label) {
40
+ try {
41
+ return JSON.parse(fs.readFileSync(filePath, "utf-8"));
42
+ }
43
+ catch (error) {
44
+ const code = typeof error === "object" && error !== null && "code" in error
45
+ ? error.code
46
+ : undefined;
47
+ if (code === "ENOENT")
48
+ return null;
49
+ const message = error instanceof Error ? error.message : String(error);
50
+ throw new Error(`Failed to read ${label} '${filePath}': ${message}`, {
51
+ cause: error instanceof Error ? error : undefined,
52
+ });
53
+ }
54
+ }
55
+ function readJsonFileBestEffort(filePath) {
56
+ try {
57
+ return JSON.parse(fs.readFileSync(filePath, "utf-8"));
58
+ }
59
+ catch {
60
+ // Package scans over installed dependencies are opportunistic.
61
+ return null;
62
+ }
63
+ }
64
+ function extractSkillPathsFromPackageRoot(packageRoot, source, bestEffort = false) {
65
+ const packageJsonPath = path.join(packageRoot, "package.json");
66
+ const pkg = bestEffort
67
+ ? readJsonFileBestEffort(packageJsonPath)
68
+ : readOptionalJsonFile(packageJsonPath, "package manifest");
69
+ if (!pkg || typeof pkg !== "object" || Array.isArray(pkg))
70
+ return [];
71
+ const pi = pkg.pi;
72
+ if (!pi || typeof pi !== "object" || Array.isArray(pi))
73
+ return [];
74
+ const skills = pi.skills;
75
+ if (!Array.isArray(skills))
76
+ return [];
77
+ return skills
78
+ .filter((entry) => typeof entry === "string")
79
+ .map((entry) => ({ path: path.resolve(packageRoot, entry), source }));
80
+ }
81
+ let cachedGlobalNpmRoot = null;
82
+ function getGlobalNpmRoot() {
83
+ if (cachedGlobalNpmRoot !== null)
84
+ return cachedGlobalNpmRoot;
85
+ try {
86
+ cachedGlobalNpmRoot = execSync("npm root -g", { encoding: "utf-8", timeout: 5000, stdio: "pipe" }).trim();
87
+ return cachedGlobalNpmRoot;
88
+ }
89
+ catch {
90
+ // Global npm root is optional in constrained environments.
91
+ cachedGlobalNpmRoot = ""; // Empty string means "tried but failed"
92
+ return null;
93
+ }
94
+ }
95
+ function collectInstalledPackageSkillPaths(cwd, agentDir, projectTrusted) {
96
+ const dirs = [
97
+ ...(projectTrusted ? [{ path: path.join(cwd, CONFIG_DIR, "npm", "node_modules"), source: "project-package" }] : []),
98
+ { path: path.join(agentDir, "npm", "node_modules"), source: "user-package" },
99
+ ];
100
+ const globalRoot = getGlobalNpmRoot();
101
+ if (globalRoot) {
102
+ dirs.push({ path: globalRoot, source: "user-package" });
103
+ }
104
+ const results = [];
105
+ for (const dir of dirs) {
106
+ if (!fs.existsSync(dir.path))
107
+ continue;
108
+ let entries;
109
+ try {
110
+ entries = fs.readdirSync(dir.path, { withFileTypes: true });
111
+ }
112
+ catch {
113
+ continue;
114
+ }
115
+ for (const entry of entries) {
116
+ if (entry.name.startsWith("."))
117
+ continue;
118
+ if (!entry.isDirectory() && !entry.isSymbolicLink())
119
+ continue;
120
+ if (entry.name.startsWith("@")) {
121
+ const scopeDir = path.join(dir.path, entry.name);
122
+ let scopeEntries;
123
+ try {
124
+ scopeEntries = fs.readdirSync(scopeDir, { withFileTypes: true });
125
+ }
126
+ catch {
127
+ continue;
128
+ }
129
+ for (const scopeEntry of scopeEntries) {
130
+ if (scopeEntry.name.startsWith("."))
131
+ continue;
132
+ if (!scopeEntry.isDirectory() && !scopeEntry.isSymbolicLink())
133
+ continue;
134
+ const pkgRoot = path.join(scopeDir, scopeEntry.name);
135
+ results.push(...extractSkillPathsFromPackageRoot(pkgRoot, dir.source, true));
136
+ }
137
+ continue;
138
+ }
139
+ const pkgRoot = path.join(dir.path, entry.name);
140
+ results.push(...extractSkillPathsFromPackageRoot(pkgRoot, dir.source, true));
141
+ }
142
+ }
143
+ return results;
144
+ }
145
+ function collectSettingsSkillPaths(cwd, agentDir, projectTrusted) {
146
+ const results = [];
147
+ const settingsFiles = [
148
+ { file: path.join(cwd, CONFIG_DIR, "settings.json"), base: path.join(cwd, CONFIG_DIR), source: "project-settings" },
149
+ { file: path.join(agentDir, "settings.json"), base: agentDir, source: "user-settings" },
150
+ ];
151
+ for (const { file, base, source } of settingsFiles) {
152
+ if (!projectTrusted && source.startsWith("project-"))
153
+ continue;
154
+ const settings = readOptionalJsonFile(file, "skills settings file");
155
+ if (!settings || typeof settings !== "object" || Array.isArray(settings))
156
+ continue;
157
+ const skills = settings.skills;
158
+ if (!Array.isArray(skills))
159
+ continue;
160
+ for (const entry of skills) {
161
+ if (typeof entry !== "string")
162
+ continue;
163
+ let resolved = entry;
164
+ if (resolved.startsWith("~/")) {
165
+ resolved = path.join(os.homedir(), resolved.slice(2));
166
+ }
167
+ else if (!path.isAbsolute(resolved)) {
168
+ resolved = path.resolve(base, resolved);
169
+ }
170
+ results.push({ path: resolved, source });
171
+ }
172
+ }
173
+ return results;
174
+ }
175
+ function isSafePackagePath(value) {
176
+ return value.length > 0
177
+ && !path.isAbsolute(value)
178
+ && value.split(/[\\/]/).every((part) => part.length > 0 && part !== "." && part !== "..");
179
+ }
180
+ function parseNpmPackageName(source) {
181
+ const spec = source.slice(4).trim();
182
+ if (!spec)
183
+ return undefined;
184
+ const match = spec.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/);
185
+ const packageName = match?.[1] ?? spec;
186
+ return isSafePackagePath(packageName) ? packageName : undefined;
187
+ }
188
+ function stripGitRef(repoPath) {
189
+ const atIndex = repoPath.indexOf("@");
190
+ const hashIndex = repoPath.indexOf("#");
191
+ const refIndex = [atIndex, hashIndex].filter((index) => index >= 0).sort((a, b) => a - b)[0];
192
+ return refIndex === undefined ? repoPath : repoPath.slice(0, refIndex);
193
+ }
194
+ function parseGitPackagePath(source) {
195
+ const spec = source.slice(4).trim();
196
+ if (!spec)
197
+ return undefined;
198
+ let host = "";
199
+ let repoPath = "";
200
+ const scpLike = spec.match(/^git@([^:]+):(.+)$/);
201
+ if (scpLike) {
202
+ host = scpLike[1] ?? "";
203
+ repoPath = scpLike[2] ?? "";
204
+ }
205
+ else if (/^[a-z][a-z0-9+.-]*:\/\//i.test(spec)) {
206
+ try {
207
+ const url = new URL(spec);
208
+ host = url.hostname;
209
+ repoPath = url.pathname.replace(/^\/+/, "");
210
+ }
211
+ catch {
212
+ return undefined;
213
+ }
214
+ }
215
+ else {
216
+ const slashIndex = spec.indexOf("/");
217
+ if (slashIndex < 0)
218
+ return undefined;
219
+ host = spec.slice(0, slashIndex);
220
+ repoPath = spec.slice(slashIndex + 1);
221
+ }
222
+ const normalizedPath = stripGitRef(repoPath).replace(/\.git$/, "").replace(/^\/+/, "");
223
+ if (!host || !isSafePackagePath(host) || !isSafePackagePath(normalizedPath) || normalizedPath.split(/[\\/]/).length < 2) {
224
+ return undefined;
225
+ }
226
+ return { host, repoPath: normalizedPath };
227
+ }
228
+ function resolveSettingsPackageRoot(source, baseDir) {
229
+ const trimmed = source.trim();
230
+ if (!trimmed)
231
+ return undefined;
232
+ if (trimmed.startsWith("git:")) {
233
+ const parsed = parseGitPackagePath(trimmed);
234
+ return parsed ? path.join(baseDir, "git", parsed.host, parsed.repoPath) : undefined;
235
+ }
236
+ if (trimmed.startsWith("npm:")) {
237
+ const packageName = parseNpmPackageName(trimmed);
238
+ return packageName ? path.join(baseDir, "npm", "node_modules", packageName) : undefined;
239
+ }
240
+ const normalized = trimmed.startsWith("file:") ? trimmed.slice(5) : trimmed;
241
+ if (normalized === "~")
242
+ return os.homedir();
243
+ if (normalized.startsWith("~/"))
244
+ return path.join(os.homedir(), normalized.slice(2));
245
+ if (path.isAbsolute(normalized))
246
+ return normalized;
247
+ if (normalized === "." || normalized === ".." || normalized.startsWith("./") || normalized.startsWith("../")) {
248
+ return path.resolve(baseDir, normalized);
249
+ }
250
+ return undefined;
251
+ }
252
+ function collectSettingsPackageSkillPaths(cwd, agentDir, projectTrusted) {
253
+ const settingsFiles = [
254
+ { file: path.join(cwd, CONFIG_DIR, "settings.json"), base: path.join(cwd, CONFIG_DIR), source: "project-package" },
255
+ { file: path.join(agentDir, "settings.json"), base: agentDir, source: "user-package" },
256
+ ];
257
+ const results = [];
258
+ for (const { file, base, source } of settingsFiles) {
259
+ if (!projectTrusted && source.startsWith("project-"))
260
+ continue;
261
+ const settings = readOptionalJsonFile(file, "skills settings file");
262
+ if (!settings || typeof settings !== "object" || Array.isArray(settings))
263
+ continue;
264
+ const packages = settings.packages;
265
+ if (!Array.isArray(packages))
266
+ continue;
267
+ for (const entry of packages) {
268
+ const packageSource = typeof entry === "string"
269
+ ? entry
270
+ : typeof entry === "object" && entry !== null && typeof entry.source === "string"
271
+ ? entry.source
272
+ : undefined;
273
+ if (!packageSource)
274
+ continue;
275
+ const packageRoot = resolveSettingsPackageRoot(packageSource, base);
276
+ if (!packageRoot)
277
+ continue;
278
+ results.push(...extractSkillPathsFromPackageRoot(packageRoot, source));
279
+ }
280
+ }
281
+ return results;
282
+ }
283
+ function buildSkillPaths(cwd, agentDir, projectTrusted = true) {
284
+ const projectSkillPaths = projectTrusted
285
+ ? [
286
+ { path: path.join(cwd, CONFIG_DIR, "skills"), source: "project" },
287
+ { path: path.join(cwd, ".agents", "skills"), source: "project" },
288
+ ]
289
+ : [];
290
+ const skillPaths = [
291
+ ...projectSkillPaths,
292
+ ...collectInstalledPackageSkillPaths(cwd, agentDir, projectTrusted),
293
+ ...collectSettingsPackageSkillPaths(cwd, agentDir, projectTrusted),
294
+ ...(projectTrusted ? extractSkillPathsFromPackageRoot(cwd, "project-package") : []),
295
+ ...collectSettingsSkillPaths(cwd, agentDir, projectTrusted),
296
+ { path: path.join(agentDir, "skills"), source: "user" },
297
+ { path: path.join(os.homedir(), ".agents", "skills"), source: "user" },
298
+ ];
299
+ const deduped = new Map();
300
+ for (const entry of skillPaths) {
301
+ const resolvedPath = path.resolve(entry.path);
302
+ if (!deduped.has(resolvedPath)) {
303
+ deduped.set(resolvedPath, { path: resolvedPath, source: entry.source });
304
+ }
305
+ }
306
+ return [...deduped.values()];
307
+ }
308
+ function inferSkillSource(filePath, cwd, agentDir, sourceHint) {
309
+ if (sourceHint)
310
+ return sourceHint;
311
+ const projectConfigRoot = path.resolve(cwd, CONFIG_DIR);
312
+ const projectSkillsRoot = path.resolve(cwd, CONFIG_DIR, "skills");
313
+ const projectPackagesRoot = path.resolve(cwd, CONFIG_DIR, "npm", "node_modules");
314
+ const projectAgentsRoot = path.resolve(cwd, ".agents");
315
+ const userSkillsRoot = path.resolve(agentDir, "skills");
316
+ const userPackagesRoot = path.resolve(agentDir, "npm", "node_modules");
317
+ const userAgentRoot = path.resolve(agentDir);
318
+ const userAgentsRoot = path.resolve(os.homedir(), ".agents");
319
+ if (isWithinPath(filePath, projectPackagesRoot))
320
+ return "project-package";
321
+ if (isWithinPath(filePath, projectSkillsRoot) || isWithinPath(filePath, projectAgentsRoot))
322
+ return "project";
323
+ if (isWithinPath(filePath, projectConfigRoot))
324
+ return "project-settings";
325
+ if (isWithinPath(filePath, userPackagesRoot))
326
+ return "user-package";
327
+ if (isWithinPath(filePath, userSkillsRoot) || isWithinPath(filePath, userAgentsRoot))
328
+ return "user";
329
+ if (isWithinPath(filePath, userAgentRoot))
330
+ return "user-settings";
331
+ const globalRoot = getGlobalNpmRoot();
332
+ if (globalRoot && isWithinPath(filePath, globalRoot))
333
+ return "user-package";
334
+ return "unknown";
335
+ }
336
+ function chooseHigherPrioritySkill(existing, candidate) {
337
+ if (!existing)
338
+ return candidate;
339
+ const existingPriority = SOURCE_PRIORITY[existing.source] ?? 0;
340
+ const candidatePriority = SOURCE_PRIORITY[candidate.source] ?? 0;
341
+ if (candidatePriority > existingPriority)
342
+ return candidate;
343
+ if (candidatePriority < existingPriority)
344
+ return existing;
345
+ return candidate.order < existing.order ? candidate : existing;
346
+ }
347
+ function maybeReadSkillDescription(filePath) {
348
+ try {
349
+ const content = fs.readFileSync(filePath, "utf-8");
350
+ const normalized = content.replace(/\r\n/g, "\n");
351
+ if (!normalized.startsWith("---"))
352
+ return undefined;
353
+ const endIndex = normalized.indexOf("\n---", 3);
354
+ if (endIndex === -1)
355
+ return undefined;
356
+ const frontmatter = normalized.slice(3, endIndex).trim();
357
+ const match = frontmatter.match(/^description:\s*(.+)$/m);
358
+ if (!match)
359
+ return undefined;
360
+ return match[1]?.trim().replace(/^['\"]|['\"]$/g, "");
361
+ }
362
+ catch {
363
+ // Description parsing is best-effort metadata extraction.
364
+ return undefined;
365
+ }
366
+ }
367
+ function collectFilesystemSkills(cwd, agentDir, skillPaths) {
368
+ const entries = [];
369
+ const seen = new Set();
370
+ let order = 0;
371
+ const pushEntry = (name, filePath, sourceHint) => {
372
+ const resolvedFile = path.resolve(filePath);
373
+ if (seen.has(resolvedFile))
374
+ return;
375
+ if (!fs.existsSync(resolvedFile))
376
+ return;
377
+ seen.add(resolvedFile);
378
+ entries.push({
379
+ name,
380
+ filePath: resolvedFile,
381
+ source: inferSkillSource(resolvedFile, cwd, agentDir, sourceHint),
382
+ description: maybeReadSkillDescription(resolvedFile),
383
+ order: order++,
384
+ });
385
+ };
386
+ for (const skillPath of skillPaths) {
387
+ if (!fs.existsSync(skillPath.path))
388
+ continue;
389
+ let stat;
390
+ try {
391
+ stat = fs.statSync(skillPath.path);
392
+ }
393
+ catch {
394
+ continue;
395
+ }
396
+ if (stat.isFile()) {
397
+ const fileName = path.basename(skillPath.path);
398
+ if (!fileName.toLowerCase().endsWith(".md"))
399
+ continue;
400
+ const skillName = fileName.toLowerCase() === "skill.md"
401
+ ? path.basename(path.dirname(skillPath.path))
402
+ : path.basename(fileName, path.extname(fileName));
403
+ pushEntry(skillName, skillPath.path, skillPath.source);
404
+ continue;
405
+ }
406
+ if (!stat.isDirectory())
407
+ continue;
408
+ const rootSkillFile = path.join(skillPath.path, "SKILL.md");
409
+ if (fs.existsSync(rootSkillFile)) {
410
+ pushEntry(path.basename(skillPath.path), rootSkillFile, skillPath.source);
411
+ }
412
+ let childEntries;
413
+ try {
414
+ childEntries = fs.readdirSync(skillPath.path, { withFileTypes: true });
415
+ }
416
+ catch {
417
+ continue;
418
+ }
419
+ for (const child of childEntries) {
420
+ if (child.name.startsWith("."))
421
+ continue;
422
+ const childPath = path.join(skillPath.path, child.name);
423
+ if (child.isDirectory() || child.isSymbolicLink()) {
424
+ const nestedSkillPath = path.join(childPath, "SKILL.md");
425
+ if (fs.existsSync(nestedSkillPath)) {
426
+ pushEntry(child.name, nestedSkillPath, skillPath.source);
427
+ }
428
+ continue;
429
+ }
430
+ if (child.isFile() && child.name.toLowerCase().endsWith(".md")) {
431
+ pushEntry(path.basename(child.name, path.extname(child.name)), childPath, skillPath.source);
432
+ }
433
+ }
434
+ }
435
+ return entries;
436
+ }
437
+ function getCachedSkills(cwd, projectTrusted = true) {
438
+ const now = Date.now();
439
+ const agentDir = getAgentDir();
440
+ if (loadSkillsCache && loadSkillsCache.cwd === cwd && loadSkillsCache.agentDir === agentDir && loadSkillsCache.projectTrusted === projectTrusted && now - loadSkillsCache.timestamp < LOAD_SKILLS_CACHE_TTL_MS) {
441
+ return loadSkillsCache.skills;
442
+ }
443
+ const skillPaths = buildSkillPaths(cwd, agentDir, projectTrusted);
444
+ const loaded = collectFilesystemSkills(cwd, agentDir, skillPaths);
445
+ const dedupedByName = new Map();
446
+ for (const entry of loaded) {
447
+ const current = dedupedByName.get(entry.name);
448
+ dedupedByName.set(entry.name, chooseHigherPrioritySkill(current, entry));
449
+ }
450
+ const skills = [...dedupedByName.values()].sort((a, b) => a.order - b.order);
451
+ loadSkillsCache = { cwd, agentDir, projectTrusted, skills, timestamp: now };
452
+ return skills;
453
+ }
454
+ export function resolveSkillPath(skillName, cwd, options = {}) {
455
+ const skills = getCachedSkills(cwd, options.projectTrusted ?? true);
456
+ const skill = skills.find((s) => s.name === skillName);
457
+ if (!skill)
458
+ return undefined;
459
+ return { path: skill.filePath, source: skill.source };
460
+ }
461
+ function readSkill(skillName, skillPath, source) {
462
+ try {
463
+ const stat = fs.statSync(skillPath);
464
+ const cached = skillCache.get(skillPath);
465
+ if (cached && cached.mtime === stat.mtimeMs) {
466
+ return cached.skill;
467
+ }
468
+ const raw = fs.readFileSync(skillPath, "utf-8");
469
+ const content = stripSkillFrontmatter(raw);
470
+ const skill = {
471
+ name: skillName,
472
+ path: skillPath,
473
+ content,
474
+ source,
475
+ };
476
+ skillCache.set(skillPath, { mtime: stat.mtimeMs, skill });
477
+ if (skillCache.size > MAX_CACHE_SIZE) {
478
+ const firstKey = skillCache.keys().next().value;
479
+ if (firstKey)
480
+ skillCache.delete(firstKey);
481
+ }
482
+ return skill;
483
+ }
484
+ catch {
485
+ // Treat unreadable skill files as unresolved so callers can surface as missing.
486
+ return undefined;
487
+ }
488
+ }
489
+ export function resolveSkills(skillNames, cwd, options = {}) {
490
+ const resolved = [];
491
+ const missing = [];
492
+ for (const name of skillNames) {
493
+ const trimmed = name.trim();
494
+ if (!trimmed)
495
+ continue;
496
+ if (trimmed === SUBAGENT_ORCHESTRATION_SKILL) {
497
+ missing.push(trimmed);
498
+ continue;
499
+ }
500
+ const location = resolveSkillPath(trimmed, cwd, options);
501
+ if (!location) {
502
+ missing.push(trimmed);
503
+ continue;
504
+ }
505
+ const skill = readSkill(trimmed, location.path, location.source);
506
+ if (skill) {
507
+ resolved.push(skill);
508
+ }
509
+ else {
510
+ missing.push(trimmed);
511
+ }
512
+ }
513
+ return { resolved, missing };
514
+ }
515
+ export function resolveSkillsWithFallback(skillNames, primaryCwd, fallbackCwd, options = {}) {
516
+ const primary = resolveSkills(skillNames, primaryCwd, options);
517
+ if (!fallbackCwd || primary.missing.length === 0)
518
+ return primary;
519
+ if (path.resolve(primaryCwd) === path.resolve(fallbackCwd))
520
+ return primary;
521
+ const fallback = resolveSkills(primary.missing, fallbackCwd, options);
522
+ return {
523
+ resolved: [...primary.resolved, ...fallback.resolved],
524
+ missing: fallback.missing,
525
+ };
526
+ }
527
+ export function buildSkillInjection(skills) {
528
+ if (skills.length === 0)
529
+ return "";
530
+ return skills
531
+ .map((s) => `<skill name="${s.name}">\n${s.content}\n</skill>`)
532
+ .join("\n\n");
533
+ }
534
+ export function normalizeSkillInput(input) {
535
+ if (input === false)
536
+ return false;
537
+ if (input === true || input === undefined)
538
+ return undefined;
539
+ if (Array.isArray(input)) {
540
+ return [...new Set(input.map((s) => s.trim()).filter((s) => s.length > 0))];
541
+ }
542
+ // Guard against JSON-encoded arrays arriving as strings (e.g. '["a","b"]').
543
+ // Models sometimes serialise the skill parameter as a JSON string instead of
544
+ // a native array, and naively splitting on "," would embed brackets/quotes
545
+ // into the skill names, causing resolution to silently fail.
546
+ const trimmed = input.trim();
547
+ if (trimmed.startsWith("[")) {
548
+ try {
549
+ const parsed = JSON.parse(trimmed);
550
+ if (Array.isArray(parsed)) {
551
+ return normalizeSkillInput(parsed);
552
+ }
553
+ }
554
+ catch {
555
+ // Not valid JSON – fall through to comma-split
556
+ }
557
+ }
558
+ return [...new Set(input.split(",").map((s) => s.trim()).filter((s) => s.length > 0))];
559
+ }
560
+ export function discoverAvailableSkills(cwd, options = {}) {
561
+ const skills = getCachedSkills(cwd, options.projectTrusted ?? true);
562
+ return skills
563
+ .filter((s) => s.name !== SUBAGENT_ORCHESTRATION_SKILL)
564
+ .map((s) => ({
565
+ name: s.name,
566
+ source: s.source,
567
+ description: s.description,
568
+ }))
569
+ .sort((a, b) => a.name.localeCompare(b.name));
570
+ }
@@ -0,0 +1 @@
1
+ export const EXTENSION_BUILD = Object.freeze({"version":"0.44.5","sha256":"53f1d8cd3c71b05fdfc903bfcecd06eb5d80bb367a16a09d235199d3f93266f2"});
@@ -0,0 +1,112 @@
1
+ import { Type } from "../shared/native-typebox.js";
2
+ import { createSubagentExecutor, normalizeSubagentParamsLike } from "../runs/foreground/subagent-executor.js";
3
+ import { activateTools, restoreLazyTools } from "../shared/lazy-tools.js";
4
+ import { runHistoryIndex } from "../runs/shared/history-index.js";
5
+ import { listSupervisorQuestionsAsync } from "../runs/shared/supervisor-questions.js";
6
+ import { renderSubagentResult } from "../tui/render.js";
7
+ import { AgentRunsParams, DelegateParams } from "./schemas.js";
8
+ import { normalizeEverydayParams } from "./tool-input.js";
9
+ export function registerCompactSubagentTools(pi, options) {
10
+ const { executor, adapt, guidelines, childSafe, asyncByDefault, state } = options;
11
+ let checking;
12
+ const checkRuns = () => {
13
+ if (pi.getActiveTools().includes("agent_runs") || !state.ownedRuns?.size)
14
+ return Promise.resolve();
15
+ const owner = state.lastUiContext?.sessionManager.getSessionId() ?? state.currentSessionId;
16
+ if (checking?.owner === owner)
17
+ return checking.promise;
18
+ const promise = Promise.resolve().then(async () => {
19
+ try {
20
+ const index = await runHistoryIndex(state);
21
+ const needed = await index.needsControls();
22
+ if (state.historyIndex === index && needed)
23
+ activateTools(pi, ["agent_runs"]);
24
+ }
25
+ catch {
26
+ // An unavailable browse index cannot establish that genuine owned work is inert.
27
+ if ((state.lastUiContext?.sessionManager.getSessionId() ?? state.currentSessionId) === owner && state.ownedRuns?.size)
28
+ activateTools(pi, ["agent_runs"]);
29
+ }
30
+ finally {
31
+ if (checking?.promise === promise)
32
+ checking = undefined;
33
+ }
34
+ });
35
+ checking = { owner, promise };
36
+ return promise;
37
+ };
38
+ const reconcileRuns = () => checkRuns();
39
+ const onRunsChanged = state.onRunsChanged;
40
+ state.onRunsChanged = () => { reconcileRuns(); onRunsChanged?.(); };
41
+ const asyncDescription = asyncByDefault ? "Background by default; false waits for the result." : "Foreground by default; true detaches work. Use false when the result must appear in your report.";
42
+ pi.registerTool({
43
+ name: "delegate",
44
+ label: "Delegate",
45
+ description: `Delegate one bounded task to a configured agent. For profiles/history, load_subagent({advanced:false}) enables agent_runs. Delegation enables run controls automatically. ${asyncDescription} Use worktree for an isolated writer, acceptance for explicit requirements, and fresh context for independent review. Fresh handoffs must include relevant exact user instructions and settled decisions or readable source references, not just summaries, alongside the bounded task. Advanced workflows remain behind load_subagent.`,
46
+ ...(childSafe ? { promptGuidelines: [...guidelines] } : {}),
47
+ parameters: Type.Object({ ...DelegateParams.properties, async: Type.Optional(Type.Boolean({ description: asyncDescription })) }, { additionalProperties: false }),
48
+ async execute(id, params, signal, onUpdate, ctx) {
49
+ const { worktree, context, async: background, ...task } = normalizeEverydayParams(params);
50
+ const request = worktree
51
+ ? { tasks: [task], worktree: true, context, async: background, cwd: task.cwd }
52
+ : { ...task, context, async: background };
53
+ const result = await executor.execute(id, normalizeSubagentParamsLike(request), signal, onUpdate, ctx);
54
+ await checkRuns();
55
+ return adapt(result, ctx);
56
+ },
57
+ renderResult: renderSubagentResult,
58
+ });
59
+ pi.registerTool({
60
+ name: "agent_runs",
61
+ defaultActive: false,
62
+ label: "Agent Runs",
63
+ description: `List ${childSafe ? "only this child's directly owned" : "your delegated"} runs across working directories (questions/failures, then live work, then unreviewed results; 20 per page). Filter globally by agent/state/text, sort, and page with the returned cursor. history reads 100 bounded native-entry previews; search finds saved visible text using words or quoted phrases, not operators or prefixes. questions pages 20 compact previews (offset/limit); questionId selects one, and questionPath/answerPath retain full records. Browse freshness is not completion or delivery proof. Inspect concise results, paths and continuations; full:true includes the full task/configuration. Answer durable questions, nudge, stop, continue, or save parent-only review. Review notes are not sent to children; put actionable instructions in continue/nudge. Inspect/review/nudge never restart finished work. Continue/answer can launch a saved child; async:false waits for its actual result. Saved continuations keep settings unless agent selects a current profile; model overrides win. Live guidance never mutates model or acceptance. profiles lists roles, sources, context and model/thinking/fallback defaults. History survives reload.`,
64
+ parameters: AgentRunsParams,
65
+ async execute(id, params, signal, onUpdate, ctx) {
66
+ const normalized = normalizeEverydayParams(params, true);
67
+ if (params.action === "list" && !params.id && options.listRuns)
68
+ return adapt(await options.listRuns({ ...normalized, signal }, ctx), ctx);
69
+ const actions = { list: "status", inspect: "status", history: "history", search: "search", nudge: "nudge", stop: "interrupt", continue: "resume", profiles: "list", questions: "questions", answer: "answer", review: "review" };
70
+ return adapt(await executor.execute(id, normalizeSubagentParamsLike({ ...normalized, action: actions[params.action] }), signal, onUpdate, ctx), ctx);
71
+ },
72
+ renderResult: renderSubagentResult,
73
+ });
74
+ pi.registerTool({
75
+ name: "load_subagent",
76
+ label: "Load Subagent",
77
+ description: `Enable agent_runs for profiles, history and run controls; advanced:false loads only those controls. By default also enable advanced subagent orchestration: parallel groups, chains, saved workflows, detailed overrides, get, extend and doctor.${childSafe ? " Agent-definition mutations remain blocked." : " Includes agent-definition management."} Ordinary delegation and control use delegate and agent_runs. After loading advanced workflows, call subagent with { action: "list" } before execution.`,
78
+ promptSnippet: "Discover profiles/history with advanced:false, or load full subagent orchestration by default.",
79
+ parameters: Type.Object({ advanced: Type.Optional(Type.Boolean({ description: "Also enable advanced orchestration (default true); false loads only agent_runs for profiles, history and controls." })) }),
80
+ async execute(_id, params) {
81
+ const advanced = params.advanced !== false;
82
+ if (advanced && !pi.getAllTools().some((tool) => tool.name === "subagent" && !("namespace" in tool && tool.namespace))) {
83
+ throw new Error("Subagent is unavailable because the full tool is excluded from this session.");
84
+ }
85
+ if (!advanced && !pi.getAllTools().some((tool) => tool.name === "agent_runs" && !("namespace" in tool && tool.namespace)))
86
+ throw new Error("Run controls are excluded from this session.");
87
+ const added = !pi.getActiveTools().includes(advanced ? "subagent" : "agent_runs");
88
+ activateTools(pi, advanced ? ["agent_runs", "subagent"] : ["agent_runs"]);
89
+ return {
90
+ content: [{ type: "text", text: advanced ? [`Subagent ${added ? "enabled" : "already enabled"}.`, ...guidelines.map((line) => `- ${line}`)].join("\n") : "Run controls enabled. Use agent_runs({action:'profiles'}) to discover agents; list, history, or search browses owned saved work." }],
91
+ details: {},
92
+ };
93
+ },
94
+ });
95
+ const reconcile = async (ctx) => {
96
+ if (options.keepAdvancedActive)
97
+ activateTools(pi, ["subagent"]);
98
+ await checkRuns();
99
+ if (!pi.getActiveTools().includes("agent_runs") && (await listSupervisorQuestionsAsync(ctx.sessionManager.getSessionId())).some((question) => question.state === "awaiting_input" || question.state === "answer_pending"))
100
+ activateTools(pi, ["agent_runs"]);
101
+ };
102
+ const restore = async (event, ctx) => {
103
+ if (event.reason !== "reload")
104
+ restoreLazyTools(pi, ctx, "load_subagent", ["subagent", "agent_runs"]);
105
+ await reconcile(ctx);
106
+ };
107
+ pi.on("session_start", restore);
108
+ pi.on("session_tree", (_event, ctx) => reconcile(ctx));
109
+ pi.on("session_compact", (_event, ctx) => reconcile(ctx));
110
+ pi.on("before_agent_start", (_event, ctx) => reconcile(ctx));
111
+ return reconcileRuns;
112
+ }