ceulen 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (358) hide show
  1. package/CHANGELOG.md +317 -12
  2. package/README.md +87 -91
  3. package/extensions/lib/advisor-marker.ts +33 -0
  4. package/extensions/lib/panel.ts +25 -2
  5. package/extensions/lib/rate.ts +24 -0
  6. package/extensions/lib/registry.ts +93 -7
  7. package/extensions/lib/tools.ts +47 -0
  8. package/extensions/lib/usage-store.ts +33 -0
  9. package/extensions/modules/advisor/commands/advisor.ts +244 -0
  10. package/extensions/modules/advisor/configPanel.ts +194 -0
  11. package/extensions/modules/advisor/index.ts +217 -0
  12. package/extensions/modules/advisor/lib/config.ts +248 -0
  13. package/extensions/modules/advisor/lib/emission-guard.ts +153 -0
  14. package/extensions/modules/advisor/lib/isolated-model.ts +160 -0
  15. package/extensions/modules/advisor/lib/model-picker.ts +47 -0
  16. package/extensions/modules/advisor/lib/watcher.ts +286 -0
  17. package/extensions/modules/advisor/test/compliance.test.ts +125 -0
  18. package/extensions/modules/advisor/test/config.test.ts +202 -0
  19. package/extensions/modules/advisor/test/configPanel.test.ts +223 -0
  20. package/extensions/modules/advisor/test/emission-guard.test.ts +201 -0
  21. package/extensions/modules/advisor/test/isolated-model.test.ts +311 -0
  22. package/extensions/modules/advisor/test/model-picker.test.ts +32 -0
  23. package/extensions/modules/advisor/test/module.test.ts +586 -0
  24. package/extensions/modules/advisor/test/watcher.test.ts +478 -0
  25. package/extensions/modules/classifier/configPanel.ts +104 -0
  26. package/extensions/modules/classifier/index.ts +297 -0
  27. package/extensions/modules/classifier/lib/settings.ts +95 -0
  28. package/extensions/modules/classifier/test/classifier.test.ts +475 -0
  29. package/extensions/modules/composer/index.ts +152 -3
  30. package/extensions/modules/composer/lib/footer.ts +119 -0
  31. package/extensions/modules/composer/lib/shapes.ts +265 -26
  32. package/extensions/modules/composer/test/editor.test.ts +1 -1
  33. package/extensions/modules/composer/test/footer.test.ts +96 -0
  34. package/extensions/modules/composer/test/module.test.ts +113 -11
  35. package/extensions/modules/composer/test/screen.test.ts +29 -1
  36. package/extensions/modules/composer/test/shapes.test.ts +224 -8
  37. package/extensions/modules/config/defaultTools.ts +96 -0
  38. package/extensions/modules/config/index.ts +147 -7
  39. package/extensions/modules/config/piSettings.ts +254 -69
  40. package/extensions/modules/config/test/defaultTools.test.ts +122 -0
  41. package/extensions/modules/config/test/menu.test.ts +64 -0
  42. package/extensions/modules/config/test/panel.test.ts +38 -23
  43. package/extensions/modules/config/test/piSettings.test.ts +130 -3
  44. package/extensions/modules/config/test/renderTools.test.ts +71 -0
  45. package/extensions/modules/config/test/tools.test.ts +146 -0
  46. package/extensions/modules/fff/index.ts +2094 -0
  47. package/extensions/modules/fff/lib/query.ts +129 -0
  48. package/extensions/modules/fff/test/index.test.ts +607 -0
  49. package/extensions/modules/fff/test/query.test.ts +71 -0
  50. package/extensions/modules/munin/configPanel.ts +105 -0
  51. package/extensions/modules/munin/index.ts +641 -0
  52. package/extensions/modules/munin/lib/helpers.ts +471 -0
  53. package/extensions/modules/munin/lib/retry.ts +20 -0
  54. package/extensions/modules/munin/lib/sdk.ts +218 -0
  55. package/extensions/modules/munin/test/config.test.ts +168 -0
  56. package/extensions/modules/munin/test/configPanel.test.ts +161 -0
  57. package/extensions/modules/munin/test/extension.test.ts +224 -0
  58. package/extensions/modules/munin/test/helpers.test.ts +523 -0
  59. package/extensions/modules/munin/test/retry.test.ts +145 -0
  60. package/extensions/modules/munin/test/stale-protocol.test.ts +554 -0
  61. package/extensions/modules/plan/configPanel.ts +152 -0
  62. package/extensions/modules/plan/index.ts +917 -0
  63. package/extensions/modules/plan/lib/plan-tools.ts +72 -0
  64. package/extensions/modules/plan/lib/prompt.ts +65 -0
  65. package/extensions/modules/plan/lib/settings.ts +166 -0
  66. package/extensions/modules/plan/lib/shell-gate.ts +200 -0
  67. package/extensions/modules/plan/test/configPanel.test.ts +96 -0
  68. package/extensions/modules/plan/test/harness.ts +133 -0
  69. package/extensions/modules/plan/test/module.test.ts +305 -0
  70. package/extensions/modules/plan/test/settings.test.ts +114 -0
  71. package/extensions/modules/plan/test/shell-gate.test.ts +103 -0
  72. package/extensions/modules/ponytail/index.ts +23 -73
  73. package/extensions/modules/ponytail/lib/config.ts +1 -6
  74. package/extensions/modules/ponytail/test/extension.test.ts +1 -85
  75. package/extensions/modules/repair/configPanel.ts +96 -0
  76. package/extensions/modules/repair/index.ts +414 -0
  77. package/extensions/modules/repair/lib/auto-bg.ts +333 -0
  78. package/extensions/modules/repair/lib/edit-repair.ts +155 -0
  79. package/extensions/modules/repair/lib/editor.ts +251 -0
  80. package/extensions/modules/repair/lib/guards.ts +34 -0
  81. package/extensions/modules/repair/lib/input-repair.ts +324 -0
  82. package/extensions/modules/repair/lib/patch.ts +481 -0
  83. package/extensions/modules/repair/lib/settings.ts +114 -0
  84. package/extensions/modules/repair/test/auto-bg.test.ts +405 -0
  85. package/extensions/modules/repair/test/edit-repair.test.ts +224 -0
  86. package/extensions/modules/repair/test/editor.test.ts +141 -0
  87. package/extensions/modules/repair/test/guards.test.ts +64 -0
  88. package/extensions/modules/repair/test/input-repair.test.ts +231 -0
  89. package/extensions/modules/repair/test/patch.test.ts +563 -0
  90. package/extensions/modules/repair/test/settings.test.ts +167 -0
  91. package/extensions/modules/repair/test/wrapper.test.ts +210 -0
  92. package/extensions/modules/router/commands/commands.ts +4 -0
  93. package/extensions/modules/router/lib/client.ts +61 -0
  94. package/extensions/modules/router/lib/provider.ts +34 -13
  95. package/extensions/modules/router/lib/systemone.ts +152 -0
  96. package/extensions/modules/router/test/unit.test.ts +179 -0
  97. package/extensions/modules/rtk/findFallback.js +68 -0
  98. package/extensions/modules/rtk/index.ts +248 -0
  99. package/extensions/modules/rtk/safe-rewrite.js +74 -0
  100. package/extensions/modules/rtk/test/findFallback.test.js +66 -0
  101. package/extensions/modules/rtk/test/index.test.js +131 -0
  102. package/extensions/modules/rtk/test/safe-rewrite.test.js +96 -0
  103. package/extensions/modules/rtk/version-gate.js +34 -0
  104. package/extensions/modules/serena/index.ts +629 -0
  105. package/extensions/modules/serena/lib/detect.ts +73 -0
  106. package/extensions/modules/serena/lib/env.ts +76 -0
  107. package/extensions/modules/serena/lib/guidance.ts +26 -0
  108. package/extensions/modules/serena/lib/normalize.ts +27 -0
  109. package/extensions/modules/serena/lib/symbol-key.ts +20 -0
  110. package/extensions/modules/serena/lib/truncate.ts +20 -0
  111. package/extensions/modules/serena/test/env.test.ts +122 -0
  112. package/extensions/modules/serena/test/index.test.ts +347 -0
  113. package/extensions/modules/serena/test/worker.test.ts +562 -0
  114. package/extensions/modules/serena/worker.ts +858 -0
  115. package/extensions/modules/steering/configPanel.ts +122 -0
  116. package/extensions/modules/steering/index.ts +616 -0
  117. package/extensions/modules/steering/lib/anchor.ts +175 -0
  118. package/extensions/modules/steering/lib/errors.ts +253 -0
  119. package/extensions/modules/steering/lib/family.ts +33 -0
  120. package/extensions/modules/steering/lib/guidance.ts +172 -0
  121. package/extensions/modules/steering/lib/history.ts +170 -0
  122. package/extensions/modules/steering/lib/settings.ts +127 -0
  123. package/extensions/modules/steering/test/anchor-regressions.test.ts +93 -0
  124. package/extensions/modules/steering/test/anchor-wiring.test.ts +99 -0
  125. package/extensions/modules/steering/test/anchor.test.ts +160 -0
  126. package/extensions/modules/steering/test/cache-stats.test.ts +43 -0
  127. package/extensions/modules/steering/test/errors.test.ts +309 -0
  128. package/extensions/modules/steering/test/family.test.ts +43 -0
  129. package/extensions/modules/steering/test/guidance.test.ts +357 -0
  130. package/extensions/modules/steering/test/harness.ts +93 -0
  131. package/extensions/modules/steering/test/history.test.ts +118 -0
  132. package/extensions/modules/steering/test/settings.test.ts +182 -0
  133. package/extensions/modules/steering/test/status.test.ts +71 -0
  134. package/extensions/modules/steering/test/toolCall.test.ts +99 -0
  135. package/extensions/modules/subagent/agents/planner.md +14 -0
  136. package/extensions/modules/subagent/agents/reviewer.md +42 -0
  137. package/extensions/modules/subagent/agents/scout.md +47 -0
  138. package/extensions/modules/subagent/agents/tester.md +12 -0
  139. package/extensions/modules/subagent/agents/worker.md +18 -0
  140. package/extensions/modules/subagent/configPanel.ts +219 -0
  141. package/extensions/modules/subagent/index.ts +2451 -0
  142. package/extensions/modules/subagent/lib/agents.ts +408 -0
  143. package/extensions/modules/subagent/lib/background.ts +383 -0
  144. package/extensions/modules/subagent/lib/herdr.ts +1019 -0
  145. package/extensions/modules/subagent/lib/history.ts +126 -0
  146. package/extensions/modules/subagent/lib/model.ts +156 -0
  147. package/extensions/modules/subagent/lib/render.ts +335 -0
  148. package/extensions/modules/subagent/lib/result.ts +110 -0
  149. package/extensions/modules/subagent/lib/roles.ts +296 -0
  150. package/extensions/modules/subagent/lib/routing.ts +223 -0
  151. package/extensions/modules/subagent/lib/runner.ts +559 -0
  152. package/extensions/modules/subagent/lib/schema.ts +21 -0
  153. package/extensions/modules/subagent/lib/security.ts +752 -0
  154. package/extensions/modules/subagent/lib/settings.ts +159 -0
  155. package/extensions/modules/subagent/lib/thread-viewer.ts +319 -0
  156. package/extensions/modules/subagent/lib/threads.ts +135 -0
  157. package/extensions/modules/subagent/lib/types.ts +18 -0
  158. package/extensions/modules/subagent/lib/widget.ts +475 -0
  159. package/extensions/modules/subagent/test/configPanel.test.ts +132 -0
  160. package/extensions/modules/subagent/test/herdr-advisor.test.ts +40 -0
  161. package/extensions/modules/subagent/test/routing.test.ts +350 -0
  162. package/extensions/modules/subagent/test/widget.test.ts +208 -0
  163. package/extensions/modules/usage/index.ts +59 -16
  164. package/extensions/modules/usage/test/genrate.test.ts +70 -0
  165. package/extensions/modules/usage/test/parsers.test.ts +13 -0
  166. package/extensions/modules/ux/UPSTREAM +24 -0
  167. package/extensions/modules/ux/index.ts +393 -0
  168. package/extensions/modules/ux/lib/audit.ts +562 -0
  169. package/extensions/modules/ux/lib/config.ts +136 -0
  170. package/extensions/modules/ux/lib/instructions.ts +77 -0
  171. package/extensions/modules/ux/test/audit.test.ts +756 -0
  172. package/extensions/modules/ux/test/extension.test.ts +394 -0
  173. package/extensions/modules/ux/test/instructions.test.ts +19 -0
  174. package/extensions/modules/web/configPanel.ts +193 -0
  175. package/extensions/modules/web/index.ts +978 -0
  176. package/extensions/modules/web/lib/agy.ts +209 -0
  177. package/extensions/modules/web/lib/brave.ts +42 -0
  178. package/extensions/modules/web/lib/cdp.ts +686 -0
  179. package/extensions/modules/web/lib/chatapi.ts +101 -0
  180. package/extensions/modules/web/lib/chatgpt.ts +796 -0
  181. package/extensions/modules/web/lib/chrome.ts +328 -0
  182. package/extensions/modules/web/lib/config.ts +136 -0
  183. package/extensions/modules/web/lib/content.ts +99 -0
  184. package/extensions/modules/web/lib/crawl4ai.ts +172 -0
  185. package/extensions/modules/web/lib/extract.ts +235 -0
  186. package/extensions/modules/web/lib/firecrawl.ts +56 -0
  187. package/extensions/modules/web/lib/format.ts +197 -0
  188. package/extensions/modules/web/lib/gemini-auth.ts +286 -0
  189. package/extensions/modules/web/lib/gemini-dr.ts +338 -0
  190. package/extensions/modules/web/lib/gemini.ts +551 -0
  191. package/extensions/modules/web/lib/imageapi.ts +559 -0
  192. package/extensions/modules/web/lib/retry.ts +71 -0
  193. package/extensions/modules/web/lib/search.ts +237 -0
  194. package/extensions/modules/web/lib/searxng.ts +69 -0
  195. package/extensions/modules/web/lib/settings.ts +148 -0
  196. package/extensions/modules/web/scripts/cdp-smoke.ts +77 -0
  197. package/extensions/modules/web/scripts/gemini-smoke.ts +107 -0
  198. package/extensions/modules/web/test/agy.test.ts +383 -0
  199. package/extensions/modules/web/test/cdp.test.ts +717 -0
  200. package/extensions/modules/web/test/chat.test.ts +171 -0
  201. package/extensions/modules/web/test/chatgpt.test.ts +633 -0
  202. package/extensions/modules/web/test/chrome.test.ts +282 -0
  203. package/extensions/modules/web/test/config.test.ts +218 -0
  204. package/extensions/modules/web/test/configPanel.test.ts +132 -0
  205. package/extensions/modules/web/test/crawl.test.ts +134 -0
  206. package/extensions/modules/web/test/crawl4ai.test.ts +105 -0
  207. package/extensions/modules/web/test/extension.test.ts +118 -0
  208. package/extensions/modules/web/test/extract.test.ts +436 -0
  209. package/extensions/modules/web/test/fixtures/dr-confirm.bin +12 -0
  210. package/extensions/modules/web/test/fixtures/dr-plan.bin +20 -0
  211. package/extensions/modules/web/test/fixtures/interaction.html +31 -0
  212. package/extensions/modules/web/test/format.test.ts +230 -0
  213. package/extensions/modules/web/test/gemini-auth.test.ts +465 -0
  214. package/extensions/modules/web/test/gemini-dr.test.ts +249 -0
  215. package/extensions/modules/web/test/gemini.test.ts +472 -0
  216. package/extensions/modules/web/test/hook.test.ts +101 -0
  217. package/extensions/modules/web/test/image.test.ts +1089 -0
  218. package/extensions/modules/web/test/retry.test.ts +119 -0
  219. package/extensions/modules/web/test/screenshot.test.ts +109 -0
  220. package/extensions/modules/web/test/search.test.ts +210 -0
  221. package/extensions/modules/web/test/settings.test.ts +165 -0
  222. package/extensions/modules/web/test/skill.test.ts +72 -0
  223. package/extensions/modules/web/types.d.ts +3 -0
  224. package/extensions/modules/web/vendor/package.json +1 -0
  225. package/extensions/modules/web/vendor/readability/LICENSE.md +13 -0
  226. package/extensions/modules/web/vendor/readability/Readability-readerable.js +123 -0
  227. package/extensions/modules/web/vendor/readability/Readability.js +2787 -0
  228. package/extensions/modules/web/vendor/readability/index.d.ts +64 -0
  229. package/extensions/modules/web/vendor/readability/index.js +9 -0
  230. package/extensions/modules/web/vendor/turndown/LICENSE +21 -0
  231. package/extensions/modules/web/vendor/turndown/turndown.cjs.js +784 -0
  232. package/extensions/modules/web/vendor/turndown-plugin-gfm/LICENSE +21 -0
  233. package/extensions/modules/web/vendor/turndown-plugin-gfm/turndown-plugin-gfm.cjs.js +163 -0
  234. package/extensions/modules/zai/configPanel.ts +151 -0
  235. package/extensions/modules/zai/index.ts +186 -0
  236. package/extensions/modules/zai/lib/anthropic.ts +159 -0
  237. package/extensions/modules/zai/lib/settings.ts +198 -0
  238. package/extensions/modules/zai/lib/signing.ts +718 -0
  239. package/extensions/modules/zai/lib/throttle.ts +198 -0
  240. package/extensions/modules/zai/test/anthropic.test.ts +132 -0
  241. package/extensions/modules/zai/test/configPanel.test.ts +207 -0
  242. package/extensions/modules/zai/test/extension.test.ts +249 -0
  243. package/extensions/modules/zai/test/settings.test.ts +183 -0
  244. package/extensions/modules/zai/test/signing-wiring.test.ts +108 -0
  245. package/extensions/modules/zai/test/signing.test.ts +345 -0
  246. package/extensions/modules/zai/test/throttle.test.ts +329 -0
  247. package/package.json +19 -4
  248. package/scripts/validate-themes.mjs +75 -0
  249. package/skills/munin/SKILL.md +117 -0
  250. package/skills/ux-capture/SKILL.md +202 -0
  251. package/skills/ux-design/SKILL.md +279 -0
  252. package/skills/ux-presets/SKILL.md +484 -0
  253. package/skills/ux-routing/SKILL.md +46 -0
  254. package/skills/web/SKILL.md +153 -0
  255. package/themes/alabaster.json +93 -0
  256. package/themes/amethyst.json +96 -0
  257. package/themes/anthracite.json +93 -0
  258. package/themes/basalt.json +91 -0
  259. package/themes/birch.json +95 -0
  260. package/themes/catppuccin-mocha.json +91 -0
  261. package/themes/dark-abyss.json +91 -0
  262. package/themes/dark-arctic.json +104 -0
  263. package/themes/dark-aurora.json +95 -0
  264. package/themes/dark-catppuccin.json +107 -0
  265. package/themes/dark-cavern.json +91 -0
  266. package/themes/dark-celestial.json +106 -0
  267. package/themes/dark-copper.json +95 -0
  268. package/themes/dark-cosmos.json +90 -0
  269. package/themes/dark-cyberpunk.json +102 -0
  270. package/themes/dark-dracula.json +98 -0
  271. package/themes/dark-eclipse.json +91 -0
  272. package/themes/dark-ember.json +95 -0
  273. package/themes/dark-equinox.json +90 -0
  274. package/themes/dark-forest.json +96 -0
  275. package/themes/dark-github.json +105 -0
  276. package/themes/dark-gruvbox.json +112 -0
  277. package/themes/dark-lavender.json +95 -0
  278. package/themes/dark-lunar.json +89 -0
  279. package/themes/dark-midnight.json +95 -0
  280. package/themes/dark-monochrome.json +94 -0
  281. package/themes/dark-monokai.json +98 -0
  282. package/themes/dark-nebula.json +90 -0
  283. package/themes/dark-neon-noir.json +100 -0
  284. package/themes/dark-nord.json +98 -0
  285. package/themes/dark-ocean.json +101 -0
  286. package/themes/dark-one.json +100 -0
  287. package/themes/dark-poimandres.json +115 -0
  288. package/themes/dark-rainforest.json +91 -0
  289. package/themes/dark-reef.json +91 -0
  290. package/themes/dark-retro.json +92 -0
  291. package/themes/dark-rose-pine.json +96 -0
  292. package/themes/dark-sakura.json +95 -0
  293. package/themes/dark-slate.json +95 -0
  294. package/themes/dark-solarized.json +97 -0
  295. package/themes/dark-solstice.json +90 -0
  296. package/themes/dark-starfall.json +91 -0
  297. package/themes/dark-sunset.json +99 -0
  298. package/themes/dark-swamp.json +90 -0
  299. package/themes/dark-synthwave.json +103 -0
  300. package/themes/dark-taiga.json +91 -0
  301. package/themes/dark-terminal.json +95 -0
  302. package/themes/dark-tokyo-night.json +101 -0
  303. package/themes/dark-tundra.json +91 -0
  304. package/themes/dark-twilight.json +91 -0
  305. package/themes/dark-volcanic.json +91 -0
  306. package/themes/dark.json +80 -0
  307. package/themes/graphite.json +92 -0
  308. package/themes/light-arctic.json +107 -0
  309. package/themes/light-aurora-day.json +91 -0
  310. package/themes/light-canyon.json +91 -0
  311. package/themes/light-catppuccin.json +106 -0
  312. package/themes/light-cirrus.json +90 -0
  313. package/themes/light-coral.json +95 -0
  314. package/themes/light-cyberpunk.json +96 -0
  315. package/themes/light-dawn.json +90 -0
  316. package/themes/light-dunes.json +91 -0
  317. package/themes/light-eucalyptus.json +95 -0
  318. package/themes/light-forest.json +100 -0
  319. package/themes/light-frost.json +95 -0
  320. package/themes/light-github.json +115 -0
  321. package/themes/light-glacier.json +91 -0
  322. package/themes/light-gruvbox.json +108 -0
  323. package/themes/light-haze.json +90 -0
  324. package/themes/light-honeycomb.json +95 -0
  325. package/themes/light-lagoon.json +91 -0
  326. package/themes/light-lavender.json +95 -0
  327. package/themes/light-meadow.json +91 -0
  328. package/themes/light-mint.json +95 -0
  329. package/themes/light-monochrome.json +101 -0
  330. package/themes/light-ocean.json +99 -0
  331. package/themes/light-one.json +99 -0
  332. package/themes/light-opal.json +91 -0
  333. package/themes/light-orchard.json +91 -0
  334. package/themes/light-paper.json +95 -0
  335. package/themes/light-poimandres.json +115 -0
  336. package/themes/light-prism.json +90 -0
  337. package/themes/light-retro.json +98 -0
  338. package/themes/light-sand.json +95 -0
  339. package/themes/light-savanna.json +91 -0
  340. package/themes/light-solarized.json +102 -0
  341. package/themes/light-soleil.json +90 -0
  342. package/themes/light-sunset.json +99 -0
  343. package/themes/light-synthwave.json +98 -0
  344. package/themes/light-tokyo-night.json +111 -0
  345. package/themes/light-wetland.json +91 -0
  346. package/themes/light-zenith.json +89 -0
  347. package/themes/light.json +80 -0
  348. package/themes/limestone.json +94 -0
  349. package/themes/mahogany.json +97 -0
  350. package/themes/marble.json +93 -0
  351. package/themes/mirage.json +79 -0
  352. package/themes/obsidian.json +91 -0
  353. package/themes/onyx.json +91 -0
  354. package/themes/pearl.json +93 -0
  355. package/themes/porcelain.json +91 -0
  356. package/themes/quartz.json +96 -0
  357. package/themes/sandstone.json +95 -0
  358. package/themes/titanium.json +90 -0
@@ -0,0 +1,752 @@
1
+ // ponytail: vendored from @bacnh85/pi-subagent 0.23.2 (extensions/security.ts).
2
+ // ceulen delta: the HARD lifetime cap defaults to OFF (0) and reads the
3
+ // `subagent.hardTimeoutMins` setting (0=off, 1-60 when set) instead of the
4
+ // always-on 20-min env default — a child producing events is never hard-killed;
5
+ // the idle window is the hang detector. Env override PI_SUBAGENT_HARD_TIMEOUT_MINS
6
+ // still wins for parity with the upstream package.
7
+ //
8
+ // Security and validation helpers for the subagent module.
9
+ //
10
+ // Centralizes all trust-boundary checks so that internal callers (tool handler,
11
+ // parallel executor, chain executor) cannot bypass them.
12
+
13
+ import * as fs from "node:fs";
14
+ import * as path from "node:path";
15
+
16
+ // ---------------------------------------------------------------------------
17
+ // Constants
18
+ // ---------------------------------------------------------------------------
19
+
20
+ /**
21
+ * Pi's built-in tools. Agents whose effective tool set is a subset of these
22
+ * run in the cheap lean loader (no extensions loaded). Any other tool name
23
+ * (web_search, serena_*, munin_*, …) requires loading the parent's extensions.
24
+ */
25
+ export const BUILTIN_TOOLS = [
26
+ "read",
27
+ "grep",
28
+ "find",
29
+ "ls",
30
+ "bash",
31
+ "edit",
32
+ "write",
33
+ ] as const;
34
+
35
+ /** Backwards-compatible alias. */
36
+ export const ALLOWED_CHILD_TOOLS = BUILTIN_TOOLS;
37
+
38
+ /**
39
+ * Tools never available to child agents, regardless of inheritance.
40
+ * `subagent` is the only delegation primitive today; if another extension ever
41
+ * adds a delegation/spawn tool, it must be added here too (recursion guard).
42
+ */
43
+ export const DENIED_CHILD_TOOLS = new Set(["subagent"]);
44
+
45
+ // ponytail: keep in sync with pi-plan/extensions/lib/plan-tools.ts READ_ONLY_TOOLS
46
+ // and pi-review/extensions/index.ts SAFE_REVIEW_TOOLS (additions must be mirrored).
47
+ // Used by sandbox: read-only agents to inherit the full read/research toolset
48
+ // (serena/web/munin/fff), not just the 4 built-ins — otherwise read-only research
49
+ // subagents (scout/planner/reviewer) can't use the tools plan mode tells them to prefer.
50
+ export const READ_ONLY_TOOLS: readonly string[] = [
51
+ // Built-in reads
52
+ "read", "grep", "find", "ls",
53
+ // ceulen bundle tools (read-only): fff + serena + munin + ux
54
+ "ffgrep", "fffind", "resolve_file", "fff_multi_grep", "related_files",
55
+ "serena_status", "serena_list_tools", "serena_get_current_config",
56
+ "serena_check_onboarding_performed", "serena_get_symbols_overview", "serena_find_symbol", "serena_find_declaration",
57
+ "serena_find_implementations", "serena_find_referencing_symbols",
58
+ "serena_search_for_pattern", "serena_get_diagnostics_for_file",
59
+ "munin_search", "munin_get", "munin_list", "munin_recent", "munin_capabilities",
60
+ "ux_audit",
61
+ // pi-extensions companions a ceulen child may inherit from standalone packages
62
+ "web_search", "web_extract", "web_map", "web_crawl", "web_screenshot", "web_pdf", "web_status",
63
+ "classify", "advisor",
64
+ ];
65
+ export const MUTATION_TOOLS: readonly string[] = ["edit", "write"];
66
+ export const EXECUTION_TOOLS: readonly string[] = ["bash"];
67
+
68
+ /**
69
+ * Generic warning sink for configuration problems. Stderr so it is visible
70
+ * with or without a TUI attached. Warnings are also buffered so the extension
71
+ * host can surface them as TUI notifications — the interactive TUI swallows
72
+ * module-load stderr, so module-load warnings alone are invisible in-TUI.
73
+ */
74
+ const warnings: string[] = [];
75
+ function warn(message: string): void {
76
+ process.stderr.write(`[ceulen-subagent] ${message}\n`);
77
+ warnings.push(message);
78
+ }
79
+
80
+ /**
81
+ * Flush env-var config warnings collected at module load. Called once from
82
+ * the subagent tool handler so the warnings surface as TUI notifications
83
+ * (module-load stderr is not visible inside the interactive TUI).
84
+ */
85
+ export function flushWarnings(): string[] {
86
+ return warnings.splice(0, warnings.length);
87
+ }
88
+
89
+ /**
90
+ * Read a numeric value from an env var, with validation:
91
+ * - undefined/empty -> defaultValue (no warning)
92
+ * - not a finite number (NaN) -> defaultValue + warning
93
+ * - below `min` -> `min` + warning
94
+ * - above `max` -> `max` + warning
95
+ * - otherwise -> the parsed value (no warning)
96
+ */
97
+ export function getNumericEnvVar(
98
+ envVar: string,
99
+ defaultValue: number,
100
+ min: number,
101
+ max: number,
102
+ ): number {
103
+ const raw = process.env[envVar];
104
+ if (raw === undefined || raw === "") return defaultValue;
105
+ const value = Number(raw);
106
+ if (!Number.isFinite(value)) {
107
+ warn(`ENV VAR: ${envVar}="${raw}" is not a number; using default ${defaultValue}.`);
108
+ return defaultValue;
109
+ }
110
+ if (value < min) {
111
+ warn(`ENV VAR: ${envVar}=${value} is below the minimum of ${min}; using ${min}.`);
112
+ return min;
113
+ }
114
+ if (value > max) {
115
+ warn(`ENV VAR: ${envVar}=${value} is above the maximum of ${max}; using ${max}.`);
116
+ return max;
117
+ }
118
+ return value;
119
+ }
120
+
121
+ /**
122
+ * Absolute maximum timeout. Any requested value above this cap is rejected
123
+ * at validation time rather than silently clamped.
124
+ */
125
+ export const MAX_TIMEOUT_MS = 60 * 60 * 1_000; // 60 minutes
126
+
127
+ /**
128
+ * Timeout caps, in minutes, shared by getNumericEnvVar for both env vars.
129
+ * No timeout may be shorter than 1 minute; the inactivity window may not
130
+ * exceed the 60-minute absolute maximum.
131
+ */
132
+ const MIN_TIMEOUT_MINS = 1;
133
+ const MAX_TIMEOUT_MINS = MAX_TIMEOUT_MS / 60_000;
134
+
135
+ /**
136
+ * Default inactivity timeout. Real SDK lifecycle activity resets this window;
137
+ * this is THE hang detector. Reads PI_SUBAGENT_INACTIVITY_TIMEOUT_MINS
138
+ * (default 3 min, range 1–60); the `subagent.idleTimeoutMins` setting
139
+ * overrides at resolve time (see settings.ts).
140
+ */
141
+ const INACTIVITY_TIMEOUT_MINS = getNumericEnvVar("PI_SUBAGENT_INACTIVITY_TIMEOUT_MINS", 3, MIN_TIMEOUT_MINS, MAX_TIMEOUT_MINS);
142
+
143
+ /**
144
+ * ceulen: the hard lifetime cap is OPT-IN and defaults to OFF. Upstream ran a
145
+ * 20-min always-on cap that hard-killed children mid-stream — the exact failure
146
+ * this port exists to remove. `subagent.hardTimeoutMins: 0` (default) disables
147
+ * it entirely; 1–60 enables an absolute ceiling; the env var overrides both.
148
+ */
149
+ const HARD_TIMEOUT_MINS_SETTING_DEFAULT = 0;
150
+ const hardTimeoutMins = getNumericEnvVar(
151
+ "PI_SUBAGENT_HARD_TIMEOUT_MINS",
152
+ HARD_TIMEOUT_MINS_SETTING_DEFAULT,
153
+ 0,
154
+ MAX_TIMEOUT_MINS,
155
+ );
156
+ export const DEFAULT_TIMEOUT_MS = INACTIVITY_TIMEOUT_MINS * 60 * 1_000;
157
+ /** 0 = disabled. resolveChildTimeouts treats 0 as "no cap". */
158
+ export const HARD_TIMEOUT_MS = hardTimeoutMins * 60 * 1_000;
159
+
160
+ // ---------------------------------------------------------------------------
161
+ // Canonical result status
162
+ // ---------------------------------------------------------------------------
163
+
164
+ export type SubagentStatus = "success" | "partial" | "error" | "aborted" | "timeout";
165
+
166
+ /** Pi SDK stop reasons that indicate successful completion. */
167
+ const SUCCESS_REASONS = new Set(["stop", "end_turn", "completed"]);
168
+
169
+ /** Pi SDK stop reasons that indicate a partial / truncated response. */
170
+ const PARTIAL_REASONS = new Set(["length", "max_tokens", "context_limit"]);
171
+
172
+ /** Pi SDK stop reasons that indicate a provider or tool error. */
173
+ const ERROR_REASONS = new Set([
174
+ "error",
175
+ "tool_error",
176
+ "authentication_error",
177
+ "provider_error",
178
+ "content_filter",
179
+ ]);
180
+
181
+ /**
182
+ * Map a raw stop reason string to a canonical SubagentStatus.
183
+ *
184
+ * `isAborted` and `isTimeout` take precedence because the Pi SDK may emit
185
+ * "aborted" or "error" for both cases. Callers should pass the flags derived
186
+ * from their own abort controllers.
187
+ */
188
+ export function classifyStopReason(
189
+ reason: string | undefined,
190
+ isAborted: boolean,
191
+ isTimeout: boolean,
192
+ ): SubagentStatus {
193
+ if (isAborted) return "aborted";
194
+ if (isTimeout) return "timeout";
195
+ if (!reason) return "success";
196
+ if (SUCCESS_REASONS.has(reason)) return "success";
197
+ if (PARTIAL_REASONS.has(reason)) return "partial";
198
+ if (ERROR_REASONS.has(reason)) return "error";
199
+ // Unknown stop reason — classify conservatively.
200
+ return "error";
201
+ }
202
+
203
+ // ---------------------------------------------------------------------------
204
+ // Safe working-directory resolver
205
+ // ---------------------------------------------------------------------------
206
+
207
+ export interface SafeCwdOptions {
208
+ /** The workspace root (parent session's cwd). Must be an absolute path. */
209
+ workspaceRoot: string;
210
+ /** The child's requested working directory, if any. */
211
+ childCwd?: string;
212
+ /**
213
+ * Trusted user setting that allows child cwd outside the workspace.
214
+ * Must never come from the tool-calling model.
215
+ */
216
+ allowExternalCwd?: boolean;
217
+ }
218
+
219
+ export interface SafeCwdResult {
220
+ path: string;
221
+ error?: string;
222
+ }
223
+
224
+ /**
225
+ * Resolve a child working directory that is guaranteed to be inside the
226
+ * workspace root.
227
+ *
228
+ * Rules:
229
+ * - No childCwd → return workspaceRoot.
230
+ * - Relative paths are resolved relative to workspaceRoot.
231
+ * - Absolute paths outside workspaceRoot are rejected unless allowExternalCwd.
232
+ * - `..` traversal that escapes workspaceRoot is rejected.
233
+ * - Symlinks are resolved via realpath and checked against workspaceRoot.
234
+ * - Non-existent directories are rejected.
235
+ * - Paths that are files instead of directories are rejected.
236
+ */
237
+ export function resolveSafeCwd(options: SafeCwdOptions): SafeCwdResult {
238
+ const { workspaceRoot, childCwd, allowExternalCwd } = options;
239
+
240
+ // Normalise workspace root to an absolute canonical path.
241
+ const resolvedRoot = resolveCanonical(workspaceRoot);
242
+ if (!resolvedRoot) {
243
+ return { path: "", error: `Workspace root does not exist: ${workspaceRoot}` };
244
+ }
245
+ if (!isDirectorySync(resolvedRoot)) {
246
+ return { path: "", error: `Workspace root is not a directory: ${workspaceRoot}` };
247
+ }
248
+
249
+ // No child cwd → use workspace root.
250
+ if (!childCwd) {
251
+ return { path: resolvedRoot };
252
+ }
253
+
254
+ // Resolve the child path.
255
+ const absPath = path.resolve(resolvedRoot, childCwd);
256
+
257
+ // If the resolved path escapes the workspace via `..`, the resolved path
258
+ // will differ from the canonical workspace root prefix. We check by
259
+ // resolving the canonical absolute path.
260
+ const canonicalPath = resolveCanonical(absPath);
261
+ if (!canonicalPath) {
262
+ return { path: "", error: `Child working directory does not exist: ${childCwd}` };
263
+ }
264
+
265
+ if (!isDirectorySync(canonicalPath)) {
266
+ return { path: "", error: `Child working directory is a file, not a directory: ${childCwd}` };
267
+ }
268
+
269
+ // Check if the child path is inside the workspace.
270
+ if (!isPathInside(canonicalPath, resolvedRoot)) {
271
+ if (allowExternalCwd) {
272
+ return { path: canonicalPath };
273
+ }
274
+ return {
275
+ path: "",
276
+ error:
277
+ `Child working directory "${childCwd}" is outside the workspace root "${workspaceRoot}". ` +
278
+ `Paths outside the workspace are rejected by default.`,
279
+ };
280
+ }
281
+
282
+ return { path: canonicalPath };
283
+ }
284
+
285
+ /**
286
+ * Check if `child` is inside `parent` or equal to it, after resolving both
287
+ * to canonical paths. Rejects `..` traversal that escapes `parent`.
288
+ */
289
+ function isPathInside(child: string, parent: string): boolean {
290
+ // Both must be absolute.
291
+ if (!path.isAbsolute(child) || !path.isAbsolute(parent)) return false;
292
+
293
+ const relative = path.relative(parent, child);
294
+ // relative must not start with ".." and must not be an absolute path.
295
+ return !relative.startsWith("..") && !path.isAbsolute(relative);
296
+ }
297
+
298
+ /**
299
+ * Resolve a path to its canonical real path, or return null if it doesn't exist.
300
+ */
301
+ function resolveCanonical(p: string): string | null {
302
+ try {
303
+ return fs.realpathSync(p);
304
+ } catch {
305
+ return null;
306
+ }
307
+ }
308
+
309
+ /**
310
+ * Synchronously check if a path is a directory.
311
+ */
312
+ function isDirectorySync(p: string): boolean {
313
+ try {
314
+ return fs.statSync(p).isDirectory();
315
+ } catch {
316
+ return false;
317
+ }
318
+ }
319
+
320
+ // ---------------------------------------------------------------------------
321
+ // Tool allowlist validation
322
+ // ---------------------------------------------------------------------------
323
+
324
+ export interface ValidateToolsOptions {
325
+ /** Tool names from the agent definition or service override. */
326
+ tools: string[];
327
+ /** When true, only read-only tools are permitted. Mutation/execution tools are rejected. */
328
+ readOnly?: boolean;
329
+ /**
330
+ * Parent session's registered tool names. When provided, a tool is accepted if
331
+ * it is a built-in OR in this set (and not in DENIED_CHILD_TOOLS) — this is
332
+ * how children inherit extension tools (web, serena, munin, …). When omitted,
333
+ * only BUILTIN_TOOLS are accepted (lean/legacy mode).
334
+ * Callers must pass a stable snapshot and not mutate it afterwards.
335
+ */
336
+ availableTools?: readonly string[];
337
+ }
338
+
339
+ export interface ValidateToolsResult {
340
+ /** Deduplicated and validated tool names. */
341
+ tools: string[];
342
+ /** Validation errors, if any. Empty array means valid. */
343
+ errors: string[];
344
+ }
345
+
346
+ /**
347
+ * Whether a tool set contains any extension tool (non-built-in). When true the
348
+ * runner loads the parent's extensions into the child; when false it uses the
349
+ * lean empty-loader stub, saving system-prompt tokens. Recon agents with an
350
+ * explicit built-in-only `tools` line stay cheap automatically.
351
+ */
352
+ export function needsExtensions(tools: readonly string[]): boolean {
353
+ const builtins = new Set<string>(BUILTIN_TOOLS);
354
+ return tools.some((t) => !builtins.has(t));
355
+ }
356
+
357
+ export function validateAgentTools(options: ValidateToolsOptions): ValidateToolsResult {
358
+ const { readOnly = false, availableTools } = options;
359
+ const extensionTools = availableTools ? new Set(availableTools) : undefined;
360
+ const seen = new Set<string>();
361
+ const tools: string[] = [];
362
+ const errors: string[] = [];
363
+
364
+ for (const raw of options.tools) {
365
+ const tool = raw.trim();
366
+ if (!tool) continue;
367
+
368
+ // Silently strip denied tools (e.g. "subagent") regardless of casing. They
369
+ // are never available to children — whether explicitly listed in an agent's
370
+ // `tools:` line or inherited via parentToolNames. This matches Claude Code,
371
+ // which removes denied tools from subagents "even when listed in the tools
372
+ // field". No error: inheritance must not crash on a tool the child can't have.
373
+ if (DENIED_CHILD_TOOLS.has(tool.toLowerCase())) {
374
+ continue;
375
+ }
376
+
377
+ // Check against allowlist: built-ins, plus inherited extension tools when availableTools given.
378
+ const isBuiltin = BUILTIN_TOOLS.includes(tool as any);
379
+ const isExtension = extensionTools?.has(tool) ?? false;
380
+ if (!isBuiltin && !isExtension) {
381
+ const allowed = extensionTools
382
+ ? "parent tools"
383
+ : BUILTIN_TOOLS.join(", ");
384
+ errors.push(`Unknown tool "${tool}". Allowed tools: ${allowed}.`);
385
+ continue;
386
+ }
387
+
388
+ // Check read-only constraint
389
+ if (readOnly && !READ_ONLY_TOOLS.includes(tool)) {
390
+ errors.push(
391
+ `Tool "${tool}" is not allowed in read-only mode. Read-only tools: ${READ_ONLY_TOOLS.join(", ")}.`,
392
+ );
393
+ continue;
394
+ }
395
+
396
+ // Deduplicate
397
+ if (seen.has(tool)) continue;
398
+ seen.add(tool);
399
+ tools.push(tool);
400
+ }
401
+
402
+ return { tools, errors };
403
+ }
404
+
405
+ // ---------------------------------------------------------------------------
406
+ // Timeout validation
407
+ // ---------------------------------------------------------------------------
408
+
409
+ export interface NormalizeTimeoutOptions {
410
+ /** Requested timeout value from tool params, if any. */
411
+ requested?: number;
412
+ /** Global default when no timeout is specified. */
413
+ defaultValue?: number;
414
+ /** Absolute maximum allowed value. */
415
+ maxValue?: number;
416
+ }
417
+
418
+ export interface NormalizeTimeoutResult {
419
+ /** The validated timeout in milliseconds, or undefined if none was set and no default applies. */
420
+ timeoutMs: number | undefined;
421
+ /** Error message if the value is invalid. */
422
+ error?: string;
423
+ }
424
+
425
+ /**
426
+ * Validate and normalise a timeout value.
427
+ *
428
+ * Rules:
429
+ * - Must be a finite integer if provided.
430
+ * - Must be positive (> 0).
431
+ * - Must not exceed maxValue.
432
+ * - If no value is provided, defaultValue is used.
433
+ * - Returns undefined only when no value and no default is configured.
434
+ */
435
+ export function normalizeTimeout(options: NormalizeTimeoutOptions): NormalizeTimeoutResult {
436
+ const { requested, defaultValue = DEFAULT_TIMEOUT_MS, maxValue = MAX_TIMEOUT_MS } = options;
437
+
438
+ if (requested === undefined || requested === null) {
439
+ // No explicit timeout — apply default.
440
+ return { timeoutMs: defaultValue };
441
+ }
442
+
443
+ if (typeof requested !== "number" || !Number.isFinite(requested)) {
444
+ return { timeoutMs: undefined, error: "Timeout must be a finite number." };
445
+ }
446
+
447
+ if (!Number.isInteger(requested)) {
448
+ return { timeoutMs: undefined, error: "Timeout must be an integer (milliseconds)." };
449
+ }
450
+
451
+ if (requested <= 0) {
452
+ return { timeoutMs: undefined, error: "Timeout must be a positive integer." };
453
+ }
454
+
455
+ if (requested > maxValue) {
456
+ return {
457
+ timeoutMs: undefined,
458
+ error: `Timeout ${requested}ms exceeds maximum allowed ${maxValue}ms (${maxValue / 60_000} minutes).`,
459
+ };
460
+ }
461
+
462
+ return { timeoutMs: requested };
463
+ }
464
+
465
+ // ---------------------------------------------------------------------------
466
+ // Child timeout resolution (shared by the tool path)
467
+ // ---------------------------------------------------------------------------
468
+
469
+ export interface ResolveChildTimeoutsOptions {
470
+ /** Per-call timeout in ms (tool `timeout` param). */
471
+ requested?: number;
472
+ /** Agent frontmatter `timeout:` in minutes. */
473
+ agentTimeoutMins?: number;
474
+ /** Caller-wide timeout in ms, used when nothing more specific is set. */
475
+ globalTimeout?: number;
476
+ /**
477
+ * Hard lifetime cap in minutes from settings/env; 0 or undefined = no cap.
478
+ * ceulen delta: 0 disables the cap (upstream had no off switch).
479
+ */
480
+ hardTimeoutMins?: number;
481
+ }
482
+
483
+ export interface ResolveChildTimeoutsResult {
484
+ /** Idle (inactivity) timeout in ms for the child run. */
485
+ timeoutMs?: number;
486
+ /** Hard lifetime cap in ms; undefined = no cap. Never shorter than the idle window when set. */
487
+ hardTimeoutMs?: number;
488
+ /** Error message if the value is invalid. */
489
+ error?: string;
490
+ }
491
+
492
+ /**
493
+ * Resolve a child run's effective timeouts — the single resolver shared by the
494
+ * tool path and the herdr path.
495
+ *
496
+ * Precedence: per-call timeout > agent frontmatter `timeout:` > global/caller
497
+ * timeout. The idle window IS the hang detector (every SDK event resets it).
498
+ * When the hard cap is enabled (hardTimeoutMins > 0), it is clamped up to the
499
+ * idle window — a lifetime cap smaller than the idle window is nonsensical.
500
+ * 0/undefined ⇒ undefined: a child producing events is never hard-killed.
501
+ */
502
+ export function resolveChildTimeouts(options: ResolveChildTimeoutsOptions): ResolveChildTimeoutsResult {
503
+ const agentMs = options.agentTimeoutMins ? options.agentTimeoutMins * 60_000 : undefined;
504
+ const result = normalizeTimeout({ requested: options.requested ?? agentMs ?? options.globalTimeout });
505
+ if (result.error) return { error: result.error };
506
+ const capMins = options.hardTimeoutMins ?? 0;
507
+ if (capMins <= 0) return { timeoutMs: result.timeoutMs, hardTimeoutMs: undefined };
508
+ return {
509
+ timeoutMs: result.timeoutMs,
510
+ hardTimeoutMs: Math.max(capMins * 60_000, result.timeoutMs ?? 0),
511
+ };
512
+ }
513
+
514
+ // ---------------------------------------------------------------------------
515
+ // Abort signal composition
516
+ // ---------------------------------------------------------------------------
517
+
518
+ /**
519
+ * Combine multiple abort signals into one, with correct listener cleanup.
520
+ *
521
+ * Works as a polyfill for AbortSignal.any() with proper cleanup semantics:
522
+ * - If any input signal is already aborted, the returned signal aborts immediately.
523
+ * - All event listeners are removed after the first abort or when `cleanup()` is called.
524
+ *
525
+ * Returns an object with the combined signal and a cleanup function.
526
+ * Callers MUST call `cleanup()` in a `finally` block.
527
+ */
528
+ export function createCombinedAbortSignal(
529
+ signals: (AbortSignal | undefined | null | false)[],
530
+ ): { signal: AbortSignal; cleanup: () => void } {
531
+ const valid = signals.filter(Boolean) as AbortSignal[];
532
+
533
+ if (valid.length === 0) {
534
+ const controller = new AbortController();
535
+ return { signal: controller.signal, cleanup: () => {} };
536
+ }
537
+
538
+ if (valid.length === 1) {
539
+ return { signal: valid[0], cleanup: () => {} };
540
+ }
541
+
542
+ // Check if any is already aborted.
543
+ for (const sig of valid) {
544
+ if (sig.aborted) {
545
+ const controller = new AbortController();
546
+ controller.abort(sig.reason);
547
+ return { signal: controller.signal, cleanup: () => {} };
548
+ }
549
+ }
550
+
551
+ // Use native AbortSignal.any when available.
552
+ if (typeof (AbortSignal as any).any === "function") {
553
+ const combined = (AbortSignal as any).any(valid);
554
+ return { signal: combined, cleanup: () => {} };
555
+ }
556
+
557
+ // Manual fallback: create a controller and forward all signals.
558
+ const controller = new AbortController();
559
+ const listeners: Array<() => void> = [];
560
+
561
+ for (const sig of valid) {
562
+ const handler = () => {
563
+ controller.abort(sig.reason);
564
+ };
565
+ sig.addEventListener("abort", handler, { once: true });
566
+ listeners.push(() => sig.removeEventListener("abort", handler));
567
+ }
568
+
569
+ const cleanup = () => {
570
+ for (const remove of listeners) {
571
+ try {
572
+ remove();
573
+ } catch {
574
+ // Best-effort cleanup.
575
+ }
576
+ }
577
+ };
578
+
579
+ return { signal: controller.signal, cleanup };
580
+ }
581
+
582
+ // ---------------------------------------------------------------------------
583
+ // Execution request validation
584
+ // ---------------------------------------------------------------------------
585
+
586
+ export const MAX_PARALLEL_TASKS = 8;
587
+ export const MAX_CONCURRENCY = 4;
588
+ export const MAX_CHAIN_LENGTH = 50;
589
+ export const PER_TASK_OUTPUT_CAP = 50 * 1024; // 50 KB
590
+ export const MAX_INSTRUCTIONS_LENGTH = 16 * 1024; // 16 KB
591
+
592
+ export interface ValidateExecutionRequestOptions {
593
+ agentName?: string;
594
+ task?: string;
595
+ tasks?: unknown[];
596
+ chain?: unknown[];
597
+ timeout?: number;
598
+ }
599
+
600
+ export interface ValidationError {
601
+ field: string;
602
+ message: string;
603
+ }
604
+
605
+ /**
606
+ * Generic validation for execution requests.
607
+ * Enforces limits that TypeBox schemas may not cover.
608
+ */
609
+ export function validateExecutionRequest(
610
+ options: ValidateExecutionRequestOptions,
611
+ ): ValidationError[] {
612
+ const errors: ValidationError[] = [];
613
+
614
+ // Timeout (single/parallel/chain share one requested timeout)
615
+ if (options.timeout !== undefined) {
616
+ const t = normalizeTimeout({ requested: options.timeout });
617
+ if (t.error) {
618
+ errors.push({ field: "timeout", message: t.error });
619
+ }
620
+ }
621
+
622
+ // Agent name
623
+ if (options.agentName !== undefined) {
624
+ if (typeof options.agentName !== "string" || options.agentName.trim().length === 0) {
625
+ errors.push({ field: "agent", message: "Agent name must be a non-empty string." });
626
+ }
627
+ }
628
+
629
+ // Task
630
+ if (options.task !== undefined) {
631
+ if (typeof options.task !== "string") {
632
+ errors.push({ field: "task", message: "Task must be a string." });
633
+ }
634
+ }
635
+
636
+ // Parallel tasks
637
+ if (options.tasks !== undefined) {
638
+ if (!Array.isArray(options.tasks)) {
639
+ errors.push({ field: "tasks", message: "Tasks must be an array." });
640
+ } else {
641
+ if (options.tasks.length > MAX_PARALLEL_TASKS) {
642
+ errors.push({
643
+ field: "tasks",
644
+ message: `Too many parallel tasks (${options.tasks.length}). Maximum is ${MAX_PARALLEL_TASKS}.`,
645
+ });
646
+ }
647
+ for (let i = 0; i < options.tasks.length; i++) {
648
+ const t = options.tasks[i] as Record<string, unknown>;
649
+ if (!t || typeof t.agent !== "string" || !t.agent.trim()) {
650
+ errors.push({ field: `tasks[${i}].agent`, message: "Agent name must be a non-empty string." });
651
+ }
652
+ if (typeof t.task !== "string") {
653
+ errors.push({ field: `tasks[${i}].task`, message: "Task must be a string." });
654
+ }
655
+ }
656
+ }
657
+ }
658
+
659
+ // Chain
660
+ if (options.chain !== undefined) {
661
+ if (!Array.isArray(options.chain)) {
662
+ errors.push({ field: "chain", message: "Chain must be an array." });
663
+ } else {
664
+ if (options.chain.length > MAX_CHAIN_LENGTH) {
665
+ errors.push({
666
+ field: "chain",
667
+ message: `Too many chain steps (${options.chain.length}). Maximum is ${MAX_CHAIN_LENGTH}.`,
668
+ });
669
+ }
670
+ for (let i = 0; i < options.chain.length; i++) {
671
+ const s = options.chain[i] as Record<string, unknown>;
672
+ if (!s || typeof s.agent !== "string" || !s.agent.trim()) {
673
+ errors.push({ field: `chain[${i}].agent`, message: "Agent name must be a non-empty string." });
674
+ }
675
+ if (typeof s.task !== "string") {
676
+ errors.push({ field: `chain[${i}].task`, message: "Task must be a string." });
677
+ }
678
+ }
679
+ }
680
+ }
681
+
682
+ return errors;
683
+ }
684
+
685
+ /**
686
+ * Truncate parallel task output to the per-task cap.
687
+ */
688
+ export function truncateParallelOutput(output: string): string {
689
+ const byteLength = Buffer.byteLength(output, "utf8");
690
+ if (byteLength <= PER_TASK_OUTPUT_CAP) return output;
691
+
692
+ let truncated = output.slice(0, PER_TASK_OUTPUT_CAP);
693
+ while (Buffer.byteLength(truncated, "utf8") > PER_TASK_OUTPUT_CAP) {
694
+ truncated = truncated.slice(0, -1);
695
+ }
696
+ return `${truncated}\n\n[Output truncated: ${byteLength - Buffer.byteLength(truncated, "utf8")} bytes omitted.]`;
697
+ }
698
+
699
+ // ---------------------------------------------------------------------------
700
+ // Rate-limit error detection
701
+ // ---------------------------------------------------------------------------
702
+
703
+ const RATE_LIMIT_PATTERNS = [
704
+ /\b429\b/,
705
+ /\b529\b/,
706
+ /rate[\s_]limit/i,
707
+ /ratelimit/i,
708
+ /too[\s_]many[\s_]requests/i,
709
+ /quota[\s_]exhausted/i,
710
+ /quota[\s_]exceeded/i,
711
+ /exceeded[\s_](?:your[\s_])?(?:current[\s_])?quota/i,
712
+ /insufficient_quota/i,
713
+ /resource[\s_]exhausted/i,
714
+ /capacity[\s_]exceeded/i,
715
+ /usage[\s_]limit/i,
716
+ /overloaded/i,
717
+ // Credential-cooldown errors (e.g. "All credentials for model X are
718
+ // cooling down") are capacity signals too: the model may be unavailable
719
+ // NOW but the next fallback candidate may not be in cooldown.
720
+ /credential[\s_]cooldown|cooldown[\s_]window|cooling[\s_]down/i,
721
+ ];
722
+
723
+ /**
724
+ * Check if an error message indicates a rate-limit / quota-exhaustion condition.
725
+ *
726
+ * Used by the sub-agent runtime to trigger automatic model fallback when the
727
+ * primary model candidate hits a 429 or similar server-side capacity error.
728
+ */
729
+ export function isRateLimitError(message: string): boolean {
730
+ return RATE_LIMIT_PATTERNS.some(p => p.test(message));
731
+ }
732
+
733
+ /**
734
+ * Whether a sub-agent result should trigger model fallback: a rate-limit /
735
+ * credential-cooldown error, or an IDLE timeout (a stalled stream with zero
736
+ * events for the whole idle window — a known router/provider failure mode).
737
+ * The HARD lifetime cap is terminal: a task that ran long while producing
738
+ * events is genuinely huge, not a stall, and retrying it on another model
739
+ * doubles the cost.
740
+ */
741
+ export function isRetryableModelResult(result: {
742
+ errorMessage?: string;
743
+ stopReason?: string;
744
+ status?: string;
745
+ }): boolean {
746
+ if (result.errorMessage && isRateLimitError(result.errorMessage)) return true;
747
+ return (
748
+ result.stopReason === "timeout" &&
749
+ result.status === "timeout" &&
750
+ !String(result.errorMessage ?? "").includes("Hard timeout")
751
+ );
752
+ }