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,251 @@
1
+ // ponytail: vendored from @bacnh85/pi-model-tools 0.9.5 — lib/str-replace-editor.ts
2
+ // Local change: none (byte-faithful port — the tool description, schema text and
3
+ // error strings are load-bearing: this tool is the DSH Minimal-pair anchor).
4
+ /**
5
+ * str-replace-editor.ts — faithful port of DeepSeek Harness' Minimal-pair
6
+ * `str_replace_editor` tool (packages/fs/tool-str-replace-editor, commit
7
+ * 47f9438, MIT). Byte-faithful name, description, and schema — the tool
8
+ * schema is the decisive anchor lever for DeepSeek v4 Pro (dsh-anchored-
9
+ * standard issue #11: the real Minimal pair anchored "we need…" 5/5; every
10
+ * read/pwsh substitution produced standard-like first lines 11/11).
11
+ *
12
+ * Implemented over Node fs; relative paths resolve against the call's cwd.
13
+ */
14
+
15
+ import { readFile, writeFile, stat, readdir, mkdir } from "node:fs/promises";
16
+ import { isAbsolute, resolve as resolvePath, dirname } from "node:path";
17
+ import { homedir } from "node:os";
18
+ import { defineTool } from "@earendil-works/pi-coding-agent";
19
+ import { Type } from "typebox";
20
+
21
+ const TRUNCATED_MESSAGE =
22
+ "To save on context only part of this file has been shown to you. You should retry this tool after you have searched inside the file with `grep -n` in order to find the line numbers of what you are looking for.";
23
+
24
+ const MAX_OUTPUT_CHARS = 16_000;
25
+
26
+ // Byte-copy of DSH's DEFAULT_DESCRIPTION (trimmed template literal).
27
+ const EDITOR_DESCRIPTION = `Custom editing tool for viewing, creating and editing files
28
+ * State is persistent across command calls and discussions with the user
29
+ * If \`path\` is a file, \`view\` displays the result of applying \`cat -n\`. If \`path\` is a directory, \`view\` lists non-hidden files and directories up to 2 levels deep
30
+ * The \`create\` command cannot be used if the specified \`path\` already exists as a file
31
+ * If a \`command\` generates a long output, it will be truncated and marked with \`\`\`
32
+
33
+ Notes for using the \`str_replace\` command:
34
+ * The \`old_str\` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!
35
+ * If the \`old_str\` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in \`old_str\` to make it unique
36
+ * The \`new_str\` parameter should contain the edited lines that should replace the \`old_str\``;
37
+
38
+ function maybeTruncate(content: string): string {
39
+ return content.length <= MAX_OUTPUT_CHARS ? content : content.slice(0, MAX_OUTPUT_CHARS) + TRUNCATED_MESSAGE;
40
+ }
41
+
42
+ function matchOffsets(content: string, search: string): number[] {
43
+ const offsets: number[] = [];
44
+ let offset = 0;
45
+ while (true) {
46
+ const match = content.indexOf(search, offset);
47
+ if (match < 0) return offsets;
48
+ offsets.push(match);
49
+ offset = match + search.length;
50
+ }
51
+ }
52
+
53
+ function lineNumbersAt(content: string, offsets: readonly number[]): number[] {
54
+ let line = 1;
55
+ let cursor = 0;
56
+ return offsets.map((offset) => {
57
+ while (cursor < offset) {
58
+ if (content[cursor] === "\n") line += 1;
59
+ cursor += 1;
60
+ }
61
+ return line;
62
+ });
63
+ }
64
+
65
+ function formatFileView(path: string, content: string, viewRange?: number[]): string {
66
+ const allLines = content.split("\n");
67
+ let lines = allLines;
68
+ let initialLine = 1;
69
+ let finalLine: number | undefined;
70
+ let prompt = `Here's the content of ${path} with line numbers (which has a total of ${allLines.length} lines)`;
71
+ if (viewRange !== undefined) {
72
+ const [requestedInitialLine, requestedFinalLine] = viewRange;
73
+ if (viewRange.length !== 2 || !viewRange.every(Number.isInteger)) {
74
+ throw new Error("Invalid `view_range`. It should be a list of two integers.");
75
+ }
76
+ initialLine = requestedInitialLine;
77
+ finalLine = requestedFinalLine;
78
+ if (initialLine < 1 || initialLine > allLines.length) {
79
+ throw new Error(`Invalid \`view_range\`: [${viewRange.join(", ")}]. Its first element \`${initialLine}\` should be within the range of lines of the file: [1, ${allLines.length}]`);
80
+ }
81
+ if (finalLine > allLines.length) {
82
+ throw new Error(`Invalid \`view_range\`: [${viewRange.join(", ")}]. Its second element \`${finalLine}\` should be smaller than the number of lines in the file: \`${allLines.length}\``);
83
+ }
84
+ if (finalLine !== -1 && finalLine < initialLine) {
85
+ throw new Error(`Invalid \`view_range\`: [${viewRange.join(", ")}]. Its second element \`${finalLine}\` should be larger or equal than its first \`${initialLine}\``);
86
+ }
87
+ lines = finalLine === -1 ? allLines.slice(initialLine - 1) : allLines.slice(initialLine - 1, finalLine);
88
+ prompt += ` with view_range=[${initialLine}, ${finalLine}]`;
89
+ }
90
+ const numbered = lines.map((line, index) => `${String(initialLine + index).padStart(6, " ")} ${line}`).join("\n");
91
+ return maybeTruncate(`${prompt}:\n${numbered}\n`);
92
+ }
93
+
94
+ async function listDirectory(dirPath: string): Promise<string> {
95
+ async function visit(dir: string, depth: number): Promise<string[]> {
96
+ const entries = await readdir(dir, { withFileTypes: true });
97
+ const rows: string[] = [];
98
+ for (const entry of entries.filter(
99
+ (candidate) => !candidate.name.startsWith(".") && candidate.name !== "node_modules" && candidate.name !== "__pycache__",
100
+ )) {
101
+ const type = entry.isDirectory() ? "d" : entry.isFile() ? "f" : "?";
102
+ const full = resolvePath(dir, entry.name);
103
+ rows.push(`${type}\t${full}`);
104
+ if (entry.isDirectory() && depth < 2) {
105
+ rows.push(...(await visit(full, depth + 1)));
106
+ }
107
+ }
108
+ return rows;
109
+ }
110
+ const rows = [`d\t${dirPath}`, ...(await visit(dirPath, 1))];
111
+ rows.sort((left, right) => {
112
+ const leftPath = left.slice(left.indexOf("\t") + 1);
113
+ const rightPath = right.slice(right.indexOf("\t") + 1);
114
+ return leftPath < rightPath ? -1 : 1;
115
+ });
116
+ const listing = maybeTruncate(rows.join("\n") + "\n");
117
+ return `Here're the files and directories up to 2 levels deep in ${dirPath}, excluding hidden items, node_modules, and Python cache directories:\n${listing}\n`;
118
+ }
119
+
120
+ function resolveTarget(cwd: string, path: string): string {
121
+ if (typeof path !== "string" || path.trim().length === 0) throw new Error("path must be a non-empty string");
122
+ // ~/… expands to the home dir, matching Pi's built-in file tools (models
123
+ // trained on DSH emit absolute paths; relative ones resolve against cwd).
124
+ const expanded =
125
+ path === "~" ? homedir() : path.startsWith("~/") || path.startsWith("~\\") ? `${homedir()}${path.slice(1)}` : path;
126
+ return isAbsolute(expanded) ? expanded : resolvePath(cwd, expanded);
127
+ }
128
+
129
+ async function statExisting(abs: string, command: "view" | "str_replace" | "insert"): Promise<Awaited<ReturnType<typeof stat>>> {
130
+ let info;
131
+ try {
132
+ info = await stat(abs);
133
+ } catch {
134
+ throw new Error(`The path ${abs} does not exist. Please provide a valid path.`);
135
+ }
136
+ if (info.isDirectory() && command !== "view") {
137
+ throw new Error(`The path ${abs} is a directory and only the \`view\` command can be used on directories`);
138
+ }
139
+ return info;
140
+ }
141
+
142
+ function requiredForCommand(value: string | undefined, parameter: string, command: string, allowEmpty = true): string {
143
+ if (value === undefined) throw new Error(`Parameter \`${parameter}\` is required for command: ${command}`);
144
+ if (!allowEmpty && value.length === 0) throw new Error(`Parameter \`${parameter}\` is empty for command: ${command}`);
145
+ return value;
146
+ }
147
+
148
+ async function viewPath(cwd: string, path: string, viewRange: number[] | undefined): Promise<string> {
149
+ const abs = resolveTarget(cwd, path);
150
+ const info = await statExisting(abs, "view");
151
+ if (info.isDirectory()) {
152
+ if (viewRange !== undefined) throw new Error("The `view_range` parameter is not allowed when `path` points to a directory.");
153
+ return listDirectory(abs);
154
+ }
155
+ const content = await readFile(abs, "utf-8");
156
+ return formatFileView(abs, content, viewRange);
157
+ }
158
+
159
+ async function createFile(cwd: string, path: string, fileText: string | undefined): Promise<string> {
160
+ const content = requiredForCommand(fileText, "file_text", "create");
161
+ const abs = resolveTarget(cwd, path);
162
+ const existing = await stat(abs).then(() => true).catch(() => false);
163
+ if (existing) throw new Error(`File already exists at: ${abs}. Cannot overwrite files using command \`create\`.`);
164
+ await mkdir(dirname(abs), { recursive: true });
165
+ await writeFile(abs, content);
166
+ return `New file created successfully at: ${abs}`;
167
+ }
168
+
169
+ async function replaceInFile(cwd: string, path: string, oldStr: string | undefined, newStr: string | undefined): Promise<string> {
170
+ const oldValue = requiredForCommand(oldStr, "old_str", "str_replace", false);
171
+ const newValue = newStr ?? "";
172
+ const abs = resolveTarget(cwd, path);
173
+ await statExisting(abs, "str_replace");
174
+ const before = await readFile(abs, "utf-8");
175
+ const offsets = matchOffsets(before, oldValue);
176
+ const offset = offsets[0];
177
+ if (offset === undefined) {
178
+ throw new Error(`No replacement was performed, old_str \`${oldValue}\` did not appear verbatim in ${abs}.`);
179
+ }
180
+ if (offsets.length > 1) {
181
+ const lines = lineNumbersAt(before, offsets);
182
+ throw new Error(`No replacement was performed. Multiple occurrences of old_str \`${oldValue}\` in lines [${lines.join(", ")}]. Please ensure it is unique`);
183
+ }
184
+ await writeFile(abs, before.slice(0, offset) + newValue + before.slice(offset + oldValue.length));
185
+ return `The file ${abs} has been edited successfully.`;
186
+ }
187
+
188
+ async function insertInFile(cwd: string, path: string, insertLine: number | undefined, newStr: string | undefined): Promise<string> {
189
+ if (insertLine === undefined) throw new Error("Parameter `insert_line` is required for command: insert");
190
+ const value = requiredForCommand(newStr, "new_str", "insert");
191
+ const abs = resolveTarget(cwd, path);
192
+ await statExisting(abs, "insert");
193
+ const before = await readFile(abs, "utf-8");
194
+ const lines = before.split("\n");
195
+ if (!Number.isInteger(insertLine) || insertLine < 0 || insertLine > lines.length) {
196
+ throw new Error(`Invalid \`insert_line\` parameter: ${insertLine}. It should be within the range of lines of the file: [0, ${lines.length}]`);
197
+ }
198
+ const after = [...lines.slice(0, insertLine), ...value.split("\n"), ...lines.slice(insertLine)].join("\n");
199
+ await writeFile(abs, after);
200
+ return `The file ${abs} has been edited successfully.`;
201
+ }
202
+
203
+ /** Tool definition factory mirroring DSH's `str_replace_editor` (Minimal pair). */
204
+ export function createStrReplaceEditorToolDefinition(cwd: string) {
205
+ return defineTool({
206
+ name: "str_replace_editor",
207
+ label: "str_replace_editor",
208
+ description: EDITOR_DESCRIPTION,
209
+ promptSnippet: "View, create, edit, or insert into files (view/create/str_replace/insert over absolute paths)",
210
+ parameters: Type.Object({
211
+ command: Type.Enum({
212
+ view: "view",
213
+ create: "create",
214
+ str_replace: "str_replace",
215
+ insert: "insert",
216
+ }),
217
+ path: Type.String({ description: "Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`." }),
218
+ file_text: Type.Optional(Type.String({ description: "Required parameter of `create` command, with the content of the file to be created." })),
219
+ insert_line: Type.Optional(Type.Number({ description: "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`." })),
220
+ new_str: Type.Optional(Type.String({ description: "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert." })),
221
+ old_str: Type.Optional(Type.String({ description: "Required parameter of `str_replace` command containing the string in `path` to replace." })),
222
+ view_range: Type.Optional(Type.Array(Type.Number(), { description: "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file." })),
223
+ }),
224
+ renderShell: "self",
225
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
226
+ const callCwd = ctx?.cwd || cwd;
227
+ try {
228
+ let text: string;
229
+ switch (params.command) {
230
+ case "view":
231
+ text = await viewPath(callCwd, params.path, params.view_range);
232
+ break;
233
+ case "create":
234
+ text = await createFile(callCwd, params.path, params.file_text);
235
+ break;
236
+ case "str_replace":
237
+ text = await replaceInFile(callCwd, params.path, params.old_str, params.new_str);
238
+ break;
239
+ case "insert":
240
+ text = await insertInFile(callCwd, params.path, params.insert_line, params.new_str);
241
+ break;
242
+ default:
243
+ throw new Error(`Unknown command: ${String(params.command)}`);
244
+ }
245
+ return { content: [{ type: "text", text }], details: undefined };
246
+ } catch (err) {
247
+ return { content: [{ type: "text", text: err instanceof Error ? err.message : String(err) }], isError: true, details: undefined };
248
+ }
249
+ },
250
+ });
251
+ }
@@ -0,0 +1,34 @@
1
+ // ponytail: vendored from @bacnh85/pi-model-tools 0.9.5 — lib/shell-helpers.ts
2
+ // PORTED SUBSET (deliberate): only the two TOOL-HARDENING guards —
3
+ // checkDangerousCommand + looksLikeCodePath — and their private deps
4
+ // (normalizedTarget, isRecord). The semantic-miss / dedicated-tool /
5
+ // error-categorization half of the upstream file belongs to the model-steering
6
+ // layer and is NOT ported here. isRecord is duplicated into this module rather
7
+ // than imported across modules (ceulen modules never reach into each other).
8
+
9
+ export function isRecord(value: unknown): value is Record<string, unknown> {
10
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11
+ }
12
+
13
+ function normalizedTarget(value: unknown): string {
14
+ return (typeof value === "string" ? value.toLowerCase() : "").split(/[?#]/, 1)[0];
15
+ }
16
+
17
+ /** True when the value looks like an indexable source file (extension match). */
18
+ export function looksLikeCodePath(value: unknown): boolean {
19
+ return /\.(ts|tsx|js|jsx|mjs|cjs|mts|cts|py|go|rs|java|kt|kts|scala|rb|php|cs|cpp|cc|cxx|c|h|hpp|swift|sh|bash|zsh|fish|lua|r|jl|ex|exs|erl|hrl|clj|cljs|fs|fsx|ml|mli|dart|vue|svelte)$/i.test(normalizedTarget(value));
20
+ }
21
+
22
+ /** Returns a human reason when a bash command is destructively dangerous. */
23
+ export function checkDangerousCommand(command: unknown): string | undefined {
24
+ if (typeof command !== "string") return undefined;
25
+ const trimmed = command.trim().toLowerCase();
26
+ for (const [, args] of trimmed.matchAll(/\brm\s+([^;&|\n]+)/g)) {
27
+ const recursive = /(?:^|\s)(?:-[a-z]*r[a-z]*|--recursive)(?:\s|$)/.test(args);
28
+ const forced = /(?:^|\s)(?:-[a-z]*f[a-z]*|--force)(?:\s|$)/.test(args);
29
+ const absolute = /(?:^|\s)(?:--\s+)?(?:["']\/[^"']*["']|\/\S*)(?:\s|$)/.test(args);
30
+ if (recursive && forced && absolute) return "Forced recursive delete of an absolute path";
31
+ }
32
+ if (/\bdd\b[^\n;&|]*\bof=["']?\/dev\/(?:sd[a-z]\d*|vd[a-z]\d*|xvd[a-z]\d*|nvme\d+n\d+(?:p\d+)?|mmcblk\d+(?:p\d+)?|disk\d+|rdisk\d+|loop\d+|md\d+|mapper\/[a-z0-9._+-]+)\b/.test(trimmed)) return "Destructive dd write to a block device";
33
+ return undefined;
34
+ }
@@ -0,0 +1,324 @@
1
+ // ponytail: vendored from @bacnh85/pi-model-tools 0.9.5 — lib/tool-input-repair.ts
2
+ // Local change: isRecord now comes from ./guards.js (upstream imported it from
3
+ // lib/model-detection.ts, which is not ported — repair is model-agnostic by
4
+ // design: upstream already ran every repair below for all families, so there
5
+ // was no family branch to drop).
6
+ /**
7
+ * tool-input-repair.ts — unified argument repair for all model families.
8
+ *
9
+ * Merges DeepSeek V4 + GLM repairs into one module. The GLM top-level
10
+ * JSON-string repair is a safe superset (any model can emit a string where
11
+ * an object is expected), so it runs for all families — no family branching.
12
+ */
13
+
14
+ import { Compile } from "typebox/compile";
15
+ import { isRecord } from "./guards.js";
16
+
17
+ export type RepairKind = "path-markdown-autolink" | "optional-null" | "json-string" | "empty-object-array" | "bare-string-array" | "json-object-wrapped-array" | "top-level-json-string" | "truncated-json-closed" | "read-notice-stripped" | "trim-match-retry" | "param-alias";
18
+
19
+ export type RepairResult = {
20
+ args: unknown;
21
+ repaired: boolean;
22
+ repairs: RepairKind[];
23
+ };
24
+
25
+ const PATH_FIELD_NAMES = new Set(["path", "filePath", "absolutePath", "relativePath", "relative_path"]);
26
+
27
+ // Cross-harness param-name aliases: models trained on Claude Code
28
+ // (`Write{file_path, content}`) or generic completions (`text`, `body`)
29
+ // hallucinate property names Pi's built-ins don't use. Only applied to the
30
+ // wrapped built-in tools, only top-level, only when the aliased target is a
31
+ // REQUIRED schema property that is missing while the alias key is present.
32
+ // A rename is only applied when the value's type matches the target property's
33
+ // schema type — renaming a wrong-typed value would just relocate the
34
+ // validation error onto a key the model never sent.
35
+ const PARAM_ALIASES: Readonly<Record<string, string>> = {
36
+ file_path: "path",
37
+ filename: "path",
38
+ file_text: "content",
39
+ text: "content",
40
+ body: "content",
41
+ // Nested edit payloads (Cursor-trained snake_case inside edits[]): the top
42
+ // 5 measured causes of edit schema-validation failures (2026-09 sessions).
43
+ old_text: "oldText",
44
+ new_text: "newText",
45
+ };
46
+
47
+ const ALIASABLE_TOOLS = new Set(["read", "write", "edit", "grep", "find", "ls", "bash"]);
48
+
49
+ const compiledCache = new WeakMap<object, ReturnType<typeof Compile>>();
50
+
51
+ function getCompiled(schema: unknown): ReturnType<typeof Compile> {
52
+ if (typeof schema !== "object" || schema === null) return Compile(schema as never);
53
+ let compiled = compiledCache.get(schema as object);
54
+ if (!compiled) { compiled = Compile(schema as never); compiledCache.set(schema as object, compiled); }
55
+ return compiled;
56
+ }
57
+
58
+ function compileCheck(schema: unknown, args: unknown): boolean { return getCompiled(schema).Check(args); }
59
+
60
+ function validationErrors(schema: unknown, args: unknown): Array<{ instancePath?: string; path?: string }> {
61
+ return Array.from(getCompiled(schema).Errors(args)) as Array<{ instancePath?: string; path?: string }>;
62
+ }
63
+
64
+ function errorPath(error: { instancePath?: string; path?: string }): string[] {
65
+ const path = error.instancePath ?? error.path ?? "";
66
+ return path.replace(/^\//, "").split("/").filter(Boolean).map((p) => p.replace(/~1/g, "/").replace(/~0/g, "~"));
67
+ }
68
+
69
+ function schemaTypes(schema: unknown): string[] {
70
+ if (!isRecord(schema)) return [];
71
+ if (typeof schema.type === "string") return [schema.type];
72
+ if (Array.isArray(schema.type)) return schema.type.filter((t): t is string => typeof t === "string");
73
+ if (Array.isArray(schema.anyOf)) return schema.anyOf.flatMap(schemaTypes);
74
+ if (Array.isArray(schema.oneOf)) return schema.oneOf.flatMap(schemaTypes);
75
+ return [];
76
+ }
77
+
78
+ function schemaAtPath(schema: unknown, path: readonly string[]): unknown {
79
+ let current = schema;
80
+ for (const part of path) {
81
+ if (!isRecord(current)) return undefined;
82
+ const types = schemaTypes(current);
83
+ if (types.includes("object") && isRecord(current.properties)) { current = current.properties[part]; continue; }
84
+ if (types.includes("array")) { current = current.items; continue; }
85
+ return undefined;
86
+ }
87
+ return current;
88
+ }
89
+
90
+ function parentAtPath(value: unknown, path: readonly string[]): { parent: unknown; key: string } | undefined {
91
+ if (path.length === 0) return undefined;
92
+ let parent = value;
93
+ for (const part of path.slice(0, -1)) {
94
+ if (Array.isArray(parent)) parent = parent[Number(part)];
95
+ else if (isRecord(parent)) parent = parent[part];
96
+ else return undefined;
97
+ }
98
+ return { parent, key: path[path.length - 1] };
99
+ }
100
+
101
+ function getAtPath(value: unknown, path: readonly string[]): unknown {
102
+ let current = value;
103
+ for (const part of path) {
104
+ if (Array.isArray(current)) current = current[Number(part)];
105
+ else if (isRecord(current)) current = current[part];
106
+ else return undefined;
107
+ }
108
+ return current;
109
+ }
110
+
111
+ function setAtPath(value: unknown, path: readonly string[], next: unknown): boolean {
112
+ if (path.length === 0) return false;
113
+ const target = parentAtPath(value, path);
114
+ if (!target) return false;
115
+ if (Array.isArray(target.parent)) target.parent[Number(target.key)] = next;
116
+ else if (isRecord(target.parent)) target.parent[target.key] = next;
117
+ else return false;
118
+ return true;
119
+ }
120
+
121
+ function deleteAtPath(value: unknown, path: readonly string[]): boolean {
122
+ const target = parentAtPath(value, path);
123
+ if (!target) return false;
124
+ if (Array.isArray(target.parent)) target.parent.splice(Number(target.key), 1);
125
+ else if (isRecord(target.parent)) delete target.parent[target.key];
126
+ else return false;
127
+ return true;
128
+ }
129
+
130
+ function isOptionalProperty(rootSchema: unknown, path: readonly string[]): boolean {
131
+ if (path.length === 0) return false;
132
+ const parentSchema = schemaAtPath(rootSchema, path.slice(0, -1));
133
+ if (!isRecord(parentSchema) || !isRecord(parentSchema.properties)) return false;
134
+ const required = Array.isArray(parentSchema.required) ? parentSchema.required : [];
135
+ return Object.hasOwn(parentSchema.properties, path[path.length - 1]) && !required.includes(path[path.length - 1]);
136
+ }
137
+
138
+ function expects(schema: unknown, type: "array" | "object"): boolean { return schemaTypes(schema).includes(type); }
139
+
140
+ /**
141
+ * Lenient JSON parse for model-emitted tool args. Strict `JSON.parse` first;
142
+ * when that fails, treat the text as possibly truncated mid-structure
143
+ * (DeepSeek truncates tool-call JSON at generation limits) — close an
144
+ * unterminated string literal and any unclosed `{`/`[` brackets, then retry.
145
+ * `truncated: true` reports that a recovery close was applied.
146
+ */
147
+ export function tryParseLenientJson(text: string): { value: unknown; truncated: boolean } | undefined {
148
+ try {
149
+ return { value: JSON.parse(text), truncated: false };
150
+ } catch { /* not strict JSON — try truncation recovery */ }
151
+
152
+ const closed = closeTruncatedJson(text);
153
+ if (closed === text) return undefined;
154
+ try {
155
+ return { value: JSON.parse(closed), truncated: true };
156
+ } catch {
157
+ return undefined;
158
+ }
159
+ }
160
+
161
+ // Append missing closers for an unterminated string + unclosed brackets,
162
+ // scanning literal-aware: a `}`/`]` inside a quoted string is data, not a closer.
163
+ function closeTruncatedJson(text: string): string {
164
+ const stack: Array<"{" | "["> = [];
165
+ let inString = false;
166
+ let escaped = false;
167
+ for (let i = 0; i < text.length; i++) {
168
+ const ch = text[i];
169
+ if (inString) {
170
+ if (escaped) escaped = false;
171
+ else if (ch === "\\") escaped = true;
172
+ else if (ch === '"') inString = false;
173
+ continue;
174
+ }
175
+ if (ch === '"') { inString = true; continue; }
176
+ if (ch === "{") { stack.push("{"); continue; }
177
+ if (ch === "[") { stack.push("["); continue; }
178
+ if (ch === "}") { if (stack[stack.length - 1] === "{") stack.pop(); continue; }
179
+ if (ch === "]") { if (stack[stack.length - 1] === "[") stack.pop(); continue; }
180
+ }
181
+ // Pre-suffix recovery, before appending closers:
182
+ // - A dangling escape backslash would turn the closing `"` we append into an
183
+ // escaped quote (`\"`) and leave the string unterminated. Complete it as a
184
+ // literal backslash instead (e.g. {"path":"C:\ truncated mid-escape).
185
+ // - A trailing comma before an unclosed bracket makes the closed JSON
186
+ // invalid (DeepSeek often truncates right after a comma). Strip trailing
187
+ // whitespace/commas so the appended closers yield valid JSON.
188
+ if (inString && escaped) text += "\\";
189
+ else if (!inString && stack.length > 0) text = text.replace(/[\s,]+$/, "");
190
+ let suffix = "";
191
+ if (inString) suffix += '"'; // unterminated string literal (e.g. {"path":"abc)
192
+ while (stack.length > 0) suffix += stack.pop() === "{" ? "}" : "]";
193
+ return suffix ? text + suffix : text;
194
+ }
195
+
196
+ function tryRepairPath(rootSchema: unknown, args: unknown, path: readonly string[]): RepairKind | undefined {
197
+ const current = getAtPath(args, path);
198
+ const targetSchema = schemaAtPath(rootSchema, path);
199
+ if (current === null && isOptionalProperty(rootSchema, path) && deleteAtPath(args, path)) return "optional-null";
200
+ if (typeof current === "string" && (expects(targetSchema, "array") || expects(targetSchema, "object"))) {
201
+ const parsedResult = tryParseLenientJson(current);
202
+ if (parsedResult !== undefined) {
203
+ const parsed = parsedResult.value;
204
+ const plainKind: RepairKind = parsedResult.truncated ? "truncated-json-closed" : "json-string";
205
+ if ((expects(targetSchema, "array") && Array.isArray(parsed)) || (expects(targetSchema, "object") && isRecord(parsed))) {
206
+ if (setAtPath(args, path, parsed)) return plainKind;
207
+ }
208
+ if (expects(targetSchema, "array") && isRecord(parsed)) {
209
+ if (setAtPath(args, path, [parsed])) return parsedResult.truncated ? "truncated-json-closed" : "json-object-wrapped-array";
210
+ }
211
+ }
212
+ }
213
+ if (expects(targetSchema, "array") && isRecord(current) && Object.keys(current).length === 0) { if (setAtPath(args, path, [])) return "empty-object-array"; }
214
+ if (expects(targetSchema, "array") && typeof current === "string") { if (setAtPath(args, path, [current])) return "bare-string-array"; }
215
+ return undefined;
216
+ }
217
+
218
+ function tryParamAliases(toolName: string, schema: unknown, args: unknown): RepairKind | undefined {
219
+ if (!ALIASABLE_TOOLS.has(toolName) || !isRecord(args) || !isRecord(schema) || !isRecord(schema.properties)) return undefined;
220
+ const required = Array.isArray(schema.required) ? schema.required : [];
221
+ let applied: RepairKind | undefined;
222
+ for (const [wrong, right] of Object.entries(PARAM_ALIASES)) {
223
+ if (!required.includes(right) || right in args || !(wrong in args)) continue;
224
+ const types = schemaTypes(schema.properties[right]);
225
+ const value = args[wrong];
226
+ const valueType = value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
227
+ if (types.length > 0 && !types.includes(valueType)) continue;
228
+ args[right] = value;
229
+ delete args[wrong];
230
+ applied = "param-alias";
231
+ }
232
+ // Nested objects/arrays (e.g. edit's edits[] items): same rename rule,
233
+ // schema-guided at each level. Replaces the live "must have required
234
+ // properties oldText, newText" failure class (23 hits / 14 days).
235
+ const visit = (current: unknown, currentSchema: unknown): void => {
236
+ if (Array.isArray(current)) {
237
+ for (const item of current) visit(item, isRecord(currentSchema) ? (currentSchema as any).items : undefined);
238
+ return;
239
+ }
240
+ if (!isRecord(current) || !isRecord(currentSchema)) return;
241
+ const req = Array.isArray(currentSchema.required) ? currentSchema.required : [];
242
+ const props = isRecord(currentSchema.properties) ? currentSchema.properties : {};
243
+ for (const [wrong, right] of Object.entries(PARAM_ALIASES)) {
244
+ if (!(wrong in current) || right in current || !req.includes(right) || !Object.hasOwn(props, right)) continue;
245
+ const value = current[wrong];
246
+ const valueType = value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
247
+ const types = schemaTypes(props[right]);
248
+ if (types.length > 0 && !types.includes(valueType)) continue;
249
+ current[right] = value;
250
+ delete current[wrong];
251
+ applied = "param-alias";
252
+ }
253
+ for (const [k, v] of Object.entries(current)) visit(v, props[k]);
254
+ };
255
+ visit(args, schema);
256
+ return applied;
257
+ }
258
+
259
+ function normalizedLinkTarget(value: string): string { return value.replace(/^https?:\/\//i, "").replace(/\s+/g, "").replace(/^\/+/, ""); }
260
+
261
+ export function unwrapDegenerateMarkdownAutolink(value: string): string {
262
+ return value.replace(/\[([^\]\n]+)\]\((https?:\/\/[^)]+)\)/g, (match, text: string, url: string) => {
263
+ const normalizedText = text.replace(/\s+/g, "");
264
+ const normalizedUrl = normalizedLinkTarget(url);
265
+ if (normalizedUrl === normalizedText) return text;
266
+ const suffix = `/${normalizedText}`;
267
+ if (normalizedUrl.endsWith(suffix) && /^[\s.]*$/.test(normalizedUrl.slice(0, -suffix.length))) return text;
268
+ return match;
269
+ });
270
+ }
271
+
272
+ function cleanPathFields(value: unknown): { value: unknown; changed: boolean } {
273
+ let changed = false;
274
+ const visit = (current: unknown, key?: string): unknown => {
275
+ if (typeof current === "string" && key && PATH_FIELD_NAMES.has(key)) {
276
+ const next = unwrapDegenerateMarkdownAutolink(current);
277
+ changed ||= next !== current;
278
+ return next;
279
+ }
280
+ if (Array.isArray(current)) return current.map((item) => visit(item));
281
+ if (!isRecord(current)) return current;
282
+ const next: Record<string, unknown> = {};
283
+ for (const [k, v] of Object.entries(current)) next[k] = visit(v, k);
284
+ return next;
285
+ };
286
+ const nextValue = visit(value);
287
+ return { value: changed ? nextValue : value, changed };
288
+ }
289
+
290
+ /**
291
+ * Unified argument repair for all model families.
292
+ * DeepSeek + GLM repairs are the same logic — GLM adds top-level-json-string
293
+ * as a safe superset. One function, no family branching needed.
294
+ */
295
+ export function repairToolArguments(toolName: string, schema: unknown, args: unknown): RepairResult {
296
+ const pathCleaned = cleanPathFields(args);
297
+ if (compileCheck(schema, pathCleaned.value)) {
298
+ return { args: pathCleaned.value, repaired: pathCleaned.changed, repairs: pathCleaned.changed ? ["path-markdown-autolink"] : [] };
299
+ }
300
+
301
+ const candidate = structuredClone(pathCleaned.value);
302
+ const repairs: RepairKind[] = pathCleaned.changed ? ["path-markdown-autolink"] : [];
303
+ const aliased = tryParamAliases(toolName, schema, candidate);
304
+ if (aliased) repairs.push(aliased);
305
+ for (const error of validationErrors(schema, candidate)) {
306
+ const repaired = tryRepairPath(schema, candidate, errorPath(error));
307
+ if (repaired) repairs.push(repaired);
308
+ }
309
+
310
+ if (repairs.length > 0 && compileCheck(schema, candidate)) {
311
+ return { args: candidate, repaired: true, repairs };
312
+ }
313
+
314
+ // Top-level JSON string → object (safe for any model; originally GLM-4.7 bug)
315
+ if (typeof candidate === "string" && expects(schema, "object")) {
316
+ const parsedResult = tryParseLenientJson(candidate);
317
+ if (parsedResult !== undefined && isRecord(parsedResult.value) && compileCheck(schema, parsedResult.value)) {
318
+ const kind: RepairKind = parsedResult.truncated ? "truncated-json-closed" : "top-level-json-string";
319
+ return { args: parsedResult.value, repaired: true, repairs: [...repairs, kind] };
320
+ }
321
+ }
322
+
323
+ return { args: repairs.length > 0 ? candidate : args, repaired: repairs.length > 0, repairs };
324
+ }