// ==UserScript== // @name Ophel Atlas - AI 对话结构化与导航工具, 全能AI助手 (支持 Gemini, ChatGPT, Claude, Grok, AI Studio, 豆包) // @name:zh-CN Ophel Atlas - AI 对话结构化与导航工具, 全能AI助手 (支持 Gemini, ChatGPT, Claude, Grok, AI Studio, 豆包) // @name:zh-TW Ophel Atlas - AI 對話結構化與導覽工具, 全能AI助手 (支持 Gemini, ChatGPT, Claude, Grok, AI Studio, 豆包) // @name:en Ophel Atlas - AI Chat Organizer & Navigator (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:de Ophel Atlas - KI-Chat-Organizer & Navigator (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:es Ophel Atlas - Organizador de Chats de IA (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:fr Ophel Atlas - Organisateur de Chat IA (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:it Ophel Atlas - Organizzatore di chat IA (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:ja Ophel Atlas - AI対話の構造化とナビゲーションツール (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:ko Ophel Atlas - AI 채팅 정리 및 탐색 도구 (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:pt-BR Ophel Atlas - Organizador de Chat de IA (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:ru Ophel Atlas - Органайзер AI-чатов (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @namespace https://github.com/urzeye/ophel // @version 1.2.4 // @author urzeye // @description 适用于 Gemini、Gemini Enterprise、AI Studio、ChatGPT、Claude、Grok、DeepSeek、QwenAI、豆包、Kimi、ChatGLM、Z.ai 的 AI 对话导航与整理工具,提供实时大纲、Search Everywhere 全局搜索、会话文件夹、置顶、提示词队列与提示词库、提示词变量、Markdown/JSON 导出、思维链导出控制、WebDAV 同步、禅模式、宽屏/全屏阅读、滚动锁定、主题切换、LaTeX/表格复制、标签页重命名、隐私模式、完成通知音、阅读历史恢复、快捷键与批量导入提示词队列,让长 AI 对话更易搜索、更易导航、更易沉淀、更易复用。 // @description:en AI chat navigator and organizer for Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM, and Z.ai. Adds real-time outlines, Search Everywhere, conversation folders, pinning, prompt queue, prompt library, Markdown/JSON export, WebDAV sync, Zen Mode, wide/full-screen reading, scroll lock, LaTeX/table copy, tab renaming, privacy mode, notifications, reading history restore, shortcuts, prompt variables, and theme tweaks. Sound presets. Batch import. // @description:zh-CN 适用于 Gemini、Gemini Enterprise、AI Studio、ChatGPT、Claude、Grok、DeepSeek、QwenAI、豆包、Kimi、ChatGLM、Z.ai 的 AI 对话导航与整理工具,提供实时大纲、Search Everywhere 全局搜索、会话文件夹、置顶、提示词队列与提示词库、提示词变量、Markdown/JSON 导出、思维链导出控制、WebDAV 同步、禅模式、宽屏/全屏阅读、滚动锁定、主题切换、LaTeX/表格复制、标签页重命名、隐私模式、完成通知音、阅读历史恢复、快捷键与批量导入提示词队列,让长 AI 对话更易搜索、更易导航、更易沉淀、更易复用。 // @description:zh-TW 適用於 Gemini、Gemini Enterprise、AI Studio、ChatGPT、Claude、Grok、DeepSeek、QwenAI、豆包、Kimi、ChatGLM、Z.ai 的 AI 對話導覽與整理工具,提供即時大綱、Search Everywhere 全域搜尋、對話資料夾、置頂、提示詞佇列與提示詞庫、提示詞變數、Markdown/JSON 匯出、思維鏈匯出控制、WebDAV 同步、禪模式、寬螢幕/全螢幕閱讀、捲動鎖定、主題切換、LaTeX/表格複製、分頁重新命名、隱私模式、完成通知音、閱讀歷史恢復、快捷鍵與批量匯入提示詞佇列,讓長 AI 對話更易搜尋、更易導覽、更易沉澱、更易複用。 // @description:de KI-Chat-Navigator für Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM und Z.ai. Mit Echtzeit-Gliederung, Search Everywhere, Ordnern, Pinning, Prompt-Queue, Markdown/JSON-Export, WebDAV-Sync, Zen Mode, Scroll Lock, Tab-Umbenennung, Benachrichtigungen und Verlauf für lange, durchsuchbare AI-Chats. // @description:es Navegador y organizador de chats con IA para Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM y Z.ai. Incluye esquemas en tiempo real, Search Everywhere, carpetas, fijado, cola y biblioteca de prompts, variables, exportación Markdown/JSON, sincronización WebDAV, Zen Mode, lectura amplia, bloqueo de desplazamiento, copia de LaTeX/tablas, renombrado de pestañas, privacidad, notificaciones e historial para chats largos y reutilizables. // @description:fr Navigateur et organisateur de chats IA pour Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM et Z.ai. Ajoute un plan en temps réel, Search Everywhere, dossiers, épinglage, file et bibliothèque de prompts, variables, export Markdown/JSON, sync WebDAV, Zen Mode, lecture large, verrouillage du défilement, copie LaTeX/tableaux, renommage des onglets, confidentialité, notifications et reprise de lecture pour des chats IA longs et réutilisables. // @description:it Navigatore e organizzatore di chat IA per Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM e Z.ai. Aggiunge outline in tempo reale, Search Everywhere, cartelle, pin, coda e libreria prompt, variabili, export Markdown/JSON, sync WebDAV, Zen Mode, lettura ampia, scroll lock, copia LaTeX/tabelle, rinomina schede, privacy, notifiche e cronologia per chat lunghe e riutilizzabili. // @description:ja Gemini、Gemini Enterprise、AI Studio、ChatGPT、Claude、Grok、DeepSeek、QwenAI、豆包、Kimi、ChatGLM、Z.ai に対応する AI対話ナビゲーション整理ツール。リアルタイム目次、Search Everywhere、会話フォルダ、ピン留め、プロンプトキューとプロンプトライブラリ、プロンプト変数、Markdown/JSON エクスポート、WebDAV 同期、禅モード、ワイド/全画面読書、スクロールロック、LaTeX/表コピー、タブ名変更、プライバシーモード、完了通知、閲覧履歴復元を提供し、長い AI 対話を検索しやすく再利用しやすくします。 // @description:ko Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, QwenAI, 豆包, Kimi, ChatGLM, Z.ai를 지원하는 AI 대화 탐색·정리 도구입니다. 실시간 개요, Search Everywhere, 대화 폴더, 고정, 프롬프트 큐와 프롬프트 라이브러리, 프롬프트 변수, Markdown/JSON 내보내기, WebDAV 동기화, Zen Mode, 와이드/전체 화면 읽기, 스크롤 잠금, LaTeX/표 복사, 탭 이름 변경, 프라이버시 모드, 완료 알림, 읽기 기록 복원을 제공해 긴 AI 대화를 더 쉽게 검색하고 재사용할 수 있게 합니다. // @description:pt-BR Navegador e organizador de chats com IA para Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM e Z.ai. Inclui outlines em tempo real, Search Everywhere, pastas, fixação, fila e biblioteca de prompts, variáveis, exportação Markdown/JSON, sincronização WebDAV, Zen Mode, leitura ampla, scroll lock, cópia de LaTeX/tabelas, renomeação de abas, privacidade, notificações e histórico para chats longos, pesquisáveis e reutilizáveis. // @description:ru Навигатор и органайзер AI-чатов для Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM и Z.ai. Добавляет структуру в реальном времени, Search Everywhere, папки, закрепление, очередь и библиотеку промптов, переменные, экспорт Markdown/JSON, синхронизацию WebDAV, Zen Mode, широкий режим, Scroll Lock, копирование LaTeX/таблиц, переименование вкладок, приватный режим, уведомления и историю чтения для длинных и переиспользуемых AI-чатов. // @license GPL-3.0-only // @icon https://raw.githubusercontent.com/urzeye/ophel/main/assets/icon.png // @homepageURL https://github.com/urzeye/ophel // @source https://github.com/urzeye/ophel.git // @supportURL https://github.com/urzeye/ophel/issues // @match http://*/* // @match https://*/* // @require https://cdn.jsdelivr.net/npm/react@18.3.1/umd/react.production.min.js // @require https://cdn.jsdelivr.net/npm/react-dom@18.3.1/umd/react-dom.production.min.js // @require https://cdn.jsdelivr.net/npm/fuzzysort@3.1.0/fuzzysort.min.js // @require https://cdn.jsdelivr.net/npm/katex@0.16.44/dist/katex.min.js // @require https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel-markdown-vendor-ophel-1.2.4.js#sha256=fcc27e6ef2b0ae986892f262d675586a026487219feafdfbf594adf47c4ed458 // @require https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel-gemini-watermark-remover-1.0.17-ophel-1.2.4.js#sha256=a11db287fdbf99b05e77765db7535a2bb629da7fef7b122222a0951ecb933c30 // @require https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel-adapters-vendor-ophel-1.2.4.js#sha256=98cde2b4169188759afe062fdc6587fd3a9bd7a970dc4db5fc8687346d5f3448 // @resource ophelAssistantMermaidRunner https://cdn.jsdelivr.net/gh/urzeye/ophel@main/assets/assistant-mermaid-runner.js // @resource ophelAssistantMermaidVendor https://cdn.jsdelivr.net/npm/@mermaid-js/tiny@11.13.0/dist/mermaid.tiny.js // @resource ophelIcon https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel-icon.193ed41c2441.png#sha256=193ed41c244185e553de148c7919de5486f5e9c323901b1f84cf220726b1b2d0 // @resource ophelKatexCss https://cdn.jsdelivr.net/npm/katex@0.16.44/dist/katex.min.css // @resource ophelLocaleDe https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel.locale.de.7e89f09466d6.json#sha256=7e89f09466d6355986de1721052abf841032fdc7d3332bb81fd6bfd4ae7d82f8 // @resource ophelLocaleEn https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel.locale.en.a0411d70dfbf.json#sha256=a0411d70dfbf347ad8674e037b3b360f512d05425f30c3651527df036c3cfc7e // @resource ophelLocaleEs https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel.locale.es.fe6a4cf44008.json#sha256=fe6a4cf44008508abd2a9eb0eef6ef4b649d6266d48c225de4ad355851d7c351 // @resource ophelLocaleFr https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel.locale.fr.364d637e7e51.json#sha256=364d637e7e51606f144deaf85cb0f42a6c2b11db5ae0d3ca31e4338c9359b08a // @resource ophelLocaleIt https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel.locale.it.ea37cef02b2b.json#sha256=ea37cef02b2b05b96ce4e1fcad13bebf48ce3276f2a938cb5edb305628533a41 // @resource ophelLocaleJa https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel.locale.ja.ad3962daf37f.json#sha256=ad3962daf37fb8507cadcb41eb114b22517ca85ac158648aeb805ab9c4f0223f // @resource ophelLocaleKo https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel.locale.ko.6744ba5a516c.json#sha256=6744ba5a516ca8882210f3bbce594d1d3ffa6112d1ebf91c9429e1090dba3ca9 // @resource ophelLocalePt https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel.locale.pt.574bc96d0e7d.json#sha256=574bc96d0e7de29e787ba4e7f51ee3c97c32c3972e2047ef0b2838c293dfe882 // @resource ophelLocaleRu https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel.locale.ru.0d32a2219a01.json#sha256=0d32a2219a01ffa4699fc3b75d563be37f11beba198cc7011b483393862dc89b // @resource ophelLocaleZhCN https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel.locale.zh-CN.1753514c2123.json#sha256=1753514c2123e9cc2c0e20c7ee989891be20092937a95e830728edbce4876692 // @resource ophelLocaleZhTW https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel.locale.zh-TW.7978d3054baa.json#sha256=7978d3054baa4a51f46c62678cab54dfc022a0839d0b46a927578d37a979c984 // @resource ophelMarkdownPreviewStyles https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel.markdown-preview.a99d491d0b81.css#sha256=a99d491d0b81cd59fa13f471267fd8ae2cd827c3d38e1552577fdc63d0f8f30a // @resource ophelNotificationBrightAlert https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel-sound-bright-alert.568967a3d9f8.ogg#sha256=568967a3d9f8a8f6af54ea01729c4882284308f2a27d78c07ffd7ee0d6951661 // @resource ophelNotificationDefault https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel-sound-default.15d3cda1ee80.mp3#sha256=15d3cda1ee8072f63639ce23ad943708458f8e194b1d827ba99338aa357e2ae9 // @resource ophelNotificationGlassPing https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel-sound-glass-ping.2379b58f953e.ogg#sha256=2379b58f953e3d86982aa8cddcae763022c6258e9820171bf905ce58b4e97766 // @resource ophelNotificationSoftChime https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel-sound-soft-chime.063564703b60.ogg#sha256=063564703b6094d70718a3e787a55cc9141611e4ecd6b6637f8828f79b4a8c3a // @resource ophelSiteIcons https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel.site-icons.2c0540f606ea.json#sha256=2c0540f606ea7f27303392a294758cccab9064f8ba5388d3d61d1485dd896c8d // @resource ophelStyles https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel.user.51383af239f9.css#sha256=51383af239f90257d685a4cb855cbd69f538959080a038d0dd653b9d9113a0b4 // @resource ophelUserQueryMarkdownStyles https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel.user-query-markdown.bf5242eedc63.css#sha256=bf5242eedc63f2f50016381319b9daf271329ebd359fc971db83ecb7fc3c148d // @resource ophelWatermarkBg48 https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel-watermark-bg-48.4afc99afe0ef.png#sha256=4afc99afe0ef108d67acc45bf4dc5da867ddb793bebc89c9243bb121ce7f0f57 // @resource ophelWatermarkBg96 https://cdn.jsdelivr.net/gh/urzeye/ophel@694ed7000488997a1f917524bd8c80e679ef2334/userscript-assets/ophel-watermark-bg-96.3e26f2233a12.png#sha256=3e26f2233a12a5829acac174d8df1f3db40e07fef04ecdd0e035732154077911 // @tag ai // @tag chat // @tag productivity // @tag navigation // @tag outline // @tag conversation // @tag prompt // @tag export // @tag chinese // @tag multilingual // @tag cross-platform // @tag ai-assistant // @tag all-in-one // @tag 全能AI助手 // @connect * // @grant GM_addStyle // @grant GM_addValueChangeListener // @grant GM_cookie // @grant GM_deleteValue // @grant GM_getResourceText // @grant GM_getResourceURL // @grant GM_getValue // @grant GM_info // @grant GM_notification // @grant GM_removeValueChangeListener // @grant GM_setValue // @grant GM_xmlhttpRequest // @grant unsafeWindow // @grant window.focus // @run-at document-start // @noframes // ==/UserScript== (async function (geminiWatermarkRemover) { 'use strict'; const d$1=new Set;const e = async e=>{d$1.has(e)||(d$1.add(e),(t=>{typeof GM_addStyle=="function"?GM_addStyle(t):(document.head||document.documentElement).appendChild(document.createElement("style")).append(t);})(e));}; const n=function(){const e="undefined"!=typeof document&&document.createElement("link").relList;return e&&e.supports&&e.supports("modulepreload")?"modulepreload":"preload"}(),r={},o=function(e,t,o){let a=Promise.resolve();if(t&&t.length>0){let e=function(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),i=o?.nonce||o?.getAttribute("nonce");a=e(t.map(e=>{if((e=function(e){return "/"+e}(e))in r)return;r[e]=true;const t=e.endsWith(".css"),o=t?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${e}"]${o}`))return;const a=document.createElement("link");return a.rel=t?"stylesheet":n,t||(a.as="script"),a.crossOrigin="",a.href=e,i&&a.setAttribute("nonce",i),document.head.appendChild(a),t?new Promise((t,n)=>{a.addEventListener("load",t),a.addEventListener("error",()=>n(new Error(`Unable to preload CSS for ${e}`)));}):void 0}));}function i(e){const t=new Event("vite:preloadError",{cancelable:true});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return a.then(t=>{for(const e of t||[])"rejected"===e.status&&i(e.reason);return e().catch(i)})};const a=function(){const e=globalThis.React;if(!e||"function"!=typeof e.createElement)throw new Error("[Ophel] React CDN runtime is missing");return e}(),i=a.Children,s=a.Component,l=a.Fragment,c=a.Profiler,d=a.PureComponent,h=a.StrictMode,u=a.Suspense,g=a.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,p=a.act,m=a.cloneElement,f=a.createContext,b=a.createElement,v=a.createFactory,y=a.createRef,w=a.forwardRef,x=a.isValidElement,k=a.lazy,S=a.memo,C=a.startTransition,T=a.unstable_act,E=a.useCallback,M=a.useContext,I=a.useDebugValue,N=a.useDeferredValue,A=a.useEffect,P=a.useId,L=a.useImperativeHandle,R=a.useInsertionEffect,$=a.useLayoutEffect,z=a.useMemo,_=a.useReducer,O=a.useRef,D=a.useState,B=a.useSyncExternalStore,q=a.useTransition,F=a.version,H=Object.freeze(Object.defineProperty({__proto__:null,Children:i,Component:s,Fragment:l,Profiler:c,PureComponent:d,StrictMode:h,Suspense:u,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:g,act:p,cloneElement:m,createContext:f,createElement:b,createFactory:v,createRef:y,default:a,forwardRef:w,isValidElement:x,lazy:k,memo:S,startTransition:C,unstable_act:T,useCallback:E,useContext:M,useDebugValue:I,useDeferredValue:N,useEffect:A,useId:P,useImperativeHandle:L,useInsertionEffect:R,useLayoutEffect:$,useMemo:z,useReducer:_,useRef:O,useState:D,useSyncExternalStore:B,useTransition:q,version:F},Symbol.toStringTag,{value:"Module"}));const U=function(){const e=globalThis.ReactDOM;if(!e||"function"!=typeof e.createRoot)throw new Error("[Ophel] ReactDOM client CDN runtime is missing");return e}();U.createRoot,U.hydrateRoot;const j=["zh-CN","zh-TW","en","ja","ko","it","fr","de","ru","es","pt"],W={styles:{metaName:"ophelStyles",fileName:"ophel.user.css"},markdownPreviewStyles:{metaName:"ophelMarkdownPreviewStyles",fileName:"ophel.markdown-preview.css"},userQueryMarkdownStyles:{metaName:"ophelUserQueryMarkdownStyles",fileName:"ophel.user-query-markdown.css"},icon:{metaName:"ophelIcon",fileName:"ophel-icon.png"},siteIcons:{metaName:"ophelSiteIcons",fileName:"ophel.site-icons.json"},notificationDefault:{metaName:"ophelNotificationDefault",fileName:"ophel-sound-default.mp3"},notificationSoftChime:{metaName:"ophelNotificationSoftChime",fileName:"ophel-sound-soft-chime.ogg"},notificationGlassPing:{metaName:"ophelNotificationGlassPing",fileName:"ophel-sound-glass-ping.ogg"},notificationBrightAlert:{metaName:"ophelNotificationBrightAlert",fileName:"ophel-sound-bright-alert.ogg"},watermarkBg48:{metaName:"ophelWatermarkBg48",fileName:"ophel-watermark-bg-48.png"},watermarkBg96:{metaName:"ophelWatermarkBg96",fileName:"ophel-watermark-bg-96.png"},assistantMermaidRunner:{metaName:"ophelAssistantMermaidRunner",fileName:"ophel-assistant-mermaid-runner.js",externalUrl:"https://cdn.jsdelivr.net/gh/urzeye/ophel@main/assets/assistant-mermaid-runner.js"},assistantMermaidVendor:{metaName:"ophelAssistantMermaidVendor",fileName:"ophel-assistant-mermaid-vendor.js",externalUrl:"https://cdn.jsdelivr.net/npm/@mermaid-js/tiny@11.13.0/dist/mermaid.tiny.js"}},V={"zh-CN":{metaName:"ophelLocaleZhCN",fileName:"ophel.locale.zh-CN.json"},"zh-TW":{metaName:"ophelLocaleZhTW",fileName:"ophel.locale.zh-TW.json"},en:{metaName:"ophelLocaleEn",fileName:"ophel.locale.en.json"},ja:{metaName:"ophelLocaleJa",fileName:"ophel.locale.ja.json"},ko:{metaName:"ophelLocaleKo",fileName:"ophel.locale.ko.json"},it:{metaName:"ophelLocaleIt",fileName:"ophel.locale.it.json"},fr:{metaName:"ophelLocaleFr",fileName:"ophel.locale.fr.json"},de:{metaName:"ophelLocaleDe",fileName:"ophel.locale.de.json"},ru:{metaName:"ophelLocaleRu",fileName:"ophel.locale.ru.json"},es:{metaName:"ophelLocaleEs",fileName:"ophel.locale.es.json"},pt:{metaName:"ophelLocalePt",fileName:"ophel.locale.pt.json"}};const K="en",G={},Q=new Set,Y=()=>{if("undefined"==typeof navigator)return K;const e=navigator.language;return e.startsWith("zh-TW")||e.startsWith("zh-HK")?"zh-TW":e.startsWith("zh")?"zh-CN":e.startsWith("ja")?"ja":e.startsWith("ko")?"ko":e.startsWith("it")?"it":e.startsWith("fr")?"fr":e.startsWith("de")?"de":e.startsWith("ru")?"ru":e.startsWith("es")?"es":e.startsWith("pt")?"pt":K};let Z=Y();function X(e){return e&&"auto"!==e?(t=e,Object.prototype.hasOwnProperty.call(V,t)?e:e.startsWith("zh-TW")||e.startsWith("zh-HK")?"zh-TW":e.startsWith("zh")?"zh-CN":e.startsWith("ja")?"ja":e.startsWith("ko")?"ko":e.startsWith("it")?"it":e.startsWith("fr")?"fr":e.startsWith("de")?"de":e.startsWith("ru")?"ru":e.startsWith("es")?"es":e.startsWith("pt")?"pt":K):Y();var t;}function J(e){const t=G[e];if(t)return t;const n=V[e].metaName;try{const t=GM_getResourceText(n);if(!t)return G[e]={},G[e];const r=JSON.parse(t);return G[e]=r,r}catch(r){return console.warn(`[Ophel] Failed to load userscript locale resource: ${e}`,r),G[e]={},G[e]}}function ee(e){const t=X(e);return Z=t,J(K),t!==K&&J(t),t}function te(){return function(e){if(e)try{const t="string"==typeof e?JSON.parse(e):e,n="object"==typeof t&&null!==t?t.state?.settings?.language:void 0;return "string"==typeof n?n:void 0}catch(t){return void console.warn("[Ophel] Failed to parse persisted settings language:",t)}}(GM_getValue("settings"))||"auto"}function ne(e){return Q.add(e),()=>{Q.delete(e);}}function re(e){const t=X(e),n=Z;Z=t,J(K),J(t),n!==t&&Q.forEach(e=>{try{e();}catch(t){console.warn("[Ophel] Userscript i18n listener failed:",t);}});}function oe(e){return X(e)}function ae(e,t){const n=J(Z),r=Z===K?n:J(K);let o=n[e]||r[e]||e;return t&&Object.keys(t).forEach(e=>{o=o.replace(new RegExp(`{${e}}`,"g"),t[e]);}),o}function ie(e){return Array.from(new Set(j.map(t=>J(t)[e]).filter(e=>"string"==typeof e&&e.trim().length>0)))}function se(){return Z}const le=Object.freeze(Object.defineProperty({__proto__:null,getAllLocalizedTexts:ie,getCurrentLang:se,getEffectiveLanguage:oe,getInitialUserscriptLanguage:te,primeUserscriptLocales:ee,setLanguage:re,subscribeI18nChanges:ne,t:ae},Symbol.toStringTag,{value:"Module"})),ce=/^https?:\/\/(?:\*\.)?(?:\[[0-9a-f:.]+\]|[a-z0-9-]+(?:\.[a-z0-9-]+)*)(?::\d{1,5})?\/\*$/i,de=e=>{const t=/^(https?):\/\/([^/]+)(\/.*)$/i.exec(e);if(!t)throw new TypeError(`Validated match pattern could not be parsed: ${e}`);return {scheme:t[1].toLowerCase(),authority:t[2],pathPattern:t[3]}},he=e=>{const t=de(e).authority.toLowerCase(),n=t.startsWith("[")?t.slice(0,t.indexOf("]")+1):t.replace(/:\d+$/,""),r=n.startsWith("*.");return {host:r?n.slice(2):n,wildcard:r}},ue=e=>{if(!ve(e))throw new TypeError(`Expected an origin-level match pattern: ${e}`);const t=de(e),n=t.authority.toLowerCase(),r=n.startsWith("*."),o=r?n.slice(2):n,a=new URL(`${t.scheme}://${o}/`);return {scheme:t.scheme,hostname:a.hostname.toLowerCase(),wildcard:r,hasExplicitPort:me(o),port:a.port}},ge=(e,t)=>e===t||e.endsWith(`.${t}`),pe=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),me=e=>e.startsWith("[")?/\]:\d+$/.test(e):/:\d+$/.test(e),fe=(e,t)=>{if("https:"!==e.protocol&&"http:"!==e.protocol)return false;const{scheme:n,authority:r,pathPattern:o}=de(t);return e.protocol===`${n}:`&&(!!((e,t,n)=>{const r=t.toLowerCase(),o=r.startsWith("*."),a=o?r.slice(2):r,i=new URL(`${n}://${a}/`),s=e.hostname.toLowerCase(),l=i.hostname.toLowerCase(),c=o?s===l||s.endsWith(`.${l}`):s===l,d=!me(a)||e.port===i.port;return c&&d})(e,r,n)&&(a=o,new RegExp(`^${a.split("*").map(pe).join(".*")}$`)).test(`${e.pathname}${e.search}`));var a;},be=e=>{const{scheme:t,authority:n}=de(e),r=n.startsWith("*.")?n.slice(2):n;return new URL(`${t}://${r}/`).origin},ve=e=>{if(!ce.test(e))return false;const{scheme:t,authority:n}=de(e),r=n.startsWith("*.")?n.slice(2):n;try{return new URL(`${t}://${r}/`),!0}catch{return false}},ye=e=>{const{scheme:t,authority:n}=de(e);return `${t}://${n.toLowerCase()}/*`},we=(e,t)=>{const n=he(e),r=he(t);return n.host===r.host||(!(!n.wildcard||!ge(r.host,n.host))||!(!r.wildcard||!ge(n.host,r.host)))},xe=()=>[{id:"default_1",title:ae("defaultPromptCodeOptTitle"),content:ae("defaultPromptCodeOptContent"),category:ae("defaultPromptCodeOptCategory")},{id:"default_2",title:ae("defaultPromptTranslateTitle"),content:ae("defaultPromptTranslateContent"),category:ae("defaultPromptTranslateCategory")}],ke="default_quick_quote_reply",Se=()=>[{id:ke,title:ae("quickQuoteReply"),description:"",iconSvg:'',showInSelectionPopover:true,steps:[{id:"default_quick_quote_reply_step",mode:"inline",promptId:"",inlineContent:ae("quickQuoteReplyTemplate"),runMode:"insert",splitMode:"none"}],createdAt:1,updatedAt:1}],Ce=[{id:"inbox",name:"收件箱",icon:"📥",isDefault:true}],Te={PAGE_WIDTH:{DEFAULT_PX:"1280",DEFAULT_PERCENT:"81",MIN_PERCENT:40,MAX_PERCENT:99,MIN_PX:1200},USER_QUERY_WIDTH:{DEFAULT_PX:"600",DEFAULT_PERCENT:"81",MIN_PERCENT:40,MAX_PERCENT:99,MIN_PX:600}},Ee={CLAUDE_KEY:/^sk-ant-sid\d{2}-/},Me=500,Ie={CLAUDE:"claude",GEMINI:"gemini",CHATGPT:"chatgpt",CHATGLM:"chatglm",GEMINI_ENTERPRISE:"gemini-enterprise",GROK:"grok",AISTUDIO:"aistudio",DOUBAO:"doubao",IMA:"ima",DEEPSEEK:"deepseek",KIMI:"kimi",QIANWEN:"qianwen",QWENAI:"qwenai",YUANBAO:"yuanbao",ZAI:"zai"},Ne=new Set(Object.values(Ie)),Ae=e=>Ne.has(e),Pe=(e,t={})=>{const n=[...e.matchPatterns];if(0===n.length&&!t.allowEmptyMatchPatterns)throw new Error(`Supported platform ${e.id} must declare at least one match pattern`);return {...e,matchPatterns:n,pattern:{test(e){let t;try{t=new URL(e);}catch{return false}return n.some(e=>fe(t,e))}}}},Le=[Pe({id:Ie.CHATGPT,name:"ChatGPT",matchPatterns:["https://chatgpt.com/*","https://*.chatgpt.com/*","https://chat.openai.com/*"],entryUrls:["https://chatgpt.com"],icon:"💬"}),Pe({id:Ie.GEMINI,name:"Gemini",matchPatterns:["https://gemini.google.com/*","https://*.gemini.google.com/*"],entryUrls:["https://gemini.google.com"],icon:"🌟"}),Pe({id:Ie.CLAUDE,name:"Claude",matchPatterns:["https://claude.ai/*","https://*.claude.ai/*","https://claude.com/*","https://*.claude.com/*"],entryUrls:["https://claude.ai"],icon:"🎭"}),Pe({id:Ie.AISTUDIO,name:"AI Studio",matchPatterns:["https://aistudio.google.com/*"],entryUrls:["https://aistudio.google.com"],icon:"🧪"}),Pe({id:Ie.GROK,name:"Grok",matchPatterns:["https://grok.com/*","https://*.grok.com/*"],entryUrls:["https://grok.com"],icon:"🤖"}),Pe({id:Ie.GEMINI_ENTERPRISE,name:"Gemini Enterprise",matchPatterns:["https://business.gemini.google/*","https://*.business.gemini.google/*"],entryUrls:["https://business.gemini.google"],icon:"🏢"}),Pe({id:Ie.DOUBAO,name:"Doubao",matchPatterns:["https://www.doubao.com/*"],entryUrls:["https://www.doubao.com"],icon:"🌱"}),Pe({id:Ie.DEEPSEEK,name:"DeepSeek",matchPatterns:["https://chat.deepseek.com/*"],entryUrls:["https://chat.deepseek.com"],icon:"🌀"}),Pe({id:Ie.KIMI,name:"Kimi",matchPatterns:["https://www.kimi.com/*"],entryUrls:["https://www.kimi.com"],icon:"🌙"}),Pe({id:Ie.ZAI,name:"Z.ai",matchPatterns:["https://chat.z.ai/*"],entryUrls:["https://chat.z.ai"],icon:"⚡"}),Pe({id:Ie.CHATGLM,name:"ChatGLM",matchPatterns:["https://chatglm.cn/*"],entryUrls:["https://chatglm.cn/main/alltoolsdetail?lang=zh"],icon:"🧠"}),Pe({id:Ie.YUANBAO,name:"Yuanbao",matchPatterns:["https://yuanbao.tencent.com/*"],entryUrls:["https://yuanbao.tencent.com"],icon:"💎"}),Pe({id:Ie.QIANWEN,name:"Qianwen",matchPatterns:["https://qianwen.com/*","https://www.qianwen.com/*"],entryUrls:["https://www.qianwen.com"],icon:"🔮"}),Pe({id:Ie.QWENAI,name:"Qwen Studio",matchPatterns:["https://chat.qwen.ai/*"],entryUrls:["https://chat.qwen.ai"],icon:"🪄"}),Pe({id:Ie.IMA,name:"ima",matchPatterns:["https://ima.qq.com/*"],entryUrls:["https://ima.qq.com"],icon:"🐼"})],Re="bookmarks",$e="ophel:usageMonitor",ze="sitepacks/installed",_e="sitepacks/origin-bindings",Oe="sitepacks/remote-state",De=Array.from( new Set(["settings","prompts","promptChains","folders","tags","conversations","readingHistory","claudeSessionKeys",Re,$e,ze,_e])),Be=[Oe,"sitepacks/extension-runtime"],qe={full:De,prompts:["prompts","promptChains"],settings:["settings"]},Fe={settings:"settings",prompts:"prompts",folders:"folders",tags:"tags"},He=new Set(["promptChains","conversations","readingHistory","claudeSessionKeys"]),Ue=new Set([$e,ze,_e]),je=new Set(De),We={settings:"backupValidationSettingsType",prompts:"backupValidationPromptsType",promptChains:"backupValidationPromptChainsType",folders:"backupValidationFoldersType",conversations:"backupValidationConversationsType",readingHistory:"backupValidationHistoryType"},Ve=e=>Boolean(e)&&"object"==typeof e&&!Array.isArray(e),Ke=(e,t)=>{if("string"!=typeof t)return t;try{return JSON.parse(t)}catch(n){throw new Xe([We[e]??"backupValidationInvalidFormat"],`Stored backup value ${e} is not valid JSON: ${String(n)}`)}},Ge=e=>Ve(e)&&Object.prototype.hasOwnProperty.call(e,"state")?e.state:void 0,Qe=(e,t)=>{const n=Fe[e];if(n){const r=Ke(e,t),o=Ge(r);return void 0===o?r:Ve(o)&&void 0!==o[n]?o[n]:o}if(He.has(e))return ((e,t)=>{const n=Ke(e,t),r=Ge(n),o=void 0===r?n:r;if("promptChains"===e){if(Array.isArray(o))return {chains:o};if(Ve(o)&&Array.isArray(o.chains))return o}if("conversations"===e&&Ve(o))return Object.prototype.hasOwnProperty.call(o,"conversations")?o:{conversations:o};if("readingHistory"===e&&Ve(o))return Object.prototype.hasOwnProperty.call(o,"history")||Object.prototype.hasOwnProperty.call(o,"lastCleanupRun")?o:{history:o};if("claudeSessionKeys"===e){if(Array.isArray(o))return {keys:o,currentKeyId:""};if(Ve(o))return o}throw new Xe([We[e]??"backupValidationInvalidFormat"],`Backup value ${e} has an invalid state shape`)})(e,t);if(e===Re)return Ke(e,t);if(Ue.has(e))return Ke(e,t);throw new Xe(["backupValidationInvalidFormat"],`Unknown backup storage key: ${e}`)},Ye=(e,t)=>["prompts","folders","tags",Re].includes(e)?Array.isArray(t)?null:We[e]??"backupValidationInvalidFormat":"promptChains"===e?Ve(t)&&Array.isArray(t.chains)?null:"backupValidationPromptChainsType":"settings"===e||"conversations"===e||"readingHistory"===e||"claudeSessionKeys"===e||Ue.has(e)?Ve(t)?null:We[e]??"backupValidationInvalidFormat":null,Ze=(e,t)=>{const n=Fe[e];if(n)return JSON.stringify({state:{[n]:t},version:0});if(He.has(e))return JSON.stringify({state:t,version:0});if(e===Re)return JSON.stringify(t);if(Ue.has(e))return t;throw new Xe(["backupValidationInvalidFormat"],`Cannot restore unknown backup storage key: ${e}`)};class Xe extends Error{errorKeys;constructor(e,t){var n;super(t),this.name="BackupCodecError",this.errorKeys=(n=e,Array.from(new Set(n)));}}const Je=e=>{if(!Ve(e))throw new Xe(["backupValidationInvalidFormat"],"Backup document must be an object");const t=[],n=e.version;if(null==n?t.push("backupValidationMissingVersion"):("number"!=typeof n||!Number.isInteger(n)||n<1||n>4)&&t.push("backupValidationInvalidFormat"),!Ve(e.data))throw t.push("backupValidationMissingData"),new Xe(t,"Backup document data must be an object");const r="number"==typeof n?n:0,o=((e,t)=>"full"===e||"prompts"===e||"settings"===e?e:null==e&&t<4?"full":null)(e.type,r);o||t.push("backupValidationInvalidFormat");const a={};for(const[s,l]of Object.entries(e.data))if(je.has(s))try{const e=Qe(s,l),n=Ye(s,e);n?t.push(n):a[s]=e;}catch(i){i instanceof Xe?t.push(...i.errorKeys):t.push(We[s]??"backupValidationInvalidFormat");}else a[s]=l;if(t.length>0||!o)throw new Xe(t,"Backup document validation failed");return {version:r,timestamp:"string"==typeof e.timestamp?e.timestamp:"",type:o,data:a}},et=async(e,t,n=(new Date).toISOString())=>{const r={};for(const o of qe[t]){const t=await e.get(o);if(null==t)continue;const n=Qe(o,t),a=Ye(o,n);if(a)throw new Xe([a],`Stored backup value ${o} is malformed`);r[o]=n;}return {version:4,timestamp:n,type:t,data:r}},tt=async(e,t)=>{const{updates:n,...r}=(e=>{const t=Je(e),n=new Set(qe[t.type]),r={},o=[],a=[];for(const[i,s]of Object.entries(t.data))je.has(i)&&n.has(i)?(r[i]=Ze(i,s),o.push(i)):a.push(i);return {document:t,updates:r,restoredKeys:o,ignoredKeys:a}})(t);return await Promise.all(Object.entries(n).map(([t,n])=>e.set(t,n))),r.ignoredKeys.length>0&&console.warn("[Ophel] Ignored non-user backup keys:",r.ignoredKeys),r},nt='@font-face {\n font-family: "Inter";\n src: local("Inter"), local("InterVariable");\n font-style: normal;\n font-weight: 100 900;\n unicode-range:\n U+0000-02FF, U+0304, U+0308, U+0329, U+0370-03FF, U+1D00-1DBF, U+1E00-1EFF,\n U+1F00-1FFF, U+0400-052F, U+1C80-1C88, U+2116, U+2DE0-2DFF, U+A640-A69F,\n U+1EA0-1EF9, U+20AB, U+2000-206F, U+20A0-20C0, U+20AC, U+2113, U+2122,\n U+2191, U+2193, U+2212, U+2215, U+2C60-2C7F, U+A720-A7FF, U+FEFF, U+FFFD;\n}',rt=["gh-platform-macos","gh-platform-windows","gh-platform-other"],ot='"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Microsoft YaHei", "PingFang SC", "Hiragino Sans SC", "Apple SD Gothic Neo", "Malgun Gothic", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", sans-serif',at=`var(--gh-font-family, ${ot})`;function it(){if("undefined"==typeof navigator)return "other";const e=navigator.userAgentData?.platform,t=[navigator.platform,e,navigator.userAgent].filter(Boolean).join(" ").toLowerCase();return /mac|iphone|ipad|ipod/.test(t)?"macos":/win/.test(t)?"windows":"other"}function st(e=it()){return "macos"===e?'"Inter", "Hiragino Sans SC", "PingFang SC", "Apple SD Gothic Neo", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Microsoft YaHei", "Malgun Gothic", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", sans-serif':ot}function lt(e){e.classList.remove(...rt),e.classList.add(function(e=it()){return `gh-platform-${e}`}());}st();function ct(e){if(e.__ophelGeminiCanvasMainInitialized)return;e.__ophelGeminiCanvasMainInitialized=true,e.document.documentElement.setAttribute("data-ophel-gemini-canvas-main","1");e.addEventListener("message",t=>{if(t.origin&&t.origin!==e.location.origin)return;const n=t.data;if("OPHEL_GEMINI_CANVAS_CODE_REQUEST"!==n?.type)return;const r="string"==typeof n.requestId?n.requestId:"";if(!r)return;const o=(t=>{const n=e.monaco?.editor?.getModels?.();if(!Array.isArray(n)||0===n.length)return "";const r=n.find(e=>{const n=e;return t&&n.uri?.toString?.()===t})||(1===n.length?n[0]:null);return "function"!=typeof r?.getValue?"":r.getValue()})("string"==typeof n.editorUri?n.editorUri:"");e.postMessage({type:"OPHEL_GEMINI_CANVAS_CODE_RESPONSE",requestId:r,code:o},"*");});}const dt="#yuanbao-canvas-container, #yb-canvas-container",ht=`${dt} .monaco-editor`;function ut(e){if(e.__ophelYuanbaoMonacoWrapInitialized)return;if("yuanbao.tencent.com"!==e.location.hostname)return;e.__ophelYuanbaoMonacoWrapInitialized=true,e.document.documentElement.setAttribute("data-ophel-yuanbao-monaco-wrap","1");const t=new Set,n=new WeakSet,r=new WeakSet;let o=null,a=false,i=false,s=null;const l=t=>{const n=t.getDomNode?.();return n instanceof e.HTMLElement&&null!==n.closest(dt)},c=e=>{l(e)&&(n.has(e)||(e.updateOptions?.({wordWrap:"on",scrollBeyondLastColumn:0,wrappingIndent:"same",scrollbar:{horizontal:"hidden"}}),n.add(e)),e.layout?.());},d=e=>{t.has(e)||(t.add(e),e.onDidDispose?.(()=>{t.delete(e);}));},h=()=>{g(),(()=>{const t=e.monaco?.editor?.getEditors?.();Array.isArray(t)&&t.forEach(d);})(),t.forEach(c),e.ResizeObserver&&(o||=new e.ResizeObserver(u),e.document.querySelectorAll(`${dt}, ${ht}`).forEach(e=>{r.has(e)||(r.add(e),o?.observe(e));}));};function u(){a||(a=true,e.setTimeout(()=>{a=false,h();},80));}function g(){const t=e.monaco?.editor,n=t?.create;if(!t||!n||n.__ophelYuanbaoMonacoWrapPatched)return;const r=function(...e){const t=n.apply(this,e);return d(t),u(),t};r.__ophelYuanbaoMonacoWrapPatched=true,t.create=r,i=true,null!==s&&(e.clearInterval(s),s=null);}new e.MutationObserver(u).observe(e.document.documentElement,{childList:true,subtree:true}),s=e.setInterval(()=>{g(),i&&h();},500),h();}const gt=/^[a-z0-9-]{2,40}$/,pt=e=>"string"==typeof e&>.test(e);function mt(e){return Array.from(e).sort().join("\0")}function ft(e){return new Set(e?e.split("\0"):[])}const bt={[Ie.AISTUDIO]:["outline","outline-user-queries","conversation-list","export-basic","model-lock","generation-detect","new-chat","stop-generation","width","zen","clean","prompt-insert","reading-history"],[Ie.CHATGLM]:["outline","outline-user-queries","export-basic","model-lock","generation-detect","new-chat","stop-generation","width","zen","clean","prompt-insert","reading-history"],[Ie.CHATGPT]:["outline","outline-user-queries","conversation-list","export-basic","model-lock","generation-detect","new-chat","stop-generation","width","zen","clean","prompt-insert","reading-history"],[Ie.CLAUDE]:["outline","outline-user-queries","document-outline","conversation-list","export-basic","model-lock","generation-detect","new-chat","stop-generation","width","zen","clean","prompt-insert","reading-history"],[Ie.DEEPSEEK]:["outline","outline-user-queries","conversation-list","export-basic","generation-detect","new-chat","stop-generation","width","zen","clean","prompt-insert","reading-history"],[Ie.DOUBAO]:["outline","outline-user-queries","conversation-list","export-basic","model-lock","generation-detect","new-chat","stop-generation","width","zen","clean","prompt-insert","reading-history"],[Ie.GEMINI]:["outline","outline-user-queries","document-outline","conversation-list","export-basic","model-lock","generation-detect","new-chat","stop-generation","width","zen","clean","prompt-insert","reading-history"],[Ie.GEMINI_ENTERPRISE]:["outline","outline-user-queries","document-outline","conversation-list","export-basic","model-lock","generation-detect","new-chat","stop-generation","width","zen","clean","prompt-insert","reading-history"],[Ie.GROK]:["outline","outline-user-queries","conversation-list","export-basic","model-lock","generation-detect","new-chat","stop-generation","width","zen","prompt-insert","reading-history"],[Ie.IMA]:["outline","outline-user-queries","export-basic","model-lock","generation-detect","new-chat","stop-generation","width","zen","clean","prompt-insert","reading-history"],[Ie.KIMI]:["outline","outline-user-queries","conversation-list","export-basic","model-lock","generation-detect","new-chat","stop-generation","width","zen","clean","prompt-insert","reading-history"],[Ie.QIANWEN]:["outline","outline-user-queries","export-basic","model-lock","generation-detect","new-chat","stop-generation","width","zen","clean","prompt-insert","reading-history"],[Ie.QWENAI]:["outline","outline-user-queries","export-basic","model-lock","generation-detect","new-chat","stop-generation","width","zen","clean","prompt-insert","reading-history"],[Ie.YUANBAO]:["outline","outline-user-queries","conversation-list","export-basic","model-lock","generation-detect","new-chat","stop-generation","width","zen","clean","prompt-insert","reading-history"],[Ie.ZAI]:["outline","outline-user-queries","export-basic","model-lock","generation-detect","new-chat","stop-generation","width","zen","prompt-insert","reading-history"]};const vt=65536,yt=50,wt=500,xt=200,kt=2e3,St=(e={})=>({errors:[],regexSafetyCheck:e.regexSafetyCheck,allowHttpMatches:true===e.allowHttpMatches}),Ct=new Set(["__proto__","prototype","constructor"]),Tt=new Set(["outline","outline-user-queries","document-outline","conversation-list","export-basic","model-lock","generation-detect","new-chat","stop-generation","width","panel-avoidance","zen","clean","prompt-insert","reading-history"]),Et=["theme","capabilities","selectors","input","conversation","generating","session","networkMonitor","modelSwitcher","export","zenMode","cleanMode","widthSelectors","panelAvoidance","documentOutline","mermaidSupport","quickQuote","supportsHostThemeSync","scrollPinRelease","outlineReverse","themeSync"],Mt=["schemaVersion","id","version","minAppVersion","name","nameI18n","description","descriptionI18n","matches",...Et],It=["targetSiteId","patchSchemaVersion","patchVersion","baseConfigVersion","minAppVersion","maxAppVersion","config"],Nt=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,At=/^#[0-9a-fA-F]{3,8}$/,Pt=e=>{if(null===e||"object"!=typeof e||Array.isArray(e))return false;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t},Lt=(e,t,n,r)=>{e.errors.push({path:t,code:n,message:r});},Rt=(e,t)=>t.errors.length>0?{valid:false,errors:t.errors}:{valid:true,value:e,errors:[]},$t=(e,t)=>"partial"===t&&null===e,zt=(e,t,n)=>{try{const r=JSON.stringify(e);if(void 0===r)return;(new TextEncoder).encode(r).byteLength>vt&&Lt(n,t,"too_large","Serialized JSON must not exceed 65536 bytes");}catch{Lt(n,t,"invalid_value","Value must be JSON serializable");}},_t=(e,t,n,r,o,a)=>{if($t(e,a))return null;if(!Pt(e))return Lt(n,t,"invalid_type","Expected an object"),null;const i=new Set(r);for(const s of Object.keys(e))!Ct.has(s)&&i.has(s)?void 0===e[s]&&Lt(n,`${t}.${s}`,"invalid_type","undefined is not valid JSON"):Lt(n,`${t}.${s}`,"unknown_key",`Unknown key: ${s}`);if("full"===a)for(const s of o)Object.prototype.hasOwnProperty.call(e,s)||Lt(n,`${t}.${s}`,"missing_required",`Missing required key: ${s}`);return e},Ot=(e,t,n,r,o={})=>!$t(e,r)&&("string"!=typeof e?(Lt(n,t,"invalid_type","Expected a string"),false):(o.allowEmpty||0!==e.length||Lt(n,t,"invalid_value","String must not be empty"),void 0!==o.maxLength&&e.length>o.maxLength&&Lt(n,t,"too_large",`String must not exceed ${o.maxLength} characters`),true)),Dt=(e,t,n,r)=>{$t(e,r)||"boolean"!=typeof e&&Lt(n,t,"invalid_type","Expected a boolean");},Bt=(e,t,n,r,o={})=>{$t(e,r)||("number"==typeof e&&Number.isFinite(e)?(o.integer&&!Number.isInteger(e)&&Lt(n,t,"invalid_value","Expected an integer"),void 0!==o.min&&e{$t(e,r)||("string"==typeof e?o.includes(e)||Lt(n,t,"invalid_value",`Expected one of: ${o.join(", ")}`):Lt(n,t,"invalid_type","Expected a string"));},Ft=(e,t,n,r,o={})=>{if($t(e,r))return false;if(!Array.isArray(e))return Lt(n,t,"invalid_type","Expected an array"),false;const a=o.maxItems??yt;e.length>a&&Lt(n,t,"too_large",`Array must not contain more than ${a} items`),void 0!==o.minItems&&e.length{const a=`${t}[${r}]`;Ot(e,a,n,"full",{allowEmpty:o.allowEmpty,maxLength:o.maxLength})&&(o.unique&&i.has(e)&&Lt(n,a,"duplicate_value",`Duplicate value: ${e}`),i.add(e),o.itemValidator?.(e,a,n));}),e.every(e=>"string"==typeof e)},Ht=(e,t,n,r)=>{Ot(e,t,n,r,{maxLength:wt});},Ut=(e,t,n,r,o=0)=>{Ft(e,t,n,r,{maxLength:wt,minItems:o});},jt=(e,t,n)=>{if(e.length>xt)Lt(n,t,"too_large","Regular expression must not exceed 200 characters");else {try{new RegExp(e);}catch{return void Lt(n,t,"invalid_pattern","Regular expression could not be compiled")}if(n.regexSafetyCheck)try{n.regexSafetyCheck(e)||Lt(n,t,"unsafe_regex","Regular expression may cause excessive backtracking");}catch{Lt(n,t,"unsafe_regex","Regular expression could not be analyzed safely");}}},Wt=(e,t,n,r)=>{Ot(e,t,n,r,{maxLength:xt})&&jt(e,t,n);},Vt=e=>(e=>e.replace(/\\(?:\r\n|[\n\r\f])/g,"").replace(/\\(?:([0-9a-fA-F]{1,6})(?:\r\n|[ \t\r\n\f])?|([^\r\n\f0-9a-fA-F]))/g,(e,t,n)=>{if(void 0===t)return n??"";const r=Number.parseInt(t,16);return 0===r||r>1114111||r>=55296&&r<=57343?"�":String.fromCodePoint(r)}))(e).replace(/\/\*[\s\S]*?\*\//g,"").toLowerCase().replace(/\s+/g," ").trim(),Kt=(e,t,n,r,o)=>{Ot(e,t,n,r,{allowEmpty:true,maxLength:o})&&((e,t,n,r)=>{if(e.length>r)return void Lt(n,t,"too_large",`CSS must not exceed ${r} characters`);const o=Vt(e),a=[{pattern:/url\s*\(/,label:"url("},{pattern:/@import\b/,label:"@import"},{pattern:/expression\s*\(/,label:"expression("},{pattern:/javascript\s*:/,label:"javascript:"}];for(const i of a)if(i.pattern.test(o))return void Lt(n,t,"unsafe_css",`CSS contains blocked token: ${i.label}`)})(e,t,n,o);},Gt=(e,t,n)=>{e.startsWith("/")&&!e.startsWith("//")||Lt(n,t,"invalid_pattern","Path must start with a single slash and remain on the current origin");},Qt=e=>{const t=Nt.exec(e);if(!t)return null;const n=t.slice(1,4).map(Number);if(n.some(e=>!Number.isSafeInteger(e)))return null;const r=t[4]?.split(".")??[];return r.some(e=>/^\d+$/.test(e)&&e.length>1&&e.startsWith("0"))?null:{major:n[0],minor:n[1],patch:n[2],prerelease:r}},Yt=e=>null!==Qt(e),Zt=(e,t)=>{const n=Qt(e),r=Qt(t);if(!n||!r)return null;for(const a of ["major","minor","patch"])if(n[a]!==r[a])return n[a]{Ot(e,t,n,r)&&!Yt(e)&&Lt(n,t,"invalid_pattern","Expected a valid semantic version");},Jt=(e,t,n)=>{if(Pt(e))for(const[r,o]of Object.entries(e))Ct.has(r)?Lt(n,`${t}.${r}`,"unknown_key",`Unsafe locale key: ${r}`):((0===r.length||r.length>35)&&Lt(n,`${t}.${r}`,"invalid_value","Invalid locale key"),Ot(o,`${t}.${r}`,n,"full"));else Lt(n,t,"invalid_type","Expected a locale-to-string object");},en=(e,t,n,r)=>{const o=_t(e,t,n,["idFromPathRegex","newConversationPathPatterns","sharePathPrefix","newTabPath"],[],r);if(o){if(void 0!==o.idFromPathRegex&&Wt(o.idFromPathRegex,`${t}.idFromPathRegex`,n,r),void 0!==o.newConversationPathPatterns&&((e,t,n,r)=>{Ft(e,t,n,r,{maxLength:xt,itemValidator:jt});})(o.newConversationPathPatterns,`${t}.newConversationPathPatterns`,n,r),void 0!==o.sharePathPrefix){const e=`${t}.sharePathPrefix`;Ot(o.sharePathPrefix,e,n,r,{maxLength:500})&&Gt(o.sharePathPrefix,e,n);}if(void 0!==o.newTabPath){const e=`${t}.newTabPath`;Ot(o.newTabPath,e,n,r,{maxLength:500})&&Gt(o.newTabPath,e,n);}}},tn=(e,t,n,r)=>{const o=_t(e,t,n,["hide","rootClass","styles"],[],r);if(o&&(void 0!==o.hide&&Ut(o.hide,`${t}.hide`,n,r),void 0!==o.rootClass&&((e,t,n,r)=>{const o=_t(e,t,n,["selector","className"],["selector","className"],r);o&&(void 0!==o.selector&&Ht(o.selector,`${t}.selector`,n,r),void 0!==o.className&&Ot(o.className,`${t}.className`,n,r,{maxLength:200}));})(o.rootClass,`${t}.rootClass`,n,r),void 0!==o.styles)){if($t(o.styles,r))return;if(!Array.isArray(o.styles))return void Lt(n,`${t}.styles`,"invalid_type","Expected an array");o.styles.length>yt&&Lt(n,`${t}.styles`,"too_large","Array must not contain more than 50 items"),o.styles.forEach((e,r)=>((e,t,n,r)=>{const o=_t(e,t,n,["selector","property","value","globalSelector","extraCss"],["selector","property","value"],r);o&&(void 0!==o.selector&&Ht(o.selector,`${t}.selector`,n,r),void 0!==o.property&&Ot(o.property,`${t}.property`,n,r,{maxLength:100}),void 0!==o.value&&Kt(o.value,`${t}.value`,n,r,kt),void 0!==o.globalSelector&&Ht(o.globalSelector,`${t}.globalSelector`,n,r),void 0!==o.extraCss&&Kt(o.extraCss,`${t}.extraCss`,n,r,kt));})(e,`${t}.styles[${r}]`,n,"full"));}},nn=(e,t,n,r)=>{$t(e,r)||(Array.isArray(e)?(e.length>yt&&Lt(n,t,"too_large","Array must not contain more than 50 items"),e.forEach((e,r)=>((e,t,n,r)=>{const o=_t(e,t,n,["selector","property","globalSelector","value","extraCss","noCenter"],["selector","property"],r);o&&(void 0!==o.selector&&Ht(o.selector,`${t}.selector`,n,r),void 0!==o.property&&Ot(o.property,`${t}.property`,n,r,{maxLength:100}),void 0!==o.globalSelector&&Ht(o.globalSelector,`${t}.globalSelector`,n,r),void 0!==o.value&&Kt(o.value,`${t}.value`,n,r,kt),void 0!==o.extraCss&&Kt(o.extraCss,`${t}.extraCss`,n,r,kt),void 0!==o.noCenter&&Dt(o.noCenter,`${t}.noCenter`,n,r));})(e,`${t}[${r}]`,n,"full"))):Lt(n,t,"invalid_type","Expected an array"));},rn=(e,t,n,r)=>{const o=_t(e,t,n,["scopeSelector","obstacleSelectors","widthSelectors","insetSelectors","defaultWidth","gap","minVisiblePanelWidth","minSafeWidth","minViewportWidth"],["widthSelectors"],r);if(o){if(void 0!==o.scopeSelector&&Ht(o.scopeSelector,`${t}.scopeSelector`,n,r),void 0!==o.obstacleSelectors&&Ut(o.obstacleSelectors,`${t}.obstacleSelectors`,n,r),void 0!==o.widthSelectors&&nn(o.widthSelectors,`${t}.widthSelectors`,n,r),void 0!==o.insetSelectors){if($t(o.insetSelectors,r))return;if(!Array.isArray(o.insetSelectors))return void Lt(n,`${t}.insetSelectors`,"invalid_type","Expected an array");o.insetSelectors.length>yt&&Lt(n,`${t}.insetSelectors`,"too_large","Array must not contain more than 50 items"),o.insetSelectors.forEach((e,r)=>((e,t,n,r)=>{const o=_t(e,t,n,["selector","scopeSelector","obstacleSelectors","applySide","insetMode","leftProperty","rightProperty","extraCss"],["selector"],r);o&&(void 0!==o.selector&&Ht(o.selector,`${t}.selector`,n,r),void 0!==o.scopeSelector&&Ht(o.scopeSelector,`${t}.scopeSelector`,n,r),void 0!==o.obstacleSelectors&&Ut(o.obstacleSelectors,`${t}.obstacleSelectors`,n,r),void 0!==o.applySide&&qt(o.applySide,`${t}.applySide`,n,r,["both","left","right"]),void 0!==o.insetMode&&qt(o.insetMode,`${t}.insetMode`,n,r,["centered","edge"]),void 0!==o.leftProperty&&Ot(o.leftProperty,`${t}.leftProperty`,n,r,{maxLength:100}),void 0!==o.rightProperty&&Ot(o.rightProperty,`${t}.rightProperty`,n,r,{maxLength:100}),void 0!==o.extraCss&&Kt(o.extraCss,`${t}.extraCss`,n,r,kt));})(e,`${t}.insetSelectors[${r}]`,n,"full"));} void 0!==o.defaultWidth&&Kt(o.defaultWidth,`${t}.defaultWidth`,n,r,kt);for(const e of ["gap","minVisiblePanelWidth","minSafeWidth","minViewportWidth"]) void 0!==o[e]&&Bt(o[e],`${t}.${e}`,n,r,{min:0});}},on=e=>Array.isArray(e)&&e.some(e=>"string"==typeof e&&e.length>0),an=(e,t,n,r)=>{ void 0!==e.theme&&((e,t,n,r)=>{const o=_t(e,t,n,["primary","secondary"],["primary","secondary"],r);if(o)for(const a of ["primary","secondary"]){const e=o[a];if(void 0!==e){const o=`${t}.${a}`;Ot(e,o,n,r)&&!At.test(e)&&Lt(n,o,"invalid_pattern","Expected a hexadecimal color literal");}}})(e.theme,`${t}.theme`,n,r),void 0!==e.capabilities&&((e,t,n,r)=>{if($t(e,r))return;if(!Array.isArray(e))return void Lt(n,t,"invalid_type","Expected an array");e.length>yt&&Lt(n,t,"too_large","Array must not contain more than 50 items");const o=new Set;e.forEach((e,r)=>{const a=`${t}[${r}]`;"string"==typeof e?(Tt.has(e)||Lt(n,a,"invalid_value",`Unknown capability: ${e}`),o.has(e)&&Lt(n,a,"duplicate_value",`Duplicate capability: ${e}`),o.add(e)):Lt(n,a,"invalid_type","Expected a string");});})(e.capabilities,`${t}.capabilities`,n,r),void 0!==e.selectors&&((e,t,n,r)=>{const o=_t(e,t,n,["textarea","submitButton","responseContainer","chatContent","userQuery","assistantResponse","newChatButton","stopButton","scrollContainer","sidebarScrollContainer","outlineExclude"],[],r);if(o){for(const e of ["textarea","submitButton","chatContent","newChatButton","stopButton","scrollContainer","outlineExclude"]) void 0!==o[e]&&Ut(o[e],`${t}.${e}`,n,r);for(const e of ["responseContainer","userQuery","assistantResponse","sidebarScrollContainer"]) void 0!==o[e]&&Ht(o[e],`${t}.${e}`,n,r);}})(e.selectors,`${t}.selectors`,n,r),void 0!==e.input&&((e,t,n,r)=>{const o=_t(e,t,n,["mode","submitKey"],["mode"],r);o&&(void 0!==o.mode&&qt(o.mode,`${t}.mode`,n,r,["textarea","contenteditable"]),void 0!==o.submitKey&&qt(o.submitKey,`${t}.submitKey`,n,r,["Enter","Ctrl+Enter"]));})(e.input,`${t}.input`,n,r),void 0!==e.conversation&&((e,t,n,r)=>{const o=_t(e,t,n,["itemSelector","idFrom","titleSelector","urlTemplate","activeMatch","navigationStrategy","shadow"],["itemSelector","idFrom","urlTemplate"],r);if(o){if(void 0!==o.itemSelector&&Ht(o.itemSelector,`${t}.itemSelector`,n,r),void 0!==o.idFrom){const e=_t(o.idFrom,`${t}.idFrom`,n,["attr","regex"],["regex"],r);void 0!==e?.attr&&Ot(e.attr,`${t}.idFrom.attr`,n,r,{maxLength:100}),void 0!==e?.regex&&Wt(e.regex,`${t}.idFrom.regex`,n,r);}if(void 0!==o.titleSelector&&Ht(o.titleSelector,`${t}.titleSelector`,n,r),void 0!==o.urlTemplate){const e=`${t}.urlTemplate`;Ot(o.urlTemplate,e,n,r,{maxLength:500})&&Gt(o.urlTemplate,e,n);} void 0!==o.activeMatch&&Ht(o.activeMatch,`${t}.activeMatch`,n,r),void 0!==o.navigationStrategy&&qt(o.navigationStrategy,`${t}.navigationStrategy`,n,r,["click-item","location"]),void 0!==o.shadow&&Dt(o.shadow,`${t}.shadow`,n,r);}})(e.conversation,`${t}.conversation`,n,r),void 0!==e.generating&&((e,t,n,r)=>{const o=_t(e,t,n,["existsSelectors"],["existsSelectors"],r);void 0!==o?.existsSelectors&&Ut(o.existsSelectors,`${t}.existsSelectors`,n,r,1);})(e.generating,`${t}.generating`,n,r),void 0!==e.session&&en(e.session,`${t}.session`,n,r),void 0!==e.networkMonitor&&((e,t,n,r)=>{const o=_t(e,t,n,["urlPatterns","urlPathEndsWith","silenceThreshold","requestBodyRules"],["urlPatterns","silenceThreshold"],r);if(o&&(void 0!==o.urlPatterns&&Ft(o.urlPatterns,`${t}.urlPatterns`,n,r,{minItems:1,maxLength:500}),void 0!==o.urlPathEndsWith&&Ft(o.urlPathEndsWith,`${t}.urlPathEndsWith`,n,r,{maxLength:500}),void 0!==o.silenceThreshold&&Bt(o.silenceThreshold,`${t}.silenceThreshold`,n,r,{min:0}),void 0!==o.requestBodyRules)){if($t(o.requestBodyRules,r))return;if(!Array.isArray(o.requestBodyRules))return void Lt(n,`${t}.requestBodyRules`,"invalid_type","Expected an array");o.requestBodyRules.length>yt&&Lt(n,`${t}.requestBodyRules`,"too_large","Array must not contain more than 50 items"),o.requestBodyRules.forEach((e,r)=>{const o=`${t}.requestBodyRules[${r}]`,a=_t(e,o,n,["type","field","metadata"],["type","field","metadata"],"full");if(a&&(void 0!==a.type&&qt(a.type,`${o}.type`,n,"full",["json-field-exists"]),void 0!==a.field&&Ot(a.field,`${o}.field`,n,"full",{maxLength:200}),void 0!==a.metadata)){const e=a.metadata;if(Pt(e))for(const[t,r]of Object.entries(e))Ct.has(t)?Lt(n,`${o}.metadata.${t}`,"unknown_key",`Unsafe key: ${t}`):null!==r&&"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r&&Lt(n,`${o}.metadata.${t}`,"invalid_type","Metadata values must be string, number, boolean, or null");else Lt(n,`${o}.metadata`,"invalid_type","Expected an object");}});}})(e.networkMonitor,`${t}.networkMonitor`,n,r),void 0!==e.modelSwitcher&&((e,t,n,r)=>{const o=_t(e,t,n,["selectorButtonSelectors","menuItemSelector","checkInterval","maxAttempts","menuRenderDelay","subMenuTriggers","subMenuSelector"],["selectorButtonSelectors","menuItemSelector"],r);if(o){ void 0!==o.selectorButtonSelectors&&Ut(o.selectorButtonSelectors,`${t}.selectorButtonSelectors`,n,r,1),void 0!==o.menuItemSelector&&Ht(o.menuItemSelector,`${t}.menuItemSelector`,n,r);for(const e of ["checkInterval","maxAttempts","menuRenderDelay"]) void 0!==o[e]&&Bt(o[e],`${t}.${e}`,n,r,{integer:true,min:"menuRenderDelay"===e?0:1});void 0!==o.subMenuTriggers&&Ft(o.subMenuTriggers,`${t}.subMenuTriggers`,n,r,{maxLength:200}),void 0!==o.subMenuSelector&&Ht(o.subMenuSelector,`${t}.subMenuSelector`,n,r);}})(e.modelSwitcher,`${t}.modelSwitcher`,n,r),void 0!==e.export&&((e,t,n,r)=>{const o=_t(e,t,n,["userQuerySelector","assistantResponseSelector","turnSelector","useShadowDOM"],["userQuerySelector","assistantResponseSelector","turnSelector","useShadowDOM"],r);if(o){for(const e of ["userQuerySelector","assistantResponseSelector"]) void 0!==o[e]&&Ht(o[e],`${t}.${e}`,n,r);void 0!==o.turnSelector&&null!==o.turnSelector&&Ht(o.turnSelector,`${t}.turnSelector`,n,r),void 0!==o.useShadowDOM&&Dt(o.useShadowDOM,`${t}.useShadowDOM`,n,r);}})(e.export,`${t}.export`,n,r),void 0!==e.zenMode&&tn(e.zenMode,`${t}.zenMode`,n,r),void 0!==e.cleanMode&&tn(e.cleanMode,`${t}.cleanMode`,n,r),void 0!==e.widthSelectors&&nn(e.widthSelectors,`${t}.widthSelectors`,n,r),void 0!==e.panelAvoidance&&rn(e.panelAvoidance,`${t}.panelAvoidance`,n,r),void 0!==e.documentOutline&&((e,t,n,r)=>{const o=_t(e,t,n,["container","scrollContainer","exclude","label","labelI18n"],["container"],r);o&&(void 0!==o.container&&Ht(o.container,`${t}.container`,n,r),void 0!==o.scrollContainer&&Ht(o.scrollContainer,`${t}.scrollContainer`,n,r),void 0!==o.exclude&&Ut(o.exclude,`${t}.exclude`,n,r),void 0!==o.label&&Ot(o.label,`${t}.label`,n,r,{maxLength:50}),void 0!==o.labelI18n&&Jt(o.labelI18n,`${t}.labelI18n`,n));})(e.documentOutline,`${t}.documentOutline`,n,r),void 0!==e.mermaidSupport&&qt(e.mermaidSupport,`${t}.mermaidSupport`,n,r,["native","fallback"]),void 0!==e.quickQuote&&qt(e.quickQuote,`${t}.quickQuote`,n,r,["enabled","native","disabled"]),void 0!==e.supportsHostThemeSync&&Dt(e.supportsHostThemeSync,`${t}.supportsHostThemeSync`,n,r),void 0!==e.scrollPinRelease&&Dt(e.scrollPinRelease,`${t}.scrollPinRelease`,n,r),void 0!==e.themeSync&&((e,t,n,r)=>{const o=_t(e,t,n,["storageKey","valuePath","valueFormat","values","darkClass","lightClass"],["storageKey","values"],r);if(o){if(void 0!==o.storageKey&&Ot(o.storageKey,`${t}.storageKey`,n,r,{maxLength:200}),void 0!==o.valuePath){const e=`${t}.valuePath`;if(Ot(o.valuePath,e,n,r,{maxLength:200}))for(const t of o.valuePath.split(".")){if(0===t.length){Lt(n,e,"invalid_value","Path segments must not be empty");break}if(Ct.has(t)){Lt(n,e,"invalid_value",`Path segment "${t}" is not allowed`);break}} void 0!==o.valueFormat&&Lt(n,`${t}.valueFormat`,"invalid_value","valueFormat is not supported together with valuePath");}else void 0!==o.valueFormat&&qt(o.valueFormat,`${t}.valueFormat`,n,r,["raw","json"]);if(void 0!==o.values){const e=_t(o.values,`${t}.values`,n,["dark","light","system"],["dark","light"],r);e&&(void 0!==e.dark&&Ot(e.dark,`${t}.values.dark`,n,r,{maxLength:100}),void 0!==e.light&&Ot(e.light,`${t}.values.light`,n,r,{maxLength:100}),void 0!==e.system&&Ot(e.system,`${t}.values.system`,n,r,{maxLength:100}));} void 0!==o.darkClass&&Ot(o.darkClass,`${t}.darkClass`,n,r,{maxLength:100}),void 0!==o.lightClass&&Ot(o.lightClass,`${t}.lightClass`,n,r,{maxLength:100})&&o.lightClass===o.darkClass&&Lt(n,`${t}.lightClass`,"invalid_value","lightClass must differ from darkClass");}})(e.themeSync,`${t}.themeSync`,n,r),void 0!==e.themeSync&&false===e.supportsHostThemeSync&&Lt(n,`${t}.themeSync`,"invalid_value","themeSync conflicts with supportsHostThemeSync: false"),"full"===r&&((e,t,n)=>{if(!Array.isArray(e.capabilities))return;const r=new Set(e.capabilities.filter(e=>"string"==typeof e&&Tt.has(e))),o=Pt(e.selectors)?e.selectors:{},a=(e,t,o)=>{r.has(e)&&!t&&Lt(n,o,"capability_requirement",`Capability ${e} requires this field`);};a("outline","string"==typeof o.responseContainer,`${t}.selectors.responseContainer`),a("conversation-list",Pt(e.conversation),`${t}.conversation`),a("export-basic",Pt(e.export),`${t}.export`),a("model-lock",Pt(e.modelSwitcher),`${t}.modelSwitcher`),a("generation-detect",Pt(e.generating)||Pt(e.networkMonitor),`${t}.generating`),a("new-chat",on(o.newChatButton),`${t}.selectors.newChatButton`),a("stop-generation",on(o.stopButton),`${t}.selectors.stopButton`),a("width",Array.isArray(e.widthSelectors)&&e.widthSelectors.length>0,`${t}.widthSelectors`),a("panel-avoidance",Pt(e.panelAvoidance),`${t}.panelAvoidance`),a("zen",Pt(e.zenMode),`${t}.zenMode`),a("clean",Pt(e.cleanMode),`${t}.cleanMode`),a("prompt-insert",on(o.textarea),`${t}.selectors.textarea`),a("prompt-insert",Pt(e.input),`${t}.input`),a("reading-history",on(o.chatContent),`${t}.selectors.chatContent`),a("outline-user-queries","string"==typeof o.userQuery,`${t}.selectors.userQuery`),a("document-outline",Pt(e.documentOutline)&&"string"==typeof e.documentOutline.container,`${t}.documentOutline.container`),r.has("outline-user-queries")&&!r.has("outline")&&Lt(n,`${t}.capabilities`,"capability_requirement","Capability outline-user-queries also requires outline");})(e,t,n);},sn=(e,t,n)=>{if(""===e||"https://*/*"===e||"http://*/*"===e)return void Lt(n,t,"invalid_pattern","Global match patterns are not allowed");const r=/^(https?):\/\/([^/]+)(\/.*)$/i.exec(e);if(!r)return void Lt(n,t,"invalid_pattern",n.allowHttpMatches?"Match pattern must use http:// or https://":"Match pattern must use https://");const o=r[1].toLowerCase();if("http"===o&&!n.allowHttpMatches)return void Lt(n,t,"invalid_pattern","Match pattern must use https://");const a=r[2];if("*"===a||a.includes("*")&&!/^\*\.[^*]+$/.test(a))return void Lt(n,t,"invalid_pattern","Top-level or malformed host wildcards are not allowed");const i=a.startsWith("*.")?a.slice(2):a;if(/^(?:\[[0-9a-fA-F:.]+\]|[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*)(?::\d{1,5})?$/.test(i))try{new URL(`${o}://${i}/`);}catch{Lt(n,t,"invalid_pattern","Match pattern contains an invalid host");}else Lt(n,t,"invalid_pattern","Match pattern contains an invalid host");};function ln(e,t={}){const n=St(t);zt(e,"$",n);const r=_t(e,"$",n,Mt,["schemaVersion","id","version","minAppVersion","name","matches","capabilities","selectors"],"full");return r?(void 0!==r.schemaVersion&&(Bt(r.schemaVersion,"$.schemaVersion",n,"full",{integer:true,min:1}),1!==r.schemaVersion&&Lt(n,"$.schemaVersion","invalid_value",`Unsupported schemaVersion: ${String(r.schemaVersion)}`)),void 0!==r.id&&Ot(r.id,"$.id",n,"full")&&!pt(r.id)&&Lt(n,"$.id","invalid_pattern","id must match ^[a-z0-9-]{2,40}$"),void 0!==r.version&&Bt(r.version,"$.version",n,"full",{integer:true,min:1}),void 0!==r.minAppVersion&&Xt(r.minAppVersion,"$.minAppVersion",n,"full"),void 0!==r.name&&Ot(r.name,"$.name",n,"full",{maxLength:200}),void 0!==r.nameI18n&&Jt(r.nameI18n,"$.nameI18n",n),void 0!==r.description&&Ot(r.description,"$.description",n,"full",{allowEmpty:true,maxLength:4e3}),void 0!==r.descriptionI18n&&Jt(r.descriptionI18n,"$.descriptionI18n",n),void 0!==r.matches&&Ft(r.matches,"$.matches",n,"full",{maxItems:10,maxLength:500,unique:true,itemValidator:sn}),an(r,"$",n,"full"),Rt(e,n)):Rt(e,n)}const cn=(e,t,n,r,o)=>{const a=(e=>new Set(e.requiredPrivateSelectorKeys??[]))(o),i="full"===r?["capabilities","selectors",...a.size>0?["sitePrivateSelectors"]:[]]:[],s=_t(e,t,n,[...Et,"sitePrivateSelectors"],i,"full");s&&(an(s,t,n,r),"full"===r&&((e,t,n,r)=>{if(!Array.isArray(e.capabilities))return;const o=new Set(e.capabilities.filter(e=>"string"==typeof e));for(const a of r)o.has(a)||Lt(n,`${t}.capabilities`,"capability_requirement",`Built-in capability cannot be removed: ${a}`);})(s,t,n,o.requiredCapabilities??[]),void 0!==s.sitePrivateSelectors&&((e,t,n,r,o,a)=>{if(!$t(e,r))if(Pt(e)){if("full"===r)for(const r of a)Object.prototype.hasOwnProperty.call(e,r)||Lt(n,`${t}.${r}`,"missing_required",`Missing required private selector: ${r}`);for(const[a,i]of Object.entries(e)){const e=`${t}.${a}`;!Ct.has(a)&&o.has(a)?$t(i,r)||("string"==typeof i?Ht(i,e,n,"full"):Ut(i,e,n,"full",1)):Lt(n,e,"unknown_key",`Private selector key is not allowed: ${a}`);}}else Lt(n,t,"invalid_type","Expected an object");})(s.sitePrivateSelectors,`${t}.sitePrivateSelectors`,n,r,(e=>new Set(e.allowedPrivateSelectorKeys??[]))(o),a));};function dn(e,t={}){const n=St(t);return cn(e,"$",n,"full",t),Rt(e,n)}function hn(e,t={}){const n=St(t);zt(e,"$",n);const r=_t(e,"$",n,It,It.filter(e=>"maxAppVersion"!==e),"full");return r?(void 0!==r.targetSiteId&&Ot(r.targetSiteId,"$.targetSiteId",n,"full")&&!pt(r.targetSiteId)&&Lt(n,"$.targetSiteId","invalid_pattern","targetSiteId must match ^[a-z0-9-]{2,40}$"),void 0!==r.patchSchemaVersion&&(Bt(r.patchSchemaVersion,"$.patchSchemaVersion",n,"full",{integer:true,min:1}),1!==r.patchSchemaVersion&&Lt(n,"$.patchSchemaVersion","invalid_value",`Unsupported patchSchemaVersion: ${String(r.patchSchemaVersion)}`)),void 0!==r.patchVersion&&Bt(r.patchVersion,"$.patchVersion",n,"full",{integer:true,min:1}),void 0!==r.baseConfigVersion&&Bt(r.baseConfigVersion,"$.baseConfigVersion",n,"full",{integer:true,min:1}),void 0!==r.minAppVersion&&Xt(r.minAppVersion,"$.minAppVersion",n,"full"),void 0!==r.maxAppVersion&&Xt(r.maxAppVersion,"$.maxAppVersion",n,"full"),"string"==typeof r.minAppVersion&&"string"==typeof r.maxAppVersion&&1===Zt(r.minAppVersion,r.maxAppVersion)&&Lt(n,"$.maxAppVersion","out_of_range","maxAppVersion must be greater than or equal to minAppVersion"),void 0!==r.config&&cn(r.config,"$.config",n,"partial",t),Rt(e,n)):Rt(e,n)}const un=864e5,gn=["https://cdn.jsdelivr.net/gh/urzeye/ophel@registry-dist/index.json","https://raw.githubusercontent.com/urzeye/ophel/registry-dist/index.json"];class pn extends Error{issues;constructor(e){super(e.map(e=>`${e.path}: ${e.message}`).join("; ")),this.name="RegistryIndexValidationError",this.issues=e;}}const mn=/^[a-z0-9-]{2,40}$/,fn=/^[a-f0-9]{64}$/i,bn=/^https:\/\/[^\s/]+\/.*$/,vn=100,yn=e=>{if(null===e||"object"!=typeof e||Array.isArray(e))return false;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t},wn=(e,t,n,r)=>{const o=new Set(t);for(const a of Object.keys(e))o.has(a)||r.push({path:`${n}.${a}`,message:"Unknown key"});},xn=(e,t,n)=>!(!Number.isSafeInteger(e)||e<1)||(n.push({path:t,message:"Expected a positive safe integer"}),false),kn=(e,t,n)=>!("string"!=typeof e||!Yt(e))||(n.push({path:t,message:"Expected a valid semantic version"}),false),Sn=(e,t,n)=>!("string"!=typeof e||!fn.test(e))||(n.push({path:t,message:"Expected a 64-character SHA-256 hex digest"}),false),Cn=(e,t,n)=>{const r=`$.packs[${t}]`;if(!yn(e))return n.push({path:r,message:"Expected an object"}),null;wn(e,["id","version","minAppVersion","matches","file","sha256","disabled"],r,n);const o=e.id;"string"==typeof o&&mn.test(o)||n.push({path:`${r}.id`,message:"Invalid pack id"});const a=xn(e.version,`${r}.version`,n),i=kn(e.minAppVersion,`${r}.minAppVersion`,n),s=((e,t,n)=>{if(!Array.isArray(e))return n.push({path:t,message:"Expected an array"}),[];e.length>10&&n.push({path:t,message:"Must not contain more than 10 match patterns"});const r=[];return e.forEach((e,o)=>{const a=`${t}[${o}]`;"string"==typeof e&&bn.test(e)?"https://*/*"!==e?r.push(e):n.push({path:a,message:"Top-level wildcard matches are forbidden"}):n.push({path:a,message:"Expected an HTTPS match pattern"});}),r})(e.matches,`${r}.matches`,n),l="string"==typeof o&&a?`packs/${o}/${e.version}.json`:null;"string"==typeof e.file&&e.file===l||n.push({path:`${r}.file`,message:`Expected immutable path: ${l}`});const c=Sn(e.sha256,`${r}.sha256`,n);return void 0!==e.disabled&&"boolean"!=typeof e.disabled&&n.push({path:`${r}.disabled`,message:"Expected a boolean"}),"string"==typeof o&&mn.test(o)&&a&&i&&"string"==typeof e.file&&e.file===l&&c&&(void 0===e.disabled||"boolean"==typeof e.disabled)?{id:o,version:e.version,minAppVersion:e.minAppVersion,matches:s,file:e.file,sha256:e.sha256.toLowerCase(),disabled:true===e.disabled}:null};function Tn(e){const t=[];if(!yn(e))throw new pn([{path:"$",message:"Expected an object"}]);wn(e,["generatedAt","schemaVersion","registryRevision","packs","patches"],"$",t),1!==e.schemaVersion&&t.push({path:"$.schemaVersion",message:"Unsupported registry schema version"}),(!Number.isSafeInteger(e.generatedAt)||e.generatedAt<1e12)&&t.push({path:"$.generatedAt",message:"Expected a Unix millisecond timestamp"});const n=xn(e.registryRevision,"$.registryRevision",t),r=Array.isArray(e.packs)?e.packs:[];Array.isArray(e.packs)?e.packs.length>vn&&t.push({path:"$.packs",message:"Must not exceed 100 entries"}):t.push({path:"$.packs",message:"Expected an array"});const o=r.map((e,n)=>Cn(e,n,t)).filter(e=>null!==e),a=Array.isArray(e.patches)?e.patches:[];Array.isArray(e.patches)?e.patches.length>vn&&t.push({path:"$.patches",message:"Must not exceed 100 entries"}):t.push({path:"$.patches",message:"Expected an array"});const i=a.map((e,n)=>((e,t,n)=>{const r=`$.patches[${t}]`;if(!yn(e))return n.push({path:r,message:"Expected an object"}),null;wn(e,["targetSiteId","patchVersion","baseConfigVersion","minAppVersion","maxAppVersion","file","sha256","disabled"],r,n);const o=e.targetSiteId;"string"==typeof o&&mn.test(o)||n.push({path:`${r}.targetSiteId`,message:"Invalid target site id"});const a=xn(e.patchVersion,`${r}.patchVersion`,n),i=xn(e.baseConfigVersion,`${r}.baseConfigVersion`,n),s=kn(e.minAppVersion,`${r}.minAppVersion`,n);let l=true;void 0!==e.maxAppVersion&&(l=kn(e.maxAppVersion,`${r}.maxAppVersion`,n),l&&s&&-1===Zt(e.maxAppVersion,e.minAppVersion)&&(n.push({path:`${r}.maxAppVersion`,message:"Must be greater than or equal to minAppVersion"}),l=false));const c="string"==typeof o&&a?`patches/${o}/${e.patchVersion}.json`:null;"string"==typeof e.file&&e.file===c||n.push({path:`${r}.file`,message:`Expected immutable path: ${c}`});const d=Sn(e.sha256,`${r}.sha256`,n);return void 0!==e.disabled&&"boolean"!=typeof e.disabled&&n.push({path:`${r}.disabled`,message:"Expected a boolean"}),"string"==typeof o&&mn.test(o)&&a&&i&&s&&l&&"string"==typeof e.file&&e.file===c&&d&&(void 0===e.disabled||"boolean"==typeof e.disabled)?{targetSiteId:o,patchVersion:e.patchVersion,baseConfigVersion:e.baseConfigVersion,minAppVersion:e.minAppVersion,..."string"==typeof e.maxAppVersion?{maxAppVersion:e.maxAppVersion}:{},file:e.file,sha256:e.sha256.toLowerCase(),disabled:true===e.disabled}:null})(e,n,t)).filter(e=>null!==e),s=new Set;o.forEach((e,n)=>{s.has(e.id)&&t.push({path:`$.packs[${n}].id`,message:`Duplicate pack id: ${e.id}`}),s.add(e.id);});const l=new Set;if(i.forEach((e,n)=>{l.has(e.targetSiteId)&&t.push({path:`$.patches[${n}].targetSiteId`,message:`Duplicate patch target: ${e.targetSiteId}`}),l.add(e.targetSiteId);}),t.length>0||!n)throw new pn(t);return {generatedAt:e.generatedAt,schemaVersion:1,registryRevision:e.registryRevision,packs:o,patches:i}}const En=(e,t,n)=>-1!==Zt(e,t)&&(!n||1!==Zt(e,n));class Mn extends Error{constructor(e){super(e),this.name="RemoteConfigStateError";}}const In=e=>{if(null===e||"object"!=typeof e||Array.isArray(e))return false;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t},Nn=/^[a-z0-9-]{2,40}$/,An=1e12,Pn=(e,t)=>{if(void 0!==e){if(!Number.isSafeInteger(e)||e{if(!In(e))throw new Mn("ignoredPatches must be an object");const t={};for(const[n,r]of Object.entries(e)){if(!Nn.test(n))throw new Mn(`ignoredPatches contains an invalid site id: ${n}`);if(!Number.isSafeInteger(r)||r<1)throw new Mn(`ignoredPatches.${n} must be a positive integer`);t[n]=r;}return t},Rn=e=>{if(void 0===e)return {};if(!In(e))throw new Mn("localPatches must be an object");const t={};for(const[n,r]of Object.entries(e)){if(!Nn.test(n))throw new Mn(`localPatches contains an invalid site id: ${n}`);if(!In(r))throw new Mn(`localPatches.${n} must be an object`);if(!Number.isSafeInteger(r.installedAt)||r.installedAt0&&(e.fileName=r.fileName),t[n]=e;}return t},$n=e=>{if(void 0===e)return {storageSchemaVersion:1,localPatches:{},ignoredPatches:{}};if(!In(e))throw new Mn("Remote config state must be an object");if(1!==e.storageSchemaVersion)throw new Mn(`Unsupported remote config storage schema: ${String(e.storageSchemaVersion)}`);const t={storageSchemaVersion:1,localPatches:Rn(e.localPatches),ignoredPatches:Ln(e.ignoredPatches)},n=(e=>{if(void 0===e)return;if(!In(e))throw new Mn("active snapshot must be an object");if("string"!=typeof e.sourceUrl)throw new Mn("active.sourceUrl must be a string");const t=Tn(e.index);if(!In(e.packs)||!In(e.patches))throw new Mn("active artifact maps must be objects");return {sourceUrl:e.sourceUrl,index:t,packs:e.packs,patches:e.patches}})(e.active),r=Pn(e.lastCheckAt,"lastCheckAt"),o=Pn(e.lastSuccessAt,"lastSuccessAt");if(n&&(t.active=n),void 0!==r&&(t.lastCheckAt=r),void 0!==o&&(t.lastSuccessAt=o),void 0!==e.lastError&&!In(e.lastError))throw new Mn("lastError must be an object");if(In(e.lastError)){const n=Pn(e.lastError.at,"lastError.at"),r=e.lastError.message,o=e.lastError.sources;if(void 0===n||"string"!=typeof r||!Array.isArray(o)||!o.every(e=>In(e)&&"string"==typeof e.sourceUrl&&"string"==typeof e.message))throw new Mn("lastError is malformed");t.lastError={at:n,message:r,sources:o};}return t};async function zn(e){return $n(await e.get(Oe))}class _n extends Error{constructor(e){super(e),this.name="RemoteConfigCacheError";}}const On=e=>{if(null===e||"object"!=typeof e||Array.isArray(e))return false;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t},Dn=/^[a-z0-9-]{2,40}$/,Bn=e=>{if(!On(e)||!On(e.index)||!On(e.manifest))return false;const t=e.index;return "string"==typeof t.id&&Number.isSafeInteger(t.version)&&"string"==typeof t.minAppVersion&&Array.isArray(t.matches)&&"string"==typeof t.file&&"string"==typeof t.sha256&&"boolean"==typeof t.disabled},qn=e=>{if(!On(e)||!On(e.index)||!On(e.patch))return false;const t=e.index;return "string"==typeof t.targetSiteId&&Number.isSafeInteger(t.patchVersion)&&Number.isSafeInteger(t.baseConfigVersion)&&"string"==typeof t.minAppVersion&&(void 0===t.maxAppVersion||"string"==typeof t.maxAppVersion)&&"string"==typeof t.file&&"string"==typeof t.sha256&&"boolean"==typeof t.disabled};const Fn={keyId:"ophel-registry-local-dev",publicKeyHex:"27d673708114a4141392fec912d1c6d4dc54b49143c9f908b71e0f5d6205362a",minRegistryRevision:1},Hn=e=>{try{const t=new URL(e);return "http:"===t.protocol&&("127.0.0.1"===t.hostname||"localhost"===t.hostname)}catch{return false}},Un=(e,t)=>!!Hn(t)||((e,t)=>!!e&&e!==t&&(Hn(e)||Hn(t)))(e,t),jn=/^(https?):\/\/[^/?#\\]+\/?$/i;class Wn extends Error{code;constructor(e,t){super(t),this.name="SitePackOriginBindingsError",this.code=e;}}const Vn=e=>{if(null===e||"object"!=typeof e||Array.isArray(e))return false;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t},Kn=(e,t,n,r)=>{const o=new Set(t),a=Object.keys(e).filter(e=>!o.has(e));if(a.length>0)throw new Wn(r,`${n} contains unknown keys: ${a.join(", ")}`)},Gn=e=>{if("string"!=typeof e||0===e.length||/\s/.test(e)||!jn.test(e))throw new Wn("invalid-origin","SitePack binding origin must contain only an http(s) scheme and exact authority");let t;try{t=new URL(e);}catch{throw new Wn("invalid-origin",`SitePack binding origin is not a valid URL: ${e}`)}if("https:"!==t.protocol&&"http:"!==t.protocol)throw new Wn("invalid-origin",`SitePack binding origin must use HTTP or HTTPS: ${e}`);if(t.username||t.password)throw new Wn("invalid-origin",`SitePack binding origin must not contain credentials: ${e}`);if(t.hostname.includes("*"))throw new Wn("invalid-origin",`SitePack binding origin must not contain a wildcard: ${e}`);if("/"!==t.pathname||e.includes("?")||e.includes("#"))throw new Wn("invalid-origin",`SitePack binding origin must not contain a path, query, or hash: ${e}`);return t.origin},Qn=e=>({mode:"explicit",packId:e.packId}),Yn=(e,t="SitePack origin binding")=>{if(!Vn(e))throw new Wn("binding-invalid",`${t} must be an object`);if("explicit"===e.mode){if(Kn(e,["mode","packId"],t,"binding-invalid"),!pt(e.packId))throw new Wn("binding-invalid",`${t}.packId must match ^[a-z0-9-]{2,40}$`);return {mode:"explicit",packId:e.packId}}throw new Wn("binding-invalid",`${t}.mode must be explicit`)},Zn=e=>Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Qn(t)])),Xn=()=>({storageSchemaVersion:1,bindings:{}}),Jn=e=>{const t={};for(const[r,o]of Object.entries(e)){const e=Gn(r);if(r!==e)throw new Wn("invalid-origin",`SitePack binding origin key must be canonical: ${r} (expected ${e})`);try{t[r]=Yn(o,`bindings[${r}]`);}catch(n){if(n instanceof Wn&&"binding-invalid"===n.code)continue;throw n}}return {storageSchemaVersion:1,bindings:Zn(t)}},er=Le.flatMap(({id:e,matchPatterns:t})=>t.map(t=>({siteId:e,pattern:t})));class tr extends Error{code;packId;validationErrors;constructor(e,t,n={}){super(t),this.name="PackManagerError",this.code=e,this.packId=n.packId,this.validationErrors=n.validationErrors;}}const nr=e=>{if(null===e||"object"!=typeof e||Array.isArray(e))return false;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t},rr=e=>structuredClone(e),or=e=>({...e,manifest:rr(e.manifest)}),ar=e=>Number.isSafeInteger(e)&&e>=1e12,ir=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),sr=(e,t)=>{if(Object.is(e,t))return true;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>sr(e,t[n]));if(!nr(e)||!nr(t))return false;const n=Object.keys(e).sort(),r=Object.keys(t).sort();return ir(n,r)&&n.every(n=>sr(e[n],t[n]))},lr=(e,t,n)=>sr(e,t)?"identical":n?"replace":t.version{const n=e.packId??t;return {code:e.code,message:e.message,...n?{packId:n}:{},...e.validationErrors?{validationErrors:e.validationErrors}:{}}},dr=(...e)=>{const t=new Map;for(const n of e.flat()){const e=`${n.packId??""}\0${n.code}\0${n.message}`;t.has(e)||t.set(e,n);}return Array.from(t.values())},hr=e=>e.enabled&&("local"===e.source||"available"===e.registryStatus);class ur{storage;appVersion;now;mutationQueue=Promise.resolve();constructor(e){if(!Yt(e.appVersion))throw new TypeError(`Invalid appVersion: ${e.appVersion}`);this.storage=e.storage,this.appVersion=e.appVersion,this.now=e.now??Date.now;}getSnapshot(){return this.enqueue(()=>this.loadSnapshot(false))}getEnabledPacks(){return this.enqueue(async()=>{const e=await this.syncRegistryPacksInternal(),t=await this.loadSnapshot(true);return {...t,issues:dr(e.issues,t.issues)}})}getOriginBindings(){return this.enqueue(()=>this.loadOriginBindingsState())}setOriginBinding(e,t){return this.enqueue(async()=>{const n=Gn(e),r=Yn(t),o=await this.loadStoredState();if(!this.parseInstalledState(o).packs.some(e=>e.manifest.id===r.packId))throw new tr("origin-binding-pack-missing",`Cannot bind ${n} to missing SitePack ${r.packId}`,{packId:r.packId});const a=await this.loadOriginBindingsState(),i=a.bindings[n];if(i&&(l=r,(s=i).mode===l.mode&&s.packId===l.packId))return {changed:false,origin:n,binding:Qn(i)};var s,l;const c=Jn({...a.bindings,[n]:r});return await this.writeOriginBindingsState(c),{changed:true,origin:n,binding:Qn(r)}})}removeOriginBinding(e){return this.enqueue(async()=>{const t=Gn(e),n=await this.loadOriginBindingsState();if(!Object.prototype.hasOwnProperty.call(n.bindings,t))return {changed:false,origin:t};const r={...n.bindings};return delete r[t],await this.writeOriginBindingsState(Jn(r)),{changed:true,origin:t}})}installLocal(e){return this.enqueue(()=>this.upsertPack(e,"local"))}installFromRegistry(e){return this.enqueue(async()=>{this.assertPackId(e);const t=await this.loadRegistryManifest(e);return this.upsertPack(t,"registry","available")})}setEnabled(e,t){return this.enqueue(async()=>{this.assertPackId(e);const n=await this.loadStoredState(),r=n.packs[e];if(void 0===r)return {changed:false};const o=this.parseStoredPack(e,r);if(t&&"registry"===o.source&&"available"!==o.registryStatus)throw new tr("registry-pack-unavailable",`Registry pack ${e} is ${o.registryStatus??"unavailable"}`,{packId:e});if(o.enabled===t)return {changed:false,pack:or(o)};const a=this.parseInstalledState(n);this.assertNoInstalledConflict(o.manifest,a.packs,e);const i={...o,enabled:t};return await this.writePack(n,e,i),{changed:true,pack:or(i)}})}uninstall(e){return this.enqueue(async()=>{this.assertPackId(e);const t=await this.loadStoredState();if(!Object.prototype.hasOwnProperty.call(t.packs,e))return {changed:false};const n=await this.loadOriginBindingsState(),r=Object.entries(n.bindings).filter(([,t])=>"explicit"===t.mode&&t.packId===e).map(([e])=>e).sort((e,t)=>e.localeCompare(t)),o={...t.packs};if(delete o[e],await this.storage.set(ze,{...t,packs:o}),r.length>0){const e={...n.bindings};for(const t of r)delete e[t];await this.writeOriginBindingsState(Jn(e));}return {changed:true,removedOriginBindings:r}})}syncRegistryPacks(){return this.enqueue(()=>this.syncRegistryPacksInternal())}enqueue(e){const t=this.mutationQueue.then(e,e);return this.mutationQueue=t.then(()=>{},()=>{}),t}getTimestamp(){const e=this.now();if(!ar(e))throw new TypeError(`PackManager now() must return a Unix millisecond timestamp: ${e}`);return e}assertPackId(e){if(!pt(e))throw new tr("invalid-pack",`Invalid SitePack id: ${e}`,{packId:e})}async loadStoredState(){const e=await this.storage.get(ze);if(void 0===e)return {storageSchemaVersion:1,packs:{}};if(!nr(e))throw new tr("storage-invalid","Installed SitePack state must be an object");const t=Object.keys(e).filter(e=>"storageSchemaVersion"!==e&&"packs"!==e);if(t.length>0)throw new tr("storage-invalid",`Installed SitePack state has unknown keys: ${t.join(", ")}`);if(1!==e.storageSchemaVersion)throw new tr("storage-schema-unsupported",`Unsupported installed SitePack storage schema: ${String(e.storageSchemaVersion)}`);if(!nr(e.packs))throw new tr("storage-invalid","Installed SitePack pack map must be an object");return {storageSchemaVersion:1,packs:{...e.packs}}}async loadOriginBindingsState(){return (e=>{if(void 0===e)return {storageSchemaVersion:1,bindings:{}};if(!Vn(e))throw new Wn("storage-invalid","SitePack origin bindings state must be an object");if(Kn(e,["storageSchemaVersion","bindings"],"SitePack origin bindings state","storage-invalid"),1!==e.storageSchemaVersion)throw new Wn("storage-schema-unsupported",`Unsupported SitePack origin bindings schema: ${String(e.storageSchemaVersion)}`);if(!Vn(e.bindings))throw new Wn("storage-invalid","SitePack origin bindings map must be an object");return Jn(e.bindings)})(await this.storage.get(_e))}async writeOriginBindingsState(e){await this.storage.set(_e,Jn(e.bindings));}parseStoredPack(e,t){if(!nr(t))throw new tr("invalid-record",`Installed pack ${e} must be an object`,{packId:e});const n=new Set(["manifest","source","installedAt","updatedAt","enabled","registryStatus"]),r=Object.keys(t).filter(e=>!n.has(e));if(r.length>0)throw new tr("invalid-record",`Installed pack ${e} has unknown keys: ${r.join(", ")}`,{packId:e});const o=this.validateManifest(t.manifest,e);if(o.id!==e)throw new tr("invalid-record",`Installed pack key ${e} does not match manifest id ${o.id}`,{packId:e});if("registry"!==t.source&&"local"!==t.source)throw new tr("invalid-record",`Installed pack ${e} has invalid source`,{packId:e});if(!ar(t.installedAt))throw new tr("invalid-record",`Installed pack ${e} has invalid installedAt`,{packId:e});if(!ar(t.updatedAt)||t.updatedAt"available"===e||"disabled"===e||"unavailable"===e)(t.registryStatus))throw new tr("invalid-record",`Installed registry pack ${e} has invalid registryStatus`,{packId:e});a=t.registryStatus;}if("local"===t.source&&void 0!==t.registryStatus)throw new tr("invalid-record",`Installed local pack ${e} must not define registryStatus`,{packId:e});return {manifest:o,source:t.source,installedAt:t.installedAt,updatedAt:t.updatedAt,enabled:t.enabled,...a?{registryStatus:a}:{}}}parseInstalledState(e){const t=[],n=[];for(const[a,i]of Object.entries(e.packs))try{t.push(this.parseStoredPack(a,i));}catch(o){if(o instanceof tr){n.push(cr(o,a));continue}throw o}t.sort((e,t)=>e.installedAt-t.installedAt||e.manifest.id.localeCompare(t.manifest.id));const r=[];for(const a of t)try{this.assertNoInstalledConflict(a.manifest,r),r.push(a);}catch(o){if(o instanceof tr){n.push(cr(o,a.manifest.id));continue}throw o}return {packs:r,issues:n}}validateManifest(e,t){const n=ln(e,{allowHttpMatches:true});if(!n.valid)throw new tr("invalid-pack",`SitePack validation failed${t?` for ${t}`:""}: ${n.errors.map(e=>`${e.path} ${e.message}`).join("; ")}`,{packId:t,validationErrors:n.errors});const r=n.value;if(!En(this.appVersion,r.minAppVersion))throw new tr("incompatible-app-version",`SitePack ${r.id} requires Ophel ${r.minAppVersion} or newer`,{packId:r.id});return this.assertNoBuiltinConflict(r),rr(r)}assertNoBuiltinConflict(e){if(Ae(e.id))throw new tr("builtin-id-conflict",`SitePack id ${e.id} conflicts with a built-in site id`,{packId:e.id});for(const t of e.matches){const n=er.find(e=>we(t,e.pattern));if(n)throw new tr("builtin-match-conflict",`SitePack ${e.id} match ${t} overlaps built-in site ${n.siteId} (${n.pattern})`,{packId:e.id})}}assertNoInstalledConflict(e,t,n){for(const r of t)if(r.manifest.id!==n)for(const t of e.matches){const n=r.manifest.matches.find(e=>we(t,e));if(n)throw new tr("installed-match-conflict",`SitePack ${e.id} match ${t} overlaps installed pack ${r.manifest.id} (${n})`,{packId:e.id})}}async loadSnapshot(e){const t=await this.loadStoredState(),n=this.parseInstalledState(t);return {storageSchemaVersion:1,packs:n.packs.filter(t=>!e||hr(t)).map(or),issues:n.issues}}async isActiveRegistryLoopback(){try{const e=await this.loadRemoteState();return Boolean(e.active&&Hn(e.active.sourceUrl))}catch{return false}}async upsertPack(e,t,n){const r=this.validateManifest(e),o=await this.loadStoredState(),a=this.parseInstalledState(o);this.assertNoInstalledConflict(r,a.packs,r.id);const i=o.packs[r.id];let s;if(void 0!==i)try{s=this.parseStoredPack(r.id,i);}catch(d){if(!(d instanceof tr))throw d}if(s&&s.source!==t)throw new tr("source-conflict",`SitePack ${r.id} is already installed from ${s.source}`,{packId:r.id});if(s){const e="registry"===t&&await this.isActiveRegistryLoopback(),a=lr(s.manifest,r,e);if("version-rollback"===a)throw new tr("version-rollback",`SitePack ${r.id} version rollback: ${r.version} < ${s.manifest.version}`,{packId:r.id});if("version-reuse"===a)throw new tr("version-reuse",`SitePack ${r.id} version ${r.version} was reused with different content`,{packId:r.id});if("identical"===a){const e="registry"===t?n:void 0;if(s.registryStatus===e)return {changed:false,pack:or(s)};const a={...s,..."registry"===t?{registryStatus:e}:{}};return await this.writePack(o,r.id,a),{changed:true,pack:or(a)}}}const l=this.getTimestamp(),c=s?{...s,manifest:r,updatedAt:Math.max(l,s.updatedAt),..."registry"===t?{registryStatus:n}:{}}:{manifest:r,source:t,installedAt:l,updatedAt:l,enabled:true,..."registry"===t?{registryStatus:n}:{}};return await this.writePack(o,r.id,c),{changed:true,pack:or(c)}}async writePack(e,t,n){await this.storage.set(ze,{...e,packs:{...e.packs,[t]:or(n)}});}async loadRemoteState(){try{return await zn(this.storage)}catch(e){throw new tr("registry-cache-invalid",`Remote SitePack cache is invalid: ${(e=>e instanceof Error?e.message:String(e))(e)}`)}}async loadRegistryManifest(e){const t=(await this.loadRemoteState()).active,n=t?.index.packs.find(t=>t.id===e);if(n?.disabled)throw new tr("registry-pack-disabled",`Registry pack ${e} is disabled`,{packId:e});const r=t?.packs[e];if(!t||!n||!r)throw new tr("registry-pack-unavailable",`Registry pack ${e} is not available in the active cache`,{packId:e});return this.validateCachedRegistryPack(e,r,n)}validateCachedRegistryPack(e,t,n){if(!Bn(t)||t.index.disabled)throw new tr("registry-cache-invalid",`Registry cache metadata is invalid for ${e}`,{packId:e});if(n.disabled)throw new tr("registry-pack-disabled",`Registry pack ${e} is disabled`,{packId:e});const r=t.index.id===n.id&&t.index.version[e.manifest.id,e])),l={...e.packs};let c=false;for(const h of t.packs){if("registry"!==h.source)continue;const e=h.manifest.id,t=a.active.index.packs.find(t=>t.id===e);let u=h;if(t)if(t.disabled)u=this.withRegistryStatus(h,"disabled");else {const r=a.active.packs[e];if(r)try{const o=this.validateCachedRegistryPack(e,r,t);this.assertNoInstalledConflict(o,Array.from(s.values()),e);const a=lr(h.manifest,o,i);if("version-rollback"===a)throw new tr("version-rollback",`Registry pack ${e} version rollback: ${o.version} < ${h.manifest.version}`,{packId:e});if("version-reuse"===a)throw new tr("version-reuse",`Registry pack ${e} version ${o.version} was reused with different content`,{packId:e});"replace"===a?(u={...h,manifest:o,updatedAt:Math.max(this.getTimestamp(),h.updatedAt),registryStatus:"available"},n.push(e)):u=this.withRegistryStatus(h,"available");}catch(d){if(!(d instanceof tr))throw d;o.push(cr(d,e));continue}else u=this.withRegistryStatus(h,"unavailable");}else u=this.withRegistryStatus(h,"unavailable");u.registryStatus!==h.registryStatus&&r.push(e),sr(u,h)||(c=true,l[e]=or(u),s.set(e,u));}return c&&await this.storage.set(ze,{...e,packs:l}),{changed:c,updatedPackIds:n,statusChangedPackIds:r,issues:dr(o)}}withRegistryStatus(e,t){return e.registryStatus===t?e:{...e,registryStatus:t}}}const gr=Object.freeze(Object.defineProperty({__proto__:null,shouldInitializeOnCurrentSite:async function(){const e=window.location.href;let t;try{t=new URL(e);}catch{return false}const n=Le.flatMap(e=>e.matchPatterns);for(const o of n)if(fe(t,o))return true;try{const e=GM_getValue(ze,null);if(e?.packs)for(const n of Object.values(e.packs))if(n.enabled&&n.manifest?.matches)for(const e of n.manifest.matches)if(fe(t,e))return !0}catch(r){console.debug("[Ophel] Failed to check installed SitePacks during whitelist check:",r);}try{const e=GM_getValue(_e,null);if(e?.bindings&&e.bindings[t.origin])return !0}catch(r){console.debug("[Ophel] Failed to check origin bindings during whitelist check:",r);}return false}},Symbol.toStringTag,{value:"Module"})),pr="ophel",mr="Ophel Atlas",fr=false,br=GM_info?.script?.version??"1.0.0";function vr(){return "undefined"!=typeof window&&window.__OPHEL_USERSCRIPT_ASSET_URLS__?.icon||""}const yr=e=>new ur({storage:e,appVersion:br}),wr="scrollTop",xr="scrollBottom",kr="goToAnchor",Sr="togglePanel",Cr="togglePanelMode",Tr="toggleTheme",Er="openSettings",Mr="switchTab1",Ir="switchTab2",Nr="switchTab3",Ar="toggleUserQueries",Pr="onlyUserQueries",Lr="toggleBookmarks",Rr="locateOutline",$r="searchOutline",zr="refreshOutline",_r="prevHeading",Or="nextHeading",Dr="toggleOutlineExpand",Br="expandLevel1",qr="expandLevel2",Fr="expandLevel3",Hr="expandLevel4",Ur="expandLevel5",jr="expandLevel6",Wr="newConversation",Vr="refreshConversations",Kr="locateConversation",Gr="prevConversation",Qr="nextConversation",Yr="exportConversation",Zr="copyLatestReply",Xr="copyLastCodeBlock",Jr="toggleScrollLock",eo="toggleZenMode",to="focusInput",no="openGlobalSearch",ro="stopGeneration",oo="togglePromptQueue",ao="showShortcuts",io="showModelSelector",so="openClaudeSettings",lo="switchClaudeKey",co="openGeminiSettings",ho="openThemeSettings",uo="openModelLockSettings",go={scrollTop:{labelKey:"shortcutScrollTop",label:"去顶部",category:"navigation"},scrollBottom:{labelKey:"shortcutScrollBottom",label:"去底部",category:"navigation"},goToAnchor:{labelKey:"shortcutGoToAnchor",label:"返回锚点",category:"navigation"},togglePanel:{labelKey:"shortcutTogglePanel",label:"展开/收起面板",category:"panel"},togglePanelMode:{labelKey:"shortcutTogglePanelMode",label:"切换面板模式(吸附/悬浮)",category:"panel"},toggleTheme:{labelKey:"shortcutToggleTheme",label:"切换主题",category:"panel"},switchTab1:{labelKey:"shortcutSwitchTab1",label:"切换到第 1 个标签",category:"panel"},switchTab2:{labelKey:"shortcutSwitchTab2",label:"切换到第 2 个标签",category:"panel"},switchTab3:{labelKey:"shortcutSwitchTab3",label:"切换到第 3 个标签",category:"panel"},toggleUserQueries:{labelKey:"shortcutToggleUserQueries",label:"显示用户问题",category:"outline"},onlyUserQueries:{labelKey:"shortcutOnlyUserQueries",label:"只显示用户问题",category:"outline"},toggleBookmarks:{labelKey:"shortcutToggleBookmarks",label:"显示用户收藏",category:"outline"},locateOutline:{labelKey:"shortcutLocateOutline",label:"定位大纲",category:"outline"},searchOutline:{labelKey:"shortcutSearchOutline",label:"搜索大纲",category:"outline"},prevHeading:{labelKey:"shortcutPrevHeading",label:"上一个标题",category:"outline"},nextHeading:{labelKey:"shortcutNextHeading",label:"下一个标题",category:"outline"},refreshOutline:{labelKey:"shortcutRefreshOutline",label:"刷新大纲",category:"outline"},toggleOutlineExpand:{labelKey:"shortcutToggleOutlineExpand",label:"展开/折叠全部",category:"outline"},expandLevel1:{labelKey:"shortcutExpandLevel1",label:"展开到 1 级",category:"outline"},expandLevel2:{labelKey:"shortcutExpandLevel2",label:"展开到 2 级",category:"outline"},expandLevel3:{labelKey:"shortcutExpandLevel3",label:"展开到 3 级",category:"outline"},expandLevel4:{labelKey:"shortcutExpandLevel4",label:"展开到 4 级",category:"outline"},expandLevel5:{labelKey:"shortcutExpandLevel5",label:"展开到 5 级",category:"outline"},expandLevel6:{labelKey:"shortcutExpandLevel6",label:"展开到 6 级",category:"outline"},newConversation:{labelKey:"shortcutNewConversation",label:"新会话",category:"conversation"},refreshConversations:{labelKey:"shortcutRefreshConversations",label:"刷新会话列表",category:"conversation"},locateConversation:{labelKey:"shortcutLocateConversation",label:"定位当前会话",category:"conversation"},prevConversation:{labelKey:"shortcutPrevConversation",label:"上一个会话",category:"conversation"},nextConversation:{labelKey:"shortcutNextConversation",label:"下一个会话",category:"conversation"},exportConversation:{labelKey:"shortcutExportConversation",label:"导出对话",category:"edit"},copyLatestReply:{labelKey:"shortcutCopyLatestReply",label:"复制最新回复",category:"edit"},copyLastCodeBlock:{labelKey:"shortcutCopyLastCodeBlock",label:"复制最后代码块",category:"edit"},toggleScrollLock:{labelKey:"shortcutToggleScrollLock",label:"锁定滚动",category:"edit"},toggleZenMode:{labelKey:"shortcutToggleZenMode",label:"切换禅模式",category:"edit"},focusInput:{labelKey:"shortcutFocusInput",label:"聚焦输入框",category:"edit"},openGlobalSearch:{labelKey:"navGlobalSearch",label:"全局搜索",category:"edit"},stopGeneration:{labelKey:"shortcutStopGeneration",label:"停止生成",category:"edit"},togglePromptQueue:{labelKey:"shortcutTogglePromptQueue",label:"显示/隐藏提示词队列",category:"edit"},showModelSelector:{labelKey:"shortcutShowModelSelector",label:"模型选择菜单",category:"edit"},openSettings:{labelKey:"shortcutOpenSettings",label:"打开设置",category:"settings"},showShortcuts:{labelKey:"shortcutShowShortcuts",label:"快捷键一览",category:"settings"},openThemeSettings:{labelKey:"shortcutOpenThemeSettings",label:"打开外观主题",category:"settings"},openModelLockSettings:{labelKey:"shortcutOpenModelLockSettings",label:"打开模型锁定",category:"settings"},openGeminiSettings:{labelKey:"shortcutOpenGeminiSettings",label:"打开 Gemini 专属",category:"settings"},openClaudeSettings:{labelKey:"shortcutOpenClaudeSettings",label:"打开 Claude 专属",category:"settings"},switchClaudeKey:{labelKey:"shortcutSwitchClaudeKey",label:"一键切换可用 Claude Key",category:"settings"}},po={navigation:{labelKey:"shortcutCategoryNavigation",label:"导航"},panel:{labelKey:"shortcutCategoryPanel",label:"面板"},outline:{labelKey:"shortcutCategoryOutline",label:"大纲"},conversation:{labelKey:"shortcutCategoryConversation",label:"会话"},edit:{labelKey:"shortcutCategoryEdit",label:"交互控制"},settings:{labelKey:"shortcutCategorySettings",label:"设置"}},mo={scrollTop:{key:"t",alt:true},scrollBottom:{key:"b",alt:true},goToAnchor:{key:"z",alt:true},togglePanel:{key:"p",alt:true},togglePanelMode:{key:"m",alt:true},toggleTheme:{key:"d",alt:true},switchTab1:{key:"1",alt:true},switchTab2:{key:"2",alt:true},switchTab3:{key:"3",alt:true},refreshOutline:{key:"r",alt:true},toggleOutlineExpand:{key:"e",alt:true},expandLevel1:{key:"1",alt:true,shift:true},expandLevel2:{key:"2",alt:true,shift:true},expandLevel3:{key:"3",alt:true,shift:true},expandLevel4:{key:"4",alt:true,shift:true},expandLevel5:{key:"5",alt:true,shift:true},expandLevel6:{key:"6",alt:true,shift:true},toggleUserQueries:{key:"q",alt:true},toggleBookmarks:{key:"c",alt:true},onlyUserQueries:{key:"q",alt:true,shift:true},prevHeading:{key:"ArrowUp",alt:true},nextHeading:{key:"ArrowDown",alt:true},locateOutline:{key:"l",alt:true},searchOutline:{key:"f",alt:true},newConversation:{key:"o",ctrl:true,shift:true},refreshConversations:{key:"r",alt:true,shift:true},locateConversation:{key:"l",alt:true,shift:true},prevConversation:{key:"[",alt:true},nextConversation:{key:"]",alt:true},exportConversation:{key:"e",ctrl:true,shift:true},copyLatestReply:{key:"c",ctrl:true,shift:true},copyLastCodeBlock:{key:";",alt:true},toggleScrollLock:{key:"s",alt:true},toggleZenMode:{key:"z",ctrl:true,shift:true},focusInput:{key:"i",alt:true},openGlobalSearch:{key:"k",ctrl:true},stopGeneration:{key:"k",alt:true},togglePromptQueue:{key:"j",alt:true},showModelSelector:{key:"/",alt:true},showShortcuts:{key:"\\",alt:true},openSettings:{key:",",alt:true},openClaudeSettings:{key:"c",ctrl:true,alt:true},switchClaudeKey:{key:"s",ctrl:true,alt:true},openGeminiSettings:{key:"g",ctrl:true,alt:true},openThemeSettings:{key:"t",ctrl:true,alt:true},openModelLockSettings:{key:"l",ctrl:true,alt:true}},fo={enabled:true,globalUrl:"https://gemini.google.com",keybindings:mo},bo={Backquote:"`",Minus:"-",Equal:"=",BracketLeft:"[",BracketRight:"]",Backslash:"\\",Semicolon:";",Quote:"'",Comma:",",Period:".",Slash:"/"},vo={"å":"a","∫":"b","ç":"c","∂":"d","´":"e","ƒ":"f","©":"g","˙":"h","ˆ":"i","∆":"j","˚":"k","¬":"l","µ":"m","˜":"n","ø":"o","π":"p","œ":"q","®":"r","ß":"s","†":"t","¨":"u","√":"v","∑":"w","≈":"x","¥":"y","Ω":"z","¡":"1","™":"2","£":"3","¢":"4","∞":"5","§":"6","¶":"7","•":"8","ª":"9","º":"0","⁄":"1","€":"2","‹":"3","›":"4","fi":"5","fl":"6","‡":"7","°":"8","·":"9","‚":"0","–":"-","—":"-","≠":"=","±":"=","“":"[","”":"[","‘":"]","’":"]","«":"\\","»":"\\","…":";","æ":"'","Æ":"'","≤":",","¯":",","≥":".","˘":".","÷":"/","¿":"/"};function yo(e,t){if(t){if(/^Key[A-Z]$/.test(t))return t.slice(3).toLowerCase();if(/^Digit[0-9]$/.test(t))return t.slice(5);if(bo[t])return bo[t]}return vo[e]?vo[e]:e}function wo(e){if(!e)return e;return {key:yo(e.key),alt:!!e.alt,ctrl:!!e.ctrl||!!e.meta,shift:!!e.shift}}function xo(e){return e?{enabled:e.enabled??true,globalUrl:e.globalUrl||fo.globalUrl,keybindings:(t=e.keybindings,(t?Object.fromEntries(Object.entries(t).map(([e,t])=>[e,null===t?null:wo(t)])):t)||fo.keybindings)}:e;var t;}function ko(e,t=false){const n=wo(e);if(!n)return [];const r=[];n.ctrl&&r.push(t?"⌘":"Ctrl"),n.meta&&t&&r.push("⌘"),n.alt&&r.push(t?"⌥":"Alt"),n.shift&&r.push(t?"⇧":"Shift");const o=yo(n.key),a={ArrowUp:"↑",ArrowDown:"↓",ArrowLeft:"←",ArrowRight:"→",",":","}[o]||o.toUpperCase();return r.push(a),r}function So(e,t=false){return ko(e,t).join(t?"":"+")}function Co(){if("undefined"==typeof navigator)return false;const e=navigator.platform?.toLowerCase?.()||"",t=navigator.userAgent?.toLowerCase?.()||"",n=navigator.userAgentData?.platform?.toLowerCase?.();return e.includes("mac")||e.includes("iphone")||e.includes("ipad")||e.includes("ipod")||!!n?.includes("mac")||t.includes("mac os")||t.includes("macintosh")||t.includes("iphone")||t.includes("ipad")||t.includes("ipod")}function To(){return "userscript"}function Eo(){try{return !0}catch{return console.warn("[Ophel] Failed to get platform type, falling back to runtime detection"),"undefined"!=typeof GM_info}}function Mo(){return function(){if(!Eo())return null;try{return "undefined"==typeof GM_info?null:"string"==typeof GM_info.scriptHandler?GM_info.scriptHandler:null}catch{return null}}()?.toLowerCase().replace(/\s+/g,"").includes("scriptcat")??false}const Io=Eo(),No={mode:"light",lightStyleId:"google-gradient",darkStyleId:"classic-dark"},Ao={enabled:false,value:"81",unit:"%"},Po={enabled:false,value:"81",unit:"%"},Lo={enabled:false,showExitButton:true},Ro={enabled:true},$o={enabled:true},zo=[{id:"panel",enabled:true},{id:"floatingToolbar",enabled:true},{id:"globalSearch",enabled:true},{id:"theme",enabled:true},{id:"zenMode",enabled:true},{id:"settings",enabled:true},{id:"scrollTop",enabled:true},{id:"manualAnchor",enabled:false},{id:"anchor",enabled:true},{id:"scrollBottom",enabled:true}],_o={collapsed:zo.map(e=>({...e})),opacity:1,floatingToolbar:{open:true},hideWhenPanelOpen:false,proximityRadius:150},Oo={language:"auto",hasAgreedToTerms:false,hasSeenOphelAdvancedGuide:false,remoteConfig:{autoUpdate:true,registrySourceUrl:""},panel:{panelExpanded:true,panelMode:"floating",edgeTriggerMode:"handle",preventAutoScroll:false,defaultPosition:"right",defaultEdgeDistance:0,edgeSnapThreshold:30,height:85,width:320,resizeOnHover:false,hoverWidth:520},geminiEnterprise:{policyRetry:{enabled:false,maxRetries:3}},content:{assistantMermaid:true,markdownFix:false,watermarkRemoval:Io,formulaCopy:true,formulaCopyFormat:"latex",formulaDelimiter:true,tableCopy:true,userQueryMarkdown:true},export:{customUserName:"",customModelName:"",exportFilenameTimestamp:false,includeThoughts:true,exportShowIndex:false,exportMarkdownDivider:"---",exportShowDialog:true,packaging:"markdown",defaultExportFormat:"markdown"},theme:{syncNativePageTheme:true,sites:{gemini:{...No},"gemini-enterprise":{...No},doubao:{...No},ima:{...No},deepseek:{...No},yuanbao:{...No},zai:{...No},_default:{...No}},customStyles:[]},layout:{pageWidth:{gemini:{...Ao},"gemini-enterprise":{...Ao},grok:{...Ao},aistudio:{...Ao},chatgpt:{...Ao},claude:{...Ao},chatglm:{...Ao},doubao:{...Ao},ima:{...Ao},deepseek:{...Ao},kimi:{...Ao},qianwen:{...Ao},qwenai:{...Ao},yuanbao:{...Ao},zai:{...Ao},_default:{...Ao}},userQueryWidth:{gemini:{...Po},"gemini-enterprise":{...Po},grok:{...Po},aistudio:{...Po},chatgpt:{...Po},claude:{...Po},chatglm:{...Po},doubao:{...Po},ima:{...Po},deepseek:{...Po},kimi:{...Po},qianwen:{...Po},qwenai:{...Po},yuanbao:{...Po},zai:{...Po},_default:{...Po}},zenMode:{gemini:{...Lo},"gemini-enterprise":{...Lo},grok:{...Lo},aistudio:{...Lo},chatgpt:{...Lo},claude:{...Lo},chatglm:{...Lo},doubao:{...Lo},ima:{...Lo},deepseek:{...Lo},kimi:{...Lo},qianwen:{...Lo},qwenai:{...Lo},yuanbao:{...Lo},zai:{...Lo},_default:{...Lo}},cleanMode:{gemini:{...$o},"gemini-enterprise":{...$o},aistudio:{...$o},chatgpt:{...$o},claude:{...$o},chatglm:{...$o},doubao:{...$o},ima:{...$o},deepseek:{...$o},kimi:{...$o},qianwen:{...$o},qwenai:{...$o},yuanbao:{...$o},zai:{...$o},_default:{...$o}},panelAvoidance:{gemini:{...Ro},"gemini-enterprise":{...Ro},grok:{...Ro},aistudio:{...Ro},chatgpt:{...Ro},claude:{...Ro},chatglm:{...Ro},doubao:{...Ro},ima:{...Ro},deepseek:{...Ro},kimi:{...Ro},qianwen:{...Ro},qwenai:{...Ro},yuanbao:{...Ro},zai:{...Ro},_default:{...Ro}}},modelLock:{gemini:{enabled:false,keyword:""},"gemini-enterprise":{enabled:false,keyword:""},ima:{enabled:false,keyword:""},qwenai:{enabled:false,keyword:""},yuanbao:{enabled:false,keyword:""}},globalSearch:{promptEnterBehavior:"smart",enableFuzzySearch:false,doubleShift:false},usageMonitor:{enabled:false,dailyLimit:100,autoResetEnabled:false},features:{order:["outline","conversations","prompts"],prompts:{enabled:true,doubleClickToSend:false,submitShortcut:"enter",promptQueue:false,quickQuoteEnabled:true},conversations:{enabled:true,syncUnpin:false,syncDelete:true,folderRainbow:true},outline:{enabled:true,maxLevel:6,autoUpdate:true,updateInterval:2,showUserQueries:true,followMode:"current",expandLevel:6,inlineBookmarkMode:"always",panelBookmarkMode:"always",showWordCount:false}},tab:{openInNewTab:false,autoRename:true,renameInterval:3,showStatus:true,hideStatusWhenRead:false,titleFormat:"{status}{title}->{model}",showNotification:Io,notificationSound:true,notificationSoundPreset:"softChime",notificationVolume:.5,notificationRepeatCount:3,notificationRepeatInterval:2,notifyWhenFocused:false,autoFocus:false,privacyMode:false,privacyTitle:"Google",customIcon:"default"},readingHistory:{persistence:true,autoRestore:true,cleanupDays:3},quickButtons:{collapsed:zo.map(e=>({...e})),opacity:_o.opacity,floatingToolbar:{..._o.floatingToolbar},hideWhenPanelOpen:_o.hideWhenPanelOpen,proximityRadius:_o.proximityRadius},claude:{currentKeyId:""},webdav:{enabled:false,url:"",username:"",password:"",syncMode:"manual",syncInterval:30,remoteDir:"ophel",dataSources:["settings","conversations","prompts","claudeSessionKeys"]},shortcuts:fo,aistudio:{collapseNavbar:false,collapseTools:false,collapseAdvanced:false,enableSearch:true,defaultModel:"",markdownFix:Io,removeWatermark:Io},chatgpt:{markdownFix:false}},Do=e=>{const t=e.trim();if(!t)throw new TypeError("Registry source must not be empty");let n;try{n=new URL(t);}catch{throw new TypeError(`Invalid registry source URL: ${t}`)}const r="http:"===n.protocol&&("127.0.0.1"===n.hostname||"localhost"===n.hostname);if("https:"!==n.protocol&&!r)throw new TypeError(`Registry source must use HTTPS: ${t}`);return n.href},Bo="settings";class qo extends Error{constructor(e){super(e),this.name="PersistedSettingsError";}}const Fo=e=>{if(null===e||"object"!=typeof e||Array.isArray(e))return false;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t},Ho=["language","hasAgreedToTerms","panel","content","theme","layout","features","tab","quickButtons","remoteConfig"],Uo=e=>{if(null==e)return;const t=(e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){throw new qo(`Persisted settings are not valid JSON: ${t.message}`)}})(e);if(!Fo(t))throw new qo("Persisted settings must be an object");if("state"in t){if(!Fo(t.state))throw new qo("Persisted settings state must be an object");if(!("settings"in t.state)||!Fo(t.state.settings))throw new qo("Persisted settings envelope must contain an object at state.settings");return t.state.settings}if(n=t,!Ho.some(e=>e in n))throw new qo("Persisted settings object has no recognized settings fields");var n;return t},jo=e=>{const t=Uo(e);if(!t)return;const n=t.remoteConfig;if(void 0!==n){if(!Fo(n))throw new qo("remoteConfig must be an object");return n}},Wo=async e=>(e=>{const t=jo(e);if(!t)return Oo.remoteConfig.autoUpdate;const{autoUpdate:n}=t;if(void 0===n)return Oo.remoteConfig.autoUpdate;if("boolean"!=typeof n)throw new qo("remoteConfig.autoUpdate must be a boolean");return n})(await e.get(Bo)),Vo=async e=>(e=>{const t=jo(e);if(!t)return;const{registrySourceUrl:n}=t;if(void 0!==n&&""!==n){if("string"!=typeof n)throw new qo("remoteConfig.registrySourceUrl must be a string");try{return Do(n)}catch(r){throw new qo(`remoteConfig.registrySourceUrl is invalid: ${r.message}`)}}})(await e.get(Bo)),Ko=(()=>{const e=".chat-turn-container.user",t=".chat-turn-container.model",n=`${t}, .model-prompt-container`,r="ms-library-table",o=[`${r} table a[href*="/prompts/"]:not([href*="new_chat"])`,`${r} .prompt-card a[href*="/prompts/"]:not([href*="new_chat"])`].join(", "),a=`${r} .prompt-cards-container`,i=".chunk-editor-main",s=`${i} footer ms-prompt-box`,l=[".ms-sliding-right-panel-dialog","mat-dialog-container.mat-mdc-dialog-container"].join(", "),c='button .material-symbols-outlined:not([class*="keyboard"])';return {capabilities:[...bt[Ie.AISTUDIO]],selectors:{textarea:["textarea.textarea","textarea.cdk-textarea-autosize",'textarea[placeholder*="prompt"]','textarea[placeholder*="Start typing"]'],submitButton:['ms-run-button button[type="submit"]','ms-run-button.supports-add-instead-of-run button[type="submit"]','button[ms-button][type="submit"]','button.ms-button-primary[type="submit"]'],responseContainer:".chat-container, main",chatContent:[".chat-turn-container",'[class*="message"]','[class*="response"]'],userQuery:e,assistantResponse:t,newChatButton:['button[iconname="add"]','button[data-test-clear="outside"]','button .material-symbols-outlined[aria-hidden="true"]'],stopButton:["ms-stop-button",'button:has(mat-icon[fonticon="stop"])','button mat-icon[fonticon="stop"]'],scrollContainer:[".chat-container",".virtual-scroll-container",'[class*="scroll"]','main [style*="overflow"]','main [class*="overflow"]'],sidebarScrollContainer:"ms-navbar-v2"},input:{mode:"textarea",submitKey:"Enter"},conversation:{itemSelector:o,idFrom:{attr:"href",regex:"/prompts/([^/?#]+)"},urlTemplate:"/prompts/{id}",navigationStrategy:"click-item",shadow:false},generating:{existsSelectors:["ms-stop-button",'button mat-icon[fonticon="stop"]',c,".mat-progress-spinner",".mat-progress-bar"]},modelSwitcher:{selectorButtonSelectors:["button.model-selector-card",".model-selector-card"],menuItemSelector:".model-options-container button.content-button",checkInterval:1e3,maxAttempts:10,menuRenderDelay:300},export:{userQuerySelector:e,assistantResponseSelector:t,turnSelector:null,useShadowDOM:false},widthSelectors:[{selector:".chat-session-content",property:"max-width"},{selector:".chat-turn-container",property:"max-width"},{selector:s,property:"max-width",extraCss:"width: 100% !important; min-width: 0 !important;"},{selector:".table-container > table",property:"width",value:"100%",noCenter:true,extraCss:"min-width: 100% !important;"}],zenMode:{hide:["ms-navbar","ms-navbar-v2","ms-right-side-panel"]},cleanMode:{hide:["ms-hallucinations-disclaimer"]},mermaidSupport:"fallback",quickQuote:"disabled",supportsHostThemeSync:true,sitePrivateSelectors:{scrollbarButton:["ms-items-scrollbar button[aria-controls]","ms-items-scrollbar button[data-test-item-id]","ms-prompt-scrollbar button[aria-controls]","ms-prompt-scrollbar button[data-test-item-id]"].join(", "),activeScrollbarButton:'[aria-pressed="true"], .ms-button-active',pageHeading:"h1[class*='mode-title'], h1.page-title, .page-title h1",sidebarTitleLink:'a.prompt-link[href*="/prompts/"], a.name-btn[href*="/prompts/"]',validTextarea:"textarea",layoutScope:i,editorScope:"ms-chunk-editor",modelSidebar:l,panelChatContentWidth:`${i} .chat-session-content`,panelChatTurnWidth:`${i} .chat-turn-container`,panelPromptBoxWidth:s,panelTableWidth:`${i} .table-container > table`,panelChatSafeArea:`${i} .chat-container .chat-view-container`,panelPromptSafeArea:`${i} footer`,markdownFixerTarget:"ms-cmark-node span.ng-star-inserted",modelNameMarker:'[data-test-id="model-name"]',runSettingsToggleButton:'button[aria-label="Toggle run settings panel"]',runSettingsCloseButton:'button[aria-label="Close run settings panel"]',modelCategoryButton:"[data-test-category-button]",modelCardName:"div > div > div > span:first-child",modelSidebarCloseButton:"button[data-test-close-button]",libraryNavigationLink:['ms-navbar-v2 a[href="/library"]','a[href="/library"]'],libraryRoot:r,libraryTable:`${r} table`,libraryMobileCards:a,libraryTableWrapper:`${r} .lib-table-wrapper`,libraryCard:".prompt-card",libraryEmptyState:[`${r} .empty-state`,`${r} [class*="empty" i]`,`${r} [class*="no-results" i]`,`${r} [class*="no-prompts" i]`,`${r} [data-test-id*="empty" i]`,`${r} [aria-label*="empty" i]`].join(", "),sidebarConversationLink:'a[href*="/prompts/"]',conversationVisibilityLink:['a.prompt-link[href*="/prompts/"]','a.name-btn[href*="/prompts/"]','a.name-link[href*="/prompts/"]','a[href*="/prompts/"]'].join(", "),conversationRemovalContainer:["tr","li","mat-row",".prompt-card"],libraryRow:["tr","mat-row",".prompt-card"],conversationMenuButton:['button[aria-haspopup="menu"]','button[aria-label*="More"]','button[aria-label*="more"]','button[aria-label*="更多"]','button[aria-label*="更多选项"]','button[aria-label*="选项"]','button[title*="More"]','button[title*="more"]'].join(", "),conversationMenuItem:'[role="menuitem"], [role="menu"] button, .mat-mdc-menu-panel button',conversationDialog:'[role="dialog"], mat-dialog-container, .mat-mdc-dialog-container',turn:"ms-chat-turn",turnContent:".turn-content",userContentNoise:'.author-label, .actions-container, button, [role="button"], svg, [aria-hidden="true"], ms-image-chunk, ms-file-chunk',assistantContentNoise:'.author-label, .actions-container, button, [role="button"], svg, [aria-hidden="true"]',userContentChunk:["ms-text-chunk","ms-prompt-chunk.text-chunk","ms-prompt-chunk","ms-cmark-node.cmark-node.user-chunk"],userPromptContainer:".user-prompt-container",userImageAttachment:"ms-image-chunk img",userFileAttachment:"ms-file-chunk",userFileName:".name",userFileAriaLabel:"[aria-label]",userFileDetails:".token-count",userFileLink:"a[href]",outlineContainer:".chat-container",outlineAssistantContainer:`${t}, .chat-turn-container:not(.user)`,markdownNode:"ms-cmark-node",thoughtChunk:"ms-thought-chunk",inlineCode:".inline-code",katex:"ms-katex",katexAnnotation:'annotation[encoding="application/x-tex"]',codeBlock:"ms-code-block",codeBlockContent:["pre code","pre"],codeBlockLanguage:".mat-expansion-panel-header-title .ng-star-inserted:last-child",assistantFragment:n,chatSession:"ms-chat-session",promptChunk:"ms-prompt-chunk",mountedContent:"ms-text-chunk, ms-thought-chunk, ms-image-chunk, ms-file-chunk, img",textChunk:"ms-text-chunk",runButton:"ms-run-button",generationTextStopIndicator:c,modelNameText:["span.title","span"],themeEventTarget:"app-root, ms-app, body"}}})(),Go=(()=>{const e=".conversation-list",t=".conversation-container",n=".conversation-inner",r=".conversation.question",o=".question-txt",a=".answer-content-wrap",i=".markdown-body",s=`${a} ${i}`,l=[".advance-thinking",".advance-thinking-area",".advanced-thinking",".advanced-thinking-data",".text-advance-thinking-content",".thinking-chain-container",".thinking-block",".thinking-content",".thinking-item","[class*='thinking']","[class*='think']","[class*='reason']","[class*='cot']"].join(", "),c=[".gh-root",".gh-user-query-markdown",".assistant-name",".interact-container",".code-no-artifacts .top-outer",".code-no-artifacts .copy-button","button","[role='button']","svg","[aria-hidden='true']","style","script"].join(", "),d=".enter-icon-container",h=".empty",u=[".enter.searching .enter-icon-container",".stop-generate",".stop-stream-tip",".answer-content-wrap .generating-icon",".enter-icon-container.stop",".enter.searching",".enter.is-main-chat.searching"],g=[".dialogue .detail .item",".dialogue .detail .item.item",".dialogue .detail .item.item.item"].join(", "),p=[i,`${i}${i}`,`${a} ${i}`].join(", "),m=["width: 100% !important;","margin-left: 0 !important;","margin-right: 0 !important;","box-sizing: border-box !important;"].join(" "),f=".selecttheme-list";return {capabilities:[...bt[Ie.CHATGLM]],selectors:{textarea:["#search-input-box textarea",".main-chat-search #search-input-box textarea",".main-chat-search textarea"],submitButton:[`${d}:not(${h})`],responseContainer:e,chatContent:[s,o],userQuery:r,assistantResponse:a,newChatButton:[".new-session",'div[class~="new-session"]'],stopButton:u,scrollContainer:[e,".chatScrollContainer"]},input:{mode:"textarea",submitKey:"Enter"},generating:{existsSelectors:[...u]},networkMonitor:{urlPatterns:["/chatglm/backend-api/assistant/stream"],silenceThreshold:2e3},modelSwitcher:{selectorButtonSelectors:[".wrapper-title",".wrapper-title .showHideText",".model-select-icon-container",".selected-model-info",".model-select-container"],menuItemSelector:".model-select-list .model-select-item",menuRenderDelay:150,checkInterval:1e3,maxAttempts:10},export:{userQuerySelector:r,assistantResponseSelector:a,turnSelector:null,useShadowDOM:false},widthSelectors:[{selector:t,property:"max-width"},{selector:n,property:"max-width"},{selector:e,property:"max-width"},{selector:g,property:"max-width"},{selector:p,property:"max-width"},{selector:".code-no-artifacts .markdown-body.md-code, .code-no-artifacts .md-code",property:"max-width",value:"100%",extraCss:m,noCenter:true},{selector:".code-no-artifacts .markdown-body.md-code > .language, .code-no-artifacts .markdown-body.md-code pre",property:"max-width",value:"100%",extraCss:"width: 100% !important; box-sizing: border-box !important;",noCenter:true},{selector:".markdown-body table, .answer-content-wrap .markdown-body table",property:"width",value:"100%",extraCss:"table-layout: fixed !important; display: table !important; min-width: 100% !important;",noCenter:true},{selector:".markdown-body table th, .markdown-body table td",property:"min-width",value:"0",noCenter:true},{selector:e,property:"width",value:"100%"},{selector:".conversation-bottom",property:"max-width",extraCss:"flex: 1 !important;"},{selector:".component-box-new",property:"max-width"}],zenMode:{hide:[".el-aside"]},cleanMode:{hide:[".policy-wrap, .policy-wrap *",".vip-btn",".slogan-banner"]},quickQuote:"native",sitePrivateSelectors:{nativeQuotePopover:['[class*="quote-button"]','[class*="reference-button"]','[aria-label*="引用"]','[aria-label*="quote"]'],themeOptionCandidates:[`.theme-popper ${f}`,`.selecttheme ${f}`,f],themeRootCandidates:["#app","[data-v-app]",".app",".app-container"],conversationScope:t,conversationInner:n,newChatGuideSafeArea:".init-page .main-chat-guide-container",canvasLayoutScope:"section.el-container:has(> .code-preview-tabs)",canvasPreviewSafeArea:".code-preview-tabs",conversationItem:".conversation-item",userText:o,assistantMarkdown:s,thinkingContainer:l,exportDecoration:c,conversationTitle:".conversation-name",collapseButton:".collapse-button-bg",markdownBody:i,userAttachmentCandidates:"a[href], button, [class*='file'], [class*='image-with-text']",attachmentNameRoot:"button, a, [class*='file']",thoughtContent:"blockquote[slot='content'], blockquote, .text-advance-thinking-content .markdown-body, .thinking-content .markdown-body, .advance-thinking-area .markdown-body, .markdown-body",avatar:".user-img, .avatar, .user-avatar, .userInfoBar-header",modelName:[".wrapper-title .showHideText",".wrapper-title .wrapper-title-innerText",".wrapper-title",".selected-model-info .model-select-name",".model-select-container .model-select-name",".model-select-list .model-select-item.selected .model-select-name",".model-select-name"],messageWidth:g,markdownWidth:p,submitButton:d,submitButtonDisabled:h}}})(),Qo=(()=>{const e='[data-message-author-role="user"]',t='[data-message-author-role="assistant"]',n=".whitespace-pre-wrap",r=".sr-only",o=".markdown.markdown-new-styling",a=`.self-end.bg-token-bg-tertiary ${n}`,i=['[data-testid="stop-button"]','form[data-type="unified-composer"] #composer-submit-button[aria-label*="Stop"]','form[data-type="unified-composer"] #composer-submit-button[aria-label*="停止"]','form[data-type="unified-composer"] button.composer-submit-btn[aria-label*="Stop"]','form[data-type="unified-composer"] button.composer-submit-btn[aria-label*="停止"]'],s='[data-radix-popper-content-wrapper] [role="menu"][data-radix-menu-content]',l='iframe[title="internal://deep-research"], iframe[src*="connector_openai_deep_research"]',c='[role="dialog"]:has([data-testid="fullscreen-shell-body"])',d=`${c} [data-testid="fullscreen-shell-body"]`,h=`${d} div:has(> .ProseMirror.markdown.prose)`,u=`${c} div.fixed[class*="start-1/2"]:has(> form[class*="group/composer"])`,g=`${d} ~ * form[class*="group/composer"]`;return {capabilities:[...bt[Ie.CHATGPT]],selectors:{textarea:["#prompt-textarea",'textarea[data-id="root"]','[contenteditable="true"]'],submitButton:['[data-testid="send-button"]','button[aria-label="Send prompt"]','button[aria-label="发送"]'],responseContainer:`#thread, main#main, ${o}`,chatContent:[t,e,".markdown"],userQuery:e,assistantResponse:t,newChatButton:['[data-testid="create-new-chat-button"]','a[href="/"]','button[aria-label="New chat"]','button[aria-label="新对话"]'],stopButton:[...i],scrollContainer:['[class*="scrollbar-gutter"], [class*="@container/main"] > div'],sidebarScrollContainer:"#history"},input:{mode:"contenteditable",submitKey:"Enter"},conversation:{itemSelector:'a[data-sidebar-item="true"][href^="/c/"], a[data-sidebar-item="true"][href*="chatgpt.com/c/"]',idFrom:{attr:"href",regex:"(?:^|/)c/([a-z0-9-]+)(?:[/?#]|$)"},titleSelector:".truncate [dir='auto']",urlTemplate:"/c/{id}",activeMatch:"[data-active]",navigationStrategy:"click-item",shadow:false},generating:{existsSelectors:[...i]},networkMonitor:{urlPatterns:["backend-api/f/conversation"],urlPathEndsWith:["backend-api/f/conversation"],silenceThreshold:3e3,requestBodyRules:[{type:"json-field-exists",field:"thinking_effort",metadata:{domCompletionRequired:true}}]},modelSwitcher:{selectorButtonSelectors:['button[class*="__composer-pill"][aria-haspopup="menu"]'],menuItemSelector:'[data-radix-collection-item][data-testid^="model-switcher-"], [role="menuitemradio"][data-testid^="model-switcher-"], [role="menuitem"][data-testid^="model-switcher-"]',checkInterval:1e3,maxAttempts:15,menuRenderDelay:500},export:{userQuerySelector:e,assistantResponseSelector:t,turnSelector:'[data-testid^="conversation-turn"]',useShadowDOM:false},widthSelectors:[{selector:'[class*="thread-content-max-width"]',property:"max-width"},{selector:'[style*="--thread-content-max-width"]',property:"max-width"},{selector:h,property:"max-width",extraCss:"width: 100% !important; min-width: 0 !important;"},{selector:u,property:"width",extraCss:"max-width: calc(100vw - 32px) !important; min-width: 0 !important;"}],zenMode:{hide:["#stage-slideover-sidebar","div.select-none:has(> .pointer-events-auto)","[data-testid='thread-disclaimer']"]},cleanMode:{hide:["div.select-none:has(> .pointer-events-auto)","[data-testid='thread-disclaimer']",'div.border-token-border-default.border-t.py-4.text-sm:has(button[aria-label="Ad options"]):has([role="link"][tabindex="0"])']},mermaidSupport:"native",quickQuote:"native",supportsHostThemeSync:true,sitePrivateSelectors:{nativeQuotePopover:['div[aria-live="polite"].start-0.top-0.select-none.absolute','div[style*="transform: translate3d"] .shadow-long',"button.btn-secondary.rounded-none.border-none"],conversationTitleFallback:[".truncate span",".truncate","span"],conversationPinnedTrailingPair:".trailing-pair",conversationPinnedTrailingIcon:".trailing svg",conversationActionButton:['button[aria-haspopup="menu"]','button[aria-label*="More"]','button[aria-label*="more"]','button[aria-label*="更多"]','button[data-testid*="menu"]',".trailing button"].join(", "),conversationActionIndicator:'button[aria-haspopup="menu"], .trailing button',conversationMenu:'[role="menu"]',conversationMenuItem:'[role="menuitem"], [data-radix-collection-item][role="menuitem"]',codexTaskMarkdown:o,codexTaskUserQuery:a,validTextarea:'#prompt-textarea, [contenteditable="true"]',userQueryText:n,srOnly:r,srOnlyFallback:"[class*='sr-only']",assistantMarkdown:".markdown, .prose, [class*='prose']",exportCleanup:`${r}, button, [role="button"], svg, [aria-hidden="true"]`,exportTurnContainer:'section[data-turn], [data-testid^="conversation-turn"]',exportMountedMessage:"[data-message-author-role]",exportImageContainer:'[class*="imagegen-image"], [data-testid*="image-gen"]',exportFileTile:'[role="group"][aria-label], [class*="file-tile"]',exportFileLabel:"[aria-label]",exportFileName:".truncate.font-semibold",deepResearchIframe:l,markdownFixerParagraph:`${t} p`,userQueryWidthRoot:":root",panelScope:"main#main",panelObstacle:[[l,"#stage-slideover-sidebar"].join(", ")],panelThreadContentWidth:'#thread [class*="thread-content-max-width"]:not(:has(form[data-type="unified-composer"]))',panelThreadLegacyWidth:'#thread [style*="--thread-content-max-width"]:not(:has(form[data-type="unified-composer"]))',panelComposerFormWidth:'main#main form[data-type="unified-composer"]',panelLibraryComposerFormWidth:g,panelNewChatHeadingInset:"#thread .relative.basis-auto.flex-col.shrink.flex.justify-end:has(h1)",panelThreadInset:'#thread [class*="--thread-content-margin:"][class*="px-(--thread-content-margin)"]',panelCanvasDialogInset:'main#main [role="dialog"][class*="fixed"][class*="inset-0"]:has(.cm-editor)',panelLibraryShellInset:d,panelLibraryComposerWrapperInset:u,nativeTocRail:".no-scrollbar",nativeTocButton:'button[aria-label][class*="h-0.5"][class*="w-4.5"]',nativeTocHoverAncestor:[".relative.flex.items-start",".fixed"],nativeTocTitleElement:["button[data-fill] [title]",'button[class*="__menu-item"] [title]',"ul button [title]","[role='menu'] [title]",".absolute [title]"],nativeTocActive:"[data-toc-active]",modelMenu:s,modelMenuItem:`${s} [data-testid^="model-switcher-"]`,modelMessageSlug:"[data-message-model-slug]",modelNameContainer:".min-w-0",modelSelectedIndicator:".trailing svg, .trailing use",modelSelectorName:"span.truncate, span[class*='truncate']"}}})(),Yo=(()=>{const e='[data-testid="user-message"]',t=".font-claude-response",n="#wiggle-file-content",r=['button[aria-label="Stop response"]'],o=':is(main[data-perf-region="main"], #main-content)',a=[[`${o} div:has(> [data-testid="chat-header"]):has([data-autoscroll-container="true"])`,`${o} div:has(> [data-testid="page-header"]):has([data-autoscroll-container="true"])`,`${o} div:has(> [data-testid="page-header"]):has(> [data-autoscroll-container="true"])`].join(", "),`${o}:not(:has([data-autoscroll-container="true"]))`].join(", "),i=[`${o} [data-testid="chat-stale-nav-frame"] > div > div:not([aria-hidden="true"]):has([data-skill-file-viewer="true"])`,`${o} [data-testid="chat-stale-nav-inert"] > div > div:not([aria-hidden="true"]):has([data-skill-file-viewer="true"])`].join(", "),s=[n,'[data-testid="artifact-panel"]','[data-testid="artifact-sidebar"]'].join(", ");return {capabilities:[...bt[Ie.CLAUDE]],selectors:{textarea:['[contenteditable="true"]',".ProseMirror",'div[role="textbox"]'],submitButton:['button[aria-label="Send Message"]','button[aria-label="Send message"]','button[data-testid="send-button"]','button[aria-label="Send"]'],responseContainer:t,chatContent:[`div${e}`,`div${t}`],userQuery:e,assistantResponse:t,newChatButton:['a[aria-label="New chat"]','a[href*="/new"]'],stopButton:[...r],scrollContainer:['[data-autoscroll-container="true"]',`${o} .overflow-y-scroll`,"#root .overflow-y-auto.overflow-x-hidden"],sidebarScrollContainer:'[data-testid="sidebar"], nav'},input:{mode:"contenteditable",submitKey:"Enter"},conversation:{itemSelector:'[data-testid="sidebar"] a[href*="/chat/"]',idFrom:{attr:"href",regex:"/chat/([a-f0-9-]+)"},titleSelector:".dframe-fade-label, span.truncate",urlTemplate:"/chat/{id}",navigationStrategy:"click-item",shadow:false},generating:{existsSelectors:[...r,'[data-is-streaming="true"]','[class*="streaming"], [class*="typing"]']},networkMonitor:{urlPatterns:["/api/"],urlPathEndsWith:["/completion"],silenceThreshold:500},modelSwitcher:{selectorButtonSelectors:['button[data-testid="model-selector-dropdown"]'],menuItemSelector:'[role="menuitem"], [role="menuitemradio"]',checkInterval:1e3,maxAttempts:20,subMenuSelector:'[aria-haspopup="menu"]',subMenuTriggers:["more models","更多模型"]},export:{userQuerySelector:e,assistantResponseSelector:t,turnSelector:null,useShadowDOM:false},widthSelectors:[{selector:`${o} [data-testid="chat-column"]`,property:"max-width",extraCss:"width: 100% !important; min-width: 0 !important;"},{selector:`${o} .max-w-screen-md`,property:"max-width",extraCss:"width: 100% !important; min-width: 0 !important;"},{selector:`${o} .max-w-3xl`,property:"max-width",extraCss:"width: 100% !important; min-width: 0 !important;"},{selector:`${o} .max-w-4xl`,property:"max-width",extraCss:"width: 100% !important; min-width: 0 !important;"}],zenMode:{hide:["aside.dframe-sidebar",'[data-testid="sidebar"]'],styles:[{selector:'main[data-perf-region="main"] .dframe-content-inner',property:"padding-left",value:"var(--df-content-gutter, 8px)"}]},cleanMode:{hide:['[data-disclaimer="true"]']},mermaidSupport:"native",quickQuote:"native",supportsHostThemeSync:true,sitePrivateSelectors:{nativeQuotePopover:['[data-selection-tooltip="true"]'],validTextarea:'[contenteditable="true"], .ProseMirror, [role="textbox"]',sidebarScrollFallback:"div.overflow-y-auto",conversationGroup:"[class*='group/nsh'], div.flex.flex-col",conversationGroupHeading:"span[role=button], h3",conversationGroupList:"ul",conversationPinnedList:"ul.-mx-1\\.5",conversationActionButton:['button[aria-haspopup="menu"]','button[data-testid*="menu"]','button[aria-label*="more"]','button[aria-label*="More"]','button[aria-label*="options"]','button[aria-label*="Options"]','button[aria-label*="更多"]','button[aria-label*="选项"]','button[aria-label*="選項"]'].join(", "),conversationMenu:'[role="menu"], [data-radix-menu-content], [data-state="open"]',conversationMenuItem:'[role="menuitem"], button',conversationMenuItemFallback:'[role="menuitem"], [role="menu"] button',conversationDialog:'[role="dialog"], [aria-modal="true"], [data-state="open"]',documentRoot:n,hiddenAncestor:'[aria-hidden="true"]',responseMarkdown:".standard-markdown, .progressive-markdown",documentViewer:'[data-skill-file-viewer="true"]',documentPanelTitle:"h2[title]",documentBackButton:'button[aria-label="Go back"]',documentContentTitle:"h1",artifactCell:".artifact-block-cell",artifactMetadata:".text-text-400",artifactTitle:".line-clamp-1",artifactContainer:".group\\/artifact-block, [class*='group/artifact-block']",artifactViewButton:'button[aria-label="View Document"]',virtualSizer:"[data-rocksteady-sizer]",virtualRow:"[data-rs-index][data-index]",virtualArticle:'[role="article"][aria-setsize]',outlineIgnoredHeading:".pointer-events-none",srOnly:".sr-only",userQueryText:"p.whitespace-pre-wrap",userMessageBubble:"[data-cds='UserMessage'], [data-user-message-bubble='true']",userMessageBoundary:`${t}, main, [role='main']`,userFileThumbnail:'[data-testid="file-thumbnail"]',thoughtToggle:"button[aria-expanded]",thoughtStatus:'span[role="status"][aria-live="polite"]',layoutScope:o,panelScope:a,panelObstacle:s,panelScrollSafeArea:`${o} [data-autoscroll-container="true"]`,panelNewChatSafeArea:`${o}:has(.ProseMirror):not(:has([data-autoscroll-container="true"]))`,panelCanvasScope:i,userQueryWidth:e}}})(),Zo=(()=>{const e=".ds-scroll-area",t=".ds-message",n=".ds-markdown",r=`${t}:has(${n})`,o=`${t}:not(:has(${n}))`,a=[`main ${e}:has(${t})`,`[role="main"] ${e}:has(${t})`,`${e}:has(${t})`].join(", "),i=".ds-icon-button",s=".ds-focus-ring",l='svg path[d="M8.3125 0.981587C8.66767 1.0545 8.97902 1.20558 9.2627 1.43374C9.48724 1.61438 9.73029 1.85933 9.97949 2.10854L14.707 6.83608L13.293 8.25014L9 3.95717V15.0431H7V3.95717L2.70703 8.25014L1.29297 6.83608L6.02051 2.10854C6.26971 1.85933 6.51277 1.61438 6.7373 1.43374C6.97662 1.24126 7.28445 1.04542 7.6875 0.981587C7.8973 0.94841 8.1031 0.956564 8.3125 0.981587Z"]',c='svg path[d^="M2 4.88"]',d=[`div[role="button"]${i}:has(${l})`,`button${i}:has(${l})`],h=[`div[role="button"]${i}:has(${c})`,`button${i}:has(${c})`],u=`:is(.ds-virtual-list:has(${t}), .ds-virtual-list:has(textarea${e}))`,g=`#root > div:has(textarea${e}):not(:has(${t}))`,p=`div[aria-hidden="false"]:has(iframe) ${e}`,m=[u,g].join(", "),f=`${u} .ds-virtual-list-items`,b=`${u} > div:has(textarea${e})`,v=[`${o} > .gh-inline-bookmark + div`,`${o} > div:not(.gh-user-query-raw):not(.gh-user-query-markdown):not(${s})`,`${o} > div.gh-user-query-markdown`].join(", "),y=".ds-virtual-list-items",w=".ds-virtual-list-visible-items";return {capabilities:[...bt[Ie.DEEPSEEK]],selectors:{textarea:['textarea[placeholder*="DeepSeek"]','textarea[placeholder*="deepseek"]',`textarea${e}`,"form textarea"],submitButton:d,responseContainer:a,chatContent:[r,o],userQuery:o,assistantResponse:r,newChatButton:['a[href="/a/chat"]','a[href="/a/chat/"]'],stopButton:h},input:{mode:"textarea",submitKey:"Enter"},conversation:{itemSelector:'a[href*="/a/chat/s/"]',idFrom:{attr:"href",regex:"/a/chat/s/([a-z0-9-]+)"},urlTemplate:"/a/chat/s/{id}",activeMatch:'[aria-current="page"]',navigationStrategy:"click-item",shadow:false},generating:{existsSelectors:[...h]},networkMonitor:{urlPatterns:["/api/v0/chat/completion"],silenceThreshold:500},export:{userQuerySelector:o,assistantResponseSelector:r,turnSelector:null,useShadowDOM:false},widthSelectors:[{selector:":root",property:"--message-list-max-width",noCenter:true},{selector:f,property:"--message-list-max-width",noCenter:true}],zenMode:{hide:[".dc04ec1d","._0fcaa63"]},cleanMode:{hide:["._0fcaa63"]},quickQuote:"enabled",sitePrivateSelectors:{sidebarScrollArea:e,message:t,assistantMarkdown:n,thoughtContainer:".ds-think-content",iconButton:i,focusRing:s,composerButton:[`div[role="button"]${i}`,`button${i}`,`${i}[aria-disabled="false"]`].join(", "),selectedModel:".ds-toggle-button--selected",newChatLayoutScope:g,canvasLayoutScope:'#root > div:has(.ds-virtual-list):has(div[aria-hidden="false"] iframe)',canvasPreviewSafeArea:p,panelAvoidanceScope:m,messageListItems:f,messageComposer:b,userMessageContent:v,nativeOutlineList:".ds-virtual-list",nativeOutlineItems:y,nativeOutlineVisibleItems:w,nativeOutlineContentRoots:`${y}, ${w}`,nativeOutlinePaddingScope:'[style*="--scroll-nav-page-padding"]',nativeOutlineExcludedAncestor:"aside, nav",mainRegion:"main, [role='main']",shareTitleMeta:'meta[property="og:title"], meta[name="twitter:title"]'}}})(),Xo=(()=>{const e="#flow_chat_sidebar",t=`${e} a[id^="conversation_"][href*="/chat/"]`,n=`${e} > div:nth-child(2)`,r='[class*="v_list_scroller"]',o='[data-target-id="message-box-target-id"]',a="[data-message-id]",i=`${a}.justify-end`,s=[".whitespace-pre-wrap.wrap-anywhere:not(.gh-user-query-markdown)",".md-box-root:not(.gh-user-query-markdown)"],l=s.join(", "),c=`${a}:not(.justify-end)`,d=[".flow-markdown-body",".md-box-root"],h=d.join(", "),u=d.map(e=>`${c} ${e}`).join(", "),g='[data-container-name="main"]',p=`${g} .max-w-\\(--content-max-width\\)`,m=`${g} .max-w-\\[var\\(--content-max-width\\)\\]`,f=`${g} .flex.h-full.min-h-0.w-full.flex-1.flex-col:has(${r}):has([class*="input-content-container"])`,b=`${g} [class*="-mt-[var(--header-height)]"][class*="flex-grow"][class*="items-center"]:has([class*="input-content-container"])`,v="aside:has(.code-canvas)",y='button[data-slot="dropdown-menu-trigger"][aria-haspopup="menu"]',w='[data-testid="chat_input_local_break_button"]';return {capabilities:[...bt[Ie.DOUBAO]],selectors:{textarea:['[data-slate-editor="true"]','textarea[data-testid="chat_input_input"]',"textarea.semi-input-textarea"],submitButton:["[data-testid='chat_input_send_button']","#flow-end-msg-send",".send-btn-wrapper button"],responseContainer:r,chatContent:[u,i],userQuery:i,assistantResponse:c,newChatButton:[n],stopButton:[w]},input:{mode:"contenteditable",submitKey:"Enter"},conversation:{itemSelector:t,idFrom:{attr:"id",regex:"^conversation_(.+)$"},titleSelector:'[data-testid="chat_list_item_title"], [class*="overallTitle-"], [class*="title-"]',urlTemplate:"/chat/{id}",activeMatch:'[aria-current="page"], [class*="active-link-"], .e2e-test-active',navigationStrategy:"click-item",shadow:false},generating:{existsSelectors:[w]},modelSwitcher:{selectorButtonSelectors:[y],menuItemSelector:'div[role="menuitem"][data-slot="dropdown-menu-item"]',menuRenderDelay:100},export:{userQuerySelector:i,assistantResponseSelector:c,turnSelector:o,useShadowDOM:false},widthSelectors:[{selector:g,property:"max-width"},{selector:".max-w-\\(--content-max-width\\)",property:"max-width"},{selector:".max-w-\\[var\\(--content-max-width\\)\\]",property:"max-width"},{selector:'[style*="--content-max-width"]',property:"--content-max-width"},{selector:".chrome70-container",property:"--center-content-max-width"}],zenMode:{hide:["nav",".container-qOgFQp",".container-hzjmF1"]},cleanMode:{hide:[".container-qOgFQp",'[aria-label="活动入口"]']},quickQuote:"native",supportsHostThemeSync:false,sitePrivateSelectors:{nativeQuotePopover:['[data-word-selection-toolbar="true"]',".toolContainer-tlVomx",".toolItem-C_B5bD"],slateElement:'[data-slate-node="element"]',historyContainer:`${e} [data-history-container="true"]`,pinnedConversation:'[class*="pin-"]',virtualRow:".v_list_row",virtualScrollHolder:'[data-name="scroll_holder"]',shareMessageList:'[class*="message-list-root-"]',messageBlock:o,messageId:a,userQueryTextContainer:l,renderedUserQueryMarkdown:s[1],assistantMarkdown:h,assistantExportDecoration:["button","[role='button']","svg","[aria-hidden='true']","picture","img",'[data-foundation-type="receive-message-action-bar"]','[data-foundation-type="receive-message-suggest-foundation"]'].join(", "),userAttachmentCard:'[data-plugin-identifier="block_type:10052"] [data-available="true"]',generatedImageBlock:'[data-plugin-identifier="block_type:2074"]',assistantImageContainers:'[class*="image-wrapper"], [class*="image-box-grid-item"], [class*="image-box-grid"]',generatedImageWrapper:'[class*="image-wrapper"]',generatedImageGridItem:'[class*="image-box-grid-item"]',modelName:".truncate",conversationMarqueeTitle:'[data-testid="conversation-list-v2-item"] span[title]',conversationMenuWrapper:'[class*="chat-item-menu-wrapper-"]',conversationMenuTrigger:y,conversationMenuInnerButton:'button[data-dbx-name="button"]',conversationMenuGenericTrigger:'button[aria-haspopup="menu"]',deleteMenuItem:'[data-radix-popper-content-wrapper] [role="menuitem"][data-slot="dropdown-menu-item"]',deleteDangerIndicator:".text-dbx-function-danger",deleteConfirmButton:'button[class*="bg-dbx-function-danger"]',openDeleteDialog:'[role="dialog"][data-state="open"][data-slot="dialog-content"]',deleteDialog:'[role="dialog"][aria-modal="true"], [role="dialog"]',openConversationMenu:'[data-radix-popper-content-wrapper] [role="menu"][data-state="open"], [data-radix-popper-content-wrapper] [role="menu"]',mainLayoutScope:g,contentWidthRoot:"#chat-route-layout",contentWidth:p,contentWidthVar:m,contentColumn:f,newChatSafeArea:b,canvasScope:v,canvasSafeArea:`${v} .code-canvas`,userQueryWidth:[`${i} .w-fit[class*="max-w-"]`,`${i} [data-plugin-identifier="block_type:10000"] > .bg-g-send-msg-bubble-bg`]}}})(),Jo=(()=>{const e="[cmdk-item]",t=".message-bubble",n=`${t}.rounded-br-lg`,r=`${t}:not(.rounded-br-lg)`,o=".response-content-markdown",a=['button[aria-label*="停止"]','button[aria-label*="Stop"]'],i="#grok-app-root",s="main[data-mcp-app-fullscreen-container]";return {capabilities:[...bt[Ie.GROK]],selectors:{textarea:[".tiptap.ProseMirror[contenteditable='true']",'[contenteditable="true"].ProseMirror',".query-bar [contenteditable='true']","form [contenteditable='true']"],submitButton:['button[type="submit"]','form button[type="submit"]','.query-bar button[type="submit"]'],responseContainer:"main",chatContent:['[class*="prose"]','[dir="ltr"]'],userQuery:n,assistantResponse:r,newChatButton:['a[href="/"]','[data-sidebar="header"] a','button[aria-label*="新"]','button[aria-label*="New"]'],stopButton:a},input:{mode:"contenteditable",submitKey:"Enter"},conversation:{itemSelector:'a[href^="/c/"]',idFrom:{attr:"href",regex:"/c/([a-zA-Z0-9-]+)"},titleSelector:"span.flex-1, span.truncate, span",urlTemplate:"/c/{id}",activeMatch:".bg-button-ghost-hover",navigationStrategy:"location",shadow:false},generating:{existsSelectors:[a.join(", "),'[class*="loading"], [class*="animate-pulse"]']},networkMonitor:{urlPatterns:["/rest/app-chat/conversations/"],urlPathEndsWith:["/responses"],silenceThreshold:500},modelSwitcher:{selectorButtonSelectors:["#model-select-trigger"],menuItemSelector:'[role="menuitem"], [role="option"]',checkInterval:1e3,maxAttempts:15,menuRenderDelay:500},export:{userQuerySelector:n,assistantResponseSelector:`${r} ${o}`,turnSelector:null,useShadowDOM:false},widthSelectors:[{selector:'[class*="[--content-max-width:"]',property:"--content-max-width"},{selector:'[style*="--content-max-width"]',property:"--content-max-width"}],zenMode:{hide:[".text-sidebar-foreground",'[data-sidebar="sidebar"]']},quickQuote:"native",sitePrivateSelectors:{nativeQuotePopover:[".absolute.bg-surface-l2.p-1.rounded-full.shadow-lg",".absolute.bg-surface-l2.p-1.rounded-full","button svg.lucide-text-quote",".absolute.bg-surface-l2.p-1.rounded-full button"],sidebarScrollContainer:'[data-sidebar="content"]',mainScrollContainer:'[class*="overflow-y-auto"][class*="px-gutter"], [class*="overflow-auto"]',fallbackScrollContainers:'[class*="overflow-y-auto"], [class*="overflow-auto"]',viewAllButton:"button.w-full.justify-start.text-xs.text-secondary.font-semibold",cmdkList:'[cmdk-list-sizer=""], [cmdk-list]',cmdkItem:e,cmdkConversationItem:`${e}[data-value^="conversation:"]`,cmdkTitle:"span.truncate",cmdkActiveIndicator:'[class*="border-border-l2"]',cmdkGroup:"[cmdk-group]",sidebarGroup:'[data-sidebar="group"]',sidebarMenuButton:'[data-sidebar="menu-button"]',sidebarMenuItem:'[data-sidebar="menu-item"]',sidebarMenu:'[data-sidebar="menu"]',sidebarIcon:'[data-sidebar="icon"] svg',actionDialog:'[role="dialog"]',cmdkRoot:"[cmdk-root]",actionIconNodes:"svg, path, use, [data-icon], [class*='icon'], [aria-label]",conversationTitle:".conversation-title",messageBubble:t,responseMarkdown:o,responseRoot:'[id^="response-"]',exportDecoration:'button, [role="button"], svg, [aria-hidden="true"]',attachmentCardCandidates:'a[href], [role="group"], [aria-label], [title], [class*="file"], [class*="attachment"]',inlineCodeSpan:"span.rounded-sm.font-mono, span.rounded-sm.\\!font-mono",modelName:".font-semibold",appLayoutScope:i,panelAvoidanceScope:s,chatSafeArea:`${s} [class*="overflow-y-auto"][class*="px-gutter"]`,newChatLogoSafeArea:`${s} .flex.flex-col.items-center.justify-center.w-full.max-w-breakout:has(svg[variant="hero"])`,inputSafeArea:`${s} .absolute.inset-x-0.bottom-0.mx-auto.max-w-breakout`,canvasSafeArea:`${i} aside:has(iframe.w-full.flex-1)`}}})(),ea=(()=>{const e="user-query",t="model-response",n="infinite-scroller.chat-history",r='conversations-list[data-test-id="all-conversations"]',o=".title-text",a="immersive-panel",i="share-landing-page",s=".cdk-visually-hidden",l='[data-test-id="gem-processing-card"]',c="immersive-entry-chip",d="immersive-panel deep-research-immersive-panel",h="message-content .markdown",u=`${i} immersive-share-landing-page structured-content-container[data-test-id="deep-research-block"]`,g=`${i} structured-content-container[data-test-id="immersive-artifact-content"]`,p=".immersive-artifact-container";return {capabilities:[...bt[Ie.GEMINI]],selectors:{textarea:['div[contenteditable="true"].ql-editor','div[contenteditable="true"]','[role="textbox"]','[aria-label*="Enter a prompt"]'],submitButton:['button[aria-label*="Send"]','button[aria-label*="发送"]',".send-button",'[data-testid*="send"]'],responseContainer:n,chatContent:[".model-response-container",t,".response-container","[data-message-id]","message-content"],userQuery:e,assistantResponse:t,newChatButton:['gem-nav-list-item[data-test-id="new-chat-button"] a','[aria-label="New chat"]','[aria-label="新对话"]','[aria-label="发起新对话"]','[data-testid="new-chat-button"]','[data-test-id="new-chat-button"]','[data-test-id="expanded-button"]','[data-test-id="temp-chat-button"]','button[aria-label="临时对话"]'],stopButton:['button:has(mat-icon[fonticon="stop"])','mat-icon[fonticon="stop"]'],scrollContainer:[n],sidebarScrollContainer:r},input:{mode:"contenteditable",submitKey:"Enter"},conversation:{itemSelector:'gem-nav-list-item[data-test-id="conversation"]',idFrom:{attr:"jslog",regex:'\\["c_([^"]+)"'},titleSelector:o,urlTemplate:"/app/{id}",activeMatch:"a.mdc-list-item--activated",navigationStrategy:"click-item",shadow:false},generating:{existsSelectors:['mat-icon[fonticon="stop"]']},networkMonitor:{urlPatterns:["BardFrontendService","StreamGenerate"],silenceThreshold:3e3},modelSwitcher:{selectorButtonSelectors:[".input-area-switch-label",".model-selector",'[data-test-id="model-selector"]','[aria-label*="model"]','button[aria-haspopup="menu"]'],menuItemSelector:'.mode-title, [role="menuitem"], [role="option"]',checkInterval:1e3,maxAttempts:15,menuRenderDelay:300},export:{userQuerySelector:e,assistantResponseSelector:`${t}, .model-response-container .markdown`,turnSelector:".conversation-turn",useShadowDOM:false},widthSelectors:[{selector:".conversation-container",property:"max-width",extraCss:"width: 100% !important; min-width: 0 !important;"},{selector:".input-area-container",property:"max-width",extraCss:"width: 100% !important; min-width: 0 !important;"},{selector:".table-block.new-table-style",property:"max-width",value:"100%",noCenter:true,extraCss:"width: 100% !important;"},{selector:e,property:"max-width",value:"100%",noCenter:true,extraCss:"display: flex !important; justify-content: flex-end !important;"},{selector:".user-query-container",property:"max-width",value:"100%",noCenter:true,extraCss:"justify-content: flex-end !important;"}],zenMode:{hide:["bard-sidenav","div.sidenav-with-history-container"]},cleanMode:{hide:["hallucination-disclaimer","g1-dynamic-upsell-button",".share-viewer_footer_disclaimer",'share-landing-page immersive-share-landing-page .page:has(structured-content-container[data-test-id="deep-research-block"]) > .footer']},mermaidSupport:"fallback",quickQuote:"enabled",supportsHostThemeSync:true,sitePrivateSelectors:{accountIdentity:["[data-email]",'[data-identifier*="@"]','[aria-label*="@"]','[title*="@"]'],myStuffMediaHost:"library-item-card",myStuffMediaCard:".library-item-card",myStuffMediaCardContainer:".library-item-card-container",myStuffDocumentHost:"library-list-item",myStuffJslogHost:"[jslog]",myStuffTitle:".title, .gds-title-m, .text-content .title",myStuffThumbnail:"img",deepResearchPanel:d,canvasCodePanel:"immersive-panel code-immersive-panel",canvasDocumentPanel:"immersive-panel extended-response-panel:has(canvas-create-button)",panelToolbarActions:"toolbar .action-buttons",deepResearchPanelExportButton:'[data-test-id="export-menu-button"]',deepResearchPanelCloseButton:`${d} [data-test-id="close-button"], ${a} [data-test-id="close-button"]`,canvasPanelDownloadButton:'[data-test-id="download-preview-button"]',panelThinking:"thinking-panel",panelToolbarTitle:"toolbar h2.title-text",canvasPanelTitle:"toolbar h2.title-text, .title-text",canvasPanelCloseButton:'toolbar [data-test-id="close-button"]',chatsExpandableSection:'expandable-section[data-test-id="chats-expandable-section"]',chatsExpandableSectionFallback:'expandable-section[storagekey="chats"]',chatsExpandableSectionHost:"expandable-section",conversationList:r,historyLoadingSpinner:'[data-test-id="loading-history-spinner"]',conversationAnchor:"a",conversationPinnedIcon:'mat-icon[fonticon="push_pin"]',conversationActiveTitle:`a.mdc-list-item--activated ${o}`,shareTitle:"h1.headline, h1[class*='headline']",conversationActionButton:['button[aria-haspopup="menu"]','button[aria-label*="More"]','button[aria-label*="more"]','button[aria-label*="更多"]','button[aria-label*="选项"]','button[title*="More"]','button[title*="more"]','button[data-test-id*="menu"]','button[data-testid*="menu"]',"button"].join(", "),conversationMoreIcon:'mat-icon[fonticon="more_vert"], mat-icon[fonticon="more_horiz"]',conversationDeleteIcon:'mat-icon[fonticon="delete"], mat-icon[data-mat-icon-name="delete"]',conversationMenuAction:'[role="menuitem"], [role="menu"] button, .mat-mdc-menu-panel button',conversationMenuContainer:'[role="menu"], .mat-mdc-menu-panel, .mat-menu-panel',conversationConfirmButton:'button[data-test-id="confirm-button"], button[data-testid="confirm-button"]',conversationDialog:'[role="dialog"], mat-dialog-container, .mat-mdc-dialog-container',shareResponseContainer:"div.content-container",markdownFixerParagraph:"message-content p",markdownFixerSource:[["source-chip","source-card","source-footnote","citation-source","citation-chip","citation-marker","grounding-chip","grounding-source","web-source","[data-source]","[data-source-id]","[data-citation]","[data-citation-id]","[data-ved]","[decode-data-ved]"].join(", "),["[cdkoverlayorigin]","[mattooltip]","[data-mdc-tooltip]","mat-icon[fonticon]","mat-icon[data-mat-icon-name]","[fonticon*='link' i]","[data-mat-icon-name*='link' i]","sup a","sup button","sup [role='button']"].join(", "),...["source","sources","citation","citations","reference","references","grounding","footnote","link","fonte","fontes","fuente","fuentes","quelle","quellen","referencia","referencias","referência","referências","riferimento","riferimenti","来源","引用","链接","出典","参照","출처","참조","источник","источники","ссылка","ссылки"].map(e=>[`[aria-label*='${e}' i]`,`[title*='${e}' i]`,`[data-test-id*='${e}' i]`].join(", "))],validTextarea:'[contenteditable="true"], [role="textbox"], .ql-editor',visuallyHidden:s,userQueryText:".query-text",userQueryLine:".query-text-line",exportMessageSource:"message-content, .conversation-turn",immersivePanel:a,exportImageScope:[".attachment-container.generated-images","response-element","generated-image","single-image.generated-image",".image-container.replace-fife-images-at-export","[data-image-attachment-index]"],userQueryImage:["img[data-test-id='uploaded-img']",".preview-image"],uploadedFile:'[data-test-id="uploaded-file"]',sharePage:i,shareTurn:`${i} .share-turn-viewer`,shareAssistantMarkdown:h,assistantExportNoise:[s,"model-thoughts",c,"gem-processing-card",l,'[data-test-id="time-estimation-message"]',".time-estimation-message","source-footnote","sources-carousel-inline","sources-carousel","mat-icon","share-button","copy-button","download-generated-image-button",".generated-image-controls",".loader"],decorativeImage:["img.katex-svg","img.favicon","img.google-icon",'img[data-test-id="favicon"]','img[data-test-id="file-icon"]','img[data-test-id="luminous-file-icon"]','img[src*="faviconV2"]','img[src*="drive-thirdparty.googleusercontent.com/32/type/"]','img[src*="google_logo_icon"]'],generatedImageControls:["share-button","copy-button","download-generated-image-button",".generated-image-controls",".loader"],generatedImageButton:"button.image-button",driveViewer:`${a} .drive-viewer`,driveViewerOwner:".drive-viewer",driveViewerTextContent:".drive-viewer-text-content",driveViewerError:".drive-viewer-msg-error",driveViewerTextCandidate:".drive-viewer-text-content pre, .drive-viewer-text-content",driveViewerName:".drive-viewer-toolstrip-name",driveActiveItemInfo:'[id="drive-active-item-info"], div[style*="display:none"]',driveViewerCloseButton:".drive-viewer-close-button",uploadedFileName:['[data-test-id="filename-label"]',".filename-label",".new-file-name"],uploadedFileAriaAction:"a[aria-label], button[aria-label]",uploadedFileType:".new-file-type",uploadedFileIcon:'[data-test-id="luminous-file-icon"]',deepResearchDocumentShare:u,deepResearchArtifactShare:g,deepResearchConfirmation:"deep-research-confirmation-widget",deepResearchPanelMarkdown:["#extended-response-markdown-content",h],deepResearchAppDocumentMarkdown:[`${d} #extended-response-markdown-content`,`${d} ${h}`],deepResearchAppTrigger:`${t} ${l}, ${t} ${c}`,deepResearchIcon:['mat-icon[data-mat-icon-name="travel_explore"]','mat-icon[fonticon="travel_explore"]'],deepResearchConfirmationTitle:'[data-test-id="title"]',deepResearchConfirmationSteps:'[data-test-id="research-steps"] .research-step',deepResearchStepDescription:".research-step-description",deepResearchStepTitle:".research-step-title",canvasCodeIcon:['mat-icon[fonticon="code_blocks"]','mat-icon[data-mat-icon-name="code_blocks"]'],canvasDocumentIcon:['mat-icon[fonticon="article"]','mat-icon[data-mat-icon-name="article"]'],canvasCard:l,canvasShareArtifact:`${i} ${p}`,canvasArtifactContainer:p,canvasEntryChip:c,canvasCodeTab:'mat-button-toggle[value="code"]',canvasTabGroup:"mat-button-toggle-group.tab-group",canvasTabToggle:"mat-button-toggle",canvasCodeBlock:"code-block",canvasCodeEditor:'xap-code-editor[data-test-id="code-editor"]',canvasDocumentMarkdown:["#extended-response-markdown-content .ProseMirror",'immersive-editor[data-test-id="immersive-editor"] .ProseMirror',"immersive-editor .ProseMirror","#extended-response-markdown-content"],canvasTabButton:"button",canvasTabRadio:"button[role='radio']",canvasTabSelected:".mat-button-toggle-checked",canvasHidden:".hidden",canvasCodeContent:'[data-test-id="code-content"], pre code, code',canvasMonacoEditor:".monaco-editor",canvasMonacoTextarea:"textarea.inputarea",canvasMonacoScrollable:".monaco-scrollable-element",canvasMonacoLine:".view-lines .view-line",canvasMonacoContentHeight:".view-lines, .margin, .lines-content",canvasTitle:".title-text, .card-title",canvasNestedTitle:".title-text",canvasCodeLanguage:".code-block-decoration span",canvasMode:"[data-mode-id]",outlineMessageContent:"message-content",outlineUserMetadataButton:'button[jslog*="BardVeMetadataKey"]',outlineAssistantMarkdown:".model-response-text, message-content",outlineThoughts:"model-thoughts",modelName:".input-area-switch-label",layoutScope:"bard-sidenav-content, body:not(:has(bard-sidenav-content)) main.chat-app",immersiveLayout:"chat-window.immersives-mode:not(.mobile-device)",chatColumnScope:"chat-window .chat-container",messageSafeArea:n,inputSafeArea:"input-container",newChatInputSafeArea:"chat-window.center-input-layout .input-area-container.is-zero-state",userQueryWidth:".user-query-bubble-with-background:not(.edit-mode)"}}})(),ta=(()=>{const e=".question-block",t="ucs-summary",n=".input-area-container",r=['button[aria-label*="Stop"]','button[aria-label*="停止"]','[data-test-id="stop-button"]',".stop-button",'md-icon-button[aria-label*="Stop"]'],o=["#model-selector-menu-anchor",".action-model-selector"],a=(e,t,n,r=false)=>({selector:e,globalSelector:`mat-sidenav-content ${e}`,property:"max-width",...t?{value:t}:{},...n?{extraCss:n}:{},noCenter:r});return {capabilities:[...bt[Ie.GEMINI_ENTERPRISE]],selectors:{textarea:["div.ProseMirror",".ProseMirror",'[contenteditable="true"]:not([type="search"])','[role="textbox"]','textarea:not([type="search"])'],submitButton:['button[aria-label*="Submit"]','button[aria-label*="提交"]','button[aria-label*="发送"]','button[aria-label*="Send"]',".send-button",'[data-testid*="send"]'],responseContainer:".conversation-container",chatContent:[".model-response-container",".message-content","[data-message-id]","ucs-conversation-message",".conversation-message"],userQuery:e,assistantResponse:t,newChatButton:[".chat-button.list-item",'button[aria-label="New chat"]','button[aria-label="新对话"]'],stopButton:[...r],scrollContainer:[".chat-mode-scroller"],sidebarScrollContainer:".conversation-list"},input:{mode:"contenteditable",submitKey:"Enter"},conversation:{itemSelector:".conversation",idFrom:{attr:"id",regex:"^menu-(\\d+)$"},titleSelector:".conversation-title",urlTemplate:"/session/{id}",navigationStrategy:"click-item",shadow:true},generating:{existsSelectors:[r.join(", "),["mat-spinner","md-spinner",".loading-spinner",'[role="progressbar"]',".generating-indicator",".response-loading"].join(", ")]},networkMonitor:{urlPatterns:["widgetStreamAssist"],silenceThreshold:3e3},modelSwitcher:{selectorButtonSelectors:[...o],menuItemSelector:"md-menu-item",checkInterval:1500,maxAttempts:20,menuRenderDelay:500},export:{userQuerySelector:e,assistantResponseSelector:t,turnSelector:".turn",useShadowDOM:true},widthSelectors:[a("mat-sidenav-content","100%",void 0,true),a(".main.chat-mode","100%",void 0,true),a(t),a("ucs-conversation"),a("ucs-search-bar"),a(".summary-container.expanded"),a(".conversation-container"),a(n,void 0,"left: 0 !important; right: 0 !important;",true)],zenMode:{hide:["ucs-nav-panel"]},cleanMode:{hide:[".disclaimer"]},mermaidSupport:"fallback",quickQuote:"enabled",supportsHostThemeSync:true,sitePrivateSelectors:{srOnly:".sr-only",sidebarScrollFallback:"mat-sidenav",conversationButton:["button.list-item","button"],conversationMenuButton:".conversation-action-menu-button",conversationMenuButtonFallback:'button[id^="menu-"]',conversationActive:".selected, .active",conversationAriaActive:'[aria-selected="true"]',conversationActionButton:[".conversation-action-menu-button",'button[id^="menu-"]','button[aria-haspopup="menu"]','button[aria-label*="More"]','button[aria-label*="more"]','button[aria-label*="更多"]','button[title*="More"]','button[title*="more"]',"button"].join(", "),conversationMenuIcon:'mat-icon[fonticon="more_vert"], mat-icon[fonticon="more_horiz"], md-icon',conversationMenuAction:'md-menu-item, [role="menuitem"], [role="menu"] button, .mat-mdc-menu-panel button',conversationMenuContainer:'md-menu-surface, .menu[popover], .mat-mdc-menu-panel, [role="menu"]',panelScope:"mat-sidenav-content, .main.chat-mode",inputArea:n,userQueryWidth:[".question-block .question-wrapper"],textareaHostExclusion:".main-input",conversationRoot:"ucs-conversation",conversationMain:".main",markdownHost:"ucs-fast-markdown",markdownDocument:".markdown-document",headingMarker:"span[data-markdown-start-index]",modelName:[...o,".model-selector",'[data-test-id="model-selector"]',".current-model"],shadowInjectionExclusion:["mat-sidenav","mat-drawer",'[class*="bg-sidebar"]'],showMoreButton:"button.show-more",showMoreIcon:".show-more-icon",showMoreExpandedIcon:".more-visible",themeMenu:'.menu[popover], md-menu-surface, .mat-menu-panel, [role="menu"]',settingsButton:".settings-button",themeTab:"md-primary-tab",themeIcon:"md-icon"}}})(),na=(()=>{const e="#scrollContainer",t=`${e} [class*="scrollWrap"]`,n='div[class*="userBubbleContainer"]',r='div[class*="userBubbleWrap"]',o=[n,r].join(", "),a=`${n} [class*="userBubble"]`,i='[class*="chatMainBubble"]',s=[a,`${r} ${i}`].join(", "),l=[`${a} [class*="content"]`,i].join(", "),c='div[class*="aiContainer"]',d=`${c} [class*="bubble"]`,h='[class*="markdown"]',u=`${d} ${h}`,g='.system-copy-exclude, [x-noteelement="excluded"], [x-copyelement="copy-exclude"]',p=[".gh-root",".gh-user-query-markdown",".gh-inline-bookmark",g,"button","[role='button']","svg","[aria-hidden='true']","style","script"].join(", "),m=':is([class*="attachmentContainer"], [class*="attachmentWrap"])',f=[`${m} img`,'[class*="imgWrap"] img'].join(", "),b=[`${m} [class*="itemWrap"]`,`${m} [class*="file"]`,`${m} [class*="doc"]`,`${m} a[href]`,`${m} [data-file-id]`,`${m} [data-doc-id]`,`${m} [data-resource-id]`],v=[`${d} [class*="imagesWrapper"] img`,`${d} [id^="image-toolkit-"] img`,`${d} [class*="bigImg"] img`,`${d} ${h} img`].join(", "),y=['[class*="imagesWrapper"]','[id^="image-toolkit-"]',".t-image__wrapper","picture","img"].join(", "),w=['div[class*="stopButton"] > div','[class*="stopButton"][role="button"]','button[class*="stopButton"]','[class*="stopButton"]'].join(", "),x='[class*="modelSelectionText"]',k=".expandable-sidebar-panel-sidebar ~ [class*='_content_']",S='[class*="chatInputContainer"]';return {capabilities:[...bt[Ie.IMA]],selectors:{textarea:['#tagTextarea [contenteditable="true"], [class*="chatInputContainer"] .tiptap.ProseMirror'],responseContainer:t,chatContent:[o,c],userQuery:o,assistantResponse:c,newChatButton:['[class*="newChatWrap"]'],stopButton:[w]},input:{mode:"contenteditable",submitKey:"Enter"},generating:{existsSelectors:['div[class*="stopButton"], [class*="stopButton"]']},networkMonitor:{urlPatterns:["/cgi-bin/assistant/qa"],urlPathEndsWith:["/cgi-bin/assistant/qa"],silenceThreshold:2e3},modelSwitcher:{selectorButtonSelectors:['[class*="currentChoiceWrap"]','[class*="modelSelectionWrap"]',x],menuItemSelector:'.modelDropdown .t-dropdown__item, .modelDropdown [class*="modelOption"], .t-popup .modelDropdown .t-dropdown__item',menuRenderDelay:200,checkInterval:1e3,maxAttempts:10},export:{userQuerySelector:o,assistantResponseSelector:c,turnSelector:null,useShadowDOM:false},zenMode:{hide:[".expandable-sidebar-panel-sidebar"]},cleanMode:{hide:['[class*="_downloadContainer_"]','[class*="footTips"]','[class*="_activityBanner"]','[class*="_activityBannerContent"]','[class*="_qaDownloadGuide"]']},widthSelectors:[{selector:e,property:"max-width",extraCss:"width: 100% !important;",noCenter:true},{selector:t,property:"max-width",extraCss:"width: 100% !important;",noCenter:true},{selector:'[class*="_chatInputContainer_"] [class*="_editorContainer_"]',property:"max-width",extraCss:"width: 100vw !important; margin: 0 auto;"}],sitePrivateSelectors:{scrollContainer:e,userText:l,assistantBubble:d,assistantMarkdown:u,assistantBubbleFallback:'[class*="bubble"]',thinking:'[class*="thinking"]',thinkingTitle:'[class*="tipsWrap"], [class*="thinkingTitle"], [class*="thinkingHeader"]',inlineReference:g,exportDecoration:p,userAttachmentImages:f,userAttachmentFiles:b,userAttachmentImageCard:'[class*="imgWrap"], [id^="image-toolkit-"]',assistantGeneratedImages:v,assistantGeneratedImageCards:y,tagTextarea:"#tagTextarea",chatInputContainer:S,inputScope:`#tagTextarea, ${S}`,submitButton:'[class*="sendBtnWrap"]',submitDisabled:'.icon-send-disable-big, [class*="sendDisableIcon"]',stopButtonChildren:[":scope > div",'[class*="container"]'],activeHistoryTitle:'[class*="historyListWrap"] [class*="itemWrap"][class*="highLight"] [class*="main"]',sidebarScrollContainer:"#HistoryScrollContainer",modelText:x,pageContent:k,mainArea:'[class*="mainArea"]',newChatContent:`${k} [class*="mainContainer"] > [class*="container"]:has(> [class*="centerContent"])`,chatPageInputContainer:`body:not(:has([class*="centerContent"])) ${S}`,editorContainer:`${S} [class*="editorContainer"]`,userQueryWidth:s}}})(),ra=(()=>{const e="a.chat-info-item, a.next-sidebar-history-item__link",t=`${e}, a.history-link`,n=".history-part",r=".next-sidebar__body",o=".chat-content-list",a=`${o}, .share-content-list`,i="body:not(:has(.chat-detail-content)) #chat-container.layout-content",s=`.chat-detail-content, ${i}`,l=".chat-content-container",c=".chat-editor",d=[o,`${o}${o}`,`${o}${o}${o}`,`.chat-detail-content ${o}`,`.chat-detail-content ${o}${o}`].join(", "),h=".chat-content-item-user",u=".chat-content-item-assistant",g=".segment.segment-user",p=".segment.segment-assistant",m=[".segment-user .segment-content",`${h} .segment-content`,".segment-container:has(.user-content) > .segment-content"].join(", "),f=[".segment-user .segment-content-box",`${h} .segment-content-box`,".segment-content-box:has(> .user-content)"].join(", "),b=[".segment-user .user-content",`${h} .user-content`,".segment-content-box > .user-content"].join(", "),v=[".segment-assistant .segment-content-box > .markdown-container > .markdown",`${u} .segment-content-box > .markdown-container > .markdown`].join(", "),y=".send-button-container",w=`${y}.stop`;return {capabilities:[...bt[Ie.KIMI]],selectors:{textarea:['.chat-input-editor[data-lexical-editor="true"]','.chat-input-editor[contenteditable="true"]','[role="textbox"].chat-input-editor'],submitButton:[`${y}:not(.disabled):not(.stop)`],responseContainer:a,chatContent:[v,f],userQuery:g,assistantResponse:p,newChatButton:["a.new-chat-btn",'a.new-chat-btn[href="/"]','a.new-chat-btn[href="https://www.kimi.com/"]'],stopButton:[w,`${y}:has(svg[name="stop"])`]},input:{mode:"contenteditable",submitKey:"Enter"},conversation:{itemSelector:t,idFrom:{attr:"href",regex:"^/chat/([A-Za-z0-9-]+)(?:/|$)"},titleSelector:"span.chat-name, .next-sidebar-history-item__title, .history-chat .title-wrapper .title",urlTemplate:"/chat/{id}",activeMatch:".router-link-active, .router-link-exact-active",navigationStrategy:"click-item",shadow:false},generating:{existsSelectors:[w,`${y} svg[name="stop"]`]},networkMonitor:{urlPatterns:["apiv2/kimi.gateway.chat.v1.ChatService/Chat"],silenceThreshold:2e3},modelSwitcher:{selectorButtonSelectors:[".current-model.active .model-name",".current-model .model-name"],menuItemSelector:['[role="menuitem"]','[role="option"]',".n-base-select-option",".n-dropdown-option",".model-item",".model-option"].join(", "),checkInterval:1e3,maxAttempts:15,menuRenderDelay:350},export:{userQuerySelector:g,assistantResponseSelector:p,turnSelector:null,useShadowDOM:false},widthSelectors:[{selector:s,property:"width",value:"100%",noCenter:true,extraCss:"max-width: 100% !important; min-width: 0 !important;"},{selector:l,property:"max-width",extraCss:"width: 100% !important; min-width: 0 !important;"},{selector:d,property:"max-width",value:"100%",noCenter:true,extraCss:"width: 100% !important; min-width: 0 !important; padding-left: 0 !important; padding-right: 0 !important;"},{selector:d,property:"width",value:"100%",noCenter:true},{selector:c,property:"max-width"}],zenMode:{hide:[".sidebar-slot.sidebar-slot--interactive"],styles:[{selector:".app.has-sidebar .main",property:"--kimi-sidebar-main-offset",value:"6px"}]},cleanMode:{hide:[".chat-bottom .legal-footer, .legal-footer",".membership-upgrade",".download-app-btn",".activity-area"]},sitePrivateSelectors:{sidebarConversation:e,historyContainer:n,historyScrollCandidates:[".history .group-list-container",n,".history .usage-content",".history .content",".history",".next-sidebar-history-list__items",".next-sidebar-history-list",r],nextSidebarBody:r,conversationHeaderTitle:".chat-header-content h2",pinnedConversation:"svg.pinned, .pinned, .next-sidebar-history-item__pinned",activeConversation:`${e}.router-link-active, ${e}.router-link-exact-active`,moreHistoryLink:['a.more-history[href*="/chat/history"]','a.nav-item.more-history[href*="/chat/history"]','a.next-sidebar__section-text-action[href*="/chat/history"]'].join(", "),closeHistory:[".header-right .close-button-container",".header-right .close-button",".history .header-right .close-button-container",".history .header-right .close-button"].join(", "),closeButtonContainer:".close-button-container",inputScope:".chat-input-editor-container",editorScope:c,submitButtonContainer:y,submitButtonDisabled:`${y}.disabled, ${y}.stop`,shareScrollContainer:".share-detail",chatDetailScrollContainer:".chat-detail-content",chatContentContainer:l,chatItem:".chat-content-item",userItem:h,assistantItem:u,userContentBox:".segment-content-box",assistantBodyMarkdown:v,markdown:".markdown",thinkingContainer:".toolcall-container.thinking-container, .thinking-container",toolcallContainer:".toolcall-container, .container-block",toolcallContentMarkdown:".markdown-container.toolcall-content-text",exportDecoration:"button, [role='button'], svg, canvas, [aria-hidden='true'], .segment-avatar, .okc-cards-container",userAttachmentList:".attachment-list",userAttachmentImage:".attachment-list-image img, .image-thumbnail img.image-main, .image-wrapper img.image-main",userFileCard:".attachment-list-file .file-card-container",userFileName:".file-card-info-name",userFileType:".file-ext",userFileSize:".file-size",fileLink:"a[href]",modelName:".current-model .model-name .name",chatLayoutScope:s,chatListWidth:d,chatActionContainer:".chat-action .bottom-action-container",chatEditor:c,chatDetailMain:".chat-detail-main",newChatLayoutScope:i,userQueryWrapper:m,userContent:f,userQueryContent:b,markdownFixerParagraph:".segment-assistant .markdown p",lastAssistant:`${u} .segment-assistant`}}})(),oa=(()=>{const e='[class*="questionItem"], .chat-question-wrap, [class*="message-select-wrapper-question"]',t="[data-chat-question-wrap]",n='[class*="answerItem"], [data-chat-answers-wrap], .chat-answers-card-wrap',r=[`${t} .message-card-wrap.question`,`${t} .question-text-card`].join(", "),o=".message-card-wrap.question",a=".question-text-card",i=`${o}[data-mt*="image"]`,s=[`${o}[data-mt*="doc"]`,`${o}[data-mt*="file"]`,`${o}[data-mt*="office"]`,`${o}:has([class*="office-card"])`].join(", "),l=[".answer-common-card .qk-markdown",".markdown-pc-special-class .qk-markdown","#qk-markdown-react",".answer-common-card"].join(", "),c=['[data-card-type="ai_generate_image_list"] img',".card_card_ai_generate_image img",'[data-tpl*="card_ai_generate_image"] img','img[data-image-menu-items*="download"]','img[class*="image-"][data-image-resource-id]'].join(", "),d=['[data-card-type="ai_generate_image_list"]',".card_card_ai_generate_image",'[data-tpl*="card_ai_generate_image"]'].join(", "),h=[".gh-root",".gh-user-query-markdown","button","[role='button']","svg","[aria-hidden='true']",".qk-md-table-action",".qk-md-copy-icon","[class*='answerToolsContent']","[class*='functionArea']","[class*='recommend-query']",".q-item",".qs-bottom","style","script"].join(", "),u=['[class*="chatInput"]','[data-chat-input-shell="true"]','[data-qw-chat-input-position="chat"]'].join(", "),g='[data-slate-editor="true"]',p=".message-list-scroll-container, #message-list-scroller",m="#qwen-message-list-area",f=`${m}, ${p}`,b=".splitCardContainer:has(#qianwen-left-panel)",v=[`${b} > div:has([data-log-params*="canvas_panel"])`,`${b} > div:has(.monaco-editor)`,`${b} > div:has([data-preview-list="true"])`].join(", "),y="#qw-chat-content",w="#pc-center-wrapper, [class*='auto-center-wrapper']",x=['[class*="page-content-"]','[class*="pageContent"]',y,'[class*="scrollOutWrapper"]'].join(", "),k="aside#new-nav-tab-wrapper",S='.qc-thinking-header, [class*="thinkingWrap"], [class*="thinkingContent"], [class*="thinkingHeader"], [class*="thinkingTitle"]',C='[class*="stop-"], [class*="stopBtn"], div[class*="stop"]',T=['[role="dialog"] [id="tongyi-for-guide-model"]','[role="dialog"] .group.rounded-8','[data-radix-popper-content-wrapper] [id="tongyi-for-guide-model"]',"[data-radix-popper-content-wrapper] .group.rounded-8"].join(", "),E=["width: 100% !important;","min-width: 0 !important;","--max-message-list-width: 100% !important;","--min-message-list-width: 0px !important;"].join(" "),M=["width: 100% !important;","min-width: 0 !important;","box-sizing: border-box !important;","--chat-input-visible-shell-width: 100% !important;","--chat-input-visible-shell-max-width: 100% !important;","--chat-input-visible-shell-side-gutter: 0px !important;"].join(" ");return {capabilities:[...bt[Ie.QIANWEN]],selectors:{textarea:['[class*="chatTextarea"]',`${u} [contenteditable="true"]`,`${g}[contenteditable="true"]`,'div[role="textbox"][contenteditable="true"]',"textarea"],submitButton:['[class*="operateBtn"]','[data-icon-type="qwpcicon-sendChat"]',"button[type='submit']"],responseContainer:f,chatContent:[e,n],userQuery:e,assistantResponse:n,newChatButton:['[class*="newChatButton"]'],stopButton:[C]},input:{mode:"contenteditable",submitKey:"Enter"},generating:{existsSelectors:[C]},networkMonitor:{urlPatterns:["api/v2/chat","api/v1/chat/snap"],silenceThreshold:2e3},modelSwitcher:{selectorButtonSelectors:[`${m} [aria-haspopup="dialog"]`,'[aria-haspopup="dialog"][aria-controls][data-state]'],menuItemSelector:T,checkInterval:1e3,maxAttempts:10,menuRenderDelay:300},export:{userQuerySelector:e,assistantResponseSelector:n,turnSelector:null,useShadowDOM:false},widthSelectors:[{selector:'[class*="scrollOutWrapper"]',property:"max-width",extraCss:"width: 100% !important;",noCenter:true},{selector:m,property:"max-width",extraCss:"width: 100% !important;",noCenter:true},{selector:w,property:"max-width",extraCss:E},{selector:p,property:"--message-content-width",noCenter:true},{selector:'[data-text-area-width-container="true"], [class*="inputMotionCarrier"]',property:"max-width",extraCss:M},{selector:'[class*="inputOutWrap"]',property:"max-width",value:"100%",extraCss:"width: 100% !important;"},{selector:'[class*="answerItem"] [class*="containerWrap"]',property:"max-width"},{selector:n,property:"max-width",extraCss:"width: 100% !important; min-width: 0 !important;"},{selector:'[class*="questionItem"], .chat-question-wrap',property:"width",extraCss:"margin-right: 0 !important"},{selector:r,property:"width",value:"100%",extraCss:"max-width: 100% !important; box-sizing: border-box !important;",noCenter:true}],zenMode:{hide:[k]},cleanMode:{hide:["#ice-container .root-G6nVVr"]},sitePrivateSelectors:{chatInput:u,slateEditor:g,submitButtonCandidates:'[class*="operateBtn"], [data-icon-type="qwpcicon-sendChat"]',submitButtonClickable:'[class*="operateBtn"], button, [role="button"]',messageList:p,messageListArea:m,scrollRootCandidates:[p,m,x],scrollContent:`${f}, ${e}, ${n}`,questionCard:t,questionTextCard:a,bubble:'[class*="bubble"]',turn:".chat-round[data-chat], [data-chat-list-key]",userTextCard:a,userImageCard:i,userFileCard:s,attachmentImage:"img",assistantContent:l,assistantGeneratedImage:c,assistantExportDecoration:[h,d,"picture","img"].join(", "),userTextDecoration:".gh-user-query-markdown, button, [role='button'], svg, [aria-hidden='true']",cleanTextDecoration:"button, [role='button'], svg, [aria-hidden='true'], style, script",thinking:S,thinkingContent:'[class*="thinkingContent"]',thinkingDecoration:'[class*="thinkingTitle"], [class*="thinkingHeader"], .qc-thinking-header, button, svg, [aria-hidden="true"]',assistantPlainTextDecoration:`${S}, .qc-thinking-header, [class*="thinkingWrap"], [class*="thinkingContent"], button, [role='button'], svg, .qk-md-table-action, .qk-md-copy-icon, [aria-hidden='true'], [class*="answerToolsContent"], [class*="functionArea"]`,chatLayoutScope:"#qianwen-left-panel",canvasLayoutScope:b,canvasPanel:v,chatContent:y,messageCenter:w,sidebar:k,modelDialog:'[role="dialog"], [data-radix-popper-content-wrapper]',modelTrigger:'[aria-haspopup="dialog"][aria-controls], [aria-haspopup="dialog"][data-state]',modelExpandToggle:"button, div, span",markdownFixerParagraph:`${n} .qk-md-paragraph`}}})(),aa=(()=>{const e="#sidebar",t=".qwen-chat-message",n=".qwen-chat-message-user, .chat-user-message-wrapper",r=".qwen-chat-message-assistant",o="button.send-button",a=["button.stop-button",'button[class*="stop-button"]',".stop-button"],i=".qwen-chat-thinking-tool-status-card-wraper, .qwen-chat-thinking-status-card",s=[".splitter-container-right-panel .qwen-chat-thinking-and-sources",".share-layout-right-panel .qwen-chat-thinking-and-sources",".qwen-chat-thinking-and-sources-share"].join(", "),l=".response-message-footer, .copy-response-button, .message-hoc-container",c='[class*="model-selector-popup"]',d='#qwen-chat-header-left .ant-dropdown-trigger:has([class*="model-selector-text"])',h='#qwen-chat-header-left [class*="model-selector-text"]',u='[class*="model-item___"]',g=`[class*="model-list"] > ${u}`,p=[`${c} .ant-dropdown-trigger:has([class*="view-more-text"])`,`${c} .ant-dropdown-trigger:has([class*="view-more-icon"])`].join(", "),m=[`${c} [class*="model-list"] > :is(${u}, [class*="model-item-selected___"])`,`${c} .ant-dropdown-trigger:has(:is([class*="view-more-text"], [class*="view-more-icon"]))`,'.ant-dropdown :is([role="menuitem"], .ant-dropdown-menu-item, .ant-dropdown-menu-title-content)','.ant-select-dropdown :is([role="option"], .ant-select-item-option)'].join(", ");return {capabilities:[...bt[Ie.QWENAI]],selectors:{textarea:["textarea.message-input-textarea","textarea"],submitButton:[`${o}:not([disabled])`],responseContainer:"#chat-message-container",chatContent:[n,r],userQuery:n,assistantResponse:r,newChatButton:[".sidebar-entry-fixed-list-content"],stopButton:[...a],scrollContainer:[".chat-messages-container > .chat-messages, #chat-messages-scroll-container"]},input:{mode:"textarea",submitKey:"Enter"},conversation:{itemSelector:".chat-item-drag",idFrom:{attr:"href",regex:"/c/([a-fA-F0-9-]+)"},titleSelector:".chat-item-drag-link-content-tip-text",urlTemplate:"/c/{id}",navigationStrategy:"click-item",shadow:false},generating:{existsSelectors:[...a]},networkMonitor:{urlPatterns:["/api/v2/chat/completions"],urlPathEndsWith:["/chat/completions"],silenceThreshold:2e3},modelSwitcher:{selectorButtonSelectors:[d,h],menuItemSelector:m,checkInterval:1e3,maxAttempts:12,menuRenderDelay:400,subMenuSelector:p,subMenuTriggers:["展开更多模型","更多模型","view more","more models"]},export:{userQuerySelector:n,assistantResponseSelector:r,turnSelector:null,useShadowDOM:false},widthSelectors:[{selector:t,property:"max-width",extraCss:"width: 100% !important; box-sizing: border-box !important;"},{selector:".message-input-wrapper",property:"max-width"}],zenMode:{hide:[e]},cleanMode:{hide:[".chat-container-statement"]},mermaidSupport:"native",quickQuote:"enabled",supportsHostThemeSync:true,sitePrivateSelectors:{sidebarRoot:e,sidebarScroll:".session-list-wrapper",conversationLink:'a[href*="/c/"]',pinnedConversation:".chat-item-title-pined-icon",layoutScope:".chat-left-panel, body:not(:has(.chat-left-panel)) .splitter-container-left-panel",messageWidth:t,inputSafeArea:".chat-layout-input-container",newChatInputSafeArea:"body:not(:has(.chat-left-panel)) .message-input-wrapper",newChatPlaceholder:"body:not(:has(.chat-left-panel)) .placeholder-logo-text",userMessageRoot:".qwen-chat-message-user",userContent:".user-message-content",assistantContent:".response-message-content",composerButton:o,latex:".qwen-markdown-latex",latexDisplay:".katex-display",codeBlock:"pre.qwen-markdown-code",codeLine:".view-lines .view-line",codeBody:".qwen-markdown-code-body",codeBodyFallback:"[data-mode-id]",mermaidCodeBody:".qwen-markdown-code-body.mermaid",mermaidCodeContent:[".qwen-markdown-code-body.mermaid > div","[data-mode-id='mermaid']"],mermaidChart:".qwen-markdown-mermaid-chart-wrapper",codeHeader:".qwen-markdown-code-header",codeHeaderActions:".qwen-markdown-code-header-actions",codeLineNumber:".margin-view-overlays .line-numbers",mermaidSwitch:".artifacts-body-header-switch",mermaidSwitchItem:".artifacts-body-header-switch-active, .artifacts-body-header-switch-unactive, .header-switch-status-small",mermaidActiveSwitch:'[class*="switch-active"]',thinkingCard:i,thoughtTrigger:".qwen-chat-thinking-tool-status-card-wraper .qwen-chat-tool-status-card, .qwen-chat-thinking-tool-status-card-wraper .qwen-chat-thinking-status-card-completed",thoughtTitle:".qwen-chat-thinking-status-card-title-text",thoughtPanel:s,thoughtPanelContent:".qwen-chat-thinking-and-sources-content-thinking-container",thoughtPanelContentFallback:".qwen-chat-thinking-and-sources-content",thoughtPanelCards:".qwen-chat-thinking-status-card",thoughtCardContent:".qwen-chat-thinking-status-card-content",thoughtMarkdown:".qwen-markdown",thoughtPanelClose:".qwen-chat-thinking-and-sources-header .anticon, .qwen-chat-thinking-and-sources-header [role='img']",phaseId:"[data-phase-id]",responseToolbar:l,exportDecoration:[".gh-root",".gh-user-query-markdown",i,l,"button","[role='button']","svg","[aria-hidden='true']","style","script"].join(", "),userImageCard:[".user-image-item",".user-image-list .qwen-image","[class*='file-message-image'] .qwen-image",".qwen-markdown-image:has(img)"].join(", "),userFileCard:".fileitem-btn, [class*='file-message-document'], .file-content-info",assistantGeneratedImage:[".chat-response-media-render img",".qwen-chat-response-control-card img",".response-message-content img",".qwen-markdown-image img","img.qwen-image"].join(", "),assistantGeneratedImageCard:[".chat-response-media-render",".qwen-chat-response-control-card",".qwen-markdown-image","picture","img"].join(", "),assistantImageDecoration:".response-message-footer, .copy-response-button",messageMarkerRoot:".qwen-chat-message, [data-message-id]",assistantMessageId:["[id^='chat-response-message-']","[id^='qwen-chat-message-assistant-']"],modelTrigger:d,modelText:h,primaryModelPopup:'.ant-dropdown:not(.ant-dropdown-hidden) [class*="model-selector-popup"]:not([class*="secondary"])',secondaryModelPopup:'.ant-dropdown:not(.ant-dropdown-hidden) [class*="model-selector-popup"][class*="secondary"]',modelItem:g,modelItemName:['[class*="model-item-name"] > span','[class*="model-item-name"]'],modelMoreTrigger:p,modelMoreInner:['[class*="view-more___"]','[class*="view-more-text"]','[class*="view-more-icon"]'],modelTriggerFallback:".ant-dropdown-trigger, [role='button'], button, [tabindex]",markdownParagraph:".qwen-markdown-paragraph",userQueryWidth:[".chat-user-message-container .chat-user-message-wrapper .chat-user-message"]}}})(),ia=(()=>{const e=".agent-dialogue__content--common__input",t=[`${e} .ql-editor[contenteditable="true"]`,'#search-bar .ql-editor[contenteditable="true"]','.ql-editor[contenteditable="true"]'].join(", "),n="#yuanbao-send-btn",r=`${n}, a.style__send-btn___RwTm5`,o="a.style__send-btn___RwTm5",a=".yb-recent-conv-list__item",i=[".yb-recent-conv-list__item-name[data-item-name]",".yb-recent-conv-list__item-name","[data-item-id][data-item-name]"].join(", "),s=[".yb-recent-conv-list__item-name.isTop",".yb-recent-conv-list__chat-top .icon-yb-ic_pin_16"].join(", "),l=["#chat-content .agent-chat__list__content-wrapper",".agent-chat__list__content-wrapper"].join(", "),c=["#chat-content .agent-chat__list__content",".agent-chat__list__content"].join(", "),d=".agent-chat__list__item--human",h=".agent-chat__list__item--ai",u=[".agent-chat__bubble--human .hyc-content-text",".agent-chat__bubble--human .agent-chat__bubble__content"].join(", "),g=[`${h} .hyc-common-markdown-style`,`${h} .hyc-content-md-done`].join(", "),p=[".agent-chat__toolbar",".agent-chat__toolbar_new",".agent-chat__question-toolbar",".hyc-common-markdown__code__hd__r"].join(", "),m=[".hyc-card-box-process-list",".hyc-common-markdown__replace-appCard"].join(", "),f=[".hyc-component-multi-modal__image img",".agent-chat__bubble--human .hyc-content-img img"].join(", "),b=[".hyc-component-multi-modal__file",".hyc-component-multi-modal__doc",".hyc-component-multi-modal__document",".hyc-content-file",".hyc-content-doc",".hyc-file-card",".hyc-doc-card","[data-file-id]","[data-doc-id]","[data-resource-id]","a[href*='/api/resource/download']",".agent-chat__bubble--human [class*='file']",".agent-chat__bubble--human [class*='doc']"].join(", "),v=['[data-card-type="image"] img','[data-box-type="loadingImage"] img',".hyc-media-box--loadingImage img",".loading-image-box img"].join(", "),y=['[data-card-type="image"]','[data-box-type="loadingImage"]',".hyc-media-box--loadingImage",".loading-image-box"].join(", "),w=".ybc-model-select-button",x=`${w} .t-button__text`,k=[".ybc-model-select-dropdown-popup .t-dropdown__item",".ybc-model-select-dropdown .t-dropdown__item",".t-popup .t-dropdown__item"].join(", "),S=[".hyc-component-reasoner__think-content .hyc-common-markdown-style",".hyc-component-deepsearch-cot__think__content__item .hyc-common-markdown-style",".hyc-common-markdown-style-cot"].join(", "),C=[".hyc-component-reasoner__think",".hyc-component-deepsearch-cot__think",".hyc-common-markdown-style-cot"].join(", "),T=[".t-dropdown__menu",".t-dropdown__submenu",".t-dropdown",".t-popup",".t-popup__content",".t-popup__content__inner",'[role="menu"]','[role="listbox"]'].join(", "),E=[".t-dropdown__item",".yb-dropdown__item",'[role="menuitem"]','[role="option"]'].join(", "),M=['[aria-haspopup="menu"]','[aria-haspopup="listbox"]',".icon-yb-ic_ellipsis",".icon-yb-ic_more_vert",".icon-yb-ic_more_vert_16",".icon-yb-ic_delete",".icon-yb-ic_delete_16",".icon-yb-ic_delete_20",".icon-more",".icon-del",".icon-delete",".icon-menu","button",'[role="button"]'].join(", "),I=[".t-dialog button",'.t-dialog [role="button"]','[role="dialog"] button','[role="dialog"] [role="button"]'].join(", "),N=".agent-dialogue__content-split-pane--show",A=[".yb-layout__content",".yb-layout__content-skeleton",N].join(", "),P=[`${N} > .Pane1`,".agent-dialogue__content--common"].join(", "),L=`${N} > .Pane2:has(#yuanbao-canvas-container)`,R="--hunyuan-chat-list-max-width",$="button, [role='button'], svg",z=`.gh-user-query-markdown, ${$}, input, label`,_=[m,p,y,$].join(", "),O=[".gh-user-query-markdown",$,"[aria-hidden='true']","style","script"].join(", "),D=[m,p,$].join(", ");return {capabilities:[...bt[Ie.YUANBAO]],selectors:{textarea:[t],submitButton:[r],responseContainer:c,chatContent:[d,h],userQuery:d,assistantResponse:h,newChatButton:['.yb-common-nav__trigger[data-desc="new-chat"]'],stopButton:[o],scrollContainer:[l,c,"#chat-content"],sidebarScrollContainer:".yb-nav__content"},input:{mode:"contenteditable",submitKey:"Enter"},conversation:{itemSelector:a,idFrom:{attr:"dt-cid",regex:"^(.+)$"},titleSelector:i,urlTemplate:"/chat/{id}",activeMatch:".active",navigationStrategy:"click-item",shadow:false},generating:{existsSelectors:[o]},networkMonitor:{urlPatterns:["/api/chat/"],silenceThreshold:2e3},modelSwitcher:{selectorButtonSelectors:[w,x],menuItemSelector:k,checkInterval:1e3,maxAttempts:10,menuRenderDelay:200},export:{userQuerySelector:d,assistantResponseSelector:h,turnSelector:null,useShadowDOM:false},widthSelectors:[{selector:":root",property:R,noCenter:true},{selector:":root",property:"--hunyuan-chat-list-width",value:`min(100%, var(${R}))`,noCenter:true}],zenMode:{hide:[".yb-nav__content-wrapper",".yb-nav-fixed.yb-nav-fixed--pc-ctx"],styles:[{selector:".agent-dialogue__content--common__input-box",property:"padding-bottom",value:"0"},{selector:".yb-nav--push.yb-nav--open~.yb-layout__content, .yb-nav--push.yb-nav--open~.yb-layout__content-skeleton",property:"margin-left",value:"0"}]},cleanMode:{hide:[".agent-dialogue__content-copyright",".yb__pc_download",".agent-dialogue__tool"]},sitePrivateSelectors:{inputContainer:e,primarySubmitButton:n,conversationPinned:s,conversationFallbackId:"[data-item-id]",agentId:[`${a}[dt-agent-id]`,"[dt-agent-id]"],userText:u,assistantMarkdown:g,userAttachmentImage:f,userAttachmentFile:b,userImageContainer:".hyc-component-multi-modal__image, .hyc-content-img",assistantGeneratedImage:v,thoughtMarkdown:S,thoughtContainer:C,assistantReasonerBody:[".hyc-component-reasoner__text .hyc-common-markdown-style",".hyc-component-reasoner__text .hyc-content-md-done",".hyc-component-reasoner__text"],dropdownMenu:T,dropdownItem:E,conversationMenuTrigger:M,dialog:'.t-dialog, [role="dialog"]',dialogButton:I,layoutScope:A,chatColumnScope:P,canvasPane:L,chatContent:".agent-dialogue__content--common__content",userTextDecoration:z,assistantExportDecoration:_,cleanTextDecoration:O,assistantPlainTextDecoration:D,headingDecoration:$,thoughtDecoration:`${p}, ${$}, [aria-hidden='true']`,assistantSpeechText:".agent-chat__speech-text",bubbleContent:".agent-chat__bubble__content",assetCard:"[data-card-url]",conversationActionExclusion:".t-checkbox, [role='checkbox']",conversationActionIcon:".iconfont-yb, .yb-icon, svg",sendIcon:"span.icon-send, .icon-send",stopIcon:"rect"}}})(),sa="data-gh-export-role",la=`[${sa}="user"]`,ca=`[${sa}="assistant"]`,da=(()=>{const e="#chat-container",t=`${e} #messages-container`,n=[t,`${e} .flex.overflow-y-scroll.flex-col.w-full.h-full`,`${e} .scrollbar-none.flex.flex-col`,`${e} [data-pane-id] .overflow-y-scroll`,`${e} [data-pane-id] .scrollbar-none`].join(", "),r=[`${e} [class*="max-w-[808px]"]`,`${e} [class*="max-w-[894px]"]`,`${e} [class*="max-w-[1000px]"]`,`${e} [class*="max-w-[960px]"]`].join(", "),o=[`${e} .messageInputContainer [class*="max-w-[768px]"]`,`${e} .messageInputContainer [class*="max-w-[854px]"]`].join(", "),a=['[id^="message-"].user-message',".user-message .chat-user.markdown-prose",".user-message .chat-user",`${e} .chat-user.markdown-prose`,`${e} .chat-user`,`${e} [data-message-author-role="user"]`,`${e} [data-role="user"]`,`${e} .message-user`,`${e} .user-message`,`${e} .chat-message-user`,`${e} .message.user`].join(", "),i=[`${e} .markdown-prose:not(.chat-user)`,`${e} [data-message-author-role="assistant"]`,`${e} [data-role="assistant"]`,`${e} .message-assistant`,`${e} .assistant-message`,`${e} .chat-message-assistant`,`${e} .markdown`,`${e} .markdown-body`,`${e} .prose`,`${e} article`,`${e} [data-markdown]`,'[id^="message-"]:not(.user-message) .markdown-prose:not(.chat-user)','[id^="message-"]:not(.user-message) .markdown-body','[id^="message-"]:not(.user-message) [data-markdown]'],s=['[id^="message-"]:not(.user-message)',...i],l=['div[aria-label="停止"] button',"button:has(span.rounded-xs):has(span.size-3)","button:has(span.rounded-xs):has(span.block)"].join(", "),c=".thinking-chain-container",d=".thinking-block",h="blockquote[slot='content']",u="blockquote";return {capabilities:[...bt[Ie.ZAI]],selectors:{textarea:["#chat-input","textarea#chat-input"],responseContainer:n,chatContent:[a,...s],userQuery:a,newChatButton:["#sidebar-new-chat-button","#new-chat-button"],stopButton:[l]},input:{mode:"textarea",submitKey:"Enter"},generating:{existsSelectors:[l]},modelSwitcher:{selectorButtonSelectors:["button.modelSelectorButton",'button[id^="model-selector-"][id$="-button"]',"#model-selector-glm-5-button","button[data-melt-dropdown-menu-trigger][data-menu-trigger].modelSelectorButton"],menuItemSelector:'button[aria-label="model-item"], button[data-melt-collapsible-trigger]',checkInterval:1e3,maxAttempts:12,menuRenderDelay:400,subMenuSelector:"button[data-melt-collapsible-trigger]",subMenuTriggers:["更多模型","more"]},export:{userQuerySelector:la,assistantResponseSelector:ca,turnSelector:null,useShadowDOM:false},zenMode:{hide:["#sidebar"]},widthSelectors:[{selector:r,property:"max-width"},{selector:o,property:"max-width"}],sitePrivateSelectors:{chatContainer:e,chatMessagesContainer:t,chatMessageWidth:r,chatInputSafeArea:`${e}:not(:has([data-pane-id] .placeholder-input)) .messageInputContainer`,newChatContentSafeArea:`${e} [data-pane-id]:has(.placeholder-input)`,userQueryWidth:`${e} .chat-user [class*="max-w-[90%]"]`,submitButton:"#send-message-button",assistantMarkdown:s,assistantBody:i,thinkingChainContainer:c,thinkingBlock:d,thinkingContent:h,blockquote:u,thinkingContainer:`${c}, ${d}`,thinkingBlockquote:`${h}, ${d} ${u}, ${c} ${u}`,userContentCandidates:[".gh-user-query-raw",".rounded-xl.whitespace-pre-wrap",".rounded-xl",".whitespace-pre-wrap","[data-user-content]",".message-content",".chat-message-content",".user-message-content",".content",'div[dir="auto"]',"p"],exportDecoration:[".gh-root",".gh-user-query-markdown","button","[role='button']","svg","[aria-hidden='true']","style","script"].join(", "),sidebarItem:"#sidebar .w-full.mb-1.relative.group",sidebarTitle:'div[dir="auto"]',sidebarItemTrigger:"button",sidebarScrollContainer:"#sidebar .overflow-y-auto",paneRoot:"[data-pane-id]",inputWithinScrollContainer:"textarea, #chat-input",horizontalScrollContainer:".scrollbar-none",themeMeta:'meta[name="theme-color"]',messageRoot:'[id^="message-"]',attachmentCards:"button",attachmentImages:"img[data-cy='image'], img.not-prose",attachmentIconImages:"img[src*='/icons/']"}}})(),ha=new Map([[Ie.AISTUDIO,{siteId:Ie.AISTUDIO,configVersion:1,baseConfig:Ko}],[Ie.CHATGLM,{siteId:Ie.CHATGLM,configVersion:2,baseConfig:Go}],[Ie.CHATGPT,{siteId:Ie.CHATGPT,configVersion:2,baseConfig:Qo}],[Ie.CLAUDE,{siteId:Ie.CLAUDE,configVersion:4,baseConfig:Yo}],[Ie.DEEPSEEK,{siteId:Ie.DEEPSEEK,configVersion:1,baseConfig:Zo}],[Ie.DOUBAO,{siteId:Ie.DOUBAO,configVersion:2,baseConfig:Xo}],[Ie.GROK,{siteId:Ie.GROK,configVersion:2,baseConfig:Jo}],[Ie.GEMINI,{siteId:Ie.GEMINI,configVersion:1,baseConfig:ea}],[Ie.GEMINI_ENTERPRISE,{siteId:Ie.GEMINI_ENTERPRISE,configVersion:1,baseConfig:ta}],[Ie.IMA,{siteId:Ie.IMA,configVersion:1,baseConfig:na}],[Ie.KIMI,{siteId:Ie.KIMI,configVersion:1,baseConfig:ra}],[Ie.QIANWEN,{siteId:Ie.QIANWEN,configVersion:1,baseConfig:oa}],[Ie.QWENAI,{siteId:Ie.QWENAI,configVersion:2,baseConfig:aa}],[Ie.YUANBAO,{siteId:Ie.YUANBAO,configVersion:1,baseConfig:ia}],[Ie.ZAI,{siteId:Ie.ZAI,configVersion:1,baseConfig:da}]]),ua=e=>ha.get(e)??null;class ga extends Error{errors;constructor(e,t){super(e),this.name="SiteConfigResolutionError",this.errors=t;}}const pa=new Set(["__proto__","prototype","constructor"]),ma=e=>{if(null===e||"object"!=typeof e||Array.isArray(e))return false;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t},fa=e=>{if(Array.isArray(e))return e.map(fa);if(!ma(e))return e;const t={};for(const[n,r]of Object.entries(e)){if(pa.has(n))throw new TypeError(`Unsafe config key: ${n}`);t[n]=fa(r);}return t},ba=(e,t)=>{const n=fa(e);for(const[r,o]of Object.entries(t)){if(pa.has(r))throw new TypeError(`Unsafe config key: ${r}`);if(void 0===o)throw new TypeError(`Config override must be JSON-compatible: ${r} is undefined`);if(null!==o)if(Array.isArray(o))n[r]=o.map(fa);else {if(ma(o)){const e=n[r],t=ma(e)?e:{};n[r]=ba(t,o);continue}n[r]=o;}else delete n[r];}return n};const va=(e,t,n="$")=>{if(null===e)return [];if(Array.isArray(e))return Array.isArray(t)?[]:[{path:n,code:"invalid_type",message:"Expected an array from the built-in config"}];if(ma(e)){if(!ma(t))return [{path:n,code:"invalid_type",message:"Expected an object from the built-in config"}];const r=[];for(const[o,a]of Object.entries(e)){if(null===a)continue;const e=`${n}.${o}`;Object.hasOwn(t,o)?r.push(...va(a,t[o],e)):r.push({path:e,code:"missing_required",message:"Built-in config field cannot be removed"});}return r}return typeof t==typeof e?[]:[{path:n,code:"invalid_type",message:`Expected ${typeof e} from the built-in config`}]},ya=(e,t,n,r,o)=>{const a=function(e,t){return ba(e,t)}(e,n),i=dn(a,{allowedPrivateSelectorKeys:r,requiredPrivateSelectorKeys:r,requiredCapabilities:o});if(!i.valid)return {config:e,outcome:{status:"rejected",stage:"merged-config",errors:i.errors}};const s=va(t,a);return s.length>0?{config:e,outcome:{status:"rejected",stage:"merged-config",errors:s}}:{config:a,outcome:{status:"applied"}}};function wa(e){if(!Yt(e.appVersion))throw new TypeError(`Invalid appVersion: ${e.appVersion}`);if(!Number.isInteger(e.configVersion)||e.configVersion<1)throw new TypeError(`configVersion must be a positive integer: ${e.configVersion}`);const t=(n=e.baseConfig,Object.keys(n.sitePrivateSelectors??{}));var n;const r=[...e.baseConfig.capabilities],o=dn(e.baseConfig,{allowedPrivateSelectorKeys:t,requiredPrivateSelectorKeys:t,requiredCapabilities:r});if(!o.valid)throw new ga("Built-in site config is invalid",o.errors);let a=fa(e.baseConfig),i={status:"absent"},s={status:"absent"};if(void 0!==e.remotePatch&&null!==e.remotePatch){const n=hn(e.remotePatch,{allowedPrivateSelectorKeys:t});if(n.valid){const o=n.value,s=((e,t,n,r)=>{if(e.targetSiteId!==t)return "target-site-mismatch";if(e.baseConfigVersion!==r)return "base-config-version-mismatch";if(-1===Zt(n,e.minAppVersion))return "below-min-app-version";if(e.maxAppVersion&&1===Zt(n,e.maxAppVersion))return "above-max-app-version";return null})(o,e.siteId,e.appVersion,e.configVersion);if(s)i={status:"skipped",reason:s,patchVersion:o.patchVersion};else {const n=ya(a,e.baseConfig,o.config,t,r);a=n.config,i={...n.outcome,patchVersion:o.patchVersion};}}else i={status:"rejected",stage:"validation",errors:n.errors};}if(void 0!==e.userOverride){const n=function(e,t={}){const n=St(t);return zt(e,"$",n),cn(e,"$",n,"partial",t),Rt(e,n)}(e.userOverride,{allowedPrivateSelectorKeys:t});if(n.valid){const o=ya(a,e.baseConfig,n.value,t,r);a=o.config,s=o.outcome;}else s={status:"rejected",stage:"validation",errors:n.errors};}return {config:a,remotePatch:i,userOverride:s}}const xa=e=>null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.applyMergedConfig,ka=e=>xa(e)&&"function"==typeof e.getBuiltinConfig&&"function"==typeof e.getBuiltinConfigVersion;function Sa(e,t){return !!xa(e)&&(e.applyMergedConfig(t),true)}const Ca=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:Ta,n:Ea,Gx:Ma,Gy:Ia,a:Na,d:Aa,h:Pa}=Ca,La=(e="")=>{const t=new Error(e);throw ((...e)=>{"captureStackTrace"in Error&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(...e);})(t,La),t},Ra=(e,t,n="")=>{const r=(o=e)instanceof Uint8Array||ArrayBuffer.isView(o)&&"Uint8Array"===o.constructor.name&&"BYTES_PER_ELEMENT"in o&&1===o.BYTES_PER_ELEMENT;var o;const a=e?.length,i=void 0!==t;if(!r||i&&a!==t){const o=(n&&`"${n}" `)+"expected Uint8Array"+(i?` of length ${t}`:"")+", got "+(r?`length=${a}`:"type="+typeof e);throw r?new RangeError(o):new TypeError(o)}return e},$a=e=>new Uint8Array(e),za=e=>Uint8Array.from(e),_a=(e,t)=>e.toString(16).padStart(t,"0"),Oa=e=>Array.from(Ra(e)).map(e=>_a(e,2)).join(""),Da=48,Ba=57,qa=65,Fa=70,Ha=97,Ua=102,ja=e=>e>=Da&&e<=Ba?e-Da:e>=qa&&e<=Fa?e-(qa-10):e>=Ha&&e<=Ua?e-(Ha-10):void 0,Wa=e=>{const t="hex invalid";if("string"!=typeof e)return La(t);const n=e.length,r=n/2;if(n%2)return La(t);const o=$a(r);for(let a=0,i=0;a(globalThis?.crypto)?.subtle??La("crypto.subtle must be defined, consider polyfill"),Ka=(...e)=>{let t=0;for(const o of e)t+=Ra(o).length;const n=$a(t);let r=0;return e.forEach(e=>{n.set(e,r),r+=e.length;}),n},Ga=BigInt,Qa=(e,t,n,r="bad number: out of range")=>{if(!(e=>"bigint"==typeof e)(e))throw new TypeError(r);if(t<=e&&e{const n=e%t;return n>=0n?n:t+n},Za=(1n<<255n)-1n,Xa=e=>{e<0n&&La("negative coordinate");let t=19n*(e>>255n)+(e&Za);return t=19n*(t>>255n)+(t&Za),t%Ta},Ja=e=>Ra(e,64,"digest"),ei=e=>e instanceof ni?e:La("Point expected"),ti=2n**256n;class ni{static BASE;static ZERO;X;Y;Z;T;constructor(e,t,n,r){const o=ti;this.X=Qa(e,0n,o),this.Y=Qa(t,0n,o),this.Z=Qa(n,1n,o),this.T=Qa(r,0n,o),Object.freeze(this);}static CURVE(){return Ca}static fromAffine(e){return new ni(e.x,e.y,1n,Xa(e.x*e.y))}static fromBytes(e,t=false){const n=Aa,r=za(Ra(e,32)),o=e[31];r[31]=-129&o;const a=ii(r);Qa(a,0n,t?ti:Ta);const i=Xa(a*a),s=Ya(i-1n),l=Xa(n*i+1n);let{isValid:c,value:d}=ci(s,l);c||La("bad point: y not sqrt");const h=1n==(1n&d),u=!!(128&o);return !t&&0n===d&&u&&La("bad point: x==0, isLastByteOdd"),u!==h&&(d=Ya(-d)),new ni(d,a,1n,Xa(d*a))}static fromHex(e,t){return ni.fromBytes(Wa(e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const e=Na,t=Aa;if(this.is0())return La("bad point: ZERO");const{X:n,Y:r,Z:o,T:a}=this,i=Xa(n*n),s=Xa(r*r),l=Xa(o*o),c=Xa(l*l),d=Xa(i*e);if(Xa(l*(d+s))!==Ya(c+Xa(t*Xa(i*s))))return La("bad point: equation left != right (1)");return Xa(n*r)!==Xa(o*a)?La("bad point: equation left != right (2)"):this}equals(e){const{X:t,Y:n,Z:r}=this,{X:o,Y:a,Z:i}=ei(e),s=Xa(t*i),l=Xa(o*r),c=Xa(n*i),d=Xa(a*r);return s===l&&c===d}is0(){return this.equals(oi)}negate(){return new ni(Ya(-this.X),this.Y,this.Z,Ya(-this.T))}double(){const{X:e,Y:t,Z:n}=this,r=Na,o=Xa(e*e),a=Xa(t*t),i=Xa(2n*n*n),s=Xa(r*o),l=Ya(e+t),c=Ya(Xa(l*l)-o-a),d=Ya(s+a),h=Ya(d-i),u=Ya(s-a),g=Xa(c*h),p=Xa(d*u),m=Xa(c*u),f=Xa(h*d);return new ni(g,p,f,m)}add(e){const{X:t,Y:n,Z:r,T:o}=this,{X:a,Y:i,Z:s,T:l}=ei(e),c=Na,d=Aa,h=Xa(t*a),u=Xa(n*i),g=Xa(Xa(o*d)*l),p=Xa(r*s),m=Ya(Xa(Ya(t+n)*Ya(a+i))-h-u),f=Ya(p-g),b=Ya(p+g),v=Ya(u-Xa(c*h)),y=Xa(m*f),w=Xa(b*v),x=Xa(m*v),k=Xa(f*b);return new ni(y,w,k,x)}subtract(e){return this.add(ei(e).negate())}multiply(e,t=true){if(!t&&0n===e)return oi;if(Qa(e,1n,Ea),!t&&this.is0())return oi;if(1n===e)return this;if(this.equals(ri))return vi(e).p;let n=oi,r=ri;for(let o=this;e>0n;o=o.double(),e>>=1n)1n&e?n=n.add(o):t&&(r=r.add(o));return n}multiplyUnsafe(e){return this.multiply(e,false)}toAffine(){const{X:e,Y:t,Z:n}=this;if(this.equals(oi))return {x:0n,y:1n};const r=((e,t)=>{(0n===e||t<=0n)&&La("no inverse n="+e+" mod="+t);let n=Ya(e,t),r=t,o=0n,a=1n;for(;0n!==n;){const e=r%n,t=o-a*(r/n);r=n,n=e,o=a,a=t;}return 1n===r?Ya(o,t):La("no inverse")})(n,Ta);1n!==Xa(n*r)&&La("invalid inverse");return {x:Xa(e*r),y:Xa(t*r)}}toBytes(){const{x:e,y:t}=this.toAffine(),n=ai(t);return n[31]|=1n&e?128:0,n}toHex(){return Oa(this.toBytes())}clearCofactor(){return this.multiply(Ga(Pa),false)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.multiply(Ea/2n,false).double();return Ea%2n&&(e=e.add(this)),e.is0()}}const ri=new ni(Ma,Ia,1n,Ya(Ma*Ia)),oi=new ni(0n,1n,1n,0n);ni.BASE=ri,ni.ZERO=oi;const ai=e=>Wa(_a(Qa(e,0n,ti),64)).reverse(),ii=e=>Ga("0x"+Oa(za(Ra(e)).reverse())),si=(e,t)=>{let n=e;for(;t-- >0n;)n=Xa(n*n);return n},li=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,ci=(e,t)=>{const n=Xa(t*Xa(t*t)),r=Xa(Xa(n*n)*t),o=(e=>{const t=Xa(e*e),n=Xa(t*e),r=Xa(si(n,2n)*n),o=Xa(si(r,1n)*e),a=Xa(si(o,5n)*o),i=Xa(si(a,10n)*a),s=Xa(si(i,20n)*i),l=Xa(si(s,40n)*s),c=Xa(si(l,80n)*l),d=Xa(si(c,80n)*l),h=Xa(si(d,10n)*a);return {pow_p_5_8:Xa(si(h,2n)*e),b2:n}})(Xa(e*r)).pow_p_5_8;let a=Xa(e*Xa(n*o));const i=Xa(t*Xa(a*a)),s=a,l=Xa(a*li),c=i===e,d=i===Ya(-e),h=i===Ya(-e*li);return c&&(a=s),(d||h)&&(a=l),1n==(1n&Ya(a))&&(a=Ya(-a)),{isValid:c||d,value:a}},di=e=>{return t=ii(e),Ya(t,Ea);var t;},hi=(...e)=>Promise.resolve((e=>{const t=pi[e];return "function"!=typeof t&&La("hashes."+e+" not set"),t})("sha512Async")(Ka(...e))).then(Ja),ui={zip215:true},gi=async(e,t,n,r=ui)=>{return o=((e,t,n,r=ui)=>{e=Ra(e,64),t=Ra(t),n=Ra(n,32);const{zip215:o=true}=r,a=e.subarray(0,32),i=ii(e.subarray(32,64));let s,l,c,d=Uint8Array.of(),h=false;try{s=ni.fromBytes(n,o),l=ni.fromBytes(a,o),c=ri.multiply(i,!1),d=Ka(a,n,t),h=!0;}catch(u){}return {hashable:d,finish:e=>{if(!h)return false;if(!o&&s.isSmallOrder())return false;const t=di(e);return l.add(s.multiply(t,false)).subtract(c).clearCofactor().is0()}}})(e,t,n,r),hi(o.hashable).then(o.finish);var o;},pi={sha512Async:async e=>{const t=Va(),n=Ka(e);return $a(await t.digest("SHA-512",n.buffer))},sha512:void 0},mi=Math.ceil(32)+1;let fi;const bi=(e,t)=>{const n=t.negate();return e?n:t},vi=e=>{const t=fi||(fi=(()=>{const e=[];let t=ri,n=t;for(let r=0;r>=a,s>128&&(s-=256,e+=1n);const l=128*i,c=l,d=l+Math.abs(s)-1,h=i%2!=0,u=s<0;0===s?r=r.add(bi(h,t[c])):n=n.add(bi(u,t[d]));}return 0n!==e&&La("invalid wnaf"),{p:n,f:r}},yi="Ed25519",wi=[{keyId:"ophel-registry-2026-07",publicKeyHex:"0cd6f101298bc5ef27b950225fb209e348d61b7b66c8631593536675a4ec6505",minRegistryRevision:1}],xi=/^[a-z0-9][a-z0-9-]{2,63}$/,ki=/^[a-f0-9]{64}$/,Si=/^[a-f0-9]{128}$/,Ci=e=>{const t=new Uint8Array(e.length/2);for(let n=0;n{if(!xi.test(e.keyId))throw new TypeError(`Invalid trusted registry signing key ID: ${e.keyId}`);if(!ki.test(e.publicKeyHex))throw new TypeError(`Invalid public key for registry signing key: ${e.keyId}`);if(!Number.isSafeInteger(e.minRegistryRevision)||e.minRegistryRevision<1)throw new TypeError(`Invalid minimum revision for registry signing key: ${e.keyId}`);if(void 0!==e.maxRegistryRevision&&(!Number.isSafeInteger(e.maxRegistryRevision)||e.maxRegistryRevision{if(!(e=>{if(null===e||"object"!=typeof e||Array.isArray(e))return false;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t})(e))throw new TypeError("Registry index signature must be an object");const t=new Set(["schemaVersion","algorithm","keyId","signature"]);for(const n of Object.keys(e))if(!t.has(n))throw new TypeError(`Unknown key in registry index signature: ${n}`);if(1!==e.schemaVersion)throw new TypeError("Registry index signature schemaVersion must be 1");if(e.algorithm!==yi)throw new TypeError(`Registry index signature algorithm must be ${yi}`);if("string"!=typeof e.keyId||!xi.test(e.keyId))throw new TypeError("Registry index signature keyId is invalid");if("string"!=typeof e.signature||!Si.test(e.signature))throw new TypeError("Registry index signature must be 128 lowercase hexadecimal characters");return {schemaVersion:1,algorithm:yi,keyId:e.keyId,signature:e.signature}},Mi=async(e,t,n=wi)=>{const r=Ei((e=>{let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(e);}catch(n){throw new SyntaxError(`Invalid UTF-8 in registry index signature: ${n instanceof Error?n.message:String(n)}`)}65279===t.charCodeAt(0)&&(t=t.slice(1));try{return JSON.parse(t)}catch(n){throw new SyntaxError(`Invalid registry index signature JSON: ${n instanceof Error?n.message:String(n)}`)}})(t)),o=n.find(e=>e.keyId===r.keyId);if(!o)throw new Error(`Unknown registry signing key: ${r.keyId}`);let a;Ti(o);try{a=await gi(Ci(r.signature),e,Ci(o.publicKeyHex),{zip215:!1});}catch(i){throw new Error(`Registry Ed25519 verification failed for key ${o.keyId}: ${i instanceof Error?i.message:String(i)}`)}if(!a)throw new Error(`Invalid Ed25519 signature for registry index: ${o.keyId}`);return o},Ii=/^[a-z0-9-]{2,40}$/,Ni=e=>e instanceof Error?e.message:String(e),Ai=(e,t)=>{let n=new TextDecoder("utf-8",{fatal:true}).decode(e);65279===n.charCodeAt(0)&&(n=n.slice(1));try{return JSON.parse(n)}catch(r){throw new SyntaxError(`Invalid JSON from ${t}: ${Ni(r)}`)}},Pi=async e=>{if(!globalThis.crypto?.subtle)throw new Error("Web Crypto SHA-256 is unavailable");const t=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),e=>e.toString(16).padStart(2,"0")).join("")},Li=async(e,t,n)=>{const r=await e(t,n);if(!(r instanceof Uint8Array))throw new TypeError(`Registry transport returned an invalid payload for ${t}`);if(0===r.byteLength)throw new Error(`Registry response is empty: ${t}`);if(r.byteLength>n)throw new Error(`Registry response exceeds ${n} bytes: ${t}`);return r},Ri=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),$i=(e,t)=>e.id===t.id&&e.version===t.version&&e.minAppVersion===t.minAppVersion&&Ri(e.matches,t.matches)&&e.file===t.file&&e.sha256===t.sha256&&e.disabled===t.disabled,zi=(e,t)=>e.targetSiteId===t.targetSiteId&&e.patchVersion===t.patchVersion&&e.baseConfigVersion===t.baseConfigVersion&&e.minAppVersion===t.minAppVersion&&e.maxAppVersion===t.maxAppVersion&&e.file===t.file&&e.sha256===t.sha256&&e.disabled===t.disabled,_i=(e,t)=>e.generatedAt===t.generatedAt&&e.schemaVersion===t.schemaVersion&&e.registryRevision===t.registryRevision&&e.packs.length===t.packs.length&&e.patches.length===t.patches.length&&e.packs.every((e,n)=>$i(e,t.packs[n]))&&e.patches.every((e,n)=>zi(e,t.patches[n])),Oi=(e,t)=>{const n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>t[n]?.index.sha256===e[n].index.sha256&&t[n]?.index.file===e[n].index.file)},Di=(e,t)=>Boolean(e&&_i(e.index,t.index)&&Oi(e.packs,t.packs)&&Oi(e.patches,t.patches)),Bi=(e,t)=>{const n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>t[n]===e[n])},qi=(e,t)=>{if(e.id!==t.id||e.version!==t.version||e.minAppVersion!==t.minAppVersion||!Ri(e.matches,t.matches))throw new Error(`Pack metadata does not match registry index: ${t.id}`)},Fi=(e,t)=>{if(e.targetSiteId!==t.targetSiteId||e.patchVersion!==t.patchVersion||e.baseConfigVersion!==t.baseConfigVersion||e.minAppVersion!==t.minAppVersion||e.maxAppVersion!==t.maxAppVersion)throw new Error(`Patch metadata does not match registry index: ${t.targetSiteId}`)},Hi=(e,t,n)=>{const r=hn(e,{allowedPrivateSelectorKeys:Object.keys(t.baseConfig.sitePrivateSelectors??{})});if(!r.valid)throw new Error(`Patch validation failed: ${r.errors.map(e=>`${e.path} ${e.message}`).join("; ")}`);const o=wa({siteId:t.siteId,appVersion:n,configVersion:t.configVersion,baseConfig:t.baseConfig,remotePatch:r.value});if("applied"!==o.remotePatch.status)throw new Error(`Patch could not be merged for ${t.siteId}: ${o.remotePatch.reason??o.remotePatch.stage??o.remotePatch.status}`);return r.value},Ui=(e,t,n)=>Boolean(t&&t.siteId===e.targetSiteId&&t.configVersion===e.baseConfigVersion&&En(n,e.minAppVersion,e.maxAppVersion));class ji{storage;transport;appVersion;resolveBuiltinConfig;sources;resolveSources;checkIntervalMs;now;trustedSigningKeys;mutationQueue=Promise.resolve();constructor(e){if(0===e.sources?.length)throw new TypeError("At least one registry source is required");if(!Number.isFinite(e.checkIntervalMs??un)||(e.checkIntervalMs??un)<=0)throw new TypeError("checkIntervalMs must be a positive finite number");if(!Yt(e.appVersion))throw new TypeError(`Invalid appVersion: ${e.appVersion}`);this.storage=e.storage,this.transport=e.transport,this.appVersion=e.appVersion,this.resolveBuiltinConfig=e.resolveBuiltinConfig,this.sources=(e.sources??gn).map(Do),this.resolveSources=e.resolveSources,this.checkIntervalMs=e.checkIntervalMs??un,this.now=e.now??Date.now,this.trustedSigningKeys=e.trustedSigningKeys??wi;}getState(){return this.enqueue(()=>zn(this.storage))}checkForUpdates(e={}){return this.enqueue(()=>this.performCheck(true===e.force,e.sources))}ignorePatch(e,t={}){return this.enqueue(async()=>{if(!Ii.test(e))return false;const n=await zn(this.storage),r=n.active?.patches[e],o=n.localPatches[e];if(!(void 0!==o)&&!(void 0!==r))return false;if(void 0!==t.patchVersion&&(!Number.isSafeInteger(t.patchVersion)||t.patchVersion<1))return false;const a=[t.patchVersion,r?.patch.patchVersion,o?.patch.patchVersion].filter(e=>Number.isSafeInteger(e)&&e>=1),i=a.length>0?Math.max(...a):void 0,s={...n.ignoredPatches};void 0!==i&&(s[e]=Math.max(n.ignoredPatches[e]??0,i));let l=n.active;if(r&&n.active){const t={...n.active.patches};delete t[e],l={...n.active,patches:t};}const c={...n.localPatches};delete c[e];const d={...n,localPatches:c,ignoredPatches:s};return l?d.active=l:delete d.active,await this.storage.set(Oe,d),true})}installLocalPatch(e,t={}){return this.enqueue(async()=>{if(!(e=>{if(null===e||"object"!=typeof e||Array.isArray(e))return false;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t})(e))throw new TypeError("Local patch must be an object");const n=e.targetSiteId;if("string"!=typeof n||!Ii.test(n))throw new TypeError(`Invalid local patch targetSiteId: ${String(n)}`);const r=await this.resolveBuiltinConfig(n);if(!r)throw new Error(`No configurable built-in adapter for site: ${n}`);const o=Hi(e,r,this.appVersion),a=await zn(this.storage),i={installedAt:this.getTimestamp(),patch:o},s=t.fileName?.trim();s&&(i.fileName=s);const l=a.localPatches[n];if(void 0!==l&&l.patch.patchVersion===o.patchVersion&&l.patch.baseConfigVersion===o.baseConfigVersion&&l.fileName===i.fileName&&JSON.stringify(l.patch)===JSON.stringify(o))return {changed:false,siteId:n,record:l};const c={...a,localPatches:{...a.localPatches,[n]:i}};return await this.storage.set(Oe,c),{changed:true,siteId:n,record:i}})}removeLocalPatch(e){return this.enqueue(async()=>{if(!Ii.test(e))return {changed:false,siteId:e};const t=await zn(this.storage);if(void 0===t.localPatches[e])return {changed:false,siteId:e};const n={...t.localPatches};delete n[e];const r={...t,localPatches:n};return await this.storage.set(Oe,r),{changed:true,siteId:e}})}clearCachedRegistrySnapshot(){return this.enqueue(async()=>{const e=await zn(this.storage),t=void 0!==e.active,n=void 0!==e.lastError;if(!t&&!n)return false;const r={storageSchemaVersion:e.storageSchemaVersion,localPatches:e.localPatches,ignoredPatches:e.ignoredPatches};return void 0!==e.lastCheckAt&&(r.lastCheckAt=e.lastCheckAt),void 0!==e.lastSuccessAt&&(r.lastSuccessAt=e.lastSuccessAt),await this.storage.set(Oe,r),true})}getTimestamp(){const e=this.now();if(!Number.isSafeInteger(e)||e<1e12)throw new TypeError(`RemoteConfigManager now() must return a Unix millisecond timestamp: ${e}`);return e}enqueue(e){const t=this.mutationQueue.then(e,e);return this.mutationQueue=t.then(()=>{},()=>{}),t}async performCheck(e,t){const n=this.now(),r=await zn(this.storage),o={downloadedPacks:0,downloadedPatches:0,removedPacks:0,removedPatches:0,disabledPacks:0,disabledPatches:0,ignoredPatches:0,incompatiblePacks:0,incompatiblePatches:0};if(!e&&void 0!==r.lastCheckAt&&n-r.lastCheckAte.message).join(" | ");return await this.storage.set(Oe,{...r,lastCheckAt:n,lastError:{at:n,message:s,sources:i}}),{status:"failed",checkedAt:n,registryRevision:r.active?.index.registryRevision??0,sourceUrl:r.active?.sourceUrl,error:s,changes:o}}async getSourceUrls(e){const t=e&&e.length>0?e:this.resolveSources?await this.resolveSources():this.sources;if(0===t.length)throw new TypeError("At least one registry source is required");return t.map(Do)}async checkSource(e,t){const n=await Li(this.transport,e,524288),r=new URL("./index.sig.json",e).href,o=await Li(this.transport,r,4096),a=await Mi(n,o,this.trustedSigningKeys),i=Tn(Ai(n,e));((e,t)=>{if(Ti(e),!Number.isSafeInteger(t)||te.maxRegistryRevision)throw new Error(`Registry signing key ${e.keyId} is not valid for registry revision ${t}`)})(a,i.registryRevision);const s=Un(t.active?.sourceUrl,e)?{...t,active:void 0}:t,l=s.active?.index.registryRevision??0;if(i.registryRevision{const n=o[t.id],a=Bn(n)?n:void 0;if(t.disabled)return r.disabledPacks+=1,null;if(!En(this.appVersion,t.minAppVersion))return r.incompatiblePacks+=1,((e,t)=>{if(!Bn(e)||!En(t,e.manifest.minAppVersion))return false;const n=ln(e.manifest);if(!n.valid)return false;try{return qi(n.value,e.index),!0}catch{return false}})(a,this.appVersion)?[t.id,a]:null;if(a&&t.version{if(!Bn(e)||!$i(e.index,t))return false;const n=ln(e.manifest);if(!n.valid)return false;try{return qi(n.value,t),!0}catch{return false}})(a,t))return [t.id,a];const i=new URL(t.file,e).href,s=await Li(this.transport,i,vt);if(await Pi(s)!==t.sha256)throw new Error(`SHA-256 mismatch for ${t.file}`);const l=ln(Ai(s,i));if(!l.valid)throw new Error(`Pack validation failed: ${l.errors.map(e=>`${e.path} ${e.message}`).join("; ")}`);return qi(l.value,t),r.downloadedPacks+=1,[t.id,{index:t,manifest:l.value}]})),l=await Promise.all(t.patches.map(async t=>{const n=a[t.targetSiteId],o=qn(n)?n:void 0;if(t.disabled)return r.disabledPatches+=1,null;const s=i[t.targetSiteId];if(void 0!==s&&t.patchVersion<=s)return r.ignoredPatches+=1,null;const l=await this.resolveBuiltinConfig(t.targetSiteId);if(!Ui(t,l,this.appVersion))return r.incompatiblePatches+=1,((e,t,n)=>{if(!qn(e)||!Ui(e.index,t,n))return false;try{return Fi(e.patch,e.index),Hi(e.patch,t,n),!0}catch{return false}})(o,l,this.appVersion)?[t.targetSiteId,o]:null;if(o&&t.patchVersion{if(!qn(e)||!zi(e.index,t))return false;try{return Fi(e.patch,t),Hi(e.patch,n,r),!0}catch{return false}})(o,t,l,this.appVersion))return void 0!==s&&t.patchVersion>s&&delete i[t.targetSiteId],[t.targetSiteId,o];const c=new URL(t.file,e).href,d=await Li(this.transport,c,vt);if(await Pi(d)!==t.sha256)throw new Error(`SHA-256 mismatch for ${t.file}`);const h=Ai(d,c),u=Hi(h,l,this.appVersion);return Fi(u,t),void 0!==s&&t.patchVersion>s&&delete i[t.targetSiteId],r.downloadedPatches+=1,[t.targetSiteId,{index:t,patch:u}]})),c=Object.fromEntries(s.filter(e=>null!==e)),d=Object.fromEntries(l.filter(e=>null!==e));return r.removedPacks=Object.keys(o).filter(e=>!(e in c)).length,r.removedPatches=Object.keys(a).filter(e=>!(e in d)).length,{snapshot:{sourceUrl:e,index:t,packs:c,patches:d},ignoredPatches:i,changes:r}}}const Wi=e=>e?[...wi,Fn]:wi,Vi={async get(e){const t=GM_getValue(e);if(null!=t)return t},async set(e,t){GM_setValue(e,t);},async remove(e){GM_deleteValue(e);},watch(e,t){const n=GM_addValueChangeListener(e,(e,n,r,o)=>{t(r,n);});return ()=>GM_removeValueChangeListener(n)}},Ki=((e,t,n={})=>{const r=n.allowRegistrySourceOverride??fr,o=n.trustLocalDevRegistrySigningKey??fr;return new ji({storage:e,transport:t,appVersion:br,resolveBuiltinConfig:ua,resolveSources:()=>(async(e,t)=>{if(!t)return gn;const n=await Vo(e);return n?[n]:gn})(e,r),trustedSigningKeys:Wi(o)})})(Vi,(e,t)=>new Promise((n,r)=>{const o=`${e}${e.includes("?")?"&":"?"}_=${Date.now()}`;let a,i=false;const s=e=>{i||(i=true,r(e instanceof Error?e:new Error(String(e))));};a=GM_xmlhttpRequest({url:o,method:"GET",headers:{Accept:"application/json"},responseType:"arraybuffer",anonymous:true,timeout:15e3,onload(e){i||(e.status<200||e.status>=300?s(new Error(`Registry request failed: HTTP ${e.status} ${e.statusText}`.trim())):e.response instanceof ArrayBuffer?e.response.byteLength>t?s(new Error(`Registry response exceeds ${t} bytes`)):(i=true,n(new Uint8Array(e.response))):s(new Error("Registry request returned no binary response")));},onprogress(e){e.loaded>t&&(s(new Error(`Registry response exceeds ${t} bytes`)),a?.abort());},onerror(e){s(e);},ontimeout(){s(new Error("Registry request timed out after 15000ms"));}});})),Gi=yr(Vi),Qi=async e=>{if("failed"===e.status)return e;try{const e=await Gi.syncRegistryPacks();e.issues.length>0&&console.warn("[Ophel] Installed SitePack sync issues:",e.issues);}catch(t){console.error("[Ophel] Failed to sync installed SitePacks:",t);}return e},Yi=Object.freeze(Object.defineProperty({__proto__:null,checkUserscriptRemoteConfigNow:async e=>Qi(await Ki.checkForUpdates({force:true,...e&&e.length>0?{sources:e}:{}})),checkUserscriptRemoteConfigOnStartup:async()=>await Wo(Vi)?Qi(await Ki.checkForUpdates({force:false})):null,clearUserscriptRemoteConfigCache:async()=>Ki.clearCachedRegistrySnapshot(),getUserscriptRemoteConfigState:()=>Ki.getState(),installUserscriptLocalRemotePatch:async(e,t)=>{const n=await Ki.installLocalPatch(e,t?{fileName:t}:{});if(!n.changed&&!n.record)return false;const{reapplyBuiltinSiteConfig:r}=await o(async()=>{const{reapplyBuiltinSiteConfig:e}=await Promise.resolve().then(()=>Fc);return {reapplyBuiltinSiteConfig:e}},void 0);return r(n.siteId)},removeUserscriptLocalRemotePatch:async e=>{if(!(await Ki.removeLocalPatch(e)).changed)return false;const{reapplyBuiltinSiteConfig:t}=await o(async()=>{const{reapplyBuiltinSiteConfig:e}=await Promise.resolve().then(()=>Fc);return {reapplyBuiltinSiteConfig:e}},void 0);return t(e)},resetUserscriptRemotePatch:async(e,t)=>{if(!(await Ki.ignorePatch(e,{patchVersion:t})))return false;const{resetBuiltinSiteConfig:n}=await o(async()=>{const{resetBuiltinSiteConfig:e}=await Promise.resolve().then(()=>Fc);return {resetBuiltinSiteConfig:e}},void 0);return n(e)}},Symbol.toStringTag,{value:"Module"})),Zi=window.__OphelAdaptersVendorMeta,Xi=window.__OphelBuiltinAdapters;Zi&&1===Zi.schemaVersion&&"1.2.4"===Zi.version?Array.isArray(Xi)&&0!==Xi.length||console.error("[Ophel] Built-in adapters vendor is missing or empty; built-in site support is disabled."):console.error(`[Ophel] Adapters vendor version mismatch: expected v1.2.4 (schema 1), got v${Zi?.version??"missing"} (schema ${Zi?.schemaVersion??"missing"}); built-in site support is disabled. Try updating the userscript so @require caches refresh.`);const Ji=1===Zi?.schemaVersion&&"1.2.4"===Zi.version?(Xi??[]).map(e=>new e):[],es=e=>e.trim().replaceAll("_","-").toLowerCase(),ts=(e,t)=>{if(!e)return;if(Object.prototype.hasOwnProperty.call(e,t))return e[t];const n=Object.entries(e);for(const o of (e=>{const t=es(e);return "pt"===t?[t,"pt-br"]:"pt-br"===t?[t,"pt"]:[t]})(t)){const e=n.find(([e])=>es(e)===o);if(e)return e[1]}const r=n.find(([e])=>"en"===es(e));return r?.[1]},ns=(e,t)=>ts(e.nameI18n,t)??e.name,rs=(e,t)=>ts(e.descriptionI18n,t)??e.description,os={static:0,explicit:1},as=e=>`${Gn(e)}/*`,is=(e,t,n)=>{const r=e.get(t)??[];r.some(e=>e.packId===n.packId&&e.source===n.source)||(r.push(n),e.set(t,r));},ss=(e,t)=>{const n=new Map,r=new Map(e.map(e=>[e.manifest.id,e])),o=e.filter(hr);for(const i of o)for(const e of i.manifest.matches)is(n,ye(e),{packId:i.manifest.id,source:"static"});const a=[];for(const[i,s]of Object.entries(t.bindings)){const e=as(i),t=r.get(s.packId);t?hr(t)&&is(n,e,{packId:t.manifest.id,source:"explicit"}):a.push({code:"binding-pack-missing",origin:i,originPattern:e,packId:s.packId,message:`SitePack origin binding ${i} references missing pack ${s.packId}`});}return {originReferences:Array.from(n.entries()).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>{const n=(e=>[...e].sort((e,t)=>e.packId.localeCompare(t.packId)||os[e.source]-os[t.source]))(t);return {originPattern:e,referenceCount:n.length,references:n}}),bindingIssues:a.sort((e,t)=>e.origin.localeCompare(t.origin)||e.packId.localeCompare(t.packId))}},ls=(e,t)=>{const n=[];for(const[o,a]of Object.entries(t.bindings))a.packId===e.manifest.id&&n.push(as(o));return r=n,Array.from(new Set(r)).sort((e,t)=>e.localeCompare(t));var r;},cs=e=>Array.from(e.trim())[0]?.toUpperCase()??"?",ds=e=>Array.from(new Set(e.map(be))),hs=e=>{const[t]=ds(e);return t?new URL("/favicon.ico",t).href:void 0};let us=[],gs={storageSchemaVersion:1,bindings:{}},ps=[...Le],ms=se(),fs=null;const bs=()=>{var e,t,n;return ms=se(),ps=[...Le,...(e=us,t=gs,n=ms,e.map(e=>{const r=Array.from( new Set([...e.manifest.matches,...ls(e,t)])),o=ds(r),a=ns(e.manifest,n),i=hs(r);return Pe({id:`pack:${e.manifest.id}`,name:a,matchPatterns:r,entryUrls:o,icon:cs(a),...i?{faviconUrl:i}:{}},{allowEmptyMatchPatterns:true})}))],ps},vs=()=>ms!==se()?bs():ps,ys=(e,t)=>(us=[...e],gs=t,bs());const ws="data-ophel-managed-tab-title",xs="data-ophel-stale-managed-tab-title",ks=/\{(?:status|title|model|site)\}/g,Ss="{model}",Cs={"(":")","[":"]","{":"}","<":">","(":")","【":"】","《":"》","「":"」","『":"』"};function Ts(e){const t=e?.replace(/\s+/g," ").trim();return t||null}function Es(){"undefined"!=typeof document&&document.documentElement?.removeAttribute(ws);}function Ms(){return "undefined"==typeof document?null:document.documentElement?.getAttribute(ws)||null}function Is(){"undefined"!=typeof document&&document.documentElement?.removeAttribute(xs);}function Ns(e,t={}){const n=Ts(e);if(!n)return null;const r=Ts(t.expectedManagedTitle),o=Ts(t.privacyTitle),a=Ts(t.siteName),i=function(e,t){const n=Ts(t),r=Ts(Ms());return Boolean(n&&e===n)||Boolean(r&&e===r)}(n,r),s=i||true===t.hasManagedTitleSignal;if(o&&n===o)return null;const l=function(e,t){let n=e,r=t.hasManagedSignal;r&&/^(?:[⏳✅]\s*)+/u.test(n)&&(n=n.replace(/^(?:[⏳✅]\s*)+/u,""));const o=function(e,t){const n=t.titleFormat||"";if(!n.includes("{title}"))return null;const r=function(e,t){const n=[e],r=Ps(e);r!==e&&n.push(r);const o=[];return n.forEach(e=>{const n=function(e,t){const n=/\{(status|title|model|site)\}/g;let r="^\\s*",o=0,a=false,i=0;for(const s of e.matchAll(n)){r+=zs(e.slice(o,s.index));const n=s[1];if("title"===n)r+=a?"[\\s\\S]*?":"(?[\\s\\S]+?)",a=true;else if("status"===n)r+=`(?(?:[⏳✅]\\s*)*)`,i+=1;else if("model"===n)r+=`(?\\[[^\\]]{1,160}\\])?`,i+=1;else if("site"===n){const e=Ts(t);r+=e?`(?${zs(e)})`:`(?[\\s\\S]*?)`,i+=1;}o=s.index+s[0].length;}if(r+=zs(e.slice(o)),r+="\\s*$",!a)return null;try{return new RegExp(r,"u")}catch{return null}}(e,t);n&&o.push(n);}),o}(n,t.siteName);if(0===r.length)return null;let o=e,a=false,i=t.hasManagedSignal;for(let s=0;s<20;s+=1){const e=$s(o,r);if(!e)break;if(!i&&!e.hasManagedSignal)break;if(!e.title||e.title===o)break;o=e.title,a=true,i=true;}return a?Ts(o):null}(n,{hasManagedSignal:r,siteName:t.siteName,titleFormat:t.titleFormat});o&&o!==n&&(n=o,r=true);return Ts(n)}(n,{hasManagedSignal:s,siteName:t.siteName,titleFormat:t.titleFormat});return l?a&&l===a&&l!==n&&i||o&&l===o?null:l:null}function As(e,t={}){const n=Ts(e);if(!n)return null;if(t.rejectManagedTitle&&function(e,t){const n=Ts(t),r=Ts("undefined"==typeof document?null:document.documentElement?.getAttribute(xs)||null);return Boolean(n&&e===n)||Boolean(r&&e===r)}(n,t.expectedManagedTitle))return null;const r=Ns(e,t);if(!r)return null;const o=Ts(t.siteName);if(o&&r===o)return null;return Ts(o?r.replace(new RegExp(`\\s*[-|]\\s*${_s(o)}$`,"i"),"").replace(new RegExp(`^${_s(o)}\\s*(?:\\||-(?!\\s*>))\\s*`,"i"),"").trim():r)}function Ps(e){let t=e;for(;t.includes(Ss);){const e=Ls(t);if(e===t)return t.replace(/\{model\}/g,"");t=e;}return t}function Ls(e){const t=Array.from(e.matchAll(ks)),n=t.findIndex(e=>e[0]===Ss&&void 0!==e.index);if(n<0)return e;const r=t[n-1],o=t[n+1],a=t[n],i=a.index??0,s=i+a[0].length,l=void 0!==r?.index?r.index+r[0].length:0,c=o?.index??e.length,d=r&&o&&"{status}"!==r[0]&&"{status}"!==o[0]?function(e,t){const n=function(e,t){const n=e.match(/^(.*?)([\[({<(【《「『])\s*$/u),r=t.match(/^\s*([\])}>)】》」』])(.*)$/u);if(!n||!r)return null;const o=n[2],a=r[1];return Cs[o]!==a?null:`${n[1]}${r[2]}`}(e,t);if(null!==n)return n;const r=Rs(e),o=Rs(t);return r&&!o?t:!r&&o||e.trim()&&e.trim()===t.trim()?e:e.trim()?(t.trim(),e):t}(e.slice(l,i),e.slice(s,c)):"";return `${e.slice(0,l)}${d}${e.slice(c)}`}function Rs(e){return /[\p{L}\p{N}]/u.test(e)}function $s(e,t){for(const n of t){const t=n.exec(e),r=Ts(t?.groups?.ophelTitle);if(t&&r)return {title:r,hasManagedSignal:false}}return null}function zs(e){return _s(e).replace(/\s+/g,"\\s+")}function _s(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Os={MAX_DEPTH:15,DEFAULT_TIMEOUT:5e3,POLL_INTERVAL:50,CACHE_TTL:3e5},Ds={ELEMENT:1,DOCUMENT:9,FRAGMENT:11},Bs=["keydown","keypress","keyup"],qs="data-ophel-interaction-layer",Fs={[qs]:"true"},Hs="data-ophel-hover-width-retain-layer",Us={...Fs,[Hs]:"true"},js=[`[${qs}="true"]`,".gh-dialog-overlay",".conversations-dialog-overlay",".conversations-folder-menu",".conversations-tag-filter-menu",".prompt-modal",".prompt-preview-modal",".import-dialog",".settings-modal-overlay",".settings-search-overlay",".quick-menu-popover"].join(", "),Ws=[`[${Hs}="true"]`,".gh-dialog-overlay",".conversations-dialog-overlay",".conversations-folder-menu",".conversations-tag-filter-menu",".prompt-modal",".gh-prompt-preview-overlay",".prompt-preview-modal",".import-dialog",".quick-menu-popover",".gh-release-notes-overlay"].join(", "),Vs=(e,t)=>(t??("undefined"!=typeof document&&document.body?[document.body]:[])).some(t=>Boolean(t.querySelector(e))),Ks=e=>Vs(js,e),Gs=e=>e instanceof HTMLElement&&("INPUT"===e.tagName||"TEXTAREA"===e.tagName||"SELECT"===e.tagName||e.isContentEditable||"true"===e.getAttribute("contenteditable")||e.classList.contains("ProseMirror")),Qs=(e,t={})=>{const{events:n=Bs,capture:r=true}=t,o=e=>{(e=>{const t=("function"==typeof e.composedPath?e.composedPath():[]).find(e=>e instanceof HTMLElement)||null;return Gs(t)?t:Gs(e.target)?e.target:null})(e)&&(e.stopPropagation(),e.stopImmediatePropagation());};return n.forEach(t=>{e.addEventListener(t,o,r);}),()=>{n.forEach(t=>{e.removeEventListener(t,o,r);});}},Ys={isValidContext:e=>null!==e&&Object.values(Ds).includes(e.nodeType),isVisible:e=>e&&null!==e.offsetParent,isConnected:e=>e&&e.isConnected,createCleanupManager(){const e=new Set;return {add:t=>(e.add(t),()=>e.delete(t)),execute(){e.forEach(e=>{try{e();}catch(t){console.error("[DOMToolkit] Cleanup error:",t);}}),e.clear();},get size(){return e.size}}}};class Zs{enabled=true;ttl;store=new WeakMap;timestamps=new WeakMap;constructor(e=Os.CACHE_TTL){this.ttl=e;}setEnabled(e){this.enabled=e;}get(e,t){if(!this.enabled)return null;const n=this.store.get(e),r=this.timestamps.get(e);if(!n||!r)return null;const o=n.get(t);if(!o)return null;const a=r.get(t);return a&&Date.now()-a>this.ttl?(n.delete(t),r.delete(t),null):Ys.isConnected(o)?o:(n.delete(t),r.delete(t),null)}set(e,t,n){if(!this.enabled||!n)return;let r=this.store.get(e),o=this.timestamps.get(e);r||(r=new Map,this.store.set(e,r)),o||(o=new Map,this.timestamps.set(e,o)),r.set(t,n),o.set(t,Date.now());}clear(){this.store=new WeakMap,this.timestamps=new WeakMap;}}class Xs{observers=new Map;getSharedObserver(e){if(!this.observers.has(e)){const t=new Set,n=new MutationObserver(e=>{for(const n of e)for(const e of n.addedNodes)e.nodeType===Ds.ELEMENT&&t.forEach(t=>{try{t(e,n);}catch(r){console.error("[DOMToolkit] Observer callback error:",r);}});});n.observe(e,{childList:true,subtree:true}),this.observers.set(e,{observer:n,callbacks:t,refCount:0});}const t=this.observers.get(e);return t.refCount++,{addCallback:e=>t.callbacks.add(e),removeCallback:n=>{t.callbacks.delete(n),t.refCount--,0===t.refCount&&(t.observer.disconnect(),this.observers.delete(e));}}}destroy(){this.observers.forEach(({observer:e})=>e.disconnect()),this.observers.clear();}}const Js=new class{cache;observerManager;doc;constructor(){this.doc=document,this.cache=new Zs,this.observerManager=new Xs;}configCache(e={}){"boolean"==typeof e.enabled&&this.cache.setEnabled(e.enabled);}clearCache(){this.cache.clear();}getComposedParent(e){if(!e)return null;if(e instanceof ShadowRoot)return e.host;if(e instanceof Element&&e.assignedSlot)return e.assignedSlot;if(e.parentNode)return e.parentNode;const t=e.getRootNode?.();return t instanceof ShadowRoot?t.host:null}getComposedParentElement(e){let t=this.getComposedParent(e);for(;t;){if(t instanceof HTMLElement)return t;t=this.getComposedParent(t);}return null}closestComposed(e,t){let n=e;for(;n;){if(n instanceof HTMLElement)try{if(n.matches(t))return n}catch{return null}n=this.getComposedParent(n);}return null}query(e,t={}){const{parent:n=this.doc,all:r=false,shadow:o=true,maxDepth:a=Os.MAX_DEPTH,useCache:i=true,filter:s=null}=t,l=Array.isArray(e)?e:[e],c=i&&!s;if(!r&&c&&1===l.length){const e=this.cache.get(n,l[0]);if(e)return e}for(const d of l)try{if(r){const e=Array.from(n.querySelectorAll(d)),t=s?e.filter(s):[...e];if(o&&this.collectInShadow(n,d,t,0,a,s),t.length>0)return t}else {const e=n.querySelectorAll(d);for(const t of e)if(!s||s(t))return c&&this.cache.set(n,d,t),t}}catch{}if(o&&!r){const e=this.findInShadow(n,l,0,a,s);return e&&c&&1===l.length&&this.cache.set(n,l[0],e),e}return r?[]:null}findInShadow(e,t,n,r,o){if(n>r)return null;if(e!==this.doc&&e.querySelectorAll)for(const i of t)try{const t=e.querySelectorAll(i);for(const e of t)if(!o||o(e))return e}catch{}const a=e.querySelectorAll?e.querySelectorAll("*"):[];for(const i of a)if(i.shadowRoot){const e=this.findInShadow(i.shadowRoot,t,n+1,r,o);if(e)return e}return null}collectInShadow(e,t,n,r,o,a){if(r>o)return;if(e!==this.doc&&e.querySelectorAll)try{const r=e.querySelectorAll(t);for(const e of r)n.includes(e)||a&&!a(e)||n.push(e);}catch{}const i=e.querySelectorAll?e.querySelectorAll("*"):[];for(const s of i)s.shadowRoot&&this.collectInShadow(s.shadowRoot,t,n,r+1,o,a);}async get(e,t={}){const{parent:n=this.doc,timeout:r=Os.DEFAULT_TIMEOUT,shadow:o=true,filter:a=null}=t,i=this.query(e,{parent:n,shadow:o,filter:a});return i&&!Array.isArray(i)?i:new Promise(t=>{const i=Ys.createCleanupManager(),s=Date.now();let l;r>0&&(l=setTimeout(()=>{i.execute(),t(null);},r),i.add(()=>clearTimeout(l)));const c=()=>{if(r>0&&Date.now()-s>=r)return;const l=this.query(e,{parent:n,shadow:o,filter:a});if(l&&!Array.isArray(l))return i.execute(),void t(l);const d=setTimeout(c,Os.POLL_INTERVAL);i.add(()=>clearTimeout(d));},d=Array.isArray(e)?e:[e],h=this.observerManager.getSharedObserver(n),u=e=>{for(const n of d)try{if(e.matches?.(n)&&(!a||a(e)))return i.execute(),void t(e);if(e.querySelectorAll){const r=e.querySelectorAll(n);for(const e of r)if(!a||a(e))return i.execute(),void t(e)}}catch{}};h.addCallback(u),i.add(()=>h.removeCallback(u)),c();})}each(e,t,n={}){const{parent:r=this.doc,shadow:o=true}=n;if("function"!=typeof t)return console.error("[DOMToolkit] each: callback must be a function"),()=>{};const a=new WeakSet;let i=true;const s=(e,n)=>{if(i&&!a.has(e)){a.add(e);try{!1===t(e,n)&&d();}catch(r){console.error("[DOMToolkit] each callback error:",r),d();}}};this.query(e,{parent:r,all:true,shadow:o}).forEach(e=>s(e,false));const l=this.observerManager.getSharedObserver(r),c=t=>{if(i)try{t.matches?.(e)&&s(t,!0),t.querySelectorAll&&t.querySelectorAll(e).forEach(e=>s(e,!0));}catch{}};l.addCallback(c);const d=()=>{i&&(i=false,l.removeCallback(c));};return d}watch(e,t,n={}){const{debounce:r=0,childList:o=true,attributes:a=true,characterData:i=false,subtree:s=false,attributeFilter:l}=n;if(!Ys.isValidContext(e))return console.error("[DOMToolkit] watch: invalid element"),()=>{};let c=null;const d=new MutationObserver((e,n)=>{if(r>0)c&&clearTimeout(c),c=setTimeout(()=>{try{t(e,n);}catch(r){console.error("[DOMToolkit] watch callback error:",r);}},r);else try{t(e,n);}catch(o){console.error("[DOMToolkit] watch callback error:",o);}});return d.observe(e,{childList:o,attributes:a,characterData:i,subtree:s,attributeFilter:l}),()=>{c&&clearTimeout(c),d.disconnect();}}watchMultiple(e,t={}){const{debounce:n=0,characterData:r=true,childList:o=true,attributes:a=false}=t;if(!Ys.isValidContext(e))return console.error("[DOMToolkit] watchMultiple: invalid container"),{add:()=>{},remove:()=>{},stop:()=>{}};const i=new Map;let s=null;const l=new Set,c=()=>{l.forEach(e=>{const t=i.get(e);if(t)try{t(e);}catch(n){console.error("[DOMToolkit] watchMultiple callback error:",n);}}),l.clear();},d=new MutationObserver(t=>{for(const n of t){let t=n.target;for(;t&&t!==e;){if(i.has(t)){l.add(t);break}t=t.parentNode;}}0!==l.size&&(n>0?(s&&clearTimeout(s),s=setTimeout(c,n)):c());});return d.observe(e,{characterData:r,childList:o,attributes:a,subtree:true}),{add:(e,t)=>i.set(e,t),remove:e=>i.delete(e),stop:()=>{s&&clearTimeout(s),d.disconnect(),i.clear();}}}on(e,t,n,r={}){const{parent:o=this.doc,capture:a=false}=r,i=e=>{const r=e.composedPath?e.composedPath():[e.target];for(const a of r){if(a===o||a===window)break;try{if(a.matches?.(t))return void n(e,a)}catch{}}try{const r=e.target.closest?.(t);r&&o.contains(r)&&n(e,r);}catch{}};return o.addEventListener(e,i,a),()=>o.removeEventListener(e,i,a)}create(e,t={},n=""){const r=this.doc.createElement(e);for(const[o,a]of Object.entries(t))"className"===o?r.className=a:"style"===o&&"object"==typeof a?Object.assign(r.style,a):"style"===o?r.setAttribute("style",a):"dataset"===o&&"object"==typeof a?Object.assign(r.dataset,a):o.startsWith("on")&&"function"==typeof a?r.addEventListener(o.slice(2).toLowerCase(),a):r.setAttribute(o,a);return n&&(r.textContent=n),r}createFromHTML(e,t={}){const{parent:n=null,mapIds:r=false}=t,o=this.doc.createElement("template");o.innerHTML=e.trim();const a=o.content.firstElementChild;if(!a)return null;if(n instanceof Element&&n.appendChild(a),r){const e={root:a};return a.id&&(e[a.id]=a),a.querySelectorAll("[id]").forEach(t=>{t.id&&(e[t.id]=t);}),e}return a}clear(e){for(;e.firstChild;)e.removeChild(e.firstChild);}css(e,t=null){if(t){const n=this.doc.getElementById(t);if(n)return n.textContent!==e&&(n.textContent=e),n}const n=this.doc.createElement("style");return t&&(n.id=t),n.textContent=e,this.doc.head.appendChild(n),n}cssToShadow(e,t,n=null){if(!e)return null;try{if(n){const r=e.getElementById(n);if(r)return r.textContent!==t&&(r.textContent=t),r}const r=this.doc.createElement("style");return n&&(r.id=n),r.textContent=t,e.appendChild(r),r}catch{return null}}cssToAllShadows(e,t,n={}){const{root:r=this.doc.body,filter:o=null}=n;if(!r)return 0;let a=0;const i=n=>{if(n.shadowRoot){if(o&&!o(n));else try{this.cssToShadow(n.shadowRoot,e,t),a++;}catch{}try{i(n.shadowRoot);}catch{}}const r=n.childNodes;for(let e=0;e{if(n>r)return;if(t.shadowRoot){try{e(t.shadowRoot,t);}catch(i){console.error("[DOMToolkit] walkShadowRoots callback error:",i);}try{o(t.shadowRoot,n+1);}catch{}}const a=t.childNodes;for(let e=0;ee.clientHeight)return e}const o=(e,t)=>{if(t>Os.MAX_DEPTH)return null;const n=e.querySelectorAll?e.querySelectorAll("*"):[];for(const a of n){if(a.scrollHeight>a.clientHeight+r){const e=window.getComputedStyle(a);if("auto"===e.overflowY||"scroll"===e.overflowY||"auto"===e.overflow||"scroll"===e.overflow)return a}if(a.shadowRoot){const e=o(a.shadowRoot,t+1);if(e)return e}}return null},a=o(t,0);return a||(this.doc.documentElement.scrollHeight>this.doc.documentElement.clientHeight?this.doc.documentElement:this.doc.body)}destroy(){this.observerManager.destroy(),this.cache.clear();}},el="https://cdn.jsdelivr.net/npm/katex@0.16.44/dist/fonts",tl=e=>e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),nl=()=>{const e=globalThis.katex;return e&&"function"==typeof e.renderToString?e:null},rl=()=>{try{const e=GM_getResourceText("ophelKatexCss");return e?(e=>e.replace(/url\((['"]?)(?!data:|https?:|\/)([^)'"]+)\1\)/g,(e,t,n)=>{const r=String(n).replace(/^\.?\//,"");return `url(${t}${r.startsWith("fonts/")?`${el}/${r.slice(6)}`:`${el}/${r}`}${t})`}))(e):""}catch(e){return console.warn("[Ophel] Failed to load KaTeX CSS resource:",e),""}},ol=(e,t,n)=>{const r=n?"div":"span";return `<${r} class="${n?"math-block gh-rendered-math":"math-inline gh-rendered-math"}" data-math="${tl(e)}">${t}`},al={type:"userscript",storage:Vi,math:{renderKatexToString:(e,{displayMode:t})=>{const n=e.replace(/\r\n?/g,"\n").trim(),r=nl();if(!r){return ol(n,`${tl(t?`$$\n${n}\n$$`:`$${n}$`)}`,t)}try{const e=r.renderToString(n,{displayMode:t,output:"htmlAndMathml",throwOnError:!1,strict:"ignore",trust:!1});return ol(n,e,t)}catch{return ol(n,`${tl(t?`$$\n${n}\n$$`:`$${n}$`)}`,t)}},renderKatexToMathML:(e,{displayMode:t})=>{const n=e.replace(/\r\n?/g,"\n").trim(),r=nl();if(!r)return ol(n,`${tl(n)}`,t);try{const e=r.renderToString(n,{displayMode:t,output:"mathml",throwOnError:!1,strict:"ignore",trust:!1});return ol(n,e,t)}catch{return ol(n,`${tl(n)}`,t)}},getKatexStylesText:async()=>rl()},remoteConfig:{async getState(){const{getUserscriptRemoteConfigState:e}=await o(async()=>{const{getUserscriptRemoteConfigState:e}=await Promise.resolve().then(()=>Yi);return {getUserscriptRemoteConfigState:e}},void 0);return e()},async checkForUpdates(e){const{checkUserscriptRemoteConfigNow:t}=await o(async()=>{const{checkUserscriptRemoteConfigNow:e}=await Promise.resolve().then(()=>Yi);return {checkUserscriptRemoteConfigNow:e}},void 0);return t(e?.sources)},async resetSite(e,t){const{resetUserscriptRemotePatch:n}=await o(async()=>{const{resetUserscriptRemotePatch:e}=await Promise.resolve().then(()=>Yi);return {resetUserscriptRemotePatch:e}},void 0);return n(e,t)},async installLocalPatch(e,t){const{installUserscriptLocalRemotePatch:n}=await o(async()=>{const{installUserscriptLocalRemotePatch:e}=await Promise.resolve().then(()=>Yi);return {installUserscriptLocalRemotePatch:e}},void 0);return n(e,t)},async removeLocalPatch(e){const{removeUserscriptLocalRemotePatch:t}=await o(async()=>{const{removeUserscriptLocalRemotePatch:e}=await Promise.resolve().then(()=>Yi);return {removeUserscriptLocalRemotePatch:e}},void 0);return t(e)},async clearCache(){const{clearUserscriptRemoteConfigCache:e}=await o(async()=>{const{clearUserscriptRemoteConfigCache:e}=await Promise.resolve().then(()=>Yi);return {clearUserscriptRemoteConfigCache:e}},void 0);return e()}},sitePacks:{ensureOrigins:async()=>"unsupported",ensureBindingOrigin:async()=>"unsupported",reconcile:async()=>({activeOrigins:[],missingPermissionOrigins:[],originReferences:[],bindingIssues:[]})},fetch:async(e,t)=>new Promise((n,r)=>{GM_xmlhttpRequest({url:e,method:t?.method||"GET",headers:t?.headers,data:t?.body,responseType:"text",onload(r){const o=r.status>=200&&r.status<300;n({ok:o,status:r.status,statusText:r.statusText,text:async()=>r.responseText,json:async()=>JSON.parse(r.responseText),blob:async()=>new Promise((n,r)=>{GM_xmlhttpRequest({url:e,method:t?.method||"GET",headers:t?.headers,responseType:"blob",onload(e){n(e.response);},onerror:r});})});},onerror(e){r(e);}});}),notify(e){GM_notification({title:e.title,text:e.message,timeout:e.timeout??5e3,silent:e.silent??true,onclick:()=>{window.focus();}});},getNotificationSoundUrl:e=>window.__OPHEL_NOTIFICATION_SOUND_URLS__?.[e],focusWindow(){window.focus();},openTab(e){window.open(e,"_blank");},hasCapability:e=>!["cookies","permissions","tabs","declarativeNetRequest","commands"].includes(e),async getClaudeSessionKey(){if(!location.hostname.endsWith("claude.ai"))return {success:false,error:ae("claudeNotOnSiteHint")};const e=document.cookie.match(/sessionKey=([^;]+)/);return e&&e[1]?{success:true,sessionKey:decodeURIComponent(e[1])}:{success:false,error:ae("claudeNoCookieFound")}},testClaudeSessionKey:async e=>new Promise(t=>{GM_xmlhttpRequest({url:"https://claude.ai/api/organizations",method:"GET",headers:{Accept:"application/json",Cookie:`sessionKey=${e}`},onload(e){try{if(200!==e.status)return void t({success:!0,isValid:!1,error:`HTTP ${e.status}`});const n=e.responseText;if(n.toLowerCase().includes("unauthorized"))return void t({success:!0,isValid:!1,error:"Unauthorized"});const r=JSON.parse(n);if(!Array.isArray(r)||0===r.length)return void t({success:!0,isValid:!1,error:"No organizations"});const o=r[0],a=o?.rate_limit_tier,i=o?.capabilities||[],s=o?.api_disabled_reason;let l="Unknown";"default_claude_max_5x"===a?l="Max(5x)":"default_claude_max_20x"===a?l="Max(20x)":"default_claude_ai"===a?l="Free":"auto_api_evaluation"===a?l="out_of_credits"===s?"API(无额度)":"API":i.includes("claude_max")?l="Max":i.includes("api")?l="API":i.includes("chat")&&(l="Free"),t({success:!0,isValid:!0,accountType:l});}catch{t({success:true,isValid:false,error:"Parse error"});}},onerror(){t({success:false,isValid:false,error:"Request failed"});}});}),async setClaudeSessionKey(e){if(!location.hostname.endsWith("claude.ai"))return {success:false,error:ae("claudeNotOnSiteHint")};const t=new Date(Date.now()+31536e6).toUTCString();return document.cookie=`sessionKey=${encodeURIComponent(e)}; domain=.claude.ai; path=/; expires=${t}; secure; samesite=lax`,location.href="https://claude.ai/",{success:true}},async switchNextClaudeKey(){if(!location.hostname.endsWith("claude.ai"))return {success:false,error:ae("claudeNotOnSiteHint")};try{const e=GM_getValue("claudeSessionKeys"),t=e?.state?.keys||[];if(0===t.length)return {success:!1,error:"noClaudeKeys"};const n=e?.state?.currentKeyId;let r=t.filter(e=>!1!==e.isValid);0===r.length&&(r=[...t]),r.sort((e,t)=>{const n=e.accountType?.toLowerCase()?.includes("pro"),r=t.accountType?.toLowerCase()?.includes("pro");return n&&!r?-1:!n&&r?1:e.name.localeCompare(t.name)});const o=r.findIndex(e=>e.id===n);if(1===r.length&&-1!==o)return {success:!1,error:"claudeOnlyOneKey"};let a=0;-1!==o&&(a=(o+1)%r.length);const i=r[a];if(!i)return {success:!1,error:"nextKeyNotFound"};if(i.key){const e=new Date(Date.now()+31536e6).toUTCString();document.cookie=`sessionKey=${encodeURIComponent(i.key)}; domain=.claude.ai; path=/; expires=${e}; secure; samesite=lax`;}return e?.state&&(e.state.currentKeyId=i.id,GM_setValue("claudeSessionKeys",e)),location.href="https://claude.ai/",{success:!0,keyName:i.name}}catch(e){return {success:false,error:e.message}}}},il=Object.freeze(Object.defineProperty({__proto__:null,getPlatformType:To,isUserscriptPlatform:Eo,platform:al},Symbol.toStringTag,{value:"Module"}));function sl(){const e=globalThis.__OphelMarkdownVendor;if(!e||"function"!=typeof e.renderMarkdown)throw new Error("[Ophel] Markdown vendor runtime is missing");return e}const ll=(e,t=true,n={})=>sl().renderMarkdown(e,t,n),cl=()=>"undefined"==typeof window?"":window.__OPHEL_MARKDOWN_PREVIEW_STYLES__||"",dl=new Map;function hl(e,t=2e3,n={}){let r=document.body,o=null;const a=document.querySelectorAll("plasmo-csui, #ophel-userscript-root");for(const h of a)if(h.shadowRoot){const e=h.shadowRoot.querySelector(".gh-root, #plasmo-shadow-container, .plasmo-csui-container, #ophel-app-container");if(e){r=e,o=h;break}r=h.shadowRoot,o=h;}const i=r.getRootNode(),s=i instanceof ShadowRoot?i:document.head,l=document.getElementById("gh-toast");l&&l.remove();for(const h of a)if(h.shadowRoot){const e=h.shadowRoot.querySelector("#gh-toast");e&&e.remove();}if(!s.querySelector("#gh-toast-style")){const e=document.createElement("style");e.id="gh-toast-style",e.textContent=`\n${nt}\n .gh-toast {\n position: fixed !important;\n left: 50% !important;\n background: color-mix(in srgb, var(--gh-bg, #ffffff) 90%, transparent) !important;\n color: var(--gh-text, #1f2937) !important;\n border: 1px solid color-mix(in srgb, var(--gh-primary, #6366f1) 20%, var(--gh-border, #d1d5db)) !important;\n padding: 10px 22px !important;\n border-radius: 9999px !important;\n font-size: 14px !important;\n font-weight: 600 !important;\n box-shadow:\n var(--gh-shadow-lg, 0 8px 32px rgba(0, 0, 0, 0.35)),\n 0 0 0 1px inset color-mix(in srgb, var(--gh-primary, #6366f1) 15%, transparent) !important;\n z-index: 2147483646 !important; /* 刚好在一级最高层(禅模式按钮 2147483647)之下 */\n pointer-events: none !important;\n opacity: 0 !important;\n transform: translateY(-20px) translateX(-50%) scale(0.92) !important;\n transition: opacity 0.3s cubic-bezier(0.16, 1, 0.3, 1), transform 0.3s cubic-bezier(0.16, 1, 0.3, 1) !important;\n font-family: ${st()} !important;\n letter-spacing: 0.2px !important;\n backdrop-filter: blur(16px) saturate(160%) !important;\n -webkit-backdrop-filter: blur(16px) saturate(160%) !important;\n max-width: min(calc(100vw - 32px), 480px);\n white-space: nowrap !important;\n overflow: hidden !important;\n text-overflow: ellipsis !important;\n }\n .gh-toast.show {\n opacity: 1 !important;\n transform: translateY(0) translateX(-50%) scale(1) !important;\n }\n .gh-toast--outline-nav {\n max-width: 360px !important;\n }\n @media (prefers-reduced-motion: reduce) {\n .gh-toast {\n transition: opacity 0.2s ease !important;\n transform: translateX(-50%) !important;\n }\n .gh-toast.show {\n transform: translateX(-50%) !important;\n }\n }\n `,s.appendChild(e);}const c=document.createElement("div");c.id="gh-toast",c.className="gh-toast";const d=!(!document.getElementById("gh-zen-mode-exit-host")&&!o?.shadowRoot?.querySelector("#gh-zen-mode-exit-host"));c.style.setProperty("top",d?"84px":"32px","important"),n.className&&c.classList.add(n.className),n.maxWidth&&Number.isFinite(n.maxWidth)&&(c.style.maxWidth=`${n.maxWidth}px`),c.textContent=e,r.appendChild(c),requestAnimationFrame(()=>{c.classList.add("show");}),setTimeout(()=>{c.classList.remove("show"),setTimeout(()=>{c.parentNode&&c.parentNode.removeChild(c);},300);},t);}function ul(e,t=2e3,n={},r=1500,o=e){const a=Date.now();a-(dl.get(o)||0)e.replace(/\r\n?/g,"\n"),n=e=>{const t=e?.split(/\r?\n/)[0]?.trim().toLowerCase()||"";return !t||/^(copy|复制)$/.test(t)?"":t.replace(/\s+/g,"")},r=e=>{const n=t(e).replace(/\s*\n\s*/g," ").trim();return n?`$${n}$`:""},o=e=>{const n=t(e).trim();if(!n)return "";return n.includes("\n")||/(^|[^\\])\\\\($|[^\\])/.test(n)?`\n$$\n${n}\n$$\n`:`\n$$${n}$$\n`},a=e=>{const t=e.querySelector('annotation[encoding="application/x-tex"]'),n=t?.textContent?.trim();if(n)return n;const r=e.getAttribute("data-tex")||e.getAttribute("data-latex");if(r)return r.trim();const o=e.getAttribute("aria-label");return o?o.trim():""},i=e=>{if(!e)return "";if(e.nodeType===Node.TEXT_NODE)return e.textContent||"";if(e.nodeType!==Node.ELEMENT_NODE)return "";const t=e,n=t.tagName?.toLowerCase()||"";return "br"===n?"\n":"style"===n||"script"===n||"template"===n||"noscript"===n||"button"===n||"svg"===n||"annotation"===n||"annotation-xml"===n||t.classList?.contains("gh-assistant-mermaid")||t.classList?.contains("katex-mathml")||t.classList?.contains("katex-html")?"":Array.from(t.childNodes).map(i).join("")},s=e=>{const t=e.querySelector("code"),r=t?.className.match(/language-([A-Za-z0-9_#+-]+)/),o=!!e.querySelector("#code-block-viewer, .cm-editor"),a=[e.getAttribute("data-language"),e.querySelector(".cm-content")?.getAttribute("data-language"),r?.[1],e.querySelector(".code-block-decoration span")?.textContent,o?e.querySelector('.sticky [class*="font-medium"]')?.textContent:null];for(const i of a){const e=n(i);if(e)return e}return ""},l=e=>{const n=!!e.querySelector("#code-block-viewer, .cm-editor"),r=e.matches(".cm-content")?e:e.querySelector(".cm-content")??null;if(r){const n=t(i(r)).replace(/\n+$/,"");if(n.trim())return {lang:s(e),code:n}}const o=e.matches("code")?e:e.querySelector("pre code, code")??null;if(o){const n=t(i(o)).replace(/\n+$/,"");if(n.trim())return {lang:s(e),code:n}}if(!n){const n=t(i(e)).replace(/\n+$/,"");if(n.trim())return {lang:s(e),code:n}}return null},c=(e,t)=>Array.from(e.childNodes).map(e=>u(e,t)).join(""),d=(e,t)=>{const n="ol"===e.tagName.toLowerCase(),r=Array.from(e.children).filter(e=>"li"===e.tagName?.toLowerCase()).map((e,r)=>h(e,t,n?r+1:null)).filter(Boolean).join("\n");return r?`\n${r}\n\n`:""},h=(e,n,r)=>{const o=" ".repeat(n),a=null===r?"-":`${r}.`,i=[],s=[];for(const t of Array.from(e.childNodes)){if(t.nodeType===Node.ELEMENT_NODE){const e=t,r=e.tagName.toLowerCase();if("ul"===r||"ol"===r){const t=d(e,n+1).replace(/^\n+|\n+$/g,"");t&&s.push(t);continue}}i.push(u(t,{listDepth:n,inListItem:true}));}const l=(c=i.join(""),t(c).replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").trim());var c;let h=l?((e,n,r)=>{const o=t(e).split("\n"),[a="",...i]=o;return 0===i.length?`${n}${a}`:[`${n}${a}`,...i.map(e=>e?`${r}${e}`:"")].join("\n")})(l,`${o}${a} `,`${o} `):`${o}${a}`;return s.length>0&&(h=`${h.trimEnd()}\n${s.join("\n")}`),h},u=(e,t={listDepth:0,inListItem:false})=>{try{if(!e)return "";if(e.nodeType===Node.TEXT_NODE)return e.textContent||"";if(e.nodeType!==Node.ELEMENT_NODE)return "";const n=e;if(n.classList?.contains("gh-assistant-mermaid"))return "";if(n.classList?.contains("math-block")){const e=n.getAttribute("data-math");if(e)return o(e)}if(n.classList?.contains("math-inline")){const e=n.getAttribute("data-math");if(e)return r(e)}if(n.classList?.contains("katex-display")){const e=a(n);if(e)return o(e)}if(n.classList?.contains("katex")){const e=a(n);if(e)return r(e)}if(n.classList?.contains("katex-mathml"))return "";if(n.classList?.contains("katex-html"))return "";if("BUTTON"===n.tagName||"SVG"===n.tagName)return "";if(n.classList?.contains("cm-content")&&n.getAttribute("data-language")){const e=l(n);if(e)return `\n\`\`\`${e.lang}\n${e.code}\n\`\`\`\n`}if(n.classList?.contains("cm-cursorLayer")||n.classList?.contains("cm-selectionLayer")||n.classList?.contains("cm-announced"))return "";const i=n.tagName?.toLowerCase()||"";if(!i)return "";if("annotation"===i||"annotation-xml"===i)return "";if("style"===i||"script"===i||"template"===i||"noscript"===i)return "";if("img"===i){const e=n.alt||n.getAttribute("alt")||"图片";return `![${e}](${n.getAttribute("src")||n.src||""})`}if("code-block"===i){const e=l(n);if(e)return `\n\`\`\`${e.lang}\n${e.code}\n\`\`\`\n`}if("pre"===i){const e=l(n);if(e)return `\n\`\`\`${e.lang}\n${e.code}\n\`\`\`\n`}if("code"===i)return "pre"===n.parentElement?.tagName.toLowerCase()?"":`\`${n.textContent}\``;if("table"===i){const e=[],t=n.querySelector("thead"),r=n.querySelector("tbody"),o=e=>e.textContent?.trim()||"";if(t){const n=t.querySelector("tr");if(n){const t=Array.from(n.querySelectorAll("td, th")).map(o);t.some(e=>e)&&(e.push("| "+t.join(" | ")+" |"),e.push("| "+t.map(()=>"---").join(" | ")+" |"));}}if(r){r.querySelectorAll("tr").forEach(t=>{const n=Array.from(t.querySelectorAll("td, th")).map(o);n.some(e=>e)&&e.push("| "+n.join(" | ")+" |");});}if(!t&&!r){const t=n.querySelectorAll("tr");let r=!0;t.forEach(t=>{const n=Array.from(t.querySelectorAll("td, th")).map(o);n.some(e=>e)&&(e.push("| "+n.join(" | ")+" |"),r&&(e.push("| "+n.map(()=>"---").join(" | ")+" |"),r=!1));});}return e.length>0?"\n"+e.join("\n")+"\n":""}if("table-block"===i||"ucs-markdown-table"===i){const e=n.querySelector("table");if(e)return u(e)}switch(i){case "h1":return `\n# ${c(n,t)}\n`;case "h2":return `\n## ${c(n,t)}\n`;case "h3":return `\n### ${c(n,t)}\n`;case "h4":return `\n#### ${c(n,t)}\n`;case "h5":return `\n##### ${c(n,t)}\n`;case "h6":return `\n###### ${c(n,t)}\n`;case "strong":case "b":return `**${c(n,t)}**`;case "em":case "i":return `*${c(n,t)}*`;case "a":return `[${c(n,t)}](${n.getAttribute("data-ophel-export-markdown-href")||n.href||""})`;case "li":return h(n,t.listDepth,"ol"===n.parentElement?.tagName?.toLowerCase()?Array.from(n.parentElement.children).filter(e=>"li"===e.tagName?.toLowerCase()).indexOf(n)+1:null);case "p":return t.inListItem?`${c(n,t).trim()}\n`:`${c(n,t)}\n\n`;case "br":return "\n";case "ul":case "ol":return d(n,t.listDepth);case "blockquote":{const e=c(n,t).replace(/\r\n/g,"\n").split("\n");return `\n${e.map(e=>e.trim().length>0?`> ${e}`:">").join("\n")}\n`}default:return n.shadowRoot?Array.from(n.shadowRoot.childNodes).map(e=>u(e,t)).join(""):c(n,t)}}catch(n){return console.error("Error processing node in htmlToMarkdown:",n),e.textContent||""}};return u(e).trim()}const vl=/^\s*(?:\[(?:Thoughts?|思维链|思考过程)\]|\*{0,2}💭\s*思考过程\*{0,2})\s*$/i,yl=/^\s*(`{3,}|~{3,})/;function wl(e){for(let t=0;t\s?/,"").trim();if(n)return vl.test(n)?t:-1}return -1}function xl(e){if(!e||!e.includes(">"))return e;const t=e.replace(/\r\n?/g,"\n").split("\n"),n=function(e){const t=[];let n="",r=0;for(const o of e){t.push(r>0);const e=o.match(yl);if(!e)continue;const a=e[1];0===r?(n=a[0],r=a.length):a[0]===n&&a.length>=r&&(n="",r=0);}return t}(t),r=[];let o=0;for(;o")){r.push(t[o]),o+=1;continue}const e=[];for(;o");)e.push(t[o]),o+=1;const a=wl(e);if(0!==a){r.push(...e);continue}const i=[...e];i[a]="> [Thoughts]";const s=[...i];for(;;){let e=o;for(;e=t.length||n[e]||!t[e].startsWith(">"))break;const r=[];let a=e;for(;a");)r.push(t[a]),a+=1;const i=wl(r);if(i<0)break;s.push(">"),s.push(...r.slice(i+1)),o=a;}r.push(...s);}return r.join("\n")}function kl(e){const t=e.trim();if(!t||!t.startsWith(">"))return false;const n=t.split("\n");return -1!==wl(n)&&n.every(e=>!e.trim()||e.trimStart().startsWith(">"))}function Sl(e){if(!Array.isArray(e)||0===e.length)return [];const t=[];let n=0;for(;n{if("user"===t.role){a+=1;const r=e.customUserName||ae("exportUserLabel"),i=e.showIndex?`${a}. `:"";n.push(`## ${i}${ml} ${r}`),n.push(""),n.push(t.content),n.push(""),o&&(n.push(o),n.push(""));}else {const r=e.customModelName||e.source,i=e.showIndex&&a>0?`${a}. `:"";n.push(`## ${i}${fl} ${r}`),n.push(""),n.push(t.content),n.push(""),o&&(n.push(o),n.push(""));}}),n.join("\n")}const Tl=e=>e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),El=(e,t)=>al.math.renderKatexToMathML(e,{displayMode:t});let Ml=null;const Il=()=>(Ml||(Ml=((e=false,t=false,n)=>{const r=sl();if("function"!=typeof r.createMarkdownIt)throw new Error("[Ophel] Markdown vendor createMarkdownIt is missing");return r.createMarkdownIt(e,t,n)})(true,false,El)),Ml),Nl='',Al=/^(
\s*

\s*)(?:(?:\s*)?\[(?:Thoughts?|思维链|思考过程)\](?:\s*<\/strong>)?|(?:\s*)?💭\s*思考过程(?:\s*<\/strong>)?)\s*(?:\s*)?/i,Pl=e=>Al.test(e),Ll=e=>{const t=e.map(e=>e.replace(Al,"$1").replace(/^

\s*

\s*<\/p>\s*/i,"

")).join("\n");return `
\n ${ae("exportThoughtCollapsedLabel")}\n
${t}
\n
`};function Rl(e,t,n){const r="user"===e.role,o="assistant"===e.role;let a=r?t.customUserName||ae("exportUserLabel"):o?t.customModelName||t.source:e.role;t.showIndex&&n&&(a=`${n}. ${a}`);const i=r?'':'';return `
\n
\n \n ${Tl(a)}\n
\n
${function(e){let t=Il().render(xl(e));t=t.replace(/\{\{([^\s{}]+)\}\}/g,'{{$1}}');const n=(e=>{const t=[];let n=0,r=-1,o=0;for(;o",o);if(-1===a&&-1===i)break;-1===i||-1!==a&&a0&&/^\s*$/.test(e);Pl(l)||n?(0===a.length&&(r+=e),a.push(l)):(a.length>0&&(r+=Ll(a),a=[]),r+=e+l),o=s;}return a.length>0&&(r+=Ll(a)),r+=t.slice(o),t=r,t=t.replace(/
`
${Tl(t)}
]*class=)/g,`
/g,"
"),t}(e.content)}
\n
`}function $l(e,t){const n=se()||"en",r=Tl(e.title),o=Tl(e.exportTime),a=Tl(e.source),i=Sl(t);let s=0;const l=i.map(t=>("user"===t.role&&(s+=1),Rl(t,e,s>0?s:void 0))).join("\n");return `\n\n\n\n\n${r}\n\n