ceulen 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (358) hide show
  1. package/CHANGELOG.md +317 -12
  2. package/README.md +87 -91
  3. package/extensions/lib/advisor-marker.ts +33 -0
  4. package/extensions/lib/panel.ts +25 -2
  5. package/extensions/lib/rate.ts +24 -0
  6. package/extensions/lib/registry.ts +93 -7
  7. package/extensions/lib/tools.ts +47 -0
  8. package/extensions/lib/usage-store.ts +33 -0
  9. package/extensions/modules/advisor/commands/advisor.ts +244 -0
  10. package/extensions/modules/advisor/configPanel.ts +194 -0
  11. package/extensions/modules/advisor/index.ts +217 -0
  12. package/extensions/modules/advisor/lib/config.ts +248 -0
  13. package/extensions/modules/advisor/lib/emission-guard.ts +153 -0
  14. package/extensions/modules/advisor/lib/isolated-model.ts +160 -0
  15. package/extensions/modules/advisor/lib/model-picker.ts +47 -0
  16. package/extensions/modules/advisor/lib/watcher.ts +286 -0
  17. package/extensions/modules/advisor/test/compliance.test.ts +125 -0
  18. package/extensions/modules/advisor/test/config.test.ts +202 -0
  19. package/extensions/modules/advisor/test/configPanel.test.ts +223 -0
  20. package/extensions/modules/advisor/test/emission-guard.test.ts +201 -0
  21. package/extensions/modules/advisor/test/isolated-model.test.ts +311 -0
  22. package/extensions/modules/advisor/test/model-picker.test.ts +32 -0
  23. package/extensions/modules/advisor/test/module.test.ts +586 -0
  24. package/extensions/modules/advisor/test/watcher.test.ts +478 -0
  25. package/extensions/modules/classifier/configPanel.ts +104 -0
  26. package/extensions/modules/classifier/index.ts +297 -0
  27. package/extensions/modules/classifier/lib/settings.ts +95 -0
  28. package/extensions/modules/classifier/test/classifier.test.ts +475 -0
  29. package/extensions/modules/composer/index.ts +152 -3
  30. package/extensions/modules/composer/lib/footer.ts +119 -0
  31. package/extensions/modules/composer/lib/shapes.ts +265 -26
  32. package/extensions/modules/composer/test/editor.test.ts +1 -1
  33. package/extensions/modules/composer/test/footer.test.ts +96 -0
  34. package/extensions/modules/composer/test/module.test.ts +113 -11
  35. package/extensions/modules/composer/test/screen.test.ts +29 -1
  36. package/extensions/modules/composer/test/shapes.test.ts +224 -8
  37. package/extensions/modules/config/defaultTools.ts +96 -0
  38. package/extensions/modules/config/index.ts +147 -7
  39. package/extensions/modules/config/piSettings.ts +254 -69
  40. package/extensions/modules/config/test/defaultTools.test.ts +122 -0
  41. package/extensions/modules/config/test/menu.test.ts +64 -0
  42. package/extensions/modules/config/test/panel.test.ts +38 -23
  43. package/extensions/modules/config/test/piSettings.test.ts +130 -3
  44. package/extensions/modules/config/test/renderTools.test.ts +71 -0
  45. package/extensions/modules/config/test/tools.test.ts +146 -0
  46. package/extensions/modules/fff/index.ts +2094 -0
  47. package/extensions/modules/fff/lib/query.ts +129 -0
  48. package/extensions/modules/fff/test/index.test.ts +607 -0
  49. package/extensions/modules/fff/test/query.test.ts +71 -0
  50. package/extensions/modules/munin/configPanel.ts +105 -0
  51. package/extensions/modules/munin/index.ts +641 -0
  52. package/extensions/modules/munin/lib/helpers.ts +471 -0
  53. package/extensions/modules/munin/lib/retry.ts +20 -0
  54. package/extensions/modules/munin/lib/sdk.ts +218 -0
  55. package/extensions/modules/munin/test/config.test.ts +168 -0
  56. package/extensions/modules/munin/test/configPanel.test.ts +161 -0
  57. package/extensions/modules/munin/test/extension.test.ts +224 -0
  58. package/extensions/modules/munin/test/helpers.test.ts +523 -0
  59. package/extensions/modules/munin/test/retry.test.ts +145 -0
  60. package/extensions/modules/munin/test/stale-protocol.test.ts +554 -0
  61. package/extensions/modules/plan/configPanel.ts +152 -0
  62. package/extensions/modules/plan/index.ts +917 -0
  63. package/extensions/modules/plan/lib/plan-tools.ts +72 -0
  64. package/extensions/modules/plan/lib/prompt.ts +65 -0
  65. package/extensions/modules/plan/lib/settings.ts +166 -0
  66. package/extensions/modules/plan/lib/shell-gate.ts +200 -0
  67. package/extensions/modules/plan/test/configPanel.test.ts +96 -0
  68. package/extensions/modules/plan/test/harness.ts +133 -0
  69. package/extensions/modules/plan/test/module.test.ts +305 -0
  70. package/extensions/modules/plan/test/settings.test.ts +114 -0
  71. package/extensions/modules/plan/test/shell-gate.test.ts +103 -0
  72. package/extensions/modules/ponytail/index.ts +23 -73
  73. package/extensions/modules/ponytail/lib/config.ts +1 -6
  74. package/extensions/modules/ponytail/test/extension.test.ts +1 -85
  75. package/extensions/modules/repair/configPanel.ts +96 -0
  76. package/extensions/modules/repair/index.ts +414 -0
  77. package/extensions/modules/repair/lib/auto-bg.ts +333 -0
  78. package/extensions/modules/repair/lib/edit-repair.ts +155 -0
  79. package/extensions/modules/repair/lib/editor.ts +251 -0
  80. package/extensions/modules/repair/lib/guards.ts +34 -0
  81. package/extensions/modules/repair/lib/input-repair.ts +324 -0
  82. package/extensions/modules/repair/lib/patch.ts +481 -0
  83. package/extensions/modules/repair/lib/settings.ts +114 -0
  84. package/extensions/modules/repair/test/auto-bg.test.ts +405 -0
  85. package/extensions/modules/repair/test/edit-repair.test.ts +224 -0
  86. package/extensions/modules/repair/test/editor.test.ts +141 -0
  87. package/extensions/modules/repair/test/guards.test.ts +64 -0
  88. package/extensions/modules/repair/test/input-repair.test.ts +231 -0
  89. package/extensions/modules/repair/test/patch.test.ts +563 -0
  90. package/extensions/modules/repair/test/settings.test.ts +167 -0
  91. package/extensions/modules/repair/test/wrapper.test.ts +210 -0
  92. package/extensions/modules/router/commands/commands.ts +4 -0
  93. package/extensions/modules/router/lib/client.ts +61 -0
  94. package/extensions/modules/router/lib/provider.ts +34 -13
  95. package/extensions/modules/router/lib/systemone.ts +152 -0
  96. package/extensions/modules/router/test/unit.test.ts +179 -0
  97. package/extensions/modules/rtk/findFallback.js +68 -0
  98. package/extensions/modules/rtk/index.ts +248 -0
  99. package/extensions/modules/rtk/safe-rewrite.js +74 -0
  100. package/extensions/modules/rtk/test/findFallback.test.js +66 -0
  101. package/extensions/modules/rtk/test/index.test.js +131 -0
  102. package/extensions/modules/rtk/test/safe-rewrite.test.js +96 -0
  103. package/extensions/modules/rtk/version-gate.js +34 -0
  104. package/extensions/modules/serena/index.ts +629 -0
  105. package/extensions/modules/serena/lib/detect.ts +73 -0
  106. package/extensions/modules/serena/lib/env.ts +76 -0
  107. package/extensions/modules/serena/lib/guidance.ts +26 -0
  108. package/extensions/modules/serena/lib/normalize.ts +27 -0
  109. package/extensions/modules/serena/lib/symbol-key.ts +20 -0
  110. package/extensions/modules/serena/lib/truncate.ts +20 -0
  111. package/extensions/modules/serena/test/env.test.ts +122 -0
  112. package/extensions/modules/serena/test/index.test.ts +347 -0
  113. package/extensions/modules/serena/test/worker.test.ts +562 -0
  114. package/extensions/modules/serena/worker.ts +858 -0
  115. package/extensions/modules/steering/configPanel.ts +122 -0
  116. package/extensions/modules/steering/index.ts +616 -0
  117. package/extensions/modules/steering/lib/anchor.ts +175 -0
  118. package/extensions/modules/steering/lib/errors.ts +253 -0
  119. package/extensions/modules/steering/lib/family.ts +33 -0
  120. package/extensions/modules/steering/lib/guidance.ts +172 -0
  121. package/extensions/modules/steering/lib/history.ts +170 -0
  122. package/extensions/modules/steering/lib/settings.ts +127 -0
  123. package/extensions/modules/steering/test/anchor-regressions.test.ts +93 -0
  124. package/extensions/modules/steering/test/anchor-wiring.test.ts +99 -0
  125. package/extensions/modules/steering/test/anchor.test.ts +160 -0
  126. package/extensions/modules/steering/test/cache-stats.test.ts +43 -0
  127. package/extensions/modules/steering/test/errors.test.ts +309 -0
  128. package/extensions/modules/steering/test/family.test.ts +43 -0
  129. package/extensions/modules/steering/test/guidance.test.ts +357 -0
  130. package/extensions/modules/steering/test/harness.ts +93 -0
  131. package/extensions/modules/steering/test/history.test.ts +118 -0
  132. package/extensions/modules/steering/test/settings.test.ts +182 -0
  133. package/extensions/modules/steering/test/status.test.ts +71 -0
  134. package/extensions/modules/steering/test/toolCall.test.ts +99 -0
  135. package/extensions/modules/subagent/agents/planner.md +14 -0
  136. package/extensions/modules/subagent/agents/reviewer.md +42 -0
  137. package/extensions/modules/subagent/agents/scout.md +47 -0
  138. package/extensions/modules/subagent/agents/tester.md +12 -0
  139. package/extensions/modules/subagent/agents/worker.md +18 -0
  140. package/extensions/modules/subagent/configPanel.ts +219 -0
  141. package/extensions/modules/subagent/index.ts +2451 -0
  142. package/extensions/modules/subagent/lib/agents.ts +408 -0
  143. package/extensions/modules/subagent/lib/background.ts +383 -0
  144. package/extensions/modules/subagent/lib/herdr.ts +1019 -0
  145. package/extensions/modules/subagent/lib/history.ts +126 -0
  146. package/extensions/modules/subagent/lib/model.ts +156 -0
  147. package/extensions/modules/subagent/lib/render.ts +335 -0
  148. package/extensions/modules/subagent/lib/result.ts +110 -0
  149. package/extensions/modules/subagent/lib/roles.ts +296 -0
  150. package/extensions/modules/subagent/lib/routing.ts +223 -0
  151. package/extensions/modules/subagent/lib/runner.ts +559 -0
  152. package/extensions/modules/subagent/lib/schema.ts +21 -0
  153. package/extensions/modules/subagent/lib/security.ts +752 -0
  154. package/extensions/modules/subagent/lib/settings.ts +159 -0
  155. package/extensions/modules/subagent/lib/thread-viewer.ts +319 -0
  156. package/extensions/modules/subagent/lib/threads.ts +135 -0
  157. package/extensions/modules/subagent/lib/types.ts +18 -0
  158. package/extensions/modules/subagent/lib/widget.ts +475 -0
  159. package/extensions/modules/subagent/test/configPanel.test.ts +132 -0
  160. package/extensions/modules/subagent/test/herdr-advisor.test.ts +40 -0
  161. package/extensions/modules/subagent/test/routing.test.ts +350 -0
  162. package/extensions/modules/subagent/test/widget.test.ts +208 -0
  163. package/extensions/modules/usage/index.ts +59 -16
  164. package/extensions/modules/usage/test/genrate.test.ts +70 -0
  165. package/extensions/modules/usage/test/parsers.test.ts +13 -0
  166. package/extensions/modules/ux/UPSTREAM +24 -0
  167. package/extensions/modules/ux/index.ts +393 -0
  168. package/extensions/modules/ux/lib/audit.ts +562 -0
  169. package/extensions/modules/ux/lib/config.ts +136 -0
  170. package/extensions/modules/ux/lib/instructions.ts +77 -0
  171. package/extensions/modules/ux/test/audit.test.ts +756 -0
  172. package/extensions/modules/ux/test/extension.test.ts +394 -0
  173. package/extensions/modules/ux/test/instructions.test.ts +19 -0
  174. package/extensions/modules/web/configPanel.ts +193 -0
  175. package/extensions/modules/web/index.ts +978 -0
  176. package/extensions/modules/web/lib/agy.ts +209 -0
  177. package/extensions/modules/web/lib/brave.ts +42 -0
  178. package/extensions/modules/web/lib/cdp.ts +686 -0
  179. package/extensions/modules/web/lib/chatapi.ts +101 -0
  180. package/extensions/modules/web/lib/chatgpt.ts +796 -0
  181. package/extensions/modules/web/lib/chrome.ts +328 -0
  182. package/extensions/modules/web/lib/config.ts +136 -0
  183. package/extensions/modules/web/lib/content.ts +99 -0
  184. package/extensions/modules/web/lib/crawl4ai.ts +172 -0
  185. package/extensions/modules/web/lib/extract.ts +235 -0
  186. package/extensions/modules/web/lib/firecrawl.ts +56 -0
  187. package/extensions/modules/web/lib/format.ts +197 -0
  188. package/extensions/modules/web/lib/gemini-auth.ts +286 -0
  189. package/extensions/modules/web/lib/gemini-dr.ts +338 -0
  190. package/extensions/modules/web/lib/gemini.ts +551 -0
  191. package/extensions/modules/web/lib/imageapi.ts +559 -0
  192. package/extensions/modules/web/lib/retry.ts +71 -0
  193. package/extensions/modules/web/lib/search.ts +237 -0
  194. package/extensions/modules/web/lib/searxng.ts +69 -0
  195. package/extensions/modules/web/lib/settings.ts +148 -0
  196. package/extensions/modules/web/scripts/cdp-smoke.ts +77 -0
  197. package/extensions/modules/web/scripts/gemini-smoke.ts +107 -0
  198. package/extensions/modules/web/test/agy.test.ts +383 -0
  199. package/extensions/modules/web/test/cdp.test.ts +717 -0
  200. package/extensions/modules/web/test/chat.test.ts +171 -0
  201. package/extensions/modules/web/test/chatgpt.test.ts +633 -0
  202. package/extensions/modules/web/test/chrome.test.ts +282 -0
  203. package/extensions/modules/web/test/config.test.ts +218 -0
  204. package/extensions/modules/web/test/configPanel.test.ts +132 -0
  205. package/extensions/modules/web/test/crawl.test.ts +134 -0
  206. package/extensions/modules/web/test/crawl4ai.test.ts +105 -0
  207. package/extensions/modules/web/test/extension.test.ts +118 -0
  208. package/extensions/modules/web/test/extract.test.ts +436 -0
  209. package/extensions/modules/web/test/fixtures/dr-confirm.bin +12 -0
  210. package/extensions/modules/web/test/fixtures/dr-plan.bin +20 -0
  211. package/extensions/modules/web/test/fixtures/interaction.html +31 -0
  212. package/extensions/modules/web/test/format.test.ts +230 -0
  213. package/extensions/modules/web/test/gemini-auth.test.ts +465 -0
  214. package/extensions/modules/web/test/gemini-dr.test.ts +249 -0
  215. package/extensions/modules/web/test/gemini.test.ts +472 -0
  216. package/extensions/modules/web/test/hook.test.ts +101 -0
  217. package/extensions/modules/web/test/image.test.ts +1089 -0
  218. package/extensions/modules/web/test/retry.test.ts +119 -0
  219. package/extensions/modules/web/test/screenshot.test.ts +109 -0
  220. package/extensions/modules/web/test/search.test.ts +210 -0
  221. package/extensions/modules/web/test/settings.test.ts +165 -0
  222. package/extensions/modules/web/test/skill.test.ts +72 -0
  223. package/extensions/modules/web/types.d.ts +3 -0
  224. package/extensions/modules/web/vendor/package.json +1 -0
  225. package/extensions/modules/web/vendor/readability/LICENSE.md +13 -0
  226. package/extensions/modules/web/vendor/readability/Readability-readerable.js +123 -0
  227. package/extensions/modules/web/vendor/readability/Readability.js +2787 -0
  228. package/extensions/modules/web/vendor/readability/index.d.ts +64 -0
  229. package/extensions/modules/web/vendor/readability/index.js +9 -0
  230. package/extensions/modules/web/vendor/turndown/LICENSE +21 -0
  231. package/extensions/modules/web/vendor/turndown/turndown.cjs.js +784 -0
  232. package/extensions/modules/web/vendor/turndown-plugin-gfm/LICENSE +21 -0
  233. package/extensions/modules/web/vendor/turndown-plugin-gfm/turndown-plugin-gfm.cjs.js +163 -0
  234. package/extensions/modules/zai/configPanel.ts +151 -0
  235. package/extensions/modules/zai/index.ts +186 -0
  236. package/extensions/modules/zai/lib/anthropic.ts +159 -0
  237. package/extensions/modules/zai/lib/settings.ts +198 -0
  238. package/extensions/modules/zai/lib/signing.ts +718 -0
  239. package/extensions/modules/zai/lib/throttle.ts +198 -0
  240. package/extensions/modules/zai/test/anthropic.test.ts +132 -0
  241. package/extensions/modules/zai/test/configPanel.test.ts +207 -0
  242. package/extensions/modules/zai/test/extension.test.ts +249 -0
  243. package/extensions/modules/zai/test/settings.test.ts +183 -0
  244. package/extensions/modules/zai/test/signing-wiring.test.ts +108 -0
  245. package/extensions/modules/zai/test/signing.test.ts +345 -0
  246. package/extensions/modules/zai/test/throttle.test.ts +329 -0
  247. package/package.json +19 -4
  248. package/scripts/validate-themes.mjs +75 -0
  249. package/skills/munin/SKILL.md +117 -0
  250. package/skills/ux-capture/SKILL.md +202 -0
  251. package/skills/ux-design/SKILL.md +279 -0
  252. package/skills/ux-presets/SKILL.md +484 -0
  253. package/skills/ux-routing/SKILL.md +46 -0
  254. package/skills/web/SKILL.md +153 -0
  255. package/themes/alabaster.json +93 -0
  256. package/themes/amethyst.json +96 -0
  257. package/themes/anthracite.json +93 -0
  258. package/themes/basalt.json +91 -0
  259. package/themes/birch.json +95 -0
  260. package/themes/catppuccin-mocha.json +91 -0
  261. package/themes/dark-abyss.json +91 -0
  262. package/themes/dark-arctic.json +104 -0
  263. package/themes/dark-aurora.json +95 -0
  264. package/themes/dark-catppuccin.json +107 -0
  265. package/themes/dark-cavern.json +91 -0
  266. package/themes/dark-celestial.json +106 -0
  267. package/themes/dark-copper.json +95 -0
  268. package/themes/dark-cosmos.json +90 -0
  269. package/themes/dark-cyberpunk.json +102 -0
  270. package/themes/dark-dracula.json +98 -0
  271. package/themes/dark-eclipse.json +91 -0
  272. package/themes/dark-ember.json +95 -0
  273. package/themes/dark-equinox.json +90 -0
  274. package/themes/dark-forest.json +96 -0
  275. package/themes/dark-github.json +105 -0
  276. package/themes/dark-gruvbox.json +112 -0
  277. package/themes/dark-lavender.json +95 -0
  278. package/themes/dark-lunar.json +89 -0
  279. package/themes/dark-midnight.json +95 -0
  280. package/themes/dark-monochrome.json +94 -0
  281. package/themes/dark-monokai.json +98 -0
  282. package/themes/dark-nebula.json +90 -0
  283. package/themes/dark-neon-noir.json +100 -0
  284. package/themes/dark-nord.json +98 -0
  285. package/themes/dark-ocean.json +101 -0
  286. package/themes/dark-one.json +100 -0
  287. package/themes/dark-poimandres.json +115 -0
  288. package/themes/dark-rainforest.json +91 -0
  289. package/themes/dark-reef.json +91 -0
  290. package/themes/dark-retro.json +92 -0
  291. package/themes/dark-rose-pine.json +96 -0
  292. package/themes/dark-sakura.json +95 -0
  293. package/themes/dark-slate.json +95 -0
  294. package/themes/dark-solarized.json +97 -0
  295. package/themes/dark-solstice.json +90 -0
  296. package/themes/dark-starfall.json +91 -0
  297. package/themes/dark-sunset.json +99 -0
  298. package/themes/dark-swamp.json +90 -0
  299. package/themes/dark-synthwave.json +103 -0
  300. package/themes/dark-taiga.json +91 -0
  301. package/themes/dark-terminal.json +95 -0
  302. package/themes/dark-tokyo-night.json +101 -0
  303. package/themes/dark-tundra.json +91 -0
  304. package/themes/dark-twilight.json +91 -0
  305. package/themes/dark-volcanic.json +91 -0
  306. package/themes/dark.json +80 -0
  307. package/themes/graphite.json +92 -0
  308. package/themes/light-arctic.json +107 -0
  309. package/themes/light-aurora-day.json +91 -0
  310. package/themes/light-canyon.json +91 -0
  311. package/themes/light-catppuccin.json +106 -0
  312. package/themes/light-cirrus.json +90 -0
  313. package/themes/light-coral.json +95 -0
  314. package/themes/light-cyberpunk.json +96 -0
  315. package/themes/light-dawn.json +90 -0
  316. package/themes/light-dunes.json +91 -0
  317. package/themes/light-eucalyptus.json +95 -0
  318. package/themes/light-forest.json +100 -0
  319. package/themes/light-frost.json +95 -0
  320. package/themes/light-github.json +115 -0
  321. package/themes/light-glacier.json +91 -0
  322. package/themes/light-gruvbox.json +108 -0
  323. package/themes/light-haze.json +90 -0
  324. package/themes/light-honeycomb.json +95 -0
  325. package/themes/light-lagoon.json +91 -0
  326. package/themes/light-lavender.json +95 -0
  327. package/themes/light-meadow.json +91 -0
  328. package/themes/light-mint.json +95 -0
  329. package/themes/light-monochrome.json +101 -0
  330. package/themes/light-ocean.json +99 -0
  331. package/themes/light-one.json +99 -0
  332. package/themes/light-opal.json +91 -0
  333. package/themes/light-orchard.json +91 -0
  334. package/themes/light-paper.json +95 -0
  335. package/themes/light-poimandres.json +115 -0
  336. package/themes/light-prism.json +90 -0
  337. package/themes/light-retro.json +98 -0
  338. package/themes/light-sand.json +95 -0
  339. package/themes/light-savanna.json +91 -0
  340. package/themes/light-solarized.json +102 -0
  341. package/themes/light-soleil.json +90 -0
  342. package/themes/light-sunset.json +99 -0
  343. package/themes/light-synthwave.json +98 -0
  344. package/themes/light-tokyo-night.json +111 -0
  345. package/themes/light-wetland.json +91 -0
  346. package/themes/light-zenith.json +89 -0
  347. package/themes/light.json +80 -0
  348. package/themes/limestone.json +94 -0
  349. package/themes/mahogany.json +97 -0
  350. package/themes/marble.json +93 -0
  351. package/themes/mirage.json +79 -0
  352. package/themes/obsidian.json +91 -0
  353. package/themes/onyx.json +91 -0
  354. package/themes/pearl.json +93 -0
  355. package/themes/porcelain.json +91 -0
  356. package/themes/quartz.json +96 -0
  357. package/themes/sandstone.json +95 -0
  358. package/themes/titanium.json +90 -0
@@ -0,0 +1,286 @@
1
+ // ponytail: vendored from @bacnh85/pi-web 0.17.8
2
+ // Gemini web cookie auto-refresh — keeps a one-time-pasted session alive.
3
+ //
4
+ // Google rotates __Secure-1PSIDTS on authenticated visits, so a pasted static
5
+ // copy dies within minutes-to-hours. Google also ships the rotation endpoint
6
+ // Chrome itself calls: POST https://accounts.google.com/RotateCookies issues a
7
+ // fresh __Secure-1PSIDTS for the cookie session (a third-party experiment
8
+ // reports this also covers DBSC-bound sessions today, but pi-web's supported
9
+ // path is incognito/unbound cookies; 400/401 = session dead server-side). We rotate on a
10
+ // 10-min keepalive (Google's declared cadence) and persist the rotated value
11
+ // to a 0600 store file so later pi sessions reuse it.
12
+ // Sources: HanaokaYuzu/Gemini-API utils/rotate_1psidts.py + constants.py;
13
+ // empirical validation in teng-lin/notebooklm-py#345 (+#312).
14
+
15
+ import fs from "node:fs";
16
+ import os from "node:os";
17
+ import path from "node:path";
18
+ import { findEnvValue } from "./config";
19
+
20
+ const ROTATE_URL = "https://accounts.google.com/RotateCookies";
21
+ // jspb sentinel body from Gemini-API — send raw so axios doesn't re-serialize
22
+ // (JSON.stringify would rewrite [000,...] to [0,...]).
23
+ // accounts.google.com refuses RotateCookies from non-browser user agents —
24
+ // verified 2026-09-14: identical valid cookie, axios default UA → 400; Chrome
25
+ // UA → 200 + fresh __Secure-1PSIDTS. Browser fingerprint required.
26
+ const ROTATE_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36";
27
+ const ROTATE_CLIENT_HINTS: Record<string, string> = {
28
+ "User-Agent": ROTATE_UA,
29
+ "sec-ch-ua": '"Chromium";v="145", "Google Chrome";v="145", "Not-A.Brand";v="24"',
30
+ "sec-ch-ua-mobile": "?0",
31
+ "sec-ch-ua-platform": '"Windows"',
32
+ };
33
+
34
+ const ROTATE_BODY = '[000,"-0000000000000000000"]';
35
+ // Google declares the next rotation interval as 600s in the response body
36
+ // (["identity.hfcr",600]) — used as the default keepalive cadence.
37
+ const DEFAULT_ROTATE_INTERVAL_MS = 600_000;
38
+ // HanaokaYuzu's anti-429 guard: never rotate more often than once a minute.
39
+ const MIN_ROTATE_GAP_MS = 60_000;
40
+
41
+ export interface CookieStoreEntry {
42
+ psid: string;
43
+ psidts: string;
44
+ updatedAt: number;
45
+ }
46
+
47
+ export interface RotateResult {
48
+ ok: boolean;
49
+ psidts?: string;
50
+ reason?: string;
51
+ /** true when the server itself rejected the rotation (400/401/no new TS) — informational only; rotation failures never clear the store (the paste TS keeps serving content). false on transport errors. */
52
+ stale?: boolean;
53
+ }
54
+
55
+ export type PostFn = (
56
+ url: string,
57
+ opts: { headers: Record<string, string>; body: string; proxy?: string; timeoutMs: number },
58
+ ) => Promise<{ status: number; setCookie: string[] }>;
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // Cookie store: single 0600 JSON file, one active session.
62
+ // The env-pasted PSID is the session identity; the store only carries freshness.
63
+ // ---------------------------------------------------------------------------
64
+
65
+ export function defaultStorePath(): string {
66
+ // findEnvValue honors process env + .env files like every sibling setting.
67
+ return findEnvValue("GEMINI_WEB_COOKIE_STORE").value || path.join(os.homedir(), ".pi", "agent", "gemini-web-cookies.json");
68
+ }
69
+
70
+ export function loadCookieStore(storePath: string = defaultStorePath()): CookieStoreEntry | null {
71
+ try {
72
+ const parsed = JSON.parse(fs.readFileSync(storePath, "utf8")) as Partial<CookieStoreEntry>;
73
+ if (parsed.psid && parsed.psidts) {
74
+ return { psid: parsed.psid, psidts: parsed.psidts, updatedAt: Number(parsed.updatedAt) || 0 };
75
+ }
76
+ } catch {
77
+ /* missing or corrupt → treated as absent */
78
+ }
79
+ return null;
80
+ }
81
+
82
+ export function saveCookieStore(entry: CookieStoreEntry, storePath: string = defaultStorePath()): void {
83
+ fs.mkdirSync(path.dirname(storePath), { recursive: true });
84
+ // mode at creation — no world-readable window before the chmod (which stays
85
+ // for rewrites of pre-existing files whose mode may have drifted).
86
+ // write-then-rename: concurrent readers (keepalive tick, auto-heal, jar
87
+ // persist) must never observe an empty/partial store.
88
+ const tmp = `${storePath}.tmp`;
89
+ fs.writeFileSync(tmp, JSON.stringify(entry, null, 2), { mode: 0o600 });
90
+ fs.renameSync(tmp, storePath);
91
+ fs.chmodSync(storePath, 0o600);
92
+ }
93
+
94
+ export function clearCookieStore(storePath: string = defaultStorePath()): void {
95
+ try {
96
+ fs.unlinkSync(storePath);
97
+ } catch {
98
+ /* already absent */
99
+ }
100
+ }
101
+
102
+ /** Store freshness for web_status — never includes cookie values. */
103
+ export function cookieStoreSnapshot(storePath: string = defaultStorePath()): { present: boolean; ageSeconds?: number; path: string } {
104
+ const store = loadCookieStore(storePath);
105
+ return store
106
+ ? { present: true, ageSeconds: Math.max(0, Math.round((Date.now() - store.updatedAt) / 1000)), path: storePath }
107
+ : { present: false, path: storePath };
108
+ }
109
+
110
+ /**
111
+ * The PSIDTS to use: the ENV value (fresh paste) always wins — a stored TS
112
+ * can be superseded and must never shadow a re-paste for the same PSID. The
113
+ * store is only a restart fallback when the env has no TS at all (users who
114
+ * delegate cookie ownership to pi after a successful opt-in rotation).
115
+ */
116
+ export function resolvePsidts(
117
+ psid: string | undefined,
118
+ envPsidts: string | undefined,
119
+ storePath: string = defaultStorePath(),
120
+ ): string | undefined {
121
+ if (envPsidts) return envPsidts;
122
+ if (!psid) return undefined;
123
+ const store = loadCookieStore(storePath);
124
+ return store && store.psid === psid && store.psidts ? store.psidts : undefined;
125
+ }
126
+
127
+ // ---------------------------------------------------------------------------
128
+ // Rotation
129
+ // ---------------------------------------------------------------------------
130
+
131
+ function parseProxy(str: string): { protocol: string; host: string; port: number } | undefined {
132
+ try {
133
+ const u = new URL(str);
134
+ return { protocol: u.protocol.replace(":", ""), host: u.hostname, port: Number(u.port) || (u.protocol === "https:" ? 443 : 80) };
135
+ } catch {
136
+ return undefined;
137
+ }
138
+ }
139
+
140
+ /** @internal exported for tests — the real rotation POST (axios, no-follow) */
141
+ export async function defaultPost(
142
+ url: string,
143
+ opts: { headers: Record<string, string>; body: string; proxy?: string; timeoutMs: number },
144
+ ): Promise<{ status: number; setCookie: string[] }> {
145
+ const axios = (await import("axios")).default;
146
+ const res = await axios.post(url, opts.body, {
147
+ headers: opts.headers,
148
+ // Read Set-Cookie off the first response — following redirects drops it
149
+ // (axios only surfaces final-response headers).
150
+ maxRedirects: 0,
151
+ // 401 is a signal to map, not an exception.
152
+ validateStatus: () => true,
153
+ timeout: opts.timeoutMs,
154
+ ...(opts.proxy ? { proxy: parseProxy(opts.proxy) } : {}),
155
+ });
156
+ const raw = res.headers["set-cookie"];
157
+ return { status: res.status, setCookie: Array.isArray(raw) ? raw : raw ? [raw] : [] };
158
+ }
159
+
160
+ function extractSetCookie(setCookie: string[], name: string): string | undefined {
161
+ for (const line of setCookie) {
162
+ const pair = line.split(";")[0];
163
+ const eq = pair.indexOf("=");
164
+ if (eq !== -1 && pair.slice(0, eq).trim() === name) return pair.slice(eq + 1).trim();
165
+ }
166
+ return undefined;
167
+ }
168
+
169
+ export async function rotateCookies(opts: {
170
+ psid: string;
171
+ psidts?: string;
172
+ proxy?: string;
173
+ timeoutMs?: number;
174
+ post?: PostFn;
175
+ }): Promise<RotateResult> {
176
+ const post = opts.post ?? defaultPost;
177
+ const cookie = opts.psidts ? `__Secure-1PSID=${opts.psid}; __Secure-1PSIDTS=${opts.psidts}` : `__Secure-1PSID=${opts.psid}`;
178
+ try {
179
+ const res = await post(ROTATE_URL, {
180
+ headers: {
181
+ "Content-Type": "application/json",
182
+ Origin: "https://accounts.google.com",
183
+ ...ROTATE_CLIENT_HINTS,
184
+ Cookie: cookie,
185
+ },
186
+ body: ROTATE_BODY,
187
+ proxy: opts.proxy,
188
+ timeoutMs: opts.timeoutMs ?? 15_000,
189
+ });
190
+ const fresh = extractSetCookie(res.setCookie, "__Secure-1PSIDTS");
191
+ if (fresh) return { ok: true, psidts: fresh };
192
+ // Only definitive rejections prove the session dead (store cleared).
193
+ // 403 (rate-limit/abuse soft-block), 429/5xx/3xx/other are transient or
194
+ // ambiguous — keep the store, like transport errors.
195
+ if (res.status === 400 || res.status === 401) {
196
+ return { ok: false, stale: true, reason: `unauthorized (${res.status}) — session expired server-side` };
197
+ }
198
+ return { ok: false, reason: `no new __Secure-1PSIDTS in response (status ${res.status}) — transient server response; store kept` };
199
+ } catch (err) {
200
+ return { ok: false, reason: err instanceof Error ? err.message : String(err) };
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Rotate once with store-first resolution and persist the outcome.
206
+ * Clears the store only when the server itself says the session is dead,
207
+ * so a stale store never shadows a future fresh paste (and a transient
208
+ * network error never wipes a good one).
209
+ */
210
+ export async function refreshGeminiAuth(
211
+ cfg: { psid?: string; psidts?: string; proxy?: string },
212
+ opts: { post?: PostFn; storePath?: string } = {},
213
+ ): Promise<RotateResult & { store: string }> {
214
+ const storePath = opts.storePath ?? defaultStorePath();
215
+ if (!cfg.psid) return { ok: false, reason: "GEMINI_WEB_SECURE_1PSID not set — nothing to rotate", store: storePath };
216
+ const result = await rotateCookies({ psid: cfg.psid, psidts: resolvePsidts(cfg.psid, cfg.psidts, storePath), proxy: cfg.proxy, post: opts.post });
217
+ if (result.ok && result.psidts) {
218
+ saveCookieStore({ psid: cfg.psid, psidts: result.psidts, updatedAt: Date.now() }, storePath);
219
+ }
220
+ // NOTE: rotation failures never clear the store — the paste TS keeps
221
+ // serving content even when the rotation endpoint refuses (proven
222
+ // 2026-09-14: rotation 400/401 while authed ask still worked).
223
+ return { ...result, store: storePath };
224
+ }
225
+
226
+ // ---------------------------------------------------------------------------
227
+ // Keepalive: one rotation tick + the lazy background timer.
228
+ // ---------------------------------------------------------------------------
229
+
230
+ /** One tick: skip when the store is fresh, else rotate+persist. Returns store freshness. */
231
+ export async function keepaliveOnce(
232
+ cfg: { psid?: string; psidts?: string; proxy?: string },
233
+ opts: { post?: PostFn; storePath?: string } = {},
234
+ ): Promise<boolean> {
235
+ if (!cfg.psid) return false;
236
+ const storePath = opts.storePath ?? defaultStorePath();
237
+ const store = loadCookieStore(storePath);
238
+ // Fresh-store skip is psid-scoped: a fresh store for ANOTHER session must
239
+ // not stop this one from taking ownership of its own generation.
240
+ if (store && store.psid === cfg.psid && Date.now() - store.updatedAt < MIN_ROTATE_GAP_MS) return true;
241
+ return (await refreshGeminiAuth(cfg, opts)).ok;
242
+ }
243
+
244
+ let keepaliveTimer: ReturnType<typeof setInterval> | null = null;
245
+ let keepalivePsid: string | undefined;
246
+
247
+ /**
248
+ * OPT-IN background rotation timer (GEMINI_WEB_KEEPALIVE=1). DEFAULT OFF.
249
+ * Live testing (2026-09-14) showed RotateCookies-issued __Secure-1PSIDTS are
250
+ * REJECTED by gemini.google.com's privileged surfaces (Deep Research
251
+ * no-chat-id / image 403) while the original paste TS keeps serving — i.e.
252
+ * rotation poisons the session for privileged tools. The paste TS itself
253
+ * stays valid indefinitely as long as the browser doesn't compete for it.
254
+ */
255
+ export function ensureKeepalive(
256
+ cfg: { psid?: string; psidts?: string; proxy?: string },
257
+ hooks?: { post?: PostFn; storePath?: string; intervalMs?: number },
258
+ ): void {
259
+ if (!cfg.psid) return;
260
+ if (keepaliveTimer && keepalivePsid === cfg.psid) return;
261
+ stopKeepalive();
262
+ if (findEnvValue("GEMINI_WEB_KEEPALIVE").value !== "1") return;
263
+ const parsed = Number(findEnvValue("GEMINI_WEB_ROTATE_INTERVAL_MS").value);
264
+ const intervalMs =
265
+ hooks?.intervalMs && hooks.intervalMs >= 1000
266
+ ? hooks.intervalMs
267
+ : Number.isFinite(parsed) && parsed >= MIN_ROTATE_GAP_MS
268
+ ? parsed
269
+ : DEFAULT_ROTATE_INTERVAL_MS;
270
+ keepalivePsid = cfg.psid;
271
+ keepaliveTimer = setInterval(() => {
272
+ void keepaliveOnce(cfg, hooks).catch(() => {});
273
+ }, intervalMs);
274
+ keepaliveTimer.unref?.();
275
+ }
276
+
277
+ export function stopKeepalive(): void {
278
+ if (keepaliveTimer) clearInterval(keepaliveTimer);
279
+ keepaliveTimer = null;
280
+ keepalivePsid = undefined;
281
+ }
282
+
283
+ /** @internal test hook — keepalive arm state */
284
+ export function __keepaliveDebug(): { armed: boolean; psid: string | undefined; intervalMs: number | null } {
285
+ return { armed: keepaliveTimer !== null, psid: keepalivePsid, intervalMs: keepaliveTimer ? (keepaliveTimer as unknown as { _idleTimeout?: number })._idleTimeout ?? null : null };
286
+ }
@@ -0,0 +1,338 @@
1
+ // ponytail: vendored from @bacnh85/pi-web 0.17.8
2
+ // Pure-Node Deep Research client for gemini.google.com — replaces the
3
+ // gemini-reverse research path, whose payload/parser drift causes 1184 and
4
+ // "research_id missing" failures. Wire shapes validated live 2026-09-13/14
5
+ // (plan + confirm turns executed via /tmp/gemini-dr2.mjs; fixtures in
6
+ // extensions/test/unit/fixtures/). Deep research is an ordinary chat turn
7
+ // flagged deep_research=True: plan turn → "Start research" confirm turn →
8
+ // poll LIST_CONVERSATION_TURNS until the report text arrives.
9
+ //
10
+ // NOTE: report polling uses the batchexecute XSRF `at` token, which only a
11
+ // live session's pages carry. On stale sessions the plan/confirm steps still
12
+ // execute (proven) but the poll returns empty payloads — geminiResearch
13
+ // surfaces that as a partial result with a clear note.
14
+
15
+ import crypto from "node:crypto";
16
+ import https from "node:https";
17
+ import { URL } from "node:url";
18
+ import { abortableSleep } from "./retry";
19
+
20
+ const DR_APP_URL = "https://gemini.google.com/app";
21
+ const DR_GENERATE_URL = "https://gemini.google.com/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate";
22
+ const DR_BATCH_URL = "https://gemini.google.com/_/BardChatUi/data/batchexecute";
23
+ const DR_CONFIRM_PROMPT = "Start research";
24
+ const DR_TOKEN_BYTES = 1950; // → 2600 base64url chars, matches gemini_webapi
25
+
26
+ export const CHROME_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36";
27
+
28
+ export interface DrResult {
29
+ title?: string;
30
+ text: string;
31
+ sources: string[];
32
+ /** Present when the cycle ran but the report was not retrievable (stale session): plan/confirm transcript stands in. */
33
+ partial?: string;
34
+ }
35
+
36
+ /** Injectable transport: GET/POST returning the full (already buffered) body. */
37
+ export type DrHttp = (
38
+ url: string,
39
+ opts: { method: "GET" | "POST"; headers: Record<string, string>; body?: string },
40
+ ) => Promise<{ status: number; headers: { get(name: string): string | null; "set-cookie"?: string[] }; buf: Buffer }>;
41
+
42
+ export interface DrOptions {
43
+ cookie: { psid: string; psidts?: string };
44
+ query: string;
45
+ timeoutMs?: number;
46
+ signal?: AbortSignal;
47
+ /** @internal test injection */
48
+ http?: DrHttp;
49
+ }
50
+
51
+ export function chromeHeaders(extra: Record<string, string> = {}): Record<string, string> {
52
+ return {
53
+ "user-agent": CHROME_UA,
54
+ "sec-ch-ua": '"Chromium";v="145", "Google Chrome";v="145", "Not-A.Brand";v="24"',
55
+ "sec-ch-ua-mobile": "?0",
56
+ "sec-ch-ua-platform": '"Windows"',
57
+ "sec-fetch-dest": "empty",
58
+ "sec-fetch-mode": "cors",
59
+ "sec-fetch-site": "same-origin",
60
+ accept: "*/*",
61
+ "accept-language": "en-US,en;q=0.9",
62
+ origin: "https://gemini.google.com",
63
+ referer: "https://gemini.google.com/",
64
+ ...extra,
65
+ };
66
+ }
67
+
68
+ /** Default transport: node:https with redirect-following (max 5) + cookie-jar accumulation over the base cookie. */
69
+ export function defaultHttp(): DrHttp {
70
+ return async (url, opts) => {
71
+ const { rest, jar } = extractCookieJar(opts.headers);
72
+ let current = url;
73
+ for (let hop = 0; hop < 5; hop++) {
74
+ const cookie = [...jar].map(([k, v]) => `${k}=${v}`).join("; ");
75
+ const res = await new Promise<{ status: number; headers: import("node:http").IncomingHttpHeaders; buf: Buffer }>((resolve, reject) => {
76
+ const req = https.request(new URL(current), { method: opts.method, headers: { ...rest, Cookie: cookie }, maxHeaderSize: 256 * 1024 }, (r) => {
77
+ const chunks: Buffer[] = [];
78
+ r.on("data", (c: Buffer) => chunks.push(c));
79
+ r.on("end", () => resolve({ status: r.statusCode ?? 0, headers: r.headers, buf: Buffer.concat(chunks) }));
80
+ });
81
+ req.on("error", reject);
82
+ req.setTimeout(120_000, () => req.destroy(new Error("timeout")));
83
+ if (opts.body) req.write(opts.body);
84
+ req.end();
85
+ });
86
+ for (const line of res.headers["set-cookie"] ?? []) {
87
+ const pair = line.split(";")[0];
88
+ const eq = pair.indexOf("=");
89
+ if (eq > 0) jar.set(pair.slice(0, eq).trim(), pair.slice(eq + 1).trim());
90
+ }
91
+ if ([301, 302, 303, 307, 308].includes(res.status) && res.headers.location) {
92
+ current = new URL(res.headers.location, current).toString();
93
+ continue;
94
+ }
95
+ return {
96
+ status: res.status,
97
+ headers: { get: (n) => (res.headers[n.toLowerCase()] as string | undefined) ?? null, "set-cookie": res.headers["set-cookie"] },
98
+ buf: res.buf,
99
+ };
100
+ }
101
+ throw new Error("too many redirects");
102
+ };
103
+ }
104
+
105
+ /** Case-independent Cookie-header extraction + jar seeding. Callers pass the
106
+ * auth cookie as `cookie` (chromeHeaders) — seeding must not depend on case,
107
+ * and the original header must be removed so exactly one Cookie header ships
108
+ * per hop (a stray empty `Cookie:` renders pages logged-out).
109
+ * @internal exported for tests */
110
+ export function extractCookieJar(headers: Record<string, string>): { rest: Record<string, string>; jar: Map<string, string> } {
111
+ const rest: Record<string, string> = {};
112
+ const jar = new Map<string, string>();
113
+ for (const [k, v] of Object.entries(headers)) {
114
+ if (k.toLowerCase() !== "cookie") {
115
+ rest[k] = v;
116
+ continue;
117
+ }
118
+ for (const pair of v.split("; ")) {
119
+ const eq = pair.indexOf("=");
120
+ if (eq > 0) jar.set(pair.slice(0, eq).trim(), pair.slice(eq + 1));
121
+ }
122
+ }
123
+ return { rest, jar };
124
+ }
125
+
126
+ /** Byte-exact frame splitter: prefix is the byte length INCLUDING the trailing newline. */
127
+ export function parseFrames(buf: Buffer): string[] {
128
+ const start = buf.indexOf(")]}'");
129
+ if (start === -1) return [];
130
+ const stream = buf.slice(start + 4);
131
+ let i = 0;
132
+ const frames: string[] = [];
133
+ while (i < stream.length) {
134
+ while (i < stream.length && stream[i] === 0x0a) i++;
135
+ const nl = stream.indexOf(0x0a, i);
136
+ if (nl === -1) break;
137
+ const len = parseInt(stream.slice(i, nl).toString("ascii"), 10);
138
+ if (!Number.isFinite(len) || len <= 0) break;
139
+ frames.push(stream.slice(nl + 1, nl + len).toString("utf8").trimEnd());
140
+ i = nl + len;
141
+ }
142
+ return frames;
143
+ }
144
+
145
+ /** All strings from a frame set, recursing into escaped inner-JSON payloads. */
146
+ export function frameStrings(frames: string[]): string[] {
147
+ const out: string[] = [];
148
+ const walk = (v: unknown, d: number): void => {
149
+ if (v == null || d > 14) return;
150
+ if (typeof v === "string") {
151
+ out.push(v);
152
+ if (v.startsWith("[") || v.startsWith("{")) { try { walk(JSON.parse(v), d + 1); } catch { /* not json */ } }
153
+ return;
154
+ }
155
+ if (Array.isArray(v)) { for (const x of v) walk(x, d + 1); return; }
156
+ if (typeof v === "object") { for (const x of Object.values(v)) walk(x, d + 1); }
157
+ };
158
+ for (const f of frames) { try { walk(JSON.parse(f), 0); } catch { /* skip */ } }
159
+ return out;
160
+ }
161
+
162
+ /** The plan title arrives as a {"11":["<title>"]} sparse-metadata leaf inside the frames. */
163
+ export function extractPlanTitle(frames: string[]): string | undefined {
164
+ let title: string | undefined;
165
+ const walk = (v: unknown, d: number): void => {
166
+ if (v == null || d > 14 || title) return;
167
+ if (typeof v === 'string') {
168
+ // the payload arrives as an escaped inner-JSON string — recurse into it
169
+ if (v.startsWith('[') || v.startsWith('{')) { try { walk(JSON.parse(v), d + 1); } catch { /* not json */ } }
170
+ return;
171
+ }
172
+ if (Array.isArray(v)) { for (const x of v) walk(x, d + 1); return; }
173
+ if (typeof v === 'object') {
174
+ const rec = v as Record<string, unknown>;
175
+ if (!title && Array.isArray(rec['11']) && typeof rec['11'][0] === 'string' && (rec['11'][0] as string).length > 3) {
176
+ title = rec['11'][0] as string;
177
+ }
178
+ for (const x of Object.values(rec)) walk(x, d + 1);
179
+ }
180
+ };
181
+ for (const f of frames) { try { walk(JSON.parse(f), 0); } catch { /* skip */ } }
182
+ return title;
183
+ }
184
+
185
+ export function extractChatIds(strings: string[]): { cid?: string; rid?: string } {
186
+ for (const s of strings) {
187
+ const cid = (s.match(/c_[0-9a-f]{16}/) || [])[0];
188
+ const rid = (s.match(/r_[0-9a-f]{16}/) || [])[0];
189
+ if (cid && rid) return { cid, rid };
190
+ }
191
+ return {};
192
+ }
193
+
194
+ function buildInner(opts: { prompt: string; metadata: unknown[]; cidRid?: { cid: string; rid: string }; requestId: string }): unknown[] {
195
+ const inner: unknown[] = new Array(81).fill(null);
196
+ inner[0] = [opts.prompt, 0, null, null, null, null, 0];
197
+ inner[1] = ["en"];
198
+ inner[2] = opts.cidRid ? [opts.cidRid.cid, opts.cidRid.rid] : opts.metadata;
199
+ inner[3] = "!" + crypto.randomBytes(DR_TOKEN_BYTES).toString("base64url");
200
+ inner[4] = crypto.randomUUID().replace(/-/g, "");
201
+ inner[6] = [1];
202
+ inner[7] = 1;
203
+ inner[10] = 1;
204
+ inner[11] = 0;
205
+ inner[17] = [[0]];
206
+ inner[18] = 0;
207
+ inner[27] = 1;
208
+ inner[30] = [4];
209
+ inner[41] = [1];
210
+ inner[49] = 1; // deep research
211
+ inner[53] = 0;
212
+ inner[54] = [[[[[1]]]]];
213
+ inner[55] = [[1]];
214
+ inner[61] = [];
215
+ inner[68] = 1;
216
+ inner[79] = 1;
217
+ inner[80] = 1;
218
+ inner[59] = opts.requestId;
219
+ return inner;
220
+ }
221
+
222
+ export class DeepResearchError extends Error {
223
+ constructor(message: string) {
224
+ super(message);
225
+ this.name = "DeepResearchError";
226
+ }
227
+ }
228
+
229
+ /**
230
+ * Run the full DR cycle: plan turn → confirm turn ("Start research") → poll
231
+ * LIST_CONVERSATION_TURNS until the report text lands. `http` is injectable
232
+ * for tests; the default is a redirect-following node:https transport with a
233
+ * cookie jar.
234
+ */
235
+ export async function geminiDeepResearch(opts: DrOptions): Promise<DrResult> {
236
+ const http = opts.http ?? defaultHttp();
237
+ const deadline = Date.now() + (opts.timeoutMs ?? 600_000);
238
+ const checkAbort = (): void => {
239
+ if (opts.signal?.aborted) throw Object.assign(new Error("web_research aborted"), { name: "AbortError" });
240
+ };
241
+
242
+ // init: redirect-following page GET. SNlM0e may be absent on degraded
243
+ // sessions — StreamGenerate tolerates at="" (proven live); batchexecute
244
+ // polling will simply return empty until a live session provides it.
245
+ const jar = new Map<string, string>();
246
+ jar.set("__Secure-1PSID", opts.cookie.psid);
247
+ if (opts.cookie.psidts) jar.set("__Secure-1PSIDTS", opts.cookie.psidts);
248
+ const initRes = await http(DR_APP_URL, { method: "GET", headers: chromeHeaders({ accept: "text/html", Cookie: [...jar].map(([k, v]) => `${k}=${v}`).join("; ") }) });
249
+ for (const line of initRes.headers["set-cookie"] ?? []) {
250
+ const pair = line.split(";")[0];
251
+ const eq = pair.indexOf("=");
252
+ if (eq > 0) jar.set(pair.slice(0, eq).trim(), pair.slice(eq + 1).trim());
253
+ }
254
+ const cookie = [...jar].map(([k, v]) => `${k}=${v}`).join("; ");
255
+ const page = initRes.buf.toString("utf8");
256
+ const snlM0e = (page.match(/"SNlM0e":\s*"(.*?)"/) || [])[1] ?? "";
257
+ const bl = (page.match(/"cfb2h":\s*"(.*?)"/) || [])[1] ?? "";
258
+ const fsid = (page.match(/"FdrFJe":\s*"(.*?)"/) || [])[1] ?? "";
259
+
260
+ const drTurn = async (prompt: string, cidRid?: { cid: string; rid: string }): Promise<{ strings: string[]; frames: string[]; ids: { cid?: string; rid?: string } }> => {
261
+ checkAbort();
262
+ const requestId = crypto.randomUUID().toUpperCase();
263
+ const inner = buildInner({ prompt, metadata: ["", "", "", null, null, null, null, null, null, ""], cidRid, requestId });
264
+ const params = new URLSearchParams({ bl, hl: "en", _reqid: "100100", rt: "c" });
265
+ if (fsid) params.set("f.sid", fsid);
266
+ const body = new URLSearchParams({ at: snlM0e, "f.req": JSON.stringify([null, JSON.stringify(inner)]) }).toString();
267
+ const res = await http(`${DR_GENERATE_URL}?${params}`, {
268
+ method: "POST",
269
+ headers: chromeHeaders({ cookie, "content-type": "application/x-www-form-urlencoded;charset=utf-8", "x-same-domain": "1", "x-goog-ext-525005358-jspb": `["${requestId}",1]` }),
270
+ body,
271
+ });
272
+ if (res.status !== 200) throw new DeepResearchError(`deep research turn failed (HTTP ${res.status})`);
273
+ const frames = parseFrames(res.buf);
274
+ const strings = frameStrings(frames);
275
+ const ids = extractChatIds(strings);
276
+ if (!ids.cid) throw new DeepResearchError("deep research turn returned no chat id");
277
+ return { strings, frames, ids };
278
+ };
279
+
280
+ // turn 1: plan
281
+ const plan = await drTurn(opts.query);
282
+ const title = extractPlanTitle(plan.frames);
283
+ // turn 2: confirm — same chat, metadata [cid, rid]
284
+ const confirm = await drTurn(DR_CONFIRM_PROMPT, { cid: plan.ids.cid!, rid: plan.ids.rid! });
285
+
286
+ // poll: LIST_CONVERSATION_TURNS (hNvQHb) until the report text arrives.
287
+ // Plan/confirm transcripts reappear verbatim in poll output — exclude any
288
+ // string already seen in those turns so a plan transcript is never
289
+ // returned as the report.
290
+ // ponytail: exact-match exclusion; a real multi-turn poll fixture would
291
+ // allow turn-index filtering instead
292
+ const priorTurnStrings = new Set([...plan.strings, ...confirm.strings]);
293
+ const pollOnce = async (): Promise<string[]> => {
294
+ const fReq = JSON.stringify([[["hNvQHb", JSON.stringify([plan.ids.cid, 10, null, 1, [1], [4], null, 1]), null, "generic"]]]);
295
+ const params = new URLSearchParams({ bl, hl: "en", _reqid: "200100", rt: "c" });
296
+ const res = await http(`${DR_BATCH_URL}?${params}`, {
297
+ method: "POST",
298
+ headers: chromeHeaders({ cookie, "content-type": "application/x-www-form-urlencoded;charset=utf-8", "x-same-domain": "1" }),
299
+ body: new URLSearchParams({ at: snlM0e, "f.req": fReq }).toString(),
300
+ });
301
+ if (res.status === 401 || res.status === 403) {
302
+ // Hard auth rejection — unlike 200-with-empty (server fluctuation) this
303
+ // cannot become a report on a later poll; surface it instead of spinning
304
+ // until the deadline.
305
+ throw new DeepResearchError(`report poll rejected (HTTP ${res.status}) — session cannot read this conversation`);
306
+ }
307
+ if (res.status !== 200) return []; // 429/5xx: transient — keep polling
308
+ return frameStrings(parseFrames(res.buf)).filter((s) => s.length > 200 && !priorTurnStrings.has(s));
309
+ };
310
+
311
+ let reportStrings: string[] = [];
312
+ let pollFailure: string | null = null;
313
+ while (Date.now() < deadline) {
314
+ checkAbort();
315
+ try {
316
+ reportStrings = await pollOnce();
317
+ } catch (err) {
318
+ if ((err as Error).name === "AbortError") throw err;
319
+ pollFailure = err instanceof Error ? err.message : String(err);
320
+ break;
321
+ }
322
+ if (reportStrings.length) break;
323
+ const wait = Math.min(20_000, Math.max(0, deadline - Date.now()));
324
+ if (wait <= 0) break;
325
+ await abortableSleep(wait, opts.signal);
326
+ }
327
+
328
+ const text = reportStrings.join("\n\n");
329
+ const sources = [...new Set((text.match(/https?:\/\/[^\s<>()\[\]{}"'`]+/g) ?? []).map((u) => u.replace(/[.,;:!?)\]]+$/, "")))].slice(0, 30);
330
+ const result: DrResult = { title, text, sources };
331
+ if (!text) {
332
+ result.partial =
333
+ `Research executed ("${title ?? opts.query}") and confirmed ("${DR_CONFIRM_PROMPT}"), but the report could not be retrieved` +
334
+ (pollFailure ? ` (${pollFailure})` : " on this session (conversation read requires a live-session token)") +
335
+ `. The report remains available in the Gemini web history for chat ${plan.ids.cid}.`;
336
+ }
337
+ return result;
338
+ }