@humain/terminal 0.0.17 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (367) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/bun/cli.d.ts +3 -1
  3. package/dist/bun/cli.d.ts.map +1 -1
  4. package/dist/bun/cli.js +3 -8
  5. package/dist/bun/cli.js.map +1 -1
  6. package/dist/bun/runtime-setup.d.ts +2 -0
  7. package/dist/bun/runtime-setup.d.ts.map +1 -0
  8. package/dist/bun/runtime-setup.js +9 -0
  9. package/dist/bun/runtime-setup.js.map +1 -0
  10. package/dist/bun/sandbox-env-setup.d.ts +2 -0
  11. package/dist/bun/sandbox-env-setup.d.ts.map +1 -0
  12. package/dist/bun/sandbox-env-setup.js +4 -0
  13. package/dist/bun/sandbox-env-setup.js.map +1 -0
  14. package/dist/bundle/chunks/anthropic-messages-XULXUBIG.js +6 -0
  15. package/dist/bundle/chunks/{azure-openai-responses-ZN52D6YC.js → azure-openai-responses-JEG2XOYC.js} +1 -1
  16. package/dist/bundle/chunks/bedrock-converse-stream.js +6 -6
  17. package/dist/bundle/chunks/{chunk-ARF4OE6X.js → chunk-2LC3S3VV.js} +8 -8
  18. package/dist/bundle/chunks/chunk-43O5DDAH.js +31 -0
  19. package/dist/bundle/chunks/{chunk-H2O6VOXT.js → chunk-46DC2JD6.js} +2 -2
  20. package/dist/bundle/chunks/chunk-7ZC4UXSL.js +2 -0
  21. package/dist/bundle/chunks/{chunk-WJZ4KLGL.js → chunk-E6KP6V7F.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-PSKDLDLZ.js → chunk-HPPQHK3J.js} +3 -3
  23. package/dist/bundle/chunks/chunk-JUPSJTFQ.js +42 -0
  24. package/dist/bundle/chunks/chunk-PL7O7J4J.js +133 -0
  25. package/dist/bundle/chunks/{chunk-PFVS5ZYL.js → chunk-RM336IEI.js} +378 -369
  26. package/dist/bundle/chunks/chunk-USJZMAIR.js +2 -0
  27. package/dist/bundle/chunks/{extract-2L7ZVN7F.js → extract-TRW5FBY6.js} +2 -2
  28. package/dist/bundle/chunks/github-copilot.js +1 -1
  29. package/dist/bundle/chunks/{google-generative-ai-FF7M7XHT.js → google-generative-ai-OX6VSCA6.js} +1 -1
  30. package/dist/bundle/chunks/{google-vertex-YMUBFRBA.js → google-vertex-GW76GSS2.js} +1 -1
  31. package/dist/bundle/chunks/image-resize-worker.js +1 -1
  32. package/dist/bundle/chunks/{mistral-conversations-O4M7IQML.js → mistral-conversations-WXGXZOFJ.js} +1 -1
  33. package/dist/bundle/chunks/node-AUOGOBCN.js +2 -0
  34. package/dist/bundle/chunks/node-KOIP55YZ.js +16 -0
  35. package/dist/bundle/chunks/openai-codex-responses-NPLWP6ZC.js +10 -0
  36. package/dist/bundle/chunks/{openai-completions-L4AHDQ5D.js → openai-completions-OT2GTJKC.js} +3 -3
  37. package/dist/bundle/chunks/openai-responses-5A6CR7GI.js +2 -0
  38. package/dist/bundle/chunks/{openrouter-images-Y2PCWAQH.js → openrouter-images-YLQ4RJ2F.js} +1 -1
  39. package/dist/bundle/chunks/{pi-messages-57K43J6J.js → pi-messages-OJF77SY3.js} +1 -1
  40. package/dist/bundle/chunks/{undici-D6ABF53Q.js → undici-KA2LJNVT.js} +1 -1
  41. package/dist/bundle/chunks/webapi-RFAXLI2D.js +5 -0
  42. package/dist/bundle/cli.js +1 -1
  43. package/dist/bundle/index.js +1 -1
  44. package/dist/bundle/rpc-entry.js +1 -1
  45. package/dist/cli/config-selector.d.ts.map +1 -1
  46. package/dist/cli/config-selector.js +2 -1
  47. package/dist/cli/config-selector.js.map +1 -1
  48. package/dist/cli/setup.d.ts +2 -0
  49. package/dist/cli/setup.d.ts.map +1 -0
  50. package/dist/cli/setup.js +13 -0
  51. package/dist/cli/setup.js.map +1 -0
  52. package/dist/cli.js +2 -14
  53. package/dist/cli.js.map +1 -1
  54. package/dist/config.d.ts +1 -0
  55. package/dist/config.d.ts.map +1 -1
  56. package/dist/config.js +1 -0
  57. package/dist/config.js.map +1 -1
  58. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  59. package/dist/core/agent-session-runtime.js +15 -7
  60. package/dist/core/agent-session-runtime.js.map +1 -1
  61. package/dist/core/agent-session.d.ts +2 -6
  62. package/dist/core/agent-session.d.ts.map +1 -1
  63. package/dist/core/agent-session.js +14 -6
  64. package/dist/core/agent-session.js.map +1 -1
  65. package/dist/core/compaction/branch-summarization.d.ts +1 -1
  66. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  67. package/dist/core/compaction/branch-summarization.js +2 -1
  68. package/dist/core/compaction/branch-summarization.js.map +1 -1
  69. package/dist/core/extensions/loader.d.ts.map +1 -1
  70. package/dist/core/extensions/loader.js +1 -2
  71. package/dist/core/extensions/loader.js.map +1 -1
  72. package/dist/core/extensions/types.d.ts +8 -2
  73. package/dist/core/extensions/types.d.ts.map +1 -1
  74. package/dist/core/extensions/types.js.map +1 -1
  75. package/dist/core/http-dispatcher.d.ts.map +1 -1
  76. package/dist/core/http-dispatcher.js +2 -0
  77. package/dist/core/http-dispatcher.js.map +1 -1
  78. package/dist/core/keybindings.d.ts +5 -0
  79. package/dist/core/keybindings.d.ts.map +1 -1
  80. package/dist/core/keybindings.js +4 -0
  81. package/dist/core/keybindings.js.map +1 -1
  82. package/dist/core/messages.d.ts +1 -1
  83. package/dist/core/messages.d.ts.map +1 -1
  84. package/dist/core/messages.js.map +1 -1
  85. package/dist/core/model-config.d.ts +15 -0
  86. package/dist/core/model-config.d.ts.map +1 -1
  87. package/dist/core/model-config.js +3 -0
  88. package/dist/core/model-config.js.map +1 -1
  89. package/dist/core/model-runtime.d.ts +1 -0
  90. package/dist/core/model-runtime.d.ts.map +1 -1
  91. package/dist/core/model-runtime.js +5 -2
  92. package/dist/core/model-runtime.js.map +1 -1
  93. package/dist/core/provider-composer.d.ts.map +1 -1
  94. package/dist/core/provider-composer.js +8 -2
  95. package/dist/core/provider-composer.js.map +1 -1
  96. package/dist/core/session-manager.d.ts +3 -2
  97. package/dist/core/session-manager.d.ts.map +1 -1
  98. package/dist/core/session-manager.js +40 -13
  99. package/dist/core/session-manager.js.map +1 -1
  100. package/dist/core/settings-manager.js.map +1 -1
  101. package/dist/core/skills.d.ts +1 -1
  102. package/dist/core/skills.d.ts.map +1 -1
  103. package/dist/core/skills.js +4 -2
  104. package/dist/core/skills.js.map +1 -1
  105. package/dist/core/system-prompt.d.ts.map +1 -1
  106. package/dist/core/system-prompt.js +8 -9
  107. package/dist/core/system-prompt.js.map +1 -1
  108. package/dist/core/tools/bash.d.ts.map +1 -1
  109. package/dist/core/tools/bash.js +3 -120
  110. package/dist/core/tools/bash.js.map +1 -1
  111. package/dist/core/tools/edit.d.ts +1 -12
  112. package/dist/core/tools/edit.d.ts.map +1 -1
  113. package/dist/core/tools/edit.js +5 -163
  114. package/dist/core/tools/edit.js.map +1 -1
  115. package/dist/core/tools/find.d.ts.map +1 -1
  116. package/dist/core/tools/find.js +4 -55
  117. package/dist/core/tools/find.js.map +1 -1
  118. package/dist/core/tools/grep.d.ts.map +1 -1
  119. package/dist/core/tools/grep.js +4 -60
  120. package/dist/core/tools/grep.js.map +1 -1
  121. package/dist/core/tools/ls.d.ts.map +1 -1
  122. package/dist/core/tools/ls.js +4 -49
  123. package/dist/core/tools/ls.js.map +1 -1
  124. package/dist/core/tools/read.d.ts.map +1 -1
  125. package/dist/core/tools/read.js +4 -120
  126. package/dist/core/tools/read.js.map +1 -1
  127. package/dist/core/tools/renderers/bash.d.ts +12 -0
  128. package/dist/core/tools/renderers/bash.d.ts.map +1 -0
  129. package/dist/core/tools/renderers/bash.js +133 -0
  130. package/dist/core/tools/renderers/bash.js.map +1 -0
  131. package/dist/core/tools/renderers/edit.d.ts +23 -0
  132. package/dist/core/tools/renderers/edit.d.ts.map +1 -0
  133. package/dist/core/tools/renderers/edit.js +167 -0
  134. package/dist/core/tools/renderers/edit.js.map +1 -0
  135. package/dist/core/tools/renderers/find.d.ts +10 -0
  136. package/dist/core/tools/renderers/find.d.ts.map +1 -0
  137. package/dist/core/tools/renderers/find.js +64 -0
  138. package/dist/core/tools/renderers/find.js.map +1 -0
  139. package/dist/core/tools/renderers/grep.d.ts +10 -0
  140. package/dist/core/tools/renderers/grep.d.ts.map +1 -0
  141. package/dist/core/tools/renderers/grep.js +69 -0
  142. package/dist/core/tools/renderers/grep.js.map +1 -0
  143. package/dist/core/tools/renderers/index.d.ts +22 -0
  144. package/dist/core/tools/renderers/index.d.ts.map +1 -0
  145. package/dist/core/tools/renderers/index.js +48 -0
  146. package/dist/core/tools/renderers/index.js.map +1 -0
  147. package/dist/core/tools/renderers/ls.d.ts +10 -0
  148. package/dist/core/tools/renderers/ls.d.ts.map +1 -0
  149. package/dist/core/tools/renderers/ls.js +58 -0
  150. package/dist/core/tools/renderers/ls.js.map +1 -0
  151. package/dist/core/tools/renderers/read.d.ts +11 -0
  152. package/dist/core/tools/renderers/read.d.ts.map +1 -0
  153. package/dist/core/tools/renderers/read.js +129 -0
  154. package/dist/core/tools/renderers/read.js.map +1 -0
  155. package/dist/core/tools/renderers/write.d.ts +10 -0
  156. package/dist/core/tools/renderers/write.d.ts.map +1 -0
  157. package/dist/core/tools/renderers/write.js +152 -0
  158. package/dist/core/tools/renderers/write.js.map +1 -0
  159. package/dist/core/tools/subagent-worktree.d.ts +1 -0
  160. package/dist/core/tools/subagent-worktree.d.ts.map +1 -1
  161. package/dist/core/tools/subagent-worktree.js +25 -1
  162. package/dist/core/tools/subagent-worktree.js.map +1 -1
  163. package/dist/core/tools/subagent.d.ts.map +1 -1
  164. package/dist/core/tools/subagent.js +5 -2
  165. package/dist/core/tools/subagent.js.map +1 -1
  166. package/dist/core/tools/write.d.ts.map +1 -1
  167. package/dist/core/tools/write.js +5 -145
  168. package/dist/core/tools/write.js.map +1 -1
  169. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +51 -12
  170. package/dist/humain/mcp-adapter/vendor/package.json +2 -2
  171. package/dist/humain/web-access/vendor/curator-page.d.ts.map +1 -1
  172. package/dist/humain/web-access/vendor/curator-page.js +3 -1
  173. package/dist/humain/web-access/vendor/curator-page.js.map +1 -1
  174. package/dist/humain/web-access/vendor/curator-server.d.ts +2 -0
  175. package/dist/humain/web-access/vendor/curator-server.d.ts.map +1 -1
  176. package/dist/humain/web-access/vendor/curator-server.js +4 -2
  177. package/dist/humain/web-access/vendor/curator-server.js.map +1 -1
  178. package/dist/humain/web-access/vendor/gemini-search.d.ts +2 -2
  179. package/dist/humain/web-access/vendor/gemini-search.d.ts.map +1 -1
  180. package/dist/humain/web-access/vendor/gemini-search.js +11 -4
  181. package/dist/humain/web-access/vendor/gemini-search.js.map +1 -1
  182. package/dist/humain/web-access/vendor/github-extract.d.ts.map +1 -1
  183. package/dist/humain/web-access/vendor/github-extract.js +238 -1
  184. package/dist/humain/web-access/vendor/github-extract.js.map +1 -1
  185. package/dist/humain/web-access/vendor/index.d.ts.map +1 -1
  186. package/dist/humain/web-access/vendor/index.js +118 -64
  187. package/dist/humain/web-access/vendor/index.js.map +1 -1
  188. package/dist/humain/web-access/vendor/mistral-search.d.ts +4 -0
  189. package/dist/humain/web-access/vendor/mistral-search.d.ts.map +1 -0
  190. package/dist/humain/web-access/vendor/mistral-search.js +274 -0
  191. package/dist/humain/web-access/vendor/mistral-search.js.map +1 -0
  192. package/dist/humain/web-access/vendor/perplexity.d.ts.map +1 -1
  193. package/dist/humain/web-access/vendor/perplexity.js +12 -1
  194. package/dist/humain/web-access/vendor/perplexity.js.map +1 -1
  195. package/dist/humain/web-access/vendor/utils.d.ts.map +1 -1
  196. package/dist/humain/web-access/vendor/utils.js +1 -2
  197. package/dist/humain/web-access/vendor/utils.js.map +1 -1
  198. package/dist/humain/web-access/vendor/xai-search.d.ts.map +1 -1
  199. package/dist/humain/web-access/vendor/xai-search.js +92 -35
  200. package/dist/humain/web-access/vendor/xai-search.js.map +1 -1
  201. package/dist/index.d.ts +1 -1
  202. package/dist/index.d.ts.map +1 -1
  203. package/dist/index.js.map +1 -1
  204. package/dist/main.d.ts.map +1 -1
  205. package/dist/main.js +4 -1
  206. package/dist/main.js.map +1 -1
  207. package/dist/modes/interactive/chat-viewport.d.ts +20 -0
  208. package/dist/modes/interactive/chat-viewport.d.ts.map +1 -0
  209. package/dist/modes/interactive/chat-viewport.js +28 -0
  210. package/dist/modes/interactive/chat-viewport.js.map +1 -0
  211. package/dist/modes/interactive/components/assistant-message.d.ts +1 -0
  212. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  213. package/dist/modes/interactive/components/assistant-message.js +18 -10
  214. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  215. package/dist/modes/interactive/components/custom-editor.d.ts +10 -1
  216. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  217. package/dist/modes/interactive/components/custom-editor.js +37 -1
  218. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  219. package/dist/modes/interactive/components/index.d.ts +1 -1
  220. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  221. package/dist/modes/interactive/components/index.js.map +1 -1
  222. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  223. package/dist/modes/interactive/components/model-selector.js +8 -17
  224. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  225. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  226. package/dist/modes/interactive/components/scoped-models-selector.js +21 -23
  227. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  228. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  229. package/dist/modes/interactive/components/settings-selector.js +14 -10
  230. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  231. package/dist/modes/interactive/components/status-indicator.d.ts +3 -1
  232. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  233. package/dist/modes/interactive/components/status-indicator.js +10 -3
  234. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  235. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  236. package/dist/modes/interactive/components/thinking-selector.js +4 -4
  237. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  238. package/dist/modes/interactive/components/tool-execution.d.ts +21 -4
  239. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  240. package/dist/modes/interactive/components/tool-execution.js +34 -32
  241. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  242. package/dist/modes/interactive/components/trust-selector.js +2 -2
  243. package/dist/modes/interactive/components/trust-selector.js.map +1 -1
  244. package/dist/modes/interactive/interactive-mode.d.ts +8 -15
  245. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  246. package/dist/modes/interactive/interactive-mode.js +96 -81
  247. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  248. package/dist/modes/interactive/session-share.d.ts.map +1 -1
  249. package/dist/modes/interactive/session-share.js +8 -12
  250. package/dist/modes/interactive/session-share.js.map +1 -1
  251. package/dist/modes/interactive/theme/dark.json +2 -1
  252. package/dist/modes/interactive/theme/light.json +2 -1
  253. package/dist/modes/interactive/theme/theme-controller.d.ts +1 -0
  254. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
  255. package/dist/modes/interactive/theme/theme-controller.js +5 -0
  256. package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
  257. package/dist/modes/interactive/theme/theme-json.d.ts +84 -0
  258. package/dist/modes/interactive/theme/theme-json.d.ts.map +1 -0
  259. package/dist/modes/interactive/theme/theme-json.js +130 -0
  260. package/dist/modes/interactive/theme/theme-json.js.map +1 -0
  261. package/dist/modes/interactive/theme/theme-schema.json +6 -2
  262. package/dist/modes/interactive/theme/theme.d.ts +14 -5
  263. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  264. package/dist/modes/interactive/theme/theme.js +18 -119
  265. package/dist/modes/interactive/theme/theme.js.map +1 -1
  266. package/dist/modes/interactive/tui-renderer.d.ts +21 -0
  267. package/dist/modes/interactive/tui-renderer.d.ts.map +1 -0
  268. package/dist/modes/interactive/tui-renderer.js +66 -0
  269. package/dist/modes/interactive/tui-renderer.js.map +1 -0
  270. package/dist/utils/exif-orientation.d.ts.map +1 -1
  271. package/dist/utils/exif-orientation.js +2 -3
  272. package/dist/utils/exif-orientation.js.map +1 -1
  273. package/dist/utils/tools-manager.d.ts +1 -0
  274. package/dist/utils/tools-manager.d.ts.map +1 -1
  275. package/dist/utils/tools-manager.js +41 -19
  276. package/dist/utils/tools-manager.js.map +1 -1
  277. package/docs/containerization.md +45 -0
  278. package/docs/development.md +19 -0
  279. package/docs/environment-variables.md +2 -0
  280. package/docs/extensions.md +5 -2
  281. package/docs/keybindings.md +5 -2
  282. package/docs/models.md +4 -1
  283. package/docs/rpc.md +1 -1
  284. package/docs/sdk.md +5 -0
  285. package/docs/settings.md +3 -3
  286. package/docs/skills.md +1 -1
  287. package/docs/terminal-setup.md +15 -0
  288. package/docs/themes.md +8 -6
  289. package/docs/tui.md +19 -0
  290. package/examples/README.md +3 -0
  291. package/examples/extensions/custom-provider-anthropic/package-lock.json +84 -84
  292. package/examples/extensions/custom-provider-anthropic/package.json +17 -17
  293. package/examples/extensions/custom-provider-gitlab-duo/package.json +14 -14
  294. package/examples/extensions/dynamic-resources/dynamic.json +2 -0
  295. package/examples/extensions/gondolin/package-lock.json +8 -8
  296. package/examples/extensions/gondolin/package.json +1 -1
  297. package/examples/extensions/sandbox/package-lock.json +6 -6
  298. package/examples/extensions/sandbox/package.json +2 -2
  299. package/examples/extensions/with-deps/package-lock.json +29 -29
  300. package/examples/extensions/with-deps/package.json +20 -20
  301. package/examples/plugins/pi-example-plugin/README.md +38 -0
  302. package/examples/plugins/pi-example-plugin/package.json +10 -0
  303. package/examples/plugins/pi-example-plugin/src/contract.ts +13 -0
  304. package/examples/plugins/pi-example-plugin/src/session.ts +23 -0
  305. package/examples/plugins/pi-example-plugin/src/tui.ts +31 -0
  306. package/npm-shrinkwrap.json +772 -205
  307. package/package.json +31 -24
  308. package/src/humain/web-access/UPSTREAM.md +12 -1
  309. package/src/humain/web-access/upstream.json +4 -4
  310. package/dist/bundle/chunks/anthropic-messages-M4LCS3KH.js +0 -6
  311. package/dist/bundle/chunks/chunk-3VI4HD7D.js +0 -31
  312. package/dist/bundle/chunks/chunk-BOW22LW6.js +0 -42
  313. package/dist/bundle/chunks/chunk-CBHC6EL7.js +0 -133
  314. package/dist/bundle/chunks/chunk-JUUC5AZY.js +0 -2
  315. package/dist/bundle/chunks/node-ZHY4LHC7.js +0 -15
  316. package/dist/bundle/chunks/openai-codex-responses-HRVCDY54.js +0 -8
  317. package/dist/bundle/chunks/openai-responses-4MWLJHIK.js +0 -2
  318. package/dist/bundle/chunks/webapi-AFS5FDJJ.js +0 -5
  319. package/dist/bundle/client.js +0 -2
  320. package/dist/cli/experimental/auth.d.ts +0 -16
  321. package/dist/cli/experimental/auth.d.ts.map +0 -1
  322. package/dist/cli/experimental/auth.js +0 -13
  323. package/dist/cli/experimental/auth.js.map +0 -1
  324. package/dist/cli/experimental/cli.d.ts +0 -6
  325. package/dist/cli/experimental/cli.d.ts.map +0 -1
  326. package/dist/cli/experimental/cli.js +0 -5
  327. package/dist/cli/experimental/cli.js.map +0 -1
  328. package/dist/cli/experimental/command-options.d.ts +0 -17
  329. package/dist/cli/experimental/command-options.d.ts.map +0 -1
  330. package/dist/cli/experimental/command-options.js +0 -35
  331. package/dist/cli/experimental/command-options.js.map +0 -1
  332. package/dist/cli/experimental/command.d.ts +0 -63
  333. package/dist/cli/experimental/command.d.ts.map +0 -1
  334. package/dist/cli/experimental/command.js +0 -127
  335. package/dist/cli/experimental/command.js.map +0 -1
  336. package/dist/cli/experimental/commands/client.d.ts +0 -13
  337. package/dist/cli/experimental/commands/client.d.ts.map +0 -1
  338. package/dist/cli/experimental/commands/client.js +0 -25
  339. package/dist/cli/experimental/commands/client.js.map +0 -1
  340. package/dist/cli/experimental/commands/pi.d.ts +0 -15
  341. package/dist/cli/experimental/commands/pi.d.ts.map +0 -1
  342. package/dist/cli/experimental/commands/pi.js +0 -28
  343. package/dist/cli/experimental/commands/pi.js.map +0 -1
  344. package/dist/cli/experimental/commands/server.d.ts +0 -13
  345. package/dist/cli/experimental/commands/server.d.ts.map +0 -1
  346. package/dist/cli/experimental/commands/server.js +0 -25
  347. package/dist/cli/experimental/commands/server.js.map +0 -1
  348. package/dist/cli/experimental/transport-address.d.ts +0 -10
  349. package/dist/cli/experimental/transport-address.d.ts.map +0 -1
  350. package/dist/cli/experimental/transport-address.js +0 -38
  351. package/dist/cli/experimental/transport-address.js.map +0 -1
  352. package/dist/client/index.d.ts +0 -3
  353. package/dist/client/index.d.ts.map +0 -1
  354. package/dist/client/index.js +0 -3
  355. package/dist/client/index.js.map +0 -1
  356. package/dist/client/remote-session.d.ts +0 -53
  357. package/dist/client/remote-session.d.ts.map +0 -1
  358. package/dist/client/remote-session.js +0 -340
  359. package/dist/client/remote-session.js.map +0 -1
  360. package/dist/client/transcript.d.ts +0 -12
  361. package/dist/client/transcript.d.ts.map +0 -1
  362. package/dist/client/transcript.js +0 -98
  363. package/dist/client/transcript.js.map +0 -1
  364. package/dist/server/create-harness.d.ts +0 -26
  365. package/dist/server/create-harness.d.ts.map +0 -1
  366. package/dist/server/create-harness.js +0 -106
  367. package/dist/server/create-harness.js.map +0 -1
@@ -0,0 +1,2 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ var sessionResourceCleanups=new Set;function registerSessionResourceCleanup(cleanup){return sessionResourceCleanups.add(cleanup),()=>{sessionResourceCleanups.delete(cleanup)}}function cleanupSessionResources(sessionId){let errors=[];for(let cleanup of sessionResourceCleanups)try{cleanup(sessionId)}catch(error){errors.push(error)}if(errors.length>0)throw new AggregateError(errors,"Failed to cleanup session resources")}var MAX_SEQUENCE=(1n<<41n)-1n,lastOrdinaryTimestamp=-1,sequence;function uuidv7(timestampMs){let requestedTimestamp=timestampMs??Date.now();if(!Number.isInteger(requestedTimestamp)||requestedTimestamp<0||requestedTimestamp>0xffffffffffff)throw new RangeError(`UUIDv7 timestamp must be an integer between 0 and ${0xffffffffffff}`);let effectiveTimestamp=timestampMs===void 0?Math.max(requestedTimestamp,lastOrdinaryTimestamp):timestampMs;timestampMs===void 0&&(lastOrdinaryTimestamp=effectiveTimestamp);let bytes=new Uint8Array(16);if(globalThis.crypto.getRandomValues(bytes),sequence===void 0)sequence=BigInt(bytes[1])<<32n|BigInt(bytes[2])<<24n|BigInt(bytes[3])<<16n|BigInt(bytes[4])<<8n|BigInt(bytes[5]);else{if(sequence===MAX_SEQUENCE)throw new RangeError("UUIDv7 generator sequence exhausted");sequence++}let timestamp=BigInt(effectiveTimestamp);for(let index=5;index>=0;index--)bytes[index]=Number(timestamp>>BigInt((5-index)*8))&255;bytes[6]=112|Number(sequence>>37n&0x0fn),bytes[7]=Number(sequence>>29n&0xffn),bytes[8]=128|Number(sequence>>23n&0x3fn),bytes[9]=Number(sequence>>15n&0xffn),bytes[10]=Number(sequence>>7n&0xffn),bytes[11]=Number((sequence&0x7fn)<<1n)|bytes[11]&1;let hex=Array.from(bytes,byte=>byte.toString(16).padStart(2,"0"));return`${hex.slice(0,4).join("")}-${hex.slice(4,6).join("")}-${hex.slice(6,8).join("")}-${hex.slice(8,10).join("")}-${hex.slice(10).join("")}`}export{registerSessionResourceCleanup,cleanupSessionResources,uuidv7};
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{require_turndown_cjs}from"./chunk-BZQ53VGE.js";import{CredentialResolutionError,DEFAULT_MODEL,activityMonitor,assertAuthFetchUrl,authFetchRedirectGuard,checkGhAvailable,extractGitHub,extractWithFirecrawl,extractWithKagi,extractWithOllama,extractWithParallel,extractWithParallelMcp,extractWithQuerit,extractWithSearch1API,extractWithTinyFish,fetchGeminiApi,fetchRemoteUrl,formatSeconds,getApiKey,getBrowserCookiesForHosts,getLastBrowserCookieDiagnostic,getUploadBase,getVersionedApiBase,getWebSearchConfigPath,hasCredentialSource,isFirecrawlAvailable,isGatewayConfigured,isGeminiAdcAvailable,isGeminiApiAvailable,isGeminiApiAvailableWithVideo,isGeminiWebAvailable,isKagiExtractAvailable,isOllamaFetchAvailable,isParallelAvailable,isPerplexityAvailable,isQueritAvailable,isSearch1APIAvailable,isTimeoutError,isTinyFishAvailable,loadFetchContentDomainPolicy,loadSsrfConfig,mapFfmpegError,parseHTML,queryGeminiApiWithInlineData,queryGeminiApiWithVideo,queryWithCookies,readExecError,redactCredential,redactGeminiApiResponse,resizeImage,resolveCredential,searchWithPerplexity,showGhHint,trimErrorText,validateRemoteUrl}from"./chunk-ARF4OE6X.js";import"./chunk-MA4UUCYX.js";import{__commonJS,__toESM}from"./chunk-JXWJOIH4.js";var require_Readability=__commonJS({"node_modules/@mozilla/readability/Readability.js"(exports,module){function Readability2(doc,options){if(options&&options.documentElement)doc=options,options=arguments[2];else if(!doc||!doc.documentElement)throw new Error("First argument to Readability constructor should be a document object.");if(options=options||{},this._doc=doc,this._docJSDOMParser=this._doc.firstChild.__JSDOMParser__,this._articleTitle=null,this._articleByline=null,this._articleDir=null,this._articleSiteName=null,this._attempts=[],this._metadata={},this._debug=!!options.debug,this._maxElemsToParse=options.maxElemsToParse||this.DEFAULT_MAX_ELEMS_TO_PARSE,this._nbTopCandidates=options.nbTopCandidates||this.DEFAULT_N_TOP_CANDIDATES,this._charThreshold=options.charThreshold||this.DEFAULT_CHAR_THRESHOLD,this._classesToPreserve=this.CLASSES_TO_PRESERVE.concat(options.classesToPreserve||[]),this._keepClasses=!!options.keepClasses,this._serializer=options.serializer||function(el){return el.innerHTML},this._disableJSONLD=!!options.disableJSONLD,this._allowedVideoRegex=options.allowedVideoRegex||this.REGEXPS.videos,this._linkDensityModifier=options.linkDensityModifier||0,this._flags=this.FLAG_STRIP_UNLIKELYS|this.FLAG_WEIGHT_CLASSES|this.FLAG_CLEAN_CONDITIONALLY,this._debug){let logNode=function(node){if(node.nodeType==node.TEXT_NODE)return`${node.nodeName} ("${node.textContent}")`;let attrPairs=Array.from(node.attributes||[],function(attr){return`${attr.name}="${attr.value}"`}).join(" ");return`<${node.localName} ${attrPairs}>`};this.log=function(){if(typeof console<"u"){let args=Array.from(arguments,arg=>arg&&arg.nodeType==this.ELEMENT_NODE?logNode(arg):arg);args.unshift("Reader: (Readability)"),console.log(...args)}else if(typeof dump<"u"){var msg=Array.prototype.map.call(arguments,function(x){return x&&x.nodeName?logNode(x):x}).join(" ");dump("Reader: (Readability) "+msg+`
3
- `)}}}else this.log=function(){}}Readability2.prototype={FLAG_STRIP_UNLIKELYS:1,FLAG_WEIGHT_CLASSES:2,FLAG_CLEAN_CONDITIONALLY:4,ELEMENT_NODE:1,TEXT_NODE:3,DEFAULT_MAX_ELEMS_TO_PARSE:0,DEFAULT_N_TOP_CANDIDATES:5,DEFAULT_TAGS_TO_SCORE:"section,h2,h3,h4,h5,h6,p,td,pre".toUpperCase().split(","),DEFAULT_CHAR_THRESHOLD:500,REGEXPS:{unlikelyCandidates:/-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i,okMaybeItsACandidate:/and|article|body|column|content|main|shadow/i,positive:/article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story/i,negative:/-ad-|hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|footer|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|widget/i,extraneous:/print|archive|comment|discuss|e[\-]?mail|share|reply|all|login|sign|single|utility/i,byline:/byline|author|dateline|writtenby|p-author/i,replaceFonts:/<(\/?)font[^>]*>/gi,normalize:/\s{2,}/g,videos:/\/\/(www\.)?((dailymotion|youtube|youtube-nocookie|player\.vimeo|v\.qq)\.com|(archive|upload\.wikimedia)\.org|player\.twitch\.tv)/i,shareElements:/(\b|_)(share|sharedaddy)(\b|_)/i,nextLink:/(next|weiter|continue|>([^\|]|$)|»([^\|]|$))/i,prevLink:/(prev|earl|old|new|<|«)/i,tokenize:/\W+/g,whitespace:/^\s*$/,hasContent:/\S$/,hashUrl:/^#.+/,srcsetUrl:/(\S+)(\s+[\d.]+[xw])?(\s*(?:,|$))/g,b64DataUrl:/^data:\s*([^\s;,]+)\s*;\s*base64\s*,/i,commas:/\u002C|\u060C|\uFE50|\uFE10|\uFE11|\u2E41|\u2E34|\u2E32|\uFF0C/g,jsonLdArticleTypes:/^Article|AdvertiserContentArticle|NewsArticle|AnalysisNewsArticle|AskPublicNewsArticle|BackgroundNewsArticle|OpinionNewsArticle|ReportageNewsArticle|ReviewNewsArticle|Report|SatiricalArticle|ScholarlyArticle|MedicalScholarlyArticle|SocialMediaPosting|BlogPosting|LiveBlogPosting|DiscussionForumPosting|TechArticle|APIReference$/,adWords:/^(ad(vertising|vertisement)?|pub(licité)?|werb(ung)?|广告|Реклама|Anuncio)$/iu,loadingWords:/^((loading|正在加载|Загрузка|chargement|cargando)(…|\.\.\.)?)$/iu},UNLIKELY_ROLES:["menu","menubar","complementary","navigation","alert","alertdialog","dialog"],DIV_TO_P_ELEMS:new Set(["BLOCKQUOTE","DL","DIV","IMG","OL","P","PRE","TABLE","UL"]),ALTER_TO_DIV_EXCEPTIONS:["DIV","ARTICLE","SECTION","P","OL","UL"],PRESENTATIONAL_ATTRIBUTES:["align","background","bgcolor","border","cellpadding","cellspacing","frame","hspace","rules","style","valign","vspace"],DEPRECATED_SIZE_ATTRIBUTE_ELEMS:["TABLE","TH","TD","HR","PRE"],PHRASING_ELEMS:["ABBR","AUDIO","B","BDO","BR","BUTTON","CITE","CODE","DATA","DATALIST","DFN","EM","EMBED","I","IMG","INPUT","KBD","LABEL","MARK","MATH","METER","NOSCRIPT","OBJECT","OUTPUT","PROGRESS","Q","RUBY","SAMP","SCRIPT","SELECT","SMALL","SPAN","STRONG","SUB","SUP","TEXTAREA","TIME","VAR","WBR"],CLASSES_TO_PRESERVE:["page"],HTML_ESCAPE_MAP:{lt:"<",gt:">",amp:"&",quot:'"',apos:"'"},_postProcessContent(articleContent){this._fixRelativeUris(articleContent),this._simplifyNestedElements(articleContent),this._keepClasses||this._cleanClasses(articleContent)},_removeNodes(nodeList,filterFn){if(this._docJSDOMParser&&nodeList._isLiveNodeList)throw new Error("Do not pass live node lists to _removeNodes");for(var i=nodeList.length-1;i>=0;i--){var node=nodeList[i],parentNode=node.parentNode;parentNode&&(!filterFn||filterFn.call(this,node,i,nodeList))&&parentNode.removeChild(node)}},_replaceNodeTags(nodeList,newTagName){if(this._docJSDOMParser&&nodeList._isLiveNodeList)throw new Error("Do not pass live node lists to _replaceNodeTags");for(let node of nodeList)this._setNodeTag(node,newTagName)},_forEachNode(nodeList,fn){Array.prototype.forEach.call(nodeList,fn,this)},_findNode(nodeList,fn){return Array.prototype.find.call(nodeList,fn,this)},_someNode(nodeList,fn){return Array.prototype.some.call(nodeList,fn,this)},_everyNode(nodeList,fn){return Array.prototype.every.call(nodeList,fn,this)},_getAllNodesWithTag(node,tagNames){return node.querySelectorAll?node.querySelectorAll(tagNames.join(",")):[].concat.apply([],tagNames.map(function(tag){var collection=node.getElementsByTagName(tag);return Array.isArray(collection)?collection:Array.from(collection)}))},_cleanClasses(node){var classesToPreserve=this._classesToPreserve,className=(node.getAttribute("class")||"").split(/\s+/).filter(cls=>classesToPreserve.includes(cls)).join(" ");for(className?node.setAttribute("class",className):node.removeAttribute("class"),node=node.firstElementChild;node;node=node.nextElementSibling)this._cleanClasses(node)},_isUrl(str){try{return new URL(str),!0}catch{return!1}},_fixRelativeUris(articleContent){var baseURI=this._doc.baseURI,documentURI=this._doc.documentURI;function toAbsoluteURI(uri){if(baseURI==documentURI&&uri.charAt(0)=="#")return uri;try{return new URL(uri,baseURI).href}catch{}return uri}var links=this._getAllNodesWithTag(articleContent,["a"]);this._forEachNode(links,function(link){var href=link.getAttribute("href");if(href)if(href.indexOf("javascript:")===0)if(link.childNodes.length===1&&link.childNodes[0].nodeType===this.TEXT_NODE){var text=this._doc.createTextNode(link.textContent);link.parentNode.replaceChild(text,link)}else{for(var container=this._doc.createElement("span");link.firstChild;)container.appendChild(link.firstChild);link.parentNode.replaceChild(container,link)}else link.setAttribute("href",toAbsoluteURI(href))});var medias=this._getAllNodesWithTag(articleContent,["img","picture","figure","video","audio","source"]);this._forEachNode(medias,function(media){var src=media.getAttribute("src"),poster=media.getAttribute("poster"),srcset=media.getAttribute("srcset");if(src&&media.setAttribute("src",toAbsoluteURI(src)),poster&&media.setAttribute("poster",toAbsoluteURI(poster)),srcset){var newSrcset=srcset.replace(this.REGEXPS.srcsetUrl,function(_,p1,p2,p3){return toAbsoluteURI(p1)+(p2||"")+p3});media.setAttribute("srcset",newSrcset)}})},_simplifyNestedElements(articleContent){for(var node=articleContent;node;){if(node.parentNode&&["DIV","SECTION"].includes(node.tagName)&&!(node.id&&node.id.startsWith("readability"))){if(this._isElementWithoutContent(node)){node=this._removeAndGetNext(node);continue}else if(this._hasSingleTagInsideElement(node,"DIV")||this._hasSingleTagInsideElement(node,"SECTION")){for(var child=node.children[0],i=0;i<node.attributes.length;i++)child.setAttributeNode(node.attributes[i].cloneNode());node.parentNode.replaceChild(child,node),node=child;continue}}node=this._getNextNode(node)}},_getArticleTitle(){var doc=this._doc,curTitle="",origTitle="";try{curTitle=origTitle=doc.title.trim(),typeof curTitle!="string"&&(curTitle=origTitle=this._getInnerText(doc.getElementsByTagName("title")[0]))}catch{}var titleHadHierarchicalSeparators=!1;function wordCount(str){return str.split(/\s+/).length}if(/ [\|\-\\\/>»] /.test(curTitle)){titleHadHierarchicalSeparators=/ [\\\/>»] /.test(curTitle);let allSeparators=Array.from(origTitle.matchAll(/ [\|\-\\\/>»] /gi));curTitle=origTitle.substring(0,allSeparators.pop().index),wordCount(curTitle)<3&&(curTitle=origTitle.replace(/^[^\|\-\\\/>»]*[\|\-\\\/>»]/gi,""))}else if(curTitle.includes(": ")){var headings=this._getAllNodesWithTag(doc,["h1","h2"]),trimmedTitle=curTitle.trim(),match=this._someNode(headings,function(heading){return heading.textContent.trim()===trimmedTitle});match||(curTitle=origTitle.substring(origTitle.lastIndexOf(":")+1),wordCount(curTitle)<3?curTitle=origTitle.substring(origTitle.indexOf(":")+1):wordCount(origTitle.substr(0,origTitle.indexOf(":")))>5&&(curTitle=origTitle))}else if(curTitle.length>150||curTitle.length<15){var hOnes=doc.getElementsByTagName("h1");hOnes.length===1&&(curTitle=this._getInnerText(hOnes[0]))}curTitle=curTitle.trim().replace(this.REGEXPS.normalize," ");var curTitleWordCount=wordCount(curTitle);return curTitleWordCount<=4&&(!titleHadHierarchicalSeparators||curTitleWordCount!=wordCount(origTitle.replace(/[\|\-\\\/>»]+/g,""))-1)&&(curTitle=origTitle),curTitle},_prepDocument(){var doc=this._doc;this._removeNodes(this._getAllNodesWithTag(doc,["style"])),doc.body&&this._replaceBrs(doc.body),this._replaceNodeTags(this._getAllNodesWithTag(doc,["font"]),"SPAN")},_nextNode(node){for(var next=node;next&&next.nodeType!=this.ELEMENT_NODE&&this.REGEXPS.whitespace.test(next.textContent);)next=next.nextSibling;return next},_replaceBrs(elem){this._forEachNode(this._getAllNodesWithTag(elem,["br"]),function(br){for(var next=br.nextSibling,replaced=!1;(next=this._nextNode(next))&&next.tagName=="BR";){replaced=!0;var brSibling=next.nextSibling;next.remove(),next=brSibling}if(replaced){var p=this._doc.createElement("p");for(br.parentNode.replaceChild(p,br),next=p.nextSibling;next;){if(next.tagName=="BR"){var nextElem=this._nextNode(next.nextSibling);if(nextElem&&nextElem.tagName=="BR")break}if(!this._isPhrasingContent(next))break;var sibling=next.nextSibling;p.appendChild(next),next=sibling}for(;p.lastChild&&this._isWhitespace(p.lastChild);)p.lastChild.remove();p.parentNode.tagName==="P"&&this._setNodeTag(p.parentNode,"DIV")}})},_setNodeTag(node,tag){if(this.log("_setNodeTag",node,tag),this._docJSDOMParser)return node.localName=tag.toLowerCase(),node.tagName=tag.toUpperCase(),node;for(var replacement=node.ownerDocument.createElement(tag);node.firstChild;)replacement.appendChild(node.firstChild);node.parentNode.replaceChild(replacement,node),node.readability&&(replacement.readability=node.readability);for(var i=0;i<node.attributes.length;i++)replacement.setAttributeNode(node.attributes[i].cloneNode());return replacement},_prepArticle(articleContent){this._cleanStyles(articleContent),this._markDataTables(articleContent),this._fixLazyImages(articleContent),this._cleanConditionally(articleContent,"form"),this._cleanConditionally(articleContent,"fieldset"),this._clean(articleContent,"object"),this._clean(articleContent,"embed"),this._clean(articleContent,"footer"),this._clean(articleContent,"link"),this._clean(articleContent,"aside");var shareElementThreshold=this.DEFAULT_CHAR_THRESHOLD;this._forEachNode(articleContent.children,function(topCandidate){this._cleanMatchedNodes(topCandidate,function(node,matchString){return this.REGEXPS.shareElements.test(matchString)&&node.textContent.length<shareElementThreshold})}),this._clean(articleContent,"iframe"),this._clean(articleContent,"input"),this._clean(articleContent,"textarea"),this._clean(articleContent,"select"),this._clean(articleContent,"button"),this._cleanHeaders(articleContent),this._cleanConditionally(articleContent,"table"),this._cleanConditionally(articleContent,"ul"),this._cleanConditionally(articleContent,"div"),this._replaceNodeTags(this._getAllNodesWithTag(articleContent,["h1"]),"h2"),this._removeNodes(this._getAllNodesWithTag(articleContent,["p"]),function(paragraph){var contentElementCount=this._getAllNodesWithTag(paragraph,["img","embed","object","iframe"]).length;return contentElementCount===0&&!this._getInnerText(paragraph,!1)}),this._forEachNode(this._getAllNodesWithTag(articleContent,["br"]),function(br){var next=this._nextNode(br.nextSibling);next&&next.tagName=="P"&&br.remove()}),this._forEachNode(this._getAllNodesWithTag(articleContent,["table"]),function(table){var tbody=this._hasSingleTagInsideElement(table,"TBODY")?table.firstElementChild:table;if(this._hasSingleTagInsideElement(tbody,"TR")){var row=tbody.firstElementChild;if(this._hasSingleTagInsideElement(row,"TD")){var cell=row.firstElementChild;cell=this._setNodeTag(cell,this._everyNode(cell.childNodes,this._isPhrasingContent)?"P":"DIV"),table.parentNode.replaceChild(cell,table)}}})},_initializeNode(node){switch(node.readability={contentScore:0},node.tagName){case"DIV":node.readability.contentScore+=5;break;case"PRE":case"TD":case"BLOCKQUOTE":node.readability.contentScore+=3;break;case"ADDRESS":case"OL":case"UL":case"DL":case"DD":case"DT":case"LI":case"FORM":node.readability.contentScore-=3;break;case"H1":case"H2":case"H3":case"H4":case"H5":case"H6":case"TH":node.readability.contentScore-=5;break}node.readability.contentScore+=this._getClassWeight(node)},_removeAndGetNext(node){var nextNode=this._getNextNode(node,!0);return node.remove(),nextNode},_getNextNode(node,ignoreSelfAndKids){if(!ignoreSelfAndKids&&node.firstElementChild)return node.firstElementChild;if(node.nextElementSibling)return node.nextElementSibling;do node=node.parentNode;while(node&&!node.nextElementSibling);return node&&node.nextElementSibling},_textSimilarity(textA,textB){var tokensA=textA.toLowerCase().split(this.REGEXPS.tokenize).filter(Boolean),tokensB=textB.toLowerCase().split(this.REGEXPS.tokenize).filter(Boolean);if(!tokensA.length||!tokensB.length)return 0;var uniqTokensB=tokensB.filter(token=>!tokensA.includes(token)),distanceB=uniqTokensB.join(" ").length/tokensB.join(" ").length;return 1-distanceB},_isValidByline(node,matchString){var rel=node.getAttribute("rel"),itemprop=node.getAttribute("itemprop"),bylineLength=node.textContent.trim().length;return(rel==="author"||itemprop&&itemprop.includes("author")||this.REGEXPS.byline.test(matchString))&&!!bylineLength&&bylineLength<100},_getNodeAncestors(node,maxDepth){maxDepth=maxDepth||0;for(var i=0,ancestors=[];node.parentNode&&(ancestors.push(node.parentNode),!(maxDepth&&++i===maxDepth));)node=node.parentNode;return ancestors},_grabArticle(page){this.log("**** grabArticle ****");var doc=this._doc,isPaging=page!==null;if(page=page||this._doc.body,!page)return this.log("No body found in document. Abort."),null;for(var pageCacheHtml=page.innerHTML;;){this.log("Starting grabArticle loop");var stripUnlikelyCandidates=this._flagIsActive(this.FLAG_STRIP_UNLIKELYS),elementsToScore=[],node=this._doc.documentElement;let shouldRemoveTitleHeader=!0;for(;node;){node.tagName==="HTML"&&(this._articleLang=node.getAttribute("lang"));var matchString=node.className+" "+node.id;if(!this._isProbablyVisible(node)){this.log("Removing hidden node - "+matchString),node=this._removeAndGetNext(node);continue}if(node.getAttribute("aria-modal")=="true"&&node.getAttribute("role")=="dialog"){node=this._removeAndGetNext(node);continue}if(!this._articleByline&&!this._metadata.byline&&this._isValidByline(node,matchString)){for(var endOfSearchMarkerNode=this._getNextNode(node,!0),next=this._getNextNode(node),itemPropNameNode=null;next&&next!=endOfSearchMarkerNode;){var itemprop=next.getAttribute("itemprop");if(itemprop&&itemprop.includes("name")){itemPropNameNode=next;break}else next=this._getNextNode(next)}this._articleByline=(itemPropNameNode??node).textContent.trim(),node=this._removeAndGetNext(node);continue}if(shouldRemoveTitleHeader&&this._headerDuplicatesTitle(node)){this.log("Removing header: ",node.textContent.trim(),this._articleTitle.trim()),shouldRemoveTitleHeader=!1,node=this._removeAndGetNext(node);continue}if(stripUnlikelyCandidates){if(this.REGEXPS.unlikelyCandidates.test(matchString)&&!this.REGEXPS.okMaybeItsACandidate.test(matchString)&&!this._hasAncestorTag(node,"table")&&!this._hasAncestorTag(node,"code")&&node.tagName!=="BODY"&&node.tagName!=="A"){this.log("Removing unlikely candidate - "+matchString),node=this._removeAndGetNext(node);continue}if(this.UNLIKELY_ROLES.includes(node.getAttribute("role"))){this.log("Removing content with role "+node.getAttribute("role")+" - "+matchString),node=this._removeAndGetNext(node);continue}}if((node.tagName==="DIV"||node.tagName==="SECTION"||node.tagName==="HEADER"||node.tagName==="H1"||node.tagName==="H2"||node.tagName==="H3"||node.tagName==="H4"||node.tagName==="H5"||node.tagName==="H6")&&this._isElementWithoutContent(node)){node=this._removeAndGetNext(node);continue}if(this.DEFAULT_TAGS_TO_SCORE.includes(node.tagName)&&elementsToScore.push(node),node.tagName==="DIV"){for(var p=null,childNode=node.firstChild;childNode;){var nextSibling=childNode.nextSibling;if(this._isPhrasingContent(childNode))p!==null?p.appendChild(childNode):this._isWhitespace(childNode)||(p=doc.createElement("p"),node.replaceChild(p,childNode),p.appendChild(childNode));else if(p!==null){for(;p.lastChild&&this._isWhitespace(p.lastChild);)p.lastChild.remove();p=null}childNode=nextSibling}if(this._hasSingleTagInsideElement(node,"P")&&this._getLinkDensity(node)<.25){var newNode=node.children[0];node.parentNode.replaceChild(newNode,node),node=newNode,elementsToScore.push(node)}else this._hasChildBlockElement(node)||(node=this._setNodeTag(node,"P"),elementsToScore.push(node))}node=this._getNextNode(node)}var candidates=[];this._forEachNode(elementsToScore,function(elementToScore){if(!(!elementToScore.parentNode||typeof elementToScore.parentNode.tagName>"u")){var innerText=this._getInnerText(elementToScore);if(!(innerText.length<25)){var ancestors2=this._getNodeAncestors(elementToScore,5);if(ancestors2.length!==0){var contentScore=0;contentScore+=1,contentScore+=innerText.split(this.REGEXPS.commas).length,contentScore+=Math.min(Math.floor(innerText.length/100),3),this._forEachNode(ancestors2,function(ancestor,level){if(!(!ancestor.tagName||!ancestor.parentNode||typeof ancestor.parentNode.tagName>"u")){if(typeof ancestor.readability>"u"&&(this._initializeNode(ancestor),candidates.push(ancestor)),level===0)var scoreDivider=1;else level===1?scoreDivider=2:scoreDivider=level*3;ancestor.readability.contentScore+=contentScore/scoreDivider}})}}}});for(var topCandidates=[],c=0,cl=candidates.length;c<cl;c+=1){var candidate=candidates[c],candidateScore=candidate.readability.contentScore*(1-this._getLinkDensity(candidate));candidate.readability.contentScore=candidateScore,this.log("Candidate:",candidate,"with score "+candidateScore);for(var t=0;t<this._nbTopCandidates;t++){var aTopCandidate=topCandidates[t];if(!aTopCandidate||candidateScore>aTopCandidate.readability.contentScore){topCandidates.splice(t,0,candidate),topCandidates.length>this._nbTopCandidates&&topCandidates.pop();break}}}var topCandidate=topCandidates[0]||null,neededToCreateTopCandidate=!1,parentOfTopCandidate;if(topCandidate===null||topCandidate.tagName==="BODY"){for(topCandidate=doc.createElement("DIV"),neededToCreateTopCandidate=!0;page.firstChild;)this.log("Moving child out:",page.firstChild),topCandidate.appendChild(page.firstChild);page.appendChild(topCandidate),this._initializeNode(topCandidate)}else if(topCandidate){for(var alternativeCandidateAncestors=[],i=1;i<topCandidates.length;i++)topCandidates[i].readability.contentScore/topCandidate.readability.contentScore>=.75&&alternativeCandidateAncestors.push(this._getNodeAncestors(topCandidates[i]));var MINIMUM_TOPCANDIDATES=3;if(alternativeCandidateAncestors.length>=MINIMUM_TOPCANDIDATES)for(parentOfTopCandidate=topCandidate.parentNode;parentOfTopCandidate.tagName!=="BODY";){for(var listsContainingThisAncestor=0,ancestorIndex=0;ancestorIndex<alternativeCandidateAncestors.length&&listsContainingThisAncestor<MINIMUM_TOPCANDIDATES;ancestorIndex++)listsContainingThisAncestor+=Number(alternativeCandidateAncestors[ancestorIndex].includes(parentOfTopCandidate));if(listsContainingThisAncestor>=MINIMUM_TOPCANDIDATES){topCandidate=parentOfTopCandidate;break}parentOfTopCandidate=parentOfTopCandidate.parentNode}topCandidate.readability||this._initializeNode(topCandidate),parentOfTopCandidate=topCandidate.parentNode;for(var lastScore=topCandidate.readability.contentScore,scoreThreshold=lastScore/3;parentOfTopCandidate.tagName!=="BODY";){if(!parentOfTopCandidate.readability){parentOfTopCandidate=parentOfTopCandidate.parentNode;continue}var parentScore=parentOfTopCandidate.readability.contentScore;if(parentScore<scoreThreshold)break;if(parentScore>lastScore){topCandidate=parentOfTopCandidate;break}lastScore=parentOfTopCandidate.readability.contentScore,parentOfTopCandidate=parentOfTopCandidate.parentNode}for(parentOfTopCandidate=topCandidate.parentNode;parentOfTopCandidate.tagName!="BODY"&&parentOfTopCandidate.children.length==1;)topCandidate=parentOfTopCandidate,parentOfTopCandidate=topCandidate.parentNode;topCandidate.readability||this._initializeNode(topCandidate)}var articleContent=doc.createElement("DIV");isPaging&&(articleContent.id="readability-content");var siblingScoreThreshold=Math.max(10,topCandidate.readability.contentScore*.2);parentOfTopCandidate=topCandidate.parentNode;for(var siblings=parentOfTopCandidate.children,s=0,sl=siblings.length;s<sl;s++){var sibling=siblings[s],append=!1;if(this.log("Looking at sibling node:",sibling,sibling.readability?"with score "+sibling.readability.contentScore:""),this.log("Sibling has score",sibling.readability?sibling.readability.contentScore:"Unknown"),sibling===topCandidate)append=!0;else{var contentBonus=0;if(sibling.className===topCandidate.className&&topCandidate.className!==""&&(contentBonus+=topCandidate.readability.contentScore*.2),sibling.readability&&sibling.readability.contentScore+contentBonus>=siblingScoreThreshold)append=!0;else if(sibling.nodeName==="P"){var linkDensity=this._getLinkDensity(sibling),nodeContent=this._getInnerText(sibling),nodeLength=nodeContent.length;(nodeLength>80&&linkDensity<.25||nodeLength<80&&nodeLength>0&&linkDensity===0&&nodeContent.search(/\.( |$)/)!==-1)&&(append=!0)}}append&&(this.log("Appending node:",sibling),this.ALTER_TO_DIV_EXCEPTIONS.includes(sibling.nodeName)||(this.log("Altering sibling:",sibling,"to div."),sibling=this._setNodeTag(sibling,"DIV")),articleContent.appendChild(sibling),siblings=parentOfTopCandidate.children,s-=1,sl-=1)}if(this._debug&&this.log("Article content pre-prep: "+articleContent.innerHTML),this._prepArticle(articleContent),this._debug&&this.log("Article content post-prep: "+articleContent.innerHTML),neededToCreateTopCandidate)topCandidate.id="readability-page-1",topCandidate.className="page";else{var div=doc.createElement("DIV");for(div.id="readability-page-1",div.className="page";articleContent.firstChild;)div.appendChild(articleContent.firstChild);articleContent.appendChild(div)}this._debug&&this.log("Article content after paging: "+articleContent.innerHTML);var parseSuccessful=!0,textLength=this._getInnerText(articleContent,!0).length;if(textLength<this._charThreshold)if(parseSuccessful=!1,page.innerHTML=pageCacheHtml,this._attempts.push({articleContent,textLength}),this._flagIsActive(this.FLAG_STRIP_UNLIKELYS))this._removeFlag(this.FLAG_STRIP_UNLIKELYS);else if(this._flagIsActive(this.FLAG_WEIGHT_CLASSES))this._removeFlag(this.FLAG_WEIGHT_CLASSES);else if(this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY))this._removeFlag(this.FLAG_CLEAN_CONDITIONALLY);else{if(this._attempts.sort(function(a,b){return b.textLength-a.textLength}),!this._attempts[0].textLength)return null;articleContent=this._attempts[0].articleContent,parseSuccessful=!0}if(parseSuccessful){var ancestors=[parentOfTopCandidate,topCandidate].concat(this._getNodeAncestors(parentOfTopCandidate));return this._someNode(ancestors,function(ancestor){if(!ancestor.tagName)return!1;var articleDir=ancestor.getAttribute("dir");return articleDir?(this._articleDir=articleDir,!0):!1}),articleContent}}},_unescapeHtmlEntities(str){if(!str)return str;var htmlEscapeMap=this.HTML_ESCAPE_MAP;return str.replace(/&(quot|amp|apos|lt|gt);/g,function(_,tag){return htmlEscapeMap[tag]}).replace(/&#(?:x([0-9a-f]+)|([0-9]+));/gi,function(_,hex,numStr){var num=parseInt(hex||numStr,hex?16:10);return(num==0||num>1114111||num>=55296&&num<=57343)&&(num=65533),String.fromCodePoint(num)})},_getJSONLD(doc){var scripts=this._getAllNodesWithTag(doc,["script"]),metadata;return this._forEachNode(scripts,function(jsonLdElement){if(!metadata&&jsonLdElement.getAttribute("type")==="application/ld+json")try{var content=jsonLdElement.textContent.replace(/^\s*<!\[CDATA\[|\]\]>\s*$/g,""),parsed=JSON.parse(content);if(Array.isArray(parsed)&&(parsed=parsed.find(it=>it["@type"]&&it["@type"].match(this.REGEXPS.jsonLdArticleTypes)),!parsed))return;var schemaDotOrgRegex=/^https?\:\/\/schema\.org\/?$/,matches=typeof parsed["@context"]=="string"&&parsed["@context"].match(schemaDotOrgRegex)||typeof parsed["@context"]=="object"&&typeof parsed["@context"]["@vocab"]=="string"&&parsed["@context"]["@vocab"].match(schemaDotOrgRegex);if(!matches||(!parsed["@type"]&&Array.isArray(parsed["@graph"])&&(parsed=parsed["@graph"].find(it=>(it["@type"]||"").match(this.REGEXPS.jsonLdArticleTypes))),!parsed||!parsed["@type"]||!parsed["@type"].match(this.REGEXPS.jsonLdArticleTypes)))return;if(metadata={},typeof parsed.name=="string"&&typeof parsed.headline=="string"&&parsed.name!==parsed.headline){var title=this._getArticleTitle(),nameMatches=this._textSimilarity(parsed.name,title)>.75,headlineMatches=this._textSimilarity(parsed.headline,title)>.75;headlineMatches&&!nameMatches?metadata.title=parsed.headline:metadata.title=parsed.name}else typeof parsed.name=="string"?metadata.title=parsed.name.trim():typeof parsed.headline=="string"&&(metadata.title=parsed.headline.trim());parsed.author&&(typeof parsed.author.name=="string"?metadata.byline=parsed.author.name.trim():Array.isArray(parsed.author)&&parsed.author[0]&&typeof parsed.author[0].name=="string"&&(metadata.byline=parsed.author.filter(function(author){return author&&typeof author.name=="string"}).map(function(author){return author.name.trim()}).join(", "))),typeof parsed.description=="string"&&(metadata.excerpt=parsed.description.trim()),parsed.publisher&&typeof parsed.publisher.name=="string"&&(metadata.siteName=parsed.publisher.name.trim()),typeof parsed.datePublished=="string"&&(metadata.datePublished=parsed.datePublished.trim())}catch(err){this.log(err.message)}}),metadata||{}},_getArticleMetadata(jsonld){var metadata={},values={},metaElements=this._doc.getElementsByTagName("meta"),propertyPattern=/\s*(article|dc|dcterm|og|twitter)\s*:\s*(author|creator|description|published_time|title|site_name)\s*/gi,namePattern=/^\s*(?:(dc|dcterm|og|twitter|parsely|weibo:(article|webpage))\s*[-\.:]\s*)?(author|creator|pub-date|description|title|site_name)\s*$/i;this._forEachNode(metaElements,function(element){var elementName=element.getAttribute("name"),elementProperty=element.getAttribute("property"),content=element.getAttribute("content");if(content){var matches=null,name=null;elementProperty&&(matches=elementProperty.match(propertyPattern),matches&&(name=matches[0].toLowerCase().replace(/\s/g,""),values[name]=content.trim())),!matches&&elementName&&namePattern.test(elementName)&&(name=elementName,content&&(name=name.toLowerCase().replace(/\s/g,"").replace(/\./g,":"),values[name]=content.trim()))}}),metadata.title=jsonld.title||values["dc:title"]||values["dcterm:title"]||values["og:title"]||values["weibo:article:title"]||values["weibo:webpage:title"]||values.title||values["twitter:title"]||values["parsely-title"],metadata.title||(metadata.title=this._getArticleTitle());let articleAuthor=typeof values["article:author"]=="string"&&!this._isUrl(values["article:author"])?values["article:author"]:void 0;return metadata.byline=jsonld.byline||values["dc:creator"]||values["dcterm:creator"]||values.author||values["parsely-author"]||articleAuthor,metadata.excerpt=jsonld.excerpt||values["dc:description"]||values["dcterm:description"]||values["og:description"]||values["weibo:article:description"]||values["weibo:webpage:description"]||values.description||values["twitter:description"],metadata.siteName=jsonld.siteName||values["og:site_name"],metadata.publishedTime=jsonld.datePublished||values["article:published_time"]||values["parsely-pub-date"]||null,metadata.title=this._unescapeHtmlEntities(metadata.title),metadata.byline=this._unescapeHtmlEntities(metadata.byline),metadata.excerpt=this._unescapeHtmlEntities(metadata.excerpt),metadata.siteName=this._unescapeHtmlEntities(metadata.siteName),metadata.publishedTime=this._unescapeHtmlEntities(metadata.publishedTime),metadata},_isSingleImage(node){for(;node;){if(node.tagName==="IMG")return!0;if(node.children.length!==1||node.textContent.trim()!=="")return!1;node=node.children[0]}return!1},_unwrapNoscriptImages(doc){var imgs=Array.from(doc.getElementsByTagName("img"));this._forEachNode(imgs,function(img){for(var i=0;i<img.attributes.length;i++){var attr=img.attributes[i];switch(attr.name){case"src":case"srcset":case"data-src":case"data-srcset":return}if(/\.(jpg|jpeg|png|webp)/i.test(attr.value))return}img.remove()});var noscripts=Array.from(doc.getElementsByTagName("noscript"));this._forEachNode(noscripts,function(noscript){if(this._isSingleImage(noscript)){var tmp=doc.createElement("div");tmp.innerHTML=noscript.innerHTML;var prevElement=noscript.previousElementSibling;if(prevElement&&this._isSingleImage(prevElement)){var prevImg=prevElement;prevImg.tagName!=="IMG"&&(prevImg=prevElement.getElementsByTagName("img")[0]);for(var newImg=tmp.getElementsByTagName("img")[0],i=0;i<prevImg.attributes.length;i++){var attr=prevImg.attributes[i];if(attr.value!==""&&(attr.name==="src"||attr.name==="srcset"||/\.(jpg|jpeg|png|webp)/i.test(attr.value))){if(newImg.getAttribute(attr.name)===attr.value)continue;var attrName=attr.name;newImg.hasAttribute(attrName)&&(attrName="data-old-"+attrName),newImg.setAttribute(attrName,attr.value)}}noscript.parentNode.replaceChild(tmp.firstElementChild,prevElement)}}})},_removeScripts(doc){this._removeNodes(this._getAllNodesWithTag(doc,["script","noscript"]))},_hasSingleTagInsideElement(element,tag){return element.children.length!=1||element.children[0].tagName!==tag?!1:!this._someNode(element.childNodes,function(node){return node.nodeType===this.TEXT_NODE&&this.REGEXPS.hasContent.test(node.textContent)})},_isElementWithoutContent(node){return node.nodeType===this.ELEMENT_NODE&&!node.textContent.trim().length&&(!node.children.length||node.children.length==node.getElementsByTagName("br").length+node.getElementsByTagName("hr").length)},_hasChildBlockElement(element){return this._someNode(element.childNodes,function(node){return this.DIV_TO_P_ELEMS.has(node.tagName)||this._hasChildBlockElement(node)})},_isPhrasingContent(node){return node.nodeType===this.TEXT_NODE||this.PHRASING_ELEMS.includes(node.tagName)||(node.tagName==="A"||node.tagName==="DEL"||node.tagName==="INS")&&this._everyNode(node.childNodes,this._isPhrasingContent)},_isWhitespace(node){return node.nodeType===this.TEXT_NODE&&node.textContent.trim().length===0||node.nodeType===this.ELEMENT_NODE&&node.tagName==="BR"},_getInnerText(e,normalizeSpaces2){normalizeSpaces2=typeof normalizeSpaces2>"u"?!0:normalizeSpaces2;var textContent=e.textContent.trim();return normalizeSpaces2?textContent.replace(this.REGEXPS.normalize," "):textContent},_getCharCount(e,s){return s=s||",",this._getInnerText(e).split(s).length-1},_cleanStyles(e){if(!(!e||e.tagName.toLowerCase()==="svg")){for(var i=0;i<this.PRESENTATIONAL_ATTRIBUTES.length;i++)e.removeAttribute(this.PRESENTATIONAL_ATTRIBUTES[i]);this.DEPRECATED_SIZE_ATTRIBUTE_ELEMS.includes(e.tagName)&&(e.removeAttribute("width"),e.removeAttribute("height"));for(var cur=e.firstElementChild;cur!==null;)this._cleanStyles(cur),cur=cur.nextElementSibling}},_getLinkDensity(element){var textLength=this._getInnerText(element).length;if(textLength===0)return 0;var linkLength=0;return this._forEachNode(element.getElementsByTagName("a"),function(linkNode){var href=linkNode.getAttribute("href"),coefficient=href&&this.REGEXPS.hashUrl.test(href)?.3:1;linkLength+=this._getInnerText(linkNode).length*coefficient}),linkLength/textLength},_getClassWeight(e){if(!this._flagIsActive(this.FLAG_WEIGHT_CLASSES))return 0;var weight=0;return typeof e.className=="string"&&e.className!==""&&(this.REGEXPS.negative.test(e.className)&&(weight-=25),this.REGEXPS.positive.test(e.className)&&(weight+=25)),typeof e.id=="string"&&e.id!==""&&(this.REGEXPS.negative.test(e.id)&&(weight-=25),this.REGEXPS.positive.test(e.id)&&(weight+=25)),weight},_clean(e,tag){var isEmbed=["object","embed","iframe"].includes(tag);this._removeNodes(this._getAllNodesWithTag(e,[tag]),function(element){if(isEmbed){for(var i=0;i<element.attributes.length;i++)if(this._allowedVideoRegex.test(element.attributes[i].value))return!1;if(element.tagName==="object"&&this._allowedVideoRegex.test(element.innerHTML))return!1}return!0})},_hasAncestorTag(node,tagName,maxDepth,filterFn){maxDepth=maxDepth||3,tagName=tagName.toUpperCase();for(var depth=0;node.parentNode;){if(maxDepth>0&&depth>maxDepth)return!1;if(node.parentNode.tagName===tagName&&(!filterFn||filterFn(node.parentNode)))return!0;node=node.parentNode,depth++}return!1},_getRowAndColumnCount(table){for(var rows=0,columns=0,trs=table.getElementsByTagName("tr"),i=0;i<trs.length;i++){var rowspan=trs[i].getAttribute("rowspan")||0;rowspan&&(rowspan=parseInt(rowspan,10)),rows+=rowspan||1;for(var columnsInThisRow=0,cells=trs[i].getElementsByTagName("td"),j=0;j<cells.length;j++){var colspan=cells[j].getAttribute("colspan")||0;colspan&&(colspan=parseInt(colspan,10)),columnsInThisRow+=colspan||1}columns=Math.max(columns,columnsInThisRow)}return{rows,columns}},_markDataTables(root){for(var tables=root.getElementsByTagName("table"),i=0;i<tables.length;i++){var table=tables[i],role=table.getAttribute("role");if(role=="presentation"){table._readabilityDataTable=!1;continue}var datatable=table.getAttribute("datatable");if(datatable=="0"){table._readabilityDataTable=!1;continue}var summary=table.getAttribute("summary");if(summary){table._readabilityDataTable=!0;continue}var caption=table.getElementsByTagName("caption")[0];if(caption&&caption.childNodes.length){table._readabilityDataTable=!0;continue}var dataTableDescendants=["col","colgroup","tfoot","thead","th"],descendantExists=function(tag){return!!table.getElementsByTagName(tag)[0]};if(dataTableDescendants.some(descendantExists)){this.log("Data table because found data-y descendant"),table._readabilityDataTable=!0;continue}if(table.getElementsByTagName("table")[0]){table._readabilityDataTable=!1;continue}var sizeInfo=this._getRowAndColumnCount(table);if(sizeInfo.columns==1||sizeInfo.rows==1){table._readabilityDataTable=!1;continue}if(sizeInfo.rows>=10||sizeInfo.columns>4){table._readabilityDataTable=!0;continue}table._readabilityDataTable=sizeInfo.rows*sizeInfo.columns>10}},_fixLazyImages(root){this._forEachNode(this._getAllNodesWithTag(root,["img","picture","figure"]),function(elem){if(elem.src&&this.REGEXPS.b64DataUrl.test(elem.src)){var parts=this.REGEXPS.b64DataUrl.exec(elem.src);if(parts[1]==="image/svg+xml")return;for(var srcCouldBeRemoved=!1,i=0;i<elem.attributes.length;i++){var attr=elem.attributes[i];if(attr.name!=="src"&&/\.(jpg|jpeg|png|webp)/i.test(attr.value)){srcCouldBeRemoved=!0;break}}if(srcCouldBeRemoved){var b64starts=parts[0].length,b64length=elem.src.length-b64starts;b64length<133&&elem.removeAttribute("src")}}if(!((elem.src||elem.srcset&&elem.srcset!="null")&&!elem.className.toLowerCase().includes("lazy"))){for(var j=0;j<elem.attributes.length;j++)if(attr=elem.attributes[j],!(attr.name==="src"||attr.name==="srcset"||attr.name==="alt")){var copyTo=null;if(/\.(jpg|jpeg|png|webp)\s+\d/.test(attr.value)?copyTo="srcset":/^\s*\S+\.(jpg|jpeg|png|webp)\S*\s*$/.test(attr.value)&&(copyTo="src"),copyTo){if(elem.tagName==="IMG"||elem.tagName==="PICTURE")elem.setAttribute(copyTo,attr.value);else if(elem.tagName==="FIGURE"&&!this._getAllNodesWithTag(elem,["img","picture"]).length){var img=this._doc.createElement("img");img.setAttribute(copyTo,attr.value),elem.appendChild(img)}}}}})},_getTextDensity(e,tags){var textLength=this._getInnerText(e,!0).length;if(textLength===0)return 0;var childrenLength=0,children=this._getAllNodesWithTag(e,tags);return this._forEachNode(children,child=>childrenLength+=this._getInnerText(child,!0).length),childrenLength/textLength},_cleanConditionally(e,tag){this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)&&this._removeNodes(this._getAllNodesWithTag(e,[tag]),function(node){var isDataTable=function(t){return t._readabilityDataTable},isList=tag==="ul"||tag==="ol";if(!isList){var listLength=0,listNodes=this._getAllNodesWithTag(node,["ul","ol"]);this._forEachNode(listNodes,list=>listLength+=this._getInnerText(list).length),isList=listLength/this._getInnerText(node).length>.9}if(tag==="table"&&isDataTable(node)||this._hasAncestorTag(node,"table",-1,isDataTable)||this._hasAncestorTag(node,"code")||[...node.getElementsByTagName("table")].some(tbl=>tbl._readabilityDataTable))return!1;var weight=this._getClassWeight(node);this.log("Cleaning Conditionally",node);var contentScore=0;if(weight+contentScore<0)return!0;if(this._getCharCount(node,",")<10){for(var p=node.getElementsByTagName("p").length,img=node.getElementsByTagName("img").length,li=node.getElementsByTagName("li").length-100,input=node.getElementsByTagName("input").length,headingDensity=this._getTextDensity(node,["h1","h2","h3","h4","h5","h6"]),embedCount=0,embeds=this._getAllNodesWithTag(node,["object","embed","iframe"]),i=0;i<embeds.length;i++){for(var j=0;j<embeds[i].attributes.length;j++)if(this._allowedVideoRegex.test(embeds[i].attributes[j].value))return!1;if(embeds[i].tagName==="object"&&this._allowedVideoRegex.test(embeds[i].innerHTML))return!1;embedCount++}var innerText=this._getInnerText(node);if(this.REGEXPS.adWords.test(innerText)||this.REGEXPS.loadingWords.test(innerText))return!0;var contentLength=innerText.length,linkDensity=this._getLinkDensity(node),textishTags=["SPAN","LI","TD"].concat(Array.from(this.DIV_TO_P_ELEMS)),textDensity=this._getTextDensity(node,textishTags),isFigureChild=this._hasAncestorTag(node,"figure"),haveToRemove=(()=>{let errs=[];return!isFigureChild&&img>1&&p/img<.5&&errs.push(`Bad p to img ratio (img=${img}, p=${p})`),!isList&&li>p&&errs.push(`Too many li's outside of a list. (li=${li} > p=${p})`),input>Math.floor(p/3)&&errs.push(`Too many inputs per p. (input=${input}, p=${p})`),!isList&&!isFigureChild&&headingDensity<.9&&contentLength<25&&(img===0||img>2)&&linkDensity>0&&errs.push(`Suspiciously short. (headingDensity=${headingDensity}, img=${img}, linkDensity=${linkDensity})`),!isList&&weight<25&&linkDensity>.2+this._linkDensityModifier&&errs.push(`Low weight and a little linky. (linkDensity=${linkDensity})`),weight>=25&&linkDensity>.5+this._linkDensityModifier&&errs.push(`High weight and mostly links. (linkDensity=${linkDensity})`),(embedCount===1&&contentLength<75||embedCount>1)&&errs.push(`Suspicious embed. (embedCount=${embedCount}, contentLength=${contentLength})`),img===0&&textDensity===0&&errs.push(`No useful content. (img=${img}, textDensity=${textDensity})`),errs.length?(this.log("Checks failed",errs),!0):!1})();if(isList&&haveToRemove){for(var x=0;x<node.children.length;x++)if(node.children[x].children.length>1)return haveToRemove;let li_count=node.getElementsByTagName("li").length;if(img==li_count)return!1}return haveToRemove}return!1})},_cleanMatchedNodes(e,filter){for(var endOfSearchMarkerNode=this._getNextNode(e,!0),next=this._getNextNode(e);next&&next!=endOfSearchMarkerNode;)filter.call(this,next,next.className+" "+next.id)?next=this._removeAndGetNext(next):next=this._getNextNode(next)},_cleanHeaders(e){let headingNodes=this._getAllNodesWithTag(e,["h1","h2"]);this._removeNodes(headingNodes,function(node){let shouldRemove=this._getClassWeight(node)<0;return shouldRemove&&this.log("Removing header with low class weight:",node),shouldRemove})},_headerDuplicatesTitle(node){if(node.tagName!="H1"&&node.tagName!="H2")return!1;var heading=this._getInnerText(node,!1);return this.log("Evaluating similarity of header:",heading,this._articleTitle),this._textSimilarity(this._articleTitle,heading)>.75},_flagIsActive(flag){return(this._flags&flag)>0},_removeFlag(flag){this._flags=this._flags&~flag},_isProbablyVisible(node){return(!node.style||node.style.display!="none")&&(!node.style||node.style.visibility!="hidden")&&!node.hasAttribute("hidden")&&(!node.hasAttribute("aria-hidden")||node.getAttribute("aria-hidden")!="true"||node.className&&node.className.includes&&node.className.includes("fallback-image"))},parse(){if(this._maxElemsToParse>0){var numTags=this._doc.getElementsByTagName("*").length;if(numTags>this._maxElemsToParse)throw new Error("Aborting parsing document; "+numTags+" elements found")}this._unwrapNoscriptImages(this._doc);var jsonLd=this._disableJSONLD?{}:this._getJSONLD(this._doc);this._removeScripts(this._doc),this._prepDocument();var metadata=this._getArticleMetadata(jsonLd);this._metadata=metadata,this._articleTitle=metadata.title;var articleContent=this._grabArticle();if(!articleContent)return null;if(this.log("Grabbed: "+articleContent.innerHTML),this._postProcessContent(articleContent),!metadata.excerpt){var paragraphs=articleContent.getElementsByTagName("p");paragraphs.length&&(metadata.excerpt=paragraphs[0].textContent.trim())}var textContent=articleContent.textContent;return{title:this._articleTitle,byline:metadata.byline||this._articleByline,dir:this._articleDir,lang:this._articleLang,content:this._serializer(articleContent),textContent,length:textContent.length,excerpt:metadata.excerpt,siteName:metadata.siteName||this._articleSiteName,publishedTime:metadata.publishedTime}}};typeof module=="object"&&(module.exports=Readability2)}});var require_Readability_readerable=__commonJS({"node_modules/@mozilla/readability/Readability-readerable.js"(exports,module){var REGEXPS={unlikelyCandidates:/-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i,okMaybeItsACandidate:/and|article|body|column|content|main|shadow/i};function isNodeVisible(node){return(!node.style||node.style.display!="none")&&!node.hasAttribute("hidden")&&(!node.hasAttribute("aria-hidden")||node.getAttribute("aria-hidden")!="true"||node.className&&node.className.includes&&node.className.includes("fallback-image"))}function isProbablyReaderable(doc,options={}){typeof options=="function"&&(options={visibilityChecker:options});var defaultOptions={minScore:20,minContentLength:140,visibilityChecker:isNodeVisible};options=Object.assign(defaultOptions,options);var nodes=doc.querySelectorAll("p, pre, article"),brNodes=doc.querySelectorAll("div > br");if(brNodes.length){var set=new Set(nodes);[].forEach.call(brNodes,function(node){set.add(node.parentNode)}),nodes=Array.from(set)}var score=0;return[].some.call(nodes,function(node){if(!options.visibilityChecker(node))return!1;var matchString=node.className+" "+node.id;if(REGEXPS.unlikelyCandidates.test(matchString)&&!REGEXPS.okMaybeItsACandidate.test(matchString)||node.matches("li p"))return!1;var textContentLength=node.textContent.trim().length;return textContentLength<options.minContentLength?!1:(score+=Math.sqrt(textContentLength-options.minContentLength),score>options.minScore)})}typeof module=="object"&&(module.exports=isProbablyReaderable)}});var require_readability=__commonJS({"node_modules/@mozilla/readability/index.js"(exports,module){var Readability2=require_Readability(),isProbablyReaderable=require_Readability_readerable();module.exports={Readability:Readability2,isProbablyReaderable}}});var import_readability=__toESM(require_readability(),1);import{existsSync as existsSync8,readFileSync as readFileSync8}from"node:fs";var import_turndown=__toESM(require_turndown_cjs(),1);var Node=class{value;next;constructor(value){this.value=value}},Queue=class{#head;#tail;#size;constructor(){this.clear()}enqueue(value){let node=new Node(value);this.#head?(this.#tail.next=node,this.#tail=node):(this.#head=node,this.#tail=node),this.#size++}dequeue(){let current=this.#head;if(current)return this.#head=this.#head.next,this.#size--,this.#head||(this.#tail=void 0),current.value}peek(){if(this.#head)return this.#head.value}clear(){this.#head=void 0,this.#tail=void 0,this.#size=0}get size(){return this.#size}*[Symbol.iterator](){let current=this.#head;for(;current;)yield current.value,current=current.next}*drain(){for(;this.#head;)yield this.dequeue()}};function pLimit(concurrency){let rejectOnClear=!1;if(typeof concurrency=="object"&&({concurrency,rejectOnClear=!1}=concurrency),validateConcurrency(concurrency),typeof rejectOnClear!="boolean")throw new TypeError("Expected `rejectOnClear` to be a boolean");let queue=new Queue,activeCount=0,resumeNext=()=>{activeCount<concurrency&&queue.size>0&&(activeCount++,queue.dequeue().run())},next=()=>{activeCount--,resumeNext()},run=async(function_,resolve2,arguments_)=>{let result=(async()=>function_(...arguments_))();resolve2(result);try{await result}catch{}next()},enqueue=(function_,resolve2,reject,arguments_)=>{let queueItem={reject};new Promise(internalResolve=>{queueItem.run=internalResolve,queue.enqueue(queueItem)}).then(run.bind(void 0,function_,resolve2,arguments_)),activeCount<concurrency&&resumeNext()},generator=(function_,...arguments_)=>new Promise((resolve2,reject)=>{enqueue(function_,resolve2,reject,arguments_)});return Object.defineProperties(generator,{activeCount:{get:()=>activeCount},pendingCount:{get:()=>queue.size},clearQueue:{value(){if(!rejectOnClear){queue.clear();return}let abortError=AbortSignal.abort().reason;for(;queue.size>0;)queue.dequeue().reject(abortError)}},concurrency:{get:()=>concurrency,set(newConcurrency){validateConcurrency(newConcurrency),concurrency=newConcurrency,queueMicrotask(()=>{for(;activeCount<concurrency&&queue.size>0;)resumeNext()})}},map:{async value(iterable,function_){let promises=Array.from(iterable,(value,index)=>generator(function_,value,index));return Promise.all(promises)}}}),generator}function validateConcurrency(concurrency){if(!((Number.isInteger(concurrency)||concurrency===Number.POSITIVE_INFINITY)&&concurrency>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up")}function extractRSCContent(html){if(!html.includes("self.__next_f.push"))return null;let chunkMap=new Map,scriptRegex=/<script>self\.__next_f\.push\(\[1,"([\s\S]*?)"\]\)<\/script>/g;for(let match of html.matchAll(scriptRegex)){let content2;try{content2=JSON.parse('"'+match[1]+'"')}catch{continue}for(let line of content2.split(`
2
+ import{require_turndown_cjs}from"./chunk-BZQ53VGE.js";import{CredentialResolutionError,DEFAULT_MODEL,activityMonitor,assertAuthFetchUrl,authFetchRedirectGuard,checkGhAvailable,extractGitHub,extractWithFirecrawl,extractWithKagi,extractWithOllama,extractWithParallel,extractWithParallelMcp,extractWithQuerit,extractWithSearch1API,extractWithTinyFish,fetchGeminiApi,fetchRemoteUrl,formatSeconds,getApiKey,getBrowserCookiesForHosts,getLastBrowserCookieDiagnostic,getUploadBase,getVersionedApiBase,getWebSearchConfigPath,hasCredentialSource,isFirecrawlAvailable,isGatewayConfigured,isGeminiAdcAvailable,isGeminiApiAvailable,isGeminiApiAvailableWithVideo,isGeminiWebAvailable,isKagiExtractAvailable,isOllamaFetchAvailable,isParallelAvailable,isPerplexityAvailable,isQueritAvailable,isSearch1APIAvailable,isTimeoutError,isTinyFishAvailable,loadFetchContentDomainPolicy,loadSsrfConfig,mapFfmpegError,pLimit,parseHTML,queryGeminiApiWithInlineData,queryGeminiApiWithVideo,queryWithCookies,readExecError,redactCredential,redactGeminiApiResponse,resizeImage,resolveCredential,searchWithPerplexity,showGhHint,trimErrorText,validateRemoteUrl}from"./chunk-2LC3S3VV.js";import"./chunk-MA4UUCYX.js";import{__commonJS,__toESM}from"./chunk-JXWJOIH4.js";var require_Readability=__commonJS({"node_modules/@mozilla/readability/Readability.js"(exports,module){function Readability2(doc,options){if(options&&options.documentElement)doc=options,options=arguments[2];else if(!doc||!doc.documentElement)throw new Error("First argument to Readability constructor should be a document object.");if(options=options||{},this._doc=doc,this._docJSDOMParser=this._doc.firstChild.__JSDOMParser__,this._articleTitle=null,this._articleByline=null,this._articleDir=null,this._articleSiteName=null,this._attempts=[],this._metadata={},this._debug=!!options.debug,this._maxElemsToParse=options.maxElemsToParse||this.DEFAULT_MAX_ELEMS_TO_PARSE,this._nbTopCandidates=options.nbTopCandidates||this.DEFAULT_N_TOP_CANDIDATES,this._charThreshold=options.charThreshold||this.DEFAULT_CHAR_THRESHOLD,this._classesToPreserve=this.CLASSES_TO_PRESERVE.concat(options.classesToPreserve||[]),this._keepClasses=!!options.keepClasses,this._serializer=options.serializer||function(el){return el.innerHTML},this._disableJSONLD=!!options.disableJSONLD,this._allowedVideoRegex=options.allowedVideoRegex||this.REGEXPS.videos,this._linkDensityModifier=options.linkDensityModifier||0,this._flags=this.FLAG_STRIP_UNLIKELYS|this.FLAG_WEIGHT_CLASSES|this.FLAG_CLEAN_CONDITIONALLY,this._debug){let logNode=function(node){if(node.nodeType==node.TEXT_NODE)return`${node.nodeName} ("${node.textContent}")`;let attrPairs=Array.from(node.attributes||[],function(attr){return`${attr.name}="${attr.value}"`}).join(" ");return`<${node.localName} ${attrPairs}>`};this.log=function(){if(typeof console<"u"){let args=Array.from(arguments,arg=>arg&&arg.nodeType==this.ELEMENT_NODE?logNode(arg):arg);args.unshift("Reader: (Readability)"),console.log(...args)}else if(typeof dump<"u"){var msg=Array.prototype.map.call(arguments,function(x){return x&&x.nodeName?logNode(x):x}).join(" ");dump("Reader: (Readability) "+msg+`
3
+ `)}}}else this.log=function(){}}Readability2.prototype={FLAG_STRIP_UNLIKELYS:1,FLAG_WEIGHT_CLASSES:2,FLAG_CLEAN_CONDITIONALLY:4,ELEMENT_NODE:1,TEXT_NODE:3,DEFAULT_MAX_ELEMS_TO_PARSE:0,DEFAULT_N_TOP_CANDIDATES:5,DEFAULT_TAGS_TO_SCORE:"section,h2,h3,h4,h5,h6,p,td,pre".toUpperCase().split(","),DEFAULT_CHAR_THRESHOLD:500,REGEXPS:{unlikelyCandidates:/-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i,okMaybeItsACandidate:/and|article|body|column|content|main|shadow/i,positive:/article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story/i,negative:/-ad-|hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|footer|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|widget/i,extraneous:/print|archive|comment|discuss|e[\-]?mail|share|reply|all|login|sign|single|utility/i,byline:/byline|author|dateline|writtenby|p-author/i,replaceFonts:/<(\/?)font[^>]*>/gi,normalize:/\s{2,}/g,videos:/\/\/(www\.)?((dailymotion|youtube|youtube-nocookie|player\.vimeo|v\.qq)\.com|(archive|upload\.wikimedia)\.org|player\.twitch\.tv)/i,shareElements:/(\b|_)(share|sharedaddy)(\b|_)/i,nextLink:/(next|weiter|continue|>([^\|]|$)|»([^\|]|$))/i,prevLink:/(prev|earl|old|new|<|«)/i,tokenize:/\W+/g,whitespace:/^\s*$/,hasContent:/\S$/,hashUrl:/^#.+/,srcsetUrl:/(\S+)(\s+[\d.]+[xw])?(\s*(?:,|$))/g,b64DataUrl:/^data:\s*([^\s;,]+)\s*;\s*base64\s*,/i,commas:/\u002C|\u060C|\uFE50|\uFE10|\uFE11|\u2E41|\u2E34|\u2E32|\uFF0C/g,jsonLdArticleTypes:/^Article|AdvertiserContentArticle|NewsArticle|AnalysisNewsArticle|AskPublicNewsArticle|BackgroundNewsArticle|OpinionNewsArticle|ReportageNewsArticle|ReviewNewsArticle|Report|SatiricalArticle|ScholarlyArticle|MedicalScholarlyArticle|SocialMediaPosting|BlogPosting|LiveBlogPosting|DiscussionForumPosting|TechArticle|APIReference$/,adWords:/^(ad(vertising|vertisement)?|pub(licité)?|werb(ung)?|广告|Реклама|Anuncio)$/iu,loadingWords:/^((loading|正在加载|Загрузка|chargement|cargando)(…|\.\.\.)?)$/iu},UNLIKELY_ROLES:["menu","menubar","complementary","navigation","alert","alertdialog","dialog"],DIV_TO_P_ELEMS:new Set(["BLOCKQUOTE","DL","DIV","IMG","OL","P","PRE","TABLE","UL"]),ALTER_TO_DIV_EXCEPTIONS:["DIV","ARTICLE","SECTION","P","OL","UL"],PRESENTATIONAL_ATTRIBUTES:["align","background","bgcolor","border","cellpadding","cellspacing","frame","hspace","rules","style","valign","vspace"],DEPRECATED_SIZE_ATTRIBUTE_ELEMS:["TABLE","TH","TD","HR","PRE"],PHRASING_ELEMS:["ABBR","AUDIO","B","BDO","BR","BUTTON","CITE","CODE","DATA","DATALIST","DFN","EM","EMBED","I","IMG","INPUT","KBD","LABEL","MARK","MATH","METER","NOSCRIPT","OBJECT","OUTPUT","PROGRESS","Q","RUBY","SAMP","SCRIPT","SELECT","SMALL","SPAN","STRONG","SUB","SUP","TEXTAREA","TIME","VAR","WBR"],CLASSES_TO_PRESERVE:["page"],HTML_ESCAPE_MAP:{lt:"<",gt:">",amp:"&",quot:'"',apos:"'"},_postProcessContent(articleContent){this._fixRelativeUris(articleContent),this._simplifyNestedElements(articleContent),this._keepClasses||this._cleanClasses(articleContent)},_removeNodes(nodeList,filterFn){if(this._docJSDOMParser&&nodeList._isLiveNodeList)throw new Error("Do not pass live node lists to _removeNodes");for(var i=nodeList.length-1;i>=0;i--){var node=nodeList[i],parentNode=node.parentNode;parentNode&&(!filterFn||filterFn.call(this,node,i,nodeList))&&parentNode.removeChild(node)}},_replaceNodeTags(nodeList,newTagName){if(this._docJSDOMParser&&nodeList._isLiveNodeList)throw new Error("Do not pass live node lists to _replaceNodeTags");for(let node of nodeList)this._setNodeTag(node,newTagName)},_forEachNode(nodeList,fn){Array.prototype.forEach.call(nodeList,fn,this)},_findNode(nodeList,fn){return Array.prototype.find.call(nodeList,fn,this)},_someNode(nodeList,fn){return Array.prototype.some.call(nodeList,fn,this)},_everyNode(nodeList,fn){return Array.prototype.every.call(nodeList,fn,this)},_getAllNodesWithTag(node,tagNames){return node.querySelectorAll?node.querySelectorAll(tagNames.join(",")):[].concat.apply([],tagNames.map(function(tag){var collection=node.getElementsByTagName(tag);return Array.isArray(collection)?collection:Array.from(collection)}))},_cleanClasses(node){var classesToPreserve=this._classesToPreserve,className=(node.getAttribute("class")||"").split(/\s+/).filter(cls=>classesToPreserve.includes(cls)).join(" ");for(className?node.setAttribute("class",className):node.removeAttribute("class"),node=node.firstElementChild;node;node=node.nextElementSibling)this._cleanClasses(node)},_isUrl(str){try{return new URL(str),!0}catch{return!1}},_fixRelativeUris(articleContent){var baseURI=this._doc.baseURI,documentURI=this._doc.documentURI;function toAbsoluteURI(uri){if(baseURI==documentURI&&uri.charAt(0)=="#")return uri;try{return new URL(uri,baseURI).href}catch{}return uri}var links=this._getAllNodesWithTag(articleContent,["a"]);this._forEachNode(links,function(link){var href=link.getAttribute("href");if(href)if(href.indexOf("javascript:")===0)if(link.childNodes.length===1&&link.childNodes[0].nodeType===this.TEXT_NODE){var text=this._doc.createTextNode(link.textContent);link.parentNode.replaceChild(text,link)}else{for(var container=this._doc.createElement("span");link.firstChild;)container.appendChild(link.firstChild);link.parentNode.replaceChild(container,link)}else link.setAttribute("href",toAbsoluteURI(href))});var medias=this._getAllNodesWithTag(articleContent,["img","picture","figure","video","audio","source"]);this._forEachNode(medias,function(media){var src=media.getAttribute("src"),poster=media.getAttribute("poster"),srcset=media.getAttribute("srcset");if(src&&media.setAttribute("src",toAbsoluteURI(src)),poster&&media.setAttribute("poster",toAbsoluteURI(poster)),srcset){var newSrcset=srcset.replace(this.REGEXPS.srcsetUrl,function(_,p1,p2,p3){return toAbsoluteURI(p1)+(p2||"")+p3});media.setAttribute("srcset",newSrcset)}})},_simplifyNestedElements(articleContent){for(var node=articleContent;node;){if(node.parentNode&&["DIV","SECTION"].includes(node.tagName)&&!(node.id&&node.id.startsWith("readability"))){if(this._isElementWithoutContent(node)){node=this._removeAndGetNext(node);continue}else if(this._hasSingleTagInsideElement(node,"DIV")||this._hasSingleTagInsideElement(node,"SECTION")){for(var child=node.children[0],i=0;i<node.attributes.length;i++)child.setAttributeNode(node.attributes[i].cloneNode());node.parentNode.replaceChild(child,node),node=child;continue}}node=this._getNextNode(node)}},_getArticleTitle(){var doc=this._doc,curTitle="",origTitle="";try{curTitle=origTitle=doc.title.trim(),typeof curTitle!="string"&&(curTitle=origTitle=this._getInnerText(doc.getElementsByTagName("title")[0]))}catch{}var titleHadHierarchicalSeparators=!1;function wordCount(str){return str.split(/\s+/).length}if(/ [\|\-\\\/>»] /.test(curTitle)){titleHadHierarchicalSeparators=/ [\\\/>»] /.test(curTitle);let allSeparators=Array.from(origTitle.matchAll(/ [\|\-\\\/>»] /gi));curTitle=origTitle.substring(0,allSeparators.pop().index),wordCount(curTitle)<3&&(curTitle=origTitle.replace(/^[^\|\-\\\/>»]*[\|\-\\\/>»]/gi,""))}else if(curTitle.includes(": ")){var headings=this._getAllNodesWithTag(doc,["h1","h2"]),trimmedTitle=curTitle.trim(),match=this._someNode(headings,function(heading){return heading.textContent.trim()===trimmedTitle});match||(curTitle=origTitle.substring(origTitle.lastIndexOf(":")+1),wordCount(curTitle)<3?curTitle=origTitle.substring(origTitle.indexOf(":")+1):wordCount(origTitle.substr(0,origTitle.indexOf(":")))>5&&(curTitle=origTitle))}else if(curTitle.length>150||curTitle.length<15){var hOnes=doc.getElementsByTagName("h1");hOnes.length===1&&(curTitle=this._getInnerText(hOnes[0]))}curTitle=curTitle.trim().replace(this.REGEXPS.normalize," ");var curTitleWordCount=wordCount(curTitle);return curTitleWordCount<=4&&(!titleHadHierarchicalSeparators||curTitleWordCount!=wordCount(origTitle.replace(/[\|\-\\\/>»]+/g,""))-1)&&(curTitle=origTitle),curTitle},_prepDocument(){var doc=this._doc;this._removeNodes(this._getAllNodesWithTag(doc,["style"])),doc.body&&this._replaceBrs(doc.body),this._replaceNodeTags(this._getAllNodesWithTag(doc,["font"]),"SPAN")},_nextNode(node){for(var next=node;next&&next.nodeType!=this.ELEMENT_NODE&&this.REGEXPS.whitespace.test(next.textContent);)next=next.nextSibling;return next},_replaceBrs(elem){this._forEachNode(this._getAllNodesWithTag(elem,["br"]),function(br){for(var next=br.nextSibling,replaced=!1;(next=this._nextNode(next))&&next.tagName=="BR";){replaced=!0;var brSibling=next.nextSibling;next.remove(),next=brSibling}if(replaced){var p=this._doc.createElement("p");for(br.parentNode.replaceChild(p,br),next=p.nextSibling;next;){if(next.tagName=="BR"){var nextElem=this._nextNode(next.nextSibling);if(nextElem&&nextElem.tagName=="BR")break}if(!this._isPhrasingContent(next))break;var sibling=next.nextSibling;p.appendChild(next),next=sibling}for(;p.lastChild&&this._isWhitespace(p.lastChild);)p.lastChild.remove();p.parentNode.tagName==="P"&&this._setNodeTag(p.parentNode,"DIV")}})},_setNodeTag(node,tag){if(this.log("_setNodeTag",node,tag),this._docJSDOMParser)return node.localName=tag.toLowerCase(),node.tagName=tag.toUpperCase(),node;for(var replacement=node.ownerDocument.createElement(tag);node.firstChild;)replacement.appendChild(node.firstChild);node.parentNode.replaceChild(replacement,node),node.readability&&(replacement.readability=node.readability);for(var i=0;i<node.attributes.length;i++)replacement.setAttributeNode(node.attributes[i].cloneNode());return replacement},_prepArticle(articleContent){this._cleanStyles(articleContent),this._markDataTables(articleContent),this._fixLazyImages(articleContent),this._cleanConditionally(articleContent,"form"),this._cleanConditionally(articleContent,"fieldset"),this._clean(articleContent,"object"),this._clean(articleContent,"embed"),this._clean(articleContent,"footer"),this._clean(articleContent,"link"),this._clean(articleContent,"aside");var shareElementThreshold=this.DEFAULT_CHAR_THRESHOLD;this._forEachNode(articleContent.children,function(topCandidate){this._cleanMatchedNodes(topCandidate,function(node,matchString){return this.REGEXPS.shareElements.test(matchString)&&node.textContent.length<shareElementThreshold})}),this._clean(articleContent,"iframe"),this._clean(articleContent,"input"),this._clean(articleContent,"textarea"),this._clean(articleContent,"select"),this._clean(articleContent,"button"),this._cleanHeaders(articleContent),this._cleanConditionally(articleContent,"table"),this._cleanConditionally(articleContent,"ul"),this._cleanConditionally(articleContent,"div"),this._replaceNodeTags(this._getAllNodesWithTag(articleContent,["h1"]),"h2"),this._removeNodes(this._getAllNodesWithTag(articleContent,["p"]),function(paragraph){var contentElementCount=this._getAllNodesWithTag(paragraph,["img","embed","object","iframe"]).length;return contentElementCount===0&&!this._getInnerText(paragraph,!1)}),this._forEachNode(this._getAllNodesWithTag(articleContent,["br"]),function(br){var next=this._nextNode(br.nextSibling);next&&next.tagName=="P"&&br.remove()}),this._forEachNode(this._getAllNodesWithTag(articleContent,["table"]),function(table){var tbody=this._hasSingleTagInsideElement(table,"TBODY")?table.firstElementChild:table;if(this._hasSingleTagInsideElement(tbody,"TR")){var row=tbody.firstElementChild;if(this._hasSingleTagInsideElement(row,"TD")){var cell=row.firstElementChild;cell=this._setNodeTag(cell,this._everyNode(cell.childNodes,this._isPhrasingContent)?"P":"DIV"),table.parentNode.replaceChild(cell,table)}}})},_initializeNode(node){switch(node.readability={contentScore:0},node.tagName){case"DIV":node.readability.contentScore+=5;break;case"PRE":case"TD":case"BLOCKQUOTE":node.readability.contentScore+=3;break;case"ADDRESS":case"OL":case"UL":case"DL":case"DD":case"DT":case"LI":case"FORM":node.readability.contentScore-=3;break;case"H1":case"H2":case"H3":case"H4":case"H5":case"H6":case"TH":node.readability.contentScore-=5;break}node.readability.contentScore+=this._getClassWeight(node)},_removeAndGetNext(node){var nextNode=this._getNextNode(node,!0);return node.remove(),nextNode},_getNextNode(node,ignoreSelfAndKids){if(!ignoreSelfAndKids&&node.firstElementChild)return node.firstElementChild;if(node.nextElementSibling)return node.nextElementSibling;do node=node.parentNode;while(node&&!node.nextElementSibling);return node&&node.nextElementSibling},_textSimilarity(textA,textB){var tokensA=textA.toLowerCase().split(this.REGEXPS.tokenize).filter(Boolean),tokensB=textB.toLowerCase().split(this.REGEXPS.tokenize).filter(Boolean);if(!tokensA.length||!tokensB.length)return 0;var uniqTokensB=tokensB.filter(token=>!tokensA.includes(token)),distanceB=uniqTokensB.join(" ").length/tokensB.join(" ").length;return 1-distanceB},_isValidByline(node,matchString){var rel=node.getAttribute("rel"),itemprop=node.getAttribute("itemprop"),bylineLength=node.textContent.trim().length;return(rel==="author"||itemprop&&itemprop.includes("author")||this.REGEXPS.byline.test(matchString))&&!!bylineLength&&bylineLength<100},_getNodeAncestors(node,maxDepth){maxDepth=maxDepth||0;for(var i=0,ancestors=[];node.parentNode&&(ancestors.push(node.parentNode),!(maxDepth&&++i===maxDepth));)node=node.parentNode;return ancestors},_grabArticle(page){this.log("**** grabArticle ****");var doc=this._doc,isPaging=page!==null;if(page=page||this._doc.body,!page)return this.log("No body found in document. Abort."),null;for(var pageCacheHtml=page.innerHTML;;){this.log("Starting grabArticle loop");var stripUnlikelyCandidates=this._flagIsActive(this.FLAG_STRIP_UNLIKELYS),elementsToScore=[],node=this._doc.documentElement;let shouldRemoveTitleHeader=!0;for(;node;){node.tagName==="HTML"&&(this._articleLang=node.getAttribute("lang"));var matchString=node.className+" "+node.id;if(!this._isProbablyVisible(node)){this.log("Removing hidden node - "+matchString),node=this._removeAndGetNext(node);continue}if(node.getAttribute("aria-modal")=="true"&&node.getAttribute("role")=="dialog"){node=this._removeAndGetNext(node);continue}if(!this._articleByline&&!this._metadata.byline&&this._isValidByline(node,matchString)){for(var endOfSearchMarkerNode=this._getNextNode(node,!0),next=this._getNextNode(node),itemPropNameNode=null;next&&next!=endOfSearchMarkerNode;){var itemprop=next.getAttribute("itemprop");if(itemprop&&itemprop.includes("name")){itemPropNameNode=next;break}else next=this._getNextNode(next)}this._articleByline=(itemPropNameNode??node).textContent.trim(),node=this._removeAndGetNext(node);continue}if(shouldRemoveTitleHeader&&this._headerDuplicatesTitle(node)){this.log("Removing header: ",node.textContent.trim(),this._articleTitle.trim()),shouldRemoveTitleHeader=!1,node=this._removeAndGetNext(node);continue}if(stripUnlikelyCandidates){if(this.REGEXPS.unlikelyCandidates.test(matchString)&&!this.REGEXPS.okMaybeItsACandidate.test(matchString)&&!this._hasAncestorTag(node,"table")&&!this._hasAncestorTag(node,"code")&&node.tagName!=="BODY"&&node.tagName!=="A"){this.log("Removing unlikely candidate - "+matchString),node=this._removeAndGetNext(node);continue}if(this.UNLIKELY_ROLES.includes(node.getAttribute("role"))){this.log("Removing content with role "+node.getAttribute("role")+" - "+matchString),node=this._removeAndGetNext(node);continue}}if((node.tagName==="DIV"||node.tagName==="SECTION"||node.tagName==="HEADER"||node.tagName==="H1"||node.tagName==="H2"||node.tagName==="H3"||node.tagName==="H4"||node.tagName==="H5"||node.tagName==="H6")&&this._isElementWithoutContent(node)){node=this._removeAndGetNext(node);continue}if(this.DEFAULT_TAGS_TO_SCORE.includes(node.tagName)&&elementsToScore.push(node),node.tagName==="DIV"){for(var p=null,childNode=node.firstChild;childNode;){var nextSibling=childNode.nextSibling;if(this._isPhrasingContent(childNode))p!==null?p.appendChild(childNode):this._isWhitespace(childNode)||(p=doc.createElement("p"),node.replaceChild(p,childNode),p.appendChild(childNode));else if(p!==null){for(;p.lastChild&&this._isWhitespace(p.lastChild);)p.lastChild.remove();p=null}childNode=nextSibling}if(this._hasSingleTagInsideElement(node,"P")&&this._getLinkDensity(node)<.25){var newNode=node.children[0];node.parentNode.replaceChild(newNode,node),node=newNode,elementsToScore.push(node)}else this._hasChildBlockElement(node)||(node=this._setNodeTag(node,"P"),elementsToScore.push(node))}node=this._getNextNode(node)}var candidates=[];this._forEachNode(elementsToScore,function(elementToScore){if(!(!elementToScore.parentNode||typeof elementToScore.parentNode.tagName>"u")){var innerText=this._getInnerText(elementToScore);if(!(innerText.length<25)){var ancestors2=this._getNodeAncestors(elementToScore,5);if(ancestors2.length!==0){var contentScore=0;contentScore+=1,contentScore+=innerText.split(this.REGEXPS.commas).length,contentScore+=Math.min(Math.floor(innerText.length/100),3),this._forEachNode(ancestors2,function(ancestor,level){if(!(!ancestor.tagName||!ancestor.parentNode||typeof ancestor.parentNode.tagName>"u")){if(typeof ancestor.readability>"u"&&(this._initializeNode(ancestor),candidates.push(ancestor)),level===0)var scoreDivider=1;else level===1?scoreDivider=2:scoreDivider=level*3;ancestor.readability.contentScore+=contentScore/scoreDivider}})}}}});for(var topCandidates=[],c=0,cl=candidates.length;c<cl;c+=1){var candidate=candidates[c],candidateScore=candidate.readability.contentScore*(1-this._getLinkDensity(candidate));candidate.readability.contentScore=candidateScore,this.log("Candidate:",candidate,"with score "+candidateScore);for(var t=0;t<this._nbTopCandidates;t++){var aTopCandidate=topCandidates[t];if(!aTopCandidate||candidateScore>aTopCandidate.readability.contentScore){topCandidates.splice(t,0,candidate),topCandidates.length>this._nbTopCandidates&&topCandidates.pop();break}}}var topCandidate=topCandidates[0]||null,neededToCreateTopCandidate=!1,parentOfTopCandidate;if(topCandidate===null||topCandidate.tagName==="BODY"){for(topCandidate=doc.createElement("DIV"),neededToCreateTopCandidate=!0;page.firstChild;)this.log("Moving child out:",page.firstChild),topCandidate.appendChild(page.firstChild);page.appendChild(topCandidate),this._initializeNode(topCandidate)}else if(topCandidate){for(var alternativeCandidateAncestors=[],i=1;i<topCandidates.length;i++)topCandidates[i].readability.contentScore/topCandidate.readability.contentScore>=.75&&alternativeCandidateAncestors.push(this._getNodeAncestors(topCandidates[i]));var MINIMUM_TOPCANDIDATES=3;if(alternativeCandidateAncestors.length>=MINIMUM_TOPCANDIDATES)for(parentOfTopCandidate=topCandidate.parentNode;parentOfTopCandidate.tagName!=="BODY";){for(var listsContainingThisAncestor=0,ancestorIndex=0;ancestorIndex<alternativeCandidateAncestors.length&&listsContainingThisAncestor<MINIMUM_TOPCANDIDATES;ancestorIndex++)listsContainingThisAncestor+=Number(alternativeCandidateAncestors[ancestorIndex].includes(parentOfTopCandidate));if(listsContainingThisAncestor>=MINIMUM_TOPCANDIDATES){topCandidate=parentOfTopCandidate;break}parentOfTopCandidate=parentOfTopCandidate.parentNode}topCandidate.readability||this._initializeNode(topCandidate),parentOfTopCandidate=topCandidate.parentNode;for(var lastScore=topCandidate.readability.contentScore,scoreThreshold=lastScore/3;parentOfTopCandidate.tagName!=="BODY";){if(!parentOfTopCandidate.readability){parentOfTopCandidate=parentOfTopCandidate.parentNode;continue}var parentScore=parentOfTopCandidate.readability.contentScore;if(parentScore<scoreThreshold)break;if(parentScore>lastScore){topCandidate=parentOfTopCandidate;break}lastScore=parentOfTopCandidate.readability.contentScore,parentOfTopCandidate=parentOfTopCandidate.parentNode}for(parentOfTopCandidate=topCandidate.parentNode;parentOfTopCandidate.tagName!="BODY"&&parentOfTopCandidate.children.length==1;)topCandidate=parentOfTopCandidate,parentOfTopCandidate=topCandidate.parentNode;topCandidate.readability||this._initializeNode(topCandidate)}var articleContent=doc.createElement("DIV");isPaging&&(articleContent.id="readability-content");var siblingScoreThreshold=Math.max(10,topCandidate.readability.contentScore*.2);parentOfTopCandidate=topCandidate.parentNode;for(var siblings=parentOfTopCandidate.children,s=0,sl=siblings.length;s<sl;s++){var sibling=siblings[s],append=!1;if(this.log("Looking at sibling node:",sibling,sibling.readability?"with score "+sibling.readability.contentScore:""),this.log("Sibling has score",sibling.readability?sibling.readability.contentScore:"Unknown"),sibling===topCandidate)append=!0;else{var contentBonus=0;if(sibling.className===topCandidate.className&&topCandidate.className!==""&&(contentBonus+=topCandidate.readability.contentScore*.2),sibling.readability&&sibling.readability.contentScore+contentBonus>=siblingScoreThreshold)append=!0;else if(sibling.nodeName==="P"){var linkDensity=this._getLinkDensity(sibling),nodeContent=this._getInnerText(sibling),nodeLength=nodeContent.length;(nodeLength>80&&linkDensity<.25||nodeLength<80&&nodeLength>0&&linkDensity===0&&nodeContent.search(/\.( |$)/)!==-1)&&(append=!0)}}append&&(this.log("Appending node:",sibling),this.ALTER_TO_DIV_EXCEPTIONS.includes(sibling.nodeName)||(this.log("Altering sibling:",sibling,"to div."),sibling=this._setNodeTag(sibling,"DIV")),articleContent.appendChild(sibling),siblings=parentOfTopCandidate.children,s-=1,sl-=1)}if(this._debug&&this.log("Article content pre-prep: "+articleContent.innerHTML),this._prepArticle(articleContent),this._debug&&this.log("Article content post-prep: "+articleContent.innerHTML),neededToCreateTopCandidate)topCandidate.id="readability-page-1",topCandidate.className="page";else{var div=doc.createElement("DIV");for(div.id="readability-page-1",div.className="page";articleContent.firstChild;)div.appendChild(articleContent.firstChild);articleContent.appendChild(div)}this._debug&&this.log("Article content after paging: "+articleContent.innerHTML);var parseSuccessful=!0,textLength=this._getInnerText(articleContent,!0).length;if(textLength<this._charThreshold)if(parseSuccessful=!1,page.innerHTML=pageCacheHtml,this._attempts.push({articleContent,textLength}),this._flagIsActive(this.FLAG_STRIP_UNLIKELYS))this._removeFlag(this.FLAG_STRIP_UNLIKELYS);else if(this._flagIsActive(this.FLAG_WEIGHT_CLASSES))this._removeFlag(this.FLAG_WEIGHT_CLASSES);else if(this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY))this._removeFlag(this.FLAG_CLEAN_CONDITIONALLY);else{if(this._attempts.sort(function(a,b){return b.textLength-a.textLength}),!this._attempts[0].textLength)return null;articleContent=this._attempts[0].articleContent,parseSuccessful=!0}if(parseSuccessful){var ancestors=[parentOfTopCandidate,topCandidate].concat(this._getNodeAncestors(parentOfTopCandidate));return this._someNode(ancestors,function(ancestor){if(!ancestor.tagName)return!1;var articleDir=ancestor.getAttribute("dir");return articleDir?(this._articleDir=articleDir,!0):!1}),articleContent}}},_unescapeHtmlEntities(str){if(!str)return str;var htmlEscapeMap=this.HTML_ESCAPE_MAP;return str.replace(/&(quot|amp|apos|lt|gt);/g,function(_,tag){return htmlEscapeMap[tag]}).replace(/&#(?:x([0-9a-f]+)|([0-9]+));/gi,function(_,hex,numStr){var num=parseInt(hex||numStr,hex?16:10);return(num==0||num>1114111||num>=55296&&num<=57343)&&(num=65533),String.fromCodePoint(num)})},_getJSONLD(doc){var scripts=this._getAllNodesWithTag(doc,["script"]),metadata;return this._forEachNode(scripts,function(jsonLdElement){if(!metadata&&jsonLdElement.getAttribute("type")==="application/ld+json")try{var content=jsonLdElement.textContent.replace(/^\s*<!\[CDATA\[|\]\]>\s*$/g,""),parsed=JSON.parse(content);if(Array.isArray(parsed)&&(parsed=parsed.find(it=>it["@type"]&&it["@type"].match(this.REGEXPS.jsonLdArticleTypes)),!parsed))return;var schemaDotOrgRegex=/^https?\:\/\/schema\.org\/?$/,matches=typeof parsed["@context"]=="string"&&parsed["@context"].match(schemaDotOrgRegex)||typeof parsed["@context"]=="object"&&typeof parsed["@context"]["@vocab"]=="string"&&parsed["@context"]["@vocab"].match(schemaDotOrgRegex);if(!matches||(!parsed["@type"]&&Array.isArray(parsed["@graph"])&&(parsed=parsed["@graph"].find(it=>(it["@type"]||"").match(this.REGEXPS.jsonLdArticleTypes))),!parsed||!parsed["@type"]||!parsed["@type"].match(this.REGEXPS.jsonLdArticleTypes)))return;if(metadata={},typeof parsed.name=="string"&&typeof parsed.headline=="string"&&parsed.name!==parsed.headline){var title=this._getArticleTitle(),nameMatches=this._textSimilarity(parsed.name,title)>.75,headlineMatches=this._textSimilarity(parsed.headline,title)>.75;headlineMatches&&!nameMatches?metadata.title=parsed.headline:metadata.title=parsed.name}else typeof parsed.name=="string"?metadata.title=parsed.name.trim():typeof parsed.headline=="string"&&(metadata.title=parsed.headline.trim());parsed.author&&(typeof parsed.author.name=="string"?metadata.byline=parsed.author.name.trim():Array.isArray(parsed.author)&&parsed.author[0]&&typeof parsed.author[0].name=="string"&&(metadata.byline=parsed.author.filter(function(author){return author&&typeof author.name=="string"}).map(function(author){return author.name.trim()}).join(", "))),typeof parsed.description=="string"&&(metadata.excerpt=parsed.description.trim()),parsed.publisher&&typeof parsed.publisher.name=="string"&&(metadata.siteName=parsed.publisher.name.trim()),typeof parsed.datePublished=="string"&&(metadata.datePublished=parsed.datePublished.trim())}catch(err){this.log(err.message)}}),metadata||{}},_getArticleMetadata(jsonld){var metadata={},values={},metaElements=this._doc.getElementsByTagName("meta"),propertyPattern=/\s*(article|dc|dcterm|og|twitter)\s*:\s*(author|creator|description|published_time|title|site_name)\s*/gi,namePattern=/^\s*(?:(dc|dcterm|og|twitter|parsely|weibo:(article|webpage))\s*[-\.:]\s*)?(author|creator|pub-date|description|title|site_name)\s*$/i;this._forEachNode(metaElements,function(element){var elementName=element.getAttribute("name"),elementProperty=element.getAttribute("property"),content=element.getAttribute("content");if(content){var matches=null,name=null;elementProperty&&(matches=elementProperty.match(propertyPattern),matches&&(name=matches[0].toLowerCase().replace(/\s/g,""),values[name]=content.trim())),!matches&&elementName&&namePattern.test(elementName)&&(name=elementName,content&&(name=name.toLowerCase().replace(/\s/g,"").replace(/\./g,":"),values[name]=content.trim()))}}),metadata.title=jsonld.title||values["dc:title"]||values["dcterm:title"]||values["og:title"]||values["weibo:article:title"]||values["weibo:webpage:title"]||values.title||values["twitter:title"]||values["parsely-title"],metadata.title||(metadata.title=this._getArticleTitle());let articleAuthor=typeof values["article:author"]=="string"&&!this._isUrl(values["article:author"])?values["article:author"]:void 0;return metadata.byline=jsonld.byline||values["dc:creator"]||values["dcterm:creator"]||values.author||values["parsely-author"]||articleAuthor,metadata.excerpt=jsonld.excerpt||values["dc:description"]||values["dcterm:description"]||values["og:description"]||values["weibo:article:description"]||values["weibo:webpage:description"]||values.description||values["twitter:description"],metadata.siteName=jsonld.siteName||values["og:site_name"],metadata.publishedTime=jsonld.datePublished||values["article:published_time"]||values["parsely-pub-date"]||null,metadata.title=this._unescapeHtmlEntities(metadata.title),metadata.byline=this._unescapeHtmlEntities(metadata.byline),metadata.excerpt=this._unescapeHtmlEntities(metadata.excerpt),metadata.siteName=this._unescapeHtmlEntities(metadata.siteName),metadata.publishedTime=this._unescapeHtmlEntities(metadata.publishedTime),metadata},_isSingleImage(node){for(;node;){if(node.tagName==="IMG")return!0;if(node.children.length!==1||node.textContent.trim()!=="")return!1;node=node.children[0]}return!1},_unwrapNoscriptImages(doc){var imgs=Array.from(doc.getElementsByTagName("img"));this._forEachNode(imgs,function(img){for(var i=0;i<img.attributes.length;i++){var attr=img.attributes[i];switch(attr.name){case"src":case"srcset":case"data-src":case"data-srcset":return}if(/\.(jpg|jpeg|png|webp)/i.test(attr.value))return}img.remove()});var noscripts=Array.from(doc.getElementsByTagName("noscript"));this._forEachNode(noscripts,function(noscript){if(this._isSingleImage(noscript)){var tmp=doc.createElement("div");tmp.innerHTML=noscript.innerHTML;var prevElement=noscript.previousElementSibling;if(prevElement&&this._isSingleImage(prevElement)){var prevImg=prevElement;prevImg.tagName!=="IMG"&&(prevImg=prevElement.getElementsByTagName("img")[0]);for(var newImg=tmp.getElementsByTagName("img")[0],i=0;i<prevImg.attributes.length;i++){var attr=prevImg.attributes[i];if(attr.value!==""&&(attr.name==="src"||attr.name==="srcset"||/\.(jpg|jpeg|png|webp)/i.test(attr.value))){if(newImg.getAttribute(attr.name)===attr.value)continue;var attrName=attr.name;newImg.hasAttribute(attrName)&&(attrName="data-old-"+attrName),newImg.setAttribute(attrName,attr.value)}}noscript.parentNode.replaceChild(tmp.firstElementChild,prevElement)}}})},_removeScripts(doc){this._removeNodes(this._getAllNodesWithTag(doc,["script","noscript"]))},_hasSingleTagInsideElement(element,tag){return element.children.length!=1||element.children[0].tagName!==tag?!1:!this._someNode(element.childNodes,function(node){return node.nodeType===this.TEXT_NODE&&this.REGEXPS.hasContent.test(node.textContent)})},_isElementWithoutContent(node){return node.nodeType===this.ELEMENT_NODE&&!node.textContent.trim().length&&(!node.children.length||node.children.length==node.getElementsByTagName("br").length+node.getElementsByTagName("hr").length)},_hasChildBlockElement(element){return this._someNode(element.childNodes,function(node){return this.DIV_TO_P_ELEMS.has(node.tagName)||this._hasChildBlockElement(node)})},_isPhrasingContent(node){return node.nodeType===this.TEXT_NODE||this.PHRASING_ELEMS.includes(node.tagName)||(node.tagName==="A"||node.tagName==="DEL"||node.tagName==="INS")&&this._everyNode(node.childNodes,this._isPhrasingContent)},_isWhitespace(node){return node.nodeType===this.TEXT_NODE&&node.textContent.trim().length===0||node.nodeType===this.ELEMENT_NODE&&node.tagName==="BR"},_getInnerText(e,normalizeSpaces2){normalizeSpaces2=typeof normalizeSpaces2>"u"?!0:normalizeSpaces2;var textContent=e.textContent.trim();return normalizeSpaces2?textContent.replace(this.REGEXPS.normalize," "):textContent},_getCharCount(e,s){return s=s||",",this._getInnerText(e).split(s).length-1},_cleanStyles(e){if(!(!e||e.tagName.toLowerCase()==="svg")){for(var i=0;i<this.PRESENTATIONAL_ATTRIBUTES.length;i++)e.removeAttribute(this.PRESENTATIONAL_ATTRIBUTES[i]);this.DEPRECATED_SIZE_ATTRIBUTE_ELEMS.includes(e.tagName)&&(e.removeAttribute("width"),e.removeAttribute("height"));for(var cur=e.firstElementChild;cur!==null;)this._cleanStyles(cur),cur=cur.nextElementSibling}},_getLinkDensity(element){var textLength=this._getInnerText(element).length;if(textLength===0)return 0;var linkLength=0;return this._forEachNode(element.getElementsByTagName("a"),function(linkNode){var href=linkNode.getAttribute("href"),coefficient=href&&this.REGEXPS.hashUrl.test(href)?.3:1;linkLength+=this._getInnerText(linkNode).length*coefficient}),linkLength/textLength},_getClassWeight(e){if(!this._flagIsActive(this.FLAG_WEIGHT_CLASSES))return 0;var weight=0;return typeof e.className=="string"&&e.className!==""&&(this.REGEXPS.negative.test(e.className)&&(weight-=25),this.REGEXPS.positive.test(e.className)&&(weight+=25)),typeof e.id=="string"&&e.id!==""&&(this.REGEXPS.negative.test(e.id)&&(weight-=25),this.REGEXPS.positive.test(e.id)&&(weight+=25)),weight},_clean(e,tag){var isEmbed=["object","embed","iframe"].includes(tag);this._removeNodes(this._getAllNodesWithTag(e,[tag]),function(element){if(isEmbed){for(var i=0;i<element.attributes.length;i++)if(this._allowedVideoRegex.test(element.attributes[i].value))return!1;if(element.tagName==="object"&&this._allowedVideoRegex.test(element.innerHTML))return!1}return!0})},_hasAncestorTag(node,tagName,maxDepth,filterFn){maxDepth=maxDepth||3,tagName=tagName.toUpperCase();for(var depth=0;node.parentNode;){if(maxDepth>0&&depth>maxDepth)return!1;if(node.parentNode.tagName===tagName&&(!filterFn||filterFn(node.parentNode)))return!0;node=node.parentNode,depth++}return!1},_getRowAndColumnCount(table){for(var rows=0,columns=0,trs=table.getElementsByTagName("tr"),i=0;i<trs.length;i++){var rowspan=trs[i].getAttribute("rowspan")||0;rowspan&&(rowspan=parseInt(rowspan,10)),rows+=rowspan||1;for(var columnsInThisRow=0,cells=trs[i].getElementsByTagName("td"),j=0;j<cells.length;j++){var colspan=cells[j].getAttribute("colspan")||0;colspan&&(colspan=parseInt(colspan,10)),columnsInThisRow+=colspan||1}columns=Math.max(columns,columnsInThisRow)}return{rows,columns}},_markDataTables(root){for(var tables=root.getElementsByTagName("table"),i=0;i<tables.length;i++){var table=tables[i],role=table.getAttribute("role");if(role=="presentation"){table._readabilityDataTable=!1;continue}var datatable=table.getAttribute("datatable");if(datatable=="0"){table._readabilityDataTable=!1;continue}var summary=table.getAttribute("summary");if(summary){table._readabilityDataTable=!0;continue}var caption=table.getElementsByTagName("caption")[0];if(caption&&caption.childNodes.length){table._readabilityDataTable=!0;continue}var dataTableDescendants=["col","colgroup","tfoot","thead","th"],descendantExists=function(tag){return!!table.getElementsByTagName(tag)[0]};if(dataTableDescendants.some(descendantExists)){this.log("Data table because found data-y descendant"),table._readabilityDataTable=!0;continue}if(table.getElementsByTagName("table")[0]){table._readabilityDataTable=!1;continue}var sizeInfo=this._getRowAndColumnCount(table);if(sizeInfo.columns==1||sizeInfo.rows==1){table._readabilityDataTable=!1;continue}if(sizeInfo.rows>=10||sizeInfo.columns>4){table._readabilityDataTable=!0;continue}table._readabilityDataTable=sizeInfo.rows*sizeInfo.columns>10}},_fixLazyImages(root){this._forEachNode(this._getAllNodesWithTag(root,["img","picture","figure"]),function(elem){if(elem.src&&this.REGEXPS.b64DataUrl.test(elem.src)){var parts=this.REGEXPS.b64DataUrl.exec(elem.src);if(parts[1]==="image/svg+xml")return;for(var srcCouldBeRemoved=!1,i=0;i<elem.attributes.length;i++){var attr=elem.attributes[i];if(attr.name!=="src"&&/\.(jpg|jpeg|png|webp)/i.test(attr.value)){srcCouldBeRemoved=!0;break}}if(srcCouldBeRemoved){var b64starts=parts[0].length,b64length=elem.src.length-b64starts;b64length<133&&elem.removeAttribute("src")}}if(!((elem.src||elem.srcset&&elem.srcset!="null")&&!elem.className.toLowerCase().includes("lazy"))){for(var j=0;j<elem.attributes.length;j++)if(attr=elem.attributes[j],!(attr.name==="src"||attr.name==="srcset"||attr.name==="alt")){var copyTo=null;if(/\.(jpg|jpeg|png|webp)\s+\d/.test(attr.value)?copyTo="srcset":/^\s*\S+\.(jpg|jpeg|png|webp)\S*\s*$/.test(attr.value)&&(copyTo="src"),copyTo){if(elem.tagName==="IMG"||elem.tagName==="PICTURE")elem.setAttribute(copyTo,attr.value);else if(elem.tagName==="FIGURE"&&!this._getAllNodesWithTag(elem,["img","picture"]).length){var img=this._doc.createElement("img");img.setAttribute(copyTo,attr.value),elem.appendChild(img)}}}}})},_getTextDensity(e,tags){var textLength=this._getInnerText(e,!0).length;if(textLength===0)return 0;var childrenLength=0,children=this._getAllNodesWithTag(e,tags);return this._forEachNode(children,child=>childrenLength+=this._getInnerText(child,!0).length),childrenLength/textLength},_cleanConditionally(e,tag){this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)&&this._removeNodes(this._getAllNodesWithTag(e,[tag]),function(node){var isDataTable=function(t){return t._readabilityDataTable},isList=tag==="ul"||tag==="ol";if(!isList){var listLength=0,listNodes=this._getAllNodesWithTag(node,["ul","ol"]);this._forEachNode(listNodes,list=>listLength+=this._getInnerText(list).length),isList=listLength/this._getInnerText(node).length>.9}if(tag==="table"&&isDataTable(node)||this._hasAncestorTag(node,"table",-1,isDataTable)||this._hasAncestorTag(node,"code")||[...node.getElementsByTagName("table")].some(tbl=>tbl._readabilityDataTable))return!1;var weight=this._getClassWeight(node);this.log("Cleaning Conditionally",node);var contentScore=0;if(weight+contentScore<0)return!0;if(this._getCharCount(node,",")<10){for(var p=node.getElementsByTagName("p").length,img=node.getElementsByTagName("img").length,li=node.getElementsByTagName("li").length-100,input=node.getElementsByTagName("input").length,headingDensity=this._getTextDensity(node,["h1","h2","h3","h4","h5","h6"]),embedCount=0,embeds=this._getAllNodesWithTag(node,["object","embed","iframe"]),i=0;i<embeds.length;i++){for(var j=0;j<embeds[i].attributes.length;j++)if(this._allowedVideoRegex.test(embeds[i].attributes[j].value))return!1;if(embeds[i].tagName==="object"&&this._allowedVideoRegex.test(embeds[i].innerHTML))return!1;embedCount++}var innerText=this._getInnerText(node);if(this.REGEXPS.adWords.test(innerText)||this.REGEXPS.loadingWords.test(innerText))return!0;var contentLength=innerText.length,linkDensity=this._getLinkDensity(node),textishTags=["SPAN","LI","TD"].concat(Array.from(this.DIV_TO_P_ELEMS)),textDensity=this._getTextDensity(node,textishTags),isFigureChild=this._hasAncestorTag(node,"figure"),haveToRemove=(()=>{let errs=[];return!isFigureChild&&img>1&&p/img<.5&&errs.push(`Bad p to img ratio (img=${img}, p=${p})`),!isList&&li>p&&errs.push(`Too many li's outside of a list. (li=${li} > p=${p})`),input>Math.floor(p/3)&&errs.push(`Too many inputs per p. (input=${input}, p=${p})`),!isList&&!isFigureChild&&headingDensity<.9&&contentLength<25&&(img===0||img>2)&&linkDensity>0&&errs.push(`Suspiciously short. (headingDensity=${headingDensity}, img=${img}, linkDensity=${linkDensity})`),!isList&&weight<25&&linkDensity>.2+this._linkDensityModifier&&errs.push(`Low weight and a little linky. (linkDensity=${linkDensity})`),weight>=25&&linkDensity>.5+this._linkDensityModifier&&errs.push(`High weight and mostly links. (linkDensity=${linkDensity})`),(embedCount===1&&contentLength<75||embedCount>1)&&errs.push(`Suspicious embed. (embedCount=${embedCount}, contentLength=${contentLength})`),img===0&&textDensity===0&&errs.push(`No useful content. (img=${img}, textDensity=${textDensity})`),errs.length?(this.log("Checks failed",errs),!0):!1})();if(isList&&haveToRemove){for(var x=0;x<node.children.length;x++)if(node.children[x].children.length>1)return haveToRemove;let li_count=node.getElementsByTagName("li").length;if(img==li_count)return!1}return haveToRemove}return!1})},_cleanMatchedNodes(e,filter){for(var endOfSearchMarkerNode=this._getNextNode(e,!0),next=this._getNextNode(e);next&&next!=endOfSearchMarkerNode;)filter.call(this,next,next.className+" "+next.id)?next=this._removeAndGetNext(next):next=this._getNextNode(next)},_cleanHeaders(e){let headingNodes=this._getAllNodesWithTag(e,["h1","h2"]);this._removeNodes(headingNodes,function(node){let shouldRemove=this._getClassWeight(node)<0;return shouldRemove&&this.log("Removing header with low class weight:",node),shouldRemove})},_headerDuplicatesTitle(node){if(node.tagName!="H1"&&node.tagName!="H2")return!1;var heading=this._getInnerText(node,!1);return this.log("Evaluating similarity of header:",heading,this._articleTitle),this._textSimilarity(this._articleTitle,heading)>.75},_flagIsActive(flag){return(this._flags&flag)>0},_removeFlag(flag){this._flags=this._flags&~flag},_isProbablyVisible(node){return(!node.style||node.style.display!="none")&&(!node.style||node.style.visibility!="hidden")&&!node.hasAttribute("hidden")&&(!node.hasAttribute("aria-hidden")||node.getAttribute("aria-hidden")!="true"||node.className&&node.className.includes&&node.className.includes("fallback-image"))},parse(){if(this._maxElemsToParse>0){var numTags=this._doc.getElementsByTagName("*").length;if(numTags>this._maxElemsToParse)throw new Error("Aborting parsing document; "+numTags+" elements found")}this._unwrapNoscriptImages(this._doc);var jsonLd=this._disableJSONLD?{}:this._getJSONLD(this._doc);this._removeScripts(this._doc),this._prepDocument();var metadata=this._getArticleMetadata(jsonLd);this._metadata=metadata,this._articleTitle=metadata.title;var articleContent=this._grabArticle();if(!articleContent)return null;if(this.log("Grabbed: "+articleContent.innerHTML),this._postProcessContent(articleContent),!metadata.excerpt){var paragraphs=articleContent.getElementsByTagName("p");paragraphs.length&&(metadata.excerpt=paragraphs[0].textContent.trim())}var textContent=articleContent.textContent;return{title:this._articleTitle,byline:metadata.byline||this._articleByline,dir:this._articleDir,lang:this._articleLang,content:this._serializer(articleContent),textContent,length:textContent.length,excerpt:metadata.excerpt,siteName:metadata.siteName||this._articleSiteName,publishedTime:metadata.publishedTime}}};typeof module=="object"&&(module.exports=Readability2)}});var require_Readability_readerable=__commonJS({"node_modules/@mozilla/readability/Readability-readerable.js"(exports,module){var REGEXPS={unlikelyCandidates:/-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i,okMaybeItsACandidate:/and|article|body|column|content|main|shadow/i};function isNodeVisible(node){return(!node.style||node.style.display!="none")&&!node.hasAttribute("hidden")&&(!node.hasAttribute("aria-hidden")||node.getAttribute("aria-hidden")!="true"||node.className&&node.className.includes&&node.className.includes("fallback-image"))}function isProbablyReaderable(doc,options={}){typeof options=="function"&&(options={visibilityChecker:options});var defaultOptions={minScore:20,minContentLength:140,visibilityChecker:isNodeVisible};options=Object.assign(defaultOptions,options);var nodes=doc.querySelectorAll("p, pre, article"),brNodes=doc.querySelectorAll("div > br");if(brNodes.length){var set=new Set(nodes);[].forEach.call(brNodes,function(node){set.add(node.parentNode)}),nodes=Array.from(set)}var score=0;return[].some.call(nodes,function(node){if(!options.visibilityChecker(node))return!1;var matchString=node.className+" "+node.id;if(REGEXPS.unlikelyCandidates.test(matchString)&&!REGEXPS.okMaybeItsACandidate.test(matchString)||node.matches("li p"))return!1;var textContentLength=node.textContent.trim().length;return textContentLength<options.minContentLength?!1:(score+=Math.sqrt(textContentLength-options.minContentLength),score>options.minScore)})}typeof module=="object"&&(module.exports=isProbablyReaderable)}});var require_readability=__commonJS({"node_modules/@mozilla/readability/index.js"(exports,module){var Readability2=require_Readability(),isProbablyReaderable=require_Readability_readerable();module.exports={Readability:Readability2,isProbablyReaderable}}});var import_readability=__toESM(require_readability(),1);import{existsSync as existsSync8,readFileSync as readFileSync8}from"node:fs";var import_turndown=__toESM(require_turndown_cjs(),1);function extractRSCContent(html){if(!html.includes("self.__next_f.push"))return null;let chunkMap=new Map,scriptRegex=/<script>self\.__next_f\.push\(\[1,"([\s\S]*?)"\]\)<\/script>/g;for(let match of html.matchAll(scriptRegex)){let content2;try{content2=JSON.parse('"'+match[1]+'"')}catch{continue}for(let line of content2.split(`
4
4
  `)){if(!line.trim())continue;let colonIdx=line.indexOf(":");if(colonIdx<=0||colonIdx>4)continue;let id=line.slice(0,colonIdx);if(!/^[0-9a-f]+$/i.test(id))continue;let payload=line.slice(colonIdx+1);if(!payload)continue;let existing=chunkMap.get(id);(!existing||payload.length>existing.length)&&chunkMap.set(id,payload)}}if(chunkMap.size===0)return null;let title=html.match(/<title[^>]*>([^<]+)<\/title>/)?.[1]?.split("|")[0]?.trim()||"",parsedCache=new Map;function getParsedChunk(id){if(parsedCache.has(id))return parsedCache.get(id);let chunk=chunkMap.get(id);if(!chunk||!chunk.startsWith("["))return parsedCache.set(id,null),null;try{let parsed=JSON.parse(chunk);return parsedCache.set(id,parsed),parsed}catch{return parsedCache.set(id,null),null}}let visitedRefs=new Set;function extractNode(node,ctx={inTable:!1,inCode:!1}){if(node==null)return"";if(typeof node=="string"){let refMatch=node.match(/^\$L([0-9a-f]+)$/i);if(refMatch){let refId=refMatch[1];if(visitedRefs.has(refId))return"";visitedRefs.add(refId);let refNode=getParsedChunk(refId),result=refNode?extractNode(refNode,ctx):"";return visitedRefs.delete(refId),result}return!ctx.inCode&&(node==="$undefined"||node==="$"||/^\$[A-Z]/.test(node))?"":node.trim()?node:""}if(typeof node=="number")return String(node);if(typeof node=="boolean"||!Array.isArray(node))return"";if(node[0]==="$"&&typeof node[1]=="string"){let tag=node[1],props=node[3]||{};if(["script","style","svg","path","circle","link","meta","template","button","input","nav","footer","aside"].includes(tag))return"";if(tag.startsWith("$L")){let refId=tag.slice(2);if(visitedRefs.has(refId))return"";if(props.baseId&&props.children)return`## ${String(props.children)}
5
5
 
6
6
  `;visitedRefs.add(refId);let refNode=getParsedChunk(refId),result="";return refNode?result=extractNode(refNode,ctx):props.children&&(result=extractNode(props.children,ctx)),visitedRefs.delete(refId),result}let children=props.children,content2=children?extractNode(children,ctx):"";switch(tag){case"h1":return`# ${content2.trim()}
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- var github_copilot_default={"anthropic-messages":{"claude-haiku-4.5":{id:"claude-haiku-4.5",name:"Claude Haiku 4.5 (latest)",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsEagerToolInputStreaming:!1}},"claude-opus-4.5":{id:"claude-opus-4.5",name:"Claude Opus 4.5 (latest)",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:2e5,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"}},"claude-opus-4.6":{id:"claude-opus-4.6",name:"Claude Opus 4.6",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{max:"max"},compat:{forceAdaptiveThinking:!0}},"claude-opus-4.7":{id:"claude-opus-4.7",name:"Claude Opus 4.7",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"claude-opus-4.8":{id:"claude-opus-4.8",name:"Claude Opus 4.8",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"claude-opus-5":{id:"claude-opus-5",name:"Claude Opus 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"claude-sonnet-4":{id:"claude-sonnet-4",name:"Claude Sonnet 4 (latest)",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:216e3,maxTokens:16e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsEagerToolInputStreaming:!1}},"claude-sonnet-4.5":{id:"claude-sonnet-4.5",name:"Claude Sonnet 4.5 (latest)",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsEagerToolInputStreaming:!1}},"claude-sonnet-4.6":{id:"claude-sonnet-4.6",name:"Claude Sonnet 4.6",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0}},"claude-sonnet-5":{id:"claude-sonnet-5",name:"Claude Sonnet 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{forceAdaptiveThinking:!0}}},"openai-completions":{"claude-fable-5":{id:"claude-fable-5",name:"Claude Fable 5",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},thinkingLevelMap:{off:null,xhigh:"xhigh",max:"max"}},"gemini-3.1-pro-preview":{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:18,cacheRead:.4,cacheWrite:0}]},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"gemini-3.5-flash":{id:"gemini-3.5-flash",name:"Gemini 3.5 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.5,output:9,cacheRead:.15,cacheWrite:0},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"gemini-3.6-flash":{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"gemini-3.7-flash":{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"gpt-4.1":{id:"gpt-4.1",name:"GPT-4.1",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!1,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:128e3,maxTokens:16384,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"kimi-k2.7-code":{id:"kimi-k2.7-code",name:"Kimi K2.7 Code",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.95,output:4,cacheRead:.19,cacheWrite:0},contextWindow:256e3,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"kimi-k3":{id:"kimi-k3",name:"Kimi K3",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:0},contextWindow:1048576,maxTokens:131072,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}}},"openai-responses":{"gpt-5-mini":{id:"gpt-5-mini",name:"GPT-5 Mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:264e3,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.2":{id:"gpt-5.2",name:"GPT-5.2",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",xhigh:"xhigh"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.2-codex":{id:"gpt-5.2-codex",name:"GPT-5.2 Codex",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",xhigh:"xhigh"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.3-codex":{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.4":{id:"gpt-5.4",name:"GPT-5.4",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0,tiers:[{inputTokensAbove:272e3,input:5,output:22.5,cacheRead:.5,cacheWrite:0}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.4-mini":{id:"gpt-5.4-mini",name:"GPT-5.4 mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.4-nano":{id:"gpt-5.4-nano",name:"GPT-5.4 nano",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",xhigh:"xhigh"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.5":{id:"gpt-5.5",name:"GPT-5.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:272e3,input:10,output:45,cacheRead:1,cacheWrite:0}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.6-luna":{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:.25,tiers:[{inputTokensAbove:2e5,input:.4,output:1.8,cacheRead:.04,cacheWrite:.5}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.6-sol":{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.4,cacheWrite:5}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.6-terra":{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:18,cacheRead:.4,cacheWrite:5}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"grok-4.5":{id:"grok-4.5",name:"Grok 4.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null}},"grok-4.6":{id:"grok-4.6",name:"Grok 4.6",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null}},"mai-code-1-flash-picker":{id:"mai-code-1-flash-picker",name:"MAI-Code-1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:256e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null}},"mai-code-1.1-flash":{id:"mai-code-1.1-flash",name:"MAI-Code-1.1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:0},contextWindow:256e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null}}}};function flattenModelCatalog(_provider,groups){return Object.assign({},...Object.values(groups))}var GITHUB_COPILOT_MODELS=flattenModelCatalog("github-copilot",github_copilot_default);function sleep(ms,signal){return new Promise((resolve,reject)=>{signal.throwIfAborted();let onAbort=()=>{clearTimeout(timeout),reject(signal.reason)},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}var CANCEL_MESSAGE="Login cancelled",TIMEOUT_MESSAGE="Device flow timed out",SLOW_DOWN_TIMEOUT_MESSAGE="Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again.";function abortableSleep(ms,signal,cancelMessage){return new Promise((resolve,reject)=>{if(signal.aborted){reject(new Error(cancelMessage));return}let onAbort=()=>{clearTimeout(timeout),reject(new Error(cancelMessage))},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}async function pollOAuthDeviceCodeFlow(options){let deadline=typeof options.expiresInSeconds=="number"?Date.now()+options.expiresInSeconds*1e3:Number.POSITIVE_INFINITY,intervalMs=Math.max(1e3,Math.floor((options.intervalSeconds??5)*1e3)),slowDownResponses=0;if(options.waitBeforeFirstPoll){let remainingMs=deadline-Date.now();remainingMs>0&&await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}for(;Date.now()<deadline;){if(options.signal.aborted)throw new Error(CANCEL_MESSAGE);let result=await options.poll();if(result.status==="complete")return result.value;if(result.status==="failed")throw new Error(result.message);result.status==="slow_down"&&(slowDownResponses+=1,intervalMs=typeof result.intervalSeconds=="number"&&Number.isFinite(result.intervalSeconds)&&result.intervalSeconds>0?Math.max(1e3,Math.floor(result.intervalSeconds*1e3)):Math.max(1e3,intervalMs+5e3));let remainingMs=deadline-Date.now();if(remainingMs<=0)break;await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}throw new Error(slowDownResponses>0?SLOW_DOWN_TIMEOUT_MESSAGE:TIMEOUT_MESSAGE)}var decode=s=>atob(s),CLIENT_ID=decode("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),COPILOT_HEADERS={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},COPILOT_API_VERSION="2026-06-01";function normalizeDomain(input){let trimmed=input.trim();if(!trimmed)return null;try{return(trimmed.includes("://")?new URL(trimmed):new URL(`https://${trimmed}`)).hostname}catch{return null}}function getUrls(domain){return{deviceCodeUrl:`https://${domain}/login/device/code`,accessTokenUrl:`https://${domain}/login/oauth/access_token`,copilotTokenUrl:`https://api.${domain}/copilot_internal/v2/token`}}function getBaseUrlFromToken(token){let match=token.match(/proxy-ep=([^;]+)/);return match?`https://${match[1].replace(/^proxy\./,"api.")}`:null}function getGitHubCopilotBaseUrl(token,enterpriseDomain){if(token){let urlFromToken=getBaseUrlFromToken(token);if(urlFromToken)return urlFromToken}return enterpriseDomain?`https://copilot-api.${enterpriseDomain}`:"https://api.individual.githubcopilot.com"}function asRecord(value){return value&&typeof value=="object"?value:void 0}function parseGitHubCopilotModelCatalog(raw,allowPolicyFallback){let data=asRecord(raw)?.data;if(!Array.isArray(data))throw new Error("Invalid Copilot models response");let accountModels=data.flatMap(rawItem=>{let item=asRecord(rawItem),id=item?.id;if(!item||typeof id!="string")return[];let capabilities=asRecord(item.capabilities);return asRecord(capabilities?.supports)?.tool_calls===!1?[]:[{id,pickerEnabled:item.model_picker_enabled===!0,policyState:asRecord(item.policy)?.state}]}),pickerModelIds=accountModels.filter(model=>model.pickerEnabled&&model.policyState!=="disabled").map(model=>model.id),usePolicyFallback=allowPolicyFallback&&pickerModelIds.length===0,availableModelIds=pickerModelIds.length>0||!allowPolicyFallback?pickerModelIds:accountModels.filter(model=>model.policyState==="enabled").map(model=>model.id),policyModelIds=accountModels.filter(model=>model.policyState==="unconfigured"&&Object.hasOwn(GITHUB_COPILOT_MODELS,model.id)&&(model.pickerEnabled||usePolicyFallback)).map(model=>model.id);return{availableModelIds,policyModelIds}}async function fetchWithRateLimitRetry(url,init,signal,retryPolicy){let retryBudgetSignal=retryPolicy.maxRetries>0&&retryPolicy.maxElapsedMs>0?AbortSignal.timeout(retryPolicy.maxElapsedMs):void 0,requestSignal=retryBudgetSignal?AbortSignal.any([signal,retryBudgetSignal]):signal,retryDeadline=retryBudgetSignal?Date.now()+retryPolicy.maxElapsedMs:void 0;for(let retry=0;;retry++){let response=await fetch(url,{...init,signal:AbortSignal.any([requestSignal,AbortSignal.timeout(5e3)])});if(response.status!==429||retry===retryPolicy.maxRetries)return response;let retryAfter=response.headers.get("retry-after"),delayMs=500*2**retry;if(retryAfter){let seconds=Number.parseFloat(retryAfter);if(delayMs=Number.isNaN(seconds)?Date.parse(retryAfter)-Date.now():seconds*1e3,!Number.isFinite(delayMs))return response}if(delayMs=Math.max(0,delayMs),retryDeadline!==void 0&&delayMs>=retryDeadline-Date.now())return response;await response.body?.cancel(),await sleep(delayMs,requestSignal)}}async function fetchGitHubCopilotModels(copilotToken,enterpriseDomain,signal,retryPolicy){let baseUrl=getGitHubCopilotBaseUrl(copilotToken,enterpriseDomain),allowPolicyFallback=baseUrl==="https://api.individual.githubcopilot.com",response=await fetchWithRateLimitRetry(`${baseUrl}/models`,{headers:{Accept:"application/json",Authorization:`Bearer ${copilotToken}`,...COPILOT_HEADERS,"X-GitHub-Api-Version":COPILOT_API_VERSION}},signal,retryPolicy);if(!response.ok)throw new Error(`${response.status} ${response.statusText}: ${await response.text()}`);return parseGitHubCopilotModelCatalog(await response.json(),allowPolicyFallback)}async function fetchJson(url,init){let response=await fetch(url,init);if(!response.ok){let text=await response.text();throw new Error(`${response.status} ${response.statusText}: ${text}`)}return response.json()}async function startDeviceFlow(domain,signal){let urls=getUrls(domain),data=await fetchJson(urls.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:CLIENT_ID,scope:"read:user"}),signal});if(!data||typeof data!="object")throw new Error("Invalid device code response");let deviceCode=data.device_code,userCode=data.user_code,verificationUri=data.verification_uri,interval=data.interval,expiresIn=data.expires_in;if(typeof deviceCode!="string"||typeof userCode!="string"||typeof verificationUri!="string"||interval!==void 0&&typeof interval!="number"||typeof expiresIn!="number")throw new Error("Invalid device code response fields");let parsedUri;try{parsedUri=new URL(verificationUri)}catch{throw new Error("Untrusted verification_uri in device code response")}if(parsedUri.protocol!=="https:"&&parsedUri.protocol!=="http:")throw new Error("Untrusted verification_uri in device code response");return{device_code:deviceCode,user_code:userCode,verification_uri:parsedUri.href,interval,expires_in:expiresIn}}async function pollForGitHubAccessToken(domain,device,signal){let urls=getUrls(domain);return pollOAuthDeviceCodeFlow({intervalSeconds:device.interval,expiresInSeconds:device.expires_in,waitBeforeFirstPoll:!0,signal,poll:async()=>{let raw=await fetchJson(urls.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:CLIENT_ID,device_code:device.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal});if(raw&&typeof raw=="object"&&typeof raw.access_token=="string")return{status:"complete",value:raw.access_token};if(raw&&typeof raw=="object"&&typeof raw.error=="string"){let{error,error_description:description,interval}=raw;if(error==="authorization_pending")return{status:"pending"};if(error==="slow_down")return{status:"slow_down",intervalSeconds:typeof interval=="number"?interval:void 0};let descriptionSuffix=description?`: ${description}`:"";return{status:"failed",message:`Device flow failed: ${error}${descriptionSuffix}`}}return{status:"failed",message:"Invalid device token response"}}})}async function refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal){let urls=getUrls(enterpriseDomain||"github.com"),raw=await fetchJson(urls.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${refreshToken}`,...COPILOT_HEADERS},signal});if(!raw||typeof raw!="object")throw new Error("Invalid Copilot token response");let token=raw.token,expiresAt=raw.expires_at;if(typeof token!="string"||typeof expiresAt!="number")throw new Error("Invalid Copilot token response fields");return{type:"oauth",refresh:refreshToken,access:token,expires:expiresAt*1e3-300*1e3,enterpriseUrl:enterpriseDomain}}async function refreshGitHubCopilotToken(refreshToken,enterpriseDomain,signal){let credentials=await refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal),{availableModelIds}=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain,signal,{maxRetries:0,maxElapsedMs:0});return{...credentials,availableModelIds}}async function enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal){let url=`${getGitHubCopilotBaseUrl(token,enterpriseDomain)}/models/${modelId}/policy`,response;try{response=await fetchWithRateLimitRetry(url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${token}`,...COPILOT_HEADERS,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})},signal,{maxRetries:2,maxElapsedMs:5e3})}catch(error){if(signal.aborted)throw error;return!1}if(response.status===429)throw new Error(`${response.status} ${response.statusText}: ${await response.text()}`);return response.ok}async function enableGitHubCopilotModels(token,modelIds,enterpriseDomain,signal){let enabledModelIds=[];for(let modelId of modelIds)try{await enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal)&&enabledModelIds.push(modelId)}catch(error){if(signal.aborted)throw error;break}return enabledModelIds}async function loginGitHubCopilot(interaction){let input=await interaction.prompt({type:"text",message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com"});if(interaction.signal.aborted)throw new Error("Login cancelled");let trimmed=input.trim(),enterpriseDomain=normalizeDomain(input);if(trimmed&&!enterpriseDomain)throw new Error("Invalid GitHub Enterprise URL/domain");let domain=enterpriseDomain||"github.com",device=await startDeviceFlow(domain,interaction.signal);interaction.notify({type:"device_code",userCode:device.user_code,verificationUri:device.verification_uri,intervalSeconds:device.interval,expiresInSeconds:device.expires_in});let githubAccessToken=await pollForGitHubAccessToken(domain,device,interaction.signal),credentials=await refreshGitHubCopilotAccessToken(githubAccessToken,enterpriseDomain??void 0,interaction.signal),models=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain??void 0,interaction.signal,{maxRetries:2,maxElapsedMs:5e3}),enabledModelIds=[];return models.policyModelIds.length>0&&(interaction.notify({type:"progress",message:"Enabling models..."}),enabledModelIds=await enableGitHubCopilotModels(credentials.access,models.policyModelIds,enterpriseDomain??void 0,interaction.signal)),{...credentials,availableModelIds:[...new Set([...models.availableModelIds,...enabledModelIds])]}}function copilotEnterpriseDomain(credential){let enterpriseUrl=credential.enterpriseUrl;if(!(typeof enterpriseUrl!="string"||!enterpriseUrl))return normalizeDomain(enterpriseUrl)??void 0}var githubCopilotOAuth={name:"GitHub Copilot",isSubscription:!0,login:loginGitHubCopilot,refresh:(credential,signal)=>refreshGitHubCopilotToken(credential.refresh,copilotEnterpriseDomain(credential),signal),async toAuth(credential){return{apiKey:credential.access,baseUrl:getGitHubCopilotBaseUrl(credential.access,copilotEnterpriseDomain(credential))}}};export{githubCopilotOAuth};
2
+ var github_copilot_default={"anthropic-messages":{"claude-fable-5":{id:"claude-fable-5",name:"Claude Fable 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,xhigh:"xhigh",max:"max"},compat:{forceAdaptiveThinking:!0}},"claude-fable-5.1":{id:"claude-fable-5.1",name:"Claude Fable 5.1",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:.25,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,xhigh:"xhigh",max:"max"},compat:{forceAdaptiveThinking:!0}},"claude-haiku-4.5":{id:"claude-haiku-4.5",name:"Claude Haiku 4.5 (latest)",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsEagerToolInputStreaming:!1}},"claude-opus-4.7":{id:"claude-opus-4.7",name:"Claude Opus 4.7",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"claude-opus-4.8":{id:"claude-opus-4.8",name:"Claude Opus 4.8",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"claude-opus-5":{id:"claude-opus-5",name:"Claude Opus 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"claude-sonnet-4.6":{id:"claude-sonnet-4.6",name:"Claude Sonnet 4.6",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0}},"claude-sonnet-5":{id:"claude-sonnet-5",name:"Claude Sonnet 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{forceAdaptiveThinking:!0}}},"openai-completions":{"gemini-3.5-flash":{id:"gemini-3.5-flash",name:"Gemini 3.5 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.5,output:9,cacheRead:.15,cacheWrite:0},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"gemini-3.6-flash":{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"gemini-3.7-flash":{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"gemini-3.8-flash":{id:"gemini-3.8-flash",name:"Gemini 3.8 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"gpt-6-astra":{id:"gpt-6-astra",name:"GPT-6 Astra",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5,tiers:[{inputTokensAbove:272e3,input:20,output:75,cacheRead:2,cacheWrite:25}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max"}},"kimi-k2.7-code":{id:"kimi-k2.7-code",name:"Kimi K2.7 Code",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.95,output:4,cacheRead:.19,cacheWrite:0},contextWindow:256e3,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"kimi-k3":{id:"kimi-k3",name:"Kimi K3",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:0},contextWindow:1048576,maxTokens:131072,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}}},"openai-responses":{"gpt-5-mini":{id:"gpt-5-mini",name:"GPT-5 Mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:264e3,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.3-codex":{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.4":{id:"gpt-5.4",name:"GPT-5.4",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0,tiers:[{inputTokensAbove:272e3,input:5,output:22.5,cacheRead:.5,cacheWrite:0}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.4-mini":{id:"gpt-5.4-mini",name:"GPT-5.4 mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.4-nano":{id:"gpt-5.4-nano",name:"GPT-5.4 nano",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",xhigh:"xhigh"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.5":{id:"gpt-5.5",name:"GPT-5.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:272e3,input:10,output:45,cacheRead:1,cacheWrite:0}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.6-luna":{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:.25,tiers:[{inputTokensAbove:2e5,input:.4,output:1.8,cacheRead:.04,cacheWrite:.5}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.6-sol":{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:.4,cacheWrite:5,tiers:[{inputTokensAbove:272e3,input:8,output:30,cacheRead:.8,cacheWrite:10}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.6-terra":{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:18,cacheRead:.4,cacheWrite:5}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"grok-4.5":{id:"grok-4.5",name:"Grok 4.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null}},"grok-4.6":{id:"grok-4.6",name:"Grok 4.6",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null}},"mai-code-1-flash-picker":{id:"mai-code-1-flash-picker",name:"MAI-Code-1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:256e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null}},"mai-code-1.1-flash":{id:"mai-code-1.1-flash",name:"MAI-Code-1.1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:0},contextWindow:256e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null}}}};function flattenModelCatalog(_provider,groups){return Object.assign({},...Object.values(groups))}var GITHUB_COPILOT_MODELS=flattenModelCatalog("github-copilot",github_copilot_default);function sleep(ms,signal){return new Promise((resolve,reject)=>{signal.throwIfAborted();let onAbort=()=>{clearTimeout(timeout),reject(signal.reason)},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}var CANCEL_MESSAGE="Login cancelled",TIMEOUT_MESSAGE="Device flow timed out",SLOW_DOWN_TIMEOUT_MESSAGE="Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again.";function abortableSleep(ms,signal,cancelMessage){return new Promise((resolve,reject)=>{if(signal.aborted){reject(new Error(cancelMessage));return}let onAbort=()=>{clearTimeout(timeout),reject(new Error(cancelMessage))},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}async function pollOAuthDeviceCodeFlow(options){let deadline=typeof options.expiresInSeconds=="number"?Date.now()+options.expiresInSeconds*1e3:Number.POSITIVE_INFINITY,intervalMs=Math.max(1e3,Math.floor((options.intervalSeconds??5)*1e3)),slowDownResponses=0;if(options.waitBeforeFirstPoll){let remainingMs=deadline-Date.now();remainingMs>0&&await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}for(;Date.now()<deadline;){if(options.signal.aborted)throw new Error(CANCEL_MESSAGE);let result=await options.poll();if(result.status==="complete")return result.value;if(result.status==="failed")throw new Error(result.message);result.status==="slow_down"&&(slowDownResponses+=1,intervalMs=typeof result.intervalSeconds=="number"&&Number.isFinite(result.intervalSeconds)&&result.intervalSeconds>0?Math.max(1e3,Math.floor(result.intervalSeconds*1e3)):Math.max(1e3,intervalMs+5e3));let remainingMs=deadline-Date.now();if(remainingMs<=0)break;await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}throw new Error(slowDownResponses>0?SLOW_DOWN_TIMEOUT_MESSAGE:TIMEOUT_MESSAGE)}var decode=s=>atob(s),CLIENT_ID=decode("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),COPILOT_HEADERS={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},COPILOT_API_VERSION="2026-06-01";function normalizeDomain(input){let trimmed=input.trim();if(!trimmed)return null;try{return(trimmed.includes("://")?new URL(trimmed):new URL(`https://${trimmed}`)).hostname}catch{return null}}function getUrls(domain){return{deviceCodeUrl:`https://${domain}/login/device/code`,accessTokenUrl:`https://${domain}/login/oauth/access_token`,copilotTokenUrl:`https://api.${domain}/copilot_internal/v2/token`}}function getBaseUrlFromToken(token){let match=token.match(/proxy-ep=([^;]+)/);return match?`https://${match[1].replace(/^proxy\./,"api.")}`:null}function getGitHubCopilotBaseUrl(token,enterpriseDomain){if(token){let urlFromToken=getBaseUrlFromToken(token);if(urlFromToken)return urlFromToken}return enterpriseDomain?`https://copilot-api.${enterpriseDomain}`:"https://api.individual.githubcopilot.com"}function asRecord(value){return value&&typeof value=="object"?value:void 0}function parseGitHubCopilotModelCatalog(raw,allowPolicyFallback){let data=asRecord(raw)?.data;if(!Array.isArray(data))throw new Error("Invalid Copilot models response");let accountModels=data.flatMap(rawItem=>{let item=asRecord(rawItem),id=item?.id;if(!item||typeof id!="string")return[];let capabilities=asRecord(item.capabilities);return asRecord(capabilities?.supports)?.tool_calls===!1?[]:[{id,pickerEnabled:item.model_picker_enabled===!0,policyState:asRecord(item.policy)?.state}]}),pickerModelIds=accountModels.filter(model=>model.pickerEnabled&&model.policyState!=="disabled").map(model=>model.id),usePolicyFallback=allowPolicyFallback&&pickerModelIds.length===0,availableModelIds=pickerModelIds.length>0||!allowPolicyFallback?pickerModelIds:accountModels.filter(model=>model.policyState==="enabled").map(model=>model.id),policyModelIds=accountModels.filter(model=>model.policyState==="unconfigured"&&Object.hasOwn(GITHUB_COPILOT_MODELS,model.id)&&(model.pickerEnabled||usePolicyFallback)).map(model=>model.id);return{availableModelIds,policyModelIds}}async function fetchWithRateLimitRetry(url,init,signal,retryPolicy){let retryBudgetSignal=retryPolicy.maxRetries>0&&retryPolicy.maxElapsedMs>0?AbortSignal.timeout(retryPolicy.maxElapsedMs):void 0,requestSignal=retryBudgetSignal?AbortSignal.any([signal,retryBudgetSignal]):signal,retryDeadline=retryBudgetSignal?Date.now()+retryPolicy.maxElapsedMs:void 0;for(let retry=0;;retry++){let response=await fetch(url,{...init,signal:AbortSignal.any([requestSignal,AbortSignal.timeout(5e3)])});if(response.status!==429||retry===retryPolicy.maxRetries)return response;let retryAfter=response.headers.get("retry-after"),delayMs=500*2**retry;if(retryAfter){let seconds=Number.parseFloat(retryAfter);if(delayMs=Number.isNaN(seconds)?Date.parse(retryAfter)-Date.now():seconds*1e3,!Number.isFinite(delayMs))return response}if(delayMs=Math.max(0,delayMs),retryDeadline!==void 0&&delayMs>=retryDeadline-Date.now())return response;await response.body?.cancel(),await sleep(delayMs,requestSignal)}}async function fetchGitHubCopilotModels(copilotToken,enterpriseDomain,signal,retryPolicy){let baseUrl=getGitHubCopilotBaseUrl(copilotToken,enterpriseDomain),allowPolicyFallback=baseUrl==="https://api.individual.githubcopilot.com",response=await fetchWithRateLimitRetry(`${baseUrl}/models`,{headers:{Accept:"application/json",Authorization:`Bearer ${copilotToken}`,...COPILOT_HEADERS,"X-GitHub-Api-Version":COPILOT_API_VERSION}},signal,retryPolicy);if(!response.ok)throw new Error(`${response.status} ${response.statusText}: ${await response.text()}`);return parseGitHubCopilotModelCatalog(await response.json(),allowPolicyFallback)}async function fetchJson(url,init){let response=await fetch(url,init);if(!response.ok){let text=await response.text();throw new Error(`${response.status} ${response.statusText}: ${text}`)}return response.json()}async function startDeviceFlow(domain,signal){let urls=getUrls(domain),data=await fetchJson(urls.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:CLIENT_ID,scope:"read:user"}),signal});if(!data||typeof data!="object")throw new Error("Invalid device code response");let deviceCode=data.device_code,userCode=data.user_code,verificationUri=data.verification_uri,interval=data.interval,expiresIn=data.expires_in;if(typeof deviceCode!="string"||typeof userCode!="string"||typeof verificationUri!="string"||interval!==void 0&&typeof interval!="number"||typeof expiresIn!="number")throw new Error("Invalid device code response fields");let parsedUri;try{parsedUri=new URL(verificationUri)}catch{throw new Error("Untrusted verification_uri in device code response")}if(parsedUri.protocol!=="https:"&&parsedUri.protocol!=="http:")throw new Error("Untrusted verification_uri in device code response");return{device_code:deviceCode,user_code:userCode,verification_uri:parsedUri.href,interval,expires_in:expiresIn}}async function pollForGitHubAccessToken(domain,device,signal){let urls=getUrls(domain);return pollOAuthDeviceCodeFlow({intervalSeconds:device.interval,expiresInSeconds:device.expires_in,waitBeforeFirstPoll:!0,signal,poll:async()=>{let raw=await fetchJson(urls.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:CLIENT_ID,device_code:device.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal});if(raw&&typeof raw=="object"&&typeof raw.access_token=="string")return{status:"complete",value:raw.access_token};if(raw&&typeof raw=="object"&&typeof raw.error=="string"){let{error,error_description:description,interval}=raw;if(error==="authorization_pending")return{status:"pending"};if(error==="slow_down")return{status:"slow_down",intervalSeconds:typeof interval=="number"?interval:void 0};let descriptionSuffix=description?`: ${description}`:"";return{status:"failed",message:`Device flow failed: ${error}${descriptionSuffix}`}}return{status:"failed",message:"Invalid device token response"}}})}async function refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal){let urls=getUrls(enterpriseDomain||"github.com"),raw=await fetchJson(urls.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${refreshToken}`,...COPILOT_HEADERS},signal});if(!raw||typeof raw!="object")throw new Error("Invalid Copilot token response");let token=raw.token,expiresAt=raw.expires_at;if(typeof token!="string"||typeof expiresAt!="number")throw new Error("Invalid Copilot token response fields");return{type:"oauth",refresh:refreshToken,access:token,expires:expiresAt*1e3-300*1e3,enterpriseUrl:enterpriseDomain}}async function refreshGitHubCopilotToken(refreshToken,enterpriseDomain,signal){let credentials=await refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal),{availableModelIds}=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain,signal,{maxRetries:0,maxElapsedMs:0});return{...credentials,availableModelIds}}async function enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal){let url=`${getGitHubCopilotBaseUrl(token,enterpriseDomain)}/models/${modelId}/policy`,response;try{response=await fetchWithRateLimitRetry(url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${token}`,...COPILOT_HEADERS,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})},signal,{maxRetries:2,maxElapsedMs:5e3})}catch(error){if(signal.aborted)throw error;return!1}if(response.status===429)throw new Error(`${response.status} ${response.statusText}: ${await response.text()}`);return response.ok}async function enableGitHubCopilotModels(token,modelIds,enterpriseDomain,signal){let enabledModelIds=[];for(let modelId of modelIds)try{await enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal)&&enabledModelIds.push(modelId)}catch(error){if(signal.aborted)throw error;break}return enabledModelIds}async function loginGitHubCopilot(interaction){let input=await interaction.prompt({type:"text",message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com"});if(interaction.signal.aborted)throw new Error("Login cancelled");let trimmed=input.trim(),enterpriseDomain=normalizeDomain(input);if(trimmed&&!enterpriseDomain)throw new Error("Invalid GitHub Enterprise URL/domain");let domain=enterpriseDomain||"github.com",device=await startDeviceFlow(domain,interaction.signal);interaction.notify({type:"device_code",userCode:device.user_code,verificationUri:device.verification_uri,intervalSeconds:device.interval,expiresInSeconds:device.expires_in});let githubAccessToken=await pollForGitHubAccessToken(domain,device,interaction.signal),credentials=await refreshGitHubCopilotAccessToken(githubAccessToken,enterpriseDomain??void 0,interaction.signal),models=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain??void 0,interaction.signal,{maxRetries:2,maxElapsedMs:5e3}),enabledModelIds=[];return models.policyModelIds.length>0&&(interaction.notify({type:"progress",message:"Enabling models..."}),enabledModelIds=await enableGitHubCopilotModels(credentials.access,models.policyModelIds,enterpriseDomain??void 0,interaction.signal)),{...credentials,availableModelIds:[...new Set([...models.availableModelIds,...enabledModelIds])]}}function copilotEnterpriseDomain(credential){let enterpriseUrl=credential.enterpriseUrl;if(!(typeof enterpriseUrl!="string"||!enterpriseUrl))return normalizeDomain(enterpriseUrl)??void 0}var githubCopilotOAuth={name:"GitHub Copilot",isSubscription:!0,login:loginGitHubCopilot,refresh:(credential,signal)=>refreshGitHubCopilotToken(credential.refresh,copilotEnterpriseDomain(credential),signal),async toAuth(credential){return{apiKey:credential.access,baseUrl:getGitHubCopilotBaseUrl(credential.access,copilotEnterpriseDomain(credential))}}};export{githubCopilotOAuth};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{GoogleGenAI,convertMessages,convertTools,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling}from"./chunk-PSKDLDLZ.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-XNGRGP62.js";import{buildBaseOptions,getPiUserAgent}from"./chunk-TXBQIIIO.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-6R7UI4IY.js";import{calculateCost,clampThinkingLevel}from"./chunk-WJZ4KLGL.js";import{AssistantMessageEventStream}from"./chunk-72KO4OMP.js";import"./chunk-JXWJOIH4.js";var toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output={role:"assistant",content:[],api:"google-generative-ai",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Generative AI adapter");let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,options?.headers),params=buildParams(model,context,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){if(part.text!==void 0){let isThinking=isThinkingPart(part);(!currentBlock||isThinking&&currentBlock.type!=="thinking"||!isThinking&&currentBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}}candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning),resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning),googleModel=model;return isGemini3ProModel(googleModel)||isGemini3FlashModel(googleModel)||isGemma4Model(googleModel)?stream(model,context,{...base,thinking:{enabled:!0,level:getThinkingLevel(resolvedLevel,googleModel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(googleModel,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,apiKey,optionsHeaders){let httpOptions={};model.baseUrl&&(httpOptions.baseUrl=model.baseUrl,httpOptions.apiVersion="");let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),new GoogleGenAI({apiKey,httpOptions:Object.keys(httpOptions).length>0?httpOptions:void 0})}function buildParams(model,context,options={}){let contents=convertMessages(model,context),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=context.tools?.length?resolveGoogleFunctionCallingMode(context.tools,options.toolChoice,supportsStrictMode):void 0,config={...Object.keys(generationConfig).length>0&&generationConfig,...context.systemPrompt&&{systemInstruction:sanitizeSurrogates(context.systemPrompt)},...context.tools&&context.tools.length>0&&{tools:convertTools(context.tools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=options.thinking.level:options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function isGemma4Model(model){return/gemma-?4/.test(model.id.toLowerCase())}function isGemini3ProModel(model){return/gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase())}function isGemini3FlashModel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"}function getDisabledThinkingConfig(model){return isGemini3ProModel(model)?{thinkingLevel:"LOW"}:isGemini3FlashModel(model)?{thinkingLevel:"MINIMAL"}:isGemma4Model(model)?{thinkingLevel:"MINIMAL"}:{thinkingBudget:0}}function getThinkingLevel(effort,model){if(isGemini3ProModel(model))switch(effort){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}if(isGemma4Model(model))switch(effort){case"minimal":case"low":return"MINIMAL";case"medium":case"high":return"HIGH"}switch(effort){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
2
+ import{GoogleGenAI,convertMessages,convertTools,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling}from"./chunk-HPPQHK3J.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-XNGRGP62.js";import{buildBaseOptions,getPiUserAgent}from"./chunk-TXBQIIIO.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-6R7UI4IY.js";import{calculateCost,clampThinkingLevel}from"./chunk-E6KP6V7F.js";import{AssistantMessageEventStream}from"./chunk-72KO4OMP.js";import"./chunk-JXWJOIH4.js";var toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output={role:"assistant",content:[],api:"google-generative-ai",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Generative AI adapter");let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,options?.headers),params=buildParams(model,context,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){if(part.text!==void 0){let isThinking=isThinkingPart(part);(!currentBlock||isThinking&&currentBlock.type!=="thinking"||!isThinking&&currentBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}}candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning),resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning),googleModel=model;return isGemini3ProModel(googleModel)||isGemini3FlashModel(googleModel)||isGemma4Model(googleModel)?stream(model,context,{...base,thinking:{enabled:!0,level:getThinkingLevel(resolvedLevel,googleModel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(googleModel,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,apiKey,optionsHeaders){let httpOptions={};model.baseUrl&&(httpOptions.baseUrl=model.baseUrl,httpOptions.apiVersion="");let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),new GoogleGenAI({apiKey,httpOptions:Object.keys(httpOptions).length>0?httpOptions:void 0})}function buildParams(model,context,options={}){let contents=convertMessages(model,context),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=context.tools?.length?resolveGoogleFunctionCallingMode(context.tools,options.toolChoice,supportsStrictMode):void 0,config={...Object.keys(generationConfig).length>0&&generationConfig,...context.systemPrompt&&{systemInstruction:sanitizeSurrogates(context.systemPrompt)},...context.tools&&context.tools.length>0&&{tools:convertTools(context.tools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=options.thinking.level:options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function isGemma4Model(model){return/gemma-?4/.test(model.id.toLowerCase())}function isGemini3ProModel(model){return/gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase())}function isGemini3FlashModel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"}function getDisabledThinkingConfig(model){return isGemini3ProModel(model)?{thinkingLevel:"LOW"}:isGemini3FlashModel(model)?{thinkingLevel:"MINIMAL"}:isGemma4Model(model)?{thinkingLevel:"MINIMAL"}:{thinkingBudget:0}}function getThinkingLevel(effort,model){if(isGemini3ProModel(model))switch(effort){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}if(isGemma4Model(model))switch(effort){case"minimal":case"low":return"MINIMAL";case"medium":case"high":return"HIGH"}switch(effort){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{GoogleGenAI,ResourceScope,ThinkingLevel,convertMessages,convertTools,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling}from"./chunk-PSKDLDLZ.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-XNGRGP62.js";import{buildBaseOptions,getPiUserAgent}from"./chunk-TXBQIIIO.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-6R7UI4IY.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import{calculateCost,clampThinkingLevel}from"./chunk-WJZ4KLGL.js";import{AssistantMessageEventStream}from"./chunk-72KO4OMP.js";import"./chunk-JXWJOIH4.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",THINKING_LEVEL_MAP={THINKING_LEVEL_UNSPECIFIED:ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,MINIMAL:ThinkingLevel.MINIMAL,LOW:ThinkingLevel.LOW,MEDIUM:ThinkingLevel.MEDIUM,HIGH:ThinkingLevel.HIGH},toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output={role:"assistant",content:[],api:"google-vertex",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Vertex adapter");let apiKey=resolveApiKey(options),client=apiKey?createClientWithApiKey(model,apiKey,options?.headers):createClient(model,resolveProject(options),resolveLocation(options),options?.headers,options?.env),params=buildParams(model,context,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){if(part.text!==void 0){let isThinking=isThinkingPart(part);(!currentBlock||isThinking&&currentBlock.type!=="thinking"||!isThinking&&currentBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}}candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google Vertex stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning),resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning),geminiModel=model;return isGemini3ProModel(geminiModel)||isGemini3FlashModel(geminiModel)?stream(model,context,{...base,thinking:{enabled:!0,level:getGemini3ThinkingLevel(resolvedLevel,geminiModel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(geminiModel,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,project,location,optionsHeaders,env){let googleAuthOptions=buildGoogleAuthOptions(env);return new GoogleGenAI({vertexai:!0,project,location,apiVersion:API_VERSION,...googleAuthOptions?{googleAuthOptions}:{},httpOptions:buildHttpOptions(model,optionsHeaders)})}function createClientWithApiKey(model,apiKey,optionsHeaders){return new GoogleGenAI({vertexai:!0,apiKey,apiVersion:API_VERSION,httpOptions:buildHttpOptions(model,optionsHeaders)})}function buildHttpOptions(model,optionsHeaders){let httpOptions={},baseUrl=resolveCustomBaseUrl(model.baseUrl);baseUrl&&(httpOptions.baseUrl=baseUrl,httpOptions.baseUrlResourceScope=ResourceScope.COLLECTION,baseUrlIncludesApiVersion(baseUrl)&&(httpOptions.apiVersion=""));let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),Object.keys(httpOptions).length>0?httpOptions:void 0}function resolveCustomBaseUrl(baseUrl){let trimmed=baseUrl.trim();if(!(!trimmed||trimmed.includes("{location}")))return trimmed}function baseUrlIncludesApiVersion(baseUrl){try{return new URL(baseUrl).pathname.split("/").some(part=>/^v\d+(?:beta\d*)?$/.test(part))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(baseUrl)}}function buildGoogleAuthOptions(env){let keyFilename=getProviderEnvValue("GOOGLE_APPLICATION_CREDENTIALS",env);return keyFilename?{keyFilename}:void 0}function resolveApiKey(options){let apiKey=options?.apiKey?.trim();if(!(!apiKey||apiKey===GCP_VERTEX_CREDENTIALS_MARKER||isPlaceholderApiKey(apiKey)))return apiKey}function isPlaceholderApiKey(apiKey){return/^<[^>]+>$/.test(apiKey)}function resolveProject(options){let project=options?.project||getProviderEnvValue("GOOGLE_CLOUD_PROJECT",options?.env)||getProviderEnvValue("GCLOUD_PROJECT",options?.env);if(!project)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return project}function resolveLocation(options){let location=options?.location||getProviderEnvValue("GOOGLE_CLOUD_LOCATION",options?.env);if(!location)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return location}function buildParams(model,context,options={}){let contents=convertMessages(model,context),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=context.tools?.length?resolveGoogleFunctionCallingMode(context.tools,options.toolChoice,supportsStrictMode):void 0,config={...Object.keys(generationConfig).length>0&&generationConfig,...context.systemPrompt&&{systemInstruction:sanitizeSurrogates(context.systemPrompt)},...context.tools&&context.tools.length>0&&{tools:convertTools(context.tools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=THINKING_LEVEL_MAP[options.thinking.level]:options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function isGemini3ProModel(model){return/gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase())}function isGemini3FlashModel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"}function getDisabledThinkingConfig(model){let geminiModel=model;return isGemini3ProModel(geminiModel)?{thinkingLevel:ThinkingLevel.LOW}:isGemini3FlashModel(geminiModel)?{thinkingLevel:ThinkingLevel.MINIMAL}:{thinkingBudget:0}}function getGemini3ThinkingLevel(effort,model){if(isGemini3ProModel(model))switch(effort){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}switch(effort){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
2
+ import{GoogleGenAI,ResourceScope,ThinkingLevel,convertMessages,convertTools,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling}from"./chunk-HPPQHK3J.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-XNGRGP62.js";import{buildBaseOptions,getPiUserAgent}from"./chunk-TXBQIIIO.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-6R7UI4IY.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import{calculateCost,clampThinkingLevel}from"./chunk-E6KP6V7F.js";import{AssistantMessageEventStream}from"./chunk-72KO4OMP.js";import"./chunk-JXWJOIH4.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",THINKING_LEVEL_MAP={THINKING_LEVEL_UNSPECIFIED:ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,MINIMAL:ThinkingLevel.MINIMAL,LOW:ThinkingLevel.LOW,MEDIUM:ThinkingLevel.MEDIUM,HIGH:ThinkingLevel.HIGH},toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output={role:"assistant",content:[],api:"google-vertex",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Vertex adapter");let apiKey=resolveApiKey(options),client=apiKey?createClientWithApiKey(model,apiKey,options?.headers):createClient(model,resolveProject(options),resolveLocation(options),options?.headers,options?.env),params=buildParams(model,context,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){if(part.text!==void 0){let isThinking=isThinkingPart(part);(!currentBlock||isThinking&&currentBlock.type!=="thinking"||!isThinking&&currentBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}}candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google Vertex stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning),resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning),geminiModel=model;return isGemini3ProModel(geminiModel)||isGemini3FlashModel(geminiModel)?stream(model,context,{...base,thinking:{enabled:!0,level:getGemini3ThinkingLevel(resolvedLevel,geminiModel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(geminiModel,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,project,location,optionsHeaders,env){let googleAuthOptions=buildGoogleAuthOptions(env);return new GoogleGenAI({vertexai:!0,project,location,apiVersion:API_VERSION,...googleAuthOptions?{googleAuthOptions}:{},httpOptions:buildHttpOptions(model,optionsHeaders)})}function createClientWithApiKey(model,apiKey,optionsHeaders){return new GoogleGenAI({vertexai:!0,apiKey,apiVersion:API_VERSION,httpOptions:buildHttpOptions(model,optionsHeaders)})}function buildHttpOptions(model,optionsHeaders){let httpOptions={},baseUrl=resolveCustomBaseUrl(model.baseUrl);baseUrl&&(httpOptions.baseUrl=baseUrl,httpOptions.baseUrlResourceScope=ResourceScope.COLLECTION,baseUrlIncludesApiVersion(baseUrl)&&(httpOptions.apiVersion=""));let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),Object.keys(httpOptions).length>0?httpOptions:void 0}function resolveCustomBaseUrl(baseUrl){let trimmed=baseUrl.trim();if(!(!trimmed||trimmed.includes("{location}")))return trimmed}function baseUrlIncludesApiVersion(baseUrl){try{return new URL(baseUrl).pathname.split("/").some(part=>/^v\d+(?:beta\d*)?$/.test(part))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(baseUrl)}}function buildGoogleAuthOptions(env){let keyFilename=getProviderEnvValue("GOOGLE_APPLICATION_CREDENTIALS",env);return keyFilename?{keyFilename}:void 0}function resolveApiKey(options){let apiKey=options?.apiKey?.trim();if(!(!apiKey||apiKey===GCP_VERTEX_CREDENTIALS_MARKER||isPlaceholderApiKey(apiKey)))return apiKey}function isPlaceholderApiKey(apiKey){return/^<[^>]+>$/.test(apiKey)}function resolveProject(options){let project=options?.project||getProviderEnvValue("GOOGLE_CLOUD_PROJECT",options?.env)||getProviderEnvValue("GCLOUD_PROJECT",options?.env);if(!project)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return project}function resolveLocation(options){let location=options?.location||getProviderEnvValue("GOOGLE_CLOUD_LOCATION",options?.env);if(!location)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return location}function buildParams(model,context,options={}){let contents=convertMessages(model,context),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=context.tools?.length?resolveGoogleFunctionCallingMode(context.tools,options.toolChoice,supportsStrictMode):void 0,config={...Object.keys(generationConfig).length>0&&generationConfig,...context.systemPrompt&&{systemInstruction:sanitizeSurrogates(context.systemPrompt)},...context.tools&&context.tools.length>0&&{tools:convertTools(context.tools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=THINKING_LEVEL_MAP[options.thinking.level]:options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function isGemini3ProModel(model){return/gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase())}function isGemini3FlashModel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"}function getDisabledThinkingConfig(model){let geminiModel=model;return isGemini3ProModel(geminiModel)?{thinkingLevel:ThinkingLevel.LOW}:isGemini3FlashModel(geminiModel)?{thinkingLevel:ThinkingLevel.MINIMAL}:{thinkingBudget:0}}function getGemini3ThinkingLevel(effort,model){if(isGemini3ProModel(model))switch(effort){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}switch(effort){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};