ceulen 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (358) hide show
  1. package/CHANGELOG.md +317 -12
  2. package/README.md +87 -91
  3. package/extensions/lib/advisor-marker.ts +33 -0
  4. package/extensions/lib/panel.ts +25 -2
  5. package/extensions/lib/rate.ts +24 -0
  6. package/extensions/lib/registry.ts +93 -7
  7. package/extensions/lib/tools.ts +47 -0
  8. package/extensions/lib/usage-store.ts +33 -0
  9. package/extensions/modules/advisor/commands/advisor.ts +244 -0
  10. package/extensions/modules/advisor/configPanel.ts +194 -0
  11. package/extensions/modules/advisor/index.ts +217 -0
  12. package/extensions/modules/advisor/lib/config.ts +248 -0
  13. package/extensions/modules/advisor/lib/emission-guard.ts +153 -0
  14. package/extensions/modules/advisor/lib/isolated-model.ts +160 -0
  15. package/extensions/modules/advisor/lib/model-picker.ts +47 -0
  16. package/extensions/modules/advisor/lib/watcher.ts +286 -0
  17. package/extensions/modules/advisor/test/compliance.test.ts +125 -0
  18. package/extensions/modules/advisor/test/config.test.ts +202 -0
  19. package/extensions/modules/advisor/test/configPanel.test.ts +223 -0
  20. package/extensions/modules/advisor/test/emission-guard.test.ts +201 -0
  21. package/extensions/modules/advisor/test/isolated-model.test.ts +311 -0
  22. package/extensions/modules/advisor/test/model-picker.test.ts +32 -0
  23. package/extensions/modules/advisor/test/module.test.ts +586 -0
  24. package/extensions/modules/advisor/test/watcher.test.ts +478 -0
  25. package/extensions/modules/classifier/configPanel.ts +104 -0
  26. package/extensions/modules/classifier/index.ts +297 -0
  27. package/extensions/modules/classifier/lib/settings.ts +95 -0
  28. package/extensions/modules/classifier/test/classifier.test.ts +475 -0
  29. package/extensions/modules/composer/index.ts +152 -3
  30. package/extensions/modules/composer/lib/footer.ts +119 -0
  31. package/extensions/modules/composer/lib/shapes.ts +265 -26
  32. package/extensions/modules/composer/test/editor.test.ts +1 -1
  33. package/extensions/modules/composer/test/footer.test.ts +96 -0
  34. package/extensions/modules/composer/test/module.test.ts +113 -11
  35. package/extensions/modules/composer/test/screen.test.ts +29 -1
  36. package/extensions/modules/composer/test/shapes.test.ts +224 -8
  37. package/extensions/modules/config/defaultTools.ts +96 -0
  38. package/extensions/modules/config/index.ts +147 -7
  39. package/extensions/modules/config/piSettings.ts +254 -69
  40. package/extensions/modules/config/test/defaultTools.test.ts +122 -0
  41. package/extensions/modules/config/test/menu.test.ts +64 -0
  42. package/extensions/modules/config/test/panel.test.ts +38 -23
  43. package/extensions/modules/config/test/piSettings.test.ts +130 -3
  44. package/extensions/modules/config/test/renderTools.test.ts +71 -0
  45. package/extensions/modules/config/test/tools.test.ts +146 -0
  46. package/extensions/modules/fff/index.ts +2094 -0
  47. package/extensions/modules/fff/lib/query.ts +129 -0
  48. package/extensions/modules/fff/test/index.test.ts +607 -0
  49. package/extensions/modules/fff/test/query.test.ts +71 -0
  50. package/extensions/modules/munin/configPanel.ts +105 -0
  51. package/extensions/modules/munin/index.ts +641 -0
  52. package/extensions/modules/munin/lib/helpers.ts +471 -0
  53. package/extensions/modules/munin/lib/retry.ts +20 -0
  54. package/extensions/modules/munin/lib/sdk.ts +218 -0
  55. package/extensions/modules/munin/test/config.test.ts +168 -0
  56. package/extensions/modules/munin/test/configPanel.test.ts +161 -0
  57. package/extensions/modules/munin/test/extension.test.ts +224 -0
  58. package/extensions/modules/munin/test/helpers.test.ts +523 -0
  59. package/extensions/modules/munin/test/retry.test.ts +145 -0
  60. package/extensions/modules/munin/test/stale-protocol.test.ts +554 -0
  61. package/extensions/modules/plan/configPanel.ts +152 -0
  62. package/extensions/modules/plan/index.ts +917 -0
  63. package/extensions/modules/plan/lib/plan-tools.ts +72 -0
  64. package/extensions/modules/plan/lib/prompt.ts +65 -0
  65. package/extensions/modules/plan/lib/settings.ts +166 -0
  66. package/extensions/modules/plan/lib/shell-gate.ts +200 -0
  67. package/extensions/modules/plan/test/configPanel.test.ts +96 -0
  68. package/extensions/modules/plan/test/harness.ts +133 -0
  69. package/extensions/modules/plan/test/module.test.ts +305 -0
  70. package/extensions/modules/plan/test/settings.test.ts +114 -0
  71. package/extensions/modules/plan/test/shell-gate.test.ts +103 -0
  72. package/extensions/modules/ponytail/index.ts +23 -73
  73. package/extensions/modules/ponytail/lib/config.ts +1 -6
  74. package/extensions/modules/ponytail/test/extension.test.ts +1 -85
  75. package/extensions/modules/repair/configPanel.ts +96 -0
  76. package/extensions/modules/repair/index.ts +414 -0
  77. package/extensions/modules/repair/lib/auto-bg.ts +333 -0
  78. package/extensions/modules/repair/lib/edit-repair.ts +155 -0
  79. package/extensions/modules/repair/lib/editor.ts +251 -0
  80. package/extensions/modules/repair/lib/guards.ts +34 -0
  81. package/extensions/modules/repair/lib/input-repair.ts +324 -0
  82. package/extensions/modules/repair/lib/patch.ts +481 -0
  83. package/extensions/modules/repair/lib/settings.ts +114 -0
  84. package/extensions/modules/repair/test/auto-bg.test.ts +405 -0
  85. package/extensions/modules/repair/test/edit-repair.test.ts +224 -0
  86. package/extensions/modules/repair/test/editor.test.ts +141 -0
  87. package/extensions/modules/repair/test/guards.test.ts +64 -0
  88. package/extensions/modules/repair/test/input-repair.test.ts +231 -0
  89. package/extensions/modules/repair/test/patch.test.ts +563 -0
  90. package/extensions/modules/repair/test/settings.test.ts +167 -0
  91. package/extensions/modules/repair/test/wrapper.test.ts +210 -0
  92. package/extensions/modules/router/commands/commands.ts +4 -0
  93. package/extensions/modules/router/lib/client.ts +61 -0
  94. package/extensions/modules/router/lib/provider.ts +34 -13
  95. package/extensions/modules/router/lib/systemone.ts +152 -0
  96. package/extensions/modules/router/test/unit.test.ts +179 -0
  97. package/extensions/modules/rtk/findFallback.js +68 -0
  98. package/extensions/modules/rtk/index.ts +248 -0
  99. package/extensions/modules/rtk/safe-rewrite.js +74 -0
  100. package/extensions/modules/rtk/test/findFallback.test.js +66 -0
  101. package/extensions/modules/rtk/test/index.test.js +131 -0
  102. package/extensions/modules/rtk/test/safe-rewrite.test.js +96 -0
  103. package/extensions/modules/rtk/version-gate.js +34 -0
  104. package/extensions/modules/serena/index.ts +629 -0
  105. package/extensions/modules/serena/lib/detect.ts +73 -0
  106. package/extensions/modules/serena/lib/env.ts +76 -0
  107. package/extensions/modules/serena/lib/guidance.ts +26 -0
  108. package/extensions/modules/serena/lib/normalize.ts +27 -0
  109. package/extensions/modules/serena/lib/symbol-key.ts +20 -0
  110. package/extensions/modules/serena/lib/truncate.ts +20 -0
  111. package/extensions/modules/serena/test/env.test.ts +122 -0
  112. package/extensions/modules/serena/test/index.test.ts +347 -0
  113. package/extensions/modules/serena/test/worker.test.ts +562 -0
  114. package/extensions/modules/serena/worker.ts +858 -0
  115. package/extensions/modules/steering/configPanel.ts +122 -0
  116. package/extensions/modules/steering/index.ts +616 -0
  117. package/extensions/modules/steering/lib/anchor.ts +175 -0
  118. package/extensions/modules/steering/lib/errors.ts +253 -0
  119. package/extensions/modules/steering/lib/family.ts +33 -0
  120. package/extensions/modules/steering/lib/guidance.ts +172 -0
  121. package/extensions/modules/steering/lib/history.ts +170 -0
  122. package/extensions/modules/steering/lib/settings.ts +127 -0
  123. package/extensions/modules/steering/test/anchor-regressions.test.ts +93 -0
  124. package/extensions/modules/steering/test/anchor-wiring.test.ts +99 -0
  125. package/extensions/modules/steering/test/anchor.test.ts +160 -0
  126. package/extensions/modules/steering/test/cache-stats.test.ts +43 -0
  127. package/extensions/modules/steering/test/errors.test.ts +309 -0
  128. package/extensions/modules/steering/test/family.test.ts +43 -0
  129. package/extensions/modules/steering/test/guidance.test.ts +357 -0
  130. package/extensions/modules/steering/test/harness.ts +93 -0
  131. package/extensions/modules/steering/test/history.test.ts +118 -0
  132. package/extensions/modules/steering/test/settings.test.ts +182 -0
  133. package/extensions/modules/steering/test/status.test.ts +71 -0
  134. package/extensions/modules/steering/test/toolCall.test.ts +99 -0
  135. package/extensions/modules/subagent/agents/planner.md +14 -0
  136. package/extensions/modules/subagent/agents/reviewer.md +42 -0
  137. package/extensions/modules/subagent/agents/scout.md +47 -0
  138. package/extensions/modules/subagent/agents/tester.md +12 -0
  139. package/extensions/modules/subagent/agents/worker.md +18 -0
  140. package/extensions/modules/subagent/configPanel.ts +219 -0
  141. package/extensions/modules/subagent/index.ts +2451 -0
  142. package/extensions/modules/subagent/lib/agents.ts +408 -0
  143. package/extensions/modules/subagent/lib/background.ts +383 -0
  144. package/extensions/modules/subagent/lib/herdr.ts +1019 -0
  145. package/extensions/modules/subagent/lib/history.ts +126 -0
  146. package/extensions/modules/subagent/lib/model.ts +156 -0
  147. package/extensions/modules/subagent/lib/render.ts +335 -0
  148. package/extensions/modules/subagent/lib/result.ts +110 -0
  149. package/extensions/modules/subagent/lib/roles.ts +296 -0
  150. package/extensions/modules/subagent/lib/routing.ts +223 -0
  151. package/extensions/modules/subagent/lib/runner.ts +559 -0
  152. package/extensions/modules/subagent/lib/schema.ts +21 -0
  153. package/extensions/modules/subagent/lib/security.ts +752 -0
  154. package/extensions/modules/subagent/lib/settings.ts +159 -0
  155. package/extensions/modules/subagent/lib/thread-viewer.ts +319 -0
  156. package/extensions/modules/subagent/lib/threads.ts +135 -0
  157. package/extensions/modules/subagent/lib/types.ts +18 -0
  158. package/extensions/modules/subagent/lib/widget.ts +475 -0
  159. package/extensions/modules/subagent/test/configPanel.test.ts +132 -0
  160. package/extensions/modules/subagent/test/herdr-advisor.test.ts +40 -0
  161. package/extensions/modules/subagent/test/routing.test.ts +350 -0
  162. package/extensions/modules/subagent/test/widget.test.ts +208 -0
  163. package/extensions/modules/usage/index.ts +59 -16
  164. package/extensions/modules/usage/test/genrate.test.ts +70 -0
  165. package/extensions/modules/usage/test/parsers.test.ts +13 -0
  166. package/extensions/modules/ux/UPSTREAM +24 -0
  167. package/extensions/modules/ux/index.ts +393 -0
  168. package/extensions/modules/ux/lib/audit.ts +562 -0
  169. package/extensions/modules/ux/lib/config.ts +136 -0
  170. package/extensions/modules/ux/lib/instructions.ts +77 -0
  171. package/extensions/modules/ux/test/audit.test.ts +756 -0
  172. package/extensions/modules/ux/test/extension.test.ts +394 -0
  173. package/extensions/modules/ux/test/instructions.test.ts +19 -0
  174. package/extensions/modules/web/configPanel.ts +193 -0
  175. package/extensions/modules/web/index.ts +978 -0
  176. package/extensions/modules/web/lib/agy.ts +209 -0
  177. package/extensions/modules/web/lib/brave.ts +42 -0
  178. package/extensions/modules/web/lib/cdp.ts +686 -0
  179. package/extensions/modules/web/lib/chatapi.ts +101 -0
  180. package/extensions/modules/web/lib/chatgpt.ts +796 -0
  181. package/extensions/modules/web/lib/chrome.ts +328 -0
  182. package/extensions/modules/web/lib/config.ts +136 -0
  183. package/extensions/modules/web/lib/content.ts +99 -0
  184. package/extensions/modules/web/lib/crawl4ai.ts +172 -0
  185. package/extensions/modules/web/lib/extract.ts +235 -0
  186. package/extensions/modules/web/lib/firecrawl.ts +56 -0
  187. package/extensions/modules/web/lib/format.ts +197 -0
  188. package/extensions/modules/web/lib/gemini-auth.ts +286 -0
  189. package/extensions/modules/web/lib/gemini-dr.ts +338 -0
  190. package/extensions/modules/web/lib/gemini.ts +551 -0
  191. package/extensions/modules/web/lib/imageapi.ts +559 -0
  192. package/extensions/modules/web/lib/retry.ts +71 -0
  193. package/extensions/modules/web/lib/search.ts +237 -0
  194. package/extensions/modules/web/lib/searxng.ts +69 -0
  195. package/extensions/modules/web/lib/settings.ts +148 -0
  196. package/extensions/modules/web/scripts/cdp-smoke.ts +77 -0
  197. package/extensions/modules/web/scripts/gemini-smoke.ts +107 -0
  198. package/extensions/modules/web/test/agy.test.ts +383 -0
  199. package/extensions/modules/web/test/cdp.test.ts +717 -0
  200. package/extensions/modules/web/test/chat.test.ts +171 -0
  201. package/extensions/modules/web/test/chatgpt.test.ts +633 -0
  202. package/extensions/modules/web/test/chrome.test.ts +282 -0
  203. package/extensions/modules/web/test/config.test.ts +218 -0
  204. package/extensions/modules/web/test/configPanel.test.ts +132 -0
  205. package/extensions/modules/web/test/crawl.test.ts +134 -0
  206. package/extensions/modules/web/test/crawl4ai.test.ts +105 -0
  207. package/extensions/modules/web/test/extension.test.ts +118 -0
  208. package/extensions/modules/web/test/extract.test.ts +436 -0
  209. package/extensions/modules/web/test/fixtures/dr-confirm.bin +12 -0
  210. package/extensions/modules/web/test/fixtures/dr-plan.bin +20 -0
  211. package/extensions/modules/web/test/fixtures/interaction.html +31 -0
  212. package/extensions/modules/web/test/format.test.ts +230 -0
  213. package/extensions/modules/web/test/gemini-auth.test.ts +465 -0
  214. package/extensions/modules/web/test/gemini-dr.test.ts +249 -0
  215. package/extensions/modules/web/test/gemini.test.ts +472 -0
  216. package/extensions/modules/web/test/hook.test.ts +101 -0
  217. package/extensions/modules/web/test/image.test.ts +1089 -0
  218. package/extensions/modules/web/test/retry.test.ts +119 -0
  219. package/extensions/modules/web/test/screenshot.test.ts +109 -0
  220. package/extensions/modules/web/test/search.test.ts +210 -0
  221. package/extensions/modules/web/test/settings.test.ts +165 -0
  222. package/extensions/modules/web/test/skill.test.ts +72 -0
  223. package/extensions/modules/web/types.d.ts +3 -0
  224. package/extensions/modules/web/vendor/package.json +1 -0
  225. package/extensions/modules/web/vendor/readability/LICENSE.md +13 -0
  226. package/extensions/modules/web/vendor/readability/Readability-readerable.js +123 -0
  227. package/extensions/modules/web/vendor/readability/Readability.js +2787 -0
  228. package/extensions/modules/web/vendor/readability/index.d.ts +64 -0
  229. package/extensions/modules/web/vendor/readability/index.js +9 -0
  230. package/extensions/modules/web/vendor/turndown/LICENSE +21 -0
  231. package/extensions/modules/web/vendor/turndown/turndown.cjs.js +784 -0
  232. package/extensions/modules/web/vendor/turndown-plugin-gfm/LICENSE +21 -0
  233. package/extensions/modules/web/vendor/turndown-plugin-gfm/turndown-plugin-gfm.cjs.js +163 -0
  234. package/extensions/modules/zai/configPanel.ts +151 -0
  235. package/extensions/modules/zai/index.ts +186 -0
  236. package/extensions/modules/zai/lib/anthropic.ts +159 -0
  237. package/extensions/modules/zai/lib/settings.ts +198 -0
  238. package/extensions/modules/zai/lib/signing.ts +718 -0
  239. package/extensions/modules/zai/lib/throttle.ts +198 -0
  240. package/extensions/modules/zai/test/anthropic.test.ts +132 -0
  241. package/extensions/modules/zai/test/configPanel.test.ts +207 -0
  242. package/extensions/modules/zai/test/extension.test.ts +249 -0
  243. package/extensions/modules/zai/test/settings.test.ts +183 -0
  244. package/extensions/modules/zai/test/signing-wiring.test.ts +108 -0
  245. package/extensions/modules/zai/test/signing.test.ts +345 -0
  246. package/extensions/modules/zai/test/throttle.test.ts +329 -0
  247. package/package.json +19 -4
  248. package/scripts/validate-themes.mjs +75 -0
  249. package/skills/munin/SKILL.md +117 -0
  250. package/skills/ux-capture/SKILL.md +202 -0
  251. package/skills/ux-design/SKILL.md +279 -0
  252. package/skills/ux-presets/SKILL.md +484 -0
  253. package/skills/ux-routing/SKILL.md +46 -0
  254. package/skills/web/SKILL.md +153 -0
  255. package/themes/alabaster.json +93 -0
  256. package/themes/amethyst.json +96 -0
  257. package/themes/anthracite.json +93 -0
  258. package/themes/basalt.json +91 -0
  259. package/themes/birch.json +95 -0
  260. package/themes/catppuccin-mocha.json +91 -0
  261. package/themes/dark-abyss.json +91 -0
  262. package/themes/dark-arctic.json +104 -0
  263. package/themes/dark-aurora.json +95 -0
  264. package/themes/dark-catppuccin.json +107 -0
  265. package/themes/dark-cavern.json +91 -0
  266. package/themes/dark-celestial.json +106 -0
  267. package/themes/dark-copper.json +95 -0
  268. package/themes/dark-cosmos.json +90 -0
  269. package/themes/dark-cyberpunk.json +102 -0
  270. package/themes/dark-dracula.json +98 -0
  271. package/themes/dark-eclipse.json +91 -0
  272. package/themes/dark-ember.json +95 -0
  273. package/themes/dark-equinox.json +90 -0
  274. package/themes/dark-forest.json +96 -0
  275. package/themes/dark-github.json +105 -0
  276. package/themes/dark-gruvbox.json +112 -0
  277. package/themes/dark-lavender.json +95 -0
  278. package/themes/dark-lunar.json +89 -0
  279. package/themes/dark-midnight.json +95 -0
  280. package/themes/dark-monochrome.json +94 -0
  281. package/themes/dark-monokai.json +98 -0
  282. package/themes/dark-nebula.json +90 -0
  283. package/themes/dark-neon-noir.json +100 -0
  284. package/themes/dark-nord.json +98 -0
  285. package/themes/dark-ocean.json +101 -0
  286. package/themes/dark-one.json +100 -0
  287. package/themes/dark-poimandres.json +115 -0
  288. package/themes/dark-rainforest.json +91 -0
  289. package/themes/dark-reef.json +91 -0
  290. package/themes/dark-retro.json +92 -0
  291. package/themes/dark-rose-pine.json +96 -0
  292. package/themes/dark-sakura.json +95 -0
  293. package/themes/dark-slate.json +95 -0
  294. package/themes/dark-solarized.json +97 -0
  295. package/themes/dark-solstice.json +90 -0
  296. package/themes/dark-starfall.json +91 -0
  297. package/themes/dark-sunset.json +99 -0
  298. package/themes/dark-swamp.json +90 -0
  299. package/themes/dark-synthwave.json +103 -0
  300. package/themes/dark-taiga.json +91 -0
  301. package/themes/dark-terminal.json +95 -0
  302. package/themes/dark-tokyo-night.json +101 -0
  303. package/themes/dark-tundra.json +91 -0
  304. package/themes/dark-twilight.json +91 -0
  305. package/themes/dark-volcanic.json +91 -0
  306. package/themes/dark.json +80 -0
  307. package/themes/graphite.json +92 -0
  308. package/themes/light-arctic.json +107 -0
  309. package/themes/light-aurora-day.json +91 -0
  310. package/themes/light-canyon.json +91 -0
  311. package/themes/light-catppuccin.json +106 -0
  312. package/themes/light-cirrus.json +90 -0
  313. package/themes/light-coral.json +95 -0
  314. package/themes/light-cyberpunk.json +96 -0
  315. package/themes/light-dawn.json +90 -0
  316. package/themes/light-dunes.json +91 -0
  317. package/themes/light-eucalyptus.json +95 -0
  318. package/themes/light-forest.json +100 -0
  319. package/themes/light-frost.json +95 -0
  320. package/themes/light-github.json +115 -0
  321. package/themes/light-glacier.json +91 -0
  322. package/themes/light-gruvbox.json +108 -0
  323. package/themes/light-haze.json +90 -0
  324. package/themes/light-honeycomb.json +95 -0
  325. package/themes/light-lagoon.json +91 -0
  326. package/themes/light-lavender.json +95 -0
  327. package/themes/light-meadow.json +91 -0
  328. package/themes/light-mint.json +95 -0
  329. package/themes/light-monochrome.json +101 -0
  330. package/themes/light-ocean.json +99 -0
  331. package/themes/light-one.json +99 -0
  332. package/themes/light-opal.json +91 -0
  333. package/themes/light-orchard.json +91 -0
  334. package/themes/light-paper.json +95 -0
  335. package/themes/light-poimandres.json +115 -0
  336. package/themes/light-prism.json +90 -0
  337. package/themes/light-retro.json +98 -0
  338. package/themes/light-sand.json +95 -0
  339. package/themes/light-savanna.json +91 -0
  340. package/themes/light-solarized.json +102 -0
  341. package/themes/light-soleil.json +90 -0
  342. package/themes/light-sunset.json +99 -0
  343. package/themes/light-synthwave.json +98 -0
  344. package/themes/light-tokyo-night.json +111 -0
  345. package/themes/light-wetland.json +91 -0
  346. package/themes/light-zenith.json +89 -0
  347. package/themes/light.json +80 -0
  348. package/themes/limestone.json +94 -0
  349. package/themes/mahogany.json +97 -0
  350. package/themes/marble.json +93 -0
  351. package/themes/mirage.json +79 -0
  352. package/themes/obsidian.json +91 -0
  353. package/themes/onyx.json +91 -0
  354. package/themes/pearl.json +93 -0
  355. package/themes/porcelain.json +91 -0
  356. package/themes/quartz.json +96 -0
  357. package/themes/sandstone.json +95 -0
  358. package/themes/titanium.json +90 -0
@@ -0,0 +1,328 @@
1
+ // ponytail: vendored from @bacnh85/pi-web 0.17.8
2
+ // Local headless Chrome capture — for localhost/private/file:// URLs the
3
+ // remote Crawl4AI daemon cannot reach (its SSRF protection blocks them).
4
+ // Zero dependencies: drives the locally installed Chrome/Chromium binary.
5
+
6
+ import { spawn } from "node:child_process";
7
+ import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import path from "node:path";
10
+
11
+ export interface LocalCapture {
12
+ base64: string;
13
+ mime: string;
14
+ size: number;
15
+ }
16
+
17
+ const CHROME_TIMEOUT_MS = 30_000;
18
+ // ponytail: tall-window approximates full page (CLI has no fullPage flag) —
19
+ // Playwright tier if this proves insufficient.
20
+ export const FULL_PAGE_HEIGHT = 8000;
21
+
22
+ /** Locate a locally installed Chrome/Chromium (or Edge as a Windows fallback). */
23
+ export function findChromeBinary(): string | null {
24
+ const candidates: string[] = [];
25
+ if (process.env.CHROME_PATH) candidates.push(process.env.CHROME_PATH);
26
+ switch (process.platform) {
27
+ case "darwin": {
28
+ const apps = ["/Applications", path.join(process.env.HOME ?? "", "Applications")];
29
+ for (const app of apps) {
30
+ candidates.push(
31
+ path.join(app, "Google Chrome.app/Contents/MacOS/Google Chrome"),
32
+ path.join(app, "Chromium.app/Contents/MacOS/Chromium"),
33
+ );
34
+ }
35
+ break;
36
+ }
37
+ case "win32": {
38
+ const roots = [
39
+ "C:\\Program Files",
40
+ "C:\\Program Files (x86)",
41
+ process.env.LOCALAPPDATA ?? "",
42
+ ].filter(Boolean);
43
+ for (const root of roots) {
44
+ candidates.push(
45
+ path.join(root, "Google\\Chrome\\Application\\chrome.exe"),
46
+ path.join(root, "Microsoft\\Edge\\Application\\msedge.exe"),
47
+ );
48
+ }
49
+ break;
50
+ }
51
+ default: {
52
+ const dirs = [
53
+ ...(process.env.PATH ?? "").split(":").filter(Boolean),
54
+ "/usr/bin",
55
+ "/usr/local/bin",
56
+ "/snap/bin",
57
+ ];
58
+ for (const dir of dirs) {
59
+ candidates.push(
60
+ path.join(dir, "google-chrome"),
61
+ path.join(dir, "google-chrome-stable"),
62
+ path.join(dir, "chromium"),
63
+ path.join(dir, "chromium-browser"),
64
+ );
65
+ }
66
+ }
67
+ }
68
+ return candidates.find((p) => existsSync(p)) ?? null;
69
+ }
70
+
71
+ /** True for URLs a remote daemon provably cannot render: file://, localhost, loopback, private ranges. */
72
+ export function isLocalUrl(raw: string): boolean {
73
+ let u: URL;
74
+ try {
75
+ u = new URL(raw);
76
+ } catch {
77
+ return false;
78
+ }
79
+ if (u.protocol === "file:") return true;
80
+ const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, "");
81
+ if (host === "localhost" || host.endsWith(".localhost")) return true;
82
+ if (host === "::1") return true;
83
+ if (host.includes(":")) {
84
+ // IPv4-mapped IPv6 is its embedded IPv4 — loopback/link-local/private
85
+ // mapped forms must not slip past the SSRF guard. new URL canonicalizes
86
+ // ::ffff:127.0.0.1 to hex form (::ffff:7f00:1), so accept both shapes.
87
+ const tail = host.startsWith("::ffff:") ? host.slice(7) : null;
88
+ if (tail) {
89
+ const dotted = tail.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
90
+ if (dotted) return isLocalUrl(`http://${dotted[1]}/`);
91
+ const hex = tail.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
92
+ if (hex) {
93
+ const bits = (parseInt(hex[1], 16) << 16) | parseInt(hex[2], 16);
94
+ return isLocalUrl(`http://${(bits >>> 24) & 0xff}.${(bits >>> 16) & 0xff}.${(bits >>> 8) & 0xff}.${bits & 0xff}/`);
95
+ }
96
+ }
97
+ // IPv6 ULA fc00::/7 and link-local fe80::/10 are private too.
98
+ if (/^f[cd]/.test(host) || /^fe[89ab]/.test(host)) return true;
99
+ return false;
100
+ }
101
+ const m = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
102
+ if (m) {
103
+ const a = Number(m[1]);
104
+ const b = Number(m[2]);
105
+ if (a === 127 || a === 10 || a === 0) return true;
106
+ if (a === 172 && b >= 16 && b <= 31) return true; // 172.16/12
107
+ if (a === 192 && b === 168) return true;
108
+ if (a === 169 && b === 254) return true; // link-local
109
+ }
110
+ return false;
111
+ }
112
+
113
+ /** Daemon SSRF/URL-blocked failures that a local-Chrome retry can rescue. */
114
+ export function isSsrfBlocked(err: unknown): boolean {
115
+ const msg = err instanceof Error ? err.message : String(err);
116
+ return /SSRF|URL blocked/i.test(msg);
117
+ }
118
+
119
+ /** Pick the capture engine: local Chrome or the remote Crawl4AI daemon. */
120
+ export function resolveEngine(engine: string | undefined, url: string): "local" | "daemon" {
121
+ if (engine === "local" || engine === "daemon") return engine;
122
+ return isLocalUrl(url) ? "local" : "daemon";
123
+ }
124
+
125
+ export interface ScreenshotArgsOpts {
126
+ chromePath: string;
127
+ outPath: string;
128
+ userDataDir: string;
129
+ url: string;
130
+ width: number;
131
+ height: number;
132
+ fullPage?: boolean;
133
+ reducedMotion?: boolean;
134
+ waitForSec?: number;
135
+ }
136
+
137
+ export function buildScreenshotArgs(opts: ScreenshotArgsOpts): string[] {
138
+ const height = opts.fullPage ? FULL_PAGE_HEIGHT : opts.height;
139
+ return [
140
+ opts.chromePath,
141
+ "--headless",
142
+ "--no-first-run",
143
+ "--disable-gpu",
144
+ `--user-data-dir=${opts.userDataDir}`,
145
+ "--hide-scrollbars",
146
+ `--window-size=${opts.width},${height}`,
147
+ ...(opts.reducedMotion ? ["--force-prefers-reduced-motion"] : []),
148
+ ...(opts.waitForSec ? [`--virtual-time-budget=${Math.round(opts.waitForSec * 1000)}`] : []),
149
+ `--screenshot=${opts.outPath}`,
150
+ opts.url,
151
+ ];
152
+ }
153
+
154
+ export function buildPdfArgs(opts: {
155
+ chromePath: string;
156
+ outPath: string;
157
+ userDataDir: string;
158
+ url: string;
159
+ reducedMotion?: boolean;
160
+ }): string[] {
161
+ return [
162
+ opts.chromePath,
163
+ "--headless",
164
+ "--no-first-run",
165
+ "--disable-gpu",
166
+ `--user-data-dir=${opts.userDataDir}`,
167
+ "--no-pdf-header-footer",
168
+ ...(opts.reducedMotion ? ["--force-prefers-reduced-motion"] : []),
169
+ `--print-to-pdf=${opts.outPath}`,
170
+ opts.url,
171
+ ];
172
+ }
173
+
174
+ function runChrome(
175
+ args: string[],
176
+ outPath: string,
177
+ signal?: AbortSignal,
178
+ timeoutMs: number = CHROME_TIMEOUT_MS,
179
+ ): Promise<void> {
180
+ return new Promise((resolve, reject) => {
181
+ const child = spawn(args[0], args.slice(1), { stdio: ["ignore", "ignore", "pipe"] });
182
+ let stderr = "";
183
+ let settled = false;
184
+ let lastSize = -1;
185
+ let stablePolls = 0;
186
+ let fileTimer: ReturnType<typeof setInterval> | undefined;
187
+ const finish = (err?: Error) => {
188
+ if (settled) return;
189
+ settled = true;
190
+ clearTimeout(killTimer);
191
+ clearInterval(fileTimer);
192
+ signal?.removeEventListener("abort", onAbort);
193
+ if (err) reject(err);
194
+ else resolve();
195
+ };
196
+ const onAbort = () => {
197
+ child.kill("SIGKILL");
198
+ finish(new Error("Local capture aborted"));
199
+ };
200
+ const killTimer = setTimeout(() => {
201
+ child.kill("SIGKILL");
202
+ // Always a failure: a complete capture is caught earlier by the
203
+ // size-stability poll, so surviving to the timeout means the output
204
+ // never settled (or never appeared) — a file here may be mid-write.
205
+ finish(new Error(`Local capture timed out after ${timeoutMs / 1000}s`));
206
+ }, timeoutMs);
207
+ signal?.addEventListener("abort", onAbort, { once: true });
208
+ child.stderr?.on("data", (d: Buffer) => {
209
+ stderr += d.toString();
210
+ });
211
+ child.on("error", (err) => finish(err));
212
+ child.on("close", (code) => {
213
+ if (existsSync(outPath)) finish();
214
+ else finish(new Error(`Chrome exited with code ${code}: ${stderr.slice(-400)}`));
215
+ });
216
+ // Resolve as soon as the capture file is written and stable, then kill —
217
+ // don't require a clean Chrome exit (some versions hang after writing,
218
+ // e.g. fresh --user-data-dir on macOS).
219
+ fileTimer = setInterval(() => {
220
+ if (!existsSync(outPath)) return;
221
+ const size = statSync(outPath).size;
222
+ if (size > 0 && size === lastSize) {
223
+ if (++stablePolls >= 2) {
224
+ child.kill("SIGKILL");
225
+ finish();
226
+ }
227
+ } else {
228
+ stablePolls = 0;
229
+ lastSize = size;
230
+ }
231
+ }, 250);
232
+ });
233
+ }
234
+
235
+ async function readCapture(outPath: string, mime: string): Promise<LocalCapture> {
236
+ const buf = readFileSync(outPath);
237
+ return { base64: buf.toString("base64"), mime, size: buf.length };
238
+ }
239
+
240
+ export function assertCaptureUrl(url: string): void {
241
+ // Trust boundary: the URL becomes a spawn argv element — a scheme check
242
+ // keeps strings like "--proxy-server=http://evil" from parsing as switches.
243
+ if (!/^https?:\/\//i.test(url) && !/^file:\/\//i.test(url)) {
244
+ throw new Error(`Invalid capture URL (${url.slice(0, 80)}): must be http://, https://, or file://`);
245
+ }
246
+ }
247
+
248
+ export async function captureScreenshot(opts: {
249
+ url: string;
250
+ width?: number;
251
+ height?: number;
252
+ fullPage?: boolean;
253
+ reducedMotion?: boolean;
254
+ waitForSec?: number;
255
+ signal?: AbortSignal;
256
+ timeoutMs?: number;
257
+ }): Promise<LocalCapture> {
258
+ assertCaptureUrl(opts.url);
259
+ const chromePath = findChromeBinary();
260
+ if (!chromePath) {
261
+ throw new Error("No local Chrome/Chromium found — install Chrome or set CHROME_PATH.");
262
+ }
263
+ const dir = mkdtempSync(path.join(tmpdir(), "pi-web-capture-"));
264
+ try {
265
+ const outPath = path.join(dir, "screenshot.png");
266
+ await runChrome(
267
+ buildScreenshotArgs({
268
+ chromePath,
269
+ outPath,
270
+ userDataDir: path.join(dir, "profile"),
271
+ url: opts.url,
272
+ width: opts.width ?? 1280,
273
+ height: opts.height ?? 800,
274
+ fullPage: opts.fullPage,
275
+ reducedMotion: opts.reducedMotion,
276
+ waitForSec: opts.waitForSec,
277
+ }),
278
+ outPath,
279
+ opts.signal,
280
+ opts.timeoutMs,
281
+ );
282
+ return await readCapture(outPath, "image/png");
283
+ } finally {
284
+ // SIGKILLed Chrome may still be writing profile files — retry briefly and
285
+ // never fail the capture over leftover temp state (OS cleans $TMPDIR).
286
+ try {
287
+ rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
288
+ } catch {
289
+ // ponytail: best-effort cleanup
290
+ }
291
+ }
292
+ }
293
+
294
+ export async function capturePdf(opts: {
295
+ url: string;
296
+ reducedMotion?: boolean;
297
+ signal?: AbortSignal;
298
+ timeoutMs?: number;
299
+ }): Promise<LocalCapture> {
300
+ assertCaptureUrl(opts.url);
301
+ const chromePath = findChromeBinary();
302
+ if (!chromePath) {
303
+ throw new Error("No local Chrome/Chromium found — install Chrome or set CHROME_PATH.");
304
+ }
305
+ const dir = mkdtempSync(path.join(tmpdir(), "pi-web-capture-"));
306
+ try {
307
+ const outPath = path.join(dir, "page.pdf");
308
+ await runChrome(
309
+ buildPdfArgs({
310
+ chromePath,
311
+ outPath,
312
+ userDataDir: path.join(dir, "profile"),
313
+ url: opts.url,
314
+ reducedMotion: opts.reducedMotion,
315
+ }),
316
+ outPath,
317
+ opts.signal,
318
+ opts.timeoutMs,
319
+ );
320
+ return await readCapture(outPath, "application/pdf");
321
+ } finally {
322
+ try {
323
+ rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
324
+ } catch {
325
+ // ponytail: best-effort cleanup
326
+ }
327
+ }
328
+ }
@@ -0,0 +1,136 @@
1
+ // ponytail: vendored from @bacnh85/pi-web 0.17.8
2
+ // Local delta: the dotenv file-walking (findEnvValue's cwd/agent-dir .env*
3
+ // parsing) is DELETED — ceulen's bundle env.ts already ingests agent-dir +
4
+ // trusted-cwd .env* into process.env, so process.env IS the full env chain.
5
+ // findEnvValue keeps its name/shape but resolves env → settings.json (`web`
6
+ // section: trusted project > global, see lib/settings.ts) → unset.
7
+
8
+ import { lookupVar } from "./settings";
9
+
10
+ // ---------------------------------------------------------------------------
11
+ // Constants
12
+ // ---------------------------------------------------------------------------
13
+
14
+ export const HOSTED_FIRECRAWL_BASE_URL = "https://api.firecrawl.dev/v2";
15
+ export const DEFAULT_SEARXNG_BASE_URL = "http://127.0.0.1:8888";
16
+ export const DEFAULT_CRAWL4AI_API_URL = "http://127.0.0.1:11235";
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // Environment + settings resolution
20
+ // ---------------------------------------------------------------------------
21
+
22
+ export function findEnvValue(name: string, cwd = process.cwd(), includeCwd = true): { value?: string; source: string } {
23
+ return lookupVar(name, cwd, includeCwd);
24
+ }
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // Context helpers
28
+ // ---------------------------------------------------------------------------
29
+
30
+ export function cwdFromContext(ctx: Record<string, unknown>): string {
31
+ return typeof ctx?.cwd === "string" && (ctx.cwd as string) ? (ctx.cwd as string) : process.cwd();
32
+ }
33
+
34
+ export function includeProjectEnv(ctx: Record<string, unknown>): boolean {
35
+ return typeof ctx?.isProjectTrusted === "function" ? (ctx.isProjectTrusted as () => boolean)() : false;
36
+ }
37
+
38
+ // ---------------------------------------------------------------------------
39
+ // URL helpers
40
+ // ---------------------------------------------------------------------------
41
+
42
+ function normalizeHttpUrl(raw: string | undefined, fallback: string): string {
43
+ let value = (raw || fallback).trim();
44
+ if (!/^https?:\/\//i.test(value)) {
45
+ value = /^(localhost|127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/i.test(value)
46
+ ? `http://${value}`
47
+ : `https://${value}`;
48
+ }
49
+ return value.replace(/\/+$/, "");
50
+ }
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // SearXNG config
54
+ // ---------------------------------------------------------------------------
55
+
56
+ export interface SearxngConfig {
57
+ baseUrl: string;
58
+ source: string;
59
+ }
60
+
61
+ export function normalizeSearxngBaseUrl(raw?: string): string {
62
+ return normalizeHttpUrl(raw, DEFAULT_SEARXNG_BASE_URL);
63
+ }
64
+
65
+ export function loadSearxngConfig(params: Record<string, unknown> = {}, cwd = process.cwd(), includeCwdEnv = false): SearxngConfig {
66
+ const baseUrlEnv = findEnvValue("SEARXNG_BASE_URL", cwd, includeCwdEnv);
67
+ const explicitBaseUrl = params.searxng_base_url as string | undefined;
68
+ const baseUrl = normalizeSearxngBaseUrl(explicitBaseUrl || (params.base_url as string) || baseUrlEnv.value);
69
+ const source = explicitBaseUrl || params.base_url ? "tool parameter" : baseUrlEnv.source || "default local";
70
+ return { baseUrl, source };
71
+ }
72
+
73
+ // ---------------------------------------------------------------------------
74
+ // Crawl4AI config
75
+ // ---------------------------------------------------------------------------
76
+
77
+ export interface Crawl4aiConfig {
78
+ baseUrl: string;
79
+ apiToken: string;
80
+ timeoutMs: number;
81
+ }
82
+
83
+ export function normalizeCrawl4aiApiUrl(raw?: string): string {
84
+ return normalizeHttpUrl(raw, DEFAULT_CRAWL4AI_API_URL);
85
+ }
86
+
87
+ export function loadCrawl4aiConfig(params: Record<string, unknown> = {}, cwd = process.cwd(), includeCwdEnv = false): Crawl4aiConfig {
88
+ const apiUrlLookup = findEnvValue("CRAWL4AI_API_URL", cwd, includeCwdEnv);
89
+ const apiTokenLookup = findEnvValue("CRAWL4AI_API_TOKEN", cwd, includeCwdEnv);
90
+ const explicitApiUrl = params.crawl4ai_api_url as string | undefined;
91
+ const explicitApiToken = params.crawl4ai_api_token as string | undefined;
92
+ const baseUrl = normalizeCrawl4aiApiUrl(explicitApiUrl || apiUrlLookup.value);
93
+ // Security: only use env-var API token when URL is default or also from env var.
94
+ // If the URL is overridden via params but no explicit token was provided, don't send
95
+ // the env-var token to a potentially attacker-controlled URL.
96
+ const apiToken = explicitApiToken || (explicitApiUrl ? "" : apiTokenLookup.value) || "";
97
+ const timeoutValue = (params.timeout_ms as number) || findEnvValue("CRAWL4AI_API_TIMEOUT_MS", cwd, includeCwdEnv).value;
98
+ const timeoutMs = timeoutValue ? Number.parseInt(String(timeoutValue), 10) : 60000;
99
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1000) throw new Error("CRAWL4AI_API_TIMEOUT_MS/timeout_ms must be an integer >= 1000.");
100
+ return { baseUrl, apiToken, timeoutMs };
101
+ }
102
+
103
+ // ---------------------------------------------------------------------------
104
+ // Firecrawl config
105
+ // ---------------------------------------------------------------------------
106
+
107
+ export interface FirecrawlConfig {
108
+ baseUrl: string;
109
+ apiKey: string;
110
+ isHosted: boolean;
111
+ timeoutMs: number;
112
+ }
113
+
114
+ export function normalizeFirecrawlBaseUrl(raw?: string): string {
115
+ let value = normalizeHttpUrl(raw, HOSTED_FIRECRAWL_BASE_URL);
116
+ if (!/\/v\d+$/i.test(value)) value += "/v2";
117
+ return value;
118
+ }
119
+
120
+ export function loadFirecrawlConfig(params: Record<string, unknown> = {}, cwd = process.cwd(), includeCwdEnv = false): FirecrawlConfig {
121
+ const apiUrlLookup = findEnvValue("FIRECRAWL_API_URL", cwd, includeCwdEnv);
122
+ const apiKeyLookup = findEnvValue("FIRECRAWL_API_KEY", cwd, includeCwdEnv);
123
+ const explicitApiKey = (params.firecrawl_api_key as string) || (params.api_key as string);
124
+ const apiUrl = (params.firecrawl_api_url as string) || (params.api_url as string) || apiUrlLookup.value;
125
+ // Security: only use env-var API key when URL is default or also from env var.
126
+ // If the URL is overridden via params but no explicit key was provided, don't send
127
+ // the env-var key to a potentially attacker-controlled URL.
128
+ const apiKey = explicitApiKey || (apiUrl !== apiUrlLookup.value && apiUrl ? "" : apiKeyLookup.value) || "";
129
+ const timeoutValue = (params.timeout_ms as number) || findEnvValue("FIRECRAWL_TIMEOUT_MS", cwd, includeCwdEnv).value;
130
+ const baseUrl = normalizeFirecrawlBaseUrl(apiUrl);
131
+ const isHosted = !apiUrl || baseUrl.startsWith(HOSTED_FIRECRAWL_BASE_URL);
132
+ const timeoutMs = timeoutValue ? Number.parseInt(String(timeoutValue), 10) : 60000;
133
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1000) throw new Error("FIRECRAWL_TIMEOUT_MS/timeout_ms must be an integer >= 1000.");
134
+ if (isHosted && !apiKey) throw new Error("FIRECRAWL_API_KEY is required for hosted Firecrawl.");
135
+ return { baseUrl, apiKey, isHosted, timeoutMs };
136
+ }
@@ -0,0 +1,99 @@
1
+ // ponytail: vendored from @bacnh85/pi-web 0.17.8
2
+ // Readable content extraction using JSDOM + Readability + Turndown.
3
+
4
+ import { createRequire } from "node:module";
5
+ import { signalWithTimeout } from "./retry";
6
+
7
+ const require = createRequire(import.meta.url);
8
+
9
+ export interface ReadableContentDeps {
10
+ Readability: any;
11
+ JSDOM: any;
12
+ TurndownService: any;
13
+ gfm: unknown;
14
+ }
15
+
16
+ export function loadReadableContentDependencies(): ReadableContentDeps {
17
+ try {
18
+ return {
19
+ // ceulen: vendored in ./vendor/ (see AGENTS.md) — only jsdom +
20
+ // gemini-reverse remain real dependencies (un-vendorable engines).
21
+ Readability: require("../vendor/readability/index.js").Readability,
22
+ JSDOM: require("jsdom").JSDOM,
23
+ TurndownService: require("../vendor/turndown/turndown.cjs.js"),
24
+ gfm: require("../vendor/turndown-plugin-gfm/turndown-plugin-gfm.cjs.js").gfm,
25
+ };
26
+ } catch (error: any) {
27
+ throw new Error(
28
+ `Readable content extraction dependencies are missing. Install ceulen dependencies with \`npm install\` in the ceulen package directory, or install the package with Pi so runtime dependencies are installed. Original error: ${error?.message || error}`,
29
+ );
30
+ }
31
+ }
32
+
33
+ export function htmlToMarkdown(html: string, deps = loadReadableContentDependencies()): string {
34
+ const turndown = new deps.TurndownService({ headingStyle: "atx", codeBlockStyle: "fenced" });
35
+ turndown.use(deps.gfm as any);
36
+ turndown.addRule("removeEmptyLinks", {
37
+ filter: (node: any) => node.nodeName === "A" && !node.textContent?.trim(),
38
+ replacement: () => "",
39
+ });
40
+ return turndown
41
+ .turndown(html)
42
+ .replace(/\[\\?\[\s*\\?\]\]\([^)]*\)/g, "")
43
+ .replace(/ +/g, " ")
44
+ .replace(/\s+,/g, ",")
45
+ .replace(/\s+\./g, ".")
46
+ .replace(/\n{3,}/g, "\n\n")
47
+ .trim();
48
+ }
49
+
50
+ export async function fetchReadableContent(
51
+ url: string,
52
+ timeoutMs = 15000,
53
+ signal?: AbortSignal,
54
+ ): Promise<{ title: string; markdown: string }> {
55
+ const response = await fetch(url, {
56
+ headers: {
57
+ "User-Agent":
58
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/120 Safari/537.36",
59
+ Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
60
+ "Accept-Language": "en-US,en;q=0.9",
61
+ },
62
+ signal: signalWithTimeout(timeoutMs, signal),
63
+ });
64
+ if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
65
+ // Raw text/JSON payloads (raw.githubusercontent.com, JSON APIs) — Readability
66
+ // shreds them to nothing. Pass through verbatim. text/html and text/xml keep
67
+ // the Readability path — they're ordinary web pages. Session mining: 9/40
68
+ // static extract failures were raw-text/JSON shapes.
69
+ const contentType = (response.headers.get("content-type") ?? "").split(";")[0].trim();
70
+ if ((contentType.startsWith("text/") && contentType !== "text/html" && contentType !== "text/xml") || contentType === "application/json") {
71
+ const body = await response.text();
72
+ const markdown = contentType === "application/json" ? "```json\n" + body + "\n```" : body;
73
+ return { title: "", markdown: markdown.slice(0, 20000) };
74
+ }
75
+ const html = await response.text();
76
+ const deps = loadReadableContentDependencies();
77
+ const dom = new deps.JSDOM(html, { url });
78
+ try {
79
+ const article = new deps.Readability(dom.window.document).parse();
80
+ if (article?.content) {
81
+ return { title: article.title || "", markdown: htmlToMarkdown(article.content, deps) };
82
+ }
83
+ } finally {
84
+ dom.window.close();
85
+ }
86
+ // Fallback: strip non-content elements and use main/article/body
87
+ const fallbackDoc = new deps.JSDOM(html, { url });
88
+ try {
89
+ const doc = fallbackDoc.window.document;
90
+ doc.querySelectorAll("script, style, noscript, nav, header, footer, aside").forEach((el: any) => el.remove());
91
+ const title = doc.querySelector("title")?.textContent?.trim() || "";
92
+ const main = doc.querySelector("main, article, [role='main'], .content, #content") || doc.body;
93
+ const fallbackHtml = main?.innerHTML || "";
94
+ if (fallbackHtml.trim().length <= 100) throw new Error("Could not extract readable content from this page.");
95
+ return { title, markdown: htmlToMarkdown(fallbackHtml, deps) };
96
+ } finally {
97
+ fallbackDoc.window.close();
98
+ }
99
+ }