ceulen 0.5.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (367) hide show
  1. package/CHANGELOG.md +365 -12
  2. package/README.md +87 -91
  3. package/extensions/lib/advisor-marker.ts +33 -0
  4. package/extensions/lib/panel.ts +25 -2
  5. package/extensions/lib/rate.ts +24 -0
  6. package/extensions/lib/registry.test.ts +67 -0
  7. package/extensions/lib/registry.ts +104 -8
  8. package/extensions/lib/tools.ts +47 -0
  9. package/extensions/lib/usage-store.ts +33 -0
  10. package/extensions/modules/advisor/commands/advisor.ts +244 -0
  11. package/extensions/modules/advisor/configPanel.ts +194 -0
  12. package/extensions/modules/advisor/index.ts +235 -0
  13. package/extensions/modules/advisor/lib/config.ts +248 -0
  14. package/extensions/modules/advisor/lib/emission-guard.ts +153 -0
  15. package/extensions/modules/advisor/lib/isolated-model.ts +160 -0
  16. package/extensions/modules/advisor/lib/model-picker.ts +47 -0
  17. package/extensions/modules/advisor/lib/watcher.ts +288 -0
  18. package/extensions/modules/advisor/test/compliance.test.ts +125 -0
  19. package/extensions/modules/advisor/test/config.test.ts +202 -0
  20. package/extensions/modules/advisor/test/configPanel.test.ts +223 -0
  21. package/extensions/modules/advisor/test/emission-guard.test.ts +201 -0
  22. package/extensions/modules/advisor/test/isolated-model.test.ts +311 -0
  23. package/extensions/modules/advisor/test/model-picker.test.ts +32 -0
  24. package/extensions/modules/advisor/test/module.test.ts +649 -0
  25. package/extensions/modules/advisor/test/watcher.test.ts +478 -0
  26. package/extensions/modules/classifier/configPanel.ts +104 -0
  27. package/extensions/modules/classifier/index.ts +297 -0
  28. package/extensions/modules/classifier/lib/settings.ts +95 -0
  29. package/extensions/modules/classifier/test/classifier.test.ts +475 -0
  30. package/extensions/modules/composer/index.ts +152 -3
  31. package/extensions/modules/composer/lib/footer.ts +119 -0
  32. package/extensions/modules/composer/lib/shapes.ts +265 -26
  33. package/extensions/modules/composer/test/editor.test.ts +1 -1
  34. package/extensions/modules/composer/test/footer.test.ts +96 -0
  35. package/extensions/modules/composer/test/module.test.ts +113 -11
  36. package/extensions/modules/composer/test/screen.test.ts +29 -1
  37. package/extensions/modules/composer/test/shapes.test.ts +224 -8
  38. package/extensions/modules/config/defaultTools.ts +96 -0
  39. package/extensions/modules/config/index.ts +147 -7
  40. package/extensions/modules/config/piSettings.ts +254 -69
  41. package/extensions/modules/config/test/defaultTools.test.ts +122 -0
  42. package/extensions/modules/config/test/menu.test.ts +64 -0
  43. package/extensions/modules/config/test/panel.test.ts +38 -23
  44. package/extensions/modules/config/test/piSettings.test.ts +130 -3
  45. package/extensions/modules/config/test/renderTools.test.ts +71 -0
  46. package/extensions/modules/config/test/tools.test.ts +146 -0
  47. package/extensions/modules/fff/index.ts +2094 -0
  48. package/extensions/modules/fff/lib/query.ts +129 -0
  49. package/extensions/modules/fff/test/index.test.ts +607 -0
  50. package/extensions/modules/fff/test/query.test.ts +71 -0
  51. package/extensions/modules/munin/configPanel.ts +108 -0
  52. package/extensions/modules/munin/index.ts +641 -0
  53. package/extensions/modules/munin/lib/helpers.ts +471 -0
  54. package/extensions/modules/munin/lib/retry.ts +20 -0
  55. package/extensions/modules/munin/lib/sdk.ts +218 -0
  56. package/extensions/modules/munin/test/config.test.ts +168 -0
  57. package/extensions/modules/munin/test/configPanel.test.ts +186 -0
  58. package/extensions/modules/munin/test/extension.test.ts +224 -0
  59. package/extensions/modules/munin/test/helpers.test.ts +523 -0
  60. package/extensions/modules/munin/test/retry.test.ts +145 -0
  61. package/extensions/modules/munin/test/stale-protocol.test.ts +554 -0
  62. package/extensions/modules/plan/configPanel.ts +152 -0
  63. package/extensions/modules/plan/index.ts +917 -0
  64. package/extensions/modules/plan/lib/plan-tools.ts +72 -0
  65. package/extensions/modules/plan/lib/prompt.ts +65 -0
  66. package/extensions/modules/plan/lib/settings.ts +166 -0
  67. package/extensions/modules/plan/lib/shell-gate.ts +200 -0
  68. package/extensions/modules/plan/test/configPanel.test.ts +96 -0
  69. package/extensions/modules/plan/test/harness.ts +133 -0
  70. package/extensions/modules/plan/test/module.test.ts +305 -0
  71. package/extensions/modules/plan/test/settings.test.ts +114 -0
  72. package/extensions/modules/plan/test/shell-gate.test.ts +103 -0
  73. package/extensions/modules/ponytail/index.ts +23 -73
  74. package/extensions/modules/ponytail/lib/config.ts +1 -6
  75. package/extensions/modules/ponytail/test/extension.test.ts +1 -85
  76. package/extensions/modules/repair/configPanel.ts +96 -0
  77. package/extensions/modules/repair/index.ts +414 -0
  78. package/extensions/modules/repair/lib/auto-bg.ts +333 -0
  79. package/extensions/modules/repair/lib/edit-repair.ts +155 -0
  80. package/extensions/modules/repair/lib/editor.ts +251 -0
  81. package/extensions/modules/repair/lib/guards.ts +34 -0
  82. package/extensions/modules/repair/lib/input-repair.ts +324 -0
  83. package/extensions/modules/repair/lib/patch.ts +481 -0
  84. package/extensions/modules/repair/lib/settings.ts +114 -0
  85. package/extensions/modules/repair/test/auto-bg.test.ts +405 -0
  86. package/extensions/modules/repair/test/edit-repair.test.ts +224 -0
  87. package/extensions/modules/repair/test/editor.test.ts +141 -0
  88. package/extensions/modules/repair/test/guards.test.ts +64 -0
  89. package/extensions/modules/repair/test/input-repair.test.ts +231 -0
  90. package/extensions/modules/repair/test/patch.test.ts +563 -0
  91. package/extensions/modules/repair/test/settings.test.ts +167 -0
  92. package/extensions/modules/repair/test/wrapper.test.ts +210 -0
  93. package/extensions/modules/router/commands/commands.ts +4 -0
  94. package/extensions/modules/router/configPanel.ts +24 -10
  95. package/extensions/modules/router/lib/client.ts +63 -0
  96. package/extensions/modules/router/lib/provider.ts +34 -13
  97. package/extensions/modules/router/lib/systemone.ts +152 -0
  98. package/extensions/modules/router/test/unit.test.ts +260 -0
  99. package/extensions/modules/rtk/findFallback.js +68 -0
  100. package/extensions/modules/rtk/index.ts +248 -0
  101. package/extensions/modules/rtk/safe-rewrite.js +74 -0
  102. package/extensions/modules/rtk/test/findFallback.test.js +66 -0
  103. package/extensions/modules/rtk/test/index.test.js +131 -0
  104. package/extensions/modules/rtk/test/safe-rewrite.test.js +96 -0
  105. package/extensions/modules/rtk/version-gate.js +34 -0
  106. package/extensions/modules/rules/index.ts +120 -0
  107. package/extensions/modules/rules/lib/rules.ts +348 -0
  108. package/extensions/modules/rules/test/lib.test.ts +263 -0
  109. package/extensions/modules/rules/test/module.test.ts +222 -0
  110. package/extensions/modules/serena/index.ts +629 -0
  111. package/extensions/modules/serena/lib/detect.ts +73 -0
  112. package/extensions/modules/serena/lib/env.ts +76 -0
  113. package/extensions/modules/serena/lib/guidance.ts +26 -0
  114. package/extensions/modules/serena/lib/normalize.ts +27 -0
  115. package/extensions/modules/serena/lib/symbol-key.ts +20 -0
  116. package/extensions/modules/serena/lib/truncate.ts +20 -0
  117. package/extensions/modules/serena/test/env.test.ts +122 -0
  118. package/extensions/modules/serena/test/index.test.ts +347 -0
  119. package/extensions/modules/serena/test/worker.test.ts +562 -0
  120. package/extensions/modules/serena/worker.ts +858 -0
  121. package/extensions/modules/steering/configPanel.ts +122 -0
  122. package/extensions/modules/steering/index.ts +616 -0
  123. package/extensions/modules/steering/lib/anchor.ts +175 -0
  124. package/extensions/modules/steering/lib/errors.ts +253 -0
  125. package/extensions/modules/steering/lib/family.ts +33 -0
  126. package/extensions/modules/steering/lib/guidance.ts +172 -0
  127. package/extensions/modules/steering/lib/history.ts +170 -0
  128. package/extensions/modules/steering/lib/settings.ts +127 -0
  129. package/extensions/modules/steering/test/anchor-regressions.test.ts +93 -0
  130. package/extensions/modules/steering/test/anchor-wiring.test.ts +99 -0
  131. package/extensions/modules/steering/test/anchor.test.ts +160 -0
  132. package/extensions/modules/steering/test/cache-stats.test.ts +43 -0
  133. package/extensions/modules/steering/test/errors.test.ts +309 -0
  134. package/extensions/modules/steering/test/family.test.ts +43 -0
  135. package/extensions/modules/steering/test/guidance.test.ts +357 -0
  136. package/extensions/modules/steering/test/harness.ts +93 -0
  137. package/extensions/modules/steering/test/history.test.ts +118 -0
  138. package/extensions/modules/steering/test/settings.test.ts +182 -0
  139. package/extensions/modules/steering/test/status.test.ts +71 -0
  140. package/extensions/modules/steering/test/toolCall.test.ts +99 -0
  141. package/extensions/modules/subagent/agents/planner.md +14 -0
  142. package/extensions/modules/subagent/agents/reviewer.md +42 -0
  143. package/extensions/modules/subagent/agents/scout.md +47 -0
  144. package/extensions/modules/subagent/agents/tester.md +12 -0
  145. package/extensions/modules/subagent/agents/worker.md +18 -0
  146. package/extensions/modules/subagent/configPanel.ts +219 -0
  147. package/extensions/modules/subagent/index.ts +2464 -0
  148. package/extensions/modules/subagent/lib/agents.ts +408 -0
  149. package/extensions/modules/subagent/lib/background.ts +383 -0
  150. package/extensions/modules/subagent/lib/herdr.ts +1019 -0
  151. package/extensions/modules/subagent/lib/history.ts +126 -0
  152. package/extensions/modules/subagent/lib/model.ts +156 -0
  153. package/extensions/modules/subagent/lib/render.ts +335 -0
  154. package/extensions/modules/subagent/lib/result.ts +110 -0
  155. package/extensions/modules/subagent/lib/roles.ts +296 -0
  156. package/extensions/modules/subagent/lib/routing.ts +228 -0
  157. package/extensions/modules/subagent/lib/runner.ts +559 -0
  158. package/extensions/modules/subagent/lib/schema.ts +21 -0
  159. package/extensions/modules/subagent/lib/security.ts +763 -0
  160. package/extensions/modules/subagent/lib/settings.ts +159 -0
  161. package/extensions/modules/subagent/lib/thread-viewer.ts +319 -0
  162. package/extensions/modules/subagent/lib/threads.ts +135 -0
  163. package/extensions/modules/subagent/lib/types.ts +18 -0
  164. package/extensions/modules/subagent/lib/widget.ts +475 -0
  165. package/extensions/modules/subagent/test/configPanel.test.ts +132 -0
  166. package/extensions/modules/subagent/test/herdr-advisor.test.ts +40 -0
  167. package/extensions/modules/subagent/test/routing.test.ts +524 -0
  168. package/extensions/modules/subagent/test/widget.test.ts +208 -0
  169. package/extensions/modules/todo/index.ts +478 -0
  170. package/extensions/modules/todo/test/todo.test.ts +252 -0
  171. package/extensions/modules/usage/index.ts +70 -16
  172. package/extensions/modules/usage/test/genrate.test.ts +70 -0
  173. package/extensions/modules/usage/test/parsers.test.ts +13 -0
  174. package/extensions/modules/usage/test/session-accumulators.test.ts +85 -0
  175. package/extensions/modules/ux/UPSTREAM +24 -0
  176. package/extensions/modules/ux/index.ts +393 -0
  177. package/extensions/modules/ux/lib/audit.ts +562 -0
  178. package/extensions/modules/ux/lib/config.ts +136 -0
  179. package/extensions/modules/ux/lib/instructions.ts +77 -0
  180. package/extensions/modules/ux/test/audit.test.ts +756 -0
  181. package/extensions/modules/ux/test/extension.test.ts +394 -0
  182. package/extensions/modules/ux/test/instructions.test.ts +19 -0
  183. package/extensions/modules/web/configPanel.ts +218 -0
  184. package/extensions/modules/web/index.ts +978 -0
  185. package/extensions/modules/web/lib/agy.ts +209 -0
  186. package/extensions/modules/web/lib/brave.ts +42 -0
  187. package/extensions/modules/web/lib/cdp.ts +686 -0
  188. package/extensions/modules/web/lib/chatapi.ts +101 -0
  189. package/extensions/modules/web/lib/chatgpt.ts +796 -0
  190. package/extensions/modules/web/lib/chrome.ts +328 -0
  191. package/extensions/modules/web/lib/config.ts +136 -0
  192. package/extensions/modules/web/lib/content.ts +99 -0
  193. package/extensions/modules/web/lib/crawl4ai.ts +172 -0
  194. package/extensions/modules/web/lib/extract.ts +235 -0
  195. package/extensions/modules/web/lib/firecrawl.ts +56 -0
  196. package/extensions/modules/web/lib/format.ts +197 -0
  197. package/extensions/modules/web/lib/gemini-auth.ts +286 -0
  198. package/extensions/modules/web/lib/gemini-dr.ts +338 -0
  199. package/extensions/modules/web/lib/gemini.ts +551 -0
  200. package/extensions/modules/web/lib/imageapi.ts +559 -0
  201. package/extensions/modules/web/lib/retry.ts +71 -0
  202. package/extensions/modules/web/lib/search.ts +237 -0
  203. package/extensions/modules/web/lib/searxng.ts +69 -0
  204. package/extensions/modules/web/lib/settings.ts +157 -0
  205. package/extensions/modules/web/scripts/cdp-smoke.ts +77 -0
  206. package/extensions/modules/web/scripts/gemini-smoke.ts +107 -0
  207. package/extensions/modules/web/test/agy.test.ts +383 -0
  208. package/extensions/modules/web/test/cdp.test.ts +717 -0
  209. package/extensions/modules/web/test/chat.test.ts +171 -0
  210. package/extensions/modules/web/test/chatgpt.test.ts +633 -0
  211. package/extensions/modules/web/test/chrome.test.ts +282 -0
  212. package/extensions/modules/web/test/config.test.ts +218 -0
  213. package/extensions/modules/web/test/configPanel.test.ts +198 -0
  214. package/extensions/modules/web/test/crawl.test.ts +134 -0
  215. package/extensions/modules/web/test/crawl4ai.test.ts +105 -0
  216. package/extensions/modules/web/test/extension.test.ts +118 -0
  217. package/extensions/modules/web/test/extract.test.ts +436 -0
  218. package/extensions/modules/web/test/fixtures/dr-confirm.bin +12 -0
  219. package/extensions/modules/web/test/fixtures/dr-plan.bin +20 -0
  220. package/extensions/modules/web/test/fixtures/interaction.html +31 -0
  221. package/extensions/modules/web/test/format.test.ts +230 -0
  222. package/extensions/modules/web/test/gemini-auth.test.ts +465 -0
  223. package/extensions/modules/web/test/gemini-dr.test.ts +249 -0
  224. package/extensions/modules/web/test/gemini.test.ts +472 -0
  225. package/extensions/modules/web/test/hook.test.ts +101 -0
  226. package/extensions/modules/web/test/image.test.ts +1089 -0
  227. package/extensions/modules/web/test/retry.test.ts +119 -0
  228. package/extensions/modules/web/test/screenshot.test.ts +109 -0
  229. package/extensions/modules/web/test/search.test.ts +210 -0
  230. package/extensions/modules/web/test/settings.test.ts +165 -0
  231. package/extensions/modules/web/test/skill.test.ts +72 -0
  232. package/extensions/modules/web/types.d.ts +3 -0
  233. package/extensions/modules/web/vendor/package.json +1 -0
  234. package/extensions/modules/web/vendor/readability/LICENSE.md +13 -0
  235. package/extensions/modules/web/vendor/readability/Readability-readerable.js +123 -0
  236. package/extensions/modules/web/vendor/readability/Readability.js +2787 -0
  237. package/extensions/modules/web/vendor/readability/index.d.ts +64 -0
  238. package/extensions/modules/web/vendor/readability/index.js +9 -0
  239. package/extensions/modules/web/vendor/turndown/LICENSE +21 -0
  240. package/extensions/modules/web/vendor/turndown/turndown.cjs.js +784 -0
  241. package/extensions/modules/web/vendor/turndown-plugin-gfm/LICENSE +21 -0
  242. package/extensions/modules/web/vendor/turndown-plugin-gfm/turndown-plugin-gfm.cjs.js +163 -0
  243. package/extensions/modules/zai/configPanel.ts +154 -0
  244. package/extensions/modules/zai/index.ts +186 -0
  245. package/extensions/modules/zai/lib/anthropic.ts +159 -0
  246. package/extensions/modules/zai/lib/settings.ts +198 -0
  247. package/extensions/modules/zai/lib/signing.ts +721 -0
  248. package/extensions/modules/zai/lib/throttle.ts +198 -0
  249. package/extensions/modules/zai/test/anthropic.test.ts +132 -0
  250. package/extensions/modules/zai/test/configPanel.test.ts +230 -0
  251. package/extensions/modules/zai/test/extension.test.ts +249 -0
  252. package/extensions/modules/zai/test/settings.test.ts +183 -0
  253. package/extensions/modules/zai/test/signing-wiring.test.ts +108 -0
  254. package/extensions/modules/zai/test/signing.test.ts +364 -0
  255. package/extensions/modules/zai/test/throttle.test.ts +329 -0
  256. package/package.json +19 -4
  257. package/scripts/validate-themes.mjs +75 -0
  258. package/skills/munin/SKILL.md +117 -0
  259. package/skills/ux-capture/SKILL.md +202 -0
  260. package/skills/ux-design/SKILL.md +279 -0
  261. package/skills/ux-presets/SKILL.md +484 -0
  262. package/skills/ux-routing/SKILL.md +46 -0
  263. package/skills/web/SKILL.md +153 -0
  264. package/themes/alabaster.json +93 -0
  265. package/themes/amethyst.json +96 -0
  266. package/themes/anthracite.json +93 -0
  267. package/themes/basalt.json +91 -0
  268. package/themes/birch.json +95 -0
  269. package/themes/catppuccin-mocha.json +91 -0
  270. package/themes/dark-abyss.json +91 -0
  271. package/themes/dark-arctic.json +104 -0
  272. package/themes/dark-aurora.json +95 -0
  273. package/themes/dark-catppuccin.json +107 -0
  274. package/themes/dark-cavern.json +91 -0
  275. package/themes/dark-celestial.json +106 -0
  276. package/themes/dark-copper.json +95 -0
  277. package/themes/dark-cosmos.json +90 -0
  278. package/themes/dark-cyberpunk.json +102 -0
  279. package/themes/dark-dracula.json +98 -0
  280. package/themes/dark-eclipse.json +91 -0
  281. package/themes/dark-ember.json +95 -0
  282. package/themes/dark-equinox.json +90 -0
  283. package/themes/dark-forest.json +96 -0
  284. package/themes/dark-github.json +105 -0
  285. package/themes/dark-gruvbox.json +112 -0
  286. package/themes/dark-lavender.json +95 -0
  287. package/themes/dark-lunar.json +89 -0
  288. package/themes/dark-midnight.json +95 -0
  289. package/themes/dark-monochrome.json +94 -0
  290. package/themes/dark-monokai.json +98 -0
  291. package/themes/dark-nebula.json +90 -0
  292. package/themes/dark-neon-noir.json +100 -0
  293. package/themes/dark-nord.json +98 -0
  294. package/themes/dark-ocean.json +101 -0
  295. package/themes/dark-one.json +100 -0
  296. package/themes/dark-poimandres.json +115 -0
  297. package/themes/dark-rainforest.json +91 -0
  298. package/themes/dark-reef.json +91 -0
  299. package/themes/dark-retro.json +92 -0
  300. package/themes/dark-rose-pine.json +96 -0
  301. package/themes/dark-sakura.json +95 -0
  302. package/themes/dark-slate.json +95 -0
  303. package/themes/dark-solarized.json +97 -0
  304. package/themes/dark-solstice.json +90 -0
  305. package/themes/dark-starfall.json +91 -0
  306. package/themes/dark-sunset.json +99 -0
  307. package/themes/dark-swamp.json +90 -0
  308. package/themes/dark-synthwave.json +103 -0
  309. package/themes/dark-taiga.json +91 -0
  310. package/themes/dark-terminal.json +95 -0
  311. package/themes/dark-tokyo-night.json +101 -0
  312. package/themes/dark-tundra.json +91 -0
  313. package/themes/dark-twilight.json +91 -0
  314. package/themes/dark-volcanic.json +91 -0
  315. package/themes/dark.json +80 -0
  316. package/themes/graphite.json +92 -0
  317. package/themes/light-arctic.json +107 -0
  318. package/themes/light-aurora-day.json +91 -0
  319. package/themes/light-canyon.json +91 -0
  320. package/themes/light-catppuccin.json +106 -0
  321. package/themes/light-cirrus.json +90 -0
  322. package/themes/light-coral.json +95 -0
  323. package/themes/light-cyberpunk.json +96 -0
  324. package/themes/light-dawn.json +90 -0
  325. package/themes/light-dunes.json +91 -0
  326. package/themes/light-eucalyptus.json +95 -0
  327. package/themes/light-forest.json +100 -0
  328. package/themes/light-frost.json +95 -0
  329. package/themes/light-github.json +115 -0
  330. package/themes/light-glacier.json +91 -0
  331. package/themes/light-gruvbox.json +108 -0
  332. package/themes/light-haze.json +90 -0
  333. package/themes/light-honeycomb.json +95 -0
  334. package/themes/light-lagoon.json +91 -0
  335. package/themes/light-lavender.json +95 -0
  336. package/themes/light-meadow.json +91 -0
  337. package/themes/light-mint.json +95 -0
  338. package/themes/light-monochrome.json +101 -0
  339. package/themes/light-ocean.json +99 -0
  340. package/themes/light-one.json +99 -0
  341. package/themes/light-opal.json +91 -0
  342. package/themes/light-orchard.json +91 -0
  343. package/themes/light-paper.json +95 -0
  344. package/themes/light-poimandres.json +115 -0
  345. package/themes/light-prism.json +90 -0
  346. package/themes/light-retro.json +98 -0
  347. package/themes/light-sand.json +95 -0
  348. package/themes/light-savanna.json +91 -0
  349. package/themes/light-solarized.json +102 -0
  350. package/themes/light-soleil.json +90 -0
  351. package/themes/light-sunset.json +99 -0
  352. package/themes/light-synthwave.json +98 -0
  353. package/themes/light-tokyo-night.json +111 -0
  354. package/themes/light-wetland.json +91 -0
  355. package/themes/light-zenith.json +89 -0
  356. package/themes/light.json +80 -0
  357. package/themes/limestone.json +94 -0
  358. package/themes/mahogany.json +97 -0
  359. package/themes/marble.json +93 -0
  360. package/themes/mirage.json +79 -0
  361. package/themes/obsidian.json +91 -0
  362. package/themes/onyx.json +91 -0
  363. package/themes/pearl.json +93 -0
  364. package/themes/porcelain.json +91 -0
  365. package/themes/quartz.json +96 -0
  366. package/themes/sandstone.json +95 -0
  367. package/themes/titanium.json +90 -0
@@ -0,0 +1,170 @@
1
+ /**
2
+ * history.ts — shared reasoning strip + leaked-content cleaning (the
3
+ * reasoning-content.ts upstream file, named for what it does to the request
4
+ * history).
5
+ *
6
+ * Used by the steering module for all detected model families. Generic — works
7
+ * for DeepSeek V4, GLM, and any reasoning model that accumulates
8
+ * reasoning_content across turns or leaks tool calls as prose.
9
+ */
10
+ // ponytail: vendored from @bacnh85/pi-model-tools 0.9.5
11
+ // (extensions/lib/reasoning-content.ts). Local change: stripReasoningContent
12
+ // takes the truncation budget as an argument (the upstream
13
+ // PI_MODEL_TOOLS_REASONING_MAX_CHARS env knob is dropped — no settings row was
14
+ // asked for; callers pass Infinity, i.e. replace-with-empty, which is the
15
+ // shipped behavior).
16
+
17
+ import { isRecord } from "./family.js";
18
+
19
+ const REASONING_FIELDS = new Set(["reasoning_content", "reasoning", "thinking_content", "chain_of_thought", "cot"]);
20
+
21
+ export function stripReasoningContent(payload: unknown, maxChars: number = Infinity): unknown {
22
+ if (!isRecord(payload)) return payload;
23
+ const messages = findMessagesArray(payload);
24
+ if (!messages || messages.length === 0) return payload;
25
+
26
+ let cloned: Record<string, unknown> | undefined;
27
+ let clonedMessages: Array<Record<string, unknown>> | undefined;
28
+ const threshold = Number.isFinite(maxChars) && maxChars > 0 ? maxChars : Infinity;
29
+
30
+ for (let i = 0; i < messages.length; i++) {
31
+ if (messages[i].role !== "assistant") continue;
32
+ for (const field of REASONING_FIELDS) {
33
+ if (!(field in messages[i])) continue;
34
+ if (!cloned) {
35
+ cloned = structuredClone(payload);
36
+ clonedMessages = findMessagesArray(cloned);
37
+ if (!clonedMessages) return payload;
38
+ }
39
+ const value = clonedMessages![i][field];
40
+ if (Number.isFinite(threshold) && typeof value === "string" && value.length > threshold) {
41
+ clonedMessages![i][field] = value.slice(0, threshold) + "\n\n[reasoning truncated]";
42
+ } else {
43
+ // Replace with empty string rather than deleting the key. DeepSeek's
44
+ // thinking-mode API requires the reasoning_content key to be PRESENT on
45
+ // assistant tool_calls messages (else 400: "reasoning_content … must be
46
+ // passed back") but accepts an empty string. Keeping the key (empty)
47
+ // satisfies the constraint while removing the non-deterministic
48
+ // reasoning bytes that break the prefix cache turn-over-turn — for BOTH
49
+ // DeepSeek (exact prefix cache) and GLM (Z.ai automatic content-similarity
50
+ // cache, https://docs.z.ai/guides/capabilities/cache, which is equally
51
+ // sensitive to a changing conversation-history prefix).
52
+ clonedMessages![i][field] = "";
53
+ }
54
+ }
55
+ }
56
+ return cloned ?? payload;
57
+ }
58
+
59
+ // ── Leaked content cleaning ──
60
+
61
+ const LEAKED_THINKING_HEADER = /^(Reasoning|Thinking|Chain of Thought)\s*:[^\n]*\n?/i;
62
+ const LEAKED_TOOL_CALL_RE = /`([a-z_]+)\(([^)]*)\)`\s*/g;
63
+ // ponytail: SDK renders this when a thinking model's prior summary is missing — display-only, no behavioral effect.
64
+ const PRIOR_REASONING_PLACEHOLDER_RE = /\(prior reasoning summary unavailable\)\s*/gi;
65
+
66
+ export function cleanLeakedContent(content: unknown, activeTools: ReadonlySet<string>): unknown {
67
+ if (typeof content !== "string") return content;
68
+ let cleaned = content;
69
+ if (PRIOR_REASONING_PLACEHOLDER_RE.test(cleaned)) cleaned = cleaned.replace(PRIOR_REASONING_PLACEHOLDER_RE, "");
70
+ // reset lastIndex for global regex reuse
71
+ PRIOR_REASONING_PLACEHOLDER_RE.lastIndex = 0;
72
+ if (LEAKED_THINKING_HEADER.test(cleaned)) cleaned = cleaned.replace(LEAKED_THINKING_HEADER, "").trimStart();
73
+ cleaned = cleaned.replace(LEAKED_TOOL_CALL_RE, (match, toolName: string) => activeTools.has(toolName) ? "" : match);
74
+ return cleaned !== content ? cleaned : content;
75
+ }
76
+
77
+ export function cleanLeakedContentFromMessages(payload: unknown, activeTools: readonly string[]): unknown {
78
+ if (!isRecord(payload)) return payload;
79
+ const messages = findMessagesArray(payload);
80
+ if (!messages || messages.length === 0) return payload;
81
+ const toolNames = new Set(activeTools);
82
+ let cloned: Record<string, unknown> | undefined;
83
+ let clonedMessages: Array<Record<string, unknown>> | undefined;
84
+
85
+ for (let i = 0; i < messages.length; i++) {
86
+ const msg = messages[i];
87
+ if (msg.role !== "assistant") continue;
88
+ const cleanedContent = cleanMessageContent(msg.content, toolNames);
89
+ if (cleanedContent === msg.content) continue;
90
+ if (!cloned) { cloned = structuredClone(payload); clonedMessages = findMessagesArray(cloned)!; }
91
+ clonedMessages![i].content = cleanedContent;
92
+ }
93
+ return cloned ?? payload;
94
+ }
95
+
96
+ /**
97
+ * True when the payload's LAST message is the current turn's plain user prompt
98
+ * — no tool result or assistant output after or inside it. This holds only on
99
+ * the turn's first provider round (incl. retries); mid-turn rounds end with a
100
+ * tool result (role "tool", or an anthropic-style user message of tool_result
101
+ * blocks). First-tool guidance may only fire while it can still be obeyed.
102
+ */
103
+ export function tailIsPlainUserPrompt(payload: unknown): boolean {
104
+ if (!isRecord(payload)) return false;
105
+ const messages = findMessagesArray(payload);
106
+ if (!messages || messages.length === 0) return false;
107
+ const last = messages[messages.length - 1] as { role?: unknown; content?: unknown };
108
+ if (last?.role !== "user") return false;
109
+ if (Array.isArray(last.content) && last.content.some((b) => (b as { type?: unknown })?.type === "tool_result")) return false;
110
+ return true;
111
+ }
112
+
113
+ /**
114
+ * Append per-turn guidance text to the LAST user message (the current prompt).
115
+ * Used instead of system-prompt injection: the system prompt is the
116
+ * byte-stable head of the prefix cache (DeepSeek exact-prefix OR GLM Z.ai
117
+ * automatic content-similarity cache), so any per-turn change there invalidates
118
+ * the cache for the whole request. The current user message is the tail of the
119
+ * request — appending to it costs zero cacheable tokens.
120
+ */
121
+ export function appendGuidanceToLastUserMessage(payload: unknown, guidance: string): unknown {
122
+ if (!isRecord(payload)) return payload;
123
+ const messages = findMessagesArray(payload);
124
+ if (!messages || messages.length === 0) return payload;
125
+ let lastUserIdx = -1;
126
+ for (let i = messages.length - 1; i >= 0; i--) {
127
+ if (messages[i].role === "user") { lastUserIdx = i; break; }
128
+ }
129
+ if (lastUserIdx < 0) return payload;
130
+
131
+ const cloned = structuredClone(payload);
132
+ const clonedMessages = findMessagesArray(cloned);
133
+ if (!clonedMessages) return payload;
134
+ const msg = clonedMessages[lastUserIdx] as { content?: unknown };
135
+ if (typeof msg.content === "string") {
136
+ msg.content = `${msg.content}\n\n${guidance}`;
137
+ return cloned;
138
+ }
139
+ if (Array.isArray(msg.content)) {
140
+ const parts = msg.content as Array<Record<string, unknown>>;
141
+ const lastText = [...parts].reverse().find((p) => isRecord(p) && typeof p.text === "string");
142
+ if (lastText) lastText.text = `${lastText.text}\n\n${guidance}`;
143
+ else parts.push({ type: "text", text: guidance });
144
+ return cloned;
145
+ }
146
+ // Unrecognized content shape (undefined/object/null): return the original so the
147
+ // caller's `withGuidance === payload` check no-ops and pendingGuidance is cleared
148
+ // — guidance is intentionally dropped rather than crashing on unexpected shapes.
149
+ return payload;
150
+ }
151
+
152
+ function cleanMessageContent(content: unknown, activeTools: ReadonlySet<string>): unknown {
153
+ if (typeof content === "string") return cleanLeakedContent(content, activeTools);
154
+ if (!Array.isArray(content)) return content;
155
+ let changed = false;
156
+ const cleaned = content.map((part: unknown) => {
157
+ if (!isRecord(part) || typeof part.text !== "string") return part;
158
+ const cleanedText = cleanLeakedContent(part.text, activeTools);
159
+ if (cleanedText === part.text) return part;
160
+ changed = true;
161
+ return { ...part, text: cleanedText };
162
+ });
163
+ return changed ? cleaned : content;
164
+ }
165
+
166
+ function findMessagesArray(payload: Record<string, unknown>): Array<Record<string, unknown>> | undefined {
167
+ if (Array.isArray(payload.messages)) return payload.messages as Array<Record<string, unknown>>;
168
+ if (isRecord(payload.body) && Array.isArray(payload.body.messages)) return payload.body.messages as Array<Record<string, unknown>>;
169
+ return undefined;
170
+ }
@@ -0,0 +1,127 @@
1
+ // steering settings — the `steering` section of the agent-dir settings.json,
2
+ // overlaid by a TRUSTED project `.pi/settings.json` `steering` section.
3
+ //
4
+ // Read per turn (before_agent_start) so a /config save needs no /reload; the
5
+ // trusted project file is only eligible when the repo is trusted (an untrusted
6
+ // checkout must not be able to steer prompts). pi-model-tools' PI_MODEL_TOOLS_*
7
+ // env knobs are gone — every one of them is a row here.
8
+ //
9
+ // "steering": {
10
+ // "firstToolHints": true, // prompt-aware bash/find/clone-first hints
11
+ // "selectionGuidance": true, // DeepSeek V4 routing table (system prompt)
12
+ // "superpower": false, // DeepSeek V4 Super Power prompt
13
+ // "superpowerPrompt": "", // custom text; empty = built-in
14
+ // "strictSerena": false, // escalate dedicated-tool misses to a block
15
+ // "stripReasoning": true, // drop accumulated reasoning_content
16
+ // "dsAnchor": true, // deepseek-v4-pro minimal-mode bootstrap
17
+ // "weNeed": false // A/B: "We need…" bootstrap directive
18
+ // }
19
+
20
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
21
+ import os from "node:os";
22
+ import path from "node:path";
23
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
24
+
25
+ export interface SteeringSettings {
26
+ firstToolHints: boolean;
27
+ selectionGuidance: boolean;
28
+ superpower: boolean;
29
+ /** Custom Super Power prompt; empty = the built-in base prompt. */
30
+ superpowerPrompt: string;
31
+ strictSerena: boolean;
32
+ stripReasoning: boolean;
33
+ dsAnchor: boolean;
34
+ weNeed: boolean;
35
+ }
36
+
37
+ export const DEFAULT_STEERING_SETTINGS: SteeringSettings = {
38
+ firstToolHints: true,
39
+ selectionGuidance: true,
40
+ superpower: false,
41
+ superpowerPrompt: "",
42
+ strictSerena: false,
43
+ stripReasoning: true,
44
+ dsAnchor: true,
45
+ weNeed: false,
46
+ };
47
+
48
+ function agentDir(): string {
49
+ return process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent");
50
+ }
51
+
52
+ function globalSettingsPath(): string {
53
+ return path.join(agentDir(), "settings.json");
54
+ }
55
+
56
+ /** <cwd>/.pi/settings.json — the trusted project overlay. */
57
+ export function projectSettingsPath(cwd: string): string {
58
+ return path.join(cwd, ".pi", "settings.json");
59
+ }
60
+
61
+ function readJson(file: string): Record<string, unknown> | null {
62
+ try {
63
+ if (!existsSync(file)) return null;
64
+ return JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>;
65
+ } catch {
66
+ return null; // unreadable/corrupt → this layer contributes nothing
67
+ }
68
+ }
69
+
70
+ function section(json: Record<string, unknown> | null): Record<string, unknown> {
71
+ const raw = json?.steering;
72
+ return raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};
73
+ }
74
+
75
+ /** Merge one settings layer's `steering` keys into out. */
76
+ function mergeLayer(out: SteeringSettings, json: Record<string, unknown> | null): void {
77
+ const s = section(json);
78
+ for (const key of ["firstToolHints", "selectionGuidance", "superpower", "strictSerena", "stripReasoning", "dsAnchor", "weNeed"] as const) {
79
+ if (typeof s[key] === "boolean") out[key] = s[key] as boolean;
80
+ }
81
+ if (typeof s.superpowerPrompt === "string") out.superpowerPrompt = s.superpowerPrompt.trim();
82
+ }
83
+
84
+ /** Effective steering settings: defaults ← global ← trusted project overlay. */
85
+ export function readSteeringSettings(ctx?: Pick<ExtensionContext, "cwd" | "isProjectTrusted">): SteeringSettings {
86
+ const out: SteeringSettings = { ...DEFAULT_STEERING_SETTINGS };
87
+ mergeLayer(out, readJson(globalSettingsPath()));
88
+ try {
89
+ if (ctx?.cwd && ctx.isProjectTrusted?.()) mergeLayer(out, readJson(projectSettingsPath(ctx.cwd)));
90
+ } catch {
91
+ /* untrusted or no ctx — global only */
92
+ }
93
+ return out;
94
+ }
95
+
96
+ /** Read-modify-write `steering` fields into the GLOBAL settings.json (merge,
97
+ * never clobber; atomic tmp+rename; a corrupt file refuses to clobber).
98
+ * Returns the written path. Exported for tests. */
99
+ export function writeSteeringSection(patch: Partial<SteeringSettings>): string {
100
+ const file = globalSettingsPath();
101
+ let settings: Record<string, unknown>;
102
+ try {
103
+ settings = existsSync(file) ? (JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>) : {};
104
+ } catch {
105
+ // Corrupt ≠ missing: writing here would replace the whole file with ONLY
106
+ // the steering section — bail instead.
107
+ throw new Error(`${file} is not valid JSON — fix or remove it before saving.`);
108
+ }
109
+ const s = (settings.steering ?? {}) as Record<string, unknown>;
110
+ for (const [key, value] of Object.entries(patch)) {
111
+ if (value === undefined) continue;
112
+ s[key] = typeof value === "string" ? value.trim() : value;
113
+ }
114
+ settings.steering = s;
115
+ mkdirSync(path.dirname(file), { recursive: true });
116
+ const tmp = file + ".tmp";
117
+ writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n", { mode: 0o600 });
118
+ renameSync(tmp, file);
119
+ return file;
120
+ }
121
+
122
+ /** True when a trusted project file carries its own `steering` section (the
123
+ * panel then discloses that those values override the global save). */
124
+ export function projectOverridesSteering(cwd: string, trusted: boolean): boolean {
125
+ if (!trusted) return false;
126
+ return Object.keys(section(readJson(projectSettingsPath(cwd)))).length > 0;
127
+ }
@@ -0,0 +1,93 @@
1
+ // Regression tests for reviewer-found ds-anchor defects (ported from
2
+ // pi-model-tools extensions/test/unit/ds-anchor-regressions.test.ts):
3
+ // 1. model_select away from target must NOT re-engage the bootstrap (stale
4
+ // sessionModel fallback) — minimal prompt/tool filter/budget pin must be
5
+ // inert for a non-target model after an explicit switch.
6
+ // 2. turn_end with stopReason error/aborted must NOT promote — the retry
7
+ // stays anchored.
8
+ // 3. anchorTrace is per-session (reset on session_start).
9
+ // 4. max_tokens pin emits exactly one budget field (no conflicting pair).
10
+ import assert from "node:assert";
11
+ import { describe, it } from "node:test";
12
+ import { createFakePi } from "./harness.js";
13
+
14
+ const MINIMAL = "You are a helpful software engineer assistant.";
15
+
16
+ describe("ds-anchor regressions", () => {
17
+ it("model_select away from target keeps the anchor inert (no stale sessionModel re-engage)", () => {
18
+ const h = createFakePi();
19
+ h.setEntries([]);
20
+ h.fire("session_start", {}, h.ctx("deepseek-v4-pro-0813"));
21
+ // switch AWAY to flash
22
+ h.fire("model_select", { model: { id: "deepseek-v4-flash" }, previousModel: undefined, source: "set" }, h.ctx("deepseek-v4-flash"));
23
+ const r = h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx("deepseek-v4-flash"));
24
+ assert.notEqual(r?.systemPrompt, MINIMAL, "flash after switch-away must NOT get the minimal prompt");
25
+ const out = h.fire("before_provider_request", { payload: { tools: [{ name: "bash" }, { name: "str_replace_editor" }, { name: "edit" }] } }, h.ctx("deepseek-v4-flash"));
26
+ assert.equal(out?.tools, undefined, "no tool substitution after switch-away");
27
+ assert.equal(out?.max_tokens, undefined, "no budget pin after switch-away");
28
+ });
29
+
30
+ it("model_select to target re-engages the bootstrap", () => {
31
+ const h = createFakePi();
32
+ h.setEntries([]);
33
+ h.fire("session_start", {}, h.ctx("deepseek-v4-flash"));
34
+ h.fire("model_select", { model: { id: "deepseek-v4-pro" }, previousModel: undefined, source: "set" }, h.ctx("deepseek-v4-pro"));
35
+ const r = h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
36
+ assert.equal(r?.systemPrompt, MINIMAL, "switch to pro engages the bootstrap");
37
+ });
38
+
39
+ it("turn_end with stopReason error does NOT promote (retry stays anchored)", () => {
40
+ const h = createFakePi();
41
+ h.setEntries([]);
42
+ h.fire("session_start", {}, h.ctx("deepseek-v4-pro"));
43
+ h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
44
+ h.fire("turn_end", { turnIndex: 0, message: { role: "assistant", stopReason: "error", content: [] }, toolResults: [] }, h.ctx("deepseek-v4-pro"));
45
+ const r = h.fire("before_agent_start", { prompt: "retry", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
46
+ assert.equal(r?.systemPrompt, MINIMAL, "error reply must not promote; retry re-anchors");
47
+ });
48
+
49
+ it("turn_end with stopReason aborted does NOT promote", () => {
50
+ const h = createFakePi();
51
+ h.setEntries([]);
52
+ h.fire("session_start", {}, h.ctx("deepseek-v4-pro"));
53
+ h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
54
+ h.fire("turn_end", { turnIndex: 0, message: { role: "assistant", stopReason: "aborted", content: [] }, toolResults: [] }, h.ctx("deepseek-v4-pro"));
55
+ const r = h.fire("before_agent_start", { prompt: "retry", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
56
+ assert.equal(r?.systemPrompt, MINIMAL, "aborted reply must not promote");
57
+ });
58
+
59
+ it("turn_end with a real reply promotes", () => {
60
+ const h = createFakePi();
61
+ h.setEntries([]);
62
+ h.fire("session_start", {}, h.ctx("deepseek-v4-pro"));
63
+ h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
64
+ h.fire("turn_end", { turnIndex: 0, message: { role: "assistant", stopReason: "stop", content: [{ type: "toolCall" }] }, toolResults: [] }, h.ctx("deepseek-v4-pro"));
65
+ const r = h.fire("before_agent_start", { prompt: "next", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
66
+ assert.notEqual(r?.systemPrompt, MINIMAL, "durable reply promotes");
67
+ });
68
+
69
+ it("anchorTrace resets per session", () => {
70
+ const h = createFakePi();
71
+ h.setEntries([]);
72
+ h.fire("session_start", {}, h.ctx("deepseek-v4-pro"));
73
+ h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
74
+ let s = h.status(h.ctx("deepseek-v4-pro"));
75
+ assert.match(s, /bootstrap: minimal prompt engaged/, "trace populated in session 1");
76
+ // new session
77
+ h.fire("session_start", {}, h.ctx("deepseek-v4-pro"));
78
+ s = h.status(h.ctx("deepseek-v4-pro"));
79
+ assert.doesNotMatch(s, /bootstrap: minimal prompt engaged/, "trace does not leak across sessions");
80
+ });
81
+
82
+ it("budget pin emits exactly one field and drops the other", () => {
83
+ const h = createFakePi();
84
+ h.setEntries([]);
85
+ h.fire("session_start", {}, h.ctx("deepseek-v4-pro"));
86
+ h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
87
+ const out = h.fire("before_provider_request", {
88
+ payload: { tools: [{ name: "bash" }, { name: "str_replace_editor" }], max_tokens: 8192, max_completion_tokens: 8192 },
89
+ }, h.ctx("deepseek-v4-pro"));
90
+ assert.equal(out.max_completion_tokens, 256000, "budget pinned on the field the payload already carries");
91
+ assert.equal(out.max_tokens, undefined, "conflicting max_tokens dropped");
92
+ });
93
+ });
@@ -0,0 +1,99 @@
1
+ // Lifecycle test, adapted from pi-model-tools
2
+ // extensions/test/unit/ds-anchor-wiring.test.ts: the real module is wired into a
3
+ // stub ExtensionAPI and the anchor lifecycle is driven directly —
4
+ // session_start → before_agent_start (#1 bootstrap) → before_provider_request
5
+ // (tool filter) → tool_call (bootstrap tool gate) → turn_end (promote) →
6
+ // before_agent_start #2 (full prompt path).
7
+
8
+ import assert from "node:assert";
9
+ import { after, before } from "node:test";
10
+ import { createFakePi, isolateAgentDir } from "./harness.js";
11
+
12
+ let restoreAgentDir: () => void;
13
+ before(() => { restoreAgentDir = isolateAgentDir("ceulen-steering-wiring-").restore; });
14
+ after(() => { restoreAgentDir(); });
15
+
16
+ const MINIMAL = "You are a helpful software engineer assistant.";
17
+ const PRO = "deepseek-v4-pro-0813";
18
+
19
+ // 1. session_start with a target model, empty durable history
20
+ const h = createFakePi(["bash", "read", "edit", "grep"]);
21
+ h.setEntries([]);
22
+ h.fire("session_start", {}, h.ctx(PRO));
23
+
24
+ // 2. first agent run → bootstrap: minimal prompt, no guidance
25
+ const r1 = h.fire("before_agent_start", { prompt: "do a task", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
26
+ assert.equal(r1?.systemPrompt, MINIMAL, "request #1 gets the Minimal prompt");
27
+
28
+ // 3. provider request → tools replaced with the byte-exact DSH Minimal pair
29
+ const payload = { model: PRO, messages: [], tools: [
30
+ { name: "bash", parameters: {} }, { name: "str_replace_editor", parameters: {} },
31
+ { name: "edit", parameters: {} }, { name: "read", parameters: {} }, { name: "grep", parameters: {} },
32
+ ] };
33
+ const out = h.fire("before_provider_request", { payload }, h.ctx(PRO));
34
+ assert.deepEqual(out.tools.map((t: any) => t?.function?.name ?? t?.name), ["bash", "str_replace_editor"], "payload tools replaced with the DSH Minimal pair (flat shape preserved)");
35
+ assert.equal(out.tools[0].description.length > 100, true, "DSH bash description is present");
36
+ assert.equal(out.tools[1].parameters.properties.command.enum.length, 4, "str_replace_editor command enum present");
37
+ assert.equal(out.tools[1].strict, undefined, "no strict field (DSH schema has none)");
38
+ assert.equal(out.max_tokens, 256000, "bootstrap budget matches DSH's captured payload");
39
+
40
+ // 4. tool_call during bootstrap: a name outside the pair is blocked, the pair passes
41
+ const blocked = h.fire("tool_call", { toolName: "read", input: {} }, h.ctx(PRO));
42
+ assert.equal(blocked?.block, true, "hidden tool (read) blocked during bootstrap");
43
+ const blockedEdit = h.fire("tool_call", { toolName: "edit", input: {} }, h.ctx(PRO));
44
+ assert.equal(blockedEdit?.block, true, "hidden tool (edit) blocked during bootstrap");
45
+ const okBash = h.fire("tool_call", { toolName: "bash", input: { command: "ls" } }, h.ctx(PRO));
46
+ assert.equal(okBash, undefined, "bash allowed during bootstrap");
47
+ const okEditor = h.fire("tool_call", { toolName: "str_replace_editor", input: { command: "view", path: "/x" } }, h.ctx(PRO));
48
+ assert.equal(okEditor, undefined, "str_replace_editor allowed during bootstrap");
49
+
50
+ // 5. assistant reply lands durably → the next before_agent_start scan promotes
51
+ h.setEntries([{ type: "message", message: { role: "assistant", content: [{ type: "toolCall" }] } }]);
52
+ h.fire("turn_end", { turnIndex: 0, message: { role: "assistant", content: [] }, toolResults: [] }, h.ctx(PRO));
53
+
54
+ // 6. second agent run → NOT minimal; full-prompt path (returns undefined when unchanged)
55
+ const r2 = h.fire("before_agent_start", { prompt: "next task", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
56
+ assert.notEqual(r2?.systemPrompt, MINIMAL, "request #2 uses the full prompt");
57
+
58
+ // 7. provider request #2 → tools NOT filtered, budget NOT pinned
59
+ const out2 = h.fire("before_provider_request", { payload }, h.ctx(PRO));
60
+ assert.equal(out2?.tools, undefined, "no tool filtering after promotion (payload untouched or guidance-only)");
61
+ assert.notEqual(out2?.max_tokens, 256000, "budget pin is bootstrap-only");
62
+
63
+ // 8. non-target model: anchor inert from the start
64
+ h.setEntries([]);
65
+ h.fire("session_start", {}, h.ctx("deepseek-v4-flash"));
66
+ const rFlash = h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx("deepseek-v4-flash"));
67
+ assert.notEqual(rFlash?.systemPrompt, MINIMAL, "flash model: normal guidance path, no anchor");
68
+ assert.ok(rFlash.systemPrompt.includes("FULL PI PROMPT"), "flash keeps the full prompt");
69
+
70
+ // 9. resume edge: target session with existing assistant reply → instantly promoted
71
+ h.setEntries([{ type: "message", message: { role: "assistant", content: [{ type: "text" }] } }]);
72
+ h.fire("session_start", {}, h.ctx(PRO));
73
+ const rResume = h.fire("before_agent_start", { prompt: "continue", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
74
+ assert.notEqual(rResume?.systemPrompt, MINIMAL, "resumed session with replies: no bootstrap");
75
+ assert.ok(rResume.systemPrompt.includes("FULL PI PROMPT"), "resumed session keeps the full prompt");
76
+
77
+ // 10. REGRESSION: session starts as FLASH (a2a gateway agent config), proxy
78
+ // silently serves deepseek-v4-pro — model_select NEVER fires. The anchor must
79
+ // still engage on the first agent run (live failure: anchorReady was latched
80
+ // only at session_start/model_select, so the bootstrap silently skipped).
81
+ h.setEntries([]); // genuinely fresh session — no durable replies yet
82
+ const servedCtx = h.ctx("deepseek/deepseek-v4-pro", { model: { id: "deepseek/deepseek-v4-pro", provider: "opencode-go" } });
83
+ h.fire("session_start", {}, h.ctx("opencode-go/deepseek-v4-flash"));
84
+ const rRewritten = h.fire("before_agent_start", { prompt: "task", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, servedCtx);
85
+ assert.equal(rRewritten?.systemPrompt, MINIMAL, "served-pro session bootstraps even though session started as flash");
86
+ const outRewritten = h.fire("before_provider_request", { payload }, servedCtx);
87
+ assert.deepEqual(outRewritten.tools.map((t: any) => t?.function?.name ?? t?.name), ["bash", "str_replace_editor"], "rewritten session gets the DSH Minimal pair");
88
+
89
+ // 11. anchor trace surfaces in the /steering status output
90
+ const h2 = createFakePi(["bash", "read", "edit", "str_replace_editor"]);
91
+ h2.setEntries([]);
92
+ h2.fire("session_start", {}, h2.ctx("deepseek-v4-pro"));
93
+ h2.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL", systemPromptOptions: {} }, h2.ctx("deepseek-v4-pro"));
94
+ h2.fire("before_provider_request", { payload: { tools: [{ name: "bash" }, { name: "str_replace_editor" }] } }, h2.ctx("deepseek-v4-pro"));
95
+ const statusText = h2.status(h2.ctx("deepseek-v4-pro"));
96
+ assert.match(statusText, /bootstrap: minimal prompt engaged/, "trace shows bootstrap engagement");
97
+ assert.match(statusText, /payload: tools=\[bash,str_replace_editor\] \+ max_tokens=256000/, "trace shows the bootstrap payload + DSH budget");
98
+
99
+ console.log("steering ds-anchor wiring: all lifecycle checks passed");
@@ -0,0 +1,160 @@
1
+ // Ported from pi-model-tools extensions/test/unit/ds-anchor.test.ts.
2
+ // Local changes: the anchorEnabled / weNeedDirectiveEnabled env toggles are
3
+ // `steering.dsAnchor` / `steering.weNeed` settings rows (covered by
4
+ // settings.test.ts), and the byte-fidelity comparison against the registered
5
+ // str_replace_editor tool is dropped — that tool belongs to the repair module,
6
+ // so only the injected DSH definition itself is asserted here.
7
+ import assert from "node:assert";
8
+ import { describe, it } from "node:test";
9
+ import {
10
+ MINIMAL_SYSTEM_PROMPT,
11
+ BOOTSTRAP_TOOLS,
12
+ isAnchorTarget,
13
+ hasPromotionSignal,
14
+ filterBootstrapTools,
15
+ dshBootstrapTools,
16
+ DSH_BOOTSTRAP_TOOL_DEFS,
17
+ WE_NEED_DIRECTIVE,
18
+ } from "../lib/anchor.js";
19
+
20
+ describe("isAnchorTarget", () => {
21
+ it("matches v4-pro ids in any case/format, rejects everything else", () => {
22
+ assert.equal(isAnchorTarget("deepseek-v4-pro"), true);
23
+ assert.equal(isAnchorTarget("deepseek-v4-pro-0813"), true);
24
+ assert.equal(isAnchorTarget("OCG/DeepSeek-V4-Pro"), true);
25
+ assert.equal(isAnchorTarget("deepseek-v4-flash"), false);
26
+ assert.equal(isAnchorTarget("deepseek-chat"), false);
27
+ assert.equal(isAnchorTarget("deepseek-v3"), false);
28
+ assert.equal(isAnchorTarget("glm-5.2"), false);
29
+ assert.equal(isAnchorTarget(""), false);
30
+ assert.equal(isAnchorTarget(undefined), false);
31
+ });
32
+ });
33
+
34
+ describe("hasPromotionSignal", () => {
35
+ it("assistant message with tool call promotes", () => {
36
+ const entries = [
37
+ { type: "message", message: { role: "user", content: [{ type: "text", text: "hi" }] } },
38
+ { type: "message", message: { role: "assistant", content: [{ type: "toolCall", id: "t1" }] } },
39
+ ];
40
+ assert.equal(hasPromotionSignal(entries), true);
41
+ });
42
+
43
+ it("text-only assistant message promotes", () => {
44
+ const entries = [
45
+ { type: "message", message: { role: "assistant", content: [{ type: "text", text: "hello" }] } },
46
+ ];
47
+ assert.equal(hasPromotionSignal(entries), true);
48
+ });
49
+
50
+ it("user-only entries do not promote", () => {
51
+ const entries = [
52
+ { type: "message", message: { role: "user", content: [{ type: "text", text: "hi" }] } },
53
+ { type: "message", message: { role: "toolResult", content: [] } },
54
+ ];
55
+ assert.equal(hasPromotionSignal(entries), false);
56
+ });
57
+
58
+ it("empty entries do not promote", () => {
59
+ assert.equal(hasPromotionSignal([]), false);
60
+ });
61
+ });
62
+
63
+ describe("filterBootstrapTools", () => {
64
+ const mixed = [
65
+ { name: "bash", parameters: {} },
66
+ { name: "str_replace_editor", parameters: {} },
67
+ { name: "edit", parameters: {} },
68
+ { name: "read", parameters: {} },
69
+ { type: "function", function: { name: "grep" } },
70
+ ];
71
+
72
+ it("keeps only bash+str_replace_editor from a mixed catalog", () => {
73
+ const res = filterBootstrapTools(mixed);
74
+ assert.equal(res.ok, true);
75
+ assert.deepEqual(res.tools.map((t: any) => t.name ?? t.function?.name), ["bash", "str_replace_editor"]);
76
+ });
77
+
78
+ it("OpenAI function.name shape is recognized", () => {
79
+ const openaiShape = [
80
+ { type: "function", function: { name: "str_replace_editor", parameters: {} } },
81
+ { type: "function", function: { name: "bash", parameters: {} } },
82
+ ];
83
+ const res = filterBootstrapTools(openaiShape);
84
+ assert.equal(res.ok, true);
85
+ assert.equal(res.tools.length, 2);
86
+ });
87
+
88
+ it("missing str_replace_editor fails open with the original array", () => {
89
+ const noEditor = [{ name: "bash" }, { name: "read" }];
90
+ const res = filterBootstrapTools(noEditor);
91
+ assert.equal(res.ok, false);
92
+ assert.equal(res.tools, noEditor); // same reference — original returned
93
+ });
94
+
95
+ it("missing bash fails open", () => {
96
+ const noBash = [{ name: "str_replace_editor" }];
97
+ const res = filterBootstrapTools(noBash);
98
+ assert.equal(res.ok, false);
99
+ assert.equal(res.tools, noBash);
100
+ });
101
+
102
+ it("non-array tools fails open", () => {
103
+ const res = filterBootstrapTools(undefined);
104
+ assert.equal(res.ok, false);
105
+ assert.deepEqual(res.tools, []);
106
+ });
107
+ });
108
+
109
+ describe("dshBootstrapTools shape preservation", () => {
110
+ it("flat payload shape in → flat DSH defs out", () => {
111
+ const flat = [{ name: "bash", parameters: {} }, { name: "str_replace_editor", parameters: {} }, { name: "edit" }];
112
+ const res = dshBootstrapTools(flat);
113
+ assert.equal(res.ok, true);
114
+ assert.equal(res.tools.length, 2);
115
+ assert.equal((res.tools[0] as any).function, undefined, "no function wrapper for flat shape");
116
+ assert.equal((res.tools[0] as any).name, "bash");
117
+ assert.equal((res.tools[1] as any).name, "str_replace_editor");
118
+ assert.equal((res.tools[1] as any).parameters.properties.command.enum.length, 4);
119
+ });
120
+
121
+ it("function-wrapped payload shape in → function-wrapped defs out", () => {
122
+ const wrapped = [
123
+ { type: "function", function: { name: "bash", parameters: {} } },
124
+ { type: "function", function: { name: "str_replace_editor", parameters: {} } },
125
+ ];
126
+ const res = dshBootstrapTools(wrapped);
127
+ assert.equal(res.ok, true);
128
+ assert.equal((res.tools[0] as any).function.name, "bash");
129
+ assert.equal((res.tools[1] as any).function.name, "str_replace_editor");
130
+ assert.equal((res.tools[0] as any).name, undefined, "function-wrapped defs keep the wrapper");
131
+ });
132
+
133
+ it("missing pair still fails open", () => {
134
+ const res = dshBootstrapTools([{ name: "bash" }, { name: "edit" }]);
135
+ assert.equal(res.ok, false);
136
+ });
137
+ });
138
+
139
+ describe("constants", () => {
140
+ it("minimal prompt is byte-stable and bootstrap set is the real Minimal pair", () => {
141
+ assert.equal(MINIMAL_SYSTEM_PROMPT, "You are a helpful software engineer assistant.");
142
+ assert.deepEqual([...BOOTSTRAP_TOOLS], ["bash", "str_replace_editor"]);
143
+ });
144
+
145
+ it("we-need directive is the DSH thinking directive", () => {
146
+ assert.match(WE_NEED_DIRECTIVE, /We need/);
147
+ });
148
+
149
+ it("DSH tool defs stay byte-faithful (no Pi serialization leaked in)", () => {
150
+ const [dshBash, dshEditor] = DSH_BOOTSTRAP_TOOL_DEFS;
151
+ assert.equal(dshBash.function.name, "bash");
152
+ assert.equal(dshEditor.function.name, "str_replace_editor");
153
+ assert.equal(dshEditor.function.parameters.required.join(","), "command,path", "DSH def requires command+path");
154
+ assert.equal(dshEditor.function.parameters.properties.command.enum.length, 4, "command enum intact");
155
+ assert.equal(dshEditor.function.parameters.properties.insert_line.type, "integer", "insert_line is integer in DSH def");
156
+ // No strict/extra fields in the injected def (byte fidelity).
157
+ assert.equal((DSH_BOOTSTRAP_TOOL_DEFS[1] as any).strict, undefined);
158
+ assert.equal((DSH_BOOTSTRAP_TOOL_DEFS[0] as any).strict, undefined);
159
+ });
160
+ });