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,616 @@
1
+ /**
2
+ * steering — per-model-family steering for ceulen.
3
+ *
4
+ * Ported from @bacnh85/pi-model-tools 0.9.5 (extensions/index.ts): the
5
+ * model-FAMILY half of that extension, with two things deliberately left to
6
+ * their own ceulen modules —
7
+ * • the tool-input repair / edit-repair / apply_patch / str_replace_editor
8
+ * TOOLS (the "repair" module),
9
+ * • the zai-provider hooks (before_provider_headers, after_provider_response,
10
+ * fast-mode body) — the "zai" module.
11
+ *
12
+ * What stays here is everything that depends on knowing WHICH model family is
13
+ * serving the request, plus the DeepSeek v4 Pro minimal-mode anchor:
14
+ *
15
+ * 1. family detection (deepseek-v4 | glm), latched from the requested model
16
+ * and the session-captured one (proxies rewrite ctx.model between hooks).
17
+ * 2. cache-safe prompt composition — static blocks (Super Power, selection
18
+ * guidance, apply_patch preference) prepend/append to the system prompt,
19
+ * while per-turn blocks (error hints, first-tool hints) ride the CURRENT
20
+ * user message tail via before_provider_request, so the cache head stays
21
+ * byte-identical.
22
+ * 3. reasoning_content strip + leaked-content cleaning of the request history.
23
+ * 4. tool-error categorization → the next turn's recovery hint, plus the
24
+ * reasoning-accumulation 400 detector.
25
+ * 5. DeepSeek-only semantic-miss / dedicated-tool steering on tool_call.
26
+ * 6. the ds-anchor two-phase bootstrap for deepseek-v4-pro.
27
+ *
28
+ * ORDERING CONTRACT (why this module is its own unit): in ceulen's registry
29
+ * `steering` loads AFTER ponytail and subagent, so this `before_agent_start`
30
+ * handler runs LAST in the chain (each handler's returned systemPrompt becomes
31
+ * the next handler's event.systemPrompt). Therefore:
32
+ * • the bootstrap branch deliberately REPLACES the whole prompt — everything
33
+ * earlier handlers composed is sacrificed for request #1, which is the
34
+ * entire point of the anchor;
35
+ * • every other branch COMPOSES: the incoming systemPrompt is preserved
36
+ * verbatim and only prepended/appended to. Never clobber outside bootstrap.
37
+ *
38
+ * Config: the `steering` section of the agent-dir settings.json, overlaid by a
39
+ * trusted project `.pi/settings.json` (lib/settings.ts), read per turn — so
40
+ * /config → Model → Steering applies without /reload.
41
+ */
42
+ // ponytail: ported from @bacnh85/pi-model-tools 0.9.5 extensions/index.ts (the
43
+ // hooks + state machine); the repair tools/hooks and the zai provider hooks are
44
+ // excluded — they are their own ceulen modules. The PI_MODEL_TOOLS_* env knobs
45
+ // became `steering` settings rows, with two dropped: the auto-block-after-
46
+ // reminders threshold is now a fixed policy inside strictSerena, and the
47
+ // reasoning-truncation budget is a function argument.
48
+
49
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
50
+ import { detectFamily, type ModelFamily } from "./lib/family.js";
51
+ import {
52
+ applyPatchPreferenceGuidance,
53
+ clearGuidanceCache,
54
+ deepSeekSelectionGuidance,
55
+ githubCloneFirstToolHint,
56
+ readUncertainPathHint,
57
+ runTaskFirstToolHint,
58
+ superPowerPrompt,
59
+ } from "./lib/guidance.js";
60
+ import {
61
+ appendGuidanceToLastUserMessage,
62
+ cleanLeakedContentFromMessages,
63
+ stripReasoningContent,
64
+ tailIsPlainUserPrompt,
65
+ } from "./lib/history.js";
66
+ import {
67
+ BOOTSTRAP_TOOLS,
68
+ MINIMAL_SYSTEM_PROMPT,
69
+ WE_NEED_DIRECTIVE,
70
+ dshBootstrapTools,
71
+ hasPromotionSignal,
72
+ isAnchorTarget,
73
+ } from "./lib/anchor.js";
74
+ import {
75
+ categorizeToolError,
76
+ detectReasoningRejection,
77
+ isSemanticMissToolCall,
78
+ missedDedicatedTool,
79
+ suggestBestSerenaCommand,
80
+ type ErrorCategory,
81
+ type ErrorInfo,
82
+ } from "./lib/errors.js";
83
+ import { readSteeringSettings, type SteeringSettings } from "./lib/settings.js";
84
+
85
+ // The integrator may import the /config contribution from either file
86
+ // (classifier imports configPanel, composer re-exports from index).
87
+ export { steeringConfig } from "./configPanel.js";
88
+
89
+ /** Reminder count at which STRICT Serena mode escalates a repeated
90
+ * bash-instead-of-dedicated-tool miss to a block. Upstream's
91
+ * PI_MODEL_TOOLS_AUTO_BLOCK_AFTER_REMINDERS knob is dropped: the policy is
92
+ * fixed and only engaged under `steering.strictSerena`. ponytail: if a
93
+ * different number is ever needed it becomes a settings row next to the
94
+ * toggle. */
95
+ const BLOCK_AFTER_REMINDERS = 3;
96
+ /** Cap on the per-tool error-history map (upstream's default). */
97
+ const MAX_ERROR_HISTORY = 100;
98
+ /** DSH's captured minimal-mode output budget — pinned on the bootstrap request. */
99
+ const BOOTSTRAP_MAX_TOKENS = 256000;
100
+ /** customType for steering notes. LLM-visible (unlike …status output). */
101
+ const STEERING_MESSAGE_TYPE = "ceulen-steering";
102
+
103
+ /** Defensive view of the assistant message fields index.ts reads (usage and
104
+ * stopReason are typed non-optional, but OpenAI-compatible providers emit
105
+ * partial/NaN records and tests inject them). */
106
+ interface AssistantLike {
107
+ role?: string;
108
+ stopReason?: string;
109
+ errorMessage?: string;
110
+ content?: unknown[];
111
+ usage?: { input?: unknown; output?: unknown; cacheRead?: unknown; cacheWrite?: unknown };
112
+ }
113
+
114
+ export default function steeringModule(pi: ExtensionAPI): void {
115
+ let sessionModel: { provider?: string; id?: string } | undefined;
116
+ let activeFamily: ModelFamily | null = null;
117
+ let hasErrorThisTurn = false;
118
+ let lastErrorInfo: ErrorInfo | null = null;
119
+ let remindedThisTurn = false;
120
+ let turnCounter = 0;
121
+ const cacheStats = { input: 0, cacheRead: 0, cacheWrite: 0, hitTurns: 0, missTurns: 0 };
122
+ // Per-turn dynamic guidance (error notes, first-tool hints, periodic
123
+ // reinforcement) stashed here and appended to the CURRENT user message by
124
+ // before_provider_request — never the system prompt (the cache head).
125
+ let pendingGuidance: string | undefined;
126
+ // Effective settings — refreshed per turn (before_agent_start) and at
127
+ // session_start (the anchor bootstrap keys off dsAnchor/weNeed).
128
+ let settings: SteeringSettings = readSteeringSettings();
129
+
130
+ // DeepSeek v4 Pro minimal-mode anchor (two-phase bootstrap) state.
131
+ // Invariant: anchorBootstrapping = dsAnchor && target && !anchorPromoted.
132
+ let anchorReady = false;
133
+ let anchorPromoted = false;
134
+ let anchorRunActive = false;
135
+ let anchorInspectedCount = 0;
136
+ let anchorWarned = false;
137
+ // Last-known thinking level (thinking_level_select) — surfaced in status
138
+ // because the DSH minimal-mode recipe requires max thinking.
139
+ let currentThinking: string | undefined;
140
+ // Ring buffer of anchor decisions — surfaced by /steering so the bootstrap can
141
+ // be verified without any debug env.
142
+ const anchorTrace: string[] = [];
143
+ function anchorTracePush(line: string) {
144
+ anchorTrace.push(`${new Date().toISOString().slice(11, 19)} ${line}`);
145
+ if (anchorTrace.length > 8) anchorTrace.shift();
146
+ }
147
+
148
+ const reminderCounts = new Map<string, number>();
149
+ const errorHistory = new Map<string, { count: number; lastCategory: ErrorCategory }>();
150
+
151
+ function recordError(toolName: string, category: ErrorCategory) {
152
+ errorHistory.set(toolName, { count: (errorHistory.get(toolName)?.count ?? 0) + 1, lastCategory: category });
153
+ while (errorHistory.size > MAX_ERROR_HISTORY) errorHistory.delete(errorHistory.keys().next().value!);
154
+ }
155
+
156
+ // Detection: check both ctx.model and session-captured model
157
+ function family(model?: { provider?: string; id?: string }): ModelFamily | null {
158
+ return detectFamily(model) ?? detectFamily(sessionModel);
159
+ }
160
+
161
+ // Anchor target: check BOTH ctx.model and session-captured model — proxies
162
+ // rewrite ctx.model between hooks (see family() above for the same defense).
163
+ function anchorTarget(model?: { id?: string }): boolean {
164
+ return settings.dsAnchor && (isAnchorTarget(model?.id) || isAnchorTarget(sessionModel?.id));
165
+ }
166
+
167
+ function warnAnchorOnce(ctx: ExtensionContext, message: string) {
168
+ if (anchorWarned) return;
169
+ anchorWarned = true;
170
+ try { ctx.ui?.notify?.(message, "warning"); } catch { /* no UI */ }
171
+ }
172
+
173
+ // Scan durable entries for a promotion signal; fail-open on error.
174
+ function scanAnchorEntries(ctx: ExtensionContext) {
175
+ if (anchorPromoted) return;
176
+ try {
177
+ const entries = ctx.sessionManager.getEntries() as unknown[];
178
+ const from = entries.length >= anchorInspectedCount ? anchorInspectedCount : 0;
179
+ if (hasPromotionSignal(entries.slice(from) as never)) anchorPromoted = true;
180
+ anchorInspectedCount = entries.length;
181
+ if (!anchorReady) anchorReady = true;
182
+ } catch {
183
+ anchorPromoted = true;
184
+ warnAnchorOnce(ctx, "steering: ds-anchor session inspection failed; full catalog exposed");
185
+ }
186
+ }
187
+
188
+ function anchorBootstrapping(model?: { id?: string }): boolean {
189
+ // Target check per hook — proxies rewrite ctx.model between hooks WITHOUT
190
+ // firing model_select (e.g. a session requested as flash that is served
191
+ // deepseek-v4-pro). Requiring a session_start-latched ready flag silently
192
+ // skipped the bootstrap for such sessions — the exact failure observed in
193
+ // a live a2a gateway session. anchorReady is display-only here.
194
+ const target = anchorTarget(model);
195
+ if (target && !anchorReady) anchorReady = true;
196
+ return target && !anchorPromoted;
197
+ }
198
+
199
+ // ── /steering ──
200
+ pi.registerCommand("steering", {
201
+ description: "Show per-model-family steering state: active family, flags, ds-anchor, prompt-cache stats.",
202
+ handler: async (_args, cmdCtx) => {
203
+ const anchorActive = anchorTarget(cmdCtx.model); // includes sessionModel fallback
204
+ const anchorState = !anchorActive || !anchorReady
205
+ ? "off"
206
+ : anchorPromoted ? "promoted" : "bootstrapping";
207
+ const totalErrors = [...errorHistory.values()].reduce((sum, e) => sum + e.count, 0);
208
+ const status = [
209
+ "## steering status",
210
+ "",
211
+ `**Active family:** ${activeFamily ?? family(cmdCtx.model) ?? "none"}`,
212
+ ` Requested: ${sessionModel?.provider ?? "none"}/${sessionModel?.id ?? "none"}`,
213
+ ` Served: ${cmdCtx.model?.provider ?? "none"}/${cmdCtx.model?.id ?? "none"}`,
214
+ "",
215
+ "**Steering (settings section `steering`):**",
216
+ ` First-tool hints (all families): ${settings.firstToolHints ? "on" : "off"}`,
217
+ ` Selection guidance (DeepSeek V4): ${settings.selectionGuidance ? "on" : "off"}`,
218
+ ` Super Power Mode (DeepSeek V4): ${settings.superpower ? "on" : "off"}${settings.superpowerPrompt ? " (custom prompt)" : ""}`,
219
+ ` Strict Serena (DeepSeek V4): ${settings.strictSerena ? `on (block after ${BLOCK_AFTER_REMINDERS} reminders)` : "off"}`,
220
+ ` Reasoning strip: ${settings.stripReasoning ? "on" : "off"}`,
221
+ ` Leaked content cleaning: always on for detected families`,
222
+ ` ds-anchor (deepseek-v4-pro): ${anchorState}`,
223
+ ` We-need directive (bootstrap): ${settings.weNeed ? "on" : "off"}`,
224
+ ` Thinking level: ${currentThinking ?? "unknown"}${currentThinking !== "max" && anchorActive ? " (recipe wants max)" : ""}`,
225
+ ` Super Power turns: ${turnCounter}`,
226
+ "",
227
+ ...(cacheStats.input > 0
228
+ ? (() => {
229
+ // hitPct = cacheRead / (input + cacheRead + cacheWrite). On
230
+ // DeepSeek, cacheWrite is always 0 (the OpenAI-compatible API does
231
+ // not emit cache_write_tokens), so this is cacheRead / (input +
232
+ // cacheRead). The `input` portion is the inherently uncached
233
+ // growing tail (new user messages + tool results); hitPct reaches
234
+ // ~98-99% on a warm, stable session whose byte-stable prefix is
235
+ // fully cached.
236
+ const total = cacheStats.input + cacheStats.cacheRead + cacheStats.cacheWrite;
237
+ const hitPct = total > 0 ? Math.round((cacheStats.cacheRead / total) * 100) : 0;
238
+ return [
239
+ "**Prompt cache (this session):**",
240
+ ` Input: ${cacheStats.input.toLocaleString()} · cached: ${cacheStats.cacheRead.toLocaleString()} · written: ${cacheStats.cacheWrite.toLocaleString()}`,
241
+ ` Hit rate: ${hitPct}% (${cacheStats.hitTurns} hit turns · ${cacheStats.missTurns} miss turns)`,
242
+ "",
243
+ ];
244
+ })()
245
+ : []),
246
+ `**Errors:** ${totalErrors} total${lastErrorInfo ? `, last: ${lastErrorInfo.category} on ${lastErrorInfo.toolName}` : ""}`,
247
+ ...(anchorTrace.length > 0 ? ["", "**ds-anchor trace:**", ...anchorTrace.map((l) => ` ${l}`)] : []),
248
+ ];
249
+ cmdCtx.ui.notify(status.join("\n"), "info");
250
+ },
251
+ });
252
+
253
+ // ── session_start ──
254
+ pi.on("session_start", (_event, ctx) => {
255
+ sessionModel = ctx.model ? { id: ctx.model.id, provider: ctx.model.provider } : undefined;
256
+ settings = readSteeringSettings(ctx);
257
+ // Capture the session's initial thinking level: thinking_level_select only
258
+ // fires on CHANGES, so a session born at max would otherwise show "unknown"
259
+ // — exactly the case the DSH recipe cares about.
260
+ currentThinking = ctx.thinkingLevel;
261
+ // ds-anchor: reset and init from durable state (resume of a session that
262
+ // already has an assistant reply = instantly promoted, no bootstrap).
263
+ anchorReady = anchorTarget(ctx.model);
264
+ anchorPromoted = false;
265
+ anchorRunActive = false;
266
+ anchorInspectedCount = 0;
267
+ anchorWarned = false;
268
+ anchorTrace.length = 0; // per-session trace — never leak prior-session lines
269
+ anchorTracePush(`session_start: requested=${ctx.model?.id ?? "?"}${anchorTarget(ctx.model) ? " → target" : " → not target"}`);
270
+ scanAnchorEntries(ctx);
271
+ activeFamily = null;
272
+ hasErrorThisTurn = false;
273
+ lastErrorInfo = null;
274
+ remindedThisTurn = false;
275
+ turnCounter = 0;
276
+ clearGuidanceCache();
277
+ reminderCounts.clear();
278
+ errorHistory.clear();
279
+ cacheStats.input = 0;
280
+ cacheStats.cacheRead = 0;
281
+ cacheStats.cacheWrite = 0;
282
+ cacheStats.hitTurns = 0;
283
+ cacheStats.missTurns = 0;
284
+ pendingGuidance = undefined;
285
+ });
286
+
287
+ // ── thinking_level_select: track the level (max is required by the DSH recipe) ──
288
+ pi.on("thinking_level_select", (event) => { currentThinking = event.level; });
289
+
290
+ // ── model_select: keep the latched model in sync + re-init the anchor when
291
+ // switching to/from a target ──
292
+ pi.on("model_select", (event, ctx) => {
293
+ // The stale-sessionModel fallback would otherwise keep matching the OLD
294
+ // target after a /model switch away (bootstrap firing on e.g. flash,
295
+ // pinning max_tokens and hiding tools for a non-target model).
296
+ sessionModel = event.model ? { id: event.model.id, provider: event.model.provider } : undefined;
297
+ if (isAnchorTarget(event.model?.id)) {
298
+ if (!anchorReady) {
299
+ anchorReady = true;
300
+ anchorPromoted = false;
301
+ anchorInspectedCount = 0;
302
+ scanAnchorEntries(ctx);
303
+ }
304
+ return;
305
+ }
306
+ // Switched away (or to a non-target): anchor goes inert.
307
+ anchorReady = false;
308
+ anchorPromoted = false;
309
+ anchorRunActive = false;
310
+ });
311
+
312
+ // ── before_agent_start: anchor bootstrap, static prompt blocks, dynamic guidance ──
313
+ //
314
+ // Cache-stability split: the system prompt is the byte-stable HEAD of the
315
+ // prefix cache — DeepSeek (exact prefix) and GLM (Z.ai automatic
316
+ // content-similarity cache, https://docs.z.ai/guides/capabilities/cache)
317
+ // both key on it. Anything that varies per turn must NOT go there — a
318
+ // changed head invalidates the cache for the whole request (measured:
319
+ // 99% → 16% hit when a prompt-aware hint fired). Per-turn guidance (error
320
+ // notes, first-tool hints, periodic reinforcement) is stashed in
321
+ // `pendingGuidance` and appended to the current user message (the request
322
+ // tail) by before_provider_request. Static content (Super Power base,
323
+ // selection guidance, apply_patch preference) stays in the system prompt —
324
+ // byte-identical per session, therefore cache-safe.
325
+ pi.on("before_agent_start", (event, ctx) => {
326
+ settings = readSteeringSettings(ctx); // read per turn — /config saves apply live
327
+ activeFamily = family(ctx.model);
328
+
329
+ // ds-anchor bootstrap: request #1 gets the byte-identical Minimal prompt
330
+ // and NO guidance (Super Power, selection guidance, hints all suppressed).
331
+ // This handler is LAST in ceulen's chain, so the returned systemPrompt
332
+ // REPLACES everything ponytail/subagent/advisor composed — deliberate, and
333
+ // the only place this module clobbers rather than composes.
334
+ if (anchorBootstrapping(ctx.model)) {
335
+ scanAnchorEntries(ctx);
336
+ if (!anchorPromoted) {
337
+ anchorRunActive = true;
338
+ pendingGuidance = undefined;
339
+ anchorTracePush(`bootstrap: minimal prompt engaged (model=${ctx.model?.id ?? "?"}${settings.weNeed ? ", +we-need directive" : ""})`);
340
+ return { systemPrompt: settings.weNeed ? WE_NEED_DIRECTIVE + MINIMAL_SYSTEM_PROMPT : MINIMAL_SYSTEM_PROMPT };
341
+ }
342
+ // Scan found a durable signal (resume edge) — fall through to the
343
+ // normal path: full prompt + full catalog.
344
+ anchorTracePush("bootstrap skipped: durable signal found (resume)");
345
+ } else if (anchorTarget(ctx.model)) {
346
+ anchorTracePush(`bootstrap skipped: already promoted=${anchorPromoted}`);
347
+ }
348
+
349
+ remindedThisTurn = false;
350
+ if (!activeFamily) return;
351
+
352
+ const dynamicParts: string[] = [];
353
+
354
+ // Shared error hint from previous turn (all families) — per-turn dynamic.
355
+ if (hasErrorThisTurn && lastErrorInfo) {
356
+ const repeatCount = errorHistory.get(lastErrorInfo.toolName)?.count ?? 0;
357
+ let hint = lastErrorInfo.hint;
358
+ // Provider-level rejections (e.g. reasoning-accumulation 400s) are not
359
+ // fixed by "simpler inputs" — the escalation advice only applies to
360
+ // tool-level errors.
361
+ if (repeatCount >= 2 && lastErrorInfo.toolName !== "provider") hint += ` You have had ${repeatCount} failures on ${lastErrorInfo.toolName}. Try simpler inputs.`;
362
+ dynamicParts.push(`Note: ${hint}`);
363
+ }
364
+ hasErrorThisTurn = false;
365
+ lastErrorInfo = null;
366
+
367
+ // Prompt-aware first-tool hints — ALL families (correctness, not steering).
368
+ // Per-turn dynamic (they depend on the current prompt) → user-message tail.
369
+ //
370
+ // activeForHint is the SAME source on every turn (host selectedTools when
371
+ // populated, pi.getActiveTools() otherwise) so the system prompt stays
372
+ // byte-identical — a per-turn source switch would invalidate the cache head.
373
+ const selected = event.systemPromptOptions?.selectedTools;
374
+ const activeForHint: readonly string[] = Array.isArray(selected) && selected.length > 0 ? selected : pi.getActiveTools();
375
+ if (settings.firstToolHints && activeForHint.includes("bash")) {
376
+ const runHint = runTaskFirstToolHint(event.prompt || "");
377
+ if (runHint) dynamicParts.push(runHint);
378
+ const ghHint = githubCloneFirstToolHint(event.prompt || "");
379
+ if (ghHint) dynamicParts.push(ghHint);
380
+ }
381
+ if (settings.firstToolHints && activeForHint.includes("find")) {
382
+ const readHint = readUncertainPathHint(event.prompt || "");
383
+ if (readHint) dynamicParts.push(readHint);
384
+ }
385
+
386
+ // Compose, never clobber: keep whatever earlier handlers put in the prompt.
387
+ let systemPrompt = event.systemPrompt;
388
+
389
+ // apply_patch preference — DeepSeek V4 (flash+pro) + GLM. DeepSeek keeps
390
+ // it as a safety net for real-world multi-file/frontmatter edits; GLM was
391
+ // excluded per the 2026-07-29 eval (edit-only usage), but 2026-09 session
392
+ // evidence showed GLM flash models falling back to bash heredocs
393
+ // (cat/python) for file creation without any steering — the hint (now with
394
+ // a create→write line) covers both families. Static per session (depends
395
+ // only on the active-tool set), so the prefix cache is unaffected.
396
+ if (activeFamily === "deepseek-v4" || activeFamily === "glm") {
397
+ const patchHint = applyPatchPreferenceGuidance(activeForHint);
398
+ if (patchHint) systemPrompt = `${systemPrompt}\n\n${patchHint}`;
399
+ }
400
+
401
+ // DeepSeek-only: Super Power Mode + verbose selection guidance (DeepSeek V4
402
+ // needs the full steering block; GLM reaches 100% with prompt-aware hints alone).
403
+ if (activeFamily === "deepseek-v4") {
404
+ const prefixParts: string[] = [];
405
+
406
+ if (settings.superpower) {
407
+ turnCounter++;
408
+ prefixParts.push(superPowerPrompt(settings.superpowerPrompt));
409
+ // Periodic reinforcement is per-turn dynamic → user-message tail, not
410
+ // the cache head (a head change every 10 turns forces a full miss).
411
+ if (turnCounter % 10 === 0) dynamicParts.push("Super Power Mode active — maximum capability, no limits.");
412
+ }
413
+
414
+ if (settings.selectionGuidance) {
415
+ if (["serena_get_symbols_overview", "serena_find_symbol", "serena_find_referencing_symbols", "serena_find_declaration", "serena_find_implementations", "obsidian", "ls", "grep", "find", "read", "edit", "bash"].some((n) => activeForHint.includes(n))) {
416
+ prefixParts.push(deepSeekSelectionGuidance(activeForHint));
417
+ }
418
+ }
419
+
420
+ if (prefixParts.length > 0) {
421
+ systemPrompt = `${prefixParts.join("\n\n---\n\n")}\n\n---\n\n${systemPrompt}`;
422
+ }
423
+ }
424
+
425
+ pendingGuidance = dynamicParts.length > 0 ? dynamicParts.join("\n\n---\n\n") : undefined;
426
+ return systemPrompt === event.systemPrompt ? undefined : { systemPrompt };
427
+ });
428
+
429
+ // ── before_provider_request: anchor payload + dynamic guidance + history cleaning ──
430
+ //
431
+ // before_provider_headers / after_provider_response are NOT registered here —
432
+ // the zai module owns those (fast-mode + client signing).
433
+ pi.on("before_provider_request", (event, ctx) => {
434
+ if (!family(ctx.model)) return;
435
+ let payload: unknown = event.payload;
436
+ // ds-anchor bootstrap: replace the provider payload's tools with the
437
+ // byte-exact DSH Minimal pair. Request-level only — Pi's global active-tool
438
+ // state is untouched; execution routes to the registered tools by name.
439
+ if (anchorBootstrapping(ctx.model) && anchorRunActive) {
440
+ const p = payload as Record<string, unknown> | undefined;
441
+ const filtered = dshBootstrapTools(p?.tools);
442
+ if (!filtered.ok) {
443
+ anchorPromoted = true; // fail-open
444
+ anchorTracePush(`FAIL-OPEN: ${filtered.reason}`);
445
+ warnAnchorOnce(ctx, `steering: ds-anchor ${filtered.reason}; bootstrap disabled, full catalog exposed`);
446
+ } else {
447
+ // max_tokens: the DSH captured minimal-mode payload sent 256000, and
448
+ // dsh-anchored-standard issue #11 isolated the output budget as a
449
+ // trajectory lever. Match it on the bootstrap request only. Exactly one
450
+ // budget field is emitted — the other is dropped from the spread so a
451
+ // payload carrying both can't send conflicting fields.
452
+ const other = p?.max_completion_tokens !== undefined ? "max_completion_tokens" : "max_tokens";
453
+ const dropped = other === "max_tokens" ? "max_completion_tokens" : "max_tokens";
454
+ const { [dropped]: _omit, ...rest } = p ?? {};
455
+ payload = { ...rest, tools: filtered.tools, [other]: BOOTSTRAP_MAX_TOKENS };
456
+ anchorTracePush(`payload: tools=[bash,str_replace_editor] + ${other}=${BOOTSTRAP_MAX_TOKENS} sent to ${ctx.model?.id ?? "?"}`);
457
+ }
458
+ }
459
+ // Append per-turn dynamic guidance to the current user message (request
460
+ // tail) so the system-prompt cache head stays byte-identical across turns
461
+ // (both DeepSeek exact-prefix and GLM Z.ai content-similarity caches).
462
+ // FIRST ROUND OF THE TURN ONLY (payload tail is still the plain user
463
+ // prompt): mid-turn rounds end with tool results, where re-appending the
464
+ // hint reads as a fresh repeated demand and loops strict models into
465
+ // re-running bash ("I've been complying") instead of settling.
466
+ if (pendingGuidance && tailIsPlainUserPrompt(payload)) {
467
+ const withGuidance = appendGuidanceToLastUserMessage(payload, pendingGuidance);
468
+ if (withGuidance !== payload) payload = withGuidance;
469
+ }
470
+ payload = cleanLeakedContentFromMessages(payload, pi.getAllTools().map((t) => t.name));
471
+ if (settings.stripReasoning) payload = stripReasoningContent(payload);
472
+ if (payload !== event.payload) return payload;
473
+ });
474
+
475
+ // ── tool_execution_end: categorize errors for the next turn's hint ──
476
+ pi.on("tool_execution_end", (event, ctx) => {
477
+ if (!event.isError || !family(ctx.model)) return;
478
+ hasErrorThisTurn = true;
479
+ const info = categorizeToolError(event.toolName, event.result, pi.getActiveTools());
480
+ lastErrorInfo = info;
481
+ recordError(event.toolName, info.category);
482
+ });
483
+
484
+ // ── message_end: detect reasoning-accumulation 400s (provider rejects the
485
+ // request once prior reasoning_content grows too large). Feeds the shared
486
+ // error-hint path so the NEXT turn's user message carries the actionable
487
+ // fix. Only fires on the stopReason === "error" assistant message, so it
488
+ // never double-counts normal tool errors (those arrive via
489
+ // tool_execution_end). ──
490
+ pi.on("message_end", (event, ctx) => {
491
+ if (!family(ctx.model)) return;
492
+ const msg = event.message as unknown as AssistantLike;
493
+ if (msg.role !== "assistant" || msg.stopReason !== "error") return;
494
+ const errorText = String(msg.errorMessage ?? "");
495
+ if (!detectReasoningRejection(errorText)) return;
496
+ hasErrorThisTurn = true;
497
+ lastErrorInfo = {
498
+ category: "reasoning_rejected",
499
+ toolName: "provider",
500
+ hint: settings.stripReasoning
501
+ ? "The provider rejected this request (accumulated reasoning_content or a content-length overflow). Reasoning strip is already on — the session context is probably genuinely too long; compact or shorten it."
502
+ : 'The provider rejected this request, likely due to accumulated reasoning_content in prior turns (or a content-length overflow). Turn on /config → Model → Steering → "Strip reasoning" and retry.',
503
+ };
504
+ recordError("provider", "reasoning_rejected");
505
+ });
506
+
507
+ // ── agent_end: the per-turn steering latch closes with the run ──
508
+ pi.on("agent_end", () => { remindedThisTurn = false; });
509
+
510
+ // ── agent_settled: end of the anchor run window ──
511
+ pi.on("agent_settled", () => { anchorRunActive = false; });
512
+
513
+ // ── turn_end: anchor promotion + prompt-cache usage bookkeeping ──
514
+ pi.on("turn_end", (event) => {
515
+ // ds-anchor: promote only on a DURABLE assistant reply — an error/aborted
516
+ // bootstrap request (429, network blip, 400 from the injected payload) must
517
+ // NOT silently promote the session (matches hasPromotionSignal's
518
+ // non-empty-content semantics; keeps the retry anchored).
519
+ const msg = event.message as unknown as AssistantLike;
520
+ if (anchorRunActive && msg.role === "assistant") {
521
+ const durable =
522
+ msg.stopReason !== "error" &&
523
+ msg.stopReason !== "aborted" &&
524
+ Array.isArray(msg.content) &&
525
+ msg.content.length > 0;
526
+ if (durable) {
527
+ anchorPromoted = true;
528
+ anchorRunActive = false;
529
+ anchorTracePush("promoted: first durable assistant reply received");
530
+ } else {
531
+ anchorTracePush(`bootstrap: reply not durable (stopReason=${msg.stopReason ?? "?"}) — retry stays anchored`);
532
+ }
533
+ }
534
+ // turn_end fires once per assistant LLM call (agent-loop emits per round),
535
+ // so each message.usage is a single API call — no double-counting.
536
+ if (msg.role !== "assistant") return;
537
+ const usage = msg.usage;
538
+ if (!usage) return;
539
+ // `?? 0` covers missing fields; the finite check also rejects NaN (some
540
+ // OpenAI-compatible providers emit NaN usage) — NaN would poison the sums
541
+ // and surface as "Hit rate: NaN%" or hide the cache block entirely.
542
+ const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
543
+ const input = num(usage.input);
544
+ const cacheRead = num(usage.cacheRead);
545
+ const cacheWrite = num(usage.cacheWrite);
546
+ if (input === 0 && cacheRead === 0 && cacheWrite === 0) return;
547
+ cacheStats.input += input;
548
+ cacheStats.cacheRead += cacheRead;
549
+ cacheStats.cacheWrite += cacheWrite;
550
+ // A turn with only cacheWrite (first turn of a session) is a miss: the
551
+ // prefix was computed and written, not read back from cache.
552
+ if (cacheRead > 0) cacheStats.hitTurns++;
553
+ else cacheStats.missTurns++;
554
+ });
555
+
556
+ // ── tool_call: DeepSeek-only steering (the dangerous-command guard and the
557
+ // read-on-guessed-path guard live in their own modules) ──
558
+ pi.on("tool_call", (event, ctx) => {
559
+ const f = family(ctx.model);
560
+ if (!f) return;
561
+
562
+ // ds-anchor bootstrap: the payload declared only bash + str_replace_editor
563
+ // (before_provider_request), so block a hallucinated name instead of
564
+ // burning a turn — the model must use the declared pair.
565
+ if (anchorBootstrapping(ctx.model) && anchorRunActive) {
566
+ if (!BOOTSTRAP_TOOLS.includes(event.toolName)) {
567
+ return { block: true, reason: `steering: ${event.toolName} is unavailable during the bootstrap request; use bash or str_replace_editor (command: "view" to read files).` };
568
+ }
569
+ return;
570
+ }
571
+
572
+ // A Serena call is the behavior we steer TOWARD — re-arm the per-turn latch.
573
+ if (event.toolName.startsWith("serena_")) { remindedThisTurn = false; return; }
574
+
575
+ // Steering is DeepSeek-only (GLM doesn't need it per eval).
576
+ if (f !== "deepseek-v4") return;
577
+
578
+ const activeTools = pi.getActiveTools();
579
+ const serenaActive = activeTools.some((t) => t.startsWith("serena_"));
580
+ const semanticMiss = serenaActive && isSemanticMissToolCall(event.toolName, event.input);
581
+ const dedicatedTool = missedDedicatedTool(event.toolName, event.input, activeTools);
582
+ if (!semanticMiss && !dedicatedTool) return;
583
+
584
+ const reason = semanticMiss
585
+ ? "For DeepSeek V4, use Serena semantic tools for code-symbol work."
586
+ : `For DeepSeek V4, use the dedicated ${dedicatedTool} tool instead of bash.`;
587
+
588
+ if (semanticMiss) {
589
+ const suggest = suggestBestSerenaCommand(event.input, activeTools);
590
+ // grep/ffgrep are first-class search tools — NEVER hard-block them. Emit a
591
+ // non-blocking steer so the model can still switch to Serena when useful.
592
+ // Only SIMPLE bash symbol searches (semanticMiss on bash) hard-block.
593
+ if (event.toolName === "grep" || event.toolName === "ffgrep") {
594
+ if (remindedThisTurn) return;
595
+ remindedThisTurn = true;
596
+ pi.sendMessage({ customType: STEERING_MESSAGE_TYPE, content: `${reason} ${suggest}`, display: true }, { deliverAs: "steer" });
597
+ return;
598
+ }
599
+ return { block: true, reason: `${reason} ${suggest}` };
600
+ }
601
+
602
+ // Dedicated-tool miss (bash where ls/find/ffind/grep/ffgrep/read/write would
603
+ // do): non-strict = one reminder per turn. Strict escalates a REPEATED miss
604
+ // for the same tool to a block at the fixed reminder count — the upstream
605
+ // env knob is gone (see BLOCK_AFTER_REMINDERS).
606
+ if (settings.strictSerena) {
607
+ const missKey = `bash→${dedicatedTool}`;
608
+ const count = (reminderCounts.get(missKey) ?? 0) + 1;
609
+ reminderCounts.set(missKey, count);
610
+ if (count >= BLOCK_AFTER_REMINDERS) return { block: true, reason: `${reason} (blocked after ${count} reminders — strict Serena mode)` };
611
+ }
612
+ if (remindedThisTurn) return;
613
+ remindedThisTurn = true;
614
+ pi.sendMessage({ customType: STEERING_MESSAGE_TYPE, content: `${reason} Use bash for real commands only.`, display: true }, { deliverAs: "steer" });
615
+ });
616
+ }