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,629 @@
1
+ import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
2
+ import { readDisabledTools } from "../../lib/tools";
3
+ import { Type, type TSchema } from "typebox";
4
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
5
+ import path from "node:path";
6
+ import { SerenaWorkerClient, type SerenaWorkerResponse } from "./worker";
7
+ import { SERENA_FIRST_GUIDANCE, SERENA_MISS_GUIDANCE, isSerenaActive, shouldBlockSemanticMiss } from "./lib/guidance";
8
+ import { normalizeProject, normalizeContext, normalizeTimeoutMs, stripControlParams } from "./lib/normalize";
9
+ import { repairSymbolNameKey } from "./lib/symbol-key";
10
+
11
+ const DEFAULT_CONTEXT = "ide";
12
+
13
+ const PROJECT_PARAM = Type.Optional(Type.String({ description: "Project path. Default: CWD." }));
14
+ const CONTEXT_PARAM = Type.Optional(Type.String({ description: "Serena context name. Default: ide." }));
15
+ const MAX_CHARS_PARAM = Type.Optional(Type.Number({ description: "Max response chars." }));
16
+ const TIMEOUT_MS_PARAM = Type.Optional(Type.Number({ description: "Timeout in ms." }));
17
+
18
+ import { truncateText } from "./lib/truncate";
19
+
20
+ const controlSchema = {
21
+ project: PROJECT_PARAM,
22
+ context: CONTEXT_PARAM,
23
+ timeout_ms: TIMEOUT_MS_PARAM,
24
+ };
25
+
26
+ const statusSchema = Type.Object({
27
+ project: PROJECT_PARAM,
28
+ context: CONTEXT_PARAM,
29
+ includeAgent: Type.Optional(Type.Boolean({ description: "Include active tools/backend details via SerenaAgent." })),
30
+ timeout_ms: TIMEOUT_MS_PARAM,
31
+ });
32
+
33
+ const listToolsSchema = Type.Object({
34
+ ...controlSchema,
35
+ includeAgent: Type.Optional(Type.Boolean({ description: "Include SerenaAgent before listing." })),
36
+ });
37
+
38
+ const overviewSchema = Type.Object({
39
+ ...controlSchema,
40
+ relative_path: Type.String({ description: "Path relative to project root." }),
41
+ depth: Type.Optional(Type.Number({ description: "Overview depth." })),
42
+ max_answer_chars: MAX_CHARS_PARAM,
43
+ });
44
+
45
+ const findSymbolSchema = Type.Object({
46
+ ...controlSchema,
47
+ name_path_pattern: Type.String({ description: "Name path pattern, e.g. MyClass/my_method." }),
48
+ depth: Type.Optional(Type.Number()),
49
+ relative_path: Type.Optional(Type.String({ description: "Optional dir/file restriction relative to project root." })),
50
+ include_body: Type.Optional(Type.Boolean()),
51
+ include_info: Type.Optional(Type.Boolean()),
52
+ substring_matching: Type.Optional(Type.Boolean()),
53
+ max_matches: Type.Optional(Type.Number()),
54
+ max_answer_chars: MAX_CHARS_PARAM,
55
+ });
56
+
57
+ const referencingSchema = Type.Object({
58
+ ...controlSchema,
59
+ name_path: Type.String({ description: "Exact symbol name path from find_symbol." }),
60
+ relative_path: Type.String({ description: "Symbol's file, relative to project root." }),
61
+ include_kinds: Type.Optional(Type.Array(Type.Number({ description: "LSP kind integers to include." }))),
62
+ exclude_kinds: Type.Optional(Type.Array(Type.Number({ description: "LSP kind integers to exclude." }))),
63
+ max_answer_chars: MAX_CHARS_PARAM,
64
+ });
65
+
66
+ const replaceBodySchema = Type.Object({
67
+ ...controlSchema,
68
+ name_path: Type.String({ description: "Exact name path to replace." }),
69
+ relative_path: Type.String({ description: "Symbol's file, relative to project root." }),
70
+ body: Type.String({ description: "Complete new symbol definition/body, including signature line." }),
71
+ });
72
+
73
+ const insertSchema = Type.Object({
74
+ ...controlSchema,
75
+ name_path: Type.String({ description: "Exact name path of reference symbol." }),
76
+ relative_path: Type.String({ description: "Symbol's file, relative to project root." }),
77
+ body: Type.String({ description: "Content to insert." }),
78
+ });
79
+
80
+ const renameSchema = Type.Object({
81
+ ...controlSchema,
82
+ name_path: Type.String({ description: "Exact name path to rename." }),
83
+ relative_path: Type.String({ description: "Symbol's file, relative to project root." }),
84
+ new_name: Type.String({ description: "New symbol name." }),
85
+ });
86
+
87
+ const safeDeleteSchema = Type.Object({
88
+ ...controlSchema,
89
+ name_path_pattern: Type.String({ description: "Name path pattern to delete if unreferenced." }),
90
+ relative_path: Type.String({ description: "Symbol's file, relative to project root." }),
91
+ });
92
+
93
+ const emptyToolSchema = Type.Object({ ...controlSchema });
94
+
95
+ const symbolRefSchema = Type.Object({
96
+ ...controlSchema,
97
+ name_path: Type.String({ description: "Exact name path to look up." }),
98
+ relative_path: Type.String({ description: "Symbol's file, relative to project root." }),
99
+ });
100
+
101
+ const diagnosticsSchema = Type.Object({
102
+ ...controlSchema,
103
+ relative_path: Type.String({ description: "Path relative to project root." }),
104
+ });
105
+
106
+ const searchPatternSchema = Type.Object({
107
+ ...controlSchema,
108
+ pattern: Type.String({ description: "Text or regex to search for." }),
109
+ relative_path: Type.Optional(Type.String({ description: "Optional dir restriction." })),
110
+ paths_include_glob: Type.Optional(Type.String()),
111
+ paths_exclude_glob: Type.Optional(Type.String()),
112
+ context_lines_before: Type.Optional(Type.Number()),
113
+ context_lines_after: Type.Optional(Type.Number()),
114
+ restrict_search_to_code_files: Type.Optional(Type.Boolean()),
115
+ multiline: Type.Optional(Type.Boolean({ description: "Unsupported; always false." })),
116
+ max_answer_chars: MAX_CHARS_PARAM,
117
+ limit: Type.Optional(Type.Number({ description: "Max matches." })),
118
+ });
119
+
120
+ const replaceContentSchema = Type.Object({
121
+ ...controlSchema,
122
+ relative_path: Type.String({ description: "Path relative to project root." }),
123
+ needle: Type.Optional(Type.String({ description: "Text or regex to replace." })),
124
+ repl: Type.Optional(Type.String({ description: "Replacement text." })),
125
+ mode: Type.Optional(Type.Union([Type.Literal("literal"), Type.Literal("regex")], { description: "Literal or regex." })),
126
+ allow_multiple_occurrences: Type.Optional(Type.Boolean()),
127
+ });
128
+
129
+ const ERROR_HINTS: Record<string, (tool?: string) => string> = {
130
+ language_server_error: () => " The language server may need a restart. Try serena_restart_language_server first.",
131
+ missing_tool: (tool) => ` The tool '${tool ?? "unknown"}' is not available. Try serena_list_tools to see available tools for this project.`,
132
+ inactive_tool: (tool) => ` The tool '${tool ?? "unknown"}' is not active in the current context. Try serena_list_tools to see active tools.`,
133
+ project_error: () => " There is a project configuration issue. Try serena_get_current_config to inspect the active project.",
134
+ };
135
+
136
+ function errorSuggestion(errorType: string | undefined, tool: string | undefined): string {
137
+ const hint = errorType ? ERROR_HINTS[errorType] : undefined;
138
+ return hint ? hint(tool) : "";
139
+ }
140
+
141
+ function resultText(response: SerenaWorkerResponse): string {
142
+ if (!response.ok) {
143
+ const suggestion = errorSuggestion(response.errorType as string | undefined, response.tool as string | undefined);
144
+ const errorDetail = response.error
145
+ ?? (typeof response.result === "string" ? response.result : undefined)
146
+ ?? "Unknown Serena error";
147
+ return `Error: ${errorDetail}${suggestion}`;
148
+ }
149
+ // For search results, show a friendly empty-state instead of raw "{}".
150
+ if (response.tool === "search_for_pattern") {
151
+ if (response.result == null || response.result === '{}' || (typeof response.result === "object" && Object.keys(response.result as object).length === 0)) {
152
+ return "No results found.";
153
+ }
154
+ }
155
+ return typeof response.result === "string" ? response.result : JSON.stringify(response.result, null, 2);
156
+ }
157
+
158
+ // Module-level singleton: the Python worker is shared across the parent session and all
159
+ // in-process pi-subagent children. Previously this lived in the factory closure, so every
160
+ // child session that loaded pi-serena spawned a separate Python process that leaked on
161
+ // child dispose (no shutdown hook). One worker serves all callers.
162
+ let worker: SerenaWorkerClient | undefined;
163
+
164
+ // Actions that only read state — safe to auto-retry once after a timeout,
165
+ // because a partial application is impossible. Mutating actions
166
+ // (replace_symbol_body, insert_*, rename_symbol, safe_delete_symbol,
167
+ // replace_content, restart_*, onboarding) may have applied before the worker
168
+ // was killed; retrying them can double-apply, so their timeout surfaces as an
169
+ // error instead. Effective action = extraPayload.tool when present (the
170
+ // `call` action is dispatched by tool name), else the action itself.
171
+ export const READ_ONLY_WORKER_ACTIONS: ReadonlySet<string> = new Set([
172
+ "get_symbols_overview",
173
+ "find_symbol",
174
+ "find_referencing_symbols",
175
+ "find_declaration",
176
+ "find_implementations",
177
+ "search_for_pattern",
178
+ "get_diagnostics_for_file",
179
+ "config", // serena_get_current_config
180
+ "check_onboarding_performed",
181
+ "status",
182
+ "list_tools",
183
+ ]);
184
+
185
+ export function isReadOnlyWorkerAction(action: string, extraPayload: Record<string, unknown> = {}): boolean {
186
+ return READ_ONLY_WORKER_ACTIONS.has(typeof extraPayload.tool === "string" ? extraPayload.tool : action);
187
+ }
188
+
189
+ /** Retry policy for callWorkerAction, extracted so tests can pin it without
190
+ * spawning a real worker: a thrown timeout-class error retries only when the
191
+ * effective action is read-only (mutators may have applied before the kill). */
192
+ export function shouldRetryAfterTimeout(
193
+ action: string,
194
+ extraPayload: Record<string, unknown>,
195
+ failure: { errorMessage?: string },
196
+ ): boolean {
197
+ if (!isReadOnlyWorkerAction(action, extraPayload)) return false;
198
+ const msg = failure.errorMessage || "";
199
+ return msg.includes("timed out") || msg.includes("killed due to timeout") || msg.includes("worker exited") || msg.includes("restarted");
200
+ }
201
+
202
+ export default function serenaToolsExtension(pi: ExtensionAPI) {
203
+ // Per-tool kill-switch: tools listed in ceulen.disabledTools register
204
+ // inactive (defaultActive: false) — /config re-activates them live via
205
+ // setActiveTools; the persisted list re-applies on every load.
206
+ const disabled = readDisabledTools();
207
+ const reg = <P extends TSchema, D = unknown>(tool: ToolDefinition<P, D>) =>
208
+ pi.registerTool({ ...tool, defaultActive: !disabled.has(tool.name) });
209
+
210
+ const getWorker = () => {
211
+ if (!worker) {
212
+ worker = new SerenaWorkerClient();
213
+ }
214
+ return worker;
215
+ };
216
+
217
+ const callWorkerAction = async (ctx: any, action: string, rawParams: Record<string, unknown>, extraPayload: Record<string, unknown> = {}, lockPath?: string) => {
218
+ const { project, context, timeoutMs, params } = stripControlParams(rawParams);
219
+ const payload = { action, project, context, params, ...extraPayload };
220
+ const requestWithRetry = async (): Promise<SerenaWorkerResponse> => {
221
+ try {
222
+ return await getWorker().request(payload, timeoutMs);
223
+ } catch (error) {
224
+ const msg = error instanceof Error ? error.message : String(error);
225
+ if (!shouldRetryAfterTimeout(action, extraPayload, { errorMessage: msg })) throw error;
226
+ return getWorker().request(payload, timeoutMs);
227
+ }
228
+ };
229
+ const run = async (): Promise<{ content: { type: "text"; text: string }[]; details: SerenaWorkerResponse }> => {
230
+ const response = await requestWithRetry();
231
+ return {
232
+ content: [{ type: "text" as const, text: truncateText(resultText(response)) }],
233
+ details: response,
234
+ };
235
+ };
236
+ return lockPath ? withFileMutationQueue(lockPath, run) : run();
237
+ };
238
+
239
+ const callSerena = async (ctx: any, tool: string, rawParams: Record<string, unknown>, lockPath?: string) => {
240
+ return callWorkerAction(ctx, "call", rawParams, { tool }, lockPath);
241
+ };
242
+
243
+ const lockPathForRelativeFile = (rawParams: Record<string, unknown>): string | undefined => {
244
+ const project = normalizeProject(rawParams.project);
245
+ if (typeof rawParams.relative_path !== "string" || !rawParams.relative_path.trim()) return undefined;
246
+ const resolved = path.resolve(project, rawParams.relative_path);
247
+ const relative = path.relative(project, resolved);
248
+ if (relative.startsWith("..") || path.isAbsolute(relative)) return undefined;
249
+ return resolved;
250
+ };
251
+
252
+ const lockPathForProject = (rawParams: Record<string, unknown>): string => path.resolve(normalizeProject(rawParams.project));
253
+
254
+ reg({
255
+ name: "serena_status",
256
+ label: "Serena Status",
257
+ description: "Show Serena worker and project status.",
258
+ parameters: statusSchema,
259
+ async execute(_id, params, _signal, _onUpdate, ctx) {
260
+ const project = normalizeProject(params.project);
261
+ const context = normalizeContext(params.context);
262
+ const response = await getWorker().request({ action: "status", project, context, includeAgent: Boolean(params.includeAgent) }, normalizeTimeoutMs(params.timeout_ms));
263
+ return { content: [{ type: "text", text: truncateText(JSON.stringify(response, null, 2)) }], details: response };
264
+ },
265
+ });
266
+
267
+ reg({
268
+ name: "serena_list_tools",
269
+ label: "Serena List Tools",
270
+ description: "List active Serena tools for project/context.",
271
+ parameters: listToolsSchema,
272
+ async execute(_id, params, _signal, _onUpdate, ctx) {
273
+ const project = normalizeProject(params.project);
274
+ const context = normalizeContext(params.context);
275
+ const response = await getWorker().request({ action: "status", project, context, includeAgent: true }, normalizeTimeoutMs(params.timeout_ms));
276
+ const tools = Array.isArray(response.activeTools) ? response.activeTools : [];
277
+ const text = tools.length > 0 ? tools.map((tool) => `- ${tool}`).join("\n") : 'No active tools found for this project/context.';
278
+ return { content: [{ type: "text", text: truncateText(text) }], details: response };
279
+ },
280
+ });
281
+
282
+ reg({
283
+ name: "serena_get_symbols_overview",
284
+ label: "Serena Symbols Overview",
285
+ description: "Get top-level symbols via the language server.",
286
+ parameters: overviewSchema,
287
+ async execute(_id, params, _signal, _onUpdate, ctx) {
288
+ return callSerena(ctx, "get_symbols_overview", params);
289
+ },
290
+ });
291
+
292
+ reg({
293
+ name: "serena_find_symbol",
294
+ label: "Serena Find Symbol",
295
+ description: "Find symbols by name path pattern.",
296
+ parameters: findSymbolSchema,
297
+ prepareArguments: (args) => repairSymbolNameKey(args, true),
298
+ async execute(_id, params, _signal, _onUpdate, ctx) {
299
+ return callSerena(ctx, "find_symbol", params);
300
+ },
301
+ });
302
+
303
+ reg({
304
+ name: "serena_find_referencing_symbols",
305
+ label: "Serena Find References",
306
+ description: "Find symbols referencing a given symbol.",
307
+ parameters: referencingSchema,
308
+ prepareArguments: (args) => repairSymbolNameKey(args, false),
309
+ async execute(_id, params, _signal, _onUpdate, ctx) {
310
+ return callSerena(ctx, "find_referencing_symbols", params);
311
+ },
312
+ });
313
+
314
+ reg({
315
+ name: "serena_replace_symbol_body",
316
+ label: "Serena Replace Symbol Body",
317
+ description: "Replace a function/class/method body via symbolic editing.",
318
+ parameters: replaceBodySchema,
319
+ prepareArguments: (args) => repairSymbolNameKey(args, false),
320
+ async execute(_id, params, _signal, _onUpdate, ctx) {
321
+ return callSerena(ctx, "replace_symbol_body", params, lockPathForRelativeFile(params));
322
+ },
323
+ });
324
+
325
+ reg({
326
+ name: "serena_insert_before_symbol",
327
+ label: "Serena Insert Before Symbol",
328
+ description: "Insert content before a known symbol definition.",
329
+ parameters: insertSchema,
330
+ prepareArguments: (args) => repairSymbolNameKey(args, false),
331
+ async execute(_id, params, _signal, _onUpdate, ctx) {
332
+ return callSerena(ctx, "insert_before_symbol", params, lockPathForRelativeFile(params));
333
+ },
334
+ });
335
+
336
+ reg({
337
+ name: "serena_insert_after_symbol",
338
+ label: "Serena Insert After Symbol",
339
+ description: "Insert content after a known symbol definition.",
340
+ parameters: insertSchema,
341
+ prepareArguments: (args) => repairSymbolNameKey(args, false),
342
+ async execute(_id, params, _signal, _onUpdate, ctx) {
343
+ return callSerena(ctx, "insert_after_symbol", params, lockPathForRelativeFile(params));
344
+ },
345
+ });
346
+
347
+ reg({
348
+ name: "serena_rename_symbol",
349
+ label: "Serena Rename Symbol",
350
+ description: "Rename a symbol across the codebase.",
351
+ parameters: renameSchema,
352
+ prepareArguments: (args) => repairSymbolNameKey(args, false),
353
+ async execute(_id, params, _signal, _onUpdate, ctx) {
354
+ return callSerena(ctx, "rename_symbol", params, lockPathForProject(params));
355
+ },
356
+ });
357
+
358
+ reg({
359
+ name: "serena_safe_delete_symbol",
360
+ label: "Serena Safe Delete Symbol",
361
+ description: "Delete a symbol with no remaining references.",
362
+ parameters: safeDeleteSchema,
363
+ prepareArguments: (args) => repairSymbolNameKey(args, true),
364
+ async execute(_id, params, _signal, _onUpdate, ctx) {
365
+ return callSerena(ctx, "safe_delete_symbol", params, lockPathForRelativeFile(params));
366
+ },
367
+ });
368
+
369
+ reg({
370
+ name: "serena_search_for_pattern",
371
+ label: "Serena Search Pattern",
372
+ description: "Search project files with path filtering.",
373
+ parameters: searchPatternSchema,
374
+ async execute(_id, params, _signal, _onUpdate, ctx) {
375
+ if (params.multiline === true) {
376
+ return {
377
+ content: [{ type: "text" as const, text: "Error: serena_search_for_pattern does not support multiline mode. Use serena_search_for_pattern without multiline or use serena_find_symbol for symbol-aware searches instead." }],
378
+ details: { ok: false, error: "multiline not supported" },
379
+ };
380
+ }
381
+ // ponytail: rename pattern → substring_pattern for Python backend
382
+ const { multiline: _ml, limit: _limit, pattern, ...restParams } = params;
383
+ const searchParams: Record<string, unknown> = { ...restParams };
384
+ if (pattern) {
385
+ searchParams.substring_pattern = pattern;
386
+ }
387
+ const result = await callSerena(ctx, "search_for_pattern", searchParams);
388
+ if (_limit && result.content?.[0]?.text) {
389
+ try {
390
+ // ponytail: parse result JSON, count matches, truncate if over limit
391
+ const parsed = JSON.parse(result.content[0].text);
392
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
393
+ const entries = Object.entries(parsed) as [string, unknown[]][];
394
+ const total = entries.reduce((s, [, v]) => s + (Array.isArray(v) ? v.length : 0), 0);
395
+ if (total > _limit) {
396
+ let kept = 0;
397
+ const out: Record<string, unknown[]> = {};
398
+ for (const [f, arr] of entries) {
399
+ if (!Array.isArray(arr)) continue;
400
+ const need = _limit - kept;
401
+ if (need <= 0) break;
402
+ out[f] = arr.slice(0, need);
403
+ kept += out[f]!.length;
404
+ }
405
+ result.content[0].text = JSON.stringify(out) + `\n\n[Results truncated to ${_limit} matches out of ${total}. Refine search or increase limit.]`;
406
+ }
407
+ }
408
+ } catch {
409
+ // ponytail: not JSON, fall back to line truncation
410
+ const lines = result.content[0].text.split("\n");
411
+ if (lines.length > _limit) {
412
+ result.content[0].text = lines.slice(0, _limit).join("\n") + `\n\n[Results truncated to ${_limit} lines. Refine search or increase limit.]`;
413
+ }
414
+ }
415
+ }
416
+ return result;
417
+ },
418
+ });
419
+
420
+ reg({
421
+ name: "serena_replace_content",
422
+ label: "Serena Replace Content",
423
+ description: "Replace file content when symbolic editing isn't the right boundary.",
424
+ parameters: replaceContentSchema,
425
+ async execute(_id, params, _signal, _onUpdate, ctx) {
426
+ const normalized = { ...params };
427
+ if (typeof normalized.needle !== "string") return { content: [{ type: "text" as const, text: "serena_replace_content requires string parameter 'needle'." }], details: { ok: false } };
428
+ if (typeof normalized.repl !== "string") return { content: [{ type: "text" as const, text: "serena_replace_content requires string parameter 'repl'." }], details: { ok: false } };
429
+ const mode = normalized.mode ?? "literal";
430
+ if (mode !== "literal" && mode !== "regex") return { content: [{ type: "text" as const, text: "serena_replace_content requires mode to be 'literal' or 'regex'." }], details: { ok: false } };
431
+ normalized.mode = mode;
432
+ return callSerena(ctx, "replace_content", normalized, lockPathForRelativeFile(params));
433
+ },
434
+ });
435
+
436
+ reg({
437
+ name: "serena_restart_language_server",
438
+ label: "Serena Restart Language Server",
439
+ description: "Restart the language server when diagnostics are stale.",
440
+ promptGuidelines: ["For a full worker restart (Python bridge), use serena_restart_worker instead."],
441
+ parameters: emptyToolSchema,
442
+ async execute(_id, params, _signal, _onUpdate, ctx) {
443
+ return callWorkerAction(ctx, "restart_language_server", params);
444
+ },
445
+ });
446
+
447
+ reg({
448
+ name: "serena_restart_worker",
449
+ label: "Serena Restart Worker",
450
+ description: "Restart the persistent Serena Python worker process. Use when diagnostics seem stale or after configuration changes.",
451
+ promptGuidelines: ["Use when the worker is unresponsive; kills and re-spawns the Python bridge."],
452
+ parameters: emptyToolSchema,
453
+ async execute(_id, _params, _signal, _onUpdate, ctx) {
454
+ // restart() spawns eagerly; without Python installed it throws
455
+ // synchronously — surface that as a tool error, never a raw throw.
456
+ try {
457
+ getWorker().restart();
458
+ } catch (error) {
459
+ const msg = error instanceof Error ? error.message : String(error);
460
+ ctx.ui.notify?.(`Failed to restart Serena worker: ${msg}`, "error");
461
+ return {
462
+ content: [{ type: "text" as const, text: `Failed to restart Serena worker: ${msg}` }],
463
+ details: { ok: false, error: msg },
464
+ };
465
+ }
466
+ return {
467
+ content: [{ type: "text" as const, text: "Serena worker restarted." }],
468
+ details: { ok: true, result: "Worker restarted" },
469
+ };
470
+ },
471
+ });
472
+
473
+ reg({
474
+ name: "serena_get_current_config",
475
+ label: "Serena Current Config",
476
+ description: "Show current project/config details.",
477
+ parameters: emptyToolSchema,
478
+ async execute(_id, params, _signal, _onUpdate, ctx) {
479
+ const resp = await callWorkerAction(ctx, "config", params);
480
+ if (resp.details?.ok && typeof resp.details.result === "string") {
481
+ // Strip the "Available but not active" section — those are backend-only tools
482
+ // not callable as Pi tools, and listing them misleads the model.
483
+ const text = resp.details.result;
484
+ const cutoff = text.indexOf("\nAvailable but not active tools:");
485
+ if (cutoff >= 0) {
486
+ resp.content[0].text = text.slice(0, cutoff);
487
+ }
488
+ }
489
+ return resp;
490
+ },
491
+ });
492
+
493
+ reg({
494
+ name: "serena_check_onboarding_performed",
495
+ label: "Serena Check Onboarding",
496
+ description: "Check whether onboarding memories exist.",
497
+ parameters: emptyToolSchema,
498
+ async execute(_id, params, _signal, _onUpdate, ctx) {
499
+ return callSerena(ctx, "check_onboarding_performed", params);
500
+ },
501
+ });
502
+
503
+ reg({
504
+ name: "serena_onboarding",
505
+ label: "Serena Onboarding",
506
+ description: "Run onboarding prompt for project memories.",
507
+ parameters: emptyToolSchema,
508
+ async execute(_id, params, _signal, _onUpdate, ctx) {
509
+ return callSerena(ctx, "onboarding", params);
510
+ },
511
+ });
512
+
513
+ // ponytail: memory tools removed — use munin_search/munin_store/munin_get for all memory operations.
514
+ // Serena keeps only code-navigation tools (find_symbol, find_declaration, replace_body, etc.)
515
+
516
+ reg({
517
+ name: "serena_find_declaration",
518
+ label: "Serena Find Declaration",
519
+ description: "Find the declaration of a symbol via the language server.",
520
+ parameters: symbolRefSchema,
521
+ prepareArguments: (args) => repairSymbolNameKey(args, false),
522
+ async execute(_id, params, _signal, _onUpdate, ctx) {
523
+ return callWorkerAction(ctx, "find_declaration", params);
524
+ },
525
+ });
526
+
527
+ reg({
528
+ name: "serena_find_implementations",
529
+ label: "Serena Find Implementations",
530
+ description: "Find implementations of a symbol via the language server.",
531
+ parameters: symbolRefSchema,
532
+ prepareArguments: (args) => repairSymbolNameKey(args, false),
533
+ async execute(_id, params, _signal, _onUpdate, ctx) {
534
+ return callWorkerAction(ctx, "find_implementations", params);
535
+ },
536
+ });
537
+
538
+ reg({
539
+ name: "serena_get_diagnostics_for_file",
540
+ label: "Serena File Diagnostics",
541
+ description: "Get LSP diagnostics (errors, warnings, hints) for a file.",
542
+ parameters: diagnosticsSchema,
543
+ async execute(_id, params, _signal, _onUpdate, ctx) {
544
+ return callWorkerAction(ctx, "get_diagnostics_for_file", params);
545
+ },
546
+ });
547
+
548
+ pi.registerCommand("serena-dashboard", {
549
+ description: "Open the Serena dashboard for the current project",
550
+ handler: async (args, ctx) => {
551
+ const project = args?.trim() || process.cwd();
552
+ const response = await getWorker().request({ action: "dashboard", project, context: DEFAULT_CONTEXT, open: true });
553
+ if (response.ok) {
554
+ const opened = response.opened ? "opened" : "available";
555
+ ctx.ui.notify(`Serena dashboard ${opened}: ${response.dashboardUrl ?? "dashboard URL unavailable"}`, "info");
556
+ } else {
557
+ ctx.ui.notify(resultText(response), "error");
558
+ }
559
+ },
560
+ });
561
+
562
+ pi.registerCommand("serena-restart", {
563
+ description: "Restart the persistent Serena worker",
564
+ handler: async (_args, ctx) => {
565
+ try {
566
+ getWorker().restart();
567
+ ctx.ui.notify("Restarted Serena worker", "info");
568
+ } catch (error) {
569
+ const msg = error instanceof Error ? error.message : String(error);
570
+ ctx.ui.notify(`Failed to restart Serena worker: ${msg}`, "error");
571
+ }
572
+ },
573
+ });
574
+
575
+ // Serena guidance — only inject when serena tools are actually active
576
+ pi.on("before_agent_start", async (event) => {
577
+ // pi.getActiveTools() is the live registry — extension-registered tools
578
+ // (like serena_find_symbol) never appear in systemPromptOptions.selectedTools.
579
+ const serenaActive = isSerenaActive(pi.getActiveTools());
580
+ if (!serenaActive) return;
581
+ return {
582
+ systemPrompt: `${event.systemPrompt}\n\n${SERENA_FIRST_GUIDANCE}`,
583
+ };
584
+ });
585
+
586
+ pi.on("tool_call", async (event) => {
587
+ // Skip semantic miss detection if serena tools are not active (e.g., plan mode)
588
+ if (!isSerenaActive(pi.getActiveTools())) return;
589
+
590
+ // Strict mode blocks obvious raw code reads/searches in-band; no reminder steering.
591
+ const strict = process.env.PI_SERENA_STRICT === "1" || process.env.PI_SERENA_STRICT_MISSES === "1";
592
+ if (!strict) return;
593
+ if (shouldBlockSemanticMiss(event.toolName, event.input as Record<string, unknown>)) {
594
+ return { block: true, reason: `Serena-first mode: ${SERENA_MISS_GUIDANCE}` };
595
+ }
596
+ });
597
+
598
+ // Eager startup: pre-spawn the worker on session start when SERENA_EAGER_STARTUP=1
599
+ pi.on("session_start", async (_event, ctx) => {
600
+ if (process.env.SERENA_EAGER_STARTUP === "1") {
601
+ // Spawn the worker via a lightweight status request to warm the Python bridge
602
+ getWorker().request({ action: "status", project: process.cwd(), context: DEFAULT_CONTEXT }, 30_000).catch(() => {
603
+ // Eager startup is best-effort; failures are handled when the tool is first used
604
+ });
605
+ }
606
+ });
607
+
608
+ // session_shutdown fires only on parent lifecycle events (reload/quit/new/fork/
609
+ // resume) — child sessions (pi-subagent) use dispose() which does NOT emit it.
610
+ // So stopping here is safe: it never runs for children, and the module-level
611
+ // singleton means children reuse this worker without spawning their own.
612
+ //
613
+ // ponytail: known race — if a child is mid-serena-request when the parent
614
+ // reloads, worker.stop() rejects that request with "Serena worker stopped"
615
+ // instead of the child seeing a clean abort. The parent session teardown aborts
616
+ // the child's subagent tool call in the same tick anyway, so the child fails
617
+ // either way; no data is lost and the worker is cleaned up. Reference-counting
618
+ // the worker across parent+children was considered and rejected as
619
+ // over-engineering for a cosmetic error-text difference during teardown.
620
+ pi.on("session_shutdown", async (_event, ctx) => {
621
+ try {
622
+ await worker?.stop();
623
+ } catch {
624
+ // worker stop failed — proceed with cleanup
625
+ } finally {
626
+ worker = undefined;
627
+ }
628
+ });
629
+ }