ceulen 0.5.1 → 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,858 @@
1
+ import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { loadDotenvValues } from "./lib/env";
6
+ import { isProjectTrusted } from "../../lib/registry.js";
7
+
8
+ export type SerenaWorkerResponse = {
9
+ id: string | null;
10
+ ok: boolean;
11
+ result?: string;
12
+ error?: string;
13
+ [key: string]: unknown;
14
+ };
15
+
16
+ type Pending = {
17
+ resolve: (value: SerenaWorkerResponse) => void;
18
+ reject: (error: Error) => void;
19
+ timer: NodeJS.Timeout;
20
+ };
21
+
22
+ type QueuedRequest = {
23
+ payload: Record<string, unknown>;
24
+ timeoutMs: number;
25
+ resolve: (value: SerenaWorkerResponse) => void;
26
+ reject: (error: Error) => void;
27
+ };
28
+
29
+ // JetBrains backend tool remapping tables — single source of truth, interpolated
30
+ // into the Python bridge via JSON and unit-tested here (see worker.test.ts).
31
+ // Serena's internal 'jetbrains' mode excludes the LSP-flavored tools and activates
32
+ // only jet_brains_* variants; the bridge maps pi-facing names + params accordingly.
33
+ export const JB_TOOL_MAP: Record<string, string> = {
34
+ get_symbols_overview: "jet_brains_get_symbols_overview",
35
+ find_symbol: "jet_brains_find_symbol",
36
+ find_referencing_symbols: "jet_brains_find_referencing_symbols",
37
+ find_declaration: "jet_brains_find_declaration",
38
+ find_implementations: "jet_brains_find_implementations",
39
+ rename_symbol: "jet_brains_rename",
40
+ safe_delete_symbol: "jet_brains_safe_delete",
41
+ };
42
+
43
+ // LSP-only params the JetBrains variants do not accept (unknown kwargs raise TypeError).
44
+ export const JB_DROP_PARAMS: Record<string, string[]> = {
45
+ jet_brains_find_symbol: ["include_kinds", "exclude_kinds", "substring_matching"],
46
+ jet_brains_find_referencing_symbols: ["include_kinds", "exclude_kinds"],
47
+ };
48
+
49
+ // pi-facing param key -> JetBrains param key (safe_delete uses name_path, not name_path_pattern).
50
+ export const JB_PARAM_RENAMES: Record<string, Record<string, string>> = {
51
+ jet_brains_safe_delete: { name_path_pattern: "name_path" },
52
+ };
53
+
54
+ const PYTHON_BRIDGE = String.raw`
55
+ from __future__ import annotations
56
+
57
+ import contextlib
58
+ import json
59
+ import os
60
+ import sys
61
+ import traceback
62
+ from typing import Any
63
+
64
+ os.environ.setdefault("SERENA_USAGE_REPORTING", "false")
65
+
66
+ try:
67
+ from serena.agent import SerenaAgent
68
+ from serena.config.context_mode import SerenaAgentContext
69
+ from serena.config.serena_config import SerenaConfig, LanguageBackend
70
+ except Exception as exc:
71
+ print(json.dumps({"id": None, "ok": False, "error": f"Failed to import Serena: {type(exc).__name__}: {exc}"}), flush=True)
72
+ raise
73
+
74
+ try:
75
+ from serena import serena_version
76
+ except Exception:
77
+ serena_version = lambda: "unknown" # type: ignore
78
+
79
+ # Guarded monkeypatch to enable textDocument/publishDiagnostics in solidlsp
80
+ try:
81
+ from solidlsp.language_servers.typescript_language_server import TypeScriptLanguageServer
82
+ _orig_get_initialize_params = TypeScriptLanguageServer._get_initialize_params
83
+ def _patched_get_initialize_params(self, repository_absolute_path: str):
84
+ params = _orig_get_initialize_params(self, repository_absolute_path)
85
+ try:
86
+ params.setdefault("capabilities", {}).setdefault("textDocument", {}).setdefault("publishDiagnostics", {"relatedInformation": True, "versionSupport": True})
87
+ except Exception:
88
+ pass
89
+ return params
90
+ TypeScriptLanguageServer._get_initialize_params = _patched_get_initialize_params
91
+ except Exception:
92
+ pass
93
+
94
+ agents: dict[str, SerenaAgent] = {}
95
+ dashboard_opened: bool = False
96
+
97
+ def env_flag(name: str, default: bool) -> bool:
98
+ raw = os.environ.get(name)
99
+ if raw is None:
100
+ return default
101
+ return raw.strip().lower() in {"1", "true", "yes", "on"}
102
+
103
+
104
+ def load_bridge_config() -> SerenaConfig:
105
+ config = SerenaConfig.from_config_file()
106
+ # Pi keeps one worker per process/session. Keep dashboard available by default,
107
+ # but do not open browser tabs unless explicitly requested.
108
+ config.web_dashboard = env_flag("SERENA_BRIDGE_WEB_DASHBOARD", True)
109
+ config.web_dashboard_open_on_launch = env_flag("SERENA_BRIDGE_OPEN_DASHBOARD", False)
110
+ # SERENA_LANGUAGE_BACKEND selects the code-intelligence backend at worker startup.
111
+ # Unset = Serena's default (LSP). Invalid values raise LanguageBackend.from_str's
112
+ # ValueError, surfaced on worker start rather than silently falling back.
113
+ backend = os.environ.get("SERENA_LANGUAGE_BACKEND")
114
+ if backend:
115
+ config.language_backend = LanguageBackend.from_str(backend)
116
+ return config
117
+
118
+
119
+ # --- JetBrains backend tool remapping -------------------------------------
120
+ # Serena's internal 'jetbrains' mode excludes the LSP-flavored tools
121
+ # (find_symbol, get_symbols_overview, find_referencing_symbols, rename_symbol,
122
+ # safe_delete_symbol, restart_language_server) and activates only jet_brains_*
123
+ # variants. pi-serena keeps a stable pi-facing tool contract (serena_* tools),
124
+ # so the bridge transparently maps LSP-flavored names + params to the active
125
+ # JetBrains variants when the backend is JetBrains.
126
+
127
+ JB_TOOL_MAP = ${JSON.stringify(JB_TOOL_MAP)}
128
+ JB_DROP_PARAMS = ${JSON.stringify(JB_DROP_PARAMS)}
129
+ JB_PARAM_RENAMES = ${JSON.stringify(JB_PARAM_RENAMES)}
130
+
131
+
132
+ def resolve_jb_tool_call(tool_name: str, params: dict[str, Any]) -> tuple[str, dict[str, Any]]:
133
+ """Map an LSP-flavored pi tool call to the active JetBrains variant."""
134
+ jb_name = JB_TOOL_MAP.get(tool_name, tool_name)
135
+ mapped = dict(params)
136
+ for rename_from, rename_to in JB_PARAM_RENAMES.get(jb_name, {}).items():
137
+ if rename_from in mapped:
138
+ mapped[rename_to] = mapped.pop(rename_from)
139
+ for drop in JB_DROP_PARAMS.get(jb_name, set()):
140
+ mapped.pop(drop, None)
141
+ return jb_name, mapped
142
+
143
+
144
+ def classify_error(message: str) -> str:
145
+ if "Tool named" in message and "not found" in message:
146
+ return "missing_tool"
147
+ if "not active" in message:
148
+ return "inactive_tool"
149
+ if "No active project" in message or "Project" in message and "not found" in message:
150
+ return "project_error"
151
+ if "Cannot extract symbols" in message or "Active languages" in message or "language server" in message or "LSP" in message:
152
+ return "language_server_error"
153
+ return "serena_error"
154
+
155
+ def respond(payload: dict[str, Any]) -> None:
156
+ # ensure_ascii=True keeps the stdout wire format pure ASCII regardless of the
157
+ # host locale — Node reads stdout as UTF-8, and JSON.parse decodes \uXXXX
158
+ # escapes back to the original characters. ensure_ascii=False wrote raw
159
+ # non-ASCII bytes that sys.stdout encoded with the locale codec, garbling
160
+ # tool output on non-UTF-8 locales.
161
+ print(json.dumps(payload, ensure_ascii=True), flush=True)
162
+
163
+
164
+ def agent_key(project: str, context: str) -> str:
165
+ return f"{os.path.abspath(project)}\0{context}"
166
+
167
+
168
+ def get_agent(project: str, context: str) -> SerenaAgent:
169
+ key = agent_key(project, context)
170
+ agent = agents.get(key)
171
+ if agent is None:
172
+ with contextlib.redirect_stdout(sys.stderr):
173
+ agent = SerenaAgent(project=project, context=SerenaAgentContext.load(context), serena_config=load_bridge_config())
174
+ agents[key] = agent
175
+ return agent
176
+
177
+
178
+ def close_agents() -> None:
179
+ for key, agent in list(agents.items()):
180
+ try:
181
+ agent.on_shutdown()
182
+ except Exception as exc:
183
+ print(f"Error shutting down Serena agent {key}: {exc}", file=sys.stderr, flush=True)
184
+ agents.clear()
185
+
186
+
187
+ def handle(req: dict[str, Any]) -> dict[str, Any]:
188
+ req_id = req.get("id")
189
+ action = req.get("action")
190
+
191
+ if action == "shutdown":
192
+ close_agents()
193
+ return {"id": req_id, "ok": True, "shutdown": True}
194
+
195
+ if action == "status":
196
+ project = str(req.get("project") or os.getcwd())
197
+ context = str(req.get("context") or "ide")
198
+ data: dict[str, Any] = {
199
+ "id": req_id,
200
+ "ok": True,
201
+ "version": serena_version(),
202
+ "pid": os.getpid(),
203
+ "cachedAgents": len(agents),
204
+ "project": os.path.abspath(project),
205
+ "context": context,
206
+ }
207
+ if req.get("includeAgent"):
208
+ agent = get_agent(project, context)
209
+ data["activeTools"] = agent.get_active_tool_names()
210
+ active_project = agent.get_active_project()
211
+ data["activeProject"] = str(active_project.project_root) if active_project else None
212
+ data["languageBackend"] = agent.get_language_backend().value
213
+ data["dashboardUrl"] = agent.get_dashboard_url()
214
+ return data
215
+
216
+ if action == "dashboard":
217
+ project = str(req.get("project") or os.getcwd())
218
+ context = str(req.get("context") or "ide")
219
+ agent = get_agent(project, context)
220
+ global dashboard_opened
221
+ opened = False
222
+ if req.get("open"):
223
+ if not dashboard_opened:
224
+ opened = agent.open_dashboard()
225
+ dashboard_opened = opened
226
+ else:
227
+ opened = True
228
+ return {"id": req_id, "ok": True, "opened": opened, "dashboardUrl": agent.get_dashboard_url()}
229
+
230
+ if action == "config":
231
+ project = str(req.get("project") or os.getcwd())
232
+ context = str(req.get("context") or "ide")
233
+ agent = get_agent(project, context)
234
+ with contextlib.redirect_stdout(sys.stderr):
235
+ result = agent.get_current_config_overview()
236
+ return {"id": req_id, "ok": True, "tool": "get_current_config", "result": result}
237
+
238
+ if action == "restart_language_server":
239
+ project = str(req.get("project") or os.getcwd())
240
+ context = str(req.get("context") or "ide")
241
+ agent = get_agent(project, context)
242
+ if agent.get_language_backend().is_jetbrains():
243
+ # The JetBrains backend has no language server to restart.
244
+ return {"id": req_id, "ok": True, "tool": "restart_language_server", "result": "Language server restart is not applicable with the JetBrains backend."}
245
+ with contextlib.redirect_stdout(sys.stderr):
246
+ agent.reset_language_server_manager()
247
+ return {"id": req_id, "ok": True, "tool": "restart_language_server", "result": "OK"}
248
+
249
+ if action == "call":
250
+ project = str(req.get("project") or os.getcwd())
251
+ context = str(req.get("context") or "ide")
252
+ tool_name = req.get("tool")
253
+ params = req.get("params") or {}
254
+ if not isinstance(tool_name, str) or not tool_name:
255
+ raise ValueError("call request requires non-empty string field 'tool'")
256
+ if not isinstance(params, dict):
257
+ raise ValueError("call request field 'params' must be an object")
258
+ agent = get_agent(project, context)
259
+ if agent.get_language_backend().is_jetbrains():
260
+ tool_name, params = resolve_jb_tool_call(tool_name, params)
261
+ with contextlib.redirect_stdout(sys.stderr):
262
+ result = agent.get_tool_by_name(tool_name).apply_ex(**params)
263
+ # Serena's apply_ex catches many tool failures and returns an "Error: ..." string.
264
+ if isinstance(result, str) and result.startswith("Error"):
265
+ return {"id": req_id, "ok": False, "tool": tool_name, "errorType": classify_error(result), "error": result, "result": result}
266
+ return {"id": req_id, "ok": True, "tool": tool_name, "result": result}
267
+
268
+ if action in ("find_declaration", "find_implementations"):
269
+ return _handle_find_symbol_action(req_id, action, req)
270
+
271
+ if action == "get_diagnostics_for_file":
272
+ return _handle_diagnostics(req_id, req)
273
+
274
+ raise ValueError(f"Unknown action: {action}")
275
+
276
+
277
+ def _get_symbol_retriever(agent: SerenaAgent):
278
+ from serena.symbol import LanguageServerSymbolRetriever
279
+ project = agent.get_active_project_or_raise()
280
+ return project, LanguageServerSymbolRetriever(project)
281
+
282
+
283
+ def _jb_declaration_regexes(name_path: str) -> list[str]:
284
+ """Candidate one-group regexes for jet_brains_find_declaration.
285
+
286
+ The JetBrains variant locates the symbol via a regex with exactly one group
287
+ and require_unique=True (the whole regex must match exactly once in the
288
+ file). We try progressively looser declaration-context patterns so common
289
+ names (methods like request) still resolve; each alternative has exactly
290
+ one capturing group.
291
+ """
292
+ import re as _re
293
+ last = _re.escape(name_path.split("/")[-1].split("[")[0])
294
+ return [
295
+ rf"\b(?:class|interface|type|function|const|let|var|def|struct|enum|trait|impl)\s+({last})\b",
296
+ rf"(?<![.\w])({last})\s*\(",
297
+ rf"\b({last})\b",
298
+ ]
299
+
300
+
301
+ def _jb_pick_unique_symbol(symbols: list[dict], name_path: str) -> dict | None:
302
+ """Return the single symbol whose name_path exactly matches, else None.
303
+
304
+ find_symbol performs name-path *pattern* matching, so multiple symbols may
305
+ match (overloads foo[0]/foo[1], same-named methods in different classes,
306
+ a field and a method sharing a name). Picking an arbitrary match would
307
+ return the wrong declaration. Only a single match, or exactly one exact
308
+ name-path match, is accepted; otherwise the caller falls through to the
309
+ regex stage (which enforces uniqueness). Mirrored in worker.test.ts.
310
+ """
311
+ if not symbols:
312
+ return None
313
+ if len(symbols) == 1:
314
+ return symbols[0]
315
+ suffix = "/" + name_path
316
+ exact = [s for s in symbols if s.get("name_path") == name_path or (s.get("name_path") or "").endswith(suffix)]
317
+ return exact[0] if len(exact) == 1 else None
318
+
319
+
320
+ def _jb_is_declaration_position_error(result: str) -> bool:
321
+ """True when jet_brains_find_declaration reports the position IS the declaration.
322
+
323
+ The JetBrains plugin resolves declarations from a *reference* position; when
324
+ the regex lands on the declaration itself it reports something like "The
325
+ cursor may not be on a resolvable reference". That error text is plugin-
326
+ server-side (not in serena-agent), so match it tolerantly. Mirrored in
327
+ worker.test.ts.
328
+ """
329
+ import re as _re
330
+ return bool(_re.search(r"not.*resolvable|may not be on|is.*declaration|declaration.*itself", result, _re.IGNORECASE))
331
+
332
+
333
+ def _jb_find_declaration(agent: SerenaAgent, name_path: str, relative_path: str) -> str:
334
+ """Route find_declaration through the JetBrains backend.
335
+
336
+ Strategy (in order, first success wins):
337
+ 1. Resolve the symbol's exact location via the plugin client's find_symbol
338
+ (include_location=True) — the declaration position, no regex ambiguity.
339
+ This handles class fields/properties that the regex heuristics miss.
340
+ 2. Fall back to jet_brains_find_declaration with declaration-context regexes;
341
+ when the regex lands on the declaration itself the JetBrains API reports
342
+ "not on a resolvable reference", which means the position IS the declaration.
343
+ Any unresolved case returns an "Error:"-prefixed string so the caller classifies
344
+ it as a failure (never a bare "ValueError:" leaked as a success result).
345
+ """
346
+ import json as _json
347
+ from serena.jetbrains.jetbrains_plugin_client import JetBrainsPluginClient
348
+
349
+ project = agent.get_active_project_or_raise()
350
+ # Stage 1: direct location lookup (robust to ambiguous names).
351
+ try:
352
+ with contextlib.redirect_stdout(sys.stderr):
353
+ with JetBrainsPluginClient.from_project(project) as client:
354
+ response = client.find_symbol(
355
+ name_path=name_path, relative_path=relative_path,
356
+ depth=0, include_location=True,
357
+ )
358
+ symbols = response.get("symbols") or []
359
+ sym = _jb_pick_unique_symbol(symbols, name_path)
360
+ if sym is not None:
361
+ text_range = sym.get("text_range") or {}
362
+ start = text_range.get("start_pos") or {}
363
+ if start.get("line") is not None and start.get("col") is not None:
364
+ return _json.dumps({"symbols": [{"name_path": sym.get("name_path", name_path), "relative_path": sym.get("relative_path", relative_path), "type": sym.get("type", "unknown"), "text_range": {"start_pos": {"line": start["line"], "col": start["col"]}}}]}, indent=2)
365
+ except Exception as exc:
366
+ # Plugin/client error — log it, then fall through to the regex stage.
367
+ print(f"[_jb_find_declaration] stage 1 find_symbol failed, falling back to regex: {type(exc).__name__}: {exc}", file=sys.stderr, flush=True)
368
+
369
+ # Stage 2: regex fallback (handles symbols the plugin lookup misses).
370
+ from serena.util.text_utils import find_text_coordinates
371
+ tool = agent.get_tool_by_name("jet_brains_find_declaration")
372
+ content = tool.create_code_editor().read_file(relative_path)
373
+ last_error = None
374
+ for regex in _jb_declaration_regexes(name_path):
375
+ try:
376
+ coords = find_text_coordinates(content, regex, require_unique=True)
377
+ except ValueError as exc:
378
+ last_error = f"Error: {type(exc).__name__}: {exc}"
379
+ continue
380
+ if coords is None:
381
+ last_error = f"Error: no match for regex {regex}"
382
+ continue
383
+ with contextlib.redirect_stdout(sys.stderr):
384
+ result = tool.apply_ex(relative_path=relative_path, regex=regex)
385
+ if isinstance(result, str) and result.startswith("Error"):
386
+ last_error = result
387
+ if _jb_is_declaration_position_error(result):
388
+ # The regex matched the declaration itself — that IS the declaration.
389
+ return _json.dumps({"symbols": [{"name_path": name_path, "relative_path": relative_path, "type": "unknown", "text_range": {"start_pos": {"line": coords.line, "col": coords.col}}}]}, indent=2)
390
+ continue
391
+ return result
392
+ return last_error or f"Error: could not resolve declaration for {name_path}"
393
+
394
+
395
+ def _find_symbol_or_raise(retriever, name_path: str, relative_path: str):
396
+ return retriever.find_unique(
397
+ name_path, substring_matching=False, within_relative_path=relative_path
398
+ )
399
+
400
+
401
+ def _format_locations(locations) -> str:
402
+ import json
403
+ result = []
404
+ for loc in locations:
405
+ uri = loc.get("uri", "")
406
+ range_data = loc.get("range", {})
407
+ start = range_data.get("start", {})
408
+ end = range_data.get("end", {})
409
+ result.append({
410
+ "uri": uri,
411
+ "range": {
412
+ "start": {"line": start.get("line"), "character": start.get("character")},
413
+ "end": {"line": end.get("line"), "character": end.get("character")},
414
+ },
415
+ })
416
+ return json.dumps(result, indent=2)
417
+
418
+
419
+ def _handle_find_symbol_action(req_id, action: str, req: dict[str, Any]) -> dict[str, Any]:
420
+ project = str(req.get("project") or os.getcwd())
421
+ context = str(req.get("context") or "ide")
422
+ params = req.get("params") or {}
423
+ name_path = params.get("name_path")
424
+ relative_path = params.get("relative_path")
425
+ if not isinstance(name_path, str) or not name_path:
426
+ return {"id": req_id, "ok": False, "tool": action, "error": f"{action} requires string parameter 'name_path'"}
427
+ if not isinstance(relative_path, str) or not relative_path:
428
+ return {"id": req_id, "ok": False, "tool": action, "error": f"{action} requires string parameter 'relative_path'"}
429
+
430
+ agent = get_agent(project, context)
431
+ if agent.get_language_backend().is_jetbrains():
432
+ # Route through the active JetBrains tools: find_declaration locates the
433
+ # symbol via a one-group regex, find_implementations takes the name path.
434
+ if action == "find_declaration":
435
+ result = _jb_find_declaration(agent, name_path, relative_path)
436
+ else:
437
+ with contextlib.redirect_stdout(sys.stderr):
438
+ result = agent.get_tool_by_name("jet_brains_find_implementations").apply_ex(relative_path=relative_path, name_path=name_path)
439
+ if isinstance(result, str) and result.startswith("Error"):
440
+ return {"id": req_id, "ok": False, "tool": action, "errorType": classify_error(result), "error": result, "result": result}
441
+ return {"id": req_id, "ok": True, "tool": action, "result": result}
442
+
443
+ project_obj, retriever = _get_symbol_retriever(agent)
444
+ try:
445
+ symbol = _find_symbol_or_raise(retriever, name_path, relative_path)
446
+ except Exception as exc:
447
+ return {"id": req_id, "ok": False, "tool": action, "error": f"Error finding symbol {name_path}: {type(exc).__name__}: {exc}"}
448
+
449
+ if symbol is None:
450
+ return {"id": req_id, "ok": False, "tool": action, "error": f"Symbol {name_path} not found in {relative_path}"}
451
+
452
+ sym_rel_path = symbol.relative_path
453
+ sym_line = symbol.line
454
+ sym_col = symbol.column
455
+ if sym_rel_path is None or sym_line is None or sym_col is None:
456
+ return {"id": req_id, "ok": False, "tool": action, "error": f"Symbol {name_path} has no position info"}
457
+
458
+ ls_manager = project_obj.get_language_server_manager_or_raise()
459
+ lang_server = ls_manager.get_language_server(sym_rel_path)
460
+ if lang_server is None:
461
+ return {"id": req_id, "ok": False, "tool": action, "error": f"No language server available for {sym_rel_path}. The language server may not be active for this file type."}
462
+
463
+ if action == "find_declaration":
464
+ locations = lang_server.request_definition(sym_rel_path, sym_line, sym_col)
465
+ else:
466
+ locations = lang_server.request_implementation(sym_rel_path, sym_line, sym_col)
467
+
468
+ if not locations:
469
+ return {"id": req_id, "ok": True, "tool": action, "result": "No declarations found."}
470
+
471
+ result = _format_locations(locations)
472
+ return {"id": req_id, "ok": True, "tool": action, "result": result}
473
+
474
+
475
+ def _handle_diagnostics(req_id, req: dict[str, Any]) -> dict[str, Any]:
476
+ project = str(req.get("project") or os.getcwd())
477
+ context = str(req.get("context") or "ide")
478
+ params = req.get("params") or {}
479
+ relative_path = params.get("relative_path")
480
+ if not isinstance(relative_path, str) or not relative_path:
481
+ return {"id": req_id, "ok": False, "tool": "get_diagnostics_for_file", "error": "get_diagnostics_for_file requires string parameter 'relative_path'"}
482
+ if os.path.isabs(relative_path):
483
+ return {"id": req_id, "ok": False, "tool": "get_diagnostics_for_file", "error": "relative_path must be a relative path, not absolute"}
484
+
485
+ agent = get_agent(project, context)
486
+ if agent.get_language_backend().is_jetbrains():
487
+ # serena-agent 1.2.0 has no JetBrains diagnostics counterpart. serena_error
488
+ # (not language_server_error) so the hint doesn't suggest restarting the
489
+ # language server, which is not applicable to the JetBrains backend.
490
+ return {"id": req_id, "ok": False, "tool": "get_diagnostics_for_file", "errorType": "serena_error", "error": "get_diagnostics_for_file requires the LSP backend; the JetBrains backend does not provide file diagnostics.", "result": json.dumps({"note": "Not applicable with the JetBrains backend."})}
491
+
492
+ import json as _json
493
+ import pathlib
494
+ from pathlib import PurePath
495
+
496
+ project_obj = agent.get_active_project_or_raise()
497
+ ls_manager = agent.execute_task(project_obj.get_language_server_manager_or_raise, name="GetDiagnosticsLanguageServerManager")
498
+ lang_server = ls_manager.get_language_server(relative_path)
499
+ if lang_server is None:
500
+ return {"id": req_id, "ok": False, "tool": "get_diagnostics_for_file", "error": f"No language server available for {relative_path}"}
501
+
502
+ try:
503
+ # Resolve full path and verify it does not escape the repository root
504
+ repo_root = str(pathlib.Path(lang_server.repository_root_path).resolve())
505
+ full_path = str(pathlib.Path(str(PurePath(lang_server.repository_root_path, relative_path))).resolve())
506
+ if not str(pathlib.Path(repo_root) / '') == os.path.commonpath([repo_root, full_path]):
507
+ return {"id": req_id, "ok": False, "tool": "get_diagnostics_for_file", "error": f"Path traversal detected: {relative_path} escapes the repository root"}
508
+ uri = pathlib.Path(full_path).as_uri()
509
+
510
+ import threading
511
+ captured = None
512
+ event = threading.Event()
513
+
514
+ def on_publish(params: dict[str, Any]) -> None:
515
+ nonlocal captured
516
+ if prev_handler:
517
+ try:
518
+ prev_handler(params)
519
+ except Exception:
520
+ pass
521
+ if params.get("uri") == uri:
522
+ captured = params
523
+ event.set()
524
+
525
+ prev_handler = lang_server.server.on_notification_handlers.get("textDocument/publishDiagnostics")
526
+ lang_server.server.on_notification("textDocument/publishDiagnostics", on_publish)
527
+
528
+ try:
529
+ with lang_server.open_file(relative_path):
530
+ event.wait(timeout=3.0)
531
+ if captured is not None:
532
+ res_val = _json.dumps(captured, indent=2, default=str)
533
+ return {"id": req_id, "ok": True, "tool": "get_diagnostics_for_file", "result": res_val}
534
+
535
+ # Fallback to pull diagnostics
536
+ result = lang_server.server.send.text_document_diagnostic({
537
+ "textDocument": {"uri": uri},
538
+ })
539
+ return {"id": req_id, "ok": True, "tool": "get_diagnostics_for_file", "result": _json.dumps(result, indent=2, default=str)}
540
+ finally:
541
+ if prev_handler:
542
+ lang_server.server.on_notification("textDocument/publishDiagnostics", prev_handler)
543
+ else:
544
+ lang_server.server.on_notification_handlers.pop("textDocument/publishDiagnostics", None)
545
+ except Exception as exc:
546
+ if isinstance(exc, AttributeError) or getattr(getattr(exc, "cause", None), "code", None) == -32601:
547
+ return {"id": req_id, "ok": True, "tool": "get_diagnostics_for_file", "result": _json.dumps({"note": "Language server does not support pull diagnostics (textDocument/diagnostic) and did not push them within timeout"})}
548
+ err_msg = f"Diagnostics error for {relative_path}: {exc}"
549
+ return {"id": req_id, "ok": False, "tool": "get_diagnostics_for_file", "error": err_msg, "errorType": "language_server_error", "result": _json.dumps({"note": err_msg})}
550
+
551
+
552
+
553
+ def main() -> int:
554
+ try:
555
+ for line in sys.stdin:
556
+ line = line.strip()
557
+ if not line:
558
+ continue
559
+ req_id = None
560
+ try:
561
+ req = json.loads(line)
562
+ if not isinstance(req, dict):
563
+ raise ValueError("request must be a JSON object")
564
+ req_id = req.get("id")
565
+ response = handle(req)
566
+ respond(response)
567
+ if req.get("action") == "shutdown":
568
+ return 0
569
+ except Exception as exc:
570
+ message = f"{type(exc).__name__}: {exc}"
571
+ print(traceback.format_exc(), file=sys.stderr, flush=True)
572
+ respond({"id": req_id, "ok": False, "errorType": classify_error(message), "error": message})
573
+ finally:
574
+ close_agents()
575
+ return 0
576
+
577
+ if __name__ == "__main__":
578
+ raise SystemExit(main())
579
+ `;
580
+
581
+ function runSync(command: string, args: string[]): string | undefined {
582
+ try {
583
+ const result = spawnSync(command, args, { encoding: "utf8" });
584
+ if (result.status === 0) return String(result.stdout).trim().replace(/\u001b\[[0-9;]*m/g, "");
585
+ } catch {
586
+ // ignore discovery failures
587
+ }
588
+ return undefined;
589
+ }
590
+
591
+ function serenaPythonCandidates(): string[] {
592
+ const candidates: string[] = [];
593
+ const configured = process.env.SERENA_PYTHON;
594
+ if (configured) candidates.push(configured);
595
+
596
+ const addToolDirCandidates = (toolDir: string | undefined) => {
597
+ if (!toolDir) return;
598
+ candidates.push(
599
+ path.join(toolDir, "serena-agent", "Scripts", "python.exe"),
600
+ path.join(toolDir, "serena-agent", "bin", "python"),
601
+ );
602
+ };
603
+
604
+ addToolDirCandidates(runSync("uv", ["tool", "dir"]));
605
+
606
+ const uvFromBash = runSync("bash", ["-lc", "command -v uv"]);
607
+ if (uvFromBash) addToolDirCandidates(runSync(uvFromBash, ["tool", "dir"]));
608
+
609
+ addToolDirCandidates(path.join(os.homedir(), ".local", "share", "uv", "tools"));
610
+ addToolDirCandidates(path.join(os.homedir(), "AppData", "Roaming", "uv", "tools"));
611
+
612
+ return [...new Set(candidates)];
613
+ }
614
+
615
+ function findSerenaPython(): string | undefined {
616
+ return serenaPythonCandidates().find((candidate) => fs.existsSync(candidate));
617
+ }
618
+
619
+ export class SerenaWorkerClient {
620
+ private process?: ChildProcessWithoutNullStreams;
621
+ private buffer = "";
622
+ private nextId = 1;
623
+ private pending = new Map<string, Pending>();
624
+ private queue: QueuedRequest[] = [];
625
+ private processing = false;
626
+ private stopping = false;
627
+ private generation = 0;
628
+ private spawning = false;
629
+
630
+ constructor(private readonly onStatus?: (text: string | undefined) => void) {}
631
+
632
+ async request(payload: Record<string, unknown>, timeoutMs = 120_000): Promise<SerenaWorkerResponse> {
633
+ return new Promise((resolve, reject) => {
634
+ this.queue.push({ payload, timeoutMs, resolve, reject });
635
+ this.processQueue();
636
+ });
637
+ }
638
+
639
+ async stop(): Promise<void> {
640
+ this.stopping = true;
641
+ this.rejectQueued(new Error("Serena worker stopped"));
642
+ this.failAll(new Error("Serena worker stopped"));
643
+ const proc = this.process;
644
+ if (!proc) {
645
+ this.stopping = false;
646
+ return;
647
+ }
648
+ try {
649
+ await new Promise<void>((resolve) => {
650
+ const id = String(this.nextId++);
651
+ const timer = setTimeout(() => {
652
+ this.pending.delete(id);
653
+ resolve();
654
+ }, 2000);
655
+ this.pending.set(id, {
656
+ resolve: () => { clearTimeout(timer); this.pending.delete(id); resolve(); },
657
+ reject: () => { clearTimeout(timer); this.pending.delete(id); resolve(); },
658
+ timer,
659
+ });
660
+ try {
661
+ proc.stdin.write(`${JSON.stringify({ id, action: "shutdown" })}\n`);
662
+ } catch {
663
+ clearTimeout(timer);
664
+ this.pending.delete(id);
665
+ resolve();
666
+ }
667
+ });
668
+ } catch {
669
+ // ignore
670
+ } finally {
671
+ proc.kill();
672
+ if (this.process === proc) {
673
+ this.process = undefined;
674
+ this.processing = false;
675
+ this.onStatus?.(undefined);
676
+ }
677
+ // Requests enqueued while we awaited the shutdown ack never started
678
+ // (processQueue early-returns while stopping) — settle them instead of
679
+ // leaving them queued forever.
680
+ this.rejectQueued(new Error("Serena worker stopped"));
681
+ this.stopping = false;
682
+ }
683
+ }
684
+
685
+ restart(): void {
686
+ if (this.process) this.process.kill();
687
+ this.rejectQueued(new Error("Serena worker restarted"));
688
+ this.failAll(new Error("Serena worker restarted"));
689
+ this.process = undefined;
690
+ this.processing = false;
691
+ this.ensureStarted();
692
+ }
693
+
694
+ private ensureStarted(): void {
695
+ if (this.spawning) return;
696
+ if (this.process && !this.process.killed && this.process.exitCode === null && this.process.signalCode === null) return;
697
+ this.spawning = true;
698
+ try {
699
+ const python = findSerenaPython();
700
+ if (!python) {
701
+ const checked = serenaPythonCandidates().map((candidate) => `- ${candidate}`).join("\n") || "- none";
702
+ throw new Error(
703
+ `Could not find Serena Python. Install with: uv tool install -p 3.13 serena-agent && serena init, or set SERENA_PYTHON to the serena-agent Python executable. Checked:\n${checked}`
704
+ );
705
+ }
706
+
707
+ this.generation += 1;
708
+ const proc = spawn(python, ["-u", "-c", PYTHON_BRIDGE], {
709
+ // Merge dot-file values (cwd .env.local/.env, then Pi global config) into the
710
+ // worker env so SERENA_* knobs work from project/global dot files, matching the
711
+ // rest of the monorepo. process.env always wins; first dot file wins.
712
+ // SERENA_USAGE_REPORTING defaults to "false" inside the Python bridge
713
+ // (os.environ.setdefault), so dot-file opt-in works without a TS-side override.
714
+ // SECURITY: cwd .env files are untrusted repo content (they can set
715
+ // NODE_OPTIONS/PYTHONPATH and reach the language servers this worker
716
+ // spawns) — they are only merged when the project is trusted (same rule
717
+ // as the bundle's lib/env.ts); the global agent-dir dot files always load.
718
+ env: { ...process.env, ...loadDotenvValues(process.cwd(), isProjectTrusted(process.cwd())) },
719
+ stdio: "pipe",
720
+ });
721
+ this.process = proc;
722
+ this.buffer = "";
723
+ this.onStatus?.(`Serena worker pid ${proc.pid} gen ${this.generation}`);
724
+ this.spawning = false;
725
+
726
+ proc.stdout.setEncoding('utf8');
727
+ proc.stdout.on("data", (chunk) => this.onStdout(String(chunk)));
728
+ proc.stderr.on("data", (chunk) => process.stderr.write(`[serena-worker] ${String(chunk)}`));
729
+ proc.stdin.on('error', () => {});
730
+ proc.on('error', (err) => {
731
+ if (this.process === proc) {
732
+ this.process = undefined;
733
+ this.onStatus?.(undefined);
734
+ this.processing = false;
735
+ this.failAll(new Error(`Serena worker process error: ${err.message}`));
736
+ }
737
+ });
738
+ proc.on("exit", (code, signal) => {
739
+ if (this.process === proc) {
740
+ this.process = undefined;
741
+ this.onStatus?.(undefined);
742
+ this.processing = false;
743
+ this.failAll(new Error(`Serena worker exited code=${code} signal=${signal}`));
744
+ }
745
+ });
746
+ } catch (error) {
747
+ this.spawning = false;
748
+ throw error;
749
+ }
750
+ }
751
+
752
+ private processQueue(): void {
753
+ if (this.processing || this.stopping) return;
754
+ const item = this.queue.shift();
755
+ if (!item) return;
756
+ this.processing = true;
757
+ try {
758
+ this.ensureStarted();
759
+ } catch (error) {
760
+ this.processing = false;
761
+ item.reject(error instanceof Error ? error : new Error(String(error)));
762
+ queueMicrotask(() => this.processQueue());
763
+ return;
764
+ }
765
+ const id = String(this.nextId++);
766
+ const request = { id, ...item.payload };
767
+ const finish = () => {
768
+ this.processing = false;
769
+ queueMicrotask(() => this.processQueue());
770
+ };
771
+ const timer = setTimeout(() => {
772
+ this.pending.delete(id);
773
+ this.killAndReset(false);
774
+ finish();
775
+ item.reject(new Error(
776
+ `Serena worker request timed out: ${item.payload.action ?? "unknown"}. ` +
777
+ `Worker has been restarted; if this was a write action, verify state before retrying — it may have partially applied.`
778
+ ));
779
+ }, item.timeoutMs);
780
+ this.pending.set(id, {
781
+ resolve: (value) => {
782
+ finish();
783
+ item.resolve(value);
784
+ },
785
+ reject: (error) => {
786
+ finish();
787
+ item.reject(error);
788
+ },
789
+ timer,
790
+ });
791
+ try {
792
+ this.process?.stdin.write(`${JSON.stringify(request)}\n`);
793
+ } catch (err) {
794
+ clearTimeout(timer);
795
+ this.pending.delete(id);
796
+ this.processing = false;
797
+ item.reject(err instanceof Error ? err : new Error(String(err)));
798
+ queueMicrotask(() => this.processQueue());
799
+ }
800
+ }
801
+
802
+ private onStdout(chunk: string): void {
803
+ this.buffer += chunk;
804
+ let index: number;
805
+ while ((index = this.buffer.indexOf("\n")) >= 0) {
806
+ const line = this.buffer.slice(0, index).trim();
807
+ this.buffer = this.buffer.slice(index + 1);
808
+ if (!line) continue;
809
+ let response: SerenaWorkerResponse;
810
+ try {
811
+ response = JSON.parse(line) as SerenaWorkerResponse;
812
+ } catch {
813
+ process.stderr.write(`[serena-worker] non-json stdout: ${line}\n`);
814
+ continue;
815
+ }
816
+ const id = response.id;
817
+ if (!id) {
818
+ // Responses with null/undefined id are not tied to a pending request.
819
+ // Surface errors (e.g. Python bridge import failures) so they aren't silently lost.
820
+ if (response.ok === false && response.error) {
821
+ process.stderr.write(`[serena-worker] error (no id): ${response.error}\n`);
822
+ }
823
+ continue;
824
+ }
825
+ const pending = this.pending.get(id);
826
+ if (!pending) continue;
827
+ this.pending.delete(id);
828
+ clearTimeout(pending.timer);
829
+ pending.resolve(response);
830
+ }
831
+ }
832
+
833
+ private killAndReset(rejectPending = true): void {
834
+ if (this.process) {
835
+ this.process.kill();
836
+ this.process = undefined;
837
+ this.onStatus?.(undefined);
838
+ }
839
+ if (rejectPending) {
840
+ this.processing = false;
841
+ this.failAll(new Error("Serena worker killed due to timeout, restarted"));
842
+ }
843
+ this.buffer = "";
844
+ }
845
+
846
+ private rejectQueued(error: Error): void {
847
+ for (const item of this.queue.splice(0)) item.reject(error);
848
+ }
849
+
850
+ private failAll(error: Error): void {
851
+ this.processing = false;
852
+ for (const [id, pending] of this.pending) {
853
+ clearTimeout(pending.timer);
854
+ pending.reject(error);
855
+ this.pending.delete(id);
856
+ }
857
+ }
858
+ }