ceulen 0.5.1 → 0.8.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 (367) hide show
  1. package/CHANGELOG.md +365 -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.test.ts +67 -0
  7. package/extensions/lib/registry.ts +104 -8
  8. package/extensions/lib/tools.ts +47 -0
  9. package/extensions/lib/usage-store.ts +33 -0
  10. package/extensions/modules/advisor/commands/advisor.ts +244 -0
  11. package/extensions/modules/advisor/configPanel.ts +194 -0
  12. package/extensions/modules/advisor/index.ts +235 -0
  13. package/extensions/modules/advisor/lib/config.ts +248 -0
  14. package/extensions/modules/advisor/lib/emission-guard.ts +153 -0
  15. package/extensions/modules/advisor/lib/isolated-model.ts +160 -0
  16. package/extensions/modules/advisor/lib/model-picker.ts +47 -0
  17. package/extensions/modules/advisor/lib/watcher.ts +288 -0
  18. package/extensions/modules/advisor/test/compliance.test.ts +125 -0
  19. package/extensions/modules/advisor/test/config.test.ts +202 -0
  20. package/extensions/modules/advisor/test/configPanel.test.ts +223 -0
  21. package/extensions/modules/advisor/test/emission-guard.test.ts +201 -0
  22. package/extensions/modules/advisor/test/isolated-model.test.ts +311 -0
  23. package/extensions/modules/advisor/test/model-picker.test.ts +32 -0
  24. package/extensions/modules/advisor/test/module.test.ts +649 -0
  25. package/extensions/modules/advisor/test/watcher.test.ts +478 -0
  26. package/extensions/modules/classifier/configPanel.ts +104 -0
  27. package/extensions/modules/classifier/index.ts +297 -0
  28. package/extensions/modules/classifier/lib/settings.ts +95 -0
  29. package/extensions/modules/classifier/test/classifier.test.ts +475 -0
  30. package/extensions/modules/composer/index.ts +152 -3
  31. package/extensions/modules/composer/lib/footer.ts +119 -0
  32. package/extensions/modules/composer/lib/shapes.ts +265 -26
  33. package/extensions/modules/composer/test/editor.test.ts +1 -1
  34. package/extensions/modules/composer/test/footer.test.ts +96 -0
  35. package/extensions/modules/composer/test/module.test.ts +113 -11
  36. package/extensions/modules/composer/test/screen.test.ts +29 -1
  37. package/extensions/modules/composer/test/shapes.test.ts +224 -8
  38. package/extensions/modules/config/defaultTools.ts +96 -0
  39. package/extensions/modules/config/index.ts +147 -7
  40. package/extensions/modules/config/piSettings.ts +254 -69
  41. package/extensions/modules/config/test/defaultTools.test.ts +122 -0
  42. package/extensions/modules/config/test/menu.test.ts +64 -0
  43. package/extensions/modules/config/test/panel.test.ts +38 -23
  44. package/extensions/modules/config/test/piSettings.test.ts +130 -3
  45. package/extensions/modules/config/test/renderTools.test.ts +71 -0
  46. package/extensions/modules/config/test/tools.test.ts +146 -0
  47. package/extensions/modules/fff/index.ts +2094 -0
  48. package/extensions/modules/fff/lib/query.ts +129 -0
  49. package/extensions/modules/fff/test/index.test.ts +607 -0
  50. package/extensions/modules/fff/test/query.test.ts +71 -0
  51. package/extensions/modules/munin/configPanel.ts +108 -0
  52. package/extensions/modules/munin/index.ts +641 -0
  53. package/extensions/modules/munin/lib/helpers.ts +471 -0
  54. package/extensions/modules/munin/lib/retry.ts +20 -0
  55. package/extensions/modules/munin/lib/sdk.ts +218 -0
  56. package/extensions/modules/munin/test/config.test.ts +168 -0
  57. package/extensions/modules/munin/test/configPanel.test.ts +186 -0
  58. package/extensions/modules/munin/test/extension.test.ts +224 -0
  59. package/extensions/modules/munin/test/helpers.test.ts +523 -0
  60. package/extensions/modules/munin/test/retry.test.ts +145 -0
  61. package/extensions/modules/munin/test/stale-protocol.test.ts +554 -0
  62. package/extensions/modules/plan/configPanel.ts +152 -0
  63. package/extensions/modules/plan/index.ts +917 -0
  64. package/extensions/modules/plan/lib/plan-tools.ts +72 -0
  65. package/extensions/modules/plan/lib/prompt.ts +65 -0
  66. package/extensions/modules/plan/lib/settings.ts +166 -0
  67. package/extensions/modules/plan/lib/shell-gate.ts +200 -0
  68. package/extensions/modules/plan/test/configPanel.test.ts +96 -0
  69. package/extensions/modules/plan/test/harness.ts +133 -0
  70. package/extensions/modules/plan/test/module.test.ts +305 -0
  71. package/extensions/modules/plan/test/settings.test.ts +114 -0
  72. package/extensions/modules/plan/test/shell-gate.test.ts +103 -0
  73. package/extensions/modules/ponytail/index.ts +23 -73
  74. package/extensions/modules/ponytail/lib/config.ts +1 -6
  75. package/extensions/modules/ponytail/test/extension.test.ts +1 -85
  76. package/extensions/modules/repair/configPanel.ts +96 -0
  77. package/extensions/modules/repair/index.ts +414 -0
  78. package/extensions/modules/repair/lib/auto-bg.ts +333 -0
  79. package/extensions/modules/repair/lib/edit-repair.ts +155 -0
  80. package/extensions/modules/repair/lib/editor.ts +251 -0
  81. package/extensions/modules/repair/lib/guards.ts +34 -0
  82. package/extensions/modules/repair/lib/input-repair.ts +324 -0
  83. package/extensions/modules/repair/lib/patch.ts +481 -0
  84. package/extensions/modules/repair/lib/settings.ts +114 -0
  85. package/extensions/modules/repair/test/auto-bg.test.ts +405 -0
  86. package/extensions/modules/repair/test/edit-repair.test.ts +224 -0
  87. package/extensions/modules/repair/test/editor.test.ts +141 -0
  88. package/extensions/modules/repair/test/guards.test.ts +64 -0
  89. package/extensions/modules/repair/test/input-repair.test.ts +231 -0
  90. package/extensions/modules/repair/test/patch.test.ts +563 -0
  91. package/extensions/modules/repair/test/settings.test.ts +167 -0
  92. package/extensions/modules/repair/test/wrapper.test.ts +210 -0
  93. package/extensions/modules/router/commands/commands.ts +4 -0
  94. package/extensions/modules/router/configPanel.ts +24 -10
  95. package/extensions/modules/router/lib/client.ts +63 -0
  96. package/extensions/modules/router/lib/provider.ts +34 -13
  97. package/extensions/modules/router/lib/systemone.ts +152 -0
  98. package/extensions/modules/router/test/unit.test.ts +260 -0
  99. package/extensions/modules/rtk/findFallback.js +68 -0
  100. package/extensions/modules/rtk/index.ts +248 -0
  101. package/extensions/modules/rtk/safe-rewrite.js +74 -0
  102. package/extensions/modules/rtk/test/findFallback.test.js +66 -0
  103. package/extensions/modules/rtk/test/index.test.js +131 -0
  104. package/extensions/modules/rtk/test/safe-rewrite.test.js +96 -0
  105. package/extensions/modules/rtk/version-gate.js +34 -0
  106. package/extensions/modules/rules/index.ts +120 -0
  107. package/extensions/modules/rules/lib/rules.ts +348 -0
  108. package/extensions/modules/rules/test/lib.test.ts +263 -0
  109. package/extensions/modules/rules/test/module.test.ts +222 -0
  110. package/extensions/modules/serena/index.ts +629 -0
  111. package/extensions/modules/serena/lib/detect.ts +73 -0
  112. package/extensions/modules/serena/lib/env.ts +76 -0
  113. package/extensions/modules/serena/lib/guidance.ts +26 -0
  114. package/extensions/modules/serena/lib/normalize.ts +27 -0
  115. package/extensions/modules/serena/lib/symbol-key.ts +20 -0
  116. package/extensions/modules/serena/lib/truncate.ts +20 -0
  117. package/extensions/modules/serena/test/env.test.ts +122 -0
  118. package/extensions/modules/serena/test/index.test.ts +347 -0
  119. package/extensions/modules/serena/test/worker.test.ts +562 -0
  120. package/extensions/modules/serena/worker.ts +858 -0
  121. package/extensions/modules/steering/configPanel.ts +122 -0
  122. package/extensions/modules/steering/index.ts +616 -0
  123. package/extensions/modules/steering/lib/anchor.ts +175 -0
  124. package/extensions/modules/steering/lib/errors.ts +253 -0
  125. package/extensions/modules/steering/lib/family.ts +33 -0
  126. package/extensions/modules/steering/lib/guidance.ts +172 -0
  127. package/extensions/modules/steering/lib/history.ts +170 -0
  128. package/extensions/modules/steering/lib/settings.ts +127 -0
  129. package/extensions/modules/steering/test/anchor-regressions.test.ts +93 -0
  130. package/extensions/modules/steering/test/anchor-wiring.test.ts +99 -0
  131. package/extensions/modules/steering/test/anchor.test.ts +160 -0
  132. package/extensions/modules/steering/test/cache-stats.test.ts +43 -0
  133. package/extensions/modules/steering/test/errors.test.ts +309 -0
  134. package/extensions/modules/steering/test/family.test.ts +43 -0
  135. package/extensions/modules/steering/test/guidance.test.ts +357 -0
  136. package/extensions/modules/steering/test/harness.ts +93 -0
  137. package/extensions/modules/steering/test/history.test.ts +118 -0
  138. package/extensions/modules/steering/test/settings.test.ts +182 -0
  139. package/extensions/modules/steering/test/status.test.ts +71 -0
  140. package/extensions/modules/steering/test/toolCall.test.ts +99 -0
  141. package/extensions/modules/subagent/agents/planner.md +14 -0
  142. package/extensions/modules/subagent/agents/reviewer.md +42 -0
  143. package/extensions/modules/subagent/agents/scout.md +47 -0
  144. package/extensions/modules/subagent/agents/tester.md +12 -0
  145. package/extensions/modules/subagent/agents/worker.md +18 -0
  146. package/extensions/modules/subagent/configPanel.ts +219 -0
  147. package/extensions/modules/subagent/index.ts +2464 -0
  148. package/extensions/modules/subagent/lib/agents.ts +408 -0
  149. package/extensions/modules/subagent/lib/background.ts +383 -0
  150. package/extensions/modules/subagent/lib/herdr.ts +1019 -0
  151. package/extensions/modules/subagent/lib/history.ts +126 -0
  152. package/extensions/modules/subagent/lib/model.ts +156 -0
  153. package/extensions/modules/subagent/lib/render.ts +335 -0
  154. package/extensions/modules/subagent/lib/result.ts +110 -0
  155. package/extensions/modules/subagent/lib/roles.ts +296 -0
  156. package/extensions/modules/subagent/lib/routing.ts +228 -0
  157. package/extensions/modules/subagent/lib/runner.ts +559 -0
  158. package/extensions/modules/subagent/lib/schema.ts +21 -0
  159. package/extensions/modules/subagent/lib/security.ts +763 -0
  160. package/extensions/modules/subagent/lib/settings.ts +159 -0
  161. package/extensions/modules/subagent/lib/thread-viewer.ts +319 -0
  162. package/extensions/modules/subagent/lib/threads.ts +135 -0
  163. package/extensions/modules/subagent/lib/types.ts +18 -0
  164. package/extensions/modules/subagent/lib/widget.ts +475 -0
  165. package/extensions/modules/subagent/test/configPanel.test.ts +132 -0
  166. package/extensions/modules/subagent/test/herdr-advisor.test.ts +40 -0
  167. package/extensions/modules/subagent/test/routing.test.ts +524 -0
  168. package/extensions/modules/subagent/test/widget.test.ts +208 -0
  169. package/extensions/modules/todo/index.ts +478 -0
  170. package/extensions/modules/todo/test/todo.test.ts +252 -0
  171. package/extensions/modules/usage/index.ts +70 -16
  172. package/extensions/modules/usage/test/genrate.test.ts +70 -0
  173. package/extensions/modules/usage/test/parsers.test.ts +13 -0
  174. package/extensions/modules/usage/test/session-accumulators.test.ts +85 -0
  175. package/extensions/modules/ux/UPSTREAM +24 -0
  176. package/extensions/modules/ux/index.ts +393 -0
  177. package/extensions/modules/ux/lib/audit.ts +562 -0
  178. package/extensions/modules/ux/lib/config.ts +136 -0
  179. package/extensions/modules/ux/lib/instructions.ts +77 -0
  180. package/extensions/modules/ux/test/audit.test.ts +756 -0
  181. package/extensions/modules/ux/test/extension.test.ts +394 -0
  182. package/extensions/modules/ux/test/instructions.test.ts +19 -0
  183. package/extensions/modules/web/configPanel.ts +218 -0
  184. package/extensions/modules/web/index.ts +978 -0
  185. package/extensions/modules/web/lib/agy.ts +209 -0
  186. package/extensions/modules/web/lib/brave.ts +42 -0
  187. package/extensions/modules/web/lib/cdp.ts +686 -0
  188. package/extensions/modules/web/lib/chatapi.ts +101 -0
  189. package/extensions/modules/web/lib/chatgpt.ts +796 -0
  190. package/extensions/modules/web/lib/chrome.ts +328 -0
  191. package/extensions/modules/web/lib/config.ts +136 -0
  192. package/extensions/modules/web/lib/content.ts +99 -0
  193. package/extensions/modules/web/lib/crawl4ai.ts +172 -0
  194. package/extensions/modules/web/lib/extract.ts +235 -0
  195. package/extensions/modules/web/lib/firecrawl.ts +56 -0
  196. package/extensions/modules/web/lib/format.ts +197 -0
  197. package/extensions/modules/web/lib/gemini-auth.ts +286 -0
  198. package/extensions/modules/web/lib/gemini-dr.ts +338 -0
  199. package/extensions/modules/web/lib/gemini.ts +551 -0
  200. package/extensions/modules/web/lib/imageapi.ts +559 -0
  201. package/extensions/modules/web/lib/retry.ts +71 -0
  202. package/extensions/modules/web/lib/search.ts +237 -0
  203. package/extensions/modules/web/lib/searxng.ts +69 -0
  204. package/extensions/modules/web/lib/settings.ts +157 -0
  205. package/extensions/modules/web/scripts/cdp-smoke.ts +77 -0
  206. package/extensions/modules/web/scripts/gemini-smoke.ts +107 -0
  207. package/extensions/modules/web/test/agy.test.ts +383 -0
  208. package/extensions/modules/web/test/cdp.test.ts +717 -0
  209. package/extensions/modules/web/test/chat.test.ts +171 -0
  210. package/extensions/modules/web/test/chatgpt.test.ts +633 -0
  211. package/extensions/modules/web/test/chrome.test.ts +282 -0
  212. package/extensions/modules/web/test/config.test.ts +218 -0
  213. package/extensions/modules/web/test/configPanel.test.ts +198 -0
  214. package/extensions/modules/web/test/crawl.test.ts +134 -0
  215. package/extensions/modules/web/test/crawl4ai.test.ts +105 -0
  216. package/extensions/modules/web/test/extension.test.ts +118 -0
  217. package/extensions/modules/web/test/extract.test.ts +436 -0
  218. package/extensions/modules/web/test/fixtures/dr-confirm.bin +12 -0
  219. package/extensions/modules/web/test/fixtures/dr-plan.bin +20 -0
  220. package/extensions/modules/web/test/fixtures/interaction.html +31 -0
  221. package/extensions/modules/web/test/format.test.ts +230 -0
  222. package/extensions/modules/web/test/gemini-auth.test.ts +465 -0
  223. package/extensions/modules/web/test/gemini-dr.test.ts +249 -0
  224. package/extensions/modules/web/test/gemini.test.ts +472 -0
  225. package/extensions/modules/web/test/hook.test.ts +101 -0
  226. package/extensions/modules/web/test/image.test.ts +1089 -0
  227. package/extensions/modules/web/test/retry.test.ts +119 -0
  228. package/extensions/modules/web/test/screenshot.test.ts +109 -0
  229. package/extensions/modules/web/test/search.test.ts +210 -0
  230. package/extensions/modules/web/test/settings.test.ts +165 -0
  231. package/extensions/modules/web/test/skill.test.ts +72 -0
  232. package/extensions/modules/web/types.d.ts +3 -0
  233. package/extensions/modules/web/vendor/package.json +1 -0
  234. package/extensions/modules/web/vendor/readability/LICENSE.md +13 -0
  235. package/extensions/modules/web/vendor/readability/Readability-readerable.js +123 -0
  236. package/extensions/modules/web/vendor/readability/Readability.js +2787 -0
  237. package/extensions/modules/web/vendor/readability/index.d.ts +64 -0
  238. package/extensions/modules/web/vendor/readability/index.js +9 -0
  239. package/extensions/modules/web/vendor/turndown/LICENSE +21 -0
  240. package/extensions/modules/web/vendor/turndown/turndown.cjs.js +784 -0
  241. package/extensions/modules/web/vendor/turndown-plugin-gfm/LICENSE +21 -0
  242. package/extensions/modules/web/vendor/turndown-plugin-gfm/turndown-plugin-gfm.cjs.js +163 -0
  243. package/extensions/modules/zai/configPanel.ts +154 -0
  244. package/extensions/modules/zai/index.ts +186 -0
  245. package/extensions/modules/zai/lib/anthropic.ts +159 -0
  246. package/extensions/modules/zai/lib/settings.ts +198 -0
  247. package/extensions/modules/zai/lib/signing.ts +721 -0
  248. package/extensions/modules/zai/lib/throttle.ts +198 -0
  249. package/extensions/modules/zai/test/anthropic.test.ts +132 -0
  250. package/extensions/modules/zai/test/configPanel.test.ts +230 -0
  251. package/extensions/modules/zai/test/extension.test.ts +249 -0
  252. package/extensions/modules/zai/test/settings.test.ts +183 -0
  253. package/extensions/modules/zai/test/signing-wiring.test.ts +108 -0
  254. package/extensions/modules/zai/test/signing.test.ts +364 -0
  255. package/extensions/modules/zai/test/throttle.test.ts +329 -0
  256. package/package.json +19 -4
  257. package/scripts/validate-themes.mjs +75 -0
  258. package/skills/munin/SKILL.md +117 -0
  259. package/skills/ux-capture/SKILL.md +202 -0
  260. package/skills/ux-design/SKILL.md +279 -0
  261. package/skills/ux-presets/SKILL.md +484 -0
  262. package/skills/ux-routing/SKILL.md +46 -0
  263. package/skills/web/SKILL.md +153 -0
  264. package/themes/alabaster.json +93 -0
  265. package/themes/amethyst.json +96 -0
  266. package/themes/anthracite.json +93 -0
  267. package/themes/basalt.json +91 -0
  268. package/themes/birch.json +95 -0
  269. package/themes/catppuccin-mocha.json +91 -0
  270. package/themes/dark-abyss.json +91 -0
  271. package/themes/dark-arctic.json +104 -0
  272. package/themes/dark-aurora.json +95 -0
  273. package/themes/dark-catppuccin.json +107 -0
  274. package/themes/dark-cavern.json +91 -0
  275. package/themes/dark-celestial.json +106 -0
  276. package/themes/dark-copper.json +95 -0
  277. package/themes/dark-cosmos.json +90 -0
  278. package/themes/dark-cyberpunk.json +102 -0
  279. package/themes/dark-dracula.json +98 -0
  280. package/themes/dark-eclipse.json +91 -0
  281. package/themes/dark-ember.json +95 -0
  282. package/themes/dark-equinox.json +90 -0
  283. package/themes/dark-forest.json +96 -0
  284. package/themes/dark-github.json +105 -0
  285. package/themes/dark-gruvbox.json +112 -0
  286. package/themes/dark-lavender.json +95 -0
  287. package/themes/dark-lunar.json +89 -0
  288. package/themes/dark-midnight.json +95 -0
  289. package/themes/dark-monochrome.json +94 -0
  290. package/themes/dark-monokai.json +98 -0
  291. package/themes/dark-nebula.json +90 -0
  292. package/themes/dark-neon-noir.json +100 -0
  293. package/themes/dark-nord.json +98 -0
  294. package/themes/dark-ocean.json +101 -0
  295. package/themes/dark-one.json +100 -0
  296. package/themes/dark-poimandres.json +115 -0
  297. package/themes/dark-rainforest.json +91 -0
  298. package/themes/dark-reef.json +91 -0
  299. package/themes/dark-retro.json +92 -0
  300. package/themes/dark-rose-pine.json +96 -0
  301. package/themes/dark-sakura.json +95 -0
  302. package/themes/dark-slate.json +95 -0
  303. package/themes/dark-solarized.json +97 -0
  304. package/themes/dark-solstice.json +90 -0
  305. package/themes/dark-starfall.json +91 -0
  306. package/themes/dark-sunset.json +99 -0
  307. package/themes/dark-swamp.json +90 -0
  308. package/themes/dark-synthwave.json +103 -0
  309. package/themes/dark-taiga.json +91 -0
  310. package/themes/dark-terminal.json +95 -0
  311. package/themes/dark-tokyo-night.json +101 -0
  312. package/themes/dark-tundra.json +91 -0
  313. package/themes/dark-twilight.json +91 -0
  314. package/themes/dark-volcanic.json +91 -0
  315. package/themes/dark.json +80 -0
  316. package/themes/graphite.json +92 -0
  317. package/themes/light-arctic.json +107 -0
  318. package/themes/light-aurora-day.json +91 -0
  319. package/themes/light-canyon.json +91 -0
  320. package/themes/light-catppuccin.json +106 -0
  321. package/themes/light-cirrus.json +90 -0
  322. package/themes/light-coral.json +95 -0
  323. package/themes/light-cyberpunk.json +96 -0
  324. package/themes/light-dawn.json +90 -0
  325. package/themes/light-dunes.json +91 -0
  326. package/themes/light-eucalyptus.json +95 -0
  327. package/themes/light-forest.json +100 -0
  328. package/themes/light-frost.json +95 -0
  329. package/themes/light-github.json +115 -0
  330. package/themes/light-glacier.json +91 -0
  331. package/themes/light-gruvbox.json +108 -0
  332. package/themes/light-haze.json +90 -0
  333. package/themes/light-honeycomb.json +95 -0
  334. package/themes/light-lagoon.json +91 -0
  335. package/themes/light-lavender.json +95 -0
  336. package/themes/light-meadow.json +91 -0
  337. package/themes/light-mint.json +95 -0
  338. package/themes/light-monochrome.json +101 -0
  339. package/themes/light-ocean.json +99 -0
  340. package/themes/light-one.json +99 -0
  341. package/themes/light-opal.json +91 -0
  342. package/themes/light-orchard.json +91 -0
  343. package/themes/light-paper.json +95 -0
  344. package/themes/light-poimandres.json +115 -0
  345. package/themes/light-prism.json +90 -0
  346. package/themes/light-retro.json +98 -0
  347. package/themes/light-sand.json +95 -0
  348. package/themes/light-savanna.json +91 -0
  349. package/themes/light-solarized.json +102 -0
  350. package/themes/light-soleil.json +90 -0
  351. package/themes/light-sunset.json +99 -0
  352. package/themes/light-synthwave.json +98 -0
  353. package/themes/light-tokyo-night.json +111 -0
  354. package/themes/light-wetland.json +91 -0
  355. package/themes/light-zenith.json +89 -0
  356. package/themes/light.json +80 -0
  357. package/themes/limestone.json +94 -0
  358. package/themes/mahogany.json +97 -0
  359. package/themes/marble.json +93 -0
  360. package/themes/mirage.json +79 -0
  361. package/themes/obsidian.json +91 -0
  362. package/themes/onyx.json +91 -0
  363. package/themes/pearl.json +93 -0
  364. package/themes/porcelain.json +91 -0
  365. package/themes/quartz.json +96 -0
  366. package/themes/sandstone.json +95 -0
  367. package/themes/titanium.json +90 -0
@@ -0,0 +1,641 @@
1
+ // munin module — Munin long-term memory tools for Pi.
2
+ //
3
+ // Ported from @bacnh85/pi-munin 0.5.12 extensions/index.ts (SDK vendored to
4
+ // lib/sdk.ts; dotenv dropped — ceulen's bundle env.ts ingests trusted .env).
5
+ // Registers the 8 munin_* tools (per-tool kill-switch via ceulen.disabledTools),
6
+ // /munin-status, the Munin Memory Protocol injection (only when configured),
7
+ // the tool_result error sanitizer, and the munin skill (resources_discover).
8
+ // Config lives at PROJECT level (.pi/settings.json `munin` section) — see
9
+ // configPanel.ts; resolution precedence is documented in lib/helpers.ts.
10
+
11
+ import type {
12
+ ExtensionAPI,
13
+ ExtensionContext,
14
+ ToolDefinition,
15
+ } from "@earendil-works/pi-coding-agent";
16
+ import fs from "node:fs";
17
+ import path from "node:path";
18
+ import { Type } from "typebox";
19
+ import { MuninClient } from "./lib/sdk.js";
20
+ import {
21
+ formatCapabilities,
22
+ parseTags,
23
+ toTextResult,
24
+ truncateText,
25
+ validateMemoryTags,
26
+ validateMemoryKey,
27
+ validateSearchQuery,
28
+ validateTagMode,
29
+ classifyError,
30
+ sanitizeErrorMessage,
31
+ getMuninConfig,
32
+ extractRemediation,
33
+ formatRemediation,
34
+ type MuninResolvedConfig,
35
+ type Remediation,
36
+ } from "./lib/helpers.js";
37
+ import { withRetry } from "./lib/retry.js";
38
+ import { readDisabledTools } from "../../lib/tools.js";
39
+
40
+ // Shared schemas — per-call overrides (params win over env/settings).
41
+ const projectParam = Type.Optional(
42
+ Type.String({ description: "Leave empty — defaults to $MUNIN_PROJECT.", default: "" }),
43
+ );
44
+ const apiKeyParam = Type.Optional(
45
+ Type.String({ description: "API key. Default: $MUNIN_API_KEY.", default: "" }),
46
+ );
47
+ const baseUrlParam = Type.Optional(
48
+ Type.String({
49
+ description: "Base URL. Default: $MUNIN_BASE_URL.",
50
+ default: "",
51
+ }),
52
+ );
53
+
54
+ const controlSchema = {
55
+ project: projectParam,
56
+ api_key: apiKeyParam,
57
+ base_url: baseUrlParam,
58
+ };
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // Always-on condensed Memory Protocol (injected only when Munin is configured)
62
+ // ---------------------------------------------------------------------------
63
+
64
+ // Portable home for the Munin Memory Protocol. The full deep reference lives
65
+ // in skills/munin/SKILL.md; this is the condensed always-on form covering the
66
+ // durable rules.
67
+ const MUNIN_PROTOCOL_HEADER = `## Munin Memory Protocol
68
+
69
+ Use Munin to recover and preserve verified project knowledge, not as a task log.
70
+ If Munin is unavailable, state that briefly when it matters and continue from
71
+ repository evidence.
72
+
73
+ ### Before acting
74
+
75
+ - Search at the start of non-trivial work and before changing architecture,
76
+ dependencies, public behavior, setup, or a previously fixed subsystem.
77
+ - For bugs, search the exact error or symptom with \`type:bug-fix\` before
78
+ attempting a new fix.
79
+ - Build focused 4-8 word queries from exact phrases, capitalized entities,
80
+ subsystem names, file paths, error codes, and dependency names. Quote exact
81
+ strings and use tags or temporal filters when they reduce noise.
82
+ - Use \`topK: 5\` for focused lookup and up to \`topK: 20\` for exploration. DO
83
+ NOT use single-word queries unless the term is a genuinely rare error code.
84
+ - Search results are leads, not facts. Retrieve promising memories
85
+ (\`munin_get\`), check validity and source anchors, and reconcile with current
86
+ repository evidence before relying on them.
87
+
88
+ ### What to store
89
+
90
+ Store only verified knowledge likely to help a future session: architecture or
91
+ product decisions (with rationale and rejected options); recurring bug root
92
+ causes (exact symptoms, fixes, verification); stable setup facts, conventions,
93
+ constraints, dependency choices; durable user/project identity facts that
94
+ materially guide work. Do NOT store temporary progress, routine completion
95
+ summaries, TODOs, raw logs, unverified hypotheses, transient file state,
96
+ generated output, or information easy to derive from authoritative files. Never
97
+ store secrets, credentials, private keys, tokens, or encryption keys.
98
+
99
+ ### Memory shape
100
+
101
+ - One concept per memory. Batch independent memories instead of combining
102
+ unrelated facts.
103
+ - Stable descriptive key; add a date when historical rather than continuously
104
+ updated. Reuse a key only for an intentional upsert.
105
+ - Include the conclusion, why it matters, evidence/verification, and durable
106
+ file/symbol anchors. Cross-reference related memories by mentioning their keys
107
+ in \`content\` (e.g. "See also: architecture/cache-policy").
108
+ - Lowercase namespaced tags with at least one \`type:\`
109
+ (\`decision\`|\`bug-fix\`|\`fact\`|\`dependency\`) and one \`domain:\`
110
+ (\`auth\`|\`frontend\`|\`backend\`|\`infra\`|\`memory\`). Add \`status:\` or
111
+ \`priority:\` only when they improve retrieval.
112
+ - Use \`validFrom\`/\`validTo\` for time-bound facts so stale information is
113
+ filtered automatically. Pin only durable, high-value anchors.
114
+
115
+ ### Lifecycle and safety
116
+
117
+ - At task end, store only newly established durable knowledge. Before context
118
+ compaction, batch-store any outstanding memories.
119
+ - Update or supersede stale memories when current evidence changes; delete only
120
+ with explicit authorization.
121
+ - Before memory operations in an E2EE project, verify the encryption key is
122
+ configured. Never print or store the key. For E2EE Elite, use the official
123
+ Munin crypto helper.
124
+ - Share memories across projects only when explicitly useful and when encryption
125
+ compatibility is confirmed.`;
126
+
127
+ // ---------------------------------------------------------------------------
128
+ // Core SDK call with retry and stale-protocol handling
129
+ // ---------------------------------------------------------------------------
130
+
131
+ function withMuninClient<T extends Record<string, unknown>>(
132
+ params: T,
133
+ callback: (client: MuninClient, projectId: string) => Promise<unknown>,
134
+ ctx?: { cwd?: string; isProjectTrusted?: () => boolean },
135
+ ): Promise<unknown> {
136
+ const { apiKey, projectId, baseUrl } = getMuninConfig(
137
+ params,
138
+ ctx?.cwd,
139
+ ctx?.isProjectTrusted?.() === true,
140
+ );
141
+ const client = new MuninClient({ apiKey, baseUrl });
142
+ return callback(client, projectId);
143
+ }
144
+
145
+ /** Fresh Error carrying the sanitized `err.message + remediation` text, with
146
+ * the original preserved as `cause` — never mutates the caught error (keeps
147
+ * its identity/stack intact for upstream consumers). Structured fields (`code`,
148
+ * `details.remediation`) are copied onto the new Error so programmatic
149
+ * consumers keep them; the message behavior is unchanged. */
150
+ function remediatedError(err: Error, remediation?: Remediation): Error {
151
+ const error = new Error(
152
+ sanitizeErrorMessage(new Error(err.message + formatRemediation(remediation))),
153
+ { cause: err },
154
+ );
155
+ const withFields = error as Error & { code?: unknown; details?: Record<string, unknown> };
156
+ const code = (err as Error & { code?: unknown }).code;
157
+ if (code !== undefined) withFields.code = code;
158
+ const details = (err as Error & { details?: Record<string, unknown> }).details;
159
+ withFields.details = { ...(details && typeof details === "object" ? details : {}) };
160
+ if (remediation) withFields.details.remediation = remediation;
161
+ return error;
162
+ }
163
+
164
+ /**
165
+ * Core Munin invocation with retry and error sanitization.
166
+ * Some actions like 'delete' are not advertised in server capabilities
167
+ * but are still supported. Pass ensureCapability: false for those.
168
+ */
169
+ export async function callMunin(
170
+ client: MuninClient,
171
+ projectId: string,
172
+ action: string,
173
+ payload: Record<string, unknown> = {},
174
+ ): Promise<unknown> {
175
+ const directAction = action === "get" ? "retrieve" : action;
176
+ // Server doesn't advertise 'delete' in capabilities, but supports it.
177
+ // Use ensureCapability: false to avoid capability-check rejection.
178
+ const invokeOptions = directAction === "delete"
179
+ ? { ensureCapability: false }
180
+ : { ensureCapability: true };
181
+
182
+ try {
183
+ return await withRetry(async () => invokeMuninAction(client, projectId, directAction, payload, invokeOptions));
184
+ } catch (error) {
185
+ // Layer 1: auto-recover from ERR_STALE_PROTOCOL via the server's
186
+ // acknowledge_setup handshake, then retry the original call exactly once.
187
+ // ponytail: single retry — no loop; ack is idempotent and server-side remembered.
188
+ const err = error instanceof Error ? error : new Error(String(error));
189
+ const remediation = extractRemediation(err);
190
+ const ack = remediation?.acknowledge_after_reading;
191
+ const isStale =
192
+ classifyError(err).type === "stale_protocol" &&
193
+ !!ack?.payload?.version;
194
+ if (isStale && typeof client.invoke === "function") {
195
+ const version = ack!.payload.version;
196
+ // Server directs the action name (default acknowledge_setup if absent).
197
+ const ackAction = ack!.action || "acknowledge_setup";
198
+ // Some servers return a non-throwing failure ({ok:false} etc.) that the
199
+ // SDK does not throw on — detect it via a flag instead of throwing inside
200
+ // the try (which the catch would re-wrap).
201
+ let ackFailed = false;
202
+ try {
203
+ // ack is a real action even when not advertised in capabilities.
204
+ const ackResult = await client.invoke(projectId, ackAction, { version }, { ensureCapability: false });
205
+ ackFailed = !!ackResult && typeof ackResult === "object" &&
206
+ ((ackResult as { ok?: boolean }).ok === false || (ackResult as { success?: boolean }).success === false || (ackResult as { acknowledged?: boolean }).acknowledged === false);
207
+ } catch {
208
+ ackFailed = true;
209
+ }
210
+ if (ackFailed) {
211
+ // ack failed (thrown or resolved-failure) → surface remediation, do NOT retry (no infinite loop).
212
+ throw remediatedError(err, remediation);
213
+ }
214
+ // Retry the original action exactly ONCE, unwrapped. ponytail: this is
215
+ // the total-attempt budget (plan 2026-09-29) — the previous withRetry
216
+ // wrapper here stacked 3+3 network attempts worst case. A stale error
217
+ // can't recur here (the ack succeeded), so withRetry's extra retry
218
+ // rounds bought nothing but stacked attempts.
219
+ try {
220
+ return await invokeMuninAction(client, projectId, directAction, payload, invokeOptions);
221
+ } catch (retryErr) {
222
+ const r = retryErr instanceof Error ? retryErr : new Error(String(retryErr));
223
+ // Only fall back to the original stale remediation when the retry error is itself stale.
224
+ // A non-stale retry failure (e.g. VALIDATION_ERROR) must surface its own cause, not a
225
+ // handshake that already succeeded.
226
+ const retryIsStale = classifyError(r).type === "stale_protocol";
227
+ throw remediatedError(r, extractRemediation(r) ?? (retryIsStale ? remediation : undefined));
228
+ }
229
+ }
230
+ // Layer 2: surface remediation in the error message even when auto-ack is skipped.
231
+ throw remediatedError(err, remediation);
232
+ }
233
+ }
234
+
235
+ /** Dispatch a single Munin action (direct method or client.invoke). Extracted for one-shot retry reuse. */
236
+ function invokeMuninAction(
237
+ client: MuninClient,
238
+ projectId: string,
239
+ directAction: string,
240
+ payload: Record<string, unknown>,
241
+ invokeOptions: { ensureCapability: boolean },
242
+ ): Promise<unknown> {
243
+ if (directAction === "capabilities") return client.capabilities(true);
244
+ // ponytail: share() has different signature — skip direct call, use invoke
245
+ const direct = client[directAction as keyof MuninClient];
246
+ if (typeof direct === "function" && directAction !== "share") {
247
+ // .call(client, …) — extracting the method to a const loses the receiver;
248
+ // the class methods read `this.invoke` (real-client round-trip caught this).
249
+ return (direct as (this: MuninClient, projectId: string, payload: Record<string, unknown>) => Promise<unknown>).call(client, projectId, payload);
250
+ }
251
+ if (typeof client.invoke === "function") {
252
+ return client.invoke(projectId, directAction, payload, invokeOptions);
253
+ }
254
+ throw new Error(`Munin SDK does not support action: ${directAction}`);
255
+ }
256
+
257
+ // ---------------------------------------------------------------------------
258
+ // Tool factory (shared shape; registered with per-tool kill-switch awareness)
259
+ // ---------------------------------------------------------------------------
260
+
261
+ // ponytail: the harness-free tool list is declared over the public
262
+ // ToolDefinition shape with loose params — TypeBox specs don't survive the
263
+ // generic (same pattern as ux_audit).
264
+ type AnyTool = ToolDefinition<any, unknown>;
265
+
266
+ function makeTools(): AnyTool[] {
267
+ return [
268
+ {
269
+ name: "munin_search",
270
+ label: "Munin Search",
271
+ description: "BEFORE work: SEARCH for relevant past fixes, decisions, context.",
272
+ promptSnippet: "BEFORE work: search memory for relevant context",
273
+ promptGuidelines: [
274
+ "Use munin_search before non-trivial work when prior context matters.",
275
+ "Give munin_search exact errors, subsystem names, file paths, and dependencies.",
276
+ "Use munin_search tags for targeting and topK 5-20.",
277
+ ],
278
+ parameters: Type.Object({
279
+ ...controlSchema,
280
+ query: Type.String({ description: "Query terms." }),
281
+ topK: Type.Optional(
282
+ Type.Number({ description: "Max results. Default 10.", default: 10 }),
283
+ ),
284
+ tags: Type.Optional(Type.String({ description: "Tags, comma-separated." })),
285
+ tag_mode: Type.Optional(
286
+ Type.String({ description: "Mode: 'all' or 'any'.", default: "all" }),
287
+ ),
288
+ since: Type.Optional(
289
+ Type.String({
290
+ description: "Results after this date (e.g., '2024-01-01').",
291
+ }),
292
+ ),
293
+ before: Type.Optional(Type.String({ description: "Results before this date." })),
294
+ include_total: Type.Optional(
295
+ Type.Boolean({ description: "Include total count.", default: false }),
296
+ ),
297
+ }),
298
+ async execute(_id, params, _signal, _onUpdate, ctx) {
299
+ const { query, topK = 10, tags, tag_mode, since, before, include_total } = params as Record<string, any>;
300
+ validateSearchQuery(query);
301
+ const tagMode = validateTagMode(tag_mode);
302
+ const result = await withMuninClient(params as Record<string, unknown>, async (client, projectId) => {
303
+ const searchParams: Record<string, unknown> = { query, topK };
304
+ if (tags) searchParams.tags = parseTags(tags);
305
+ if (tagMode) searchParams.tagMode = tagMode;
306
+ if (since) searchParams.since = since;
307
+ if (before) searchParams.before = before;
308
+ if (include_total) searchParams.includeTotal = include_total;
309
+ return callMunin(client, projectId, "search", searchParams);
310
+ }, ctx);
311
+ return {
312
+ content: [{ type: "text" as const, text: toTextResult(result) }],
313
+ details: result,
314
+ };
315
+ },
316
+ },
317
+ {
318
+ name: "munin_get",
319
+ label: "Munin Get Memory",
320
+ description: "AFTER search: retrieve full memory by key.",
321
+ promptSnippet: "After search, get full content by key",
322
+ promptGuidelines: [
323
+ "Use munin_get after search to retrieve full content of promising results.",
324
+ "Verify munin_get results against current repository evidence before using them.",
325
+ ],
326
+ parameters: Type.Object({
327
+ ...controlSchema,
328
+ key: Type.String({ description: "Key to retrieve." }),
329
+ }),
330
+ async execute(_id, params, _signal, _onUpdate, ctx) {
331
+ const { key: rawKey } = params as Record<string, any>;
332
+ const key = validateMemoryKey(rawKey);
333
+ const result = await withMuninClient(params as Record<string, unknown>, async (client, projectId) => {
334
+ return callMunin(client, projectId, "get", { key });
335
+ }, ctx);
336
+ return {
337
+ content: [{ type: "text" as const, text: toTextResult(result) }],
338
+ details: result,
339
+ };
340
+ },
341
+ },
342
+ {
343
+ name: "munin_store",
344
+ label: "Munin Store Memory",
345
+ description:
346
+ "AT SESSION END (or after fix): STORE verified durable knowledge.",
347
+ promptSnippet: "Store durable knowledge in long-term memory",
348
+ promptGuidelines: ["munin_store: follow the Munin Memory Protocol for tags, content shape, and exclusions (no secrets, logs, TODOs)."],
349
+ parameters: Type.Object({
350
+ ...controlSchema,
351
+ key: Type.String({
352
+ description: "Unique kebab-case key: domain/subject.",
353
+ }),
354
+ title: Type.String({ description: "Short title." }),
355
+ content: Type.String({
356
+ description: "Conclusion, why it matters, evidence, anchors.",
357
+ }),
358
+ tags: Type.String({
359
+ description: "Comma-separated; one type: + one domain:.",
360
+ }),
361
+ valid_from: Type.Optional(
362
+ Type.String({ description: "Valid-from ISO date." }),
363
+ ),
364
+ valid_to: Type.Optional(
365
+ Type.String({ description: "Expiry ISO date." }),
366
+ ),
367
+ pinned: Type.Optional(
368
+ Type.Boolean({
369
+ description: "Pin for higher relevance.",
370
+ default: false,
371
+ }),
372
+ ),
373
+ }),
374
+ async execute(_id, params, _signal, _onUpdate, ctx) {
375
+ const { key: rawKey, title, content, tags, valid_from, valid_to, pinned } = params as Record<string, any>;
376
+ const key = validateMemoryKey(rawKey);
377
+ const tagValidation = validateMemoryTags(tags);
378
+ if (!tagValidation.ok) throw new Error(tagValidation.message);
379
+ const result = await withMuninClient(params as Record<string, unknown>, async (client, projectId) => {
380
+ const payload: Record<string, unknown> = { key, title, content, tags: tagValidation.tags };
381
+ if (valid_from) payload.validFrom = valid_from;
382
+ if (valid_to) payload.validTo = valid_to;
383
+ if (typeof pinned === "boolean") payload.pinned = pinned;
384
+ return callMunin(client, projectId, "store", payload);
385
+ }, ctx);
386
+ const keyStr = (result as { key?: string })?.key ?? key;
387
+ return {
388
+ content: [
389
+ {
390
+ type: "text" as const,
391
+ text: `Stored memory \`${keyStr}\` with tags \`${tags ?? "none"}\`.`,
392
+ },
393
+ ],
394
+ details: result,
395
+ };
396
+ },
397
+ },
398
+ {
399
+ name: "munin_list",
400
+ label: "Munin List Memories",
401
+ description: "LIST all stored memories.",
402
+ promptSnippet: "List available memories",
403
+ promptGuidelines: [
404
+ "Use munin_list to explore stored knowledge while planning.",
405
+ ],
406
+ parameters: Type.Object({
407
+ ...controlSchema,
408
+ limit: Type.Optional(
409
+ Type.Number({ description: "Max results. Default 20.", default: 20 }),
410
+ ),
411
+ offset: Type.Optional(
412
+ Type.Number({ description: "Offset.", default: 0 }),
413
+ ),
414
+ }),
415
+ async execute(_id, params, _signal, _onUpdate, ctx) {
416
+ const { limit = 20, offset = 0 } = params as Record<string, any>;
417
+ const result = await withMuninClient(params as Record<string, unknown>, async (client, projectId) => {
418
+ return callMunin(client, projectId, "list", { limit, offset });
419
+ }, ctx);
420
+ return {
421
+ content: [{ type: "text" as const, text: toTextResult(result) }],
422
+ details: result,
423
+ };
424
+ },
425
+ },
426
+ {
427
+ name: "munin_recent",
428
+ label: "Munin Recent Memories",
429
+ description: "CHECK recently updated memories.",
430
+ promptSnippet: "Show recent updates",
431
+ promptGuidelines: [
432
+ "Use munin_recent to see what was added or modified recently.",
433
+ ],
434
+ parameters: Type.Object({
435
+ ...controlSchema,
436
+ limit: Type.Optional(
437
+ Type.Number({ description: "Max results. Default 10.", default: 10 }),
438
+ ),
439
+ }),
440
+ async execute(_id, params, _signal, _onUpdate, ctx) {
441
+ const { limit = 10 } = params as Record<string, any>;
442
+ const result = await withMuninClient(params as Record<string, unknown>, async (client, projectId) => {
443
+ return callMunin(client, projectId, "recent", { limit });
444
+ }, ctx);
445
+ return {
446
+ content: [{ type: "text" as const, text: toTextResult(result) }],
447
+ details: result,
448
+ };
449
+ },
450
+ },
451
+ {
452
+ name: "munin_delete",
453
+ label: "Munin Delete Memory",
454
+ description:
455
+ "DELETE memory — only when user explicitly asks.",
456
+ promptSnippet: "Delete a memory from storage",
457
+ promptGuidelines: [
458
+ "Use munin_delete only when the user explicitly asks; it always requires confirmation.",
459
+ ],
460
+ parameters: Type.Object({
461
+ ...controlSchema,
462
+ key: Type.String({ description: "Key to delete." }),
463
+ }),
464
+ async execute(_id, params, _signal, _onUpdate, ctx) {
465
+ const { key: rawKey } = params as Record<string, any>;
466
+ const key = validateMemoryKey(rawKey);
467
+ const confirmed = await ctx.ui.confirm(
468
+ "Delete Munin memory?",
469
+ `Delete memory \`${key}\` from long-term storage? This cannot be undone.`,
470
+ );
471
+ if (!confirmed) {
472
+ return {
473
+ content: [
474
+ { type: "text" as const, text: `Delete cancelled for memory \`${key}\`.` },
475
+ ],
476
+ details: { cancelled: true, key },
477
+ };
478
+ }
479
+ const result = await withMuninClient(params as Record<string, unknown>, async (client, projectId) => {
480
+ return callMunin(client, projectId, "delete", { key, force: true });
481
+ }, ctx);
482
+ return {
483
+ content: [{ type: "text" as const, text: `Deleted memory \`${key}\`.` }],
484
+ details: result,
485
+ };
486
+ },
487
+ },
488
+ {
489
+ name: "munin_capabilities",
490
+ label: "Munin Capabilities",
491
+ description: "CHECK available Munin server features.",
492
+ promptSnippet: "Show Munin capabilities",
493
+ promptGuidelines: [
494
+ "Use munin_capabilities to check which server features are available.",
495
+ ],
496
+ parameters: Type.Object({
497
+ ...controlSchema,
498
+ }),
499
+ async execute(_id, params, _signal, _onUpdate, ctx) {
500
+ const result = await withMuninClient(params as Record<string, unknown>, async (client, projectId) => {
501
+ return callMunin(client, projectId, "capabilities", {});
502
+ }, ctx);
503
+ return {
504
+ content: [{ type: "text" as const, text: truncateText(formatCapabilities(result as Record<string, unknown>)) }],
505
+ details: result,
506
+ };
507
+ },
508
+ },
509
+ {
510
+ name: "munin_share",
511
+ label: "Munin Share Memory",
512
+ description: "SHARE memories between projects.",
513
+ promptSnippet: "Share memories between projects",
514
+ promptGuidelines: [
515
+ "Use munin_share to share memories between projects; it always requires confirmation.",
516
+ "The munin_share source and target projects must be accessible with the API key.",
517
+ ],
518
+ parameters: Type.Object({
519
+ ...controlSchema,
520
+ memory_ids: Type.Array(Type.String(), { description: "Memory IDs to share." }),
521
+ target_project_ids: Type.Array(Type.String(), { description: "Target project IDs." }),
522
+ }),
523
+ async execute(_id, params, _signal, _onUpdate, ctx) {
524
+ const { memory_ids, target_project_ids } = params as Record<string, any>;
525
+ const confirmed = await ctx.ui.confirm(
526
+ "Share Munin memories?",
527
+ `Share ${memory_ids.length} memories with ${target_project_ids.length} target projects?`,
528
+ );
529
+ if (!confirmed) {
530
+ return {
531
+ content: [{ type: "text" as const, text: "Memory sharing cancelled." }],
532
+ details: { cancelled: true },
533
+ };
534
+ }
535
+ const result = await withMuninClient(params as Record<string, unknown>, async (client, projectId) => {
536
+ return callMunin(client, projectId, "share", { memoryIds: memory_ids, targetProjectIds: target_project_ids });
537
+ }, ctx);
538
+ return {
539
+ content: [{ type: "text" as const, text: toTextResult(result) }],
540
+ details: result,
541
+ };
542
+ },
543
+ },
544
+ ];
545
+ }
546
+
547
+ // ponytail: acknowledge_setup, encrypt, decrypt, versions, diff, rollback — speculative server features, cut until needed
548
+ // ponytail: recall, capture, summarize — composite tools the agent can do with 1-2 primitive calls
549
+
550
+ // ---------------------------------------------------------------------------
551
+ // Extension
552
+ // ---------------------------------------------------------------------------
553
+
554
+ /** Masked status of a configured value (never prints it). */
555
+ function maskValue(v: string | undefined): string {
556
+ return v ? "present" : "missing";
557
+ }
558
+
559
+ /** One-line source disclosure, e.g. "env" / "project (.pi/settings.json)". */
560
+ function sourceLabel(source: string, cfg: MuninResolvedConfig): string {
561
+ if (source === "project") return cfg.projectTrusted ? "project (.pi/settings.json)" : "project";
562
+ return source;
563
+ }
564
+
565
+ export { MUNIN_PROTOCOL_HEADER };
566
+
567
+ export default function muninExtension(pi: ExtensionAPI) {
568
+ // Skill ships in-package (../../../skills/munin, 3 levels up from the module
569
+ // dir) and is contributed through resources_discover — NOT via the
570
+ // package.json `pi.skills` manifest — so the kill-switch gates it too:
571
+ // disabled module ⇒ factory never runs ⇒ no munin skill registered.
572
+ const skillsRoot = new URL("../../../skills/", import.meta.url).pathname;
573
+ pi.on("resources_discover", () => ({
574
+ skillPaths: [path.join(fs.realpathSync(skillsRoot), "munin")],
575
+ }));
576
+
577
+ // Per-tool kill-switch (ceulen.disabledTools): listed tools register
578
+ // inactive — /config re-activates them live via setActiveTools.
579
+ const disabled = readDisabledTools();
580
+ for (const tool of makeTools()) {
581
+ pi.registerTool({ ...tool, defaultActive: !disabled.has(tool.name) } as AnyTool);
582
+ }
583
+
584
+ pi.registerCommand("munin-status", {
585
+ description:
586
+ "Show Munin configuration status (API key present, project, base URL)",
587
+ handler: async (_args, ctx) => {
588
+ try {
589
+ const cfg = getMuninConfig({}, ctx.cwd, ctx.isProjectTrusted?.() === true);
590
+ ctx.ui.notify(
591
+ `Munin Status:\n` +
592
+ ` API Key: ${maskValue(cfg.apiKey)} (${sourceLabel(cfg.sources.apiKey, cfg)})\n` +
593
+ ` Project: ${cfg.projectId} (${sourceLabel(cfg.sources.projectId, cfg)})\n` +
594
+ ` Base URL: ${cfg.baseUrl} (${sourceLabel(cfg.sources.baseUrl, cfg)})` +
595
+ (cfg.sources.apiKey === "default" ? "\n Run /config → Memory → Munin to configure this project." : ""),
596
+ "info",
597
+ );
598
+ } catch (err) {
599
+ ctx.ui.notify(
600
+ `Munin Status: ${sanitizeErrorMessage(err instanceof Error ? err : new Error(String(err)))}`,
601
+ "error",
602
+ );
603
+ }
604
+ },
605
+ });
606
+
607
+ pi.on("before_agent_start", async (event, ctx) => {
608
+ try {
609
+ getMuninConfig({}, ctx.cwd, ctx.isProjectTrusted?.() === true);
610
+ } catch {
611
+ return; // skip header if Munin not configured
612
+ }
613
+ return {
614
+ systemPrompt: `${MUNIN_PROTOCOL_HEADER}\n\n---\n\n${event.systemPrompt}`,
615
+ };
616
+ });
617
+
618
+ pi.on("tool_result", async (event) => {
619
+ if (!event.toolName.startsWith("munin_") || !event.isError) return;
620
+ const text = event.content.map((part) => (part as { text?: string })?.text ?? "").join("\n");
621
+ // Strip any existing "Munin <type> error:" prefix to avoid double-wrapping.
622
+ // classifyError may add this prefix on a previous pass — loop so a
623
+ // doubly-wrapped stack ("Munin x error: Munin y error: ...") unwinds fully.
624
+ let cleanText = text;
625
+ while (/^Munin \w+ error: /.test(cleanText)) cleanText = cleanText.replace(/^Munin \w+ error: /, "");
626
+ const classified = classifyError(new Error(cleanText));
627
+ const sanitized = sanitizeErrorMessage(new Error(classified.message));
628
+ // Error messages are also bounded — a malicious server can balloon agent context
629
+ // via oversized remediation fields (url/version), so truncate like success paths.
630
+ const bounded = truncateText(`Munin ${classified.type} error: ${sanitized}`);
631
+ return {
632
+ content: [
633
+ {
634
+ type: "text" as const,
635
+ text: bounded,
636
+ },
637
+ ],
638
+ details: { errorType: classified.type, message: sanitized },
639
+ };
640
+ });
641
+ }