// ==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: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.0.30 // @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: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 https://gemini.google.com/* // @match https://business.gemini.google/* // @match https://aistudio.google.com/* // @match https://grok.com/* // @match https://chat.openai.com/* // @match https://chatgpt.com/* // @match https://claude.ai/* // @match https://www.doubao.com/* // @match https://ima.qq.com/* // @match https://chat.deepseek.com/* // @match https://www.kimi.com/* // @match https://chatglm.cn/* // @match https://chat.qwen.ai/* // @match https://www.qianwen.com/* // @match https://yuanbao.tencent.com/* // @match https://chat.z.ai/* // @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 // @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@userscript-assets/userscript-assets/ophel-icon.193ed41c2441.png // @resource ophelKatexCss https://cdn.jsdelivr.net/npm/katex@0.16.44/dist/katex.min.css // @resource ophelLocaleDe https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.de.929b0a6d06ea.json // @resource ophelLocaleEn https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.en.49ff0c1af66e.json // @resource ophelLocaleEs https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.es.1d51cb2afeea.json // @resource ophelLocaleFr https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.fr.7e5e932fa421.json // @resource ophelLocaleJa https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.ja.cc40edab6bc3.json // @resource ophelLocaleKo https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.ko.fdb003e59090.json // @resource ophelLocalePt https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.pt.a745ddea9e3f.json // @resource ophelLocaleRu https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.ru.3c3767bb6aee.json // @resource ophelLocaleZhCN https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.zh-CN.82c5fbfdef1d.json // @resource ophelLocaleZhTW https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.zh-TW.9be1467e4378.json // @resource ophelNotificationBrightAlert https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel-sound-bright-alert.568967a3d9f8.ogg // @resource ophelNotificationDefault https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel-sound-default.15d3cda1ee80.mp3 // @resource ophelNotificationGlassPing https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel-sound-glass-ping.2379b58f953e.ogg // @resource ophelNotificationSoftChime https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel-sound-soft-chime.063564703b60.ogg // @resource ophelStyles https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.user.c97a8c847e4d.css // @resource ophelWatermarkBg48 https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel-watermark-bg-48.4afc99afe0ef.png // @resource ophelWatermarkBg96 https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel-watermark-bg-96.3e26f2233a12.png // @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-idle // @noframes // @downloadURL none // ==/UserScript== (function () { '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 t=function(){const e="undefined"!=typeof document&&document.createElement("link").relList;return e&&e.supports&&e.supports("modulepreload")?"modulepreload":"preload"}(),n={},r=function(e,r,o){let i=Promise.resolve();if(r&&r.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]"),a=o?.nonce||o?.getAttribute("nonce");i=e(r.map(e=>{if((e=function(e){return "/"+e}(e))in n)return;n[e]=true;const r=e.endsWith(".css"),o=r?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${e}"]${o}`))return;const i=document.createElement("link");return i.rel=r?"stylesheet":t,r||(i.as="script"),i.crossOrigin="",i.href=e,a&&i.setAttribute("nonce",a),document.head.appendChild(i),r?new Promise((t,n)=>{i.addEventListener("load",t),i.addEventListener("error",()=>n(new Error(`Unable to preload CSS for ${e}`)));}):void 0}));}function a(e){const t=new Event("vite:preloadError",{cancelable:true});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return i.then(t=>{for(const e of t||[])"rejected"===e.status&&a(e.reason);return e().catch(a)})};const o=function(){const e=globalThis.React;if(!e||"function"!=typeof e.createElement)throw new Error("[Ophel] React CDN runtime is missing");return e}(),i=o.Children,a=o.Component,s=o.Fragment,l=o.Profiler,c=o.PureComponent,d=o.StrictMode,u=o.Suspense,h=o.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,g=o.act,p=o.cloneElement,m=o.createContext,f=o.createElement,b=o.createFactory,y=o.createRef,v=o.forwardRef,w=o.isValidElement,x=o.lazy,k=o.memo,S=o.startTransition,C=o.unstable_act,E=o.useCallback,_=o.useContext,A=o.useDebugValue,T=o.useDeferredValue,M=o.useEffect,I=o.useId,N=o.useImperativeHandle,L=o.useInsertionEffect,D=o.useLayoutEffect,R=o.useMemo,q=o.useReducer,P=o.useRef,B=o.useState,O=o.useSyncExternalStore,z=o.useTransition,F=o.version,j=Object.freeze(Object.defineProperty({__proto__:null,Children:i,Component:a,Fragment:s,Profiler:l,PureComponent:c,StrictMode:d,Suspense:u,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:h,act:g,cloneElement:p,createContext:m,createElement:f,createFactory:b,createRef:y,default:o,forwardRef:v,isValidElement:w,lazy:x,memo:k,startTransition:S,unstable_act:C,useCallback:E,useContext:_,useDebugValue:A,useDeferredValue:T,useEffect:M,useId:I,useImperativeHandle:N,useInsertionEffect:L,useLayoutEffect:D,useMemo:R,useReducer:q,useRef:P,useState:B,useSyncExternalStore:O,useTransition:z,version:F},Symbol.toStringTag,{value:"Module"}));const $=function(){const e=globalThis.ReactDOM;if(!e||"function"!=typeof e.createRoot)throw new Error("[Ophel] ReactDOM client CDN runtime is missing");return e}();$.createRoot,$.hydrateRoot;const H={styles:{metaName:"ophelStyles",fileName:"ophel.user.css"},icon:{metaName:"ophelIcon",fileName:"ophel-icon.png"},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"}},U={"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"},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 W="en",V={},G=new Set,Q=()=>{if("undefined"==typeof navigator)return W;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("fr")?"fr":e.startsWith("de")?"de":e.startsWith("ru")?"ru":e.startsWith("es")?"es":e.startsWith("pt")?"pt":W};let K=Q();function Z(e){return e&&"auto"!==e?(t=e,Object.prototype.hasOwnProperty.call(U,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("fr")?"fr":e.startsWith("de")?"de":e.startsWith("ru")?"ru":e.startsWith("es")?"es":e.startsWith("pt")?"pt":W):Q();var t;}function Y(e){const t=V[e];if(t)return t;const n=U[e].metaName;try{const t=GM_getResourceText(n);if(!t)return V[e]={},V[e];const r=JSON.parse(t);return V[e]=r,r}catch(r){return console.warn(`[Ophel] Failed to load userscript locale resource: ${e}`,r),V[e]={},V[e]}}function J(e){const t=Z(e);return K=t,Y(W),t!==W&&Y(t),t}function X(){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 ee(e){return G.add(e),()=>{G.delete(e);}}function te(e){const t=Z(e),n=K;K=t,Y(W),Y(t),n!==t&&G.forEach(e=>{try{e();}catch(t){console.warn("[Ophel] Userscript i18n listener failed:",t);}});}function ne(e){return Z(e)}function re(e,t){const n=Y(K),r=K===W?n:Y(W);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 oe(){return K}const ie=Object.freeze(Object.defineProperty({__proto__:null,getCurrentLang:oe,getEffectiveLanguage:ne,getInitialUserscriptLanguage:X,primeUserscriptLocales:J,setLanguage:te,subscribeI18nChanges:ee,t:re},Symbol.toStringTag,{value:"Module"})),ae=new Set,se=new Set(Object.values(H).filter(({fileName:e})=>/\.(mp3|ogg)$/i.test(e)).map(({metaName:e})=>e)),le=Object.fromEntries(Object.values(H).map(({metaName:e,fileName:t})=>{const n=t.split(".").pop()?.toLowerCase();return [e,"css"===n?"text/css":"png"===n?"image/png":"mp3"===n?"audio/mpeg":"ogg"===n?"audio/ogg":"application/octet-stream"]}));function ce(e,t){if(!t.startsWith("data:")||!se.has(e))return t;try{const n=t.indexOf(",");if(-1===n)return t;const r=t.slice(5,n),o=t.slice(n+1),i=r.split(";").filter(Boolean),a=i[0]||"",s=le[e]||a||"application/octet-stream",l=i.includes("base64")?function(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r"string"==typeof e&&e.length>0)),window.__OPHEL_USERSCRIPT_ASSET_URLS__={icon:ue(H.icon.metaName)||"",watermarkBg48:ue(H.watermarkBg48.metaName)||"",watermarkBg96:ue(H.watermarkBg96.metaName)||"",assistantMermaidRunner:ue(H.assistantMermaidRunner.metaName)||"",assistantMermaidVendor:ue(H.assistantMermaidVendor.metaName)||""},J(X()),"undefined"==typeof chrome||!chrome.storage){const e=["settings","prompts","folders","tags","readingHistory","claudeSessionKeys","conversations"];window.chrome={storage:{local:{get:(t,n)=>{if(null===t){const t={};for(const n of e){const e=GM_getValue(n);null!=e&&(t[n]=e);}n(t);}else if("string"==typeof t){const e=GM_getValue(t);n({[t]:e});}else {const e={};for(const n of t)e[n]=GM_getValue(n);n(e);}},set:(e,t)=>{for(const[n,r]of Object.entries(e))GM_setValue(n,r);t?.();},remove:(e,t)=>{const n="string"==typeof e?[e]:e;for(const r of n)GM_deleteValue(r);t?.();},clear:t=>{for(const n of e)GM_deleteValue(n);t?.();}},sync:{get:(t,n)=>{if(null===t){const t={};for(const n of e){const e=GM_getValue(n);null!=e&&(t[n]=e);}n(t);}else if("string"==typeof t){const e=GM_getValue(t);n({[t]:e});}else {const e={};for(const n of t)e[n]=GM_getValue(n);n(e);}},set:(e,t)=>{for(const[n,r]of Object.entries(e))GM_setValue(n,r);t?.();},remove:(e,t)=>{const n="string"==typeof e?[e]:e;for(const r of n)GM_deleteValue(r);t?.();},clear:t=>{for(const n of e)GM_deleteValue(n);t?.();}},onChanged:{addListener:()=>{},removeListener:()=>{}}},runtime:{getManifest:()=>({version:"1.0.0"}),getURL:e=>e,sendMessage:()=>Promise.resolve({})}};}const pe=window.chrome?.storage;pe&&!pe.onChanged&&(pe.onChanged={addListener:()=>{},removeListener:()=>{}});const me=window.chrome?.runtime;if(me&&!me.onMessage&&(me.onMessage={addListener:()=>{},removeListener:()=>{}}),window.top!==window.self)throw new Error("Ophel: Running in iframe, skipping initialization");if(window.ophelUserscriptInitialized)throw new Error("Ophel: Already initialized");window.ophelUserscriptInitialized=true,async function(){const[{getAdapter:e},{App:t},{initNetworkMonitor:n}]=await Promise.all([r(()=>Promise.resolve().then(()=>Up),void 0),r(()=>Promise.resolve().then(()=>ev),void 0),r(()=>Promise.resolve().then(()=>Tv),void 0)]),i=e();if(!i)return;i.afterPropertiesSet({});let a=null,s=null;const l=()=>{a?.disconnect(),a=null,null!==s&&(window.clearInterval(s),s=null);};await(async()=>{try{const e=document.createElement("div");e.id="ophel-userscript-root",e.style.cssText="all: initial; display: block; position: fixed; inset: 0; width: 0; height: 0; overflow: visible; pointer-events: none; z-index: 2147483647;";const n=()=>document.body||document.documentElement,r=async()=>{n()||await new Promise(e=>{const t=new MutationObserver(()=>{n()&&(t.disconnect(),e());});t.observe(document.documentElement,{childList:!0,subtree:!0});});},i=()=>{const t=n();t&&e.parentElement!==t&&t.appendChild(e);};await r(),i(),[250,600,1200,2e3,3500,5e3].forEach(e=>setTimeout(i,e)),a=new MutationObserver(()=>{e.isConnected||i();}),a.observe(document.documentElement,{childList:!0,subtree:!0}),s=window.setInterval(()=>{e.isConnected||i();},2e3),window.location.hostname.includes("chatglm.cn")&&e.classList.add("gh-site-chatglm");const l=e.attachShadow({mode:"open"}),c=document.createElement("style");c.textContent=he,l.appendChild(c);const d=document.createElement("div");d.id="ophel-app-container",l.appendChild(d);const u=()=>{const[,e]=o.useState(0);return o.useEffect(()=>ee(()=>{e(e=>e+1);}),[]),o.createElement(t)};$.createRoot(d).render(o.createElement(u));}catch(e){throw l(),e}})();const{useSettingsStore:c,getSettingsState:d}=await r(async()=>{const{useSettingsStore:e,getSettingsState:t}=await Promise.resolve().then(()=>qo);return {useSettingsStore:e,getSettingsState:t}},void 0),{useConversationsStore:u}=await r(async()=>{const{useConversationsStore:e}=await Promise.resolve().then(()=>Gp);return {useConversationsStore:e}},void 0),{useFoldersStore:h}=await r(async()=>{const{useFoldersStore:e}=await Promise.resolve().then(()=>Jp);return {useFoldersStore:e}},void 0),{useTagsStore:g}=await r(async()=>{const{useTagsStore:e}=await Promise.resolve().then(()=>tm);return {useTagsStore:e}},void 0),{usePromptsStore:p}=await r(async()=>{const{usePromptsStore:e}=await Promise.resolve().then(()=>fm);return {usePromptsStore:e}},void 0),{useClaudeSessionKeysStore:m}=await r(async()=>{const{useClaudeSessionKeysStore:e}=await Promise.resolve().then(()=>ly);return {useClaudeSessionKeysStore:e}},void 0),{useReadingHistoryStore:f}=await r(async()=>{const{useReadingHistoryStore:e}=await Promise.resolve().then(()=>vb);return {useReadingHistoryStore:e}},void 0),b=e=>{if(e.getState()._hasHydrated)return Promise.resolve(true);return new Promise(t=>{let n,r=false;const o=e=>{r||(r=true,window.clearTimeout(n),t(e));},i=e.subscribe(e=>{e._hasHydrated&&(i(),o(true));});n=window.setTimeout(()=>{i(),e.setState({_hasHydrated:true}),o(false);},5e3);})};await Promise.all([b(c),b(u),b(h),b(g),b(p),b(m),b(f)]);const y=d(),v=i.getSiteId(),{initCoreModules:w,subscribeModuleUpdates:x,initUrlChangeObserver:k}=await r(async()=>{const{initCoreModules:e,subscribeModuleUpdates:t,initUrlChangeObserver:n}=await Promise.resolve().then(()=>Vw);return {initCoreModules:e,subscribeModuleUpdates:t,initUrlChangeObserver:n}},void 0),S={adapter:i,settings:y,siteId:v};await w(S),n(),x(S),k(S),window.addEventListener("unload",l),window.addEventListener("unload",de);}();const fe=o.Fragment,be=(e,t,n)=>o.createElement(e,function(e,t){return void 0===t?e??{}:{...e??{},key:t}}(t,n)),ye=be,ve=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("circle",{cx:"12",cy:"12",r:"4"}), be("line",{x1:"12",y1:"2",x2:"12",y2:"4"}), be("line",{x1:"12",y1:"20",x2:"12",y2:"22"}), be("line",{x1:"4.93",y1:"4.93",x2:"6.34",y2:"6.34"}), be("line",{x1:"17.66",y1:"17.66",x2:"19.07",y2:"19.07"}), be("line",{x1:"2",y1:"12",x2:"4",y2:"12"}), be("line",{x1:"20",y1:"12",x2:"22",y2:"12"}), be("line",{x1:"4.93",y1:"19.07",x2:"6.34",y2:"17.66"}), be("line",{x1:"17.66",y1:"6.34",x2:"19.07",y2:"4.93"})]}),we=({size:e=18,color:t="currentColor",className:n=""})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:be("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})}),xe=({size:e=18,color:t="currentColor",className:n=""})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,className:n,style:{display:"block"},children:be("path",{fill:t,fillRule:"evenodd",clipRule:"evenodd",d:"M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zM12 18c-.89 0-1.74-.2-2.5-.55C11.56 16.5 13 14.42 13 12s-1.44-4.5-3.5-5.45C10.26 6.2 11.11 6 12 6c3.31 0 6 2.69 6 6s-2.69 6-6 6z"})}),ke=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("line",{x1:"18",y1:"6",x2:"6",y2:"18"}), be("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),Se=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("circle",{cx:"12",cy:"5",r:"2.5"}), be("line",{x1:"12",y1:"7.5",x2:"12",y2:"22"}), be("line",{x1:"7",y1:"10",x2:"17",y2:"10"}), be("path",{d:"M4 14C4 19 8 22 12 22C16 22 20 19 20 14"}), be("path",{d:"M1.5 16.5L4 14L6.5 16.5"}), be("path",{d:"M17.5 16.5L20 14L22.5 16.5"})]}),Ce=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[ be("path",{d:"M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2"}), be("path",{d:"M12 10v6"}), be("path",{d:"m9 13 3 3 3-3"})]}),Ee=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("line",{x1:"12",y1:"5",x2:"12",y2:"19"}), be("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),_e=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("circle",{cx:"12",cy:"12",r:"3"}), be("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"})]}),Ae=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("polyline",{points:"23 4 23 10 17 10"}), be("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]}),Te=({size:e=18,color:t="currentColor",className:n=""})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:be("line",{x1:"5",y1:"12",x2:"19",y2:"12"})}),Me=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}), be("polyline",{points:"14 2 14 8 20 8"}), be("line",{x1:"16",y1:"13",x2:"8",y2:"13"}), be("line",{x1:"16",y1:"17",x2:"8",y2:"17"}), be("line",{x1:"10",y1:"9",x2:"8",y2:"9"})]}),Ie=({size:e=18,color:t="currentColor",className:n=""})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,className:n,style:{display:"block"},children:be("path",{fill:t,stroke:t,strokeWidth:"0.3",d:"M19.75 6.5a.75.75 0 0 1-.75-.75V5h-.75a.75.75 0 0 1 0-1.5H19v-.75a.75.75 0 0 1 1.5 0v.75h.75a.75.75 0 0 1 0 1.5h-.75v.75a.75.75 0 0 1-.75.75M8.799 3.728a.34.34 0 0 1 .1-.18c.046-.04.082-.048.102-.048s.056.007.102.049a.34.34 0 0 1 .1.178a6.57 6.57 0 0 0 1.767 3.304a6.55 6.55 0 0 0 3.303 1.767c.07.014.135.053.178.1c.042.046.049.082.049.102s-.007.056-.049.102a.34.34 0 0 1-.178.1a6.56 6.56 0 0 0-3.303 1.768a6.56 6.56 0 0 0-1.766 3.302a.34.34 0 0 1-.101.18c-.046.04-.082.048-.102.048s-.056-.007-.102-.049a.34.34 0 0 1-.1-.178a6.57 6.57 0 0 0-1.767-3.304a6.55 6.55 0 0 0-3.303-1.767a.34.34 0 0 1-.179-.1c-.04-.047-.048-.082-.049-.102c0-.02.008-.056.049-.101a.34.34 0 0 1 .18-.102a6.56 6.56 0 0 0 3.302-1.766a6.56 6.56 0 0 0 1.767-3.303M9 2c-.883 0-1.52.695-1.67 1.422A5.06 5.06 0 0 1 5.97 5.97a5.06 5.06 0 0 1-2.546 1.36c-.728.15-1.424.788-1.423 1.673c.002.882.697 1.517 1.423 1.668a5.05 5.05 0 0 1 2.547 1.358c.87.871 1.22 1.88 1.359 2.549C7.48 15.305 8.118 16 9 16c.885 0 1.521-.695 1.672-1.423a5.06 5.06 0 0 1 1.358-2.546a5.06 5.06 0 0 1 2.548-1.36c.727-.15 1.422-.787 1.422-1.67c0-.885-.695-1.521-1.423-1.672a5.05 5.05 0 0 1-2.546-1.359a5.06 5.06 0 0 1-1.359-2.548C10.521 2.695 9.885 2 9.002 2M9.5 16.954v1.796c0 .966.784 1.75 1.75 1.75h7.5a1.75 1.75 0 0 0 1.75-1.75v-7.5a1.75 1.75 0 0 0-1.75-1.75h-1.796a2.7 2.7 0 0 0-.15-1.5h1.946A3.25 3.25 0 0 1 22 11.25v7.5A3.25 3.25 0 0 1 18.75 22h-7.5A3.25 3.25 0 0 1 8 18.75v-1.946a2.7 2.7 0 0 0 1.5.15M12 13.75a.75.75 0 0 1 .75-.75h5.5a.75.75 0 0 1 0 1.5h-5.5a.75.75 0 0 1-.75-.75m.75 2.25a.75.75 0 0 0 0 1.5h3.5a.75.75 0 0 0 0-1.5zm-10 3a.75.75 0 0 0 0 1.5h.75v.75a.75.75 0 0 0 1.5 0v-.75h.75a.75.75 0 0 0 0-1.5H5v-.75a.75.75 0 0 0-1.5 0V19z"})}),Ne=({size:e=16,color:t="currentColor",className:n=""})=>be("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block"},children:be("path",{fill:t,d:"M334.6432 189.27616a30.80192 30.80192 0 0 1 0 43.66336l-119.6032 119.1936a31.00672 31.00672 0 0 1-43.78624 0l-59.8016-59.55584a30.80192 30.80192 0 0 1 0-43.70432 31.04768 31.04768 0 0 1 43.8272 0l37.888 37.76512L290.816 189.27616a31.04768 31.04768 0 0 1 43.8272 0z m86.58944 81.42848c0-17.03936 13.88544-30.88384 30.96576-30.88384h438.43584a30.9248 30.9248 0 1 1 0 61.76768H452.1984a30.9248 30.9248 0 0 1-30.96576-30.88384zM334.6432 467.43552a30.80192 30.80192 0 0 1 0 43.66336l-119.6032 119.1936a31.04768 31.04768 0 0 1-43.78624 0l-59.8016-59.5968a30.80192 30.80192 0 0 1 0-43.66336 31.04768 31.04768 0 0 1 43.8272 0l37.888 37.76512L290.816 467.43552a31.04768 31.04768 0 0 1 43.8272 0zM421.23264 548.864c0-17.03936 13.88544-30.88384 30.96576-30.88384h438.43584a30.9248 30.9248 0 1 1 0 61.76768H452.1984a30.9248 30.9248 0 0 1-30.96576-30.88384zM334.6432 745.59488a30.80192 30.80192 0 0 1 0 43.66336l-119.6032 119.1936a31.00672 31.00672 0 0 1-43.78624 0l-59.8016-59.5968a30.80192 30.80192 0 0 1 0-43.66336 31.04768 31.04768 0 0 1 43.8272 0l37.888 37.76512L290.816 745.59488a31.04768 31.04768 0 0 1 43.8272 0z m86.58944 81.42848c0-17.03936 13.88544-30.88384 30.96576-30.88384h438.43584a30.9248 30.9248 0 1 1 0 61.76768H452.1984a30.9248 30.9248 0 0 1-30.96576-30.88384z"})}),Le=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"}), be("circle",{cx:"9",cy:"11",r:"1",fill:t,stroke:"none"}), be("circle",{cx:"12",cy:"11",r:"1",fill:t,stroke:"none"}), be("circle",{cx:"15",cy:"11",r:"1",fill:t,stroke:"none"})]}),De=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}), be("polyline",{points:"7 10 12 15 17 10"}), be("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),Re=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}), be("polyline",{points:"17 8 12 3 7 8"}), be("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),qe=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("circle",{cx:"12",cy:"12",r:"10"}), be("line",{x1:"12",y1:"8",x2:"12",y2:"16"}), be("line",{x1:"8",y1:"12",x2:"16",y2:"12"})]}),Pe=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("circle",{cx:"12",cy:"12",r:"10"}), be("line",{x1:"8",y1:"12",x2:"16",y2:"12"})]}),Be=({size:e=18,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:be("path",{d:"M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm8.94 3A8.994 8.994 0 0 0 13 3.06V1h-2v2.06A8.994 8.994 0 0 0 3.06 11H1v2h2.06A8.994 8.994 0 0 0 11 20.94V23h2v-2.06A8.994 8.994 0 0 0 20.94 13H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"})}),Oe=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("line",{x1:"12",y1:"19",x2:"12",y2:"5"}), be("polyline",{points:"5 12 12 5 19 12"})]}),ze=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("line",{x1:"12",y1:"5",x2:"12",y2:"19"}), be("polyline",{points:"19 12 12 19 5 12"})]}),Fe=({size:e=20,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:be("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73v.18a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.38a2 2 0 0 0-.73-2.73l-.15-.1a2 2 0 0 1-1-1.72v-.51a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z"})}),je=({size:e=20,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:be("path",{d:"M13.5 10.5L21 3 M16 3h5v5 M2 21h5 M12 21a9 9 0 0 0 9-9 9 9 0 0 0-9-9 9 9 0 0 0-9 9c0 4.97 4.03 9 9 9z"})}),$e=({size:e=20,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block",...r},children:be("path",{d:"M553.79358 660.032655v-121.03257a19.643494 19.643494 0 0 1 9.872902-17.085748l370.924415-213.827617a40.054312 40.054312 0 0 0 0-69.468399L553.844735 19.521745 529.597297 5.402984a40.105467 40.105467 0 0 0-60.158201 34.734199v600.916992a19.796959 19.796959 0 0 1-18.97848 19.745804c-217.561928 8.952113-430.673377 66.501412-430.673377 180.832687 0 125.227275 254.649254 181.80463 491.752367 181.80463s491.956986-56.577355 491.956986-181.90694c0-117.656345-225.900182-175.103334-449.805322-181.446546z m30.38603-525.412312l211.014096 121.3395a19.745804 19.745804 0 0 1 0 34.22265l-211.014096 121.953359a19.745804 19.745804 0 0 1-29.669861-17.085747V151.706091a19.745804 19.745804 0 0 1 29.669861-17.085748z m232.601478 765.226636a1211.655731 1211.655731 0 0 1-610.12488 0c-83.68947-25.986706-101.95178-53.149975-101.951781-58.316623s18.313466-32.278762 101.951781-58.418933a992.405691 992.405691 0 0 1 242.320915-37.598876 19.745804 19.745804 0 0 1 20.461973 19.694649v79.187836a19.745804 19.745804 0 0 0 19.796959 19.745804h44.658256a19.796959 19.796959 0 0 0 19.796959-19.745804v-79.187836a19.745804 19.745804 0 0 1 20.461973-19.745803 992.405691 992.405691 0 0 1 242.37207 37.65003c83.638315 26.037861 101.696006 52.99651 101.696006 58.316623s-18.057691 32.381072-101.696006 58.418933z",fill:t})}),He=({size:e=20,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:be("path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z M3.27 6.96L12 12.01l8.73-5.05 M12 22.08V12"})}),Ue=({size:e=20,color:t="currentColor",className:n="",style:r})=>ye("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block",...r},children:[ be("path",{d:"M511.5 119.3l366.8 168.8c-0.4 14.7-1.6 35-4.5 60.2-5.9 52.4-20.6 137.5-56.7 245.4-23 68.8-86.3 145.9-183.1 222.9-48.8 38.9-95.1 68.8-122.2 85.3-26.6-16.9-71.8-47.1-119.7-86.2-95.6-78-159-155.6-183.5-224.5-38.5-108.6-53.1-192.1-58.5-243.1-2.6-24.8-3.4-44.5-3.5-58.7l364.9-170.1m-0.2-55.1L98 257s-16 126.8 63.6 351c67.6 190.3 349.8 352.3 349.8 352.3s289.2-159 353.2-350.6C938.3 388.8 928 256 928 256L511.3 64.2z",fill:t}), be("path",{d:"M511.3 273.3c25.4 0 46.1 20.7 46.1 46.1s-20.7 46.1-46.1 46.1c-25.4 0-46.1-20.7-46.1-46.1s20.7-46.1 46.1-46.1m0-50c-53.1 0-96.1 43-96.1 96.1s43 96.1 96.1 96.1 96.1-43 96.1-96.1-43-96.1-96.1-96.1z",fill:t}), be("path",{d:"M486.3 383.8h50v384h-50z",fill:t}), be("path",{d:"M513 599h94.5v50H513zM513 717h94.5v50H513z",fill:t})]}),We=({size:e=20,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:be("path",{d:"M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z M12 16v-4 M12 8h.01"})}),Ve=({size:e=20,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:be("path",{d:"M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"})}),Ge=({size:e=20,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:be("path",{d:"M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2z M2 12h20 M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})}),Qe=({size:e=20,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:be("path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"})}),Ke=({size:e=20,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:be("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z M9 12l2 2 4-4"})}),Ze=({size:e=20,color:t="currentColor",className:n="",style:r,filled:o=false})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:o?t:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:be("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),Ye=({size:e=20,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:be("path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"})}),Je=({size:e=20,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:be("path",{d:"M11 18c0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2 2 .9 2 2zm-2-8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0-6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm6 4c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"})}),Xe=({size:e=18,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:be("path",{d:"M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"})}),et=({size:e=18,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:be("path",{d:"M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-1 8h-3v3h-2v-3h-3v-2h3V9h2v3h3v2z"})}),tt=({size:e=18,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:be("path",{d:"M6 2v6h.01L6 8.01 10 12l-4 4 .01.01H6V22h12v-5.99h-.01L18 16l-4-4 4-3.99-.01-.01H18V2H6zm10 14.5V20H8v-3.5l4-4 4 4zm-4-5l-4-4V4h8v3.5l-4 4z"})}),nt=({size:e=18,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:be("path",{d:"M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"})}),rt=({size:e=20,className:t=""})=>ye("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[ be("path",{d:"M15 3h6v6"}), be("path",{d:"M9 21H3v-6"}), be("path",{d:"M21 3l-7 7"}), be("path",{d:"M3 21l7-7"})]}),ot=({size:e=20,className:t=""})=>ye("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[ be("path",{d:"M4 14h6v6"}), be("path",{d:"M20 10h-6V4"}), be("path",{d:"M14 10l7-7"}), be("path",{d:"M3 21l7-7"})]}),it=({size:e=20,className:t=""})=>be("svg",{width:e,height:e,viewBox:"0 0 1024 1024",version:"1.1",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",className:t,children:be("path",{d:"M606.72 304.64V235.52H346.624l51.712-16.384c-7.168-24.576-25.088-62.464-40.448-90.112l-76.288 22.016c13.824 26.624 27.136 59.904 33.792 84.48H62.976v69.12h94.208C189.44 388.608 230.4 460.8 284.16 519.68c-61.952 48.128-139.264 82.432-232.448 105.984 14.336 15.872 35.328 49.152 43.008 66.048 96.256-27.648 176.128-67.072 242.176-120.832 62.464 52.736 139.776 92.16 233.472 117.248 10.752-19.968 31.744-50.688 47.616-66.048-89.088-20.992-164.352-55.808-225.792-103.424 52.224-57.856 92.672-128 122.88-214.016h91.648z m-171.52 0a474.624 474.624 0 0 1-97.28 165.376c-46.08-47.104-81.92-102.4-107.52-165.376h204.8z m237.568 622.08h-90.112l141.824-414.72h104.448l142.848 414.72h-93.184l-31.232-106.496h-143.872l-30.72 106.496z m100.864-351.744c-11.264 45.568-24.576 92.672-37.888 135.68l-12.8 45.568h105.472l-13.312-45.568c-13.824-43.008-28.672-90.624-41.472-135.68z",fill:"currentColor"})}),at=({size:e=20,className:t="",style:n})=>be("svg",{width:e,height:e,viewBox:"0 0 1024 1024",version:"1.1",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",className:t,style:n,children:be("path",{d:"M512 136.83c-206.88 0-375.17 168.31-375.17 375.17S305.12 887.17 512 887.17 887.17 718.86 887.17 512 718.88 136.83 512 136.83z m265.73 202h-85.94c-12.32-44.9-29.26-84.4-49.88-116.19a319.22 319.22 0 0 1 135.82 116.2zM656.3 512a625.41 625.41 0 0 1-10.54 115.44H378.24a637.45 637.45 0 0 1 0-230.88h267.52A625.41 625.41 0 0 1 656.3 512zM512 829.45c-44.2 0-91.56-54.92-119.52-144.29h239C603.56 774.53 556.2 829.45 512 829.45zM392.48 338.84c28-89.37 75.32-144.29 119.52-144.29s91.56 54.92 119.52 144.29z m-10.39-116.19c-20.62 31.79-37.56 71.29-49.88 116.19h-85.94a319.22 319.22 0 0 1 135.82-116.19z m-165.5 173.91h102.85a709.08 709.08 0 0 0 0 230.88H216.59a313.34 313.34 0 0 1 0-230.88z m29.68 288.6h85.94c12.32 44.9 29.26 84.4 49.88 116.19a319.22 319.22 0 0 1-135.82-116.19z m395.64 116.19c20.62-31.79 37.56-71.29 49.88-116.19h85.94a319.22 319.22 0 0 1-135.82 116.19z m165.5-173.91H704.56a709.08 709.08 0 0 0 0-230.88h102.85a313.34 313.34 0 0 1 0 230.88z",fill:"currentColor"})}),st=({size:e=20,color:t="currentColor",className:n="",style:r})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:[ be("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",ry:"2"}), be("line",{x1:"6",y1:"8",x2:"6",y2:"8"}), be("line",{x1:"10",y1:"8",x2:"10",y2:"8"}), be("line",{x1:"14",y1:"8",x2:"14",y2:"8"}), be("line",{x1:"18",y1:"8",x2:"18",y2:"8"}), be("line",{x1:"6",y1:"12",x2:"6",y2:"12"}), be("line",{x1:"10",y1:"12",x2:"10",y2:"12"}), be("line",{x1:"14",y1:"12",x2:"14",y2:"12"}), be("line",{x1:"18",y1:"12",x2:"18",y2:"12"}), be("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]}),lt=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}), be("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),ct=({size:e=16,className:t="",...n})=>ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:`more-horizontal-icon ${t}`,...n,children:[ be("circle",{cx:"12",cy:"12",r:"1",className:"dot dot-2"}), be("circle",{cx:"19",cy:"12",r:"1",className:"dot dot-3"}), be("circle",{cx:"5",cy:"12",r:"1",className:"dot dot-1"}), be("style",{children:"\n .more-horizontal-icon .dot {\n transform-box: fill-box;\n transform-origin: center;\n animation: dot-jump 3s infinite;\n }\n .more-horizontal-icon .dot-1 {\n animation-delay: 0s;\n }\n .more-horizontal-icon .dot-2 {\n animation-delay: 0.1s;\n }\n .more-horizontal-icon .dot-3 {\n animation-delay: 0.2s;\n }\n @keyframes dot-jump {\n 0%, 90%, 100% { transform: translateY(0); }\n 5% { transform: translateY(-3px); }\n 10% { transform: translateY(0); }\n }\n "})]}),dt=({size:e=20,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:be("path",{d:"M18 15l-6-6-6 6"})}),ut=({size:e=20,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:be("path",{d:"M6 9l6 6 6-6"})}),ht=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[ be("path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"}), be("path",{d:"m14.5 9-5 5"}), be("path",{d:"m9.5 9 5 5"})]}),gt=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[ be("path",{d:"M12 2H2v10l9.29 9.29c.94.94 2.48.94 3.42 0l6.58-6.58c.94-.94.94-2.48 0-3.42L12 2Z"}), be("path",{d:"M7 7h.01"})]}),pt=({size:e=24,className:t,color:n="currentColor"})=>ye("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,style:{color:n},children:[ be("circle",{cx:"12",cy:"12",r:"10"}), be("circle",{cx:"12",cy:"12",r:"4"}), be("line",{x1:"21.17",x2:"12",y1:"8",y2:"8"}), be("line",{x1:"3.95",x2:"8.54",y1:"6.06",y2:"14"}), be("line",{x1:"10.88",x2:"15.46",y1:"21.94",y2:"14"})]}),mt=({size:e=24,className:t,color:n="currentColor"})=>be("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,style:{color:n},children:be("path",{d:"M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4"})}),ft=({size:e=24,className:t,color:n="currentColor"})=>ye("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,style:{color:n},children:[ be("path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"}), be("polyline",{points:"14 2 14 8 20 8"}), be("path",{d:"m9 15 2 2 4-4"})]}),bt=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}), be("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),yt=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("polyline",{points:"3 6 5 6 21 6"}), be("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}), be("line",{x1:"10",y1:"11",x2:"10",y2:"17"}), be("line",{x1:"14",y1:"11",x2:"14",y2:"17"})]}),vt=({size:e=18,color:t="currentColor",className:n="",filled:r=false,style:o})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:r?t:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...o},children:[ be("line",{x1:"12",y1:"17",x2:"12",y2:"22"}), be("path",{d:"M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V17z"})]}),wt=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}), be("circle",{cx:"12",cy:"12",r:"3"})]}),xt=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("circle",{cx:"11",cy:"11",r:"8"}), be("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),kt=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("line",{x1:"12",y1:"19",x2:"12",y2:"5"}), be("polyline",{points:"5 12 12 5 19 12"})]}),St=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("line",{x1:"12",y1:"5",x2:"12",y2:"19"}), be("polyline",{points:"19 12 12 19 5 12"})]}),Ct=({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("circle",{cx:"12",cy:"12",r:"10"}), be("polyline",{points:"12 6 12 12 16 14"})]}),Et=({size:e=18,color:t,className:n="",style:r})=>{const i=`sparkle-gradient-${o.useId().replace(/:/g,"")}`,a=!t||"brand"===t,s=a?`url(#${i})`:t,l="number"==typeof e?1.25*e:e; return ye("svg",{viewBox:"0 0 1024 1024",width:l,height:l,xmlns:"http://www.w3.org/2000/svg",className:n,style:{display:"block",flexShrink:0,overflow:"visible",filter:a?"drop-shadow(0px 2px 5px rgba(0, 0, 0, 0.45)) drop-shadow(0px 0px 1px rgba(0,0,0,0.2))":"none",...r},children:[ be("defs",{children:a&&ye("linearGradient",{id:i,x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[ be("stop",{offset:"0%",stopColor:"#22d3ee"}), be("stop",{offset:"35%",stopColor:"#8b5cf6"}), be("stop",{offset:"70%",stopColor:"#f43f5e"}), be("stop",{offset:"100%",stopColor:"#f59e0b"})]})}), ye("g",{style:{fill:s,stroke:s,strokeWidth:12,strokeLinejoin:"round",strokeLinecap:"round"},children:[ be("path",{d:"M380.77 475.76c-2.29 0-4.29-1.55-4.85-3.77l-11.9-47.04-47.08-14.51a5.002 5.002 0 0 1-3.52-5.05c0.13-2.29 1.8-4.2 4.05-4.64l46.76-8.95 11.53-46.79c0.55-2.23 2.55-3.8 4.85-3.8h0.01c2.3 0 4.3 1.56 4.85 3.79l11.67 46.8 46.77 8.95c2.26 0.43 3.93 2.34 4.05 4.64a4.994 4.994 0 0 1-3.52 5.05l-47.07 14.5-11.76 47.03a4.986 4.986 0 0 1-4.84 3.79z m-41.69-68.96l30.57 9.42a5 5 0 0 1 3.38 3.55l7.71 30.49 7.62-30.47a5.01 5.01 0 0 1 3.38-3.57l30.57-9.42-30.18-5.77a5.006 5.006 0 0 1-3.91-3.7L380.66 367l-7.47 30.32c-0.47 1.9-2 3.35-3.92 3.71l-30.19 5.77zM513.43 939.45h-0.04c-8-0.02-14.96-5.46-16.93-13.21L415.8 607.36l-319.06-98.3a17.495 17.495 0 0 1-12.32-17.7c0.45-8.03 6.32-14.72 14.22-16.22l191.92-36.28c9.5-1.8 18.65 4.45 20.45 13.95s-4.45 18.65-13.94 20.45l-122.51 23.16 260.96 80.4c5.84 1.8 10.31 6.51 11.81 12.43l66.26 261.97 46.87-181.85c2.41-9.36 11.95-14.99 21.31-12.58s14.99 11.95 12.58 21.31l-63.97 248.22c-2 7.73-8.97 13.13-16.95 13.13zM826.61 540.39c-7.44 0-14.35-4.79-16.69-12.27-2.89-9.22 2.24-19.04 11.46-21.94l31.03-9.73-261.1-49.94a17.496 17.496 0 0 1-13.69-12.96l-65.07-260.98-47.06 190.3c-2.32 9.38-11.8 15.11-21.19 12.79-9.38-2.32-15.11-11.81-12.79-21.19l63.97-258.72a17.497 17.497 0 0 1 16.97-13.3h0.02c8.03 0 15.04 5.47 16.98 13.27l79.41 318.52 318.43 60.91a17.5 17.5 0 0 1 14.18 16.18c0.46 8.01-4.58 15.3-12.23 17.7l-97.39 30.55c-1.74 0.55-3.5 0.81-5.24 0.81zM842.91 908.24c-2.29 0-4.29-1.55-4.85-3.77l-11.9-47.04-47.08-14.51a5.002 5.002 0 0 1-3.52-5.05c0.13-2.29 1.8-4.21 4.05-4.64l46.76-8.95 11.53-46.79c0.55-2.23 2.55-3.8 4.85-3.8h0.01c2.3 0 4.3 1.56 4.85 3.79l11.67 46.8 46.77 8.95c2.26 0.43 3.93 2.34 4.05 4.64a4.994 4.994 0 0 1-3.52 5.05l-47.07 14.5-11.76 47.03a4.975 4.975 0 0 1-4.84 3.79z m-41.68-68.96l30.57 9.42a5 5 0 0 1 3.38 3.55l7.71 30.49 7.62-30.47a5.01 5.01 0 0 1 3.38-3.57l30.57-9.42-30.18-5.77a5.006 5.006 0 0 1-3.91-3.7l-7.56-30.33-7.47 30.32c-0.47 1.9-2 3.35-3.92 3.71l-30.19 5.77zM874.6 220.76c-1.85 0-3.73-0.3-5.58-0.93l-67.48-23.04c-4.37-1.49-7.9-4.6-9.94-8.76-2.04-4.16-2.34-8.85-0.85-13.22l23.05-67.47c3.09-9.03 12.95-13.87 21.98-10.79l67.48 23.04c4.37 1.49 7.9 4.6 9.94 8.76 2.04 4.16 2.34 8.85 0.85 13.22L891 209.04c-2.45 7.19-9.2 11.72-16.4 11.72z m0.88-19.86z m0 0z m-64.94-22.17l62.4 21.31 21.31-62.39-62.4-21.31-21.31 62.39zM147.92 229.91a9.91 9.91 0 0 1-3.34-0.58 9.982 9.982 0 0 1-6.49-7.61l-17.36-93.88c-0.65-3.51 0.62-7.11 3.34-9.43 2.72-2.32 6.47-3.01 9.83-1.82l89.99 31.91a9.982 9.982 0 0 1 6.49 7.61c0.65 3.51-0.62 7.11-3.34 9.43l-72.63 61.97a9.951 9.951 0 0 1-6.49 2.4z m-4.38-88.67l11.06 59.82 46.28-39.49-57.34-20.33zM170.16 908.56c-29.21 0-52.97-23.76-52.97-52.96s23.76-52.96 52.97-52.96 52.97 23.76 52.97 52.96-23.76 52.96-52.97 52.96z m0-85.92c-18.18 0-32.97 14.79-32.97 32.96 0 18.18 14.79 32.96 32.97 32.96s32.97-14.79 32.97-32.96c0-18.18-14.79-32.96-32.97-32.96z"}), be("path",{d:"M720.52 570.25c-4.83 0-9.57-2.33-12.46-6.63-4.62-6.88-2.79-16.2 4.08-20.82 59.91-40.27 107.08-81.41 136.42-118.97 27-34.56 36.95-64.05 28.02-83.02-9.9-21.04-43.7-32.21-95.17-31.46-55 0.81-127.81 15.68-205.01 41.87-7.84 2.66-16.36-1.54-19.02-9.38-2.66-7.84 1.54-16.36 9.38-19.02 81.25-27.57 155.32-42.6 214.21-43.46 81.98-1.2 112 25.81 122.76 48.69 9.9 21.04 12.46 57.94-31.53 114.26-31.26 40.03-80.82 83.39-143.33 125.4a15.005 15.005 0 0 1-8.35 2.54zM206.58 758.85c-19.37 0-36.69-1.63-51.82-4.9-32.77-7.08-54.56-21.65-64.74-43.3-12.12-25.77-6.13-57.5 17.79-94.3 20.83-32.03 55.73-67.88 100.95-103.69 6.49-5.14 15.93-4.05 21.07 2.45 5.14 6.49 4.05 15.93-2.45 21.07-42.7 33.81-75.35 67.19-94.42 96.53-12.3 18.91-25.02 45.57-15.8 65.17 12.64 26.87 65.89 37.07 142.46 27.28 84.33-10.77 188.04-43.64 292.05-92.54 9.16-4.31 18.36-8.76 27.37-13.24 7.42-3.69 16.42-0.67 20.11 6.74 3.69 7.42 0.67 16.42-6.74 20.11-9.2 4.58-18.61 9.14-27.97 13.54-106.76 50.2-213.66 83.99-301.01 95.15-20.52 2.62-39.51 3.93-56.85 3.93z"}), be("path",{d:"M598.89 616.45a16.71 16.71 0 1 0 33.42 0 16.71 16.71 0 1 0-33.42 0Z"}), be("path",{d:"M664.77 608.33h-18.14c-4.2 0-7.64-3.44-7.64-7.64v-18.14c0-4.2 3.44-7.64 7.64-7.64h18.14c4.2 0 7.64 3.44 7.64 7.64v18.14c0 4.2-3.44 7.64-7.64 7.64zM690.73 554.4l-12.28 21.27c-0.98 1.7 0.25 3.83 2.21 3.83h24.57c1.97 0 3.2-2.13 2.21-3.83l-12.28-21.27c-0.99-1.7-3.45-1.7-4.43 0z"})]})]})},_t=({size:e=15,color:t="currentColor",className:n=""})=>be("svg",{viewBox:"0 0 1024 1024",width:e,height:e,xmlns:"http://www.w3.org/2000/svg",className:n,style:{display:"block",flexShrink:0},children:be("path",{d:"M674.432 64c20.224 0 37.888 18.944 37.888 40.576v297.792h232.192c7.616 0 15.168 2.752 20.16 8.128a41.92 41.92 0 0 1 10.176 56.832l-295.36 473.728a34.688 34.688 0 0 1-30.272 18.944c-20.16 0-37.824-18.944-37.824-40.576V621.632h-232.32a27.584 27.584 0 0 1-20.16-8.128 41.92 41.92 0 0 1-10.048-56.832l295.296-473.728A34.688 34.688 0 0 1 674.432 64zM44.8 140.8h358.4a44.8 44.8 0 0 1 0 89.6H44.8a44.8 44.8 0 1 1 0-89.6z m0 640h358.4a44.8 44.8 0 0 1 0 89.6H44.8a44.8 44.8 0 0 1 0-89.6z m0-320h166.4a44.8 44.8 0 0 1 0 89.6H44.8a44.8 44.8 0 1 1 0-89.6z",fill:t})}),At=({size:e=18,color:t="currentColor",className:n=""})=>be("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:be("polyline",{points:"20 6 9 17 4 12"})}),Tt="scrollTop",Mt="scrollBottom",It="goToAnchor",Nt="togglePanel",Lt="toggleTheme",Dt="openSettings",Rt="switchTab1",qt="switchTab2",Pt="switchTab3",Bt="toggleUserQueries",Ot="onlyUserQueries",zt="toggleBookmarks",Ft="locateOutline",jt="searchOutline",$t="refreshOutline",Ht="prevHeading",Ut="nextHeading",Wt="toggleOutlineExpand",Vt="expandLevel1",Gt="expandLevel2",Qt="expandLevel3",Kt="expandLevel4",Zt="expandLevel5",Yt="expandLevel6",Jt="newConversation",Xt="refreshConversations",en="locateConversation",tn="prevConversation",nn="nextConversation",rn="exportConversation",on="copyLatestReply",an="copyLastCodeBlock",sn="toggleScrollLock",ln="focusInput",cn="openGlobalSearch",dn="stopGeneration",un="togglePromptQueue",hn="showShortcuts",gn="showModelSelector",pn="openClaudeSettings",mn="switchClaudeKey",fn="openGeminiSettings",bn="openThemeSettings",yn="openModelLockSettings",vn={scrollTop:{labelKey:"shortcutScrollTop",label:"去顶部",category:"navigation"},scrollBottom:{labelKey:"shortcutScrollBottom",label:"去底部",category:"navigation"},goToAnchor:{labelKey:"shortcutGoToAnchor",label:"返回锚点",category:"navigation"},togglePanel:{labelKey:"shortcutTogglePanel",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"},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"}},wn={navigation:{labelKey:"shortcutCategoryNavigation",label:"导航"},panel:{labelKey:"shortcutCategoryPanel",label:"面板"},outline:{labelKey:"shortcutCategoryOutline",label:"大纲"},conversation:{labelKey:"shortcutCategoryConversation",label:"会话"},edit:{labelKey:"shortcutCategoryEdit",label:"交互控制"},settings:{labelKey:"shortcutCategorySettings",label:"设置"}},xn={scrollTop:{key:"t",alt:true},scrollBottom:{key:"b",alt:true},goToAnchor:{key:"z",alt:true},togglePanel:{key:"p",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},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}},kn={enabled:true,globalUrl:"https://gemini.google.com",keybindings:xn},Sn={Backquote:"`",Minus:"-",Equal:"=",BracketLeft:"[",BracketRight:"]",Backslash:"\\",Semicolon:";",Quote:"'",Comma:",",Period:".",Slash:"/"},Cn={"å":"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 En(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(Sn[t])return Sn[t]}return Cn[e]?Cn[e]:e}function _n(e){if(!e)return e;return {key:En(e.key),alt:!!e.alt,ctrl:!!e.ctrl||!!e.meta,shift:!!e.shift}}function An(e){return e?{enabled:e.enabled??true,globalUrl:e.globalUrl||kn.globalUrl,keybindings:(t=e.keybindings,(t?Object.fromEntries(Object.entries(t).map(([e,t])=>[e,null===t?null:_n(t)])):t)||kn.keybindings)}:e;var t;}function Tn(e,t=false){const n=_n(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=En(n.key),i={ArrowUp:"↑",ArrowDown:"↓",ArrowLeft:"←",ArrowRight:"→",",":","}[o]||o.toUpperCase();return r.push(i),r.join(t?"":"+")}function Mn(){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")}const In="prompts",Nn="outline",Ln="conversations",Dn="settings",Rn="general",qn="appearance",Pn="features",Bn="siteSettings",On="globalSearch",zn="shortcuts",Fn="backup",jn="permissions",$n="about",Hn="outline",Un="conversations",Wn="prompts",Vn="tab",Gn="reminder",Qn="content",Kn="readingHistory",Zn="toolbox",Yn="presets",Jn="custom",Xn="layout",er="modelLock",tr={"appearance-preset-light":{page:qn,subTab:Yn},"appearance-preset-dark":{page:qn,subTab:Yn},"appearance-custom-styles":{page:qn,subTab:Jn},"tab-show-notification":{page:Pn,subTab:Gn},"tab-notification-sound":{page:Pn,subTab:Gn},"tab-notification-sound-preset":{page:Pn,subTab:Gn},"tab-notification-volume":{page:Pn,subTab:Gn},"tab-notification-repeat-count":{page:Pn,subTab:Gn},"tab-notification-repeat-interval":{page:Pn,subTab:Gn},"tab-notify-when-focused":{page:Pn,subTab:Gn},"tab-auto-focus":{page:Pn,subTab:Gn},"usage-monitor-enabled":{page:Pn,subTab:Gn},"usage-monitor-daily-limit":{page:Pn,subTab:Gn},"usage-monitor-auto-reset":{page:Pn,subTab:Gn}},nr=[{prefix:"panel-",route:{page:Rn,subTab:"panel"}},{prefix:"quick-buttons-",route:{page:Rn,subTab:"shortcuts"}},{prefix:"tools-menu-",route:{page:Rn,subTab:"toolsMenu"}},{prefix:"shortcuts-",route:{page:zn}},{prefix:"shortcut-binding-",route:{page:zn}},{prefix:"layout-",route:{page:Bn,subTab:Xn}},{prefix:"model-lock-",route:{page:Bn,subTab:er}},{prefix:"gemini-",route:{page:Bn,subTab:"gemini"}},{prefix:"aistudio-",route:{page:Bn,subTab:"aistudio"}},{prefix:"chatgpt-",route:{page:Bn,subTab:"chatgpt"}},{prefix:"claude-",route:{page:Bn,subTab:"claude"}},{prefix:"global-search-",route:{page:On}},{prefix:"tab-",route:{page:Pn,subTab:Vn}},{prefix:"outline-",route:{page:Pn,subTab:Hn}},{prefix:"conversation-",route:{page:Pn,subTab:Un}},{prefix:"export-",route:{page:Pn,subTab:Un}},{prefix:"prompt-",route:{page:Pn,subTab:Wn}},{prefix:"reading-history-",route:{page:Pn,subTab:Kn}},{prefix:"content-",route:{page:Pn,subTab:Qn}},{prefix:"appearance-preset-",route:{page:qn,subTab:Yn}},{prefix:"appearance-custom-",route:{page:qn,subTab:Jn}}],rr={"general.panel.defaultOpen":"panel-default-open","general.panel.defaultPosition":"panel-default-position","general.panel.defaultEdgeDistance":"panel-edge-distance","general.panel.width":"panel-width","general.panel.height":"panel-height","general.panel.edgeSnap":"panel-edge-snap","general.panel.edgeSnapThreshold":"panel-edge-snap-threshold","general.panel.autoHide":"panel-auto-hide","general.shortcuts.quickButtonsOpacity":"quick-buttons-opacity","general.toolsMenu":"tools-menu-scrollTop","siteSettings.layout.pageWidth.enabled":"layout-page-width-enabled","siteSettings.layout.pageWidth.value":"layout-page-width-value","siteSettings.layout.userQueryWidth.enabled":"layout-user-query-width-enabled","siteSettings.layout.userQueryWidth.value":"layout-user-query-width-value","siteSettings.layout.zenMode.enabled":"layout-zen-mode-enabled","siteSettings.modelLock":"model-lock-gemini","globalSearch.promptEnterBehavior":"global-search-prompt-enter-behavior","globalSearch.enableFuzzySearch":"global-search-fuzzy-search","globalSearch.doubleShift":"global-search-double-shift","shortcuts.enabled":"shortcuts-enabled","shortcuts.globalUrl":"shortcuts-global-url","features.prompts.submitShortcut":"shortcuts-prompt-submit-shortcut","features.tab.openInNewTab":"tab-open-new","features.tab.autoRename":"tab-auto-rename","usageMonitor.enabled":"usage-monitor-enabled","usageMonitor.dailyLimit":"usage-monitor-daily-limit","usageMonitor.autoResetEnabled":"usage-monitor-auto-reset","features.outline.autoUpdate":"outline-auto-update","features.outline.inlineBookmarkMode":"outline-inline-bookmark-mode","features.outline.panelBookmarkMode":"outline-panel-bookmark-mode","features.outline.preventAutoScroll":"outline-prevent-auto-scroll","features.prompts.promptQueue":"prompt-queue","features.export.includeThoughts":"export-include-thoughts","features.readingHistory.persistence":"reading-history-persistence","features.content.assistantMermaid":"content-assistant-mermaid","features.content.formulaCopy":"content-formula-copy","panel.preventAutoScroll":"outline-prevent-auto-scroll","content.markdownFix":"gemini-markdown-fix","content.watermarkRemoval":"gemini-watermark-removal","geminiEnterprise.policyRetry.enabled":"gemini-policy-retry","geminiEnterprise.policyRetry.maxRetries":"gemini-policy-max-retries","aistudio.collapseNavbar":"aistudio-collapse-navbar","aistudio.collapseRunSettings":"aistudio-collapse-run-settings","aistudio.collapseTools":"aistudio-collapse-tools","aistudio.collapseAdvanced":"aistudio-collapse-advanced","aistudio.enableSearch":"aistudio-enable-search","aistudio.removeWatermark":"aistudio-remove-watermark","aistudio.markdownFix":"aistudio-markdown-fix","chatgpt.markdownFix":"chatgpt-markdown-fix","claude.sessionKeys":"claude-session-keys","appearance.presets.light":"appearance-preset-light","appearance.presets.dark":"appearance-preset-dark","appearance.custom.styles":"appearance-custom-styles"},or=e=>{const t=e?.trim();if(t)return rr[t]??t},ir=e=>{const t=or(e);if(t)return tr[t]?tr[t]:nr.find(e=>t.startsWith(e.prefix))?.route},ar=[{settingId:"panel-default-open",title:"默认显示面板",keywords:["panel","default open","默认打开"]},{settingId:"panel-default-position",title:"默认位置",keywords:["panel","left","right","默认侧边"]},{settingId:"panel-edge-distance",title:"默认边距",keywords:["panel","edge distance","margin"]},{settingId:"panel-width",title:"面板宽度",keywords:["panel width","宽度"]},{settingId:"panel-height",title:"面板高度",keywords:["panel height","高度"]},{settingId:"panel-edge-snap",title:"边缘自动吸附",keywords:["snap","edge","吸附"]},{settingId:"panel-edge-snap-threshold",title:"边缘吸附阈值",keywords:["snap threshold","edge snap","吸附阈值"]},{settingId:"panel-auto-hide",title:"自动隐藏面板",keywords:["auto hide","panel"]},{settingId:"quick-buttons-opacity",title:"快捷按钮透明度",keywords:["quick buttons","opacity","透明度"]},{settingId:"tools-menu-export",title:"工具箱:显示导出按钮",keywords:["tools menu","export","工具箱","导出"]},{settingId:"tools-menu-copyMarkdown",title:"工具箱:显示复制 Markdown",keywords:["tools menu","copy","markdown","工具箱"]},{settingId:"tools-menu-move",title:"工具箱:显示移动按钮",keywords:["tools menu","move","folder","工具箱"]},{settingId:"tools-menu-setTag",title:"工具箱:显示标签按钮",keywords:["tools menu","tag","标签","工具箱"]},{settingId:"tools-menu-scrollLock",title:"工具箱:显示滚动锁定",keywords:["tools menu","scroll lock","锁定滚动","工具箱"]},{settingId:"tools-menu-modelLock",title:"工具箱:显示模型锁定",keywords:["tools menu","model lock","模型锁定","工具箱"]},{settingId:"tools-menu-cleanup",title:"工具箱:显示清理按钮",keywords:["tools menu","cleanup","清理","工具箱"]},{settingId:"tools-menu-settings",title:"工具箱:显示设置按钮",keywords:["tools menu","settings","设置","工具箱"]},{settingId:"tab-open-new",title:"新会话打开方式",keywords:["tab","new conversation","open in new tab","新标签页"]},{settingId:"tab-auto-rename",title:"自动重命名标签页",keywords:["tab","auto rename","自动命名"]},{settingId:"tab-rename-interval",title:"标签页重命名间隔",keywords:["tab","rename interval","重命名间隔"]},{settingId:"tab-title-format",title:"标签页标题格式",keywords:["tab","title format","标题模板"]},{settingId:"tab-show-status",title:"显示状态图标",keywords:["tab","status","状态图标"]},{settingId:"tab-show-notification",title:"启用新消息通知",keywords:["tab","notification","消息提醒"]},{settingId:"tab-notification-sound",title:"通知音效",keywords:["tab","notification sound","声音提醒"]},{settingId:"tab-notification-volume",title:"通知音量",keywords:["tab","notification volume","音量"]},{settingId:"tab-notify-when-focused",title:"标签页聚焦时也提醒",keywords:["tab","focused","notify","聚焦提醒"]},{settingId:"tab-auto-focus",title:"自动聚焦到对话页",keywords:["tab","auto focus","自动聚焦"]},{settingId:"usage-monitor-enabled",title:"启用高级模型对话本地计数与预估",keywords:["usage","counter","estimate","token","quota","limit","advanced model","高级模型","本地计数","预估"]},{settingId:"usage-monitor-daily-limit",title:"每日对话次数预估上限",keywords:["daily limit","quota","limit","每日上限","次数上限","token"]},{settingId:"usage-monitor-auto-reset",title:"自动归零",keywords:["auto reset","reset","midnight","自动归零","重置","清零"]},{settingId:"tab-privacy-mode",title:"隐私模式",keywords:["tab","privacy","隐私"]},{settingId:"tab-privacy-title",title:"隐私模式标题",keywords:["tab","privacy title","隐私标题"]},{settingId:"outline-auto-update",title:"自动更新大纲",keywords:["outline","auto update","自动刷新"]},{settingId:"outline-update-interval",title:"大纲更新间隔",keywords:["outline","interval","刷新频率"]},{settingId:"outline-follow-mode",title:"自动跟随浏览位置",keywords:["outline","follow","自动跟随"]},{settingId:"outline-show-word-count",title:"显示字数统计",keywords:["outline","word count","字数"]},{settingId:"outline-inline-bookmark-mode",title:"内联收藏模式",keywords:["outline","bookmark","收藏","inline"]},{settingId:"outline-panel-bookmark-mode",title:"面板收藏模式",keywords:["outline","bookmark","收藏","panel"]},{settingId:"outline-prevent-auto-scroll",title:"阻止自动滚动页面",keywords:["outline","auto scroll","禁止滚动"]},{settingId:"conversation-folder-rainbow",title:"会话文件夹彩虹色",keywords:["conversation","folder","rainbow","文件夹颜色"]},{settingId:"conversation-sync-unpin",title:"同步时自动取消置顶",keywords:["conversation","sync","unpin","置顶"]},{settingId:"conversation-sync-delete",title:"删除时同步删除云端",keywords:["conversation","sync","delete","cloud","删除","云端"]},{settingId:"export-custom-user-name",title:"导出:自定义用户名称",keywords:["export","user name","导出用户名"]},{settingId:"export-custom-model-name",title:"导出:自定义模型名称",keywords:["export","model name","导出模型名"]},{settingId:"export-filename-timestamp",title:"导出文件名包含时间戳",keywords:["export","filename","timestamp","时间戳"]},{settingId:"export-include-thoughts",title:"导出包含思维链",keywords:["export","thoughts","reasoning","thinking","思维链","思路","推理"]},{settingId:"export-images-base64",title:"导出时将图片转 Base64",keywords:["export","image","base64","图片"]},{settingId:"prompt-double-click-send",title:"提示词双击发送",keywords:["prompt","double click","send","双击发送"]},{settingId:"prompt-queue",title:"提示词队列",keywords:["prompt","queue","提示词队列","连续提问"]},{settingId:"reading-history-persistence",title:"阅读记录持久化",keywords:["reading history","persistence","持久化"]},{settingId:"reading-history-auto-restore",title:"自动恢复阅读位置",keywords:["reading history","restore","恢复位置"]},{settingId:"reading-history-cleanup-days",title:"阅读记录清理天数",keywords:["reading history","cleanup","days","清理周期"]},{settingId:"content-assistant-mermaid",title:"AI 回复 Mermaid 渲染",keywords:["content","mermaid","diagram","assistant response","AI 回复"]},{settingId:"content-user-query-markdown",title:"用户提问样式优化",keywords:["content","markdown","latex","math","user query","用户提问","数学公式"]},{settingId:"content-formula-copy",title:"公式复制增强",keywords:["content","formula","copy","数学公式"]},{settingId:"content-formula-delimiter",title:"公式分隔符",keywords:["content","formula delimiter","分隔符"]},{settingId:"content-table-copy",title:"表格复制增强",keywords:["content","table copy","复制表格"]},{settingId:"layout-page-width-enabled",title:"页面宽度覆盖",keywords:["layout","page width","页面宽度"]},{settingId:"layout-page-width-value",title:"页面宽度值",keywords:["layout","page width value","页面宽度值"]},{settingId:"layout-user-query-width-enabled",title:"用户问题宽度覆盖",keywords:["layout","user query width","提问宽度"]},{settingId:"layout-user-query-width-value",title:"用户问题宽度值",keywords:["layout","user query width value","提问宽度值"]},{settingId:"layout-zen-mode-enabled",title:"布局:启用禅模式 (Zen Mode)",keywords:["layout","zen mode","禅模式","disclaimer","免责声明","隐藏"]},{settingId:"model-lock-gemini",title:"模型锁定:Gemini",keywords:["model lock","gemini","模型锁定"]},{settingId:"model-lock-gemini-enterprise",title:"模型锁定:Gemini Enterprise",keywords:["model lock","gemini enterprise","模型锁定"]},{settingId:"model-lock-aistudio",title:"模型锁定:AI Studio",keywords:["model lock","aistudio","模型锁定"]},{settingId:"model-lock-chatgpt",title:"模型锁定:ChatGPT",keywords:["model lock","chatgpt","模型锁定"]},{settingId:"model-lock-claude",title:"模型锁定:Claude",keywords:["model lock","claude","模型锁定"]},{settingId:"model-lock-grok",title:"模型锁定:Grok",keywords:["model lock","grok","模型锁定"]},{settingId:"model-lock-qianwen",title:"模型锁定:Qianwen",keywords:["model lock","qianwen","tongyi","通义千问","模型锁定"]},{settingId:"model-lock-qwenai",title:"模型锁定:QwenAI",keywords:["model lock","qwenai","chat.qwen.ai","国际版千问","模型锁定"]},{settingId:"model-lock-yuanbao",title:"模型锁定:Yuanbao",keywords:["model lock","yuanbao","腾讯元宝","模型锁定"]},{settingId:"model-lock-ima",title:"模型锁定:ima",keywords:["model lock","ima","ima.qq.com","腾讯 ima","模型锁定"]},{settingId:"model-lock-zai",title:"模型锁定:Z.ai",keywords:["model lock","z.ai","zai","模型锁定"]},{settingId:"gemini-markdown-fix",title:"Gemini:Markdown 修复",keywords:["gemini","markdown","fix","修复"]},{settingId:"gemini-watermark-removal",title:"Gemini:去水印",keywords:["gemini","watermark","去水印"]},{settingId:"gemini-policy-retry",title:"Gemini:策略重试",keywords:["gemini","policy retry","策略重试"]},{settingId:"gemini-policy-max-retries",title:"Gemini:最大重试次数",keywords:["gemini","max retries","最大重试"]},{settingId:"aistudio-collapse-navbar",title:"AI Studio:折叠左侧导航",keywords:["aistudio","collapse navbar","折叠导航"]},{settingId:"aistudio-collapse-run-settings",title:"AI Studio:折叠 Run settings",keywords:["aistudio","run settings","折叠运行设置"]},{settingId:"aistudio-collapse-tools",title:"AI Studio:折叠 Tools",keywords:["aistudio","tools","折叠工具"]},{settingId:"aistudio-collapse-advanced",title:"AI Studio:折叠 Advanced",keywords:["aistudio","advanced","折叠高级选项"]},{settingId:"aistudio-enable-search",title:"AI Studio:启用搜索",keywords:["aistudio","search","启用搜索"]},{settingId:"aistudio-remove-watermark",title:"AI Studio:去水印",keywords:["aistudio","watermark","去水印"]},{settingId:"aistudio-markdown-fix",title:"AI Studio:Markdown 修复",keywords:["aistudio","markdown","fix","修复"]},{settingId:"chatgpt-markdown-fix",title:"ChatGPT:Markdown 修复",keywords:["chatgpt","markdown","fix","修复"]},{settingId:"claude-session-keys",title:"Claude:Session Keys",keywords:["claude","session key","token","密钥"]},{settingId:"global-search-prompt-enter-behavior",title:"全局搜索:提示词回车行为",keywords:["global search","prompt","enter","全局搜索","提示词","回车"]},{settingId:"global-search-fuzzy-search",title:"Global Search: Enable fuzzy search",keywords:["global search","fuzzy","search everywhere","matching"]},{settingId:"global-search-double-shift",title:"全局搜索:双击 Shift 触发",keywords:["global search","double shift","shortcut","全局搜索","双击 shift","快捷键"]},{settingId:"global-search-shortcut-setting-link",title:"全局搜索:快捷键设置入口",keywords:["global search","shortcut","keybinding","全局搜索","快捷键","键位设置"]},{settingId:"shortcuts-enabled",title:"启用自定义快捷键",keywords:["shortcuts","enable","快捷键","自定义","总开关"]},{settingId:"shortcuts-global-url",title:"全局快捷键 URL",keywords:["shortcuts","global url","alt+g","快捷键","url"]},{settingId:"shortcuts-browser-shortcuts",title:"浏览器快捷键设置入口",keywords:["shortcuts","browser shortcuts","chrome://extensions/shortcuts","快捷键"]},{settingId:"shortcuts-prompt-submit-shortcut",title:"发送快捷键",keywords:["shortcuts","submit","enter","ctrl+enter","发送","快捷键"]},{settingId:"appearance-preset-light",title:"浅色主题预设",keywords:["appearance","theme","light","浅色"]},{settingId:"appearance-preset-dark",title:"深色主题预设",keywords:["appearance","theme","dark","深色"]},{settingId:"appearance-custom-styles",title:"自定义主题样式",keywords:["appearance","custom style","主题样式","css"]},...Object.entries(vn).map(([e,t])=>({settingId:`shortcut-binding-${e}`,title:`快捷键:${t.label}`,keywords:["shortcut","shortcuts","keybinding","hotkey","keyboard","快捷键","键位","按键",t.label,t.labelKey,e,t.category]}))],sr=Object.entries(rr).reduce((e,[t,n])=>(e[n]||(e[n]=[]),e[n].push(t),e),{}),lr=e=>e.trim().toLowerCase(),cr=(e,t)=>{const n=lr(e),r=(e=>lr(e).split(" ").map(e=>e.trim()).filter(e=>e.length>0))(n);return ar.map((e,t)=>{const o=lr(e.title),i=lr((e.keywords||[]).join(" ")),a=lr(e.settingId),s=lr((sr[e.settingId]||[]).join(" ")),l=`${o} ${i} ${a} ${s}`;if(r.some(e=>!l.includes(e)))return null;let c=0;return n?(o===n&&(c+=200),o.startsWith(n)&&(c+=120),o.includes(n)&&(c+=80),i.includes(n)&&(c+=70),a.includes(n)&&(c+=60),s.includes(n)&&(c+=50),r.forEach(e=>{o.startsWith(e)&&(c+=16),o.includes(e)&&(c+=8),i.includes(e)&&(c+=6),a.includes(e)&&(c+=5),s.includes(e)&&(c+=4);}),c+=Math.max(0,24-Math.min(24,o.length))):c=1e3-t,{item:e,score:c,index:t}}).filter(e=>!!e).sort((e,t)=>t.score!==e.score?t.score-e.score:e.index-t.index).map(({item:e})=>e)},dr={[In]:{label:"tabPrompts",icon:"✏️",IconComponent:Ie},[Ln]:{label:"tabConversations",icon:"💬",IconComponent:Le},[Nn]:{label:"tabOutline",icon:"📑",IconComponent:Me},[Dn]:{label:"tabSettings",icon:"⚙️"}},ur={scrollTop:{icon:"⬆",labelKey:"scrollTop",canToggle:false,isPanelOnly:false,IconComponent:Oe},panel:{icon:"✨",labelKey:"panelTitle",canToggle:false,isPanelOnly:true,IconComponent:Et},floatingToolbar:{icon:"🧰",labelKey:"tools",canToggle:true,isPanelOnly:false,IconComponent:({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4",stroke:"currentColor",strokeWidth:"1.5",transform:"rotate(0 12 12)"}), be("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4",stroke:"currentColor",strokeWidth:"1.5",transform:"rotate(60 12 12)"}), be("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4",stroke:"currentColor",strokeWidth:"1.5",transform:"rotate(120 12 12)"}), be("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})]})},globalSearch:{icon:"🔎",labelKey:"navGlobalSearch",canToggle:true,isPanelOnly:false,IconComponent:xt},anchor:{icon:"⚓",canToggle:true,labelKey:"showCollapsedAnchorLabel",isPanelOnly:false,IconComponent:Se},theme:{icon:"☀",labelKey:"showCollapsedThemeLabel",canToggle:true,isPanelOnly:false},manualAnchor:{icon:"📍",labelKey:"manualAnchorLabel",canToggle:true,isPanelOnly:false,isGroup:true,IconComponent:({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ be("path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}), be("line",{x1:"12",y1:"7",x2:"12",y2:"13"}), be("line",{x1:"9",y1:"10",x2:"15",y2:"10"})]})},scrollBottom:{icon:"⬇",labelKey:"scrollBottom",canToggle:false,isPanelOnly:false,IconComponent:ze}},hr=["📁","📂","📥","🗂️","📊","📈","📉","📋","💼","📅","📌","📎","📝","✒️","🔍","💡","💻","⌨️","🖥️","🖱️","🐛","🔧","🔨","⚙️","🤖","👾","🧠","⚡","🔥","✨","🎓","📚","🎨","🎭","🎬","🎹","🎵","📷","🖌️","🖍️","🏠","🛒","✈️","🎮","⚽","🍔","☕","❤️","🔴","🟠","🟡","🟢","🔵","🟣","⚫","⚪","⭐","🌟","🎉","🔒","🔑","🚫","✅","❓"],gr=["#FF461F","#FF6B6B","#FA8072","#DC143C","#CD5C5C","#FF4500","#FFA500","#FFB347","#F0E68C","#DAA520","#FFD700","#9ACD32","#32CD32","#3CB371","#20B2AA","#00CED1","#5F9EA0","#4682B4","#6495ED","#4169E1","#0000CD","#8A2BE2","#9370DB","#BA55D3","#DB7093","#C71585","#8B4513","#A0522D","#708090","#2F4F4F"],pr=1500,mr=2e3,fr=3e3,br="#10b981",yr="#ef4444",vr="var(--gh-text-secondary)",wr=[{id:"default",labelKey:"notificationSoundPresetDefault",fallback:"Default"},{id:"softChime",labelKey:"notificationSoundPresetSoftChime",fallback:"Soft Chime"},{id:"glassPing",labelKey:"notificationSoundPresetGlassPing",fallback:"Glass Ping"},{id:"brightAlert",labelKey:"notificationSoundPresetBrightAlert",fallback:"Bright Alert"}],xr=["settings","prompts","folders","tags","conversations","readingHistory"],kr=["conversations","readingHistory"],Sr=()=>[{id:"default_1",title:re("defaultPromptCodeOptTitle")||"代码优化",content:re("defaultPromptCodeOptContent")||"请帮我优化以下代码,提高性能和可读性:\n\n",category:re("defaultPromptCodeOptCategory")||"编程"},{id:"default_2",title:re("defaultPromptTranslateTitle")||"翻译助手",content:re("defaultPromptTranslateContent")||"请将以下内容翻译成中文,保持专业术语的准确性:\n\n",category:re("defaultPromptTranslateCategory")||"翻译"}],Cr=[{id:"inbox",name:"收件箱",icon:"📥",isDefault:true}],Er={DEFAULT_PX:"1280",DEFAULT_PERCENT:"81",MIN_PERCENT:40,MAX_PERCENT:100,MIN_PX:1200},_r={DEFAULT_PX:"600",DEFAULT_PERCENT:"81",MIN_PERCENT:40,MAX_PERCENT:100,MIN_PX:600},Ar={CLAUDE_KEY:/^sk-ant-sid\d{2}-/},Tr=500,Mr="claude",Ir="gemini",Nr="chatgpt",Lr="chatglm",Dr="gemini-enterprise",Rr="grok",qr="aistudio",Pr="doubao",Br="ima",Or="deepseek",zr="kimi",Fr="qianwen",jr="qwenai",$r="yuanbao",Hr="zai",Ur=[{id:Nr,name:"ChatGPT",pattern:/chatgpt\.com/,url:"https://chatgpt.com",icon:"💬"},{id:Ir,name:"Gemini",pattern:/gemini\.google\.com/,url:"https://gemini.google.com",icon:"🌟"},{id:Mr,name:"Claude",pattern:/claude\.(ai|com)/,url:"https://claude.ai",icon:"🎭"},{id:qr,name:"AI Studio",pattern:/aistudio\.google\.com/,url:"https://aistudio.google.com",icon:"🧪"},{id:Dr,name:"Gemini Enterprise",pattern:/business\.gemini\.google/,url:"https://business.gemini.google",icon:"🏢"},{id:Rr,name:"Grok",pattern:/grok\.com/,url:"https://grok.com",icon:"🤖"},{id:Pr,name:"Doubao",pattern:/www\.doubao\.com/,url:"https://www.doubao.com",icon:"🌱"},{id:Or,name:"DeepSeek",pattern:/chat\.deepseek\.com/,url:"https://chat.deepseek.com",icon:"🌀"},{id:zr,name:"Kimi",pattern:/www\.kimi\.com/,url:"https://www.kimi.com",icon:"🌙"},{id:Hr,name:"Z.ai",pattern:/chat\.z\.ai/,url:"https://chat.z.ai",icon:"⚡"},{id:Lr,name:"ChatGLM",pattern:/chatglm\.cn/,url:"https://chatglm.cn/main/alltoolsdetail?lang=zh",icon:"🧠"},{id:$r,name:"Yuanbao",pattern:/yuanbao\.tencent\.com/,url:"https://yuanbao.tencent.com",icon:"💎"},{id:Fr,name:"Qianwen",pattern:/www\.qianwen\.com/,url:"https://www.qianwen.com",icon:"🔮"},{id:jr,name:"QwenAI",pattern:/chat\.qwen\.ai/,url:"https://chat.qwen.ai",icon:"🪄"},{id:Br,name:"ima",pattern:/ima\.qq\.com/,url:"https://ima.qq.com",icon:"🐼"}],Wr="__all__",Vr="__recent__",Gr="export",Qr="copyMarkdown",Kr="move",Zr="setTag",Yr="scrollLock",Jr="modelLock",Xr="cleanup",eo="settings",to=[{id:Gr,labelKey:"export",defaultLabel:"Export",IconComponent:Re,defaultVisible:true},{id:Qr,labelKey:"exportToClipboard",defaultLabel:"Copy Markdown",IconComponent:lt,defaultVisible:true},{id:Kr,labelKey:"conversationsMoveTo",defaultLabel:"Move",IconComponent:Ce,defaultVisible:true},{id:Zr,labelKey:"conversationsSetTag",defaultLabel:"Set Tag",IconComponent:gt,defaultVisible:true},{id:Yr,labelKey:"shortcutToggleScrollLock",defaultLabel:"Scroll Lock",IconComponent:({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[ be("path",{d:"M12 3v12"}), be("path",{d:"m8 11 4 4 4-4"}), be("path",{d:"M19 19H5"}), be("circle",{cx:"12",cy:"11",r:"9",strokeOpacity:"0.3"}), be("path",{d:"m4.9 4.9 14.2 14.2"})]}),isToggle:true,defaultVisible:true},{id:Jr,labelKey:"modelLockTitle",defaultLabel:"Model Lock",IconComponent:({size:e=18,color:t="currentColor",className:n=""})=>ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[ be("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}), be("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}), be("circle",{cx:"9",cy:"15",r:"1.5",fill:t,stroke:"none"}), be("circle",{cx:"15",cy:"15",r:"1.5",fill:t,stroke:"none"}), be("path",{d:"M9 19h6"})]}),isToggle:true,defaultVisible:true},{id:Xr,labelKey:"cleanup",defaultLabel:"Cleanup",IconComponent:ht,isDanger:true,defaultVisible:true},{id:eo,labelKey:"tabSettings",defaultLabel:"Settings",IconComponent:_e,isSystem:true,defaultVisible:true}],no=e=>{let t;const n=new Set,r=(e,r)=>{const o="function"==typeof e?e(t):e;if(!Object.is(o,t)){const e=t;t=(null!=r?r:"object"!=typeof o||null===o)?o:Object.assign({},t,o),n.forEach(n=>n(t,e));}},o=()=>t,i={setState:r,getState:o,getInitialState:()=>a,subscribe:e=>(n.add(e),()=>n.delete(e))},a=t=e(r,o,i);return i},ro=e=>e;const oo=e=>{const t=(e=>e?no(e):no)(e),n=e=>function(e,t=ro){const n=o.useSyncExternalStore(e.subscribe,o.useCallback(()=>t(e.getState()),[e,t]),o.useCallback(()=>t(e.getInitialState()),[e,t]));return o.useDebugValue(n),n}(t,e);return Object.assign(n,t),n},io=e=>oo;function ao(e,t){let n;try{n=e();}catch(r){return}return {getItem:e=>{var t;const r=e=>null===e?null:JSON.parse(e,void 0),o=null!=(t=n.getItem(e))?t:null;return o instanceof Promise?o.then(r):r(o)},setItem:(e,t)=>n.setItem(e,JSON.stringify(t,void 0)),removeItem:e=>n.removeItem(e)}}const so=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then:e=>so(e)(n),catch(e){return this}}}catch(n){return {then(e){return this},catch:e=>so(e)(n)}}},lo=(e,t)=>(n,r,o)=>{let i={storage:ao(()=>localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},a=false,s=0;const l=new Set,c=new Set;let d=i.storage;if(!d)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...e);},r,o);const u=()=>{const e=i.partialize({...r()});return d.setItem(i.name,{state:e,version:i.version})},h=o.setState;o.setState=(e,t)=>(h(e,t),u());const g=e((...e)=>(n(...e),u()),r,o);let p;o.getInitialState=()=>g;const m=()=>{var e,t;if(!d)return;const o=++s;a=false,l.forEach(e=>{var t;return e(null!=(t=r())?t:g)});const h=(null==(t=i.onRehydrateStorage)?void 0:t.call(i,null!=(e=r())?e:g))||void 0;return so(d.getItem.bind(d))(i.name).then(e=>{if(e){if("number"!=typeof e.version||e.version===i.version)return [false,e.state];if(i.migrate){const t=i.migrate(e.state,e.version);return t instanceof Promise?t.then(e=>[true,e]):[true,t]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided");}return [false,void 0]}).then(e=>{var t;if(o!==s)return;const[a,l]=e;return p=i.merge(l,null!=(t=r())?t:g),n(p,true),a?u():void 0}).then(()=>{o===s&&(null==h||h(p,void 0),p=r(),a=true,c.forEach(e=>e(p)));}).catch(e=>{o===s&&(null==h||h(void 0,e));})};return o.persist={setOptions:e=>{i={...i,...e},e.storage&&(d=e.storage);},clearStorage:()=>{null==d||d.removeItem(i.name);},getOptions:()=>i,rehydrate:()=>m(),hasHydrated:()=>a,onHydrate:e=>(l.add(e),()=>{l.delete(e);}),onFinishHydration:e=>(c.add(e),()=>{c.delete(e);})},i.skipHydration||m(),p||g};const co=true;new class{area;constructor(e){this.area=e?.area||"local";}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);}async getAll(){return console.warn("[Storage Polyfill] getAll() is not supported in userscript"),{}}async setMany(e){for(const[t,n]of Object.entries(e))GM_setValue(t,n);}watch(e){if("string"==typeof e){const t=GM_addValueChangeListener(e,(e,t,n,r)=>{});return ()=>GM_removeValueChangeListener(t)}{const t=[];for(const[n,r]of Object.entries(e)){const e=GM_addValueChangeListener(n,(e,t,n,o)=>{r({newValue:n,oldValue:t});});t.push(e);}return ()=>t.forEach(e=>GM_removeValueChangeListener(e))}}}({area:"local"});const uo="ophel:clearAllFlag",ho="ophel_skip_restore",go={mode:"light",lightStyleId:"google-gradient",darkStyleId:"classic-dark"},po={enabled:false,value:"1280",unit:"px"},mo={enabled:false,value:"600",unit:"px"},fo={enabled:false},bo={language:"auto",hasAgreedToTerms:false,panel:{defaultOpen:true,autoHide:false,edgeSnap:true,preventAutoScroll:false,defaultPosition:"right",defaultEdgeDistance:25,edgeSnapThreshold:18,height:85,width:320},geminiEnterprise:{policyRetry:{enabled:false,maxRetries:3}},content:{assistantMermaid:true,markdownFix:true, // 油猴脚本环境默认开启(GM_xmlhttpRequest 已通过 @grant 声明) watermarkRemoval:co,formulaCopy:true,formulaDelimiter:true,tableCopy:true,exportImagesToBase64:false,userQueryMarkdown:true},export:{customUserName:"",customModelName:"",exportFilenameTimestamp:false,includeThoughts:true},theme:{sites:{gemini:{...go},"gemini-enterprise":{...go},doubao:{...go},ima:{...go},deepseek:{...go},yuanbao:{...go},zai:{...go},_default:{...go}},customStyles:[]},layout:{pageWidth:{gemini:{...po},"gemini-enterprise":{...po},aistudio:{...po},doubao:{...po},ima:{...po},deepseek:{...po},yuanbao:{...po},zai:{...po},_default:{...po}},userQueryWidth:{gemini:{...mo},"gemini-enterprise":{...mo},aistudio:{...mo},doubao:{...mo},ima:{...mo},deepseek:{...mo},yuanbao:{...mo},zai:{...mo},_default:{...mo}},zenMode:{gemini:{...fo},"gemini-enterprise":{...fo},aistudio:{...fo},doubao:{...fo},ima:{...fo},deepseek:{...fo},yuanbao:{...fo},zai:{...fo},_default:{...fo}}},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},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:true,autoRename:true,renameInterval:3,showStatus:true,titleFormat:"{status}{title}->{model}", // 油猴脚本环境默认开启(GM_notification 已通过 @grant 声明) showNotification:co,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:30},collapsedButtons:[{id:"panel",enabled:true},{id:"floatingToolbar",enabled:true},{id:"globalSearch",enabled:true},{id:"theme",enabled:true},{id:"scrollTop",enabled:true},{id:"manualAnchor",enabled:false},{id:"anchor",enabled:true},{id:"scrollBottom",enabled:true}],quickButtonsOpacity:1,floatingToolbar:{open:true},claude:{currentKeyId:""},webdav:{enabled:false,url:"",username:"",password:"",syncMode:"manual",syncInterval:30,remoteDir:"ophel",dataSources:["settings","conversations","prompts","claudeSessionKeys"]},shortcuts:kn,aistudio:{collapseNavbar:false,collapseTools:false,collapseAdvanced:false,enableSearch:true,defaultModel:"",markdownFix:co,removeWatermark:co},chatgpt:{markdownFix:true}};function yo(e,t){const n=e.theme?.sites;return n&&t in n?n[t]:n?._default??go}function vo(e,t){const n=e.layout?.pageWidth;return n&&t in n?n[t]:n?._default??po}function wo(e,t){return e.modelLock?.[t]??{enabled:false,keyword:""}}function xo(e,t){const n=e.layout?.userQueryWidth;return n&&t in n?n[t]:n?._default??mo}function ko(e,t){const n=e.layout?.zenMode;return n&&t in n?n[t]:n?._default??fo}let So=null;const Co="ophel:restoreFlag";let Eo=null;function _o(){if("undefined"==typeof window)return false;const e=new URL(window.location.href);if("1"!==e.searchParams.get(ho))return false;e.searchParams.delete(ho);const t=`${e.pathname}${e.search}${e.hash}`||window.location.pathname+window.location.search+window.location.hash;return window.history.replaceState(window.history.state,"",t),true}const Ao={getItem:e=>{const t=GM_getValue(e);return null==t?null:"string"==typeof t?t:JSON.stringify(t)},setItem:(e,t)=>{GM_setValue(e,t);},removeItem:e=>{GM_deleteValue(e);}},To=e=>({...e,content:{...bo.content,...e.content},usageMonitor:{...bo.usageMonitor,...e.usageMonitor},shortcuts:An(e.shortcuts)||bo.shortcuts}),Mo=e=>"object"!=typeof e||null===e?JSON.stringify(e):Array.isArray(e)?JSON.stringify(e.map(Mo)):JSON.stringify(Object.keys(e).sort().reduce((t,n)=>(t[n]=Mo(e[n]),t),{})),Io={...Ao,setItem:async(e,t)=>Ao.setItem(e,t)},No=io()(lo((e,t)=>({settings:bo,_hasHydrated:false,_syncVersion:0,setSettings:t=>e(e=>({settings:To({...e.settings,...t})})),updateNestedSetting:(t,n,r)=>e(e=>({settings:{...e.settings,[t]:{...e.settings[t],[n]:r}}})),updateDeepSetting:(t,n,r,o)=>e(e=>{const i=e.settings[t],a=i?.[n]||{};return {settings:{...e.settings,[t]:{...i,[n]:{...a,[r]:o}}}}}),replaceSettings:t=>e({settings:To({...bo,...t})}),resetSettings:()=>e({settings:To(bo)}),setHasHydrated:t=>e({_hasHydrated:t})}),{name:"settings",storage:ao(()=>Io),partialize:e=>({settings:e.settings}),onRehydrateStorage:()=>e=>{if(e){const t=To(e.settings);Mo(t)!==Mo(e.settings)&&No.setState({settings:t});}No.setState({_hasHydrated:true});}})),Lo=()=>No(e=>e._hasHydrated),Do=()=>No.getState().settings,Ro=e=>No.subscribe(t=>e(t.settings)),qo=Object.freeze(Object.defineProperty({__proto__:null,getSettingsState:Do,subscribeSettings:Ro,useSettingsHydrated:Lo,useSettingsStore:No},Symbol.toStringTag,{value:"Module"})),Po=new Map,Bo=5e3;function Oo(e,t=2e3,n={}){const r=document.getElementById("gh-toast");if(r&&r.remove(),!document.getElementById("gh-toast-style")){const e=document.createElement("style");e.id="gh-toast-style",e.textContent="\n .gh-toast {\n position: fixed !important;\n top: 32px !important;\n left: 50% !important;\n transform: translateX(-50%) !important;\n background: var(--gh-brand-gradient);\n color: white;\n border: none;\n padding: 10px 24px;\n border-radius: 9999px;\n font-size: 14px;\n font-weight: 500;\n box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.15), 0 8px 10px -6px rgba(0, 0, 0, 0.1);\n z-index: 2147483647;\n pointer-events: none;\n opacity: 0;\n transition: opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1);\n font-family: 'Google Sans', Roboto, sans-serif;\n }\n .gh-toast.show {\n opacity: 1;\n }\n .gh-toast--outline-nav {\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n max-width: 360px;\n }\n ",document.head.appendChild(e);}const o=document.createElement("div");o.id="gh-toast",o.className="gh-toast",n.className&&o.classList.add(n.className),n.maxWidth&&Number.isFinite(n.maxWidth)&&(o.style.maxWidth=`${n.maxWidth}px`),o.textContent=e,document.body.appendChild(o),requestAnimationFrame(()=>{o.classList.add("show");}),setTimeout(()=>{o.classList.remove("show"),setTimeout(()=>{o.parentNode&&o.parentNode.removeChild(o);},300);},t);}function zo(e,t=2e3,n={},r=1500,o=e){const i=Date.now();i-(Po.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`},i=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():""},a=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(a).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"),i=[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 a of i){const e=n(a);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(a(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(a(o)).replace(/\n+$/,"");if(n.trim())return {lang:s(e),code:n}}if(!n){const n=t(a(e)).replace(/\n+$/,"");if(n.trim())return {lang:s(e),code:n}}return null},c=(e,t)=>Array.from(e.childNodes).map(e=>h(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)=>u(e,t,n?r+1:null)).filter(Boolean).join("\n");return r?`\n${r}\n\n`:""},u=(e,n,r)=>{const o=" ".repeat(n),i=null===r?"-":`${r}.`,a=[],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}}a.push(h(t,{listDepth:n,inListItem:true}));}const l=(c=a.join(""),t(c).replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").trim());var c;let u=l?((e,n,r)=>{const o=t(e).split("\n"),[i="",...a]=o;return 0===a.length?`${n}${i}`:[`${n}${i}`,...a.map(e=>e?`${r}${e}`:"")].join("\n")})(l,`${o}${i} `,`${o} `):`${o}${i}`;return s.length>0&&(u=`${u.trimEnd()}\n${s.join("\n")}`),u},h=(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=i(n);if(e)return o(e)}if(n.classList?.contains("katex")){const e=i(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 a=n.tagName?.toLowerCase()||"";if(!a)return "";if("annotation"===a||"annotation-xml"===a)return "";if("style"===a||"script"===a||"template"===a||"noscript"===a)return "";if("img"===a){const e=n.alt||n.getAttribute("alt")||"图片";return `![${e}](${n.src||n.getAttribute("src")||""})`}if("code-block"===a){const e=l(n);if(e)return `\n\`\`\`${e.lang}\n${e.code}\n\`\`\`\n`}if("pre"===a){const e=l(n);if(e)return `\n\`\`\`${e.lang}\n${e.code}\n\`\`\`\n`}if("code"===a)return "pre"===n.parentElement?.tagName.toLowerCase()?"":`\`${n.textContent}\``;if("table"===a){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"===a||"ucs-markdown-table"===a){const e=n.querySelector("table");if(e)return h(e)}switch(a){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.href||""})`;case "li":return u(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=>h(e,t)).join(""):c(n,t)}}catch(n){return console.error("Error processing node in htmlToMarkdown:",n),e.textContent||""}};return h(e).trim()}function Wo(e,t){const n=[];return n.push(`# ${e.title}`),n.push(""),n.push("---"),n.push(""),n.push(`## ${jo} ${re("exportMetaTitle")}`),n.push(`- **${re("exportMetaConvTitle")}**: ${e.title}`),n.push(`- **${re("exportMetaTime")}**: ${e.exportTime}`),n.push(`- **${re("exportMetaSource")}**: ${e.source}`),n.push(`- **${re("exportMetaUrl")}**: ${e.url}`),n.push(""),n.push("---"),n.push(""),t.forEach(t=>{if("user"===t.role){const r=e.customUserName||re("exportUserLabel");n.push(`## ${$o} ${r}`),n.push(""),n.push(t.content),n.push(""),n.push("---"),n.push("");}else {const r=e.customModelName||e.source;n.push(`## ${Ho} ${r}`),n.push(""),n.push(t.content),n.push(""),n.push("---"),n.push("");}}),n.join("\n")}const Vo={MAX_DEPTH:15,DEFAULT_TIMEOUT:5e3,POLL_INTERVAL:50,CACHE_TTL:3e5},Go={ELEMENT:1,DOCUMENT:9,FRAGMENT:11},Qo=["keydown","keypress","keyup"],Ko=e=>e instanceof HTMLElement&&("INPUT"===e.tagName||"TEXTAREA"===e.tagName||"SELECT"===e.tagName||e.isContentEditable||"true"===e.getAttribute("contenteditable")||e.classList.contains("ProseMirror")),Zo=(e,t={})=>{const{events:n=Qo,capture:r=true}=t,o=e=>{(e=>{const t=("function"==typeof e.composedPath?e.composedPath():[]).find(e=>e instanceof HTMLElement)||null;return Ko(t)?t:Ko(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);});}},Yo={isValidContext:e=>null!==e&&Object.values(Go).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 Jo{enabled=true;ttl;store=new WeakMap;timestamps=new WeakMap;constructor(e=Vo.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 i=r.get(t);return i&&Date.now()-i>this.ttl?(n.delete(t),r.delete(t),null):Yo.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 Xo{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===Go.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 ei=new class{cache;observerManager;doc;constructor(){this.doc=document,this.cache=new Jo,this.observerManager=new Xo;}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:i=Vo.MAX_DEPTH,useCache:a=true,filter:s=null}=t,l=Array.isArray(e)?e:[e],c=a&&!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,i,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,i,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 a of t)try{const t=e.querySelectorAll(a);for(const e of t)if(!o||o(e))return e}catch{}const i=e.querySelectorAll?e.querySelectorAll("*"):[];for(const a of i)if(a.shadowRoot){const e=this.findInShadow(a.shadowRoot,t,n+1,r,o);if(e)return e}return null}collectInShadow(e,t,n,r,o,i){if(r>o)return;if(e!==this.doc&&e.querySelectorAll)try{const r=e.querySelectorAll(t);for(const e of r)n.includes(e)||i&&!i(e)||n.push(e);}catch{}const a=e.querySelectorAll?e.querySelectorAll("*"):[];for(const s of a)s.shadowRoot&&this.collectInShadow(s.shadowRoot,t,n,r+1,o,i);}async get(e,t={}){const{parent:n=this.doc,timeout:r=Vo.DEFAULT_TIMEOUT,shadow:o=true,filter:i=null}=t,a=this.query(e,{parent:n,shadow:o,filter:i});return a&&!Array.isArray(a)?a:new Promise(t=>{const a=Yo.createCleanupManager(),s=Date.now();let l;r>0&&(l=setTimeout(()=>{a.execute(),t(null);},r),a.add(()=>clearTimeout(l)));const c=()=>{if(r>0&&Date.now()-s>=r)return;const l=this.query(e,{parent:n,shadow:o,filter:i});if(l&&!Array.isArray(l))return a.execute(),void t(l);const d=setTimeout(c,Vo.POLL_INTERVAL);a.add(()=>clearTimeout(d));},d=Array.isArray(e)?e:[e],u=this.observerManager.getSharedObserver(n),h=e=>{for(const n of d)try{if(e.matches?.(n)&&(!i||i(e)))return a.execute(),void t(e);if(e.querySelectorAll){const r=e.querySelectorAll(n);for(const e of r)if(!i||i(e))return a.execute(),void t(e)}}catch{}};u.addCallback(h),a.add(()=>u.removeCallback(h)),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 i=new WeakSet;let a=true;const s=(e,n)=>{if(a&&!i.has(e)){i.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(a)try{t.matches?.(e)&&s(t,!0),t.querySelectorAll&&t.querySelectorAll(e).forEach(e=>s(e,!0));}catch{}};l.addCallback(c);const d=()=>{a&&(a=false,l.removeCallback(c));};return d}watch(e,t,n={}){const{debounce:r=0,childList:o=true,attributes:i=true,characterData:a=false,subtree:s=false,attributeFilter:l}=n;if(!Yo.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:i,characterData:a,subtree:s,attributeFilter:l}),()=>{c&&clearTimeout(c),d.disconnect();}}watchMultiple(e,t={}){const{debounce:n=0,characterData:r=true,childList:o=true,attributes:i=false}=t;if(!Yo.isValidContext(e))return console.error("[DOMToolkit] watchMultiple: invalid container"),{add:()=>{},remove:()=>{},stop:()=>{}};const a=new Map;let s=null;const l=new Set,c=()=>{l.forEach(e=>{const t=a.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(a.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:i,subtree:true}),{add:(e,t)=>a.set(e,t),remove:e=>a.delete(e),stop:()=>{s&&clearTimeout(s),d.disconnect(),a.clear();}}}on(e,t,n,r={}){const{parent:o=this.doc,capture:i=false}=r,a=e=>{const r=e.composedPath?e.composedPath():[e.target];for(const i of r){if(i===o||i===window)break;try{if(i.matches?.(t))return void n(e,i)}catch{}}try{const r=e.target.closest?.(t);r&&o.contains(r)&&n(e,r);}catch{}};return o.addEventListener(e,a,i),()=>o.removeEventListener(e,a,i)}create(e,t={},n=""){const r=this.doc.createElement(e);for(const[o,i]of Object.entries(t))"className"===o?r.className=i:"style"===o&&"object"==typeof i?Object.assign(r.style,i):"style"===o?r.setAttribute("style",i):"dataset"===o&&"object"==typeof i?Object.assign(r.dataset,i):o.startsWith("on")&&"function"==typeof i?r.addEventListener(o.slice(2).toLowerCase(),i):r.setAttribute(o,i);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 i=o.content.firstElementChild;if(!i)return null;if(n instanceof Element&&n.appendChild(i),r){const e={root:i};return i.id&&(e[i.id]=i),i.querySelectorAll("[id]").forEach(t=>{t.id&&(e[t.id]=t);}),e}return i}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 i=0;const a=n=>{if(n.shadowRoot){if(o&&!o(n));else try{this.cssToShadow(n.shadowRoot,e,t),i++;}catch{}try{a(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(a){console.error("[DOMToolkit] walkShadowRoots callback error:",a);}try{o(t.shadowRoot,n+1);}catch{}}const i=t.childNodes;for(let e=0;ee.clientHeight)return e}const o=(e,t)=>{if(t>Vo.MAX_DEPTH)return null;const n=e.querySelectorAll?e.querySelectorAll("*"):[];for(const i of n){if(i.scrollHeight>i.clientHeight+r){const e=window.getComputedStyle(i);if("auto"===e.overflowY||"scroll"===e.overflowY||"auto"===e.overflow||"scroll"===e.overflow)return i}if(i.shadowRoot){const e=o(i.shadowRoot,t+1);if(e)return e}}return null},i=o(t,0);return i||(this.doc.documentElement.scrollHeight>this.doc.documentElement.clientHeight?this.doc.documentElement:this.doc.body)}destroy(){this.observerManager.destroy(),this.cache.clear();}},ti=[/^flowchart\b/i,/^graph\b/i,/^sequenceDiagram\b/i,/^classDiagram(?:-v2)?\b/i,/^stateDiagram(?:-v2)?\b/i,/^erDiagram\b/i,/^gantt\b/i,/^gitGraph\b/i],ni=[{pattern:/^flow\s*-?\s*chart\b/i,replacement:"flowchart"},{pattern:/^sequence\s*-?\s*diagram\b/i,replacement:"sequenceDiagram"},{pattern:/^class\s*-?\s*diagram(?:\s*-\s*|\s+)v2\b/i,replacement:"classDiagram-v2"},{pattern:/^class\s*-?\s*diagram\b/i,replacement:"classDiagram"},{pattern:/^state\s*-?\s*diagram(?:\s*-\s*|\s+)v2\b/i,replacement:"stateDiagram-v2"},{pattern:/^state\s*-?\s*diagram\b/i,replacement:"stateDiagram"},{pattern:/^er\s*-?\s*diagram\b/i,replacement:"erDiagram"},{pattern:/^git\s*-?\s*graph\b/i,replacement:"gitGraph"}];function ri(e){const t=e.matches("code")?e:e.querySelector("code"),n=[e.getAttribute("data-language"),e.getAttribute("data-test-language"),t?.getAttribute("data-language"),t?.getAttribute("data-test-language"),e.className,t?.className].filter(Boolean).join(" ").toLowerCase();return n.includes("language-mermaid")||n.includes("lang-mermaid")||/\bmermaid\b/.test(n)}function oi(e){const t=ii(e);if(!t)return false;const n=t.split("\n").map(e=>e.trim()).find(e=>e&&!e.startsWith("%%"));return !!n&&ti.some(e=>e.test(n))}function ii(e){const t=e.replace(/\r\n/g,"\n").replace(/\n+$/,"").trim();if(!t)return "";const n=t.split("\n"),r=function(e){return e.findIndex(e=>{const t=e.trim();return Boolean(t)&&!t.startsWith("%%")})}(n);if(-1===r)return t;const o=n[r],i=o.trim(),a=o.match(/^\s*/)?.[0]||"";for(const{pattern:s,replacement:l}of ni){const e=i.match(s);if(e)return n[r]=`${a}${l}${i.slice(e[0].length)}`,n.join("\n")}return t}function ai(e){const t=e.matches("code")?e:e.querySelector("code");return (t?.textContent||e.textContent||"").replace(/\r\n/g,"\n").replace(/\n+$/,"").trim()||null}function si(e){const t=e.closest("code-block, ms-code-block, ucs-code-block");if(t)return t;const n=e.closest("pre");if(n)return n;const r=e.closest(".cm-editor, #code-block-viewer");return r||e}function li(e){const t=ei.query("code-block, ms-code-block, pre, pre code, [data-language], [data-test-language], [data-test-id='code-content'], .cm-content, #code-block-viewer",{parent:e,all:true,shadow:true})||[],n=new Set,r=[];for(const o of t){if(!(o instanceof HTMLElement))continue;if(o.closest(".gh-assistant-mermaid"))continue;const e=si(o);if(!e||n.has(e))continue;const t=ai(e);t&&((ri(e)||oi(t))&&(n.add(e),r.push({element:e,source:t})));}return r}class ci{textarea=null;_cachedFlutterScrollContainer=null;getSessionId(){const e=window.location.href.split("?")[0].split("/").filter(e=>e);return e.length>0?e[e.length-1]:"default"}supportsNewTab(){return true}getNewTabUrl(){return window.location.origin}supportsTabRename(){return true}getSessionName(){const e=document.title;if(e){const t=e.split(" - ");return t.length>1?t.slice(0,-1).join(" - ").trim():e.trim()}return null}isNewConversation(){return false}isSharePage(){return window.location.pathname.startsWith("/share/")} /** * 获取当前团队 ID(用于会话隔离) * 仅在支持多团队的站点(如 Gemini Enterprise)中实现 * @returns 团队 ID 或 null(无团队/默认团队) */getCurrentCid(){return null}getConversationList(){return []}getCurrentConversationInfo(){const e=this.getSessionId();return !e||"default"===e||this.isNewConversation()?null:{id:e,title:this.getConversationTitle()||this.getSessionName()||"",url:window.location.href,cid:this.getCurrentCid()||void 0}}getSidebarScrollContainer(){return null}getConversationObserverConfig(){return null} /** * 导航到指定会话(SPA 导航,不刷新页面) * 各站点适配器应覆盖此方法实现站点特定的导航逻辑 * @param id 会话 ID * @param url 会话 URL(用于降级硬刷新) * @returns 是否成功导航 */navigateToConversation(e,t){return !!t&&(window.location.href=t,true)}async deleteConversationOnSite(e){return {id:e.id,success:false,method:"none",reason:"not_supported"}}async deleteConversationsOnSite(e){const t=[];for(const n of e)t.push(await this.deleteConversationOnSite(n));return t}async loadAllConversations(){const e=this.getSidebarScrollContainer();if(!e)return;let t=0,n=0;for(;n<3;){e.scrollTop=e.scrollHeight,await new Promise(e=>setTimeout(e,500));const r=(ei.query(".conversation",{all:true,shadow:true})||[]).length;r===t?n++:(t=r,n=0);}}isGenerating(){return false}requiresDomConfirmationForNetworkGeneration(){return false}getModelName(){return null}getModelLockCheckText(e){return e?.textContent||e?.innerText||""}getNetworkMonitorConfig(){return null} /** * 切换站点主题(子类可覆盖以实现站点特定的主题切换逻辑) * @param targetMode 目标主题模式 * @returns 是否成功切换 */async toggleTheme(e){return false}getNativeThemeCss(){return null}getWidthSelectors(){return []}getUserQueryWidthSelectors(){return []}getZenModeSelectors(){return []}getMarkdownFixerConfig(){return null}getAssistantMermaidSupportMode(){return "native"}getAssistantMermaidBlocks(e){return li(e)}getSubmitButtonSelectors(){return []}findSubmitButton(e){return null} /** * 获取发送消息的快捷键配置 * 子类可覆盖以适配不同平台的发送键设置 * @returns 发送键配置:key 为 "Enter" 或 "Ctrl+Enter" */getSubmitKeyConfig(){return {key:"Enter"}}findTextarea(){for(const e of this.getTextareaSelectors()){const t=document.querySelectorAll(e);for(const e of Array.from(t))if(this.isValidTextarea(e))return this.textarea=e,e}return null}isValidTextarea(e){return !e.closest(".gh-main-panel")&&!e.closest(".gh-queue-panel")&&(!Array.from(e.classList).some(e=>e.startsWith("gh-queue-")||e.startsWith("gh-"))&&null!==e.offsetParent)}clearTextarea(){this.textarea&&(this.textarea instanceof HTMLInputElement||this.textarea instanceof HTMLTextAreaElement?this.textarea.value="":this.textarea.textContent="",this.textarea.dispatchEvent(new Event("input",{bubbles:true})));}getTextareaElement(){return this.textarea&&this.textarea.isConnected?this.textarea:this.findTextarea()}getScrollContainer(){const e=["infinite-scroller.chat-history",".chat-mode-scroller","main",'[role="main"]',".conversation-container",".chat-container","div.content-container"];for(const n of e){const e=document.querySelector(n);if(e&&e.scrollHeight>e.clientHeight)return this._cachedFlutterScrollContainer=null,e}if(this._cachedFlutterScrollContainer&&this._cachedFlutterScrollContainer.isConnected)return this._cachedFlutterScrollContainer;if(this.getSiteId()===Ir){const e=document.querySelectorAll('iframe[sandbox*="allow-same-origin"]');for(const n of Array.from(e))try{const e=n.contentDocument||n.contentWindow?.document;if(e){const t=e.querySelector('flt-semantics[style*="overflow-y: scroll"]:not([style*="overflow-x: scroll"])');if(t&&t.scrollHeight>t.clientHeight)return this._cachedFlutterScrollContainer=t,t}}catch(t){console.warn("[Ophel] Failed to access iframe:",t.message);}}return null}getVisibleAnchorElement(){const e=this.getScrollContainer();if(!e)return null;const t=e.scrollTop,n=this.getChatContentSelectors();if(!n.length)return null;const r=Array.from(e.querySelectorAll(n.join(", ")));if(!r.length)return null;let o=null;for(let i=0;i0&&(o=r[0]),o){const e=t-o.offsetTop,n=o.getAttribute("data-message-id")||o.id;if(n){let t=`[data-message-id="${n}"]`;return o.matches(t)||(t=`#${n}`),{type:"selector",selector:t,offset:e}}{const t=r.indexOf(o);if(-1!==t){return {type:"index",index:t,offset:e,textSignature:(o.textContent||"").trim().substring(0,50)}}}}return null}restoreScroll(e){const t=this.getScrollContainer();if(!t||!e)return false;let n=null;if("selector"===e.type&&e.selector)n=t.querySelector(e.selector);else if("index"===e.type&&"number"==typeof e.index){const r=this.getChatContentSelectors(),o=Array.from(t.querySelectorAll(r.join(", ")));if(o[e.index]){if(n=o[e.index],e.textSignature){if((n.textContent||"").trim().substring(0,50)!==e.textSignature){const t=o.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature);t&&(n=t);}}}else if(e.textSignature){const t=o.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature);t&&(n=t);}}if(n){const r=n.offsetTop+(e.offset||0);return t.scrollTo({top:r,behavior:"instant"}),true}return false}getResponseContainerSelector(){return ""}getChatContentSelectors(){return []}getUserQuerySelector(){return null}extractTextWithLineBreaks(e){const t=[],n=new Set(["div","p","li","h1","h2","h3","h4","h5","h6","pre","blockquote","tr","section","article"]),r=e=>{if(e.nodeType===Node.TEXT_NODE){const n=e.textContent||"";t.push(n);}else if(e.nodeType===Node.ELEMENT_NODE){const o=e,i=o.tagName.toLowerCase();if("br"===i)return void t.push("\n");for(const e of o.childNodes)r(e);if(n.has(i)&&t.length>0){t[t.length-1].endsWith("\n")||t.push("\n");}}};return r(e),t.join("").replace(/\n{3,}/g,"\n\n").trim()} /** * 使用 Range API 计算两个 DOM 节点之间的文本长度 * 通用于 Heading 类型的 OutlineItem 字数统计 * @param startEl 起始元素(不包含其内容,从其之后开始) * @param endEl 结束元素(不包含,在其之前结束);若为 null 则使用 fallbackContainer * @param fallbackContainer 当 endEl 为 null 时使用的容器末尾 * @returns 文本字符数 */calculateRangeWordCount(e,t,n){if(!e)return 0;try{const r=document.createRange();if(r.setStartAfter(e),t)r.setEndBefore(t);else {if(!n?.lastChild)return 0;r.setEndAfter(n.lastChild);}return r.toString().trim().length}catch{return 0}}extractUserQueryText(e){return this.extractTextWithLineBreaks(e)}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportText(e){return this.extractUserQueryText(e)} /** * 将渲染后的 HTML 替换到用户提问元素中 * 子类可重写以处理特殊的 DOM 结构 * @returns 是否成功替换 */replaceUserQueryContent(e,t){return false}extractAssistantResponseText(e){return this.extractTextWithLineBreaks(e)}isInRenderedMarkdownContainer(e){return null!==e.closest(".gh-user-query-markdown")}usesShadowDOM(){return false}extractOutline(e=6,t=false,n=false){return []} /** * 根据标题级别和文本查找元素(支持 Shadow DOM 穿透) * 用于大纲跳转时元素失效后的重新查找 * @param level 标题级别 (1-6) * @param text 标题文本内容 * @returns 匹配的元素,未找到返回 null */findElementByHeading(e,t){const n=document.querySelectorAll(`h${e}`);for(const r of Array.from(n))if(r.textContent?.trim()===t)return r;return null} /** * 根据 queryIndex 和文本查找用户提问元素 * 用于大纲跳转时元素失效后的重新查找 * @param queryIndex 用户提问的序号(从 1 开始) * @param text 用户提问文本(用于验证和回退搜索) * @returns 匹配的元素,未找到返回 null */findUserQueryElement(e,t){const n=this.getUserQuerySelector();if(!n)return null;const r=ei.query(n,{all:true,shadow:true});if(!r||0===r.length)return null;if(r.length>=e){const n=r[e-1],o=this.extractUserQueryText(n);if(o===t||o.startsWith(t)||t.startsWith(o))return n}for(const o of r){const e=this.extractUserQueryText(o);if(e===t||e.startsWith(t)||t.startsWith(e))return o}return null}async resolveOutlineTarget(e,t){return e.isUserQuery&&0===e.level&&void 0!==t?this.findUserQueryElement(t,e.text):this.findElementByHeading(e.level,e.text)}supportsScrollLock(){return false}getExportConfig(){return null}async prepareConversationExport(e){return null}async restoreConversationAfterExport(e,t){}getLatestReplyText(){return null}getLastCodeBlockText(){const e=this.getLatestReplyText(),t=this.extractLastFencedCodeBlockText(e||"");if(t)return t;const n=this.getAssistantResponseElementsForCodeSearch();for(let r=n.length-1;r>=0;r-=1){const e=n[r],t=this.extractLastCodeBlockTextFromDomRoot(e);if(t)return t;const o=this.extractAssistantResponseText(e).trim(),i=this.extractLastFencedCodeBlockText(o);if(i)return i}return 0===n.length?this.extractLastCodeBlockTextFromDomRoot(this.getPrimaryCodeSearchRoot()):null}getNewChatButtonSelectors(){return []}startNewConversation(){const e=this.captureConversationNavigationState(),t=this.findVisibleElementBySelectors(this.getNewChatButtonSelectors());return t?(this.simulateClick(t),window.setTimeout(()=>{this.hasConversationNavigationChanged(e)||this.navigateToNewConversationUrl();},150),true):this.navigateToNewConversationUrl()}getStopButtonSelectors(){return []}stopGeneration(){const e=this.findVisibleElementBySelectors(this.getStopButtonSelectors());return !!e&&(this.simulateClick(e),true)}bindNewChatListeners(e){document.addEventListener("keydown",t=>{t.ctrlKey&&t.shiftKey&&("o"===t.key||"O"===t.key)&&setTimeout(e,500);}),document.addEventListener("click",t=>{const n=this.getNewChatButtonSelectors();if(0===n.length)return;const r=t.composedPath();for(const o of r){if(o===document||o===window)break;for(const t of n)if(o.matches&&o.matches(t))return void setTimeout(e,500)}},true);}getDefaultLockSettings(){return {enabled:false,keyword:""}}getModelSwitcherConfig(e){return null}simulateClick(e){e.click();} /** * 点击模型选择器按钮(公开方法,供外部调用) * 使用 simulateClick 确保在 Radix UI 等框架中也能正常工作 * 使用 findElementBySelectors 支持 Shadow DOM 穿透(与 lockModel 一致) * @returns 是否成功点击 */clickModelSelector(){const e=this.getModelSwitcherConfig("");if(!e||!e.selectorButtonSelectors)return false;const t=this.findElementBySelectors(e.selectorButtonSelectors);return !(!t||null===t.offsetParent)&&(this.simulateClick(t),true)}lockModel(e,t){const n=this.getModelSwitcherConfig(e);if(!n)return;const{targetModelKeyword:r,selectorButtonSelectors:o,menuItemSelector:i,checkInterval:a=1e3,maxAttempts:s=10,menuRenderDelay:l=500,subMenuTriggers:c=[],subMenuSelector:d}=n,u=e=>(e||"").toLowerCase().trim(),h=u(r);let g=0;const p=s,m=setInterval(()=>{g++;const e=this.findElementBySelectors(o);if(e){clearInterval(m);if(u(this.getModelLockCheckText(e)).includes(h))return void(t&&t());this.performMenuSearch(e,h,i,l,c,d,t,s);}else g>=p&&(clearInterval(m),console.warn(`Ophel: Model selector button not found after ${p} attempts.`),this.showModelLockFailure(r,"button_not_found"));},a);}performMenuSearch(e,t,n,r,o,i,a,s=10){this.simulateClick(e);const l=Math.max(3,s);let c=0;const d=()=>{c++;const s=this.getVisibleMenuItems(n,e);if(!(s.length>0))return c>=l?(document.body.click(),console.warn("Ophel: Menu items not found."),void this.showModelLockFailure(t,"menu_empty")):void setTimeout(d,r);this.searchAndSelectModel(s,t,n,r,o,i,a);};setTimeout(d,r);}searchAndSelectModel(e,t,n,r,o,i,a){const s=e=>(e||"").toLowerCase().trim(),l=this.findBestMatchingItem(e,t);if(l)return this.simulateClick(l),void setTimeout(()=>{document.body.click(),a&&a();},100);let c;if(i&&(c=e.find(e=>e.matches(i))),!c&&o.length>0&&(c=e.find(e=>{const t=s(e.textContent||"");return o.some(e=>t.includes(s(e)))})),c)return this.simulateClick(c),void setTimeout(()=>{const e=this.getVisibleMenuItems(n,c),r=this.findBestMatchingItem(e,t);if(r)return this.simulateClick(r),void setTimeout(()=>{document.body.click(),a&&a();},100);document.body.click(),console.warn(`Ophel: Model "${t}" not found in sub-menu.`),this.showModelLockFailure(t,"not_found");},r);document.body.click(),console.warn(`Ophel: Model "${t}" not found in menu.`),this.showModelLockFailure(t,"not_found");}getVisibleMenuItems(e,t){const n=this.getVisibleElementsBySelector(e);if(!t||0===n.length)return n;const r=this.getMenuContainerByAria(t);if(r){const e=n.filter(e=>r.contains(e));if(e.length>0)return e}const o=this.getMenuContainerSelector(),i=new Map;for(const a of n){const e=a.closest(o);if(!e||!this.isElementVisible(e))continue;const t=i.get(e);t?t.push(a):i.set(e,[a]);}if(i.size>0){const e=this.pickBestMenuContainer(t,i);if(e)return i.get(e)||n}return n}getVisibleElementsBySelector(e){return ei.query(e,{all:true,shadow:true,filter:e=>this.isElementVisible(e)})||[]}getMenuContainerByAria(e){const t=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(!t)return null;const n=`#${this.escapeSelector(t)}`,r=ei.query(n,{shadow:true});return r&&this.isElementVisible(r)?r:null}getMenuContainerSelector(){return ['[role="menu"]','[role="listbox"]',"md-menu-surface",".mdc-menu-surface",".mat-menu-panel",".menu[popover]","[data-radix-popper-content-wrapper]",".cdk-overlay-pane"].join(", ")}pickBestMenuContainer(e,t){const n=e.getBoundingClientRect();let r=null;return t.forEach((e,t)=>{if(0===e.length)return;const o=t.getBoundingClientRect(),i=this.getRectDistance(n,o);(!r||ir.count)&&(r={container:t,distance:i,count:e.length});}),r?r.container:null}getRectDistance(e,t){const n=Math.max(e.left-t.right,t.left-e.right,0),r=Math.max(e.top-t.bottom,t.top-e.bottom,0);return Math.sqrt(n*n+r*r)}isElementVisible(e){if(!e)return false;const t=e;if(!t.isConnected)return false;const n=window.getComputedStyle(t);if("none"===n.display||"hidden"===n.visibility||0===parseFloat(n.opacity))return false;const r=t.getBoundingClientRect();return r.width>0&&r.height>0}escapeSelector(e){return "undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/[^a-zA-Z0-9_-]/g,"\\$&")}findBestMatchingItem(e,t){const n=e=>(e||"").toLowerCase().trim();for(const r of e){const e=n(r.textContent||r.innerText||"");if(e.split("\n")[0].trim()===t||e===t)return r}for(const r of e){if(n(r.textContent||r.innerText||"").split("\n")[0].trim().endsWith(t))return r}for(const r of e){if(n(r.textContent||r.innerText||"").includes(t))return r}}async showModelLockFailure(e,t){try{const{showToast:n}=await r(async()=>{const{showToast:e}=await Promise.resolve().then(()=>Fo);return {showToast:e}},void 0),{t:o}=await r(async()=>{const{t:e}=await Promise.resolve().then(()=>ie);return {t:e}},void 0);let i;switch(t){case "button_not_found":i=o("modelLockFailedNoButton")||"模型选择器未找到";break;case "menu_empty":i=o("modelLockFailedMenuEmpty")||"模型菜单加载失败";break;default:i=(o("modelLockFailedNotFound")||'未找到模型 "{model}"').replace("{model}",e);}n(i,3e3);}catch(n){console.error("Ophel: Failed to show toast:",n);}}findElementBySelectors(e){return ei.query(e,{shadow:true})}findAllElementsBySelector(e){return ei.query(e,{all:true,shadow:true})||[]}afterPropertiesSet(e={}){const{modelLockConfig:t}=e;t&&t.enabled&&this.lockModel(t.keyword);}shouldInjectIntoShadow(e){return true}findVisibleElementBySelectors(e){if(0===e.length)return null;const t=ei.query(e,{all:true,shadow:true,filter:e=>this.isElementVisible(e)});for(const n of t||[]){if(!(n instanceof HTMLElement))continue;const e=this.resolveClickableTarget(n);if(e&&this.isElementVisible(e))return e}return null}extractLastFencedCodeBlockText(e){if(!e)return null;const t=/```[^\n]*\n([\s\S]*?)```/g;let n=null;for(const r of e.matchAll(t))n=r[1]||null;return n&&n.trim()?n.replace(/\r\n/g,"\n").replace(/\n+$/,""):null}extractLastCodeBlockTextFromDomRoot(e){const t=ei.query("pre code, pre, pre.code-block, .code-block code",{parent:e,all:true,shadow:true,filter:e=>this.shouldIncludeCodeElement(e)})||[];for(let n=t.length-1;n>=0;n-=1){const e=t[n];if(!(e instanceof HTMLElement))continue;const r=e.cloneNode(true);r.querySelectorAll('button, [role="button"], svg, [aria-hidden="true"], .gh-copy-btn, [data-testid*="copy"]').forEach(e=>e.remove());const o=r.textContent?.replace(/\r\n/g,"\n").replace(/\n+$/,"")||"";if(o.trim())return o}return null}getAssistantResponseElementsForCodeSearch(){const e=this.getExportConfig();return e?.assistantResponseSelector&&ei.query(e.assistantResponseSelector,{parent:this.getPrimaryCodeSearchRoot(),all:true,shadow:true,filter:e=>this.shouldIncludeAssistantResponseElement(e)})||[]}getPrimaryCodeSearchRoot(){const e=this.getResponseContainerSelector();if(e){const t=ei.query(e,{shadow:true});if(t)return t}return this.getScrollContainer()||document}resolveClickableTarget(e){return e?e.matches("button, a, [role='button'], [tabindex], md-icon-button, ms-stop-button")?e:e.closest("button, a, [role='button'], [tabindex], md-icon-button, ms-stop-button")||e:null}shouldIncludeAssistantResponseElement(e){return !e.closest(".gh-root, .gh-user-query-markdown, .gh-markdown-preview, .gh-assistant-mermaid")&&this.isElementVisible(e)}shouldIncludeCodeElement(e){return !e.closest(".gh-root, .gh-user-query-markdown, .gh-markdown-preview, .gh-assistant-mermaid")&&this.isElementVisible(e)}isAssistantMermaidCandidate(e){return ri(e)}extractAssistantMermaidSource(e){return ai(e)}navigateToNewConversationUrl(){const e=this.getNewTabUrl();if(!e)return false;try{const t=new URL(e,window.location.origin).href;return t===window.location.href&&this.isNewConversation()||(window.location.href=t),!0}catch{return window.location.href=e,true}}captureConversationNavigationState(){return {href:window.location.href,sessionId:this.getSessionId(),isNewConversation:this.isNewConversation()}}hasConversationNavigationChanged(e){return window.location.href!==e.href||this.getSessionId()!==e.sessionId||this.isNewConversation()!==e.isNewConversation}}const di="delete_ui_failed",ui="delete_batch_aborted_after_ui_failure",hi="delete_api_disabled_unstable",gi="delete_api_auth_missing",pi="delete_api_key_missing",mi="delete_api_request_failed",fi="delete_api_not_found_but_visible",bi=["delete","remove","删除","刪除","削除","삭제","supprimer","eliminar","löschen","excluir","hapus","удалить"],yi=["cancel","取消","キャンセル","취소","annuler","abbrechen","annulla","batal","cancelar","отмена"],vi="/$rpc/google.internal.alkali.applications.makersuite.v1.MakerSuiteService",wi="ms-chat-turn",xi=".chat-turn-container.model, .model-prompt-container",ki=".chat-turn-container.model",Si="ms-thought-chunk",Ci="data-gh-aistudio-export-root",Ei="data-gh-aistudio-export-turn",_i="data-gh-aistudio-export-role",Ai="user",Ti="assistant",Mi=`[${Ci}="1"] [${Ei}="1"]`,Ii=`[${Ci}="1"] [${_i}="${Ai}"]`,Ni=`[${Ci}="1"] [${_i}="${Ti}"]`;const Li=new Set(["chatglm.cn"]),Di="SKIN_MODE",Ri={light:"1",dark:"2",system:"3"},qi=[".userInfoBar-header .me-icon",".userInfoBar-header .me",".userInfoBar-header img.avatar"],Pi=".selecttheme-list",Bi=".conversation-list",Oi=".conversation.question",zi=".question-txt",Fi=".answer-content-wrap .markdown-body",ji=["#search-input-box textarea",".main-chat-search #search-input-box textarea",".main-chat-search textarea"],$i=".enter-icon-container";const Hi="ChatGPT",Ui=["delete","remove","删除","刪除","supprimer","eliminar","löschen","削除","삭제","удалить","excluir"],Wi="delete_ui_failed",Vi="delete_batch_aborted_after_ui_failure",Gi="delete_api_token_missing",Qi="delete_api_request_failed",Ki="delete_api_not_found_but_visible",Zi=['button[data-testid="model-switcher-dropdown-button"][aria-label="模型选择器"]','button[data-testid="model-switcher-dropdown-button"][aria-label*="model"]','button[data-testid="model-switcher-dropdown-button"][aria-haspopup="menu"]','button[id^="radix-"][data-testid="model-switcher-dropdown-button"]','header button[data-testid="model-switcher-dropdown-button"]','button[data-testid="model-switcher-dropdown-button"]','[aria-haspopup="menu"][aria-label*="模型"]','[aria-haspopup="menu"][aria-label*="model"]'],Yi='[data-radix-popper-content-wrapper] [role="menu"][data-radix-menu-content]',Ji=`${Yi} [role="menuitem"][data-testid^="model-switcher-"]`;function Xi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function ea(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=false;try{n=this instanceof e;}catch{}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype;}else n={};return Object.defineProperty(n,"__esModule",{value:true}),Object.keys(e).forEach(function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:true,get:function(){return e[t]}});}),n}var ta,na;function ra(){if(na)return ta;function e(t){return t instanceof Map?t.clear=t.delete=t.set=function(){throw new Error("map is read-only")}:t instanceof Set&&(t.add=t.clear=t.delete=function(){throw new Error("set is read-only")}),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{const r=t[n],o=typeof r;"object"!==o&&"function"!==o||Object.isFrozen(r)||e(r);}),t}na=1;class t{ /** * @param {CompiledMode} mode */ constructor(e){ void 0===e.data&&(e.data={}),this.data=e.data,this.isMatchIgnored=false;}ignoreMatch(){this.isMatchIgnored=true;}}function n(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function r(e,...t){const n=Object.create(null);for(const r in e)n[r]=e[r];return t.forEach(function(e){for(const t in e)n[t]=e[t];}), /** @type {T} */n}const o=e=>!!e.scope;class i{ /** * Creates a new HTMLRenderer * * @param {Tree} parseTree - the parse tree (must support `walk` API) * @param {{classPrefix: string}} options */ constructor(e,t){this.buffer="",this.classPrefix=t.classPrefix,e.walk(this);} /** * Adds texts to the output stream * * @param {string} text */addText(e){this.buffer+=n(e);} /** * Adds a node open to the output stream (if needed) * * @param {Node} node */openNode(e){if(!o(e))return;const t=((e,{prefix:t})=>{if(e.startsWith("language:"))return e.replace("language:","language-");if(e.includes(".")){const n=e.split(".");return [`${t}${n.shift()}`,...n.map((e,t)=>`${e}${"_".repeat(t+1)}`)].join(" ")}return `${t}${e}`})(e.scope,{prefix:this.classPrefix});this.span(t);} /** * Adds a node close to the output stream (if needed) * * @param {Node} node */closeNode(e){o(e)&&(this.buffer+="");}value(){return this.buffer} /** * Builds a span element * * @param {string} className */ span(e){this.buffer+=``;}}const a=(e={})=>{const t={children:[]};return Object.assign(t,e),t};class s{constructor(){this.rootNode=a(),this.stack=[this.rootNode];}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode} /** @param {Node} node */add(e){this.top.children.push(e);} /** @param {string} scope */openNode(e){const t=a({scope:e});this.add(t),this.stack.push(t);}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)} /** * @typedef { import("./html_renderer").Renderer } Renderer * @param {Renderer} builder */walk(e){return this.constructor._walk(e,this.rootNode)} /** * @param {Renderer} builder * @param {Node} node */static _walk(e,t){return "string"==typeof t?e.addText(t):t.children&&(e.openNode(t),t.children.forEach(t=>this._walk(e,t)),e.closeNode(t)),e} /** * @param {Node} node */static _collapse(e){"string"!=typeof e&&e.children&&(e.children.every(e=>"string"==typeof e)?e.children=[e.children.join("")]:e.children.forEach(e=>{s._collapse(e);}));}}class l extends s{ /** * @param {*} options */ constructor(e){super(),this.options=e;} /** * @param {string} text */addText(e){""!==e&&this.add(e);} /** @param {string} scope */startScope(e){this.openNode(e);}endScope(){this.closeNode();} /** * @param {Emitter & {root: DataNode}} emitter * @param {string} name */__addSublanguage(e,t){const n=e.root;t&&(n.scope=`language:${t}`),this.add(n);}toHTML(){return new i(this,this.options).value()}finalize(){return this.closeAllNodes(),true}}function c(e){return e?"string"==typeof e?e:e.source:null}function d(e){return g("(?=",e,")")}function u(e){return g("(?:",e,")*")}function h(e){return g("(?:",e,")?")}function g(...e){return e.map(e=>c(e)).join("")}function p(...e){const t=function(e){const t=e[e.length-1];return "object"==typeof t&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}(e);return "("+(t.capture?"":"?:")+e.map(e=>c(e)).join("|")+")"}function m(e){return new RegExp(e.toString()+"|").exec("").length-1}const f=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function b(e,{joinWith:t}){let n=0;return e.map(e=>{n+=1;const t=n;let r=c(e),o="";for(;r.length>0;){const e=f.exec(r);if(!e){o+=r;break}o+=r.substring(0,e.index),r=r.substring(e.index+e[0].length),"\\"===e[0][0]&&e[1]?o+="\\"+String(Number(e[1])+t):(o+=e[0],"("===e[0]&&n++);}return o}).map(e=>`(${e})`).join(t)}const y="[a-zA-Z]\\w*",v="[a-zA-Z_]\\w*",w="\\b\\d+(\\.\\d+)?",x="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",k="\\b(0b[01]+)",S={begin:"\\\\[\\s\\S]",relevance:0},C={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[S]},E={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[S]},_=function(e,t,n={}){const o=r({scope:"comment",begin:e,end:t,contains:[]},n);o.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:true,relevance:0});const i=p("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return o.contains.push({begin:g(/[ ]+/, // necessary to prevent us gobbling up doctags like /* @author Bob Mcgill */ "(",i,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),o},A=_("//","$"),T=_("/\\*","\\*/"),M=_("#","$"),I={scope:"number",begin:w,relevance:0},N={scope:"number",begin:x,relevance:0},L={scope:"number",begin:k,relevance:0},D={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[S,{begin:/\[/,end:/\]/,relevance:0,contains:[S]}]},R={scope:"title",begin:y,relevance:0},q={scope:"title",begin:v,relevance:0},P={begin:"\\.\\s*"+v,relevance:0};var B=Object.freeze({__proto__:null,APOS_STRING_MODE:C,BACKSLASH_ESCAPE:S,BINARY_NUMBER_MODE:L,BINARY_NUMBER_RE:k,COMMENT:_,C_BLOCK_COMMENT_MODE:T,C_LINE_COMMENT_MODE:A,C_NUMBER_MODE:N,C_NUMBER_RE:x,END_SAME_AS_BEGIN:function(e){return Object.assign(e,{ /** @type {ModeCallback} */ "on:begin":(e,t)=>{t.data._beginMatch=e[1];}, /** @type {ModeCallback} */ "on:end":(e,t)=>{t.data._beginMatch!==e[1]&&t.ignoreMatch();}})},HASH_COMMENT_MODE:M,IDENT_RE:y,MATCH_NOTHING_RE:/\b\B/,METHOD_GUARD:P,NUMBER_MODE:I,NUMBER_RE:w,PHRASAL_WORDS_MODE:{begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},QUOTE_STRING_MODE:E,REGEXP_MODE:D,RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(e={})=>{const t=/^#![ ]*\//;return e.binary&&(e.begin=g(t,/.*\b/,e.binary,/\b.*/)),r({scope:"meta",begin:t,end:/$/,relevance:0, /** @type {ModeCallback} */ "on:begin":(e,t)=>{0!==e.index&&t.ignoreMatch();}},e)},TITLE_MODE:R,UNDERSCORE_IDENT_RE:v,UNDERSCORE_TITLE_MODE:q});function O(e,t){"."===e.input[e.index-1]&&t.ignoreMatch();}function z(e,t){ void 0!==e.className&&(e.scope=e.className,delete e.className);}function F(e,t){t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",e.__beforeBegin=O,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,void 0===e.relevance&&(e.relevance=0));}function j(e,t){Array.isArray(e.illegal)&&(e.illegal=p(...e.illegal));}function $(e,t){if(e.match){if(e.begin||e.end)throw new Error("begin & end are not supported with match");e.begin=e.match,delete e.match;}}function H(e,t){ void 0===e.relevance&&(e.relevance=1);}const U=(e,t)=>{if(!e.beforeMatch)return;if(e.starts)throw new Error("beforeMatch cannot be used with starts");const n=Object.assign({},e);Object.keys(e).forEach(t=>{delete e[t];}),e.keywords=n.keywords,e.begin=g(n.beforeMatch,d(n.begin)),e.starts={relevance:0,contains:[Object.assign(n,{endsParent:true})]},e.relevance=0,delete n.beforeMatch;},W=["of","and","for","in","not","or","if","then","parent","list","value"];function V(e,t,n="keyword"){const r=Object.create(null);return "string"==typeof e?o(n,e.split(" ")):Array.isArray(e)?o(n,e):Object.keys(e).forEach(function(n){Object.assign(r,V(e[n],t,n));}),r;function o(e,n){t&&(n=n.map(e=>e.toLowerCase())),n.forEach(function(t){const n=t.split("|");r[n[0]]=[e,G(n[0],n[1])];});}}function G(e,t){return t?Number(t):function(e){return W.includes(e.toLowerCase())}(e)?0:1}const Q={},K=e=>{console.error(e);},Z=(e,...t)=>{console.log(`WARN: ${e}`,...t);},Y=(e,t)=>{Q[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),Q[`${e}/${t}`]=true);},J=new Error;function X(e,t,{key:n}){let r=0;const o=e[n],i={},a={};for(let s=1;s<=t.length;s++)a[s+r]=o[s],i[s+r]=true,r+=m(t[s-1]);e[n]=a,e[n]._emit=i,e[n]._multi=true;}function ee(e){!function(e){e.scope&&"object"==typeof e.scope&&null!==e.scope&&(e.beginScope=e.scope,delete e.scope);}(e),"string"==typeof e.beginScope&&(e.beginScope={_wrap:e.beginScope}),"string"==typeof e.endScope&&(e.endScope={_wrap:e.endScope}),function(e){if(Array.isArray(e.begin)){if(e.skip||e.excludeBegin||e.returnBegin)throw K("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),J;if("object"!=typeof e.beginScope||null===e.beginScope)throw K("beginScope must be object"),J;X(e,e.begin,{key:"beginScope"}),e.begin=b(e.begin,{joinWith:""});}}(e),function(e){if(Array.isArray(e.end)){if(e.skip||e.excludeEnd||e.returnEnd)throw K("skip, excludeEnd, returnEnd not compatible with endScope: {}"),J;if("object"!=typeof e.endScope||null===e.endScope)throw K("endScope must be object"),J;X(e,e.end,{key:"endScope"}),e.end=b(e.end,{joinWith:""});}}(e);}function te(e){function t(t,n){return new RegExp(c(t),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(n?"g":""))}class n{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0;} // @ts-ignore addRule(e,t){t.position=this.position++,this.matchIndexes[this.matchAt]=t,this.regexes.push([t,e]),this.matchAt+=m(e)+1;}compile(){0===this.regexes.length&&(this.exec=()=>null);const e=this.regexes.map(e=>e[1]);this.matcherRe=t(b(e,{joinWith:"|"}),true),this.lastIndex=0;} /** @param {string} s */exec(e){this.matcherRe.lastIndex=this.lastIndex;const t=this.matcherRe.exec(e);if(!t)return null;const n=t.findIndex((e,t)=>t>0&&void 0!==e),r=this.matchIndexes[n];return t.splice(0,n),Object.assign(t,r)}}class o{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0;} // @ts-ignore getMatcher(e){if(this.multiRegexes[e])return this.multiRegexes[e];const t=new n;return this.rules.slice(e).forEach(([e,n])=>t.addRule(e,n)),t.compile(),this.multiRegexes[e]=t,t}resumingScanAtSamePosition(){return 0!==this.regexIndex}considerAll(){this.regexIndex=0;} // @ts-ignore addRule(e,t){this.rules.push([e,t]),"begin"===t.type&&this.count++;} /** @param {string} s */exec(e){const t=this.getMatcher(this.regexIndex);t.lastIndex=this.lastIndex;let n=t.exec(e);if(this.resumingScanAtSamePosition())if(n&&n.index===this.lastIndex);else {const t=this.getMatcher(0);t.lastIndex=this.lastIndex+1,n=t.exec(e);}return n&&(this.regexIndex+=n.position+1,this.regexIndex===this.count&&this.considerAll()),n}}if(e.compilerExtensions||(e.compilerExtensions=[]),e.contains&&e.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return e.classNameAliases=r(e.classNameAliases||{}),function n(i,a){const s= /** @type CompiledMode */i;if(i.isCompiled)return s;[z,$,ee,U].forEach(e=>e(i,a)),e.compilerExtensions.forEach(e=>e(i,a)),i.__beforeBegin=null,[F,j,H].forEach(e=>e(i,a)),i.isCompiled=true;let l=null;return "object"==typeof i.keywords&&i.keywords.$pattern&&(i.keywords=Object.assign({},i.keywords),l=i.keywords.$pattern,delete i.keywords.$pattern),l=l||/\w+/,i.keywords&&(i.keywords=V(i.keywords,e.case_insensitive)),s.keywordPatternRe=t(l,true),a&&(i.begin||(i.begin=/\B|\b/),s.beginRe=t(s.begin),i.end||i.endsWithParent||(i.end=/\B|\b/),i.end&&(s.endRe=t(s.end)),s.terminatorEnd=c(s.end)||"",i.endsWithParent&&a.terminatorEnd&&(s.terminatorEnd+=(i.end?"|":"")+a.terminatorEnd)),i.illegal&&(s.illegalRe=t( /** @type {RegExp | string} */ i.illegal)),i.contains||(i.contains=[]),i.contains=[].concat(...i.contains.map(function(e){return function(e){e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(function(t){return r(e,{variants:null},t)}));if(e.cachedVariants)return e.cachedVariants;if(ne(e))return r(e,{starts:e.starts?r(e.starts):null});if(Object.isFrozen(e))return r(e);return e}("self"===e?i:e)})),i.contains.forEach(function(e){n( /** @type Mode */ e,s);}),i.starts&&n(i.starts,a),s.matcher=function(e){const t=new o;return e.contains.forEach(e=>t.addRule(e.begin,{rule:e,type:"begin"})),e.terminatorEnd&&t.addRule(e.terminatorEnd,{type:"end"}),e.illegal&&t.addRule(e.illegal,{type:"illegal"}),t}(s),s}( /** @type Mode */ e)}function ne(e){return !!e&&(e.endsWithParent||ne(e.starts))}class re extends Error{constructor(e,t){super(e),this.name="HTMLInjectionError",this.html=t;}}const oe=n,ie=r,ae=Symbol("nomatch"),se=function(n){const r=Object.create(null),o=Object.create(null),i=[];let a=true;const s="Could not find the language '{}', did you forget to load/include a language module?",c={disableAutodetect:true,name:"Plain text",contains:[]};let m={ignoreUnescapedHTML:false,throwUnescapedHTML:false,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:l};function f(e){return m.noHighlightRe.test(e)}function b(e,t,n){let r="",o="";"object"==typeof t?(r=e,n=t.ignoreIllegals,o=t.language):(Y("10.7.0","highlight(lang, code, ...args) has been deprecated."),Y("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),o=e,r=t),void 0===n&&(n=true);const i={code:r,language:o};_("before:highlight",i);const a=i.result?i.result:y(i.language,i.code,n);return a.code=i.code,_("after:highlight",a),a}function y(e,n,o,i){const l=Object.create(null);function c(e,t){return e.keywords[t]}function d(){if(!A.keywords)return void M.addText(I);let e=0;A.keywordPatternRe.lastIndex=0;let t=A.keywordPatternRe.exec(I),n="";for(;t;){n+=I.substring(e,t.index);const r=C.case_insensitive?t[0].toLowerCase():t[0],o=c(A,r);if(o){const[e,i]=o;if(M.addText(n),n="",l[r]=(l[r]||0)+1,l[r]<=7&&(N+=i),e.startsWith("_"))n+=t[0];else {const n=C.classNameAliases[e]||e;h(t[0],n);}}else n+=t[0];e=A.keywordPatternRe.lastIndex,t=A.keywordPatternRe.exec(I);}n+=I.substring(e),M.addText(n);}function u(){null!=A.subLanguage?function(){if(""===I)return;let e=null;if("string"==typeof A.subLanguage){if(!r[A.subLanguage])return void M.addText(I);e=y(A.subLanguage,I,true,T[A.subLanguage]),T[A.subLanguage]=/** @type {CompiledMode} */ e._top;}else e=v(I,A.subLanguage.length?A.subLanguage:null);A.relevance>0&&(N+=e.relevance),M.__addSublanguage(e._emitter,e.language);}():d(),I="";}function h(e,t){""!==e&&(M.startScope(t),M.addText(e),M.endScope());}function g(e,t){let n=1;const r=t.length-1;for(;n<=r;){if(!e._emit[n]){n++;continue}const r=C.classNameAliases[e[n]]||e[n],o=t[n];r?h(o,r):(I=o,d(),I=""),n++;}}function p(e,t){return e.scope&&"string"==typeof e.scope&&M.openNode(C.classNameAliases[e.scope]||e.scope),e.beginScope&&(e.beginScope._wrap?(h(I,C.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap),I=""):e.beginScope._multi&&(g(e.beginScope,t),I="")),A=Object.create(e,{parent:{value:A}}),A}function f(e,n,r){let o=function(e,t){const n=e&&e.exec(t);return n&&0===n.index}(e.endRe,r);if(o){if(e["on:end"]){const r=new t(e);e["on:end"](n,r),r.isMatchIgnored&&(o=false);}if(o){for(;e.endsParent&&e.parent;)e=e.parent;return e}}if(e.endsWithParent)return f(e.parent,n,r)}function b(e){return 0===A.matcher.regexIndex?(I+=e[0],1):(R=true,0)}function w(e){const t=e[0],r=n.substring(e.index),o=f(A,e,r);if(!o)return ae;const i=A;A.endScope&&A.endScope._wrap?(u(),h(t,A.endScope._wrap)):A.endScope&&A.endScope._multi?(u(),g(A.endScope,e)):i.skip?I+=t:(i.returnEnd||i.excludeEnd||(I+=t),u(),i.excludeEnd&&(I=t));do{A.scope&&M.closeNode(),A.skip||A.subLanguage||(N+=A.relevance),A=A.parent;}while(A!==o.parent);return o.starts&&p(o.starts,e),i.returnEnd?0:t.length}let x={};function k(r,i){const s=i&&i[0];if(I+=r,null==s)return u(),0;if("begin"===x.type&&"end"===i.type&&x.index===i.index&&""===s){if(I+=n.slice(i.index,i.index+1),!a){const t=new Error(`0 width match regex (${e})`);throw t.languageName=e,t.badRule=x.rule,t}return 1}if(x=i,"begin"===i.type)return function(e){const n=e[0],r=e.rule,o=new t(r),i=[r.__beforeBegin,r["on:begin"]];for(const t of i)if(t&&(t(e,o),o.isMatchIgnored))return b(n);return r.skip?I+=n:(r.excludeBegin&&(I+=n),u(),r.returnBegin||r.excludeBegin||(I=n)),p(r,e),r.returnBegin?0:n.length}(i);if("illegal"===i.type&&!o){const e=new Error('Illegal lexeme "'+s+'" for mode "'+(A.scope||"")+'"');throw e.mode=A,e}if("end"===i.type){const e=w(i);if(e!==ae)return e}if("illegal"===i.type&&""===s)return I+="\n",1;if(D>1e5&&D>3*i.index){throw new Error("potential infinite loop, way more iterations than matches")}return I+=s,s.length}const C=S(e);if(!C)throw K(s.replace("{}",e)),new Error('Unknown language: "'+e+'"');const E=te(C);let _="",A=i||E;const T={},M=new m.__emitter(m);!function(){const e=[];for(let t=A;t!==C;t=t.parent)t.scope&&e.unshift(t.scope);e.forEach(e=>M.openNode(e));}();let I="",N=0,L=0,D=0,R=false;try{if(C.__emitTokens)C.__emitTokens(n,M);else {for(A.matcher.considerAll();;){D++,R?R=!1:A.matcher.considerAll(),A.matcher.lastIndex=L;const e=A.matcher.exec(n);if(!e)break;const t=k(n.substring(L,e.index),e);L=e.index+t;}k(n.substring(L));}return M.finalize(),_=M.toHTML(),{language:e,value:_,relevance:N,illegal:!1,_emitter:M,_top:A}}catch(q){if(q.message&&q.message.includes("Illegal"))return {language:e,value:oe(n),illegal:true,relevance:0,_illegalBy:{message:q.message,index:L,context:n.slice(L-100,L+100),mode:q.mode,resultSoFar:_},_emitter:M};if(a)return {language:e,value:oe(n),illegal:false,relevance:0,errorRaised:q,_emitter:M,_top:A};throw q}}function v(e,t){t=t||m.languages||Object.keys(r);const n=function(e){const t={value:oe(e),illegal:false,relevance:0,_top:c,_emitter:new m.__emitter(m)};return t._emitter.addText(e),t}(e),o=t.filter(S).filter(E).map(t=>y(t,e,false));o.unshift(n);const i=o.sort((e,t)=>{if(e.relevance!==t.relevance)return t.relevance-e.relevance;if(e.language&&t.language){if(S(e.language).supersetOf===t.language)return 1;if(S(t.language).supersetOf===e.language)return -1}return 0}),[a,s]=i,l=a;return l.secondBest=s,l}function w(e){let t=null;const n=function(e){let t=e.className+" ";t+=e.parentNode?e.parentNode.className:"";const n=m.languageDetectRe.exec(t);if(n){const t=S(n[1]);return t||(Z(s.replace("{}",n[1])),Z("Falling back to no-highlight mode for this block.",e)),t?n[1]:"no-highlight"}return t.split(/\s+/).find(e=>f(e)||S(e))}(e);if(f(n))return;if(_("before:highlightElement",{el:e,language:n}),e.dataset.highlighted)return void console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e);if(e.children.length>0&&(m.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(e)),m.throwUnescapedHTML)){throw new re("One of your code blocks includes unescaped HTML.",e.innerHTML)}t=e;const r=t.textContent,i=n?b(r,{language:n,ignoreIllegals:true}):v(r);e.innerHTML=i.value,e.dataset.highlighted="yes",function(e,t,n){const r=t&&o[t]||n;e.classList.add("hljs"),e.classList.add(`language-${r}`);}(e,n,i.language),e.result={language:i.language,re:i.relevance,relevance:i.relevance},i.secondBest&&(e.secondBest={language:i.secondBest.language,relevance:i.secondBest.relevance}),_("after:highlightElement",{el:e,result:i,text:r});}let x=false;function k(){if("loading"===document.readyState)return x||window.addEventListener("DOMContentLoaded",function(){k();},false),void(x=true);document.querySelectorAll(m.cssSelector).forEach(w);}function S(e){return e=(e||"").toLowerCase(),r[e]||r[o[e]]}function C(e,{languageName:t}){"string"==typeof e&&(e=[e]),e.forEach(e=>{o[e.toLowerCase()]=t;});}function E(e){const t=S(e);return t&&!t.disableAutodetect}function _(e,t){const n=e;i.forEach(function(e){e[n]&&e[n](t);});}Object.assign(n,{highlight:b,highlightAuto:v,highlightAll:k,highlightElement:w,highlightBlock:function(e){return Y("10.7.0","highlightBlock will be removed entirely in v12.0"),Y("10.7.0","Please use highlightElement now."),w(e)},configure:function(e){m=ie(m,e);},initHighlighting:()=>{k(),Y("10.6.0","initHighlighting() deprecated. Use highlightAll() now.");},initHighlightingOnLoad:function(){k(),Y("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.");},registerLanguage:function(e,t){let o=null;try{o=t(n);}catch(i){if(K("Language definition for '{}' could not be registered.".replace("{}",e)),!a)throw i;K(i),o=c;}o.name||(o.name=e),r[e]=o,o.rawDefinition=t.bind(null,n),o.aliases&&C(o.aliases,{languageName:e});},unregisterLanguage:function(e){delete r[e];for(const t of Object.keys(o))o[t]===e&&delete o[t];},listLanguages:function(){return Object.keys(r)},getLanguage:S,registerAliases:C,autoDetection:E,inherit:ie,addPlugin:function(e){!function(e){e["before:highlightBlock"]&&!e["before:highlightElement"]&&(e["before:highlightElement"]=t=>{e["before:highlightBlock"](Object.assign({block:t.el},t));}),e["after:highlightBlock"]&&!e["after:highlightElement"]&&(e["after:highlightElement"]=t=>{e["after:highlightBlock"](Object.assign({block:t.el},t));});}(e),i.push(e);},removePlugin:function(e){const t=i.indexOf(e);-1!==t&&i.splice(t,1);}}),n.debugMode=function(){a=false;},n.safeMode=function(){a=true;},n.versionString="11.11.1",n.regex={concat:g,lookahead:d,either:p,optional:h,anyNumberOfTimes:u};for(const t in B)"object"==typeof B[t]&&e(B[t]);return Object.assign(n,B),n},le=se({});return le.newInstance=()=>se({}),ta=le,le.HighlightJS=le,le.default=le,ta}const oa=Xi(ra());function ia(e){const t=e.regex,n={},r={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[n]}]};Object.assign(n,{className:"variable",variants:[{begin:t.concat(/\$[\w\d#@][\w\d_]*/, // Perl at all like $ident$, @ident@, etc. "(?![\\w\\d])(?![$])")},r]});const o={className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},i=e.inherit(e.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),a={begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},s={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,n,o]};o.contains.push(s);const l={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,n]},c=e.SHEBANG({binary:`(${["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"].join("|")})`,relevance:10}),d={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:true,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return {name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"],literal:["true","false"],built_in:["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset","alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias","set","shopt","autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp","chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"]},contains:[c,e.SHEBANG(),d,l,i,a,{match:/(\/[a-z._-]+)+/},s,{match:/\\"/},{className:"string",begin:/'/,end:/'/},{match:/\\'/},n]}}const aa=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],sa=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),la=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),ca=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),da=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src", // @font-face "stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function ua(e){const t=e.regex,n=(e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}))(e),r=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return {name:"CSS",case_insensitive:true,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"},contains:[n.BLOCK_COMMENT,{begin:/-(webkit|moz|ms|o)-(?=[a-z])/},n.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:"selector-class",begin:"\\.[a-zA-Z-][a-zA-Z0-9_-]*",relevance:0},n.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{begin:":("+la.join("|")+")"},{begin:":(:)?("+ca.join("|")+")"}]},n.CSS_VARIABLE,{className:"attribute",begin:"\\b("+da.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,contains:[n.BLOCK_COMMENT,n.HEXCOLOR,n.IMPORTANT,n.CSS_NUMBER_MODE,...r,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"},contains:[...r,{className:"string",begin:/[^)]/,endsWithParent:true,excludeEnd:true}]},n.FUNCTION_DISPATCH]},{begin:t.lookahead(/@/),end:"[{;]",relevance:0,illegal:/:/, // break on Less variables @var: ... contains:[{className:"keyword",begin:/@-?\w[\w]*(-\w+)*/},{begin:/\s/,endsWithParent:true,excludeEnd:true,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:"and or not only",attribute:sa.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...r,n.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+aa.join("|")+")\\b"}]}}function ha(e){const t=e.regex;return {name:"Diff",aliases:["patch"],contains:[{className:"meta",relevance:10,match:t.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/)},{className:"comment",variants:[{begin:t.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/),end:/$/},{match:/^\*{15}$/}]},{className:"addition",begin:/^\+/,end:/$/},{className:"deletion",begin:/^-/,end:/$/},{className:"addition",begin:/^!/,end:/$/}]}}function ga(e){return {name:"Dockerfile",aliases:["docker"],case_insensitive:true,keywords:["from","maintainer","expose","env","arg","user","onbuild","stopsignal"],contains:[e.HASH_COMMENT_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.NUMBER_MODE,{beginKeywords:"run cmd entrypoint volume add copy workdir label healthcheck shell",starts:{end:/[^\\]$/,subLanguage:"bash"}}],illegal:"ya(e,t,n-1))}const va="[A-Za-z$_][0-9A-Za-z$_]*",wa=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],xa=["true","false","null","undefined","NaN","Infinity"],ka=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],Sa=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],Ca=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],Ea=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],_a=[].concat(Ca,ka,Sa);function Aa(e){const t=e.regex,n=va,r="<>",o="",i={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/, /** * @param {RegExpMatchArray} match * @param {CallbackResponse} response */ isTrulyOpeningTag:(e,t)=>{const n=e[0].length+e.index,r=e.input[n];if("<"===r||","===r)return void t.ignoreMatch();let o;">"===r&&(((e,{after:t})=>{const n="`${e}\\s*\\(`),t.concat("(?!",E.join("|"),")")),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0};var E;const _={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:true,keywords:"prototype",className:"property",relevance:0},A={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},w]},T="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",M={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(T)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[w]};return {name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:a,exports:{PARAMS_CONTAINS:v,CLASS_REFERENCE:k},illegal:/#(?![$_A-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),{label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,h,g,p,m,f,{match:/\$\d+/},d,k,{scope:"attr",match:n+t.lookahead(":"),relevance:0},M,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[f,e.REGEXP_MODE,{className:"function",begin:T,returnBegin:true,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:true},{begin:/(\s*)\(/,end:/\)/,excludeBegin:true,excludeEnd:true,keywords:a,contains:v}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:r,end:o},{match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:i.begin,"on:begin":i.isTrulyOpeningTag,end:i.end}],subLanguage:"xml",contains:[{begin:i.begin,end:i.end,skip:true,contains:["self"]}]}]},S,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:true,label:"func.def",contains:[w,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},_,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[w]},C,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},x,A,{match:/\$[(.]/}]}}const Ta="[A-Za-z$_][0-9A-Za-z$_]*",Ma=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],Ia=["true","false","null","undefined","NaN","Infinity"],Na=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],La=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],Da=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],Ra=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],qa=[].concat(Da,Na,La);function Pa(e){const t=e.regex,n=function(e){const t=e.regex,n=Ta,r="<>",o="",i={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/, /** * @param {RegExpMatchArray} match * @param {CallbackResponse} response */ isTrulyOpeningTag:(e,t)=>{const n=e[0].length+e.index,r=e.input[n];if("<"===r||","===r)return void t.ignoreMatch();let o;">"===r&&(((e,{after:t})=>{const n="`${e}\\s*\\(`),t.concat("(?!",E.join("|"),")")),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0};var E;const _={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:true,keywords:"prototype",className:"property",relevance:0},A={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},w]},T="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",M={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(T)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[w]};return {name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:a,exports:{PARAMS_CONTAINS:v,CLASS_REFERENCE:k},illegal:/#(?![$_A-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),{label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,h,g,p,m,f,{match:/\$\d+/},d,k,{scope:"attr",match:n+t.lookahead(":"),relevance:0},M,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[f,e.REGEXP_MODE,{className:"function",begin:T,returnBegin:true,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:true},{begin:/(\s*)\(/,end:/\)/,excludeBegin:true,excludeEnd:true,keywords:a,contains:v}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:r,end:o},{match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:i.begin,"on:begin":i.isTrulyOpeningTag,end:i.end}],subLanguage:"xml",contains:[{begin:i.begin,end:i.end,skip:true,contains:["self"]}]}]},S,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:true,label:"func.def",contains:[w,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},_,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[w]},C,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},x,A,{match:/\$[(.]/}]}}(e),r=Ta,o=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],i={begin:[/namespace/,/\s+/,e.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},a={beginKeywords:"interface",end:/\{/,excludeEnd:true,keywords:{keyword:"interface extends",built_in:o},contains:[n.exports.CLASS_REFERENCE]},s={$pattern:Ta,keyword:Ma.concat(["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"]),literal:Ia,built_in:qa.concat(o),"variable.language":Ra},l={className:"meta",begin:"@"+r},c=(e,t,n)=>{const r=e.contains.findIndex(e=>e.label===t);if(-1===r)throw new Error("can not find mode to replace");e.contains.splice(r,1,n);};Object.assign(n.keywords,s),n.exports.PARAMS_CONTAINS.push(l);const d=n.contains.find(e=>"attr"===e.scope),u=Object.assign({},d,{match:t.concat(r,t.lookahead(/\s*\?:/))});n.exports.PARAMS_CONTAINS.push([n.exports.CLASS_REFERENCE,d,u]),n.contains=n.contains.concat([l,i,a,u]),c(n,"shebang",e.SHEBANG()),c(n,"use_strict",{className:"meta",relevance:10,begin:/^\s*['"]use strict['"]/});return n.contains.find(e=>"func.def"===e.label).relevance=0,Object.assign(n,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),n}function Ba(e){const t=e.regex,n=t.concat(/[\p{L}_]/u,t.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),r={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},o={begin:/\s/,contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},i=e.inherit(o,{begin:/\(/,end:/\)/}),a=e.inherit(e.APOS_STRING_MODE,{className:"string"}),s=e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),l={endsWithParent:true,illegal:/`]+/}]}]}]};return {name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:true,unicodeRegex:true,contains:[{className:"meta",begin://,relevance:10,contains:[o,s,a,i,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin://,contains:[o,i,s,a]}]}]},e.COMMENT(//,{relevance:10}),{begin://,relevance:10},r,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[s]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag",begin:/)/,end:/>/,keywords:{name:"style"},contains:[l],starts:{end:/<\/style>/,returnEnd:true,subLanguage:["css","xml"]}},{className:"tag",begin:/)/,end:/>/,keywords:{name:"script"},contains:[l],starts:{end:/<\/script>/,returnEnd:true,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:t.concat(//,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:n,relevance:0,starts:l}]},{className:"tag",begin:t.concat(/<\//,t.lookahead(t.concat(n,/>/))),contains:[{className:"name",begin:n,relevance:0},{begin:/>/,relevance:0,endsParent:true}]}]}}function Oa(e){const t="true false yes no null",n="[\\w#;/?:@&=+$,.~*'()[\\]]+",r={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},o=e.inherit(r,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),i={className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},a={end:",",endsWithParent:true,excludeEnd:true,keywords:t,relevance:0},s={begin:/\{/,end:/\}/,contains:[a],illegal:"\\n",relevance:0},l={begin:"\\[",end:"\\]",contains:[a],illegal:"\\n",relevance:0},c=[{className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:true,excludeEnd:true,relevance:0},{className:"type",begin:"!\\w+!"+n},{className:"type",begin:"!<"+n+">"},{className:"type",begin:"!"+n},{className:"type",begin:"!!"+n},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:t,keywords:{literal:t}},i,{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},s,l,{className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},r],d=[...c];return d.pop(),d.push(o),a.contains=d,{name:"YAML",case_insensitive:true,aliases:["yml"],contains:c}}const za=String.raw`\[`,Fa=String.raw`\(`,ja=(e,t,n=0)=>{let r=0,o=t-1;for(;o>=n&&92===e.charCodeAt(o);)r++,o--;return r},$a=(e,t,n)=>{let r=e.src.charCodeAt(t-1),o=e.src.charCodeAt(t+1),i=e.md.utils.isSpace;return {canOpen:n||!i(o),canClose:!(o>=48&&o<=57)&&(n||!i(r))}},Ha=(e,t,n,r)=>{let o=e.bMarks[t]+e.tShift[t],i=e.eMarks[t];if(36!==e.src.charCodeAt(o)||36!==e.src.charCodeAt(o+1))return false;if(r)return true;let a,s=e.skipSpacesBack(i,o),l=o+2,c=false;s-l>=2&&36===e.src.charCodeAt(s-1)&&36===e.src.charCodeAt(s-2)?(a=e.src.slice(l,s-2),c=true):a=e.src.slice(l,i);let d=t,u="";for(;!(c||(d++,d>=n||(l=e.bMarks[d]+e.tShift[d],i=e.eMarks[d],l=2&&36===e.src.charCodeAt(s-1)&&36===e.src.charCodeAt(s-2)&&(u=e.src.slice(l,s-2),c=true);e.line=c?d+1:d;let h=e.push("math_block","math",0);return h.block=true,h.content=(a?`${a}\n`:"")+e.getLines(t+1,d,e.tShift[t],true)+(u?`${u}\n`:""),h.map=[t,e.line],h.markup="$$",true},Ua=(e,t,n,r)=>{let o=e.bMarks[t]+e.tShift[t],i=e.eMarks[t];if(92!==e.src.charCodeAt(o)||91!==e.src.charCodeAt(o+1))return false;if(r)return true;let a,s=e.skipSpacesBack(i,o),l=o+2,c=false;s-l>=2&&93===e.src.charCodeAt(s-1)&&92===e.src.charCodeAt(s-2)?(a=e.src.slice(l,s-2),c=true):a=e.src.slice(l,i);let d=t,u="";for(;!(c||(d++,d>=n||(l=e.bMarks[d]+e.tShift[d],i=e.eMarks[d],l=2&&93===e.src.charCodeAt(s-1)&&92===e.src.charCodeAt(s-2)&&(u=e.src.slice(l,s-2).trimEnd(),c=true);if(!c)return false;e.line=d+1;let h=e.push("math_block","math",0);return h.block=true,h.content=(a?`${a}\n`:"")+e.getLines(t+1,d,e.tShift[t],true)+(u?`${u}\n`:""),h.map=[t,e.line],h.markup=za,true},Wa={alt:["paragraph","reference","blockquote","list"]},Va=(e,t)=>{if("function"!=typeof t?.render)throw TypeError('[@mdit/plugin-tex]: "render" option should be a function');let{allowInlineWithSpace:n=false,mathFence:r=false,delimiters:o="dollars",render:i}=t;if(r){let t=e.renderer.rules.fence;e.renderer.rules.fence=(e,n,r,o,a)=>{let s=e[n];return "math"===s.info.trim()?i(s.content,true,o):t(e,n,r,o,a)};}("dollars"===o||"all"===o)&&(e.inline.ruler.after("escape","math_inline_dollar",(e=>(t,n)=>{if("$"!==t.src[t.pos])return false;let r=$a(t,t.pos,e);if(!r.canOpen)return n||(t.pending+="$"),t.pos++,true;let o,i=t.pos+1;for(;-1!==(i=t.src.indexOf("$",i));){for(o=i-1;92===t.src.charCodeAt(o);)o--;if((i-o)%2==1)break;i++;}if(-1===i)return n||(t.pending+="$"),t.pos+=1,true;if(i-(t.pos+1)===0)return n||(t.pending+="$$"),t.pos+=2,true;if(r=$a(t,i,e),!r.canClose)return n||(t.pending+="$"),t.pos+=1,true;if(!n){let e=t.push("math_inline","math",0);e.markup="$",e.content=t.src.slice(t.pos+1,i);}return t.pos=i+1,true})(n)),e.block.ruler.after("blockquote","math_block_dollar",Ha,Wa)),("brackets"===o||"all"===o)&&(e.inline.ruler.before("escape","math_inline_bracket",(e,t)=>{let n=e.pos;if(92!==e.src.charCodeAt(n)||40!==e.src.charCodeAt(n+1))return false;let r=n+2,o=false,i=e.src.length;for(;ri(e[t].content,false,r),e.renderer.rules.math_block=(e,t,n,r)=>i(e[t].content,true,r);},Ga={};function Qa(e,t){"string"!=typeof t&&(t=Qa.defaultChars);const n=function(e){let t=Ga[e];if(t)return t;t=Ga[e]=[];for(let n=0;n<128;n++){const e=String.fromCharCode(n);t.push(e);}for(let n=0;n=55296&&e<=57343?"���":String.fromCharCode(e),r+=6;continue}}if(240==(248&i)&&r+91114111?t+="����":(e-=65536,t+=String.fromCharCode(55296+(e>>10),56320+(1023&e))),r+=9;continue}}t+="�";}}return t})}Qa.defaultChars=";/?:@&=+$,#",Qa.componentChars="";const Ka={};function Za(e,t,n){"string"!=typeof t&&(n=t,t=Za.defaultChars),void 0===n&&(n=true);const r=function(e){let t=Ka[e];if(t)return t;t=Ka[e]=[];for(let n=0;n<128;n++){const e=String.fromCharCode(n);/^[0-9a-z]$/i.test(e)?t.push(e):t.push("%"+("0"+n.toString(16).toUpperCase()).slice(-2));}for(let n=0;n=55296&&t<=57343){if(t>=55296&&t<=56319&&i+1=56320&&t<=57343){o+=encodeURIComponent(e[i]+e[i+1]),i++;continue}}o+="%EF%BF%BD";}else o+=encodeURIComponent(e[i]);}return o}function Ya(e){let t="";return t+=e.protocol||"",t+=e.slashes?"//":"",t+=e.auth?e.auth+"@":"",e.hostname&&-1!==e.hostname.indexOf(":")?t+="["+e.hostname+"]":t+=e.hostname||"",t+=e.port?":"+e.port:"",t+=e.pathname||"",t+=e.search||"",t+=e.hash||"",t}function Ja(){this.protocol=null,this.slashes=null,this.auth=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.pathname=null;}Za.defaultChars=";/?:@&=+$,-_.!~*'()#",Za.componentChars="-_.!~*'()";const Xa=/^([a-z0-9.+-]+:)/i,es=/:[0-9]*$/,ts=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,ns=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),rs=["'"].concat(ns),os=["%","/","?",";","#"].concat(rs),is=["/","?","#"],as=/^[+a-z0-9A-Z_-]{0,63}$/,ss=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,ls={javascript:true,"javascript:":true},cs={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true};function ds(e,t){if(e&&e instanceof Ja)return e;const n=new Ja;return n.parse(e,t),n}Ja.prototype.parse=function(e,t){let n,r,o,i=e;if(i=i.trim(),!t&&1===e.split("#").length){const e=ts.exec(i);if(e)return this.pathname=e[1],e[2]&&(this.search=e[2]),this}let a=Xa.exec(i);if(a&&(a=a[0],n=a.toLowerCase(),this.protocol=a,i=i.substr(a.length)),(t||a||i.match(/^\/\/[^@\/]+@[^@\/]+/))&&(o="//"===i.substr(0,2),!o||a&&ls[a]||(i=i.substr(2),this.slashes=true)),!ls[a]&&(o||a&&!cs[a])){let e,t,n=-1;for(let s=0;s127?r+="x":r+=n[e];if(!r.match(as)){const r=e.slice(0,t),o=e.slice(t+1),a=n.match(ss);a&&(r.push(a[1]),o.unshift(a[2])),o.length&&(i=o.join(".")+i),this.hostname=r.join(".");break}}}}this.hostname.length>255&&(this.hostname=""),a&&(this.hostname=this.hostname.substr(1,this.hostname.length-2));}const s=i.indexOf("#");-1!==s&&(this.hash=i.substr(s),i=i.slice(0,s));const l=i.indexOf("?");return -1!==l&&(this.search=i.substr(l),i=i.slice(0,l)),i&&(this.pathname=i),cs[n]&&this.hostname&&!this.pathname&&(this.pathname=""),this},Ja.prototype.parseHost=function(e){let t=es.exec(e);t&&(t=t[0],":"!==t&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e);};const us=Object.freeze(Object.defineProperty({__proto__:null,decode:Qa,encode:Za,format:Ya,parse:ds},Symbol.toStringTag,{value:"Module"})),hs=/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,gs=/[\0-\x1F\x7F-\x9F]/,ps=/[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/,ms=/[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/,fs=/[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/,bs=Object.freeze(Object.defineProperty({__proto__:null,Any:hs,Cc:gs,Cf:/[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/,P:ps,S:ms,Z:fs},Symbol.toStringTag,{value:"Module"})),ys=new Uint16Array('ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms„‹•˜¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTLJNjǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉Dzኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0᾽g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙ῜ῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map(e=>e.charCodeAt(0))),vs=new Uint16Array("Ȁaglq\tɭ\0\0p;䀦os;䀧t;䀾t;䀼uot;䀢".split("").map(e=>e.charCodeAt(0)));var ws;const xs=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]),ks= // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins null!==(ws=String.fromCodePoint)&&void 0!==ws?ws:function(e){let t="";return e>65535&&(e-=65536,t+=String.fromCharCode(e>>>10&1023|55296),e=56320|1023&e),t+=String.fromCharCode(e),t};var Ss,Cs;(Cs=Ss||(Ss={}))[Cs.NUM=35]="NUM",Cs[Cs.SEMI=59]="SEMI",Cs[Cs.EQUALS=61]="EQUALS",Cs[Cs.ZERO=48]="ZERO",Cs[Cs.NINE=57]="NINE",Cs[Cs.LOWER_A=97]="LOWER_A",Cs[Cs.LOWER_F=102]="LOWER_F",Cs[Cs.LOWER_X=120]="LOWER_X",Cs[Cs.LOWER_Z=122]="LOWER_Z",Cs[Cs.UPPER_A=65]="UPPER_A",Cs[Cs.UPPER_F=70]="UPPER_F",Cs[Cs.UPPER_Z=90]="UPPER_Z";var Es,_s,As,Ts,Ms,Is;function Ns(e){return e>=Ss.ZERO&&e<=Ss.NINE}function Ls(e){return e>=Ss.UPPER_A&&e<=Ss.UPPER_F||e>=Ss.LOWER_A&&e<=Ss.LOWER_F}function Ds(e){return e===Ss.EQUALS||function(e){return e>=Ss.UPPER_A&&e<=Ss.UPPER_Z||e>=Ss.LOWER_A&&e<=Ss.LOWER_Z||Ns(e)}(e)}(_s=Es||(Es={}))[_s.VALUE_LENGTH=49152]="VALUE_LENGTH",_s[_s.BRANCH_LENGTH=16256]="BRANCH_LENGTH",_s[_s.JUMP_TABLE=127]="JUMP_TABLE",(Ts=As||(As={}))[Ts.EntityStart=0]="EntityStart",Ts[Ts.NumericStart=1]="NumericStart",Ts[Ts.NumericDecimal=2]="NumericDecimal",Ts[Ts.NumericHex=3]="NumericHex",Ts[Ts.NamedEntity=4]="NamedEntity",(Is=Ms||(Ms={}))[Is.Legacy=0]="Legacy",Is[Is.Strict=1]="Strict",Is[Is.Attribute=2]="Attribute";class Rs{constructor(e,t,n){this.decodeTree=e,this.emitCodePoint=t,this.errors=n,this.state=As.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=Ms.Strict;}startEntity(e){this.decodeMode=e,this.state=As.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1;} /** * Write an entity to the decoder. This can be called multiple times with partial entities. * If the entity is incomplete, the decoder will return -1. * * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the * entity is incomplete, and resume when the next string is written. * * @param string The string containing the entity (or a continuation of the entity). * @param offset The offset at which the entity begins. Should be 0 if this is not the first call. * @returns The number of characters that were consumed, or -1 if the entity is incomplete. */write(e,t){switch(this.state){case As.EntityStart:return e.charCodeAt(t)===Ss.NUM?(this.state=As.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1)):(this.state=As.NamedEntity,this.stateNamedEntity(e,t));case As.NumericStart:return this.stateNumericStart(e,t);case As.NumericDecimal:return this.stateNumericDecimal(e,t);case As.NumericHex:return this.stateNumericHex(e,t);case As.NamedEntity:return this.stateNamedEntity(e,t)}} /** * Switches between the numeric decimal and hexadecimal states. * * Equivalent to the `Numeric character reference state` in the HTML spec. * * @param str The string containing the entity (or a continuation of the entity). * @param offset The current offset. * @returns The number of characters that were consumed, or -1 if the entity is incomplete. */stateNumericStart(e,t){return t>=e.length?-1:(32|e.charCodeAt(t))===Ss.LOWER_X?(this.state=As.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1)):(this.state=As.NumericDecimal,this.stateNumericDecimal(e,t))}addToNumericResult(e,t,n,r){if(t!==n){const o=n-t;this.result=this.result*Math.pow(r,o)+parseInt(e.substr(t,o),r),this.consumed+=o;}} /** * Parses a hexadecimal numeric entity. * * Equivalent to the `Hexademical character reference state` in the HTML spec. * * @param str The string containing the entity (or a continuation of the entity). * @param offset The current offset. * @returns The number of characters that were consumed, or -1 if the entity is incomplete. */stateNumericHex(e,t){const n=t;for(;t=55296&&e<=57343||e>1114111?65533:null!==(t=xs.get(e))&&void 0!==t?t:e}(this.result),this.consumed),this.errors&&(e!==Ss.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed} /** * Parses a named entity. * * Equivalent to the `Named character reference state` in the HTML spec. * * @param str The string containing the entity (or a continuation of the entity). * @param offset The current offset. * @returns The number of characters that were consumed, or -1 if the entity is incomplete. */stateNamedEntity(e,t){const{decodeTree:n}=this;let r=n[this.treeIndex],o=(r&Es.VALUE_LENGTH)>>14;for(;t>14,0!==o){if(i===Ss.SEMI)return this.emitNamedEntityData(this.treeIndex,o,this.consumed+this.excess);this.decodeMode!==Ms.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0);}}return -1} /** * Emit a named entity that was not terminated with a semicolon. * * @returns The number of characters consumed. */emitNotTerminatedNamedEntity(){var e;const{result:t,decodeTree:n}=this,r=(n[t]&Es.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,r,this.consumed),null===(e=this.errors)||void 0===e||e.missingSemicolonAfterCharacterReference(),this.consumed} /** * Emit a named entity. * * @param result The index of the entity in the decode tree. * @param valueLength The number of bytes in the entity. * @param consumed The number of characters consumed. * * @returns The number of characters consumed. */emitNamedEntityData(e,t,n){const{decodeTree:r}=this;return this.emitCodePoint(1===t?r[e]&~Es.VALUE_LENGTH:r[e+1],n),3===t&&this.emitCodePoint(r[e+2],n),n} /** * Signal to the parser that the end of the input was reached. * * Remaining data will be emitted and relevant errors will be produced. * * @returns The number of characters consumed. */end(){var e;switch(this.state){case As.NamedEntity:return 0===this.result||this.decodeMode===Ms.Attribute&&this.result!==this.treeIndex?0:this.emitNotTerminatedNamedEntity();case As.NumericDecimal:return this.emitNumericEntity(0,2);case As.NumericHex:return this.emitNumericEntity(0,3);case As.NumericStart:return null===(e=this.errors)||void 0===e||e.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case As.EntityStart:return 0}}}function qs(e){let t="";const n=new Rs(e,e=>t+=ks(e));return function(e,r){let o=0,i=0;for(;(i=e.indexOf("&",i))>=0;){t+=e.slice(o,i),n.startEntity(r);const a=n.write(e,i+1);if(a<0){o=i+n.end();break}o=i+a,i=0===a?o+1:o;}const a=t+e.slice(o);return t="",a}}function Ps(e,t,n,r){const o=(t&Es.BRANCH_LENGTH)>>7,i=t&Es.JUMP_TABLE;if(0===o)return 0!==i&&r===i?n:-1;if(i){const t=r-i;return t<0||t>=o?-1:e[n+t]-1}let a=n,s=a+o-1;for(;a<=s;){const t=a+s>>>1,n=e[t];if(nr))return e[t+o];s=t-1;}}return -1}const Bs=qs(ys);function Os(e,t=Ms.Legacy){return Bs(e,t)}function zs(e){return "[object String]"===function(e){return Object.prototype.toString.call(e)}(e)}qs(vs);const Fs=Object.prototype.hasOwnProperty;function js(e){return Array.prototype.slice.call(arguments,1).forEach(function(t){if(t){if("object"!=typeof t)throw new TypeError(t+"must be object");Object.keys(t).forEach(function(n){e[n]=t[n];});}}),e}function $s(e,t,n){return [].concat(e.slice(0,t),n,e.slice(t+1))}function Hs(e){return !(e>=55296&&e<=57343)&&(!(e>=64976&&e<=65007)&&(!!(65535&~e&&65534!=(65535&e))&&(!(e>=0&&e<=8)&&(11!==e&&(!(e>=14&&e<=31)&&(!(e>=127&&e<=159)&&!(e>1114111)))))))}function Us(e){if(e>65535){const t=55296+((e-=65536)>>10),n=56320+(1023&e);return String.fromCharCode(t,n)}return String.fromCharCode(e)}const Ws=/\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g,Vs=new RegExp(Ws.source+"|"+/&([a-z#][a-z0-9]{1,31});/gi.source,"gi"),Gs=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i;function Qs(e){return e.indexOf("\\")<0&&e.indexOf("&")<0?e:e.replace(Vs,function(e,t,n){return t||function(e,t){if(35===t.charCodeAt(0)&&Gs.test(t)){const n="x"===t[1].toLowerCase()?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return Hs(n)?Us(n):e}const n=Os(e);return n!==e?n:e}(e,n)})}const Ks=/[&<>"]/,Zs=/[&<>"]/g,Ys={"&":"&","<":"<",">":">",'"':"""};function Js(e){return Ys[e]}function Xs(e){return Ks.test(e)?e.replace(Zs,Js):e}const el=/[.?*+^$[\]\\(){}|-]/g;function tl(e){switch(e){case 9:case 32:return true}return false}function nl(e){if(e>=8192&&e<=8202)return true;switch(e){case 9:case 10:case 11:case 12:case 13:case 32:case 160:case 5760:case 8239:case 8287:case 12288:return true}return false}function rl(e){return ps.test(e)||ms.test(e)}function ol(e){switch(e){case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:case 42:case 43:case 44:case 45:case 46:case 47:case 58:case 59:case 60:case 61:case 62:case 63:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 124:case 125:case 126:return true;default:return false}}function il(e){return e=e.trim().replace(/\s+/g," "),"Ṿ"==="ẞ".toLowerCase()&&(e=e.replace(/ẞ/g,"ß")),e.toLowerCase().toUpperCase()}const al={mdurl:us,ucmicro:bs},sl=Object.freeze(Object.defineProperty({__proto__:null,arrayReplaceAt:$s,assign:js,escapeHtml:Xs,escapeRE:function(e){return e.replace(el,"\\$&")},fromCodePoint:Us,has:function(e,t){return Fs.call(e,t)},isMdAsciiPunct:ol,isPunctChar:rl,isSpace:tl,isString:zs,isValidEntityCode:Hs,isWhiteSpace:nl,lib:al,normalizeReference:il,unescapeAll:Qs,unescapeMd:function(e){return e.indexOf("\\")<0?e:e.replace(Ws,"$1")}},Symbol.toStringTag,{value:"Module"}));const ll=Object.freeze(Object.defineProperty({__proto__:null,parseLinkDestination:function(e,t,n){let r,o=t;const i={ok:false,pos:0,str:""};if(60===e.charCodeAt(o)){for(o++;o32))return i;if(41===r){if(0===a)break;a--;}o++;}return t===o||0!==a||(i.str=Qs(e.slice(t,o)),i.pos=o,i.ok=true),i},parseLinkLabel:function(e,t,n){let r,o,i,a;const s=e.posMax,l=e.pos;for(e.pos=t+1,r=1;e.pos=n)return a;let r=e.charCodeAt(i);if(34!==r&&39!==r&&40!==r)return a;t++,i++,40===r&&(r=41),a.marker=r;}for(;i"+Xs(i.content)+""},cl.code_block=function(e,t,n,r,o){const i=e[t];return ""+Xs(e[t].content)+"\n"},cl.fence=function(e,t,n,r,o){const i=e[t],a=i.info?Qs(i.info).trim():"";let s,l="",c="";if(a){const e=a.split(/(\s+)/g);l=e[0],c=e.slice(2).join("");}if(s=n.highlight&&n.highlight(i.content,l,c)||Xs(i.content),0===s.indexOf("${s}\n`}return `
${s}
\n`},cl.image=function(e,t,n,r,o){const i=e[t];return i.attrs[i.attrIndex("alt")][1]=o.renderInlineAsText(i.children,n,r),o.renderToken(e,t,n)},cl.hardbreak=function(e,t,n){return n.xhtmlOut?"
\n":"
\n"},cl.softbreak=function(e,t,n){return n.breaks?n.xhtmlOut?"
\n":"
\n":"\n"},cl.text=function(e,t){return Xs(e[t].content)},cl.html_block=function(e,t){return e[t].content},cl.html_inline=function(e,t){return e[t].content},dl.prototype.renderAttrs=function(e){let t,n,r;if(!e.attrs)return "";for(r="",t=0,n=e.attrs.length;t\n":">",o},dl.prototype.renderInline=function(e,t,n){let r="";const o=this.rules;for(let i=0,a=e.length;i=0&&(n=this.attrs[t][1]),n},hl.prototype.attrJoin=function(e,t){const n=this.attrIndex(e);n<0?this.attrPush([e,t]):this.attrs[n][1]=this.attrs[n][1]+" "+t;},gl.prototype.Token=hl;const pl=/\r\n?|\n/g,ml=/\0/g;function fl(e){return /^\s]/i.test(e)}function bl(e){return /^<\/a\s*>/i.test(e)}const yl=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,vl=/\((c|tm|r)\)/i,wl=/\((c|tm|r)\)/gi,xl={c:"©",r:"®",tm:"™"};function kl(e,t){return xl[t.toLowerCase()]}function Sl(e){let t=0;for(let n=e.length-1;n>=0;n--){const r=e[n];"text"!==r.type||t||(r.content=r.content.replace(wl,kl)),"link_open"===r.type&&"auto"===r.info&&t--,"link_close"===r.type&&"auto"===r.info&&t++;}}function Cl(e){let t=0;for(let n=e.length-1;n>=0;n--){const r=e[n];"text"!==r.type||t||yl.test(r.content)&&(r.content=r.content.replace(/\+-/g,"±").replace(/\.{2,}/g,"…").replace(/([?!])…/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---(?=[^-]|$)/gm,"$1—").replace(/(^|\s)--(?=\s|$)/gm,"$1–").replace(/(^|[^-\s])--(?=[^-\s]|$)/gm,"$1–")),"link_open"===r.type&&"auto"===r.info&&t--,"link_close"===r.type&&"auto"===r.info&&t++;}}const El=/['"]/,_l=/['"]/g;function Al(e,t,n){return e.slice(0,t)+n+e.slice(t+1)}function Tl(e,t){let n;const r=[];for(let o=0;o=0&&!(r[n].level<=a);n--);if(r.length=n+1,"text"!==i.type)continue;let s=i.content,l=0,c=s.length;e:for(;l=0)p=s.charCodeAt(d.index-1);else for(n=o-1;n>=0&&("softbreak"!==e[n].type&&"hardbreak"!==e[n].type);n--)if(e[n].content){p=e[n].content.charCodeAt(e[n].content.length-1);break}let m=32;if(l=48&&p<=57&&(h=u=false),u&&h&&(u=f,h=b),u||h){if(h)for(n=r.length-1;n>=0;n--){let u=r[n];if(r[n].level=0;i--){const a=r[i];if("link_close"!==a.type){if("html_inline"===a.type&&(fl(a.content)&&o>0&&o--,bl(a.content)&&o++),!(o>0)&&"text"===a.type&&e.md.linkify.test(a.content)){const o=a.content;let s=e.md.linkify.match(o);const l=[];let c=a.level,d=0;s.length>0&&0===s[0].index&&i>0&&"text_special"===r[i-1].type&&(s=s.slice(1));for(let t=0;td){const t=new e.Token("text","",0);t.content=o.slice(d,a),t.level=c,l.push(t);}const u=new e.Token("link_open","a",1);u.attrs=[["href",r]],u.level=c++,u.markup="linkify",u.info="auto",l.push(u);const h=new e.Token("text","",0);h.content=i,h.level=c,l.push(h);const g=new e.Token("link_close","a",-1);g.level=--c,g.markup="linkify",g.info="auto",l.push(g),d=s[t].lastIndex;}if(d=0;t--)"inline"===e.tokens[t].type&&(vl.test(e.tokens[t].content)&&Sl(e.tokens[t].children),yl.test(e.tokens[t].content)&&Cl(e.tokens[t].children));}],["smartquotes",function(e){if(e.md.options.typographer)for(let t=e.tokens.length-1;t>=0;t--)"inline"===e.tokens[t].type&&El.test(e.tokens[t].content)&&Tl(e.tokens[t].children,e);}],["text_join",function(e){let t,n;const r=e.tokens,o=r.length;for(let i=0;i0&&this.level++,this.tokens.push(r),r},Nl.prototype.isEmpty=function(e){return this.bMarks[e]+this.tShift[e]>=this.eMarks[e]},Nl.prototype.skipEmptyLines=function(e){for(let t=this.lineMax;et;)if(!tl(this.src.charCodeAt(--e)))return e+1;return e},Nl.prototype.skipChars=function(e,t){for(let n=this.src.length;en;)if(t!==this.src.charCodeAt(--e))return e+1;return e},Nl.prototype.getLines=function(e,t,n,r){if(e>=t)return "";const o=new Array(t-e);for(let i=0,a=e;an?new Array(e-n+1).join(" ")+this.src.slice(c,l):this.src.slice(c,l);}return o.join("")},Nl.prototype.Token=hl;function Ll(e,t){const n=e.bMarks[t]+e.tShift[t],r=e.eMarks[t];return e.src.slice(n,r)}function Dl(e){const t=[],n=e.length;let r=0,o=e.charCodeAt(r),i=false,a=0,s="";for(;r=r)return -1;let i=e.src.charCodeAt(o++);if(i<48||i>57)return -1;for(;;){if(o>=r)return -1;if(i=e.src.charCodeAt(o++),!(i>=48&&i<=57)){if(41===i||46===i)break;return -1}if(o-n>=10)return -1}return o`\\x00-\\x20]+|'[^']*'|\"[^\"]*\"))?)*\\s*\\/?>",Bl="<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>",Ol=new RegExp("^(?:"+Pl+"|"+Bl+"|\x3c!---?>|\x3c!--(?:[^-]|-[^-]|--[^>])*--\x3e|<[?][\\s\\S]*?[?]>|]*>|)"),zl=new RegExp("^(?:"+Pl+"|"+Bl+")"),Fl=[[/^<(script|pre|style|textarea)(?=(\s|>|$))/i,/<\/(script|pre|style|textarea)>/i,true],[/^/,true],[/^<\?/,/\?>/,true],[/^/,true],[/^/,true],[new RegExp("^|$))","i"),/^$/,true],[new RegExp(zl.source+"\\s*$"),/^$/,false]];const jl=[["table",function(e,t,n,r){if(t+2>n)return false;let o=t+1;if(e.sCount[o]=4)return false;let i=e.bMarks[o]+e.tShift[o];if(i>=e.eMarks[o])return false;const a=e.src.charCodeAt(i++);if(124!==a&&45!==a&&58!==a)return false;if(i>=e.eMarks[o])return false;const s=e.src.charCodeAt(i++);if(124!==s&&45!==s&&58!==s&&!tl(s))return false;if(45===a&&tl(s))return false;for(;i=4)return false;c=Dl(l),c.length&&""===c[0]&&c.shift(),c.length&&""===c[c.length-1]&&c.pop();const u=c.length;if(0===u||u!==d.length)return false;if(r)return true;const h=e.parentType;e.parentType="table";const g=e.md.block.ruler.getRules("blockquote"),p=[t,0];e.push("table_open","table",1).map=p,e.push("thead_open","thead",1).map=[t,t+1],e.push("tr_open","tr",1).map=[t,t+1];for(let b=0;b=4)break;if(c=Dl(l),c.length&&""===c[0]&&c.shift(),c.length&&""===c[c.length-1]&&c.pop(),f+=u-c.length,f>65536)break;if(o===t+2){e.push("tbody_open","tbody",1).map=m=[t+2,0];}e.push("tr_open","tr",1).map=[o,o+1];for(let t=0;t=4))break;r++,o=r;}e.line=o;const i=e.push("code_block","code",0);return i.content=e.getLines(t,o,4+e.blkIndent,false)+"\n",i.map=[t,e.line],true}],["fence",function(e,t,n,r){let o=e.bMarks[t]+e.tShift[t],i=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4)return false;if(o+3>i)return false;const a=e.src.charCodeAt(o);if(126!==a&&96!==a)return false;let s=o;o=e.skipChars(o,a);let l=o-s;if(l<3)return false;const c=e.src.slice(s,o),d=e.src.slice(o,i);if(96===a&&d.indexOf(String.fromCharCode(a))>=0)return false;if(r)return true;let u=t,h=false;for(;(u++,!(u>=n))&&(o=s=e.bMarks[u]+e.tShift[u],i=e.eMarks[u],!(o=4||(o=e.skipChars(o,a),o-s=4)return false;if(62!==e.src.charCodeAt(o))return false;if(r)return true;const s=[],l=[],c=[],d=[],u=e.md.block.ruler.getRules("blockquote"),h=e.parentType;e.parentType="blockquote";let g,p=false;for(g=t;g=i)break;if(62===e.src.charCodeAt(o++)&&!t){let t,n,r=e.sCount[g]+1;32===e.src.charCodeAt(o)?(o++,r++,n=false,t=true):9===e.src.charCodeAt(o)?(t=true,(e.bsCount[g]+r)%4==3?(o++,r++,n=false):n=true):t=false;let a=r;for(s.push(e.bMarks[g]),e.bMarks[g]=o;o=i,l.push(e.bsCount[g]),e.bsCount[g]=e.sCount[g]+1+(t?1:0),c.push(e.sCount[g]),e.sCount[g]=a-r,d.push(e.tShift[g]),e.tShift[g]=o-e.bMarks[g];continue}if(p)break;let r=false;for(let o=0,i=u.length;o";const b=[t,0];f.map=b,e.md.block.tokenize(e,t,g),e.push("blockquote_close","blockquote",-1).markup=">",e.lineMax=a,e.parentType=h,b[1]=e.line;for(let y=0;y=4)return false;let i=e.bMarks[t]+e.tShift[t];const a=e.src.charCodeAt(i++);if(42!==a&&45!==a&&95!==a)return false;let s=1;for(;i=4)return false;if(e.listIndent>=0&&e.sCount[l]-e.listIndent>=4&&e.sCount[l]=e.blkIndent&&(g=true),(h=ql(e,l))>=0){if(d=true,a=e.bMarks[l]+e.tShift[l],u=Number(e.src.slice(a,h-1)),g&&1!==u)return false}else {if(!((h=Rl(e,l))>=0))return false;d=false;}if(g&&e.skipSpaces(h)>=e.eMarks[l])return false;if(r)return true;const p=e.src.charCodeAt(h-1),m=e.tokens.length;d?(s=e.push("ordered_list_open","ol",1),1!==u&&(s.attrs=[["start",u]])):s=e.push("bullet_list_open","ul",1);const f=[l,0];s.map=f,s.markup=String.fromCharCode(p);let b=false;const y=e.md.block.ruler.getRules("list"),v=e.parentType;for(e.parentType="list";l=o?1:r-t,g>4&&(g=1);const m=t+g;s=e.push("list_item_open","li",1),s.markup=String.fromCharCode(p);const f=[l,0];s.map=f,d&&(s.info=e.src.slice(a,h-1));const v=e.tight,w=e.tShift[l],x=e.sCount[l],k=e.listIndent;if(e.listIndent=e.blkIndent,e.blkIndent=m,e.tight=true,e.tShift[l]=u-e.bMarks[l],e.sCount[l]=r,u>=o&&e.isEmpty(l+1)?e.line=Math.min(e.line+2,n):e.md.block.tokenize(e,l,n,true),e.tight&&!b||(c=false),b=e.line-l>1&&e.isEmpty(e.line-1),e.blkIndent=e.listIndent,e.listIndent=k,e.tShift[l]=w,e.sCount[l]=x,e.tight=v,s=e.push("list_item_close","li",-1),s.markup=String.fromCharCode(p),l=e.line,f[1]=l,l>=n)break;if(e.sCount[l]=4)break;let S=false;for(let o=0,i=y.length;o=4)return false;if(91!==e.src.charCodeAt(o))return false;function s(t){const n=e.lineMax;if(t>=n||e.isEmpty(t))return null;let r=false;if(e.sCount[t]-e.blkIndent>3&&(r=true),e.sCount[t]<0&&(r=true),!r){const r=e.md.block.ruler.getRules("reference"),o=e.parentType;e.parentType="reference";let i=false;for(let a=0,s=r.length;a=4)return false;if(!e.md.options.html)return false;if(60!==e.src.charCodeAt(o))return false;let a=e.src.slice(o,i),s=0;for(;s=4)return false;let a=e.src.charCodeAt(o);if(35!==a||o>=i)return false;let s=1;for(a=e.src.charCodeAt(++o);35===a&&o6||oo&&tl(e.src.charCodeAt(l-1))&&(i=l),e.line=t+1;const c=e.push("heading_open","h"+String(s),1);c.markup="########".slice(0,s),c.map=[t,e.line];const d=e.push("inline","",0);return d.content=e.src.slice(o,i).trim(),d.map=[t,e.line],d.children=[],e.push("heading_close","h"+String(s),-1).markup="########".slice(0,s),true},["paragraph","reference","blockquote"]],["lheading",function(e,t,n){const r=e.md.block.ruler.getRules("paragraph");if(e.sCount[t]-e.blkIndent>=4)return false;const o=e.parentType;e.parentType="paragraph";let i,a=0,s=t+1;for(;s3)continue;if(e.sCount[s]>=e.blkIndent){let t=e.bMarks[s]+e.tShift[s];const n=e.eMarks[s];if(t=n))){a=61===i?1:2;break}}if(e.sCount[s]<0)continue;let t=false;for(let o=0,i=r.length;o3)continue;if(e.sCount[i]<0)continue;let t=false;for(let o=0,a=r.length;o=n))&&!(e.sCount[a]=i){e.line=n;break}const t=e.line;let l=false;for(let i=0;i=e.line)throw new Error("block rule didn't increment state.line");break}if(!l)throw new Error("none of the block rules matched");e.tight=!s,e.isEmpty(e.line-1)&&(s=true),a=e.line,a0&&(this.level++,this._prev_delimiters.push(this.delimiters),this.delimiters=[],o={delimiters:this.delimiters}),this.pendingLevel=this.level,this.tokens.push(r),this.tokens_meta.push(o),r},Hl.prototype.scanDelims=function(e,t){const n=this.posMax,r=this.src.charCodeAt(e),o=e>0?this.src.charCodeAt(e-1):32;let i=e;for(;i?@[]^_`{|}~-".split("").forEach(function(e){Vl[e.charCodeAt(0)]=1;});const Ql={tokenize:function(e,t){const n=e.pos,r=e.src.charCodeAt(n);if(t)return false;if(126!==r)return false;const o=e.scanDelims(e.pos,true);let i=o.length;const a=String.fromCharCode(r);if(i<2)return false;let s;i%2&&(s=e.push("text","",0),s.content=a,i--);for(let l=0;l=0;n--){const r=t[n];if(95!==r.marker&&42!==r.marker)continue;if(-1===r.end)continue;const o=t[r.end],i=n>0&&t[n-1].end===r.end+1&&t[n-1].marker===r.marker&&t[n-1].token===r.token-1&&t[r.end+1].token===o.token+1,a=String.fromCharCode(r.marker),s=e.tokens[r.token];s.type=i?"strong_open":"em_open",s.tag=i?"strong":"em",s.nesting=1,s.markup=i?a+a:a,s.content="";const l=e.tokens[o.token];l.type=i?"strong_close":"em_close",l.tag=i?"strong":"em",l.nesting=-1,l.markup=i?a+a:a,l.content="",i&&(e.tokens[t[n-1].token].content="",e.tokens[t[r.end+1].token].content="",n--);}}const Zl={tokenize:function(e,t){const n=e.pos,r=e.src.charCodeAt(n);if(t)return false;if(95!==r&&42!==r)return false;const o=e.scanDelims(e.pos,42===r);for(let i=0;i\x00-\x20]*)$/;const Xl=/^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i,ec=/^&([a-z][a-z0-9]{1,31});/i;function tc(e){const t={},n=e.length;if(!n)return;let r=0,o=-2;const i=[];for(let a=0;as;l-=i[l]+1){const t=e[l];if(t.marker===n.marker&&(t.open&&t.end<0)){let r=false;if((t.close||n.open)&&(t.length+n.length)%3==0&&(t.length%3==0&&n.length%3==0||(r=true)),!r){const r=l>0&&!e[l-1].open?i[l-1]+1:0;i[a]=a-l+r,i[l]=r,n.open=false,t.end=a,t.close=false,c=-1,o=-2;break}}} -1!==c&&(t[n.marker][(n.open?3:0)+(n.length||0)%3]=c);}}const nc=[["text",function(e,t){let n=e.pos;for(;n0)return false;const n=e.pos;if(n+3>e.posMax)return false;if(58!==e.src.charCodeAt(n))return false;if(47!==e.src.charCodeAt(n+1))return false;if(47!==e.src.charCodeAt(n+2))return false;const r=e.pending.match(Wl);if(!r)return false;const o=r[1],i=e.md.linkify.matchAtStart(e.src.slice(n-o.length));if(!i)return false;let a=i.url;if(a.length<=o.length)return false;a=a.replace(/\*+$/,"");const s=e.md.normalizeLink(a);if(!e.md.validateLink(s))return false;if(!t){e.pending=e.pending.slice(0,-o.length);const t=e.push("link_open","a",1);t.attrs=[["href",s]],t.markup="linkify",t.info="auto";e.push("text","",0).content=e.md.normalizeLinkText(a);const n=e.push("link_close","a",-1);n.markup="linkify",n.info="auto";}return e.pos+=a.length-o.length,true}],["newline",function(e,t){let n=e.pos;if(10!==e.src.charCodeAt(n))return false;const r=e.pending.length-1,o=e.posMax;if(!t)if(r>=0&&32===e.pending.charCodeAt(r))if(r>=1&&32===e.pending.charCodeAt(r-1)){let t=r-1;for(;t>=1&&32===e.pending.charCodeAt(t-1);)t--;e.pending=e.pending.slice(0,t),e.push("hardbreak","br",0);}else e.pending=e.pending.slice(0,-1),e.push("softbreak","br",0);else e.push("softbreak","br",0);for(n++;n=r)return false;let o=e.src.charCodeAt(n);if(10===o){for(t||e.push("hardbreak","br",0),n++;n=55296&&o<=56319&&n+1=56320&&t<=57343&&(i+=e.src[n+1],n++);}const a="\\"+i;if(!t){const t=e.push("text_special","",0);o<256&&0!==Vl[o]?t.content=i:t.content=a,t.markup=a,t.info="escape";}return e.pos=n+1,true}],["backticks",function(e,t){let n=e.pos;if(96!==e.src.charCodeAt(n))return false;const r=n;n++;const o=e.posMax;for(;n=u)return false;if(l=p,o=e.md.helpers.parseLinkDestination(e.src,p,e.posMax),o.ok){for(a=e.md.normalizeLink(o.str),e.md.validateLink(a)?p=o.pos:a="",l=p;p=u||41!==e.src.charCodeAt(p))&&(c=true),p++;}if(c){if(void 0===e.env.references)return false;if(p=0?r=e.src.slice(l,p++):p=g+1):p=g+1,r||(r=e.src.slice(h,g)),i=e.env.references[il(r)],!i)return e.pos=d,false;a=i.href,s=i.title;}if(!t){e.pos=h,e.posMax=g;const t=[["href",a]];e.push("link_open","a",1).attrs=t,s&&t.push(["title",s]),e.linkLevel++,e.md.inline.tokenize(e),e.linkLevel--,e.push("link_close","a",-1);}return e.pos=p,e.posMax=u,true}],["image",function(e,t){let n,r,o,i,a,s,l,c,d="";const u=e.pos,h=e.posMax;if(33!==e.src.charCodeAt(e.pos))return false;if(91!==e.src.charCodeAt(e.pos+1))return false;const g=e.pos+2,p=e.md.helpers.parseLinkLabel(e,e.pos+1,false);if(p<0)return false;if(i=p+1,i=h)return false;for(c=i,s=e.md.helpers.parseLinkDestination(e.src,i,e.posMax),s.ok&&(d=e.md.normalizeLink(s.str),e.md.validateLink(d)?i=s.pos:d=""),c=i;i=h||41!==e.src.charCodeAt(i))return e.pos=u,false;i++;}else {if(void 0===e.env.references)return false;if(i=0?o=e.src.slice(c,i++):i=p+1):i=p+1,o||(o=e.src.slice(g,p)),a=e.env.references[il(o)],!a)return e.pos=u,false;d=a.href,l=a.title;}if(!t){r=e.src.slice(g,p);const t=[];e.md.inline.parse(r,e.md,e.env,t);const n=e.push("image","img",0),o=[["src",d],["alt",""]];n.attrs=o,n.children=t,n.content=r,l&&o.push(["title",l]);}return e.pos=i,e.posMax=h,true}],["autolink",function(e,t){let n=e.pos;if(60!==e.src.charCodeAt(n))return false;const r=e.pos,o=e.posMax;for(;;){if(++n>=o)return false;const t=e.src.charCodeAt(n);if(60===t)return false;if(62===t)break}const i=e.src.slice(r+1,n);if(Jl.test(i)){const n=e.md.normalizeLink(i);if(!e.md.validateLink(n))return false;if(!t){const t=e.push("link_open","a",1);t.attrs=[["href",n]],t.markup="autolink",t.info="auto";e.push("text","",0).content=e.md.normalizeLinkText(i);const r=e.push("link_close","a",-1);r.markup="autolink",r.info="auto";}return e.pos+=i.length+2,true}if(Yl.test(i)){const n=e.md.normalizeLink("mailto:"+i);if(!e.md.validateLink(n))return false;if(!t){const t=e.push("link_open","a",1);t.attrs=[["href",n]],t.markup="autolink",t.info="auto";e.push("text","",0).content=e.md.normalizeLinkText(i);const r=e.push("link_close","a",-1);r.markup="autolink",r.info="auto";}return e.pos+=i.length+2,true}return false}],["html_inline",function(e,t){if(!e.md.options.html)return false;const n=e.posMax,r=e.pos;if(60!==e.src.charCodeAt(r)||r+2>=n)return false;const o=e.src.charCodeAt(r+1);if(33!==o&&63!==o&&47!==o&&!function(e){const t=32|e;return t>=97&&t<=122}(o))return false;const i=e.src.slice(r).match(Ol);if(!i)return false;if(!t){const t=e.push("html_inline","",0);t.content=i[0],a=t.content,/^\s]/i.test(a)&&e.linkLevel++,function(e){return /^<\/a\s*>/i.test(e)}(t.content)&&e.linkLevel--;}var a;return e.pos+=i[0].length,true}],["entity",function(e,t){const n=e.pos,r=e.posMax;if(38!==e.src.charCodeAt(n))return false;if(n+1>=r)return false;if(35===e.src.charCodeAt(n+1)){const r=e.src.slice(n).match(Xl);if(r){if(!t){const t="x"===r[1][0].toLowerCase()?parseInt(r[1].slice(1),16):parseInt(r[1],10),n=e.push("text_special","",0);n.content=Hs(t)?Us(t):Us(65533),n.markup=r[0],n.info="entity";}return e.pos+=r[0].length,true}}else {const r=e.src.slice(n).match(ec);if(r){const n=Os(r[0]);if(n!==r[0]){if(!t){const t=e.push("text_special","",0);t.content=n,t.markup=r[0],t.info="entity";}return e.pos+=r[0].length,true}}}return false}]],rc=[["balance_pairs",function(e){const t=e.tokens_meta,n=e.tokens_meta.length;tc(e.delimiters);for(let r=0;r0&&r++,"text"===o[t].type&&t+1=e.pos)throw new Error("inline rule didn't increment state.pos");break}}else e.pos=e.posMax;a||e.pos++,i[t]=e.pos;},oc.prototype.tokenize=function(e){const t=this.ruler.getRules(""),n=t.length,r=e.posMax,o=e.md.options.maxNesting;for(;e.pos=e.pos)throw new Error("inline rule didn't increment state.pos");break}if(a){if(e.pos>=r)break}else e.pending+=e.src[e.pos++];}e.pending&&e.pushPending();},oc.prototype.parse=function(e,t,n,r){const o=new this.State(e,t,n,r);this.tokenize(o);const i=this.ruler2.getRules(""),a=i.length;for(let s=0;s=3&&":"===e[t-3]||t>=3&&"/"===e[t-3]?0:r.match(n.re.no_http)[0].length:0}},"mailto:":{validate:function(e,t,n){const r=e.slice(t);return n.re.mailto||(n.re.mailto=new RegExp("^"+n.re.src_email_name+"@"+n.re.src_host_strict,"i")),n.re.mailto.test(r)?r.match(n.re.mailto)[0].length:0}}},uc="biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split("|");function hc(e){const t=e.re=function(e){const t={};e=e||{},t.src_Any=hs.source,t.src_Cc=gs.source,t.src_Z=fs.source,t.src_P=ps.source,t.src_ZPCc=[t.src_Z,t.src_P,t.src_Cc].join("|"),t.src_ZCc=[t.src_Z,t.src_Cc].join("|");const n="[><|]";return t.src_pseudo_letter="(?:(?![><|]|"+t.src_ZPCc+")"+t.src_Any+")",t.src_ip4="(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",t.src_auth="(?:(?:(?!"+t.src_ZCc+"|[@/\\[\\]()]).)+@)?",t.src_port="(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?",t.src_host_terminator="(?=$|[><|]|"+t.src_ZPCc+")(?!"+(e["---"]?"-(?!--)|":"-|")+"_|:\\d|\\.-|\\.(?!$|"+t.src_ZPCc+"))",t.src_path="(?:[/?#](?:(?!"+t.src_ZCc+"|"+n+"|[()[\\]{}.,\"'?!\\-;]).|\\[(?:(?!"+t.src_ZCc+"|\\]).)*\\]|\\((?:(?!"+t.src_ZCc+"|[)]).)*\\)|\\{(?:(?!"+t.src_ZCc+'|[}]).)*\\}|\\"(?:(?!'+t.src_ZCc+'|["]).)+\\"|\\\'(?:(?!'+t.src_ZCc+"|[']).)+\\'|\\'(?="+t.src_pseudo_letter+"|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!"+t.src_ZCc+"|[.]|$)|"+(e["---"]?"\\-(?!--(?:[^-]|$))(?:-*)|":"\\-+|")+",(?!"+t.src_ZCc+"|$)|;(?!"+t.src_ZCc+"|$)|\\!+(?!"+t.src_ZCc+"|[!]|$)|\\?(?!"+t.src_ZCc+"|[?]|$))+|\\/)?",t.src_email_name='[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*',t.src_xn="xn--[a-z0-9\\-]{1,59}",t.src_domain_root="(?:"+t.src_xn+"|"+t.src_pseudo_letter+"{1,63})",t.src_domain="(?:"+t.src_xn+"|(?:"+t.src_pseudo_letter+")|(?:"+t.src_pseudo_letter+"(?:-|"+t.src_pseudo_letter+"){0,61}"+t.src_pseudo_letter+"))",t.src_host="(?:(?:(?:(?:"+t.src_domain+")\\.)*"+t.src_domain+"))",t.tpl_host_fuzzy="(?:"+t.src_ip4+"|(?:(?:(?:"+t.src_domain+")\\.)+(?:%TLDS%)))",t.tpl_host_no_ip_fuzzy="(?:(?:(?:"+t.src_domain+")\\.)+(?:%TLDS%))",t.src_host_strict=t.src_host+t.src_host_terminator,t.tpl_host_fuzzy_strict=t.tpl_host_fuzzy+t.src_host_terminator,t.src_host_port_strict=t.src_host+t.src_port+t.src_host_terminator,t.tpl_host_port_fuzzy_strict=t.tpl_host_fuzzy+t.src_port+t.src_host_terminator,t.tpl_host_port_no_ip_fuzzy_strict=t.tpl_host_no_ip_fuzzy+t.src_port+t.src_host_terminator,t.tpl_host_fuzzy_test="localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:"+t.src_ZPCc+"|>|$))",t.tpl_email_fuzzy='(^|[><|]|"|\\(|'+t.src_ZCc+")("+t.src_email_name+"@"+t.tpl_host_fuzzy_strict+")",t.tpl_link_fuzzy="(^|(?![.:/\\-_@])(?:[$+<=>^`||]|"+t.src_ZPCc+"))((?![$+<=>^`||])"+t.tpl_host_port_fuzzy_strict+t.src_path+")",t.tpl_link_no_ip_fuzzy="(^|(?![.:/\\-_@])(?:[$+<=>^`||]|"+t.src_ZPCc+"))((?![$+<=>^`||])"+t.tpl_host_port_no_ip_fuzzy_strict+t.src_path+")",t}(e.__opts__),n=e.__tlds__.slice();function r(e){return e.replace("%TLDS%",t.src_tlds)}e.onCompile(),e.__tlds_replaced__||n.push("a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]"),n.push(t.src_xn),t.src_tlds=n.join("|"),t.email_fuzzy=RegExp(r(t.tpl_email_fuzzy),"i"),t.link_fuzzy=RegExp(r(t.tpl_link_fuzzy),"i"),t.link_no_ip_fuzzy=RegExp(r(t.tpl_link_no_ip_fuzzy),"i"),t.host_fuzzy_test=RegExp(r(t.tpl_host_fuzzy_test),"i");const o=[];function i(e,t){throw new Error('(LinkifyIt) Invalid schema "'+e+'": '+t)}e.__compiled__={},Object.keys(e.__schemas__).forEach(function(t){const n=e.__schemas__[t];if(null===n)return;const r={validate:null,link:null};if(e.__compiled__[t]=r,"[object Object]"===ac(n))return !function(e){return "[object RegExp]"===ac(e)}(n.validate)?sc(n.validate)?r.validate=n.validate:i(t,n):r.validate=function(e){return function(t,n){const r=t.slice(n);return e.test(r)?r.match(e)[0].length:0}}(n.validate),void(sc(n.normalize)?r.normalize=n.normalize:n.normalize?i(t,n):r.normalize=function(e,t){t.normalize(e);});!function(e){return "[object String]"===ac(e)}(n)?i(t,n):o.push(t);}),o.forEach(function(t){e.__compiled__[e.__schemas__[t]]&&(e.__compiled__[t].validate=e.__compiled__[e.__schemas__[t]].validate,e.__compiled__[t].normalize=e.__compiled__[e.__schemas__[t]].normalize);}),e.__compiled__[""]={validate:null,normalize:function(e,t){t.normalize(e);}};const a=Object.keys(e.__compiled__).filter(function(t){return t.length>0&&e.__compiled__[t]}).map(lc).join("|");e.re.schema_test=RegExp("(^|(?!_)(?:[><|]|"+t.src_ZPCc+"))("+a+")","i"),e.re.schema_search=RegExp("(^|(?!_)(?:[><|]|"+t.src_ZPCc+"))("+a+")","ig"),e.re.schema_at_start=RegExp("^"+e.re.schema_search.source,"i"),e.re.pretest=RegExp("("+e.re.schema_test.source+")|("+e.re.host_fuzzy_test.source+")|@","i"),function(e){e.__index__=-1,e.__text_cache__="";}(e);}function gc(e,t){const n=e.__index__,r=e.__last_index__,o=e.__text_cache__.slice(n,r);this.schema=e.__schema__.toLowerCase(),this.index=n+t,this.lastIndex=r+t,this.raw=o,this.text=o,this.url=o;}function pc(e,t){const n=new gc(e,t);return e.__compiled__[n.schema].normalize(n,e),n}function mc(e,t){if(!(this instanceof mc))return new mc(e,t);var n;t||(n=e,Object.keys(n||{}).reduce(function(e,t){return e||cc.hasOwnProperty(t)},false)&&(t=e,e={})),this.__opts__=ic({},cc,t),this.__index__=-1,this.__last_index__=-1,this.__schema__="",this.__text_cache__="",this.__schemas__=ic({},dc,e),this.__compiled__={},this.__tlds__=uc,this.__tlds_replaced__=false,this.re={},hc(this);}mc.prototype.add=function(e,t){return this.__schemas__[e]=t,hc(this),this},mc.prototype.set=function(e){return this.__opts__=ic(this.__opts__,e),this},mc.prototype.test=function(e){if(this.__text_cache__=e,this.__index__=-1,!e.length)return false;let t,n,r,o,i,a,s,l,c;if(this.re.schema_test.test(e))for(s=this.re.schema_search,s.lastIndex=0;null!==(t=s.exec(e));)if(o=this.testSchemaAt(e,t[2],s.lastIndex),o){this.__schema__=t[2],this.__index__=t.index+t[1].length,this.__last_index__=t.index+t[0].length+o;break}return this.__opts__.fuzzyLink&&this.__compiled__["http:"]&&(l=e.search(this.re.host_fuzzy_test),l>=0&&(this.__index__<0||l=0&&null!==(r=e.match(this.re.email_fuzzy))&&(i=r.index+r[1].length,a=r.index+r[0].length,(this.__index__<0||ithis.__last_index__)&&(this.__schema__="mailto:",this.__index__=i,this.__last_index__=a))),this.__index__>=0},mc.prototype.pretest=function(e){return this.re.pretest.test(e)},mc.prototype.testSchemaAt=function(e,t,n){return this.__compiled__[t.toLowerCase()]?this.__compiled__[t.toLowerCase()].validate(e,n,this):0},mc.prototype.match=function(e){const t=[];let n=0;this.__index__>=0&&this.__text_cache__===e&&(t.push(pc(this,n)),n=this.__last_index__);let r=n?e.slice(n):e;for(;this.test(r);)t.push(pc(this,n)),r=r.slice(this.__last_index__),n+=this.__last_index__;return t.length?t:null},mc.prototype.matchAtStart=function(e){if(this.__text_cache__=e,this.__index__=-1,!e.length)return null;const t=this.re.schema_at_start.exec(e);if(!t)return null;const n=this.testSchemaAt(e,t[2],t[0].length);return n?(this.__schema__=t[2],this.__index__=t.index+t[1].length,this.__last_index__=t.index+t[0].length+n,pc(this,0)):null},mc.prototype.tlds=function(e,t){return e=Array.isArray(e)?e:[e],t?(this.__tlds__=this.__tlds__.concat(e).sort().filter(function(e,t,n){return e!==n[t-1]}).reverse(),hc(this),this):(this.__tlds__=e.slice(),this.__tlds_replaced__=true,hc(this),this)},mc.prototype.normalize=function(e){e.schema||(e.url="http://"+e.url),"mailto:"!==e.schema||/^mailto:/i.test(e.url)||(e.url="mailto:"+e.url);},mc.prototype.onCompile=function(){};const fc=2147483647,bc=36,yc=/^xn--/,vc=/[^\0-\x7F]/,wc=/[\x2E\u3002\uFF0E\uFF61]/g,xc={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},kc=Math.floor,Sc=String.fromCharCode;function Cc(e){throw new RangeError(xc[e])}function Ec(e,t){const n=e.split("@");let r="";n.length>1&&(r=n[0]+"@",e=n[1]);const o=function(e,t){const n=[];let r=e.length;for(;r--;)n[r]=t(e[r]);return n}((e=e.replace(wc,".")).split("."),t).join(".");return r+o}function _c(e){const t=[];let n=0;const r=e.length;for(;n=55296&&o<=56319&&n=48&&e<58?e-48+26:e>=65&&e<91?e-65:e>=97&&e<123?e-97:bc},Tc=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},Mc=function(e,t,n){let r=0;for(e=n?kc(e/700):e>>1,e+=kc(e/t);e>455;r+=bc)e=kc(e/35);return kc(r+36*e/(e+38))},Ic=function(e){const t=[],n=e.length;let r=0,o=128,i=72,a=e.lastIndexOf("-");a<0&&(a=0);for(let s=0;s=128&&Cc("not-basic"),t.push(e.charCodeAt(s));for(let s=a>0?a+1:0;s=n&&Cc("invalid-input");const a=Ac(e.charCodeAt(s++));a>=bc&&Cc("invalid-input"),a>kc((fc-r)/t)&&Cc("overflow"),r+=a*t;const l=o<=i?1:o>=i+26?26:o-i;if(akc(fc/c)&&Cc("overflow"),t*=c;}const l=t.length+1;i=Mc(r-a,l,0==a),kc(r/l)>fc-o&&Cc("overflow"),o+=kc(r/l),r%=l,t.splice(r++,0,o);}return String.fromCodePoint(...t)},Nc=function(e){const t=[],n=(e=_c(e)).length;let r=128,o=0,i=72;for(const l of e)l<128&&t.push(Sc(l));const a=t.length;let s=a;for(a&&t.push("-");s=r&&tkc((fc-o)/l)&&Cc("overflow"),o+=(n-r)*l,r=n;for(const c of e)if(cfc&&Cc("overflow"),c===r){let e=o;for(let n=bc;;n+=bc){const r=n<=i?1:n>=i+26?26:n-i;if(e=0))try{t.hostname=Lc(t.hostname);}catch(n){}return Za(Ya(t))}function Fc(e){const t=ds(e,true);if(t.hostname&&(!t.protocol||Oc.indexOf(t.protocol)>=0))try{t.hostname=Dc(t.hostname);}catch(n){}return Qa(Ya(t),Qa.defaultChars+"%")}function jc(e,t){if(!(this instanceof jc))return new jc(e,t);t||zs(e)||(t=e||{},e="default"),this.inline=new oc,this.block=new $l,this.core=new Il,this.renderer=new dl,this.linkify=new mc,this.validateLink=Bc,this.normalizeLink=zc,this.normalizeLinkText=Fc,this.utils=sl,this.helpers=js({},ll),this.options={},this.configure(e),t&&this.set(t);}jc.prototype.set=function(e){return js(this.options,e),this},jc.prototype.configure=function(e){const t=this;if(zs(e)){const t=e;if(!(e=Rc[t]))throw new Error('Wrong `markdown-it` preset "'+t+'", check name')}if(!e)throw new Error("Wrong `markdown-it` preset, can't be empty");return e.options&&t.set(e.options),e.components&&Object.keys(e.components).forEach(function(n){e.components[n].rules&&t[n].ruler.enableOnly(e.components[n].rules),e.components[n].rules2&&t[n].ruler2.enableOnly(e.components[n].rules2);}),this},jc.prototype.enable=function(e,t){let n=[];Array.isArray(e)||(e=[e]),["core","block","inline"].forEach(function(t){n=n.concat(this[t].ruler.enable(e,true));},this),n=n.concat(this.inline.ruler2.enable(e,true));const r=e.filter(function(e){return n.indexOf(e)<0});if(r.length&&!t)throw new Error("MarkdownIt. Failed to enable unknown rule(s): "+r);return this},jc.prototype.disable=function(e,t){let n=[];Array.isArray(e)||(e=[e]),["core","block","inline"].forEach(function(t){n=n.concat(this[t].ruler.disable(e,true));},this),n=n.concat(this.inline.ruler2.disable(e,true));const r=e.filter(function(e){return n.indexOf(e)<0});if(r.length&&!t)throw new Error("MarkdownIt. Failed to disable unknown rule(s): "+r);return this},jc.prototype.use=function(e){const t=[this].concat(Array.prototype.slice.call(arguments,1));return e.apply(e,t),this},jc.prototype.parse=function(e,t){if("string"!=typeof e)throw new Error("Input data should be a String");const n=new this.core.State(e,this,t);return this.core.process(n),n.tokens},jc.prototype.render=function(e,t){return t=t||{},this.renderer.render(this.parse(e,t),this.options,t)},jc.prototype.parseInline=function(e,t){const n=new this.core.State(e,this,t);return n.inlineMode=true,this.core.process(n),n.tokens},jc.prototype.renderInline=function(e,t){return t=t||{},this.renderer.render(this.parseInline(e,t),this.options,t)};var $c=false,Hc={false:"push",true:"unshift",after:"push",before:"unshift"},Uc={isPermalinkSymbol:true};function Wc(e,t,n,r){var o;if(!$c){var i="Using deprecated markdown-it-anchor permalink option, see https://github.com/valeriangalliat/markdown-it-anchor#permalinks";"object"==typeof process&&process&&process.emitWarning?process.emitWarning(i):console.warn(i),$c=true;}var a=[Object.assign(new n.Token("link_open","a",1),{attrs:[].concat(t.permalinkClass?[["class",t.permalinkClass]]:[],[["href",t.permalinkHref(e,n)]],Object.entries(t.permalinkAttrs(e,n)))}),Object.assign(new n.Token("html_block","",0),{content:t.permalinkSymbol,meta:Uc}),new n.Token("link_close","a",-1)];t.permalinkSpace&&n.tokens[r+1].children[Hc[t.permalinkBefore]](Object.assign(new n.Token("text","",0),{content:" "})),(o=n.tokens[r+1].children)[Hc[t.permalinkBefore]].apply(o,a);}function Vc(e){return "#"+e}function Gc(e){return {}}var Qc={class:"header-anchor",symbol:"#",renderHref:Vc,renderAttrs:Gc};function Kc(e){function t(n){return n=Object.assign({},t.defaults,n),function(t,r,o,i){return e(t,n,r,o,i)}}return t.defaults=Object.assign({},Qc),t.renderPermalinkImpl=e,t}function Zc(e){var t=[],n=e.filter(function(e){if("class"!==e[0])return true;t.push(e[1]);});return t.length>0&&n.unshift(["class",t.join(" ")]),n}var Yc=Kc(function(e,t,n,r,o){var i,a=[Object.assign(new r.Token("link_open","a",1),{attrs:Zc([].concat(t.class?[["class",t.class]]:[],[["href",t.renderHref(e,r)]],t.ariaHidden?[["aria-hidden","true"]]:[],Object.entries(t.renderAttrs(e,r))))}),Object.assign(new r.Token("html_inline","",0),{content:t.symbol,meta:Uc}),new r.Token("link_close","a",-1)];if(t.space){var s="string"==typeof t.space?t.space:" ";r.tokens[o+1].children[Hc[t.placement]](Object.assign(new r.Token("string"==typeof t.space?"html_inline":"text","",0),{content:s}));}(i=r.tokens[o+1].children)[Hc[t.placement]].apply(i,a);});Object.assign(Yc.defaults,{space:true,placement:"after",ariaHidden:false});var Jc=Kc(Yc.renderPermalinkImpl);Jc.defaults=Object.assign({},Yc.defaults,{ariaHidden:true});var Xc=Kc(function(e,t,n,r,o){var i=[Object.assign(new r.Token("link_open","a",1),{attrs:Zc([].concat(t.class?[["class",t.class]]:[],[["href",t.renderHref(e,r)]],Object.entries(t.renderAttrs(e,r))))})].concat(t.safariReaderFix?[new r.Token("span_open","span",1)]:[],r.tokens[o+1].children,t.safariReaderFix?[new r.Token("span_close","span",-1)]:[],[new r.Token("link_close","a",-1)]);r.tokens[o+1]=Object.assign(new r.Token("inline","",0),{children:i});});Object.assign(Xc.defaults,{safariReaderFix:false});var ed=Kc(function(e,t,n,r,o){var i;if(!["visually-hidden","aria-label","aria-describedby","aria-labelledby"].includes(t.style))throw new Error("`permalink.linkAfterHeader` called with unknown style option `"+t.style+"`");if(!["aria-describedby","aria-labelledby"].includes(t.style)&&!t.assistiveText)throw new Error("`permalink.linkAfterHeader` called without the `assistiveText` option in `"+t.style+"` style");if("visually-hidden"===t.style&&!t.visuallyHiddenClass)throw new Error("`permalink.linkAfterHeader` called without the `visuallyHiddenClass` option in `visually-hidden` style");var a=r.tokens[o+1].children.filter(function(e){return "text"===e.type||"code_inline"===e.type}).reduce(function(e,t){return e+t.content},""),s=[],l=[];if(t.class&&l.push(["class",t.class]),l.push(["href",t.renderHref(e,r)]),l.push.apply(l,Object.entries(t.renderAttrs(e,r))),"visually-hidden"===t.style){if(s.push(Object.assign(new r.Token("span_open","span",1),{attrs:[["class",t.visuallyHiddenClass]]}),Object.assign(new r.Token("text","",0),{content:t.assistiveText(a)}),new r.Token("span_close","span",-1)),t.space){var c="string"==typeof t.space?t.space:" ";s[Hc[t.placement]](Object.assign(new r.Token("string"==typeof t.space?"html_inline":"text","",0),{content:c}));}s[Hc[t.placement]](Object.assign(new r.Token("span_open","span",1),{attrs:[["aria-hidden","true"]]}),Object.assign(new r.Token("html_inline","",0),{content:t.symbol,meta:Uc}),new r.Token("span_close","span",-1));}else s.push(Object.assign(new r.Token("html_inline","",0),{content:t.symbol,meta:Uc}));"aria-label"===t.style?l.push(["aria-label",t.assistiveText(a)]):["aria-describedby","aria-labelledby"].includes(t.style)&&l.push([t.style,e]);var d=[Object.assign(new r.Token("link_open","a",1),{attrs:Zc(l)})].concat(s,[new r.Token("link_close","a",-1)]);(i=r.tokens).splice.apply(i,[o+3,0].concat(d)),t.wrapper&&(r.tokens.splice(o,0,Object.assign(new r.Token("html_block","",0),{content:t.wrapper[0]+"\n"})),r.tokens.splice(o+3+d.length+1,0,Object.assign(new r.Token("html_block","",0),{content:t.wrapper[1]+"\n"})));});function td(e,t,n,r){var o=e,i=r;if(n&&Object.prototype.hasOwnProperty.call(t,o))throw new Error("User defined `id` attribute `"+e+"` is not unique. Please fix it in your Markdown to continue.");for(;Object.prototype.hasOwnProperty.call(t,o);)o=e+"-"+i,i+=1;return t[o]=true,o}function nd(e,t){t=Object.assign({},nd.defaults,t),e.core.ruler.push("anchor",function(e){for(var n,r={},o=e.tokens,i=Array.isArray(t.level)?(n=t.level,function(e){return n.includes(e)}):function(e){return function(t){return t>=e}}(t.level),a=0;a=s))&&(u=e.bMarks[f]+e.tShift[f],h=e.eMarks[f],!(u=4)){for(c=u+1;c<=h&&r[(c-u)%i]===e.src[c];c++);if(!(Math.floor((c-u)/i)(e.enabled.indexOf(r)>=0&&(n[r]=t[r]),n),{}));const n=Object.keys(e.shortcuts).reduce((n,r)=>t[r]?Array.isArray(e.shortcuts[r])?(e.shortcuts[r].forEach(e=>{n[e]=r;}),n):(n[e.shortcuts[r]]=r,n):n,{}),r=Object.keys(t);let o;o=0===r.length?"^$":r.map(e=>`:${e}:`).concat(Object.keys(n)).sort().reverse().map(e=>e.replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")).join("|");const i=RegExp(o),a=RegExp(o,"g");return {defs:t,shortcuts:n,scanRE:i,replaceRE:a}}(e.utils.assign({},{defs:{},shortcuts:{},enabled:[]},t||{}));e.renderer.rules.emoji=od,e.core.ruler.after("linkify","emoji",function(e,t,n,r,o){const i=e.utils.arrayReplaceAt,a=e.utils.lib.ucmicro,s=e.utils.has,l=new RegExp([a.Z.source,a.P.source,a.Cc.source].join("|"));function c(e,r,i){let a=0;const c=[];if(e.replace(o,function(r,o,d){let u;if(s(n,r)){if(u=n[r],o>0&&!l.test(d[o-1]))return;if(o+r.lengtha){const t=new i("text","",0);t.content=e.slice(a,o),c.push(t);}const h=new i("emoji","",0);h.markup=u,h.content=t[u],c.push(h),a=o+r.length;}),a=0;l--)t=s[l],"link_open"!==t.type&&"link_close"!==t.type||"auto"===t.info&&(o-=t.nesting),"text"===t.type&&0===o&&r.test(t.content)&&(n[a].children=s=i(s,l,c(t.content,t.level,e.Token)));}}}(e,n.defs,n.shortcuts,n.scanRE,n.replaceRE));}Object.assign(ed.defaults,{style:"visually-hidden",space:true,placement:"after",wrapper:null}),nd.permalink={__proto__:null,legacy:Wc,renderHref:Vc,renderAttrs:Gc,makePermalink:Kc,linkInsideHeader:Yc,ariaHidden:Jc,headerLink:Xc,linkAfterHeader:ed},nd.defaults={level:1,slugify:function(e){return encodeURIComponent(String(e).trim().toLowerCase().replace(/\s+/g,"-"))},uniqueSlugStartIndex:1,tabIndex:"-1",getTokensText:function(e){return e.filter(function(e){return ["text","code_inline"].includes(e.type)}).map(function(e){return e.content}).join("")},permalink:false,renderPermalink:Wc,permalinkClass:Jc.defaults.class,permalinkSpace:Jc.defaults.space,permalinkSymbol:"¶",permalinkBefore:"before"===Jc.defaults.placement,permalinkHref:Jc.defaults.renderHref,permalinkAttrs:Jc.defaults.renderAttrs},nd.default=nd;const ad={angry:[">:(",">:-("],blush:[':")',':-")'],broken_heart:["=0;r--)if(e[r].level===n)return r;return -1}function i(e,t){return "inline"===e[t].type&&function(e){return "paragraph_open"===e.type}(e[t-1])&&function(e){return "list_item_open"===e.type}(e[t-2])&&function(e){return 0===e.content.indexOf("[ ] ")||0===e.content.indexOf("[x] ")||0===e.content.indexOf("[X] ")}(e[t])}function a(r,o){if(r.children.unshift(function(t,n){var r=new n("html_inline","",0),o=e?' disabled="" ':"";0===t.content.indexOf("[ ] ")?r.content='':0!==t.content.indexOf("[x] ")&&0!==t.content.indexOf("[X] ")||(r.content='');return r}(r,o)),r.children[1].content=r.children[1].content.slice(3),r.content=r.content.slice(3),t)if(n){r.children.pop();var i="task-item-"+Math.ceil(1e7*Math.random()-1e3);r.children[0].content=r.children[0].content.slice(0,-1)+' id="'+i+'">',r.children.push(function(e,t,n){var r=new n("html_inline","",0);return r.content='",r.attrs=[{for:t}],r}(r.content,i,o));}else r.children.unshift(function(e){var t=new e("html_inline","",0);return t.content="",t}(o));}return dd=function(s,l){l&&(e=!l.enabled,t=!!l.label,n=!!l.labelAfter),s.core.ruler.after("inline","github-task-lists",function(t){for(var n=t.tokens,s=2;se.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),md=()=>{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/")?`${gd}/${r.slice(6)}`:`${gd}/${r}`}${t})`}))(e):""}catch(e){return console.warn("[Ophel] Failed to load KaTeX CSS resource:",e),""}},fd=(e,{displayMode:t})=>{const n=e.replace(/\r\n?/g,"\n").trim(),r=(()=>{const e=globalThis.katex;return e&&"function"==typeof e.renderToString?e:null})();if(!r){const e=t?`$$\n${n}\n$$`:`$${n}$`,r=t?"div":"span";return `<${r} class="${t?"math-block gh-rendered-math":"math-inline gh-rendered-math"}" data-math="${pd(n)}">${pd(e)}`}try{const e=r.renderToString(n,{displayMode:t,output:"htmlAndMathml",throwOnError:!1,strict:"ignore",trust:!1}),o=t?"div":"span";return `<${o} class="${t?"math-block gh-rendered-math":"math-inline gh-rendered-math"}" data-math="${pd(n)}">${e}`}catch{const e=t?`$$\n${n}\n$$`:`$${n}$`,r=t?"div":"span";return `<${r} class="${t?"math-block gh-rendered-math":"math-inline gh-rendered-math"}" data-math="${pd(n)}">${pd(e)}`}};oa.registerLanguage("javascript",Aa),oa.registerLanguage("js",Aa),oa.registerLanguage("typescript",Pa),oa.registerLanguage("ts",Pa),oa.registerLanguage("python",function(e){const t=e.regex,n=new RegExp("[\\p{XID_Start}_]\\p{XID_Continue}*","u"),r=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],o={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:r,built_in:["__import__","abs","all","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]},i={className:"meta",begin:/^(>>>|\.\.\.) /},a={className:"subst",begin:/\{/,end:/\}/,keywords:o,illegal:/#/},s={begin:/\{\{/,relevance:0},l={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,i],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,i],relevance:10},{begin:/([fF][rR]|[rR][fF]|[fF])'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,i,s,a]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,i,s,a]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fF][rR]|[rR][fF]|[fF])'/,end:/'/,contains:[e.BACKSLASH_ESCAPE,s,a]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,s,a]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},c="[0-9](_?[0-9])*",d=`(\\b(${c}))?\\.(${c})|\\b(${c})\\.`,u=`\\b|${r.join("|")}`,h={className:"number",relevance:0,variants:[{begin:`(\\b(${c})|(${d}))[eE][+-]?(${c})[jJ]?(?=${u})`},{begin:`(${d})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${u})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${u})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${u})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${u})`},{begin:`\\b(${c})[jJ](?=${u})`}]},g={className:"comment",begin:t.lookahead(/# type:/),end:/$/,keywords:o,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:true}]},p={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:true},{begin:/\(/,end:/\)/,excludeBegin:true,excludeEnd:true,keywords:o,contains:["self",i,h,l,e.HASH_COMMENT_MODE]}]};return a.contains=[l,h,i],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:true,keywords:o,illegal:/(<\/|\?)|=>/,contains:[i,h,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},l,g,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,n],scope:{1:"keyword",3:"title.function"},contains:[p]},{variants:[{match:[/\bclass/,/\s+/,n,/\s*/,/\(\s*/,n,/\s*\)/]},{match:[/\bclass/,/\s+/,n]}],scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[h,p,l]}]}}),oa.registerLanguage("css",ua),oa.registerLanguage("html",Ba),oa.registerLanguage("xml",Ba),oa.registerLanguage("vue",Ba),oa.registerLanguage("json",function(e){const t=["true","false","null"],n={scope:"literal",beginKeywords:t.join(" ")};return {name:"JSON",aliases:["jsonc"],keywords:{literal:t},contains:[{className:"attr",begin:/"(\\.|[^\\"\r\n])*"(?=\s*:)/,relevance:1.01},{match:/[{}[\],:]/,className:"punctuation",relevance:0},e.QUOTE_STRING_MODE,n,e.C_NUMBER_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],illegal:"\\S"}}),oa.registerLanguage("java",function(e){const t=e.regex,n="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",r=n+ya("(?:<"+n+"~~~(?:\\s*,\\s*"+n+"~~~)*>)?",/~~~/g,2),o={keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","default","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits","goto","when"],literal:["false","true","null"],type:["char","boolean","long","float","int","byte","short","double"],built_in:["super","this"]},i={className:"meta",begin:"@"+n,contains:[{begin:/\(/,end:/\)/,contains:["self"]}]},a={className:"params",begin:/\(/,end:/\)/,keywords:o,relevance:0,contains:[e.C_BLOCK_COMMENT_MODE],endsParent:true};return {name:"Java",aliases:["jsp"],keywords:o,illegal:/<\/|#/,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{ // eat up @'s in emails to prevent them to be recognized as doctags begin:/\w+@/,relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{begin:/import java\.[a-z]+\./,keywords:"import",relevance:2},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/,className:"string",contains:[e.BACKSLASH_ESCAPE]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{match:[/\b(?:class|interface|enum|extends|implements|new)/,/\s+/,n],className:{1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{begin:[t.concat(/(?!else)/,n),/\s+/,n,/\s+/,/=(?!=)/],className:{1:"type",3:"variable",5:"operator"}},{begin:[/record/,/\s+/,n],className:{1:"keyword",3:"title.class"},contains:[a,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"new throw return else",relevance:0},{begin:["(?:"+r+"\\s+)",e.UNDERSCORE_IDENT_RE,/\s*(?=\()/],className:{2:"title.function"},keywords:o,contains:[{className:"params",begin:/\(/,end:/\)/,keywords:o,relevance:0,contains:[i,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,ba,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},ba,i]}}),oa.registerLanguage("go",function(e){const t={keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"],literal:["true","false","iota","nil"],built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"]};return {name:"Go",aliases:["golang"],keywords:t,illegal:""},i]}}),oa.registerLanguage("bash",ia),oa.registerLanguage("shell",ia),oa.registerLanguage("sh",ia),oa.registerLanguage("sql",function(e){const t=e.regex,n=e.COMMENT("--","$"),r=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],o=r,i=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","versioning","when","whenever","where","width_bucket","window","with","within","without","year","add","asc","collation","desc","final","first","last","view"].filter(e=>!r.includes(e)),a={match:t.concat(/\b/,t.either(...o),/\s*\(/),relevance:0,keywords:{built_in:o}};function s(e){return t.concat(/\b/,t.either(...e.map(e=>e.replace(/\s+/,"\\s+"))),/\b/)}const l={scope:"keyword",match:s(["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"]),relevance:0};return {name:"SQL",case_insensitive:true,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:function(e,{exceptions:t,when:n}={}){const r=n;return t=t||[],e.map(e=>e.match(/\|\d+$/)||t.includes(e)?e:r(e)?`${e}|0`:e)}(i,{when:e=>e.length<3}),literal:["true","false","unknown"],type:["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"],built_in:["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"]},contains:[{scope:"type",match:s(["double precision","large object","with timezone","without timezone"])},l,a,{scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},{scope:"string",variants:[{begin:/'/,end:/'/,contains:[{match:/''/}]}]},{begin:/"/,end:/"/,contains:[{match:/""/}]},e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,n,{scope:"operator",match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0}]}}),oa.registerLanguage("yaml",Oa),oa.registerLanguage("yml",Oa),oa.registerLanguage("diff",ha),oa.registerLanguage("git",ha),oa.registerLanguage("dockerfile",ga),oa.registerLanguage("docker",ga);const bd=(e=false)=>{const t=new jc({html:false,breaks:true,linkify:true,highlight:(e,t)=>{if(t&&oa.getLanguage(t))try{return oa.highlight(e,{language:t}).value}catch{}try{return oa.highlightAuto(e).value}catch{return ""}}});return t.use(hd,{enabled:true,label:false}),t.use(ld),t.use(cd),t.use(nd,{permalink:false}),t.use(rd,"info",{render:(e,t)=>1===e[t].nesting?'
':"
\n"}),t.use(rd,"warning",{render:(e,t)=>1===e[t].nesting?'
':"
\n"}),t.use(rd,"danger",{render:(e,t)=>1===e[t].nesting?'
':"
\n"}),e&&t.use(Va,{delimiters:"all",allowInlineWithSpace:false,render:(e,t)=>fd(e,{displayMode:t})}),t},yd=bd(),vd=bd(true),wd=(e,t=true,n={})=>{if(!e)return "";let r=(n.enableMath?vd:yd).render(e);return t&&(r=r.replace(/\{\{([^\s{}]+)\}\}/g,'{{$1}}')),r=r.replace(/
md(),kd="delete_ui_failed",Sd="delete_batch_aborted_after_ui_failure",Cd="delete_api_org_missing",Ed="delete_api_request_failed",_d="delete_api_not_found_but_visible",Ad=["delete","remove","删除","刪除","削除","삭제","supprimer","eliminar","elimina","löschen","excluir","hapus","हट","मिट"],Td=["cancel","取消","annuler","abbrechen","annulla","キャンセル","취소","batal","cancelar"],Md=/^[a-f0-9-]{36}$/i,Id=[/(^|[^\\])\$\$[\s\S]+?\$\$/m,/\\\[[\s\S]+?\\\]/m],Nd=[/((^|[^\\$])\$[^\s$](?:[^$\n]*[^\s$])?\$(?!\$))/,/\\\([^\n]+?\\\)/];function Ld(e){const t=e.trim();if(!t)return  false;const n=function(e){return e.replace(/```[\s\S]*?```/g,"").replace(/`[^`\n]*`/g,"")}(t);return /^#{1,6}\s/m.test(t)||/\*\*[^*]+\*\*/.test(t)||new RegExp("(?e.test(n))||Nd.some(e=>e.test(n))}const Dd=/\/a\/chat\/s\/([a-z0-9-]+)/i,Rd=/\/share\/([a-z0-9-]+)/i,qd="__appKit_@deepseek/chat_themePreference",Pd='a[href*="/a/chat/s/"]',Bd=".ds-message",Od=`${Bd}:has(.ds-markdown)`,zd=".ds-message:not(:has(.ds-markdown))",Fd=".ds-think-content",jd=[`${zd} > .gh-inline-bookmark + div`,`${zd} > div:not(.gh-user-query-raw):not(.gh-user-query-markdown):not(.ds-focus-ring)`,`${zd} > div.gh-user-query-markdown`].join(", "),$d="https://chat.deepseek.com/",Hd="gh.deepseek.delete.refresh",Ud="data-gh-deepseek-export-root",Wd="data-gh-deepseek-export-role",Vd="user",Gd="assistant",Qd=`[${Ud}="1"] [${Wd}="${Vd}"]`,Kd=`[${Ud}="1"] [${Wd}="${Gd}"]`,Zd="M2 4.88",Yd="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",Jd="delete_api_missing_auth_token",Xd="delete_api_request_failed",eu="delete_api_invalid_response",tu="delete_api_business_failed";const nu=/^(?:\/code)?\/chat\/([^/?#]+)/,ru='[data-testid="send_message"]',ou='[data-testid="message_content"].justify-end',iu=`${ru}, ${ou}`,au='[data-testid="message_text_content"]',su=`${ru} ${au}, ${ou} ${au}`,lu="delete_ui_failed",cu="delete_batch_aborted_after_ui_failure";const du=function(){const e=globalThis.ReactDOM;if(!e||"function"!=typeof e.createPortal)throw new Error("[Ophel] ReactDOM CDN runtime is missing");return e}(),uu=du.createPortal;du.flushSync,du.unstable_batchedUpdates,du.version;const hu="ophel-global-tooltip-styles",gu=8,pu=10;function mu(e){if(!e||"undefined"==typeof document)return null;const t=e.getRootNode?.();return t instanceof ShadowRoot?t:document.body}function fu(e){if("undefined"==typeof document||!e||e instanceof ShadowRoot)return;if(document.getElementById(hu))return;const t=document.createElement("style");t.id=hu,t.textContent="\n  .ophel-tooltip {\n    background-color: rgba(30, 30, 35, 0.95);\n    color: #ffffff;\n    padding: 6px 12px;\n    border-radius: 6px;\n    font-size: 13px;\n    line-height: 1.5;\n    z-index: 2147483647;\n    pointer-events: none;\n    white-space: pre-wrap;\n    word-wrap: break-word;\n    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);\n    border: 1px solid rgba(255, 255, 255, 0.1);\n    backdrop-filter: blur(4px);\n    animation: tooltip-fade-in 0.15s ease-out;\n  }\n\n  @keyframes tooltip-fade-in {\n    from {\n      opacity: 0;\n      transform: scale(0.95);\n    }\n    to {\n      opacity: 1;\n      transform: scale(1);\n    }\n  }\n",document.head.appendChild(t);}function bu(e,t,n={}){const{preferredPlacement:r="bottom",gap:o=gu,viewportPadding:i=pu}=n,a="top"===r?e.top-t.height-o:e.bottom+o,s="top"===r?e.bottom+o:e.top-t.height-o;let l=a;(lwindow.innerHeight-i)&&(l=s),lwindow.innerHeight-i&&(l=Math.max(i,window.innerHeight-t.height-i));let c=e.left+e.width/2-t.width/2;return cwindow.innerWidth-i&&(c=window.innerWidth-t.width-i),{top:l,left:c}}const yu=new class{tooltipEl=null;activeTrigger=null;activeContainer=null;positionOptions={};handleWindowChange=()=>{this.positionTooltip();};handleWindowBlur=()=>{this.hide();};handleVisibilityChange=()=>{document.hidden&&this.hide();};show(e,t,n=260,r={}){if(!t||!e.isConnected)return void this.hide(e);const o=mu(e);if(!o)return;fu(o),this.activeTrigger&&this.activeTrigger!==e&&this.activeTrigger.removeAttribute("aria-describedby"),this.activeTrigger=e,this.activeContainer=o,this.positionOptions=r;const i=this.ensureTooltipElement(o);i.textContent=t,i.style.maxWidth="number"==typeof n?`${n}px`:n,i.style.opacity="0",e.setAttribute("aria-describedby",i.id),this.attachGlobalListeners(),this.positionTooltip();}hide(e){e&&this.activeTrigger&&e!==this.activeTrigger||(this.activeTrigger&&this.activeTrigger.removeAttribute("aria-describedby"),this.activeTrigger=null,this.positionOptions={},this.detachGlobalListeners(),this.tooltipEl?.parentNode&&this.tooltipEl.parentNode.removeChild(this.tooltipEl));}ensureTooltipElement(e){return this.tooltipEl||(this.tooltipEl=document.createElement("div"),this.tooltipEl.className="ophel-tooltip",this.tooltipEl.id=`ophel-tooltip-${Math.random().toString(36).slice(2,9)}`,this.tooltipEl.setAttribute("role","tooltip"),this.tooltipEl.style.position="fixed",this.tooltipEl.style.top="0",this.tooltipEl.style.left="0",this.tooltipEl.style.pointerEvents="none",this.tooltipEl.style.zIndex="2147483647"),this.tooltipEl.parentNode===e&&this.tooltipEl.isConnected||e.appendChild(this.tooltipEl),this.tooltipEl}positionTooltip(){if(!this.tooltipEl||!this.activeTrigger||!this.tooltipEl.isConnected)return;const e=this.activeTrigger.getBoundingClientRect(),t=this.tooltipEl.getBoundingClientRect(),{top:n,left:r}=bu(e,t,this.positionOptions);this.tooltipEl.style.top=`${n}px`,this.tooltipEl.style.left=`${r}px`,this.tooltipEl.style.opacity="1";}attachGlobalListeners(){window.addEventListener("scroll",this.handleWindowChange,true),window.addEventListener("resize",this.handleWindowChange),window.addEventListener("blur",this.handleWindowBlur),document.addEventListener("visibilitychange",this.handleVisibilityChange);}detachGlobalListeners(){window.removeEventListener("scroll",this.handleWindowChange,true),window.removeEventListener("resize",this.handleWindowChange),window.removeEventListener("blur",this.handleWindowBlur),document.removeEventListener("visibilitychange",this.handleVisibilityChange);}};function vu(e,t){let n=null;const r=()=>{n&&(clearTimeout(n),n=null);},o=()=>{r(),yu.hide(e);},i=()=>{var o;(r(),"function"==typeof(o=t.disabled)?o():Boolean(o))||(n=setTimeout(()=>{if(!e.isConnected)return;const n=t.getContent();yu.show(e,n,t.maxWidth??260,t);},t.delay??300));};return e.addEventListener("mouseenter",i),e.addEventListener("mouseleave",o),e.addEventListener("focus",i),e.addEventListener("blur",o),e.addEventListener("pointerdown",o),e.addEventListener("click",o),{hide:o,destroy:()=>{e.removeEventListener("mouseenter",i),e.removeEventListener("mouseleave",o),e.removeEventListener("focus",i),e.removeEventListener("blur",o),e.removeEventListener("pointerdown",o),e.removeEventListener("click",o),o();}}}const wu=({content:e,children:t,maxWidth:n=260,delay:r=300,className:o="",triggerClassName:i="",triggerStyle:a={},disabled:s=false})=>{const[l,c]=B(false),[d,u]=B({top:0,left:0}),[h,g]=B(false),[p,m]=B(null),f=P(null),b=P(null),y=P(null),v=P(false),w=E(()=>{v.current=false,y.current&&(clearTimeout(y.current),y.current=null),c(false),g(false);},[]),x=E(()=>{v.current=true,s||(y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{c(true),g(true);},r));},[r,s]),k=E(()=>{const e=f.current?.getBoundingClientRect(),t=b.current?.getBoundingClientRect();e&&t&&u(bu(e,t,{preferredPlacement:"bottom"}));},[]);return M(()=>{if(f.current){const e=mu(f.current);m(e),fu(e);}},[]),M(()=>{(l||h)&&f.current&&(k(),h&&g(false));},[e,h,l,k]),M(()=>{if(!l&&!h)return;const e=()=>{k();},t=()=>{document.hidden&&w();};return window.addEventListener("scroll",e,true),window.addEventListener("resize",e),window.addEventListener("blur",w),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("scroll",e,true),window.removeEventListener("resize",e),window.removeEventListener("blur",w),document.removeEventListener("visibilitychange",t);}},[w,h,l,k]),M(()=>()=>{y.current&&clearTimeout(y.current);},[]),M(()=>{s?w():v.current&&(y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{c(true),g(true);},r));},[r,s,w]),ye("div",{ref:f,className:`ophel-tooltip-trigger ${o} ${i}`,onMouseEnter:x,onMouseLeave:w,onFocus:x,onBlur:w,style:{display:"inline-flex",...a},children:[t,l&&e&&p&&uu(
   be("div",{ref:b,className:"ophel-tooltip",style:{position:"fixed",top:d.top,left:d.left,maxWidth:n,opacity:h?0:1},children:e}),p)]})};let xu;xu={type:"userscript",storage:{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)}},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:re("claudeNotOnSiteHint")};const e=document.cookie.match(/sessionKey=([^;]+)/);return e&&e[1]?{success:true,sessionKey:decodeURIComponent(e[1])}:{success:false,error:re("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],i=o?.rate_limit_tier,a=o?.capabilities||[],s=o?.api_disabled_reason;let l="Unknown";"default_claude_max_5x"===i?l="Max(5x)":"default_claude_max_20x"===i?l="Max(20x)":"default_claude_ai"===i?l="Free":"auto_api_evaluation"===i?l="out_of_credits"===s?"API(无额度)":"API":a.includes("claude_max")?l="Max":a.includes("api")?l="API":a.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:re("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:re("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 i=0;-1!==o&&(i=(o+1)%r.length);const a=r[i];if(!a)return {success:!1,error:"nextKeyNotFound"};if(a.key){const e=new Date(Date.now()+31536e6).toUTCString();document.cookie=`sessionKey=${encodeURIComponent(a.key)}; domain=.claude.ai; path=/; expires=${e}; secure; samesite=lax`;}return e?.state&&(e.state.currentKeyId=a.id,GM_setValue("claudeSessionKeys",e)),location.href="https://claude.ai/",{success:!0,keyName:a.name}}catch(e){return {success:false,error:e.message}}}};const ku=Object.freeze(Object.defineProperty({__proto__:null,get platform(){return xu}},Symbol.toStringTag,{value:"Module"})),Su="http://www.w3.org/2000/svg";function Cu(e,t={}){const n=document.createElementNS(Su,e);for(const[r,o]of Object.entries(t))n.setAttribute(r,o);return n}function Eu(e={}){const{size:t=16,color:n="currentColor",className:r=""}=e,o=Cu("svg",{xmlns:Su,width:t.toString(),height:t.toString(),viewBox:"0 0 24 24",fill:"none",stroke:n,"stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...r?{class:r}:{}}),i=Cu("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),a=Cu("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"});return o.appendChild(i),o.appendChild(a),o}function _u(e,t={}){for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(function(e={}){const{size:t=16,color:n="currentColor",className:r=""}=e,o=Cu("svg",{xmlns:Su,width:t.toString(),height:t.toString(),viewBox:"0 0 24 24",fill:"none",stroke:n,"stroke-width":"2.5","stroke-linecap":"round","stroke-linejoin":"round",...r?{class:r}:{}}),i=Cu("polyline",{points:"20 6 9 17 4 12"});return o.appendChild(i),o}({...t,color:"#22c55e"})),setTimeout(()=>{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(Eu(t));},1500);}function Au(e,t={}){e.querySelectorAll(".gh-code-copy-btn, .gh-table-copy-btn").forEach(e=>{if(!e.querySelector("svg")){for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(Eu(t));}});}const Tu="CHECK_PERMISSIONS",Mu="REQUEST_PERMISSIONS",Iu="CLEAR_ALL_DATA",Nu="RESTORE_DATA";function Lu(e){return chrome.runtime.sendMessage(e)}const Du="GH_MONITOR_INIT",Ru="GH_MONITOR_START",qu="GH_MONITOR_COMPLETE",Pu="OPHEL_GEMINI_MYSTUFF_SYNC_REQUEST",Bu="OPHEL_GEMINI_MYSTUFF_CACHE_SYNC",Ou="OPHEL_EXTENSION_UPDATE_AVAILABLE";let zu=null,Fu=null,ju=false;function $u(){if("undefined"==typeof window)return null;const e=window.trustedTypes;return e?.createPolicy?e:null}function Hu(e){return `ophel-userscript-${e}-${Math.random().toString(36).slice(2,8)}`}function Uu(e){if(zu||function(){if(zu)return  true;const e=$u();if(!e)return  false;try{return zu=e.createPolicy(Hu("html"),{createHTML:e=>e}),!0}catch(t){return console.warn("[TrustedTypes] Failed to create Trusted Types policy:",t),false}}(),zu)try{return zu.createHTML(e)}catch(t){console.warn("[TrustedTypes] Failed to create safe HTML:",t);}return e}function Wu(e,t){try{const n=Uu(t);return e.innerHTML=n,!0}catch(n){return console.warn("[TrustedTypes] Failed to set innerHTML:",n),false}}function Vu(e){if(Fu||function(){if(Fu)return  true;const e=$u();if(!e)return  false;try{return Fu=e.createPolicy(Hu("script-url"),{createScriptURL:e=>e}),!0}catch(t){return console.warn("[TrustedTypes] Failed to create Trusted Types script URL policy:",t),false}}(),Fu)try{return Fu.createScriptURL(e)}catch(t){console.warn("[TrustedTypes] Failed to create safe script URL:",t);}return e}function Gu(e,t){let n=null;const r=t=>{if(!Reflect.set(e,"src",t))throw new Error("Trusted Types prevented script src assignment")};try{return r(Vu(t)),!0}catch(o){n=o;}if(function(){if(ju)return  true;const e=$u();if(!e)return  false;try{return e.createPolicy("default",{createHTML:e=>e,createScript:e=>e,createScriptURL:e=>e}),ju=!0,!0}catch(o){const t=o instanceof Error?o.message:String(o);return /default/i.test(t)&&/already exists/i.test(t)?(ju=true,true):(console.warn("[TrustedTypes] Failed to create default Trusted Types policy:",o),false)}}())try{return r(t),!0}catch(o){n=o;}return console.warn("[TrustedTypes] Failed to set script src:",n),false}const Qu="delete_ui_failed",Ku="delete_ui_exception",Zu="delete_batch_aborted_after_ui_failure",Yu=["delete","remove","删除","删掉","supprimer","eliminar","löschen","삭제","削除","移除","excluir","hapus","удал"],Ju=["cancel","取消","annuler","abbrechen","취소","キャンセル","batal","отмен"],Xu="data-ophel-export-thought-id",eh=/([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,})/i,th=/(google|account|账号|帳號|conta|compte|cuenta|konto|アカウント|계정|учет)/i,nh="ophel-gemini-mystuff-active",rh="ophel-gemini-mystuff-style",oh="ophel-mystuff-open-btn",ih="data-ophel-mystuff-open",ah="data-ophel-mystuff-open-suppress",sh=/^https:\/\/lh\d+\.googleusercontent\.com\//i;class lh{constructor(e){this.options=e;}started=false;mediaWatchStop=null;tooltipBindings=new WeakMap;pendingRequests=new Map;recordsByKind={media:new Map,document:new Map};mediaByTimestamp=new Map;mediaByThumbnail=new Map;documentByTimestamp=new Map;documentByTitle=new Map;start(){this.started||(this.started=true,this.injectStyles(),this.mediaWatchStop=ei.each(".library-item-card",e=>this.enhanceMediaCard(e),{shadow:true}),document.addEventListener("click",this.handleDocumentClick,true),window.addEventListener("message",this.handleWindowMessage),window.addEventListener("gh-url-change",this.handleRouteChange),this.refreshForCurrentRoute(false),setTimeout(()=>this.refreshForCurrentRoute(false),600),setTimeout(()=>this.refreshForCurrentRoute(false),1500));}handleRouteChange=()=>{this.refreshForCurrentRoute(false);};handleWindowMessage=e=>{const{type:t,payload:n}=e.data||{};e.source!==window&&t!==Bu||t===Bu&&this.handleCachePayload(n);};handleDocumentClick=e=>{if(!this.isMyStuffPath()||e.defaultPrevented||0!==e.button)return;const t=e.target instanceof Element?e.target:null;if(!t)return;const n=t.closest(`[${ih}="1"]`);if(n){const t=n.closest("library-item-card");if(!t)return;return this.preventNativeNavigation(e),this.dismissActionButtonVisualState(n),void this.openHostInNewTab(t,"media",this.preparePendingTab())}if(t.closest("library-item-card"))return;const r=t.closest("library-list-item");r&&(this.preventNativeNavigation(e),this.openHostInNewTab(r,"document",this.preparePendingTab()));};preventNativeNavigation(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();}refreshForCurrentRoute(e){const t=this.isMyStuffPath();document.documentElement.classList.toggle(nh,t),t&&(this.enhanceExistingMediaCards(),this.requestSync(e,this.getKindsForCurrentPath()).catch(()=>{}));}injectStyles(){if(document.getElementById(rh))return;const e=document.createElement("style");e.id=rh,e.textContent=`\n      .${nh} library-item-card .library-item-card,\n      .${nh} .library-item-card-container {\n        position: relative;\n      }\n\n      .${nh} .${oh} {\n        position: absolute;\n        top: 8px;\n        right: 8px;\n        width: 32px;\n        height: 32px;\n        border: none;\n        border-radius: 999px;\n        display: flex;\n        align-items: center;\n        justify-content: center;\n        padding: 0;\n        background: rgba(15, 23, 42, 0.68);\n        color: #ffffff;\n        box-shadow: 0 4px 14px rgba(15, 23, 42, 0.18);\n        backdrop-filter: blur(6px);\n        cursor: pointer;\n        opacity: 0;\n        pointer-events: none;\n        transform: translateY(-2px);\n        transition:\n          opacity 0.18s ease,\n          transform 0.18s ease,\n          background-color 0.18s ease,\n          color 0.18s ease;\n        z-index: 3;\n      }\n\n      .${nh} library-item-card:hover .${oh},\n      .${nh} library-item-card:focus-within .${oh},\n      .${nh} .library-item-card:hover .${oh},\n      .${nh} .library-item-card:focus-within .${oh},\n      .${nh} .library-item-card-container:hover .${oh},\n      .${nh} .library-item-card-container:focus-within .${oh} {\n        opacity: 1;\n        pointer-events: auto;\n        transform: translateY(0);\n      }\n\n      .${nh} .${oh}:hover {\n        background: rgba(15, 23, 42, 0.82);\n        color: #ffffff;\n      }\n\n      .${nh} .${oh}[${ah}="1"] {\n        opacity: 0 !important;\n        pointer-events: none !important;\n        transform: translateY(-2px) !important;\n      }\n\n      .${nh} .${oh} svg {\n        width: 16px;\n        height: 16px;\n        stroke: currentColor;\n        fill: none;\n        stroke-width: 2;\n        stroke-linecap: round;\n        stroke-linejoin: round;\n      }\n\n      body.dark-theme .${oh},\n      html[dark-theme] .${oh},\n      html.dark .${oh} {\n        background: rgba(15, 23, 42, 0.68);\n        color: #f9fafb;\n        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.32);\n      }\n\n      body.dark-theme .${oh}:hover,\n      html[dark-theme] .${oh}:hover,\n      html.dark .${oh}:hover {\n        background: rgba(15, 23, 42, 0.82);\n        color: #ffffff;\n      }\n\n    `,document.head.appendChild(e);}enhanceExistingMediaCards(){document.querySelectorAll(".library-item-card").forEach(e=>this.enhanceMediaCard(e));}enhanceMediaCard(e){if(!this.isMyStuffPath())return;const t=e.closest("library-item-card"),n=e.matches(".library-item-card")?e:e.querySelector(".library-item-card");if(!t||!n)return;if(n.querySelector(`[${ih}="1"]`))return;const r=document.createElement("button");r.type="button",r.className=`${oh} ophel-tooltip-trigger`,r.setAttribute(ih,"1"),r.setAttribute("aria-label",this.getOpenInNewTabLabel()),r.appendChild(function(e={}){const{size:t=16,color:n="currentColor",className:r=""}=e,o=Cu("svg",{xmlns:Su,width:t.toString(),height:t.toString(),viewBox:"0 0 24 24",fill:"none",stroke:n,"stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",...r?{class:r}:{}}),i=Cu("path",{d:"M14 5h5v5"}),a=Cu("path",{d:"M10 14 19 5"}),s=Cu("path",{d:"M19 14v4a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h4"});return o.appendChild(i),o.appendChild(a),o.appendChild(s),o}()),n.appendChild(r),this.tooltipBindings.set(r,vu(r,{getContent:()=>this.getOpenInNewTabLabel(),delay:300,maxWidth:260,preferredPlacement:"top"}));}isMyStuffPath(){const e=this.getNormalizedPath();return "/mystuff"===e||"/mystuff/"===e||e.startsWith("/mystuff/")}getKindsForCurrentPath(){return this.getNormalizedPath().startsWith("/mystuff/documents")?["document"]:["media","document"]}getNormalizedPath(){return window.location.pathname.replace(/^\/u\/\d+/,"")}handleCachePayload(e){if(!e||!Array.isArray(e.items)||!Array.isArray(e.kinds))return;this.replaceRecords(e.kinds,e.items);const t=e.requestId?this.pendingRequests.get(e.requestId):null;t&&e.requestId&&(clearTimeout(t.timeoutId),this.pendingRequests.delete(e.requestId),t.resolve(e));}replaceRecords(e,t){for(const n of e)this.recordsByKind[n].clear(),t.filter(e=>e.kind===n).forEach(e=>this.recordsByKind[n].set(this.getRecordKey(e),e));this.rebuildIndexes();}rebuildIndexes(){this.mediaByTimestamp.clear(),this.mediaByThumbnail.clear(),this.documentByTimestamp.clear(),this.documentByTitle.clear(),this.recordsByKind.media.forEach(e=>{this.pushIndex(this.mediaByTimestamp,e.timestamp,e);const t=this.normalizeThumbnailUrl(e.thumbnailUrl);t&&this.pushIndex(this.mediaByThumbnail,t,e);}),this.recordsByKind.document.forEach(e=>{this.pushIndex(this.documentByTimestamp,e.timestamp,e);const t=this.normalizeTitle(e.title);t&&this.pushIndex(this.documentByTitle,t,e);});}pushIndex(e,t,n){if(null==t||""===t||0===t)return;const r=e.get(t)||[];r.push(n),e.set(t,r);}async requestSync(e,t){const n=`ophel-mystuff-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r={requestId:n,force:e,kinds:t},o=new Promise((e,t)=>{const r=setTimeout(()=>{this.pendingRequests.delete(n),t(new Error("mystuff-sync-timeout"));},12e3);this.pendingRequests.set(n,{resolve:e,reject:t,timeoutId:r});});return window.postMessage({type:Pu,payload:r},"*"),o}preparePendingTab(){return "userscript"!==xu.type?null:window.open("about:blank","_blank")}async openHostInNewTab(e,t,n){const r=await this.resolveRecord(e,t);if(!r)return n&&!n.closed&&n.close(),console.warn("[GeminiAdapter][MyStuff] record not found for host",{kind:t,locator:this.extractLocator(e,t)}),void Oo(re("geminiMystuffLocateFailed")||"未找到原始会话定位信息",2500);const o=this.buildRecordUrl(r);!n||n.closed?xu.openTab(o):n.location.href=o;}async resolveRecord(e,t){const n=this.extractLocator(e,t);let r=this.findRecord(n);if(r)return r;try{await this.requestSync(!0,[t]);}catch(o){console.warn("[GeminiAdapter][MyStuff] sync failed before open",{kind:t,error:o});}return r=this.findRecord(n),r}extractLocator(e,t){const n=e.closest("[jslog]")||e.querySelector("[jslog]"),r=n?.getAttribute("jslog")||"",o=this.extractJslogMeta(r);return {kind:t,status:o?.status,timestamp:o?.timestamp,timestampNano:o?.timestampNano,title:"document"===t?this.extractTitle(e):void 0,thumbnailUrl:"media"===t?this.extractThumbnailUrl(e):void 0}}extractJslogMeta(e){if(!e)return null;const t=Array.from(e.matchAll(/\[(\d+),\[(\d+)(?:,(\d+))?\]\]/g)),n=t[t.length-1];return n?{status:Number(n[1]),timestamp:Number(n[2]),timestampNano:n[3]?Number(n[3]):void 0}:null}extractTitle(e){const t=e.querySelector(".title, .gds-title-m, .text-content .title");return t?.textContent?.trim()||""}extractThumbnailUrl(e){const t=e.querySelector("img");return t instanceof HTMLImageElement?this.normalizeThumbnailUrl(t.currentSrc||t.src||""):""}normalizeTitle(e){return (e||"").trim().replace(/\s+/g," ").toLowerCase()}normalizeThumbnailUrl(e){if(!e)return "";let t=e;try{t=new URL(e,window.location.href).toString();}catch{t=e;}return sh.test(t)?t.replace(/=[^/?#]+$/,""):t}findRecord(e){return "media"===e.kind?this.findMediaRecord(e):this.findDocumentRecord(e)}findMediaRecord(e){const t=new Map,n=this.normalizeThumbnailUrl(e.thumbnailUrl);if(n)for(const r of this.mediaByThumbnail.get(n)||[])t.set(this.getRecordKey(r),r);if(e.timestamp)for(const r of this.mediaByTimestamp.get(e.timestamp)||[])t.set(this.getRecordKey(r),r);return this.pickBestRecord(Array.from(t.values()),e)}findDocumentRecord(e){const t=new Map,n=this.normalizeTitle(e.title);if(e.timestamp)for(const r of this.documentByTimestamp.get(e.timestamp)||[])t.set(this.getRecordKey(r),r);if(n)for(const r of this.documentByTitle.get(n)||[])t.set(this.getRecordKey(r),r);return this.pickBestRecord(Array.from(t.values()),e)}pickBestRecord(e,t){if(0===e.length)return null;const n=this.normalizeThumbnailUrl(t.thumbnailUrl),r=this.normalizeTitle(t.title),o=e.map(e=>{let o=0;return void 0!==t.status&&e.status===t.status&&(o+=20),void 0!==t.timestamp&&e.timestamp===t.timestamp&&(o+=80),n&&this.normalizeThumbnailUrl(e.thumbnailUrl)===n&&(o+=200),r&&this.normalizeTitle(e.title)===r&&(o+=120),void 0!==t.timestampNano&&(o-=Math.min(Math.abs((e.timestampNano||0)-t.timestampNano)/1e6,20)),{record:e,score:o}}).sort((e,t)=>t.score-e.score);return o[0]?.record||null}buildRecordUrl(e){const t=e.conversationId.replace(/^c_/,""),n=e.responseId.replace(/^r_/,""),r=new URL(`${window.location.origin}${this.options.getUserPathPrefix()}/app/${t}`);return r.searchParams.set(ho,"1"),r.hash=n,r.toString()}getRecordKey(e){return `${e.conversationId}:${e.responseId}`}getOpenInNewTabLabel(){return re("geminiMystuffOpenInNewTab")||"在新标签页中打开"}dismissActionButtonVisualState(e){this.tooltipBindings.get(e)?.hide(),e.blur(),e.setAttribute(ah,"1");const t=()=>{e.removeAttribute(ah),window.removeEventListener("pointermove",t,true),window.removeEventListener("pointerdown",t,true),window.removeEventListener("keydown",t,true),window.removeEventListener("wheel",t,true),window.removeEventListener("touchstart",t,true),e.removeEventListener("focus",t,true);};window.addEventListener("pointermove",t,true),window.addEventListener("pointerdown",t,true),window.addEventListener("keydown",t,true),window.addEventListener("wheel",t,true),window.addEventListener("touchstart",t,true),e.addEventListener("focus",t,true);}}class ch extends ci{exportIncludeThoughtsOverride=null;cachedAccountEmail=null;accountEmailLastDetectAt=0;myStuffEnhancer=null;getUserPathPrefix(){const e=window.location.pathname.match(/^\/u\/(\d+)(?:\/|$)/);if(!e)return "";return `/u/${e[1]}`}getCurrentCid(){const e=this.getCurrentAccountEmail();if(e)return e;const t=window.location.pathname.match(/^\/u\/(\d+)(?:\/|$)/);return t?t[1]:"0"}getCurrentAccountEmail(){const e=Date.now();if(e-this.accountEmailLastDetectAt<2e3)return this.cachedAccountEmail;this.accountEmailLastDetectAt=e;const t=["aria-label","title","data-email","data-identifier"],n=new Set;["[data-email]",'[data-identifier*="@"]','[aria-label*="@"]','[title*="@"]'].forEach(e=>{document.querySelectorAll(e).forEach(e=>n.add(e));});for(const r of n)for(const e of t){const t=r.getAttribute(e),n=this.extractEmailFromAttr(e,t);if(n)return this.cachedAccountEmail=n,n}return this.cachedAccountEmail}extractEmailFromAttr(e,t){return t&&("data-email"===e||"data-identifier"===e||th.test(t))?this.extractEmail(t):null}extractEmail(e){if(!e)return null;const t=e.match(eh);return t?t[1].toLowerCase():null}match(){return window.location.hostname.includes("gemini.google")&&!window.location.hostname.includes("business.gemini.google")}getSiteId(){return Ir}getName(){return "Gemini"}getThemeColors(){return {primary:"#4285f4",secondary:"#34a853"}}getNativeThemeCss(){return "\n/* =============================================\n * Gemini 站点原生主题适配器 (Gemini Theme Adapter)\n * ============================================= */\n:root body.light-theme, :root body.dark-theme, :root {\n  /* 1. 核心页面背景层 */\n  --bard-color-lm-surface: var(--gh-bg) !important;\n  --bard-color-lm-surface-bright: var(--gh-bg) !important;\n  --bard-color-lm-surface-dim: var(--gh-bg-secondary) !important;\n  --bard-color-footer-background: var(--gh-bg-secondary) !important;\n  --bard-color-inverse-primary-background: var(--gh-bg-tertiary) !important;\n\n  /* 2. 侧边栏与浮动层:使用极其微弱的主色调混合背景,避免大面积色块导致“太亮”或“太腻” */\n  --bard-color-sidenav-background-desktop: color-mix(in srgb, var(--gh-primary) 5%, var(--gh-bg)) !important;\n  --gem-sys-color--surface-container: color-mix(in srgb, var(--gh-primary) 5%, var(--gh-bg)) !important;\n  --gem-sys-color--surface-container-high: color-mix(in srgb, var(--gh-primary) 8%, var(--gh-bg)) !important;\n  --bard-color-icon-container-background: color-mix(in srgb, var(--gh-primary) 6%, var(--gh-bg)) !important;\n\n  /* 3. 全局核心文字 */\n  --bard-color-lm-on-surface: var(--gh-text) !important;\n  --bard-color-sentence-prefix-color: var(--gh-text) !important;\n  --bard-color-lm-on-surface-variant: var(--gh-text-secondary) !important;\n  --bard-color-sentence-words-color: var(--gh-text-secondary) !important;\n  --bard-color-image-lightbox-text: var(--gh-text-tertiary) !important;\n  --bard-color-code-comment: var(--gh-text-tertiary) !important;\n\n  /* 4. 品牌高亮与强调色(绑定我们插件的主题色段) */\n  --bard-color-surface-tint: var(--gh-primary) !important;\n  --bard-color-form-field-outline-active: var(--gh-primary) !important;\n  --bard-color-brand-text-gradient-stop-1: var(--gh-primary) !important;\n  --bard-color-chrome-experiment-badge: var(--gh-primary) !important;\n  --bard-color-share-link: var(--gh-primary) !important;\n\n  /* 5. 分叉对话、状态卡片相关 */\n  --bard-color-zero-state-card-selected: var(--gh-active-bg) !important;\n  --bard-color-zero-state-prompt-chip-background: var(--gh-hover) !important;\n\n  /* 6. 其他元素 */\n  --gem-sys-color--surface-container-high: var(--gh-bg-tertiary) !important;\n  --gem-sys-color--primary: var(--gh-primary) !important;\n  /* 图标颜色 */\n  --mat-icon-color: var(--gh-primary) !important;\n}\n"}getNewTabUrl(){return `https://gemini.google.com${this.getUserPathPrefix()}/app`}isNewConversation(){const e=window.location.pathname.replace(/^\/u\/\d+/,"");if("/app"===e||"/app/"===e)return  true;if("/gems/create"===e||"/gems/create/"===e)return  true;if(e.startsWith("/gems/edit/"))return  true;if(e.startsWith("/gem/")){return e.split("/").filter(Boolean).length<=2}return  false}getConversationList(){const e=ei.query(".conversation",{all:true})||[],t=this.getCurrentCid(),n=this.getUserPathPrefix();return Array.from(e).map(e=>{const r=(e.getAttribute("jslog")||"").match(/\["c_([^"]+)"/),o=r?r[1]:"",i=e.querySelector(".conversation-title")?.textContent?.trim()||"",a=!!e.querySelector('mat-icon[fonticon="push_pin"]');return {id:o,cid:t,title:i,url:o?`https://gemini.google.com${n}/app/${o}`:"",isActive:e.classList.contains("selected"),isPinned:a}}).filter(e=>e.id)}getSidebarScrollContainer(){return ei.query('infinite-scroller[scrollable="true"]')||ei.query("infinite-scroller")}getConversationObserverConfig(){return {selector:".conversation",shadow:false,extractInfo:e=>{const t=(e.getAttribute("jslog")||"").match(/\["c_([^"]+)"/),n=t?t[1]:"";if(!n)return null;const r=e.querySelector(".conversation-title")?.textContent?.trim()||"",o=!!e.querySelector('mat-icon[fonticon="push_pin"]');return {id:n,cid:this.getCurrentCid(),title:r,url:`https://gemini.google.com${this.getUserPathPrefix()}/app/${n}`,isPinned:o}},getTitleElement:e=>e.querySelector(".conversation-title")||e}}navigateToConversation(e,t){const n=document.querySelector(`.conversation[jslog*="${e}"]`);if(n){const e=n.querySelector("button.list-item")||n.querySelector("button");return e?e.click():n.click(),true}return super.navigateToConversation(e,t)}async deleteConversationOnSite(e){const t=await this.deleteConversationOnSiteInternal(e);return t.success&&this.scheduleFullReloadAfterDelete([e.id]),t}async deleteConversationsOnSite(e){const t=[],n=[];for(let r=0;r0&&this.scheduleFullReloadAfterDelete(n),t}async deleteConversationOnSiteInternal(e){try{const t=await this.deleteConversationViaUi(e.id);return {id:e.id,success:t,method:t?"ui":"none",reason:t?void 0:Qu}}catch(t){return console.error(`[GeminiAdapter] deleteConversationOnSiteInternal error for "${e.id}":`,t),{id:e.id,success:false,method:"none",reason:Ku}}}async deleteConversationViaUi(e){const t=await this.findConversationRowWithRetry(e);if(!t)return  false;t.scrollIntoView({block:"center",behavior:"auto"}),this.revealConversationActions(t);let n=await this.findConversationMenuButton(t);if(!n)return  false;const r=await this.openConversationMenu(t,n);if(!r)return  false;const o=await this.waitForDeleteMenuItem(n,2500,r);if(!o)return document.body.click(),false;this.simulateClick(o);if(!(await this.waitForDialogOpen(2200)))return  false;const i=await this.waitForDeleteConfirmButton(2800);if(!i)return  false;this.simulateClick(i);const a=await this.waitForConversationRemoved(e,4500),s=await this.waitForDialogClosed(1200),l=a||s;return l&&this.syncConversationListAfterDelete(e),l}async openConversationMenu(e,t){let n=t;for(let r=0;r<4;r++){if(document.body.click(),await this.sleep(60),this.revealConversationActions(e),n&&n.isConnected||(n=await this.findConversationMenuButton(e)),!n)return null;this.simulateClick(n);const t=await this.waitForMenuOpen(n,900);if(t)return t}return null}async waitForMenuOpen(e,t=900){const n=Date.now();for(;Date.now()-nthis.revealConversationActions(e));const o=r.flatMap(e=>Array.from(e.querySelectorAll(t))).filter(e=>!e.classList.contains("list-item")&&!(e instanceof HTMLButtonElement&&e.disabled));if(o.length>0){const t=o.find(e=>null!==e.querySelector('mat-icon[fonticon="more_vert"], mat-icon[fonticon="more_horiz"]'));if(t)return t;const r=o.find(t=>this.isLikelyMenuButton(t,e));if(r)return r;const i=o.filter(e=>this.isVisible(e)).sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0];if(i)return i;if(n>=8){const e=o[o.length-1];if(e)return e}}await this.sleep(100);}return null}getMenuSearchScopes(e){const t=[e,e.parentElement,e.parentElement?.parentElement,e.closest("li")].filter(e=>e instanceof HTMLElement),n=new Set,r=[];for(const o of t)n.has(o)||(n.add(o),r.push(o));return r}isLikelyMenuButton(e,t){if(!t.contains(e))return  false;if(e.classList.contains("list-item"))return  false;if("menu"===e.getAttribute("aria-haspopup"))return  true;const n=this.getSignalText(e);return n.includes("more")||n.includes("更多")||n.includes("选项")||n.includes("menu")||n.includes("菜单")}async waitForDeleteMenuItem(e,t=2500,n){const r=Date.now();let o=[];for(;Date.now()-rthis.isVisible(e));r.length>0&&(o=r),await this.sleep(80);}if(o.length>0){const e=o[o.length-1],t=this.getSignalText(e);if(!this.hasKeyword(t,Ju))return e}return null}getMenuActionCandidates(e,t){const n='[role="menuitem"], [role="menu"] button, .mat-mdc-menu-panel button',r=[];t&&r.push(...Array.from(t.querySelectorAll(n)));const o=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(o){const e=document.getElementById(o);e&&r.push(...Array.from(e.querySelectorAll(n)));}const i=this.findVisibleMenuContainer();i&&r.push(...Array.from(i.querySelectorAll(n))),r.push(...this.findAllElementsBySelector(n));const a=new Set,s=[];for(const l of r)a.has(l)||(a.add(l),s.push(l));return s}getMenuContainerFromTrigger(e){const t=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(!t)return null;const n=document.getElementById(t);return n instanceof HTMLElement?n:null}findVisibleMenuContainer(){const e=Array.from(document.querySelectorAll('[role="menu"], .mat-mdc-menu-panel, .mat-menu-panel')).filter(e=>this.isVisible(e));return 0===e.length?null:e[e.length-1]}async waitForDialogOpen(e=2200){const t=Date.now();for(;Date.now()-tthis.isVisible(e));for(const o of n){const e=this.getSignalText(o);if(this.hasKeyword(e,Yu)&&!this.hasKeyword(e,Ju))return o}const r=n.filter(e=>!this.hasKeyword(this.getSignalText(e),Ju)).sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0];if(r)return r;await this.sleep(80);}return null}async waitForDialogClosed(e=1200){const t=Date.now();for(;Date.now()-tthis.isVisible(e))||null}async waitForConversationRemoved(e,t=4500){const n=Date.now();for(;Date.now()-nn.includes(e.toLowerCase()))}isVisible(e){if(!(e instanceof HTMLElement))return  false;if(!e.isConnected)return  false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return  false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}simulateClick(e){const t=["pointerdown","mousedown","pointerup","mouseup","click"];let n=false;for(const r of t)try{"function"==typeof PointerEvent?e.dispatchEvent(new PointerEvent(r,{bubbles:!0,cancelable:!0,pointerId:1})):e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{try{e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{}}n||e.click();}getSessionName(){const e=document.querySelector(".conversation-title");if(e){const t=e.textContent?.trim();if(t)return t}return super.getSessionName()}getConversationTitle(){const e=document.querySelector(".conversation.selected .conversation-title");return e&&e.textContent?.trim()||null}getNewChatButtonSelectors(){return [".new-chat-button",".chat-history-new-chat-button",'[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="临时对话"]']}getLatestReplyText(){const e=document.querySelector(this.getResponseContainerSelector());if(!e)return null;const t=e.querySelectorAll("model-response");if(0===t.length)return null;const n=t[t.length-1],r=this.exportIncludeThoughtsOverride;try{this.exportIncludeThoughtsOverride=!1;return this.extractAssistantResponseText(n)||null}finally{this.exportIncludeThoughtsOverride=r;}}getWidthSelectors(){return [{selector:".conversation-container",property:"max-width"},{selector:".input-area-container",property:"max-width"},{selector:".table-block.new-table-style",property:"max-width",value:"100%",noCenter:true,extraCss:"width: 100% !important;"},{selector:"user-query",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;"}]}getUserQueryWidthSelectors(){return [{selector:".user-query-bubble-with-background:not(.edit-mode)",property:"max-width",noCenter:true}]}getZenModeSelectors(){return [{selector:"hallucination-disclaimer",action:"hide"}]}getMarkdownFixerConfig(){return {selector:"message-content p",fixSpanContent:false}}getAssistantMermaidSupportMode(){return "fallback"}getTextareaSelectors(){return ['div[contenteditable="true"].ql-editor','div[contenteditable="true"]','[role="textbox"]','[aria-label*="Enter a prompt"]']}getSubmitButtonSelectors(){return ['button[aria-label*="Send"]','button[aria-label*="发送"]',".send-button",'[data-testid*="send"]']}isValidTextarea(e){if(null===e.offsetParent)return  false;const t="true"===e.getAttribute("contenteditable"),n="textbox"===e.getAttribute("role");return !e.closest(".gh-main-panel")&&(t||n||e.classList.contains("ql-editor"))}insertPrompt(e){const t=this.textarea;if(!t)return  false;if(!t.isConnected)return this.textarea=null,false;if(t.focus(),document.activeElement!==t&&!t.contains(document.activeElement))return console.warn("[Ophel] insertPrompt: focus failed"),false;try{document.execCommand("selectAll",!1,void 0);if(!document.execCommand("insertText",!1,e))throw new Error("execCommand returned false")}catch{t.textContent=e,t.dispatchEvent(new Event("input",{bubbles:true})),t.dispatchEvent(new Event("change",{bubbles:true}));}return  true}clearTextarea(){this.textarea&&(this.textarea.isConnected?(this.textarea.focus(),(document.activeElement===this.textarea||this.textarea.contains(document.activeElement))&&(document.execCommand("selectAll",false,void 0),document.execCommand("delete",false,void 0))):this.textarea=null);}getScrollContainer(){return this.isSharePage()?document.querySelector("div.content-container"):document.querySelector("infinite-scroller.chat-history")}getResponseContainerSelector(){return this.isSharePage()?"div.content-container":"infinite-scroller.chat-history"}getChatContentSelectors(){return [".model-response-container","model-response",".response-container","[data-message-id]","message-content"]}getUserQuerySelector(){return "user-query"}sanitizeUserQueryElement(e){const t=e.cloneNode(true);return t.querySelectorAll(".cdk-visually-hidden").forEach(e=>e.remove()),t}extractUserQueryText(e){const t=this.sanitizeUserQueryElement(e),n=t.querySelector(".query-text")||t;return this.extractTextWithLineBreaks(n)}extractUserQueryMarkdown(e){const t=this.sanitizeUserQueryElement(e),n=t.querySelectorAll(".query-text-line");if(0===n.length)return this.extractUserQueryText(t);return Array.from(n).map(e=>e.querySelector("br")&&""===e.textContent?.trim()?"":e.textContent?.trim()||"").join("\n")}async prepareConversationExport(e){if(this.exportIncludeThoughtsOverride=e.includeThoughts,!e.includeThoughts)return this.clearThoughtExportMarkers(),{toggledThoughtIds:[]};const t=new Set;this.clearThoughtExportMarkers();let n=0,r=-1;for(let o=0;o<10&&n<2;o++){const e=this.getThoughtNodesForExport();e.length===r?n++:(n=0,r=e.length);for(const n of e){if(this.isThoughtExpanded(n))continue;const e=this.getThoughtHeaderButton(n);if(!e)continue;let r=n.getAttribute(Xu);r||(r=`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,n.setAttribute(Xu,r));try{e.scrollIntoView({block:"center",behavior:"auto"});}catch{}this.simulateClick(e);await this.waitForThoughtState(n,true,2200)&&t.add(r),await this.sleep(60);}await this.sleep(120);}return this.getThoughtNodesForExport().forEach(e=>{const n=e.getAttribute(Xu);n&&!t.has(n)&&e.removeAttribute(Xu);}),{toggledThoughtIds:Array.from(t)}}async restoreConversationAfterExport(e,t){const n=this.parseExportLifecycleState(t);if(!n)return this.exportIncludeThoughtsOverride=null,void this.clearThoughtExportMarkers();try{for(let e=n.toggledThoughtIds.length-1;e>=0;e--){const t=n.toggledThoughtIds[e],r=this.findThoughtNodeByMarker(t);if(!r)continue;const o=this.getThoughtHeaderButton(r);if(o){if(this.isThoughtExpanded(r)){try{o.scrollIntoView({block:"center",behavior:"auto"});}catch{}this.simulateClick(o),await this.waitForThoughtState(r,!1,1800);}r.removeAttribute(Xu),await this.sleep(40);}else r.removeAttribute(Xu);}}finally{this.exportIncludeThoughtsOverride=null,this.clearThoughtExportMarkers();}}parseExportLifecycleState(e){if(!e||"object"!=typeof e)return null;const t=e;if(!Array.isArray(t.toggledThoughtIds))return null;return {toggledThoughtIds:t.toggledThoughtIds.filter(e=>"string"==typeof e&&e.length>0)}}getThoughtNodesForExport(){return Array.from(document.querySelectorAll('model-thoughts[data-test-id="model-thoughts"], model-thoughts'))}getThoughtHeaderButton(e){return e.querySelector('button[data-test-id="thoughts-header-button"]')}isThoughtExpanded(e){const t=e.querySelector("button[data-test-id='thoughts-header-button'] mat-icon"),n=t?.getAttribute("data-mat-icon-name")||t?.getAttribute("fonticon")||"";if(n.includes("expand_less"))return  true;if(n.includes("expand_more"))return  false;return !!e.querySelector('[data-test-id="thoughts-content"]')||null!==e.querySelector(".thoughts-content-expanded")}isThoughtContentReady(e){const t=e.querySelector('[data-test-id="thoughts-content"]');return !!t&&(t.textContent?.trim().length||0)>0}async waitForThoughtState(e,t,n=2200){const r=Date.now();for(;Date.now()-r{e.hasAttribute(Xu)&&e.removeAttribute(Xu);});}shouldIncludeThoughtsInExport(){return "boolean"!=typeof this.exportIncludeThoughtsOverride||this.exportIncludeThoughtsOverride}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}extractThoughtBlockquotesFromElement(e){const t=Array.from(e.querySelectorAll("model-thoughts")),n=[];for(const r of t){const e=r.querySelector('[data-test-id="thoughts-content"]')||r.querySelector(".thoughts-content");if(!e)continue;const t=(Uo(e)||this.extractTextWithLineBreaks(e)).trim();t&&n.push(this.formatAsThoughtBlockquote(t));}return n}sanitizeAssistantExportElement(e){const t=e.cloneNode(true);return t.querySelectorAll(".cdk-visually-hidden").forEach(e=>e.remove()),t.querySelectorAll(`model-thoughts[${Xu}]`).forEach(e=>{e.removeAttribute(Xu);}),t}shouldSkipOutlineHeading(e){return !!this.isInRenderedMarkdownContainer(e)||!!e.classList.contains("cdk-visually-hidden")}extractAssistantResponseText(e){const t=this.sanitizeAssistantExportElement(e),n=this.shouldIncludeThoughtsInExport();let r=[];n&&(r=this.extractThoughtBlockquotesFromElement(t)),t.querySelectorAll("model-thoughts").forEach(e=>e.remove());const o=(Uo(t)||this.extractTextWithLineBreaks(t)).trim();if(n&&r.length>0){const e=r.join("\n\n");return o?`${e}\n\n${o}`:e}return o}replaceUserQueryContent(e,t){const n=e.querySelector(".query-text");if(!n)return  false;if(n.nextElementSibling?.classList.contains("gh-user-query-markdown"))return  false;const r=document.createElement("div");return r.className="gh-user-query-markdown gh-markdown-preview",!!Wu(r,t)&&(n.style.display="none",n.after(r),true)}getExportConfig(){return {userQuerySelector:"user-query",assistantResponseSelector:"model-response, .model-response-container .markdown",turnSelector:".conversation-turn",useShadowDOM:false}}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector(this.getResponseContainerSelector());if(!o)return r;const i=e=>{const t=e.closest("message-content");if(t&&t.id){const e=t.id.match(/(r_[a-f0-9]+)/);if(e)return e[1]}return null},a={},s=(e,t,n)=>{a[e]||(a[e]={});const r=`${t}-${n}`,o=a[e][r]||0;return a[e][r]=o+1,`${e}::${r}::${o}`},l=this.getUserQuerySelector(),c=(e,t,n)=>{if(!e)return 0;try{if(n){let t=e.nextElementSibling,n=0;for(;t;){const e=t.tagName.toLowerCase();if("user-query"===e)break;if("model-response"===e){const e=t.querySelector(".model-response-text, message-content");if(e){const r=t.querySelector("model-thoughts"),o=r?.textContent?.trim().length||0,i=e.textContent?.trim().length||0;n+=Math.max(0,i-o);}}t=t.nextElementSibling;}return n}const r=e.closest("message-content");return this.calculateRangeWordCount(e,t,r||o)}catch{return 0}};if(!t){const t=[];for(let n=1;n<=e;n++)t.push(`h${n}`);const a=Array.from(o.querySelectorAll(t.join(", ")));return a.forEach((t,o)=>{if(this.shouldSkipOutlineHeading(t))return;const l=parseInt(t.tagName.charAt(1),10);if(l<=e){const e={level:l,text:t.textContent?.trim()||"",element:t},d=i(t);if(d){const n=t.tagName.toLowerCase();e.id=s(d,n,e.text);}if(n){let n=null;for(let e=o+1;e{const a=t.tagName.toLowerCase();if("user-query"===a){let e=this.extractUserQueryText(t),o=false;e.length>200&&(e=e.substring(0,200),o=true);const i={level:0,text:e,element:t,isUserQuery:true,isTruncated:o},a=(e=>{const t=e.querySelector('button[jslog*="BardVeMetadataKey"]');if(t){const e=(t.getAttribute("jslog")||"").match(/BardVeMetadataKey.*?["'](r_[a-f0-9]+)["']/);if(e)return e[1]}return null})(t);a&&(i.id=a),n&&(i.wordCount=c(t,null,true)),r.push(i);}else if(/^h[1-6]$/.test(a)){if(this.shouldSkipOutlineHeading(t))return;const l=parseInt(a.charAt(1),10);if(l<=e){const e={level:l,text:t.textContent?.trim()||"",element:t},a=i(t);if(a){const n=t.tagName.toLowerCase();e.id=s(a,n,e.text);}if(n){let n=null;for(let t=o+1;t0&&e.length<=20)return e}}return null}getNetworkMonitorConfig(){return {urlPatterns:["BardFrontendService","StreamGenerate"],silenceThreshold:3e3}}afterPropertiesSet(e={}){super.afterPropertiesSet(e),this.myStuffEnhancer||(this.myStuffEnhancer=new lh({getUserPathPrefix:()=>this.getUserPathPrefix()}),this.myStuffEnhancer.start());}getDefaultLockSettings(){return {enabled:false,keyword:""}}getModelSwitcherConfig(e){return {targetModelKeyword:e,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}}
   /**
      * 切换 Gemini 主题
      * 直接修改 localStorage + body.className 实现即时无感切换
      * @param targetMode 目标主题模式
      */
   async toggleTheme(e){try{const t="dark"===e?"Bard-Dark-Theme":"Bard-Light-Theme";return localStorage.setItem("Bard-Color-Theme",t),"dark"===e?(document.body.classList.add("dark-theme"),document.body.classList.remove("light-theme")):(document.body.classList.remove("dark-theme"),document.body.classList.add("light-theme")),document.body.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"Bard-Color-Theme",newValue:t,storageArea:localStorage})),!0}catch(t){return console.error("[GeminiAdapter] toggleTheme error:",t),false}}}const dh="delete_ui_failed",uh="delete_batch_aborted_after_ui_failure",hh=["delete","remove","删除","删掉","移除","supprimer","eliminar","löschen","삭제","削除","hapus","удал"],gh=["cancel","取消","annuler","abbrechen","취소","キャンセル","batal","отмен"];const ph=["M13 21L12 23L11 21V16H4.5V13.7129L4.65234 13.4697L6.95801 9.78027L6.41797 5.99512C6.11675 3.8866 7.75289 2 9.88281 2H14.1172C16.2471 2 17.8832 3.8866 17.582 5.99512L17.041 9.78027L19.5 13.7129V16H13V21Z"].map(e=>e.replace(/\s+/g,"")),mh="delete_ui_failed",fh="delete_batch_aborted_after_ui_failure",bh="delete_api_request_failed",yh="delete_api_not_found_but_visible",vh=["delete","remove","删除","刪除","supprimer","eliminar","löschen","削除","삭제","удал","excluir"],wh=["confirm","ok","yes","确定","確認","确认","確定","check"];const xh=/^\/chat\/([a-z0-9]+)(?:\/|$)/i,kh="#scrollContainer",Sh=`${kh} [class*="scrollWrap"]`,Ch='div[class*="userBubbleContainer"]',Eh=`${Ch} [class*="userBubble"]`,_h=`${Eh} [class*="content"]`,Ah='div[class*="aiContainer"]',Th=`${`${Ah} [class*="bubble"]`} [class*="markdown"]`,Mh='[class*="thinking"]',Ih='.system-copy-exclude, [x-noteelement="excluded"], [x-copyelement="copy-exclude"]',Nh='[class*="sendBtnWrap"]',Lh=['div[class*="stopButton"] > div','[class*="stopButton"][role="button"]','button[class*="stopButton"]','[class*="stopButton"]'].join(", "),Dh='[class*="currentChoiceWrap"], [class*="modelSelectionWrap"], [class*="modelSelectionText"]',Rh='[class*="modelSelectionText"]';const qh=/^\/chat\/([a-z0-9-]+)(?:\/|$)/i,Ph=["/docs/","/website/","/table/"],Bh="__tea_cache_tokens_",Oh="kimi-auth",zh=[Oh,"kimi_auth","access_token","accessToken","token","auth","authorization"],Fh=["value","token","access_token","accessToken","auth","authorization","id_token","idToken","jwt"],jh=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,$h=/(token|auth|jwt|tea)/i,Hh="a.chat-info-item",Uh=`${Hh}, a.history-link`,Wh=".history-part",Vh="span.chat-name",Gh=".history-chat .title-wrapper .title",Qh=".chat-content-list",Kh=".chat-content-item",Zh=".chat-content-item-user",Yh=".chat-content-item-assistant",Jh=".segment.segment-user",Xh=".segment-assistant .markdown",eg="CUSTOM_THEME",tg="delete_api_missing_auth_token",ng="delete_api_request_failed",rg="delete_api_invalid_response",og="delete_api_business_failed";const ig=/\/chat\/([a-f0-9]+)/i,ag=/\/group\/([a-f0-9]+)/i,sg="tongyi-theme-preference",lg="model-select-expanded",cg='[class*="questionItem"]',dg='[class*="answerItem"]',ug='[class*="bubble"]',hg='[class*="chatInput"]',gg=".message-list-scroll-container, #message-list-scroller",pg="#qwen-message-list-area",mg="aside#new-nav-tab-wrapper",fg='.qc-thinking-header, [class*="thinkingWrap"], [class*="thinkingContent"], [class*="thinkingHeader"], [class*="thinkingTitle"]',bg='[class*="stop-"], [class*="stopBtn"], div[class*="stop"]',yg='[role="dialog"], [data-radix-popper-content-wrapper]',vg=['[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(", ");const wg=/\/c\/([a-f0-9-]+)/i,xg="theme",kg="#sidebar",Sg=".session-list-wrapper",Cg=".chat-item-drag",Eg=".chat-item-drag-link-content-tip-text",_g="#chat-messages-scroll-container",Ag="#chat-message-container",Tg=".qwen-chat-message-user, .chat-user-message-wrapper",Mg=".qwen-chat-message-assistant",Ig=".user-message-content",Ng=".response-message-content",Lg="button.send-button",Dg=["button.stop-button",'button[class*="stop-button"]',".stop-button"],Rg="pre.qwen-markdown-code",qg=".artifacts-body-header-switch",Pg=".artifacts-body-header-switch-active, .artifacts-body-header-switch-unactive, .header-switch-status-small",Bg="data-ophel-qwenai-mermaid-export-switched",Og=".qwen-chat-thinking-tool-status-card-wraper, .qwen-chat-thinking-status-card",zg=".qwen-chat-thinking-status-card-title-text",Fg=".response-message-footer, .copy-response-button, .message-hoc-container",jg='#qwen-chat-header-left .ant-dropdown-trigger:has([class*="model-selector-text"])',$g='#qwen-chat-header-left [class*="model-selector-text"]',Hg='[class*="model-selector-popup"]',Ug=[`${Hg} [class*="model-list"] > [class*="model-item___"]`,`${Hg} [class*="model-list"] > [class*="model-item-selected___"]`].join(", "),Wg=[`${Hg} .ant-dropdown-trigger:has([class*="view-more-text"])`,`${Hg} .ant-dropdown-trigger:has([class*="view-more-icon"])`].join(", "),Vg=[Ug,Wg,'.ant-dropdown [role="menuitem"]',".ant-dropdown .ant-dropdown-menu-item",".ant-dropdown .ant-dropdown-menu-title-content",'.ant-select-dropdown [role="option"]',".ant-select-dropdown .ant-select-item-option"].join(", ");const Gg="yuanbao.tencent.com",Qg=/^\/chat\/([^/?#]+)(?:\/([^/?#]+))?/,Kg="yb_web_theme_mode",Zg="#yuanbao-send-btn, a.style__send-btn___RwTm5",Yg="a.style__send-btn___RwTm5",Jg=".yb-recent-conv-list__item",Xg=".yb-recent-conv-list__item.active",ep=".yb-recent-conv-list__item-name[data-item-name], .yb-recent-conv-list__item-name, [data-item-id][data-item-name]",tp="#chat-content .agent-chat__list__content, .agent-chat__list__content",np=".agent-chat__list__item--human",rp=".agent-chat__list__item--ai",op=".agent-chat__list__item--ai .hyc-common-markdown-style, .agent-chat__list__item--ai .hyc-content-md-done",ip=".agent-chat__toolbar, .agent-chat__toolbar_new, .agent-chat__question-toolbar, .hyc-common-markdown__code__hd__r",ap=".hyc-card-box-process-list, .hyc-common-markdown__replace-appCard",sp=".ybc-model-select-button .t-button__text",lp=[".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(", "),cp=[".hyc-component-reasoner__think",".hyc-component-deepsearch-cot__think",".hyc-common-markdown-style-cot"].join(", "),dp=[".hyc-component-reasoner__text .hyc-common-markdown-style",".hyc-component-reasoner__text .hyc-content-md-done",".hyc-component-reasoner__text"],up=[".t-dropdown__menu",".t-dropdown__submenu",".t-dropdown",".t-popup",".t-popup__content",".t-popup__content__inner",'[role="menu"]','[role="listbox"]'].join(", "),hp=[".t-dropdown__item",".yb-dropdown__item",'[role="menuitem"]','[role="option"]'].join(", "),gp=['[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(", "),pp='.t-dialog, [role="dialog"]',mp="--hunyuan-chat-list-max-width",fp=/删除|delete/i,bp=/删除|确认|确定|delete|confirm/i,yp=/取消|cancel/i,vp="ui_failed",wp="ui_exception",xp="batch_aborted_after_ui_failure";const kp=/\/c\/([a-z0-9-]+)(?:\/|$)/i,Sp=["#chat-input","textarea#chat-input"],Cp="#send-message-button",Ep=["#sidebar-new-chat-button","#new-chat-button"],_p=["button.modelSelectorButton",'button[id^="model-selector-"][id$="-button"]',"#model-selector-glm-5-button","button[data-melt-dropdown-menu-trigger][data-menu-trigger].modelSelectorButton"],Ap="#chat-container",Tp=[`${Ap} .flex.overflow-y-scroll.flex-col.w-full.h-full`,`${Ap} .scrollbar-none.flex.flex-col`,`${Ap} [data-pane-id] .overflow-y-scroll`,`${Ap} [data-pane-id] .scrollbar-none`].join(", "),Mp=[`${Ap} .chat-user.markdown-prose`,`${Ap} .chat-user`,`${Ap} [data-message-author-role="user"]`,`${Ap} [data-role="user"]`,`${Ap} .message-user`,`${Ap} .user-message`,`${Ap} .chat-message-user`,`${Ap} .message.user`].join(", "),Ip=[`${Ap} .markdown-prose:not(.chat-user)`,`${Ap} [data-message-author-role="assistant"]`,`${Ap} [data-role="assistant"]`,`${Ap} .message-assistant`,`${Ap} .assistant-message`,`${Ap} .chat-message-assistant`,`${Ap} .markdown`,`${Ap} .markdown-body`,`${Ap} .prose`,`${Ap} article`,`${Ap} [data-markdown]`].join(", "),Np="data-gh-export-role",Lp=`[${Np}="user"]`,Dp=`[${Np}="assistant"]`,Rp=".thinking-chain-container, .thinking-block",qp=[".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"],Pp=['div[aria-label="停止"] button',"button:has(span.rounded-xs):has(span.size-3)","button:has(span.rounded-xs):has(span.block)"].join(", "),Bp="#sidebar .w-full.mb-1.relative.group",Op='div[dir="auto"]',zp="theme",Fp={light:"#F4F6F8",dark:"#141618"},jp=/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i;const $p=[new class extends ci{clearOnInit=false;cloneWithoutSrOnly(e){const t=e.cloneNode(true);return t.querySelectorAll(".sr-only").forEach(e=>e.remove()),t}match(){return window.location.hostname.includes("business.gemini.google")}getSiteId(){return Dr}getName(){return "Gemini Enterprise"}getThemeColors(){return {primary:"#4285f4",secondary:"#34a853"}}getNewTabUrl(){return "https://business.gemini.google"}isNewConversation(){return !window.location.pathname.includes("/session/")}isSharePage(){return window.location.pathname.includes("/r/share/")}supportsTabRename(){return  true}getCurrentCid(){const e=window.location.pathname.match(/\/home\/cid\/([^/]+)/);return e?e[1]:""}getSessionName(){const e=ei.query(".conversation",{all:true,shadow:true});for(const t of e){const e=t.querySelector("button.list-item")||t.querySelector("button");if(!e)continue;if(e.classList.contains("selected")||e.classList.contains("active")||"true"===e.getAttribute("aria-selected")){const t=e.querySelector(".conversation-title");if(t){const e=t.textContent?.trim();if(e)return e}}}return super.getSessionName()}getConversationTitle(){const e=ei.query(".conversation",{all:true,shadow:true});for(const t of e){const e=t.querySelector("button.list-item")||t.querySelector("button");if(e&&(e.classList.contains("selected")||e.classList.contains("active")))return e.querySelector(".conversation-title")?.textContent?.trim()||null}return null}getConversationList(){const e=ei.query(".conversation",{all:true,shadow:true}),t=this.getCurrentCid();return Array.from(e).map(e=>{const n=e.querySelector("button.list-item")||e.querySelector("button");if(!n)return null;const r=n.querySelector(".conversation-action-menu-button");let o="";if(r&&r.id&&r.id.startsWith("menu-")&&(o=r.id.replace("menu-","")),!o||!/^\d+$/.test(o))return null;const i=n.querySelector(".conversation-title"),a=i&&i.textContent?.trim()||"",s=n.classList.contains("selected")||n.classList.contains("active")||"true"===n.getAttribute("aria-selected");let l=`https://business.gemini.google/session/${o}`;return t&&(l=`https://business.gemini.google/home/cid/${t}/r/session/${o}`),{id:o,cid:t,title:a,url:l,isActive:s}}).filter(e=>null!==e)}getLatestReplyText(){const e=ei.query("ucs-conversation",{shadow:true});if(!e||!e.shadowRoot)return null;const t=e.shadowRoot.querySelector(".main");if(!t)return null;const n=t.querySelectorAll(".turn");if(0===n.length)return null;const r=n[n.length-1].querySelector("ucs-summary");if(!r)return null;const o=this.extractSummaryContent(r);if(!o)return this.extractTextWithLineBreaks(r);const i=this.cloneWithoutSrOnly(o),a=Uo(i).trim();return a||this.extractTextWithLineBreaks(i)}getSidebarScrollContainer(){return ei.query(".conversation-list",{shadow:true})||ei.query("mat-sidenav",{shadow:true})}getConversationObserverConfig(){return {selector:".conversation",shadow:true,extractInfo:e=>{const t=e.querySelector("button.list-item")||e.querySelector("button");if(!t)return null;const n=t.querySelector(".conversation-action-menu-button");if(!n||!n.id?.startsWith("menu-"))return null;const r=n.id.replace("menu-","");if(!/^\d+$/.test(r))return null;const o=t.querySelector(".conversation-title"),i=o?.textContent?.trim()||"",a=this.getCurrentCid();return {id:r,cid:a,title:i,url:`https://business.gemini.google/home/cid/${a}/r/session/${r}`}},getTitleElement:e=>{const t=e.querySelector("button.list-item")||e.querySelector("button");return t?.querySelector(".conversation-title")||e}}}navigateToConversation(e,t){const n=ei.query(".conversation",{all:true,shadow:true});if(n)for(const r of Array.from(n)){if(r.querySelector(`#menu-${e}`)||r.querySelector(`.conversation-action-menu-button[id="menu-${e}"]`)){const e=r.querySelector("button.list-item")||r.querySelector("button");return e?e.click():r.click(),true}}return super.navigateToConversation(e,t)}async deleteConversationOnSite(e){const t=await this.deleteConversationOnSiteInternal(e);return t.success&&this.scheduleFullReloadAfterDelete([e.id]),t}async deleteConversationsOnSite(e){const t=[],n=[];for(let r=0;r0&&this.scheduleFullReloadAfterDelete(n),t}async deleteConversationOnSiteInternal(e){const t=await this.deleteConversationViaUi(e.id);return {id:e.id,success:t,method:t?"ui":"none",reason:t?void 0:dh}}async deleteConversationViaUi(e){const t=await this.findConversationRowWithRetry(e);if(!t)return  false;t.scrollIntoView({block:"center",behavior:"auto"}),this.revealConversationActions(t);const n=await this.findConversationMenuButton(t);if(!n)return  false;const r=await this.openConversationMenu(t,n);if(!r)return  false;const o=await this.waitForDeleteMenuItem(n,2500,r);if(!o)return document.body.click(),false;this.simulateClick(o),this.removeConversationRowElement(t,e);const i=await this.waitForConversationRemoved(e,5200),a=await this.waitForMenuClosed(1200),s=i||a;return s&&this.syncConversationListAfterDelete(e),s}async openConversationMenu(e,t){let n=t;for(let r=0;r<4;r++){if(document.body.click(),await this.sleep(60),this.revealConversationActions(e),n&&n.isConnected||(n=await this.findConversationMenuButton(e)),!n)return null;this.simulateClick(n);const t=await this.waitForMenuOpen(n,900);if(t)return t}return null}async waitForMenuOpen(e,t=900){const n=Date.now();for(;Date.now()-nthis.revealConversationActions(e));const o=r.flatMap(e=>Array.from(e.querySelectorAll(t))).filter(e=>!(e instanceof HTMLButtonElement&&e.disabled));if(o.length>0){if(n){const e=o.find(e=>e.id===`menu-${n}`);if(e)return e}const e=o.find(e=>null!==e.querySelector('mat-icon[fonticon="more_vert"], mat-icon[fonticon="more_horiz"], md-icon'));if(e)return e;const t=o.filter(e=>this.isVisible(e)).sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0];if(t)return t}await this.sleep(90);}return null}getMenuSearchScopes(e){const t=[e,e.parentElement,e.parentElement?.parentElement,e.closest("li")].filter(e=>e instanceof HTMLElement),n=new Set,r=[];for(const o of t)n.has(o)||(n.add(o),r.push(o));return r}revealConversationActions(e){const t=["mouseenter","mouseover","mousemove"];for(const n of t)e.dispatchEvent(new MouseEvent(n,{bubbles:true,cancelable:true,view:window}));}async waitForDeleteMenuItem(e,t=2500,n){const r=Date.now();let o=[];for(;Date.now()-rthis.isVisible(e));r.length>0&&(o=r),await this.sleep(80);}if(o.length>0){const e=o[o.length-1],t=this.getSignalText(e);if(!this.hasKeyword(t,gh))return e}return null}getMenuActionCandidates(e,t){const n='md-menu-item, [role="menuitem"], [role="menu"] button, .mat-mdc-menu-panel button',r=[];t&&r.push(...Array.from(t.querySelectorAll(n)));const o=this.getMenuContainerFromTrigger(e);o&&r.push(...Array.from(o.querySelectorAll(n)));const i=this.findVisibleMenuContainer();i&&r.push(...Array.from(i.querySelectorAll(n))),r.push(...this.findAllElementsBySelector(n));const a=new Set,s=[];for(const l of r)a.has(l)||(a.add(l),s.push(l));return s}getMenuContainerFromTrigger(e){const t=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(!t)return null;const n="undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(t):t;return ei.query(`#${n}`,{shadow:true})||null}findVisibleMenuContainer(){const e=this.findAllElementsBySelector('md-menu-surface, .menu[popover], .mat-mdc-menu-panel, [role="menu"]').filter(e=>this.isVisible(e));return 0===e.length?null:e[e.length-1]}async waitForMenuClosed(e=1200){const t=Date.now();for(;Date.now()-te instanceof HTMLElement),r=new Set;for(const o of n)r.has(o)||(r.add(o),o.isConnected&&o.remove());}async waitForConversationRemoved(e,t=5200){const n=Date.now();for(;Date.now()-nn.includes(e.toLowerCase()))}isVisible(e){if(!(e instanceof HTMLElement))return  false;if(!e.isConnected)return  false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return  false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}getNewChatButtonSelectors(){return [".chat-button.list-item",'button[aria-label="New chat"]','button[aria-label="新对话"]']}getWidthSelectors(){const e=(e,t,n,r=false)=>({selector:e,globalSelector:`mat-sidenav-content ${e}`,property:"max-width",value:t,extraCss:n,noCenter:r});return [e("mat-sidenav-content","100%",void 0,true),e(".main.chat-mode","100%",void 0,true),e("ucs-summary"),e("ucs-conversation"),e("ucs-search-bar"),e(".summary-container.expanded"),e(".conversation-container"),e(".input-area-container",void 0,"left: 0 !important; right: 0 !important;",true)]}getUserQueryWidthSelectors(){return [{selector:".question-block .question-wrapper",property:"max-width",noCenter:true}]}getZenModeSelectors(){return [{selector:".disclaimer",action:"hide"}]}getTextareaSelectors(){return ["div.ProseMirror",".ProseMirror",'[contenteditable="true"]:not([type="search"])','[role="textbox"]','textarea:not([type="search"])']}getSubmitButtonSelectors(){return ['button[aria-label*="Submit"]','button[aria-label*="提交"]','button[aria-label*="发送"]','button[aria-label*="Send"]',".send-button",'[data-testid*="send"]']}isValidTextarea(e){if("search"===e.type)return  false;if(e.classList.contains("main-input"))return  false;if(e.getAttribute("aria-label")?.includes("搜索"))return  false;if(e.placeholder?.includes("搜索"))return  false;if(e.classList.contains("prompt-search-input"))return  false;if("prompt-search"===e.id)return  false;if(e.closest(".gh-main-panel"))return  false;if(e.closest(".gh-queue-panel"))return  false;if(Array.from(e.classList).some(e=>e.startsWith("gh-queue-")||e.startsWith("gh-")))return  false;const t=null!==e.offsetParent,n="true"===e.getAttribute("contenteditable"),r=e.classList.contains("ProseMirror");return t&&(n||r||"TEXTAREA"===e.tagName)}findTextarea(){const e=ei.query(this.getTextareaSelectors(),{shadow:true,filter:e=>this.isValidTextarea(e)});return e?(this.textarea=e,e):super.findTextarea()}clearTextarea(){this.textarea&&(this.textarea.isConnected?(this.textarea.focus(),document.execCommand("selectAll",false,void 0),document.execCommand("insertText",false,"​")):this.textarea=null);}clearTextareaNormal(){this.textarea&&(this.textarea.isConnected?(this.textarea.focus(),document.execCommand("selectAll",false,void 0),document.execCommand("delete",false,void 0)):this.textarea=null);}insertPrompt(e){const t=this.textarea||this.findTextarea();if(!t)return console.warn("[GeminiEnterpriseAdapter] Editor not found during insert."),false;if(!t.isConnected)return this.textarea=null,false;this.textarea=t,t.click(),t.focus();const n=()=>(t.textContent?.replace(/[\u200B\u200C\u200D\uFEFF]/g,"")||"").includes(e);try{const r=new DataTransfer;r.setData("text/plain",e);const o=new ClipboardEvent("paste",{bubbles:!0,cancelable:!0,clipboardData:r});if(t.dispatchEvent(o),n())return t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.dispatchEvent(new KeyboardEvent("keydown",{bubbles:!0,key:" ",code:"Space"})),t.dispatchEvent(new KeyboardEvent("keyup",{bubbles:!0,key:" ",code:"Space"})),!0}catch{}try{document.execCommand("selectAll",!1,void 0);if(document.execCommand("insertText",!1,e)&&n())return t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),!0}catch{}try{t.focus();const r=t.ownerDocument.getSelection();r&&(r.selectAllChildren(t),r.collapseToEnd());const o=new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e});t.dispatchEvent(o);const i=new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e});if(t.dispatchEvent(i),n())return !0}catch{}try{let r=t.querySelector("p"),o=!1;if(r||(r=document.createElement("p"),t.appendChild(r),o=!0),r.textContent=e,(o||e)&&(t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))),t.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e})),t.dispatchEvent(new KeyboardEvent("keydown",{bubbles:!0,key:" ",code:"Space"})),t.dispatchEvent(new KeyboardEvent("keyup",{bubbles:!0,key:" ",code:"Space"})),t.dispatchEvent(new Event("change",{bubbles:!0})),n())return !0}catch{}return console.warn("[GeminiEnterpriseAdapter] All insert strategies failed for content insertion."),false}getScrollContainer(){const e=ei.query(".chat-mode-scroller",{shadow:true});return e&&e.scrollHeight>e.clientHeight?e:super.getScrollContainer()}getResponseContainerSelector(){return ".conversation-container"}getChatContentSelectors(){return [".model-response-container",".message-content","[data-message-id]","ucs-conversation-message",".conversation-message"]}getUserQuerySelector(){return ".question-block"}extractUserQueryText(e){const t=e.querySelector("ucs-fast-markdown");if(!t||!t.shadowRoot)return this.extractTextWithLineBreaks(e);const n=t.shadowRoot.querySelector(".markdown-document");return n?this.extractTextWithLineBreaks(n):this.extractTextWithLineBreaks(e)}extractAssistantResponseText(e){const t=this.extractSummaryContent(e);if(!t)return this.extractTextWithLineBreaks(e);const n=this.cloneWithoutSrOnly(t),r=Uo(n).trim();return r||this.extractTextWithLineBreaks(n)}extractUserQueryMarkdown(e){const t=e.querySelector("ucs-fast-markdown");if(!t||!t.shadowRoot)return e.textContent?.trimEnd()||"";const n=t.shadowRoot.querySelector(".markdown-document");if(!n)return e.textContent?.trimEnd()||"";const r=n.querySelectorAll("p");if(0===r.length)return n.textContent?.trimEnd()||"";return Array.from(r).map(e=>e.textContent||"").join("\n").trimEnd()}replaceUserQueryContent(e,t){const n=e.querySelector("ucs-fast-markdown");if(!n||!n.shadowRoot)return  false;const r=n.shadowRoot.querySelector(".markdown-document");if(!r)return  false;if(r.nextElementSibling?.classList.contains("gh-user-query-markdown"))return  false;const o=document.createElement("div");return o.className="gh-user-query-markdown gh-markdown-preview",!!Wu(o,t)&&(r.style.display="none",r.after(o),true)}usesShadowDOM(){return  true}extractSummaryContent(e){const t=(e,n=0)=>{if(n>10||!e)return null;const r=e.shadowRoot||(11===e.nodeType?e:null)||e;if("querySelector"in r){const e=r.querySelector(".markdown-document");if(e)return e}const o="querySelectorAll"in r?r.querySelectorAll("*"):[];for(const i of Array.from(o))if(i.shadowRoot){const e=t(i.shadowRoot,n+1);if(e)return e}return null};return t(e)}findHeadingsInShadowDOM(e,t,n,r,o,i={}){if(!(r>15))if("shadowRoot"in e&&e.shadowRoot)this.findHeadingsInShadowDOM(e.shadowRoot,t,n,r+1,o,i);else {if(e!==document&&"querySelectorAll"in e){const r=Array.from({length:n},(e,t)=>`h${t+1}`).join(", ");try{e.querySelectorAll(r).forEach(e=>{if(this.isInRenderedMarkdownContainer(e))return;const n=e.querySelectorAll("span[data-markdown-start-index]");if(n.length>0){const r=parseInt(e.tagName[1],10),a=Array.from(n).map(e=>e.textContent?.trim()).join("");if(a){const n={level:r,text:a,element:e};if(o){const t=`${e.tagName.toLowerCase()}-${a}`,r=i[t]||0;i[t]=r+1,n.id=`${o}::${t}::${r}`;}t.push(n);}}});}catch{}}if("querySelectorAll"in e){const a=e.querySelectorAll("*");for(const e of Array.from(a))e.shadowRoot&&this.findHeadingsInShadowDOM(e.shadowRoot,t,n,r+1,o,i);}}}extractOutline(e=6,t=false,n=false){const r=[],o=e=>{const t=this.extractSummaryContent(e);return t?t.textContent?.trim().length||0:e.textContent?.trim().length||0};if(!t)return this.findHeadingsInShadowDOM(document,r,e,0),n&&r.forEach((e,t)=>{if(!e.element)return;const n=e.element.closest(".markdown-document");if(n){let o=null;for(let n=t+1;n{const i=(t.getAttribute("jslog")||"").match(/(\d+_\d+)/),a=i?i[1]:void 0,s=t.querySelector(".question-block"),l=t.querySelector("ucs-summary");if(s){let e=this.extractUserQueryText(s),t=false;e.length>200&&(e=e.substring(0,200),t=true);const i={level:0,text:e,element:s,isUserQuery:true,isTruncated:t,id:a};n&&l&&(i.wordCount=o(l)),r.push(i);}if(l){const t=[];if(this.findHeadingsInShadowDOM(l,t,e,0,a),n){const e=this.extractSummaryContent(l);t.forEach((n,r)=>{if(!n.element)return;let o=null;for(let e=r+1;er.push(e));}}),r}findElementByHeading(e,t){const n=ei.query(`h${e}`,{all:true,shadow:true});for(const r of n)if(r.textContent?.trim()===t)return r;return null}getExportConfig(){return {userQuerySelector:".question-block",assistantResponseSelector:"ucs-summary",turnSelector:".turn",useShadowDOM:true}}getAssistantMermaidSupportMode(){return "fallback"}getAssistantMermaidBlocks(e){const t=e instanceof Element?e.matches("ucs-summary")?e:e.closest("ucs-summary")||ei.query("ucs-summary",{parent:e,shadow:true}):ei.query("ucs-summary",{parent:e,shadow:true})||null;if(!t)return [];const n=this.extractSummaryContent(t);return li(n||t)}isGenerating(){const e=(t,n=0)=>{if(n>10)return  false;const r=t.querySelector('button[aria-label*="Stop"], button[aria-label*="停止"], [data-test-id="stop-button"], .stop-button, md-icon-button[aria-label*="Stop"]');if(r&&null!==r.offsetParent)return  true;const o=t.querySelector('mat-spinner, md-spinner, .loading-spinner, [role="progressbar"], .generating-indicator, .response-loading');if(o&&null!==o.offsetParent)return  true;const i=t.querySelectorAll("*");for(const a of Array.from(i))if(a.shadowRoot&&e(a.shadowRoot,n+1))return  true;return  false};return e(document)}getStopButtonSelectors(){return ['button[aria-label*="Stop"]','button[aria-label*="停止"]','[data-test-id="stop-button"]',".stop-button",'md-icon-button[aria-label*="Stop"]']}requiresDomConfirmationForNetworkGeneration(){return  true}getModelName(){const e=(t,n=0)=>{if(n>10)return null;const r=["#model-selector-menu-anchor",".action-model-selector",".model-selector",'[data-test-id="model-selector"]',".current-model"];for(const e of r){const n=t.querySelector(e);if(n&&n.textContent){const e=n.textContent.trim(),t=e.match(/(\d+\.?\d*\s*)?(Pro|Flash|Ultra|Nano|Gemini|auto|自动)/i);if(t)return t[0].trim();if(e.length<=20&&e.length>0)return e}}const o=t.querySelectorAll("*");for(const i of Array.from(o))if(i.shadowRoot){const t=e(i.shadowRoot,n+1);if(t)return t}return null};return e(document)}getNetworkMonitorConfig(){return {urlPatterns:["widgetStreamAssist"],silenceThreshold:3e3}}afterPropertiesSet(e={}){this.clearOnInit=e.clearOnInit||false,super.afterPropertiesSet(e),this.clearOnInit&&this.clearTextarea();}lockModel(e,t=null){super.lockModel(e,t??void 0);}shouldInjectIntoShadow(e){return !(e.closest("mat-sidenav")||e.closest("mat-drawer")||e.closest('[class*="bg-sidebar"]'))}async loadAllConversations(){for(let e=0;e<20;e++){const e=(ei.query("button.show-more",{all:true,shadow:true})||[]).filter(e=>{const t=e.querySelector(".show-more-icon");return t&&!t.classList.contains("more-visible")});if(0===e.length)break;for(const t of e)t.click();await new Promise(e=>setTimeout(e,300));}}getDefaultLockSettings(){return {enabled:true,keyword:"3 Pro"}}getModelSwitcherConfig(e){return {targetModelKeyword:e||"3 Pro",selectorButtonSelectors:["#model-selector-menu-anchor",".action-model-selector"],menuItemSelector:"md-menu-item",checkInterval:1500,maxAttempts:20,menuRenderDelay:500}}
   /**
      * 模拟点击原生设置切换主题 (针对 Gemini Enterprise)
      * @param targetMode 目标主题模式
      */
   async toggleTheme(e){let t=false;const n=()=>{if(!t){try{ei.query('.menu[popover], md-menu-surface, .mat-menu-panel, [role="menu"]',{all:!0,shadow:!0}).forEach(e=>{const t=e;"0"!==t.style.opacity&&(t.style.setProperty("opacity","0","important"),t.style.setProperty("visibility","hidden","important"),t.style.setProperty("pointer-events","none","important"));});}catch{}requestAnimationFrame(n);}};n(),document.body.classList.add("gh-stealth-mode");try{let t=ei.query(".settings-button",{shadow:!0});if(!t)return console.error("[GeminiEnterpriseAdapter] Settings button not found (.settings-button)"),!1;"function"==typeof t.click?t.click():t.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window}));let n=0;const r=()=>{const t="system"===e?"computer":"dark"===e?"dark_mode":"light_mode",n=ei.query("md-primary-tab",{all:!0,shadow:!0});for(const e of n){const n=e.querySelector("md-icon")||ei.query("md-icon",{parent:e,shadow:!0});if(n&&n.textContent?.trim()===t)return e.click(),!0}return !1};return await new Promise(e=>{const o=setInterval(()=>{n++,r()?(clearInterval(o),e(!0)):n>20&&(clearInterval(o),console.error("[GeminiEnterpriseAdapter] Target theme option not found"),e(!1),t&&"function"==typeof t.click&&t.click());},100);})}finally{t=true,setTimeout(()=>{document.body.classList.remove("gh-stealth-mode");},200);}}},new ch,new class extends ci{sessionAccessToken=null;sessionAccessTokenExpiresAt=0;lastModelLockAttemptAt=0;lastModelLockAttemptKeyword="";cachedSelectedModelName=null;cachedSelectedModelSlug=null;cachedSelectedModelExpiresAt=0;cachedSelectedModelContextKey="";cachedSelectedModelObservedAt=0;cachedModelDisplayNamesBySlug=new Map;match(){return window.location.hostname.includes("chatgpt.com")}getSiteId(){return Nr}getName(){return "ChatGPT"}getThemeColors(){return {primary:"#10a37f",secondary:"#1a7f64"}}getNativeThemeCss(){return "\n/* =============================================\n * ChatGPT 站点原生主题适配器 (ChatGPT Theme Adapter)\n * ============================================= */\n:root, .dark, .light {\n  /* 1. 核心页面容器及背景:主背景也稍微混入一点主题色(2%),避免纯白色大面积太刺眼 */\n  --bg-primary: color-mix(in srgb, var(--gh-primary) 1%, var(--gh-bg)) !important;\n  --bg-secondary: color-mix(in srgb, var(--gh-primary) 2%, var(--gh-bg)) !important;\n  --bg-tertiary: color-mix(in srgb, var(--gh-primary) 3%, var(--gh-bg)) !important;\n\n  /* 悬浮层、气泡和弹窗 */\n  --bg-elevated-primary: var(--gh-bg-secondary) !important;\n  --bg-elevated-secondary: var(--gh-bg-tertiary) !important;\n\n  /* 底层遮罩 */\n  --bg-scrim: var(--gh-overlay-bg) !important;\n\n  /* 2. 文本与图标层级 */\n  --icon-primary: var(--gh-text) !important;\n  --icon-secondary: var(--gh-text-secondary) !important;\n  --icon-tertiary: var(--gh-text-tertiary) !important;\n\n  /* 3. 边框 (使用极其微弱的透明度保持原生通透感) */\n  --border-default: color-mix(in srgb, var(--gh-primary) 15%, transparent) !important;\n  --border-heavy: color-mix(in srgb, var(--gh-primary) 25%, transparent) !important;\n  --border-light: color-mix(in srgb, var(--gh-primary) 8%, transparent) !important;\n\n  /* 4. 品牌高亮/突出显示(绑定 Ophel 主题色) */\n  --bg-accent-static: var(--gh-primary) !important;\n  --text-accent: var(--gh-primary) !important;\n  --icon-accent: var(--gh-primary) !important;\n  --interactive-label-accent-default: var(--gh-primary) !important;\n  --interactive-label-accent-hover: var(--gh-primary) !important;\n  --interactive-label-accent-press: var(--gh-primary) !important;\n  --interactive-label-accent-inactive: var(--gh-primary) !important;\n  --interactive-label-accent-selected: var(--gh-primary) !important;\n  --interactive-icon-accent-default: var(--gh-primary) !important;\n\n  /* 5. 交互状态 (按钮 Hover 等) */\n  /* - 次级交互(普通按钮/Icon Hover) */\n  --interactive-bg-secondary-hover: var(--gh-hover) !important;\n  --interactive-bg-secondary-press: var(--gh-active-bg) !important;\n  --interactive-bg-secondary-selected: var(--gh-active-bg) !important;\n\n  /* - 第三级交互(如模型选择器等) */\n  --interactive-bg-tertiary-default: var(--gh-bg-secondary) !important;\n  --interactive-bg-tertiary-hover: var(--gh-hover) !important;\n  --interactive-bg-tertiary-press: var(--gh-active-bg) !important;\n\n  /* 6. 其他小细节 */\n  --utility-scrollbar: var(--gh-border) !important;\n  /* 行内代码块背景 */\n  --gray-100: var(--gh-bg-tertiary) !important;\n}\n\n/* 按钮颜色 */\n.composer-btn {\n  color: var(--gh-primary) !important;\n}\n\n/* 链接颜色 */\na.decorated-link:where(:not(.not-markdown *)) {\n  color: var(--gh-primary) !important;\n}\n"}getNewTabUrl(){return "https://chatgpt.com"}getSessionId(){const e=window.location.pathname.match(/\/c\/([a-z0-9-]+)(?:\/|$)/i);return e?.[1]?e[1]:super.getSessionId()}isNewConversation(){const e=window.location.pathname;return "/"===e||""===e}getCurrentCid(){try{const e=localStorage.getItem("_account");if(e)return JSON.parse(e)}catch{}return null}getConversationList(){const e=document.querySelectorAll('#history a[data-sidebar-item="true"]')||[],t=this.getCurrentCid()||void 0;return Array.from(e).map(e=>{const n=(e.getAttribute("href")||"").match(/\/c\/([a-f0-9-]+)/),r=n?n[1]:"",o=e.querySelector("span"),i=o?.textContent?.trim()||"",a=e.hasAttribute("data-active"),s=e.querySelector(".trailing-pair"),l=(s?.querySelectorAll(".trailing svg")||[]).length>1;return {id:r,cid:t,title:i,url:r?`https://chatgpt.com/c/${r}`:"",isActive:a,isPinned:l}}).filter(e=>e.id)}getSidebarScrollContainer(){const e=document.querySelector("#history");if(e){const t=e.closest("nav");if(t)return t}return null}getConversationObserverConfig(){return {selector:'#history a[data-sidebar-item="true"]',shadow:false,extractInfo:e=>{const t=(e.getAttribute("href")||"").match(/\/c\/([a-f0-9-]+)/),n=t?t[1]:"";if(!n)return null;const r=e.querySelector("span"),o=r?.textContent?.trim()||"",i=e.hasAttribute("data-active"),a=this.getCurrentCid()||void 0,s=e.querySelector(".trailing-pair");return {id:n,cid:a,title:o,url:`https://chatgpt.com/c/${n}`,isActive:i,isPinned:(s?.querySelectorAll(".trailing svg")||[]).length>1}},getTitleElement:e=>e.querySelector("span")||e}}navigateToConversation(e,t){const n=document.querySelector(`#history a[href="/c/${e}"], a[data-sidebar-item][href="/c/${e}"]`);return n?(n.click(),true):super.navigateToConversation(e,t)}async deleteConversationOnSite(e){return this.deleteConversationOnSiteInternal(e)}async deleteConversationsOnSite(e){const t=[];for(let n=0;nt+5e3)return this.sessionAccessToken;try{const e=await fetch("/api/auth/session",{method:"GET",credentials:"include"});if(!e.ok)return this.clearSessionAccessToken(),null;const n=await e.json(),r=[n?.accessToken,n?.access_token,n?.token,n?.user?.accessToken].find(e=>"string"==typeof e&&e.length>0)||null;return "string"==typeof r&&r.length>0?(this.sessionAccessToken=r,this.sessionAccessTokenExpiresAt=t+3e5,r):(this.clearSessionAccessToken(),null)}catch{return this.clearSessionAccessToken(),null}}getCookieValue(e){const t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));if(!n)return null;try{return decodeURIComponent(n[1])}catch{return n[1]}}getChatgptAccountId(){try{const e=localStorage.getItem("_account");if(!e)return null;const t=JSON.parse(e);return "string"==typeof t&&t&&"personal"!==t?t:null}catch{return null}}buildNativeDeleteHeaders(e,t){const n={accept:"*/*",authorization:`Bearer ${e}`};"PATCH"===t&&(n["content-type"]="application/json");const r=this.getChatgptAccountId();r&&(n["chatgpt-account-id"]=r);const o=this.getCookieValue("oai-did");o&&(n["oai-device-id"]=o);const i=document.documentElement.lang||navigator.language;return i&&(n["oai-language"]=i),n}async performNativeDeleteRequest(e,t,n="PATCH"){const r=this.buildNativeDeleteHeaders(t,n);return fetch(e,{method:n,headers:r,body:"PATCH"===n?JSON.stringify({is_visible:false}):void 0,credentials:"include"})}async isConversationAlreadyGone(e){return !(await this.findConversationRowWithRetry(e))}syncSidebarAfterRemoteDelete(e){const t=this.findConversationRow(e);if(!t)return;(t.closest("li")||t).remove();}toDeleteApiHttpReason(e){switch(e){case 401:case 403:return "delete_api_unauthorized";case 404:return "delete_api_not_found";case 429:return "delete_api_rate_limited";default:return `delete_api_http_${e}`}}async tryDeleteViaNativeApi(e){let t=await this.getSessionAccessToken();if(!t)return {id:e,success:false,method:"none",reason:Gi};const n=async(e,n="PATCH")=>{let r=await this.performNativeDeleteRequest(e,t,n);if(401===r.status||403===r.status){if(t=await this.getSessionAccessToken(true),!t)return this.clearSessionAccessToken(),r;r=await this.performNativeDeleteRequest(e,t,n);}return r},r=encodeURIComponent(e),o=[`/backend-api/conversation/${r}`,`/backend-api/conversations/${r}`];try{let t=null;for(const r of o){let o=await n(r,"PATCH");if(t=o.status,o.ok)return this.syncSidebarAfterRemoteDelete(e),{id:e,success:!0,method:"api"};if(405===o.status&&(o=await n(r,"DELETE"),t=o.status,o.ok))return this.syncSidebarAfterRemoteDelete(e),{id:e,success:!0,method:"api"};if(404!==o.status)return 401!==o.status&&403!==o.status||this.clearSessionAccessToken(),{id:e,success:!1,method:"api",reason:this.toDeleteApiHttpReason(o.status)}}return 404===t&&await this.isConversationAlreadyGone(e)?(this.syncSidebarAfterRemoteDelete(e),{id:e,success:!0,method:"api"}):{id:e,success:!1,method:"api",reason:404===t?Ki:this.toDeleteApiHttpReason(t??0)}}catch(i){return i instanceof Error&&"AbortError"===i.name?{id:e,success:false,method:"api",reason:"delete_api_timeout"}:{id:e,success:false,method:"api",reason:Qi}}}async deleteConversationViaUi(e){const t=await this.findConversationRowWithRetry(e);if(!t)return  false;const n=await this.findConversationMenuButton(t,e);if(!n)return  false;document.body.click(),await this.sleep(50),this.simulateClick(n);const r=await this.waitForDeleteMenuItem(n);if(!r)return  false;this.simulateClick(r);const o=await this.waitForDeleteConfirmButton();return o&&this.simulateClick(o),this.waitForConversationRemoved(e,4e3)}async findConversationRowWithRetry(e){const t=this.findConversationRow(e);return t||(await this.loadAllConversations(),await this.sleep(200),this.findConversationRow(e))}findConversationRow(e){return document.querySelector(`#history a[data-sidebar-item="true"][href="/c/${e}"]`)}async findConversationMenuButton(e,t){const n=['button[aria-haspopup="menu"]','button[aria-label*="More"]','button[aria-label*="more"]','button[aria-label*="更多"]','button[data-testid*="menu"]',".trailing button"].join(", "),r=this.findConversationItemContainer(e,t),o=[r,e.closest("li"),e.parentElement,e].filter((e,t,n)=>!!e&&n.indexOf(e)===t);for(let i=0;i<8;i++){o.forEach(e=>{e.dispatchEvent(new MouseEvent("mouseenter",{bubbles:true})),e.dispatchEvent(new MouseEvent("mousemove",{bubbles:true}));});for(const e of o){const o=this.findFirstInScope(e,n,n=>this.isMenuButtonForConversation(n,t,r||e));if(o)return o}await this.sleep(100);}return null}findConversationItemContainer(e,t){const n=`/c/${t}`;let r=e,o=null;for(let i=0;i<8&&r;i++){const e=Array.from(r.querySelectorAll('a[data-sidebar-item="true"][href^="/c/"]'));if(e.some(e=>e.getAttribute("href")===n)){o||1!==e.length||(o=r);const t=!!r.querySelector('button[aria-haspopup="menu"], .trailing button');if(1===e.length&&t)return r}if("history"===r.id)break;r=r.parentElement;}return o||e.closest("li")||e.parentElement||e}findFirstInScope(e,t,n){const r=Array.from(e.querySelectorAll(t));for(const o of r)if(this.isVisible(o)&&(!n||n(o)))return o;return null}isMenuButtonForConversation(e,t,n){if(!n.contains(e))return  false;const r=`/c/${t}`,o=e.closest("li");if(o){const e=Array.from(o.querySelectorAll('a[data-sidebar-item="true"][href^="/c/"]'));if(1===e.length&&e[0].getAttribute("href")===r&&o.contains(n.querySelector(`a[data-sidebar-item="true"][href="${r}"]`)))return  true}const i=Array.from(n.querySelectorAll('a[data-sidebar-item="true"][href^="/c/"]'));return 1===i.length&&i[0].getAttribute("href")===r}getMenuContainerFromTrigger(e){const t=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(t){const e=document.getElementById(t);if(e)return e}const n=Array.from(document.querySelectorAll('[role="menu"]'));let r=null,o=Number.POSITIVE_INFINITY;const i=e.getBoundingClientRect(),a=i.left+i.width/2,s=i.top+i.height/2;for(const l of n){if(!this.isVisible(l))continue;const e=l.getBoundingClientRect(),t=e.left+e.width/2,n=e.top+e.height/2,i=Math.hypot(t-a,n-s);i0?n:r;for(const e of o){if(!this.isVisible(e))continue;const t=(e.textContent||"").trim().toLowerCase();if(Ui.some(e=>t.includes(e.toLowerCase())))return e}await this.sleep(80);}return null}async waitForDeleteConfirmButton(e=2500){const t=Date.now();for(;Date.now()-te.includes(t.toLowerCase())))return t}await this.sleep(80);}return null}async waitForConversationRemoved(e,t=3e3){const n=Date.now();for(;Date.now()-n0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}getSessionName(){const e=document.title;return e&&e!==Hi?e.replace(` | ${Hi}`,"").replace(` - ${Hi}`,"").trim():super.getSessionName()}getConversationTitle(){const e=document.querySelector("#history a[data-active] span"),t=e?.textContent?.trim();return t||this.getSessionName()}getNewChatButtonSelectors(){return ['[data-testid="create-new-chat-button"]','a[href="/"]','button[aria-label="New chat"]','button[aria-label="新对话"]']}getLatestReplyText(){const e=document.querySelector(this.getResponseContainerSelector());if(!e)return null;const t=e.querySelectorAll('[data-message-author-role="assistant"]');if(0===t.length)return null;const n=t[t.length-1],r=(n.querySelector(".markdown, .prose, [class*='prose']")||n).cloneNode(true);r.querySelectorAll('.sr-only, button, [role="button"], svg, [aria-hidden="true"]').forEach(e=>e.remove());const o=Uo(r).trim();return o||this.extractTextWithLineBreaks(r)}getWidthSelectors(){return [{selector:'[class*="thread-content-max-width"]',property:"max-width"},{selector:'[style*="--thread-content-max-width"]',property:"max-width"}]}getUserQueryWidthSelectors(){return [{selector:":root",property:"--user-chat-width",noCenter:true}]}getZenModeSelectors(){return [{selector:"div.select-none:has(> .pointer-events-auto)",action:"hide"}]}getMarkdownFixerConfig(){return {selector:'[data-message-author-role="assistant"] p',fixSpanContent:false,shouldSkip:e=>{if(!this.isGenerating())return  false;const t=e.closest('[data-message-author-role="assistant"]');if(!t)return  false;const n=document.querySelectorAll(this.getChatContentSelectors().find(e=>e.includes("assistant"))||'[data-message-author-role="assistant"]');return t===n[n.length-1]}}}getTextareaSelectors(){return ["#prompt-textarea",'textarea[data-id="root"]','[contenteditable="true"]']}getSubmitButtonSelectors(){return ['[data-testid="send-button"]','button[aria-label="Send prompt"]','button[aria-label="发送"]']}isValidTextarea(e){return null!==e.offsetParent&&(!e.closest(".gh-main-panel")&&("prompt-textarea"===e.id||"true"===e.getAttribute("contenteditable")))}insertPrompt(e){const t=this.textarea;if(!t)return  false;if(!t.isConnected)return this.textarea=null,false;if(t.focus(),document.activeElement!==t&&!t.contains(document.activeElement))return console.warn("[Ophel] insertPrompt: focus failed"),false;try{document.execCommand("selectAll",!1,void 0);if(!document.execCommand("insertText",!1,e))throw new Error("execCommand returned false")}catch{"TEXTAREA"===t.tagName?t.value=e:t.textContent=e,t.dispatchEvent(new Event("input",{bubbles:true}));}return  true}clearTextarea(){this.textarea&&(this.textarea.isConnected?(this.textarea.focus(),"TEXTAREA"===this.textarea.tagName?this.textarea.value="":(document.execCommand("selectAll",false,void 0),document.execCommand("delete",false,void 0)),this.textarea.dispatchEvent(new Event("input",{bubbles:true}))):this.textarea=null);}getScrollContainer(){const e=document.querySelector('[class*="scrollbar-gutter"], [class*="@container/main"] > div');if(e&&e.scrollHeight>e.clientHeight)return e;const t=document.querySelectorAll("div");let n=null,r=0;for(const o of Array.from(t)){const e=getComputedStyle(o);("auto"===e.overflowY||"scroll"===e.overflowY)&&o.scrollHeight>o.clientHeight&&o.scrollHeight>r&&(o.closest("nav")||(r=o.scrollHeight,n=o));}return n}getResponseContainerSelector(){return "#thread, main#main"}getChatContentSelectors(){return ['[data-message-author-role="assistant"]','[data-message-author-role="user"]',".markdown"]}getUserQuerySelector(){return '[data-message-author-role="user"]'}extractUserQueryText(e){const t=e.matches(".whitespace-pre-wrap")?e:e.querySelector(".whitespace-pre-wrap");return t?this.extractTextWithLineBreaks(t).trim():this.extractTextWithLineBreaks(e).trim()}extractUserQueryMarkdown(e){const t=e.querySelector(".whitespace-pre-wrap");if(!t)return this.extractUserQueryText(e).trim();const n=t.cloneNode(true);n.querySelectorAll(".sr-only").forEach(e=>e.remove());const r=Uo(n).trim();return r||this.extractUserQueryText(t).trim()}extractUserQueryExportText(e){return this.extractUserQueryMarkdown(e).trim()||this.extractUserQueryText(e)}shouldSkipElement(e){return e.classList.contains("sr-only")}extractTextWithLineBreaks(e){const t=[],n=new Set(["div","p","li","h1","h2","h3","h4","h5","h6","pre","blockquote","tr","section","article"]),r=e=>{if(e.nodeType===Node.TEXT_NODE){const n=e.textContent||"";t.push(n);}else if(e.nodeType===Node.ELEMENT_NODE){const o=e,i=o.tagName.toLowerCase();if(this.shouldSkipElement(o))return;if("br"===i)return void t.push("\n");for(const e of o.childNodes)r(e);if(n.has(i)&&t.length>0){t[t.length-1].endsWith("\n")||t.push("\n");}}};return r(e),t.join("").replace(/\n{3,}/g,"\n\n").trim()}replaceUserQueryContent(e,t){const n=e.querySelector(".whitespace-pre-wrap");if(!n)return  false;if(n.nextElementSibling?.classList.contains("gh-user-query-markdown"))return  false;n.style.display="none";const r=document.createElement("div");return r.className="gh-user-query-markdown gh-markdown-preview",r.innerHTML=t,n.after(r),true}getExportConfig(){return {userQuerySelector:'[data-message-author-role="user"]',assistantResponseSelector:'[data-message-author-role="assistant"]',turnSelector:'[data-testid^="conversation-turn"]',useShadowDOM:false}}getAssistantMermaidSupportMode(){return "native"}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector(this.getResponseContainerSelector());if(!o)return r;const i={},a=(e,t,n)=>{if(!e)return 0;try{if(n){const n=o.querySelectorAll('[data-message-author-role="assistant"]');let r="";for(const o of Array.from(n)){const n=e.compareDocumentPosition(o);if(!(n&Node.DOCUMENT_POSITION_FOLLOWING))continue;if(t){const e=t.compareDocumentPosition(o);if(!(e&Node.DOCUMENT_POSITION_PRECEDING))continue}const i=o.querySelector(".markdown, .prose, [class*='prose']");if(i)r+=i.textContent||"";else {const e=o.cloneNode(!0);e.querySelectorAll(".sr-only, [class*='sr-only']").forEach(e=>e.remove()),r+=e.textContent||"";}}return r.trim().length}if(t)return this.calculateRangeWordCount(e,t,o);const r=o.querySelectorAll(s);let i=!1,a=null;for(const t of Array.from(r)){if(i){a=t;break}(t===e||t.contains(e)||e.contains(t))&&(i=!0);}if(a)return this.calculateRangeWordCount(e,a,o);const l=o.querySelectorAll('[data-message-author-role="assistant"]');if(l.length>0){const t=l[l.length-1];return this.calculateRangeWordCount(e,null,t)}return this.calculateRangeWordCount(e,null,o)}catch{return 0}},s=this.getUserQuerySelector(),l=[];for(let u=1;u<=e;u++)l.push(`h${u}`);const c=`${s}, ${l.join(", ")}`,d=Array.from(o.querySelectorAll(c));return d.forEach((o,l)=>{const c=o.tagName.toLowerCase(),u=o.matches(s),h=/^h[1-6]$/.test(c);let g=false;if(t&&u&&(g=true),h&&!this.shouldSkipElement(o)&&!this.isInRenderedMarkdownContainer(o)){parseInt(c.charAt(1),10)<=e&&(g=true);}if(g){let e;if(u){let t=this.extractUserQueryText(o),n=false;t.length>200&&(t=t.substring(0,200),n=true),e={level:0,text:t,element:o,isUserQuery:true,isTruncated:n};}else {e={level:parseInt(c.charAt(1),10),text:o.textContent?.trim()||"",element:o,isUserQuery:false};}const t=(e=>{const t=e.closest("[data-message-id]");return t?t.getAttribute("data-message-id"):null})(o);if(t&&(e.id=u?t:((e,t,n)=>{i[e]||(i[e]={});const r=`${t}-${n}`,o=i[e][r]||0;return i[e][r]=o+1,`${e}::${r}::${o}`})(t,c,e.text)),n){let t=null;for(let n=l+1;nDate.now()&&(this.cachedSelectedModelName||this.cachedSelectedModelSlug)?{name:this.cachedSelectedModelName,slug:this.cachedSelectedModelSlug}:(this.cachedSelectedModelName=null,this.cachedSelectedModelSlug=null,this.cachedSelectedModelContextKey="",this.cachedSelectedModelObservedAt=0,this.cachedSelectedModelExpiresAt=0,null)}getRecentSelectedModelState(){const e=this.getRememberedSelectedModelState();return e?Date.now()-this.cachedSelectedModelObservedAt>3500?null:e:null}getLatestMessageModelSlug(){const e=Array.from(document.querySelectorAll("[data-message-model-slug]")).at(-1);return e?.getAttribute("data-message-model-slug")?.trim()||null}readModelStateFromOpenMenu(){const e=document.querySelector(Yi);if(!this.isVisible(e))return null;const t=Array.from(document.querySelectorAll(Ji));if(0===t.length)return null;let n=null,r=null;for(const o of t){const e=o.getAttribute("data-testid")||"",t=e.startsWith("model-switcher-")?e.replace(/^model-switcher-/,"").trim():"",i=o.querySelector(".min-w-0 > span")?.textContent?.replace(/\s+/g," ").trim()||"";t&&i&&this.cachedModelDisplayNamesBySlug.set(t,i);Boolean(o.querySelector(".trailing svg, .trailing use"))&&(n=i||null,r=t||null);}return this.rememberSelectedModelState(n,r),{name:n,slug:r}}extractModelNameFromSelectorButton(e){const t=e.getAttribute("aria-label");if(t){const e=t.match(/(?:模型为|model is)\s*(.+)/i);if(e)return e[1].trim()}const n=e.querySelector(".text-token-text-tertiary")?.textContent?.trim();return n||null}getReliableCurrentModelSignals(){const e=this.readModelStateFromOpenMenu(),t=this.findModelSelectorButton();return [e?.name,e?.slug,t?this.extractModelNameFromSelectorButton(t):null].filter(e=>Boolean(e&&e.trim()))}getCurrentModelSignalsForLockCheck(){const e=this.readModelStateFromOpenMenu(),t=this.getRecentSelectedModelState(),n=this.findModelSelectorButton();return [e?.name,e?.slug,t?.name,t?.slug,n?this.extractModelNameFromSelectorButton(n):null].filter(e=>Boolean(e&&e.trim()))}getModelName(){const e=this.readModelStateFromOpenMenu();if(e?.name)return e.name;const t=this.getLatestMessageModelSlug();if(t)return this.cachedModelDisplayNamesBySlug.get(t)||t;const n=this.getRememberedSelectedModelState();if(n?.name)return n.name;const r=this.findModelSelectorButton();if(r){const e=this.extractModelNameFromSelectorButton(r);if(e)return e}return null}getNetworkMonitorConfig(){return {urlPatterns:["backend-api/f/conversation"],urlPathEndsWith:["backend-api/f/conversation"],silenceThreshold:3e3}}getDefaultLockSettings(){return {enabled:false,keyword:""}}getModelLockCheckText(e){return this.getCurrentModelSignalsForLockCheck().join(" ")}findElementBySelectors(e){for(const t of e){const e=Array.from(document.querySelectorAll(t));for(const t of e)if(this.isVisible(t))return t}return super.findElementBySelectors(e)}lockModel(e,t){const n=e.trim();if(!n)return;const r=n.toLowerCase();if(this.getReliableCurrentModelSignals().join(" ").toLowerCase().trim().includes(r))return void t?.();const o=this.findModelSelectorButton(),i="true"===o?.getAttribute("aria-expanded")||Boolean(this.readModelStateFromOpenMenu()),a=this.lastModelLockAttemptKeyword===n&&Date.now()-this.lastModelLockAttemptAt<1200;i||a||(this.lastModelLockAttemptKeyword=n,this.lastModelLockAttemptAt=Date.now(),super.lockModel(n,()=>{this.lastModelLockAttemptAt=0,t?.();}));}clickModelSelector(){const e=this.findModelSelectorButton();return !!e&&(this.simulateClick(e),true)}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:[...Zi],menuItemSelector:'[data-radix-collection-item][role="menuitem"], [role="menuitem"], [role="option"]',checkInterval:1e3,maxAttempts:15,menuRenderDelay:500}}simulateClick(e){if(e.matches('button[data-testid="model-switcher-dropdown-button"][aria-haspopup="menu"]')){const t=e.getAttribute("aria-expanded");e.click();const n=e.getAttribute("aria-expanded");if("true"===n||n!==t)return;return void e.dispatchEvent(new PointerEvent("pointerdown",{bubbles:true,cancelable:true,view:window,pointerId:1,button:0,buttons:1,pointerType:"mouse",isPrimary:true}))}e.click();}
   /**
      * 切换 ChatGPT 主题
      * 直接修改 localStorage.theme + html.className 实现即时无感切换
      * @param targetMode 目标主题模式
      */
   async toggleTheme(e){try{return localStorage.setItem("theme",e),document.documentElement.className=e,window.dispatchEvent(new StorageEvent("storage",{key:"theme",newValue:e,storageArea:localStorage})),!0}catch(t){return console.error("[ChatGPTAdapter] toggleTheme error:",t),false}}},new class extends ci{match(){const e=window.location.hostname;return "grok.com"===e||e.endsWith(".grok.com")}getSiteId(){return Rr}getName(){return "Grok"}getThemeColors(){return {primary:"#f39c12",secondary:"#1e1f22"}}getNativeThemeCss(){return "\n.bg-surface, .bg-surface-base {\n    background-color: color-mix(in srgb, var(--gh-primary) 2%, var(--gh-bg)) !important\n}\n\n.[&_a:not(.not-prose)]:text-current a:not(.not-prose) {\n    color: var(--gh-primary) !important;\n}\n\n\n"}getNewTabUrl(){return "https://grok.com/"}isNewConversation(){const e=window.location.pathname;return "/"===e||""===e}cachedDialogConversations=null;reloadScheduled=false;async loadAllConversations(){const e=document.querySelector('[data-sidebar="content"]');if(!e)return;const t=e.querySelector("button.w-full.justify-start.text-xs.text-secondary.font-semibold");if(t){const{showToast:e}=await r(async()=>{const{showToast:e}=await Promise.resolve().then(()=>Fo);return {showToast:e}},void 0),{t:n}=await r(async()=>{const{t:e}=await Promise.resolve().then(()=>ie);return {t:e}},void 0);e(n("grokSyncingConversations")||"正在同步会话,请稍候..."),t.click();let o=null;for(let t=0;t<30&&(await new Promise(e=>setTimeout(e,100)),o=document.querySelector('[cmdk-list-sizer=""], [cmdk-list]'),!o);t++);if(o){let e=0,t=0;const n=15;for(let r=0;rsetTimeout(e,400));const n=o.scrollHeight;if(n===e){if(t++,t>=3)break}else t=0,e=n;}}return this.cacheDialogConversations(),this.dispatchEscapeKey(),void setTimeout(()=>{this.cachedDialogConversations=null;},5e3)}}cacheDialogConversations(){const e=new Map;document.querySelectorAll('a[href^="/c/"]').forEach(t=>{if(this.isCmdkActionItem(t))return;const n=t.getAttribute("href");if(!n)return;const r=this.extractConversationIdFromHref(n);if(!r)return;if(e.has(r))return;let o="New Chat",i=false;const a=t.closest("[cmdk-item]");if(a){const e=a.querySelector("span.truncate");o=e?.textContent?.trim()||o,i=null!==a.querySelector('[class*="border-border-l2"]');}else o=t.textContent?.trim()||o;e.set(r,{id:r,title:o,url:n,isPinned:false,isActive:i});}),this.cachedDialogConversations=e;}getConversationList(){const e=new Map,t=document.querySelector('[data-sidebar="content"]');if(t){t.querySelectorAll('[data-sidebar="group"]').forEach(t=>{const n=t.querySelectorAll('a[href^="/c/"]');0!==n.length&&n.forEach(t=>{const n=t.getAttribute("href");if(!n)return;const r=this.extractConversationIdFromHref(n);if(!r)return;const o=t.querySelector("span.flex-1, span.truncate, span"),i=o?.textContent?.trim()||t.textContent?.trim()||"New Chat",a=t.classList.contains("bg-button-ghost-hover"),s=this.isPinnedSidebarConversation(t);e.set(r,{id:r,title:i,url:n,isPinned:s,isActive:a});});});}return document.querySelectorAll('a[href^="/c/"]').forEach(t=>{if(this.isCmdkActionItem(t))return;const n=t.getAttribute("href");if(!n)return;const r=this.extractConversationIdFromHref(n);if(!r)return;if(e.has(r))return;let o="New Chat",i=false;const a=t.closest("[cmdk-item]");if(a){const e=a.querySelector("span.truncate");o=e?.textContent?.trim()||o,i=null!==a.querySelector('[class*="border-border-l2"]');}else o=t.textContent?.trim()||o;e.set(r,{id:r,title:o,url:n,isPinned:false,isActive:i});}),this.cachedDialogConversations&&this.cachedDialogConversations.forEach((t,n)=>{e.has(n)||e.set(n,t);}),Array.from(e.values())}getSidebarScrollContainer(){return document.querySelector('[data-sidebar="content"]')}getConversationObserverConfig(){return {selector:'[data-sidebar="content"] a[href^="/c/"], [cmdk-item][data-value^="conversation:"] a[href^="/c/"]',shadow:false,extractInfo:e=>{const t=e.getAttribute("href");if(!t)return null;const n=this.extractConversationIdFromHref(t);if(!n)return null;const r=!!e.closest('[data-sidebar="content"]'),o=!!e.closest("[cmdk-item]");let i="",a=false;if(r){const t=e.querySelector("span.flex-1, span.truncate, span");i=t?.textContent?.trim()||e.textContent?.trim()||"",a=this.isPinnedSidebarConversation(e);}else if(o){const t=e.closest("[cmdk-item]"),n=t?.querySelector("span.truncate");i=n?.textContent?.trim()||"",a=false;}return {id:n,title:i,url:t,isPinned:a}},getTitleElement:e=>{const t=e.closest("[cmdk-item]");return t?t.querySelector("span.truncate")||e:e.querySelector("span.flex-1, span.truncate, span")||e}}}navigateToConversation(e,t){return t?(window.location.href=t,true):(window.location.href=`/c/${e}`,true)}async deleteConversationOnSite(e){const t=await this.deleteConversationOnSiteInternal(e);return t.success&&this.scheduleFullReloadAfterDelete([e.id]),t}async deleteConversationsOnSite(e){const t=[],n=[];for(let r=0;r0&&this.scheduleFullReloadAfterDelete(n),t}async deleteConversationOnSiteInternal(e){const t=await this.tryDeleteViaNativeApi(e.id);if(t.success)return t;return await this.deleteConversationViaUi(e.id)?{id:e.id,success:true,method:"ui"}:{id:e.id,success:false,method:"none",reason:t.reason||mh}}async tryDeleteViaNativeApi(e){const t=`/rest/app-chat/conversations/soft/${encodeURIComponent(e)}`;try{const n=await fetch(t,{method:"DELETE",headers:this.buildNativeDeleteHeaders(),credentials:"include"});return n.ok?(this.syncConversationListAfterDelete(e),{id:e,success:!0,method:"api"}):404===n.status?this.isConversationVisible(e)?{id:e,success:!1,method:"api",reason:yh}:(this.syncConversationListAfterDelete(e),{id:e,success:!0,method:"api"}):{id:e,success:!1,method:"api",reason:this.toDeleteApiHttpReason(n.status)}}catch{return {id:e,success:false,method:"api",reason:bh}}}buildNativeDeleteHeaders(){const e={accept:"*/*","x-xai-request-id":this.generateRequestId()},t=this.getStatsigId();return t&&(e["x-statsig-id"]=t),e}getStatsigId(){const e=["x-statsig-id","statsig.stableID","statsig.stable_id","statsigStableId"];for(const t of e){const e=localStorage.getItem(t);if("string"==typeof e&&e.length>0)return e}try{for(let e=0;e0)return t}catch{}if(n.length>0)return n}}}catch{}return null}generateRequestId(){return "undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`}toDeleteApiHttpReason(e){switch(e){case 401:case 403:return "delete_api_unauthorized";case 429:return "delete_api_rate_limited";default:return `delete_api_http_${e}`}}syncConversationListAfterDelete(e){this.cachedDialogConversations?.delete(e);const t=this.findConversationAnchors(e);for(const n of t){this.getConversationItemContainer(n).remove();}}scheduleFullReloadAfterDelete(e){if(this.reloadScheduled||0===e.length)return;const t=this.extractConversationIdFromHref(window.location.pathname);if(t&&e.includes(t))try{window.history.replaceState(window.history.state,"","/");}catch{}this.reloadScheduled=true,window.setTimeout(()=>{window.location.reload();},120);}async deleteConversationViaUi(e){let t=false;try{let n=await this.findConversationAnchorWithRetry(e,400);if(n||(t=await this.openConversationDialogIfNeeded(),this.getCmdkListElement()&&await this.scrollCmdkListToLoadAll(),n=await this.findConversationAnchorWithRetry(e,1200)),!n)return !1;const r=this.getConversationItemContainer(n);this.revealConversationActions(r,n);const o=await this.waitForDeleteButton(r,2e3);if(!o)return !1;this.simulateClick(o);const i=await this.waitForConfirmButton(r,2200);if(!i)return !1;this.simulateClick(i);const a=await this.waitForConversationRemoved(e,4e3);return a&&this.syncConversationListAfterDelete(e),a}finally{t&&this.closeConversationDialog();}}async openConversationDialogIfNeeded(){if(this.getCmdkListElement())return  false;const e=this.getViewAllButton();if(!e)return  false;this.simulateClick(e);const t=Date.now();for(;Date.now()-t<2500;){if(this.getCmdkListElement())return  true;await this.sleep(80);}return  false}getViewAllButton(){const e=document.querySelector('[data-sidebar="content"]');return e?e.querySelector("button.w-full.justify-start.text-xs.text-secondary.font-semibold"):null}getCmdkListElement(){return document.querySelector('[cmdk-list-sizer=""], [cmdk-list]')}closeConversationDialog(){this.dispatchEscapeKey();}dispatchEscapeKey(){const e=document.activeElement||document.body||document.documentElement;if(e)try{const t=new KeyboardEvent("keydown",{key:"Escape",code:"Escape",keyCode:27,which:27,bubbles:!0,cancelable:!0});e.dispatchEvent(t);}catch{e.dispatchEvent(new Event("keydown",{bubbles:true,cancelable:true}));}}async scrollCmdkListToLoadAll(){const e=this.getCmdkListElement();if(!e)return;let t=-1,n=0;for(let r=0;r<16;r++){e.scrollTop=e.scrollHeight,await this.sleep(300);const r=e.scrollHeight;if(r===t){if(n++,n>=3)break}else t=r,n=0;}}async findConversationAnchorWithRetry(e,t){const n=this.findConversationAnchors(e)[0];if(n)return n;const r=Date.now();for(;Date.now()-rthis.extractConversationIdFromHref(t.getAttribute("href"))===e)}getConversationItemContainer(e){const t=[e.closest("[cmdk-item]"),e.closest('[data-sidebar="menu-button"]'),e.closest('[data-sidebar="menu-item"]'),e.closest("li"),e.parentElement,e];for(const n of t)if(n instanceof HTMLElement)return n;return e}revealConversationActions(e,t){try{e.scrollIntoView({block:"center",inline:"nearest",behavior:"instant"});}catch{}e.dispatchEvent(new MouseEvent("mouseenter",{bubbles:true})),e.dispatchEvent(new MouseEvent("mousemove",{bubbles:true})),e.dispatchEvent(new MouseEvent("mouseover",{bubbles:true})),t&&(t.focus(),t.dispatchEvent(new FocusEvent("focus",{bubbles:true})));}async waitForDeleteButton(e,t){const n=Date.now();for(;Date.now()-ne.querySelector("svg")&&!(e.textContent||"").trim()),n=this.pickRightMostButton(t);if(n)return n}return null}pickConfirmButton(e,t){for(const n of e)if(this.hasKeyword(this.getElementSignal(n),wh))return n;for(const n of e)if(this.hasKeyword(this.getIconSignal(n),wh))return n;for(const n of e)if(this.hasKeyword(this.getElementSignal(n),vh))return n;if(false!==t?.allowIconOnlyFallback){const t=e.filter(e=>e.querySelector("svg")&&!(e.textContent||"").trim()),n=this.pickRightMostButton(t);if(n)return n}return null}pickRightMostButton(e){if(0===e.length)return null;return [...e].sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0]||null}findButtonsInScopes(e){const t=new Set,n=[];for(const r of e){const e=Array.from(r.querySelectorAll("button"));for(const r of e)t.has(r)||this.isVisible(r)&&(t.add(r),n.push(r));}return n}getElementSignal(e){return [e.textContent||"",e.getAttribute("aria-label")||"",e.getAttribute("title")||"",e.getAttribute("data-testid")||"",e.className||""].join(" ").toLowerCase()}getIconSignal(e){return Array.from(e.querySelectorAll("svg, path, use, [data-icon], [class*='icon'], [aria-label]")).map(e=>[e.getAttribute("aria-label")||"",e.getAttribute("data-icon")||"",e.getAttribute("name")||"",e.className||""].join(" ")).join(" ").toLowerCase()}hasKeyword(e,t){const n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}async waitForConversationRemoved(e,t){const n=Date.now();for(;Date.now()-ne.isConnected&&this.isVisible(e))}extractConversationIdFromHref(e){if(!e)return null;const t=e.match(/\/c\/([a-zA-Z0-9-]+)/);return t?t[1]:null}isPinnedSidebarConversation(e){if(!e.closest('[data-sidebar="content"]'))return  false;const t=e.closest('a[href^="/c/"]')??e;if(!this.hasPinnedIcon(t))return  false;const n=t.closest('[data-sidebar="menu-item"]'),r=t.closest('[data-sidebar="menu"]');return !n||!r||this.isPinnedSectionItem(n)}hasPinnedIcon(e){const t=e.querySelector('[data-sidebar="icon"] svg');if(!t)return  false;if(!this.isDomElementVisible(t))return  false;const n=Array.from(t.querySelectorAll("path"));return 0!==n.length&&n.some(e=>{const t=(e.getAttribute("d")||"").replace(/\s+/g,"");return !!t&&ph.some(e=>t===e)})}isPinnedSectionItem(e){let t=e.previousElementSibling;for(;t;){if(!t.matches('[data-sidebar="menu-item"]'))return  false;t=t.previousElementSibling;}return  true}isCmdkActionItem(e){const t=e.closest("[cmdk-item]");if(!t)return  false;if((t.getAttribute("data-value")||"").toLowerCase().startsWith("action:"))return  true;const n=t.closest("[cmdk-group]");if(!n)return  false;const r=(n.getAttribute("data-value")||"").replace(/\s+/g,"").toLowerCase();return !("actionsshowall"!==r&&!r.startsWith("actions"))}isDomElementVisible(e){if(!e)return  false;if(!e.isConnected)return  false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return  false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}isVisible(e){return e instanceof HTMLElement&&this.isDomElementVisible(e)}async sleep(e){await new Promise(t=>setTimeout(t,e));}getCurrentConversationTitleFromSources(){const e=this.extractConversationIdFromHref(window.location.pathname);if(!e)return null;const t=this.getConversationList().find(t=>t.id===e);if(t?.title?.trim())return t.title.trim();const n=document.querySelector(`[data-sidebar="content"] a[href="/c/${e}"], a[href="/c/${e}"]`);if(!n)return null;const r=n.querySelector("span.flex-1, span.truncate, span")?.textContent?.trim();return r||n.textContent?.trim()||null}getConversationTitleFromPage(){const e=document.querySelector(".conversation-title"),t=e?.textContent?.trim();return t||null}getSessionName(){return this.getCurrentConversationTitleFromSources()||this.getConversationTitleFromPage()}getConversationTitle(){return this.getCurrentConversationTitleFromSources()||this.getConversationTitleFromPage()}getNewChatButtonSelectors(){return ['a[href="/"]','[data-sidebar="header"] a','button[aria-label*="新"]','button[aria-label*="New"]']}getLatestReplyText(){const e=document.querySelectorAll(".message-bubble:not(.rounded-br-lg)");if(0===e.length)return null;const t=e[e.length-1],n=t.querySelector(".response-content-markdown");if(n){const e=n.cloneNode(true);e.querySelectorAll('button, [role="button"], svg, [aria-hidden="true"]').forEach(e=>e.remove());const t=Uo(e).trim();return t||this.extractTextWithLineBreaks(e)}return this.extractTextWithLineBreaks(t)}getWidthSelectors(){return [{selector:'[class*="--content-max-width"]',property:"--content-max-width"}]}getUserQueryWidthSelectors(){return [{selector:".message-bubble.rounded-br-lg",property:"max-width"}]}getTextareaSelectors(){return [".tiptap.ProseMirror[contenteditable='true']",'[contenteditable="true"].ProseMirror',".query-bar [contenteditable='true']","form [contenteditable='true']"]}getSubmitButtonSelectors(){return ['button[type="submit"]','form button[type="submit"]','.query-bar button[type="submit"]']}isValidTextarea(e){return null!==e.offsetParent&&(!e.closest(".gh-main-panel")&&"true"===e.getAttribute("contenteditable"))}insertPrompt(e){const t=this.textarea;if(!t)return  false;if(!t.isConnected)return this.textarea=null,false;if(t.focus(),"true"===t.getAttribute("contenteditable")){t.innerHTML=`

${e}

`,t.dispatchEvent(new Event("input",{bubbles:true}));const n=window.getSelection();if(n){const e=document.createRange();e.selectNodeContents(t),e.collapse(false),n.removeAllRanges(),n.addRange(e);}return true}return false}clearTextarea(){this.textarea&&(this.textarea.isConnected?(this.textarea.focus(),"true"===this.textarea.getAttribute("contenteditable")&&(this.textarea.innerHTML='


',this.textarea.dispatchEvent(new Event("input",{bubbles:true})))):this.textarea=null);}getScrollContainer(){const e=document.querySelector("main");if(e){const t=e.querySelector('[class*="overflow-auto"]');if(t&&t.scrollHeight>t.clientHeight)return t;if(e.scrollHeight>e.clientHeight)return e}const t=document.querySelectorAll('[class*="overflow-y-auto"], [class*="overflow-auto"]');for(const n of Array.from(t)){const e=n;if(e.scrollHeight>e.clientHeight+100)return e}return null}getResponseContainerSelector(){return "main"}getChatContentSelectors(){return ['[class*="prose"]','[dir="ltr"]']}getUserQuerySelector(){return ".message-bubble.rounded-br-lg"}cloneUserQuerySource(e){const t=e.querySelector(".response-content-markdown");if(!t)return null;const n=(t.querySelector(".gh-user-query-original")||t).cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown").forEach(e=>e.remove()),n}isLikelyInlineCodeSpan(e){if("span"!==e.tagName.toLowerCase())return false;if(e.childElementCount>0)return false;const t=e.getAttribute("class")||"",n=/(^|\s)!?font-mono(\s|$)/.test(t),r=/(^|\s)rounded-sm(\s|$)/.test(t);return n&&r}normalizeUserQueryMarkdownSource(e){return e.querySelectorAll("span").forEach(t=>{const n=t;if(!this.isLikelyInlineCodeSpan(n))return;const r=(e.ownerDocument||document).createElement("code");r.textContent=n.textContent||"",n.replaceWith(r);}),e}extractUserQueryMarkdownFromSource(e){return Uo(this.normalizeUserQueryMarkdownSource(e)).trim()}extractUserQueryText(e){const t=this.cloneUserQuerySource(e);return t?this.extractTextWithLineBreaks(t).trim():this.extractTextWithLineBreaks(e).trim()}extractUserQueryMarkdown(e){const t=this.cloneUserQuerySource(e);if(t){const e=this.extractUserQueryMarkdownFromSource(t);if(e)return e}return e.textContent?.trim()||""}extractUserQueryExportText(e){const t=this.cloneUserQuerySource(e);if(!t)return this.extractUserQueryText(e);return this.extractUserQueryMarkdownFromSource(t)||this.extractUserQueryText(e)}replaceUserQueryContent(e,t){const n=e.querySelector(".response-content-markdown");if(!n)return false;if(n.querySelector(".gh-user-query-markdown"))return false;const r=Array.from(n.children),o=document.createElement("div");o.className="gh-user-query-original",o.style.display="none",r.forEach(e=>{o.appendChild(e);}),n.appendChild(o);const i=document.createElement("div");return i.className="gh-user-query-markdown gh-markdown-preview",i.innerHTML=t,n.insertBefore(i,o),true}getExportConfig(){return {userQuerySelector:this.getUserQuerySelector(),assistantResponseSelector:".message-bubble:not(.rounded-br-lg) .response-content-markdown",turnSelector:"",useShadowDOM:false}}getAssistantMermaidSupportMode(){return "native"}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector(this.getResponseContainerSelector());if(!o)return r;const i=e=>{const t=e.closest('[id^="response-"]');return t?t.id:null},a={},s=(e,t,n)=>{a[e]||(a[e]={});const r=`${t}-${n}`,o=a[e][r]||0;return a[e][r]=o+1,`${e}::${r}::${o}`},l=this.getUserQuerySelector();if(!t){const t=[];for(let n=1;n<=e;n++)t.push(`h${n}`);const a=Array.from(o.querySelectorAll(t.join(", ")));return a.forEach((t,l)=>{if(this.isInRenderedMarkdownContainer(t))return;const c=parseInt(t.tagName.charAt(1),10);if(c<=e){const e={level:c,text:t.textContent?.trim()||"",element:t},d=i(t);if(d){const n=t.tagName.toLowerCase();e.id=s(d,n,e.text);}if(n){let n=null;for(let e=l+1;e{const c=t.tagName.toLowerCase();if(t.matches(l)){let e=this.extractUserQueryText(t),a=false;e.length>200&&(e=e.substring(0,200),a=true);const s={level:0,text:e,element:t,isUserQuery:true,isTruncated:a},c=i(t);c&&(s.id=c),n&&(s.wordCount=(e=>{const t=e.closest('[id^="response-"]');if(!t)return 0;let n=t.nextElementSibling,r=0;for(;n&&!n.querySelector(l);){const e=n.querySelector(".message-bubble:not(.rounded-br-lg)");if(e){const t=e.querySelector(".response-content-markdown");t&&(r+=t.textContent?.trim().length||0);}n=n.nextElementSibling;}if(0===r){const t=o.querySelectorAll(".message-bubble:not(.rounded-br-lg)");for(const n of Array.from(t)){if(!(e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING))continue;const t=e.parentElement?.nextElementSibling?.querySelector(l);if(t&&!(t.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_PRECEDING))continue;const o=n.querySelector(".response-content-markdown");o&&(r+=o.textContent?.trim().length||0);}}return r})(t)),r.push(s);}else if(/^h[1-6]$/.test(c)){if(this.isInRenderedMarkdownContainer(t))return;const d=parseInt(c.charAt(1),10);if(d<=e){const e={level:d,text:t.textContent?.trim()||"",element:t},h=i(t);if(h&&(e.id=s(h,c,e.text)),n){let n=null;for(let t=a+1;tt.id===e);if(t?.title?.trim())return t.title.trim();const n=document.querySelector(`a.prompt-link[href*="/prompts/${e}"], a.name-btn[href*="/prompts/${e}"], a[href*="/prompts/${e}"]`),r=n?.textContent?.trim();return r||null}getSessionName(){return this.getCurrentConversationTitleFromSources()}getConversationTitle(){return this.getCurrentConversationTitleFromSources()}getTextareaSelectors(){return ["textarea.textarea","textarea.cdk-textarea-autosize",'textarea[placeholder*="prompt"]','textarea[placeholder*="Start typing"]']}getSubmitButtonSelectors(){return ['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"]']}getSubmitKeyConfig(){try{const e=localStorage.getItem("aiStudioUserPreference");if(!e)return {key:"Enter"};return 2===JSON.parse(e).enterKeyBehavior?{key:"Ctrl+Enter"}:{key:"Enter"}}catch{return {key:"Enter"}}}isValidTextarea(e){return null!==e.offsetParent&&(!e.closest(".gh-main-panel")&&"textarea"===e.tagName.toLowerCase())}insertPrompt(e){const t=this.textarea;return !!t&&(t.isConnected?(t.focus(),"textarea"===t.tagName.toLowerCase()&&(t.value=e,t.dispatchEvent(new Event("input",{bubbles:true})),t.dispatchEvent(new Event("change",{bubbles:true})),t.selectionStart=t.selectionEnd=e.length,true)):(this.textarea=null,false))}clearTextarea(){const e=this.textarea;e&&(e.isConnected?(e.focus(),"textarea"===e.tagName.toLowerCase()&&(e.value="",e.dispatchEvent(new Event("input",{bubbles:true})),e.dispatchEvent(new Event("change",{bubbles:true})))):this.textarea=null);}getScrollContainer(){const e=[".chat-container",".virtual-scroll-container",'[class*="scroll"]','main [style*="overflow"]'];for(const n of e){const e=document.querySelector(n);if(e&&e.scrollHeight>e.clientHeight)return e}const t=document.querySelector("main");if(t){const e=t.querySelector('[class*="overflow"]');if(e&&e.scrollHeight>e.clientHeight)return e}return null}getResponseContainerSelector(){return ".chat-container, main"}getChatContentSelectors(){return [".chat-turn-container",'[class*="message"]','[class*="response"]']}getWidthSelectors(){return [{selector:".chat-session-content",property:"max-width"},{selector:".chat-turn-container",property:"max-width"},{selector:".table-container > table",property:"width",value:"100%",noCenter:true,extraCss:"min-width: 100% !important;"}]}getZenModeSelectors(){return [{selector:"ms-hallucinations-disclaimer",action:"hide"}]}getMarkdownFixerConfig(){return {selector:"ms-cmark-node span.ng-star-inserted",fixSpanContent:true}}lockModel(e,t){if(!e)return;let n=0;const r=setInterval(async()=>{n++;const o=document.querySelector("button.model-selector-card");if(o){clearInterval(r),o.click();if(!(await this.waitForModelSidebar()))return console.warn("[AIStudioAdapter] 模型侧边栏加载超时"),void this.closeModelSidebar();const n=`model-carousel-row-models/${e}`,a=document.getElementById(n);if(a){const n=a.querySelector("div > div > div > span:first-child"),r=n?.textContent?.trim()||e,o=this.getSessionId();o&&localStorage.setItem(`ophel:aistudio:model:${o}`,r),a.click(),t&&t();try{const e=No.getState().settings;e.aistudio?.collapseRunSettings&&setTimeout(()=>{const e=document.querySelector('button[aria-label="Close run settings panel"]');e&&e.click();},500);}catch(i){console.error("[AIStudioAdapter] Auto-collapse run settings failed:",i);}}else console.warn(`[AIStudioAdapter] 未找到目标模型: ${e}`),this.closeModelSidebar();}else {const e=document.querySelector('button[aria-label="Toggle run settings panel"]');e?(e.click(),n=Math.max(0,n-2)):n>=10&&(clearInterval(r),console.warn("[AIStudioAdapter] 未找到模型选择按钮"));}},1e3);}async getModelList(){let e=false,t=document.querySelector("button.model-selector-card");if(!t){const n=document.querySelector('button[aria-label="Toggle run settings panel"]');if(n){e=true,n.click();for(let e=0;e<20&&(await new Promise(e=>setTimeout(e,200)),t=document.querySelector("button.model-selector-card"),!t);e++);}}if(!t)return console.warn("[AIStudioAdapter] 模型选择器按钮未找到"),[];t.click();const n=await this.waitForModelSidebar();if(!n){if(console.warn("[AIStudioAdapter] 模型侧边栏加载超时"),e){const e=document.querySelector('button[aria-label="Close run settings panel"]');e&&e.click();}return []}const r=this.extractModelsFromSidebar(n);return this.closeModelSidebar(),e&&setTimeout(()=>{const e=document.querySelector('button[aria-label="Close run settings panel"]');e&&e.click();},500),r}async waitForModelSidebar(){const e=Date.now();for(;Date.now()-e<5e3;){const e=document.querySelector(".ms-sliding-right-panel-dialog, mat-dialog-container.mat-mdc-dialog-container");if(e)return await new Promise(e=>setTimeout(e,300)),e;await new Promise(e=>setTimeout(e,100));}return null}extractModelsFromSidebar(e){const t=[];return e.querySelectorAll(".model-options-container button.content-button").forEach(e=>{const n=(e.id||"").replace("model-carousel-row-","").replace("models/",""),r=e.querySelector("div > div > div > span:first-child"),o=r?.textContent?.trim()||n;n&&o&&t.push({id:n,name:o});}),t}closeModelSidebar(){const e=document.querySelector("button[data-test-close-button]");e?e.click():document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:true}));}async loadAllConversations(){const e="/library"===window.location.pathname;if(!e){const e=document.querySelector('a.view-all-history-link[href="/library"]');if(!e)return void(window.location.href="/library");e.click(),await this.waitForLibraryTable();}const t=this.extractLibraryConversations();t.length>0&&(this.cachedLibraryConversations=t),e||window.history.back(),setTimeout(()=>{this.cachedLibraryConversations=null;},1e4);}async waitForLibraryTable(){for(let e=0;e<50;e++){await new Promise(e=>setTimeout(e,100));if(document.querySelector("ms-library-table table tbody tr"))return await new Promise(e=>setTimeout(e,200)),true}return false}extractLibraryConversations(){const e=[];return document.querySelectorAll("ms-library-table table tbody tr").forEach(t=>{const n=t.querySelector('a[href*="/prompts/"]');if(!n)return;const r=n.getAttribute("href")||"",o=r.match(/\/prompts\/([^/]+)/);if(!o)return;const i=o[1],a=n.textContent?.trim()||"Untitled";e.push({id:i,title:a,url:r,isActive:window.location.pathname.includes(i),isPinned:false});}),e}extractSidebarConversations(){const e=new Map;return document.querySelectorAll('a[href*="/prompts/"]').forEach(t=>{const n=t.getAttribute("href");if(!n||n.includes("new_chat"))return;const r=n.match(/\/prompts\/([^/]+)/);if(!r)return;const o=r[1];if(e.has(o))return;const i=t.textContent?.trim()||"Untitled",a=window.location.pathname.includes(o);e.set(o,{id:o,title:i,url:n,isActive:a,isPinned:false});}),Array.from(e.values())}getConversationList(){return "/library"===window.location.pathname?this.extractLibraryConversations():this.cachedLibraryConversations&&this.cachedLibraryConversations.length>0?this.cachedLibraryConversations:this.extractSidebarConversations()}getSidebarScrollContainer(){const e=document.querySelector("aside");return e||null}getConversationObserverConfig(){return {selector:'a.prompt-link[href*="/prompts/"]:not([href*="new_chat"])',shadow:true,extractInfo:e=>{const t=e.getAttribute("href");if(!t)return null;const n=t.match(/\/prompts\/([^/]+)/);if(!n)return null;return {id:n[1],title:e.textContent?.trim()||"Untitled",url:t,isPinned:false}},getTitleElement:e=>e}}navigateToConversation(e,t){const n=document.querySelector(`a.prompt-link[href*="/prompts/${e}"], a.name-btn[href*="/prompts/${e}"]`);return n?(n.click(),true):(window.location.href=t||`/prompts/${e}`,true)}async deleteConversationOnSite(e){return (await this.deleteConversationsOnSite([e]))[0]||{id:e.id,success:false,method:"none",reason:di}}async deleteConversationsOnSite(e){const t=await this.enterLibraryPageForDelete(),n=[],r=[];let o=false;try{for(let t=0;t0&&this.scheduleFullReloadAfterDelete(r),n}finally{t.enteredLibrary&&!o&&await this.restoreFromLibraryPage(t.originalPath);}}async deleteConversationOnSiteInternal(e){const t=this.shouldUseNativeDeleteApi()?await this.tryDeleteViaGrpcApi(e.id):{id:e.id,success:false,method:"none",reason:hi};if(t.success)return t;const n=await this.deleteConversationViaUi(e.id);return {id:e.id,success:n,method:n?"ui":"none",reason:n?void 0:t.reason||di}}shouldUseNativeDeleteApi(){return false}async tryDeleteViaGrpcApi(e){const t=await this.buildGoogleAuthorizationHeader(window.location.origin);if(!t)return {id:e,success:false,method:"none",reason:gi};const n=this.resolveGoogleApiKey();if(!n)return {id:e,success:false,method:"none",reason:pi};const r=this.normalizePromptName(e),o=this.getDeletePromptEndpoints();let i=0;try{for(const a of o){const o=await fetch(a,{method:"POST",credentials:"include",headers:{accept:"*/*",authorization:t,"content-type":"application/json+protobuf","x-goog-api-key":n,"x-goog-authuser":this.resolveGoogAuthUser(),"x-user-agent":"grpc-web-javascript/0.1"},body:JSON.stringify([r])});if(i=o.status,o.ok)return this.cachedRpcOrigin=this.normalizeRpcOriginFromEndpoint(a),this.syncConversationListAfterDelete(e),{id:e,success:!0,method:"api"};if(404!==o.status){if(!(400===o.status||o.status>=500))return {id:e,success:!1,method:"api",reason:this.toDeleteApiHttpReason(o.status)}}else if(!this.isConversationVisible(e))return this.cachedRpcOrigin=this.normalizeRpcOriginFromEndpoint(a),this.syncConversationListAfterDelete(e),{id:e,success:!0,method:"api"}}return 404===i?{id:e,success:!1,method:"api",reason:fi}:{id:e,success:!1,method:"api",reason:this.toDeleteApiHttpReason(i||0)}}catch{return {id:e,success:false,method:"api",reason:mi}}}toDeleteApiHttpReason(e){switch(e){case 401:case 403:return "delete_api_unauthorized";case 429:return "delete_api_rate_limited";default:return `delete_api_http_${e}`}}normalizePromptName(e){return e?e.startsWith("prompts/")?e:`prompts/${e}`:""}getDeletePromptEndpoints(){const e=[];this.cachedRpcOrigin&&e.push(this.cachedRpcOrigin),e.push(...this.resolveRpcOriginsFromPerformance()),e.push("https://alkalimakersuite-pa.clients6.google.com");return Array.from(new Set(e.filter(Boolean))).map(e=>`${e}${vi}/DeletePrompt`)}resolveRpcOriginsFromPerformance(){const e=performance.getEntriesByType("resource");if(!e||0===e.length)return [];const t=[];for(let n=e.length-1;n>=0;n--){const r=e[n]?.name;if(!r||!r.includes(vi))continue;const o=this.normalizeRpcOriginFromEndpoint(r);o&&t.push(o);}return Array.from(new Set(t))}normalizeRpcOriginFromEndpoint(e){try{const t=new URL(e);return this.isLikelyRpcHost(t.hostname)?`${t.protocol}//${t.host}`:null}catch{return null}}isLikelyRpcHost(e){return /(?:^|\.)alkalimakersuite-[a-z0-9-]+\.clients\d+\.google\.com$/i.test(e)}async buildGoogleAuthorizationHeader(e){const t=Math.floor(Date.now()/1e3),n=this.getCookieValue("SAPISID"),r=this.getCookieValue("__Secure-1PAPISID"),o=this.getCookieValue("__Secure-3PAPISID"),i=[],a=n||r||o;if(a){const n=await this.buildSapisidHashToken(a,e,t);n&&i.push(`SAPISIDHASH ${n}`);}if(r){const n=await this.buildSapisidHashToken(r,e,t);n&&i.push(`SAPISID1PHASH ${n}`);}if(o){const n=await this.buildSapisidHashToken(o,e,t);n&&i.push(`SAPISID3PHASH ${n}`);}return 0===i.length?null:i.join(" ")}async buildSapisidHashToken(e,t,n){try{const r=`${n} ${e} ${t}`,o=await crypto.subtle.digest("SHA-1",(new TextEncoder).encode(r));return `${n}_${Array.from(new Uint8Array(o)).map(e=>e.toString(16).padStart(2,"0")).join("")}`}catch{return null}}resolveGoogleApiKey(){if(this.cachedApiKey&&this.isValidGoogleApiKey(this.cachedApiKey))return this.cachedApiKey;const e=window.WIZ_global_data,t=e?.SNlM0e;if(this.isValidGoogleApiKey(t))return this.cachedApiKey=t,t;for(let r=0;rt.id!==e));[`a.prompt-link[href*="/prompts/${e}"]`,`a.name-btn[href*="/prompts/${e}"]`,`a[href*="/prompts/${e}"]`].forEach(e=>{Array.from(document.querySelectorAll(e)).forEach(e=>{(e.closest("tr")||e.closest("li")||e.closest("mat-row")||e).remove();});});}isConversationVisible(e){return Boolean(document.querySelector(`a.prompt-link[href*="/prompts/${e}"], a.name-btn[href*="/prompts/${e}"], a[href*="/prompts/${e}"]`))}scheduleFullReloadAfterDelete(e){if(0===e.length)return;const t=this.getSessionId();if(t&&e.includes(t))try{window.history.replaceState(window.history.state,"","/prompts/new_chat");}catch{}}async deleteConversationViaUi(e){const t=await this.findLibraryRowByPromptId(e,1500);if(!t)return false;const n=this.findLibraryRowMenuButton(t);if(!n)return false;this.simulateClick(n);const r=await this.waitForDeleteMenuItem(2500);if(!r)return false;this.simulateClick(r);const o=await this.waitForDeleteConfirmButton(2500);if(!o)return false;this.simulateClick(o);const i=await this.waitForConversationRemoved(e,5e3);return i&&this.syncConversationListAfterDelete(e),i}async enterLibraryPageForDelete(){const e=`${window.location.pathname}${window.location.search}${window.location.hash}`;if("/library"===window.location.pathname)return {enteredLibrary:false,originalPath:e};const t=document.querySelector('a.view-all-history-link[href="/library"]');if(!t)return {enteredLibrary:false,originalPath:e};t.click();return await this.waitForLibraryTable()&&"/library"===window.location.pathname?{enteredLibrary:true,originalPath:e}:{enteredLibrary:false,originalPath:e}}async restoreFromLibraryPage(e){if(!e||"/library"!==window.location.pathname)return;window.history.back();const t=Date.now();for(;Date.now()-t<3e3;){if("/library"!==window.location.pathname)return;await this.sleep(80);}}async findLibraryRowByPromptId(e,t=1200){const n=Date.now();for(;Date.now()-nthis.isVisible(e));if(n.length>0)return n.sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0];const r=Array.from(e.querySelectorAll("button")).filter(e=>this.isVisible(e));return 0===r.length?null:r.sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0]}async waitForDeleteMenuItem(e=2500){const t=Date.now();for(;Date.now()-tthis.isVisible(e))||null}async waitForConversationRemoved(e,t=3500){const n=Date.now();for(;Date.now()-nn.includes(e.toLowerCase()))}isVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}getUserQuerySelector(){return ".chat-turn-container.user"}textCache=new Map;wordCountCache=new Map;lastSessionIdForCache=null;extractUserQueryText(e){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";const t=this.getSessionId();this.lastSessionIdForCache!==t&&(this.textCache.clear(),this.wordCountCache.clear(),this.lastSessionIdForCache=t);const n=e.closest("ms-chat-turn")?.id;let r="";const o=this.findUserContentChunk(e);if(o)r=this.extractTextWithLineBreaks(o).trim();else {const t=e.querySelector(".turn-content");if(t){if(t.querySelector(".author-label")){const e=t.cloneNode(true),n=e.querySelector(".author-label");n?.remove(),r=e.textContent?.trim()||"";}else r=t.textContent?.trim()||"";}else r=this.extractTextWithLineBreaks(e);}if(!r&&n){const e=this.getTextFromScrollbar(n);e&&(r=e);}return r?(n&&this.textCache.set(n,r),r):n&&this.textCache.has(n)?this.textCache.get(n):""}extractUserQueryMarkdown(e){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";const t=(this.findUserContentChunk(e)||e).cloneNode(true);t.querySelectorAll('.author-label, .actions-container, button, [role="button"], svg, [aria-hidden="true"]').forEach(e=>e.remove()),this.normalizeAssistantExportDom(t);const n=Uo(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}extractUserQueryExportText(e){return this.extractUserQueryMarkdown(e).trim()||this.extractUserQueryText(e)}findUserContentChunk(e){const t=["ms-text-chunk","ms-prompt-chunk.text-chunk","ms-prompt-chunk","ms-cmark-node.cmark-node.user-chunk"];for(const n of t){const t=e.querySelector(n);if(!t)continue;if(this.extractTextWithLineBreaks(t).trim())return t}return null}getExportConfig(){return this.exportSnapshotActive?{userQuerySelector:Ii,assistantResponseSelector:Ni,turnSelector:Mi,useShadowDOM:false}:{userQuerySelector:this.getUserQuerySelector(),assistantResponseSelector:ki,turnSelector:null,useShadowDOM:false}}getAssistantMermaidSupportMode(){return "fallback"}async prepareConversationExport(e){this.exportIncludeThoughtsOverride=e.includeThoughts,this.clearExportSnapshot();const t=this.getScrollContainer()||document.querySelector(this.getResponseContainerSelector()),n=document.querySelector(this.getResponseContainerSelector())||document.querySelector("main")||document.body,r=t instanceof HTMLElement?await this.collectExportMessageSnapshots(t):this.readVisibleExportMessageSnapshots(n);return 0===r.length?null:(this.mountExportSnapshot(r),{count:r.length})}async restoreConversationAfterExport(e,t){this.clearExportSnapshot(),this.exportIncludeThoughtsOverride=null;}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector(".chat-container")||document.querySelector("main");if(!o)return r;const i={},a=this.getUserQuerySelector(),s=e=>{const t=e.closest("ms-chat-turn");if(!t)return 0;const n=t.id;let r=t.nextElementSibling,o=0,i=false;for(;r;){if(r.querySelector(a))break;const e=r.querySelector(".chat-turn-container.model, .chat-turn-container:not(.user)");if(e){const t=e.querySelectorAll("ms-cmark-node");for(const e of Array.from(t)){if(e.closest("ms-thought-chunk"))continue;const t=e.textContent?.trim().length||0;t>0&&(i=true,o+=t);}}r=r.nextElementSibling;}return i&&n&&this.wordCountCache.set(n,o),0===o&&n&&this.wordCountCache.has(n)?this.wordCountCache.get(n):o};if(!t){const t=[];for(let n=1;n<=e;n++)t.push(`h${n}`);const a=Array.from(o.querySelectorAll(t.join(", ")));return a.forEach((t,s)=>{if(t.closest("textarea")||t.closest(".user-prompt-container"))return;if(this.isInRenderedMarkdownContainer(t))return;const l=parseInt(t.tagName.charAt(1),10);if(l<=e){const e={level:l,text:t.textContent?.trim()||"",element:t},c=(e=>{const t=e.closest("ms-chat-turn");return t&&t.id?t.id.replace(/^turn-/,""):null})(t);if(c){const n=t.tagName.toLowerCase();e.id=((e,t,n)=>{i[e]||(i[e]={});const r=`${t}-${n}`,o=i[e][r]||0;return i[e][r]=o+1,`${e}::${r}::${o}`})(c,n,e.text);}if(n){let n=null;for(let e=s+1;e{const a=t.tagName.toLowerCase();if(t.classList.contains("user")&&t.classList.contains("chat-turn-container")){let e=this.extractUserQueryText(t),o=false;e.length>200&&(e=e.substring(0,200),o=true);const i={level:0,text:e,element:t,isUserQuery:true,isTruncated:o},a=t.closest("ms-chat-turn"),l=a?.nextElementSibling;if(l&&"ms-chat-turn"===l.tagName.toLowerCase()){const e=this.extractTextWithLineBreaks(l).trim().substring(0,50);e&&(i.context=e);}n&&(i.wordCount=s(t)),r.push(i);}else if(/^h[1-6]$/.test(a)){if(t.closest(".user-prompt-container")||t.closest("textarea"))return;if(this.isInRenderedMarkdownContainer(t))return;const s=parseInt(a.charAt(1),10);if(s<=e){const e={level:s,text:t.textContent?.trim()||"",element:t};if(n){let n=null;for(let t=i+1;te.remove());const r=this.extractAssistantResponseMarkdown(t).trim();if(n.length>0){const e=n.join("\n\n");return r?`${e}\n\n${r}`:e}return r}extractAssistantResponseMarkdown(e){const t=e.cloneNode(true);t.querySelectorAll(`${Si}, .author-label, .actions-container, button, [role="button"], svg, [aria-hidden="true"]`).forEach(e=>e.remove()),this.normalizeAssistantExportDom(t);const n=Uo(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}shouldIncludeThoughtsInExport(){return "boolean"==typeof this.exportIncludeThoughtsOverride&&this.exportIncludeThoughtsOverride}extractThoughtBlockquotesFromElement(e){const t=Array.from(e.querySelectorAll(Si)),n=[];return t.forEach(e=>{const t=this.extractThoughtMarkdown(e).trim();t&&n.push(this.formatAsThoughtBlockquote(t));}),n}extractThoughtMarkdown(e){const t=e.cloneNode(true);t.querySelectorAll('.author-label, .actions-container, button, [role="button"], svg, [aria-hidden="true"]').forEach(e=>e.remove()),this.normalizeAssistantExportDom(t);const n=Uo(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}normalizeAssistantExportDom(e){this.unwrapCmarkNodes(e),this.replaceInlineCodeSpans(e),this.replaceKatexComponents(e),this.replaceCodeBlockComponents(e);}unwrapCmarkNodes(e){Array.from(e.querySelectorAll("ms-cmark-node")).forEach(e=>{e instanceof HTMLElement&&e.parentNode&&e.replaceWith(...Array.from(e.childNodes));});}replaceInlineCodeSpans(e){e.querySelectorAll(".inline-code").forEach(e=>{if(!(e instanceof HTMLElement))return;if("code"===e.tagName.toLowerCase())return;const t=document.createElement("code");t.textContent=e.textContent||"",e.replaceWith(t);});}replaceKatexComponents(e){e.querySelectorAll("ms-katex").forEach(e=>{if(!(e instanceof HTMLElement))return;const t=e.querySelector('annotation[encoding="application/x-tex"]')?.textContent?.trim()||"";if(!t)return;const n=document.createElement(e.classList.contains("inline")?"span":"div");n.className=e.classList.contains("inline")?"math-inline":"math-block",n.setAttribute("data-math",t),e.replaceWith(n);});}replaceCodeBlockComponents(e){e.querySelectorAll("ms-code-block").forEach(e=>{if(!(e instanceof HTMLElement))return;const t=this.extractCodeBlockFromComponent(e);if(!t)return;const n=document.createElement("pre"),r=document.createElement("code");t.language&&(r.className=`language-${t.language}`),r.textContent=t.code,n.appendChild(r),e.replaceWith(n);});}extractCodeBlockFromComponent(e){const t=e.querySelector("pre code")||e.querySelector("pre"),n=t?.textContent?.replace(/\r\n/g,"\n").replace(/\n+$/,"")||"";if(!n.trim())return null;return {language:[e.getAttribute("data-test-language"),e.getAttribute("data-language"),e.querySelector(".mat-expansion-panel-header-title .ng-star-inserted:last-child")?.textContent].map(e=>e?.trim().toLowerCase()||"").find(e=>e&&"code"!==e)||"",code:n}}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}getLatestReplyText(){const e=this.exportIncludeThoughtsOverride;this.exportIncludeThoughtsOverride=false;const t=document.querySelectorAll(`${ki}, .model-prompt-container`);try{for(let e=t.length-1;e>=0;e-=1){const n=this.extractAssistantResponseText(t[e]).trim();if(n)return n}return null}finally{this.exportIncludeThoughtsOverride=e;}}isExportSnapshotElement(e){return e.hasAttribute(_i)}async collectExportMessageSnapshots(e){const t=this.buildExportSnapshotPositions(e),n=e.scrollTop;let r=[];try{for(const n of t){e.scrollTop=n,e.dispatchEvent(new Event("scroll",{bubbles:!0})),e.getBoundingClientRect(),await this.sleep(80);const t=this.readVisibleExportMessageSnapshots(e);r=this.mergeExportMessageBatch(r,t);}}finally{e.scrollTop=n,e.dispatchEvent(new Event("scroll",{bubbles:true}));}return this.repairLikelyTruncatedUserSnapshots(r,e)}buildExportSnapshotPositions(e){const t=Math.max(0,e.scrollHeight-e.clientHeight),n=e.scrollTop;if(t<=0)return [n];const r=Math.max(160,Math.floor(.75*e.clientHeight)),o=new Set([0,n,t]);for(let i=0;ie-t)}readVisibleExportMessageSnapshots(e){return Array.from(e.querySelectorAll(wi)).filter(e=>e instanceof HTMLElement&&!e.closest(`[${Ci}]`)).flatMap(t=>this.extractExportSnapshotsFromTurn(t,e))}extractExportSnapshotsFromTurn(e,t){const n=[],r=this.getTurnRenderOrder(e,t),o=this.getUserContainerForTurn(e);if(o){const t=this.normalizeExportMessageContent(this.extractUserQueryMarkdown(o));t&&n.push({role:Ai,turnKey:this.getExportTurnKey(e,"user",t),order:r,content:t});}const i=this.getAssistantFragmentsForTurn(e);if(i.length>0){let t="";i.forEach(e=>{const n=this.normalizeExportMessageContent(this.extractAssistantResponseText(e));t=this.mergeSnapshotContent(t,n);}),t&&n.push({role:Ti,turnKey:this.getExportTurnKey(e,"assistant",t),order:r+.5,content:t});}return n}getTurnRenderOrder(e,t){const n=e.getBoundingClientRect();if(t instanceof HTMLElement){const e=t.getBoundingClientRect();return t.scrollTop+(n.top-e.top)}return window.scrollY+n.top}getUserContainerForTurn(e){return Array.from(e.querySelectorAll(".chat-turn-container.user")).filter(t=>t instanceof HTMLElement&&t.closest(wi)===e)[0]||null}getAssistantFragmentsForTurn(e){return Array.from(e.querySelectorAll(xi)).filter(t=>{if(!(t instanceof HTMLElement))return false;if(t.closest(wi)!==e)return false;const n=t.parentElement?.closest(xi);return n?.closest(wi)!==e})}getExportTurnKey(e,t,n){const r=e.closest("ms-chat-turn")?.id?.replace(/^turn-/,"").trim();if(r)return `${t}:${r}`;return `${t}:content:${n.replace(/\s+/g," ").trim().slice(0,120)}`}mergeSnapshotContent(e,t){if(!t)return e;if(!e)return t;if(e===t||e.includes(t))return e;if(t.includes(e))return t;const n=this.normalizeSnapshotComparisonText(e),r=this.normalizeSnapshotComparisonText(t);if(n&&r){if(r.startsWith(n)&&t.length>=e.length)return t;if(n.startsWith(r)&&e.length>=t.length)return e}return `${e}\n\n${t}`.trim()}async repairLikelyTruncatedUserSnapshots(e,t){const n=e.filter(e=>this.isLikelyTruncatedUserSnapshot(e));if(0===n.length)return e;const r=e.map(e=>({...e})),o=t.scrollTop;try{for(const e of n){const n=Math.max(0,e.order-Math.max(120,.25*t.clientHeight)),o=e.order+Math.max(120,.25*t.clientHeight),i=[n,e.order,o].map(e=>Math.round(e));for(const a of i){t.scrollTop=a,t.dispatchEvent(new Event("scroll",{bubbles:!0})),t.getBoundingClientRect(),await this.sleep(120);const n=this.readVisibleExportMessageSnapshots(t).find(t=>t.turnKey===e.turnKey);if(!n)continue;const o=r.findIndex(t=>t.turnKey===e.turnKey);if(-1===o)break;if(r[o]={...r[o],order:Math.min(r[o].order,n.order),content:this.mergeSnapshotContent(r[o].content,n.content)},!this.isLikelyTruncatedUserSnapshot(r[o]))break}}}finally{t.scrollTop=o,t.dispatchEvent(new Event("scroll",{bubbles:true}));}return r}isLikelyTruncatedUserSnapshot(e){if(e.role!==Ai)return false;const t=e.content.trim();return /(?:\.{3}|…)$/.test(t)}normalizeSnapshotComparisonText(e){return e.replace(/\r\n/g,"\n").replace(/\u2026/g,"...").replace(/\.{3}\s*$/g,"").replace(/\s+/g," ").trim()}normalizeExportMessageContent(e){return e.replace(/\r\n/g,"\n").replace(/\u00a0/g," ").trim()}mergeExportMessageBatch(e,t){if(0===t.length)return e;if(0===e.length)return t.map(e=>({...e}));const n=e.map(e=>({...e}));let r=null;for(let o=0;ot.turnKey===e.turnKey);if(-1!==i){const t=n[i];n[i]={...t,order:Math.min(t.order,e.order),content:this.mergeSnapshotContent(t.content,e.content)},r=i;continue}const a=this.findNextKnownSnapshotIndex(n,t,o+1);let s=n.length;null!==r?(s=r+1,null!==a&&s>a&&(s=a)):null!==a&&(s=a),n.splice(s,0,{...e}),r=s;}return n}findNextKnownSnapshotIndex(e,t,n){for(let r=n;re.turnKey===n);if(-1!==o)return o}return null}mountExportSnapshot(e){this.clearExportSnapshot();const t=document.createElement("div");t.setAttribute(Ci,"1"),t.style.display="none",e.forEach(e=>{const n=document.createElement("div");n.setAttribute(Ei,"1");const r=document.createElement("div");r.setAttribute(_i,e.role),r.textContent=e.content,n.appendChild(r),t.appendChild(n);}),document.body.appendChild(t),this.exportSnapshotRoot=t,this.exportSnapshotActive=true;}clearExportSnapshot(){this.exportSnapshotActive=false;const e=this.exportSnapshotRoot;this.exportSnapshotRoot=null,e?.isConnected&&e.remove(),document.querySelectorAll(`[${Ci}]`).forEach(t=>{t!==e&&t.parentNode?.removeChild(t);});}getNewChatButtonSelectors(){return ['button[iconname="add"]','button[data-test-clear="outside"]','button .material-symbols-outlined[aria-hidden="true"]']} /** * 切换 AI Studio 主题 * AI Studio 使用 localStorage.aiStudioUserPreference.theme 存储主题 * 值域:light / dark / system * @param targetMode 目标主题模式 */ async toggleTheme(e){try{const t=localStorage.getItem("aiStudioUserPreference")||"{}",n=JSON.parse(t);n.theme=e,localStorage.setItem("aiStudioUserPreference",JSON.stringify(n));const r=document.body;"dark"===e?(r.classList.add("dark-theme"),r.classList.remove("light-theme")):(r.classList.remove("dark-theme"),r.classList.add("light-theme")),r.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"aiStudioUserPreference",newValue:JSON.stringify(n),storageArea:localStorage}));const o=document.querySelector("app-root, ms-app, body");return o&&o.dispatchEvent(new CustomEvent("themechange",{detail:{theme:e}})),!0}catch(t){return console.error("[AIStudioAdapter] toggleTheme error:",t),false}} /** * 将 Ophel 扩展配置应用到 AI Studio 的 localStorage * 在页面加载时调用,用于设置默认界面状态和模型 * @param settings Ophel 的 AI Studio 设置 */ applySettings(e){try{const t=localStorage.getItem("aiStudioUserPreference")||"{}",n=JSON.parse(t);let r=!1;if(void 0!==e.collapseNavbar){const t=!e.collapseNavbar;n.isNavbarExpanded!==t&&(n.isNavbarExpanded=t,r=!0);}if(void 0!==e.collapseTools){const t=!e.collapseTools;n.areToolsOpen!==t&&(n.areToolsOpen=t,r=!0);}if(void 0!==e.collapseAdvanced){const t=!e.collapseAdvanced;n.isAdvancedOpen!==t&&(n.isAdvancedOpen=t,r=!0);}if(void 0!==e.enableSearch&&n.enableSearchAsATool!==e.enableSearch&&(n.enableSearchAsATool=e.enableSearch,r=!0),e.defaultModel&&""!==e.defaultModel.trim()){const t=e.defaultModel.trim();n.promptModel!==t&&(n.promptModel=t,n._promptModelOverride=t,r=!0);}r&&(localStorage.setItem("aiStudioUserPreference",JSON.stringify(n)),window.dispatchEvent(new StorageEvent("storage",{key:"aiStudioUserPreference",newValue:JSON.stringify(n),storageArea:localStorage})));}catch(t){console.error("[AIStudioAdapter] applySettings error:",t);}}},new class extends ci{activeOrganizationId=null;activeOrganizationIdExpiresAt=0;match(){return window.location.hostname.includes("claude.ai")||window.location.hostname.includes("claude.com")}getSiteId(){return Mr}getName(){return "Claude"}getThemeColors(){return {primary:"#d97757",secondary:"#c66045"}}getNativeThemeCss(){return "\n.bg-bg-100 {\n --tw-bg-opacity: 1;\n background-color: color-mix(in srgb, var(--gh-primary) 2%, var(--gh-bg)) !important\n}\n"}getNewTabUrl(){return "https://claude.ai/new"}isNewConversation(){return "/new"===window.location.pathname||"/"===window.location.pathname}isSharePage(){return window.location.pathname.startsWith("/public/")}getConversationList(){const e=document.querySelectorAll('a[data-dd-action-name="sidebar-chat-item"]');return Array.from(e).map(e=>{const t=e.getAttribute("href")||"",n=t.match(/\/chat\/([a-f0-9-]+)/),r=n?n[1]:"",o=e.querySelector("span.truncate"),i=o?.textContent?.trim()||"",a=window.location.href.includes(r);let s=false;const l=e.closest("div.flex.flex-col");if(l){const e=l.querySelector("h3"),t=e&&!e.hasAttribute("role"),n=l.querySelector("ul"),r=n?.classList.contains("-mx-1.5");s=t||r;}return {id:r,title:i,url:t.startsWith("http")?t:`https://claude.ai${t}`,isActive:a,isPinned:s}}).filter(e=>e.id)}getSidebarScrollContainer(){const e=document.querySelector("nav");if(e){return e.querySelector("div.overflow-y-auto")||e}return null}async deleteConversationOnSite(e){return this.deleteConversationOnSiteInternal(e)}async deleteConversationsOnSite(e){const t=[];for(let n=0;nt+5e3)return this.activeOrganizationId;if(this.isUserscriptRuntime()){const e=await this.fetchOrganizationIdFromApi();if(e)return this.activeOrganizationId=e,this.activeOrganizationIdExpiresAt=t+6e5,e;const n=this.getOrganizationIdFromStorage();if(n)return this.activeOrganizationId=n,this.activeOrganizationIdExpiresAt=t+6e5,n;const r=this.getCookieValue("lastActiveOrg");return this.isValidOrganizationId(r)?(this.activeOrganizationId=r,this.activeOrganizationIdExpiresAt=t+6e5,r):null}const n=this.getCookieValue("lastActiveOrg");if(this.isValidOrganizationId(n))return this.activeOrganizationId=n,this.activeOrganizationIdExpiresAt=t+6e5,n;const r=this.getOrganizationIdFromStorage();if(r)return this.activeOrganizationId=r,this.activeOrganizationIdExpiresAt=t+6e5,r;const o=await this.fetchOrganizationIdFromApi();return o?(this.activeOrganizationId=o,this.activeOrganizationIdExpiresAt=t+6e5,o):null}isUserscriptRuntime(){return true}async fetchOrganizationIdFromApi(){try{const e=await fetch("/api/organizations",{method:"GET",headers:{accept:"application/json, text/plain, */*"},credentials:"include"});if(!e.ok)return null;const t=await e.json();return this.extractOrganizationId(t)}catch{return null}}getOrganizationIdFromStorage(){const e=["lastActiveOrg","activeOrg","organizationId","lastActiveOrganization","LSS-lastActiveOrg"];for(const t of e){const e=localStorage.getItem(t),n=this.extractOrganizationId(e);if(n)return n}for(let t=0;t0?t:null}getCookieValue(e){const t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));if(!n)return null;try{return decodeURIComponent(n[1])}catch{return n[1]}}syncSidebarAfterRemoteDelete(e){const t=this.findConversationRow(e);if(!t)return;(t.closest("li")||t).remove();}async deleteConversationViaUi(e){const t=await this.findConversationRowWithRetry(e);if(!t)return false;const n=await this.findConversationMenuButton(t);if(!n)return false;this.simulateClick(n);const r=await this.waitForDeleteMenuItem(n);if(!r)return false;if(this.simulateClick(r),await this.waitForConversationRemoved(e,1e3))return true;const o=await this.waitForDeleteConfirmButton();return o&&this.simulateClick(o),this.waitForConversationRemoved(e,5e3)}async isConversationStillVisible(e){return !!(await this.findConversationRowWithRetry(e))}async findConversationRowWithRetry(e){const t=this.findConversationRow(e);return t||(await this.loadAllConversations(),await this.sleep(200),this.findConversationRow(e))}findConversationRow(e){return document.querySelector(`a[data-dd-action-name="sidebar-chat-item"][href="/chat/${e}"], a[data-dd-action-name="sidebar-chat-item"][href$="/chat/${e}"], a[data-dd-action-name="sidebar-chat-item"][href*="/chat/${e}?"]`)}async findConversationMenuButton(e){const t=e.closest("li")||e.parentElement||e,n=['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(", ");for(let r=0;r<10;r++){t.dispatchEvent(new MouseEvent("mouseenter",{bubbles:true})),t.dispatchEvent(new MouseEvent("mousemove",{bubbles:true})),e.dispatchEvent(new MouseEvent("mouseenter",{bubbles:true})),e.dispatchEvent(new MouseEvent("mousemove",{bubbles:true}));const r=Array.from(t.querySelectorAll(n)).filter(e=>this.isVisible(e));if(r.length>0){const e=this.pickRightMostElement(r);if(e)return e}const o=Array.from(t.querySelectorAll("button")).filter(e=>this.isVisible(e));if(o.length>0){const e=this.pickRightMostElement(o);if(e)return e}await this.sleep(80);}return null}getMenuScopeFromTrigger(e){const t=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(t){const e=document.getElementById(t);if(e)return e}const n=Array.from(document.querySelectorAll('[role="menu"], [data-radix-menu-content], [data-state="open"]')).filter(e=>this.isVisible(e));return 0===n.length?null:this.pickNearestElement(e,n)}async waitForDeleteMenuItem(e,t=2500){const n=Date.now();for(;Date.now()-nthis.isVisible(e))||null}async waitForConversationRemoved(e,t=3500){const n=Date.now();for(;Date.now()-nt.getBoundingClientRect().right-e.getBoundingClientRect().right)[0]}pickNearestElement(e,t){if(0===t.length)return null;const n=e.getBoundingClientRect(),r=n.left+n.width/2,o=n.top+n.height/2;let i=null,a=Number.POSITIVE_INFINITY;for(const s of t){const e=s.getBoundingClientRect(),t=e.left+e.width/2,n=e.top+e.height/2,l=Math.hypot(t-r,n-o);ln.includes(e.toLowerCase()))}isVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}getTextareaSelectors(){return ['[contenteditable="true"]',".ProseMirror",'div[role="textbox"]']}getSubmitButtonSelectors(){return ['button[aria-label="Send Message"]','button[data-testid="send-button"]','button[aria-label="Send"]']}isValidTextarea(e){if(null===e.offsetParent)return false;if(e.closest(".gh-main-panel"))return false;const t="true"===e.getAttribute("contenteditable"),n=e.classList.contains("ProseMirror"),r="textbox"===e.getAttribute("role");return t||n||r}insertPrompt(e){const t=this.getTextareaElement();if(!t)return false;t.focus();try{if(document.execCommand("selectAll",!1,void 0),!document.execCommand("insertText",!1,e))throw new Error("execCommand failed")}catch{t.textContent=e,t.dispatchEvent(new Event("input",{bubbles:true}));}return true}clearTextarea(){const e=this.getTextareaElement();if(e){e.focus();try{document.execCommand("selectAll",!1,void 0),document.execCommand("delete",!1,void 0);}catch{e.textContent="";}e.dispatchEvent(new Event("input",{bubbles:true}));}}getConversationTitle(){const e=this.getSessionId();if(e&&"default"!==e){const t=document.querySelector(`a[href*="${e}"]`);if(t)return t.querySelector("span.truncate")?.textContent?.trim()||null}return null}findClaudeScrollContainer(){const e=e=>{if(!e)return false;const t=window.getComputedStyle(e).overflowY;return !("auto"!==t&&"scroll"!==t&&"overlay"!==t&&"true"!==e.getAttribute("data-autoscroll-container"))&&e.scrollHeight>e.clientHeight+4};let t=document.querySelector('.font-claude-response, [data-testid="user-message"]');for(;t&&t!==document.body;){if(e(t))return t;t=t.parentElement;}const n=['[data-autoscroll-container="true"]',"#main-content .overflow-y-scroll","#root .overflow-y-auto.overflow-x-hidden"];for(const r of n){const t=document.querySelector(r);if(e(t))return t}return null}getScrollContainer(){const e=this.findClaudeScrollContainer(),t=document.scrollingElement,n=e?e.scrollHeight-e.clientHeight:-1,r=t?t.scrollHeight-t.clientHeight:-1;return e&&t&&r>n+100&&t.scrollHeight>t.clientHeight+4?t:e||(t&&t.scrollHeight>t.clientHeight+4?t:super.getScrollContainer())}getChatContentSelectors(){return ['div[data-testid="user-message"]',"div.font-claude-response"]}getModelName(){const e=document.querySelector('button[data-testid="model-selector-dropdown"]');return e&&e.textContent?e.textContent.trim():null}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:['button[data-testid="model-selector-dropdown"]'],menuItemSelector:'div[role="menuitem"]',checkInterval:1e3,maxAttempts:20,subMenuSelector:'[aria-haspopup="menu"]',subMenuTriggers:["more models","更多模型"]}}simulateClick(e){const t=["pointerdown","mousedown","pointerup","mouseup","click"];for(const n of t)e.dispatchEvent(new PointerEvent(n,{bubbles:true,cancelable:true,view:window,pointerId:1}));}getNewChatButtonSelectors(){return ['a[data-dd-action-name="sidebar-new-item"]','a[href="/new"]']}getDefaultLockSettings(){return {enabled:false,keyword:"sonnet"}}getClaudeChatCandidates(e){return Array.from(e.querySelectorAll(this.getChatContentSelectors().join(", ")))}getRelativeTop(e,t){const n=e.getBoundingClientRect();return t.getBoundingClientRect().top-n.top+e.scrollTop}getOutlineRoot(){return this.getScrollContainer()||this.findClaudeScrollContainer()||document}getVisibleAnchorElement(){const e=this.getScrollContainer();if(!e)return null;const t=this.getClaudeChatCandidates(e);if(!t.length)return null;const n=e.scrollTop;let r=null,o=Number.NEGATIVE_INFINITY;t.forEach(t=>{const i=this.getRelativeTop(e,t);i<=n+100&&i>o&&(r=t,o=i);}),r||(r=t[0],o=this.getRelativeTop(e,r));const i=n-o,a=r.getAttribute("data-message-id")||r.id;if(a){let e=`[data-message-id="${a}"]`;return r.matches(e)||(e=`#${a}`),{type:"selector",selector:e,offset:i}}const s=t.indexOf(r);if(-1===s)return null;return {type:"index",index:s,offset:i,textSignature:(r.textContent||"").trim().substring(0,50)}}restoreScroll(e){const t=this.getScrollContainer();if(!t||!e)return false;let n=null;if("selector"===e.type&&e.selector)n=t.querySelector(e.selector);else if("index"===e.type&&"number"==typeof e.index){const r=this.getClaudeChatCandidates(t);if(r[e.index]){if(n=r[e.index],e.textSignature){(n.textContent||"").trim().substring(0,50)!==e.textSignature&&(n=r.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature)||n);}}else e.textSignature&&(n=r.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature)||null);}if(!n)return false;const r=this.getRelativeTop(t,n)+(e.offset||0);return t.scrollTo({top:r,behavior:"instant"}),true}extractOutline(e=6,t=false,n=false){const r=[],o=this.getOutlineRoot(),i=e=>e.replace(/[\s\S]*?<\/thinking>/gi,"").trim(),a=this.getUserQuerySelector(),s=Array.from(o.querySelectorAll("h1, h2, h3, h4, h5, h6"));if(s.forEach((t,o)=>{const i=parseInt(t.tagName[1]);if(i>e)return;if(t.classList.contains("pointer-events-none"))return;const a=t.textContent?.trim()||"";if(!a)return;const l={level:i,text:a.length>200?a.slice(0,200):a,element:t,isUserQuery:false,isTruncated:a.length>80};if(n){let e=null;for(let t=o+1;t{const t=e.textContent?.trim()||"";if(!t)return;const s={level:0,text:t.length>200?t.slice(0,200):t,element:e,isUserQuery:true,isTruncated:t.length>60};n&&(s.wordCount=(e=>{const t=Array.from(o.querySelectorAll(a)),n=Array.from(o.querySelectorAll(".font-claude-response")),r=t.indexOf(e);if(-1===r)return 0;const s=t[r+1];let l=0;for(const o of n){if(!(e.compareDocumentPosition(o)&Node.DOCUMENT_POSITION_FOLLOWING))continue;if(s&&s.compareDocumentPosition(o)&Node.DOCUMENT_POSITION_FOLLOWING)continue;const t=o.querySelector(".standard-markdown, .progressive-markdown");if(t){const e=t.textContent?.trim()||"";l+=i(e).length;}}return l})(e)),r.push(s);}),r.sort((e,t)=>{if(!e.element||!t.element)return 0;return e.element.compareDocumentPosition(t.element)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1});}return r}isGenerating(){if(document.querySelector('button[aria-label="Stop response"]'))return true;return !!document.querySelector('[class*="streaming"], [class*="typing"]')}getStopButtonSelectors(){return ['button[aria-label="Stop response"]']}getNetworkMonitorConfig(){return {urlPatterns:["/api/","/completion"],silenceThreshold:500}}getExportConfig(){return {userQuerySelector:'[data-testid="user-message"]',assistantResponseSelector:".font-claude-response",turnSelector:null,useShadowDOM:false}}getAssistantMermaidSupportMode(){return "native"}getLatestReplyText(){const e=document.querySelectorAll(".font-claude-response");if(0===e.length)return null;const t=e[e.length-1],n=t.querySelector(".standard-markdown, .progressive-markdown");if(n){return Uo(n).trim()||n.textContent?.trim()||null}return t.textContent?.trim()||null}getResponseContainerSelector(){return ".font-claude-response"}getUserQuerySelector(){return '[data-testid="user-message"]'}extractUserQueryText(e){return e.textContent?.trim()||""}extractUserQueryMarkdown(e){const t=e.querySelectorAll("p.whitespace-pre-wrap");if(0===t.length)return "";const n=[];return t.forEach(e=>{const t=e.textContent||"";Ld(t)&&n.push(t);}),0===n.length?"":"# CLAUDE_INCREMENTAL\nplaceholder"}replaceUserQueryContent(e,t){if(e.querySelector(".gh-claude-enhanced"))return false;const n=e.querySelectorAll("p.whitespace-pre-wrap");if(0===n.length)return false;let r=false;return n.forEach(e=>{const t=e.textContent||"";if(!Ld(t))return;const n=wd(t,false,{enableMath:true}),o=document.createElement("div");o.className="gh-claude-enhanced gh-user-query-markdown gh-markdown-preview whitespace-pre-wrap break-words",o.innerHTML=n,e.replaceWith(o),r=true;}),r}extractAssistantResponseText(e){let t="";const n=e.querySelectorAll(".artifact-block-cell");n.length>0&&n.forEach(n=>{const r=n.querySelector(".line-clamp-1"),o=r?.textContent?.trim()||"Untitled",i=n.querySelector(".text-text-400"),a=i?.textContent?.trim(),s=e.querySelector('a[download][href^="blob:"]'),l=s?.getAttribute("href");t+=l?`\n[Artifact: ${o}${a?` - ${a}`:""} | Download: ${l}]\n\n`:`\n[Artifact: ${o}${a?` - ${a}`:""}]\n\n`;});const r=e.querySelector(".standard-markdown, .progressive-markdown");if(r){const e=Uo(r);t+=e||r.textContent?.trim()||"";}return t.trim()}getConversationObserverConfig(){return {selector:'a[data-dd-action-name="sidebar-chat-item"]',shadow:false,extractInfo:e=>{const t=e.getAttribute("href")||"",n=t.match(/\/chat\/([a-f0-9-]+)/),r=n?n[1]:"";if(!r)return null;const o=e.querySelector("span.truncate"),i=o?.textContent?.trim()||"";let a=false;const s=e.closest("div.flex.flex-col");if(s){const e=s.querySelector("h3"),t=e&&!e.hasAttribute("role"),n=s.querySelector("ul"),r=n?.classList.contains("-mx-1.5");a=t||r;}return {id:r,title:i,url:`https://claude.ai${t}`,isActive:window.location.href.includes(r),isPinned:a}},getTitleElement:e=>e.querySelector("span.truncate")}}navigateToConversation(e,t){const n=t||`https://claude.ai/chat/${e}`,r=document.querySelector(`a[href*="${e}"]`);return r?(r.click(),true):(window.location.href=n,true)}getSessionName(){return this.getConversationTitle()}getWidthSelectors(){return [{selector:"#main-content .max-w-3xl",property:"max-width"},{selector:"#main-content .max-w-4xl",property:"max-width"}]}getZenModeSelectors(){return [{selector:'[data-disclaimer="true"]',action:"hide"}]}getUserQueryWidthSelectors(){return [{selector:'[data-testid="user-message"]',property:"max-width"}]}async toggleTheme(e){try{const t={value:e,tabId:crypto.randomUUID(),timestamp:Date.now()};return localStorage.setItem("LSS-userThemeMode",JSON.stringify(t)),window.dispatchEvent(new StorageEvent("storage",{key:"LSS-userThemeMode",newValue:JSON.stringify(t)})),await new Promise(e=>setTimeout(e,300)),!0}catch(t){return console.error("[ClaudeAdapter] toggleTheme error:",t),false}}},new class extends ci{nativeOutlineCache=null;exportSnapshotRoot=null;exportSnapshotActive=false;exportIncludeThoughtsOverride=null;match(){const e="chat.deepseek.com"===window.location.hostname;return e&&this.consumePendingDeleteRefresh(),e}getSiteId(){return Or}getName(){return "DeepSeek"}getThemeColors(){return {primary:"#4b6bfe",secondary:"#3a5ae0"}}getNativeThemeCss(){return "\n/* =============================================\n * DeepSeek 站点原生主题适配器 (DeepSeek Theme Adapter)\n * ============================================= */\nbody, page, .ds-theme {\n /* 核心页面背景层 - 覆盖基础背景 */\n --dsw-alias-bg-base: color-mix(in srgb, var(--gh-primary) 2%, var(--gh-bg)) !important;\n\n --dsr-side-hover-bg: var(--gh-hover) !important;\n\n --dsw-alias-markdown-inline-code: var(--gh-bg-tertiary) !important;\n --dsw-alias-markdown-code-block-banner: var(--gh-bg-tertiary) !important;\n --dsw-alias-markdown-code-block: var(--gh-bg-secondary) !important;\n}\n\n/* 侧边栏背景 */\n.b8812f16, .f3d18f6a {\n background-color: var(--dsw-alias-bg-base) !important;\n}\n"}getTextareaSelectors(){return ['textarea[placeholder*="DeepSeek"]','textarea[placeholder*="deepseek"]',"textarea.ds-scroll-area","form textarea"]}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus();const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),t.setSelectionRange(e.length,e.length),true}clearTextarea(){const e=this.getTextareaElement();if(!e||!e.isConnected)return;const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),e.dispatchEvent(new Event("change",{bubbles:true})),e.setSelectionRange(0,0);}getSessionId(){const e=window.location.pathname,t=e.match(Dd);if(t?.[1])return t[1];const n=e.match(Rd);return n?.[1]||""}isNewConversation(){const e=window.location.pathname;return !this.isSharePage()&&("/"===e||"/a/chat"===e||"/a/chat/"===e||!Dd.test(e))}getNewTabUrl(){return "https://chat.deepseek.com/"}getSessionName(){const e=this.getConversationTitle();if(e)return e;const t=document.title.trim();return t&&"DeepSeek"!==t&&t.replace(/\s*[-|]\s*DeepSeek$/i,"").trim()||null}getCurrentCid(){try{for(let e=0;e{const r=this.extractConversationInfo(t,e);r&&n.set(r.id,r);}),Array.from(n.values())}getConversationObserverConfig(){return {selector:Pd,shadow:false,extractInfo:e=>this.extractConversationInfo(e,this.getCurrentCid()||void 0),getTitleElement:e=>this.findTitleElement(e)}}async deleteConversationOnSite(e){const t=this.getSessionId(),n=this.getUserToken();if(!n)return {id:e.id,success:false,method:"api",reason:Jd};const r=await this.deleteConversationViaApi(e,n);return r.success&&(e.id===t?this.scheduleHomeRefreshAfterDelete():this.schedulePageReloadAfterDelete()),r}async deleteConversationsOnSite(e){if(0===e.length)return [];const t=this.getSessionId(),n=this.getUserToken();if(!n)return e.map(e=>({id:e.id,success:false,method:"api",reason:Jd}));const r=[];let o=false,i=false;for(const a of e){const e=await this.deleteConversationViaApi(a,n);r.push(e),e.success&&(i=true,a.id===t&&(o=true));}return i&&(o?this.scheduleHomeRefreshAfterDelete():this.schedulePageReloadAfterDelete()),r}getConversationTitle(){if(this.isSharePage())return this.getShareConversationTitle();const e=this.getSessionId(),t=(e?document.querySelector(`${Pd}[href*="/a/chat/s/${e}"]`):null)||document.querySelector(`${Pd}[aria-current="page"]`);return t?this.extractConversationTitle(t):null}navigateToConversation(e,t){const n=document.querySelector(`${Pd}[href*="/a/chat/s/${e}"]`);return n?(n.click(),true):super.navigateToConversation(e,t||`https://chat.deepseek.com/a/chat/s/${e}`)}getSidebarScrollContainer(){const e=document.querySelector(Pd);return e?.closest(".ds-scroll-area")||null}getScrollContainer(){const e=Array.from(document.querySelectorAll(Bd)).filter(e=>!e.parentElement?.closest(Bd)),t=this.pickBestScrollableAncestor(e);if(t)return t;const n=Array.from(document.querySelectorAll(`${Od}, ${zd}`)).filter(e=>!e.closest(".gh-root, .gh-table-container"));return this.pickBestScrollableAncestor(n)}getResponseContainerSelector(){return 'main .ds-scroll-area:has(.ds-message), [role="main"] .ds-scroll-area:has(.ds-message), .ds-scroll-area:has(.ds-message)'}getUserQuerySelector(){return zd}getChatContentSelectors(){return [Od,zd]}extractUserQueryText(e){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";const t=(this.findUserContentRoot(e)||e).cloneNode(true);return t.querySelectorAll(".gh-user-query-markdown, button, [role=button], svg, .ds-icon-button, [aria-hidden=true]").forEach(e=>e.remove()),this.extractTextWithLineBreaks(t).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}replaceUserQueryContent(e,t){const n=this.findUserContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e);}if(n===e){const t=document.createElement("div");for(t.className="gh-user-query-raw";e.firstChild;)t.appendChild(e.firstChild);return t.style.display="none",e.appendChild(t),e.appendChild(r),true}return n.style.display="none",n.after(r),true}extractAssistantResponseText(e){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";const t=this.shouldIncludeThoughtsInExport(),n=this.resolveAssistantMessageElement(e),r=this.resolveAssistantBodyMarkdownElement(e),o=t&&n?this.extractThoughtBlockquotesFromMessage(n):[],i=r?this.extractMarkdownText(r):"";return t&&o.length>0?i?`${o.join("\n\n")}\n\n${i}`:o.join("\n\n"):i}extractOutline(e=6,t=false,n=false){const r=this.getScrollContainer()||document.querySelector(this.getResponseContainerSelector());if(!r)return [];const o=[],i=[],a=Array.from(r.querySelectorAll(Bd)).filter(e=>!e.parentElement?.closest(Bd));if(a.forEach((r,s)=>{const l=this.getAssistantBodyMarkdown(r);if(!l){if(!t)return;const e=this.extractUserQueryMarkdown(r);if(!e)return;let l;n&&(l=this.findNextAssistantMarkdown(a,s)?.textContent?.trim().length||0);const c=this.createUserQueryOutlineItem(e,r,l);return i.push(c),void o.push(c)}const c=Array.from(l.querySelectorAll("h1, h2, h3, h4, h5, h6"));c.forEach((t,r)=>{const i=Number.parseInt(t.tagName.slice(1),10);if(Number.isNaN(i)||i>e)return;const a=t.textContent?.trim()||"";if(!a)return;let s;if(n){let e=null;for(let t=r+1;t80;return {level:0,text:o?`${r.slice(0,80)}...`:r,element:t,isUserQuery:true,isTruncated:o,wordCount:n}}getExportConfig(){return this.exportSnapshotActive?{userQuerySelector:Qd,assistantResponseSelector:Kd,turnSelector:null,useShadowDOM:false}:{userQuerySelector:zd,assistantResponseSelector:Od,turnSelector:null,useShadowDOM:false}}async prepareConversationExport(e){this.exportIncludeThoughtsOverride=e.includeThoughts,this.clearExportSnapshot();const t=this.getScrollContainer()||document.querySelector(this.getResponseContainerSelector());if(!(t instanceof HTMLElement))return null;const n=await this.collectExportMessageSnapshots(t);return 0===n.length?null:(this.mountExportSnapshot(n),{count:n.length})}async restoreConversationAfterExport(e,t){this.clearExportSnapshot(),this.exportIncludeThoughtsOverride=null;}getLatestReplyText(){const e=this.exportIncludeThoughtsOverride;this.exportIncludeThoughtsOverride=false;const t=this.getScrollContainer()||document.querySelector(this.getResponseContainerSelector());try{if(t instanceof HTMLElement){const e=t.scrollTop,n=Math.max(0,t.scrollHeight-t.clientHeight);try{t.scrollTop=n,t.dispatchEvent(new Event("scroll",{bubbles:!0})),t.getBoundingClientRect();const e=this.extractLatestReplyTextFromMessages(this.getVisibleAssistantMessages(t));if(e)return e}finally{t.scrollTop=e,t.dispatchEvent(new Event("scroll",{bubbles:!0}));}}return this.extractLatestReplyTextFromMessages(this.getVisibleAssistantMessages(document))}finally{this.exportIncludeThoughtsOverride=e;}}getLastCodeBlockText(){const e=this.exportIncludeThoughtsOverride;this.exportIncludeThoughtsOverride=false;const t=this.getScrollContainer()||document.querySelector(this.getResponseContainerSelector());try{if(t instanceof HTMLElement){const e=this.buildBottomUpScanPositions(t),n=t.scrollTop;try{for(const n of e){t.scrollTop=n,t.dispatchEvent(new Event("scroll",{bubbles:!0})),t.getBoundingClientRect();const e=this.extractLastCodeBlockTextFromMessages(this.getVisibleAssistantMessages(t));if(e)return e}}finally{t.scrollTop=n,t.dispatchEvent(new Event("scroll",{bubbles:!0}));}}return this.extractLastCodeBlockTextFromMessages(this.getVisibleAssistantMessages(document))}finally{this.exportIncludeThoughtsOverride=e;}}getSubmitButtonSelectors(){return [`div[role="button"].ds-icon-button:has(svg path[d="${Yd}"])`,`button.ds-icon-button:has(svg path[d="${Yd}"])`]}findSubmitButton(e){const t=this.getSubmitButtonSelectors().join(", ");if(!t)return null;const n=[e?.closest("form"),e?.parentElement,e?.closest("div"),document.body].filter(Boolean),r=new Set;for(const o of n){const e=o.querySelectorAll(t);for(const t of Array.from(e)){const e=t;if(!r.has(e)&&null!==e.offsetParent)return r.add(e),e}}return null}getNewChatButtonSelectors(){return ['a[href="/a/chat"]','a[href="/a/chat/"]']}getWidthSelectors(){return [{selector:":root",property:"--message-list-max-width",noCenter:true},{selector:".ds-virtual-list-items, .ds-virtual-list-visible-items",property:"--message-list-max-width",extraCss:"padding-left: max(0px, calc((100% - var(--message-list-max-width)) / 2)) !important; padding-right: max(0px, calc((100% - var(--message-list-max-width)) / 2)) !important;",noCenter:true}]}getUserQueryWidthSelectors(){return [{selector:jd,property:"max-width",noCenter:true}]}isGenerating(){const e=this.findComposerButtons();for(const t of e){const e=t.querySelector("svg path");if((e?.getAttribute("d")||"").startsWith(Zd))return true}return false}getStopButtonSelectors(){return [`div[role="button"].ds-icon-button:has(svg path[d^="${Zd}"])`,`button.ds-icon-button:has(svg path[d^="${Zd}"])`]}getModelName(){const e=Array.from(document.querySelectorAll(".ds-toggle-button--selected")).map(e=>e.innerText?.trim()||e.textContent?.trim()||"").filter(Boolean);return 0===e.length?"DeepSeek":`DeepSeek (${e.join(", ")})`}getNetworkMonitorConfig(){return {urlPatterns:["/api/v0/chat/completion"],silenceThreshold:500}}async toggleTheme(e){try{const t=JSON.stringify({value:e,__version:"0"});localStorage.setItem(qd,t);const n=document.body;return n&&(n.classList.remove("light","dark"),n.classList.add("change-theme",e),"dark"===e?n.setAttribute("data-ds-dark-theme","dark"):n.removeAttribute("data-ds-dark-theme"),n.style.colorScheme=e,window.setTimeout(()=>{document.body===n&&n.classList.remove("change-theme");},300)),window.dispatchEvent(new StorageEvent("storage",{key:qd,newValue:t,storageArea:localStorage})),!0}catch(t){return console.error("[DeepSeekAdapter] toggleTheme error:",t),false}}findComposerButtons(){const e=this.getTextareaElement(),t=[e?.closest("form"),e?.parentElement,e?.closest("div"),document.body].filter(Boolean),n=new Set,r=[];for(const o of t){const e=o.querySelectorAll('div[role="button"].ds-icon-button, button.ds-icon-button, .ds-icon-button[aria-disabled="false"]');for(const t of Array.from(e)){const e=t;null===e.offsetParent||n.has(e)||(n.add(e),r.push(e));}if(r.length>0)return r}return r}pickBestScrollableAncestor(e){const t=new Map;for(const o of e){const e=this.findScrollableAncestor(o);if(!e)continue;const n=t.get(e)||0;t.set(e,n+this.scoreScrollContainer(e));}let n=null,r=-1;for(const[o,i]of t.entries())i>r&&(n=o,r=i);return r>0?n:null}findScrollableAncestor(e){let t=e instanceof HTMLElement?e:e?.parentElement||null;for(;t&&t!==document.body;){if(this.isPrimaryScrollContainer(t))return t;t=t.parentElement;}return null}isPrimaryScrollContainer(e){if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("auto"!==t.overflowY&&"scroll"!==t.overflowY)return false;if(e.scrollHeight<=e.clientHeight)return false;if(e.clientHeight<220)return false;const n=e.getBoundingClientRect();return !(n.width<320||n.height<220)}scoreScrollContainer(e){const t=window.innerHeight||document.documentElement.clientHeight||0,n=window.innerWidth||document.documentElement.clientWidth||0,r=e.getBoundingClientRect(),o=e.querySelectorAll(Bd).length,i=e.querySelectorAll(zd).length,a=e.querySelectorAll(Od).length;let s=0;return s+=200*Math.min(o,80),s+=120*Math.min(i,40),s+=120*Math.min(a,40),e.scrollTop>0&&(s+=800),r.height>=.35*t&&(s+=500),r.width>=.45*n&&(s+=350),(e.matches("main, [role='main']")||e.closest("main, [role='main']"))&&(s+=250),e.querySelector("textarea")&&(s-=700),e.querySelector(".gh-table-container")&&(s-=250),s}extractNativeUserQueries(e){const t=this.collectNativeOutlineEntries();if(0===t.length)return [];const n=[],r=new Map;let o=0;return t.forEach(t=>{const i=this.findMatchingUserQueryIndex(e,t.text,o),a=i>=0?e[i]:null;i>=0&&(o=i+1);const s=this.createUserQueryOutlineItem(t.text,a?.element||null);s.wordCount=a?.wordCount;const l=this.normalizeUserQueryMatchText(t.text),c=r.get(l)||0;r.set(l,c+1),s.id=a?.id||`deepseek-user-query::${c}::${this.normalizeUserQueryMatchText(t.text)}`,n.push(s);}),n}mergeOutlineWithNativeUserQueries(e,t){if(!e.some(e=>e.isUserQuery))return [...t,...e];const n=[],r=[];let o=null,i=0;e.forEach(e=>{if(!e.isUserQuery)return void(o?o.assistantItems.push(e):n.push(e));const a=this.findMatchingNativeUserQueryIndex(t,e,i);a>=0?(o={type:"matched",nativeIndex:a,assistantItems:[]},i=a+1):o={type:"unmatched",userItem:e,assistantItems:[]},r.push(o);});const a=r.find(e=>"matched"===e.type);if(!a)return [...t,...e];const s=[];let l=0;if(n.length>0){const e=Math.max(a.nativeIndex-1,0);for(;l<=e&&l{if("matched"!==e.type)s.push(e.userItem,...e.assistantItems);else {for(;l<=e.nativeIndex&&l({...e})):[];const n=this.findNativeOutlineScrollContainer(t),r=this.getNativeOutlineSnapshot(e,t,n);if(this.nativeOutlineCache&&this.nativeOutlineCache.sessionId===e&&this.nativeOutlineCache.snapshot===r)return this.nativeOutlineCache.items.map(e=>({...e}));const o=this.scanNativeOutlineEntries(t,n);return o.length>0&&(this.nativeOutlineCache={sessionId:e,snapshot:r,items:o.map(e=>({...e}))}),o}findNativeOutlineList(){const e=Array.from(document.querySelectorAll(".ds-virtual-list")).filter(e=>e instanceof HTMLElement&&e.querySelector(".ds-virtual-list-items, .ds-virtual-list-visible-items")&&!e.querySelector(Pd)&&!e.closest("aside, nav"));let t=null,n=-1;return e.forEach(e=>{const r=e.getBoundingClientRect();let o=0;e.closest('[style*="--scroll-nav-page-padding"]')&&(o+=2500),e.closest("main, [role='main']")&&(o+=600),e.querySelector(".ds-virtual-list-visible-items")&&(o+=400),r.width>=140&&r.width<=420&&(o+=350),r.height>=120&&(o+=250),e.scrollHeight>e.clientHeight+20&&(o+=300),e.querySelector(Bd)&&(o-=1500),o>n&&(t=e,n=o);}),n>0?t:null}findNativeOutlineScrollContainer(e){const t=[e,e.closest(".ds-scroll-area"),e.parentElement,e.closest('[style*="--scroll-nav-page-padding"]')?.querySelector(".ds-scroll-area")].filter(e=>e instanceof HTMLElement);let n=null,r=-1;return t.forEach(t=>{const o=window.getComputedStyle(t);if(!(t.scrollHeight>t.clientHeight+8||"auto"===o.overflowY||"scroll"===o.overflowY||t.classList.contains("ds-virtual-list")||t.classList.contains("ds-scroll-area"))||t.clientHeight<=0)return;let i=0;t===e&&(i+=500),t.classList.contains("ds-virtual-list")&&(i+=350),t.classList.contains("ds-scroll-area")&&(i+=250),i+=Math.min(t.scrollHeight-t.clientHeight,2e3),i>r&&(n=t,r=i);}),r>0?n:null}getNativeOutlineSnapshot(e,t,n){const r=t.querySelector(".ds-virtual-list-items"),o=t.querySelector(".ds-virtual-list-visible-items"),i=n||t;return [e,i.scrollHeight,i.clientHeight,r?.scrollHeight||0,o?.childElementCount||0].join("::")}scanNativeOutlineEntries(e,t){const n=this.readVisibleNativeOutlineEntries(e);if(!t)return n;const r=Math.max(0,t.scrollHeight-t.clientHeight);if(r<=0)return n;const o=t.scrollTop,i=Math.max(48,Math.floor(.6*t.clientHeight)),a=new Set([0,r,o]);for(let l=0;le-t).forEach(n=>{t.scrollTop=n,t.dispatchEvent(new Event("scroll",{bubbles:!0})),t.getBoundingClientRect(),e.getBoundingClientRect();const r=this.readVisibleNativeOutlineEntries(e);s=this.mergeNativeOutlineEntryBatch(s,r,n);});}finally{t.scrollTop=o,t.dispatchEvent(new Event("scroll",{bubbles:true}));}return s}readVisibleNativeOutlineEntries(e){const t=e.querySelector(".ds-virtual-list-visible-items")||e.querySelector(".ds-virtual-list-items");if(!t)return [];const n=[];return Array.from(t.children).forEach((e,t)=>{if(!(e instanceof HTMLElement))return;const r=this.extractNativeOutlineText(e);r&&n.push({text:r,batchIndex:t});}),n}extractNativeOutlineText(e){const t=Array.from(e.children).filter(e=>e instanceof HTMLElement);for(const n of t){const e=this.normalizeOutlineText(n.innerText||n.textContent||"");if(e)return e}return this.normalizeOutlineText(e.innerText||e.textContent||"")}mergeNativeOutlineEntryBatch(e,t,n){if(0===t.length)return e;if(0===e.length)return t.map(e=>({...e,scrollTop:e.scrollTop??n}));for(let r=Math.min(e.length,t.length);r>0;r-=1){const o=e.slice(-r),i=t.slice(0,r);if(this.nativeOutlineEntrySequenceEquals(o,i))return [...e,...t.slice(r).map(e=>({...e,scrollTop:e.scrollTop??n}))]}return [...e,...t.map(e=>({...e,scrollTop:e.scrollTop??n}))]}nativeOutlineEntrySequenceEquals(e,t){return e.length===t.length&&e.every((e,n)=>this.nativeOutlineEntryEquals(e,t[n]))}nativeOutlineEntryEquals(e,t){return this.normalizeUserQueryMatchText(e.text)===this.normalizeUserQueryMatchText(t.text)}findMatchingUserQueryIndex(e,t,n){for(let r=n;r0&&t<=e.length?e[t-1]:e.find(e=>this.isEquivalentUserQueryText(e.text,n))||null}buildNativeOutlineJumpPositions(e,t,n,r,o){const i=Math.max(0,r.scrollHeight-r.clientHeight),a=e.length>1?Math.round(i*Math.max(n-1,0)/Math.max(e.length-1,1)):0,s=e.filter(e=>this.isEquivalentUserQueryText(e.text,o)).map(e=>e.scrollTop).filter(e=>"number"==typeof e),l=[t.scrollTop,a,a-.5*r.clientHeight,a+.5*r.clientHeight,...s,0,i],c=new Set;return l.map(e=>Math.max(0,Math.min(i,Math.round(e||0)))).filter(e=>!c.has(e)&&(c.add(e),true))}findVisibleNativeOutlineItem(e,t,n){const r=e.querySelector(".ds-virtual-list-visible-items")||e.querySelector(".ds-virtual-list-items");if(!r)return null;const o=Array.from(r.children).filter(e=>e instanceof HTMLElement);if("number"==typeof t.batchIndex&&t.batchIndex>=0&&t.batchIndexthis.isEquivalentUserQueryText(this.extractNativeOutlineText(e),n))||null}dispatchNativeOutlineClick(e){e.dispatchEvent(new MouseEvent("mousedown",{bubbles:true,cancelable:true})),e.dispatchEvent(new MouseEvent("mouseup",{bubbles:true,cancelable:true})),e.click();}async waitForUserQueryElement(e,t){for(let n=0;n<8;n+=1){const n=this.findUserQueryElement(e,t);if(n)return n;await this.sleep(80);}return null}sleep(e){return new Promise(t=>window.setTimeout(t,e))}isExportSnapshotElement(e){return e.hasAttribute(Wd)}async collectExportMessageSnapshots(e){const t=this.buildExportSnapshotPositions(e),n=e.scrollTop;let r=[];try{for(const n of t){e.scrollTop=n,e.dispatchEvent(new Event("scroll",{bubbles:!0})),e.getBoundingClientRect(),await this.sleep(80);const t=this.readVisibleExportMessageSnapshots(e);r=this.mergeExportMessageBatch(r,t);}}finally{e.scrollTop=n,e.dispatchEvent(new Event("scroll",{bubbles:true}));}return r}buildExportSnapshotPositions(e){const t=Math.max(0,e.scrollHeight-e.clientHeight),n=e.scrollTop;if(t<=0)return [n];const r=Math.max(160,Math.floor(.75*e.clientHeight)),o=new Set([0,n,t]);for(let i=0;ie-t)}buildBottomUpScanPositions(e){const t=Math.max(0,e.scrollHeight-e.clientHeight);if(t<=0)return [e.scrollTop];const n=Math.max(160,Math.floor(.9*e.clientHeight)),r=[];for(let o=t;o>0;o-=n)r.push(o);return 0!==r[r.length-1]&&r.push(0),r}shouldIncludeThoughtsInExport(){return "boolean"==typeof this.exportIncludeThoughtsOverride&&this.exportIncludeThoughtsOverride}resolveAssistantMessageElement(e){if(e.matches(Bd))return e;const t=e.closest(Bd);return t instanceof HTMLElement?t:null}resolveAssistantBodyMarkdownElement(e){if(e.matches(".ds-markdown")&&!this.isThoughtMarkdownElement(e))return e;const t=this.resolveAssistantMessageElement(e);return t?this.getAssistantBodyMarkdown(t):null}getAssistantBodyMarkdown(e){const t=Array.from(e.querySelectorAll(".ds-markdown")).filter(e=>e instanceof HTMLElement&&!this.isThoughtMarkdownElement(e));return t.length>0?t[t.length-1]:null}isThoughtMarkdownElement(e){return null!==e.closest(Fd)}extractThoughtBlockquotesFromMessage(e){const t=Array.from(e.querySelectorAll(`${Fd} .ds-markdown`)).filter(e=>e instanceof HTMLElement),n=[];return t.forEach(e=>{const t=this.extractMarkdownText(e);t&&n.push(this.formatAsThoughtBlockquote(t));}),n}extractMarkdownText(e){const t=e.cloneNode(true);t.querySelectorAll('button, [role="button"], svg, .ds-icon-button, .ds-focus-ring, [aria-hidden="true"]').forEach(e=>e.remove());const n=Uo(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}getVisibleAssistantMessages(e){return Array.from(e.querySelectorAll(Od)).filter(e=>e instanceof HTMLElement&&!e.closest(`[${Ud}]`)&&!e.closest(".gh-root")&&!e.parentElement?.closest(Bd))}extractLatestReplyTextFromMessages(e){for(let t=e.length-1;t>=0;t-=1){const n=this.extractAssistantResponseText(e[t]).trim();if(n)return n}return null}extractLastCodeBlockTextFromMessages(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t],r=this.getAssistantBodyMarkdown(n);if(!r)continue;const o=this.extractAssistantResponseText(n),i=this.extractLastFencedCodeBlock(o);if(i)return i;const a=this.extractLastCodeBlockTextFromDom(r);if(a)return a}return null}extractLastFencedCodeBlock(e){if(!e)return null;const t=/```[^\n]*\n([\s\S]*?)```/g;let n=null;for(const r of e.matchAll(t))n=r[1]||null;return n&&n.trim()?n.replace(/\r\n/g,"\n").replace(/\n+$/,""):null}extractLastCodeBlockTextFromDom(e){const t=Array.from(e.querySelectorAll("pre code, pre"));for(let n=t.length-1;n>=0;n-=1){const e=t[n];if(!(e instanceof HTMLElement))continue;const r=e.cloneNode(true);r.querySelectorAll('button, [role="button"], svg, .ds-icon-button, [aria-hidden="true"]').forEach(e=>e.remove());const o=r.textContent?.replace(/\r\n/g,"\n").replace(/\n+$/,"")||"";if(o.trim())return o}return null}readVisibleExportMessageSnapshots(e){return Array.from(e.querySelectorAll(Bd)).filter(e=>e instanceof HTMLElement&&!e.closest(`[${Ud}]`)&&!e.parentElement?.closest(Bd)).map(e=>this.extractExportMessageSnapshot(e)).filter(e=>null!==e)}extractExportMessageSnapshot(e){if(this.getAssistantBodyMarkdown(e)){const t=this.normalizeExportMessageContent(this.extractAssistantResponseText(e));return t?{role:Gd,content:t}:null}const t=this.normalizeExportMessageContent(this.extractUserQueryMarkdown(e));return t?{role:Vd,content:t}:null}normalizeExportMessageContent(e){return e.replace(/\r\n/g,"\n").replace(/\u00a0/g," ").trim()}mergeExportMessageBatch(e,t){if(0===t.length)return e;if(0===e.length)return t.map(e=>({...e}));for(let r=Math.min(e.length,t.length);r>0;r-=1){const n=e.slice(-r),o=t.slice(0,r);if(this.exportMessageSequenceEquals(n,o))return [...e,...t.slice(r).map(e=>({...e}))]}const n=e.map(e=>({...e}));return t.forEach(e=>{this.exportMessageEntryEquals(n[n.length-1],e)||n.push({...e});}),n}exportMessageSequenceEquals(e,t){return e.length===t.length&&e.every((e,n)=>this.exportMessageEntryEquals(e,t[n]))}exportMessageEntryEquals(e,t){return !(!e||!t)&&(e.role===t.role&&e.content===t.content)}mountExportSnapshot(e){this.clearExportSnapshot();const t=document.createElement("div");t.setAttribute(Ud,"1"),t.style.display="none",e.forEach(e=>{const n=document.createElement("div");n.setAttribute(Wd,e.role),n.textContent=e.content,t.appendChild(n);}),document.body.appendChild(t),this.exportSnapshotRoot=t,this.exportSnapshotActive=true;}clearExportSnapshot(){this.exportSnapshotActive=false;const e=this.exportSnapshotRoot;this.exportSnapshotRoot=null,e?.isConnected&&e.remove(),document.querySelectorAll(`[${Ud}]`).forEach(t=>{t!==e&&t.parentNode?.removeChild(t);});}async deleteConversationViaApi(e,t){try{const n=await fetch("/api/v0/chat_session/delete",{method:"POST",headers:this.buildDeleteHeaders(t),body:JSON.stringify({chat_session_id:e.id}),credentials:"include"});if(!n.ok)return {id:e.id,success:!1,method:"api",reason:this.toDeleteApiHttpReason(n.status)};const r=await this.safeParseJson(n);return this.isDeleteSuccessPayload(r)?{id:e.id,success:!0,method:"api"}:{id:e.id,success:!1,method:"api",reason:this.toDeleteApiPayloadReason(r)}}catch{return {id:e.id,success:false,method:"api",reason:Xd}}}buildDeleteHeaders(e){return {accept:"*/*",authorization:`Bearer ${e}`,"content-type":"application/json","x-client-platform":"web","x-client-locale":this.getClientLocale(),"x-client-timezone-offset":String(60*-(new Date).getTimezoneOffset())}}getUserToken(){const e=localStorage.getItem("userToken");if(!e)return null;try{const t=JSON.parse(e).value;if("string"==typeof t&&t.trim())return t.trim()}catch{}return e.trim().replace(/^"|"$/g,"")||null}getClientLocale(){return (document.documentElement.lang||navigator.language||"en-US").replace(/-/g,"_")}isDeleteSuccessPayload(e){if(!e||"object"!=typeof e)return false;const t=e;if(0!==t.code)return false;const n=t.data;if(!n||"object"!=typeof n)return true;const r=n.biz_code;return void 0===r||0===r}toDeleteApiPayloadReason(e){if(!e||"object"!=typeof e)return eu;const t=e;if("string"==typeof t.msg&&t.msg.trim())return `${tu}:${t.msg.trim()}`;const n=t.data;if(n&&"object"==typeof n){const e=n;if("string"==typeof e.biz_msg&&e.biz_msg.trim())return `${tu}:${e.biz_msg.trim()}`}return tu}toDeleteApiHttpReason(e){switch(e){case 401:case 403:return "delete_api_unauthorized";case 404:return "delete_api_not_found";case 429:return "delete_api_rate_limited";default:return `delete_api_http_${e||0}`}}async safeParseJson(e){try{return await e.json()}catch{return null}}scheduleHomeRefreshAfterDelete(){try{sessionStorage.setItem(Hd,"1");}catch{}window.location.replace($d);}schedulePageReloadAfterDelete(){window.setTimeout(()=>{window.location.reload();},0);}consumePendingDeleteRefresh(){let e=false;try{if(e="1"===sessionStorage.getItem(Hd),!e)return;sessionStorage.removeItem(Hd);}catch{return}if("/"===window.location.pathname||""===window.location.pathname)setTimeout(()=>{window.location.reload();},0);else {try{sessionStorage.setItem(Hd,"1");}catch{}window.location.replace($d);}}findNextAssistantMarkdown(e,t){for(let n=t+1;n!e.parentElement?.closest(Bd)),t=e?this.extractUserQueryText(e):"",n=this.normalizeOutlineText(t);if(n)return n.length>80?`${n.slice(0,80)}...`:n;const r=document.querySelector('meta[property="og:title"], meta[name="twitter:title"]')?.getAttribute("content")?.replace(/\s*[-|]\s*DeepSeek$/i,"")?.trim();return r&&"来自分享的对话"!==r?r:r||"DeepSeek Share"}isPinnedConversationLink(e){const t=this.findConversationGroup(e);if(!t)return false;const n=Array.from(t.children),r=n.filter(e=>this.isConversationLink(e));if(0===r.length)return false;const o=r[0],i=n.indexOf(o);if(i<=0)return false;const a=n.find((e,t)=>t0,l=null!==a.querySelector(":scope > .ds-focus-ring, .ds-focus-ring"),c=null!==a.querySelector(":scope > span, span");return s&&l&&c}findConversationGroup(e){let t=e.parentElement;for(;t&&t!==document.body;){const n=Array.from(t.children),r=n.filter(e=>this.isConversationLink(e));if(r.length>0){const o=n.indexOf(r[0]);if(n.some((e,t)=>tt===e))return t}t=t.parentElement;}return null}isConversationLink(e){return e.matches(Pd)}extractConversationTitle(e){const t=e.getAttribute("aria-label")?.trim();if(t)return t;const n=this.findTitleElement(e),r=n?.innerText?.trim()||n?.textContent?.trim()||"";if(r)return r.replace(/\s+/g," ").trim();return (e.innerText?.trim()||e.textContent?.trim()||"").replace(/\s+/g," ").trim()}findTitleElement(e){const t=Array.from(e.children).find(e=>e instanceof HTMLElement&&(!e.classList.contains("ds-focus-ring")&&(!e.querySelector('[role="button"], .ds-icon-button')&&!!e.innerText?.trim())));if(t)return t;const n=e.querySelectorAll("span, p, div");for(const r of Array.from(n)){if(r.innerText?.trim()||r.textContent?.trim()||"")return r}return e}findUserContentRoot(e){if(!e.matches(zd)&&!e.closest(zd))return null;const t=e.matches(zd)?e:e.closest(zd);if(!t)return null;return Array.from(t.children).filter(e=>e instanceof HTMLElement&&(!e.matches("button, [role=button], .ds-icon-button")&&e.innerText?.trim().length))[0]||t}},new class extends ci{lastScrollHeight=0;lastScrollTop=0;match(){return "www.doubao.com"===window.location.hostname}getSiteId(){return Pr}getName(){return "豆包"}getThemeColors(){return {primary:"#315efb",secondary:"#0f6eff"}}getNativeThemeCss(){return "\n/* =============================================\n * Doubao 站点原生主题适配器 (Doubao Theme Adapter)\n * ============================================= */\n\nbody {\n --chat-bg-color: color-mix(in srgb, var(--gh-primary) 1%, var(--gh-bg)) !important;\n}\n\n.bg-dbx-bg-base-web {\n background-color: color-mix(in srgb, var(--gh-primary) 1%, var(--gh-bg)) !important;\n}\n\n"}getTextareaSelectors(){return ['[data-slate-editor="true"]','textarea[data-testid="chat_input_input"]',"textarea.semi-input-textarea"]}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;if(t.focus(),t instanceof HTMLTextAreaElement){const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),t.setSelectionRange(e.length,e.length);}else if(t.isContentEditable){const n=window.getSelection();if(n){t.focus(),n.selectAllChildren(t),n.collapseToEnd();const e=t.querySelector('[data-slate-node="element"]');if(e&&n.rangeCount>0){const t=document.createRange();t.selectNodeContents(e),t.collapse(false),n.removeAllRanges(),n.addRange(t);}}const r=new DataTransfer;r.setData("text/plain",e),t.dispatchEvent(new ClipboardEvent("paste",{clipboardData:r,bubbles:true,cancelable:true,composed:true}));}return true}clearTextarea(){const e=this.getTextareaElement();if(e&&e.isConnected)if(e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement){const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),e.dispatchEvent(new Event("change",{bubbles:true}));}else e.isContentEditable&&(e.focus(),document.execCommand("selectAll",false),e.dispatchEvent(new KeyboardEvent("keydown",{key:"Backspace",code:"Backspace",keyCode:8,bubbles:true,composed:true})),document.execCommand("delete",false),e.dispatchEvent(new InputEvent("input",{inputType:"deleteContentBackward",bubbles:true,composed:true})),e.dispatchEvent(new KeyboardEvent("keyup",{key:"Backspace",code:"Backspace",keyCode:8,bubbles:true,composed:true})));}getConversationTitle(){const e=document.querySelector('a[data-testid="chat_list_thread_item"][class*="active-"]');if(!e)return null;const t=e instanceof HTMLAnchorElement?e:e.closest("a");if(!t)return null;const n=t.querySelector('[data-testid="chat_list_item_title"], [class^="section-item-title-"], [class*="section-item-title-"]');return n?.textContent?.trim()||null}getSessionId(){const e=window.location.pathname.match(nu);return e&&"new"!==e[1]?e[1]:""}isNewConversation(){return /^(?:\/code)?\/chat\/(new\/?)?$/.test(window.location.pathname)}getNewTabUrl(){return `https://www.doubao.com${window.location.pathname.startsWith("/code/")?"/code":""}/chat/`}supportsNewTab(){return true}getConversationList(){const e=document.querySelectorAll('a[data-testid="chat_list_thread_item"]');if(!e.length)return [];const t=new Map;return e.forEach(e=>{const n=e,r=(n.getAttribute("href")||"").match(nu),o=r?.[1];if(!o||"new"===o)return;const i=n.querySelector('[data-testid="chat_list_item_title"], [class^="section-item-title-"], [class*="section-item-title-"]')?.textContent?.trim()||"",a=n.className.includes("active-"),s=!!n.querySelector('[id="chat_list_item_pin_icon"], [class^="pin-"], [class*="pin-"]');t.set(o,{id:o,title:i,url:`https://www.doubao.com/chat/${o}`,isActive:a,isPinned:s});}),Array.from(t.values())}navigateToConversation(e,t){const n=document.querySelector(`a[data-testid="chat_list_thread_item"][href*="/chat/${e}"]`);return n?(n.click(),true):(window.location.href=t||`https://www.doubao.com/chat/${e}`,true)}async loadAllConversations(){const e=this.getSidebarScrollContainer();if(!e)return;let t=0,n=0;for(;n<3;){e.scrollTop=e.scrollHeight,await new Promise(e=>setTimeout(e,500));const r=e.querySelectorAll('a[data-testid="chat_list_thread_item"]').length;r===t?n++:(t=r,n=0);}}getSidebarScrollContainer(){return document.querySelector('[data-testid="chat_list_wrapper"]')}getConversationObserverConfig(){return {selector:'a[data-testid="chat_list_thread_item"]',shadow:false,extractInfo:e=>{const t=e,n=(t.getAttribute("href")||"").match(nu),r=n?.[1];if(!r||"new"===r)return null;return {id:r,title:t.querySelector('[data-testid="chat_list_item_title"], [class^="section-item-title-"], [class*="section-item-title-"]')?.textContent?.trim()||"",url:`https://www.doubao.com/chat/${r}`,isActive:t.className.includes("active-"),isPinned:!!t.querySelector('[id="chat_list_item_pin_icon"], [class^="pin-"], [class*="pin-"]')}},getTitleElement:e=>e.querySelector('[data-testid="chat_list_item_title"], [class^="section-item-title-"], [class*="section-item-title-"]')}}async deleteConversationOnSite(e){const t=await this.deleteConversationViaUi(e.id);return {id:e.id,success:t,method:t?"ui":"none",reason:t?void 0:lu}}async deleteConversationsOnSite(e){const t=[];for(let n=0;nt.clientHeight)return t;t=t.parentElement;}}const t=document.querySelectorAll('[class^="scrollable-"]');for(const n of t){if("column-reverse"===window.getComputedStyle(n).flexDirection&&n.scrollHeight>n.clientHeight)return n}return document.querySelector('[data-testid="scroll_view"]')}getResponseContainerSelector(){return '[data-testid="message-list"]'}getUserQuerySelector(){return iu}getChatContentSelectors(){return ['[data-testid="receive_message"] .flow-markdown-body',su]}extractAssistantMarkdown(e){const t=((e.matches(".flow-markdown-body")?e:e.querySelector(".flow-markdown-body"))||e).cloneNode(true);t.querySelectorAll('button, [role="button"], svg, [aria-hidden="true"]').forEach(e=>e.remove());const n=Uo(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}getLatestReplyText(){const e=document.querySelectorAll('[data-testid="receive_message"]');if(0===e.length)return null;const t=e[e.length-1];return this.extractAssistantMarkdown(t)||null}getUserMessageTextContainer(e){return e.matches(su)||e.matches(au)?e:e.querySelector(au)}extractUserQueryText(e){const t=this.getUserMessageTextContainer(e);return t?this.extractTextWithLineBreaks(t).trim():""}extractUserQueryMarkdown(e){const t=this.getUserMessageTextContainer(e);return t?this.extractTextWithLineBreaks(t).trim():""}extractUserQueryExportText(e){const t=this.getUserMessageTextContainer(e);if(!t)return this.extractUserQueryText(e);const n=t.textContent?.trim();return n||this.extractUserQueryText(t)}replaceUserQueryContent(e,t){const n=this.getUserMessageTextContainer(e);if(!n)return false;if(n.nextElementSibling?.classList.contains("gh-user-query-markdown"))return false;const r=document.createElement("div");r.className=`${n.className} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t;const o=n.getAttribute("style");return o&&r.setAttribute("style",o),n.style.display="none",n.after(r),true}findModelSelectorButton(){const e=document.querySelectorAll('button[data-slot="dropdown-menu-trigger"][aria-haspopup="menu"]');for(const t of e){const e=t;if(null!==e.offsetParent){const t=e.querySelector(".truncate");if(t&&t.textContent?.trim())return e}}return null}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:['button[data-slot="dropdown-menu-trigger"][aria-haspopup="menu"]'],menuItemSelector:'div[role="menuitem"][data-slot="dropdown-menu-item"]',menuRenderDelay:100}}getModelName(){const e=this.findModelSelectorButton();if(!e)return null;const t=e.innerText?.trim();return t?t.split("\n")[0].trim():null}clickModelSelector(){const e=this.findModelSelectorButton();return !!e&&(this.simulateClick(e),true)}simulateClick(e){const t=e.getBoundingClientRect(),n=t.left+Math.max(1,Math.min(t.width/2,t.width-1)),r=t.top+Math.max(1,Math.min(t.height/2,t.height-1)),o={bubbles:true,cancelable:true,composed:true,view:window,button:0,buttons:1,clientX:n,clientY:r};e.dispatchEvent(new PointerEvent("pointerenter",{...o,pointerId:1,pointerType:"mouse",isPrimary:true})),e.dispatchEvent(new PointerEvent("pointerover",{...o,pointerId:1,pointerType:"mouse",isPrimary:true})),e.dispatchEvent(new MouseEvent("mouseenter",o)),e.dispatchEvent(new MouseEvent("mouseover",o)),e.dispatchEvent(new PointerEvent("pointerdown",{...o,pointerId:1,pointerType:"mouse",isPrimary:true})),e.dispatchEvent(new MouseEvent("mousedown",o)),e.dispatchEvent(new PointerEvent("pointerup",{...o,pointerId:1,pointerType:"mouse",isPrimary:true})),e.dispatchEvent(new MouseEvent("mouseup",o)),e.dispatchEvent(new MouseEvent("click",o));}async deleteConversationViaUi(e){const t=await this.findConversationRowWithRetry(e);if(!t)return false;if(!(await this.openConversationMenu(t,e)))return false;const n=await this.waitForDeleteMenuItem(2500);if(!n)return false;this.simulateClick(n);const r=await this.waitForDeleteConfirmButton(2500);return !!r&&(this.simulateClick(r),this.waitForConversationRemoved(e,7e3))}async findConversationRowWithRetry(e){const t=this.findConversationRow(e);return t||(await this.loadAllConversations(),await this.sleep(200),this.findConversationRow(e))}findConversationRow(e){return document.querySelector(`#conversation_${e}, a[data-testid="chat_list_thread_item"][href*="/chat/${e}"]`)}getConversationMenuButtons(e,t){const n=`[data-testid="chat_list_item_setting_more_${t}"]`,r=[],o=[],i=new Set,a=e=>{e&&(i.has(e)||(i.add(e),this.isVisible(e)?r.push(e):o.push(e)));},s=e.querySelector(n);if(!s)return [];const l=s.querySelector('button[data-slot="dropdown-menu-trigger"][aria-haspopup="menu"]'),c=s.querySelector('button[data-dbx-name="button"]'),d=s.querySelector('[data-testid="chat_item_dropdown_entry"]'),u=d?.closest("button");return a(l),a(c),a(u),a(s),[...r,...o]}async openConversationMenu(e,t){for(let n=0;n<10;n+=1){e.dispatchEvent(new MouseEvent("mouseenter",{bubbles:true})),e.dispatchEvent(new MouseEvent("mousemove",{bubbles:true}));const n=this.getConversationMenuButtons(e,t);if(0!==n.length){for(const t of n){document.body.click(),await this.sleep(50);if(await this.tryActivateConversationAction(e,t))return true}await this.sleep(100);}else await this.sleep(80);}return false}async waitForDeleteMenuItem(e=2500){const t=Date.now();for(;Date.now()-tthis.isVisible(e)&&this.getSignalText(e).includes("删除"))||null}async waitForConversationRemoved(e,t=3500){const n=Date.now();for(;Date.now()-nthis.isVisible(e)))return true;await this.sleep(50);}return false}getSignalText(e){return [e.textContent||"",e.getAttribute("aria-label")||"",e.getAttribute("title")||"",e.className||""].join(" ").toLowerCase()}isVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector('[data-testid="message-list"]');if(!o)return r;const i=(t,i)=>{const a=Array.from(t.querySelectorAll("h1, h2, h3, h4, h5, h6"));a.forEach((t,s)=>{const l=parseInt(t.tagName[1],10);if(l>e)return;const c=t.textContent?.trim()||"";if(!c)return;let d;if(n){let e=null;for(let t=s+1;t{const t=this.extractUserQueryMarkdown(e);if(!t)return;let o;if(n){let t=e.nextElementSibling;for(;t&&!t.querySelector('[data-testid="receive_message"]');)t=t.nextElementSibling;if(t){const e=t.querySelector(".flow-markdown-body");o=e?.textContent?.length||0;}}r.push({level:0,text:t.length>80?t.slice(0,80)+"...":t,element:e,isUserQuery:true,isTruncated:t.length>80,wordCount:o});});}return o.querySelectorAll('[data-testid="receive_message"] .flow-markdown-body').forEach(e=>i(e)),r}return a.forEach(e=>{let o=0;const a=e.querySelector('[data-testid="receive_message"]'),s=a?.querySelector(".flow-markdown-body");if(s&&n&&(o=s.textContent?.length||0),t){const t=e.querySelector(iu);if(t){const e=this.extractUserQueryMarkdown(t);e&&r.push({level:0,text:e.length>80?e.slice(0,80)+"...":e,element:t,isUserQuery:true,isTruncated:e.length>80,wordCount:n?o:void 0});}}s&&i(s,s);}),r}getExportConfig(){return {userQuerySelector:su,assistantResponseSelector:'[data-testid="receive_message"]',turnSelector:'[data-testid="union_message"]',useShadowDOM:false}}toggleTheme(){return Promise.resolve(false)}isGenerating(){const e=document.querySelector('[data-testid="chat_input_local_break_button"]');return null!==e&&null!==e.offsetParent}getStopButtonSelectors(){return ['[data-testid="chat_input_local_break_button"]']}getNewChatButtonSelectors(){return ['[data-testid="create_conversation_button"]']}getSubmitButtonSelectors(){return ["[data-testid='chat_input_send_button']","#flow-end-msg-send",".send-btn-wrapper button"]}getWidthSelectors(){return [{selector:'[data-container-name="main"]',property:"max-width"},{selector:'[data-testid="message-block-container"]',property:"--message-block-container-inline-width"},{selector:".max-w-\\(--content-max-width\\)",property:"max-width"},{selector:".chrome70-container",property:"--center-content-max-width"}]}getUserQueryWidthSelectors(){return [{selector:'[data-testid="send_message"] .w-fit[class*="max-w-"]',property:"max-width"},{selector:'[data-testid="message_content"].justify-end [data-testid="message_text_content"].w-fit[class*="max-w-"]',property:"max-width"}]}getVisibleAnchorElement(){const e=this.getScrollContainer();if(!e)return null;const t=this.getChatContentSelectors();if(!t.length)return null;const n=Array.from(e.querySelectorAll(t.join(", ")));if(!n.length)return null;const r=e.getBoundingClientRect();let o=null;for(let i=0;i=r.top-50&&t.bottom<=r.bottom+50){o=e;break}if(t.top<=r.top&&t.bottom>=r.top){o=e;break}}if(!o)for(let i=0;ir.bottom){o=e;break}}if(o){const e=n.indexOf(o);if(-1!==e){return {type:"index",index:e,offset:0,textSignature:(o.textContent||"").trim().substring(0,50)}}}return null}restoreScroll(e){const t=this.getScrollContainer();if(!t||!e)return false;let n=null;if("index"===e.type&&"number"==typeof e.index){const r=this.getChatContentSelectors(),o=Array.from(t.querySelectorAll(r.join(", ")));if(o[e.index]){if(n=o[e.index],e.textSignature){if((n.textContent||"").trim().substring(0,50)!==e.textSignature){const t=o.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature);t&&(n=t);}}}else if(e.textSignature){const t=o.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature);t&&(n=t);}}return !!n&&(n.scrollIntoView({block:"start",behavior:"instant"}),setTimeout(()=>{this.lastScrollHeight=t.scrollHeight,this.lastScrollTop=t.scrollTop;},50),true)}},new class extends ci{exportIncludeThoughts=void 0;match(){return "ima.qq.com"===window.location.hostname}getSiteId(){return Br}getName(){return "ima"}getThemeColors(){return {primary:"#07a45f",secondary:"#05854d"}}getSessionId(){const e=window.location.pathname.match(xh);return e?.[1]||""}isNewConversation(){return "/"===(window.location.pathname.replace(/\/+$/,"")||"/")}getCurrentCid(){const e=window.localStorage.getItem("ima-official-website-uid");if(!e)return null;try{const t=JSON.parse(e);if("string"==typeof t&&t.trim())return t.trim();if(t&&"object"==typeof t)for(const e of ["uid","id","userId","openId"]){const n=t[e];if("string"==typeof n&&n.trim())return n.trim()}}catch{}return e.trim()||null}getSessionName(){const e=this.getActiveHistoryTitle();if(e)return e;const t=document.title.trim();if(!t)return null;const n=t.replace(/\s*[-|]\s*ima$/i,"").replace(/^ima\s*[-|]\s*/i,"").trim();return n&&"ima"!==n.toLowerCase()?n:null}getNewTabUrl(){return "https://ima.qq.com/"}getConversationTitle(){return this.getActiveHistoryTitle()||this.getSessionName()}getTextareaSelectors(){return ['#tagTextarea [contenteditable="true"], [class*="chatInputContainer"] .tiptap.ProseMirror']}isValidTextarea(e){return !!super.isValidTextarea(e)&&(!!e.isContentEditable&&!!e.closest("#tagTextarea, [class*='chatInputContainer']"))}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus(),this.selectAllEditorContent(t);if(this.tryPasteText(t,e))return true;try{if(document.execCommand("insertText",!1,e))return this.dispatchEditorInput(t,e,"insertText"),!0}catch{}return t.textContent=e,this.dispatchEditorInput(t,e,"insertText"),true}clearTextarea(){const e=this.getTextareaElement();if(e&&e.isConnected){e.focus(),this.selectAllEditorContent(e);try{document.execCommand("delete",!1);}catch{}e.textContent="",this.dispatchEditorInput(e,"","deleteContentBackward");}}getSubmitButtonSelectors(){return [Nh]}findSubmitButton(e){const t=[e?.closest("#tagTextarea"),e?.closest('[class*="chatInputContainer"]'),document.querySelector('[class*="chatInputContainer"]'),document.body].filter(Boolean);for(const n of t){const e=n.querySelector(Nh);if(e&&this.isVisibleElement(e)&&!e.querySelector('.icon-send-disable-big, [class*="sendDisableIcon"]'))return e}return null}getNewChatButtonSelectors(){return ['[class*="newChatWrap"]']}getSidebarScrollContainer(){return document.querySelector("#HistoryScrollContainer")}getScrollContainer(){const e=document.querySelector(kh);return e instanceof HTMLElement?e:null}getResponseContainerSelector(){return Sh}getChatContentSelectors(){return [Ch,Ah]}getUserQuerySelector(){return Ch}extractUserQueryText(e){const t=this.findUserContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown, button, [role='button'], svg").forEach(e=>{e.remove();}),this.extractTextWithLineBreaks(n).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}replaceUserQueryContent(e,t){const n=this.findUserContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e),n.style.display="none";}return n.after(r),true}extractAssistantResponseText(e){const t=e.cloneNode(true);t.querySelectorAll(`${Ih}, button, [role='button'], svg, [aria-hidden='true']`).forEach(e=>e.remove());const n=this.shouldIncludeThoughtsInExport(),r=n?this.extractThoughtBlockquotes(t):[];t.querySelectorAll(Mh).forEach(e=>e.remove());const o=this.findAssistantMarkdownRoot(t),i=o instanceof HTMLElement?o:t,a=Uo(i).trim();if(n&&r.length>0){const e=r.join("\n\n");return a?`${e}\n\n${a}`:e}return a||this.extractTextWithLineBreaks(i).trim()}getLatestReplyText(){const e=document.querySelectorAll(Ah),t=e[e.length-1];if(!t)return null;return this.extractAssistantResponseText(t)||null}extractOutline(e=6,t=false,n=false){const r=document.querySelector(Sh)||document.querySelector(kh);if(!r)return [];const o=[],i=Array.from(r.querySelectorAll(`${Ch}, ${Ah}`)).filter(e=>!e.closest(".gh-root"));return i.forEach((r,a)=>{if(r.matches(Ch)){if(!t)return;const e=this.extractUserQueryText(r);if(!e)return;let s;if(n){const e=i.slice(a+1).find(e=>e.matches(Ah));s=e?this.extractAssistantResponseText(e).length:0;}return void o.push({level:0,text:this.truncateText(e,80),element:r,isUserQuery:true,isTruncated:e.length>80,wordCount:s})}const s=this.findAssistantMarkdownRoot(r);if(!s)return;const l=Array.from(s.querySelectorAll("h1, h2, h3, h4, h5, h6")).filter(e=>!this.isInRenderedMarkdownContainer(e));l.forEach((t,r)=>{const i=Number.parseInt(t.tagName.slice(1),10);if(Number.isNaN(i)||i>e)return;const a=this.extractHeadingText(t);if(!a)return;let c;if(n){let e=null;for(let t=r+1;te.remove()),this.extractTextWithLineBreaks(t).trim()}shouldIncludeThoughtsInExport(){return void 0!==this.exportIncludeThoughts&&this.exportIncludeThoughts}extractThoughtBlockquotes(e){const t=Array.from(e.querySelectorAll(Mh)),n=[];for(const r of t){const e=r.cloneNode(true);e.querySelectorAll('[class*="tipsWrap"], [class*="thinkingTitle"], [class*="thinkingHeader"], button, [role=\'button\'], svg, [aria-hidden=\'true\']').forEach(e=>e.remove());const t=(Uo(e)||this.extractTextWithLineBreaks(e)).trim();t&&n.push(this.formatAsThoughtBlockquote(t));}return n}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}truncateText(e,t){return e.length>t?`${e.slice(0,t)}...`:e}tryPasteText(e,t){if("undefined"==typeof DataTransfer||"undefined"==typeof ClipboardEvent)return false;try{const n=new DataTransfer;n.setData("text/plain",t);const r=new ClipboardEvent("paste",{clipboardData:n,bubbles:!0,cancelable:!0,composed:!0});if(!e.dispatchEvent(r))return !0}catch{return false}return false}selectAllEditorContent(e){const t=window.getSelection();if(!t)return;const n=document.createRange();n.selectNodeContents(e),t.removeAllRanges(),t.addRange(n);}dispatchEditorInput(e,t,n){e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:t,inputType:n})),e.dispatchEvent(new Event("change",{bubbles:true}));}isVisibleElement(e){if(!e||!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility)return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}simulateClick(e){const t=["pointerdown","mousedown","pointerup","mouseup","click"];let n=false;for(const r of t)try{"function"==typeof PointerEvent?e.dispatchEvent(new PointerEvent(r,{bubbles:!0,cancelable:!0,pointerId:1})):e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{try{e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{}}n||e.click();}findStopButton(){const e=Array.from(document.querySelectorAll('div[class*="stopButton"], [class*="stopButton"]'));for(const t of e){if(!(t instanceof HTMLElement&&this.isVisibleElement(t)))continue;const e=[t.querySelector(":scope > div"),t.querySelector('[class*="container"]'),t];for(const t of e)if(t instanceof HTMLElement&&this.isVisibleElement(t))return t}return null}},new class extends ci{match(){return Li.has(window.location.hostname)}getSiteId(){return Lr}getName(){return "智谱清言"}getThemeColors(){return {primary:"#2454FF",secondary:"#1F46D6"}}async toggleTheme(e){const t=Ri[e]||Ri.light;try{localStorage.setItem(Di,t);if(await this.applyThemeByClick(e))return !0;const n="system"===e&&"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,r="system"===e?n?"dark":"light":e,o=e=>{e&&(e.classList.toggle("dark-theme","dark"===r),e.classList.remove("light-theme"),e.setAttribute("data-theme",r),e.setAttribute("data-color-scheme",r),e.style.colorScheme=r);},i=new Set;document.documentElement&&i.add(document.documentElement),document.body&&i.add(document.body);const a=[document.querySelector("#app"),document.querySelector("[data-v-app]"),document.querySelector(".app"),document.querySelector(".app-container")];for(const e of a)e instanceof HTMLElement&&i.add(e);for(const e of i)o(e);return window.dispatchEvent(new StorageEvent("storage",{key:Di,newValue:t,storageArea:localStorage})),!0}catch{return false}}simulateClick(e){const t=["pointerdown","mousedown","pointerup","mouseup","click"];let n=false;for(const r of t){const t=new MouseEvent(r,{bubbles:true,cancelable:true,view:window});n=e.dispatchEvent(t)||n;}n||e.click();}async applyThemeByClick(e){const t=this.findVisibleElement(qi);if(!t)return false;this.simulateClick(t),await this.delay(120);const n=await this.waitForVisibleElement(".themes",1500);if(!n)return false;this.simulateClick(n),await this.delay(120);const r=await this.findThemeOption(e,1500);return !!r&&(this.simulateClick(r),await this.delay(80),true)}findVisibleElement(e){for(const t of e){const e=document.querySelector(t);if(e&&null!==e.offsetParent)return this.resolveClickable(e)}return null}resolveClickable(e){return e.closest(".me-icon")||e.closest(".me")||e.closest(".userInfoBar-header")||e}async waitForVisibleElement(e,t=800){const n=Date.now();for(;Date.now()-n0)break}return Array.from(t)}matchThemeOption(e,t){const n=t.map(e=>e.replace(/\s+/g,"").toLowerCase());for(const r of e){const e=r.textContent?.replace(/\s+/g,"").toLowerCase()||"";if(e&&n.some(t=>e.includes(t)))return r}return null}async delay(e){await new Promise(t=>window.setTimeout(t,e));}getTextareaSelectors(){return ji}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus();const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),t.setSelectionRange(e.length,e.length),true}clearTextarea(){const e=this.getTextareaElement();if(!e||!e.isConnected)return;const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),e.dispatchEvent(new Event("change",{bubbles:true})),e.setSelectionRange(0,0);}getSessionId(){const e=new URLSearchParams(window.location.search).get("cid");return e?e.trim():""}isNewConversation(){return !this.getSessionId()}getNewChatButtonSelectors(){return [".new-session",'div[class~="new-session"]']}getNewTabUrl(){return new URL("/main/alltoolsdetail?lang=zh",window.location.origin).toString()}getSessionName(){const e=this.getConversationTitle();if(e)return e;const t=document.title.trim();if(!t)return null;const n=t.replace(/\s*[-|]\s*(智谱清言|ChatGLM(?:\s*\d+)?)\s*$/i,"").trim();return n&&"智谱清言"!==n&&"chatglm"!==n.toLowerCase()?n:null}getConversationTitle(){return null}getSubmitButtonSelectors(){return [`${$i}:not(.empty)`]}findSubmitButton(){const e=document.querySelector($i);return !e||e.classList.contains("empty")||null===e.offsetParent?null:e}getScrollContainer(){const e=document.querySelector(Bi);if(e&&e.scrollHeight>e.clientHeight)return e;const t=document.querySelector(".chatScrollContainer");return t&&t.scrollHeight>t.clientHeight?t:super.getScrollContainer()}getResponseContainerSelector(){return Bi}getChatContentSelectors(){return [Fi,zi]}getUserQuerySelector(){return Oi}extractUserQueryText(e){const t=e.querySelector(zi)||e;return this.extractTextWithLineBreaks(t).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}replaceUserQueryContent(e,t){const n=e.querySelector(zi);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");r.className=[...n.classList,"gh-user-query-markdown","gh-markdown-preview"].filter(e=>"dots"!==e&&"dot-3-line"!==e).join(" ").trim(),r.innerHTML=t;const o=n.getAttribute("style");o&&r.setAttribute("style",o),r.style.textAlign="left",r.style.display="block",r.style.width="100%",n.style.display="none";const i=e.querySelector(".collapse-button-bg");return i&&(i.style.display="none"),n.after(r),true}extractAssistantResponseText(e){const t=e.matches(".markdown-body")?e:e.querySelector(".markdown-body");if(!t)return "";const n=Uo(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}getLatestReplyText(){const e=document.querySelectorAll(Fi);if(0===e.length)return null;const t=e[e.length-1];return this.extractAssistantResponseText(t)||null}extractOutline(e=6,t=false,n=false){const r=document.querySelector(Bi);if(!r)return [];const o=[],i=Array.from(r.querySelectorAll(".conversation-item"));return i.forEach((r,a)=>{const s=r.querySelector(Oi);if(s&&t){const e=this.extractUserQueryMarkdown(s);if(e){let t;if(n){const e=(e=>{for(let t=e+1;t80?`${e.slice(0,80)}...`:e,element:s,isUserQuery:true,isTruncated:e.length>80,wordCount:t});}}const l=r.querySelectorAll(Fi);l.length&&l.forEach(t=>{const r=Array.from(t.querySelectorAll("h1, h2, h3, h4, h5, h6"));r.forEach((i,a)=>{if(this.isInRenderedMarkdownContainer(i))return;const s=Number.parseInt(i.tagName.slice(1),10);if(Number.isNaN(s)||s>e)return;const l=i.textContent?.trim()||"";if(!l)return;let c;if(n){let e=null;for(let t=a+1;tt.startsWith(e)))return "";const n=e.match(qh);return n?n[1]:""}isNewConversation(){const e=window.location.pathname;return "/"===e||""===e||"/chat/history"===e||e.startsWith("/chat/history/")}isSharePage(){return window.location.pathname.startsWith("/kimiplus/")}getSessionName(){const e=this.getConversationTitle();if(e)return e;const t=document.title.trim();if(!t||"Kimi"===t)return null;return t.replace(/\s*-\s*Kimi$/i,"").trim()||null}getCurrentCid(){try{for(let e=0;e{const r=this.extractConversationInfo(e,t);r&&n.push(r);}),this.mergeConversationInfos(n)}getConversationObserverConfig(){return {selector:Uh,shadow:false,extractInfo:e=>this.extractConversationInfo(e,this.getCurrentCid()||void 0),getTitleElement:e=>e.querySelector(`${Vh}, ${Gh}`)||e}}getSidebarScrollContainer(){const e=[document.querySelector(".history .group-list-container"),document.querySelector(Wh),document.querySelector(".history .usage-content"),document.querySelector(".history .content"),document.querySelector(".history")].filter(Boolean);for(const t of e){const e=this.findScrollableParent(t);if(e)return e;if(t instanceof HTMLElement&&t.scrollHeight>t.clientHeight)return t}return null}async loadAllConversations(){await this.openMoreHistoryView();try{let e=0,t=0;const n=4;for(;tsetTimeout(e,500));const r=document.querySelectorAll(Uh).length;r===e?t++:(e=r,t=0);}this.cacheFullListSnapshot(this.collectConversationListFromDom());}finally{await this.closeMoreHistoryView();}}async deleteConversationOnSite(e){const t=this.getAuthToken();if(!t)return this.logMissingDeleteTokenOnce(),{id:e.id,success:false,method:"api",reason:tg};const n=this.getSessionId(),r=await this.deleteConversationViaApi(e,t);return r.success&&e.id===n&&this.navigateToHomeAfterDelete(),r}async deleteConversationsOnSite(e){if(0===e.length)return [];const t=this.getAuthToken();if(!t)return this.logMissingDeleteTokenOnce(),e.map(e=>({id:e.id,success:false,method:"api",reason:tg}));const n=this.getSessionId(),r=[],o=[];for(const i of e){const e=await this.deleteConversationViaApi(i,t);r.push(e),e.success&&o.push(i.id);}if(o.length>0){n&&o.includes(n)?this.navigateToHomeAfterDelete():this.scheduleReloadAfterBatchDelete();}return r}navigateToConversation(e,t){const n=`${Uh}[href*="/chat/${e}"]`,r=document.querySelector(n);return r?(r.click(),true):super.navigateToConversation(e,t||`https://www.kimi.com/chat/${e}`)}getConversationTitle(){const e=document.querySelector(".chat-header-content h2")?.textContent?.trim();if(e)return e;const t=this.getActiveConversationLink();if(t){const e=this.extractConversationTitle(t);if(e)return e}const n=this.getSessionId();if(n){const e=document.querySelector(`${Uh}[href*="/chat/${n}"]`);if(e){const t=this.extractConversationTitle(e);if(t)return t}}return null}getTextareaSelectors(){return ['.chat-input-editor[data-lexical-editor="true"]','.chat-input-editor[contenteditable="true"]','[role="textbox"].chat-input-editor']}isValidTextarea(e){return null!==e.offsetParent&&(!!e.isContentEditable&&(!e.closest(".gh-main-panel")&&!e.closest(".gh-queue-panel")&&!!e.closest(".chat-input-editor-container")))}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;if(t.focus(),document.activeElement!==t&&!t.contains(document.activeElement))return false;if(this.insertByExecCommand(t,e))return true;return this.insertByPasteEvent(t,e)||(t.textContent=e,t.dispatchEvent(new Event("input",{bubbles:true})),t.dispatchEvent(new Event("change",{bubbles:true}))),true}clearTextarea(){const e=this.getTextareaElement();if(!e||!e.isConnected)return;const t=()=>0===(e.textContent||"").replace(/[\u200b\u00a0]/g,"").trim().length,n=()=>{this.selectEditorAll(e);try{document.dispatchEvent(new Event("selectionchange"));}catch{}},r=t=>{try{e.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,composed:!0,cancelable:!0,inputType:t}));}catch{}},o=(t,n,r)=>{e.dispatchEvent(new KeyboardEvent("keydown",{key:t,code:n,keyCode:r,which:r,bubbles:true,cancelable:true,composed:true})),e.dispatchEvent(new KeyboardEvent("keyup",{key:t,code:n,keyCode:r,which:r,bubbles:true,cancelable:true,composed:true}));},i=()=>{if(e.isConnected){e.focus(),n(),r("deleteContentBackward");try{document.execCommand("delete",!1,void 0);}catch{}if(!t())try{document.execCommand("insertText",!1,"");}catch{}if(t()||o("Backspace","Backspace",8),t()||(r("deleteContentForward"),o("Delete","Delete",46)),t()||(()=>{try{const e=window.getSelection();if(!e||0===e.rangeCount)return;e.getRangeAt(0).deleteContents();}catch{}})(),!t()){this.clearByExecCommand(e)&&t()||(e.innerHTML="


");}(t=>{try{e.dispatchEvent(new InputEvent("input",{bubbles:!0,composed:!0,inputType:t}));}catch{e.dispatchEvent(new Event("input",{bubbles:true}));}})("deleteContentBackward"),e.dispatchEvent(new Event("change",{bubbles:true}));}};i();[30,120,240].forEach(n=>{setTimeout(()=>{e.isConnected&&(t()||i());},n);});}getSubmitButtonSelectors(){return [".send-button-container:not(.disabled):not(.stop)"]}findSubmitButton(e){const t=[e?.closest(".chat-editor"),e?.closest(".chat-input-editor-container"),e?.parentElement,document.body].filter(Boolean),n=new Set;for(const r of t){const e=r.querySelectorAll(".send-button-container");for(const t of Array.from(e)){const e=t;if(!n.has(e)&&(n.add(e),null!==e.offsetParent&&!e.classList.contains("disabled")&&!e.classList.contains("stop")))return e}}return null}getScrollContainer(){const e=document.querySelector(".chat-detail-content");if(e&&e.scrollHeight>e.clientHeight)return e;const t=document.querySelector(".chat-content-container"),n=this.findScrollableParent(t);return n&&!n.closest(Wh)?n:super.getScrollContainer()}getResponseContainerSelector(){return Qh}getChatContentSelectors(){return [Xh,".segment-user .segment-content-box"]}getUserQuerySelector(){return Jh}extractUserQueryText(e){const t=e.querySelector(".segment-content-box");return this.extractTextWithLineBreaks(t||e).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}replaceUserQueryContent(e,t){if(e.querySelector(".gh-user-query-markdown"))return false;const n=e.querySelector(".segment-content-box");if(!n)return false;const r=document.createElement("div");r.className=`${n.className} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t;const o=n.getAttribute("style");return o&&r.setAttribute("style",o),n.style.display="none",n.after(r),true}extractAssistantResponseText(e){const t=e.matches(".markdown")?e:e.querySelector(".markdown");if(!t)return "";const n=Uo(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}getLatestReplyText(){const e=document.querySelectorAll(Xh);if(0===e.length)return null;const t=e[e.length-1];return this.extractAssistantResponseText(t)||null}extractOutline(e=6,t=false,n=false){const r=document.querySelector(Qh);if(!r)return [];const o=[],i=this.getChatItems(r);return i.forEach((r,a)=>{if(r.matches(Zh)||r.querySelector(Jh)){if(!t)return;const e=r.querySelector(Jh)||r,s=this.extractUserQueryMarkdown(e);if(!s)return;let l;if(n){const e=this.findNextAssistantMarkdown(i,a);l=e?.textContent?.trim().length||0;}return void o.push({level:0,text:s.length>80?`${s.slice(0,80)}...`:s,element:e,isUserQuery:true,isTruncated:s.length>80,wordCount:l})}if(!r.matches(Yh)&&!r.querySelector(Xh))return;const s=r.querySelector(".markdown");if(!s)return;const l=Array.from(s.querySelectorAll("h1, h2, h3, h4, h5, h6"));l.forEach((t,r)=>{const i=Number.parseInt(t.tagName.slice(1),10);if(Number.isNaN(i)||i>e)return;const a=t.textContent?.trim()||"";if(!a)return;let c;if(n){let e=null;for(let t=r+1;t{if(!this.isGenerating())return false;const t=e.closest(".segment-assistant");if(!t)return false;const n=document.querySelectorAll(`${Yh} .segment-assistant`);return t===n[n.length-1]}}}simulateClick(e){const t=["pointerdown","mousedown","pointerup","mouseup","click"];let n=false;for(const r of t)try{"function"==typeof PointerEvent?e.dispatchEvent(new PointerEvent(r,{bubbles:!0,cancelable:!0,pointerId:1})):e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{try{e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{}}n||e.click();}normalizeThemeStorageValue(){const e=localStorage.getItem(eg);if(!e)return;const t=e.trim();if(t)if("light"!==t&&"dark"!==t)try{const e=JSON.parse(t);if("light"===e||"dark"===e)return}catch{}else localStorage.setItem(eg,JSON.stringify(t));}async deleteConversationViaApi(e,t){try{const n=new URL("/apiv2/kimi.chat.v1.ChatService/DeleteChat",window.location.origin).toString(),r=await fetch(n,{method:"POST",headers:this.buildDeleteHeaders(t),body:JSON.stringify({chat_id:e.id}),credentials:"include"});if(!r.ok)return {id:e.id,success:!1,method:"api",reason:this.toDeleteApiHttpReason(r.status)};const o=await this.safeParseJson(r);return this.isDeleteSuccessPayload(o,e.id)?{id:e.id,success:!0,method:"api"}:{id:e.id,success:!1,method:"api",reason:this.toDeleteApiPayloadReason(o)}}catch{return {id:e.id,success:false,method:"api",reason:ng}}}buildDeleteHeaders(e){const t=this.parseJwtPayload(e),n={accept:"*/*",authorization:`Bearer ${e}`,"connect-protocol-version":"1","content-type":"application/json","x-language":this.getClientLanguage(),"r-timezone":this.getClientTimezone(),"x-msh-platform":"web","x-msh-version":"1.0.0"},r="string"==typeof t.device_id?t.device_id.trim():"",o="string"==typeof t.ssid?t.ssid.trim():"",i="string"==typeof t.sub?t.sub.trim():"";return r&&(n["x-msh-device-id"]=r),o&&(n["x-msh-session-id"]=o),i&&(n["x-traffic-id"]=i),n}getAuthToken(){const e=this.getCookieToken(Oh);if(e)return e;const t=this.findAuthTokenInStorage(localStorage);if(t)return t;try{const e=this.findAuthTokenInStorage(sessionStorage);if(e)return e}catch{}return null}getCookieToken(e){const t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=document.cookie.match(new RegExp(`(?:^|;\\s*)${t}=([^;]*)`));return n?.[1]?this.extractTokenFromRaw(n[1]):null}findAuthTokenInStorage(e){for(const t of zh){const n=e.getItem(t),r=this.extractTokenFromRaw(n);if(r)return r}for(let t=0;t6||null==e)return null;if("string"==typeof e)return this.extractTokenFromRaw(e);if(Array.isArray(e)){for(const r of e){const e=this.findTokenInUnknown(r,t+1,n);if(e)return e}return null}if("object"!=typeof e)return null;if(n.has(e))return null;n.add(e);const r=e;for(const o of Fh){if(!(o in r))continue;const e=this.findTokenInUnknown(r[o],t+1,n);if(e)return e}for(const[o,i]of Object.entries(r)){if(Fh.includes(o)||t>0&&!$h.test(o)&&"object"!=typeof i)continue;const e=this.findTokenInUnknown(i,t+1,n);if(e)return e}return null}logMissingDeleteTokenOnce(){this.loggedMissingDeleteToken||(this.loggedMissingDeleteToken=true,console.warn("[KimiAdapter] DeleteChat skipped: auth token not found in cookie/storage."));}parseJwtPayload(e){try{const t=e.split(".");if(t.length<2)return {};const n=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=n.padEnd(4*Math.ceil(n.length/4),"="),o=atob(r),i=JSON.parse(o);return i&&"object"==typeof i?i:{}}catch{return {}}}getClientLanguage(){return document.documentElement.lang||navigator.language||"en-US"}getClientTimezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch{return "UTC"}}isDeleteSuccessPayload(e,t){if(!e||"object"!=typeof e)return false;const n=e,r=n.chatId,o=n.chat_id;return r===t||o===t}toDeleteApiPayloadReason(e){if(!e||"object"!=typeof e)return rg;const t=e,n="string"==typeof t.message&&t.message.trim()||"string"==typeof t.msg&&t.msg.trim()||"string"==typeof t.error&&t.error.trim()||"";return n?`${og}:${n}`:og}toDeleteApiHttpReason(e){switch(e){case 401:case 403:return "delete_api_unauthorized";case 404:return "delete_api_not_found";case 429:return "delete_api_rate_limited";default:return `delete_api_http_${e||0}`}}async safeParseJson(e){try{return await e.json()}catch{return null}}scheduleReloadAfterBatchDelete(){this.deleteReloadScheduled||(this.deleteReloadScheduled=true,window.setTimeout(()=>{window.location.reload();},120));}navigateToHomeAfterDelete(){const e=window.location.pathname;"/"!==e&&""!==e?window.location.href=this.getNewTabUrl():this.scheduleReloadAfterBatchDelete();}extractConversationInfo(e,t){const n=e.getAttribute("href")||"",r=this.extractConversationIdFromHref(n);if(!r)return null;return {id:r,cid:t,title:this.extractConversationTitle(e),url:`https://www.kimi.com/chat/${r}`,isActive:e.classList.contains("router-link-active")||e.classList.contains("router-link-exact-active"),isPinned:!!e.querySelector("svg.pinned, .pinned")}}extractConversationTitle(e){const t=e.querySelector(Vh)?.textContent?.trim()||e.querySelector(Gh)?.textContent?.trim()||"";if(t)return t;const n=e.textContent?.replace(/\s+/g," ").trim()||"";return n.length>120?`${n.slice(0,120)}...`:n}extractConversationIdFromHref(e){if(!e)return null;try{const t=new URL(e,window.location.origin).pathname.match(qh);return t?t[1]:null}catch{return null}}findScrollableParent(e){let t=e;for(;t&&t!==document.body;){const e=window.getComputedStyle(t);if(("auto"===e.overflowY||"scroll"===e.overflowY)&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement;}return null}getActiveConversationLink(){const e=document.querySelector(`${Hh}.router-link-active, ${Hh}.router-link-exact-active`);if(e)return e;const t=window.location.pathname,n=t.endsWith("/")?t.slice(0,-1):t;return n?document.querySelector(`${Hh}[href="${n}"]`):null}isHistoryPath(e=window.location.pathname){return "/chat/history"===e||e.startsWith("/chat/history/")}async openMoreHistoryView(){if(this.isHistoryPath())return;const e=document.querySelector('a.more-history[href*="/chat/history"], a.nav-item.more-history[href*="/chat/history"]');if(!e)return;const t=window.location.pathname,n=document.querySelectorAll(Hh).length;e.click();const r=Date.now()+3e3;for(;Date.now()n)return;await new Promise(e=>setTimeout(e,120));}}async closeMoreHistoryView(){if(!this.isHistoryPath())return;const e=document.querySelector([".header-right .close-button-container",".header-right .close-button",".history .header-right .close-button-container",".history .header-right .close-button"].join(", "));if(!e)return;const t=e.closest(".close-button-container")||e;if(this.simulateClick(t),!(await this.waitForHistoryClosed(900))&&(t.click(),!(await this.waitForHistoryClosed(1200)))){try{window.history.back();}catch{}await this.waitForHistoryClosed(1500);}}async waitForHistoryClosed(e){const t=Date.now()+e;for(;Date.now()setTimeout(e,80));}return !this.isHistoryPath()}cacheFullListSnapshot(e){e.length&&(this.fullListSnapshot=e.map(e=>({...e})),this.fullListSnapshotExpiresAt=Date.now()+15e3,this.fullListSnapshotUsesLeft=6);}getFreshFullListSnapshot(){if(!this.fullListSnapshot.length)return [];const e=Date.now()>this.fullListSnapshotExpiresAt,t=this.fullListSnapshotUsesLeft<=0;return e||t?(this.fullListSnapshot=[],this.fullListSnapshotExpiresAt=0,this.fullListSnapshotUsesLeft=0,[]):this.fullListSnapshot.map(e=>({...e}))}mergeConversationInfos(...e){const t=new Map;return e.forEach(e=>{e.forEach(e=>{const n=t.get(e.id);n?t.set(e.id,{...n,title:n.title||e.title,isActive:n.isActive||e.isActive,isPinned:n.isPinned||e.isPinned}):t.set(e.id,e);});}),Array.from(t.values())}selectEditorAll(e){const t=window.getSelection();if(!t)return;const n=document.createRange();n.selectNodeContents(e),t.removeAllRanges(),t.addRange(n);}insertByExecCommand(e,t){try{this.selectEditorAll(e);if(document.execCommand("insertText",!1,t))return !0}catch{}return false}insertByPasteEvent(e,t){try{if("undefined"==typeof DataTransfer)return !1;const n=e.textContent||"",r=new DataTransfer;r.setData("text/plain",t);if(!e.dispatchEvent(new ClipboardEvent("paste",{clipboardData:r,bubbles:!0,cancelable:!0,composed:!0})))return !0;return (e.textContent||"")!==n||0===t.length}catch{return false}}clearByExecCommand(e){try{return this.selectEditorAll(e),document.execCommand("delete",!1,void 0)}catch{return false}}getChatItems(e){const t=Array.from(e.querySelectorAll(Kh)).filter(e=>!e.parentElement?.closest(Kh));return t.length>0?t:Array.from(e.children).filter(e=>e.matches(Zh)||e.matches(Yh)||null!==e.querySelector(Jh)||null!==e.querySelector(Xh))}findNextAssistantMarkdown(e,t){for(let n=t+1;nt.id===e);if(t?.title)return t.title;this.refreshConversationSnapshot();}return this.getSessionName()}getConversationList(){const e=this.collectConversationListFromDom(),t=this.getFreshConversationSnapshot();return 0===e.length?(0===t.length&&this.refreshConversationSnapshot(),t):0===t.length?(this.refreshConversationSnapshot(),e):this.mergeConversationInfos(t,e)}getConversationObserverConfig(){return {selector:Cg,shadow:false,extractInfo:e=>this.extractSidebarConversationInfo(e,this.getCurrentCid()||void 0),getTitleElement:e=>e.querySelector(Eg)||e}}getSidebarScrollContainer(){return document.querySelector(`${kg} ${Sg}`)||document.querySelector(Sg)||document.querySelector(kg)}async loadAllConversations(){await this.refreshConversationSnapshot({force:true,fetchAllPages:true});}navigateToConversation(e,t){const n=this.getCurrentCid()||void 0,r=document.querySelectorAll(Cg);for(const o of Array.from(r)){const t=this.extractSidebarConversationInfo(o,n);if(!t||t.id!==e)continue;const r=o.querySelector("a, button, [role='button']")||o;return this.simulateClick(r),true}return super.navigateToConversation(e,t||`https://chat.qwen.ai/c/${e}`)}getTextareaSelectors(){return ["textarea.message-input-textarea","textarea"]}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus();const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),t.setSelectionRange(e.length,e.length),true}clearTextarea(){const e=this.getTextareaElement();if(!e||!e.isConnected)return;const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),e.dispatchEvent(new Event("change",{bubbles:true})),e.setSelectionRange(0,0);}getSubmitButtonSelectors(){return [`${Lg}:not([disabled])`]}findSubmitButton(){const e=document.querySelector(Lg);return this.isVisibleActionElement(e)?e.hasAttribute("disabled")||this.isStopLikeButton(e)?null:e:null}getNewChatButtonSelectors(){return [".sidebar-entry-fixed-list-content"]}getScrollContainer(){const e=document.querySelector(_g);return e instanceof HTMLElement?e:null}getResponseContainerSelector(){return Ag}getAssistantMermaidSupportMode(){return "native"}getChatContentSelectors(){return [Tg,Mg]}getUserQuerySelector(){return Tg}getLatestReplyText(){const e=document.querySelectorAll(Mg),t=e[e.length-1];return t?this.extractAssistantResponseText(t):null}extractUserQueryText(e){const t=this.findUserContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown, button, [role='button'], svg, [aria-hidden='true']").forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}replaceUserQueryContent(e,t){const n=this.findUserContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e),n.style.display="none";}return n.after(r),true}extractAssistantResponseText(e){const t=this.findAssistantContentRoot(e);if(!t)return "";const n=this.shouldIncludeThoughtsInExport(),r=n?this.getThoughtBlocksForElement(e):[],o=t.cloneNode(true);this.normalizeQwenCodeBlocks(o),o.querySelectorAll(`${Og}, ${Fg}, button, [role='button'], svg, [aria-hidden='true']`).forEach(e=>e.remove());const i=(Uo(o)||this.extractTextWithLineBreaks(o)).trim();if(n&&r.length>0){const e=r.join("\n\n");return i?`${e}\n\n${i}`:e}return i}getLastCodeBlockText(){const e=document.querySelectorAll(Mg);for(let t=e.length-1;t>=0;t-=1){const n=this.findAssistantContentRoot(e[t]);if(!n)continue;const r=Array.from(n.querySelectorAll(Rg));for(let e=r.length-1;e>=0;e-=1){const t=this.extractQwenCodeBlockText(r[e]);if(t)return t}}return super.getLastCodeBlockText()}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector(Ag)||document.querySelector(_g);if(!o)return r;const i=Array.from(o.querySelectorAll(`${Tg}, ${Mg}`)).filter(e=>!e.closest(".gh-root"));return i.forEach((o,a)=>{if(o.matches(Tg)){if(!t)return;const e=this.extractUserQueryText(o);if(!e)return;let s;if(n){const e=i.slice(a+1).find(e=>e.matches(Mg));s=e?this.extractAssistantPlainText(e).length:0;}return void r.push({level:0,text:this.truncateText(e,80),element:o,isUserQuery:true,isTruncated:e.length>80,wordCount:s})}const s=Array.from(o.querySelectorAll("h1, h2, h3, h4, h5, h6")).filter(e=>!e.closest(Og)&&!this.isInRenderedMarkdownContainer(e));s.forEach((t,i)=>{const a=parseInt(t.tagName[1],10);if(a>e)return;const l=t.textContent?.trim()||"";if(!l)return;let c;if(n){let e=null;for(let t=i+1;t!e.closest(".gh-root"));for(const r of n)await this.captureThoughtBlocksForMessage(r);return {shouldCloseThoughtPanel:!t&&null!==this.getVisibleThoughtPanel()}}async restoreConversationAfterExport(e,t){try{this.parseThoughtExportState(t)?.shouldCloseThoughtPanel&&await this.closeThoughtPanelIfNeeded(),await this.restoreMermaidBlocksAfterExport();}finally{this.exportIncludeThoughtsOverride=null,this.clearThoughtExportCache();}}async toggleTheme(e){try{const t=this.resolveThemeMode(e);return !!(await this.updateThemePreference(e))&&(this.syncThemeState(t,e),!0)}catch(t){return console.error("[QwenAiAdapter] toggleTheme error:",t),false}}getModelName(){const e=document.querySelector($g),t=e?.innerText?.trim()||e?.textContent?.trim()||"";return t?t.split("\n")[0].trim():null}getModelLockCheckText(e){return this.getModelName()||super.getModelLockCheckText(e)}clickModelSelector(){const e=this.findModelTrigger();return !!e&&(this.simulateClick(e),true)}lockModel(e,t){const n=this.normalizeModelKeyword(e);if(!n)return;let r=0;const o=async()=>{r++;const i=this.findModelTrigger();if(!i)return r>=12?void this.showQwenModelLockFailure(e,"button_not_found"):void window.setTimeout(o,1e3);if(this.normalizeModelKeyword(this.getModelLockCheckText(i)).includes(n))return void t?.();const a=await this.selectQwenModel(n);a.success?t?.():this.showQwenModelLockFailure(e,a.reason||"not_found");};o();}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:[jg,$g],menuItemSelector:Vg,checkInterval:1e3,maxAttempts:12,menuRenderDelay:400,subMenuSelector:Wg,subMenuTriggers:["展开更多模型","更多模型","view more","more models"]}}isGenerating(){return null!==this.findStopButton()}getStopButtonSelectors(){return [...Dg]}stopGeneration(){const e=this.findStopButton();return !!e&&(this.simulateClick(e),true)}getNetworkMonitorConfig(){return {urlPatterns:["/api/v2/chat/completions"],urlPathEndsWith:["/chat/completions"],silenceThreshold:2e3}}getWidthSelectors(){return [{selector:".qwen-chat-message",property:"max-width",extraCss:"width: 100% !important; box-sizing: border-box !important;"}]}getUserQueryWidthSelectors(){return [{selector:".chat-user-message-container .chat-user-message-wrapper .chat-user-message",property:"max-width",noCenter:true}]}getZenModeSelectors(){return [{selector:kg,action:"hide"},{selector:".chat-container-statement",action:"hide"}]}getMarkdownFixerConfig(){return {selector:`${Mg} .qwen-markdown-paragraph`,fixSpanContent:false,shouldSkip:e=>{if(!this.isGenerating())return false;const t=e.closest(Mg);if(!t)return false;const n=document.querySelectorAll(Mg);return t===n[n.length-1]}}}getFreshConversationSnapshot(){return this.conversationSnapshot.length>0&&Date.now()-this.conversationSnapshotFetchedAt<3e4||this.conversationSnapshotPromise||this.refreshConversationSnapshot(),this.conversationSnapshot.map(e=>({...e}))}async refreshConversationSnapshot(e={}){const{force:t=false,fetchAllPages:n=false}=e,r=this.conversationSnapshot.length>0&&Date.now()-this.conversationSnapshotFetchedAt<3e4;return !t&&r?this.conversationSnapshot.map(e=>({...e})):(this.conversationSnapshotPromise||(this.conversationSnapshotPromise=(async()=>{try{const e=await this.fetchConversationSnapshot(n);e.length>0&&(this.conversationSnapshot=e,this.conversationSnapshotFetchedAt=Date.now());}catch(e){console.warn("[QwenAiAdapter] Failed to refresh conversation snapshot:",e);}finally{this.conversationSnapshotPromise=null;}return this.conversationSnapshot.map(e=>({...e}))})()),this.conversationSnapshotPromise)}async fetchConversationSnapshot(e){const t=this.getSessionId(),n=e?100:5,r=[],o=new Set;for(let i=1;i<=n;i++){const n=await this.fetchConversationPage(i);if(0===n.length)break;let a=0;for(const e of n)o.has(e.id)||(o.add(e.id),r.push(e),a++);if(0===a)break;if(!e&&t&&o.has(t))break}return r}async fetchConversationPage(e){const t=new URL("/api/v2/chats/",window.location.origin);t.searchParams.set("page",String(e)),t.searchParams.set("exclude_project","true");const n=await fetch(t.toString(),{method:"GET",credentials:"include",cache:"no-store",headers:{Accept:"application/json, text/plain, */*","X-Request-Id":crypto.randomUUID(),source:"web"}});if(!n.ok)throw new Error(`fetch conversations failed: ${n.status}`);const r=await n.json();if(false===r.success)return [];const o=Array.isArray(r.data)?r.data:[],i=this.getCurrentCid()||void 0,a=[];return o.forEach(e=>{const t=this.normalizeConversationApiItem(e,i);t&&a.push(t);}),a}normalizeConversationApiItem(e,t){if(!e||"object"!=typeof e)return null;const n=e,r="string"==typeof n.id?n.id.trim():"",o="string"==typeof n.title?n.title.trim():"";return r&&o?{id:r,cid:t,title:o,url:`https://chat.qwen.ai/c/${r}`,isPinned:Boolean(n.pinned),isActive:r===this.getSessionId()}:null}collectConversationListFromDom(){const e=document.querySelectorAll(Cg);if(0===e.length)return [];const t=this.getCurrentCid()||void 0,n=[];return e.forEach(e=>{const r=this.extractSidebarConversationInfo(e,t);r&&n.push(r);}),n}extractSidebarConversationInfo(e,t){const n=this.extractConversationIdFromElement(e);if(!n)return null;const r=e.querySelector(Eg),o=r?.textContent?.trim()||"";return o?{id:n,cid:t,title:o,url:`https://chat.qwen.ai/c/${n}`,isPinned:!!e.querySelector(".chat-item-title-pined-icon"),isActive:n===this.getSessionId()}:null}extractConversationIdFromElement(e){const t=e.querySelector('a[href*="/c/"]'),n=t?.getAttribute("href"),r=this.extractConversationIdFromText(n);if(r)return r;const o=[e,...Array.from(e.querySelectorAll("*"))];for(const i of o){const e=i.getAttributeNames?.()||[];for(const t of e){const e=i.getAttribute(t),n=this.extractConversationIdFromText(e);if(n)return n}}return null}extractConversationIdFromText(e){if(!e)return null;const t=e.match(wg);if(t?.[1])return t[1];const n=e.match(/\b[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\b/i);return n?.[0]||null}mergeConversationInfos(...e){const t=new Map;for(const n of e)for(const e of n){const n=t.get(e.id);t.set(e.id,{...n,...e});}return Array.from(t.values())}normalizeQwenCodeBlocks(e){Array.from(e.querySelectorAll(Rg)).forEach(e=>{const t=this.extractQwenCodeBlockText(e);if(!t)return;const n=this.extractQwenCodeLanguage(e),r=document.createElement("pre"),o=document.createElement("code");n&&(o.className=`language-${n}`),o.textContent=t,r.appendChild(o),e.replaceWith(r);});}extractQwenCodeBlockText(e){const t=this.extractQwenMermaidSource(e);if(t)return t;const n=Array.from(e.querySelectorAll(".view-lines .view-line")).map(e=>this.normalizeQwenCodeLineText(e.textContent||"")).filter((e,t,n)=>!(t===n.length-1&&""===e&&n.length>1));if(n.length>0){const e=n.join("\n").replace(/\n+$/,"");return e.trim()?e:null}const r=e.querySelector(".qwen-markdown-code-body")||e.querySelector("[data-mode-id]")||e,o=this.normalizeQwenCodeLineText(r.textContent||"");return o.trim()?o:null}extractQwenMermaidSource(e){if(!this.isQwenMermaidCodeBlock(e))return null;const t=[],n=e=>{e&&(t.includes(e)||t.push(e));},r=e.querySelector(".qwen-markdown-code-body.mermaid");n(r),Array.from(e.querySelectorAll(".qwen-markdown-code-body.mermaid > div")).forEach(e=>n(e)),Array.from(e.querySelectorAll("[data-mode-id='mermaid']")).forEach(e=>n(e));let o=null;for(const i of t){const e=this.extractQwenCodeLinesFromRoot(i);e&&((!o||e.length>o.length)&&(o=e));}return o}isQwenMermaidCodeBlock(e){if("mermaid"===this.extractQwenCodeHeaderLabel(e).toLowerCase())return true;const t=e.querySelector(".qwen-markdown-code-body");return !!t?.classList.contains("mermaid")||null!==e.querySelector(".qwen-markdown-mermaid-chart-wrapper")}extractQwenCodeLanguage(e){const t=this.extractQwenCodeHeaderLabel(e).toLowerCase();if(t)return t;const n=e.querySelector(".qwen-markdown-code-body");if(!n)return "";const r=Array.from(n.classList).find(e=>"qwen-markdown-code-body"!==e&&!["monaco","editor","body"].includes(e.toLowerCase()));return r?.trim().toLowerCase()||""}extractQwenCodeHeaderLabel(e){const t=e.querySelector(".qwen-markdown-code-header");if(!t)return "";const n=Array.from(t.children);for(const o of n){if(!(o instanceof HTMLElement))continue;if(o.classList.contains("qwen-markdown-code-header-actions"))continue;const e=o.textContent?.trim()||"";if(e)return e}const r=t.firstElementChild;return r?.textContent?.trim()||""}extractQwenCodeLinesFromRoot(e){const t=Array.from(e.querySelectorAll(".view-lines .view-line"));if(0===t.length)return null;const n=t.map(e=>this.normalizeQwenCodeLineText(e.textContent||"")).filter((e,t,n)=>!(t===n.length-1&&""===e&&n.length>1));if(0===n.length)return null;const r=n.join("\n").replace(/\n+$/,"");return r.trim()?r:null}normalizeQwenCodeLineText(e){return e.replace(/\u00a0/g," ").replace(/\u200b/g,"").replace(/\r\n/g,"\n").replace(/\n/g,"").replace(/\s+$/g,"")}shouldIncludeThoughtsInExport(){return "boolean"==typeof this.exportIncludeThoughtsOverride&&this.exportIncludeThoughtsOverride}getThoughtBlocksForElement(e){const t=e.closest(Mg);return this.exportThoughtBlocks.get(e)||(t?this.exportThoughtBlocks.get(t):void 0)||[]}clearThoughtExportCache(){this.exportThoughtBlocks=new WeakMap;}async prepareMermaidBlocksForExport(){this.clearMermaidExportMarkers();const e=Array.from(document.querySelectorAll(Rg)).filter(e=>this.isQwenMermaidCodeBlock(e));for(const t of e){if(!(t instanceof HTMLElement))continue;const e=this.getQwenMermaidActiveView(t),n=this.findQwenMermaidViewTab(t,"code"),r=this.findQwenMermaidViewTab(t,"preview");if("code"!==e&&n){try{n.scrollIntoView({block:"center",behavior:"auto"});}catch{}this.simulateClick(n);}let o=await this.waitForMermaidCodeViewReady(t);!o&&"code"===e&&r&&n&&(this.simulateClick(r),await this.sleep(100),this.simulateClick(n),o=await this.waitForMermaidCodeViewReady(t)),o&&"code"!==e&&t.setAttribute(Bg,"true");}}async restoreMermaidBlocksAfterExport(){const e=Array.from(document.querySelectorAll(`${Rg}[${Bg}]`));for(const t of e){if(!(t instanceof HTMLElement))continue;const e=this.findQwenMermaidViewTab(t,"preview");e&&"preview"!==this.getQwenMermaidActiveView(t)&&(this.simulateClick(e),await this.sleep(80)),t.removeAttribute(Bg);}}clearMermaidExportMarkers(){document.querySelectorAll(`${Rg}[${Bg}]`).forEach(e=>e.removeAttribute(Bg));}getQwenMermaidActiveView(e){const t=e.querySelector(qg);if(!(t instanceof HTMLElement))return null;const n=Array.from(t.querySelectorAll(Pg));for(const r of n){if(!(r instanceof HTMLElement))continue;const e=r.textContent?.trim().toLowerCase()||"";if(e&&r.className.includes("switch-active")){if(e.includes("code"))return "code";if(e.includes("preview"))return "preview"}}return null}findQwenMermaidViewTab(e,t){const n=e.querySelector(qg);if(!(n instanceof HTMLElement))return null;const r=Array.from(n.querySelectorAll(Pg));for(const o of r){if(!(o instanceof HTMLElement))continue;if((o.textContent?.trim().toLowerCase()||"").includes(t))return o}return null}async waitForMermaidCodeViewReady(e,t=2200){const n=Date.now();let r="",o=0;const i=this.getQwenMermaidExpectedLineCount(e);for(;Date.now()-nr.length?(r=t,o=0):t.length>0&&(o+=1);const n=r?r.split("\n").length:0;if((i>1?n>=i:n>0)&&o>=2)return true}await this.sleep(80);}const a=r?r.split("\n").length:0;return i>1?a>=i:r.length>0}getQwenMermaidExpectedLineCount(e){const t=Array.from(e.querySelectorAll(".margin-view-overlays .line-numbers")).map(e=>parseInt(e.textContent?.trim()||"",10)).filter(e=>Number.isFinite(e)&&e>0);return 0===t.length?0:Math.max(...t)}parseThoughtExportState(e){if(!e||"object"!=typeof e)return null;return {shouldCloseThoughtPanel:Boolean(e.shouldCloseThoughtPanel)}}async captureThoughtBlocksForMessage(e){const t=this.findThoughtTriggerForMessage(e);if(!t)return;const n=this.getThoughtPanelSignature();try{t.scrollIntoView({block:"center",behavior:"auto"});}catch{}this.simulateClick(t);const r=await this.waitForThoughtPanelUpdate(n);if(!r)return;const o=this.extractThoughtBlockquotesFromPanel(r);o.length>0&&this.exportThoughtBlocks.set(e,o),await this.sleep(60);}findThoughtTriggerForMessage(e){const t=Array.from(e.querySelectorAll(".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"));for(const n of t){if(!(n instanceof HTMLElement))continue;if(!this.isQwenElementVisible(n))continue;const e=n.querySelector(zg)?.textContent?.trim()||n.textContent?.trim()||"";if(e&&/已.*完成思考|已经完成思考/i.test(e))return n}return null}getVisibleThoughtPanel(){const e=document.querySelector(".splitter-container-right-panel .qwen-chat-thinking-and-sources");return this.isQwenElementVisible(e)?e:null}getThoughtPanelSignature(e){const t=e||this.getVisibleThoughtPanel();if(!t)return null;const n=Array.from(t.querySelectorAll("[data-phase-id]")).map(e=>e.getAttribute("data-phase-id")?.trim()||"").filter(Boolean);if(n.length>0)return n.join("|");const r=this.extractThoughtBlockquotesFromPanel(t);return 0===r.length?null:r.join("\n\n")}async waitForThoughtPanelUpdate(e,t=2200){const n=Date.now();for(;Date.now()-ne.remove());const i=(Uo(n)||this.extractTextWithLineBreaks(n)).trim();i&&r.push(this.formatAsThoughtBlockquote(i,t));}return r}formatAsThoughtBlockquote(e,t){const n=e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">"),r=(t||"").trim();return ["> [Thoughts]",...r&&!/已.*完成思考|已经完成思考/i.test(r)?[`> **${r}**`,">"]:[],...n].join("\n")}async closeThoughtPanelIfNeeded(e=1500){const t=this.getVisibleThoughtPanel();if(!t)return;const n=t.querySelector(".qwen-chat-thinking-and-sources-header .anticon, .qwen-chat-thinking-and-sources-header [role='img']");if(!n||!this.isQwenElementVisible(n))return;this.simulateClick(n);const r=Date.now();for(;Date.now()-r [class*="model-item___"]')).filter(e=>e instanceof HTMLElement&&this.isQwenElementVisible(e))}findBestQwenModelItem(e,t){const n=this.normalizeModelKeyword(t);if(!n)return null;for(const r of e){if(this.normalizeModelKeyword(this.getQwenModelItemName(r))===n)return r}for(const r of e){if(this.normalizeModelKeyword(this.getQwenModelItemName(r)).endsWith(n))return r}for(const r of e){if(this.normalizeModelKeyword(this.getQwenModelItemName(r)).includes(n))return r}return null}getQwenModelItemName(e){return ((e.querySelector('[class*="model-item-name"] > span')||e.querySelector('[class*="model-item-name"]')||e).textContent||"").trim()}findQwenMoreTrigger(e){const t=e.querySelector(Wg);return t instanceof HTMLElement&&this.isQwenElementVisible(t)?t:null}async openQwenMoreMenu(e){const t=[e];[e.querySelector('[class*="view-more___"]'),e.querySelector('[class*="view-more-text"]'),e.querySelector('[class*="view-more-icon"]')].forEach(e=>{e instanceof HTMLElement&&!t.includes(e)&&t.push(e);});for(const n of t){this.dispatchQwenMoreMenuHover(n);let t=await this.waitForVisibleQwenSecondaryPopup(e,3,100);if(t)return t;if(this.simulateClick(n),t=await this.waitForVisibleQwenSecondaryPopup(e,4,120),t)return t}return this.waitForVisibleQwenSecondaryPopup(e,4,150)}async waitForVisibleQwenSecondaryPopup(e,t=8,n=150){for(let r=0;r{try{if(t.startsWith("pointer")&&"undefined"!=typeof PointerEvent)return void e.dispatchEvent(new PointerEvent(t,{...n,pointerType:"mouse",isPrimary:!0}));e.dispatchEvent(new MouseEvent(t,n));}catch{}});}clickQwenModelItem(e){this.simulateClick(e),window.setTimeout(()=>{document.body.click();},100);}normalizeModelKeyword(e){return (e||"").toLowerCase().replace(/\s+/g," ").trim()}isQwenElementVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===parseFloat(t.opacity||"1"))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}sleep(e){return new Promise(t=>window.setTimeout(t,e))}async showQwenModelLockFailure(e,t){try{const{showToast:n}=await r(async()=>{const{showToast:e}=await Promise.resolve().then(()=>Fo);return {showToast:e}},void 0),{t:o}=await r(async()=>{const{t:e}=await Promise.resolve().then(()=>ie);return {t:e}},void 0);let i;switch(t){case "button_not_found":i=o("modelLockFailedNoButton")||"模型选择器未找到";break;case "menu_empty":i=o("modelLockFailedMenuEmpty")||"模型菜单加载失败";break;default:i=(o("modelLockFailedNotFound")||'未找到模型 "{model}"').replace("{model}",e);}n(i,3e3);}catch(n){console.error("[QwenAiAdapter] Failed to show model lock error:",n);}}readCookieValue(e){const t=new RegExp(`(?:^|; )${e}=([^;]+)`),n=document.cookie.match(t);if(!n?.[1])return null;try{return decodeURIComponent(n[1]).trim()||null}catch{return n[1].trim()||null}}extractUidFromToken(e){if(!e)return null;try{const t=e.split(".")[1];if(!t)return null;const n=t.replace(/-/g,"+").replace(/_/g,"/"),r=atob(n.padEnd(4*Math.ceil(n.length/4),"=")),o=JSON.parse(r).id;return "string"==typeof o&&o.trim()?o.trim():null}catch{return null}}findUserContentRoot(e){return e.matches(Ig)?e:e.querySelector(Ig)||e}findAssistantContentRoot(e){return e.matches(Ng)?e:e.querySelector(Ng)||e}extractAssistantPlainText(e){const t=this.findAssistantContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return this.normalizeQwenCodeBlocks(n),n.querySelectorAll(`${Og}, ${Fg}, button, [role='button'], svg, [aria-hidden='true']`).forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}findModelTrigger(){const e=document.querySelector(jg);if(e instanceof HTMLElement&&this.isVisibleActionElement(e))return e;const t=document.querySelector($g);if(!t)return null;const n=t.closest(".ant-dropdown-trigger, [role='button'], button, [tabindex]");return n instanceof HTMLElement?n:t}isStopLikeButton(e){if(!e)return false;const t=e.querySelector("use"),n=t?.getAttribute("xlink:href")||t?.getAttribute("href")||"",r=(e.innerText||e.textContent||"").trim().toLowerCase();return /stop/i.test(n)||r.includes("stop")||r.includes("停止")}findStopButton(){const e=this.findVisibleElementBySelectors(this.getStopButtonSelectors());if(e&&!this.isDisabledActionElement(e))return e;const t=document.querySelector(Lg);return this.isVisibleActionElement(t)&&!this.isDisabledActionElement(t)&&this.isStopLikeButton(t)?t:null}isVisibleActionElement(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}isDisabledActionElement(e){return !(e instanceof HTMLElement)||(e.hasAttribute("disabled")||"true"===e.getAttribute("aria-disabled")||/\bdisabled\b/i.test(e.className||""))}truncateText(e,t){return e.length>t?`${e.slice(0,t)}...`:e}},new class extends ci{exportIncludeThoughts=void 0;match(){const e=window.location.hostname;return "www.qianwen.com"===e||"qianwen.com"===e}getSiteId(){return Fr}getName(){return "Qianwen"}getThemeColors(){return {primary:"#615ced",secondary:"#4b45c0"}}getNativeThemeCss(){return "\n/* =============================================\n * Qianwen (通义千问) 站点原生主题适配器 (Qianwen Theme Adapter)\n * ============================================= */\nbody {\n /* 主要背景 */\n --color-canvas-default: var(--gh-bg) !important;\n\n /* 次要/浮动层背景 (混入极低浓度主题色) */\n --color-canvas-subtle: color-mix(in srgb, var(--gh-primary) 2%, var(--gh-bg)) !important;\n\n /* 代码块与表格背景 */\n --color-inline-code-bg: var(--gh-bg-tertiary) !important;\n --color-table-head-th-bg: var(--gh-bg-secondary) !important;\n\n /* 边框体系 */\n --color-border-muted: color-mix(in srgb, var(--gh-primary) 10%, transparent) !important;\n --color-table-border: color-mix(in srgb, var(--gh-primary) 10%, transparent) !important;\n --color-table-row-border: color-mix(in srgb, var(--gh-primary) 10%, transparent) !important;\n --color-border-default: color-mix(in srgb, var(--gh-primary) 15%, transparent) !important;\n\n /* 主色调/链接色 */\n --color-link: var(--gh-primary) !important;\n --color-link-border: var(--gh-primary) !important;\n --color-qk-link-border: var(--gh-primary) !important;\n}\n"}getSessionId(){const e=window.location.pathname.match(ig);return e?.[1]||super.getSessionId()}isNewConversation(){const e=window.location.pathname.replace(/\/+$/,"")||"/";return "/"===e||"/chat"===e}isSharePage(){return window.location.pathname.startsWith("/share/")}getCurrentCid(){const e=localStorage.getItem("qianwen-uniq-id");if(!e)return null;try{const t=JSON.parse(e);if("string"==typeof t&&t.trim())return t.trim();if(t&&"object"==typeof t)for(const e of ["uid","id","cid","userId"]){const n=t[e];if("string"==typeof n&&n.trim())return n.trim()}}catch{}return e.trim()||null}getSessionName(){const e=document.title.trim();if(!e)return null;const t=e.replace(/\s*[-|]\s*通义千问$/i,"").replace(/\s*[-|]\s*Qwen$/i,"").replace(/\s*[-|]\s*Qianwen$/i,"").trim();return !t||/^(通义千问|Qwen|Qianwen)$/i.test(t)?null:t}getNewTabUrl(){return "https://www.qianwen.com"}getCurrentConversationInfo(){return ag.test(window.location.pathname)?null:super.getCurrentConversationInfo()}getConversationTitle(){return this.getSessionName()}getTextareaSelectors(){return ['[class*="chatTextarea"]',`${hg} [contenteditable="true"]`,'[data-slate-editor="true"][contenteditable="true"]','div[role="textbox"][contenteditable="true"]',"textarea"]}isValidTextarea(e){return !!super.isValidTextarea(e)&&(!e.closest(fg)&&(!!(e.isContentEditable||e instanceof HTMLTextAreaElement)&&!(!e.closest(hg)&&!e.matches('[data-slate-editor="true"]'))))}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;if(t.focus(),t instanceof HTMLTextAreaElement||t instanceof HTMLInputElement){const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),true}try{if(document.execCommand("selectAll",!1),document.execCommand("insertText",!1,e))return t.dispatchEvent(new InputEvent("input",{bubbles:!0,composed:!0,data:e,inputType:"insertText"})),!0}catch{}return t.textContent=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e,inputType:"insertText"})),t.dispatchEvent(new Event("change",{bubbles:true})),true}clearTextarea(){const e=this.getTextareaElement();if(e&&e.isConnected){if(e.focus(),e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement){const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),void e.dispatchEvent(new Event("change",{bubbles:true}))}try{document.execCommand("selectAll",!1),document.execCommand("delete",!1);}catch{}e.textContent="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:"",inputType:"deleteContentBackward"})),e.dispatchEvent(new Event("change",{bubbles:true}));}}getSubmitButtonSelectors(){return ['[class*="operateBtn"]','[data-icon-type="qwpcicon-sendChat"]',"button[type='submit']"]}findSubmitButton(e){const t=[e?.closest(hg),e?.parentElement,e?.closest("div"),document.body].filter(Boolean);for(const n of t){const e=n.querySelectorAll('[class*="operateBtn"], [data-icon-type="qwpcicon-sendChat"]');for(const t of Array.from(e)){const e=t.closest('[class*="operateBtn"], button, [role="button"]');if(e&&this.isVisibleElement(e)&&!this.isDisabledActionButton(e))return e}}return super.findSubmitButton(e)}getNewChatButtonSelectors(){return ['[class*="newChatButton"]']}getScrollContainer(){const e=[gg,pg];for(const r of e){const e=document.querySelectorAll(r);for(const t of Array.from(e)){const e=t;if(e.scrollHeight>e.clientHeight)return e}}const t=document.querySelector(pg);if(!t)return null;let n=t;for(;n&&n!==document.body;){if(n.scrollHeight>n.clientHeight)return n;n=n.parentElement;}return null}getResponseContainerSelector(){return `${pg}, ${gg}`}getChatContentSelectors(){return [cg,dg]}getUserQuerySelector(){return cg}getLatestReplyText(){const e=document.querySelectorAll(dg),t=e[e.length-1];return t?this.extractAssistantResponseText(t):null}extractUserQueryText(e){const t=this.findUserQueryContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown, button, [role='button'], svg, [aria-hidden='true']").forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}replaceUserQueryContent(e,t){const n=this.findUserQueryContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e),n.style.display="none";}return n.after(r),true}extractAssistantResponseText(e){const t=e.cloneNode(true);t.querySelectorAll('button, [role="button"], svg, .qk-md-table-action, .qk-md-copy-icon, [aria-hidden="true"], [class*="answerToolsContent"], [class*="functionArea"]').forEach(e=>e.remove());const n=this.shouldIncludeThoughtsInExport();let r=[];n&&(r=this.extractThoughtBlockquotes(t));const o=`${fg}, [class*="thinkingTitle"]`;t.querySelectorAll(o).forEach(e=>e.remove());const i=(Uo(t)||this.extractTextWithLineBreaks(t)).trim();if(n&&r.length>0){const e=r.join("\n\n");return i?`${e}\n\n${i}`:e}return i}async prepareConversationExport(e){return this.exportIncludeThoughts=e.includeThoughts,null}async restoreConversationAfterExport(e,t){this.exportIncludeThoughts=void 0;}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector(pg)||document.querySelector(this.getResponseContainerSelector());if(!o)return r;const i=Array.from(o.querySelectorAll(`${cg}, ${dg}`)).filter(e=>!e.closest(".gh-root"));return i.forEach((o,a)=>{if(o.matches(cg)){if(!t)return;const e=this.extractUserQueryText(o);if(!e)return;let s;if(n){const e=i.slice(a+1).find(e=>e.matches(dg));s=e?this.extractAssistantPlainText(e).length:0;}return void r.push({level:0,text:this.truncateText(e,80),element:o,isUserQuery:true,isTruncated:e.length>80,wordCount:s})}const s=Array.from(o.querySelectorAll("h1, h2, h3, h4, h5, h6")).filter(e=>!e.closest(fg)&&!this.isInRenderedMarkdownContainer(e));s.forEach((t,i)=>{const a=parseInt(t.tagName[1],10);if(a>e)return;const l=t.textContent?.trim()||"";if(!l)return;let c;if(n){let e=null;for(let t=i+1;t{r++;const i=this.findModelSelectorTrigger();if(!i)return void(r<10?setTimeout(o,500):console.warn(`Ophel: Qianwen model selector not found for "${e}".`));if(this.normalizeText(this.getModelName()||"").includes(n))t?.();else {try{localStorage.setItem(lg,"1");}catch{}this.simulateClick(i),setTimeout(async()=>{let i=this.findVisibleModelDialogItems(),a=this.findBestMatchingDialogItem(i,n);!a&&this.expandMoreModels()&&(await new Promise(e=>setTimeout(e,400)),i=this.findVisibleModelDialogItems(),a=this.findBestMatchingDialogItem(i,n)),a?(this.simulateClick(a),setTimeout(()=>{document.body.click(),t?.();},150)):r<10?setTimeout(o,500):(document.body.click(),console.warn(`Ophel: Qianwen model "${e}" not found.`));},300);}};o();}simulateClick(e){const t=["pointerdown","mousedown","pointerup","mouseup","click"];for(const n of t)e.dispatchEvent(new PointerEvent(n,{bubbles:true,cancelable:true,view:window,pointerId:1}));}getWidthSelectors(){return [{selector:'[class*="scrollOutWrapper"]',property:"max-width",extraCss:"width: 100% !important;",noCenter:true},{selector:`${pg}`,property:"max-width",extraCss:"width: 100% !important;",noCenter:true}]}getUserQueryWidthSelectors(){return [{selector:`${cg} ${ug}`,property:"max-width"}]}getZenModeSelectors(){return [{selector:mg,action:"hide"},{selector:"#ice-container .root-G6nVVr",action:"hide"},{selector:'[aria-haspopup="dialog"][aria-controls][data-state]',action:"hide"}]}getMarkdownFixerConfig(){return {selector:`${dg} .qk-md-paragraph`,fixSpanContent:false,shouldSkip:e=>{if(!this.isGenerating())return false;const t=e.closest(dg);if(!t)return false;const n=document.querySelectorAll(dg);return t===n[n.length-1]}}}shouldIncludeThoughtsInExport(){return void 0!==this.exportIncludeThoughts&&this.exportIncludeThoughts}extractThoughtBlockquotes(e){const t=Array.from(e.querySelectorAll('[class*="thinkingContent"]')),n=[];for(const r of t){const e=r.cloneNode(true);e.querySelectorAll('[class*="thinkingTitle"], [class*="thinkingHeader"], .qc-thinking-header, button, svg, [aria-hidden="true"]').forEach(e=>e.remove());const t=(Uo(e)||this.extractTextWithLineBreaks(e)).trim();t&&n.push(this.formatAsThoughtBlockquote(t));}return n}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}extractAssistantPlainText(e){const t=e.cloneNode(true);return t.querySelectorAll(`${fg}, .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"]`).forEach(e=>e.remove()),this.extractTextWithLineBreaks(t).trim()}findUserQueryContentRoot(e){return e.matches(ug)?e:e.querySelector(ug)||e}findModelSelectorTrigger(){return Array.from(document.querySelectorAll('[aria-haspopup="dialog"][aria-controls], [aria-haspopup="dialog"][data-state]')).filter(e=>{const t=e;if(!this.isVisibleElement(t))return false;if(t.closest(mg))return false;if(t.closest(hg))return false;const n=t.getBoundingClientRect(),r=t.innerText?.trim()||t.textContent?.trim()||"";return n.top<180&&n.width>0&&n.height>0&&r.length>0})[0]||null}findVisibleModelDialogItems(){const e=Array.from(document.querySelectorAll(yg)).filter(e=>this.isVisibleElement(e));if(0===e.length)return [];const t=[];return e.forEach(e=>{const n=e.querySelectorAll(vg);for(const r of Array.from(n)){const e=r;this.isVisibleElement(e)&&(e.innerText?.trim()&&t.push(e));}}),t}findBestMatchingDialogItem(e,t){if(0===e.length)return null;const n=this.normalizeText(t);for(const r of e){const e=this.normalizeText(r.innerText||r.textContent||"");if(!e)continue;if(e.split("\n")[0].trim()===n)return r}for(const r of e){if(this.normalizeText(r.innerText||r.textContent||"").split("\n")[0].trim().endsWith(n))return r}for(const r of e){if(this.normalizeText(r.innerText||r.textContent||"").includes(n))return r}return null}expandMoreModels(){const e=Array.from(document.querySelectorAll(yg)).filter(e=>this.isVisibleElement(e));for(const t of e){const e=t.querySelectorAll("button, div, span");for(const t of Array.from(e)){const e=t;if(!this.isVisibleElement(e))continue;const n=this.normalizeText(e.innerText||e.textContent||"");if(n&&((n.includes(this.normalizeText("查看更多模型"))||n.includes(this.normalizeText("view more models"))||n.includes(this.normalizeText("更多模型")))&&!n.includes(this.normalizeText("收起"))&&!n.includes(this.normalizeText("collapse"))))return this.simulateClick(e),true}}return false}truncateText(e,t){return e.length>t?`${e.slice(0,t)}...`:e}normalizeText(e){return (e||"").replace(/\s+/g," ").trim().toLowerCase()}isDisabledActionButton(e){const t=this.getElementClassName(e);return e.hasAttribute("disabled")||"true"===e.getAttribute("aria-disabled")||/disabled/i.test(t)}isVisibleElement(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}getElementClassName(e){return "string"==typeof e.className?e.className:""}},new class extends ci{exportIncludeThoughtsOverride=null;match(){return window.location.hostname===Gg}getSiteId(){return $r}getName(){return "元宝"}getThemeColors(){return {primary:"#1677ff",secondary:"#0b5bd3"}}getTextareaSelectors(){return ['.agent-dialogue__content--common__input .ql-editor[contenteditable="true"], #search-bar .ql-editor[contenteditable="true"], .ql-editor[contenteditable="true"]']}isValidTextarea(e){return !!super.isValidTextarea(e)&&("true"===e.getAttribute("contenteditable")&&!!e.closest(".agent-dialogue__content--common__input"))}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus();try{if(document.execCommand("selectAll",!1),!document.execCommand("insertText",!1,e))throw new Error("execCommand returned false");return t.dispatchEvent(new InputEvent("input",{bubbles:!0,composed:!0,data:e,inputType:"insertText"})),!0}catch{return t.textContent=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e,inputType:"insertText"})),t.dispatchEvent(new Event("change",{bubbles:true})),true}}clearTextarea(){const e=this.getTextareaElement();if(e&&e.isConnected){e.focus();try{document.execCommand("selectAll",!1),document.execCommand("delete",!1);}catch{e.textContent="";}e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:"",inputType:"deleteContentBackward"})),e.dispatchEvent(new Event("change",{bubbles:true}));}}simulateClick(e){const t=e.getBoundingClientRect(),n=t.left+Math.max(1,Math.min(t.width/2,Math.max(t.width-1,1))),r=t.top+Math.max(1,Math.min(t.height/2,Math.max(t.height-1,1))),o={bubbles:true,cancelable:true,composed:true,view:window,button:0,buttons:1,clientX:n,clientY:r},i=t=>"function"==typeof PointerEvent&&e.dispatchEvent(new PointerEvent(t,{...o,pointerId:1,pointerType:"mouse",isPrimary:true}));i("pointerenter"),i("pointerover"),i("pointermove"),e.dispatchEvent(new MouseEvent("mouseenter",o)),e.dispatchEvent(new MouseEvent("mouseover",o)),e.dispatchEvent(new MouseEvent("mousemove",o)),i("pointerdown"),e.dispatchEvent(new MouseEvent("mousedown",o)),i("pointerup"),e.dispatchEvent(new MouseEvent("mouseup",o)),e.dispatchEvent(new MouseEvent("click",o));}getSubmitButtonSelectors(){return [Zg]}findSubmitButton(){const e=document.querySelector("#yuanbao-send-btn");if(this.isVisibleElement(e)&&!this.isDisabledActionButton(e))return e;const t=Array.from(document.querySelectorAll(Zg));for(const n of t){const e=n;if(this.isVisibleElement(e)&&(!this.isDisabledActionButton(e)&&!this.isStopLikeButton(e)))return e}return null}getSessionId(){const e=window.location.pathname.match(Qg);return e?.[2]||""}isNewConversation(){const e=window.location.pathname.replace(/\/+$/,""),t=e.match(Qg);return t?!t[2]:""===e||"/"===e}getNewTabUrl(){const e=this.getAgentId();return e?`https://${Gg}/chat/${e}`:`https://${Gg}/`}getSessionName(){const e=this.getConversationTitle();if(e)return e;const t=document.title.trim();if(!t)return null;const n=t.replace(/\s*[-|]\s*(腾讯元宝|元宝)$/i,"").trim();return !n||/^(腾讯元宝|元宝)$/i.test(n)?null:n}getCurrentCid(){const e=localStorage.getItem("yb_user_id");if(!e)return null;try{const t=JSON.parse(e);if("string"==typeof t&&t.trim())return t.trim();if(t&&"object"==typeof t)for(const e of ["uid","id","cid","userId"]){const n=t[e];if("string"==typeof n&&n.trim())return n.trim()}}catch{}return e.trim()||null}getConversationTitle(){const e=document.querySelector(Xg);return e?this.extractConversationTitle(e):null}getCurrentConversationInfo(){const e=super.getCurrentConversationInfo();if(!e)return null;const t=document.querySelector(Xg),n=t?this.extractConversationInfo(t,this.getCurrentCid()||void 0):null;return n&&n.id===e.id?{...e,title:n.title||e.title,url:n.url||e.url,cid:n.cid??e.cid,isActive:n.isActive??e.isActive,isPinned:n.isPinned??e.isPinned}:e}getConversationList(){const e=this.getCurrentCid()||void 0,t=document.querySelectorAll(Jg),n=new Map;return t.forEach(t=>{const r=this.extractConversationInfo(t,e);r&&n.set(r.id,r);}),Array.from(n.values())}getConversationObserverConfig(){return {selector:Jg,shadow:false,extractInfo:e=>this.extractConversationInfo(e,this.getCurrentCid()||void 0),getTitleElement:e=>e.querySelector(ep)||e}}getSidebarScrollContainer(){return document.querySelector(".yb-nav__content")}async loadAllConversations(){const e=this.getSidebarScrollContainer();if(!(e instanceof HTMLElement))return;let t=0,n=0;for(;n<4;){e.scrollTop=e.scrollHeight,e.dispatchEvent(new Event("scroll",{bubbles:true})),await new Promise(e=>window.setTimeout(e,500));const r=document.querySelectorAll(Jg).length;r===t?n+=1:(t=r,n=0);}}navigateToConversation(e,t){const n=this.captureConversationNavigationState(),r=this.findConversationRowById(e);if(r){const o=r.querySelector(ep),i=this.resolveClickableTarget(o)||r.querySelector("a[href]")||this.resolveClickableTarget(r)||r;return this.simulateClick(i),window.setTimeout(()=>{this.hasConversationNavigationChanged(n)||super.navigateToConversation(e,t||this.buildConversationUrl(e));},800),true}return super.navigateToConversation(e,t||this.buildConversationUrl(e))}async deleteConversationOnSite(e){try{const t=await this.deleteConversationViaUi(e.id);return {id:e.id,success:t,method:t?"ui":"none",reason:t?void 0:vp}}catch(t){return console.error(`[YuanbaoAdapter] deleteConversationOnSite error for "${e.id}":`,t),{id:e.id,success:false,method:"none",reason:wp}}}async deleteConversationsOnSite(e){const t=[];for(let n=0;nt.clientHeight)return t;const e=this.findScrollableParent(t);if(e)return e}return super.getScrollContainer()}getResponseContainerSelector(){return tp}getChatContentSelectors(){return [np,rp]}getUserQuerySelector(){return np}extractUserQueryText(e){const t=this.findUserContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown, button, [role='button'], svg, input, label").forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}replaceUserQueryContent(e,t){const n=this.findUserContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e),n.style.display="none";}return n.after(r),true}extractAssistantResponseText(e){const t=this.shouldIncludeThoughtsInExport(),n=e.cloneNode(true);n.querySelectorAll(`${ap}, ${ip}`).forEach(e=>e.remove()),n.querySelectorAll("button, [role='button'], svg").forEach(e=>e.remove());const r=t?this.extractThoughtBlockquotes(n):[];n.querySelectorAll(cp).forEach(e=>e.remove());const o=this.findAssistantBodyRoot(n)||n,i=Uo(o).trim()||this.extractTextWithLineBreaks(o).trim();if(t&&r.length>0){const e=r.join("\n\n");return i?`${e}\n\n${i}`:e}return i}getLatestReplyText(){const e=document.querySelectorAll(rp),t=e[e.length-1];return t?this.extractAssistantResponseText(t):null}extractOutline(e=6,t=false,n=false){const r=document.querySelector(tp)||this.getScrollContainer()||document,o=Array.from(r.querySelectorAll(`${np}, ${rp}`)).filter(e=>!e.closest(".gh-root")),i=[];return o.forEach((r,a)=>{if(r.matches(np)){if(!t)return;const e=this.extractUserQueryText(r);if(!e)return;let s;if(n){const e=o.slice(a+1).find(e=>e.matches(rp));s=e?this.extractAssistantPlainText(e).length:0;}return void i.push({level:0,text:this.truncateText(e,80),element:r,isUserQuery:true,isTruncated:e.length>80,wordCount:s})}const s=this.findAssistantMarkdownRoot(r);if(!s)return;const l=Array.from(s.querySelectorAll("h1, h2, h3, h4, h5, h6")).filter(e=>!this.isInRenderedMarkdownContainer(e));l.forEach((t,r)=>{const o=Number.parseInt(t.tagName.slice(1),10);if(Number.isNaN(o)||o>e)return;const a=this.extractHeadingText(t);if(!a)return;let c;if(n){let e=null;for(let t=r+1;tt.clientHeight)return t;t=t.parentElement;}return null}findUserContentRoot(e){return e.querySelector(".agent-chat__bubble--human .hyc-content-text, .agent-chat__bubble--human .agent-chat__bubble__content")||e.querySelector(".agent-chat__bubble__content")||e}findAssistantContentRoot(e){const t=this.findAssistantBodyRoot(e);if(t)return t;const n=this.findAssistantMarkdownRoot(e);return n||(e.querySelector(".agent-chat__speech-text")||e.querySelector(".agent-chat__bubble__content")||e)}findAssistantMarkdownRoot(e){const t=this.findFirstAssistantNodeOutsideThoughts(e,dp.slice(0,2));if(t)return t;if(e.matches(op)&&!this.isThoughtElement(e))return e;const n=Array.from(e.querySelectorAll(op));return n.find(e=>!this.isThoughtElement(e))||n[0]||null}extractAssistantPlainText(e){const t=this.findAssistantContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return n.querySelectorAll(`${ap}, ${ip}`).forEach(e=>e.remove()),n.querySelectorAll("button, [role='button'], svg").forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}extractHeadingText(e){const t=e.cloneNode(true);return t.querySelectorAll("button, [role='button'], svg").forEach(e=>e.remove()),this.extractTextWithLineBreaks(t).trim()}findAssistantBodyRoot(e){const t=this.findFirstAssistantNodeOutsideThoughts(e,dp);if(t)return t;const n=this.findAssistantMarkdownRoot(e);if(n instanceof HTMLElement)return n;const r=e.querySelector(".agent-chat__speech-text");if(r&&!this.isThoughtElement(r))return r;const o=e.querySelector(".agent-chat__bubble__content");return o&&!this.isThoughtElement(o)?o:e instanceof HTMLElement?e:null}shouldIncludeThoughtsInExport(){return "boolean"==typeof this.exportIncludeThoughtsOverride&&this.exportIncludeThoughtsOverride}extractThoughtBlockquotes(e){const t=Array.from(e.querySelectorAll(lp)).filter(e=>!e.parentElement?.closest(lp)),n=[];for(const r of t){const e=r.cloneNode(true);e.querySelectorAll(`${ip}, button, [role='button'], svg, [aria-hidden='true']`).forEach(e=>e.remove());const t=(Uo(e)||this.extractTextWithLineBreaks(e)).trim();t&&n.push(this.formatAsThoughtBlockquote(t));}return n}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}findFirstAssistantNodeOutsideThoughts(e,t){for(const n of t){if(e.matches(n)&&!this.isThoughtElement(e))return e;const t=Array.from(e.querySelectorAll(n)).find(e=>e instanceof HTMLElement&&!this.isThoughtElement(e));if(t)return t}return null}isThoughtElement(e){return null!==e.closest(cp)}findConversationRowById(e){const t=document.querySelector(`${Jg}[dt-cid="${e}"]`);if(t)return t;const n=Array.from(document.querySelectorAll(Jg));for(const r of n){const t=this.extractConversationInfo(r,this.getCurrentCid()||void 0);if(t?.id===e)return r}return null}async deleteConversationViaUi(e){let t=this.findConversationRowById(e);if(t||(await this.loadAllConversations(),t=this.findConversationRowById(e)),!t)return false;const n=this.captureConversationNavigationState();t.scrollIntoView({block:"center",behavior:"auto"}),this.revealConversationActions(t);let r=this.findConversationMenuTrigger(t);if(!r)return false;const o=await this.openConversationAction(t,r);if(!o)return false;let i="dialog"===o.kind?o.dialog:null;if("menu"===o.kind){const e=await this.waitForDeleteMenuItem(o.menu,2e3);if(!e)return document.body.click(),false;this.simulateClick(e),i=await this.waitForDialogOpen(1200);}if(i){const e=await this.waitForDeleteConfirmButton(i,2e3);if(!e)return false;this.simulateClick(e);}return !!(await this.waitForConversationDeleteResult(e,n,4500))||!!i&&(await this.waitForDialogClosed(1200),this.waitForConversationDeleteResult(e,n,800))}revealConversationActions(e){const t=e.querySelector(ep),n=[e,t].filter(e=>e instanceof HTMLElement);for(const r of n){const e=r.getBoundingClientRect(),t=e.left+Math.max(1,Math.min(e.width/2,Math.max(e.width-1,1))),n=e.top+Math.max(1,Math.min(e.height/2,Math.max(e.height-1,1))),o={bubbles:true,cancelable:true,composed:true,view:window,clientX:t,clientY:n};if("function"==typeof PointerEvent)for(const i of ["pointerenter","pointerover","pointermove"])r.dispatchEvent(new PointerEvent(i,{...o,pointerId:1,pointerType:"mouse",isPrimary:true}));for(const i of ["mouseenter","mouseover","mousemove"])r.dispatchEvent(new MouseEvent(i,o));}}findConversationMenuTrigger(e){return this.getConversationActionCandidates(e)[0]||null}getConversationActionCandidates(e,t){const n=Array.from(e.querySelectorAll(gp)),r=[],o=new Set,i=(e,t=0)=>{if(!(e instanceof HTMLElement)||o.has(e))return;o.add(e);const n=this.getConversationActionScore(e);Number.isFinite(n)&&r.push({element:e,score:n+t});};i(t,25);for(const a of n)i(a);return r.sort((e,t)=>t.score-e.score),r.map(({element:e})=>e)}getConversationActionScore(e){if(e.closest(ep))return Number.NEGATIVE_INFINITY;if(e.closest(".t-checkbox, [role='checkbox']"))return Number.NEGATIVE_INFINITY;if(e.matches("input, label"))return Number.NEGATIVE_INFINITY;const t=this.getConversationActionSignal(e),n=window.getComputedStyle(e);let r=0;return e.matches('[aria-haspopup="menu"], [aria-haspopup="listbox"]')&&(r+=120),/(ellipsis|more[_-]?vert|icon-more|icon-menu|menu)/i.test(t)&&(r+=70),/(delete|删除)/i.test(t)&&(r+=45),/(action|operate|dropdown|popup)/i.test(t)&&(r+=15),e.matches("button, [role='button']")&&(r+=10),e.querySelector(".iconfont-yb, .yb-icon, svg")&&(r+=5),"none"!==n.pointerEvents&&(r+=5),this.isVisibleElement(e)&&(r+=30),r}async openConversationAction(e,t){let n=t;for(let r=0;r<4;r+=1){document.body.click(),await this.sleep(80),this.revealConversationActions(e);const t=this.getConversationActionCandidates(e,n);if(0===t.length)return null;n=t[0]||null;for(const e of t){if(!e.isConnected)continue;this.simulateClick(e);const t=await this.waitForConversationActionOpen(e,1e3);if(t)return t}}return null}async waitForConversationActionOpen(e,t){const n=Date.now();for(;Date.now()-ne instanceof HTMLElement&&this.isVisibleElement(e)&&this.isDropdownMenuContainer(e));return n.length>0?n[n.length-1]:null}isDropdownMenuContainer(e){return !!e.matches(hp)||!!e.querySelector(hp)}async waitForDeleteMenuItem(e,t){const n=Date.now();for(;Date.now()-ne instanceof HTMLElement&&this.isVisibleElement(e)),n=t.find(e=>e.className.includes("theme-error"))||t.find(e=>fp.test(this.getElementText(e)));if(n)return n;await this.sleep(80);}return null}async waitForDialogOpen(e){const t=Date.now();for(;Date.now()-te instanceof HTMLElement&&this.isVisibleElement(e))||null}async waitForDeleteConfirmButton(e,t){const n=Date.now();for(;Date.now()-ne instanceof HTMLElement&&this.isVisibleElement(e)),n=t.find(e=>{const t=this.getElementText(e);return bp.test(t)&&!yp.test(t)})||t.find(e=>/primary|danger/i.test(e.className));if(n)return n;await this.sleep(80);}return null}async waitForDialogClosed(e){const t=Date.now();for(;Date.now()-te instanceof HTMLElement&&this.isVisibleElement(e)))return true;await this.sleep(80);}return false}async waitForConversationDeleteResult(e,t,n){const r=Date.now(),o=t.sessionId===e;for(;Date.now()-rwindow.setTimeout(t,e))}findStopButton(){const e=Array.from(document.querySelectorAll(Yg));for(const t of e){const e=t;if(this.isVisibleElement(e)&&this.isStopLikeButton(e))return e}return null}isDisabledActionButton(e){if(!(e instanceof HTMLElement))return true;const t="string"==typeof e.className?e.className:"";return e.hasAttribute("disabled")||"true"===e.getAttribute("aria-disabled")||/disabled/i.test(t)}isStopLikeButton(e){if(!(e instanceof HTMLElement))return false;if(e.querySelector("span.icon-send, .icon-send"))return false;if(e.querySelector("rect"))return true;const t=e.innerText?.trim()||e.textContent?.trim()||"";return /停止|stop/i.test(t)}isVisibleElement(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}truncateText(e,t){return e.length>t?`${e.slice(0,t)}...`:e}},new class extends ci{exportIncludeThoughtsOverride=null;match(){return "chat.z.ai"===window.location.hostname}getSiteId(){return Hr}getName(){return "Z.ai"}getThemeColors(){return {primary:"#0881F0",secondary:"#0B6ED8"}}getTextareaSelectors(){return [...Sp]}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus();const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),t.setSelectionRange(e.length,e.length),true}clearTextarea(){const e=this.getTextareaElement();if(!e||!e.isConnected)return;const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),e.dispatchEvent(new Event("change",{bubbles:true})),e.setSelectionRange(0,0);}getSubmitButtonSelectors(){return [`${Cp}:not([disabled])`]}findSubmitButton(){const e=document.querySelector(Cp);return !e||e.hasAttribute("disabled")||null===e.offsetParent?null:e}getResponseContainerSelector(){return Tp}getChatContentSelectors(){return [Mp,Ip]}getUserQuerySelector(){return Mp}extractUserQueryText(e){const t=this.findUserContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown, button, [role=button], svg, [aria-hidden=true]").forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}replaceUserQueryContent(e,t){const n=this.findUserContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e);}if(n===e){const t=document.createElement("div");for(t.className="gh-user-query-raw";e.firstChild;)t.appendChild(e.firstChild);return t.style.display="none",e.appendChild(t),e.appendChild(r),true}return n.style.display="none",n.after(r),true}getExportConfig(){return {userQuerySelector:Lp,assistantResponseSelector:Dp,turnSelector:null,useShadowDOM:false}}async prepareConversationExport(e){this.exportIncludeThoughtsOverride=e.includeThoughts,this.clearExportMarkers();const t=document.querySelector(this.getResponseContainerSelector())||document.querySelector(Ap)||document.body;return this.markExportMessages(t),null}async restoreConversationAfterExport(e,t){this.clearExportMarkers(),this.exportIncludeThoughtsOverride=null;}clearExportMarkers(){document.querySelectorAll(`[${Np}]`).forEach(e=>e.removeAttribute(Np));}shouldSkipExportElement(e){return !!e.closest(".gh-root")||(!!e.closest(".gh-user-query-markdown")||!!e.closest(Rp))}collectExportMessages(e){const t=Array.from(e.querySelectorAll(Mp)),n=this.collectTopLevelBlocks(t).filter(e=>!this.shouldSkipExportElement(e)),r=Array.from(e.querySelectorAll(Ip));return {users:n,assistants:this.collectTopLevelBlocks(r).filter(e=>!this.shouldSkipExportElement(e)&&!e.closest(Mp))}}markExportMessages(e){const{users:t,assistants:n}=this.collectExportMessages(e);t.forEach(e=>e.setAttribute(Np,"user")),n.forEach(e=>e.setAttribute(Np,"assistant"));}shouldIncludeThoughtsInExport(){return "boolean"!=typeof this.exportIncludeThoughtsOverride||this.exportIncludeThoughtsOverride}formatAsThoughtBlockquote(e){return ["> **💭 思考过程**",">",...e.replace(/\r\n/g,"\n").replace(/\n{3,}/g,"\n\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}extractThoughtBlockquotesFromElement(e){const t=[],n=[],r=e=>{const t=document.createElement("div");return Array.from(e.childNodes).forEach(e=>t.appendChild(e.cloneNode(true))),Uo(t)||this.extractTextWithLineBreaks(e)},o=Array.from(e.querySelectorAll("blockquote[slot='content'], .thinking-block blockquote, .thinking-chain-container blockquote"));if(o.length>0){const e=this.collectTopLevelBlocks(o);for(const o of e){const e=r(o).trim();e&&t.push(this.formatAsThoughtBlockquote(e));const i=o.closest(".thinking-chain-container")||o.closest(".thinking-block")||o;n.push(i);}return {blocks:t,removalNodes:this.collectTopLevelBlocks(n)}}const i=Array.from(e.querySelectorAll(Rp)),a=this.collectTopLevelBlocks(i);for(const s of a){const e=r(s.querySelector("blockquote[slot='content']")||s.querySelector("blockquote")||s).trim();e&&t.push(this.formatAsThoughtBlockquote(e)),n.push(s);}return {blocks:t,removalNodes:this.collectTopLevelBlocks(n)}}extractAssistantResponseText(e){const t=e.cloneNode(true),n=this.shouldIncludeThoughtsInExport(),r=this.extractThoughtBlockquotesFromElement(t),o=n?r.blocks:[];r.removalNodes.length>0&&r.removalNodes.forEach(e=>e.remove()),t.querySelectorAll(Rp).forEach(e=>e.remove());const i=(Uo(t)||this.extractTextWithLineBreaks(t)).trim();if(o.length>0){const e=o.join("\n\n");return i?`${e}\n\n${i}`:e}return i}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector(this.getResponseContainerSelector())||document.querySelector(Ap);if(!o)return r;const i=this.getUserQuerySelector();if(!i)return r;const a=[];for(let g=1;g<=e;g++)a.push(`h${g}`);const s=`${i}, ${a.join(", ")}`,l=Array.from(o.querySelectorAll(i)),c=this.collectTopLevelBlocks(l).filter(e=>!this.shouldSkipOutlineElement(e)),d=new Set(c),u=Array.from(o.querySelectorAll(s)).filter(e=>e.matches(i)?d.has(e):!this.shouldSkipOutlineElement(e)),h=(e,t,n)=>{if(!e)return 0;try{if(n){const n=o.querySelectorAll(Ip);let r="";for(const o of Array.from(n)){const n=e.compareDocumentPosition(o);if(!(n&Node.DOCUMENT_POSITION_FOLLOWING))continue;if(t){const e=t.compareDocumentPosition(o);if(!(e&Node.DOCUMENT_POSITION_PRECEDING))continue}const i=o.cloneNode(!0);i.querySelectorAll(`${Rp}, .gh-user-query-markdown`).forEach(e=>e.remove()),r+=i.textContent||"";}return r.trim().length}if(t)return this.calculateRangeWordCount(e,t,o);const r=o.querySelectorAll(i);let a=!1,s=null;for(const t of Array.from(r)){if(a){s=t;break}(t===e||t.contains(e)||e.contains(t))&&(a=!0);}if(s)return this.calculateRangeWordCount(e,s,o);const l=o.querySelectorAll(Ip);if(l.length>0){const t=l[l.length-1];return this.calculateRangeWordCount(e,null,t)}return this.calculateRangeWordCount(e,null,o)}catch{return 0}};return u.forEach((o,a)=>{const s=o.tagName.toLowerCase(),l=o.matches(i),c=/^h[1-6]$/.test(s);let d,g=false;if(t&&l&&(g=true),c&&!this.shouldSkipOutlineElement(o)){const t=parseInt(s.charAt(1),10);!Number.isNaN(t)&&t<=e&&(g=true);}if(g){if(l){let e=this.extractUserQueryText(o),t=false;e.length>200&&(e=e.substring(0,200),t=true),d={level:0,text:e,element:o,isUserQuery:true,isTruncated:t};}else {d={level:parseInt(s.charAt(1),10),text:o.textContent?.trim()||"",element:o,isUserQuery:false};}if(n){let e=null;for(let t=a+1;tt.id===e);return t?.title||null}getConversationList(){const e=document.querySelectorAll(Bp);if(!e.length)return [];const t=this.getCurrentCid()||void 0,n=[];return e.forEach(e=>{const r=this.extractConversationId(e);if(!r)return;const o=this.extractConversationTitle(e);o&&n.push({id:r,cid:t,title:o,url:`https://chat.z.ai/c/${r}`,isActive:r===this.getSessionId()});}),n}getConversationObserverConfig(){return {selector:Bp,shadow:false,extractInfo:e=>{const t=this.extractConversationId(e);if(!t)return null;const n=this.extractConversationTitle(e);return n?{id:t,title:n,url:`https://chat.z.ai/c/${t}`,cid:this.getCurrentCid()||void 0,isActive:t===this.getSessionId()}:null},getTitleElement:e=>e.querySelector(Op)||e}}getSidebarScrollContainer(){return document.querySelector("#sidebar .overflow-y-auto")}getScrollContainer(){const e=this.collectScrollAnchorRoots(),t=this.pickBestScrollableAncestor(e);if(t)return t;const n=Array.from(document.querySelectorAll("[data-pane-id]"));return this.pickBestScrollableAncestor(n)}navigateToConversation(e,t){const n=document.querySelectorAll(Bp);for(const r of Array.from(n)){if(this.extractConversationId(r)!==e)continue;const t=r.querySelector("button");if(t)return t.click(),true}return super.navigateToConversation(e,t||`https://chat.z.ai/c/${e}`)}getModelName(){const e=this.getSelectedModelFromStorage();if(e)return e;const t=this.findElementBySelectors(_p),n=t?.textContent?.trim();return n||null}lockModel(e,t){this.isNewConversation()&&super.lockModel(e,t);}getModelSwitcherConfig(e){return this.isNewConversation()?{targetModelKeyword:e,selectorButtonSelectors:[..._p],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"]}:null}async toggleTheme(e){try{const t="undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,n="system"===e?t?"dark":"light":e;localStorage.setItem(zp,e),document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(n),document.documentElement.style.colorScheme=n,document.body.style.colorScheme=n;const r=document.querySelector('meta[name="theme-color"]');return r&&r.setAttribute("content",Fp[n]),window.dispatchEvent(new StorageEvent("storage",{key:zp,newValue:e,storageArea:localStorage})),!0}catch(t){return console.error("[ZaiAdapter] toggleTheme error:",t),false}}getWidthSelectors(){return [{selector:`${Ap} [class*="max-w-[1000px]"]`,property:"max-width"},{selector:`${Ap} [class*="max-w-[960px]"]`,property:"max-width"}]}getUserQueryWidthSelectors(){return [{selector:`${Ap} .chat-user [class*="max-w-[90%]"]`,property:"max-width",noCenter:true}]}getZenModeSelectors(){const e=[];try{const t=localStorage.getItem("sidebar");"true"!==t&&'"true"'!==t||e.push({selector:"div.self-center.m-auto:has(> svg)",action:"click"});}catch{}return e}extractConversationTitle(e){const t=e.querySelector(Op);return t?.textContent?.trim()||""}collectScrollAnchorRoots(){const e=Array.from(document.querySelectorAll(`${Mp}, ${Ip}`));return this.collectTopLevelBlocks(e).filter(e=>!e.closest(".gh-root, .gh-table-container"))}pickBestScrollableAncestor(e){const t=new Map;for(const o of e){const e=this.findScrollableAncestor(o);if(!e)continue;const n=t.get(e)||0;t.set(e,n+this.scoreScrollContainer(e));}let n=null,r=-1;for(const[o,i]of t.entries())i>r&&(n=o,r=i);return r>0?n:null}findScrollableAncestor(e){let t=e instanceof HTMLElement?e:e?.parentElement||null;for(;t&&t!==document.body;){if(this.isPrimaryScrollContainer(t))return t;t=t.parentElement;}return null}isPrimaryScrollContainer(e){if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("auto"!==t.overflowY&&"scroll"!==t.overflowY)return false;if(e.scrollHeight<=e.clientHeight)return false;if(e.clientHeight<220)return false;const n=e.getBoundingClientRect();return !(n.width<320||n.height<220)}scoreScrollContainer(e){const t=window.innerHeight||document.documentElement.clientHeight||0,n=window.innerWidth||document.documentElement.clientWidth||0,r=e.getBoundingClientRect(),o=e.querySelectorAll(Mp).length,i=e.querySelectorAll(Ip).length;let a=0;return a+=160*Math.min(o,60),a+=160*Math.min(i,60),o>0&&i>0&&(a+=700),e.scrollTop>0&&(a+=900),r.height>=.35*t&&(a+=500),r.width>=.45*n&&(a+=350),e.closest("[data-pane-id]")&&(a+=300),e.querySelector("textarea, #chat-input")&&(a-=700),e.matches(".scrollbar-none")&&e.scrollWidth>e.clientWidth&&(a-=400),a}shouldSkipOutlineElement(e){return !this.isOutlineElementVisible(e)||(!!e.closest(".gh-root")||(!!this.isInRenderedMarkdownContainer(e)||!!e.closest(Rp)))}isOutlineElementVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;if(e.closest("[hidden], [aria-hidden='true']"))return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}findUserContentRoot(e){const t=(e.matches(Mp)?e:e.closest(Mp))||e;for(const n of qp){const e=t.querySelector(n);if(!e)continue;if(e.closest(".gh-user-query-markdown"))continue;if(e.closest("button, [role=button]"))continue;const r=e.textContent?.trim();if(r)return e}return t}collectTopLevelBlocks(e){return e.length<=1?e:e.filter(t=>!e.some(e=>e!==t&&e.contains(t)))}extractConversationId(e){const t=["data-conversation-id","data-chat-id","data-session-id","data-cid","data-id"];for(const o of t){const t=this.matchConversationId(e.getAttribute(o));if(t)return t;const n=e.querySelector(`[${o}]`),r=this.matchConversationId(n?.getAttribute(o));if(r)return r}const n=e.getAttribute("aria-controls"),r=this.matchConversationId(n);return r||""}matchConversationId(e){if(!e)return "";const t=e.match(jp);return t?.[0]||""}getSelectedModelFromStorage(){try{const e=localStorage.getItem("selectedModels");if(!e)return null;const t=JSON.parse(e);return Array.isArray(t)&&"string"==typeof t[0]?t[0]:"string"==typeof t?t:null}catch{return null}}}];function Hp(){for(const e of $p)if(e.match())return e;return null}const Up=Object.freeze(Object.defineProperty({__proto__:null,SiteAdapter:ci,getAdapter:Hp,getAllAdapters:function(){return [...$p]}},Symbol.toStringTag,{value:"Module"})),Wp=io()(lo((e,t)=>({conversations:{},lastUsedFolderId:"inbox",_hasHydrated:false,addConversation:t=>e(e=>({conversations:{...e.conversations,[t.id]:t}})),updateConversation:(t,n)=>e(e=>e.conversations[t]?{conversations:{...e.conversations,[t]:{...e.conversations[t],...n,updatedAt:Date.now()}}}:e),deleteConversation:t=>e(e=>{const{[t]:n,...r}=e.conversations;return {conversations:r}}),moveToFolder:(t,n)=>e(e=>e.conversations[t]?{conversations:{...e.conversations,[t]:{...e.conversations[t],folderId:n,updatedAt:Date.now()}}}:e),togglePin:n=>{const r=t();if(!r.conversations[n])return false;const o=!r.conversations[n].pinned;return e(e=>({conversations:{...e.conversations,[n]:{...e.conversations[n],pinned:o,updatedAt:Date.now()}}})),o},setConversationTags:(t,n)=>e(e=>{if(!e.conversations[t])return e;const r={...e.conversations[t]};return n.length>0?r.tagIds=n:delete r.tagIds,{conversations:{...e.conversations,[t]:r}}}),removeTagFromAll:t=>e(e=>{const n={};let r=false;for(const[o,i]of Object.entries(e.conversations))if(i.tagIds?.includes(t)){const e=i.tagIds.filter(e=>e!==t);n[o]={...i,tagIds:e.length>0?e:void 0},r=true;}else n[o]=i;return r?{conversations:n}:e}),moveConversationsToInbox:t=>e(e=>{const n={};let r=false;for(const[o,i]of Object.entries(e.conversations))i.folderId===t?(n[o]={...i,folderId:"inbox"},r=true):n[o]=i;return r?{conversations:n}:e}),setLastUsedFolderId:t=>e({lastUsedFolderId:t}),setHasHydrated:t=>e({_hasHydrated:t})}),{name:"conversations",storage:ao(()=>Ao),partialize:e=>({conversations:e.conversations,lastUsedFolderId:e.lastUsedFolderId}),onRehydrateStorage:()=>e=>{Wp.setState({_hasHydrated:true});}})),Vp=()=>Wp.getState(),Gp=Object.freeze(Object.defineProperty({__proto__:null,getConversationsStore:Vp,useConversationsStore:Wp},Symbol.toStringTag,{value:"Module"})),Qp=(e,t)=>{const n=(e||"").trim(),r=(t||"").trim();return r&&n.startsWith(r)?n.slice(r.length).trim():n},Kp=e=>({...e,name:Qp(e.name,e.icon)}),Zp=io()(lo((e,t)=>({folders:Cr,_hasHydrated:false,addFolder:(t,n)=>{const r={id:"folder_"+Date.now(),name:Qp(t,n),icon:n};return e(e=>({folders:[...e.folders,r]})),r},updateFolder:(t,n)=>e(e=>({folders:e.folders.map(e=>{if(e.id!==t)return e;const r={...e,...n};return {...r,name:Qp(r.name,r.icon)}})})),deleteFolder:t=>{"inbox"!==t&&e(e=>({folders:e.folders.filter(e=>e.id!==t)}));},moveFolder:(t,n)=>e(e=>{const r=e.folders.findIndex(e=>e.id===t);if(-1===r||0===r)return e;const o="up"===n?r-1:r+1;if(o<=0||o>=e.folders.length)return e;const i=[...e.folders];return [i[r],i[o]]=[i[o],i[r]],{folders:i}}),setHasHydrated:t=>e({_hasHydrated:t})}),{name:"folders",storage:ao(()=>Ao),partialize:e=>({folders:e.folders}),merge:(e,t)=>{const n=e;return n?.folders?{...t,...n,folders:(r=n.folders,r.map(Kp))}:t;var r;},onRehydrateStorage:()=>e=>{Zp.setState({_hasHydrated:true});}})),Yp=()=>Zp.getState(),Jp=Object.freeze(Object.defineProperty({__proto__:null,getFoldersStore:Yp,useFoldersStore:Zp},Symbol.toStringTag,{value:"Module"})),Xp=io()(lo((e,t)=>({tags:[],_hasHydrated:false,addTag:(n,r)=>{if(t().tags.some(e=>e.name.toLowerCase()===n.toLowerCase()))return null;const o={id:"tag_"+Date.now()+"_"+Math.random().toString(36).substr(2,5),name:n,color:r};return e(e=>({tags:[...e.tags,o]})),o},updateTag:(n,r,o)=>{if(t().tags.some(e=>e.id!==n&&e.name.toLowerCase()===r.toLowerCase()))return null;let i=null;return e(e=>({tags:e.tags.map(e=>e.id===n?(i={...e,name:r,color:o},i):e)})),i},deleteTag:t=>e(e=>({tags:e.tags.filter(e=>e.id!==t)})),setHasHydrated:t=>e({_hasHydrated:t})}),{name:"tags",storage:ao(()=>Ao),partialize:e=>({tags:e.tags}),onRehydrateStorage:()=>e=>{Xp.setState({_hasHydrated:true});}})),em=()=>Xp.getState(),tm=Object.freeze(Object.defineProperty({__proto__:null,getTagsStore:em,useTagsStore:Xp},Symbol.toStringTag,{value:"Module"}));class nm{siteAdapter;observerConfig=null;sidebarObserverStop=null;observerContainer=null;titleWatcher=null;pollInterval=null;geminiMigrationTimer=null;geminiMigrationRetryCount=0;syncUnpin=false;syncDelete=true;onChangeCallbacks=[];constructor(e){this.siteAdapter=e;}get folders(){return Yp().folders}get conversations(){return Vp().conversations}get lastUsedFolderId(){return Vp().lastUsedFolderId}get tags(){return em().tags} /** * 订阅数据变更事件 * @returns 取消订阅函数 */onDataChange(e){return this.onChangeCallbacks.push(e),()=>{this.onChangeCallbacks=this.onChangeCallbacks.filter(t=>t!==e);}}notifyDataChange(){this.onChangeCallbacks.forEach(e=>e());}async init(){await this.waitForHydration();"pending_email"===this.tryMigrateGeminiLegacyCidToEmail()&&this.startGeminiMigrationRetry();const e=await(Eo||(Eo=new Promise(e=>{"undefined"!=typeof chrome&&chrome.storage?.local?chrome.storage.local.get(Co,t=>{const n=t?.[Co];if(void 0===n)return void e(false);const r="number"==typeof n?n:Number(n);Number.isFinite(r)?Date.now()-r<=1e4?e(true):chrome.storage.local.remove(Co,()=>e(false)):e(true);}):e(false);}),Eo));if(0===Object.keys(this.getAllConversations()).length&&this.siteAdapter.loadAllConversations&&!e)try{await this.waitForSidebarReady()&&await this.autoFullSync();}catch{}this.startSidebarObserver();}tryMigrateGeminiLegacyCidToEmail(){if(this.siteAdapter.getSiteId()!==Ir)return "noop";const e=this.conversations,t=Object.entries(e).filter(([e,t])=>this.isGeminiConversation(t));if(0===t.length)return "noop";const n=t.filter(([e,t])=>this.isLegacyGeminiCid(t.cid));if(0===n.length)return "noop";const r=this.siteAdapter.getCurrentCid?.();if(!this.isEmailCid(r))return "pending_email";const o=this.getGeminiUserIndexFromPath(),i=n.some(([e,t])=>(t.cid||"0")===o),a=t.some(([e,t])=>t.cid===r),s=new Set(n.map(([e,t])=>t.cid||"0"));let l=null;if(i?l=o:a||1!==s.size||(l=Array.from(s)[0]),!l)return "noop";const c=n.filter(([e,t])=>(t.cid||"0")===l);if(0===c.length)return "noop";const d={...e},u=this.getGeminiUserPathPrefix();return c.forEach(([e,t])=>{d[e]={...t,cid:r,url:this.buildGeminiConversationUrl(e,u)};}),Wp.setState({conversations:d}),this.notifyDataChange(),console.warn(`[ConversationManager] Gemini legacy cid migrated: ${l} -> ${r}, updated ${c.length} conversations.`),"migrated"}startGeminiMigrationRetry(){if(this.siteAdapter.getSiteId()!==Ir)return;if(this.geminiMigrationTimer)return;this.geminiMigrationRetryCount=0,this.geminiMigrationTimer=setInterval(()=>{const e=this.tryMigrateGeminiLegacyCidToEmail();this.geminiMigrationRetryCount+=1,("pending_email"!==e||this.geminiMigrationRetryCount>=120)&&this.stopGeminiMigrationRetry();},1500);}stopGeminiMigrationRetry(){this.geminiMigrationTimer&&(clearInterval(this.geminiMigrationTimer),this.geminiMigrationTimer=null),this.geminiMigrationRetryCount=0;}isEmailCid(e){return "string"==typeof e&&e.includes("@")}isLegacyGeminiCid(e){return !e||/^\d+$/.test(e)}getGeminiUserIndexFromPath(){const e=window.location.pathname.match(/^\/u\/(\d+)(?:\/|$)/);return e?e[1]:"0"}getGeminiUserPathPrefix(){const e=window.location.pathname.match(/^\/u\/(\d+)(?:\/|$)/);return e?`/u/${e[1]}`:""}isGeminiConversation(e){return e.siteId===Ir||(!e.siteId||e.siteId===Ir)&&("string"==typeof e.url&&e.url.includes("gemini.google.com"))}buildGeminiConversationUrl(e,t){return `https://gemini.google.com${t}/app/${e}`}async waitForHydration(){const e=[Zp,Xp,Wp];await Promise.all(e.map(e=>new Promise(t=>{if(e.getState()._hasHydrated)return void t();const n=e.subscribe(e=>{e._hasHydrated&&(n(),t());});})));}async waitForSidebarReady(e=1e4){const t=Date.now();for(;Date.now()-tsetTimeout(e,250));}return false}async autoFullSync(){await this.siteAdapter.loadAllConversations(),await new Promise(e=>setTimeout(e,400));let e=0,t=this.siteAdapter.getConversationList().length;for(let n=0;n<10;n++){if(n>0){const e=this.siteAdapter.getSidebarScrollContainer();if(!e)break;const t=e;t.scrollTop=t.scrollHeight,await new Promise(e=>setTimeout(e,400));}const{newCount:r,updatedCount:o}=this.syncConversations(null,true);(r>0||o>0)&&this.notifyDataChange(),await new Promise(e=>setTimeout(e,300));const i=this.siteAdapter.getConversationList().length;if(r>0||i>t?(t=Math.max(t,i),e=0):e++,e>=2)break}}destroy(){this.stopGeminiMigrationRetry(),this.stopSidebarObserver();}updateSettings(e){this.syncUnpin=e.syncUnpin,"boolean"==typeof e.syncDelete&&(this.syncDelete=e.syncDelete);}startSidebarObserver(){if(this.sidebarObserverStop)return;const e=this.siteAdapter.getConversationObserverConfig();if(!e)return;this.observerConfig=e;const t=(n=0)=>{const r=this.siteAdapter.getSidebarScrollContainer()||document;if(e.shadow&&n<5){if(!this.siteAdapter.getSidebarScrollContainer())return void setTimeout(()=>t(n+1),1e3)}this.observerContainer=r,this.sidebarObserverStop=ei.each(e.selector,(t,n)=>{this.handleObservedElement(t,n,e);},{parent:r,shadow:e.shadow});};t(),e.shadow&&this.startPolling();}stopSidebarObserver(){this.sidebarObserverStop&&(this.sidebarObserverStop(),this.sidebarObserverStop=null),this.observerContainer=null,this.titleWatcher&&("function"==typeof this.titleWatcher.stop&&this.titleWatcher.stop(),this.titleWatcher=null),this.stopPolling();}handleObservedElement(e,t,n){const r=(o=5)=>{const i=n.extractInfo(e);i?.id?(this.updateConversationFromObservation(i,t),this.monitorConversationTitle(e,i.id)):o>0&&setTimeout(()=>r(o-1),500);};r();}updateConversationFromObservation(e,t){const n=this.conversations[e.id];if(t&&!n)Vp().addConversation({id:e.id,siteId:this.siteAdapter.getSiteId(),cid:e.cid,title:e.title,url:e.url,folderId:this.lastUsedFolderId,pinned:e.isPinned||false,createdAt:Date.now(),updatedAt:Date.now()}),this.notifyDataChange();else if(n){let t=false;const r={};e.title&&e.title!==n.title&&(r.title=e.title,t=true),e.url&&e.url!==n.url&&(r.url=e.url,t=true),void 0!==e.cid&&e.cid!==n.cid&&(r.cid=e.cid,t=true),void 0!==e.isPinned&&e.isPinned!==n.pinned&&(e.isPinned?(r.pinned=true,t=true):!e.isPinned&&this.syncUnpin&&(r.pinned=false,t=true)),t&&(Vp().updateConversation(e.id,r),this.notifyDataChange());}}startPolling(){this.pollInterval||(this.pollInterval=setInterval(()=>{if(!this.observerConfig)return;const e=this.observerConfig,t=ei.query(e.selector,{all:true,shadow:e.shadow});Array.isArray(t)&&t.forEach(t=>{const n=e.extractInfo(t);if(!n?.id)return;const r=this.conversations[n.id];r?n.title&&n.title!==r.title&&(Vp().updateConversation(n.id,{title:n.title}),this.notifyDataChange()):(this.updateConversationFromObservation(n,true),this.monitorConversationTitle(t,n.id));});},3e3));}stopPolling(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null);}monitorConversationTitle(e,t){if(!e.dataset.ghTitleObserver){if(e.dataset.ghTitleObserver="true",!this.titleWatcher){const e=this.siteAdapter.getSidebarScrollContainer()||document.body;this.titleWatcher=ei.watchMultiple(e,{debounce:500});}this.titleWatcher.add(e,()=>{const n=this.observerConfig;if(!n)return;const r=n.extractInfo(e),o=r?.id;if(!o||o!==t)return;const i=this.conversations[t];if(!i)return;let a=false;const s={};r.title&&r.title!==i.title&&(s.title=r.title,a=true),void 0!==r.isPinned&&r.isPinned!==i.pinned&&(r.isPinned?(s.pinned=true,a=true):!r.isPinned&&this.syncUnpin&&(s.pinned=false,a=true)),a&&(Vp().updateConversation(t,s),this.notifyDataChange());});}}getFolders(){return this.folders}getConversations(e){const t=this.siteAdapter.getCurrentCid?.()||null;let n=Object.values(this.conversations).filter(e=>this.matchesCid(e,t));return e&&(n=n.filter(t=>t.folderId===e)),n}createFolder(e,t){return Yp().addFolder(e,t)}updateFolder(e,t){Yp().updateFolder(e,t);}deleteFolder(e){"inbox"!==e&&(Vp().moveConversationsToInbox(e),Yp().deleteFolder(e));}moveFolder(e,t){Yp().moveFolder(e,t);}async deleteConversation(e){const t=await this.deleteConversations([e]);return t.results.length>0?t.results[0]:{id:e,localDeleted:false,remoteEnabled:this.syncDelete,remoteAttempted:false,remoteSuccess:false,remoteMethod:"none",reason:"not_found"}}async deleteConversations(e){const t=Array.from(new Set(e.filter(Boolean)));if(0===t.length)return {total:0,localDeletedCount:0,remoteAttemptedCount:0,remoteSuccessCount:0,remoteFailedCount:0,failedIds:[],results:[]};const n=t.map(e=>{const t=this.conversations[e];return t?t.siteId&&t.siteId!==this.siteAdapter.getSiteId()?null:{id:t.id,title:t.title,url:t.url}:null}).filter(e=>Boolean(e)),r=new Map;if(this.syncDelete&&n.length>0)try{(await this.siteAdapter.deleteConversationsOnSite(n)).forEach(e=>{r.set(e.id,e);});}catch(c){console.error(`[ConversationManager] deleteConversationsOnSite failed on ${this.siteAdapter.getName()}:`,c);const e=c instanceof Error&&c.message||"remote_delete_failed";n.forEach(t=>{r.set(t.id,{id:t.id,success:false,method:"api",reason:e});});}let o=0,i=0,a=0,s=0;const l=[];return t.forEach(e=>{const t=Boolean(this.conversations[e]),n=this.syncDelete,c=r.get(e),d=c?.method||"none",u=n&&r.has(e)&&"none"!==d,h=u&&(c?.success||false);u&&(i++,h?a++:s++),t&&(Vp().deleteConversation(e),o++),l.push({id:e,localDeleted:t,remoteEnabled:n,remoteAttempted:u,remoteSuccess:h,remoteMethod:d,reason:c?.reason||(t?void 0:"not_found")});}),o>0&&this.notifyDataChange(),{total:t.length,localDeletedCount:o,remoteAttemptedCount:i,remoteSuccessCount:a,remoteFailedCount:s,failedIds:l.filter(e=>!e.localDeleted).map(e=>e.id),results:l}}moveConversation(e,t){Vp().moveToFolder(e,t);}setLastUsedFolder(e){Vp().setLastUsedFolderId(e);}getTags(){return this.tags}createTag(e,t){return em().addTag(e,t)}updateTag(e,t,n){return em().updateTag(e,t,n)}deleteTag(e){em().deleteTag(e),Vp().removeTagFromAll(e);}setConversationTags(e,t){Vp().setConversationTags(e,t);}togglePin(e){return Vp().togglePin(e)}renameConversation(e,t){t&&Vp().updateConversation(e,{title:t});}updateConversation(e,t){Vp().updateConversation(e,t);}getConversation(e){return this.conversations[e]}getLastUsedFolderId(){return this.lastUsedFolderId}getAllConversations(){const e=this.siteAdapter.getCurrentCid?.()||null,t={};for(const[n,r]of Object.entries(this.conversations))this.matchesCid(r,e)&&(t[n]=r);return t}syncConversations(e=null,t=false){const n=this.siteAdapter.getConversationList();if(!n||0===n.length)return {newCount:0,updatedCount:0};const r=this.conversations;let o=0,i=0;const a=Date.now(),s=e||this.lastUsedFolderId||"inbox",l=Vp();return n.forEach(e=>{const t=e.id,n=r[t];if(n){const r={};let o=false;n.title!==e.title&&(r.title=e.title,o=true),e.isPinned&&!n.pinned?(r.pinned=true,o=true):!e.isPinned&&n.pinned&&this.syncUnpin&&(r.pinned=false,o=true),n.siteId||(r.siteId=this.siteAdapter.getSiteId(),o=true),e.cid&&!n.cid&&(r.cid=e.cid,o=true),o&&(l.updateConversation(t,r),i++);}else l.addConversation({id:e.id,siteId:this.siteAdapter.getSiteId(),cid:e.cid,title:e.title,url:e.url,folderId:s,pinned:e.isPinned||false,createdAt:a,updatedAt:a}),o++;}),e&&l.setLastUsedFolderId(e),{newCount:o,updatedCount:i}}matchesCid(e,t){const n=this.siteAdapter.getSiteId();return (!e.siteId||e.siteId===n)&&(t?!e.cid||e.cid===t:!e.cid)}getSidebarConversationOrder(){const e=this.siteAdapter.getConversationObserverConfig?.();if(!e)return [];const t=ei.query(e.selector,{all:true,shadow:e.shadow});return Array.from(t||[]).map(t=>e.extractInfo?.(t)?.id).filter(e=>Boolean(e))}formatTime(e){if(!e)return "";const t=new Date(e),n=(new Date).getTime()-t.getTime();return n<6e4?re("justNow"):n<36e5?Math.floor(n/6e4)+re("minutesAgo"):n<864e5?Math.floor(n/36e5)+re("hoursAgo"):n<6048e5?Math.floor(n/864e5)+re("daysAgo"):t.toLocaleDateString()}resolveConversationForExport(e){const t=this.conversations[e],n=this.siteAdapter.getCurrentConversationInfo();if(!n||n.id!==e)return t||null;const r=t?.title?.trim()||n.title?.trim()||re("untitledConversation"),o=n.url||t?.url||window.location.href,i=n.cid??t?.cid,a=n.isPinned??t?.pinned??false;if(t){const n={};let s=false;return t.title?.trim()||r===t.title||(n.title=r,s=true),o!==t.url&&(n.url=o,s=true),void 0!==i&&i!==t.cid&&(n.cid=i,s=true),a!==t.pinned&&(n.pinned=a,s=true),s?(Vp().updateConversation(e,n),this.notifyDataChange(),{...t,...n,updatedAt:Date.now()}):t}const s=Date.now(),l={id:e,siteId:this.siteAdapter.getSiteId(),cid:i,title:r,url:o,folderId:this.lastUsedFolderId||"inbox",pinned:a,createdAt:s,updatedAt:s};return this.siteAdapter.isSharePage()||(Vp().addConversation(l),this.notifyDataChange()),l}async exportConversation(e,t){if(this.siteAdapter.getSessionId()!==e)return Oo(re("exportNeedOpenFirst")),false;const n=this.resolveConversationForExport(e);if(!n)return console.error("[ConversationManager] Conversation not found:",e),false;const r=this.siteAdapter.getScrollContainer?.()||null,o=r?.scrollTop??null,i=window.scrollY,a=No.getState().settings,s={conversationId:e,format:t,includeThoughts:a.export?.includeThoughts??true};let l=false,c=null;try{if(r){let e=0,t=0;const n=50;for(;tsetTimeout(e,500));const n=r.scrollHeight;if(n===e){if(t++,t>=3)break}else t=0,e=n;}}l=!0,c=await this.siteAdapter.prepareConversationExport(s);const e=this.extractConversationMessages();if(0===e.length)return console.error("[ConversationManager] No messages found"),!1;const o=(n.title||"conversation").replace(/[<>:"/\\|?*]/g,"_").substring(0,50),i=(d=n.title||"未命名",u=this.siteAdapter.getName(),h=n.id,g={customUserName:a.export?.customUserName,customModelName:a.export?.customModelName},{title:d,id:h,url:window.location.href,exportTime:(new Date).toLocaleString(),source:u,customUserName:g?.customUserName,customModelName:g?.customModelName});let p,m,f,b="";if(a.export?.exportFilenameTimestamp){const e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0");b=`_${t}-${n}-${r}_${o}-${i}-${String(e.getSeconds()).padStart(2,"0")}`;}const y=this.siteAdapter.getName(),v=`${y.replace(/[<>:"/\\|?*]/g,"_")} - `;return "clipboard"===t?(p=Wo(i,e),await navigator.clipboard.writeText(p),Oo(re("copySuccess")),!0):("markdown"===t?(p=function(e){return e?e.startsWith("\ufeff")?e:`\ufeff${e}`:"\ufeff"}(Wo(i,e)),m=`${v}${o}${b}.md`,f="text/markdown;charset=utf-8"):"json"===t?(p=function(e,t){const n={metadata:{title:e.title,id:e.id,url:e.url,exportTime:e.exportTime,source:e.source},messages:t.map(e=>({role:e.role,content:e.content}))};return JSON.stringify(n,null,2)}(i,e),m=`${v}${o}${b}.json`,f="application/json;charset=utf-8"):(p=function(e,t){const n=[];return n.push(`${re("exportMetaConvTitle")}: ${e.title}`),n.push(`${re("exportMetaTime")}: ${e.exportTime}`),n.push(`${re("exportMetaSource")}: ${e.source}`),n.push(`${re("exportMetaUrl")}: ${e.url}`),n.push(""),n.push("=".repeat(50)),n.push(""),t.forEach(t=>{if("user"===t.role){const t=e.customUserName||re("exportUserLabel");n.push(`[${t}]`);}else {const t=e.customModelName||e.source;n.push(`[${t}]`);}n.push(t.content),n.push(""),n.push("-".repeat(50)),n.push("");}),n.join("\n")}(i,e),m=`${v}${o}${b}.txt`,f="text/plain;charset=utf-8"),await async function(e,t,n="text/plain;charset=utf-8"){try{const r=new Blob([e],{type:n}),o=URL.createObjectURL(r),i=document.createElement("a");return i.href=o,i.download=t,i.click(),URL.revokeObjectURL(o),!0}catch(r){return console.error("[Exporter] Download failed:",r),Oo("下载失败: "+(r instanceof Error?r.message:String(r))),!1}}(p,m,f),Oo(re("exportSuccess")),!0)}catch(p){return console.error("[ConversationManager] Export failed:",p),false}finally{if(l)try{await this.siteAdapter.restoreConversationAfterExport(s,c);}catch(m){console.warn("[ConversationManager] Export state restore failed:",m);}r&&null!==o?r.scrollTop=o:window.scrollTo({top:i,behavior:"auto"});}var d,u,h,g;}extractConversationMessages(){const e=[],t=this.siteAdapter.getExportConfig?.();if(!t)return console.warn("[ConversationManager] Export config not available"),e;const{userQuerySelector:n,assistantResponseSelector:r,turnSelector:o,useShadowDOM:i}=t;if(o){const t=ei.query(o,{all:true,shadow:i})||[];if(t.length>0){const o=(e,t)=>{const n=[];e.matches?.(t)&&n.push(e);return (ei.query(t,{parent:e,all:true,shadow:i})||[]).forEach(e=>{n.includes(e)||n.push(e);}),n},a=(e,t)=>{if(e===t)return 0;const n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0},s=(t,n)=>{if("user"===t){const r=this.siteAdapter.extractUserQueryExportText(n);return void e.push({role:t,content:r})}const r=this.siteAdapter.extractAssistantResponseText,o=ci.prototype.extractAssistantResponseText;let i="";r&&r!==o&&(i=r.call(this.siteAdapter,n)),i||(i=Uo(n)||n.textContent?.trim()||""),e.push({role:t,content:i});};return t.forEach(e=>{[...o(e,n).map(e=>({role:"user",element:e})),...o(e,r).map(e=>({role:"assistant",element:e}))].sort((e,t)=>a(e.element,t.element)).forEach(({role:e,element:t})=>{s(e,t);});}),e}}const a=ei.query(n,{all:true,shadow:i})||[],s=ei.query(r,{all:true,shadow:i})||[],l=Math.max(a.length,s.length);for(let c=0;c{const t=await Ao.getItem("bookmarks");return t?JSON.stringify({state:{bookmarks:JSON.parse(t)},version:0}):null},setItem:async(e,t)=>{const n=JSON.parse(t),r=n.state?.bookmarks||[];await Ao.setItem("bookmarks",JSON.stringify(r));},removeItem:async e=>{await Ao.removeItem("bookmarks");}},om=io()(lo((e,t)=>({bookmarks:[],addBookmark:(t,n,r,o,i,a)=>{const s={id:crypto.randomUUID(),sessionId:t,siteId:n,cid:r,title:o.text,level:o.level,signature:i,scrollTop:a,timestamp:Date.now()};e(e=>({bookmarks:[...e.bookmarks,s]}));},removeBookmark:t=>{e(e=>({bookmarks:e.bookmarks.filter(e=>e.id!==t)}));},updateBookmark:(t,n)=>{e(e=>({bookmarks:e.bookmarks.map(e=>e.id===t?{...e,...n}:e)}));},toggleBookmark:(e,n,r,o,i,a)=>{const s=t(),l=s.getBookmarkId(e,i);l?s.removeBookmark(l):s.addBookmark(e,n,r,o,i,a);},getBookmarksBySession:e=>t().bookmarks.filter(t=>t.sessionId===e),getBookmarkId:(e,n)=>{const r=t().bookmarks.find(t=>t.sessionId===e&&t.signature===n);return r?r.id:null},clearSessionBookmarks:t=>{e(e=>({bookmarks:e.bookmarks.filter(e=>e.sessionId!==t)}));},clearAllBookmarks:()=>{e({bookmarks:[]});}}),{name:"bookmarks",storage:ao(()=>rm)})),im="gh-inline-bookmark",am="gh-inline-bookmark--bookmarked",sm="gh-inline-bookmark-global-styles",lm="gh-inline-bookmark-scoped-styles";class cm{outlineManager;adapter;displayMode="always";unsubscribe=null;unsubscribeBookmarks=null;injectedElements=new WeakSet;injectedRoots=new WeakSet;constructor(e,t,n="always"){this.outlineManager=e,this.adapter=t,this.displayMode=n,this.injectGlobalStyles(),this.unsubscribe=e.subscribe(()=>{this.injectBookmarkIcons();}),this.unsubscribeBookmarks=om.subscribe(()=>{this.updateAllIconStates();}),this.injectBookmarkIcons(),this.setDisplayMode(n);}injectGlobalStyles(){if(document.getElementById(sm))return;const e=document.createElement("style");e.id=sm,e.textContent="\n :root {\n --gh-icon-display: flex;\n --gh-icon-opacity-default: 0.3;\n --gh-icon-opacity-parent-hover: 0.5;\n }\n\n body.gh-inline-bookmark-mode-always {\n --gh-icon-display: flex;\n --gh-icon-opacity-default: 0.3;\n --gh-icon-opacity-parent-hover: 0.3;\n }\n\n body.gh-inline-bookmark-mode-hover {\n --gh-icon-display: flex;\n --gh-icon-opacity-default: 0; /* 默认隐藏 */\n --gh-icon-opacity-parent-hover: 0.5; /* 父元素悬停时显示 */\n }\n\n body.gh-inline-bookmark-mode-hidden {\n --gh-icon-display: none;\n --gh-icon-opacity-default: 0;\n }\n ",document.head.appendChild(e);}injectScopedStyles(e){if(this.injectedRoots.has(e))return;if(e instanceof Document){if(document.getElementById(lm))return void this.injectedRoots.add(e)}else if(e.querySelector(`#${lm}`))return void this.injectedRoots.add(e);const t=document.createElement("style");t.id=lm,t.textContent=`\n .${im} {\n position: absolute;\n left: var(--gh-icon-left, -24px); /* 支持通过 CSS 变量调整位置 */\n top: 50%;\n transform: translateY(-50%);\n cursor: pointer;\n transition: opacity 0.2s, transform 0.2s;\n align-items: center;\n justify-content: center;\n width: 20px;\n height: 20px;\n z-index: 10;\n color: var(--gh-primary, #f59e0b);\n\n /* 使用 CSS 变量控制显示 */\n display: var(--gh-icon-display, flex);\n opacity: var(--gh-icon-opacity-default, 0.3);\n }\n\n /* Hover Effects depend on local structure, so must be in scoped css */\n .${im}:hover {\n opacity: 1 !important;\n transform: translateY(-50%) scale(1.1);\n }\n\n .${im}.${am} {\n opacity: 1 !important;\n }\n\n /* Parent Hover Effect */\n .gh-has-inline-bookmark:hover .${im}:not(.${am}) {\n opacity: var(--gh-icon-opacity-parent-hover, 0.5);\n }\n\n /* Ensure parent relative positioning */\n .gh-has-inline-bookmark {\n position: relative !important;\n }\n `,e instanceof Document?document.head.appendChild(t):e.appendChild(t),this.injectedRoots.add(e);}setDisplayMode(e){this.displayMode=e,document.body.classList.remove("gh-inline-bookmark-mode-always","gh-inline-bookmark-mode-hover","gh-inline-bookmark-mode-hidden"),document.body.classList.add(`gh-inline-bookmark-mode-${e}`);}injectBookmarkIcons(){const e=this.outlineManager.getFlatItems(),t=this.adapter.getSessionId(),n=om.getState();for(let r=0;r{e.stopPropagation(),e.preventDefault(),this.handleBookmarkClick(o,l,s);}),i.insertBefore(s,i.firstChild),this.injectedElements.add(i);}}createStarSvgElement(e){const t=Cu("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:e?"#f59e0b":"none",stroke:e?"#f59e0b":"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"}),n=Cu("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"});return t.appendChild(n),t}handleBookmarkClick(e,t,n){const r=om.getState(),o=this.adapter.getSessionId(),i=this.adapter.getSiteId(),a=this.adapter.getCurrentCid()||"",s=this.outlineManager.getScrollContainer(),l=e.element.offsetTop+(s?.scrollTop||0);r.toggleBookmark(o,i,a,e,t,l);}updateAllIconStates(){const e=om.getState(),t=this.adapter.getSessionId();ei.query(`.${im}`,{all:true,shadow:true}).forEach(n=>{const r=n,o=r.dataset.signature;if(!o)return;const i=null!==e.getBookmarkId(t,o);i!==r.classList.contains(am)&&(i?(r.classList.add(am),r.replaceChildren(this.createStarSvgElement(true))):(r.classList.remove(am),r.replaceChildren(this.createStarSvgElement(false))));});}cleanup(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.unsubscribeBookmarks&&(this.unsubscribeBookmarks(),this.unsubscribeBookmarks=null),document.getElementById(sm)?.remove(),document.getElementById(lm)?.remove();ei.query(`#${lm}`,{all:true,shadow:true}).forEach(e=>e.remove());ei.query(`.${im}`,{all:true,shadow:true}).forEach(e=>e.remove());ei.query(".gh-has-inline-bookmark",{all:true,shadow:true}).forEach(e=>{e.classList.remove("gh-has-inline-bookmark");}),document.body.classList.remove("gh-inline-bookmark-mode-always","gh-inline-bookmark-mode-hover","gh-inline-bookmark-mode-hidden"),this.injectedElements=new WeakSet,this.injectedRoots=new WeakSet;}}class dm{siteAdapter;settings;tree=[];flatItems=[];flatNodes=[];scrollNodes=[];scrollPositions=[];scrollHeights=[];scrollPositionsStale=true;minLevel=1;treeKey="";listeners=[];updateIntervalId=null;isAutoUpdating=false;expandLevel=6;levelCounts={};isAllExpanded=false;searchQuery="";preSearchState=null;preSearchExpandLevel=null;searchLevelManual=false;matchCount=0;bookmarkMode=false;preBookmarkModeState=null;ghostBookmarkIds=new Set;wasGenerating=false;postGenerationScheduled=false;lastTreeChangeTime=0;fallbackRefreshTimer=null;static FALLBACK_DELAY=3e3;isActive=false;isRefreshing=false;unsubscribeBookmarks=null;onExpandLevelChange;onShowUserQueriesChange;constructor(e,t,n,r){this.siteAdapter=e,this.settings=t,this.onExpandLevelChange=n,this.onShowUserQueriesChange=r,this.expandLevel=t.expandLevel??6,window.addEventListener("message",this.handleMessage.bind(this)),this.unsubscribeBookmarks=om.subscribe(()=>{this.isActive&&this.refresh();});}setActive(e){this.isActive=e,this.updateAutoUpdateState();}updateAutoUpdateState(){const e=this.settings.enabled&&this.settings.autoUpdate&&this.isActive;e&&!this.isAutoUpdating?this.startAutoUpdate():!e&&this.isAutoUpdating&&this.stopAutoUpdate();}updateSettings(e){this.settings=e,void 0!==e.expandLevel&&(this.expandLevel=e.expandLevel),this.refresh(),this.updateAutoUpdateState();}observer=null;updateDebounceTimer=null;handleMessage(e){if(e.source!==window)return;const{type:t}=e.data||{};"GH_MONITOR_START"===t?this.settings.autoUpdate&&this.startAutoUpdate():"GH_MONITOR_COMPLETE"===t&&(this.stopAutoUpdate(),this.refresh());}startAutoUpdate(){this.observer||(this.isAutoUpdating=true,this.observer=new MutationObserver(()=>{this.triggerAutoUpdate();}),this.observer.observe(document.body,{childList:true,subtree:true,characterData:true}));}stopAutoUpdate(){this.observer&&(this.observer.disconnect(),this.observer=null),this.updateDebounceTimer&&(clearTimeout(this.updateDebounceTimer),this.updateDebounceTimer=null),this.isAutoUpdating=false;}triggerAutoUpdate(){const e=1e3*(this.settings.updateInterval||2);this.updateDebounceTimer||(this.updateDebounceTimer=setTimeout(()=>{this.executeAutoUpdate();},e));}executeAutoUpdate(){this.updateDebounceTimer&&(clearTimeout(this.updateDebounceTimer),this.updateDebounceTimer=null);const e=this.siteAdapter.isGenerating();!this.wasGenerating||e||this.postGenerationScheduled||(this.postGenerationScheduled=true,setTimeout(()=>{this.postGenerationScheduled=false,this.treeKey="",this.refresh();},500)),this.wasGenerating=e;const t=this.treeKey;this.refresh(),this.treeKey!==t&&(this.lastTreeChangeTime=Date.now(),this.fallbackRefreshTimer&&clearTimeout(this.fallbackRefreshTimer),this.fallbackRefreshTimer=setTimeout(()=>{this.fallbackRefreshTimer=null,Date.now()-this.lastTreeChangeTime>=dm.FALLBACK_DELAY-100&&(this.treeKey="",this.refresh());},dm.FALLBACK_DELAY));}subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(t=>t!==e);}}notify(){this.listeners.forEach(e=>e());}getTree(){return this.tree}getFlatItems(){return this.flatItems}getSignature(e){return this.generateSignature(e)}getSearchQuery(){return this.searchQuery}getScrollContainer(){return this.siteAdapter.getScrollContainer()}markScrollPositionsStale(){this.scrollPositionsStale=true;}setBookmarkMode(e){e&&!this.bookmarkMode?(this.preBookmarkModeState=this.saveTreeCollapsedState(this.tree),this.collapseAllExpandedState(this.tree),this.expandBookmarkPaths(this.tree)):!e&&this.bookmarkMode&&this.preBookmarkModeState&&(this.restoreTreeCollapsedState(this.tree,this.preBookmarkModeState),this.preBookmarkModeState=null),this.bookmarkMode=e,this.searchQuery&&this.performSearch(this.searchQuery),this.notify();}toggleBookmarkMode(){this.setBookmarkMode(!this.bookmarkMode);}getBookmarkMode(){return this.bookmarkMode}saveTreeCollapsedState(e){const t={},n=(e,r)=>{const o=`${r}/${e.level}-${e.text}`;t[o]=e.collapsed,e.children.forEach((e,t)=>n(e,`${o}/${t}`));};return e.forEach((e,t)=>n(e,`root/${t}`)),t}restoreTreeCollapsedState(e,t){const n=(e,r)=>{const o=`${r}/${e.level}-${e.text}`;o in t&&(e.collapsed=t[o]),e.children.forEach((e,t)=>n(e,`${o}/${t}`));};e.forEach((e,t)=>n(e,`root/${t}`));}collapseAllExpandedState(e){e.forEach(e=>{e.collapsed=true,e.children.length>0&&this.collapseAllExpandedState(e.children);});}expandBookmarkPaths(e){let t=false;return e.forEach(e=>{let n=false;e.children.length>0&&(n=this.expandBookmarkPaths(e.children)),n&&(e.collapsed=false),(e.isBookmarked||n)&&(t=true);}),t}extractUserQueryText(e){return this.siteAdapter.extractUserQueryText(e)}findElementByHeading(e,t){return this.siteAdapter.findElementByHeading(e,t)} /** * 根据 queryIndex 和文本查找用户提问元素 * 用于大纲跳转时元素失效后的重新查找 * @param queryIndex 用户提问的序号(从 1 开始) * @param text 用户提问文本(用于验证和回退搜索) */findUserQueryElement(e,t){return this.siteAdapter.findUserQueryElement(e,t)}async resolveOutlineTarget(e,t){return this.siteAdapter.resolveOutlineTarget(e,t)}getState(){const e=this.settings.showUserQueries?0:1;let t;t=this.searchQuery&&!this.searchLevelManual?100:this.expandLevel??6;const n=this.settings.showUserQueries?0:1;return tt.removeBookmark(e)),this.ghostBookmarkIds.clear(),this.refresh(),e.length}generateSignature(e){if(e.id)return e.id;let t="";if(e.context)t=e.context;else try{e.element?.nextElementSibling&&(t=(e.element.nextElementSibling.textContent||"").trim().substring(0,50));}catch{}return `${e.text}::${t}`}toggleBookmark(e){const t=this.siteAdapter.getSessionId(),n=this.siteAdapter.getSiteId(),r=this.siteAdapter.getCurrentCid()||"",o=this.generateSignature(e);let i=0;e.element instanceof HTMLElement?i=e.element.offsetTop:void 0!==e.scrollTop&&(i=e.scrollTop);const a=om.getState(),s=a.getBookmarkId(t,o);s?(a.removeBookmark(s),e.isBookmarked=false,e.bookmarkId=void 0):(a.addBookmark(t,n,r,e,o,i),e.isBookmarked=true,e.bookmarkId=a.getBookmarkId(t,o)||void 0),this.notify();}refresh(e){if(this.settings.enabled&&!this.isRefreshing){this.isRefreshing=true;try{this._doRefresh(e);}finally{this.isRefreshing=false;}}}_doRefresh(e){const t=No.getState().settings,n=t?.features?.outline?.showWordCount??false;let r=this.siteAdapter.extractOutline(this.settings.maxLevel,this.settings.showUserQueries,n);const o=this.siteAdapter.getSessionId(),i=om.getState().getBookmarksBySession(o);if(this.ghostBookmarkIds=new Set,i.length>0){const e=new Set(i.map(e=>e.id));r.forEach(t=>{const n=this.generateSignature(t),r=i.find(e=>e.signature===n&&e.title===t.text);r&&(t.isBookmarked=true,t.bookmarkId=r.id,e.delete(r.id));});const t={},n={};e.forEach(e=>{const n=i.find(t=>t.id===e);n&&(t[n.title]||(t[n.title]=[]),t[n.title].push(n.id));}),r.forEach(e=>{e.isBookmarked||(n[e.text]||(n[e.text]=[]),n[e.text].push(e));});const o=om.getState();Object.keys(t).forEach(r=>{const i=t[r],a=n[r];if(i&&a&&1===i.length&&1===a.length){const t=i[0],n=a[0],r=this.generateSignature(n);o.updateBookmark(t,{signature:r}),n.isBookmarked=true,n.bookmarkId=t,e.delete(t);}}),this.ghostBookmarkIds=new Set(e);const a=[];if(e.forEach(e=>{const t=i.find(t=>t.id===e);if(t){if(0===t.level&&!this.settings.showUserQueries)return;a.push({level:t.level,text:t.title,element:null,isUserQuery:0===t.level,isBookmarked:true,isGhost:true,bookmarkId:t.id,scrollTop:t.scrollTop});}}),a.length>0){const e=e=>e.isGhost?e.scrollTop:e.element instanceof HTMLElement?e.element.offsetTop:0;r=[...r,...a].sort((t,n)=>e(t)-e(n));}}if(0===r.length)return void(this.tree.length>0&&(this.tree=[],this.flatNodes=[],this.scrollNodes=[],this.scrollPositions=[],this.scrollHeights=[],this.scrollPositionsStale=true,this.notify()));this.levelCounts={},r.forEach(e=>{this.levelCounts[e.level]=(this.levelCounts[e.level]||0)+1;});const a=r.filter(e=>!e.isUserQuery).map(e=>e.level);this.minLevel=a.length>0?Math.min(...a):1;const s=n?"wc:1":"wc:0",l=this.siteAdapter.getSessionId()||"no-session",c="undefined"!=typeof window?window.location.pathname:"",d=`${this.siteAdapter.getSiteId()}:${l}:${c}`+"|"+s+"|"+r.map(e=>`${e.text}:${e.isBookmarked}`).join("|"),u={};if(this.tree.length>0&&this.captureTreeState(this.tree,u),this.treeKey===d&&0!==this.tree.length&&void 0===e)return void(this.scrollPositionsStale=true);this.tree=this.buildTree(r,this.minLevel),this.treeKey=d,this.flatItems=r,this.flatNodes=this.flattenTree(this.tree),this.updateScrollPositions();const h=void 0!==e?e:this.expandLevel??6;this.expandLevel=h;const g=this.settings.showUserQueries?0:1,p=h0&&this.restoreTreeState(this.tree,u),this.searchQuery&&this.performSearch(this.searchQuery),this.bookmarkMode&&this.expandBookmarkPaths(this.tree);const m=Math.max(...Object.keys(this.levelCounts).map(Number),1);this.isAllExpanded=this.expandLevel>=m,this.notify();}buildTree(e,t){const n=[],r=[];let o=0;return e.forEach((e,i)=>{const a=e.isUserQuery?0:e.level-t+1;let s;e.isUserQuery&&(o++,s=o);const l={...e,relativeLevel:a,index:i,queryIndex:s,children:[],collapsed:false},c=e;for(c.isBookmarked&&(l.isBookmarked=true),c.isGhost&&(l.isGhost=true),c.bookmarkId&&(l.bookmarkId=c.bookmarkId);r.length>0&&r[r.length-1].relativeLevel>=a;)r.pop();0===r.length?n.push(l):r[r.length-1].children.push(l),r.push(l);}),n}flattenTree(e){const t=[],n=e=>{e.forEach(e=>{t.push(e),e.children.length>0&&n(e.children);});};return n(e),t}updateScrollPositions(){this.scrollNodes=[],this.scrollPositions=[],this.scrollHeights=[];const e=this.getScrollContainer();if(!e||0===this.flatNodes.length)return;const t=e.getBoundingClientRect().top,n=e.scrollTop,r=[];let o=0;const i=this.shouldKeepPreviousVisibleItem(),a=e=>{const t=e.scrollTop;if(!i||"number"!=typeof t||Number.isNaN(t))return false;const n="number"!=typeof e.scrollHeight||Number.isNaN(e.scrollHeight)?0:e.scrollHeight;return r.push({node:e,top:t,height:n,order:o}),o+=1,true};if(this.flatNodes.forEach(e=>{if(e.isGhost)return;let i=e.element;if(i&&i.isConnected||(i=e.isUserQuery&&0===e.level&&void 0!==e.queryIndex?this.findUserQueryElement(e.queryIndex,e.text):this.findElementByHeading(e.level,e.text),i&&(e.element=i)),!i||!i.isConnected)return void a(e);const s=i.getClientRects();if(0===s.length)return void a(e);const l=i.getBoundingClientRect(),c=l.top-t+n,d=l.height||s[0]?.height||0;e.scrollTop=c,e.scrollHeight=d,r.push({node:e,top:c,height:d,order:o}),o+=1;}),0===r.length)return void(this.scrollPositionsStale=false);let s=true;for(let l=1;le.top===t.top?e.order-t.order:e.top-t.top),r.forEach(e=>{this.scrollNodes.push(e.node),this.scrollPositions.push(e.top),this.scrollHeights.push(e.height);}),this.scrollPositionsStale=false;}captureTreeState(e,t){e.forEach(e=>{const n=`${e.level}_${e.text}`,r=e.children&&e.children.length>0;t[n]={collapsed:e.collapsed,forceExpanded:e.forceExpanded,hadChildren:r},r&&this.captureTreeState(e.children,t);});}restoreTreeState(e,t){e.forEach(e=>{const n=`${e.level}_${e.text}`,r=t[n];if(r){const t=e.children&&e.children.length>0;!r.hadChildren&&t||(e.collapsed=r.collapsed),void 0!==r.forceExpanded&&(e.forceExpanded=r.forceExpanded);}e.children.length>0&&this.restoreTreeState(e.children,t);});}initializeCollapsedState(e,t){e.forEach(e=>{if(e.children&&e.children.length>0){const n=e.children.every(e=>e.level>t);e.collapsed=n,this.initializeCollapsedState(e.children,t);}else e.collapsed=false;});}clearForceExpandedState(e,t){e.forEach(e=>{if(e.forceExpanded=false,e.children&&e.children.length>0){const n=e.children.every(e=>e.level>t);e.collapsed=n,this.clearForceExpandedState(e.children,t);}else e.collapsed=false;});}toggleNode(e){e.collapsed=!e.collapsed,e.collapsed||(e.forceExpanded=true),this.notify();}collapseAll(){const e=this.settings.showUserQueries?0:this.minLevel||1;this.setLevel(e);}expandAll(){const e=Math.max(...Object.keys(this.levelCounts).map(Number),1);this.setLevel(e);}setLevel(e){if(this.bookmarkMode)return void Oo(re("bookmarkModeDisableLevel"));this.expandLevel=e,this.tree.length>0&&this.clearForceExpandedState(this.tree,e);const t=Math.max(...Object.keys(this.levelCounts).map(Number),1);this.isAllExpanded=e>=t,this.searchQuery&&(this.searchLevelManual=true),this.onExpandLevelChange&&this.onExpandLevelChange(e),this.notify();}setShowUserQueries(e){this.settings.showUserQueries=e,this.refresh(),this.notify(),this.onShowUserQueriesChange&&this.onShowUserQueriesChange(e);}toggleGroupMode(){this.setShowUserQueries(!this.settings.showUserQueries);}revealNode(e){const t=e=>{e.forEach(e=>{e.forceVisible=false,e.children&&e.children.length>0&&t(e.children);});};t(this.tree);const n=(e,t,r=[])=>{for(const o of e){if(o.index===t)return r.forEach(e=>{e.collapsed=false,e.forceExpanded=true,e.forceVisible=true;}),o.forceVisible=true,true;if(o.children&&o.children.length>0&&n(o.children,t,[...r,o]))return true}return false};n(this.tree,e)&&this.notify();}clearForceVisible(){const e=t=>{t.forEach(t=>{if(t.forceVisible&&(t.forceVisible=false,t.forceExpanded=false,t.children&&t.children.length>0)){const e=t.children.every(e=>e.relativeLevel>this.expandLevel);t.collapsed=e;}t.children&&t.children.length>0&&e(t.children);});};e(this.tree),this.notify();}setSearchQuery(e){if(e)!this.searchQuery&&this.tree.length>0&&(this.preSearchState={},this.captureTreeState(this.tree,this.preSearchState),this.preSearchExpandLevel=this.expandLevel),this.tree.length>0&&this.clearForceExpandedState(this.tree,0),this.searchQuery=e,this.searchLevelManual=false,this.performSearch(e);else if(this.searchQuery="",this.searchLevelManual=false,this.tree.length>0){null!==this.preSearchExpandLevel&&(this.expandLevel=this.preSearchExpandLevel,this.preSearchExpandLevel=null);const e=this.expandLevel??6;this.clearForceExpandedState(this.tree,e),this.preSearchState&&(this.restoreTreeState(this.tree,this.preSearchState),this.preSearchState=null);}this.notify();}performSearch(e){const t=e=>e.toLowerCase(),n=t(e);let r=0;const o=e=>{let i=false;return e.forEach(e=>{const a=t(e.text).includes(n);if(e.isMatch=a,a)if(this.bookmarkMode){const t=e=>!!e.isBookmarked||(e.children?.some(t)||false);(e.isBookmarked||t(e))&&r++;}else r++;if(e.children.length>0){let t=true;if(this.bookmarkMode){const n=e=>!!e.isBookmarked||(e.children?.some(n)||false);e.isBookmarked&&!e.children.some(n)&&(t=false);}e.hasMatchedDescendant=!!t&&o(e.children);}else e.hasMatchedDescendant=false;e.hasMatchedDescendant&&(e.collapsed=false),(a||e.hasMatchedDescendant)&&(i=true);}),i};o(this.tree),this.matchCount=r;}findVisibleItemIndex(e,t){if("current"!==this.settings.followMode)return null;this.scrollPositionsStale&&this.updateScrollPositions();const n=this.scrollNodes.length;if(0===n)return null;const r=e,o=e+t;let i=0,a=n-1,s=-1;for(;i<=a;){const e=i+a>>1;this.scrollPositions[e]<=r?(s=e,i=e+1):a=e-1;}if(s>=0){const e=this.scrollPositions[s],t=this.scrollHeights[s]||0;return er)?this.scrollNodes[s].index:s+1({prompts:Sr(),_hasHydrated:false,addPrompt:t=>{const n={id:"custom_"+Date.now(),...t};return e(e=>({prompts:[...e.prompts,n]})),n},updatePrompt:(t,n)=>e(e=>({prompts:e.prompts.map(e=>e.id===t?{...e,...n}:e)})),deletePrompt:t=>e(e=>({prompts:e.prompts.filter(e=>e.id!==t)})),renameCategory:(t,n)=>e(e=>({prompts:e.prompts.map(e=>e.category===t?{...e,category:n}:e)})),deleteCategory:(t,n="未分类")=>e(e=>({prompts:e.prompts.map(e=>e.category===t?{...e,category:n}:e)})),updateOrder:t=>e(e=>{const n=[];return t.forEach(t=>{const r=e.prompts.find(e=>e.id===t);r&&n.push(r);}),e.prompts.forEach(e=>{n.find(t=>t.id===e.id)||n.push(e);}),{prompts:n}}),setHasHydrated:t=>e({_hasHydrated:t}),togglePin:t=>e(e=>({prompts:e.prompts.map(e=>e.id===t?{...e,pinned:!e.pinned}:e)})),updateLastUsed:t=>e(e=>({prompts:e.prompts.map(e=>e.id===t?{...e,lastUsedAt:Date.now()}:e)})),setPrompts:t=>e({prompts:t})}),{name:"prompts",storage:ao(()=>Ao),partialize:e=>({prompts:e.prompts}),onRehydrateStorage:()=>e=>{um.setState({_hasHydrated:true});}})),hm=()=>um.getState().prompts,gm=()=>um.getState(),pm=()=>{const e=hm(),t=new Set;return e.forEach(e=>{e.category&&t.add(e.category);}),Array.from(t)},mm=(e="",t=Wr)=>{let n=hm();if(t!==Wr&&t!==Vr&&(n=n.filter(e=>e.category===t)),e){const t=e.toLowerCase();n=n.filter(e=>e.title.toLowerCase().includes(t)||e.content.toLowerCase().includes(t));}return n},fm=Object.freeze(Object.defineProperty({__proto__:null,filterPrompts:mm,getCategories:pm,getPromptsState:hm,getPromptsStore:gm,usePromptsStore:um},Symbol.toStringTag,{value:"Module"})),bm="ophel:aistudio-submit-shortcut-synced";class ym{adapter;constructor(e){this.adapter=e;}async init(){um.getState()._hasHydrated||await new Promise(e=>{const t=um.subscribe(n=>{n._hasHydrated&&(t(),e());});});}getPrompts(){return gm().prompts}addPrompt(e){return gm().addPrompt(e)}updatePrompt(e,t){gm().updatePrompt(e,t);}deletePrompt(e){gm().deletePrompt(e);}getCategories(){return pm()}renameCategory(e,t){gm().renameCategory(e,t);}deleteCategory(e,t="未分类"){gm().deleteCategory(e,t);}updateOrder(e){gm().updateOrder(e);}filterPrompts(e="",t=Wr){return mm(e,t)}togglePin(e){gm().togglePin(e);}updateLastUsed(e){gm().updateLastUsed(e);}setPrompts(e){gm().setPrompts(e);}async insertPrompt(e){const t=[0,80,120,180,240];for(let n=0;n0&&await new Promise(e=>setTimeout(e,t[n])),this.adapter.findTextarea();if(this.adapter.insertPrompt(e))return true}return false}getEditorContent(e){return e?e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement?e.value||"":e.textContent||"":""}isElementDisabled(e){if(!e)return true;if(e instanceof HTMLButtonElement&&e.disabled)return true;if(e.hasAttribute("disabled"))return true;return "true"===e.getAttribute("aria-disabled")||"true"===e.getAttribute("data-disabled")}isElementVisible(e){if(!e||!e.isConnected)return false;if(e.closest(".gh-main-panel"))return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===parseFloat(t.opacity||"1"))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}collectSubmitButtons(e){const t=[],n=new Set;for(const r of e){const e=ei.query(r,{all:true,shadow:true});if(e&&Array.isArray(e))for(const r of e)r instanceof HTMLElement&&!n.has(r)&&(n.add(r),t.push(r));}return t}getRectDistance(e,t){const n=Math.max(e.left-t.right,t.left-e.right,0),r=Math.max(e.top-t.bottom,t.top-e.bottom,0);return Math.sqrt(n*n+r*r)}findBestSubmitButton(e,t){const n=this.adapter.findSubmitButton(t);if(n&&this.isElementVisible(n))return n;const r=this.collectSubmitButtons(e).filter(e=>this.isElementVisible(e));if(0===r.length)return null;if(!t||!t.isConnected)return r[0];const o=t.closest("form");if(o){const e=r.filter(e=>e.closest("form")===o);if(e.length>0){return e.find(e=>!this.isElementDisabled(e))||e[0]}}const i=t.getBoundingClientRect();let a=r[0],s=Number.POSITIVE_INFINITY;for(const l of r){const e=this.getRectDistance(i,l.getBoundingClientRect());esetTimeout(e,50));}return null}syncAiStudioSubmitShortcut(e="enter"){if(this.adapter.getSiteId()!==qr)return false;const t="ctrlEnter"===e?2:1;let n={};const r=localStorage.getItem("aiStudioUserPreference");if(r)try{const e=JSON.parse(r);e&&"object"==typeof e&&(n=e);}catch{}if(n.enterKeyBehavior===t)return false;try{localStorage.setItem("aiStudioUserPreference",JSON.stringify({...n,enterKeyBehavior:t}));}catch{return false}return window.dispatchEvent(new CustomEvent(bm,{detail:{submitShortcut:2===t?"ctrlEnter":"enter"}})),true}async waitForSubmitConfirmation(e,t,n){const r=Date.now()+1500,o=e.trim().length>0;for(;Date.now()0){const e=this.findBestSubmitButton(t,r);if(!e&&n.button&&!n.button.isConnected)return true;if(e&&!n.wasDisabled&&this.isElementDisabled(e))return true}await new Promise(e=>setTimeout(e,60));}return false}resolveSubmitKeyConfig(e){return "ctrlEnter"===e?{key:"Ctrl+Enter"}:"enter"===e?{key:"Enter"}:this.adapter.getSubmitKeyConfig()}dispatchSubmitByKeyboard(e,t){e.focus();const n="Ctrl+Enter"===this.resolveSubmitKeyConfig(t).key,r=/Mac|iPhone|iPad|iPod/.test(navigator.platform),o={key:"Enter",code:"Enter",keyCode:13,which:13,bubbles:true,cancelable:true,composed:true,ctrlKey:n&&!r,metaKey:n&&r,shiftKey:false};return e.dispatchEvent(new KeyboardEvent("keydown",o)),e.dispatchEvent(new KeyboardEvent("keypress",o)),e.dispatchEvent(new KeyboardEvent("keyup",o)),true}shouldRetryWithKeyboard(e){if(this.adapter.isGenerating?.())return false;const t=this.adapter.getTextareaElement()||this.adapter.findTextarea();if(!t)return false;const n=this.getEditorContent(t).replace(/[\u200B\u200C\u200D\uFEFF]/g,"").trim(),r=e.replace(/[\u200B\u200C\u200D\uFEFF]/g,"").trim();return !!n&&(!!r&&(n===r||n.includes(r)||r.includes(n)))}async submitPrompt(e){this.syncAiStudioSubmitShortcut(e??"enter");const t=this.adapter.getSubmitButtonSelectors(),n=this.adapter.getTextareaElement()||this.adapter.findTextarea(),r=this.getEditorContent(n);if(!r.replace(/[\u200B\u200C\u200D\uFEFF]/g,"").trim())return false;let o=false,i=null,a=null,s=true;if(t.length>0){a=this.findBestSubmitButton(t,n),s=this.isElementDisabled(a);let e=a;if(s){const r=null===a?2e3:500,o=await this.waitForEnabledSubmitButton(t,n,r);o&&(e=o,a=o,s=false);}e&&!this.isElementDisabled(e)&&(e.click(),i=e,o=true);}if(!o){const t=n||this.adapter.getTextareaElement()||this.adapter.findTextarea();if(!t)return false;o=this.dispatchSubmitByKeyboard(t,e);}if(!o)return false;let l=await this.waitForSubmitConfirmation(r,t,{button:i||a,clicked:!!i,wasDisabled:s});if(l)return true;if(!i||!this.shouldRetryWithKeyboard(r))return false;const c=this.adapter.getTextareaElement()||this.adapter.findTextarea();if(!c)return false;return !!this.dispatchSubmitByKeyboard(c,e)&&(l=await this.waitForSubmitConfirmation(r,t,{button:this.findBestSubmitButton(t,c),clicked:false,wasDisabled:false}),l)}}const vm=e=>({id:`q_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,content:e,createdAt:Date.now(),status:"pending",type:"prompt"}),wm=io()((e,t)=>({items:[],isProcessing:false,isPaused:false,enqueue:t=>{const n=vm(t);return e(e=>({items:[...e.items,n]})),n},enqueueMany:t=>{const n=t.map(e=>e.trim()).filter(Boolean).map(e=>vm(e));return 0===n.length?[]:(e(e=>({items:[...e.items,...n]})),n)},dequeue:()=>{const{items:n}=t(),r=n.find(e=>"pending"===e.status);return r?(e(e=>({items:e.items.map(e=>e.id===r.id?{...e,status:"sending"}:e),isProcessing:true})),r):null},remove:t=>e(e=>({items:e.items.filter(e=>e.id!==t)})),updateContent:(t,n)=>e(e=>({items:e.items.map(e=>e.id===t?{...e,content:n}:e)})),updateStatus:(t,n)=>e(e=>{const r=e.items.map(e=>e.id===t?{...e,status:n}:e),o=r.some(e=>"pending"===e.status||"sending"===e.status);return {items:r,isProcessing:o}}),clear:()=>e({items:[],isProcessing:false}),pause:()=>e({isPaused:true}),resume:()=>e({isPaused:false})}));class xm{adapter;promptManager;intervalId=null;idleCount=0;IDLE_THRESHOLD=2;POLL_INTERVAL=1e3;constructor(e,t){this.adapter=e,this.promptManager=t;}start(){this.intervalId||(this.idleCount=0,this.intervalId=setInterval(()=>this.tick(),this.POLL_INTERVAL));}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.idleCount=0;}isRunning(){return null!==this.intervalId}async tick(){const e=wm.getState();if(0===e.items.filter(e=>"pending"===e.status).length||e.isPaused)return void(this.idleCount=0);if(e.items.filter(e=>"sending"===e.status).length>0)return void(this.idleCount=0);this.adapter.isGenerating()?this.idleCount=0:(this.idleCount++,this.idleCount>=this.IDLE_THRESHOLD&&(this.idleCount=0,await this.dispatchNext()));}async dispatchNext(){const e=wm.getState(),t=e.dequeue();if(t)try{if(!(await this.promptManager.insertPrompt(t.content)))return void e.updateStatus(t.id,"failed");const n=No.getState().settings.features?.prompts?.submitShortcut??"enter";if(!(await this.promptManager.submitPrompt(n)))return void e.updateStatus(t.id,"failed");e.updateStatus(t.id,"sent");}catch(n){console.error("[QueueDispatcher] 发送失败:",n),e.updateStatus(t.id,"failed");}}async sendImmediately(e,t){try{if(!(await this.promptManager.insertPrompt(e)))return !1;return await this.promptManager.submitPrompt(t)}catch(n){return console.error("[QueueDispatcher] 立即发送失败:",n),false}}async processNextNow(){const e=wm.getState();if(e.isPaused)return false;if(this.adapter.isGenerating())return false;if(e.items.some(e=>"sending"===e.status))return false;return !!e.items.some(e=>"pending"===e.status)&&(this.idleCount=0,await this.dispatchNext(),true)}}const km=[{id:"google-gradient",name:"Google 渐变",description:"默认主题,蓝绿渐变 Header",variables:{"--gh-bg":"#ffffff","--gh-bg-secondary":"#f9fafb","--gh-bg-tertiary":"#f3f4f6","--gh-text":"#1f2937","--gh-text-secondary":"#6b7280","--gh-text-tertiary":"#9ca3af","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#e5e7eb","--gh-border-active":"#4285f4","--gh-hover":"#f3f4f6","--gh-active-bg":"#e5e7eb","--gh-input-bg":"#ffffff","--gh-input-border":"#d1d5db","--gh-input-focus-border":"#4285f4","--gh-input-focus-shadow":"0 0 0 2px rgba(66, 133, 244, 0.1)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.1)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.3)","--gh-shadow-brand":"0 4px 12px rgba(66, 133, 244, 0.3)","--gh-primary":"#4285f4","--gh-secondary":"#34a853","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #4285f4 0%, #34a853 100%)","--gh-tag-active-bg":"#4285f4","--gh-checkbox-bg":"#4f46e5","--gh-badge-text":"#4b5563","--gh-badge-bg":"#ffffff","--gh-badge-border":"#e5e7eb","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(66, 133, 244, 0.1) 0%, rgba(52, 211, 153, 0.1) 100%)","--gh-folder-bg-default":"#e0f2fe","--gh-folder-bg-expanded":"#c7d2fe","--gh-folder-bg-0":"#fef9e7","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fefce8","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(16, 185, 129, 0.25)","--gh-outline-locate-border":"#10b981","--gh-outline-locate-shadow":"rgba(16, 185, 129, 0.5)","--gh-outline-sync-bg":"rgba(52, 211, 153, 0.1)","--gh-outline-sync-border":"#34d399","--gh-user-query-bg":"rgba(66, 133, 244, 0.08)","--gh-user-query-hover-bg":"rgba(66, 133, 244, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #4285f4 0%, #34a853 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.2)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.3)","--gh-glass-text":"#ffffff","--gh-card-bg":"#ffffff","--gh-card-border":"#e5e7eb","--gh-overlay-bg":"rgba(0, 0, 0, 0.5)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.2)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.5)","--gh-emoji-selected-bg":"#dbeafe","--gh-highlight-pulse":"rgba(59, 130, 246, 0.3)","--gh-slider-dot-bg":"#d1d5db","--gh-code-bg":"rgba(0, 0, 0, 0.05)"}},{id:"purple",name:"紫罗兰",description:"优雅紫色主题",variables:{"--gh-bg":"#ffffff","--gh-bg-secondary":"#faf5ff","--gh-bg-tertiary":"#f3e8ff","--gh-text":"#1f2937","--gh-text-secondary":"#6b7280","--gh-text-tertiary":"#9ca3af","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#e9d5ff","--gh-border-active":"#8b5cf6","--gh-hover":"#f3e8ff","--gh-active-bg":"#e9d5ff","--gh-input-bg":"#ffffff","--gh-input-border":"#d8b4fe","--gh-input-focus-border":"#8b5cf6","--gh-input-focus-shadow":"0 0 0 2px rgba(139, 92, 246, 0.1)","--gh-shadow":"0 10px 40px rgba(139, 92, 246, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.1)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.3)","--gh-shadow-brand":"0 4px 12px rgba(139, 92, 246, 0.3)","--gh-primary":"#8b5cf6","--gh-secondary":"#a855f7","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #8b5cf6 0%, #a855f7 100%)","--gh-tag-active-bg":"#8b5cf6","--gh-checkbox-bg":"#8b5cf6","--gh-badge-text":"#4b5563","--gh-badge-bg":"#ffffff","--gh-badge-border":"#e9d5ff","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(139, 92, 246, 0.1) 0%, rgba(168, 85, 247, 0.1) 100%)","--gh-folder-bg-default":"#f3e8ff","--gh-folder-bg-expanded":"#e9d5ff","--gh-folder-bg-0":"#fef9e7","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fefce8","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(139, 92, 246, 0.25)","--gh-outline-locate-border":"#10b981","--gh-outline-locate-shadow":"rgba(16, 185, 129, 0.5)","--gh-outline-sync-bg":"rgba(16, 185, 129, 0.1)","--gh-outline-sync-border":"#34d399","--gh-user-query-bg":"rgba(139, 92, 246, 0.08)","--gh-user-query-hover-bg":"rgba(139, 92, 246, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #8b5cf6 0%, #a855f7 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.2)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.3)","--gh-glass-text":"#ffffff","--gh-card-bg":"#ffffff","--gh-card-border":"#e9d5ff","--gh-overlay-bg":"rgba(0, 0, 0, 0.5)","--gh-btn-shadow":"0 2px 6px rgba(139, 92, 246, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(139, 92, 246, 0.2)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.5)","--gh-emoji-selected-bg":"#f3e8ff","--gh-highlight-pulse":"rgba(139, 92, 246, 0.3)","--gh-slider-dot-bg":"#d8b4fe","--gh-code-bg":"rgba(139, 92, 246, 0.08)"}},{id:"ocean",name:"海洋蓝",description:"清新海洋主题",variables:{"--gh-bg":"#ffffff","--gh-bg-secondary":"#f0f9ff","--gh-bg-tertiary":"#e0f2fe","--gh-text":"#1f2937","--gh-text-secondary":"#6b7280","--gh-text-tertiary":"#9ca3af","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#bae6fd","--gh-border-active":"#0ea5e9","--gh-hover":"#e0f2fe","--gh-active-bg":"#bae6fd","--gh-input-bg":"#ffffff","--gh-input-border":"#7dd3fc","--gh-input-focus-border":"#0ea5e9","--gh-input-focus-shadow":"0 0 0 2px rgba(14, 165, 233, 0.1)","--gh-shadow":"0 10px 40px rgba(14, 165, 233, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.1)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.3)","--gh-shadow-brand":"0 4px 12px rgba(14, 165, 233, 0.3)","--gh-primary":"#0ea5e9","--gh-secondary":"#06b6d4","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #0ea5e9 0%, #06b6d4 100%)","--gh-tag-active-bg":"#0ea5e9","--gh-checkbox-bg":"#0ea5e9","--gh-badge-text":"#4b5563","--gh-badge-bg":"#ffffff","--gh-badge-border":"#bae6fd","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(14, 165, 233, 0.1) 0%, rgba(6, 182, 212, 0.1) 100%)","--gh-folder-bg-default":"#e0f2fe","--gh-folder-bg-expanded":"#bae6fd","--gh-folder-bg-0":"#fef9e7","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fefce8","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(14, 165, 233, 0.25)","--gh-outline-locate-border":"#f97316","--gh-outline-locate-shadow":"rgba(249, 115, 22, 0.5)","--gh-outline-sync-bg":"rgba(249, 115, 22, 0.1)","--gh-outline-sync-border":"#fb923c","--gh-user-query-bg":"rgba(14, 165, 233, 0.08)","--gh-user-query-hover-bg":"rgba(14, 165, 233, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #0ea5e9 0%, #06b6d4 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.2)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.3)","--gh-glass-text":"#ffffff","--gh-card-bg":"#ffffff","--gh-card-border":"#bae6fd","--gh-overlay-bg":"rgba(0, 0, 0, 0.5)","--gh-btn-shadow":"0 2px 6px rgba(14, 165, 233, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(14, 165, 233, 0.2)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.5)","--gh-emoji-selected-bg":"#e0f2fe","--gh-highlight-pulse":"rgba(14, 165, 233, 0.3)","--gh-slider-dot-bg":"#7dd3fc","--gh-code-bg":"rgba(14, 165, 233, 0.08)"}},{id:"sakura",name:"樱花物语",description:"柔美粉色主题",variables:{"--gh-bg":"#fff5f7","--gh-bg-secondary":"#fff0f3","--gh-bg-tertiary":"#ffe4e9","--gh-text":"#4a0418","--gh-text-secondary":"#9d4f64","--gh-text-tertiary":"#d48aa0","--gh-text-on-primary":"#881337","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#fecdd3","--gh-border-active":"#fb7185","--gh-hover":"#ffe4e9","--gh-active-bg":"#fecdd3","--gh-input-bg":"#ffffff","--gh-input-border":"#fda4af","--gh-input-focus-border":"#fb7185","--gh-input-focus-shadow":"0 0 0 2px rgba(251, 113, 133, 0.2)","--gh-shadow":"0 10px 40px rgba(251, 113, 133, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(255, 179, 193, 0.2)","--gh-shadow-lg":"0 20px 60px rgba(251, 113, 133, 0.25)","--gh-shadow-brand":"0 4px 12px rgba(251, 113, 133, 0.3)","--gh-primary":"#fb7185","--gh-secondary":"#f43f5e","--gh-danger":"#e11d48","--gh-header-bg":"linear-gradient(135deg, #ff9a9e 0%, #fad0c4 99%, #fad0c4 100%)","--gh-tag-active-bg":"#fb7185","--gh-checkbox-bg":"#fb7185","--gh-badge-text":"#881337","--gh-badge-bg":"#fff1f2","--gh-badge-border":"#fecdd3","--gh-badge-shadow":"#fff0f3","--gh-selected-gradient":"linear-gradient(135deg, rgba(251, 113, 133, 0.15) 0%, rgba(244, 63, 94, 0.1) 100%)","--gh-folder-bg-default":"#fff1f2","--gh-folder-bg-expanded":"#ffe4e6","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#f5f3ff","--gh-outline-locate-bg":"rgba(251, 113, 133, 0.2)","--gh-outline-locate-border":"#10b981","--gh-outline-locate-shadow":"rgba(16, 185, 129, 0.5)","--gh-outline-sync-bg":"rgba(16, 185, 129, 0.1)","--gh-outline-sync-border":"#34d399","--gh-user-query-bg":"rgba(251, 113, 133, 0.08)","--gh-user-query-hover-bg":"rgba(251, 113, 133, 0.15)","--gh-bg-danger":"#fff1f2","--gh-text-danger":"#e11d48","--gh-bg-danger-hover":"#ffe4e6","--gh-brand-gradient":"linear-gradient(135deg, #fb7185 0%, #f43f5e 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.4)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.6)","--gh-glass-text":"#881337","--gh-card-bg":"#ffffff","--gh-card-border":"#ffe4e6","--gh-overlay-bg":"rgba(255, 241, 242, 0.6)","--gh-btn-shadow":"0 2px 6px rgba(251, 113, 133, 0.2)","--gh-btn-shadow-hover":"0 4px 12px rgba(251, 113, 133, 0.3)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.6)","--gh-emoji-selected-bg":"#ffe4e6","--gh-highlight-pulse":"rgba(251, 113, 133, 0.3)","--gh-slider-dot-bg":"#fda4af","--gh-code-bg":"rgba(251, 113, 133, 0.08)"}},{id:"mint",name:"清新薄荷",description:"活力青绿主题",variables:{"--gh-bg":"#f0fdf9","--gh-bg-secondary":"#e6fffa","--gh-bg-tertiary":"#ccfbf1","--gh-text":"#134e4a","--gh-text-secondary":"#2d7a74","--gh-text-tertiary":"#5eead4","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#99f6e4","--gh-border-active":"#2dd4bf","--gh-hover":"#ccfbf1","--gh-active-bg":"#99f6e4","--gh-input-bg":"#ffffff","--gh-input-border":"#5eead4","--gh-input-focus-border":"#2dd4bf","--gh-input-focus-shadow":"0 0 0 2px rgba(45, 212, 191, 0.2)","--gh-shadow":"0 10px 40px rgba(45, 212, 191, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(45, 212, 191, 0.2)","--gh-shadow-lg":"0 20px 60px rgba(45, 212, 191, 0.25)","--gh-shadow-brand":"0 4px 12px rgba(45, 212, 191, 0.3)","--gh-primary":"#2dd4bf","--gh-secondary":"#14b8a6","--gh-danger":"#f87171","--gh-header-bg":"linear-gradient(135deg, #14b8a6 0%, #34d399 100%)","--gh-tag-active-bg":"#2dd4bf","--gh-checkbox-bg":"#2dd4bf","--gh-badge-text":"#115e59","--gh-badge-bg":"#ccfbf1","--gh-badge-border":"#99f6e4","--gh-badge-shadow":"#e6fffa","--gh-selected-gradient":"linear-gradient(135deg, rgba(45, 212, 191, 0.15) 0%, rgba(20, 184, 166, 0.1) 100%)","--gh-folder-bg-default":"#ccfbf1","--gh-folder-bg-expanded":"#99f6e4","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(45, 212, 191, 0.25)","--gh-outline-locate-border":"#f43f5e","--gh-outline-locate-shadow":"rgba(244, 63, 94, 0.5)","--gh-outline-sync-bg":"rgba(244, 63, 94, 0.1)","--gh-outline-sync-border":"#fb7185","--gh-user-query-bg":"rgba(45, 212, 191, 0.1)","--gh-user-query-hover-bg":"rgba(45, 212, 191, 0.2)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#f87171","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #2dd4bf 0%, #14b8a6 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.4)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.6)","--gh-glass-text":"#115e59","--gh-card-bg":"#ffffff","--gh-card-border":"#99f6e4","--gh-overlay-bg":"rgba(240, 253, 249, 0.6)","--gh-btn-shadow":"0 2px 6px rgba(45, 212, 191, 0.2)","--gh-btn-shadow-hover":"0 4px 12px rgba(45, 212, 191, 0.3)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.6)","--gh-emoji-selected-bg":"#ccfbf1","--gh-highlight-pulse":"rgba(45, 212, 191, 0.3)","--gh-slider-dot-bg":"#5eead4","--gh-code-bg":"rgba(45, 212, 191, 0.1)"}},{id:"nordic",name:"北欧霜雪",description:"极简冷淡主题",variables:{"--gh-bg":"#f8fafc","--gh-bg-secondary":"#f1f5f9","--gh-bg-tertiary":"#e2e8f0","--gh-text":"#0f172a","--gh-text-secondary":"#475569","--gh-text-tertiary":"#94a3b8","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#cbd5e1","--gh-border-active":"#64748b","--gh-hover":"#e2e8f0","--gh-active-bg":"#cbd5e1","--gh-input-bg":"#ffffff","--gh-input-border":"#cbd5e1","--gh-input-focus-border":"#64748b","--gh-input-focus-shadow":"0 0 0 2px rgba(100, 116, 139, 0.15)","--gh-shadow":"0 10px 40px rgba(15, 23, 42, 0.08)","--gh-shadow-sm":"0 1px 3px rgba(15, 23, 42, 0.05)","--gh-shadow-lg":"0 20px 60px rgba(15, 23, 42, 0.12)","--gh-shadow-brand":"0 4px 12px rgba(100, 116, 139, 0.2)","--gh-primary":"#64748b","--gh-secondary":"#475569","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #64748b 0%, #475569 100%)","--gh-tag-active-bg":"#64748b","--gh-checkbox-bg":"#64748b","--gh-badge-text":"#334155","--gh-badge-bg":"#f1f5f9","--gh-badge-border":"#cbd5e1","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(100, 116, 139, 0.1) 0%, rgba(71, 85, 105, 0.08) 100%)","--gh-folder-bg-default":"#f1f5f9","--gh-folder-bg-expanded":"#e2e8f0","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(100, 116, 139, 0.15)","--gh-outline-locate-border":"#ef4444","--gh-outline-locate-shadow":"rgba(239, 68, 68, 0.5)","--gh-outline-sync-bg":"rgba(239, 68, 68, 0.1)","--gh-outline-sync-border":"#f87171","--gh-user-query-bg":"rgba(100, 116, 139, 0.06)","--gh-user-query-hover-bg":"rgba(100, 116, 139, 0.12)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #64748b 0%, #475569 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.5)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.7)","--gh-glass-text":"#334155","--gh-card-bg":"#ffffff","--gh-card-border":"#cbd5e1","--gh-overlay-bg":"rgba(241, 245, 249, 0.6)","--gh-btn-shadow":"0 2px 6px rgba(100, 116, 139, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(100, 116, 139, 0.25)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.6)","--gh-emoji-selected-bg":"#e2e8f0","--gh-highlight-pulse":"rgba(100, 116, 139, 0.25)","--gh-slider-dot-bg":"#94a3b8","--gh-code-bg":"rgba(100, 116, 139, 0.06)"}},{id:"lemon-soda",name:"柠檬苏打",description:"明亮活力主题",variables:{"--gh-bg":"#fefce8","--gh-bg-secondary":"#fef9c3","--gh-bg-tertiary":"#fde047","--gh-text":"#854d0e","--gh-text-secondary":"#a16207","--gh-text-tertiary":"#ca8a04","--gh-text-on-primary":"#854d0e","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#fde047","--gh-border-active":"#eab308","--gh-hover":"#fef9c3","--gh-active-bg":"#fde047","--gh-input-bg":"#ffffff","--gh-input-border":"#fde047","--gh-input-focus-border":"#eab308","--gh-input-focus-shadow":"0 0 0 2px rgba(234, 179, 8, 0.2)","--gh-shadow":"0 10px 40px rgba(234, 179, 8, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(234, 179, 8, 0.2)","--gh-shadow-lg":"0 20px 60px rgba(234, 179, 8, 0.25)","--gh-shadow-brand":"0 4px 12px rgba(234, 179, 8, 0.3)","--gh-primary":"#eab308","--gh-secondary":"#ca8a04","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #eab308 0%, #84cc16 100%)","--gh-tag-active-bg":"#eab308","--gh-checkbox-bg":"#eab308","--gh-badge-text":"#854d0e","--gh-badge-bg":"#fef9c3","--gh-badge-border":"#fde047","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(234, 179, 8, 0.15) 0%, rgba(132, 204, 22, 0.1) 100%)","--gh-folder-bg-default":"#fef9c3","--gh-folder-bg-expanded":"#fde047","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(234, 179, 8, 0.2)","--gh-outline-locate-border":"#3b82f6","--gh-outline-locate-shadow":"rgba(59, 130, 246, 0.5)","--gh-outline-sync-bg":"rgba(59, 130, 246, 0.1)","--gh-outline-sync-border":"#60a5fa","--gh-user-query-bg":"rgba(234, 179, 8, 0.08)","--gh-user-query-hover-bg":"rgba(234, 179, 8, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #eab308 0%, #84cc16 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.4)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.6)","--gh-glass-text":"#854d0e","--gh-card-bg":"#ffffff","--gh-card-border":"#fde047","--gh-overlay-bg":"rgba(254, 252, 232, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(234, 179, 8, 0.2)","--gh-btn-shadow-hover":"0 4px 12px rgba(234, 179, 8, 0.3)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.8)","--gh-emoji-selected-bg":"#fde047","--gh-highlight-pulse":"rgba(234, 179, 8, 0.3)","--gh-slider-dot-bg":"#d4d4d8","--gh-code-bg":"rgba(234, 179, 8, 0.1)"}},{id:"ancient-scroll",name:"羊皮卷",description:"复古纸张主题",variables:{"--gh-bg":"#fffbeb","--gh-bg-secondary":"#fef3c7","--gh-bg-tertiary":"#fde68a","--gh-text":"#451a03","--gh-text-secondary":"#92400e","--gh-text-tertiary":"#b45309","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#fde68a","--gh-border-active":"#d97706","--gh-hover":"#fef3c7","--gh-active-bg":"#fde68a","--gh-input-bg":"#ffffff","--gh-input-border":"#fcd34d","--gh-input-focus-border":"#d97706","--gh-input-focus-shadow":"0 0 0 2px rgba(217, 119, 6, 0.2)","--gh-shadow":"0 10px 40px rgba(146, 64, 14, 0.1)","--gh-shadow-sm":"0 1px 3px rgba(146, 64, 14, 0.15)","--gh-shadow-lg":"0 20px 60px rgba(146, 64, 14, 0.2)","--gh-shadow-brand":"0 4px 12px rgba(217, 119, 6, 0.25)","--gh-primary":"#d97706","--gh-secondary":"#b45309","--gh-danger":"#dc2626","--gh-header-bg":"linear-gradient(135deg, #d97706 0%, #92400e 100%)","--gh-tag-active-bg":"#d97706","--gh-checkbox-bg":"#d97706","--gh-badge-text":"#78350f","--gh-badge-bg":"#fef3c7","--gh-badge-border":"#fcd34d","--gh-badge-shadow":"#fffbeb","--gh-selected-gradient":"linear-gradient(135deg, rgba(217, 119, 6, 0.15) 0%, rgba(146, 64, 14, 0.1) 100%)","--gh-folder-bg-default":"#fef3c7","--gh-folder-bg-expanded":"#fde68a","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(217, 119, 6, 0.2)","--gh-outline-locate-border":"#0d9488","--gh-outline-locate-shadow":"rgba(13, 148, 136, 0.5)","--gh-outline-sync-bg":"rgba(13, 148, 136, 0.1)","--gh-outline-sync-border":"#14b8a6","--gh-user-query-bg":"rgba(217, 119, 6, 0.08)","--gh-user-query-hover-bg":"rgba(217, 119, 6, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#dc2626","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #d97706 0%, #92400e 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.4)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.6)","--gh-glass-text":"#78350f","--gh-card-bg":"#fffbeb","--gh-card-border":"#fde68a","--gh-overlay-bg":"rgba(255, 251, 235, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(217, 119, 6, 0.25)","--gh-btn-shadow-hover":"0 4px 12px rgba(217, 119, 6, 0.35)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.6)","--gh-emoji-selected-bg":"#fde68a","--gh-highlight-pulse":"rgba(217, 119, 6, 0.3)","--gh-slider-dot-bg":"#d6d3d1","--gh-code-bg":"rgba(217, 119, 6, 0.08)","--gh-bg-image":"url(\"data:image/svg+xml,%3Csvg viewBox='0 0 400 400' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)' opacity='0.12'/%3E%3C/svg%3E\")"}},{id:"mono-pro",name:"极致黑白",description:"纯粹单色主题",variables:{"--gh-bg":"#ffffff","--gh-bg-secondary":"#f4f4f5","--gh-bg-tertiary":"#e4e4e7","--gh-text":"#09090b","--gh-text-secondary":"#52525b","--gh-text-tertiary":"#a1a1aa","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#e4e4e7","--gh-border-active":"#18181b","--gh-hover":"#f4f4f5","--gh-active-bg":"#e4e4e7","--gh-input-bg":"#ffffff","--gh-input-border":"#d4d4d8","--gh-input-focus-border":"#18181b","--gh-input-focus-shadow":"0 0 0 2px rgba(24, 24, 27, 0.1)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.12)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.1)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.2)","--gh-shadow-brand":"0 4px 12px rgba(0, 0, 0, 0.2)","--gh-primary":"#18181b","--gh-secondary":"#3f3f46","--gh-danger":"#71717a","--gh-header-bg":"#000000","--gh-tag-active-bg":"#18181b","--gh-checkbox-bg":"#18181b","--gh-badge-text":"#18181b","--gh-badge-bg":"#f4f4f5","--gh-badge-border":"#e4e4e7","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(24, 24, 27, 0.08) 0%, rgba(63, 63, 70, 0.05) 100%)","--gh-folder-bg-default":"#f4f4f5","--gh-folder-bg-expanded":"#e4e4e7","--gh-folder-bg-0":"#f4f4f5","--gh-folder-bg-1":"#f4f4f5","--gh-folder-bg-2":"#f4f4f5","--gh-folder-bg-3":"#f4f4f5","--gh-folder-bg-4":"#f4f4f5","--gh-folder-bg-5":"#f4f4f5","--gh-folder-bg-6":"#f4f4f5","--gh-folder-bg-7":"#f4f4f5","--gh-outline-locate-bg":"rgba(24, 24, 27, 0.08)","--gh-outline-locate-border":"#dc2626","--gh-outline-locate-shadow":"rgba(220, 38, 38, 0.5)","--gh-outline-sync-bg":"rgba(220, 38, 38, 0.1)","--gh-outline-sync-border":"#ef4444","--gh-user-query-bg":"rgba(24, 24, 27, 0.04)","--gh-user-query-hover-bg":"rgba(24, 24, 27, 0.08)","--gh-bg-danger":"#f4f4f5","--gh-text-danger":"#18181b","--gh-bg-danger-hover":"#e4e4e7","--gh-brand-gradient":"linear-gradient(135deg, #000000 0%, #333333 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.15)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.25)","--gh-glass-text":"#ffffff","--gh-card-bg":"#ffffff","--gh-card-border":"#e4e4e7","--gh-overlay-bg":"rgba(255, 255, 255, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.25)","--gh-search-highlight-bg":"rgba(0, 0, 0, 0.1)","--gh-emoji-selected-bg":"#e4e4e7","--gh-highlight-pulse":"rgba(24, 24, 27, 0.2)","--gh-slider-dot-bg":"#a1a1aa","--gh-code-bg":"rgba(24, 24, 27, 0.05)"}},{id:"porcelain",name:"青花瓷",description:"东方古典主题",variables:{"--gh-bg":"#f9fbff","--gh-bg-secondary":"#eff6ff","--gh-bg-tertiary":"#e0e7ff","--gh-text":"#1e4e79","--gh-text-secondary":"#4e7ca1","--gh-text-tertiary":"#64748b","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"rgba(78, 124, 161, 0.2)","--gh-border-active":"#1e4e79","--gh-hover":"#eff6ff","--gh-active-bg":"#dbeafe","--gh-input-bg":"#ffffff","--gh-input-border":"#bfdbfe","--gh-input-focus-border":"#1e4e79","--gh-input-focus-shadow":"0 0 0 2px rgba(30, 78, 121, 0.1)","--gh-shadow":"0 10px 40px -10px rgba(30, 78, 121, 0.15), 0 4px 12px -4px rgba(30, 78, 121, 0.1)","--gh-shadow-sm":"0 2px 6px rgba(30, 78, 121, 0.08)","--gh-shadow-lg":"0 20px 60px rgba(30, 78, 121, 0.2)","--gh-shadow-brand":"0 4px 12px rgba(30, 78, 121, 0.25)","--gh-primary":"#1e4e79","--gh-secondary":"#4e7ca1","--gh-danger":"#dc2626","--gh-header-bg":"linear-gradient(135deg, #1e4e79 0%, #2c3e50 100%)","--gh-tag-active-bg":"#1e4e79","--gh-checkbox-bg":"#1e4e79","--gh-badge-text":"#1e4e79","--gh-badge-bg":"#eff6ff","--gh-badge-border":"rgba(78, 124, 161, 0.3)","--gh-badge-shadow":"#f9fbff","--gh-selected-gradient":"linear-gradient(135deg, rgba(30, 78, 121, 0.1) 0%, rgba(78, 124, 161, 0.05) 100%)","--gh-folder-bg-default":"#eff6ff","--gh-folder-bg-expanded":"#dbeafe","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(30, 78, 121, 0.15)","--gh-outline-locate-border":"#b91c1c","--gh-outline-locate-shadow":"rgba(185, 28, 28, 0.5)","--gh-outline-sync-bg":"rgba(185, 28, 28, 0.1)","--gh-outline-sync-border":"#dc2626","--gh-user-query-bg":"rgba(30, 78, 121, 0.05)","--gh-user-query-hover-bg":"rgba(30, 78, 121, 0.1)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#dc2626","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #1e4e79 0%, #2c3e50 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.7)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.85)","--gh-glass-text":"#1e4e79","--gh-card-bg":"#ffffff","--gh-card-border":"rgba(78, 124, 161, 0.15)","--gh-overlay-bg":"rgba(249, 251, 255, 0.85)","--gh-btn-shadow":"0 2px 6px rgba(30, 78, 121, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(30, 78, 121, 0.25)","--gh-search-highlight-bg":"rgba(78, 124, 161, 0.2)","--gh-emoji-selected-bg":"#dbeafe","--gh-highlight-pulse":"rgba(30, 78, 121, 0.2)","--gh-slider-dot-bg":"#94a3b8","--gh-code-bg":"rgba(30, 78, 121, 0.06)","--gh-bg-image":"url(\"data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.5' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.1'/%3E%3C/svg%3E\")"}},{id:"shortbread",name:"奶油脆饼",description:"莫兰迪治愈主题",variables:{"--gh-bg":"#f5f5f4","--gh-bg-secondary":"#e7e5e4","--gh-bg-tertiary":"#d6d3d1","--gh-text":"#44403c","--gh-text-secondary":"#78716c","--gh-text-tertiary":"#a8a29e","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#d6d3d1","--gh-border-active":"#a8a29e","--gh-hover":"#e7e5e4","--gh-active-bg":"#d6d3d1","--gh-input-bg":"#ffffff","--gh-input-border":"#d6d3d1","--gh-input-focus-border":"#78716c","--gh-input-focus-shadow":"0 0 0 2px rgba(120, 113, 108, 0.2)","--gh-shadow":"0 10px 40px rgba(120, 113, 108, 0.1)","--gh-shadow-sm":"0 1px 3px rgba(120, 113, 108, 0.1)","--gh-shadow-lg":"0 20px 60px rgba(120, 113, 108, 0.15)","--gh-shadow-brand":"0 4px 12px rgba(120, 113, 108, 0.2)","--gh-primary":"#78716c","--gh-secondary":"#57534e","--gh-danger":"#ef4444","--gh-header-bg":"#78716c","--gh-tag-active-bg":"#78716c","--gh-checkbox-bg":"#78716c","--gh-badge-text":"#44403c","--gh-badge-bg":"#e7e5e4","--gh-badge-border":"#d6d3d1","--gh-badge-shadow":"#f5f5f4","--gh-selected-gradient":"linear-gradient(135deg, rgba(120, 113, 108, 0.15) 0%, rgba(87, 83, 78, 0.1) 100%)","--gh-folder-bg-default":"#e7e5e4","--gh-folder-bg-expanded":"#d6d3d1","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(120, 113, 108, 0.2)","--gh-outline-locate-border":"#2563eb","--gh-outline-locate-shadow":"rgba(37, 99, 235, 0.5)","--gh-outline-sync-bg":"rgba(37, 99, 235, 0.1)","--gh-outline-sync-border":"#3b82f6","--gh-user-query-bg":"rgba(120, 113, 108, 0.08)","--gh-user-query-hover-bg":"rgba(120, 113, 108, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #78716c 0%, #57534e 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.5)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.7)","--gh-glass-text":"#44403c","--gh-card-bg":"#ffffff","--gh-card-border":"#d6d3d1","--gh-overlay-bg":"rgba(245, 245, 244, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(120, 113, 108, 0.2)","--gh-btn-shadow-hover":"0 4px 12px rgba(120, 113, 108, 0.3)","--gh-search-highlight-bg":"rgba(120, 113, 108, 0.3)","--gh-emoji-selected-bg":"#d6d3d1","--gh-highlight-pulse":"rgba(120, 113, 108, 0.3)","--gh-slider-dot-bg":"#d6d3d1","--gh-code-bg":"rgba(120, 113, 108, 0.08)","--gh-bg-image":"url(\"data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.15'/%3E%3C/svg%3E\")"}},{id:"unicorn-dream",name:"独角兽",description:"梦幻童话主题",variables:{"--gh-bg":"#faf5ff","--gh-bg-secondary":"#f3e8ff","--gh-bg-tertiary":"#e9d5ff","--gh-text":"#5b21b6","--gh-text-secondary":"#7c3aed","--gh-text-tertiary":"#8b5cf6","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#e9d5ff","--gh-border-active":"#d8b4fe","--gh-hover":"#f3e8ff","--gh-active-bg":"#e9d5ff","--gh-input-bg":"#ffffff","--gh-input-border":"#e9d5ff","--gh-input-focus-border":"#22d3ee","--gh-input-focus-shadow":"0 0 0 2px rgba(34, 211, 238, 0.3)","--gh-shadow":"0 10px 40px rgba(139, 92, 246, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(139, 92, 246, 0.15)","--gh-shadow-lg":"0 20px 60px rgba(139, 92, 246, 0.2)","--gh-shadow-brand":"0 4px 12px rgba(244, 114, 182, 0.3)","--gh-primary":"#f472b6","--gh-secondary":"#22d3ee","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #f472b6 0%, #22d3ee 50%, #a78bfa 100%)","--gh-tag-active-bg":"#f472b6","--gh-checkbox-bg":"#f472b6","--gh-badge-text":"#7c3aed","--gh-badge-bg":"#f3e8ff","--gh-badge-border":"#e9d5ff","--gh-badge-shadow":"#faf5ff","--gh-selected-gradient":"linear-gradient(135deg, rgba(244, 114, 182, 0.2) 0%, rgba(34, 211, 238, 0.2) 100%)","--gh-folder-bg-default":"#f3e8ff","--gh-folder-bg-expanded":"#e9d5ff","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(167, 139, 250, 0.2)","--gh-outline-locate-border":"#a78bfa","--gh-outline-locate-shadow":"rgba(167, 139, 250, 0.5)","--gh-outline-sync-bg":"rgba(167, 139, 250, 0.15)","--gh-outline-sync-border":"#a78bfa","--gh-user-query-bg":"rgba(167, 139, 250, 0.1)","--gh-user-query-hover-bg":"rgba(167, 139, 250, 0.2)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #f472b6 0%, #22d3ee 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.4)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.6)","--gh-glass-text":"#5b21b6","--gh-card-bg":"#ffffff","--gh-card-border":"#e9d5ff","--gh-overlay-bg":"rgba(250, 245, 255, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(167, 139, 250, 0.25)","--gh-btn-shadow-hover":"0 4px 12px rgba(167, 139, 250, 0.35)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.6)","--gh-emoji-selected-bg":"#e9d5ff","--gh-highlight-pulse":"rgba(244, 114, 182, 0.3)","--gh-slider-dot-bg":"#e2e8f0","--gh-code-bg":"rgba(167, 139, 250, 0.1)","--gh-bg-image":"url(\"data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.01' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.4'/%3E%3C/svg%3E\")","--gh-bg-animation":"gh-mist-drift 20s linear infinite alternate"}}],Sm=[{id:"classic-dark",name:"经典深黑",description:"默认深色主题",variables:{"--gh-bg":"#1e1e1e","--gh-bg-secondary":"#0b0b0b","--gh-bg-tertiary":"#262626","--gh-text":"#e3e3e3","--gh-text-secondary":"#a0a0a0","--gh-text-tertiary":"#6b7280","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#333333","--gh-border-active":"#818cf8","--gh-hover":"#262626","--gh-active-bg":"#333333","--gh-input-bg":"#262626","--gh-input-border":"#404040","--gh-input-focus-border":"#818cf8","--gh-input-focus-shadow":"0 0 0 2px rgba(129, 140, 248, 0.2)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.6)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.3)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.7)","--gh-shadow-brand":"0 4px 12px rgba(129, 140, 248, 0.3)","--gh-primary":"#818cf8","--gh-secondary":"#6366f1","--gh-danger":"#fca5a5","--gh-header-bg":"#1e1e1e","--gh-tag-active-bg":"rgba(129, 140, 248, 0.6)","--gh-checkbox-bg":"#818cf8","--gh-badge-text":"#e5e7eb","--gh-badge-bg":"#374151","--gh-badge-border":"#4b5563","--gh-badge-shadow":"#1f2937","--gh-selected-gradient":"linear-gradient(135deg, rgba(129, 140, 248, 0.25) 0%, rgba(99, 102, 241, 0.15) 100%)","--gh-folder-bg-default":"rgba(66, 133, 244, 0.15)","--gh-folder-bg-expanded":"rgba(66, 133, 244, 0.3)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(52, 211, 153, 0.3)","--gh-outline-locate-border":"#fbbf24","--gh-outline-locate-shadow":"rgba(251, 191, 36, 0.6)","--gh-outline-sync-bg":"rgba(251, 191, 36, 0.15)","--gh-outline-sync-border":"#f59e0b","--gh-user-query-bg":"rgba(66, 133, 244, 0.15)","--gh-user-query-hover-bg":"rgba(66, 133, 244, 0.25)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #1a73e8 0%, #1e8e3e 100%)","--gh-brand-border":"#333333","--gh-glass-bg":"rgba(255, 255, 255, 0.08)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.12)","--gh-glass-text":"#e3e3e3","--gh-card-bg":"#0b0b0b","--gh-card-border":"#333333","--gh-overlay-bg":"rgba(0, 0, 0, 0.7)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(129, 140, 248, 0.3)","--gh-highlight-pulse":"rgba(129, 140, 248, 0.4)","--gh-slider-dot-bg":"#4b5563","--gh-code-bg":"rgba(255, 255, 255, 0.08)"}},{id:"midnight-blue",name:"午夜蓝",description:"深邃蓝色主题",variables:{"--gh-bg":"#0f172a","--gh-bg-secondary":"#020617","--gh-bg-tertiary":"#1e293b","--gh-text":"#e2e8f0","--gh-text-secondary":"#94a3b8","--gh-text-tertiary":"#64748b","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#334155","--gh-border-active":"#60a5fa","--gh-hover":"#1e293b","--gh-active-bg":"#334155","--gh-input-bg":"#1e293b","--gh-input-border":"#475569","--gh-input-focus-border":"#60a5fa","--gh-input-focus-shadow":"0 0 0 2px rgba(96, 165, 250, 0.2)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.7)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.4)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.8)","--gh-shadow-brand":"0 4px 12px rgba(96, 165, 250, 0.3)","--gh-primary":"#60a5fa","--gh-secondary":"#3b82f6","--gh-danger":"#fca5a5","--gh-header-bg":"linear-gradient(135deg, #1e40af 0%, #3b82f6 100%)","--gh-tag-active-bg":"rgba(96, 165, 250, 0.6)","--gh-checkbox-bg":"#60a5fa","--gh-badge-text":"#e2e8f0","--gh-badge-bg":"#334155","--gh-badge-border":"#475569","--gh-badge-shadow":"#1e293b","--gh-selected-gradient":"linear-gradient(135deg, rgba(96, 165, 250, 0.25) 0%, rgba(59, 130, 246, 0.15) 100%)","--gh-folder-bg-default":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-expanded":"rgba(59, 130, 246, 0.3)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(96, 165, 250, 0.3)","--gh-outline-locate-border":"#fbbf24","--gh-outline-locate-shadow":"rgba(251, 191, 36, 0.6)","--gh-outline-sync-bg":"rgba(251, 191, 36, 0.15)","--gh-outline-sync-border":"#f59e0b","--gh-user-query-bg":"rgba(96, 165, 250, 0.15)","--gh-user-query-hover-bg":"rgba(96, 165, 250, 0.25)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #1e40af 0%, #3b82f6 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.08)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.12)","--gh-glass-text":"#e2e8f0","--gh-card-bg":"#020617","--gh-card-border":"#334155","--gh-overlay-bg":"rgba(0, 0, 0, 0.7)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(96, 165, 250, 0.3)","--gh-highlight-pulse":"rgba(96, 165, 250, 0.4)","--gh-slider-dot-bg":"#475569","--gh-code-bg":"rgba(96, 165, 250, 0.12)"}},{id:"forest",name:"暗夜森林",description:"深绿色主题",variables:{"--gh-bg":"#0f1a14","--gh-bg-secondary":"#050a07","--gh-bg-tertiary":"#14261c","--gh-text":"#d1fae5","--gh-text-secondary":"#86efac","--gh-text-tertiary":"#6ee7b7","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#1f3d2b","--gh-border-active":"#34d399","--gh-hover":"#14261c","--gh-active-bg":"#1f3d2b","--gh-input-bg":"#14261c","--gh-input-border":"#2a5a3d","--gh-input-focus-border":"#34d399","--gh-input-focus-shadow":"0 0 0 2px rgba(52, 211, 153, 0.2)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.7)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.4)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.8)","--gh-shadow-brand":"0 4px 12px rgba(52, 211, 153, 0.3)","--gh-primary":"#34d399","--gh-secondary":"#10b981","--gh-danger":"#fca5a5","--gh-header-bg":"linear-gradient(135deg, #065f46 0%, #10b981 100%)","--gh-tag-active-bg":"rgba(52, 211, 153, 0.6)","--gh-checkbox-bg":"#34d399","--gh-badge-text":"#d1fae5","--gh-badge-bg":"#1f3d2b","--gh-badge-border":"#2a5a3d","--gh-badge-shadow":"#14261c","--gh-selected-gradient":"linear-gradient(135deg, rgba(52, 211, 153, 0.25) 0%, rgba(16, 185, 129, 0.15) 100%)","--gh-folder-bg-default":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-expanded":"rgba(16, 185, 129, 0.3)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(52, 211, 153, 0.3)","--gh-outline-locate-border":"#e879f9","--gh-outline-locate-shadow":"rgba(232, 121, 249, 0.6)","--gh-outline-sync-bg":"rgba(232, 121, 249, 0.15)","--gh-outline-sync-border":"#d946ef","--gh-user-query-bg":"rgba(52, 211, 153, 0.15)","--gh-user-query-hover-bg":"rgba(52, 211, 153, 0.25)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #065f46 0%, #10b981 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.08)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.12)","--gh-glass-text":"#d1fae5","--gh-card-bg":"#050a07","--gh-card-border":"#1f3d2b","--gh-overlay-bg":"rgba(0, 0, 0, 0.7)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(52, 211, 153, 0.3)","--gh-highlight-pulse":"rgba(52, 211, 153, 0.4)","--gh-slider-dot-bg":"#2a5a3d","--gh-code-bg":"rgba(52, 211, 153, 0.12)"}},{id:"cyberpunk",name:"赛博霓虹",description:"高对比科技主题",variables:{"--gh-bg":"#050505","--gh-bg-secondary":"#121212","--gh-bg-tertiary":"#1a1a1a","--gh-text":"#e0e0e0","--gh-text-secondary":"#a0a0a0","--gh-text-tertiary":"#707070","--gh-text-on-primary":"#ffffff","--gh-footer-text":"#f472b6","--gh-border":"#333333","--gh-border-active":"#f472b6","--gh-hover":"#1a1a1a","--gh-active-bg":"#262626","--gh-input-bg":"#121212","--gh-input-border":"#404040","--gh-input-focus-border":"#f472b6","--gh-input-focus-shadow":"0 0 0 2px rgba(244, 114, 182, 0.3)","--gh-shadow":"0 0 20px rgba(244, 114, 182, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.8)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.9)","--gh-shadow-brand":"0 0 15px rgba(244, 114, 182, 0.4)","--gh-primary":"#f472b6","--gh-secondary":"#22d3ee","--gh-danger":"#ff0055","--gh-header-bg":"linear-gradient(45deg, #000000 0%, #1a1a1a 100%)","--gh-tag-active-bg":"#f472b6","--gh-checkbox-bg":"#f472b6","--gh-badge-text":"#f472b6","--gh-badge-bg":"#1a1a1a","--gh-badge-border":"#333333","--gh-badge-shadow":"#000000","--gh-selected-gradient":"linear-gradient(135deg, rgba(244, 114, 182, 0.2) 0%, rgba(34, 211, 238, 0.2) 100%)","--gh-folder-bg-default":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-expanded":"rgba(34, 211, 238, 0.2)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.2)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.2)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.2)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.2)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.2)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.2)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.2)","--gh-outline-locate-bg":"rgba(244, 114, 182, 0.2)","--gh-outline-locate-border":"#facc15","--gh-outline-locate-shadow":"0 0 10px rgba(250, 204, 21, 0.6)","--gh-outline-sync-bg":"rgba(250, 204, 21, 0.15)","--gh-outline-sync-border":"#eab308","--gh-user-query-bg":"rgba(34, 211, 238, 0.1)","--gh-user-query-hover-bg":"rgba(34, 211, 238, 0.2)","--gh-bg-danger":"rgba(255, 0, 85, 0.15)","--gh-text-danger":"#ff0055","--gh-bg-danger-hover":"rgba(255, 0, 85, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #be185d 0%, #0891b2 100%)","--gh-brand-border":"#333333","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.1)","--gh-glass-text":"#f472b6","--gh-card-bg":"#0a0a0a","--gh-card-border":"#333333","--gh-overlay-bg":"rgba(0, 0, 0, 0.85)","--gh-btn-shadow":"0 0 10px rgba(244, 114, 182, 0.3)","--gh-btn-shadow-hover":"0 0 15px rgba(244, 114, 182, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.5)","--gh-emoji-selected-bg":"rgba(244, 114, 182, 0.3)","--gh-highlight-pulse":"rgba(34, 211, 238, 0.4)","--gh-slider-dot-bg":"#555555","--gh-code-bg":"rgba(244, 114, 182, 0.1)"}},{id:"coffee",name:"醇香咖啡",description:"暖调护眼主题",variables:{"--gh-bg":"#1c1917","--gh-bg-secondary":"#292524","--gh-bg-tertiary":"#44403c","--gh-text":"#e7e5e4","--gh-text-secondary":"#a8a29e","--gh-text-tertiary":"#78716c","--gh-text-on-primary":"#e7e5e4","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#44403c","--gh-border-active":"#d4a373","--gh-hover":"#292524","--gh-active-bg":"#44403c","--gh-input-bg":"#292524","--gh-input-border":"#57534e","--gh-input-focus-border":"#d4a373","--gh-input-focus-shadow":"0 0 0 2px rgba(212, 163, 115, 0.2)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.6)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.4)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.7)","--gh-shadow-brand":"0 4px 12px rgba(212, 163, 115, 0.2)","--gh-primary":"#d4a373","--gh-secondary":"#a96e45","--gh-danger":"#ef4444","--gh-header-bg":"#292524","--gh-tag-active-bg":"#d4a373","--gh-checkbox-bg":"#d4a373","--gh-badge-text":"#e7e5e4","--gh-badge-bg":"#44403c","--gh-badge-border":"#57534e","--gh-badge-shadow":"#1c1917","--gh-selected-gradient":"linear-gradient(135deg, rgba(212, 163, 115, 0.2) 0%, rgba(169, 110, 69, 0.15) 100%)","--gh-folder-bg-default":"rgba(212, 163, 115, 0.15)","--gh-folder-bg-expanded":"rgba(169, 110, 69, 0.25)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(212, 163, 115, 0.25)","--gh-outline-locate-border":"#22d3ee","--gh-outline-locate-shadow":"rgba(34, 211, 238, 0.6)","--gh-outline-sync-bg":"rgba(34, 211, 238, 0.15)","--gh-outline-sync-border":"#06b6d4","--gh-user-query-bg":"rgba(212, 163, 115, 0.1)","--gh-user-query-hover-bg":"rgba(212, 163, 115, 0.2)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #d4a373 0%, #a96e45 100%)","--gh-brand-border":"#44403c","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.08)","--gh-glass-text":"#e7e5e4","--gh-card-bg":"#292524","--gh-card-border":"#44403c","--gh-overlay-bg":"rgba(28, 25, 23, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(212, 163, 115, 0.25)","--gh-highlight-pulse":"rgba(212, 163, 115, 0.3)","--gh-slider-dot-bg":"#78716c","--gh-code-bg":"rgba(212, 163, 115, 0.12)"}},{id:"sunset",name:"幻梦落日",description:"紫橙渐变艺术主题",variables:{"--gh-bg":"#120a21","--gh-bg-secondary":"#1d1136","--gh-bg-tertiary":"#2a1b4b","--gh-text":"#f3e8ff","--gh-text-secondary":"#d8b4fe","--gh-text-tertiary":"#a78bfa","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#4c1d95","--gh-border-active":"#f97316","--gh-hover":"#2a1b4b","--gh-active-bg":"#392463","--gh-input-bg":"#1d1136","--gh-input-border":"#5b21b6","--gh-input-focus-border":"#f97316","--gh-input-focus-shadow":"0 0 0 2px rgba(249, 115, 22, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.5)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.3)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.6)","--gh-shadow-brand":"0 4px 12px rgba(249, 115, 22, 0.3)","--gh-primary":"#f97316","--gh-secondary":"#8b5cf6","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #4c1d95 0%, #be185d 100%)","--gh-tag-active-bg":"#f97316","--gh-checkbox-bg":"#f97316","--gh-badge-text":"#f3e8ff","--gh-badge-bg":"#2a1b4b","--gh-badge-border":"#4c1d95","--gh-badge-shadow":"#120a21","--gh-selected-gradient":"linear-gradient(135deg, rgba(139, 92, 246, 0.25) 0%, rgba(249, 115, 22, 0.2) 100%)","--gh-folder-bg-default":"rgba(139, 92, 246, 0.2)","--gh-folder-bg-expanded":"rgba(249, 115, 22, 0.3)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(249, 115, 22, 0.25)","--gh-outline-locate-border":"#22d3ee","--gh-outline-locate-shadow":"rgba(34, 211, 238, 0.6)","--gh-outline-sync-bg":"rgba(34, 211, 238, 0.15)","--gh-outline-sync-border":"#06b6d4","--gh-user-query-bg":"rgba(139, 92, 246, 0.1)","--gh-user-query-hover-bg":"rgba(139, 92, 246, 0.2)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #8b5cf6 0%, #f97316 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.1)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.15)","--gh-glass-text":"#f3e8ff","--gh-card-bg":"#1d1136","--gh-card-border":"#4c1d95","--gh-overlay-bg":"rgba(18, 10, 33, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.5)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.6)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(139, 92, 246, 0.3)","--gh-highlight-pulse":"rgba(249, 115, 22, 0.4)","--gh-slider-dot-bg":"#a78bfa","--gh-code-bg":"rgba(139, 92, 246, 0.12)"}},{id:"dracula",name:"德古拉",description:"经典极客主题",variables:{"--gh-bg":"#282a36","--gh-bg-secondary":"#21222c","--gh-bg-tertiary":"#44475a","--gh-text":"#f8f8f2","--gh-text-secondary":"#bd93f9","--gh-text-tertiary":"#6272a4","--gh-text-on-primary":"#f8f8f2","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#44475a","--gh-border-active":"#ff79c6","--gh-hover":"#44475a","--gh-active-bg":"#21222c","--gh-input-bg":"#21222c","--gh-input-border":"#6272a4","--gh-input-focus-border":"#ff79c6","--gh-input-focus-shadow":"0 0 0 2px rgba(255, 121, 198, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.5)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.3)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.6)","--gh-shadow-brand":"0 4px 12px rgba(255, 121, 198, 0.3)","--gh-primary":"#ff79c6","--gh-secondary":"#bd93f9","--gh-danger":"#ff5555","--gh-header-bg":"#21222c","--gh-tag-active-bg":"#ff79c6","--gh-checkbox-bg":"#ff79c6","--gh-badge-text":"#f8f8f2","--gh-badge-bg":"#44475a","--gh-badge-border":"#6272a4","--gh-badge-shadow":"#282a36","--gh-selected-gradient":"linear-gradient(135deg, rgba(189, 147, 249, 0.25) 0%, rgba(255, 121, 198, 0.15) 100%)","--gh-folder-bg-default":"rgba(189, 147, 249, 0.15)","--gh-folder-bg-expanded":"rgba(255, 121, 198, 0.25)","--gh-folder-bg-0":"rgba(241, 250, 140, 0.15)","--gh-folder-bg-1":"rgba(255, 121, 198, 0.15)","--gh-folder-bg-2":"rgba(189, 147, 249, 0.15)","--gh-folder-bg-3":"rgba(80, 250, 123, 0.15)","--gh-folder-bg-4":"rgba(139, 233, 253, 0.15)","--gh-folder-bg-5":"rgba(255, 184, 108, 0.15)","--gh-folder-bg-6":"rgba(139, 233, 253, 0.15)","--gh-folder-bg-7":"rgba(255, 121, 198, 0.15)","--gh-outline-locate-bg":"rgba(255, 121, 198, 0.25)","--gh-outline-locate-border":"#4ade80","--gh-outline-locate-shadow":"rgba(74, 222, 128, 0.6)","--gh-outline-sync-bg":"rgba(74, 222, 128, 0.15)","--gh-outline-sync-border":"#22c55e","--gh-user-query-bg":"rgba(189, 147, 249, 0.1)","--gh-user-query-hover-bg":"rgba(189, 147, 249, 0.2)","--gh-bg-danger":"rgba(255, 85, 85, 0.15)","--gh-text-danger":"#ff5555","--gh-bg-danger-hover":"rgba(255, 85, 85, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #bd93f9 0%, #ff79c6 100%)","--gh-brand-border":"#44475a","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.08)","--gh-glass-text":"#f8f8f2","--gh-card-bg":"#21222c","--gh-card-border":"#44475a","--gh-overlay-bg":"rgba(40, 42, 54, 0.9)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(241, 250, 140, 0.5)","--gh-emoji-selected-bg":"rgba(189, 147, 249, 0.3)","--gh-highlight-pulse":"rgba(255, 121, 198, 0.4)","--gh-slider-dot-bg":"#6272a4","--gh-code-bg":"rgba(189, 147, 249, 0.12)"}},{id:"deep-abyss",name:"深海幽蓝",description:"静谧蓝绿主题",variables:{"--gh-bg":"#042f2e","--gh-bg-secondary":"#134e4a","--gh-bg-tertiary":"#115e59","--gh-text":"#ccfbf1","--gh-text-secondary":"#5eead4","--gh-text-tertiary":"#2dd4bf","--gh-text-on-primary":"#042f2e","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#115e59","--gh-border-active":"#2dd4bf","--gh-hover":"#134e4a","--gh-active-bg":"#115e59","--gh-input-bg":"#134e4a","--gh-input-border":"#115e59","--gh-input-focus-border":"#2dd4bf","--gh-input-focus-shadow":"0 0 0 2px rgba(45, 212, 191, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.6)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.4)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.7)","--gh-shadow-brand":"0 4px 12px rgba(45, 212, 191, 0.3)","--gh-primary":"#2dd4bf","--gh-secondary":"#0ea5e9","--gh-danger":"#f87171","--gh-header-bg":"linear-gradient(135deg, #0f766e 0%, #0369a1 100%)","--gh-tag-active-bg":"#2dd4bf","--gh-checkbox-bg":"#2dd4bf","--gh-badge-text":"#ccfbf1","--gh-badge-bg":"#115e59","--gh-badge-border":"#2d7a74","--gh-badge-shadow":"#042f2e","--gh-selected-gradient":"linear-gradient(135deg, rgba(45, 212, 191, 0.25) 0%, rgba(14, 165, 233, 0.15) 100%)","--gh-folder-bg-default":"rgba(45, 212, 191, 0.15)","--gh-folder-bg-expanded":"rgba(14, 165, 233, 0.25)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(45, 212, 191, 0.25)","--gh-outline-locate-border":"#fb923c","--gh-outline-locate-shadow":"rgba(251, 146, 60, 0.6)","--gh-outline-sync-bg":"rgba(251, 146, 60, 0.15)","--gh-outline-sync-border":"#f97316","--gh-user-query-bg":"rgba(45, 212, 191, 0.1)","--gh-user-query-hover-bg":"rgba(45, 212, 191, 0.2)","--gh-bg-danger":"rgba(248, 113, 113, 0.15)","--gh-text-danger":"#f87171","--gh-bg-danger-hover":"rgba(248, 113, 113, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #2dd4bf 0%, #0ea5e9 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.08)","--gh-glass-text":"#ccfbf1","--gh-card-bg":"#134e4a","--gh-card-border":"#115e59","--gh-overlay-bg":"rgba(4, 47, 46, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(45, 212, 191, 0.25)","--gh-highlight-pulse":"rgba(45, 212, 191, 0.3)","--gh-slider-dot-bg":"#334155","--gh-code-bg":"rgba(45, 212, 191, 0.1)","--gh-bg-image":"url(\"data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='turbulence' baseFrequency='0.02' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.15'/%3E%3C/svg%3E\")"}},{id:"crimson-moon",name:"猩红赤月",description:"暗红狂野主题",variables:{"--gh-bg":"#0f0f0f","--gh-bg-secondary":"#1c1c1c","--gh-bg-tertiary":"#2a2a2a","--gh-text":"#fecaca","--gh-text-secondary":"#f87171","--gh-text-tertiary":"#ef4444","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#450a0a","--gh-border-active":"#ef4444","--gh-hover":"#2a2a2a","--gh-active-bg":"#450a0a","--gh-input-bg":"#1c1c1c","--gh-input-border":"#450a0a","--gh-input-focus-border":"#ef4444","--gh-input-focus-shadow":"0 0 0 2px rgba(239, 68, 68, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.8)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.6)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.9)","--gh-shadow-brand":"0 4px 12px rgba(239, 68, 68, 0.3)","--gh-primary":"#ef4444","--gh-secondary":"#991b1b","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #7f1d1d 0%, #991b1b 100%)","--gh-tag-active-bg":"#ef4444","--gh-checkbox-bg":"#ef4444","--gh-badge-text":"#fee2e2","--gh-badge-bg":"#450a0a","--gh-badge-border":"#7f1d1d","--gh-badge-shadow":"#0f0f0f","--gh-selected-gradient":"linear-gradient(135deg, rgba(239, 68, 68, 0.25) 0%, rgba(153, 27, 27, 0.15) 100%)","--gh-folder-bg-default":"rgba(239, 68, 68, 0.15)","--gh-folder-bg-expanded":"rgba(153, 27, 27, 0.25)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(251, 113, 133, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(239, 68, 68, 0.25)","--gh-outline-locate-border":"#fbbf24","--gh-outline-locate-shadow":"rgba(251, 191, 36, 0.6)","--gh-outline-sync-bg":"rgba(251, 191, 36, 0.15)","--gh-outline-sync-border":"#f59e0b","--gh-user-query-bg":"rgba(239, 68, 68, 0.1)","--gh-user-query-hover-bg":"rgba(239, 68, 68, 0.2)","--gh-bg-danger":"rgba(239, 68, 68, 0.2)","--gh-text-danger":"#fecaca","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.3)","--gh-brand-gradient":"linear-gradient(135deg, #ef4444 0%, #991b1b 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.08)","--gh-glass-text":"#fecaca","--gh-card-bg":"#1c1c1c","--gh-card-border":"#450a0a","--gh-overlay-bg":"rgba(15, 15, 15, 0.9)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.5)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.6)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(239, 68, 68, 0.25)","--gh-highlight-pulse":"rgba(239, 68, 68, 0.3)","--gh-slider-dot-bg":"#f87171","--gh-code-bg":"rgba(239, 68, 68, 0.12)"}},{id:"retro-terminal",name:"黑客终端",description:"复古 CRT 主题",variables:{"--gh-bg":"#0c0c0c","--gh-bg-secondary":"#000000","--gh-bg-tertiary":"#1a1a1a","--gh-text":"#22c55e","--gh-text-secondary":"#15803d","--gh-text-tertiary":"#14532d","--gh-text-on-primary":"#22c55e","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#14532d","--gh-border-active":"#22c55e","--gh-hover":"#1a1a1a","--gh-active-bg":"#14532d","--gh-input-bg":"#000000","--gh-input-border":"#15803d","--gh-input-focus-border":"#4ade80","--gh-input-focus-shadow":"0 0 0 2px rgba(74, 222, 128, 0.3)","--gh-shadow":"0 0 20px rgba(34, 197, 94, 0.1)","--gh-shadow-sm":"0 0 10px rgba(34, 197, 94, 0.1)","--gh-shadow-lg":"0 0 40px rgba(34, 197, 94, 0.2)","--gh-shadow-brand":"0 0 15px rgba(34, 197, 94, 0.3)","--gh-primary":"#15803d","--gh-secondary":"#4ade80","--gh-danger":"#ef4444","--gh-header-bg":"#000000","--gh-tag-active-bg":"#22c55e","--gh-checkbox-bg":"#22c55e","--gh-badge-text":"#22c55e","--gh-badge-bg":"#000000","--gh-badge-border":"#15803d","--gh-badge-shadow":"#000000","--gh-selected-gradient":"linear-gradient(90deg, rgba(34, 197, 94, 0.25) 0%, rgba(34, 197, 94, 0.05) 100%)","--gh-folder-bg-default":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-expanded":"rgba(34, 197, 94, 0.2)","--gh-folder-bg-0":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-1":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-2":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-3":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-4":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-5":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-6":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-7":"rgba(34, 197, 94, 0.1)","--gh-outline-locate-bg":"rgba(34, 197, 94, 0.5)","--gh-outline-locate-border":"#f59e0b","--gh-outline-locate-shadow":"0 0 15px rgba(245, 158, 11, 0.6)","--gh-outline-sync-bg":"rgba(245, 158, 11, 0.1)","--gh-outline-sync-border":"#d97706","--gh-user-query-bg":"rgba(34, 197, 94, 0.05)","--gh-user-query-hover-bg":"rgba(34, 197, 94, 0.1)","--gh-bg-danger":"rgba(239, 68, 68, 0.2)","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.3)","--gh-brand-gradient":"linear-gradient(135deg, #022c22 0%, #15803d 100%)","--gh-brand-border":"#15803d","--gh-glass-bg":"rgba(0, 0, 0, 0.8)","--gh-glass-bg-hover":"rgba(0, 0, 0, 0.9)","--gh-glass-text":"#22c55e","--gh-card-bg":"#000000","--gh-card-border":"#15803d","--gh-overlay-bg":"rgba(0, 0, 0, 0.9)","--gh-btn-shadow":"0 0 8px rgba(34, 197, 94, 0.4)","--gh-btn-shadow-hover":"0 0 12px rgba(34, 197, 94, 0.6)","--gh-search-highlight-bg":"rgba(34, 197, 94, 0.4)","--gh-emoji-selected-bg":"rgba(34, 197, 94, 0.2)","--gh-highlight-pulse":"rgba(34, 197, 94, 0.5)","--gh-slider-dot-bg":"#14532d","--gh-code-bg":"rgba(34, 197, 94, 0.15)","--gh-bg-image":"repeating-linear-gradient(to bottom, transparent 0px, transparent 2px, rgba(34, 197, 94, 0.05) 2px, rgba(34, 197, 94, 0.05) 4px)","--gh-bg-animation":"gh-scanline 8s linear infinite"}},{id:"eva-unit-01",name:"代号:暴走",description:"机甲撞色主题",variables:{"--gh-bg":"#2e1065","--gh-bg-secondary":"#1e0b4b","--gh-bg-tertiary":"#4c1d95","--gh-text":"#d9f99d","--gh-text-secondary":"#bef264","--gh-text-tertiary":"#a3e635","--gh-text-on-primary":"#1e0b4b","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#d9f99d","--gh-border-active":"#a3e635","--gh-hover":"#4c1d95","--gh-active-bg":"#5b21b6","--gh-input-bg":"#1e0b4b","--gh-input-border":"#5b21b6","--gh-input-focus-border":"#a3e635","--gh-input-focus-shadow":"0 0 0 2px rgba(163, 230, 53, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.6)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.4)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.7)","--gh-shadow-brand":"0 4px 12px rgba(163, 230, 53, 0.3)","--gh-primary":"#a3e635","--gh-secondary":"#f97316","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #4c1d95 0%, #a3e635 100%)","--gh-tag-active-bg":"#a3e635","--gh-checkbox-bg":"#a3e635","--gh-badge-text":"#1e0b4b","--gh-badge-bg":"#d9f99d","--gh-badge-border":"#a3e635","--gh-badge-shadow":"#2e1065","--gh-selected-gradient":"linear-gradient(135deg, rgba(163, 230, 53, 0.25) 0%, rgba(249, 115, 22, 0.15) 100%)","--gh-folder-bg-default":"rgba(163, 230, 53, 0.15)","--gh-folder-bg-expanded":"rgba(249, 115, 22, 0.25)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(163, 230, 53, 0.3)","--gh-outline-locate-border":"#f97316","--gh-outline-locate-shadow":"rgba(249, 115, 22, 0.6)","--gh-outline-sync-bg":"rgba(249, 115, 22, 0.15)","--gh-outline-sync-border":"#ea580c","--gh-user-query-bg":"rgba(163, 230, 53, 0.1)","--gh-user-query-hover-bg":"rgba(163, 230, 53, 0.2)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #a3e635 0%, #f97316 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.1)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.15)","--gh-glass-text":"#d9f99d","--gh-card-bg":"#1e0b4b","--gh-card-border":"#5b21b6","--gh-overlay-bg":"rgba(46, 16, 101, 0.85)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.5)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.6)","--gh-search-highlight-bg":"rgba(249, 115, 22, 0.5)","--gh-emoji-selected-bg":"rgba(163, 230, 53, 0.3)","--gh-highlight-pulse":"rgba(163, 230, 53, 0.4)","--gh-slider-dot-bg":"#4b5563","--gh-code-bg":"rgba(163, 230, 53, 0.12)"}},{id:"aurora",name:"极光行者",description:"自然奇观主题",variables:{"--gh-bg":"#020617","--gh-bg-secondary":"#0f172a","--gh-bg-tertiary":"#1e293b","--gh-text":"#e0f2fe","--gh-text-secondary":"#bae6fd","--gh-text-tertiary":"#7dd3fc","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#1e293b","--gh-border-active":"#38bdf8","--gh-hover":"#0f172a","--gh-active-bg":"#1e293b","--gh-input-bg":"#0f172a","--gh-input-border":"#1e293b","--gh-input-focus-border":"#38bdf8","--gh-input-focus-shadow":"0 0 0 2px rgba(56, 189, 248, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.7)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.5)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.8)","--gh-shadow-brand":"0 4px 12px rgba(56, 189, 248, 0.3)","--gh-primary":"#38bdf8","--gh-secondary":"#34d399","--gh-danger":"#f87171","--gh-header-bg":"linear-gradient(135deg, #0f172a 0%, #1e40af 100%)","--gh-tag-active-bg":"#38bdf8","--gh-checkbox-bg":"#38bdf8","--gh-badge-text":"#e0f2fe","--gh-badge-bg":"#1e293b","--gh-badge-border":"#38bdf8","--gh-badge-shadow":"#020617","--gh-selected-gradient":"linear-gradient(135deg, rgba(56, 189, 248, 0.25) 0%, rgba(52, 211, 153, 0.15) 100%)","--gh-folder-bg-default":"rgba(56, 189, 248, 0.15)","--gh-folder-bg-expanded":"rgba(52, 211, 153, 0.25)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(244, 114, 182, 0.25)","--gh-outline-locate-border":"#f472b6","--gh-outline-locate-shadow":"rgba(244, 114, 182, 0.5)","--gh-outline-sync-bg":"rgba(244, 114, 182, 0.15)","--gh-outline-sync-border":"#f472b6","--gh-user-query-bg":"rgba(56, 189, 248, 0.1)","--gh-user-query-hover-bg":"rgba(56, 189, 248, 0.2)","--gh-bg-danger":"rgba(248, 113, 113, 0.15)","--gh-text-danger":"#f87171","--gh-bg-danger-hover":"rgba(248, 113, 113, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #0369a1 0%, #0f766e 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.08)","--gh-glass-text":"#e0f2fe","--gh-card-bg":"#0f172a","--gh-card-border":"#1e293b","--gh-overlay-bg":"rgba(2, 6, 23, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(56, 189, 248, 0.25)","--gh-highlight-pulse":"rgba(56, 189, 248, 0.3)","--gh-slider-dot-bg":"#7dd3fc","--gh-code-bg":"rgba(56, 189, 248, 0.12)"}}],Cm=(e,t)=>{const n=((e,t)=>("light"===t?km:Sm).find(t=>t.id===e))(e,t);return n||("light"===t?km[0]:Sm[0])},Em="google-gradient",_m="classic-dark";class Am{mode;preference;lightPresetId;darkPresetId;cleanPresetId;themeObserver=null;onModeChange;adapter;customStyles=[];skipNextDetection=false;listeners=new Set;systemMediaQuery=null;handleSystemChange=e=>{if("system"!==this.preference)return;const t=e.matches?"dark":"light";this.mode!==t&&(this.mode=t,this.emitChange(),this.syncPageTheme(t,"system"),this.onModeChange&&this.onModeChange(t,this.preference));};constructor(e,t,n,r="google-gradient",o="classic-dark"){const i="system"===e?"system":"dark"===e?"dark":"light";this.preference=i,this.mode=this.resolveMode(i),this.lightPresetId=r,this.darkPresetId=o,this.onModeChange=t,this.adapter=n,this.injectGlobalStyles(),this.ensureSystemListener();}ensureSystemListener(){!this.systemMediaQuery&&"undefined"!=typeof window&&window.matchMedia&&(this.systemMediaQuery=window.matchMedia("(prefers-color-scheme: dark)"),"function"==typeof this.systemMediaQuery.addEventListener?this.systemMediaQuery.addEventListener("change",this.handleSystemChange):"function"==typeof this.systemMediaQuery.addListener&&this.systemMediaQuery.addListener(this.handleSystemChange));}getSystemMode(){return "undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}resolveMode(e){return "system"===e?this.getSystemMode():e}syncPageTheme(e,t=e){if("system"===t){!this.applySystemPreference(e)&&this.adapter&&"function"==typeof this.adapter.toggleTheme&&this.adapter.toggleTheme(e).catch(()=>{});}else this.adapter&&"function"==typeof this.adapter.toggleTheme&&this.adapter.toggleTheme(t).catch(()=>{});this.apply(e);}applySystemPreference(e){if(!this.adapter)return false;const t=this.adapter.getSiteId();try{switch(t){case Nr:return localStorage.setItem("theme","system"),document.documentElement.className=e,window.dispatchEvent(new StorageEvent("storage",{key:"theme",newValue:"system",storageArea:localStorage})),!0;case Hr:return localStorage.setItem("theme","system"),document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(e),document.documentElement.style.colorScheme=e,document.body.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"theme",newValue:"system",storageArea:localStorage})),!0;case Rr:return localStorage.setItem("theme","system"),document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(e),document.documentElement.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"theme",newValue:"system",storageArea:localStorage})),!0;case jr:{const t=localStorage.getItem("theme");localStorage.setItem("theme","system"),document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(e),document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e,document.body&&(document.body.setAttribute("data-theme",e),document.body.style.colorScheme=e);const n=document.querySelector('meta[name="color-scheme"]');return n&&n.setAttribute("content",e),"system"!==t&&this.adapter?.toggleTheme?this.adapter.toggleTheme("system").catch(()=>{}):window.dispatchEvent(new StorageEvent("storage",{key:"theme",newValue:"system",storageArea:localStorage})),!0}case qr:{const t=localStorage.getItem("aiStudioUserPreference")||"{}";let n={};try{n=JSON.parse(t);}catch{n={};}n.theme="system";const r=JSON.stringify(n);localStorage.setItem("aiStudioUserPreference",r);const o=document.body;"dark"===e?(o.classList.add("dark-theme"),o.classList.remove("light-theme")):(o.classList.remove("dark-theme"),o.classList.add("light-theme")),o.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"aiStudioUserPreference",newValue:r,storageArea:localStorage}));const i=document.querySelector("app-root, ms-app, body");return i&&i.dispatchEvent(new CustomEvent("themechange",{detail:{theme:e}})),!0}case Ir:return localStorage.removeItem("Bard-Color-Theme"),"dark"===e?(document.body.classList.add("dark-theme"),document.body.classList.remove("light-theme")):(document.body.classList.remove("dark-theme"),document.body.classList.add("light-theme")),document.body.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"Bard-Color-Theme",newValue:null,storageArea:localStorage})),!0;case Mr:{const e={value:"auto",tabId:crypto.randomUUID(),timestamp:Date.now()},t=JSON.stringify(e);return localStorage.setItem("LSS-userThemeMode",t),window.dispatchEvent(new StorageEvent("storage",{key:"LSS-userThemeMode",newValue:t})),!0}case Dr:return !(!this.adapter||"function"!=typeof this.adapter.toggleTheme)&&(this.adapter.toggleTheme("system").catch(()=>{}),!0);default:return !1}}catch{return false}}injectGlobalStyles(){if(document.getElementById("gh-global-styles"))return;const e=document.createElement("style");e.id="gh-global-styles",e.textContent="\n ::view-transition-old(root),\n ::view-transition-new(root) {\n animation: none;\n mix-blend-mode: normal;\n }\n\n ::view-transition-new(root) {\n clip-path: circle(0px at var(--theme-x, 50%) var(--theme-y, 50%));\n }\n ",document.head.appendChild(e);}injectNativeSiteThemeAdapter(){if(!this.adapter)return;const e=this.adapter.getNativeThemeCss();if(!e||document.getElementById("ophel-native-adaptive-style"))return;const t=document.createElement("style");t.id="ophel-native-adaptive-style",t.textContent=e,document.head.appendChild(t);}setAdapter(e){this.adapter=e,this.injectNativeSiteThemeAdapter();}setOnModeChange(e){this.onModeChange=e;}updateMode(e){const t="system"===e?"system":"dark"===e?"dark":"light";this.preference=t,this.mode=this.resolveMode(t),this.emitChange(),"system"!==this.preference?this.apply(this.mode):this.syncPageTheme(this.mode,"system");}detectCurrentTheme(){const e=document.documentElement.className;if(/\bdark\b/i.test(e))return "dark";if(/\blight\b/i.test(e))return "light";const t=document.body.className;if(/\bdark-theme\b/i.test(t))return "dark";if(/\blight-theme\b/i.test(t))return "light";const n=document.body.dataset.theme||document.documentElement.dataset.theme;return "dark"===n?"dark":"light"===n?"light":"dark"===document.body.style.colorScheme?"dark":"light"}detectThemePreference(){if(!this.adapter)return null;const e=this.adapter.getSiteId();try{switch(e){case Nr:case Rr:case Hr:{const e=localStorage.getItem("theme");return "light"===e||"dark"===e||"system"===e?e:null}case qr:{const e=localStorage.getItem("aiStudioUserPreference");if(!e)return null;let t={};try{t=JSON.parse(e);}catch{t={};}const n=t.theme;return "light"===n||"dark"===n||"system"===n?n:null}case Ir:{const e=localStorage.getItem("Bard-Color-Theme");return e?/dark/i.test(e)?"dark":/light/i.test(e)?"light":null:"system"}case Mr:{const e=localStorage.getItem("LSS-userThemeMode");if(!e)return null;let t={};try{t=JSON.parse(e);}catch{t={};}const n=t.value;return "auto"===n||"system"===n?"system":"dark"===n||"light"===n?n:null}case Dr:{const e=ei.query("md-primary-tab",{all:!0,shadow:!0});if(!e||0===e.length)return null;const t=[];for(const r of e){let e=r.querySelector("md-icon");e||(e=ei.query("md-icon",{parent:r,shadow:!0}));const n=e?.textContent?.trim();if("computer"!==n&&"light_mode"!==n&&"dark_mode"!==n)continue;const o=r,i=Boolean(o.selected||o.active||0===o.tabIndex);t.push({icon:n,selected:i});}const n=t.find(e=>e.selected);return n?"computer"===n.icon?"system":"dark_mode"===n.icon?"dark":"light":null}case Pr:return "light";default:return null}}catch{return null}}apply(e){const t=e||this.mode,n=this.adapter.getSiteId()===Ir;"dark"===t?(document.body.classList.add("dark-theme"),document.body.classList.remove("light-theme"),document.body.style.colorScheme="dark"):(document.body.classList.remove("dark-theme"),document.body.style.colorScheme="light",n&&document.body.classList.add("light-theme")),this.syncPluginUITheme(t);}getCurrentPreset(){const e="dark"===this.mode?this.darkPresetId:this.lightPresetId;return Cm(e,this.mode)}setPresets(e,t){this.lightPresetId=e,this.darkPresetId=t,this.syncPluginUITheme();}setCustomStyles(e){this.customStyles=e||[];const t="dark"===this.mode?this.darkPresetId:this.lightPresetId;this.customStyles.some(e=>e.id===t)&&this.syncPluginUITheme();}syncPluginUITheme(e){const t=e||this.mode,n=document.documentElement,r="dark"===t?this.darkPresetId:this.lightPresetId,o=this.customStyles.find(e=>e.id===r);let i=null;if(o);else try{const e=Cm(r,t);i=e.variables;}catch(s){return void console.error("[ThemeManager] getPreset FAILED:",s)}const a=null!==this.themeObserver;if(a&&this.themeObserver?.disconnect(),"dark"===t?(document.body.dataset.ghMode="dark",document.body.style.colorScheme="dark"):(delete document.body.dataset.ghMode,document.body.style.colorScheme="light"),i)for(const[l,c]of Object.entries(i))n.style.setProperty(l,c);document.querySelectorAll("plasmo-csui, #ophel-userscript-root").forEach(e=>{const n=e.shadowRoot;if(n){let a=n.querySelector("#gh-theme-vars");if(a||(a=document.createElement("style"),a.id="gh-theme-vars"),o)a.textContent=o.css;else if(i){const e=(r=i,Object.entries(r).map(([e,t])=>`${e}: ${t} !important;`).join("\n "));a.textContent=`:host {\n${e}\ncolor-scheme: ${t};\n}\n\n:host([data-theme="dark"]),\n:host .gh-root[data-theme="dark"] {\n${e}\n}\n`;}e.dataset.theme=t,n.append(a);}var r;}),a&&this.themeObserver&&(this.themeObserver.observe(document.body,{attributes:true,attributeFilter:["class","data-theme","style"]}),this.themeObserver.observe(document.documentElement,{attributes:true,attributeFilter:["class","data-theme"]}));}monitorTheme(){const e=()=>{if(this.skipNextDetection)return void(this.skipNextDetection=false);const e=this.detectCurrentTheme(),t=this.detectThemePreference()??e,n="system"===t?this.getSystemMode():t;"system"===t?(this.ensureSystemListener(),e!==n?this.syncPageTheme(n,"system"):this.syncPluginUITheme(n)):this.syncPluginUITheme(n),this.mode===n&&this.preference===t||(this.mode=n,this.preference=t,this.emitChange(),this.onModeChange&&this.onModeChange(n,t));};e(),this.themeObserver||(this.themeObserver=new MutationObserver(()=>{e();}),this.themeObserver.observe(document.body,{attributes:true,attributeFilter:["class","data-theme","style"]}),this.themeObserver.observe(document.documentElement,{attributes:true,attributeFilter:["class","data-theme"]}));}stopMonitoring(){this.themeObserver&&(this.themeObserver.disconnect(),this.themeObserver=null);}getTransitionOrigin(e){let t=95,n=5;if(e&&void 0!==e.clientX)return t=e.clientX/window.innerWidth*100,n=e.clientY/window.innerHeight*100,{x:t,y:n};const r=document.getElementById("theme-toggle-btn")||document.getElementById("quick-theme-btn");if(r){const e=r.getBoundingClientRect();t=(e.left+e.width/2)/window.innerWidth*100,n=(e.top+e.height/2)/window.innerHeight*100;}return {x:t,y:n}}async applyWithTransition(e,t){const{x:n,y:r}=this.getTransitionOrigin(t);document.documentElement.style.setProperty("--theme-x",`${n}%`),document.documentElement.style.setProperty("--theme-y",`${r}%`),this.stopMonitoring();const o=window.matchMedia("(prefers-reduced-motion: reduce)").matches;if(!document.startViewTransition||o){try{e();}finally{this.monitorTheme();}return false}try{const t=document.startViewTransition(()=>{e();});t.ready.then(()=>{const e=window.innerWidth-n/100*window.innerWidth,t=window.innerHeight-r/100*window.innerHeight,o=Math.hypot(Math.max(n/100*window.innerWidth,e),Math.max(r/100*window.innerHeight,t)),i=[`circle(0px at ${n}% ${r}%)`,`circle(${o}px at ${n}% ${r}%)`];document.documentElement.animate({clipPath:i},{duration:500,easing:"ease-in",pseudoElement:"::view-transition-new(root)",fill:"forwards"});}),await t.finished.catch(()=>{});}catch{return e(),this.monitorTheme(),false}return this.skipNextDetection=true,this.monitorTheme(),true} /** * 切换主题(User Action)- 带圆形扩散动画 * @param event 可选的鼠标事件,用于确定动画中心 */async toggle(e){const t="dark"===("system"===this.preference?this.mode:this.detectCurrentTheme())?"light":"dark";this.preference=t;let n=95,r=5;if(e&&void 0!==e.clientX)n=e.clientX/window.innerWidth*100,r=e.clientY/window.innerHeight*100;else {const e=document.getElementById("theme-toggle-btn")||document.getElementById("quick-theme-btn");if(e){const t=e.getBoundingClientRect();n=(t.left+t.width/2)/window.innerWidth*100,r=(t.top+t.height/2)/window.innerHeight*100;}}document.documentElement.style.setProperty("--theme-x",`${n}%`),document.documentElement.style.setProperty("--theme-y",`${r}%`),this.stopMonitoring();const o=()=>{this.adapter&&"function"==typeof this.adapter.toggleTheme&&this.adapter.toggleTheme(t).catch(()=>{}),this.apply(t);};if(!document.startViewTransition||window.matchMedia("(prefers-reduced-motion: reduce)").matches)return o(),this.mode=t,this.emitChange(),this.monitorTheme(),t;const i=document.startViewTransition(()=>{o();});return i.ready.then(()=>{const e=window.innerWidth-n/100*window.innerWidth,t=window.innerHeight-r/100*window.innerHeight,o=Math.hypot(Math.max(n/100*window.innerWidth,e),Math.max(r/100*window.innerHeight,t)),i=[`circle(0px at ${n}% ${r}%)`,`circle(${o}px at ${n}% ${r}%)`];document.documentElement.animate({clipPath:i},{duration:500,easing:"ease-in",pseudoElement:"::view-transition-new(root)",fill:"forwards"});}),await i.finished.catch(()=>{}),this.skipNextDetection=true,this.onModeChange&&this.onModeChange(t,this.preference),this.monitorTheme(),this.mode=t,this.emitChange(),t} /** * 设置主题模式(绝对操作) * 与 toggle() 不同,此方法明确指定目标模式,无论调用多少次结果都是确定的 * 如果当前已是目标模式,则不做任何操作 * @param targetMode 目标模式 * @param event 可选的鼠标事件,用于确定动画中心 * @returns 包含最终模式和是否触发了动画 */async setMode(e,t){const n="system"===e?"system":"dark"===e?"dark":"light";if("system"===n){this.preference="system",this.ensureSystemListener();const e=this.getSystemMode(),n=this.mode!==e;let r=false;return Boolean(t)&&n?r=await this.applyWithTransition(()=>{this.syncPageTheme(e,"system");},t):this.syncPageTheme(e,"system"),n&&(this.mode=e,this.emitChange()),this.onModeChange&&this.onModeChange(e,this.preference),{mode:e,animated:r}}if(this.detectCurrentTheme()===n)return this.preference=n,this.syncPageTheme(n,n),this.onModeChange&&this.onModeChange(n,this.preference),{mode:n,animated:false};return {mode:await this.toggle(t),animated:true}}getMode(){return this.mode}getPreference(){return this.preference}getSnapshot=()=>this.mode; /** * 订阅模式变化(用于 useSyncExternalStore) * @returns 取消订阅函数 */ subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e);});emitChange(){for(const e of this.listeners)e();}destroy(){this.stopMonitoring(),this.listeners.clear();}}function Tm(e){const{mode:t,onModeChange:n,adapter:r,lightPresetId:o=Em,darkPresetId:i=_m,apply:a=false}=e,s=window.__ophelThemeManager||new Am(t,n,r,o,i);window.__ophelThemeManager||(window.__ophelThemeManager=s),s.setAdapter(r??null),s.setPresets(o,i),void 0!==n&&s.setOnModeChange(n);const l="system"===t?"system":"dark"===t?"dark":"light";return s.getPreference()!==l?s.updateMode(l):a&&s.apply(),s}class Mm{handlers=new Map;settings=null;isMac=Mn();isListening=false;processedEvents=new WeakSet;updateSettings(e){this.settings=An(e)||null;}register(e,t){this.handlers.set(e,t);}registerAll(e){for(const[t,n]of Object.entries(e))n&&this.handlers.set(t,n);}unregister(e){this.handlers.delete(e);}clearAll(){this.handlers.clear();}startListening(){this.isListening||(window.addEventListener("keydown",this.handleKeyDown,true),document.addEventListener("keydown",this.handleKeyDown,true),this.isListening=true);}stopListening(){this.isListening&&(window.removeEventListener("keydown",this.handleKeyDown,true),document.removeEventListener("keydown",this.handleKeyDown,true),this.isListening=false);}shouldIgnoreEvent(e){const t=e.target;if(!(t&&t instanceof Element))return false;return !("INPUT"!==t.tagName&&"TEXTAREA"!==t.tagName&&!t.isContentEditable&&"true"!==t.getAttribute("contenteditable")&&!t.classList.contains("ProseMirror")||e.ctrlKey||e.metaKey||e.altKey)}matchesBinding(e,t){const n=_n(t);if(!n)return false;const r=En(e.key,e.code).toLowerCase(),o=n.key.toLowerCase();let i=r===o||"arrowup"===o&&"arrowup"===r||"arrowdown"===o&&"arrowdown"===r||"arrowleft"===o&&"arrowleft"===r||"arrowright"===o&&"arrowright"===r;if(!i&&n.shift&&/^[0-9]$/.test(o)&&e.code===`Digit${o}`&&(i=true),!i)return false;const a=!!n.alt===e.altKey,s=!!n.shift===e.shiftKey;let l;if(this.isMac){l=!!n.ctrl===e.metaKey&&!e.ctrlKey;}else l=!!n.ctrl===e.ctrlKey;return a&&s&&l}handleKeyDown=e=>{if(this.processedEvents.has(e))return;if(this.processedEvents.add(e),false===e.isTrusted)return;if(!this.settings?.enabled)return;if(!this.isMac&&e.getModifierState("AltGraph"))return;if(this.shouldIgnoreEvent(e))return;const t={...xn,...this.settings.keybindings};for(const[n,r]of Object.entries(t))if(null!==r&&this.matchesBinding(e,r)){const t=this.handlers.get(n);if(t)return e.preventDefault(),e.stopPropagation(),void t()}};trigger(e){const t=this.handlers.get(e);t&&t();}destroy(){this.stopListening(),this.clearAll();}}let Im=null;let Nm=null;const Lm=new Set,Dm=()=>Nm,Rm=e=>{Nm=e,Lm.forEach(e=>e());},qm=e=>(Lm.add(e),()=>Lm.delete(e)),Pm=()=>Nm;function Bm(){const e=(window.unsafeWindow?window.unsafeWindow:window).document.querySelectorAll("iframe");for(const t of e)try{const e=t.contentDocument||t.contentWindow?.document;if(e){const t=e.querySelector('flt-semantics[style*="overflow-y: scroll"]');if(t&&t.scrollHeight>t.clientHeight)return t}}catch{}return null}function Om(e,t){{const n=Bm();if(!n)return Promise.resolve({success:false,reason:"no_flutter_container"});let r;switch(e){case "scrollToTop":n.scrollTop=0,r={success:true,scrollTop:n.scrollTop};break;case "scrollToBottom":n.scrollTop=n.scrollHeight,r={success:true,scrollTop:n.scrollTop};break;case "scrollTo":"number"==typeof t&&(n.scrollTop=t),r={success:true,scrollTop:n.scrollTop};break;case "getScrollInfo":r={success:true,scrollTop:n.scrollTop,scrollHeight:n.scrollHeight};break;default:r={success:false};}return Promise.resolve(r)}}async function zm(e){const t=await Om("getScrollInfo");if(t.success){const e=t.scrollTop||0,n=t.scrollHeight||0;return await Om("scrollToTop"),{container:Hm(),previousScrollTop:e,scrollHeight:n}}const n=e?.getScrollContainer();if(n&&n.scrollHeight>n.clientHeight){const t=n.scrollTop,r=n.scrollHeight;return "doubao"===e?.getSiteId()&&"undefined"!=typeof window&&"column-reverse"===window.getComputedStyle(n).flexDirection?n.scrollTo({top:-r,behavior:"instant",__bypassLock:true}):n.scrollTo({top:0,behavior:"instant",__bypassLock:true}),{container:n,previousScrollTop:t,scrollHeight:r}}const r=document.documentElement;return {container:r,previousScrollTop:r.scrollTop,scrollHeight:r.scrollHeight}}async function Fm(e){const t=await Om("getScrollInfo");if(t.success){const e=t.scrollTop||0;return await Om("scrollToBottom"),{container:Hm(),previousScrollTop:e}}const n=e?.getScrollContainer();if(n&&n.scrollHeight>n.clientHeight){const t=n.scrollTop;return "doubao"===e?.getSiteId()&&"undefined"!=typeof window&&"column-reverse"===window.getComputedStyle(n).flexDirection?n.scrollTo({top:0,behavior:"instant",__bypassLock:true}):n.scrollTo({top:n.scrollHeight,behavior:"instant",__bypassLock:true}),{container:n,previousScrollTop:t}}const r=document.documentElement;return {container:r,previousScrollTop:r.scrollTop}}async function jm(e,t){const n=await Om("scrollTo",t);if(n.success)return {success:true,currentScrollTop:n.scrollTop||0};const r=e?.getScrollContainer();return r&&r.scrollHeight>r.clientHeight?(r.scrollTo({top:t,behavior:"instant",__bypassLock:true}),{success:true,currentScrollTop:r.scrollTop}):(document.documentElement.scrollTo({top:t,behavior:"instant",__bypassLock:true}),{success:true,currentScrollTop:document.documentElement.scrollTop})}async function $m(e){const t=await Om("getScrollInfo");if(t.success)return {scrollTop:t.scrollTop||0,scrollHeight:t.scrollHeight||0,clientHeight:0,isFlutterMode:true};const n=e?.getScrollContainer();return n&&n.scrollHeight>n.clientHeight?{scrollTop:n.scrollTop,scrollHeight:n.scrollHeight,clientHeight:n.clientHeight,isFlutterMode:false}:{scrollTop:document.documentElement.scrollTop,scrollHeight:document.documentElement.scrollHeight,clientHeight:document.documentElement.clientHeight,isFlutterMode:false}}function Hm(){const e=document.createElement("div");return Object.defineProperty(e,"__isFlutterProxy",{value:true}),e}function Um(e){return true===e.__isFlutterProxy}const Wm=1200,Vm=2,Gm=10,Qm=50;async function Km(e){const{adapter:t,targetHeight:n,loadAll:r=false,onProgress:o,signal:i,allowShortCircuit:a=false}=e;let{previousScrollTop:s,container:l}=await zm(t);if(Um(l)){return {success:true,finalHeight:(await $m(t)).scrollHeight,heightAdded:0,previousScrollTop:s,isFlutterMode:true,silent:true}}let c=l.scrollHeight,d=c,u=0,h=0;for(;;){if(i?.aborted)return {success:false,finalHeight:l.scrollHeight,heightAdded:l.scrollHeight-c,previousScrollTop:s,isFlutterMode:false,silent:false};if(h++,h>=Qm)return {success:true,finalHeight:l.scrollHeight,heightAdded:l.scrollHeight-c,previousScrollTop:s,isFlutterMode:false,silent:false};const e="doubao"===t?.getSiteId()&&"undefined"!=typeof window&&"column-reverse"===window.getComputedStyle(l).flexDirection;if(l.scrollTop=e?-l.scrollHeight:0,l.dispatchEvent(new WheelEvent("wheel",{deltaY:-100,bubbles:true})),await Zm(Wm),i?.aborted)return {success:false,finalHeight:l.scrollHeight,heightAdded:l.scrollHeight-c,previousScrollTop:s,isFlutterMode:false,silent:false};if(t&&("HTML"===l.tagName||"BODY"===l.tagName)){const e=t.getScrollContainer();if(e&&e!==l&&"HTML"!==e.tagName&&"BODY"!==e.tagName){l=e,c=l.scrollHeight,d=l.scrollHeight;const n="doubao"===t?.getSiteId()&&"undefined"!=typeof window&&"column-reverse"===window.getComputedStyle(l).flexDirection;l.scrollTop=n?-l.scrollHeight:0;}}const r=l.scrollHeight;if(void 0!==n&&r>=n)return {success:true,finalHeight:r,heightAdded:r-c,previousScrollTop:s,isFlutterMode:false,silent:false};if(r>d)d=r,u=0,o?.(`${Math.round(r/1e3)}k`);else {u++;const e=l.scrollHeight>l.clientHeight+100,t=1===h&&r===c;if(t&&a)return {success:true,finalHeight:r,heightAdded:0,previousScrollTop:s,isFlutterMode:false,silent:true};if(t&&e)return {success:true,finalHeight:r,heightAdded:0,previousScrollTop:s,isFlutterMode:false,silent:true};if(u>=(e?Vm:Gm))return {success:true,finalHeight:r,heightAdded:r-c,previousScrollTop:s,isFlutterMode:false,silent:false}}}}function Zm(e){return new Promise(t=>setTimeout(t,e))}function Ym(e,t,n){if(!t)return;const r=t.getSessionId(),o=e.getConversations();if(0===o.length)return void Oo(re("noConversations")||"暂无会话");const i=[...o].sort((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)),a=i.findIndex(e=>e.id===r);let s;s=-1===a?0:"prev"===n?a>0?a-1:i.length-1:a(Im||(Im=new Mm),Im),[]),m=E(async()=>{if(!t)return;const e=await $m(t);Rm(e.scrollTop),await Km({adapter:t,loadAll:true,allowShortCircuit:true}),await zm(t),Oo(re("scrolledToTop")||"已滚动到顶部");},[t]),f=E(async()=>{if(!t)return;const e=await $m(t);Rm(e.scrollTop),await Fm(t),Oo(re("scrolledToBottom")||"已滚动到底部");},[t]),b=E(async()=>{if(!t)return;const e=Dm();if(null===e)return void Oo(re("noAnchor")||"无可用锚点");const n=(await $m(t)).scrollTop;await jm(t,e),Rm(n);},[t]),y=E(()=>{n&&(n.refresh(),Oo(re("outlineRefreshed")||"大纲已刷新"));},[n]),v=E(()=>{if(!n)return;n.getState().isAllExpanded?n.collapseAll():n.expandAll();},[n]),w=E(e=>{n?.setLevel(e);},[n]),x=E(()=>{n?.toggleGroupMode();},[n]),k=E(()=>{n?.toggleBookmarkMode();},[n]),S=E(()=>{n?.setShowUserQueries(true),n?.setLevel(0);},[n]),C=P(null),_=E(async e=>{if(!n)return;const t=n.getState().tree;if(!t||0===t.length)return;const r=e=>{const t=[];for(const n of e)t.push(n),n.children&&n.children.length>0&&!n.collapsed&&t.push(...r(n.children));return t},o=r(t);if(0===o.length)return;let i,a=-1;if(null!==C.current){const e=o.findIndex(e=>e.index===C.current);if(-1!==e){const t=o[e];let r=t.element;if(r&&r.isConnected||(r=await n.resolveOutlineTarget(t,t.queryIndex)),r&&r.isConnected){const t=r.getBoundingClientRect(),n=window.innerHeight;Math.abs(t.top-n/2)<2*n&&(a=e);}}}if(-1===a){const e=n.getScrollContainer();if(e){const t=n.findVisibleItemIndex(e.scrollTop,e.clientHeight);null!==t&&(a=o.findIndex(e=>e.index===t));}}i=-1===a?"prev"===e?o.length-1:0:"prev"===e?Math.max(0,a-1):Math.min(o.length-1,a+1);const s=o[i];if(s){C.current=s.index,n.revealNode(s.index);let e=s.element;if(e&&e.isConnected||(e=await n.resolveOutlineTarget(s,s.queryIndex),e&&(s.element=e)),e&&e.isConnected){e.scrollIntoView({behavior:"smooth",block:"start"});Oo(s.text?.replace(/\s+/g," ").trim()||re("locatingOutline")||"正在定位大纲位置...",1e3,{className:"gh-toast--outline-nav",maxWidth:360});}}},[n]),A=E(()=>_("prev"),[_]),T=E(()=>_("next"),[_]),I=E(()=>{Oo(re("syncingConversations")||"正在同步会话列表..."),window.dispatchEvent(new CustomEvent("ophel:refreshConversations"));},[]),N=E(()=>{s();},[s]),L=E(()=>{l?.();},[l]),D=E(e=>{d?u&&h&&h():i(),window.dispatchEvent(new CustomEvent("ophel:switchTab",{detail:{index:e}}));},[d,i,u,h]),q=E(()=>D(0),[D]),B=E(()=>D(1),[D]),O=E(()=>D(2),[D]),z=E(()=>{if(!e?.features?.outline?.enabled)return void Oo(re("outlineDisabled")||"大纲功能已禁用");!d?i():u&&h&&h(),window.__ophelPendingLocateOutline=true,window.dispatchEvent(new CustomEvent("ophel:locateOutline")),Oo(re("locatingOutline")||"正在定位大纲位置...");},[e,d,u,i,h]),F=E(()=>{if(!e?.features?.outline?.enabled)return void Oo(re("outlineDisabled")||"大纲功能已禁用");!d?i():u&&h&&h(),window.__ophelPendingSearchOutline=true,setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:searchOutline"));},50);},[e,d,u,i,h]),j=E(()=>{if(!e?.features?.conversations?.enabled)return void Oo(re("conversationsDisabled")||"会话功能已禁用");if(t?.isSharePage()||t?.isNewConversation())return void Oo(re("noConversationToLocate")||"当前无会话可定位");!d?i():u&&h&&h(),window.__ophelPendingLocateConversation=true,window.dispatchEvent(new CustomEvent("ophel:locateConversation")),Oo(re("locatingConversation")||"正在定位当前会话...");},[t,e,d,u,i,h]),$=E(()=>{if(t?.startNewConversation())return;const e=Mn(),n=new KeyboardEvent("keydown",{key:"o",code:"KeyO",ctrlKey:!e,metaKey:e,shiftKey:true,bubbles:true});document.dispatchEvent(n);},[t]),H=E(async()=>{if(!o||!t)return;const e=t.getSessionId();if(e){Oo(re("exportStarted")||"正在导出会话,请勿操作当前页面...",Bo);try{await o.exportConversation(e,"markdown"),Oo(re("exportSuccess")||"导出成功");}catch(n){console.error("Export failed:",n),Oo(re("exportFailed")||"导出失败");}}else Oo(re("exportNeedOpenFirst")||"请先打开要导出的会话");},[o,t]),U=E(async()=>{if(!t)return;const e=t.getLatestReplyText();if(e)try{await navigator.clipboard.writeText(e),Oo(re("replyCopied")||"已复制最新回复");}catch{Oo(re("copyFailed")||"复制失败");}else Oo(re("noReplyToCopy")||"无可复制内容");},[t]),W=E(()=>{g?g():Oo(re("scrollLockToggled")||"滚动锁定已切换");},[g]),V=E(()=>{if(!t)return;const e=t.findTextarea();e?(e.focus(),Oo(re("inputFocused")||"已聚焦输入框")):Oo(re("noTextarea")||"未找到输入框");},[t]),G=E(()=>{if(!t)return;if(t.stopGeneration())return void Oo(re("generationStopped")||"已停止生成");const e=['[data-testid="stop-button"]','button[aria-label*="Stop"]','button[aria-label*="停止"]',".stop-button",'md-icon-button[aria-label*="Stop"]'];for(const t of e){const e=document.querySelector(t);if(e&&null!==e.offsetParent)return e.click(),void Oo(re("generationStopped")||"已停止生成")}Oo(re("notGenerating")||"当前未在生成");},[t]),Q=E(()=>{o&&Ym(o,t,"prev");},[o,t]),K=E(()=>{o&&Ym(o,t,"next");},[o,t]),Z=E(async()=>{const e=t?.getLastCodeBlockText?.()||"";if(e.trim()){try{await navigator.clipboard.writeText(e),Oo(re("codeBlockCopied")||"代码块已复制");}catch{Oo(re("copyFailed")||"复制失败");}return}const n=Array.from(document.querySelectorAll("pre code, pre, pre.code-block, .code-block code")).filter(e=>!e.closest(".gh-root, .gh-user-query-markdown, .gh-markdown-preview"));if(0===n.length)return void Oo(re("noCodeBlock")||"未找到代码块");const r=n[n.length-1].cloneNode(true);r.querySelectorAll('button, [role="button"], svg, [aria-hidden="true"]').forEach(e=>e.remove());const o=(r.textContent||"").replace(/\r\n/g,"\n").replace(/\n+$/,"");if(o.trim())try{await navigator.clipboard.writeText(o),Oo(re("codeBlockCopied")||"代码块已复制");}catch{Oo(re("copyFailed")||"复制失败");}else Oo(re("noCodeBlock")||"未找到代码块");},[t]),Y=E(()=>{c?c():(N(),setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:"shortcuts"}}));},100));},[c,N]),J=E(()=>{if(!t)return;t.clickModelSelector()||Oo(re("modelSelectorNotFound")||"未找到模型选择器");},[t]),X=E(()=>{window.dispatchEvent(new CustomEvent("ophel:togglePromptQueue"));},[]),ee=E((e,t)=>{N(),setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:e,subTab:t}}));},100);},[N]),te=E(()=>ee("siteSettings","claude"),[ee]),ne=E(()=>ee("siteSettings","gemini"),[ee]),oe=E(()=>ee("appearance"),[ee]),ie=E(()=>ee("siteSettings","modelLock"),[ee]),ae=E(async()=>{if(location.hostname.includes("claude.ai")||location.hostname.includes("claude.com"))try{const{platform:e}=await r(async()=>{const{platform:e}=await Promise.resolve().then(()=>ku);return {platform:e}},void 0),t=await e.switchNextClaudeKey();if(t.success)Oo((re("claudeKeySwitched")||"Session Key 已切换")+`: ${t.keyName}`,2e3);else if("claudeOnlyOneKey"===t.error)Oo(re("claudeOnlyOneKeyTip")||"当前只有一个可用 Key,且正在使用中",2e3);else if("noClaudeKeys"===t.error)Oo(re("noClaudeKeys")||"未配置任何 Session Key",2e3);else {const e=re(t.error);Oo(e!==t.error?e:t.error||re("operationFailed"),2e3);}}catch(e){Oo("切换失败: "+e.message,2e3);}else Oo(re("claudeShortcutOnlyOnSite")||"快捷键仅在 Claude 站点可用",2e3);},[]);return M(()=>{const e=()=>{if("visible"===document.visibilityState&&!document.hasFocus())try{window.focus();}catch{}},t=window.setTimeout(e,150);return window.addEventListener("pageshow",e),()=>{window.clearTimeout(t),window.removeEventListener("pageshow",e);}},[]),M(()=>{p.updateSettings(e?.shortcuts);},[p,e?.shortcuts]),M(()=>{const e={[Tt]:m,[Mt]:f,[It]:b,[Nt]:i,[Lt]:a,[Dt]:N,[Rt]:q,[qt]:B,[Pt]:O,[$t]:y,[Wt]:v,[Vt]:()=>w(1),[Gt]:()=>w(2),[Qt]:()=>w(3),[Kt]:()=>w(4),[Zt]:()=>w(5),[Yt]:()=>w(6),[Bt]:x,[zt]:k,[Ot]:S,[Ht]:A,[Ut]:T,[Ft]:z,[jt]:F,[Jt]:$,[Xt]:I,[en]:j,[tn]:Q,[nn]:K,[rn]:H,[on]:U,[an]:Z,[sn]:W,[ln]:V,[cn]:L,[dn]:G,[hn]:Y,[gn]:J,[pn]:te,[mn]:ae,[fn]:ne,[bn]:oe,[yn]:ie,[un]:X};return p.registerAll(e),p.startListening(),()=>{p.stopListening(),p.clearAll();}},[p,m,f,b,i,a,N,q,B,O,y,v,w,x,k,S,A,T,z,F,$,I,j,Q,K,H,U,Z,W,V,L,G,Y,te,J,ae,ne,oe,ie,X]),p}const Xm="ophel",ef="Ophel Atlas",tf=GM_info?.script?.version??"1.0.0",nf="undefined"!=typeof window&&window.__OPHEL_USERSCRIPT_ASSET_URLS__?.icon||"",rf=({checked:e,onChange:t,disabled:n=false,size:r="md"})=>{const o="sm"===r?{w:32,h:18,thumb:14}:{w:36,h:20,thumb:16}; return ye("label",{style:{position:"relative",display:"inline-block",width:`${o.w}px`,height:`${o.h}px`,flexShrink:0},children:[ be("input",{type:"checkbox",checked:e,onChange:()=>t(!e),disabled:n,style:{opacity:0,width:0,height:0,position:"absolute"}}), be("span",{style:{position:"absolute",cursor:n?"not-allowed":"pointer",top:0,left:0,right:0,bottom:0,backgroundColor:e?"var(--gh-primary, #4285f4)":"var(--gh-input-border, #d1d5db)",borderRadius:`${o.h}px`,transition:"background-color 0.3s"},children:be("span",{style:{position:"absolute",height:`${o.thumb}px`,width:`${o.thumb}px`,left:e?o.w-o.thumb-2+"px":"2px",bottom:(o.h-o.thumb)/2+"px",backgroundColor:"var(--gh-bg, #ffffff)",borderRadius:"50%",transition:"left 0.3s"}})})]})};let of=false;const af=({children:e,onClose:t,closeOnOverlayClick:n=true,closeOnEscape:r=true,dialogClassName:o,dialogStyle:i})=>{const a=P(null);M(()=>{(()=>{if(of)return;const e=document.createElement("style");e.id="gh-dialog-styles",e.textContent="\n .gh-dialog-overlay {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: var(--gh-overlay-bg, rgba(0,0,0,0.5));\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 2147483647;\n }\n .gh-dialog {\n background: var(--gh-bg, white);\n border-radius: 12px;\n padding: 20px;\n min-width: 280px;\n max-width: 400px;\n box-shadow: var(--gh-shadow-lg, 0 20px 50px rgba(0,0,0,0.3));\n }\n .gh-dialog-title {\n font-size: 16px;\n font-weight: 600;\n color: var(--gh-text, #1f2937);\n margin-bottom: 12px;\n }\n .gh-dialog-message {\n font-size: 14px;\n color: var(--gh-text-secondary, #6b7280);\n margin-bottom: 20px;\n line-height: 1.5;\n white-space: pre-wrap;\n }\n .gh-dialog-buttons {\n display: flex;\n gap: 8px;\n justify-content: flex-end;\n }\n .gh-dialog-btn {\n padding: 8px 16px;\n border-radius: 6px;\n font-size: 14px;\n cursor: pointer;\n transition: all 0.2s;\n border: none;\n }\n .gh-dialog-btn-secondary {\n border: 1px solid var(--gh-border, #d1d5db);\n background: var(--gh-bg, white);\n color: var(--gh-text, #374151);\n }\n .gh-dialog-btn-secondary:hover {\n background: var(--gh-hover, #f3f4f6);\n }\n .gh-dialog-btn-primary {\n background: var(--gh-brand-gradient, linear-gradient(135deg, #4285f4 0%, #34a853 100%));\n color: white;\n }\n .gh-dialog-btn-danger {\n background: var(--gh-text-danger, #ef4444);\n color: white;\n }\n .gh-dialog-input {\n width: 100%;\n padding: 10px 12px;\n border: 1px solid var(--gh-border, #d1d5db);\n border-radius: 6px;\n font-size: 14px;\n box-sizing: border-box;\n margin-bottom: 20px;\n background: var(--gh-bg, #ffffff);\n color: var(--gh-text, #1f2937);\n }\n .gh-dialog-input:focus {\n outline: none;\n border-color: var(--gh-input-focus-border, #4285f4);\n }\n",document.head.appendChild(e),of=true;})();const e=e=>{r&&"Escape"===e.key&&t();};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[r,t]),M(()=>{const e=a.current;if(e)return Zo(e,{capture:false})},[]);return uu(be("div",{ref:a,className:"gh-dialog-overlay gh-interactive",onClick:n?t:void 0,children:be("div",{className:o?`gh-dialog ${o}`:"gh-dialog",style:i,onClick:e=>e.stopPropagation(),children:e})}),document.body)},sf=({title:e,message:t,confirmText:n,cancelText:r,danger:o=false,closeOnOverlayClick:i=true,onConfirm:a,onCancel:s,extraAction:l})=>ye(af,{onClose:s,closeOnOverlayClick:i,children:[ be("div",{className:"gh-dialog-title",children:e}), be("div",{className:"gh-dialog-message",children:t}), ye("div",{className:"gh-dialog-buttons",style:{justifyContent:l?"space-between":"flex-end"},children:[l&&ye("button",{className:"gh-dialog-btn",style:{background:"transparent",color:"var(--gh-primary, #4285f4)",padding:"8px 12px",textDecoration:"underline"},onClick:l.onClick,children:["↗ ",l.text]}), ye("div",{style:{display:"flex",gap:"8px"},children:[ be("button",{className:"gh-dialog-btn gh-dialog-btn-secondary",onClick:s,children:r||re("cancel")||"取消"}), be("button",{className:"gh-dialog-btn "+(o?"gh-dialog-btn-danger":"gh-dialog-btn-primary"),onClick:a,children:n||re("confirm")||"确定"})]})]})]}),lf=({title:e,defaultValue:t="",placeholder:n,confirmText:r,cancelText:o,closeOnOverlayClick:i=true,onConfirm:a,onCancel:s})=>{const[l,c]=B(t),d=P(null);M(()=>{d.current?.focus(),d.current?.select();},[]);const u=()=>{a(l);}; return ye(af,{onClose:s,closeOnOverlayClick:i,children:[ be("div",{className:"gh-dialog-title",children:e}), be("input",{ref:d,type:"text",className:"gh-dialog-input",value:l,onChange:e=>c(e.target.value),placeholder:n,onKeyDown:e=>"Enter"===e.key&&u()}), ye("div",{className:"gh-dialog-buttons",children:[ be("button",{className:"gh-dialog-btn gh-dialog-btn-secondary",onClick:s,children:o||re("cancel")||"取消"}), be("button",{className:"gh-dialog-btn gh-dialog-btn-primary",onClick:u,children:r||re("confirm")||"确定"})]})]})},cf=({variant:e="secondary",size:t="md",style:n,children:r,...o})=>{const i="sm"===t?{padding:"4px 8px",fontSize:"12px"}:{padding:"8px 16px",fontSize:"14px"}; return be("button",{...o,style:{borderRadius:"6px",cursor:o.disabled?"not-allowed":"pointer",transition:"all 0.2s",fontWeight:500,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"4px",opacity:o.disabled?.5:1,...i,...{primary:{background:"var(--gh-brand-gradient, linear-gradient(135deg, #4285f4 0%, #34a853 100%))",color:"white",border:"none"},secondary:{background:"var(--gh-bg, white)",color:"var(--gh-text, #374151)",border:"1px solid var(--gh-input-border, #d1d5db)"},danger:{background:"var(--gh-text-danger, #ef4444)",color:"white",border:"none"},ghost:{background:"transparent",color:"var(--gh-text-secondary, #6b7280)",border:"none"}}[e],...n},children:r})},df=({value:e,onChange:t,min:n,max:r,defaultValue:o,disabled:i=false,style:a,className:s="settings-input",step:l=1})=>{const[c,d]=B(e.toString()),u=P(false),h=P(null),g=P(null);M(()=>{u.current||d(e.toString());},[e]);const p=E(i=>{let a=parseInt(i);isNaN(a)&&(a=o??e??0),void 0!==n&&ar&&(a=r),d(a.toString()),a!==e&&t(a);},[n,r,o,e,t]),m=E(t=>{if(i)return;let n=parseInt(c);isNaN(n)&&(n=o??e??0);p((n+t).toString());},[c,o,e,i,p]);M(()=>()=>{h.current&&clearTimeout(h.current);},[]);const[f,b]=B(false); return ye("div",{className:s,onMouseEnter:()=>b(true),onMouseLeave:()=>b(false),style:{...a,position:"relative",display:"inline-flex",alignItems:"center"},children:[ be("input",{ref:g,type:"text",inputMode:"numeric",pattern:"[0-9]*",style:{width:"100%",paddingRight:"20px",height:"100%",border:"none",background:"transparent",outline:"none",color:"inherit",fontSize:"inherit",fontFamily:"inherit",paddingLeft:"8px",textAlign:"left"},value:c,disabled:i,onChange:e=>{const t=e.target.value.replace(/[^0-9-]/g,"");d(t);},onFocus:()=>{h.current&&(clearTimeout(h.current),h.current=null),u.current=true;},onBlur:()=>{h.current=setTimeout(()=>{document.activeElement!==g.current&&(u.current=false,p(c));},100);},onKeyDown:e=>{"Enter"===e.key?(p(c),g.current?.blur()):"ArrowUp"===e.key?(e.preventDefault(),m(l)):"ArrowDown"===e.key&&(e.preventDefault(),m(-l));}}),!i&&ye("div",{style:{position:"absolute",right:"2px",top:"2px",bottom:"2px",display:"flex",flexDirection:"column",width:"16px",background:"transparent",opacity:f?1:.2,transition:"opacity 0.2s ease",pointerEvents:f?"auto":"none"},children:[ be("button",{type:"button",tabIndex:-1,onClick:e=>{e.preventDefault(),m(l);},style:{flex:1,border:"none",background:"var(--gh-hover, #f3f4f6)",borderRadius:"3px 3px 0 0",cursor:"pointer",padding:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--gh-text-secondary, #6b7280)",marginBottom:"1px"},children:be(dt,{size:8})}), be("button",{type:"button",tabIndex:-1,onClick:e=>{e.preventDefault(),m(-l);},style:{flex:1,border:"none",background:"var(--gh-hover, #f3f4f6)",borderRadius:"0 0 3px 3px",cursor:"pointer",padding:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--gh-text-secondary, #6b7280)"},children:be(ut,{size:8})})]})]})},uf=({options:e,value:t,onChange:n,placeholder:r,disabled:o=false,emptyText:i,maxMenuHeight:a=260,className:s,buttonClassName:l,menuClassName:c,optionClassName:d,ariaLabel:u,onOpenChange:h})=>{const[g,p]=B(false),[m,f]=B(-1),b=P(null),y=P(null),v=P([]),w=R(()=>e.findIndex(e=>e.value===t),[e,t]),x=w>=0?e[w]:null;M(()=>{h?.(g);},[g,h]),M(()=>{if(!g)return;const t=w>=0?w:e.findIndex(e=>!e.disabled);f(t);},[g,e,w]),M(()=>{if(!g||m<0)return;const e=v.current[m];e?.scrollIntoView({block:"nearest"});},[g,m]),M(()=>{if(!g)return;const e=e=>{const t=b.current;if(!t)return;const n=(e=>{const t=e.composedPath;return "function"==typeof t?t.call(e):[]})(e);if(n.length>0)return void(n.includes(t)||p(false));const r=e.target;r&&!t.contains(r)&&p(false);},t=()=>{p(false);};return window.addEventListener("pointerdown",e,true),window.addEventListener("blur",t),()=>{window.removeEventListener("pointerdown",e,true),window.removeEventListener("blur",t);}},[g]);const k=e=>{p(false),e&&window.requestAnimationFrame(()=>{y.current?.focus({preventScroll:true});});},S=(t,n)=>{if(0===e.length)return -1;let r=t;for(let o=0;o=e.length&&(r=0),r<0&&(r=e.length-1),!e[r]?.disabled)return r;return -1},C=t=>{const r=e[t];r&&!r.disabled&&(n(r.value),k(true));}; return ye("div",{ref:b,className:s,style:{position:"relative",width:"100%"},children:[ ye("button",{ref:y,type:"button",className:l,disabled:o,"aria-label":u,"aria-haspopup":"listbox","aria-expanded":g,onClick:()=>!o&&p(e=>!e),onKeyDown:e=>{if(!o){if("ArrowDown"===e.key||"ArrowUp"===e.key){if(e.preventDefault(),!g)return void p(true);const t=S(m<0?w:m,"ArrowDown"===e.key?1:-1);return void(t>=0&&f(t))}if("Enter"===e.key||" "===e.key)return e.preventDefault(),void p(e=>!e);"Escape"===e.key&&g&&(e.preventDefault(),p(false));}},title:x?.title,style:{width:"100%",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",textAlign:"left"},children:[ be("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:"8px"},children:x?.label||r}), be(ut,{size:16,style:{flexShrink:0,transition:"transform 0.2s ease",transform:g?"rotate(180deg)":"rotate(0deg)"}})]}),g&&be("div",{role:"listbox",tabIndex:-1,className:c,onKeyDown:t=>{if("ArrowDown"===t.key){t.preventDefault();const e=S(m,1);return void(e>=0&&f(e))}if("ArrowUp"===t.key){t.preventDefault();const e=S(m,-1);return void(e>=0&&f(e))}if("Home"===t.key){t.preventDefault();const n=e.findIndex(e=>!e.disabled);return void(n>=0&&f(n))}if("End"===t.key){t.preventDefault();const n=[...e].reverse().findIndex(e=>!e.disabled);return void(n>=0&&f(e.length-n-1))}return "Enter"===t.key?(t.preventDefault(),void(m>=0&&C(m))):"Escape"===t.key?(t.preventDefault(),void k(true)):void("Tab"===t.key&&k(false))},style:{position:"absolute",top:"calc(100% + 4px)",left:0,right:0,maxHeight:`${a}px`,overflowY:"auto",zIndex:100,borderRadius:"8px",border:"1px solid var(--gh-input-border, #d1d5db)",boxShadow:"var(--gh-shadow-md, 0 8px 16px rgba(0,0,0,0.12))",background:"var(--gh-bg, #ffffff)",padding:"4px"},children:0===e.length?be("div",{style:{padding:"8px 10px",color:"var(--gh-text-tertiary, #9ca3af)",fontSize:"13px",textAlign:"left"},children:i||"No options"}):e.map((e,n)=>{const r=e.value===t,o=n===m; return be("button",{ref:e=>{v.current[n]=e;},type:"button",role:"option","aria-selected":r,className:d,disabled:e.disabled,title:e.title,onMouseEnter:()=>{e.disabled||f(n);},onClick:()=>C(n),style:{width:"100%",border:"none",borderRadius:"6px",padding:"7px 10px",textAlign:"left",background:r?"var(--gh-border-active, #3b82f6)":o?"var(--gh-hover, #f3f4f6)":"transparent",color:r?"#ffffff":"var(--gh-text, #1f2937)",cursor:e.disabled?"not-allowed":"pointer",display:"flex",alignItems:"center",gap:"8px",fontSize:"14px",lineHeight:1.4},children:e.label},e.value)})})]})};let hf=false;const gf=e=>{if("inbox"===e.id)return (()=>{const e=re("conversationsInbox");return "conversationsInbox"===e?"Inbox":e})();const t=(e.name||"").trim(),n=(e.icon||"").trim();return n&&t.startsWith(n)?t.slice(n.length).trim():t},pf=({children:e,onClose:t})=>{M(()=>{(()=>{if(hf)return;const e=document.createElement("style");e.id="gh-dialog-styles",e.textContent="\n .conversations-dialog-overlay {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: var(--gh-overlay-bg, rgba(0,0,0,0.5));\n z-index: 1000003;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .conversations-dialog {\n background: var(--gh-bg, white);\n border-radius: 12px;\n padding: 20px;\n min-width: 320px;\n max-width: min(480px, calc(100vw - 40px));\n box-shadow: var(--gh-shadow-lg, 0 10px 40px rgba(0,0,0,0.2));\n }\n .conversations-dialog-title {\n font-size: 16px;\n font-weight: 600;\n color: var(--gh-text, #1f2937);\n margin-bottom: 16px;\n }\n .conversations-dialog-message {\n font-size: 14px;\n color: var(--gh-text-secondary, #4b5563);\n margin-bottom: 20px;\n line-height: 1.5;\n white-space: pre-line;\n word-break: break-word;\n overflow-wrap: break-word;\n }\n .conversations-dialog-section {\n margin-bottom: 16px;\n }\n .conversations-dialog-section label {\n display: block;\n font-size: 13px;\n color: var(--gh-text-secondary, #6b7280);\n margin-bottom: 8px;\n }\n .conversations-dialog-input {\n width: 100%;\n padding: 10px 12px;\n border: 1px solid var(--gh-input-border, #d1d5db);\n border-radius: 8px;\n font-size: 14px;\n box-sizing: border-box;\n background: var(--gh-input-bg, #ffffff);\n color: var(--gh-text, #1f2937);\n }\n .conversations-dialog-input:focus {\n outline: none;\n border-color: var(--gh-input-focus-border, #4285f4);\n box-shadow: var(--gh-input-focus-shadow, 0 0 0 2px rgba(66,133,244,0.1));\n }\n .conversations-dialog-buttons {\n display: flex;\n justify-content: flex-end;\n gap: 8px;\n margin-top: 20px;\n }\n .emoji-grid-hidden-scrollbar::-webkit-scrollbar {\n display: none;\n width: 0;\n height: 0;\n }\n @keyframes gh-highlight-fade {\n 0% { background-color: var(--gh-highlight-pulse, rgba(59, 130, 246, 0.3)); }\n 100% { background-color: transparent; }\n }\n .conversations-folder-select-highlight {\n animation: gh-highlight-fade 2s ease-out;\n }\n",document.head.appendChild(e),hf=true;})();const e=e=>{"Escape"===e.key&&t();};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[t]);return uu(be("div",{className:"conversations-dialog-overlay",onClick:t,children:be("div",{className:"conversations-dialog",onClick:e=>e.stopPropagation(),children:e})}),document.body)},mf=({title:e,message:t,confirmText:n,cancelText:r,danger:o,onConfirm:i,onCancel:a})=>ye(pf,{onClose:a,children:[ be("div",{className:"conversations-dialog-title",children:e}), be("div",{className:"conversations-dialog-message",children:t}), ye("div",{className:"conversations-dialog-buttons",children:[ be(cf,{variant:"secondary",onClick:a,children:r||re("cancel")||"取消"}), be(cf,{variant:o?"danger":"primary",onClick:i,children:n||re("confirm")||"确定"})]})]}),ff=({folder:e,onConfirm:t,onCancel:n})=>{const r=e?.icon||"📁",[o,i]=B(e?.name.replace(e.icon,"").trim()||""),[a,s]=B(r),[l,c]=B(hr.includes(r)?r:null),d=P(null);M(()=>{d.current?.focus(),d.current?.select();},[]);const u=()=>{const e=o.trim();e&&t(e,a);}; return ye(pf,{onClose:n,children:[ be("div",{className:"conversations-dialog-title",children:e?re("conversationsRename")||"重命名":re("conversationsAddFolder")||"新建文件夹"}), ye("div",{className:"conversations-dialog-section",children:[ be("label",{children:re("conversationsIcon")||"图标"}), ye("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"4px",background:"var(--gh-bg-secondary, #f9fafb)",borderRadius:"4px",border:"1px solid var(--gh-border, #e5e7eb)",marginBottom:"8px"},children:[ be("span",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)",flexShrink:0},children:re("conversationsCustomIcon")||"自定义图标"}), be("input",{type:"text",value:a,onChange:e=>{let t=e.target.value;const n=/[^\p{Extended_Pictographic}\u200d\ufe0f]/gu;t&&n.test(t)&&(t=t.replace(n,"")),s(t),t&&!hr.includes(t)?c(null):hr.includes(t)&&c(t);},maxLength:4,placeholder:"☺",style:{width:"60px",textAlign:"center",border:"1px solid var(--gh-input-border, #d1d5db)",borderRadius:"4px",padding:"2px",fontSize:"16px",background:"var(--gh-input-bg, #ffffff)",color:"var(--gh-text, #1f2937)"}})]}), be("div",{style:{display:"grid",gridTemplateColumns:"repeat(8, 1fr)",gap:"4px",maxHeight:"120px",overflowY:"auto",padding:"2px",scrollbarWidth:"none",msOverflowStyle:"none"},className:"emoji-grid-hidden-scrollbar",children:hr.map(e=>be("button",{type:"button",onClick:()=>(e=>{c(e),s(e);})(e),style:{width:"24px",height:"24px",padding:0,display:"flex",alignItems:"center",justifyContent:"center",border:"none",background:l===e?"#dbeafe":"transparent",cursor:"pointer",borderRadius:"4px",fontSize:"16px",transition:"background 0.15s"},onMouseEnter:t=>{l!==e&&(t.currentTarget.style.background="var(--gh-hover, #f3f4f6)");},onMouseLeave:t=>{l!==e&&(t.currentTarget.style.background="transparent");},children:e},e))})]}), ye("div",{className:"conversations-dialog-section",children:[ be("label",{children:re("conversationsFolderName")||"名称"}), be("input",{ref:d,type:"text",className:"conversations-dialog-input",value:o,onChange:e=>i(e.target.value),placeholder:re("conversationsFolderNamePlaceholder")||"输入文件夹名称",onKeyDown:e=>"Enter"===e.key&&u()})]}), ye("div",{className:"conversations-dialog-buttons",children:[ be(cf,{variant:"secondary",onClick:n,children:re("cancel")||"取消"}), be(cf,{variant:"primary",onClick:u,children:re("confirm")||"确定"})]})]})},bf=({title:e,currentValue:t,placeholder:n,onConfirm:r,onCancel:o})=>{const[i,a]=B(t),s=P(null);M(()=>{s.current?.focus(),s.current?.select();},[]);const l=()=>{const e=i.trim();e&&e!==t?r(e):o();}; return ye(pf,{onClose:o,children:[ be("div",{className:"conversations-dialog-title",children:e}), be("div",{className:"conversations-dialog-section",children:be("input",{ref:s,type:"text",className:"conversations-dialog-input",value:i,onChange:e=>a(e.target.value),placeholder:n,onKeyDown:e=>"Enter"===e.key&&l()})}), ye("div",{className:"conversations-dialog-buttons",children:[ be(cf,{variant:"secondary",onClick:o,children:re("cancel")||"取消"}), be(cf,{variant:"primary",onClick:l,children:re("confirm")||"确定"})]})]})},yf=({folders:e,excludeFolderId:t,activeFolderId:n,title:r,onSelect:o,onCancel:i,onCreateFolder:a})=>{const[s,l]=B(""),c=P(null);M(()=>{c.current?.focus();},[]),M(()=>{n&&setTimeout(()=>{const e=document.getElementById(`folder-select-${n}`);e&&(e.scrollIntoView({block:"center",behavior:"smooth"}),e.classList.add("conversations-folder-select-highlight"));},150);},[n]);const d=e.filter(e=>e.id!==t&&(!s||gf(e).toLowerCase().includes(s.toLowerCase()))); return ye(pf,{onClose:i,children:[ be("div",{className:"conversations-dialog-title",children:r||re("conversationsMoveTo")||"移动到..."}), ye("div",{style:{display:"flex",gap:"8px",marginBottom:"12px"},children:[ be("input",{ref:c,type:"text",className:"conversations-dialog-input",style:{flex:1},placeholder:re("conversationsSearchFolder")||"搜索文件夹...",value:s,onChange:e=>l(e.target.value)}),a&&be(cf,{variant:"primary",style:{padding:"8px 12px"},onClick:()=>{i(),a();},title:re("conversationsAddFolder")||"新建文件夹",children:"+"})]}), ye("div",{className:"conversations-folder-select-list",children:[d.map(e=>ye("div",{id:`folder-select-${e.id}`,className:"conversations-folder-select-item",onClick:()=>o(e.id),children:[e.icon," ",gf(e)]},e.id)),0===d.length&&be("div",{style:{padding:"16px",textAlign:"center",color:"var(--gh-text-tertiary, #9ca3af)"},children:re("conversationsNoSearchResult")||"未找到匹配结果"})]}), be("div",{className:"conversations-dialog-buttons",children:be(cf,{variant:"secondary",onClick:i,children:re("cancel")||"取消"})})]})},vf=({tags:e,conv:t,onCancel:n,onCreateTag:r,onUpdateTag:o,onDeleteTag:i,onSetConversationTags:a,onRefresh:s})=>{const[l,c]=B(null),[d,u]=B(""),[h,g]=B(gr[0]),[p,m]=B(gr[0]),[f,b]=B(false),[y,v]=B(false),[w,x]=B(false),[k,S]=B(null),[C,E]=B(new Set(t?.tagIds||[])),_=P(null),A=P(null);M(()=>{_.current?.focus();},[]),M(()=>{E(new Set(t?.tagIds||[]));},[t?.id,t?.tagIds]);const T=(e,t="click")=>{let n=e.startsWith("#")?e:`#${e}`;g(n),"input"!==t&&(m(n),b(false));},I=async()=>{const e=d.trim();if(!e)return;v(true);let t=null;l?(t=await o(l,e,h),t&&(c(null),u(""))):(t=await r(e,h),t&&u("")),v(false),s();}; return ye(pf,{onClose:n,children:[ ye("div",{className:"conversations-dialog-title",style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ be("span",{children:re("conversationsManageTags")||"管理标签"}), be(wu,{content:re("close")||"关闭",children:be("span",{style:{cursor:"pointer",padding:"4px",fontSize:"20px",color:"var(--gh-text-secondary, #9ca3af)",lineHeight:1,width:"24px",height:"24px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"4px"},onClick:n,children:be(ke,{size:18})})})]}), ye("div",{style:{border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",marginBottom:"16px",background:"var(--gh-bg-secondary, #fafafa)"},children:[ ye("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)",fontWeight:500,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ be("span",{children:re(t?"conversationsSelectTag":"conversationsExistingTags")}), ye("span",{style:{fontSize:"11px",color:"var(--gh-text-secondary, #9ca3af)"},children:[e.length," 个"]})]}), be("div",{style:{maxHeight:"320px",overflowY:"auto",scrollbarWidth:"none",msOverflowStyle:"none"},children:0===e.length?be("div",{style:{padding:"24px 16px",textAlign:"center",color:"var(--gh-text-secondary, #9ca3af)"},children:re("conversationsNoTags")||"暂无标签,在下方创建"}):e.map(e=>{const n=C.has(e.id),r=l===e.id; return ye("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",borderBottom:"1px solid var(--gh-border, #f3f4f6)",cursor:t?"pointer":"default",background:r?"var(--gh-bg-warning-light, #fffbeb)":n?"var(--gh-folder-bg-default)":"transparent",transition:"background 0.15s"},onClick:()=>{t&&(async(e,n)=>{if(!t||!a)return;const r=new Set(C);n?r.add(e):r.delete(e),E(r),await a(t.id,Array.from(r)),s();})(e.id,!n);},onMouseEnter:e=>{r||n||(e.currentTarget.style.background="var(--gh-hover, #f9fafb)");},onMouseLeave:e=>{r||n||(e.currentTarget.style.background="transparent");},children:[ ye("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[t&&be("input",{type:"checkbox",checked:n,onChange:()=>{},onClick:e=>e.stopPropagation(),style:{cursor:"pointer",width:"16px",height:"16px",accentColor:e.color}}), ye("span",{style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"4px 10px",borderRadius:"4px",fontSize:"13px",color:"white",backgroundColor:e.color,fontWeight:n?500:400,boxShadow:n?"var(--gh-shadow-sm, 0 1px 3px rgba(0,0,0,0.2))":"none"},children:[e.name,r&&be(bt,{size:10})]})]}), ye("div",{style:{display:"flex",gap:"2px"},children:[ be(wu,{content:re("edit")||"编辑",children:be("button",{style:{background:r?"#fed7aa":"transparent",border:"none",color:r?"#ea580c":"#9ca3af",cursor:"pointer",padding:"6px",fontSize:"14px",borderRadius:"4px",transition:"all 0.15s"},onClick:t=>{t.stopPropagation(),(e=>{c(e.id),u(e.name),T(e.color),_.current?.focus();})(e);},onMouseEnter:e=>{r||(e.currentTarget.style.background="#e0f2fe",e.currentTarget.style.color="#0284c7");},onMouseLeave:e=>{r||(e.currentTarget.style.background="transparent",e.currentTarget.style.color="#9ca3af");},children:be(bt,{size:14})})}), be(wu,{content:re("delete")||"删除",children:be("button",{style:{background:"transparent",border:"none",color:"var(--gh-text-tertiary, #9ca3af)",cursor:"pointer",padding:"6px",fontSize:"14px",borderRadius:"4px",transition:"all 0.15s"},onClick:t=>{var n;t.stopPropagation(),n=e.id,S(n);},onMouseEnter:e=>{e.currentTarget.style.background="#fee2e2",e.currentTarget.style.color="#dc2626";},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="#9ca3af";},children:be(ke,{size:18})})})]})]},e.id)})})]}), ye("div",{style:{border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",padding:"12px",background:l?"var(--gh-bg-warning-light, #fffbeb)":"var(--gh-bg, #ffffff)",transition:"background 0.2s"},children:[ ye("div",{style:{fontSize:"12px",color:l?"var(--gh-text-warning, #b45309)":"var(--gh-text-secondary, #6b7280)",fontWeight:500,marginBottom:"10px",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ be("span",{children:l?re("conversationsEditTag")||"编辑标签":re("conversationsNewTag")||"新建标签"}),l&&be("button",{style:{background:"none",border:"none",color:"var(--gh-text-tertiary, #9ca3af)",cursor:"pointer",fontSize:"11px",padding:"2px 6px"},onClick:()=>{c(null),u(""),T(gr[0]);},children:re("conversationsCancelEdit")||"取消编辑"})]}), be("input",{ref:_,type:"text",className:"conversations-dialog-input",placeholder:re("conversationsTagName")||"标签名称",value:d,onChange:e=>u(e.target.value),onKeyDown:e=>"Enter"===e.key&&I(),style:{marginBottom:"12px",borderColor:l?"#fbbf24":void 0}}), ye("div",{style:{marginBottom:"12px",position:"relative"},children:[ ye("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 10px",border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",cursor:"pointer",background:"var(--gh-bg-secondary, #fafafa)",transition:"border-radius 0.15s, background-color 0.2s",userSelect:"none"},onClick:()=>x(!w),onMouseEnter:e=>e.currentTarget.style.backgroundColor="var(--gh-hover, #f3f4f6)",onMouseLeave:e=>e.currentTarget.style.backgroundColor="var(--gh-bg-secondary, #fafafa)",children:[ be("div",{style:{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:h,border:"1px solid var(--gh-border, rgba(0,0,0,0.1))",flexShrink:0}}), be("span",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #666)",flex:1},children:w?re("conversationsCollapseColor")||"收起颜色":re("conversationsSelectColor")||"选择颜色"}), be(ut,{size:16,color:"#9ca3af",style:{transition:"transform 0.2s",transform:w?"rotate(180deg)":"rotate(0deg)"}})]}),w&&ye("div",{style:{position:"absolute",top:"100%",left:0,right:0,marginTop:"4px",border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",padding:"10px",background:"var(--gh-bg, #ffffff)",zIndex:10,boxShadow:"var(--gh-shadow, 0 4px 12px rgba(0,0,0,0.15))"},children:[ be("div",{style:{display:"grid",gridTemplateColumns:"repeat(10, 1fr)",gap:"6px",marginBottom:"12px"},children:gr.map(e=>be(wu,{content:e,children:be("div",{style:{width:"100%",aspectRatio:"1",borderRadius:"4px",backgroundColor:e,cursor:"pointer",border:h.toLowerCase()===e.toLowerCase()?"2px solid #333":"1px solid rgba(0,0,0,0.05)",transition:"transform 0.1s",boxSizing:"border-box"},onClick:()=>{T(e),x(false);},onMouseEnter:e=>e.currentTarget.style.transform="scale(1.15)",onMouseLeave:e=>e.currentTarget.style.transform="scale(1)"})},e))}), ye("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[ ye("div",{style:{position:"relative",width:"28px",height:"28px",borderRadius:"50%",overflow:"hidden",cursor:"pointer",boxShadow:"var(--gh-shadow-sm, 0 1px 3px rgba(0,0,0,0.1))",border:gr.includes(h.toUpperCase())?"2px solid transparent":"2px solid #666",flexShrink:0},children:[ be("div",{style:{width:"100%",height:"100%",background:gr.includes(h.toUpperCase())?"conic-gradient(from 180deg, red, yellow, lime, aqua, blue, magenta, red)":h}}), be("input",{ref:A,type:"color",value:h,onChange:e=>{T(e.target.value,"picker"),x(false);},style:{position:"absolute",left:"-50%",top:"-50%",width:"200%",height:"200%",opacity:0,cursor:"pointer"}})]}), ye("div",{style:{display:"flex",alignItems:"center",flex:1,background:"var(--gh-bg-secondary, #f3f4f6)",border:"1px solid "+(f?"#ef4444":"var(--gh-border, #e5e7eb)"),borderRadius:"6px",padding:"4px 8px",height:"30px",boxSizing:"border-box"},children:[ be("span",{style:{fontSize:"11px",color:"var(--gh-text-secondary, #6b7280)",marginRight:"6px",fontFamily:"monospace",fontWeight:600},children:"HEX"}), be("input",{type:"text",value:p,onChange:e=>(e=>{if(m(e),/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/.test(e)){b(false);let t=e;4===e.length&&(t=`#${e[1]}${e[1]}${e[2]}${e[2]}${e[3]}${e[3]}`),T(t,"input");}else b(true);})(e.target.value),onBlur:()=>{f&&(m(h),b(false));},style:{border:"none",background:"transparent",outline:"none",fontSize:"13px",fontFamily:"monospace",width:"100%",color:"var(--gh-text, #374151)",textTransform:"uppercase"}})]})]})]})]}), be(cf,{variant:"primary",style:{width:"100%",...l&&{background:"var(--gh-warning-gradient, linear-gradient(135deg, #f59e0b 0%, #d97706 100%))"}},disabled:!d.trim()||y,onClick:I,children:l?re("conversationsUpdateTag")||"更新标签":re("conversationsNewTag")||"新建标签"})]}),k&&be(mf,{title:re("conversationsDeleteTag")||"删除标签",message:re("confirmDelete")||"确定删除这个标签吗?此操作不可撤销。",confirmText:re("delete")||"删除",cancelText:re("cancel")||"取消",danger:true,onConfirm:async()=>{k&&(await i(k),S(null),s());},onCancel:()=>S(null)})]})},wf=()=>({url:"https://greasyfork.org/zh-CN/scripts/563646-ophel-ai-chat-page-enhancer",icon:be(ft,{size:14}),label:re("reviewBtn")||"Review"}),xf=()=>{const{settings:e,setSettings:t}=No();if(!e||e.hasAgreedToTerms)return null; return ye("div",{className:"disclaimer-modal-overlay",children:[ ye("div",{className:"disclaimer-modal",children:[ ye("div",{className:"disclaimer-header",children:[ be("img",{src:nf,alt:"Ophel",className:"disclaimer-icon-img"}), ye("div",{className:"disclaimer-slogan-container",children:[ be("span",{className:"sparkle","aria-hidden":"true",children:"✨"}), be("h2",{className:"disclaimer-title",children:re("welcomeSlogan")||"AI 之益,触手可及"}), be("span",{className:"sparkle","aria-hidden":"true",children:"✨"})]})]}), ye("div",{className:"disclaimer-content",children:[ ye("div",{className:"disclaimer-section",children:[ be("p",{children:re("disclaimerText")||"本插件为通用辅助工具,依赖于第三方站点的页面结构和布局。如果原网站更新导致功能失效,恳请前往 GitHub 提交 Issue 反馈,我们将尽快修复。"}), be("p",{className:"disclaimer-warning",children:re("disclaimerWarning")||"请勿因第三方站点改版导致的问题在应用商店给出差评,感谢您的理解与支持!"})]}), ye("div",{className:"disclaimer-section privacy-section",children:[ ye("div",{className:"privacy-header",children:[ be(Ke,{size:20,className:"privacy-icon"}), be("h3",{className:"privacy-title",children:re("privacyTitle")||"隐私保护"})]}), be("p",{className:"privacy-content",children:re("privacyText")||"本插件所有数据均存储在本地浏览器中,不会主动上传到任何服务器。您的账号信息和使用数据完全由您自己掌控,确保隐私安全。"})]}), ye("div",{className:"disclaimer-section quote-section",children:[ be("p",{className:"disclaimer-quote-text",children:re("communityMotto")||"一个人可以走的更快,但一群人可以走得更远。"}), ye("div",{className:"action-row",children:[ ye("a",{href:"https://github.com/urzeye/ophel",target:"_blank",rel:"noopener noreferrer",className:"star-btn",children:[ be(Ve,{size:18}), be("span",{children:re("giveStar")||"点个 Star"})]}), ye("a",{href:wf().url,target:"_blank",rel:"noopener noreferrer",className:"star-btn review-btn",children:[wf().icon, be("span",{children:wf().label})]})]}), ye("div",{className:"secondary-links",children:[ be("a",{href:"https://github.com/urzeye/ophel/pulls",target:"_blank",rel:"noopener noreferrer",className:"sec-link",children:"PR"}), be("span",{className:"divider",children:"/"}), be("a",{href:"https://github.com/urzeye/ophel/issues",target:"_blank",rel:"noopener noreferrer",className:"sec-link",children:"Issue"})]})]})]}), be("div",{className:"disclaimer-footer",children:be("button",{className:"disclaimer-agree-btn",onClick:()=>{t({hasAgreedToTerms:true});},children:re("agreeButton")||"我已知晓并同意"})})]}), be("style",{children:'\n .disclaimer-modal-overlay {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: rgba(0, 0, 0, 0.6);\n backdrop-filter: blur(4px);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 99999;\n font-family: \'Inter\', -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n pointer-events: auto;\n }\n\n .disclaimer-modal {\n background: var(--gh-bg, #ffffff);\n border-radius: 16px;\n width: 90%;\n max-width: 600px;\n box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);\n overflow: hidden;\n color: var(--gh-text, #1f2937);\n border: 1px solid var(--gh-border, rgba(0,0,0,0.1));\n animation: modal-pop 0.3s cubic-bezier(0.16, 1, 0.3, 1);\n }\n\n .disclaimer-header {\n padding: 24px 24px 0;\n text-align: center;\n }\n\n .disclaimer-icon-img {\n width: 64px;\n height: 64px;\n margin-bottom: 20px;\n object-fit: contain;\n border-radius: 50%;\n background: var(--gh-bg, #ffffff);\n padding: 6px;\n border: 1px solid var(--gh-border, rgba(0,0,0,0.1));\n box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);\n transition: transform 0.8s cubic-bezier(0.34, 1.56, 0.64, 1);\n /* Ensure centering if parent is flex or block */\n display: inline-block;\n }\n\n .disclaimer-icon-img:hover {\n transform: rotate(360deg) scale(1.1);\n border-color: #3b82f6;\n box-shadow: 0 10px 15px -3px rgba(59, 130, 246, 0.2);\n }\n\n .disclaimer-slogan-container {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n }\n\n .sparkle {\n font-size: 18px;\n }\n\n .disclaimer-title {\n font-size: 20px;\n font-weight: 700;\n margin: 0;\n background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);\n -webkit-background-clip: text;\n -webkit-text-fill-color: transparent;\n }\n\n .disclaimer-content {\n padding: 24px;\n }\n\n .disclaimer-section {\n margin-bottom: 20px;\n }\n\n .disclaimer-section h3 {\n font-size: 16px;\n font-weight: 600;\n margin: 0 0 8px;\n display: flex;\n align-items: center;\n gap: 6px;\n }\n\n .disclaimer-section p {\n font-size: 14px;\n line-height: 1.6;\n margin: 0;\n color: var(--gh-text-secondary, #4b5563);\n }\n\n .disclaimer-warning {\n margin-top: 8px !important;\n color: #ef4444 !important;\n font-weight: 500;\n background: rgba(239, 68, 68, 0.1);\n padding: 8px 12px;\n border-radius: 6px;\n }\n\n .quote-section {\n text-align: center;\n background: var(--gh-bg-secondary, #f3f4f6);\n padding: 20px;\n border-radius: 12px;\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 16px;\n margin-bottom: 0;\n }\n\n .privacy-section {\n background: rgba(16, 185, 129, 0.1);\n border: 1px solid rgba(16, 185, 129, 0.2);\n border-radius: 12px;\n padding: 16px;\n margin-bottom: 20px;\n }\n\n .privacy-header {\n display: flex;\n align-items: center;\n gap: 8px;\n margin-bottom: 8px;\n color: #10b981;\n }\n\n .privacy-title {\n font-size: 15px;\n font-weight: 600;\n margin: 0;\n }\n\n .privacy-content {\n font-size: 13px !important;\n color: #059669 !important;\n line-height: 1.5 !important;\n margin: 0;\n }\n\n :host-context([data-gh-mode="dark"]) .privacy-content {\n color: #34d399 !important;\n }\n\n .disclaimer-quote-text {\n font-size: 15px;\n font-weight: 600;\n line-height: 1.5;\n color: var(--gh-text, #1f2937) !important;\n margin: 0 !important;\n font-style: italic;\n }\n\n .action-row {\n display: flex;\n align-items: center;\n gap: 12px;\n flex-wrap: wrap;\n justify-content: center;\n }\n\n .star-btn {\n display: flex;\n align-items: center;\n gap: 8px;\n background: #24292e; /* GitHub Dark */\n color: white;\n padding: 8px 20px;\n border-radius: 20px;\n text-decoration: none;\n font-weight: 600;\n font-size: 14px;\n transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);\n box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);\n border: 1px solid rgba(255,255,255,0.1);\n }\n\n .star-btn:hover {\n transform: translateY(-2px);\n box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.2);\n background: #2f363d;\n border-color: rgba(255,255,255,0.2);\n color: white;\n }\n\n .review-btn {\n background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);\n }\n\n .review-btn:hover {\n background: linear-gradient(135deg, #4338ca 0%, #6d28d9 100%);\n }\n\n .star-btn:active {\n transform: scale(0.96);\n }\n\n :host-context([data-gh-mode="dark"]) .star-btn {\n background: #3b82f6;\n border: none;\n }\n\n :host-context([data-gh-mode="dark"]) .star-btn:hover {\n background: #2563eb;\n }\n\n :host-context([data-gh-mode="dark"]) .review-btn {\n background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);\n }\n\n :host-context([data-gh-mode="dark"]) .review-btn:hover {\n background: linear-gradient(135deg, #4338ca 0%, #6d28d9 100%);\n }\n\n .secondary-links {\n display: flex;\n align-items: center;\n gap: 8px;\n font-size: 13px;\n color: var(--gh-text-secondary, #6b7280);\n }\n\n .sec-link {\n color: var(--gh-text-secondary, #6b7280);\n text-decoration: none;\n transition: color 0.2s;\n }\n\n .sec-link:hover {\n color: #3b82f6;\n text-decoration: underline;\n }\n\n .divider {\n opacity: 0.5;\n }\n\n .disclaimer-footer {\n padding: 0 24px 24px;\n }\n\n .disclaimer-agree-btn {\n width: 100%;\n padding: 12px;\n background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);\n color: white;\n border: none;\n border-radius: 8px;\n font-size: 16px;\n font-weight: 600;\n cursor: pointer;\n transition: transform 0.1s, opacity 0.2s;\n }\n\n .disclaimer-agree-btn:hover {\n opacity: 0.9;\n }\n\n .disclaimer-agree-btn:active {\n transform: scale(0.98);\n }\n\n @keyframes modal-pop {\n from {\n opacity: 0;\n transform: scale(0.95) translateY(10px);\n }\n to {\n opacity: 1;\n transform: scale(1) translateY(0);\n }\n }\n '})]})};const kf=({isVisible:e,text:t,onStop:n})=>{if(!e)return null;const r=be("div",{className:"gh-loading-mask",style:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",background:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:2147483646,pointerEvents:"auto"},children:ye("div",{className:"gh-loading-content",style:{background:"var(--gh-bg, #fff)",padding:"24px 32px",borderRadius:"12px",display:"flex",flexDirection:"column",alignItems:"center",gap:"12px",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.15)",minWidth:"200px"},children:[ be("div",{className:"gh-loading-spinner",style:{fontSize:"32px"},children:"⏳"}), be("div",{className:"gh-loading-text",style:{color:"var(--gh-text, #333)",fontSize:"14px",fontWeight:500},children:t||re("loadingHistory")}), be("div",{className:"gh-loading-hint",style:{color:"var(--gh-text-secondary, #9ca3af)",fontSize:"12px",textAlign:"center"},children:re("loadingHint")}),n&&be("button",{className:"gh-loading-stop-btn",style:{marginTop:"8px",padding:"8px 20px",background:"var(--gh-primary, #4285f4)",color:"white",border:"none",borderRadius:"6px",fontSize:"13px",cursor:"pointer"},onClick:n,children:re("stopLoading")})]})});return document?.body?uu(r,document.body):r};let Sf=false;const Cf=({anchorEl:e,onClose:t,children:n})=>{const r=P(null),[o,i]=B(null);if(M(()=>{if((()=>{if(Sf)return;const e=document.createElement("style");e.id="gh-menu-styles",e.textContent="\n .conversations-folder-menu {\n background: var(--gh-bg, white);\n border: 1px solid var(--gh-border, #e5e7eb);\n border-radius: 6px;\n box-shadow: var(--gh-shadow, 0 4px 12px rgba(0,0,0,0.15));\n z-index: 10000000;\n padding: 3px;\n min-width: 80px;\n }\n .conversations-folder-menu button {\n display: block;\n width: 100%;\n padding: 6px 10px;\n border: none;\n background: none;\n text-align: left;\n font-size: 12px;\n color: var(--gh-text, #374151);\n cursor: pointer;\n border-radius: 4px;\n white-space: nowrap;\n }\n .conversations-folder-menu button:hover {\n background: var(--gh-hover, #f3f4f6);\n }\n",document.head.appendChild(e),Sf=true;})(),!e)return;const n=n=>{const o=n.composedPath(),i=r.current&&o.includes(r.current),a=o.includes(e);i||a||t();},o=setTimeout(()=>{document.addEventListener("click",n,true);},0);return ()=>{clearTimeout(o),document.removeEventListener("click",n,true);}},[e,t]),M(()=>{if(!e||!r.current)return;const t=e.getBoundingClientRect(),n=r.current.getBoundingClientRect(),o=window.innerWidth,a=window.innerHeight,s=n.width||150,l=n.height||200;let c=t.left,d=t.bottom+4;c+s>o-10&&(c=t.right-s),c<10&&(c=10),d+l>a-10&&(d=t.top-l-4),d<10&&(d=10),i({left:c,top:d});},[e]),!e)return null;const a=be("div",{ref:r,className:"conversations-folder-menu",style:{position:"fixed",top:o?`${o.top}px`:"-9999px",left:o?`${o.left}px`:"-9999px",zIndex:2147483647,pointerEvents:"auto"},children:n});return uu(a,document.body)},Ef=({onClick:e,danger:t,children:n})=>be("button",{onClick:e,style:t?{color:"var(--gh-text-danger, #ef4444)"}:void 0,children:n}),_f=({folder:e,anchorEl:t,onClose:n,onRename:r,onDelete:o})=>ye(Cf,{anchorEl:t,onClose:n,children:[ be(Ef,{onClick:()=>{n(),r();},children:re("conversationsRename")||"重命名"}), be(Ef,{danger:true,onClick:()=>{n(),o();},children:re("conversationsDelete")||"删除"})]}),Af=({conversation:e,anchorEl:t,onClose:n,onRename:r,onTogglePin:o,onSetTags:i,onMoveTo:a,onDelete:s})=>ye(Cf,{anchorEl:t,onClose:n,children:[ be(Ef,{onClick:()=>{n(),r();},children:re("conversationsRename")||"重命名"}), be(Ef,{onClick:()=>{n(),o();},children:e.pinned?re("conversationsUnpin")||"取消置顶":re("conversationsPin")||"置顶"}), be(Ef,{onClick:()=>{n(),i();},children:re("conversationsSetTags")||"设置标签"}), be(Ef,{onClick:()=>{n(),a();},children:re("conversationsMoveTo")||"移动到..."}), be(Ef,{danger:true,onClick:()=>{n(),s();},children:re("conversationsDelete")||"删除"})]}),Tf=({anchorEl:e,onClose:t,onExportMarkdown:n,onExportJSON:r,onExportTXT:o})=>ye(Cf,{anchorEl:e,onClose:t,children:[ be(Ef,{onClick:()=>{t(),n();},children:ye("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[ be($e,{size:14}), be("span",{children:re("exportToMarkdown")||"Markdown"})]})}), be(Ef,{onClick:()=>{t(),r();},children:ye("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[ be(lt,{size:14}), be("span",{children:re("exportToJSON")||"JSON"})]})}), be(Ef,{onClick:()=>{t(),o();},children:ye("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[ be($e,{size:14}), be("span",{children:re("exportToTXT")||"TXT"})]})})]});e(".gh-panel-content::-webkit-scrollbar{display:none;width:0;height:0}.conversations-folder-item.expanded{border-bottom-left-radius:0!important;border-bottom-right-radius:0!important;border-bottom:none!important}.conversations-list{width:100%!important;box-sizing:border-box!important;margin:0!important;border-top-left-radius:0!important;border-top-right-radius:0!important;border-top:none!important}.conversations-toolbar-btn{background:transparent!important;border:1px solid transparent!important;box-shadow:none!important;color:var(--gh-text-secondary, #6b7280)!important;border-radius:6px!important;transition:all .2s ease!important;min-width:28px!important;height:28px!important;margin:0!important;padding:0!important;cursor:pointer;display:flex;align-items:center;justify-content:center}.conversations-toolbar-btn:hover{background:#7f7f7f26!important;color:var(--gh-text, #374151)!important}.conversations-toolbar-btn.active{background:var(--gh-primary, #3b82f6)!important;color:#fff!important;border-color:var(--gh-primary, #3b82f6)!important}.conversations-toolbar-btn svg{fill:currentColor!important;width:16px!important;height:16px!important}.conversations-content{display:flex;flex-direction:column;flex:1;min-height:200px;overflow-x:hidden;overflow-y:auto}.conversations-toolbar{display:flex;gap:6px;padding:10px 12px;border-bottom:1px solid var(--gh-border, #e5e7eb);flex-shrink:0;background:var(--gh-bg, #ffffff)}.conversations-toolbar-btn{padding:5px 8px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:6px;background:var(--gh-bg-secondary, #f9fafb);font-size:13px;color:var(--gh-text, #374151);cursor:pointer;transition:all .2s;display:flex;align-items:center;justify-content:center;min-width:32px;height:32px;flex-shrink:0}.conversations-toolbar-btn svg{width:16px;height:16px}.conversations-toolbar-btn:hover{background:var(--gh-hover, #f3f4f6);border-color:var(--gh-text-secondary, #9ca3af)}.conversations-toolbar-btn.batch-mode.active{background:var(--gh-border-active);color:#fff;border-color:var(--gh-border-active)}.conversations-toolbar-btn:disabled{opacity:.6;cursor:wait}.conversations-folder-select-dropdown{width:100%}.conversations-folder-select{padding:5px 8px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:6px;background:var(--gh-bg-secondary, #f9fafb);font-size:13px;color:var(--gh-text, #374151);cursor:pointer;min-width:80px;height:32px;width:100%;line-height:1;font-family:inherit;appearance:none;-webkit-appearance:none}.conversations-folder-select:hover{background:var(--gh-hover, #f3f4f6)}.conversations-folder-select:focus{outline:none;border-color:var(--gh-border-active)}.conversations-folder-select:disabled{opacity:.6;cursor:not-allowed}.conversations-folder-select-menu{scrollbar-width:thin}.conversations-folder-select-option{font-family:inherit}.conversations-folder-list{flex:1;overflow-y:auto;padding:8px;scrollbar-width:none;-ms-overflow-style:none}.conversations-folder-list::-webkit-scrollbar{display:none;width:0;height:0}.conversations-content{scrollbar-width:none;-ms-overflow-style:none}.conversations-content::-webkit-scrollbar{display:none;width:0;height:0}.conversations-unsupported-mask{position:absolute;inset:0;z-index:12;display:flex;align-items:center;justify-content:center;padding:16px;background:linear-gradient(180deg,#f8fafceb,#f8fafcd1);-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);pointer-events:all}.conversations-unsupported-card{width:100%;max-width:280px;border-radius:16px;padding:16px 18px 18px;background:var(--gh-bg, #ffffff);border:1px solid rgba(148,163,184,.25);box-shadow:0 16px 32px #0f172a1f;text-align:center;color:var(--gh-text, #374151)}.conversations-unsupported-icon{width:44px;height:44px;margin:0 auto 10px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:20px;color:#6a3a00;background:linear-gradient(135deg,#ffd29a,#ffb86b);box-shadow:0 8px 18px #ffab5859}.conversations-unsupported-title{font-size:14px;font-weight:600;margin-bottom:6px}.conversations-unsupported-desc{font-size:12px;color:var(--gh-text-secondary, #6b7280);line-height:1.4}:host([data-theme=\"dark\"]) .conversations-unsupported-mask,.gh-root[data-theme=dark] .conversations-unsupported-mask,body[data-gh-mode=dark] .conversations-unsupported-mask,html[data-theme=dark] .conversations-unsupported-mask{background:linear-gradient(180deg,#0a0a0aeb,#0a0a0adb)}:host([data-theme=\"dark\"]) .conversations-unsupported-card,.gh-root[data-theme=dark] .conversations-unsupported-card,body[data-gh-mode=dark] .conversations-unsupported-card,html[data-theme=dark] .conversations-unsupported-card{background:#1b1b1b;border:1px solid rgba(255,255,255,.08);box-shadow:0 18px 36px #0000008c;color:var(--gh-text, #e3e3e3)}:host([data-theme=\"dark\"]) .conversations-unsupported-icon,.gh-root[data-theme=dark] .conversations-unsupported-icon,body[data-gh-mode=dark] .conversations-unsupported-icon,html[data-theme=dark] .conversations-unsupported-icon{color:#f7d6a8;background:linear-gradient(135deg,#6c420c,#c37a24);box-shadow:0 10px 20px #00000080}.conversations-folder-item{display:flex;align-items:center;justify-content:space-between;padding:10px 12px;margin-bottom:4px;border-radius:8px;background:var(--gh-bg-secondary, #f9fafb);cursor:pointer;transition:all .2s;flex-wrap:wrap}.conversations-folder-item:hover{background:var(--gh-hover, #f3f4f6)}.conversations-folder-item.default{background:var(--gh-folder-bg-default)}.conversations-folder-item.expanded{border:2px solid var(--gh-border-active);box-shadow:0 2px 8px var(--gh-shadow-sm);border-radius:8px 8px 0 0}.conversations-folder-info{display:flex;align-items:center;gap:8px;flex:1;min-width:0;position:relative}.conversations-folder-icon{font-size:18px;width:24px;height:24px;display:flex;align-items:center;justify-content:center;line-height:1;flex-shrink:0}.conversations-folder-name{font-size:14px;font-weight:500;color:var(--gh-text, #1f2937);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;-webkit-user-select:none;user-select:none}.conversations-folder-count{font-size:12px;color:var(--gh-text-secondary, #6b7280);flex-shrink:0;-webkit-user-select:none;user-select:none}.conversations-folder-menu-btn{width:24px;height:24px;border:none;background:transparent;color:var(--gh-text-secondary, #6b7280);cursor:pointer;border-radius:4px;font-size:14px}.conversations-folder-menu-btn:hover{background:var(--gh-border, #e5e7eb)}.conversations-folder-controls{display:flex;align-items:center;gap:4px;flex-shrink:0}.conversations-folder-order-btns{position:absolute;right:0;top:50%;transform:translateY(-50%);display:flex;align-items:center;gap:2px;opacity:0;transition:opacity .2s;background:inherit;padding-left:8px}.conversations-folder-item:hover .conversations-folder-order-btns{opacity:1}.conversations-folder-order-btn{width:20px;height:20px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:4px;background:var(--gh-bg, white);color:var(--gh-text-secondary, #6b7280);cursor:pointer;font-size:11px;display:flex;align-items:center;justify-content:center;transition:all .15s}.conversations-folder-order-btn:hover:not(:disabled){background:var(--gh-hover, #f3f4f6);border-color:var(--gh-text-tertiary, #9ca3af);color:var(--gh-text, #374151)}.conversations-folder-order-btn:disabled{opacity:.3;cursor:default}.conversations-folder-menu{background:var(--gh-bg, white);border:1px solid var(--gh-border, #e5e7eb);border-radius:8px;box-shadow:0 4px 12px #00000026;z-index:1000002;padding:4px;min-width:100px}.conversations-folder-menu button{display:block;width:100%;padding:8px 12px;border:none;background:none;text-align:left;font-size:13px;color:var(--gh-text, #374151);cursor:pointer;border-radius:4px}.conversations-folder-menu button:hover{background:var(--gh-hover, #f3f4f6)}.conversations-empty{text-align:center;padding:40px 20px;color:var(--gh-text-secondary, #9ca3af);font-size:14px}.conversations-search-bar{padding:8px 12px;border-bottom:1px solid var(--gh-border, #e5e7eb);background:var(--gh-bg-secondary, #f9fafb);flex-shrink:0}.conversations-search-wrapper{display:flex;align-items:center;gap:0;position:relative}.conversations-search-wrapper.has-filter .conversations-tag-search-btn{border-radius:0;border-right:none}.conversations-search-input-group{flex:1;position:relative;height:36px;min-width:0}.conversations-search-input{width:100%;height:100%;padding:0 12px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:8px 0 0 8px;font-size:14px;box-sizing:border-box;transition:all .2s;background:var(--gh-input-bg, #ffffff);color:var(--gh-text, #1f2937)}.conversations-search-input:focus{outline:none;border-color:var(--gh-border-active);z-index:1;position:relative}.conversations-pin-filter-btn{cursor:pointer;width:36px;height:36px;color:var(--gh-text-tertiary, #9ca3af);font-size:14px;display:flex;align-items:center;justify-content:center;border:1px solid var(--gh-input-border, #d1d5db);border-left:none;background:var(--gh-bg, white);box-sizing:border-box;transition:all .2s}.conversations-pin-filter-btn:hover{background:var(--gh-hover, #f3f4f6);color:var(--gh-text, #374151)}.conversations-pin-filter-btn.active{color:var(--gh-border-active);background:var(--gh-folder-bg-default);box-shadow:inset 0 0 0 1px var(--gh-border-active)}.conversations-result-bar{text-align:center;padding:6px;color:var(--gh-border-active);font-size:13px;background:var(--gh-folder-bg-default);border-radius:4px;margin-top:8px;display:none}.conversations-result-bar.visible{display:block}.conversations-tag{display:inline-flex;align-items:center;padding:2px 6px;border-radius:4px;font-size:11px;margin:0;color:#fff;background-color:var(--gh-text-secondary, #9ca3af);line-height:1.2;max-width:80px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;vertical-align:middle;flex-shrink:0}.conversations-tag-list{display:flex;align-items:center;gap:4px;border:none;padding:0;margin:0;flex-shrink:0;min-width:0;max-width:52%;overflow:hidden}.conversations-tag-list:empty{display:none}.conversations-tag-more{color:var(--gh-text-secondary, #6b7280);background:var(--gh-bg-secondary, #f3f4f6);border:1px solid var(--gh-border, #e5e7eb)}.conversations-hidden-tags-tooltip{display:flex;flex-direction:column;gap:6px;min-width:110px}.conversations-hidden-tag-item{display:flex;align-items:center;gap:6px;font-size:12px;line-height:1.25}.conversations-hidden-tag-dot{width:8px;height:8px;border-radius:999px;flex-shrink:0}.conversations-tag-search-btn{cursor:pointer;width:36px;height:36px;color:var(--gh-text-tertiary, #9ca3af);font-size:14px;display:flex;align-items:center;justify-content:center;border:1px solid var(--gh-input-border, #d1d5db);border-left:none;border-radius:0;background:var(--gh-bg, white);box-sizing:border-box;transition:all .2s}.conversations-tag-search-btn:hover{background:var(--gh-hover, #f3f4f6);color:var(--gh-text, #374151)}.conversations-tag-search-btn.active{color:var(--gh-border-active);background:var(--gh-folder-bg-default);box-shadow:inset 0 0 0 1px var(--gh-border-active)}.conversations-tag-search-btn.empty{opacity:.5}.conversations-search-clear{cursor:pointer;width:36px;height:36px;color:var(--gh-text-tertiary, #9ca3af);font-size:18px;display:flex;align-items:center;justify-content:center;border:1px solid var(--gh-input-border, #d1d5db);border-left:none;border-radius:0 8px 8px 0;background:var(--gh-bg, white);box-sizing:border-box;transition:all .2s;-webkit-user-select:none;user-select:none}.conversations-search-clear:hover{background:var(--gh-bg-danger, #fef2f2);color:var(--gh-text-danger, #ef4444)}.conversations-search-clear.disabled{opacity:.3;cursor:default;background:var(--gh-bg-secondary, #f9fafb);pointer-events:none}.conversations-tag-filter-menu{position:absolute;top:calc(100% + 4px);right:0;width:200px;background:var(--gh-bg, white);border:1px solid var(--gh-border, #e5e7eb);border-radius:8px;box-shadow:0 4px 12px #00000026;z-index:1000;display:flex;flex-direction:column;overflow:hidden;animation:fadeIn .2s}.conversations-tag-filter-list{overflow-y:auto;flex:1;padding:4px;display:flex;flex-direction:column;gap:2px}.conversations-tag-filter-footer{padding:4px;border-top:1px solid var(--gh-border, #e5e7eb);background:var(--gh-bg-secondary, #f9fafb);flex-shrink:0}.conversations-tag-filter-item{display:flex;align-items:center;gap:8px;padding:8px;cursor:pointer;border-radius:6px;font-size:13px;color:var(--gh-text, #374151);width:100%;box-sizing:border-box;overflow:hidden}.conversations-tag-filter-item span:not(.conversations-tag-dot){white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1}.conversations-tag-filter-item.selected{background:var(--gh-folder-bg-default);color:var(--gh-primary, #3b82f6);font-weight:500}.conversations-tag-filter-item.selected:after{content:\"✓\";margin-left:auto;font-size:14px;font-weight:700}.conversations-tag-dot{width:10px;height:10px;border-radius:50%;display:inline-block;flex-shrink:0;border:1px solid rgba(0,0,0,.05)}.conversations-tag-filter-divider{height:1px;background:var(--gh-border, #e5e7eb);margin:4px 0;flex-shrink:0}.conversations-tag-filter-action{color:var(--gh-border-active);font-weight:500;justify-content:center}.conversations-tag-manager-list{max-height:250px;overflow-y:auto;border:1px solid var(--gh-border, #e5e7eb);border-radius:4px;margin-bottom:12px;padding:4px}.conversations-tag-manager-item{display:flex;align-items:center;justify-content:space-between;padding:8px;border-bottom:1px solid var(--gh-hover, #f3f4f6)}.conversations-tag-manager-item:last-child{border-bottom:none}.conversations-tag-manager-item:hover{background:var(--gh-bg-secondary, #f9fafb)}.conversations-tag-preview{padding:2px 8px;border-radius:4px;font-size:12px;color:#fff;max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;vertical-align:middle;display:inline-block}.conversations-tag-actions{display:flex;gap:4px;flex-shrink:0}.conversations-tag-btn{width:24px;height:24px;border:none;background:transparent;cursor:pointer;display:flex;align-items:center;justify-content:center;color:var(--gh-text-tertiary, #9ca3af);border-radius:4px;transition:all .2s}.conversations-tag-btn:hover{background:var(--gh-bg-danger-hover, #fee2e2);color:var(--gh-text-danger, #ef4444)}.conversations-tag-btn.edit:hover{background:var(--gh-folder-bg-default, #e0f2fe);color:var(--gh-primary, #3b82f6)}.conversations-color-picker{display:grid;grid-template-columns:repeat(10,1fr);gap:6px;margin:12px 0}.conversations-color-item{width:24px;height:24px;border-radius:4px;cursor:pointer;border:2px solid transparent;transition:transform .1s}.conversations-color-item:hover{transform:scale(1.1)}.conversations-color-item.selected{border-color:var(--gh-text, #374151);transform:scale(1.1);box-shadow:0 2px 4px #0003}.conversations-list{width:calc(100% - 8px);margin:-4px 4px 4px;padding:8px;background:var(--gh-bg-secondary);border:2px solid var(--gh-border-active);border-top:none;border-radius:0 0 8px 8px;max-height:300px;overflow-y:auto;overflow-x:hidden;scrollbar-width:none;-ms-overflow-style:none}.conversations-list::-webkit-scrollbar{display:none}.conversations-list-empty{padding:12px;color:var(--gh-text-secondary, #9ca3af);font-size:13px;text-align:center}.conversations-item{display:flex;align-items:center;padding:8px 34px 8px 12px;margin-bottom:4px;border-radius:6px;background:var(--gh-bg, white);cursor:pointer;transition:background-color .2s;gap:8px;position:relative}.conversations-item:hover{background:var(--gh-hover, #f3f4f6)}.conversations-item:before{content:\"\";position:absolute;left:0;top:50%;transform:translateY(-50%) scaleY(0);width:4px;height:80%;background-color:var(--gh-primary, #428cf1);border-radius:0 4px 4px 0;transition:transform .2s}.conversations-item:hover:before{transform:translateY(-50%) scaleY(1)}.conversations-item-title{display:block;font-size:14px;color:var(--gh-text, #374151);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;line-height:1.35}.conversations-item-main{flex:1;min-width:0}.conversations-item-headline{display:flex;align-items:center;gap:6px;min-width:0}.conversations-item-meta{display:flex;align-items:center;gap:6px;position:absolute;top:50%;right:8px;transform:translateY(-50%)}.conversations-item-time{display:none}.conversations-item-menu-btn{width:20px;height:20px;border:none;background:transparent;color:var(--gh-text-tertiary, #9ca3af);cursor:pointer;border-radius:4px;font-size:12px;opacity:0;pointer-events:none;transform:translate(4px);transition:opacity .18s ease,transform .18s ease,background-color .2s,color .2s;flex-shrink:0;display:flex;align-items:center;justify-content:center}.conversations-folder-checkbox,.conversations-item-checkbox{appearance:none;-webkit-appearance:none;width:16px;height:16px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:4px;background-color:var(--gh-bg, #ffffff);cursor:pointer;position:relative;margin:0;padding:0;display:inline-flex;align-items:center;justify-content:center;transition:all .2s}.conversations-folder-checkbox:checked,.conversations-item-checkbox:checked{background-color:var(--gh-primary, #4285f4);border-color:var(--gh-primary, #4285f4)}.conversations-folder-checkbox:checked:after,.conversations-item-checkbox:checked:after{content:\"\";width:10px;height:10px;background-image:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='4' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E\");background-size:contain;background-repeat:no-repeat;background-position:center;display:block}.conversations-folder-checkbox:hover,.conversations-item-checkbox:hover{border-color:var(--gh-primary, #4285f4)}.conversations-item:hover .conversations-item-menu-btn{opacity:1;pointer-events:auto;transform:translate(0)}.conversations-item:focus-within .conversations-item-menu-btn{opacity:1;pointer-events:auto;transform:translate(0)}.conversations-item-menu-btn:hover{background:var(--gh-border, #e5e7eb);color:var(--gh-text, #374151)}.conversations-content.is-narrow .conversations-item{padding-right:34px}.conversations-content.is-narrow .conversations-item-title{font-size:13px}.conversations-content.is-narrow .conversations-tag{max-width:72px}.conversations-content.is-narrow .conversations-tag-list{max-width:46%}@media(hover:none){.conversations-item-menu-btn{opacity:.72;pointer-events:auto;transform:none}}.conversations-item-menu{background:var(--gh-bg, white);border:1px solid var(--gh-border, #e5e7eb);border-radius:8px;box-shadow:0 4px 12px #00000026;z-index:1000002;padding:4px;min-width:120px}.conversations-item-menu button{display:block;width:100%;padding:8px 12px;border:none;background:none;text-align:left;font-size:13px;color:var(--gh-text, #374151);cursor:pointer;border-radius:4px}.conversations-item-menu button:hover{background:var(--gh-hover, #f3f4f6)}.conversations-item-menu button.danger{color:var(--gh-text-danger, #dc2626)}.conversations-item-menu button.danger:hover{background:var(--gh-bg-danger, #fef2f2)}.conversations-item.locate-highlight{background:var(--gh-outline-locate-bg)!important;border:2px solid var(--gh-outline-locate-border)!important;border-radius:6px;box-shadow:inset 0 0 8px var(--gh-outline-locate-shadow);animation:conversationsLocatePulse .6s ease-in-out 2}@keyframes conversationsLocatePulse{0%,to{transform:scale(1)}50%{transform:scale(1.01)}}.conversations-folder-checkbox{margin-right:8px;width:16px;height:16px;cursor:pointer;accent-color:var(--gh-checkbox-bg, #4f46e5);flex-shrink:0}.conversations-item-checkbox{width:16px;height:16px;margin-right:8px;cursor:pointer;accent-color:var(--gh-checkbox-bg, #4f46e5);flex-shrink:0}.conversations-batch-bar{position:sticky;bottom:0;left:0;right:0;background:var(--gh-bg, white);padding:8px 12px;display:flex;align-items:center;justify-content:space-between;border-radius:8px;margin-top:8px;border:1px solid var(--gh-border, #e5e7eb);box-shadow:0 -2px 10px #0000000d}.conversations-batch-info{color:var(--gh-text, #374151);font-size:13px;font-weight:500}.conversations-batch-btns{display:flex;gap:8px}.conversations-batch-btn{padding:4px 10px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:6px;font-size:12px;cursor:pointer;transition:all .2s;background:var(--gh-hover, #f3f4f6);color:var(--gh-text, #374151)}.conversations-batch-btn:hover{background:var(--gh-border, #e5e7eb);border-color:var(--gh-text-tertiary, #9ca3af)}.conversations-batch-btn.danger{background:var(--gh-bg-danger-hover, #fee2e2);color:var(--gh-text-danger, #dc2626);border-color:var(--gh-bg-danger-hover, #fecaca)}.conversations-batch-btn.danger:hover{background:var(--gh-bg-danger-hover, #fecaca);border-color:var(--gh-text-danger, #f87171)}.conversations-batch-btn.cancel{background:transparent;border:none;color:var(--gh-text-secondary, #6b7280)}.conversations-batch-btn.cancel:hover{background:var(--gh-hover, #f3f4f6);color:var(--gh-text, #374151);border:none}.conversations-dialog-overlay{position:fixed;inset:0;background:#00000080;z-index:1000003;display:flex;align-items:center;justify-content:center}.conversations-dialog{background:var(--gh-bg, white);border-radius:12px;padding:20px;min-width:320px;box-shadow:0 10px 40px #0003}.conversations-dialog-title{font-size:16px;font-weight:600;color:var(--gh-text, #1f2937);margin-bottom:16px}.conversations-dialog-message{font-size:14px;color:var(--gh-badge-text, #4b5563);margin-bottom:20px;line-height:1.5;white-space:pre-line}.conversations-dialog-section{margin-bottom:16px}.conversations-dialog-section label{display:block;font-size:13px;color:var(--gh-text-secondary, #6b7280);margin-bottom:8px}.conversations-dialog-input{width:100%;padding:10px 12px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:8px;font-size:14px;box-sizing:border-box;background:var(--gh-input-bg, #ffffff);color:var(--gh-text, #1f2937)}.conversations-dialog-input:focus{outline:none;border-color:var(--gh-primary, #4285f4);box-shadow:0 0 0 2px #4285f41a}.conversations-dialog-buttons{display:flex;justify-content:flex-end;gap:8px;margin-top:20px}.conversations-folder-select-list{max-height:250px;overflow-y:auto;margin:12px 0}.conversations-folder-select-item{padding:12px 16px;border-radius:8px;cursor:pointer;transition:all .2s;font-size:14px}.conversations-folder-select-item:hover{background:var(--gh-hover, #f3f4f6)}.conversations-emoji-picker{display:flex;flex-wrap:wrap;gap:4px}.conversations-emoji-btn{width:36px;height:36px;border:1px solid var(--gh-border, #e5e7eb);border-radius:8px;background:var(--gh-bg-secondary, #f9fafb);font-size:18px;cursor:pointer;transition:all .2s}.conversations-emoji-btn:hover{background:var(--gh-hover, #f3f4f6);border-color:var(--gh-input-border, #d1d5db)}.conversations-emoji-btn.selected{background:var(--gh-selected-gradient, #e0e7ff);border-color:var(--gh-primary, #4285f4);box-shadow:0 0 0 2px #4285f433}.conversations-highlight{background:#ffd50066;padding:0 2px;border-radius:2px}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}.conversations-tag-filter-list,.conversations-tag-manager-list{max-height:200px;overflow-y:auto;scrollbar-width:none;-ms-overflow-style:none}.conversations-tag-filter-list::-webkit-scrollbar,.conversations-tag-manager-list::-webkit-scrollbar{display:none;width:0;height:0}.conversations-tag-filter-menu{position:absolute;top:100%;right:0;background:var(--gh-bg, white);border:1px solid var(--gh-border, #e5e7eb);border-radius:8px;box-shadow:0 4px 12px #00000026;z-index:1000;min-width:150px;max-height:250px;overflow:hidden}.conversations-tag-filter-item{display:flex;align-items:center;gap:8px;padding:8px 12px;cursor:pointer;font-size:13px;color:var(--gh-text, #374151)}.conversations-tag-filter-item:hover{background:var(--gh-hover, #f3f4f6)}.conversations-tag-filter-item.selected{background:#3b82f61a}.conversations-tag-dot{width:10px;height:10px;border-radius:50%;flex-shrink:0}.conversations-tag-filter-footer{border-top:1px solid var(--gh-border, #e5e7eb)}.conversations-tag-filter-action{color:var(--gh-primary, #3b82f6)!important}");const Mf=()=>{const e=re("conversationsInbox");return "conversationsInbox"===e?"Inbox":e},If=e=>{if("inbox"===e.id)return Mf();const t=(e.name||"").trim(),n=(e.icon||"").trim();return n&&t.startsWith(n)?t.slice(n.length).trim():t},Nf=({manager:e,onInteractionStateChange:t})=>{const n={[Lr]:"ChatGLM",[Hr]:"Z.ai",[Fr]:"Qianwen",[jr]:"QwenAI",[Br]:"ima"},{settings:r}=No(),[i,a]=B([]),[s,l]=B({}),[c,d]=B([]),[u,h]=B("inbox"),[g,p]=B(null),[m,f]=B(false),[b,y]=B(new Set),[v,w]=B(false),[x,k]=B(false),[S,C]=B(""),[_,A]=B(false),[T,I]=B(new Set),[N,L]=B(null),[D,q]=B(false),[O,z]=B(false),[F,j]=B(false),$=oe(),H=e.siteAdapter?.getSiteId?.(),U=!(!H||!n[H]),W=H?n[H]||H:"",V=re("conversationsUnsupportedTitle",{site:W})||`${W} 会话暂不支持`,G=re("conversationsUnsupportedDesc")||"当前站点限制导致会话列表无法稳定获取",Q=re("conversationsUnsupportedSync",{site:W})||`${W} 会话暂不支持同步`,K=U,[Z,Y]=B(null),[J,X]=B(null),ee=P(null),te=P(null),ne=P(null),ie=P(null),ae=P(null);M(()=>{const e=ee.current;if(!e||"undefined"==typeof ResizeObserver)return;const t=()=>{j(e.clientWidth<=340);};t();const n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);const se=E(async()=>{a([...e.getFolders()]),l({...e.getAllConversations()}),d([...e.getTags()]),h(e.getLastUsedFolderId());},[e]);M(()=>{se();},[se]),M(()=>{const t=e.onDataChange(()=>{se();});return ()=>t()},[e,se]);const le=E(e=>{if(!e&&!_&&0===T.size)return void L(null);const t=new Set,n=new Set,r=new Map,o=e.toLowerCase();i.forEach(n=>{e&&If(n).toLowerCase().includes(o)&&t.add(n.id);}),Object.values(s).forEach(t=>{let i=true;if(e&&!t.title.toLowerCase().includes(o)&&(i=false),_&&!t.pinned&&(i=false),T.size>0){const e=t.tagIds?.some(e=>T.has(e));e||(i=false);}i&&(n.add(t.id),r.set(t.id,t.folderId));}),L({folderMatches:t,conversationMatches:n,conversationFolderMap:r,totalCount:n.size});},[i,s,_,T]);M(()=>{le(S);},[_,T,le,S]),M(()=>{if(!D)return;const e=e=>{const t=e.composedPath(),n=ie.current&&t.includes(ie.current),r=ae.current&&t.includes(ae.current);n||r||q(false);},t=setTimeout(()=>{document.addEventListener("click",e,true);},0);return ()=>{clearTimeout(t),document.removeEventListener("click",e,true);}},[D]),M(()=>{const e=!!(J||Z||D||O||m||x);t?.(e);},[J,Z,D,O,m,x,t]);const ce=E(async()=>{if(U)Oo(Q);else {w(true);try{await(e.siteAdapter?.loadAllConversations?.());const t=e.siteAdapter?.getConversationList?.()?.length||0,{newCount:n,updatedCount:r}=await e.syncConversations(u,!1);se(),Oo(0===t?re("conversationsSyncNoSidebarItems"):re("conversationsSyncResult").replace("{scanned}",String(t)).replace("{added}",String(n)).replace("{updated}",String(r)));}finally{w(false);}}},[U,Q,e,u,se]),de=E(()=>{if(e.siteAdapter?.isSharePage?.()||e.siteAdapter?.isNewConversation?.())return;const t=e.siteAdapter?.getSessionId?.();if(!t||"default"===t||"app"===t)return;const n=e.getConversation(t);n?(p(n.folderId),setTimeout(()=>{const e=ee.current;if(!e)return;const n=e.querySelector(`.conversations-item[data-id="${t}"]`);n&&(n.scrollIntoView({behavior:"smooth",block:"center"}),n.classList.add("locate-highlight"),setTimeout(()=>n.classList.remove("locate-highlight"),2e3));},100)):ce();},[e,ce]);M(()=>{const e=()=>{window.__ophelPendingLocateConversation=false,de();};return window.__ophelPendingLocateConversation&&setTimeout(()=>{e();},100),window.addEventListener("ophel:locateConversation",e),()=>{window.removeEventListener("ophel:locateConversation",e);}},[de]),M(()=>{const e=()=>{ce();};return window.addEventListener("ophel:refreshConversations",e),()=>{window.removeEventListener("ophel:refreshConversations",e);}},[ce]);const ue=()=>{y(new Set),f(false);},he=S||_||T.size>0,ge=t=>{let n=Object.values(s).filter(e=>e.folderId===t);N&&(n=n.filter(e=>N.conversationMatches.has(e.id)));const r=e.getSidebarConversationOrder();return n.sort((e,t)=>{if(e.pinned&&!t.pinned)return -1;if(!e.pinned&&t.pinned)return 1;const n=r.indexOf(e.id),o=r.indexOf(t.id);return -1===n&&-1===o?(t.updatedAt||0)-(e.updatedAt||0):-1===n?1:-1===o?-1:n-o}),n},pe=(e,t)=>{if(!t)return e;return e.split(new RegExp(`(${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})`,"gi")).map((e,n)=>e.toLowerCase()===t.toLowerCase()?be("span",{className:"conversations-highlight",children:e},n):e)},me=e=>{const t=ge(e);return t.length>0&&t.every(e=>b.has(e.id))},ve=e=>{if(!N)return true;const t=N.folderMatches.has(e.id),n=Array.from(N.conversationFolderMap.values()).includes(e.id);return t||n},we=R(()=>i.map(e=>{const t=If(e),n=`${e.icon?`${e.icon} `:""}${t}`.trim();return {value:e.id,title:n,label:ye(fe,{children:[e.icon&&be("span",{style:{flexShrink:0},children:e.icon}), be("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})]})}}),[i,$]); return ye(fe,{children:[ be(kf,{isVisible:x,text:`${re("delete")||"删除"}...`}), ye("div",{ref:ee,className:"conversations-content "+(F?"is-narrow":""),style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",position:"relative"},children:[K&&be("div",{className:"conversations-unsupported-mask","aria-hidden":"true",children:ye("div",{className:"conversations-unsupported-card",children:[ be("div",{className:"conversations-unsupported-icon",children:"!"}), be("div",{className:"conversations-unsupported-title",children:V}), be("div",{className:"conversations-unsupported-desc",children:G})]})}), ye("div",{className:"conversations-toolbar",children:[ be(wu,{content:re("conversationsSelectFolder")||"选择文件夹",triggerStyle:{flex:1,minWidth:0},children:be(uf,{className:"conversations-folder-select-dropdown",buttonClassName:"conversations-folder-select",menuClassName:"conversations-folder-select-menu",optionClassName:"conversations-folder-select-option",options:we,value:u,ariaLabel:re("conversationsSelectFolder")||"选择文件夹",onOpenChange:z,onChange:t=>{h(t),e.setLastUsedFolder(t);}})}), be(wu,{content:re("conversationsSync")||"同步",children:be("button",{className:"conversations-toolbar-btn sync",disabled:v||U,onClick:ce,children:be(v?tt:nt,{size:18})})}), be(wu,{content:re("conversationsLocate")||"定位当前对话",children:be("button",{className:"conversations-toolbar-btn locate",onClick:de,children:be(Be,{size:18})})}), be(wu,{content:re("conversationsBatchMode")||"批量操作",children:be("button",{className:"conversations-toolbar-btn batch-mode "+(m?"active":""),onClick:()=>{m&&y(new Set),f(!m);},children:be(Xe,{size:18})})}), be(wu,{content:re("conversationsAddFolder")||"新建文件夹",children:be("button",{className:"conversations-toolbar-btn add-folder",onClick:()=>{t?.(true),Y({type:"folder"});},children:be(et,{size:18})})})]}), ye("div",{className:"conversations-search-bar",children:[ ye("div",{className:"conversations-search-wrapper",style:{position:"relative"},children:[ be("div",{className:"conversations-search-input-group",children:be("input",{ref:te,type:"text",className:"conversations-search-input",placeholder:re("conversationsSearchPlaceholder")||"搜索会话...",value:S,onChange:e=>{return t=e.target.value,C(t),ne.current&&clearTimeout(ne.current),void(ne.current=setTimeout(()=>le(t),150));var t;}})}), be(wu,{content:re("conversationsFilterPinned")||"筛选置顶",children:be("div",{className:"conversations-pin-filter-btn "+(_?"active":""),style:{userSelect:"none"},onClick:()=>A(!_),children:be(vt,{size:14})})}), be(wu,{content:re("conversationsFilterByTags")||"按标签筛选",children:be("div",{ref:ae,className:"conversations-tag-search-btn "+(T.size>0?"active":""),style:{userSelect:"none"},onClick:()=>{const e=!D;e&&t?.(true),q(e);},children:be(gt,{size:14})})}),D&&ye("div",{ref:ie,className:"conversations-tag-filter-menu",children:[ be("div",{className:"conversations-tag-filter-list",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:0===c.length?be("div",{className:"conversations-tag-filter-item",style:{color:"var(--gh-text-tertiary, #9ca3af)",cursor:"default"},children:re("conversationsNoTags")||"暂无标签"}):c.map(e=>ye("div",{className:"conversations-tag-filter-item "+(T.has(e.id)?"selected":""),onClick:()=>{const t=new Set(T);t.has(e.id)?t.delete(e.id):t.add(e.id),I(t);},children:[ be("span",{className:"conversations-tag-dot",style:{backgroundColor:e.color}}), be("span",{children:e.name})]},e.id))}), be("div",{className:"conversations-tag-filter-footer",children:be("div",{className:"conversations-tag-filter-item conversations-tag-filter-action",onClick:()=>{q(false),t?.(true),Y({type:"tagManager",conv:void 0});},children:re("conversationsManageTags")||"管理标签"})})]}), be(wu,{content:re("conversationsClearAll")||"清除所有筛选",children:be("div",{className:"conversations-search-clear "+(he?"":"disabled"),onClick:he?()=>{C(""),A(false),I(new Set),L(null);}:void 0,children:be(ke,{size:14})})})]}),S&&N&&ye("div",{className:"conversations-result-bar visible",children:[N.totalCount," ",re("conversationsSearchResult")||"个结果"]})]}), be("div",{className:"conversations-folder-list",children:0===i.filter(ve).length?be("div",{className:"conversations-empty",children:N?re("conversationsNoSearchResult")||"未找到匹配结果":re("conversationsEmpty")||"暂无会话"}):i.filter(ve).map((n,a)=>{const l=(d=n.id,N?Array.from(N.conversationFolderMap.values()).includes(d):g===d);var d;const u=(e=>N?Object.values(s).filter(t=>t.folderId===e&&N.conversationMatches.has(t.id)).length:Object.values(s).filter(t=>t.folderId===e).length)(n.id),h=If(n),f=r?.features?.conversations?.folderRainbow??false;let v="transparent";return n.isDefault?v="var(--gh-folder-bg-default)":f?v=`var(--gh-folder-bg-${a%8})`:l&&(v="var(--gh-folder-bg-expanded, rgba(59, 130, 246, 0.08))"),ye(o.Fragment,{children:[ ye("div",{className:`conversations-folder-item ${l?"expanded":""} ${n.isDefault?"default":""}`,"data-folder-id":n.id,style:{background:v},onClick:()=>(e=>{p(g===e?null:e);})(n.id),children:[ ye("div",{className:"conversations-folder-info",children:[m&&be("input",{type:"checkbox",className:"conversations-folder-checkbox",checked:me(n.id),ref:e=>{e&&(e.indeterminate=(e=>{const t=ge(e),n=t.filter(e=>b.has(e.id));return n.length>0&&n.length((e,t)=>{const n=ge(e),r=new Set(b);t?n.forEach(e=>r.add(e.id)):n.forEach(e=>r.delete(e.id)),y(r);})(n.id,e.target.checked),onClick:e=>e.stopPropagation()}), be("span",{className:"conversations-folder-icon",style:{userSelect:"none"},children:n.icon}), be(wu,{content:h,children:be("span",{className:"conversations-folder-name",children:S&&N?.folderMatches.has(n.id)?pe(h,S):h})}),!n.isDefault&&ye("div",{className:"conversations-folder-order-btns",style:{userSelect:"none"},children:[ be("button",{className:"conversations-folder-order-btn",title:re("moveUp")||"上移",disabled:a<=1,onClick:()=>{e.moveFolder(n.id,"up"),se();},children:be(kt,{size:12})}), be("button",{className:"conversations-folder-order-btn",title:re("moveDown")||"下移",disabled:a>=i.length-1,onClick:()=>{e.moveFolder(n.id,"down"),se();},children:be(St,{size:12})})]})]}), ye("div",{className:"conversations-folder-controls",children:[ ye("span",{className:"conversations-folder-count",children:["(",u,")"]}), be("button",{className:"conversations-folder-menu-btn",style:{userSelect:"none",visibility:n.isDefault?"hidden":"visible",pointerEvents:n.isDefault?"none":"auto"},onClick:e=>{e.stopPropagation(),t?.(true),X({type:"folder",folder:n,anchorEl:e.currentTarget});},children:be(ct,{size:16})})]})]}),l&&be("div",{className:"conversations-list","data-folder-id":n.id,children:0===ge(n.id).length?be("div",{className:"conversations-list-empty",children:re("conversationsEmpty")||"暂无会话"}):ge(n.id).map(n=>ye("div",{className:"conversations-item","data-id":n.id,onClick:()=>(t=>{if(m){const e=new Set(b);return e.has(t.id)?e.delete(t.id):e.add(t.id),void y(e)}e.siteAdapter?.navigateToConversation(t.id,t.url);})(n),children:[m&&be("input",{type:"checkbox",className:"conversations-item-checkbox",checked:b.has(n.id),onChange:()=>{},onClick:e=>{e.stopPropagation();const t=new Set(b);t.has(n.id)?t.delete(n.id):t.add(n.id),y(t);}}),(()=>{const e=n.tagIds||[],t=F?1:2,r=e.map(e=>c.find(t=>t.id===e)).filter(e=>!!e),o=r.slice(0,t),i=r.slice(t).length; return be("div",{className:"conversations-item-main",children:ye("div",{className:"conversations-item-headline",children:[ be(wu,{content:n.title,triggerStyle:{flex:1,minWidth:0,overflow:"hidden",display:"block"},children:ye("span",{className:"conversations-item-title",style:{userSelect:"none"},children:[n.pinned&&be(vt,{size:12,filled:true,style:{display:"inline-block",marginRight:"4px",verticalAlign:"middle"}}),S&&N?.conversationMatches.has(n.id)?pe(n.title||"无标题",S):n.title||"无标题"]})}),e.length>0&&ye("div",{className:"conversations-tag-list",children:[o.map(e=>be("span",{className:"conversations-tag",style:{backgroundColor:e.color},children:e.name},e.id)),i>0&&be(wu,{content:be("div",{className:"conversations-hidden-tags-tooltip",children:r.map(e=>ye("div",{className:"conversations-hidden-tag-item",children:[ be("span",{className:"conversations-hidden-tag-dot",style:{backgroundColor:e.color}}), be("span",{children:e.name})]},e.id))}),delay:120,triggerStyle:{display:"inline-flex"},children:ye("span",{className:"conversations-tag conversations-tag-more",children:["+",i]})})]})]})})})(), be("div",{className:"conversations-item-meta",children:be("button",{className:"conversations-item-menu-btn",title:re("more")||"更多操作",onClick:e=>{e.stopPropagation(),t?.(true),X({type:"conversation",conv:n,anchorEl:e.currentTarget});},children:be(ct,{size:16})})})]},n.id))})]},n.id)})}),m&&b.size>0&&ye("div",{className:"conversations-batch-bar",children:[ be("span",{className:"conversations-batch-info",children:(re("batchSelected")||"已选 {n} 个").replace("{n}",String(b.size))}), ye("div",{className:"conversations-batch-btns",children:[ be(wu,{content:re("exportToClipboard")||"复制 Markdown",children:be("button",{className:"conversations-batch-btn",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:async()=>{const t=Array.from(b)[0];await e.exportConversation(t,"clipboard");},children:be(lt,{size:16})})}), be(wu,{content:re("batchExport")||"导出",children:be("button",{className:"conversations-batch-btn",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:e=>{t?.(true),X({type:"export",anchorEl:e.currentTarget});},children:be(Re,{size:16})})}), be(wu,{content:re("batchMove")||"移动",children:be("button",{className:"conversations-batch-btn",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:()=>{t?.(true),Y({type:"folderSelect",convIds:Array.from(b)});},children:be(Ce,{size:16})})}), be(wu,{content:re("batchDelete")||"删除",children:be("button",{className:"conversations-batch-btn danger",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:()=>{t?.(true),Y({type:"confirm",title:re("batchDelete")||"批量删除",message:`确定删除选中的 ${b.size} 个会话吗?`,danger:true,onConfirm:async()=>{if(!x){Y(null),k(true),await new Promise(e=>setTimeout(e,0));try{const t=await e.deleteConversations(Array.from(b));if(0===t.localDeletedCount)return void Oo(re("deleteError")||"删除失败");t.remoteAttemptedCount>0&&t.remoteFailedCount>0&&Oo(`已删除 ${t.localDeletedCount} 个,本地成功,云端失败 ${t.remoteFailedCount} 个`),ue(),await se();}finally{k(false);}}}});},children:be(yt,{size:16})})}), be(wu,{content:re("batchExit")||"退出",children:be("button",{className:"conversations-batch-btn cancel",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:ue,children:be(ke,{size:16})})})]})]})]}),"confirm"===Z?.type&&be(mf,{title:Z.title,message:Z.message,danger:Z.danger,onConfirm:Z.onConfirm,onCancel:()=>Y(null)}),"folder"===Z?.type&&be(ff,{folder:Z.folder,onConfirm:async(t,n)=>{let r=null;if(Z.folder)await e.updateFolder(Z.folder.id,{name:t,icon:n});else {const o=await e.createFolder(t,n);o&&(r=o.id);}se(),Z.returnToSelect?Y({type:"folderSelect",conv:Z.returnToSelect.conv,convIds:Z.returnToSelect.convIds,activeFolderId:r||void 0}):Y(null);},onCancel:()=>Y(null)}),"rename"===Z?.type&&be(bf,{title:re("conversationsRename")||"重命名",currentValue:Z.conv.title,onConfirm:async t=>{await e.renameConversation(Z.conv.id,t),se(),Y(null);},onCancel:()=>Y(null)}),"folderSelect"===Z?.type&&be(yf,{folders:i,excludeFolderId:Z.conv?.folderId,activeFolderId:Z.activeFolderId,onSelect:async t=>{if(Z.conv)await e.moveConversation(Z.conv.id,t);else if(Z.convIds){for(const n of Z.convIds)await e.moveConversation(n,t);ue();}se(),Y(null);},onCancel:()=>Y(null),onCreateFolder:()=>Y({type:"folder",returnToSelect:{conv:Z.conv,convIds:Z.convIds}})}),"tagManager"===Z?.type&&be(vf,{tags:c,conv:Z.conv,onCancel:()=>Y(null),onCreateTag:async(t,n)=>e.createTag(t,n),onUpdateTag:async(t,n,r)=>e.updateTag(t,n,r),onDeleteTag:async t=>e.deleteTag(t),onSetConversationTags:async(t,n)=>e.setConversationTags(t,n),onRefresh:()=>se()}),"folder"===J?.type&&be(_f,{folder:J.folder,anchorEl:J.anchorEl,onClose:()=>X(null),onRename:()=>{X(null),Y({type:"folder",folder:J.folder});},onDelete:()=>{X(null);const t=If(J.folder),n=Mf(),r=re("conversationsDeleteConfirm",{folder:t,inbox:n});Y({type:"confirm",title:re("conversationsDelete")||"删除",message:"conversationsDeleteConfirm"===r?`Delete folder "${t}"? Conversations will be moved to ${n}.`:r,danger:true,onConfirm:async()=>{await e.deleteFolder(J.folder.id),se(),Y(null);}});}}),"conversation"===J?.type&&be(Af,{conversation:J.conv,anchorEl:J.anchorEl,onClose:()=>X(null),onRename:()=>{X(null),Y({type:"rename",conv:J.conv});},onTogglePin:async()=>{X(null),await e.togglePin(J.conv.id),se();},onSetTags:()=>{X(null),Y({type:"tagManager",conv:J.conv});},onMoveTo:()=>{X(null),Y({type:"folderSelect",conv:J.conv});},onDelete:()=>{X(null),Y({type:"confirm",title:re("conversationsDelete")||"删除",message:`确定删除会话 "${J.conv.title}" 吗?`,danger:true,onConfirm:async()=>{if(!x){Y(null),k(true),await new Promise(e=>setTimeout(e,0));try{const t=await e.deleteConversation(J.conv.id);if(!t.localDeleted)return void Oo(re("deleteError")||"删除失败");t.remoteAttempted&&!t.remoteSuccess&&Oo("已从面板删除,但云端删除失败"),await se();}finally{k(false);}}}});}}),"export"===J?.type&&be(Tf,{anchorEl:J.anchorEl,onClose:()=>X(null),onExportMarkdown:async()=>{X(null);const t=b.size>0?Array.from(b)[0]:e.siteAdapter.getSessionId();await e.exportConversation(t,"markdown");},onExportJSON:async()=>{X(null);const t=b.size>0?Array.from(b)[0]:e.siteAdapter.getSessionId();await e.exportConversation(t,"json");},onExportTXT:async()=>{X(null);const t=b.size>0?Array.from(b)[0]:e.siteAdapter.getSessionId();await e.exportConversation(t,"txt");}})]})};function Lf(e,t){if(e<1e3)return e.toString();if("zh-CN"===t||"zh-TW"===t){if(e>=1e4)return (e/1e4).toFixed(1).replace(/\.0$/,"")+"w";if(e>=1e3)return (e/1e3).toFixed(1).replace(/\.0$/,"")+"k"}return e>=1e3?e>=1e6?(e/1e6).toFixed(1).replace(/\.0$/,"")+"m":(e/1e3).toFixed(1).replace(/\.0$/,"")+"k":e.toString()}const Df=(e,t,n,r,o,i)=>{const a={},s={},l=new Map,c=e=>{const t=l.get(e.index);if(void 0!==t)return t;let n=!!e.isBookmarked;if(!n&&e.children&&e.children.length>0)for(const r of e.children)if(c(r)){n=true;break}return l.set(e.index,n),n},d=(e,l,u,h,g)=>{a[e.index]=l;const p=c(e);let m;if(i)if(p||g){const t=!r||e.isMatch||e.hasMatchedDescendant;m=!u&&t;}else m=false;else {const i=e.relativeLevel===n,a=e.relativeLevel<=t||h;if(i)m=!r||(e.isMatch||e.hasMatchedDescendant);else {const t=!r||e.isMatch||e.hasMatchedDescendant||h;m=r&&!o?t&&!u:r&&o?t&&a&&!u:a&&!u;}u&&(m=false);}e.forceVisible&&(m=true),s[e.index]=m;const f=e.collapsed||u,b=e.forceExpanded||h,y=g||e.isBookmarked&&!(e=>!(!e.children||0===e.children.length)&&e.children.some(c))(e);e.children&&e.children.length>0&&e.children.forEach(t=>d(t,e.index,f,b,y));};return e.forEach(e=>d(e,null,false,false,false)),{parentMap:a,visibleMap:s}},Rf=({node:e,onToggle:t,onClick:n,onCopy:r,onToggleBookmark:o,activeIndex:i,visibleHighlightIndex:a,setItemRef:s,visibleMap:l,searchQuery:c,extractUserQueryText:d})=>{const u=e.index===i,h=e.index===a,g=e.children&&e.children.length>0,p=g&&!e.collapsed,m=l[e.index]??true,f=["outline-item",`outline-level-${e.relativeLevel}`,e.isUserQuery?"user-query-node":"",e.isGhost?"ghost-node":"",u?"sync-highlight":"",h?"sync-highlight-visible":"",m?"":"outline-hidden"].filter(Boolean).join(" "),[b,y]=B(false),[v,w]=B(false); return ye(fe,{children:[ be(wu,{content:e.wordCount&&e.wordCount>0?ye("div",{children:[e.text, ye("div",{style:{fontSize:"12px",opacity:.8,marginTop:"2px"},children:["(",Lf(e.wordCount,oe())," ",re("words")||"words",")"]})]}):e.text,disabled:v,triggerStyle:{width:"100%",display:"block"},triggerClassName:m?"":"outline-hidden",delay:500,children:ye("div",{className:f,"data-index":e.index,"data-level":e.relativeLevel,ref:t=>s(e.index,t),onClick:()=>n(e),children:[ be("span",{className:"outline-item-toggle "+(g?p?"expanded":"":"invisible"),onClick:n=>{g&&(n.stopPropagation(),t(e));},children:be(ut,{size:16,style:{transform:"rotate(-90deg)"}})}),e.isUserQuery&&ye("span",{className:"user-query-badge",children:[ be("span",{className:"user-query-badge-icon",children:"💬"}), be("span",{className:"user-query-badge-number",children:e.queryIndex})]}), be("span",{className:"outline-item-text "+(e.isGhost?"ghost-text":""),children:(()=>{if(c&&e.isMatch)try{const t=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`(${t})`,"gi"),r=e.text.split(n); return be(fe,{children:r.map((e,t)=>e.toLowerCase()===c.toLowerCase()?be("mark",{style:{backgroundColor:"var(--gh-search-highlight-bg)",color:"inherit",padding:0,borderRadius:"2px"},children:e},t):e)})}catch{return e.text}return e.text})()}), be("span",{className:"outline-item-bookmark-wrapper "+(e.isBookmarked?"active":""),children:be(wu,{content:e.isBookmarked?re("removeBookmark")||"Remove Bookmark":re("addBookmark")||"Add Bookmark",children:be("span",{className:"outline-item-bookmark-btn "+(e.isBookmarked?"active":""),onClick:t=>o(t,e),onMouseEnter:()=>w(true),onMouseLeave:()=>w(false),children:be(Ze,{size:14,filled:e.isBookmarked,color:e.isBookmarked?"#f59e0b":"currentColor"})})})}), be(wu,{content:re("copy")||"复制",children:be("span",{className:"outline-item-copy-btn",onClick:async t=>{t.stopPropagation(),t.preventDefault();let n=e.text;if(e.element&&e.element.isConnected)if(e.isUserQuery&&d){const t=d(e.element);t&&(n=t);}else {const t=e.element.textContent;t&&(n=t.trim());}try{await navigator.clipboard.writeText(n),y(!0),setTimeout(()=>y(!1),1500);}catch(r){console.error("[DEBUG] Clipboard API failed, trying fallback:",r);try{const e=document.createElement("textarea");e.value=n,e.style.position="fixed",e.style.left="-9999px",document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e),y(!0),setTimeout(()=>y(!1),1500);}catch(o){console.error("[DEBUG] Fallback copy also failed:",o);}}},onMouseEnter:()=>w(true),onMouseLeave:()=>w(false),children:b? be(At,{size:14,color:"#10b981"}): be(lt,{size:14})})})]})}),g&&e.children.map((e,u)=>be(Rf,{node:e,onToggle:t,onClick:n,onCopy:r,onToggleBookmark:o,activeIndex:i,visibleHighlightIndex:a,setItemRef:s,visibleMap:l,searchQuery:c,extractUserQueryText:d},`${e.level}-${e.text}-${u}`))]})},qf=({manager:e,onJumpBefore:t})=>{const{settings:n}=No(),r=e.getState(),[o,i]=B(r.tree),[a,s]=B(null),[l,c]=B(null),[d,u]=B(e.getSearchQuery()),[h,g]=B(r.isAllExpanded),[p,m]=B(r.includeUserQueries),[f,b]=B("bottom"),[y,v]=B(r.expandLevel??6),[w,x]=B(r.levelCounts),[k,S]=B(r.displayLevel),[C,_]=B(r.minRelativeLevel),[A,T]=B(r.searchLevelManual),[I,N]=B(r.matchCount),[L,D]=B(r.bookmarkMode),q=P(null),O=P(null),z=P(0),F=P(false),j=P(null),$=P(null),H=P(new Map),U=P({parentMap:{},visibleMap:{},hasData:false});M(()=>(e.setActive(true),()=>{e.setActive(false);}),[e]),M(()=>{const e=()=>{O.current&&(O.current.focus(),O.current.select());};return window.addEventListener("ophel:searchOutline",e),window.__ophelPendingSearchOutline&&(delete window.__ophelPendingSearchOutline,setTimeout(e,100)),()=>{window.removeEventListener("ophel:searchOutline",e);}},[]),M(()=>{const t=()=>{const t=e.getState(),r=e=>{let t=0;for(const n of e)t+=1,n.children&&n.children.length>0&&(t+=r(n.children));return t},o=r(t.tree),a=z.current;"latest"===(n?.features?.outline?.followMode||"current")&&o>a&&(F.current=true),i([...t.tree]),u(e.getSearchQuery()),g(t.isAllExpanded),v(t.expandLevel??6),x(t.levelCounts||{}),m(t.includeUserQueries),S(t.displayLevel),_(t.minRelativeLevel),T(t.searchLevelManual),N(t.matchCount),D(t.bookmarkMode),z.current=o;};return t(),e.subscribe(t)},[e,n?.features?.outline?.followMode]),M(()=>{if(F.current&&q.current){const e=q.current;requestAnimationFrame(()=>{e.scrollTo({top:e.scrollHeight,behavior:"smooth"});}),F.current=false;}},[o]);const W=E(e=>{j.current!==e&&(j.current=e,s(e));},[]),V=E(e=>{$.current!==e&&($.current=e,c(e));},[]),G=E((e,t)=>{const n=H.current;t?n.set(e,t):n.delete(e);},[]),Q=E(e=>{if(null===e)return null;const{parentMap:t,visibleMap:n,hasData:r}=U.current;if(!r)return e;let o=e;for(;null!=o;){if(n[o])return o;o=t[o];}return null},[]),K=R(()=>Df(o,k,C,d,A,L),[o,k,C,d,A,L]),{parentMap:Z,visibleMap:Y}=K,J=R(()=>{const e=t=>{for(const n of t){if(Y[n.index])return true;if(n.children&&n.children.length>0&&e(n.children))return true}return false};return e(o)},[o,Y]);U.current={parentMap:Z,visibleMap:Y,hasData:o.length>0},M(()=>{const e=Q(j.current);V(e);},[Z,Y,o.length,Q,V]),M(()=>{if("current"!==(n?.features?.outline?.followMode||"current"))return W(null),void V(null);let t,r=null,o=0,i=0,a=null,s=null,l=null;const c=new Map,d=()=>{e.markScrollPositionsStale();},u=t=>{if(c.has(t))return;const n=new MutationObserver(()=>{s||(s=setTimeout(()=>{s=null;const t="undefined"!=typeof window?window.requestIdleCallback:void 0;if(t){if(null!==l)return;l=t(()=>{l=null,e.markScrollPositionsStale();},{timeout:500});}else e.markScrollPositionsStale();},300));});n.observe(t,{childList:true,subtree:true,characterData:true}),c.set(t,n);},h=()=>{if(!r)return;const t=r.scrollTop,n=r.clientHeight,o=r.scrollHeight;o!==i&&(i=o,e.markScrollPositionsStale());const a=e.findVisibleItemIndex(t,n);if(null===a)return W(null),void V(null);W(a);const s=Q(a);V(s),null!==s&&requestAnimationFrame(()=>{const e=q.current;if(!e)return;const t=H.current.get(s)||null;if(!t)return;const n=e.getBoundingClientRect(),r=t.getBoundingClientRect();if(r.topn.bottom){const t=r.top-n.top-n.height/2+r.height/2;e.scrollBy({top:t,behavior:"instant"});}});},g=()=>{const n=e.getScrollContainer();n?(r=n,i=n.scrollHeight,r.addEventListener("scroll",h,{passive:true}),window.addEventListener("resize",d,{passive:true}),(e=>{try{u(e);}catch(t){console.warn("[OutlineTab] Failed to attach MutationObserver:",t);}})(n),"undefined"!=typeof ResizeObserver&&(a=new ResizeObserver(()=>{i=r?.scrollHeight||0,e.markScrollPositionsStale();}),a.observe(r)),h()):o<20?(o++,t=setTimeout(g,300)):console.warn("[OutlineTab] Failed to find scroll container after retries");};return g(),()=>{if(r&&r.removeEventListener("scroll",h),window.removeEventListener("resize",d),s&&clearTimeout(s),null!==l){const e="undefined"!=typeof window?window.cancelIdleCallback:void 0;e&&e(l),l=null;}c.forEach(e=>e.disconnect()),c.clear(),a&&(a.disconnect(),a=null),t&&clearTimeout(t);}},[e,o.length,n?.features?.outline?.followMode,Q,W,V]),M(()=>{const e=q.current;if(!e)return;const t=()=>{const t=e.scrollTop+e.clientHeight>=e.scrollHeight-10;b(t?"top":"bottom");};return e.addEventListener("scroll",t),t(),()=>e.removeEventListener("scroll",t)},[]);const X=E(t=>{e.toggleNode(t);},[e]),ee=E(async n=>{let r=n.element,o=false;if(!r||!r.isConnected){t&&(await t(),o=true);const i=await e.resolveOutlineTarget(n,n.queryIndex);i&&(r=i,n.element=r);}if(r&&r.isConnected)t&&!o&&await t(),r.scrollIntoView({behavior:"instant",block:"start",__bypassLock:true}),r.classList.add("outline-highlight"),setTimeout(()=>r?.classList.remove("outline-highlight"),2e3);else if(n.isGhost&&void 0!==n.scrollTop){const t=e.getScrollContainer();t&&(t.scrollTo({top:n.scrollTop,behavior:"smooth"}),Oo(re("bookmarkContentMissing")||"收藏内容不存在,已跳转到保存位置",3e3));}else Oo(re("bookmarkContentMissing")||"收藏内容已被删除或折叠",2e3);},[e,t]),te=E((e,t)=>{e.stopPropagation();const n=t.text;navigator.clipboard.writeText(n);},[]),ne=E(t=>e.extractUserQueryText(t),[e]),oe=E(t=>{e.setSearchQuery(t.target.value);},[e]),ie=E(()=>{e.setSearchQuery("");},[e]),ae=E(()=>{h?e.collapseAll():e.expandAll();},[e,h]),se=E((t,n)=>{t.stopPropagation(),e.toggleBookmark(n);},[e]),le=E(()=>{e.toggleBookmarkMode();},[e]),ce=E(()=>{e.toggleGroupMode();},[e]),de=E(()=>{const e=q.current;e&&("bottom"===f?e.scrollTo({top:e.scrollHeight,behavior:"smooth"}):e.scrollTo({top:0,behavior:"smooth"}));},[f]),ue=E(()=>{const t=e.getScrollContainer();if(!t)return;d&&(e.setSearchQuery(""),u(""));const n=e=>{const t=[];return e.forEach(e=>{t.push(e),e.children&&e.children.length>0&&t.push(...n(e.children));}),t},r=n(o),i=t.getBoundingClientRect(),a=i.top,s=i.bottom;let l=null;for(const e of r){if(!e.element||!e.element.isConnected)continue;const t=e.element.getBoundingClientRect();if(t.top>=a&&t.topa){l=e;break}}if(!l){let e=1/0;for(const t of r){if(!t.element||!t.element.isConnected)continue;const n=t.element.getBoundingClientRect(),r=Math.abs(n.top-a);r{const t=q.current;if(!t)return;const n=t.querySelector(`.outline-item[data-index="${l.index}"]`);n&&(n.scrollIntoView({behavior:"instant",block:"center"}),n.classList.add("highlight"),setTimeout(()=>{n.classList.remove("highlight"),e.clearForceVisible();},3e3));},50));},[o,d,e]),he=E(t=>{e.setLevel(t);},[e]);return M(()=>{const e=()=>{window.__ophelPendingLocateOutline=false,ue();};return window.__ophelPendingLocateOutline&&setTimeout(()=>{e();},100),window.addEventListener("ophel:locateOutline",e),()=>{window.removeEventListener("ophel:locateOutline",e);}},[ue]),ye("div",{className:"gh-outline-tab",style:{display:"flex",flexDirection:"column",height:"100%"},children:[ ye("div",{className:"outline-fixed-toolbar",style:{padding:"8px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",flexDirection:"column",gap:"8px",backgroundColor:"var(--gh-bg, #fff)"},children:[ ye("div",{style:{display:"flex",gap:"4px",alignItems:"center"},children:[ ye("div",{style:{display:"flex",gap:"2px"},children:[ be(wu,{content:p?re("outlineOnlyUserQueries")||"仅显示提问":re("outlineShowUserQueries")||"显示所有",children:be("button",{onClick:ce,className:"outline-toolbar-btn "+(p?"active-subtle":""),children:be(_t,{size:15})})}), be(wu,{content:re("bookmarkMode")||"收藏",children:be("button",{onClick:le,className:"outline-toolbar-btn "+(L?"active-subtle":""),children:be(Ze,{size:16,filled:L,color:"currentColor"})})}), be(wu,{content:L?re("bookmarkModeDisabled")||"收藏模式下不可用":re(h?"outlineCollapseAll":"outlineExpandAll"),children:be("button",{onClick:L?void 0:ae,disabled:L,style:{width:"26px",height:"26px",padding:0,border:"1px solid var(--gh-input-border, #d1d5db)",borderRadius:"4px",backgroundColor:"var(--gh-bg, #fff)",color:L?"var(--gh-text-disabled, #9ca3af)":"var(--gh-text, #374151)",cursor:L?"not-allowed":"pointer",opacity:L?.5:1,display:"flex",alignItems:"center",justifyContent:"center"},children:be(h?Pe:qe,{size:16})})}), be(wu,{content:re("outlineLocateCurrent")||"定位到当前位置",children:be("button",{onClick:ue,style:{width:"26px",height:"26px",padding:0,border:"1px solid var(--gh-input-border, #d1d5db)",borderRadius:"4px",backgroundColor:"var(--gh-bg, #fff)",color:"var(--gh-text, #374151)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:be(Be,{size:16})})}), be(wu,{content:"bottom"===f?re("outlineScrollBottom")||"滚动到底部":re("outlineScrollTop")||"回到顶部",children:be("button",{onClick:de,style:{width:"26px",height:"26px",padding:0,border:"1px solid var(--gh-input-border, #d1d5db)",borderRadius:"4px",backgroundColor:"var(--gh-bg, #fff)",color:"var(--gh-text, #374151)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"14px"},children:be("bottom"===f?ze:Oe,{size:16})})})]}), ye("div",{className:"outline-search-wrapper",style:{flex:1,position:"relative",display:"flex",alignItems:"center"},children:[ be("input",{ref:O,type:"text",className:"outline-search-input",placeholder:re("outlineSearch")||"搜索...",value:d,onChange:oe,style:{width:"100%",padding:"4px 24px 4px 8px",borderRadius:"4px",border:"1px solid var(--gh-input-border, #d1d5db)",fontSize:"12px",boxSizing:"border-box",height:"26px",backgroundColor:"var(--gh-input-bg, #fff)",color:"var(--gh-text, #374151)"}}),d&&be("button",{className:"outline-search-clear",onClick:ie,style:{position:"absolute",right:"4px",background:"none",border:"none",color:"var(--gh-text-tertiary, #9ca3af)",cursor:"pointer",fontSize:"14px",padding:0,display:"flex",alignItems:"center",justifyContent:"center"},children:be(ke,{size:14})})]})]}), be("div",{className:"outline-level-slider-container",style:{padding:"0 4px"},children:ye("div",{className:"outline-level-dots",style:{display:"flex",justifyContent:"space-between",position:"relative",padding:"6px 0",alignItems:"center"},children:[ be("div",{className:"outline-level-line-bg",style:{position:"absolute",top:"50%",left:"4px",right:"4px",height:"4px",background:"var(--gh-border, #e5e7eb)",zIndex:0,transform:"translateY(-50%)",borderRadius:"2px"}}), be("div",{className:"outline-level-progress",style:{position:"absolute",top:"50%",left:"4px",height:"4px",background:L?"var(--gh-text-disabled, #9ca3af)":"var(--gh-primary, #3b82f6)",zIndex:0,transform:"translateY(-50%)",borderRadius:"2px",width:`calc((${y} / 6) * (100% - 8px))`,transition:"width 0.2s ease"}}),[0,1,2,3,4,5,6].map(e=>{let t="";t=L?re("bookmarkModeDisabled")||"收藏模式下不可用":0===e?p?re("outlineOnlyUserQueries")||"仅显示提问":re("outlineCollapseAll")||"折叠全部":`H${e}: ${w[e]||0}`;const n=e<=y; return be(wu,{content:t,children:be("div",{className:`outline-level-dot ${n?"active":""} ${L?"disabled":""}`,"data-level":e,onClick:L?void 0:()=>he(e),style:{width:"14px",height:"14px",borderRadius:"50%",backgroundColor:n?L?"var(--gh-text-disabled, #9ca3af)":"var(--gh-primary, #3b82f6)":"var(--gh-slider-dot-bg, #d1d5db)",border:n?"2px solid var(--gh-bg, #fff)":"none",zIndex:1,cursor:L?"not-allowed":"pointer",position:"relative",transition:"all 0.2s ease",boxSizing:"border-box",boxShadow:n?L?"0 0 0 1px var(--gh-text-disabled, #9ca3af)":"0 0 0 1px var(--gh-primary, #3b82f6)":"none",opacity:L?.5:1}})},e)})]})})]}),d&&ye("div",{className:"outline-result-bar",style:{textAlign:"center",padding:"6px 8px",margin:"0 8px 0 8px",color:"var(--gh-border-active)",fontSize:"13px",background:I>0?"var(--gh-folder-bg-default)":"transparent",borderRadius:"4px",border:0===I?"1px dashed var(--gh-border, #e5e7eb)":"none",flexShrink:0},children:[I," ",re("outlineSearchResult")||"个结果"]}), be("div",{ref:q,className:`gh-outline-tree-container gh-panel-bookmark-mode-${n?.features?.outline?.panelBookmarkMode||"always"}`,style:{flex:1,overflowY:"auto",padding:d?"0 8px 8px 8px":"8px"},children:(()=>{const e=t=>t.some(t=>t.isBookmarked||t.children&&t.children.length>0&&e(t.children)),t=e(o),n=0===o.length,r=!d&&(n||!J),i=p&&0===k?re("outlineEmptyDescUserQueryOnly")||"Only user queries are shown. Send a message to build the outline.":re("outlineEmptyDescDefault")||"Outline items will appear as the conversation grows.",s=i.indexOf(","),c=i.indexOf(",");let u=-1;u=s>=0&&c>=0?Math.min(s,c):Math.max(s,c);const h=u>=0?i.slice(0,u).trim():i,g=u>=0?i.slice(u+1).trim():"";return !L||t||d?r?ye("div",{className:"outline-empty-state",children:[ be("div",{className:"outline-empty-state-icon","aria-hidden":"true",children:be(Me,{size:18,color:"currentColor"})}), be("div",{className:"outline-empty-state-title",children:re("outlineEmpty")||"暂无大纲内容"}), ye("div",{className:"outline-empty-state-desc",children:[ be("span",{className:"outline-empty-state-desc-line",children:h}),g&&be("span",{className:"outline-empty-state-desc-line",children:g})]})]}):be("div",{className:"outline-list",children:o.map((e,t)=>be(Rf,{node:e,onToggle:X,onClick:ee,onCopy:te,onToggleBookmark:se,activeIndex:a,visibleHighlightIndex:l,setItemRef:G,visibleMap:Y,searchQuery:d,extractUserQueryText:ne},`${e.level}-${e.text}-${t}`))}):ye("div",{style:{textAlign:"center",color:"var(--gh-text-tertiary, #9ca3af)",marginTop:"40px",display:"flex",flexDirection:"column",alignItems:"center",gap:"8px"},children:[ be("div",{style:{width:"40px",height:"40px",borderRadius:"50%",background:"rgba(245, 158, 11, 0.1)",display:"flex",alignItems:"center",justifyContent:"center",color:"#f59e0b",marginBottom:"8px"},children:be(Ze,{size:20,filled:true,color:"#f59e0b"})}), be("div",{style:{fontSize:"14px",fontWeight:500,color:"var(--gh-text, #374151)"},children:re("outlineNoBookmarks")||"暂无收藏"}), be("div",{style:{fontSize:"12px",opacity:.7},children:re("outlineAddBookmarkHint")||"点击条目旁的星号添加收藏"})]})})()})]})},Pf=({variables:e,onConfirm:t,onCancel:n})=>{const[r,o]=B(e.map(e=>({name:e.raw,value:e.options?e.options[0]:e.defaultValue??""}))),i=P(null);M(()=>{setTimeout(()=>{i.current?.focus();},100);},[]);const a=()=>{const e={};r.forEach(t=>{e[t.name]=t.value;}),t(e);},s=(e,t)=>{o(n=>{const r=[...n];return r[e]={...r[e],value:t},r});}; return be(af,{onClose:n,closeOnOverlayClick:false,dialogClassName:"prompt-modal-content",dialogStyle:{width:"400px",maxWidth:"90%",maxHeight:"80vh",display:"flex",flexDirection:"column",boxShadow:"0 4px 20px rgba(0,0,0,0.2)",animation:"slideUp 0.2s ease-out",padding:0},children:ye("div",{onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),a()),"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),n());},style:{display:"flex",flexDirection:"column",flex:1,minHeight:0},children:[ ye("div",{style:{padding:"16px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ be("h3",{style:{margin:0,fontSize:"16px",fontWeight:600,color:"var(--gh-text, #374151)"},children:re("promptVariableTitle")||"填写变量"}), be("button",{onClick:n,style:{background:"none",border:"none",cursor:"pointer",fontSize:"18px",color:"var(--gh-text-secondary, #9ca3af)"},children:be(ke,{size:18})})]}), be("div",{style:{padding:"16px",overflowY:"auto",flex:1},children:e.map((e,t)=>ye("div",{style:{marginBottom:"16px",display:"flex",flexDirection:"column",gap:"6px"},children:[ be("label",{style:{fontSize:"14px",fontWeight:500,color:"var(--gh-text, #374151)",wordBreak:"break-all"},children:e.name}),e.options? be("select",{value:r[t]?.value??"",onChange:e=>s(t,e.target.value),style:{width:"100%",padding:"8px 12px",borderRadius:"6px",border:"1px solid var(--gh-input-border, #d1d5db)",fontSize:"14px",outline:"none",background:"var(--gh-input-bg, white)",color:"var(--gh-text, #374151)",boxSizing:"border-box",cursor:"pointer",transition:"border-color 0.2s, box-shadow 0.2s"},onFocus:e=>{e.target.style.borderColor="var(--gh-primary, #4285f4)",e.target.style.boxShadow="0 0 0 2px rgba(66, 133, 244, 0.1)";},onBlur:e=>{e.target.style.borderColor="var(--gh-input-border, #d1d5db)",e.target.style.boxShadow="none";},children:e.options.map(e=>be("option",{value:e,children:e},e))}): be("input",{ref:0===t?i:void 0,type:"text",value:r[t]?.value??"",onChange:e=>s(t,e.target.value),placeholder:e.defaultValue?`${re("promptVariablePlaceholder")||"请输入"} (${re("default")||"默认"}: ${e.defaultValue})`:re("promptVariablePlaceholder")||"请输入",style:{width:"100%",padding:"8px 12px",borderRadius:"6px",border:"1px solid var(--gh-input-border, #d1d5db)",fontSize:"14px",outline:"none",background:"var(--gh-input-bg, white)",color:"var(--gh-text, #374151)",boxSizing:"border-box",transition:"border-color 0.2s, box-shadow 0.2s"},onFocus:e=>{e.target.style.borderColor="var(--gh-primary, #4285f4)",e.target.style.boxShadow="0 0 0 2px rgba(66, 133, 244, 0.1)";},onBlur:e=>{e.target.style.borderColor="var(--gh-input-border, #d1d5db)",e.target.style.boxShadow="none";}})]},e.raw))}), ye("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"flex-end",gap:"8px"},children:[ be("button",{onClick:n,style:{padding:"8px 16px",borderRadius:"6px",border:"1px solid var(--gh-border, #d1d5db)",background:"var(--gh-bg, white)",color:"var(--gh-text, #374151)",fontSize:"14px",cursor:"pointer"},children:re("cancel")||"取消"}), be("button",{onClick:a,style:{padding:"8px 16px",borderRadius:"6px",border:"none",background:"var(--gh-primary, #4285f4)",color:"white",fontSize:"14px",cursor:"pointer",fontWeight:500},children:re("confirm")||"确认"})]})]})})},Bf=e=>{const t=e.indexOf(":");if(-1===t)return {raw:e,name:e};const n=e.substring(0,t),r=e.substring(t+1);if(r.includes("|")){return {raw:e,name:n,options:r.split("|").filter(e=>e.length>0)}}return {raw:e,name:n,defaultValue:r}},Of=e=>{const t=/\{\{([^\s{}]+)\}\}/g,n=new Set,r=[];let o;for(;null!==(o=t.exec(e));){const e=o[1];n.has(e)||(n.add(e),r.push(Bf(e)));}return r},zf=({manager:e,onPromptSelect:t,selectedPromptId:n})=>{const r=No(e=>e.settings.features?.prompts?.doubleClickToSend??false),o=No(e=>e.settings.features?.prompts?.submitShortcut??"enter"),[i,a]=B([]),[s,l]=B([]),[c,d]=B(Wr),[u,h]=B(""),[g,p]=B(false),[m,f]=B(null),[b,y]=B(false),[v,w]=B({show:false,title:"",message:"",onConfirm:()=>{}}),[x,k]=B({show:false,title:"",defaultValue:"",onConfirm:()=>{}}),[S,C]=B(null),_=P(null),[A,T]=B({show:false,prompt:null,variables:[],submitAfterInsert:false}),[I,N]=B({show:false,prompts:[]}),[L,D]=B(false),[R,q]=B({show:false,prompt:null}),O=P(null),z=P(null),F=P(null),[j,$]=B(null),H=P(null),U=P(null),W=E(()=>{const t=e.getPrompts(),n=e.getCategories();a(t),l(n),d(e=>{if(e===Wr)return e;if(!n.includes(e))return Wr;return t.some(t=>t.category===e)?e:Wr});},[e]),V=E((t,n=false)=>{const r=e.getPrompts().find(e=>e.id===t);if(!r)return false;const o=Of(r.content);return 0!==o.length&&(T({show:true,prompt:r,variables:o,submitAfterInsert:n}),true)},[e]),G=E(n=>{const r=e.getPrompts().find(e=>e.id===n);return !!r&&(d(Wr),h(""),t?.(null),$(r.id),true)},[e,t]);M(()=>{const e=window,n=n=>{const r=n.detail,o=r?.promptId;if(!o)return;V(o,Boolean(r?.submitAfterInsert))&&(t?.(null),e.__ophelPendingPromptVariableDialog=null);};window.addEventListener("ophel:openPromptVariableDialog",n);const r=e.__ophelPendingPromptVariableDialog;if(r?.promptId){V(r.promptId,Boolean(r.submitAfterInsert))&&(t?.(null),e.__ophelPendingPromptVariableDialog=null);}return ()=>{window.removeEventListener("ophel:openPromptVariableDialog",n);}},[t,V]),M(()=>{const e=window,t=t=>{const n=t.detail,r=n?.promptId;if(!r)return;G(r)&&(e.__ophelPendingLocatePrompt=null);};window.addEventListener("ophel:locatePrompt",t);const n=e.__ophelPendingLocatePrompt;if(n?.promptId){G(n.promptId)&&(e.__ophelPendingLocatePrompt=null);}return ()=>{window.removeEventListener("ophel:locatePrompt",t);}},[G]),M(()=>{W();},[W]),M(()=>()=>{null!==O.current&&window.clearTimeout(O.current),null!==z.current&&window.clearTimeout(z.current);},[]),M(()=>{L&&H.current&&Au(H.current,{size:14,color:"#6b7280"});},[L,m?.content]),M(()=>{R.show&&U.current&&Au(U.current,{size:14,color:"#6b7280"});},[R.show,R.prompt]);const Q=(e,t,n)=>{w({show:true,title:e,message:t,onConfirm:n});},K=async(e,t=false)=>{const n=Of(e.content);n.length>0?T({show:true,prompt:e,variables:n,submitAfterInsert:t}):await Z(e,e.content,t);},Z=async(n,r,i=false)=>{if(await e.insertPrompt(r)){let r=true;i&&(r=await e.submitPrompt(o),r||Oo(re("promptSendFailed")||"发送失败,提示词已保留在输入框中")),e.updateLastUsed(n.id),t?.(i&&r?null:n),i?r&&Oo(`${re("promptSent")||"已发送"}: ${n.title}`):Oo(`${re("inserted")||"已插入"}: ${n.title}`);}else Oo(re("insertFailed")||"未找到输入框,请点击输入框后重试");},Y=()=>{const t=I.prompts;e.setPrompts(t),W(),N({show:false,prompts:[]}),Oo((re("promptImportSuccess")||"已导入 {count} 个提示词").replace("{count}",t.length.toString()));},J=()=>{const t=I.prompts,n=e.getPrompts(),r=new Set(n.map(e=>e.id)),o=t.filter(e=>r.has(e.id)),i=t.filter(e=>!r.has(e.id));o.forEach(t=>{e.updatePrompt(t.id,{title:t.title,content:t.content,category:t.category,pinned:t.pinned});}),i.forEach(t=>{e.addPrompt({title:t.title,content:t.content,category:t.category,pinned:t.pinned});}),W(),N({show:false,prompts:[]});const a=`已合并:更新 ${o.length} 个,新增 ${i.length} 个`;Oo(re("promptMergeSuccess")?.replace("{updated}",o.length.toString()).replace("{added}",i.length.toString())||a);},X=async()=>{if(!m?.title||!m?.content)return void Oo(re("fillTitleContent")||"请填写标题和内容");const t=m.category||re("uncategorized")||"未分类";let n=false;if(m.id){const r=i.find(e=>e.id===m.id),o=r?.category;if(o&&o!==t&&c===o){0===i.filter(e=>e.category===o&&e.id!==m.id).length&&(n=true);}await e.updatePrompt(m.id,{title:m.title,content:m.content,category:t}),Oo(re("promptUpdated")||"提示词已更新"),n&&d(t);}else await e.addPrompt({title:m.title,content:m.content,category:t}),Oo(re("promptAdded")||"提示词已添加");ee(),W();},ee=E(()=>{p(false),f(null);},[]),te=E(()=>{y(false);},[]),ne=E(()=>{w(e=>({...e,show:false}));},[]),oe=E(()=>{k(e=>({...e,show:false}));},[]),ie=E(()=>{q({show:false,prompt:null});},[]),ae=E(()=>{N({show:false,prompts:[]});},[]),se=E(()=>{T({show:false,prompt:null,variables:[],submitAfterInsert:false});},[]),le=e=>{if(e)f({...e});else {const e=c===Wr||c===Vr?s[0]||re("uncategorized")||"未分类":c;f({title:"",content:"",category:e});}p(true);},ce=(t,n)=>{var r;n.stopPropagation(),n.preventDefault(),r=re("newCategoryName")||"请输入新分类名称",k({show:true,title:r,defaultValue:t,onConfirm:async n=>{n&&n.trim()&&n!==t&&(await e.renameCategory(t,n.trim()),Oo((re("categoryRenamedTo")||"分类已重命名为「{name}」").replace("{name}",n.trim())),c===t&&d(n.trim()),W());}});},de=()=>{_.current&&_.current.classList.remove("dragging"),document.querySelectorAll(".drop-above, .drop-below").forEach(e=>{e.classList.remove("drop-above","drop-below");}),C(null),_.current=null;},ue=(()=>{let t;if(c===Vr){if(t=e.getPrompts().filter(e=>e.lastUsedAt).sort((e,t)=>(t.lastUsedAt||0)-(e.lastUsedAt||0)).slice(0,10),u){const e=u.toLowerCase();t=t.filter(t=>t.title.toLowerCase().includes(e)||t.content.toLowerCase().includes(e));}}else t=e.filterPrompts(u,c);return c!==Vr&&(t=t.sort((e,t)=>e.pinned&&!t.pinned?-1:!e.pinned&&t.pinned?1:0)),t})();M(()=>{if(!(x.show||v.show||b||g||R.show||I.show||A.show))return;const e=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation?.(),x.show?oe():v.show?ne():A.show?se():b?te():g?ee():R.show?ie():I.show&&ae());};return document.addEventListener("keydown",e,true),()=>{document.removeEventListener("keydown",e,true);}},[te,ne,ee,ae,ie,oe,se,v.show,I.show,b,g,R.show,x.show,A.show]),M(()=>{if(!j)return;const e=F.current;if(!e)return;const t="undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(j):j.replace(/["\\]/g,"\\$&"),n=e.querySelector(`.prompt-item[data-prompt-id="${t}"]`);n&&(n.scrollIntoView({behavior:"smooth",block:"center"}),null!==z.current&&window.clearTimeout(z.current),z.current=window.setTimeout(()=>{$(e=>e===j?null:e),z.current=null;},2200));},[j,i,u,c]); return ye("div",{className:"gh-prompts-tab",style:{display:"flex",flexDirection:"column",height:"100%"},children:[ ye("div",{style:{padding:"12px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",background:"var(--gh-bg-secondary, #f9fafb)",display:"flex",gap:"8px",alignItems:"center"},children:[ be("input",{type:"text",className:"prompt-search-input",placeholder:re("searchPlaceholder"),value:u,onChange:e=>h(e.target.value),style:{flex:1,padding:"8px 12px",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"8px",fontSize:"14px",boxSizing:"border-box",background:"var(--gh-bg, #ffffff)",color:"var(--gh-text, #1f2937)"}}), be(wu,{content:re("promptImport")||"导入",children:be("button",{onClick:()=>{const e=document.createElement("input");e.type="file",e.accept=".json",e.onchange=async e=>{const t=e.target.files?.[0];if(t)try{const e=await t.text(),n=JSON.parse(e);if(!Array.isArray(n))return void Oo(re("promptImportFailed")||"导入失败:文件格式错误");N({show:!0,prompts:n});}catch{Oo(re("promptImportFailed")||"导入失败:文件解析错误");}},e.click();},style:{width:"32px",height:"32px",border:"1px solid var(--gh-border, #d1d5db)",background:"var(--gh-bg, white)",borderRadius:"6px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"16px",flexShrink:0},children:be(De,{size:16})})}), be(wu,{content:re("promptExport")||"导出",children:be("button",{onClick:()=>{const t=e.getPrompts(),n=JSON.stringify(t,null,2),r=new Blob([n],{type:"application/json"}),o=URL.createObjectURL(r),i=document.createElement("a");i.href=o,i.download=`${Xm}-prompts-${(new Date).toISOString().split("T")[0]}.json`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(o),Oo(re("promptExportSuccess")||"导出成功");},style:{width:"32px",height:"32px",border:"1px solid var(--gh-border, #d1d5db)",background:"var(--gh-bg, white)",borderRadius:"6px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"16px",flexShrink:0},children:be(Re,{size:16})})})]}), ye("div",{style:{padding:"8px 12px",display:"flex",gap:"6px",flexWrap:"wrap",background:"var(--gh-bg, white)",borderBottom:"1px solid var(--gh-border, #e5e7eb)",userSelect:"none"},children:[ be("span",{onClick:()=>d(Wr),style:{padding:"4px 10px",background:c===Wr?"var(--gh-primary, #4285f4)":"var(--gh-hover, #f3f4f6)",borderRadius:"12px",fontSize:"12px",color:c===Wr?"white":"#4b5563",cursor:"pointer",border:c===Wr?"1px solid var(--gh-primary, #4285f4)":"1px solid transparent"},children:re("allCategory")}),s.map(e=>{const t=(e=>{let t=0;for(let n=0;nd(e),style:{padding:"4px 10px",background:c===e?"var(--gh-primary, #4285f4)":`var(--gh-category-${t})`,borderRadius:"12px",fontSize:"12px",color:c===e?"white":"#4b5563",cursor:"pointer",border:c===e?"1px solid var(--gh-primary, #4285f4)":"1px solid transparent",maxWidth:"80px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})},e)}), be(wu,{content:re("promptRecentUsed")||"最近使用",children:be("span",{onClick:()=>d(Vr),style:{padding:"4px 8px",display:"inline-flex",alignItems:"center",justifyContent:"center",lineHeight:1,background:c===Vr?"var(--gh-primary, #4285f4)":"var(--gh-hover, #f3f4f6)",borderRadius:"12px",fontSize:"12px",color:c===Vr?"white":"#4b5563",cursor:"pointer",border:c===Vr?"1px solid var(--gh-primary, #4285f4)":"1px solid transparent"},children:be(Ct,{size:14})})}),s.length>0&&be("button",{onClick:()=>y(true),style:{padding:"4px 8px",background:"transparent",border:"1px dashed var(--gh-border, #d1d5db)",borderRadius:"12px",fontSize:"11px",color:"var(--gh-text-secondary, #9ca3af)",cursor:"pointer"},children:re("manageCategory")||"管理"})]}), be("div",{ref:F,style:{flex:1,overflowY:"auto",padding:"8px",scrollbarWidth:"none"},children:0===ue.length?be("div",{style:{textAlign:"center",padding:"40px 20px",color:"var(--gh-text-tertiary, #9ca3af)",fontSize:"14px"},children:"暂无提示词"}):ue.map(t=>{const o=n===t.id,i=j===t.id,a=o||i; return ye("div",{"data-prompt-id":t.id,className:`prompt-item ${a?"selected":""} ${i?"located":""} ${S===t.id?"dragging":""}`,onClick:()=>{return e=t,$(null),void(r?(null!==O.current&&(window.clearTimeout(O.current),O.current=null),O.current=window.setTimeout(()=>{O.current=null,K(e);},340)):K(e));var e;},onDoubleClick:()=>{return e=t,null!==O.current&&(window.clearTimeout(O.current),O.current=null),void(r&&K(e,true));var e;},draggable:false,onDragStart:e=>((e,t,n)=>{C(t),_.current=n,e.dataTransfer.effectAllowed="move",n.classList.add("dragging");})(e,t.id,e.currentTarget),onDragOver:e=>((e,t)=>{if(e.preventDefault(),e.dataTransfer.dropEffect="move",!S||S===t)return;const n=e.currentTarget,r=n.getBoundingClientRect(),o=r.top+r.height/2;document.querySelectorAll(".drop-above, .drop-below").forEach(e=>{e.classList.remove("drop-above","drop-below");}),e.clientY(async(t,n)=>{if(t.preventDefault(),!S||S===n)return void de();const r=e.getPrompts(),o=r.findIndex(e=>e.id===S),i=r.findIndex(e=>e.id===n);if(-1===o||-1===i)return void de();const a=[...r],[s]=a.splice(o,1),l=t.currentTarget.getBoundingClientRect(),c=t.clientYe.id===n);oe.id)),Oo(re("orderUpdated")||"顺序已更新"),W(),de();})(n,t.id),style:{background:a?"linear-gradient(135deg, #e8f0fe 0%, #f1f8e9 100%)":"var(--gh-bg, white)",border:a?"1px solid var(--gh-primary, #4285f4)":"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",padding:"12px",marginBottom:"8px",cursor:"pointer",transition:"all 0.2s",position:"relative",userSelect:"none"},children:[ ye("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"8px"},children:[ be("div",{style:{fontWeight:600,fontSize:"14px",color:"var(--gh-text, #1f2937)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",paddingRight:"8px"},children:t.title}), be("span",{style:{fontSize:"11px",padding:"2px 6px",background:"var(--gh-hover, #f3f4f6)",borderRadius:"4px",color:"var(--gh-text-secondary, #6b7280)",flexShrink:0},children:t.category||re("uncategorized")||"未分类"})]}), be("div",{style:{fontSize:"13px",color:"var(--gh-text-secondary, #6b7280)",lineHeight:1.4,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:t.content}), ye("div",{className:"prompt-item-actions",style:{position:"absolute",top:"8px",right:"8px",gap:"4px"},children:[ be(wu,{content:t.pinned?re("promptUnpin")||"取消置顶":re("promptPin")||"置顶",children:be("button",{onClick:n=>((t,n)=>{n.stopPropagation(),n.preventDefault(),e.togglePin(t),W();})(t.id,n),style:{width:"24px",height:"24px",border:"1px solid var(--gh-border, #e5e7eb)",background:t.pinned?"var(--gh-primary, #4285f4)":"var(--gh-bg, white)",borderRadius:"4px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"var(--gh-shadow-sm, 0 1px 3px rgba(0,0,0,0.1))",fontSize:"12px",color:t.pinned?"white":"var(--gh-text-secondary, #6b7280)"},children:be(vt,{size:12,filled:t.pinned})})}), be(wu,{content:"拖动排序",children:be("button",{onMouseDown:e=>{e.stopPropagation();const t=e.currentTarget.closest(".prompt-item");t&&(t.draggable=true);},onMouseUp:e=>{const t=e.currentTarget.closest(".prompt-item");t&&(t.draggable=false);},style:{width:"24px",height:"24px",border:"1px solid var(--gh-border, #e5e7eb)",background:"var(--gh-bg, white)",borderRadius:"4px",cursor:"grab",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"var(--gh-shadow-sm, 0 1px 3px rgba(0,0,0,0.1))",fontSize:"12px"},children:be(Je,{size:14})})}), be(wu,{content:re("promptMarkdownPreview")||"预览",children:be("button",{onClick:e=>{e.stopPropagation(),e.preventDefault(),q({show:true,prompt:t});},style:{width:"24px",height:"24px",border:"1px solid var(--gh-border, #e5e7eb)",background:"var(--gh-bg, white)",borderRadius:"4px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"var(--gh-shadow-sm, 0 1px 3px rgba(0,0,0,0.1))",fontSize:"12px"},children:be(wt,{size:14})})}), be(wu,{content:re("copy"),children:be("button",{onClick:e=>(async(e,t)=>{t.stopPropagation(),t.preventDefault();try{await navigator.clipboard.writeText(e),Oo(re("copied")||"已复制");}catch{const t=document.createElement("textarea");t.value=e,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),Oo(re("copied")||"已复制");}})(t.content,e),style:{width:"24px",height:"24px",border:"1px solid var(--gh-border, #e5e7eb)",background:"var(--gh-bg, white)",borderRadius:"4px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"var(--gh-shadow-sm, 0 1px 3px rgba(0,0,0,0.1))",fontSize:"12px"},children:be(lt,{size:14})})}), be(wu,{content:re("edit"),children:be("button",{onClick:e=>{e.stopPropagation(),e.preventDefault(),le(t);},style:{width:"24px",height:"24px",border:"1px solid var(--gh-border, #e5e7eb)",background:"var(--gh-bg, white)",borderRadius:"4px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"var(--gh-shadow-sm, 0 1px 3px rgba(0,0,0,0.1))",fontSize:"12px"},children:be(bt,{size:14})})}), be(wu,{content:re("delete"),children:be("button",{onClick:n=>((t,n)=>{n.stopPropagation(),n.preventDefault(),Q(re("confirmDelete")||"确认删除","确定删除该提示词?",async()=>{await e.deletePrompt(t),Oo(re("deleted")||"已删除"),W();});})(t.id,n),style:{width:"24px",height:"24px",border:"1px solid var(--gh-border, #e5e7eb)",background:"var(--gh-bg, white)",borderRadius:"4px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"var(--gh-shadow-sm, 0 1px 3px rgba(0,0,0,0.1))",fontSize:"12px",color:"var(--gh-text-danger, #ef4444)"},children:be(yt,{size:14})})})]})]},t.id)})}), be("div",{style:{padding:"12px"},children:ye("button",{onClick:()=>le(),style:{width:"100%",padding:"10px",background:"var(--gh-header-bg)",color:"var(--gh-footer-text, var(--gh-text-on-primary, white))",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:500,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"6px",boxShadow:"var(--gh-btn-shadow)",transition:"transform 0.2s, box-shadow 0.2s"},onMouseEnter:e=>{e.currentTarget.style.transform="translateY(-1px)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow-hover)";},onMouseLeave:e=>{e.currentTarget.style.transform="translateY(0)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow)";},children:[ be("span",{children:"+"}), be("span",{children:re("addPrompt")})]})}),g?uu( be("div",{className:"prompt-modal gh-interactive",style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"var(--gh-overlay-bg)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:2147483646,animation:"fadeIn 0.2s"},children:ye("div",{className:"prompt-modal-content",onClick:e=>e.stopPropagation(),style:{background:"var(--gh-bg, white)",borderRadius:"12px",width:"90%",maxWidth:"500px",padding:"24px",animation:"slideUp 0.3s",boxShadow:"var(--gh-shadow, 0 20px 50px rgba(0,0,0,0.3))"},children:[ be("div",{style:{fontSize:"18px",fontWeight:600,marginBottom:"20px",color:"var(--gh-text, #1f2937)"},children:re(m?.id?"editPrompt":"addNewPrompt")}), ye("div",{style:{marginBottom:"16px"},children:[ be("label",{style:{display:"block",fontSize:"14px",fontWeight:500,color:"var(--gh-text, #374151)",marginBottom:"6px"},children:re("title")}), be("input",{type:"text",value:m?.title||"",onChange:e=>f({...m,title:e.target.value}),style:{width:"100%",padding:"8px 12px",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"6px",fontSize:"14px",boxSizing:"border-box",background:"var(--gh-bg, #ffffff)",color:"var(--gh-text, #1f2937)"}})]}), ye("div",{style:{marginBottom:"16px"},children:[ be("label",{style:{display:"block",fontSize:"14px",fontWeight:500,color:"var(--gh-text, #374151)",marginBottom:"6px"},children:re("category")}), be("input",{type:"text",value:m?.category||"",onChange:e=>f({...m,category:e.target.value}),placeholder:re("categoryPlaceholder")||"输入或选择分类",style:{width:"100%",padding:"8px 12px",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"6px",fontSize:"14px",boxSizing:"border-box",background:"var(--gh-bg, #ffffff)",color:"var(--gh-text, #1f2937)"}}),s.length>0&&be("div",{style:{marginTop:"6px",display:"flex",gap:"4px",flexWrap:"wrap",userSelect:"none"},children:s.map(e=>be("span",{onClick:()=>f({...m,category:e}),style:{padding:"2px 8px",fontSize:"11px",background:m?.category===e?"var(--gh-primary, #4285f4)":"var(--gh-hover, #f3f4f6)",color:m?.category===e?"var(--gh-text-on-primary, white)":"var(--gh-text-secondary, #6b7280)",borderRadius:"10px",cursor:"pointer",transition:"all 0.15s"},children:e},e))})]}), be("div",{style:{marginBottom:"16px"},children:ye("div",{children:[ ye("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"6px"},children:[ be("label",{style:{fontSize:"14px",fontWeight:500,color:"var(--gh-text, #374151)"},children:re("content")}), be("button",{onClick:()=>D(!L),style:{padding:"2px 8px",fontSize:"12px",background:L?"var(--gh-primary, #4285f4)":"var(--gh-hover, #f3f4f6)",color:L?"white":"var(--gh-text-secondary, #6b7280)",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"4px",cursor:"pointer"},children:re("promptMarkdownPreview")||"预览"})]}), be("textarea",{value:m?.content||"",onChange:e=>f({...m,content:e.target.value}),style:{width:"100%",minHeight:"120px",padding:"8px 12px",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"6px",fontSize:"14px",resize:"vertical",boxSizing:"border-box",fontFamily:"inherit",background:"var(--gh-bg, #ffffff)",color:"var(--gh-text, #1f2937)",display:L?"none":"block"}}),L&&ye(fe,{children:[ be("div",{className:"gh-markdown-preview",style:{width:"100%",minHeight:"120px",maxHeight:"200px",padding:"8px 12px",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"6px",fontSize:"14px",boxSizing:"border-box",background:"var(--gh-bg-secondary, #f9fafb)",color:"var(--gh-text, #1f2937)",overflowY:"auto",lineHeight:1.6},ref:H,onClick:e=>{const t=e.target.closest(".gh-code-copy-btn");if(t){const e=t.nextElementSibling?.textContent||"";navigator.clipboard.writeText(e).then(()=>{_u(t,{size:14});});}},dangerouslySetInnerHTML:{__html:Uu(wd(m?.content||""))}}), be("style",{children:"\n/* highlight.js GitHub Dark 主题 */\n.hljs {\n background: var(--gh-bg-tertiary, #1e1e1e);\n color: var(--gh-text, #e6edf3);\n padding: 12px;\n border-radius: 6px;\n overflow-x: auto;\n font-family: 'SF Mono', Consolas, 'Liberation Mono', Menlo, monospace;\n font-size: 13px;\n line-height: 1.5;\n /* 代码块自动换行 */\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n.hljs-comment,\n.hljs-quote { color: #8b949e; font-style: italic; }\n.hljs-keyword,\n.hljs-selector-tag { color: #ff7b72; }\n.hljs-string,\n.hljs-doctag { color: #a5d6ff; }\n.hljs-number,\n.hljs-literal { color: #79c0ff; }\n.hljs-title,\n.hljs-section,\n.hljs-selector-id { color: #d2a8ff; font-weight: bold; }\n.hljs-function > .hljs-title { color: #d2a8ff; }\n.hljs-type,\n.hljs-class .hljs-title { color: #7ee787; }\n.hljs-attribute { color: #79c0ff; }\n.hljs-variable,\n.hljs-template-variable { color: #ffa657; }\n.hljs-built_in { color: #ffa657; }\n.hljs-addition { color: #aff5b4; background: rgba(46, 160, 67, 0.15); }\n.hljs-deletion { color: #ffdcd7; background: rgba(248, 81, 73, 0.15); }\n\n/* 变量占位符高亮 */\n.gh-variable-highlight {\n background: rgba(56, 139, 253, 0.2);\n color: #58a6ff;\n padding: 2px 6px;\n border-radius: 4px;\n font-weight: 500;\n}\n\n/* Markdown 渲染样式 */\n.gh-markdown-preview {\n line-height: 1.6;\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview h1,\n.gh-markdown-preview h2,\n.gh-markdown-preview h3 {\n margin: 16px 0 8px;\n font-weight: 600;\n border-bottom: 1px solid var(--gh-border, #30363d);\n padding-bottom: 4px;\n}\n.gh-markdown-preview h1 { font-size: 1.5em; }\n.gh-markdown-preview h2 { font-size: 1.3em; }\n.gh-markdown-preview h3 { font-size: 1.1em; }\n.gh-markdown-preview p { margin: 8px 0; }\n.gh-markdown-preview code:not(.hljs) {\n background: var(--gh-bg-tertiary, #343942);\n padding: 2px 6px;\n border-radius: 4px;\n font-size: 13px;\n}\n.gh-markdown-preview pre {\n margin: 12px 0;\n position: relative;\n max-width: 100%;\n overflow: hidden;\n}\n.gh-markdown-preview pre code {\n display: block;\n max-width: 100%;\n overflow-x: auto;\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n/* 代码块复制按钮 */\n.gh-code-copy-btn {\n position: absolute;\n top: 8px;\n right: 8px;\n padding: 4px 8px;\n background: var(--gh-bg-secondary, #2d333b);\n border: 1px solid var(--gh-border, #444c56);\n border-radius: 4px;\n color: var(--gh-text-secondary, #8b949e);\n font-size: 12px;\n cursor: pointer;\n opacity: 0;\n transition: opacity 0.2s;\n}\n.gh-markdown-preview pre:hover .gh-code-copy-btn {\n opacity: 1;\n}\n.gh-code-copy-btn:hover {\n background: var(--gh-hover, #373e47);\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview blockquote {\n border-left: 3px solid var(--gh-primary, #4285f4);\n margin: 12px 0;\n padding: 8px 16px;\n background: var(--gh-bg-secondary, #161b22);\n color: var(--gh-text-secondary, #8b949e);\n}\n.gh-markdown-preview ul,\n.gh-markdown-preview ol {\n margin: 8px 0;\n padding-left: 24px;\n}\n.gh-markdown-preview li { margin: 4px 0; }\n.gh-markdown-preview a {\n color: var(--gh-primary, #58a6ff);\n text-decoration: none;\n}\n.gh-markdown-preview a:hover { text-decoration: underline; }\n\n/* 任务列表样式 */\n.gh-markdown-preview .task-list-item {\n list-style: none;\n margin-left: -20px;\n}\n.gh-markdown-preview .task-list-item input[type=\"checkbox\"] {\n margin-right: 8px;\n pointer-events: none;\n}\n\n/* 高亮 ==text== */\n.gh-markdown-preview mark {\n background: rgba(255, 235, 59, 0.4);\n color: inherit;\n padding: 2px 4px;\n border-radius: 3px;\n}\n\n/* 容器样式 :::info, :::warning, :::danger */\n.gh-container {\n margin: 12px 0;\n padding: 12px 16px;\n border-radius: 6px;\n border-left: 4px solid;\n}\n.gh-container-info {\n background: rgba(56, 139, 253, 0.1);\n border-color: #388bfd;\n}\n.gh-container-warning {\n background: rgba(255, 166, 87, 0.1);\n border-color: #ffa657;\n}\n.gh-container-danger {\n background: rgba(248, 81, 73, 0.1);\n border-color: #f85149;\n}\n"})]})]})}), ye("div",{style:{display:"flex",gap:"12px",justifyContent:"flex-end",marginTop:"24px"},children:[ be(cf,{variant:"ghost",onClick:ee,style:{background:"var(--gh-hover, #f3f4f6)"},children:re("cancel")}), be(cf,{variant:"primary",onClick:X,children:re(m?.id?"save":"add")})]})]})}),document.body):null,b?uu( be("div",{className:"prompt-modal gh-interactive",style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"var(--gh-overlay-bg)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:2147483646,animation:"fadeIn 0.2s"},children:ye("div",{onClick:e=>e.stopPropagation(),style:{background:"var(--gh-bg, white)",borderRadius:"12px",width:"90%",maxWidth:"400px",padding:"24px",animation:"slideUp 0.3s",boxShadow:"var(--gh-shadow-lg, 0 20px 50px rgba(0,0,0,0.3))"},children:[ be("div",{style:{fontSize:"18px",fontWeight:600,marginBottom:"20px",color:"var(--gh-text, #1f2937)"},children:re("categoryManage")||"分类管理"}), be("div",{style:{maxHeight:"300px",overflowY:"auto"},children:0===s.length?be("div",{style:{textAlign:"center",color:"var(--gh-text-tertiary, #9ca3af)",padding:"20px"},children:re("categoryEmpty")||"暂无分类"}):s.map(t=>{const n=i.filter(e=>e.category===t).length; return ye("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 0",borderBottom:"1px solid var(--gh-border, #e5e7eb)"},children:[ ye("div",{children:[ be("div",{style:{fontWeight:500,color:"var(--gh-text, #374151)"},children:t}), ye("div",{style:{fontSize:"12px",color:"var(--gh-text-tertiary, #9ca3af)"},children:[n," ",re("promptCountSuffix")||" 个提示词"]})]}), ye("div",{style:{display:"flex",gap:"8px"},children:[ be(wu,{content:re("rename")||"重命名",children:be(cf,{size:"sm",onClick:e=>ce(t,e),style:{color:"var(--gh-primary, #4285f4)"},children:re("rename")||"重命名"})}), be(wu,{content:re("delete")||"删除",children:be(cf,{size:"sm",onClick:n=>((t,n)=>{n.stopPropagation(),n.preventDefault(),Q(re("confirmDeleteCategory")||"确认删除分类",(re("confirmDeleteCategoryMsg")||"确定删除分类「{name}」?关联的提示词将移至「未分类」").replace("{name}",t),async()=>{await e.deleteCategory(t),Oo((re("categoryDeletedMsg")||"分类「{name}」已删除").replace("{name}",t)),c===t&&d(Wr),W();});})(t,n),style:{border:"1px solid var(--gh-border-danger, #fecaca)",background:"var(--gh-bg-danger, #fef2f2)",color:"var(--gh-text-danger, #ef4444)"},children:re("delete")||"删除"})})]})]},t)})}), be("div",{style:{marginTop:"20px",display:"flex",justifyContent:"flex-end"},children:be(cf,{variant:"ghost",onClick:te,style:{background:"var(--gh-hover, #f3f4f6)"},children:re("close")||"关闭"})})]})}),document.body):null,R.show&&R.prompt?uu( be("div",{className:"prompt-preview-modal gh-interactive",onClick:e=>{e.target===e.currentTarget&&ie();},style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"var(--gh-overlay-bg, rgba(0, 0, 0, 0.5))",display:"flex",alignItems:"center",justifyContent:"center",zIndex:10001,animation:"fadeIn 0.2s ease-out"},children:ye("div",{style:{width:"90%",maxWidth:"600px",maxHeight:"80vh",background:"var(--gh-bg, white)",borderRadius:"12px",boxShadow:"var(--gh-shadow-lg)",overflow:"hidden",display:"flex",flexDirection:"column",animation:"slideUp 0.3s ease-out"},children:[ ye("div",{style:{padding:"16px 20px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ ye("div",{children:[ be("div",{style:{fontSize:"16px",fontWeight:600,color:"var(--gh-text, #1f2937)"},children:R.prompt.title}), be("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)",marginTop:"4px"},children:R.prompt.category})]}), be("button",{onClick:ie,style:{width:"28px",height:"28px",border:"none",background:"var(--gh-hover, #f3f4f6)",borderRadius:"6px",cursor:"pointer",fontSize:"16px",display:"flex",alignItems:"center",justifyContent:"center"},children:be(ke,{size:16})})]}), be("div",{className:"gh-markdown-preview",style:{flex:1,padding:"20px",overflowY:"auto"},ref:U,onClick:e=>{const t=e.target.closest(".gh-code-copy-btn");if(t){const e=t.nextElementSibling?.textContent||"";navigator.clipboard.writeText(e).then(()=>{_u(t,{size:14});});}},dangerouslySetInnerHTML:{__html:Uu(wd(R.prompt.content))}}), be("style",{children:"\n/* highlight.js GitHub Dark 主题 */\n.hljs {\n background: var(--gh-bg-tertiary, #1e1e1e);\n color: var(--gh-text, #e6edf3);\n padding: 12px;\n border-radius: 6px;\n overflow-x: auto;\n font-family: 'SF Mono', Consolas, 'Liberation Mono', Menlo, monospace;\n font-size: 13px;\n line-height: 1.5;\n /* 代码块自动换行 */\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n.hljs-comment,\n.hljs-quote { color: #8b949e; font-style: italic; }\n.hljs-keyword,\n.hljs-selector-tag { color: #ff7b72; }\n.hljs-string,\n.hljs-doctag { color: #a5d6ff; }\n.hljs-number,\n.hljs-literal { color: #79c0ff; }\n.hljs-title,\n.hljs-section,\n.hljs-selector-id { color: #d2a8ff; font-weight: bold; }\n.hljs-function > .hljs-title { color: #d2a8ff; }\n.hljs-type,\n.hljs-class .hljs-title { color: #7ee787; }\n.hljs-attribute { color: #79c0ff; }\n.hljs-variable,\n.hljs-template-variable { color: #ffa657; }\n.hljs-built_in { color: #ffa657; }\n.hljs-addition { color: #aff5b4; background: rgba(46, 160, 67, 0.15); }\n.hljs-deletion { color: #ffdcd7; background: rgba(248, 81, 73, 0.15); }\n\n/* 变量占位符高亮 */\n.gh-variable-highlight {\n background: rgba(56, 139, 253, 0.2);\n color: #58a6ff;\n padding: 2px 6px;\n border-radius: 4px;\n font-weight: 500;\n}\n\n/* Markdown 渲染样式 */\n.gh-markdown-preview {\n line-height: 1.6;\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview h1,\n.gh-markdown-preview h2,\n.gh-markdown-preview h3 {\n margin: 16px 0 8px;\n font-weight: 600;\n border-bottom: 1px solid var(--gh-border, #30363d);\n padding-bottom: 4px;\n}\n.gh-markdown-preview h1 { font-size: 1.5em; }\n.gh-markdown-preview h2 { font-size: 1.3em; }\n.gh-markdown-preview h3 { font-size: 1.1em; }\n.gh-markdown-preview p { margin: 8px 0; }\n.gh-markdown-preview code:not(.hljs) {\n background: var(--gh-bg-tertiary, #343942);\n padding: 2px 6px;\n border-radius: 4px;\n font-size: 13px;\n}\n.gh-markdown-preview pre {\n margin: 12px 0;\n position: relative;\n max-width: 100%;\n overflow: hidden;\n}\n.gh-markdown-preview pre code {\n display: block;\n max-width: 100%;\n overflow-x: auto;\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n/* 代码块复制按钮 */\n.gh-code-copy-btn {\n position: absolute;\n top: 8px;\n right: 8px;\n padding: 4px 8px;\n background: var(--gh-bg-secondary, #2d333b);\n border: 1px solid var(--gh-border, #444c56);\n border-radius: 4px;\n color: var(--gh-text-secondary, #8b949e);\n font-size: 12px;\n cursor: pointer;\n opacity: 0;\n transition: opacity 0.2s;\n}\n.gh-markdown-preview pre:hover .gh-code-copy-btn {\n opacity: 1;\n}\n.gh-code-copy-btn:hover {\n background: var(--gh-hover, #373e47);\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview blockquote {\n border-left: 3px solid var(--gh-primary, #4285f4);\n margin: 12px 0;\n padding: 8px 16px;\n background: var(--gh-bg-secondary, #161b22);\n color: var(--gh-text-secondary, #8b949e);\n}\n.gh-markdown-preview ul,\n.gh-markdown-preview ol {\n margin: 8px 0;\n padding-left: 24px;\n}\n.gh-markdown-preview li { margin: 4px 0; }\n.gh-markdown-preview a {\n color: var(--gh-primary, #58a6ff);\n text-decoration: none;\n}\n.gh-markdown-preview a:hover { text-decoration: underline; }\n\n/* 任务列表样式 */\n.gh-markdown-preview .task-list-item {\n list-style: none;\n margin-left: -20px;\n}\n.gh-markdown-preview .task-list-item input[type=\"checkbox\"] {\n margin-right: 8px;\n pointer-events: none;\n}\n\n/* 高亮 ==text== */\n.gh-markdown-preview mark {\n background: rgba(255, 235, 59, 0.4);\n color: inherit;\n padding: 2px 4px;\n border-radius: 3px;\n}\n\n/* 容器样式 :::info, :::warning, :::danger */\n.gh-container {\n margin: 12px 0;\n padding: 12px 16px;\n border-radius: 6px;\n border-left: 4px solid;\n}\n.gh-container-info {\n background: rgba(56, 139, 253, 0.1);\n border-color: #388bfd;\n}\n.gh-container-warning {\n background: rgba(255, 166, 87, 0.1);\n border-color: #ffa657;\n}\n.gh-container-danger {\n background: rgba(248, 81, 73, 0.1);\n border-color: #f85149;\n}\n"})]})}),document.body):null,I.show?uu( be("div",{className:"import-dialog gh-interactive",onClick:e=>{e.target===e.currentTarget&&ae();},style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"var(--gh-overlay-bg, rgba(0, 0, 0, 0.5))",display:"flex",alignItems:"center",justifyContent:"center",zIndex:10001},children:ye("div",{style:{width:"90%",maxWidth:"400px",background:"var(--gh-bg, white)",borderRadius:"12px",boxShadow:"var(--gh-shadow-lg)",padding:"24px"},children:[ be("div",{style:{fontSize:"16px",fontWeight:600,marginBottom:"12px",color:"var(--gh-text)"},children:re("promptImportTitle")||"导入提示词"}), ye("div",{style:{fontSize:"14px",color:"var(--gh-text-secondary)",marginBottom:"20px",lineHeight:1.6},children:[(re("promptImportMessage2")||"发现 {count} 个提示词,请选择导入方式:").replace("{count}",I.prompts.length.toString()), ye("ul",{style:{margin:"8px 0 0 0",paddingLeft:"20px"},children:[ be("li",{children:re("promptImportOverwriteDesc")||"覆盖:清空现有,使用导入的"}), be("li",{children:re("promptImportMergeDesc")||"合并:相同ID更新,新ID追加"})]})]}), ye("div",{style:{display:"flex",gap:"12px",justifyContent:"flex-end"},children:[ be(cf,{variant:"ghost",onClick:ae,style:{background:"var(--gh-hover, #f3f4f6)"},children:re("cancel")||"取消"}), be(cf,{variant:"ghost",onClick:J,style:{background:"var(--gh-primary-light, #e3f2fd)",color:"var(--gh-primary, #4285f4)"},children:re("promptMerge")||"合并"}), be(cf,{variant:"primary",onClick:Y,children:re("promptOverwrite")||"覆盖"})]})]})}),document.body):null,v.show&&be(sf,{title:v.title,message:v.message,danger:true,closeOnOverlayClick:false,onConfirm:()=>{ne(),v.onConfirm();},onCancel:ne}),x.show&&be(lf,{title:x.title,defaultValue:x.defaultValue,closeOnOverlayClick:false,onConfirm:e=>{oe(),x.onConfirm(e);},onCancel:oe}),A.show&&be(Pf,{variables:A.variables,onConfirm:async e=>{const{prompt:t,submitAfterInsert:n}=A;if(!t)return;const r=((e,t)=>e.replace(/\{\{([^\s{}]+)\}\}/g,(e,n)=>n in t?t[n]:e))(t.content,e);T({show:false,prompt:null,variables:[],submitAfterInsert:false}),await new Promise(e=>{window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>e());});}),await Z(t,r,n);},onCancel:se}), be("style",{children:"\n @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }\n @keyframes slideUp { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }\n "})]})},Ff=({onClose:e,isOpen:t,promptManager:n,conversationManager:r,outlineManager:o,adapter:i,onThemeToggle:a,themeMode:s,selectedPromptId:l,onPromptSelect:c,edgeSnapState:d,isEdgePeeking:u=false,onEdgeSnap:h,onUnsnap:g,onInteractionStateChange:p,onOpenSettings:m,onMouseEnter:f,onMouseLeave:b})=>{const y=E(e=>{const t=e.getBoundingClientRect();return {clientX:t.left+t.width/2,clientY:t.top+t.height/2}},[]),{settings:v}=No(),w=v||bo,x=w.features?.order||bo.features.order,k=i?.getSiteId()||"_default",S=yo(w,k),C="light"===(s||("dark"===S.mode?"dark":"light"))?S.lightStyleId||"google-gradient":S.darkStyleId||"classic-dark",_="google-gradient"===C?"currentColor":"brand",A=Array.isArray(w.theme?.customStyles)?w.theme.customStyles.find(e=>e.id===C):null,{panelRef:T,headerRef:I}=function(e={}){const{edgeSnapHide:t=false,edgeSnapState:n,snapThreshold:r=30,onEdgeSnap:o,onUnsnap:i}=e,a=P(null),s=P(null),l=P(false),c=P(false),d=P({x:0,y:0}),u=E(e=>{if(e.target.closest(".gh-panel-controls"))return;const t=a.current;if(!t)return;e.preventDefault(),n&&i?.();const r=t.getBoundingClientRect();d.current={x:e.clientX-r.left,y:e.clientY-r.top},t.style.left=r.left+"px",t.style.top=r.top+"px",t.style.right="auto",t.style.transform="none",c.current=false,l.current=true,t.classList.add("dragging"),document.body.style.userSelect="none";},[n,i]),h=E(e=>{if(!l.current)return;const t=a.current;t&&(e.preventDefault(),c.current=true,t.style.left=e.clientX-d.current.x+"px",t.style.top=e.clientY-d.current.y+"px");},[]),g=E(()=>{if(!l.current)return;const e=a.current,n=c.current;if(l.current=false,document.body.style.userSelect="",e?.classList.remove("dragging"),t&&n&&e){const t=e.getBoundingClientRect();t.left{const e=a.current;if(!e)return;if(n)return;const t=e.getBoundingClientRect(),r=window.innerWidth,o=window.innerHeight;let i=t.left,s=t.top;t.right>r&&(i=r-t.width-10),t.bottom>o&&(s=o-t.height-10),t.left<0&&(i=10),t.top<0&&(s=10),i===t.left&&s===t.top||(e.style.left=i+"px",e.style.top=s+"px",e.style.right="auto",e.style.transform="none");},[n]);return M(()=>{const e=s.current;if(e)return e.addEventListener("mousedown",u),document.addEventListener("mousemove",h),document.addEventListener("mouseup",g),window.addEventListener("resize",p),()=>{e.removeEventListener("mousedown",u),document.removeEventListener("mousemove",h),document.removeEventListener("mouseup",g),window.removeEventListener("resize",p);}},[u,h,g,p]),{panelRef:a,headerRef:s}}({edgeSnapHide:w.panel?.edgeSnap,edgeSnapState:d,snapThreshold:w.panel?.edgeSnapThreshold??30,onEdgeSnap:h,onUnsnap:g}),N=w.panel?.defaultPosition??"right",L=w.panel?.defaultEdgeDistance??40,D=e=>e&&e.length>0?e[0]:In,[R,q]=B(In),[z,F]=B(false);M(()=>{v&&!z&&(q(D(v.features?.order)),F(true));},[v,z]),M(()=>{z&&x&&x.length>0&&(x.includes(R)||q(D(x)));},[x,z,R]),M(()=>{const e=()=>{q(Nn);},t=()=>{q(Ln);},n=e=>{const t=e.detail?.index;"number"==typeof t&&x[t]&&q(x[t]);};return window.addEventListener("ophel:locateOutline",e),window.addEventListener("ophel:searchOutline",e),window.addEventListener("ophel:locateConversation",t),window.addEventListener("ophel:switchTab",n),()=>{window.removeEventListener("ophel:locateOutline",e),window.removeEventListener("ophel:searchOutline",e),window.removeEventListener("ophel:locateConversation",t),window.removeEventListener("ophel:switchTab",n);}},[x]),M(()=>{if(!t)return;const e=T.current;return e?Zo(e):void 0},[t,T]);const j=null!==O(qm,Pm),[$,H]=B(false),[U,W]=B(""),V=P(false),G=E(async()=>{V.current=false;const e=new AbortController,t=setInterval(()=>{V.current&&e.abort();},100);let n=setTimeout(()=>{V.current||(H(true),W(re("loadingHistory")));},1600);try{const t=await Km({adapter:i||null,loadAll:!0,signal:e.signal,allowShortCircuit:!0,onProgress:e=>{W(`${re("loadingHistory")} ${e}`);}});Rm(t.previousScrollTop),n&&(clearTimeout(n),n=null),H(!1),W(""),t.success&&!t.silent&&Oo(re("historyLoaded"),2e3);}finally{clearInterval(t),n&&clearTimeout(n);}},[i]),Q=E(()=>{V.current=true;},[]),K=E(async()=>{const{previousScrollTop:e}=await Fm(i||null);Rm(e);},[i]),Z=E(async()=>{const e=Dm();if(null===e)return;const t=(await $m(i||null)).scrollTop;await jm(i||null,e),Rm(t);},[i]),Y=E(async()=>{const e=await $m(i||null);Rm(e.scrollTop);},[i]);if(!t)return null;const J=x.filter(e=>e!==Dn&&((e!==In||false!==w.features?.prompts?.enabled)&&((e!==Ln||false!==w.features?.conversations?.enabled)&&(e!==Nn||false!==w.features?.outline?.enabled)))); return ye(fe,{children:[ be(kf,{isVisible:$,text:U,onStop:Q}), ye("div",{ref:T,onMouseEnter:f,onMouseLeave:b,className:`gh-main-panel gh-interactive ${d?`edge-snapped-${d}`:""} ${u?"edge-peek":""}`,style:{position:"fixed",top:"50%",..."left"===N?{left:`${L}px`,right:"auto"}:{right:`${L}px`,left:"auto"},transform:"translateY(-50%)",width:`${w.panel?.width??320}px`,height:`${w.panel?.height??85}vh`, // @ts-ignore - 注入 CSS 变量供吸附计算使用 "--panel-width":`${w.panel?.width??320}px`,minHeight:"500px",backgroundColor:"var(--gh-bg, #ffffff)",backgroundImage:"var(--gh-bg-image, none)",backgroundBlendMode:"overlay",animation:"var(--gh-bg-animation, none)",borderRadius:"12px",boxShadow:"var(--gh-shadow, 0 10px 40px rgba(0,0,0,0.15))",display:"flex",flexDirection:"column",overflow:"hidden",border:"1px solid var(--gh-border, #e5e7eb)",zIndex:9999,fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'},children:[A?be("style",{children:A.css}):null, ye("div",{ref:I,className:"gh-panel-header",style:{padding:"12px 14px",borderRadius:"12px 12px 0 0",display:"flex",alignItems:"center",justifyContent:"space-between",userSelect:"none"},children:[ be(wu,{content:re("aboutPageDesc"),children:ye("div",{style:{display:"flex",alignItems:"center",gap:"6px",cursor:"pointer"},onDoubleClick:()=>{window.postMessage({type:"GH_PRIVACY_TOGGLE"},"*");},children:[ be(Et,{size:18,color:_}), be("span",{style:{fontSize:"15px",fontWeight:600},children:re("panelTitle")})]})}), ye("div",{className:"gh-panel-controls",style:{display:"flex",gap:"4px",alignItems:"center"},children:[a&&be(wu,{content:re("toggleTheme"),children:be("button",{onClick:e=>{a?.(y(e.currentTarget));},style:{background:"var(--gh-glass-bg, rgba(255,255,255,0.2))",border:"none",color:"var(--gh-glass-text, white)",width:"24px",height:"24px",borderRadius:"6px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"14px",transition:"all 0.2s"},children:be("dark"===s?ve:we,{size:14})})}), be(wu,{content:re("newTabTooltip")||"新标签页打开",children:be("button",{onClick:()=>window.open(window.location.origin,"_blank"),style:{background:"var(--gh-glass-bg, rgba(255,255,255,0.2))",border:"none",color:"var(--gh-glass-text, white)",width:"24px",height:"24px",borderRadius:"6px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"16px",transition:"all 0.2s"},children:be(Ee,{size:14})})}), be(wu,{content:re("tabSettings"),children:be("button",{onClick:()=>{m?.();},style:{background:"var(--gh-glass-bg, rgba(255,255,255,0.2))",border:"none",color:"var(--gh-glass-text, white)",width:"24px",height:"24px",borderRadius:"6px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"14px",transition:"all 0.2s"},children:be(_e,{size:14})})}), be(wu,{content:re(R===Nn?"refreshOutline":R===In?"refreshPrompts":R===Ln?"refreshConversations":"refresh"),children:be("button",{onClick:()=>{R===Nn?o?.refresh():R===In?n?.init():R===Ln&&r?.notifyDataChange();},style:{background:"var(--gh-glass-bg, rgba(255,255,255,0.2))",border:"none",color:"var(--gh-glass-text, white)",width:"24px",height:"24px",borderRadius:"6px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"14px",transition:"all 0.2s"},children:be(Ae,{size:14})})}), be(wu,{content:re("collapse"),children:be("button",{onClick:e,style:{background:"var(--gh-glass-bg, rgba(255,255,255,0.2))",border:"none",color:"var(--gh-glass-text, white)",width:"24px",height:"24px",borderRadius:"6px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"18px",fontWeight:600,transition:"all 0.2s"},children:be(Te,{size:14})})})]})]}), be("div",{className:"gh-panel-tabs",style:{display:"flex",borderBottom:"1px solid var(--gh-border, #e5e7eb)",padding:"0",background:"var(--gh-bg-secondary, #f9fafb)"},children:J.map(e=>{let t=null;return e===Nn?t=Me:e===In?t=Ie:e===Ln&&(t=Le),ye("button",{onClick:()=>q(e),style:{flex:1,padding:"10px 8px",border:"none",background:"transparent",borderBottom:R===e?"3px solid var(--gh-primary, #4285f4)":"3px solid transparent",color:R===e?"var(--gh-primary, #4285f4)":"var(--gh-text-secondary, #6b7280)",fontWeight:R===e?600:400,cursor:"pointer",fontSize:"13px",whiteSpace:"nowrap",display:"flex",alignItems:"center",justifyContent:"center",gap:"4px",transition:"all 0.2s"},children:[ be("span",{style:{display:"flex",alignItems:"center"},children:t&&be(t,{size:16})}), be("span",{children:re(`tab${e.charAt(0).toUpperCase()+e.slice(1)}`)})]},e)})}), ye("div",{className:"gh-panel-content",style:{flex:1,overflowY:"auto",padding:"0",scrollbarWidth:"none",msOverflowStyle:"none"},children:[R===In&&be(zf,{manager:n,selectedPromptId:l,onPromptSelect:c}),R===Ln&&be(Nf,{manager:r,onInteractionStateChange:p}),R===Nn&&be(qf,{manager:o,onJumpBefore:Y})]}), ye("div",{className:"gh-panel-footer",style:{display:"flex",justifyContent:"space-around",alignItems:"center",padding:"10px 16px",borderTop:"1px solid var(--gh-border, #e5e7eb)",background:"var(--gh-bg-secondary, #f9fafb)"},children:[ be(wu,{content:re("scrollTop"),triggerStyle:{flex:1,maxWidth:"120px"},children:ye("button",{className:"gh-interactive scroll-nav-btn",onClick:G,style:{width:"100%",height:"32px",display:"flex",alignItems:"center",justifyContent:"center",gap:"4px",background:"var(--gh-header-bg)",color:"var(--gh-footer-text, var(--gh-text-on-primary, white))",border:"none",borderRadius:"8px",cursor:"pointer",fontSize:"14px",transition:"transform 0.2s, box-shadow 0.2s",boxShadow:"var(--gh-btn-shadow)"},onMouseEnter:e=>{e.currentTarget.style.transform="translateY(-1px)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow-hover)";},onMouseLeave:e=>{e.currentTarget.style.transform="translateY(0)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow)";},children:[ be(Oe,{size:14}), be("span",{children:re("scrollTop")})]})}), be(wu,{content:j?re("jumpToAnchor"):"暂无锚点",triggerStyle:{flex:"0 0 32px"},children:be("button",{className:"gh-interactive scroll-nav-btn anchor-btn",onClick:Z,disabled:!j,style:{width:"32px",height:"32px",background:"var(--gh-header-bg)",color:"var(--gh-footer-text, var(--gh-text-on-primary, white))",border:"none",borderRadius:"50%",padding:0,cursor:j?"pointer":"default",fontSize:"14px",display:"flex",alignItems:"center",justifyContent:"center",transition:"transform 0.2s, box-shadow 0.2s",boxShadow:"var(--gh-btn-shadow)",opacity:j?1:.4},onMouseEnter:e=>{if(j){e.currentTarget.style.transform="scale(1.1)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow-hover)";const t=e.currentTarget.querySelector("div");t&&(t.style.transform="rotate(360deg)");}},onMouseLeave:e=>{e.currentTarget.style.transform="scale(1)",e.currentTarget.style.boxShadow=j?"var(--gh-btn-shadow)":"none";const t=e.currentTarget.querySelector("div");t&&(t.style.transform="rotate(0deg)");},children:be("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",transition:"transform 0.5s cubic-bezier(0.34, 1.56, 0.64, 1)"},children:be(Se,{size:14})})})}), be(wu,{content:re("scrollBottom"),triggerStyle:{flex:1,maxWidth:"120px"},children:ye("button",{className:"gh-interactive scroll-nav-btn",onClick:K,style:{width:"100%",height:"32px",display:"flex",alignItems:"center",justifyContent:"center",gap:"4px",background:"var(--gh-header-bg)",color:"var(--gh-footer-text, var(--gh-text-on-primary, white))",border:"none",borderRadius:"8px",cursor:"pointer",fontSize:"14px",transition:"transform 0.2s, box-shadow 0.2s",boxShadow:"var(--gh-btn-shadow)"},onMouseEnter:e=>{e.currentTarget.style.transform="translateY(-1px)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow-hover)";},onMouseLeave:e=>{e.currentTarget.style.transform="translateY(0)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow)";},children:[ be(ze,{size:14}), be("span",{children:re("scrollBottom")})]})})]})]})]})};e(".gh-queue-capsule{position:fixed;z-index:99998;display:flex;align-items:center;gap:6px;padding:6px 14px;border-radius:20px;background:var(--gh-bg, #ffffff);border:1px solid var(--gh-border, #e5e7eb);color:var(--gh-text, #1f2937);font-size:13px;font-weight:500;cursor:pointer;-webkit-user-select:none;user-select:none;box-shadow:0 2px 12px #00000014;transition:all .2s ease;font-family:var(--gh-font-family, system-ui, -apple-system, sans-serif)}.gh-queue-capsule:hover{transform:translateY(-1px);background:var(--gh-bg-secondary, #f9fafb);box-shadow:0 4px 16px #0000001f}.gh-queue-capsule-icon{font-size:14px;line-height:1}.gh-queue-capsule-badge{display:inline-flex;align-items:center;justify-content:center;min-width:18px;height:18px;padding:0 5px;border-radius:9px;background:var(--gh-bg-accent, #eef2ff);color:var(--gh-accent, #4285f4);font-size:11px;font-weight:600}.gh-queue-panel{position:fixed;z-index:99999;width:420px;max-width:calc(100vw - 40px);max-height:400px;border-radius:16px;background:var(--gh-bg, #ffffff);border:1px solid var(--gh-border, #e5e7eb);box-shadow:0 8px 32px #0000001f,0 2px 8px #0000000f;display:flex;flex-direction:column;overflow:hidden;font-family:var(--gh-font-family, system-ui, -apple-system, sans-serif)}.gh-queue-header{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid var(--gh-border-light, #f3f4f6)}.gh-queue-header-title{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:600;color:var(--gh-text, #1f2937)}.gh-queue-header-actions{display:flex;align-items:center;gap:4px}.gh-queue-header-btn{display:flex;align-items:center;justify-content:center;width:28px;height:28px;border:none;border-radius:6px;background:transparent;color:var(--gh-text-secondary, #6b7280);cursor:pointer;font-size:16px;transition:all .15s}.gh-queue-header-btn:hover{background:var(--gh-bg-tertiary, #f3f4f6);color:var(--gh-text, #1f2937)}.gh-queue-list{flex:1;overflow-y:auto;padding:8px;max-height:180px}.gh-queue-empty{display:flex;align-items:center;justify-content:center;padding:16px;color:var(--gh-text-tertiary, #9ca3af);font-size:13px}.gh-queue-item{display:flex;align-items:flex-start;gap:8px;padding:8px 10px;border-radius:8px;margin-bottom:4px;background:var(--gh-bg-secondary, #f9fafb);transition:background .15s}.gh-queue-item:hover{background:var(--gh-bg-tertiary, #f3f4f6)}.gh-queue-item-index{flex-shrink:0;width:20px;height:20px;display:flex;align-items:center;justify-content:center;border-radius:50%;background:var(--gh-accent, #4285f4);color:#fff;font-size:11px;font-weight:600;margin-top:1px}.gh-queue-item-content{flex:1;min-width:0;font-size:13px;line-height:1.5;color:var(--gh-text, #1f2937);word-break:break-word;display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.gh-queue-item-actions{flex-shrink:0;display:flex;align-items:center;gap:4px;opacity:0;transition:opacity .15s}.gh-queue-item:hover .gh-queue-item-actions{opacity:1}.gh-queue-item-remove,.gh-queue-item-force-send,.gh-queue-item-edit{display:flex;align-items:center;justify-content:center;width:22px;height:22px;border:none;border-radius:4px;background:transparent;color:var(--gh-text-tertiary, #9ca3af);cursor:pointer;transition:all .15s}.gh-queue-item-remove:hover{background:var(--gh-bg-danger, #fef2f2);color:var(--gh-text-danger, #dc2626)}.gh-queue-item-force-send:hover,.gh-queue-item-edit:hover{background:var(--gh-bg-accent, #eef2ff);color:var(--gh-accent, #4285f4)}.gh-queue-item-edit-area{flex:1;min-width:0;display:flex;flex-direction:column;gap:6px}.gh-queue-item-edit-input{width:100%;padding:6px 8px;border:1px solid var(--gh-accent, #4285f4);border-radius:6px;background:var(--gh-bg, #ffffff);color:var(--gh-text, #1f2937);font-size:13px;line-height:1.5;resize:vertical;min-height:48px;max-height:120px;outline:none;font-family:inherit}.gh-queue-item-edit-actions-row{display:flex;align-items:center;justify-content:flex-end;gap:4px}.gh-queue-item-edit-btn-save,.gh-queue-item-edit-btn-cancel{display:flex;align-items:center;justify-content:center;width:24px;height:24px;border:none;border-radius:4px;background:transparent;cursor:pointer;transition:all .15s}.gh-queue-item-edit-btn-save{color:var(--gh-accent, #4285f4)}.gh-queue-item-edit-btn-save:hover{background:var(--gh-bg-accent, #eef2ff)}.gh-queue-item-edit-btn-cancel{color:var(--gh-text-tertiary, #9ca3af)}.gh-queue-item-edit-btn-cancel:hover{background:var(--gh-bg-tertiary, #f3f4f6);color:var(--gh-text, #1f2937)}.gh-queue-item[data-status=sending]{border-left:3px solid var(--gh-accent, #4285f4)}.gh-queue-item[data-status=sent]{opacity:.5}.gh-queue-item[data-status=failed]{border-left:3px solid var(--gh-text-danger, #dc2626)}.gh-queue-input-area{padding:12px;border-top:1px solid var(--gh-border-light, #f3f4f6)}.gh-queue-input-wrapper{display:flex;align-items:flex-end;gap:8px}.gh-queue-input{flex:1;min-height:36px;max-height:120px;padding:8px 12px;border:1.5px solid var(--gh-border, #e5e7eb);border-radius:10px;background:var(--gh-bg, #ffffff);color:var(--gh-text, #1f2937);font-size:13px;line-height:1.5;resize:none;outline:none;font-family:inherit;transition:border-color .15s}.gh-queue-input:focus{border-color:var(--gh-accent, #4285f4)}.gh-queue-input::placeholder{color:var(--gh-text-tertiary, #9ca3af)}.gh-queue-send-btn{flex-shrink:0;display:flex;align-items:center;justify-content:center;width:36px;height:36px;border:none;border-radius:10px;background:var(--gh-accent, #4285f4);color:#fff;cursor:pointer;font-size:16px;transition:all .15s}.gh-queue-send-btn:hover{background:var(--gh-accent-hover, #3b78e7)}.gh-queue-send-btn:disabled{opacity:.5;cursor:not-allowed}.gh-queue-status{display:flex;align-items:center;gap:6px;padding:6px 12px;font-size:11px;color:var(--gh-text-tertiary, #9ca3af)}.gh-queue-disable-hint{margin-left:4px;opacity:.6;font-size:10px;cursor:help}.gh-queue-status-dot{width:6px;height:6px;border-radius:50%;background:#22c55e}.gh-queue-status-dot[data-generating=true]{background:#f59e0b;animation:gh-queue-pulse 1.5s infinite}@keyframes gh-queue-pulse{0%,to{opacity:1}50%{opacity:.4}}.gh-queue-shortcut-hint{margin-left:auto;font-size:10px;color:var(--gh-text-tertiary, #9ca3af);opacity:.6}.gh-queue-batch-dialog{max-width:560px}.gh-queue-batch-section{margin-bottom:16px}.gh-queue-batch-label{margin-bottom:8px;font-size:13px;font-weight:600;color:var(--gh-text, #1f2937)}.gh-queue-batch-mode-group{display:flex;gap:8px;flex-wrap:wrap}.gh-queue-batch-mode-btn{padding:8px 12px;border:1px solid var(--gh-border, #d1d5db);border-radius:8px;background:var(--gh-bg, #ffffff);color:var(--gh-text-secondary, #6b7280);cursor:pointer;font-size:13px;transition:all .15s ease}.gh-queue-batch-mode-btn:hover{border-color:var(--gh-accent, #4285f4);color:var(--gh-text, #1f2937)}.gh-queue-batch-mode-btn[data-active=true]{border-color:var(--gh-accent, #4285f4);background:var(--gh-bg-accent, #eef2ff);color:var(--gh-accent, #4285f4)}.gh-queue-batch-delimiter-input{margin-bottom:0}.gh-queue-batch-textarea{width:100%;min-height:160px;max-height:300px;padding:10px 12px;border:1px solid var(--gh-border, #d1d5db);border-radius:10px;background:var(--gh-bg, #ffffff);color:var(--gh-text, #1f2937);font-size:13px;line-height:1.55;resize:vertical;box-sizing:border-box;outline:none;font-family:inherit}.gh-queue-batch-textarea:focus{border-color:var(--gh-accent, #4285f4)}.gh-queue-batch-preview{margin-bottom:20px;padding:12px;border:1px solid var(--gh-border-light, #e5e7eb);border-radius:10px;background:var(--gh-bg-secondary, #f9fafb);display:flex;flex-direction:column}.gh-queue-batch-preview-header{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:10px;font-size:12px;color:var(--gh-text-secondary, #6b7280)}.gh-queue-batch-preview-body{max-height:220px;overflow-y:auto;min-height:0}.gh-queue-batch-preview-list{margin:0;padding-left:18px;display:flex;flex-direction:column;gap:6px}.gh-queue-batch-preview-item{color:var(--gh-text, #1f2937);font-size:13px;line-height:1.5;white-space:pre-wrap;word-break:break-word}.gh-queue-batch-preview-empty,.gh-queue-batch-preview-more{font-size:12px;color:var(--gh-text-tertiary, #9ca3af)}");const jf=e=>e.replace(/\r\n?/g,"\n"),$f=({adapter:e,dispatcher:t})=>{const[n,r]=B(false),[i,a]=B(false),[s,l]=B(""),[c,d]=B(false),[u,h]=B(""),[g,p]=B("line"),[m,f]=B(""),[b,y]=B(null),[v,w]=B(""),[x,k]=B(null),S=wm(e=>e.items),C=wm(),_=P(null),A=P(null),T=P(null),I=S.filter(e=>"pending"===e.status).length,N=S.filter(e=>"pending"===e.status||"sending"===e.status).length,L=S.filter(e=>"pending"===e.status||"sending"===e.status).length,D=No(e=>e.settings.features?.prompts?.submitShortcut??"enter"),R=No(e=>e.settings?.shortcuts),q=R?.keybindings?.togglePromptQueue,O=o.useMemo(()=>{if(null===q)return "";const e=navigator.userAgent.toLowerCase().includes("mac");if(q){const t=_n(q);return t?Tn(t,e):""}return e?"⌥J":"Alt+J"},[q]),z=o.useMemo(()=>((e,t,n)=>{const r=jf(e),o=jf((e=>e.replace(/\\(\\|n|r|t)/g,(e,t)=>{switch(t){case "n":return "\n";case "r":return "\r";case "t":return "\t";case "\\":return "\\";default:return t}}))(n));return ("line"===t?r.split("\n"):o?r.split(o):[]).map(e=>e.trim()).filter(Boolean)})(u,g,m),[m,u,g]),F=E(()=>{const t=e.getTextareaElement();if(!t)return void k(null);const n=t.getBoundingClientRect(),r=window.innerHeight-n.top+12,o=Math.min(420,window.innerWidth-40);let i=n.right-20-o;i<20&&(i=20);const a=window.innerWidth-(i+o);k({bottom:r,right:a,width:o});},[e]);M(()=>{F();let t=null,n=null;const r=()=>{n=e.getTextareaElement(),n&&(t=new ResizeObserver(()=>{F();}),t.observe(n),n.parentElement&&t.observe(n.parentElement));};r();const o=setInterval(()=>{F(),t||n||r();},2e3);return window.addEventListener("resize",F),()=>{clearInterval(o),window.removeEventListener("resize",F),t&&t.disconnect();}},[F,e]),M(()=>{const t=setInterval(()=>{a(e.isGenerating());},1e3);return ()=>clearInterval(t)},[e]),M(()=>{const e=()=>{r(e=>!e);};return window.addEventListener("ophel:togglePromptQueue",e),()=>window.removeEventListener("ophel:togglePromptQueue",e)},[]),M(()=>{n&&_.current&&setTimeout(()=>_.current?.focus(),100);},[n]),M(()=>{if(!c)return;const e=window.setTimeout(()=>A.current?.focus(),60);return ()=>window.clearTimeout(e)},[c]),M(()=>{const e=T.current;if(e)return Zo(e,{capture:false})},[n,x]),M(()=>{if(!n||c)return;const e=e=>{T.current&&!T.current.contains(e.target)&&r(false);},t=setTimeout(()=>{document.addEventListener("mousedown",e);},100);return ()=>{clearTimeout(t),document.removeEventListener("mousedown",e);}},[c,n]);const j=E(async()=>{const e=s.trim();e&&(l(""),i?(C.enqueue(e),t.isRunning()||t.start()):await t.sendImmediately(e,D));},[s,i,C,t,D]),$=E(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),e.stopPropagation(),j()),"Escape"===e.key&&(e.stopPropagation(),r(false));},[j]),H=E(e=>{C.remove(e);},[C]),U=E(async(e,n)=>{C.remove(e);await t.sendImmediately(n,D)||(C.enqueue(n),t.isRunning()||t.start());},[C,t,D]),W=E(()=>{C.clear();},[C]),V=E(()=>{h(""),p("line"),f(""),d(false);},[]),G=E(async()=>{if("delimiter"===g&&!m.trim())return void Oo(re("queueBatchDelimiterRequired")||"请输入分隔符",2500);if(0===z.length)return void Oo(re("queueBatchImportEmpty")||"没有可导入的提示词",2500);const n=C.enqueueMany(z);0!==n.length?(t.isRunning()||t.start(),e.isGenerating()||await t.processNextNow(),Oo(re("queueBatchImportSuccess",{count:String(n.length)})||`已导入 ${n.length} 条提示词`,2500),V()):Oo(re("queueBatchImportEmpty")||"没有可导入的提示词",2500);},[e,m,z,g,t,V,C]),Q=E((e,t)=>{y(e),w(t);},[]),K=E(e=>{v.trim()&&C.updateContent(e,v.trim()),y(null);},[v,C]),Z=E(()=>{y(null);},[]),Y=E(()=>{_.current&&(_.current.style.height="0px",_.current.style.height=Math.min(_.current.scrollHeight,120)+"px");},[]);M(()=>{Y();},[s,Y]);const J=E(e=>{l(e.target.value);},[]);if(!x)return null;const X=document.querySelector(".gh-root")||document.body,ee={bottom:x.bottom,right:x.right},te={bottom:x.bottom,right:x.right,width:x.width};return n?ye(fe,{children:[uu( ye("div",{className:"gh-queue-panel",style:te,ref:T,children:[ ye("div",{className:"gh-queue-header",children:[ ye("div",{className:"gh-queue-header-title",children:[ be("span",{children:be(Ne,{size:18,color:"currentColor"})}), be("span",{children:re("queueTitle")}),I>0&&be("span",{className:"gh-queue-capsule-badge",children:I})]}), ye("div",{className:"gh-queue-header-actions",children:[ be("button",{className:"gh-queue-header-btn",onClick:()=>d(true),title:re("queueBatchImport")||"批量导入",children:be(De,{size:16,color:"currentColor"})}),L>0&&be("button",{className:"gh-queue-header-btn",onClick:W,title:re("queueClearAll"),children:be(ht,{size:16,color:"currentColor"})}), be("button",{className:"gh-queue-header-btn",onClick:()=>r(false),title:"Esc",children:ye("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ be("line",{x1:"18",y1:"6",x2:"6",y2:"18"}), be("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}), be("div",{className:"gh-queue-list",children:0===S.filter(e=>"pending"===e.status||"sending"===e.status).length?be("div",{className:"gh-queue-empty",children:re("queueEmpty")}):S.filter(e=>"pending"===e.status||"sending"===e.status).map((e,t)=>ye("div",{className:"gh-queue-item","data-status":e.status,children:[ be("span",{className:"gh-queue-item-index",children:t+1}),b===e.id?ye("div",{className:"gh-queue-item-edit-area",children:[ be("textarea",{className:"gh-queue-item-edit-input",value:v,onChange:e=>{w(e.target.value);const t=e.target;t.style.height="0px",t.style.height=Math.min(t.scrollHeight,120)+"px";},onKeyDown:t=>{"Enter"!==t.key||t.shiftKey||(t.preventDefault(),K(e.id)),"Escape"===t.key&&Z();},autoFocus:true}), ye("div",{className:"gh-queue-item-edit-actions-row",children:[ be("button",{className:"gh-queue-item-edit-btn-save",onClick:()=>K(e.id),title:re("queueEditSave")||"保存",children:be("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:be("polyline",{points:"20 6 9 17 4 12"})})}), be("button",{className:"gh-queue-item-edit-btn-cancel",onClick:Z,title:re("queueEditCancel")||"取消",children:ye("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ be("line",{x1:"18",y1:"6",x2:"6",y2:"18"}), be("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}):ye(fe,{children:[ be("span",{className:"gh-queue-item-content",children:e.content}), ye("div",{className:"gh-queue-item-actions",children:["pending"===e.status&&be("button",{className:"gh-queue-item-edit",onClick:()=>Q(e.id,e.content),title:re("queueEdit")||"编辑",children:ye("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ be("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}), be("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),"pending"===e.status&&be("button",{className:"gh-queue-item-force-send",onClick:()=>U(e.id,e.content),title:re("queueForceSend")||"Force Send",children:ye("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ be("line",{x1:"12",y1:"19",x2:"12",y2:"5"}), be("polyline",{points:"5 12 12 5 19 12"})]})}), be("button",{className:"gh-queue-item-remove",onClick:()=>H(e.id),title:re("queueRemove"),children:ye("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ be("line",{x1:"18",y1:"6",x2:"6",y2:"18"}), be("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]})]},e.id))}), be("div",{className:"gh-queue-input-area",children:ye("div",{className:"gh-queue-input-wrapper",children:[ be("textarea",{ref:_,className:"gh-queue-input",value:s,onChange:J,onKeyDown:$,placeholder:re(i?"queuePlaceholderBusy":"queuePlaceholderIdle"),rows:1}), be("button",{className:"gh-queue-send-btn",onClick:j,disabled:!s.trim(),title:"Enter",children:ye("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[ be("line",{x1:"12",y1:"19",x2:"12",y2:"5"}), be("polyline",{points:"5 12 12 5 19 12"})]})})]})}), ye("div",{className:"gh-queue-status",children:[ be("span",{className:"gh-queue-status-dot","data-generating":i?"true":"false"}), be("span",{children:re(i?"queueStatusBusy":"queueStatusIdle")}), ye("span",{className:"gh-queue-disable-hint",title:re("queueSettingDesc"),children:["(",re("queueDisableHint"),")"]}),O&&be("span",{className:"gh-queue-shortcut-hint",children:O})]})]}),X),c&&ye(af,{onClose:V,closeOnOverlayClick:false,closeOnEscape:false,dialogClassName:"gh-queue-batch-dialog",dialogStyle:{maxWidth:560,width:"min(560px, calc(100vw - 32px))"},children:[ be("div",{className:"gh-dialog-title",children:re("queueBatchImportTitle")||"批量导入提示词"}), be("div",{className:"gh-dialog-message",children:re("queueBatchImportDesc")||"粘贴多条提示词后,按所选规则拆分并加入队列。"}), ye("div",{className:"gh-queue-batch-section",children:[ be("div",{className:"gh-queue-batch-label",children:re("queueBatchSplitModeLabel")||"拆分方式"}), ye("div",{className:"gh-queue-batch-mode-group",children:[ be("button",{className:"gh-queue-batch-mode-btn","data-active":"line"===g,onClick:()=>p("line"),children:re("queueBatchSplitModeLine")||"按行拆分"}), be("button",{className:"gh-queue-batch-mode-btn","data-active":"delimiter"===g,onClick:()=>p("delimiter"),children:re("queueBatchSplitModeDelimiter")||"自定义分隔符"})]})]}),"delimiter"===g&&ye("div",{className:"gh-queue-batch-section",children:[ be("div",{className:"gh-queue-batch-label",children:re("queueBatchDelimiterLabel")||"分隔符"}), be("input",{className:"gh-dialog-input gh-queue-batch-delimiter-input",value:m,onChange:e=>f(e.target.value),placeholder:re("queueBatchDelimiterPlaceholder")||"例如:\\n、---"})]}), ye("div",{className:"gh-queue-batch-section",children:[ be("div",{className:"gh-queue-batch-label",children:re("queueBatchInputLabel")||"批量内容"}), be("textarea",{ref:A,className:"gh-queue-batch-textarea",value:u,onChange:e=>h(e.target.value),placeholder:re("queueBatchInputPlaceholder")||"粘贴多条提示词,每条按规则拆分后入队"})]}), ye("div",{className:"gh-queue-batch-preview",children:[ ye("div",{className:"gh-queue-batch-preview-header",children:[ be("span",{children:re("queueBatchPreviewTitle")||"预览"}), be("span",{children:re("queueBatchPreviewCount",{count:String(z.length)})||`将导入 ${z.length} 条`})]}), be("div",{className:"gh-queue-batch-preview-body",children:0===z.length?be("div",{className:"gh-queue-batch-preview-empty",children:re("queueBatchPreviewEmpty")||"暂无可导入内容"}):ye(fe,{children:[ be("ol",{className:"gh-queue-batch-preview-list",children:z.slice(0,5).map((e,t)=>be("li",{className:"gh-queue-batch-preview-item",children:e},`${t}-${e.slice(0,20)}`))}),z.length>5&&be("div",{className:"gh-queue-batch-preview-more",children:re("queueBatchPreviewMore",{count:String(z.length-5)})||`还有 ${z.length-5} 条未展示`})]})})]}), ye("div",{className:"gh-dialog-buttons",children:[ be("button",{className:"gh-dialog-btn gh-dialog-btn-secondary",onClick:V,children:re("cancel")||"取消"}), be("button",{className:"gh-dialog-btn gh-dialog-btn-primary",onClick:()=>{G();},disabled:0===z.length||"delimiter"===g&&!m.trim(),children:re("queueBatchImportAction")||"导入队列"})]})]})]}):uu( ye("div",{className:"gh-queue-capsule",style:ee,onClick:()=>r(true),title:O,children:[ be("span",{className:"gh-queue-capsule-icon",children:be(Ne,{size:15,color:"currentColor"})}), be("span",{children:N>0?re("queueInQueue",{count:String(N)}):re("queueQuickAsk")}),N>0&&be("span",{className:"gh-queue-capsule-badge",children:N})]}),X)},Hf=({isPanelOpen:e,onPanelToggle:t,onThemeToggle:n,themeMode:r,onExport:i,onMove:a,onSetTag:s,onScrollLock:l,onSettings:c,onCleanup:d,onGlobalSearch:u,scrollLocked:h,onCopyMarkdown:g,onModelLockToggle:p,isModelLocked:m})=>{const f=E(e=>{const t=e.getBoundingClientRect();return {clientX:t.left+t.width/2,clientY:t.top+t.height/2}},[]),{settings:b}=No(),y=b||bo,v=Hp(),w=y.collapsedButtons||[],x=y.panel?.defaultPosition??"right",k="left"===x?{left:"16px",right:"auto"}:{right:"16px",left:"auto"},S=Math.min(Math.max(y.quickButtonsOpacity??1,.4),1),C=v?.getSiteId()||"_default",_=yo(y,C),A="google-gradient"===("light"===(r||("dark"===_.mode?"dark":"light"))?_.lightStyleId||"google-gradient":_.darkStyleId||"classic-dark")?"currentColor":"brand",T=P(null),[I,N]=B(false);M(()=>{if(!I)return;const e=e=>{const t=e.target;T.current&&!T.current.contains(t)&&N(false);};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[I]);const[L,D]=B(null),[R,q]=B(false),[z,F]=B(false),j=P(null),$=P(null),H=P(null),U=P(false),W=P(null),V=P(false),G=null!==O(qm,Pm),[Q,K]=B(false),[Z,Y]=B(false),[J,X]=B(false),[ee,te]=B(""),ne=P(false),oe=E(async()=>{ne.current=false;const e=new AbortController,t=setInterval(()=>{ne.current&&e.abort();},100);let n=setTimeout(()=>{ne.current||(X(true),te(re("loadingHistory")));},1600);try{const t=await Km({adapter:v,loadAll:!0,signal:e.signal,allowShortCircuit:!0,onProgress:e=>{te(`${re("loadingHistory")} ${e}`);}});Rm(t.previousScrollTop),Y(t.isFlutterMode),n&&(window.clearTimeout(n),n=null),X(!1),te(""),t.success&&!t.silent&&Oo(re("historyLoaded"),2e3);}finally{clearInterval(t),n&&window.clearTimeout(n);}},[v]),ie=E(()=>{ne.current=true;},[]),ae=E(async()=>{const{previousScrollTop:e,container:t}=await Fm(v);Rm(e),Y(Um(t));},[v]),se=E(async()=>{const e=Dm();if(null===e)return;const t=(await $m(v)).scrollTop;await jm(v,e),Rm(t);},[v]),le=E(async()=>{const e=await $m(v);Rm(e.scrollTop),Y(e.isFlutterMode);},[v]),ce=E((e,t)=>{const n=T.current?.getBoundingClientRect();if(!n)return {x:e,y:t};const r=Math.max(8,window.innerWidth-n.width-8),o=Math.max(8,window.innerHeight-n.height-8);return {x:Math.min(Math.max(e,8),r),y:Math.min(Math.max(t,8),o)}},[8]),de={scrollTop:oe,scrollBottom:ae,panel:t,anchor:se,theme:e=>{e?.stopPropagation();const t=e?.currentTarget;t?n?.(f(t)):n?.();},floatingToolbar:e=>{e?.stopPropagation(),N(e=>!e);},globalSearch:e=>{e?.stopPropagation(),N(false),u?.();}},ue=(t,n,o)=>{const i=n.isPanelOnly,a="floatingToolbar"===t,s=!!a&&I;if(!o||i&&e)return null;let l;if("theme"===t)l=be("dark"===r?ve:we,{size:20});else if(n.IconComponent){const e=n.IconComponent;l=be(e,{size:"panel"===t?21:18,color:"panel"===t?A:void 0});}else l=n.icon;const c="anchor"===t,d=c&&!G,u=c?G?re("goToAnchor")||"返回锚点":re("noAnchor")||"暂无锚点":re(n.labelKey)||n.labelKey; return be(wu,{content:u,children:be("button",{className:`quick-prompt-btn gh-interactive ${i?"panel-only":""} ${s?"active":""} ${a?"tools-trigger-btn":""}`,onClick:e=>de[t]?.(e),style:{opacity:d?.4:1,cursor:d?"default":"pointer"},disabled:d,children:l})},t)},he=e=>{if(!e)return null;const t=ur.manualAnchor,n=t?.IconComponent; return be(o.Fragment,{children:be(wu,{content:re("setAnchor")||"设置锚点",children:be("button",{className:"quick-prompt-btn manual-anchor-btn set-btn gh-interactive",onClick:le,children:n?be(n,{size:18}):"📍"})})},"manualAnchor")},ge=(e,t)=>be("div",{className:"divider "},t),pe={[Gr]:()=>i?.(),[Qr]:()=>g?.(),[Kr]:()=>a?.(),[Zr]:()=>s?.(),[Yr]:()=>l?.(!h),[Jr]:()=>p?.(),[Xr]:()=>d?.(),[eo]:()=>c?.()},me=e=>e===Yr?h||false:e===Jr&&m||false;M(()=>{if(!T.current)return;let e=null;const t=()=>{e&&(clearTimeout(e),e=null),K(true);},n=()=>{e=window.setTimeout(()=>{K(false);},300);},r=T.current;return r.addEventListener("mouseenter",t),r.addEventListener("mouseleave",n),()=>{r.removeEventListener("mouseenter",t),r.removeEventListener("mouseleave",n),e&&clearTimeout(e);}},[]),M(()=>{D(null);},[x]),M(()=>{let e=null,t=null,n=false;const r=()=>{D(e=>{if(!e)return e;const t=ce(e.x,e.y);return t.x===e.x&&t.y===e.y?e:t});},o=()=>{null===e?e=requestAnimationFrame(()=>{e=null,r(),n&&(n=false,o());}):n=true;},i=()=>{o(),null!==t&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null,r();},120);};return window.addEventListener("resize",i),window.visualViewport?.addEventListener("resize",i),()=>{window.removeEventListener("resize",i),window.visualViewport?.removeEventListener("resize",i),null!==e&&cancelAnimationFrame(e),null!==t&&window.clearTimeout(t);}},[ce]);const xe=()=>{j.current&&(window.clearTimeout(j.current),j.current=null);},ke=()=>{F(false),xe(),$.current=null,H.current=null,U.current&&(U.current=false,q(false)),T.current&&null!==W.current&&T.current.hasPointerCapture(W.current)&&T.current.releasePointerCapture(W.current),W.current=null;}; return ye(fe,{children:[ be(kf,{isVisible:J,text:ee,onStop:ie}), ye("div",{ref:T,className:`quick-btn-group gh-interactive ${e?"":"collapsed"} ${R?"dragging":""} ${z?"pressing":""}`,onPointerDown:e=>{if(0!==e.button)return;if(!T.current)return;W.current=e.pointerId,$.current={x:e.clientX,y:e.clientY},V.current=false,F(true);const t=T.current.getBoundingClientRect();H.current={x:e.clientX-t.left,y:e.clientY-t.top},xe(),j.current=window.setTimeout(()=>{T.current&&null!==W.current&&(T.current.setPointerCapture(W.current),F(false),U.current=true,V.current=true,q(true));},150);},onPointerMove:e=>{if(!$.current)return;if(!U.current){const t=e.clientX-$.current.x,n=e.clientY-$.current.y;return void(Math.hypot(t,n)>6&&(xe(),F(false)))}e.preventDefault();const t=H.current||{x:0,y:0},n=e.clientX-t.x,r=e.clientY-t.y;D(ce(n,r));},onPointerUp:ke,onPointerCancel:ke,onPointerLeave:()=>{U.current||(xe(),F(false),$.current=null,H.current=null,W.current=null);},onClickCapture:e=>{V.current&&(e.preventDefault(),e.stopPropagation(),V.current=false);},style:{position:"fixed",top:L?`${L.y}px`:"50%",left:L?`${L.x}px`:k.left,right:L?"auto":k.right,transform:L?"none":"translateY(-50%)",display:"flex",flexDirection:"column",gap:"8px",zIndex:9998,transition:"opacity 0.3s",opacity:S},children:[ be("div",{className:"quick-btn-drag-handle",style:{"--quick-btn-press-duration":"150ms"},"aria-hidden":"true"}),(()=>{const t=[],n=new Set(["scrollTop","scrollBottom","anchor","manualAnchor"]),r=w.map(t=>{if("manualAnchor"===t.id)return null;const r=ur[t.id];if(!r)return null;const o=!r.canToggle||t.enabled;return o?r.isPanelOnly&&e?null:{id:t.id,def:r,enabled:o,group:n.has(t.id)?"navigation":"tools"}:null}).filter(e=>null!==e);let o=0;for(;o=2&&ne.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),children:(()=>{const e=[];let t=false,n=false;const r=y.toolsMenu??to.map(e=>e.id),o=new Set(r);for(const i of to){if(!(i.isSystem||o.has(i.id)))continue;i.isDanger&&!t&&(e.push(be("div",{className:"menu-divider"},`divider-before-${i.id}`)),t=true),i.isSystem&&!n&&(e.push(be("div",{className:"menu-divider"},`divider-before-${i.id}`)),n=true);const r=i.IconComponent,a=`quick-menu-btn ${!!i.isToggle&&me(i.id)?"active":""} ${i.isDanger?"danger":""}`;e.push( be(wu,{content:re(i.labelKey)||i.defaultLabel,children:be("button",{className:a,onClick:()=>{pe[i.id]?.(),N(false);},children:be(r,{size:18})})},i.id));}return e})()})]})]})},Uf=({title:e,onClear:t,adapter:n})=>{const[r,o]=B(120),i=P(null),a=P(null),s=E(e=>{let t=e,n=e.parentElement;for(let r=0;r<10&&n&&n!==document.body;r++){const e=window.getComputedStyle(n);if(e.borderRadius&&parseFloat(e.borderRadius)>0){t=n;break}n=n.parentElement;}return t},[]),l=E(()=>{const e=n?.getTextareaElement();if(!e||!e.isConnected)return void o(120);const t=s(e),r=t.getBoundingClientRect(),l=window.innerHeight,c=l-r.top+20,d=Math.max(50,Math.min(c,l-50));o(d),t!==a.current&&i.current&&(a.current&&i.current.unobserve(a.current),i.current.observe(t),a.current=t);},[n,s]);return M(()=>{if(!e)return;const t=n?.getTextareaElement();if(i.current=new ResizeObserver(()=>{l();}),t){const e=s(t);i.current.observe(e),a.current=e;}l();const r=[50,200,400].map(e=>setTimeout(l,e));return window.addEventListener("resize",l),()=>{window.removeEventListener("resize",l),r.forEach(e=>clearTimeout(e)),i.current&&(i.current.disconnect(),i.current=null),a.current=null;}},[e,n,s,l]),e?ye("div",{className:"selected-prompt-bar gh-interactive",style:{position:"fixed",bottom:`${r}px`,left:"50%",transform:"translateX(-50%)",background:"var(--gh-brand-gradient)",color:"var(--gh-text-on-primary, white)",padding:"8px 16px",borderRadius:"20px",boxShadow:"var(--gh-shadow-brand)",display:"flex",alignItems:"center",gap:"8px",zIndex:999998,maxWidth:"80%",animation:"slideInUp 0.3s ease",userSelect:"none",transition:"bottom 0.2s ease"},children:[ be("style",{children:"\n @keyframes slideInUp {\n from {\n transform: translate(-50%, 20px);\n opacity: 0;\n }\n to {\n transform: translate(-50%, 0);\n opacity: 1;\n }\n }\n "}), be("span",{style:{fontSize:"12px",color:"var(--gh-text-on-primary, rgba(255,255,255,0.8))",whiteSpace:"nowrap",userSelect:"none"},children:re("currentPrompt")||"当前提示词"}), be(wu,{content:e,children:be("span",{className:"selected-prompt-text",style:{fontSize:"13px",fontWeight:500,color:"var(--gh-text-on-primary, white)",maxWidth:"300px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",userSelect:"none"},children:e})}), be(wu,{content:re("clear")||"清除",children:be("button",{className:"clear-prompt-btn",onClick:t,style:{background:"var(--gh-glass-bg, rgba(255,255,255,0.2))",border:"none",color:"var(--gh-text-on-primary, white)",width:"20px",height:"20px",borderRadius:"50%",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"14px",lineHeight:"1",padding:0,marginLeft:"4px",transition:"all 0.2s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--gh-glass-bg-hover, rgba(255,255,255,0.3))",e.currentTarget.style.transform="scale(1.1)";},onMouseLeave:e=>{e.currentTarget.style.background="var(--gh-glass-bg, rgba(255,255,255,0.2))",e.currentTarget.style.transform="scale(1)";},children:be(ke,{size:14})})})]}):null},Wf={"zh-CN":"简体中文","zh-TW":"繁體中文",en:"English",es:"Español",pt:"Português",ru:"Русский",ja:"日本語",de:"Deutsch",fr:"Français",ko:"한국어"},Vf=({currentLang:e,themeMode:t="light",onSelect:n,onClose:r,triggerRef:o})=>{const i=P(null),[a,s]=B({top:0,left:0});M(()=>{if(!o.current)return;const e=o.current.getBoundingClientRect();s({top:e.top-10,left:e.right});},[o]);const l="dark"===t?{bg:"#1f2937",border:"#374151",text:"#e5e7eb",hover:"#374151",activeBg:"rgba(59, 130, 246, 0.2)"}:{bg:"#ffffff",border:"#e5e7eb",text:"#374151",hover:"#f3f4f6",activeBg:"rgba(59, 130, 246, 0.1)"};return uu( ye("div",{className:"lang-menu-portal",style:{position:"relative",zIndex:2147483647},children:[ be("div",{style:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:2e6,background:"transparent"},onClick:e=>{e.stopPropagation(),r();}}), be("div",{ref:i,style:{position:"fixed",bottom:window.innerHeight-a.top+5,left:a.left-150,width:"150px",background:l.bg,border:`1px solid ${l.border}`,borderRadius:"8px",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.15)",padding:"4px",zIndex:2000001,animation:"ophel-lang-pop 0.1s ease-out",display:"flex",flexDirection:"column",maxHeight:"500px",overflowY:"auto"},children:Object.entries(Wf).map(([t,r])=>ye("button",{onClick:e=>{e.stopPropagation(),n(t);},style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",border:"none",background:e===t?l.activeBg:"transparent",color:e===t?"#3b82f6":l.text,fontSize:"13px",cursor:"pointer",borderRadius:"4px",textAlign:"left",width:"100%",fontWeight:e===t?500:400,transition:"background-color 0.1s"},onMouseEnter:n=>{e!==t&&(n.currentTarget.style.backgroundColor=l.hover);},onMouseLeave:n=>{e!==t&&(n.currentTarget.style.backgroundColor=e===t?l.activeBg:"transparent");},children:[ be("span",{children:r}),e===t&&be("span",{children:"✓"})]},t))}), be("style",{children:"\n @keyframes ophel-lang-pop {\n from { opacity: 0; transform: scale(0.95); }\n to { opacity: 1; transform: scale(1); }\n }\n "})]}),document.body)},Gf=({siteId:e="_default"})=>{const{settings:t,setSettings:n}=No(),r=!window.__ophelThemeManager,i=window.__ophelThemeManager,a=O(i?.subscribe??(()=>()=>{}),i?.getSnapshot??(()=>"light")),s=t?.theme?.sites,l=s&&e in s?s[e]:s?._default,c=l?.mode||"light",d=async(r,o)=>{if(c===r)return;const i=window.__ophelThemeManager;if(i?.setMode)await i.setMode(r,o?.nativeEvent);else {const o=t?.theme?.sites||{},i=o[e]||o._default||{};n({theme:{...t?.theme,sites:{...o,[e]:{lightStyleId:"google-gradient",darkStyleId:"classic-dark",...i,mode:r}}}});}},u=e=>{n({language:e}),te(e);},h=ne(t?.language||"auto"),[g,p]=o.useState(false),m=o.useRef(null),f=o.useRef(null),[b,y]=o.useState("normal"),v=o.useRef("normal"),w={en:"EN","zh-CN":"简","zh-TW":"繁",ja:"JP",ko:"KR",fr:"FR",de:"DE",ru:"RU",es:"ES",pt:"PT"},x=["zh-CN","en"],k=x.includes(h)?"es":h,S=Array.from(new Set([...x,k]));return o.useEffect(()=>{v.current=b;},[b]),o.useEffect(()=>{const e=f.current;if(!e)return;const t=t=>{e.classList.toggle("is-compact","compact"===t),e.classList.toggle("is-icon","icon"===t);},n=n=>(t(n),e.scrollWidth<=e.clientWidth+1),r=()=>{const e=v.current;let r="normal";if(!n("normal")){r=n("compact")?"compact":"icon";}t(e),r!==v.current&&y(r);},o=()=>{"function"!=typeof requestAnimationFrame?r():requestAnimationFrame(r);};if(o(),"undefined"!=typeof ResizeObserver){const t=new ResizeObserver(()=>o());return t.observe(e),()=>t.disconnect()}return window.addEventListener("resize",o),()=>window.removeEventListener("resize",o)},[h]),ye("div",{className:"settings-sidebar-footer",children:[!r&&ye("div",{ref:f,className:`settings-theme-segmented ${"compact"===b?"is-compact":""} ${"icon"===b?"is-icon":""}`,children:[ be(wu,{content:re("themeLight")||"浅色",triggerStyle:{flex:1},children:ye("button",{className:"settings-theme-segment "+("light"===c?"active":""),onClick:e=>d("light",e),children:[ be("span",{className:"segment-icon",children:be(ve,{size:16})}), be("span",{className:"segment-label",children:re("themeLight")||"浅色"})]})}), be(wu,{content:re("themeDark")||"深色",triggerStyle:{flex:1},children:ye("button",{className:"settings-theme-segment "+("dark"===c?"active":""),onClick:e=>d("dark",e),children:[ be("span",{className:"segment-icon",children:be(we,{size:16})}), be("span",{className:"segment-label",children:re("themeDark")||"深色"})]})}), be(wu,{content:re("themeSystem")||"系统",triggerStyle:{flex:1},children:ye("button",{className:"settings-theme-segment "+("system"===c?"active":""),onClick:e=>d("system",e),children:[ be("span",{className:"segment-icon",children:be(xe,{size:16})}), be("span",{className:"segment-label",children:re("themeSystem")||"系统"})]})})]}), ye("div",{className:"settings-lang-inline",children:[ be("button",{className:"lang-icon",onClick:e=>{e.stopPropagation(),p(!g);},children:be(at,{size:16})}), be("div",{className:"lang-links-container",children:S.map((e,t)=>ye(o.Fragment,{children:[ be("button",{className:"lang-link "+(h===e?"active":""),onClick:()=>u(e),children:w[e]||e}),t{e.stopPropagation(),p(!g);},children:be(it,{size:18})})}),g&&be(Vf,{currentLang:h,themeMode:a,onSelect:e=>{u(e),p(false);},onClose:()=>p(false),triggerRef:m})]}), be("style",{children:'\n .settings-lang-inline {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 3px 4px;\n background: var(--gh-bg-secondary, #f3f4f6);\n border-radius: 8px;\n margin-top: 4px; /* Reduced gap */\n height: 32px;\n }\n\n :host-context([data-gh-mode="dark"]) .settings-lang-inline {\n background: rgba(255, 255, 255, 0.08); /* 匹配深色模式下的 segmented */\n }\n\n .lang-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: var(--gh-text-secondary, #9ca3af);\n padding: 4px;\n margin-left: 2px;\n background: transparent;\n border: none;\n cursor: pointer;\n transition: color 0.2s;\n }\n\n .lang-icon:hover {\n color: var(--gh-text, #374151);\n }\n\n :host-context([data-gh-mode="dark"]) .lang-icon:hover {\n color: #e5e7eb;\n }\n\n /* 中间语言链接容器 */\n .lang-links-container {\n flex: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 2px;\n }\n\n .lang-link {\n background: none;\n border: none;\n padding: 2px 4px;\n cursor: pointer;\n font-size: 13px;\n color: var(--gh-text-secondary, #6b7280);\n transition: all 0.2s;\n border-radius: 4px;\n font-weight: 500;\n }\n\n .lang-link:hover {\n color: var(--gh-text, #374151);\n background: rgba(0, 0, 0, 0.05);\n }\n\n :host-context([data-gh-mode="dark"]) .lang-link:hover {\n color: #f3f4f6;\n background: rgba(255, 255, 255, 0.1);\n }\n\n .lang-link.active {\n color: var(--gh-text, #111827);\n font-weight: 600;\n }\n\n :host-context([data-gh-mode="dark"]) .lang-link.active {\n color: #f9fafb;\n }\n\n .lang-divider {\n color: var(--gh-text-secondary, #d1d5db);\n font-size: 12px;\n margin: 0 1px;\n }\n\n .lang-more-btn {\n display: flex;\n align-items: center;\n justify-content: center;\n background: transparent;\n border: none;\n color: var(--gh-text-secondary, #9ca3af);\n cursor: pointer;\n padding: 2px;\n border-radius: 4px;\n transition: all 0.2s;\n margin-right: 2px;\n }\n .lang-more-btn:hover, .lang-more-btn.active {\n color: var(--gh-text, #374151);\n background: rgba(0, 0, 0, 0.05); /* Match hover styles */\n }\n :host-context([data-gh-mode="dark"]) .lang-more-btn:hover {\n color: #e5e7eb;\n background: rgba(255, 255, 255, 0.1);\n }\n '})]})},Qf={Gemini:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAABF1BMVEVHcExCiPvvTVP1Skoxhv/1WEP2uBhDivA8mdt4xWo8wGbkxSoxhv8xhv8KumEPumU+i/z6REL6vRI9wGeR0lztakvvvB7d0C72nh/ngEM2h/4yh/9wheMatH8+k/GscqotqazuWlOl1VSx1Esxhv8zh/83i/k6j/I0iP1LifY/iPs7lOc4h/6teaI7nc5Sto7uTlTkWGPUYHgcuG/Da42WfLxciexsid9Fq6eceLeBgtAuqaU8u3U3pLtlw3JEosFhuoG1ykWYxlf1SEkksYqIzWHvxB5QlOTcyiztpCWdnobLn0w6sZHkbVp8kMiSkLDBgoPTf2hvnL/JxjdcocBTqqjnkTXOtDdvrJKHsnTWbXSqsVi8lmybZV14AAAAJHRSTlMAt47pjhj6GPz7GBfqXl7qpV5ej66u9Y6P9Ojn5463jo63t+jInk8+AAABNklEQVQ4jZWSaVeCQABFJ1lMKpcsl/bFUIiEosUTiAsIAraZa/X/f0cz4EkKGE/v673nzTszA8A/k8utEAgCzyldorBCQpcSWEGXrm+wBZDfHmMWIH51l4wVCI8/HsTxU58/3K9F892nD59zXDaav70uOM+HO6hyGfKXZ8h5XhCEvT9LS5OJ++X88AsYckk3SrZtu67jDIeWxfEIV1BIv2W7QNN0YTr9nM9GI6vKsrUFh9nc8gTTNPvvne58Nm6tX1ahUPklwCOKfSSk2uNWPSiQgaHFDhLERn1ZERjptZx3e5rY8Cvgiv3wg5z1UIW3gq1FXvYOqmh6h0ReNTRQBTKOojkAKU0cKNCI44DR1IGiNOM/DMirqqGcxHMAVNkwcBzkZfkQKzCyzGAFkMngOUinVwihfANLZTmrCtehmQAAAABJRU5ErkJggg==",ChatGPT:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAD4UlEQVRYheXXaYjVVRgG8N+YOVlhiVhpWWSW0WZlYEjZRLTRAkaKpBJEESREChGt1pfMihZoIYIkCkXFaSEiworINYhS2yCTyG0qzYy2cbTbh+dM945zZ7P8Ui/8uff//s/ynOd93nPew//dGvrY/kCMwLDy3oJv0fZvgqpnDWjCQmzBH+XZUnxN/2TgnuwAzMAD6I8V+LL0PRXj8Duex24cg9/wKd7BV/sKrt2mlgFX4kI01nwbinmolKcVP5ffCr7BTAzc18mHYR2+wMk1/n64AK+XyTZhTgE4BhNwJ9bjT8zFgH0BME1ovbXGNxpPYacwMw9ndtH/NGFuF67ry8Sj8JBQ+BPGFv8kbJBVLcXlogvC1qwC9oiasc7DDizDYb2ZfILQXsEebMVJ5dsSSblZGFR8B4tOPlLVwipcq6qXRfhVBNutjcZnQu39eAvf40RR/auSekfXgH1NUrIFj+FJ/Ci0L8TZuLsAu6a7yfvh6dLwjvI+Hz/UAXAJnpDwVITi6TVjjVdlqwUfl/9XdwdgJDYKfYOLb8FeAJpFlN9JeN4TLbSK4mdiSOl7ECZjtWqKXtkdgEvL4A+W94YuAFSwFjeKqAbhhuLbgw8wUTXthmI2fsFy2crr2qQy+Kw6AE4ovlewTeK6t50lgq2IJubjnJrv7TqYU9upX83/HYWB4TW+Cg6XmB+qSuX2OgC2S5zX4k3Jgjdwffn+nGhhsi5YGIGvS6OhxTdN4t0mq18jOjmuTv9jZUdsxiESolYRY/tCHyljXVyPgY1YLLvazcX3sghnsWw6Z8iRPERnGyJ53yBp/HZhpUH10NssG9fgOv3/ZmG5CGZ2DRMDRFjLRGjrdBbhGglRc5nweNFEs5yoROC7cVlXAOAKEVFFUmiSpFT7KmdKyu3Cu+VpT822LgA0lFWvkjCN7A7AVWXwT2QT2SUhOLemzVQRbUU2o8clrptls6oFsKQwcHtp/4yOoe9kE+WwuUvSbYGIaRselaN1qxQhzTi/9BteB8CWwtB9EtbPdTzW69o4OTheKu+NqvFvP2w+xBTVQmOQhKatrFgBsLEspiIV0oSeJid5v0JiOrbGP0SyYwaOLL7+IqilIs4NohlSmGyXI32uHPG9tukS+/dxShdtxuAFSbmdUqTU0nuLMDK9c9eerREPC33rcY+UYGOk7Joj9LZKWdako7BGS7zXqpbwfbaBuE0orFdwVvCijtVPYwG4UnQ0padJelOWj8JFOF2qn00S+5sKyNVSxFQkBONlX7gXz4o29os1ScWzWceLyiJhoVe3rr5ezfa29qvaUeW9RbSx369q/x37C/dbHMwqTvecAAAAAElFTkSuQmCC","AI Studio":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAZlBMVEUBAQEFBQUCAgIAAAAKCgoEBAQHBwcJCQkICAgGBgYDAwP8/PwLCwvd3d1fX1++vr6fn58RERHs7OwkJCSSkpIhISFGRkZ+fn5vb2+vr69AQEAvLy9QUFBWVlYoKCg1NTXNzc0ZGRnSaSLwAAACAElEQVQ4jW1S4XobIQzDBhsbuLtck2Zdt7Xd+7/kZMja/ZgDXzgsZFmQJGdKOUnKGUuZy5TmOsdME5BiN/4DS/8F0ATEyHQqDsxMlpZMyIiorhnLco7iKmKCSZMhL156kPE445seJdIUOIsvnCf201bVBVjJvEQiyztXZQAnAMWUHsXJh6uP+9OJhce2UmohF0fPb5fjOO7MrFu/gSZGIgkB0c/16emCwCbfeu8vyi3WFBhRcdq+nwbaofejR1zetNSKyolzbslf+49UTk66b33FcfUxGhhawuCfHfIN9ZleIr3dCdpdCDlkUt57GABAa/KK/NVWYy7wrUlre8eHuhZVG7f+y4YZ1qq+SgRDSG4qJHYerqZekQ4fAOAUJdhbUxKqelV9M7WKCQaOWIDJAIDq+2ZWQWMabULnBBCH615dde8AmGnVYBCGSBy1EGkVBtW9l1JqzOhxMUBkmwymk6GOYoDiSjOqfALEQWu29woA8oYSDSXe+zvel1MIx3552UoZ+JWynExp+3hmabg1d4h7225gqED81ZCu23Z8xkc/ftd5HgwIzim35/3yFb/qbGEChBkyGp44bifstQFtZYx/GeZEF/E8VxdocPlQ1oOZb4JFmtNima0shkcXbfng0yhbgMkyucPuNm1U/zo8phXhJJoADQJSwRAPJ66qRtgfxqkYA+wij7QAAAAASUVORK5CYII=",Claude:"data:image/svg+xml;base64,PHN2ZyBmaWxsPSIjRDk3NzU3IiByb2xlPSJpbWciIHZpZXdCb3g9IjAgMCAyNCAyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48dGl0bGU+Q2xhdWRlPC90aXRsZT48cGF0aCBkPSJtNC43MTQ0IDE1Ljk1NTUgNC43MTc0LTIuNjQ3MS4wNzktLjIzMDctLjA3OS0uMTI3NWgtLjIzMDdsLS43ODkzLS4wNDg2LTIuNjk1Ni0uMDcyOS0yLjMzNzUtLjA5NzEtMi4yNjQ2LS4xMjE0LS41NzA3LS4xMjE1LS41MzQzLS43MDQyLjA1NDYtLjM1MjIuNDc5Ny0uMzIxOC42ODYuMDYwOCAxLjUxNzkuMTAzMiAyLjI3NjcuMTU3OCAxLjY1MTQuMDk3MiAyLjQ0NjguMjU1aC4zODg2bC4wNTQ2LS4xNTc5LS4xMzM2LS4wOTcxLS4xMDMyLS4wOTcyTDYuOTczIDkuODM1NmwtMi41NS0xLjY4NzktMS4zMzU2LS45NzE0LS43MjI1LS40OTE4LS4zNjQzLS40NjE0LS4xNTc4LTEuMDA3OC42NTU3LS43MjI1Ljg4MDMuMDYwNy4yMjQ2LjA2MDcuODkyNS42ODYgMS45MDY0IDEuNDc1NCAyLjQ4OTMgMS44MzM2LjM2NDMuMzAzNS4xNDU3LS4xMDMyLjAxODItLjA3MjgtLjE2NC0uMjczMy0xLjM1MzktMi40NDY3LTEuNDQ1LTIuNDg5My0uNjQzNS0xLjAzMi0uMTctLjYxOTRjLS4wNjA3LS4yNTUtLjEwMzItLjQ2NzQtLjEwMzItLjcyODVMNi4yODcuMTMzNSA2LjY5OTcgMGwuOTk1Ny4xMzM2LjQxOS4zNjQyLjYxOTIgMS40MTQ3IDEuMDAxOCAyLjIyODIgMS41NTQzIDMuMDI5Ni40NTUzLjg5ODUuMjQyOS44MzE4LjA5MS4yNTVoLjE1Nzl2LS4xNDU3bC4xMjc1LTEuNzA2LjIzNjgtMi4wOTQ3LjIzMDctMi42OTU3LjA3ODktLjc1ODkuMzc2NC0uOTEwNy43NDY4LS40OTE4LjU4MjguMjc5My40Nzk3LjY4Ni0uMDY2OC40NDMzLS4yODUzIDEuODUxNy0uNTU4NiAyLjkwMjEtLjM2NDMgMS45NDI5aC4yMTI1bC4yNDI5LS4yNDI5Ljk4MzUtMS4zMDUzIDEuNjUxNC0yLjA2NDMuNzI4Ni0uODE5Ni44NS0uOTA0Ni41NDY0LS40MzExaDEuMDMyMWwuNzU5IDEuMTI5My0uMzQgMS4xNjU3LTEuMDYyNSAxLjM0NzgtLjg4MDQgMS4xNDE0LTEuMjYyOCAxLjctLjc4OTMgMS4zNi4wNzI5LjEwOTMuMTg4Mi0uMDE4MyAyLjg1MzUtLjYwNyAxLjU0MjEtLjI3OTQgMS44Mzk2LS4zMTU3LjgzMTguMzg4Ni4wOTEuMzk0Ni0uMzI3OC44MDc1LTEuOTY3LjQ4NTctMi4zMDcyLjQ2MTQtMy40MzY0LjgxMzYtLjA0MjUuMDMwNC4wNDg2LjA2MDcgMS41NDgyLjE0NTcuNjYxOC4wMzY0aDEuNjIxbDMuMDE3NS4yMjQ3Ljc4OTIuNTIyLjQ3MzYuNjM3Ni0uMDc5LjQ4NTctMS4yMTQyLjYxOTMtMS42MzkzLS4zODg2LTMuODI1LS45MTA3LTEuMzExMy0uMzI3OWgtLjE4MjJ2LjEwOTNsMS4wOTI5IDEuMDY4NiAyLjAwMzUgMS44MDkyIDIuNTA3NSAyLjMzMTQuMTI3NS41NzY4LS4zMjE4LjQ1NTQtLjM0LS4wNDg2LTIuMjAzOS0xLjY1NzUtLjg1LS43NDY4LTEuOTI0Ni0xLjYyMWgtLjEyNzV2LjE3bC40NDMyLjY0OTYgMi4zNDM2IDMuNTIxNC4xMjE0IDEuMDgwNy0uMTcuMzUyMS0uNjA3MS4yMTI1LS42Njc5LS4xMjE0LTEuMzcyMS0xLjkyNDZMMTQuMzggMTcuOTU5bC0xLjE0MTQtMS45NDI4LS4xMzk3LjA3OS0uNjc0IDcuMjU1Mi0uMzE1Ni4zNzAzLS43Mjg2LjI3OTMtLjYwNzEtLjQ2MTQtLjMyMTgtLjc0NjguMzIxOC0xLjQ3NTMuMzg4Ni0xLjkyNDYuMzE1Ny0xLjUzLjI4NTMtMS45MDA0LjE3LS42MzE0LS4wMTIxLS4wNDI1LS4xMzk3LjAxODItMS40MzI4IDEuOTY3Mi0yLjE3OTYgMi45NDQ2LTEuNzI0MyAxLjg0NTYtLjQxMjguMTY0LS43MTY0LS4zNzA0LjA2NjctLjY2MTguNDAwOC0uNTg4OSAyLjM4Ni0zLjAzNTcgMS40Mzg5LTEuODgyLjkyOS0xLjA4NjgtLjAwNjItLjE1NzloLS4wNTQ2bC02LjMzODUgNC4xMTY0LTEuMTI5My4xNDU3LS40ODU3LS40NTU0LjA2MDgtLjc0NjcuMjMwNy0uMjQyOSAxLjkwNjQtMS4zMTE0WiIvPjwvc3ZnPg==",Grok:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAF00lEQVRYhbWXX0iUXxrHP+d1zsw7oyiDbLbq7NCEJk78XEkqIkmTvAiCWMTtJqho21qCvZKKiEb2LoL4tcyFFF1EgXS7WBdSLr/+YKvyM4yZpXK3sndWUZxJzfKdcZ69KGez5lV/bH3hXMyc53m+z7/znPMqlkMBLtM0y9PpdL1hGE1AvYiEALdSyg9oVoYtIiml1AyQAH7OZrN3tdZPQ6GQFYvF7C8JARARpZTSHo/nZDab/QNQBRSsQrZW2MAL4K9VVVXXYrFYBsjmHBAR5ff7S969excB/vyNSJ1w2efzRVKpVEopJS5AhcNh/Yn8xHcmxzTN4/Pz84TD4Q4gXbBlyxYdj8ePAn/h26U8HzGNjY28ePGiANiWSqXeNjY2/qMgmUwGReRH4FffixzgwIEDxONxpqenARCR3yQSib+5stnsD8DGtRry+XwEg0E2bdpEOBzG7XYzPT3N06dPefbsGYlEgsXFxZy82+3myJEjbNy4kRs3bnxuqiqbzdajtf5Ray1rWbt375a+vj4ZHx+XTCazbH348EGeP38uXV1dUllZmdM5evSovHr1StatW5fP5mW01j+tRlxYWCgnTpyQVCqVI1xYWJDx8XGxLEsmJyclk8nI/Py8DA8Py7Fjx8Q0Tdm3b5/Mzs7KuXPnnGz/5AJ+vVLK3W4358+f5+TJk7jdbhYXF+nt7SUajWJZFtlsFq011dXVzMzM8OTJE6ampti1axdXr14F4P79+3lti0gIl8s1sVL0LS0tuQgty5L29nYxTdNR3uPxSHNzc05ncnJS6uvr88q6XK4JtNb2Sg4MDQ1JJpOR8fFxaW1tXbVPmpubZWxsLFcqy7Jk8+bNTvK2wQqzvb29nbq6OgC6u7vp6+tzLJVhGOzcuZNbt25hmibJZBIAr9eL1+t1UtM4RWKapvT09OTS6NDFubV161Z5+fKlDA8PS2Njoxw8eFAWFhbEtm3Zu3evo57h5FpxcTEVFRUA3L17NxdRPtTV1XHz5k2GhoZobW2lv7+f/v5+LMvCMAy2b9/uqOty2igqKqKwsBCAwcFBRwOBQIBoNEo0GuXatWu8f/8egLdv3zIzMwNAeXn5L3dAKYVSH2/rqampvDLl5eVEIhFOnTrFw4cPl+2JCNlsFoCCAucrxtEB27ax7Y9vh1Ao9NV+WVkZbW1tdHZ2MjY29tW+aZqYpgmwYvkce2B6eprJyUkAWlpalkVRVFRETU0NV65c4fXr14jIV/qBQID169cjIsTj8V/ugG3b3Lt3D4CGhgb27NmzbP/Bgwe5eudDW1sbxcXFJJNJBgYGHOVWHEThcDg3UAYHB6WiomLVQbQ0CZf0ent7xe/3Ow8iEXEs0Ojo6OeO4na7nSP5hB07dnD9+vXc77NnzzI3N5dXVkSSuFyuMadoampqxLZtGRgYkGAwKFpr8fl8UltbK9XV1VJSUiI+n09KS0ultrZWOjo6ZHZ2VjKZjMzNzcnp06dXy9hzl1Lq30BlPg+PHz/Oo0ePOHz4MIlEgoaGBs6cOUN9fT2ZTIaJiQnS6TRer5eysjLKysowjI9tdfHiRaLR6GoJ+w9a68v5vNu2bZt0d3fnRrDf75cLFy7I6Oio2Lb91YNk6Y0wMjIibW1ta3rgaK0vK7fb/TsRucVnD1K/309HRweXLl3KHcUlBINBmpqa2L9/P6FQiJKSEizLYmRkhDt37vD48WMmJibyHs0vYCulfq9M09ywuLh4B9gEUFpaSlNTE7dv317xmH0DxA3D2GeEw+E3InJ16d/q6mp6enq+NzlANBAIvFEiojZs2OCxLOsC8Edg9bP2/8EGutLp9CkR+WAopeTQoUO2aZqdQNd3JgfoMk2zMxKJLCil/tcokUjEqKys9Gqt/6S1jmmtF9bYyWtZGa31Pz0eTwfgjUQiuStAfeGdArTH4wmIyA8ishv4LbBeRIrX+Hme/jRd00qpfwFPlFJ/Nwzj51Ao9CYWi6WBXOT/BWa+grSwiwH0AAAAAElFTkSuQmCC","Gemini Enterprise":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMAAAADACAYAAABS3GwHAAAACXBIWXMAAAsTAAALEwEAmpwYAAAR4klEQVR4nO2de2wV153HTZ7dplK2SUq3jbSbJkSrjQTxvWd4BAgkvALYnutGdbrdpmmaSgRmjIFACiEP8zDvpwmBOIBnQptAUbv7x/61QpumadJtpUrbVt22eTeJqoo8zIyvHxgbvqu5NmDj+5jXndf9fqTzTyLE3Dnnw5zznd+ZU1VFCCGEEEIIIYQQQgghhBBCfKPuKMbJGo7LOj62WkbHMeu/8RaTxFPTjtuHBj2GN1nDKUpAEo+s4ceXD/5h7VjY10dI2Wg4gS/IGvoKCWD9v7lHcR27gCSS+hdRW+Rf/8HWjoVhXychZSGjo7WUALKOPbz9JJFkdPyp5BNAx/+FfZ2E+M79R3CrjcE/2DTcwi4giSKjYaVdAWQdK8K+XkJ8JaPjdQcCvMbbTxJD3SF8WdYw4ECAcws1/EPY102IL9TrWGJ7/n/pncBi3n6SCGQNv3QhwC/Cvm5CPFOv47aMhvNOBbD+jJUcsQtIrMloWOd48F9aCzwV9vUT4prmZlwh63jXrQAZDW9XAWPYBSSW1GmY73rwD7W6dswN+3cQ4gpZx394FSCj46e8/SR2fP2H+EqdhrOeBdDQX6Pj5rB/DyGOqGtHi6zlFrJenwBWa+HtJ7HB2tRSewSf1lkCaD4IoKHD2kwT9u8ixBa1R7Citj23gM0J4JMES3n7SeSZ2Yyrao7gL7VHBgXwSwJZx/szf4arwv59hBRl4SE8WHMEsATwW4LMi/gmbz+J9IuvhYfxh5rDwEUJ2v2TQNbxW+vvCPt3EpKX+S/g2wsPAQstAfJJoHmXoF7HA7z9JHI0nMCVC9rw5wWWAHYkcPsU0PAm1wIkcsxvwyPzXwAsAUpJ4Hk9oOE7Yf9eQi7ScALXzGvD+5YAIyQ4PFoCP9YDsoZ3FrXhanYBiQTz2rDyvjbAagUl8DkZkjU0hf27Cama34ovzTuI0/OeHxSgkAS+J0MaOmpfwk3sAhIqcw6ibe7zgCVAIQnKmAztZ/eT0Jh3EHfOPoCBuQeBixK0jZRggRMJnE+DBjLtGM8hQIIHGDPrAF6dcwCYYwmQR4KLTwEHEriYCp1k95PAuXc/Hpn9HDDbEiCPBAXXA+WIRxmLkiCZ2YabZu3HJ7OGBLggQU6Ag8XXA+WIR2UNn379KMZyFJBAuHc/jt+7H7AEmJXvKeBEAp/iUVnDD9n9pOzM2IcF9zwLWAJckKDYVMhVMuR2OtSOOg4BUjam7MINM/bhI0uACxLMsiNBQMmQrOPDjIa/5xAgZWFGK47P3AfMvCCACwnKnQzJOn7C7ie+M60Vj8xoBWZYAuwbFGDEVMiGBIElQ0yFiJ9M341b796LzrstAVoHBcgrwXOFJQgyGZI1ZHnmMPGFO5pxzbS9+PXdewGrzbArgZd41IdkSNbxBitGiWem7cHB6XuA6UMCXHgK2JXATTzqYzLUyiFAXDN1Fx6cthuYZgmQT4J9+SWwtSgOqnBOw8McAsQx03bhzqk70T3VEsCOBB6SoTLHo7217UhzCBDbTNyMG+/ahffu2gVMtZpNCYJKhpzGo9YOsoZDuIFDgNha9E7ZgVem7AQsAXIS7C4tQeSTIR2vzW/FtRwCpDDAmMnbcXTyDsASIK8Ee0ZLEJdkKKPjGA/cIAWZuB2bJm0HLAFsSXDhKbA3VsnQeg4BMopJW/H9idsBS4BJO+xJ4CYeDT0Zsg7sYzJEhiO2oV5sQ//EbcAoCXbml6Bs8WgAyZC1lZJfmCM5xFbMFVtwRtoKSJYARSS4KIATCSJaOCdr6JM11HAYVDBiE6alN6NLbAGEJUARCQpOhdwkQxEpnJM19GQ03BN2P5AQSLdgSmoTOtNbgPSQAIUksL0odpMMhRyPZnR01mmYwkFYQaQ2Ykb1JpipzYDVRkmw7ZIEuadARJMh3+JRDV3yi5gTdr+QAKhuwYLqjed6UpvOI7VpUIBCEoyYCm2PVjJUhnj0TN2LyHAQJpjUhn45teHcmVTLeeRaEQmKLop3xCgZcrow1vGNsPuJlIHqdQPfr14/MJDaeA6pjUMCFJDAzqL48ng0CclQZnA61C/r+B4HYVIAxqTW969Lrz+H1Iahlk+Cy58CDiRwE49GNRnKXGqtPI4p5oxbimtTzf0/Sq8bQHq91QpIUGo9EFQ8Gp1kCEPtRMMJ/F3Y/UhcMHENbkw197+Wbu5HToBCEthYD3hOhuJZOIehKdHPWUodM+5s7qtOPd3/bvqZfuQEaB7IL8FG5xJ4TobiVTiHIQk+qG3HxLD7ldgg/WTft1NP9XWnnz6LnAAFJCi6Hgg5GYpM4Zw+ovXK7XiEgzDCJ7Snn+zbmn7qLHLNEuDp/vwSrHcuQZSToSDOIshciEp1tFlnooXd32QYqTW941JPnPl1+sk+5Fo+CXIClFgPFJAgvTm6yVCgZxHoF6dEv6rXcRsHYQSoXtvzUHpNbza9tg+5lk+CZzxI4CIejUwyVM6jWnV01utYFHb/VyxiNa4Xa3pfEmvOIP3EUBshwfCngEMJ7C6Kgy6c85gM+XlUa+ZS+2n9i7gx7PFQUYjVZ2rSq3s/Eqt7YQlQUIIRU6Hii2IvyVAcCud8T4b0YesCDR9xb0EATFiZHZte1X1U/KAXuWYJMEqCIlOhMiRDcSicK2MyhMtE+E/5ML4axFioOMTjPQ1iVc8n4vEe5FoeCfJPhQosioNKhuJUOKf7IIGO07m1ATAm7DGTCFKrshPEyu5XxMpuiFU9gy2fBGs8SLDOuQRukqHEFc7pRZOiV+p0TAh7/MSWKSuMG8Tyrtb0imy/eKwbOQEKSZB3KmRTgggnQzEqnEOBp8E5WcdRHuDnALEIV6eXZZeL5V0dYkUXcs0SoJAEP3AigYdkyEPhXMK3VMLOtCijYTk/116MZlwhlmUbpKbs29KyLMRyqw0JUEiCIusBX5OhDdFPhiJROKeXnBZ9YK0PZv4MV3mdISQIjBGN2QbR2PlnqakTUlMWlgAlJVjlQgIXyVCohXNekqEIxKOZwiK8Z4nQcAJXVlVy7Y5QjG9JjcbvpcZOSEuH2igJui5J8FjXZU8BBxIUXQ+c9S0ZisOWyqDj0UzhqdHv63V8q6KeCBNW/u06STUWCcV4S1JN5Fqj1UpIsKKQBEWSodXBJkOphCZDcpkEGCbCXzI6Vje04fqqpDLl0e6bJcVsEYr52cWBP7yNkiB7UYLRUyEHEgSVDMWgcC4KyVCmuAifZXS01Oi4uSoRNOMKqdGYIynmCUk1zuYd+KUksLMe8CMZ8lI4V2gqFKfCucPBJkMlRDiX0XBS1tAQy3WCWGrcJilGs1DNd0sO+mISOFkUj0qGAopHXSRDcSicqw1ZgmEyvCtreOb+I7i1KspMbsp+WSjGEqEab0iqcd7xwB8hQbH1gM/J0NroJ0NJKpzLuG0azltHv9brWBKZF2sppeOfJNVcJhTzpFCMfk+DvuhUqEgytCLgZChKWypjXDiX8ThFknX8JqNhnXwY/xzYgBeL/vr5oTn9Vkk1f+P5X3q/JAgqGYrylsoYFs5l/Jwm6WjLrRnKkSRNbjJvF4p5XFKMvrINeCZDlbOlUi+jDIPnHhyvO4pxvgz+lGKMkxTj40AHvutkyMaTwE3hXEK3VM6NSTzqUoRTvuxbFqr549AGv1/JEAvnvCdDh8OPR120Y54FCPVf/wpJhuKwpXJhxOJRu0+BBAkQUDLELZWIYzJUNgFyi9+wB78bCVg4V9HJUGZQgJf9WQSrxqlYSeCqZohbKucmKBnybRF8QYJQYlDbEngsnIvjlsoKL5zLFB74fdbityxfrgv0RVilFc552VJZwYVzmSBehBUUoqnjH8tSClHuZIhbKmNdOCdb1aI6Xrf2ENS04/aqKDBhcXasUI3FkmK8HtiToeR6gFsqE1M4p+G8rOEXGR2PNhzBl6qizKTG018TivGUpJpvhy8BC+c81ww9H2rh3FuyhiczGm6pih8Y42hDTDkl4JbK2JxFIA9tiMm0oy4xX5hLqd1fLbolshyLYm6pDD0ZqnPwFLiwJTLR3xcdtin+zUAkYOFc9JMhDe/JOpbNPYrrqirpsyiSavyrpJq/K5sESdpSGbOzCGptSCDr+N96HQ/Ect+vf2CMtMSs81UEFs5FekulrOGPso6HeBD35Z9GbDQaRnwviMmQ5y2VUTqLoLYd79dV+hfh7HwcV1LN5ZJqdgQmAbdUopyFczWH8WlNOxqtaW/Y4ytWn0eXVKPV0xvmCi6cc1MzNNP/L8711xxG2/yov7iKMkLNjpcU87+ZDIW0pXK/y3j0BfzXwkP4l7DHT2Kw1geSanwSSjLELZW4PBkqFI/e9wI65h/i8anlOzVGMdsCTYZYOAe7ydC8NpzgdCcAxBKzRijmR2VbFHNLJRyeRfDBnAO4L4i+JxckWNRxvaSYLwWXDPEsgll5JJh9ECfmHcINHJhhrg0U83ToyVCFnUUw6zmYsw9wrh+dr1Grxq/cS5D8LZU+f3Hu9ZkHY1menPDaosGtmu4lSOiWSp/j0TbRhqvD7m9SAKEa/yapZndFF855+djWnvyFczNa0TtzHx7mwIsBkxo77pQU8x3v64EK31K5d1CAu1vx9oxnMT7sfiVO3xmoxquRiUdjehbB9L14ZfoBfJGDL4bc0YxrhGocZeGc62To+EwNnwu7H4knMEao5rqSX6rglkpclGAXzk/dja2J2Y9Lqqok1fxeycpSbqnEXbvRP203vssxk0CsnWdCNXorMhmyt6Wyb/IO3B92P5EyIpacvldSzWxZCufifRZB9107Wc9TEaQbO+8WimmGngxF5SyC7eiauBOzw+4XEiDpxeYUoZqdlX5K5cTt6Jy0C1M4+CoQ0dg5TVLMrkrdUiltRY/YgXvC7gcSIkI15kqKcaYCC+f6xDYs5OAj1pOgvmhEmrAtlektGBBb0MCuJyPeE1TElsrNOF+9BQ+x68koJNXcmPTCuerNaGbXkyJlE0Vqh2K+pbK6BcdY3kBKFtAV/Q5RTLdUVrec+/m4VlzL7ic2S6nNd5NSOFe98dzb47ewpJk4ILWkY0LRnWUx2VJZvX6gZ8IGpNj5xO32ylgXzlWvG2BlJ3GPUMz9cS2cS63v38u+J94XxarxP6EXzjlNhpoHfsmvNxBfkJYYt/pWPRpEMvTM2Wz1UxE5QJokg4mK+XBctlRWNw/wTS/xH6GYx6K/pfLsT9j3pCyMX2J8Uajmh2VNhjzEo6mnz344fg3zflJGpEZzQVEBQkyGUmvP1LHzSdkp+Vn2ELZUptae+RG7ngSCWNR5k6QYH/smgcfCudTaM59OaM6OZfeTwBBLzIdKT4WC2VKZeqLvQXY9CRyhmCedS+D7lsqT7HoSCpOWdt4hqcZZVxL4kAyl1/QOiNV9/GoziXCtUBm3VKZX9zzLvifhvxtQjE+9rwccxqOP93aIxzpvYveT0BGK2WTvKeBjPLqqd2nYv5uQHGIRrrZ1Io1vyVD3O9bfydtPIoNQze/aEsCHZEha2fOdsH8vISNoaMCVkmr80ZMENtYD6ZVdb1onYvL2k8ghNRrftC2Ay8K59MqeB8L+nYTkpxlXSKr5O2cSOEqGfmv9Hbz9JJlPgRLJUHp5lv/6kxisBewmQg4kSC/Pvse5P0nWewEnEjRlG8P+XYTYQiz66+dtvR22mQyJpuxndyinvsDbT2KDpJgtjgUolAw1ZVvC/j2EOEIs6vqKrUrREsmQWGr2T1nRfTNvP4kdQjH+3etTQCw1+ZUHEk/SqnGfKwGGS9CYnRP27yDE/Ysxp5HosCZU4y3r0A7efhJbJNV4xoMAT4Z9/YR4YvKjp2+RVOO8cwGM85MaT3+Nt5/EHqEabzgWQDFeC/u6CfEFoRqLXUx/FvP2k0QwYXF2rFCNAQeDf8D6M2FfNyG+YU1pHAjwKm89SRRCMVc4mAItC/t6CfEVK9GxK4CVHPH2k8QhKcafbEx//hD2dRJSFiTVaC0pgGLs4e0niSStmrWlBTAXhn2dhJQFa1OLpBh9RV5+9U1Y+bfrePtJYhGKebzIE+DlsK+PkLKSUoxx+U+XMU6JpcZtvP0k8VgDffDIVePUYDNf5uAnhBBCCCGEEEIIIYQQQgip8pX/BwILOckUNulSAAAAAElFTkSuQmCC",DeepSeek:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAgVBMVEX///9Na/5GZv5Kaf5EZP5CY/77/P89YP7x8/9YdP709v/Gz//5+v/p7P9bdv58kf6otP5Tcf45Xf7V2//k6P/c4f+AlP6Vpf5qgv50if5Rbv6El/7O1f+yvv+drP7W3f+NoP5fe/65xP+gr/7Ayv9uhP69x//g5f+zv/+Mnv8nUv732IziAAABdklEQVQ4jc1SCZaDIAyFJIhK1Vatu1a7O/c/4ISqtcsBZv57gln4CT8I8V/hH75cGzcI3MD0YeSy1Q4fYXebDbvdEGqIA2tncb55BPaJXZ0WCNBCSp1aTwSEKUePcWvNXHFkBg4NezqSkOWolbLWSckXoD4zM0gJ/GHBHQUg34B4XA4hGVuApuprBty5CDKXZwu4BRblJQRYGRBa0Si8GPdxEcx8IdJrGU8sVeSRpChC6iYJEl07j5+mtCRYJm4PTCNVuyRc/FnfTNlr1gnLwKnxfnIfEIJF0Nz2jmeRVryFs/u20/fnjOxRqH0xIG/OPKWSinWKHncKVPGqzOLsiEkXnOkp+dMXaPTcp9XPGdissx5hqpe2nOfsHnLo7ctjCDyE0Ur2U/AxA7aN6O25JBVSybeOSJ98YVgkHA+b1wwDAF49eny0SETjESha5JuwLxRO40IdV91xrOvtWxHhnwYk5iGobCOO44hPOKbr83x7vX1F/h6/P7IT00XL7ioAAAAASUVORK5CYII=",Doubao:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAsVBMVEVHcEzK5P/K5P/L5f/K5P+juM7K5P/K5f/K5P/K4/0eHyLK5P/K5P/K5P8PERIiJCYRFRpeaXQpKy1ZYGTK5f/O6P9GMy4+LSlMOjb/4Nbzy8D918w2JB/vw7f50cYJBQfQp5zruazfsqaee3PEgXFmYmWhr74dHiAvGxVZMixZQz7E3PW8loy4x9h5V0+Yn6iBaWSPj5FUVFesucrZl4jRt7R5f4jO3PAoDgO/1/DcztGl0EnsAAAAFHRSTlMAT5SN9QqhHeX9mojIyyFP24jI6xCzqC0AAAIcSURBVDiNbVOJlpswDIRkk0A2e7TFNodtjLmPEALk2P7/h1XYbJqk1XvAe55B0owlw7jFyly8WY5j7Rbmyvg3NmvbuYW93jzjr9M5Qk49vaZYPv5uqcMspdci3WuGdZdk8zKd1CklEJSkZ3vivGyecYxd18WEUkqyB4bOf3ABryoXU4LJVTEsjS8Vvu8JwBUkKPCURWl6VQW0sCPBbuWSooybFhiFSuFMRdZK4D4luHIpjn3P82JKioMirME/7U/mQou0bLg3RVPQXhHslWEq/HIGnJTJ9L8XBEFTkC8FmMZCtwgacVF2jT/h3Pfbq/ZrYexUC0MFjZWxaBrAWdt2zXVQhDdtAgITMKnaWHIecMZYJEqdwTJUBXQEAjQRVpIHvmzdTna1vti/BKjQh+kJKsR9fhTxZSZon6cMZRK3JxDBTyE+McFsXeLtVqJMIsa9gHMuRykjTdhpmarJMmF+4PHI5yyKZPTb0TLNGwEn0uc+i3x4xDC3YGqrETjt0k4COCYjYwJ/zcO50peFMkxAZCfY5CJrCJ1Frr+vuz6kxD2n6Sh9v2nDsJgJm7uBRvBcEoj9kGWZfT/a1vc6oP0oxsRGSI++bT0MLeCOkFEkTs5MeBpr5GTgFLQo4/NhqNEdrhYHDX0YBxyGgYswDPPaety+ZQ+HoVDzFId5Hv54Xs73bQ7RiZOI4bt9/89+rz62Pz9z8utz+3G3/n8AizBVNlqUq8sAAAAASUVORK5CYII=",Kimi:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAbFBMVEVHcExvcHB0dXUAAAEFBQYdHR0CAgKFhYVaWloDAwQxPk8TExQsLixCQ0NSUlF7fHw/QEBNTk0BAQIJCQn///8wMDEjJScQEBFaW1oaGxs8PDxLS0v09PSam5pvcG+7u7vd3d0Xhf0QWq8LOGx10D/DAAAAEnRSTlMA5beDuDfZ/ibp/YXLuoKC1oV4m0C2AAABk0lEQVQ4jXWTjZajIAyFaauiZ2Z2Z4mEAC3azvu/496g9tROGz2C3o/8CcaotaemG8jdjYauObVms75xL63pF70dXuvODdVJ/1YnN6iPN/7XKAjwRmKuQ2tOr/Wf6/VHx493EW7X6w1JhMZ065eQ8uLU+ZwzgBteKXRmq8GfR1snch7Hi5agq2gw9ASs+lonBeP2wKbTRjwBm3+YpvgLeNAVCTHsARnX/FYgxn0OM9bP9/VEIdAeqDanBVGRyfEemOZxPFslgl4hctoBk+NJsYgWwX9g7/0jMOl40TCWaxT2yT83amkFpkGJ5NOvVlMNYylWQw7D2lWe5rL8HziZCsMSbm86etjutUnVX4peUkzyaZqgxA5CizP7nLKX/GU+OKKi+l/qatxaXkzsOYv8MW1g1Bxr4UsQrR71eTgRwb7/jCiXGU91RREakgeCnSdHPTiSBPOckvalSE4xguUkIod6+PpDKXgBVSwu8awNyHcdxLFYKaXYC6xIyRENAP/V3893+/d4gDwBsLZ4Iv99/Lcc//+vBkqfTIfVbAAAAABJRU5ErkJggg==","Z.ai":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAYFBMVEUtLS3///8AAAD9/f0eHh77+/ssLCyenp6bm5snJycjIyNPT0/a2tpOTk5kZGShoaEJCQlfX1+SkpLR0dF3d3dCQkKIiIi5ubk4ODjw8PDm5uYRERGpqanExMR9fX0WFhYW+xctAAAA+UlEQVQ4jY2T7RaCIAxA18IhSKF9l5bv/5YFbIkdyu4fd9hVZBuwWgDSY11gElyDRRqXBIcGihh0UWi+5F/GJgr4LQ+AQVgHwSjBEAc2CBULZuvrhO8ohXpnM0HVcuwK9xwdZoIW4Xji4NzmW5CxifbC+StSLgAxeGNhE88+CUw/cF6PUBJsx3nHax8C9ZW0kIoC3jn/UFAS1IPz9+mVXCCQWo1UFEJvI52FkjBKtYceSkJofeSGUrR5JfHKwqXlqhvKhfbM+dNR2qZVJtgDr+7fX1rVM2HndcBDN+iE35p8C8tzRtnsyU8uDu2vsW/+uziLV2/58v7kCT8OC8uRxXhyAAAAAElFTkSuQmCC",ChatGLM:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAEhUlEQVRYhb2XTWhUVxTHf+/Om8kHozGMtZOFg8UYV8HEbQa7aYkYrIssNEGMLUGUUppaMFZatdCFgWJXflACmk1skCw0REi1UG3SZZIiLmKsqWNhFNJqcDoZ5+t0cTPvzZt5mYzG9g+P997Mfef/P+eec+69kAcRWScip0RkTt48pkTkkohswg0i0iUiz/4D4kI8E5GeQvJPV2PxUTQjj6KZV/2sC8AQHZIpYJ1raFwwPp3hxkSa0YkMkSdZx3+hoCK8TbGrxaQtbJYy8xx4xxCRS8DBlUgXYsLF4RQXhlMsxKQsoaGgYuRsJaGgWm7I14aITAFNpQxdHE5xZiBZNnE+avwGI2eraKx3FfGHISLLWl2ICftPJhifzhQZ7Wg1adzsIdykLA8XYsLdB1kGx1JcGUs7xt/5vso1EssKiDzJsvtowjHHNX6Dw+1ejrR7qfEbJT2/+yDL7qOLVtTCTR5GzlaVJ8CN/HC7l+NdPpQyiMXhfgRii/o/fxWsqYYtIX3PYXw6w+6ji9b7b4PVRVEoSlM38hMfVlC71ssX52FypqTj1K2Hho2woxnaWjyEmzzWFI5OZDjSvoKAvoGkgzz4ViXDP5csJwei8/q6PQX91yHyVAEZy7lCOCwPjqUZzEueDYEKavzF5HXroS6g7zlSgNnH8CLuFBNP2LniVkUO630DSeu5xm9Su9ZrvW/fCm0tOrT581yIyRm4PQl3pm1hts3ixLUEDI6lrRB5TUWg1mcRd+/R93Kwfau+PuuA0Qn4/Du7hENBRXTejhyAlRFXxlLWj9WVCq+p6N4D54+VT16Ixs1Znv5tCwhv89B/3RkZBXpu8ptNoNZH9x7o/uD1iHPIb0ahoKKxXjE5Az/cLBBw94GdnUoZhIJq1eSRJ1nO5OVU7wEfoxPa+xu/2smqI/CPnZ2VFYq9762OHGD/yYT1HAoqOneaDC15/iJuT0NRc85khIbQ6shPnHvpiGrvAZ3Q/rzqmX2cJyD0tq0jlZai8nkVfNyX4MKwndC9XT46d7r3EktAY72yajSbFUZ+SRd9sBJ0C190NLKOVpPjXdr76LyzjdcF8gTkBudw9dZL7j0sbptuWIgJfQNJdhxadFRSR6vJ+d5K673/uv1Nw8aCCAAc7/I5otD5ZcLhjZvHfQNJtnXGizYrh9u9TvJruinlsPd9+9mxHI+Opx3ZC7p9NtYrQkFjyWNdtm4LSyioOHesgnCTB9DZ3n8Nhm7ZY9pa4KuPlhEAMPRjmk++TZJKlzcFOZH5G5UXcRi6qYnzF6ctG3VnzV9LXDck9x5m6f4mye9/ZksK2RDwsKPZpLPVJJ4wuB/R5eW2Z2hrgZ59xQuZISJzwKbCD6LzOnGu/pQhlRbSS0JMU+E1DSp9CqVKb8tAE/bs0wJcMG2IyGng1HIGckImZ4qX11LYvhXebYZdLSWX78uGiKwD5ijjYDI5A7MRuP/YFhP9S9f0mmoIBqAhtPKeYQnPgWYAROTgao5mr4mi82GP/H+H04OuMRGRTSJyWfRR+k1jTkROi55yC/8C7thSyJF3OSAAAAAASUVORK5CYII=",QwenAI:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAaVBMVEVHcExeTe1cUe1fVO1cNOlhV+9wcfJVQvBQR/NeSu5WO+phRupVEeSFkff///9gRulhT+tiOediVu308/64sfWon/NfLOVua/BqYO7W0/qLeO1WPenm5PyRhvCDbe3Au/Z3fPNTEeRRLuid/6vZAAAADnRSTlMAg+XYqru9MxBfz/W/ga+H9kIAAAGTSURBVDiNdZPrYoMgDIV1VattB8hNEZTJ+z/kkqCt3er5ZZvPQ3KCRfFSVTdN0xWnKqMcx2FoT4GBRQFEc1avAmMjelw/168zY8xxIOCY4Qc0f78BNwWA4VIekGM7nYG6SkI8CUD2dq6gewCHJXnOudgoQHI7X0ZrPcfAFD5sijrGqMmiE+Q+O2ziXZocpPRY0mDxR6qm/KQUE/78bzHTFBdoyDvMQCzTUwb1lUcAQEh8YbHW9iAYZHAokxdXA+A1HrluZZ6CQrGBgBYA4dHCkEHPvdmacGVeMwAcN8HoCN5n+tVmgUDCISMdkiI8hkSn3vIeAOALvsHRQlDHnNIxOewLAIlGBYuVHjycGkAXahMd+h5fnKyl1HBl3HvPqc0aAW6xrbCulLvfl5qjItpiSU35XuStC9HlpCAH3LRjytG4M8UF9T1skWdgKmgacQXgjtdou3O1SHnVm8GIcR0/oJZv2Qbj9rhubze6XKYFNfbPwM8+DrAyKwDV53pRPJRa8Vqc1Yt2mqFuy1Og6B4V6PDHL81hMVCAJrPEAAAAAElFTkSuQmCC",Qianwen:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAaVBMVEVHcExeTe1cUe1fVO1cNOlhV+9wcfJVQvBQR/NeSu5WO+phRupVEeSFkff///9gRulhT+tiOediVu308/64sfWon/NfLOVua/BqYO7W0/qLeO1WPenm5PyRhvCDbe3Au/Z3fPNTEeRRLuid/6vZAAAADnRSTlMAg+XYqru9MxBfz/W/ga+H9kIAAAGTSURBVDiNdZPrYoMgDIV1VattB8hNEZTJ+z/kkqCt3er5ZZvPQ3KCRfFSVTdN0xWnKqMcx2FoT4GBRQFEc1avAmMjelw/168zY8xxIOCY4Qc0f78BNwWA4VIekGM7nYG6SkI8CUD2dq6gewCHJXnOudgoQHI7X0ZrPcfAFD5sijrGqMmiE+Q+O2ziXZocpPRY0mDxR6qm/KQUE/78bzHTFBdoyDvMQCzTUwb1lUcAQEh8YbHW9iAYZHAokxdXA+A1HrluZZ6CQrGBgBYA4dHCkEHPvdmacGVeMwAcN8HoCN5n+tVmgUDCISMdkiI8hkSn3vIeAOALvsHRQlDHnNIxOewLAIlGBYuVHjycGkAXahMd+h5fnKyl1HBl3HvPqc0aAW6xrbCulLvfl5qjItpiSU35XuStC9HlpCAH3LRjytG4M8UF9T1skWdgKmgacQXgjtdou3O1SHnVm8GIcR0/oJZv2Qbj9rhubze6XKYFNfbPwM8+DrAyKwDV53pRPJRa8Vqc1Yt2mqFuy1Og6B4V6PDHL81hMVCAJrPEAAAAAElFTkSuQmCC",ima:"data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5OjcBCgoKDQwNGg8PGjclHyU3Kzc3Nzc3Kzc3Nys3Ny01Nzc1LTcuKzI3NzctNys3Liw3Kys3NzctKysrLis3NCsrN//AABEIACAAIAMBIgACEQEDEQH/xAAYAAEBAQEBAAAAAAAAAAAAAAAGBQgHA//EACYQAAEDBAICAgIDAAAAAAAAAAECAwQFBhEhADEHExJBYYEUIlH/xAAXAQEBAQEAAAAAAAAAAAAAAAAEAAUB/8QAHREAAgEEAwAAAAAAAAAAAAAAAAECAwQRIQUSE//aAAwDAQACEQMRAD8Ag+SPINy1G9ZFJoM2XEYiSv4rDERRQt51KviSSNqyrQHWMaznmhYXvTEYEtSVSA2n2lPRXj+2P3nkqfEt+jOS7kmQ4UZ5psrfnekezGMdgZJPWtnQ5CsvyXSLwqsmn0+PLZcZaLqVPpSA4gEAnRODsa5HGNZnvVCfENSUyS2r1FXQXjWf3jmePG3kG5aderFIr0yXLZlyv4r7EtRWtl1SviCCdpwrRHWM6zjnU7y8m0iz6rGp1Qjy3nHmw6pTCUkNoJIHZGTo64gp8W3q05EuSHDhSXnWwtid6R7MYx2RkEdb2NjkSeSb5Et926bVlUmNKRHecUhaVrz8SUnOFY3jhC0rCk2ZSJ7tNnRHbhkthCJDzZ9LScglI+znHf4TrW39RW9HWUqSr4/Svo8mlxazk55nXV55aCTrtvqkELtsKVeNJgO1KbFauCM2ULkMtn0upySEn7GM9/lWt6YeOaE7a1rRaTJkpkOtqWtSkZ+IKjnCc7xz1bURylBC3VAAH4/Z/wA4KhyUqs1BCKaljZ//2Q==",Yuanbao:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAMAAABHPGVmAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAA51BMVEUAAAAAz3AAzHAAy3AAzXAAzHAAzHAAzXAAzHAAzHAAy3AAz3AAzXAAzXAAynAAzXAAzHEAzHAAy3AAzHAAy3AAzHAAzHAw1ooQz3kg04Ig0oJQ3J2A5bfP9uR/5bef7Mkw1ov////f+e2/8ttg36ZA2ZOw79Jw4q5g36XP9eSQ6MDv/PZA2ZQg04EQ0Hmv79Jv4q6P6cDf+O2P6MDf39+QkJBgYGCAgICfn5+vr68QEBAAAABwcHAgICDv7++/v7+goKBAQEB/f38w1YtQUFAwMDCQ6cDPz8+Pj49fX1+A5rig7Mlw4q+cA9JGAAAAFnRSTlMAEFBwj6/P3++/QCCfYDB/b5CA37CgSCmUoAAAAAFiS0dEIcRsDRYAAATWSURBVGjetZp9f5pIEMeXoICiXkiaSTSX6GqpJtjYtMbmShKbXu7ay+X9v577gCC77CwssPf7S5eHLzOzj7NLiKKMA7PVtmwHAMCxO52W2TVUn1WSa/ZsQGS3+wM9hG4LBexBvW5TgvGbBaWy+24DxKDllCNi9epi3I4ioT7GaFVB1MMcqjqKi01FT52eVYcAdCoYc+gMR3UYAI6pHo3heT0GALTUXGXB8PfaDABbwWWuDXBR01mqlIEDcDluwgBwBuWMCW1kSCklYsB01pBRTHEjxiV93xgCjjQuUcxhSBt7C4qiH48bY3qhgQFg4eNm3CP6lH7QAsFb5WF8aUZpk5bICulh4qBHEaFzTRAk+LsRakwpXWiCQCfP6ENqiD5I3mHubkayiCC6YgLg8DWstyu9iiDX2iB8DXMh8xZt3qtkckVDYm/RQCOkIxgSNZJIS42UQd4QCHaQakH5eOr7vn8juerlDfF3DBooz1RO57MgfWi1GCJ37CtYPymYJ/crVuKb+YzyGiOYI7b3BYBrWsWUTwEVJWKsHaOb/s8+7LYUMbmgqKZCf9Hlwg6fs3vL5l2fqFSXaOj3axzmzmBSyPhCqTLlOJ48pP/OOLOHcsTNjBYqN1a4TN2CEXdnIPWYP6Ul4t0Q9cVtHCI6NzHjSxmC0ilXO3tsSEbCveLIcnMZlDNyDe2YEAOkkAjDhca/VULkG5qRtRIMQim9Gs99/+Opv7hdKRKE2B8Qc//7TP0dpeLGJJN42Z8KX1oq1l8eYdbRn6WPrO82m69rofgeK9yJbQDvWMhKxvjjWxjpLlf8EIbho4TC1i+LMImTaxnkMWaE3554O+LCDf4Iu446Jsx6fSFhbMNE3zkX7tDP+DPshNohzJ+RBPI1hXBfvQmLLOGqFwuRRX6TQtivvk/K1lUhkqA8p5BHwVnhD4n1H6SQpTpkI5Tw4mY8hEvUBKqQbbGz+H7FIXa5vxDIfVhUtSilf3JV2Cr3V4ElWwljyr61k41ZsWaKEPqSlDzhkDEP8aDUlJcU8ldW9pTUrhccwk2nPaarl5rygLWT1GHfMQbnLTDJAZSacpdCHhA0agqf0+gyw+9Of4uPrEMszE/yvos3BAxCcvnrM2TC84y2vJ/xAPALgfB5E5sQcpIzBXHYOg79c77l3T+G4T8I45V/4TtC8pFHHUbX2y3SuJ+wQiE302eWQCWNRVnTfJJpwE24i8JSn2HHs3pPMGVUnyLmSHv8IkgDZSWu0ZLtFUsb5VV8k52sGY8AodSI/hRLAKSbBAa6w/CqwVVs4sPDrsJ5JZdN8UVTL0sHo9dh9K8yIniVrMqZDI5sY0kxMlIEYwjW6lMtyzFyBJ+KkkQlcVrhkmJ2XpC+YA2RVbB9FZBwgtVbYYIkn+Y2oViTt9UV9/6r8duk5BkQNtJUNhWHy+X7SMvJUOFuMWWbJJ91Ctt5KHNYZaEbdZ6GFzPyMAYxFDas1WUTXK6t4eUpQ74VpC34TsE24EATRWF77n9m6KGUMXREX3Xzt4kstT35Rq3SUz0yY9YOjPKmf+WDHpmqHF+IErk1IlPFjMSYk6oM5WjUx1T0VA2M4zU5HeWqxMY6anzSq3tSfPTKa3z0aqdBv40fIuuZTQ5diTK6ptfppMfhrLZnHig76T8EnUECfKwPQAAAAABJRU5ErkJggg=="},Kf=({title:e,description:t,children:n,className:r="",style:o,settingId:i})=>ye("div",{className:`settings-card ${r}`,style:o,"data-setting-id":i,children:[e&&be("div",{className:"settings-card-title",children:e}),t&&be("div",{className:"settings-card-desc",children:t}),n]}),Zf=({label:e,description:t,children:n,disabled:r=false,onDisabledClick:o,style:i,settingId:a})=>{const s=r&&!!o; return ye("div",{className:`settings-row ${r?"disabled":""} ${s?"disabled-clickable":""}`,"data-setting-id":a,style:i,onClick:()=>{s&&o?.();},children:[ ye("div",{className:"settings-row-info",children:[ be("div",{className:"settings-row-label",children:e}),t&&be("div",{className:"settings-row-desc",children:t})]}),n&&be("div",{className:"settings-row-control",children:n})]})},Yf=({label:e,description:t,checked:n,onChange:r,disabled:o=false,onDisabledClick:i,settingId:a})=>be(Zf,{label:e,description:t,disabled:o,onDisabledClick:i,settingId:a,children:be(rf,{checked:n,onChange:r,disabled:o})}),Jf=({tabs:e,activeTab:t,onTabChange:n})=>be("div",{className:"settings-tab-group",children:e.map(e=>be("button",{className:"settings-tab-item "+(t===e.id?"active":""),onClick:()=>n(e.id),children:e.label},e.id))}),Xf=({title:e,Icon:t})=>ye("h1",{className:"settings-page-title",style:{display:"flex",alignItems:"center"},children:[t&&be(t,{size:28,className:"settings-page-title-icon",style:{marginRight:8,color:"var(--gh-primary, #4285f4)"}}),e]}),eb=()=>{const e=String(Ur.length); return ye("div",{children:[ be(Xf,{title:re("navAbout")||"关于",Icon:We}), ye("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:8,marginBottom:24},children:[ be("span",{style:{fontSize:18},children:"✨"}), be("div",{className:"about-slogan",children:re("aboutPageDesc")||"AI 之益,触手可及"}), be("span",{style:{fontSize:18},children:"✨"})]}), ye("div",{className:"about-hero-card",children:[ be("img",{src:nf,alt:ef,className:"about-hero-logo",onError:e=>{e.target.style.display="none";}}), ye("div",{className:"about-hero-content",children:[ ye("div",{className:"about-hero-title",children:[ef, ye("span",{className:"about-hero-version",children:["v",tf]})]}), be("div",{className:"about-hero-desc",children:re("aboutDescription",{appName:ef})||`${ef} 是一款面向 Gemini、ChatGPT、Claude、AI Studio、Grok 等 AI 平台的浏览器增强扩展。它集中展示账号与余额、提供智能排序和当前站点识别,并提供自动刷新与临口防火墙绕过等自动化能力;支持数据导入导出工具。`})]})]}), be("div",{className:"about-section-title",children:re("rateAndReview")||"好评鼓励"}), ye("div",{className:"about-links-grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))"},children:[ ye("a",{href:"https://chromewebstore.google.com/detail/ophel-ai-%E5%AF%B9%E8%AF%9D%E5%A2%9E%E5%BC%BA%E5%B7%A5%E5%85%B7/lpcohdfbomkgepfladogodgeoppclakd",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",children:[ ye("div",{className:"about-link-header",children:[ be(pt,{size:24,color:"#4285F4"}),re("chromeStore")||"Chrome 商店"]}), be("button",{className:"about-link-btn",style:{marginTop:"auto"},children:re("reviewBtn")||"Review"})]}), ye("a",{href:"https://addons.mozilla.org/zh-CN/firefox/addon/ophel-ai-chat-enhancer/",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",children:[ ye("div",{className:"about-link-header",children:[ be(mt,{size:24,color:"#FF7139"}),re("firefoxAddons")||"Firefox 扩展"]}), be("button",{className:"about-link-btn",style:{marginTop:"auto",background:"#FF7139"},children:re("reviewBtn")||"Review"})]}), ye("a",{href:"https://greasyfork.org/zh-CN/scripts/563646-ophel-ai-chat-page-enhancer",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",children:[ ye("div",{className:"about-link-header",children:[ be(ft,{size:24,color:"currentColor"}),re("greasyFork")||"Greasy Fork"]}), be("button",{className:"about-link-btn",style:{marginTop:"auto",background:"#333"},children:re("reviewBtn")||"Review"})]})]}), be("div",{className:"about-section-title",children:re("communityAndSupport")||"社区与支持"}), ye("div",{style:{fontSize:"13px",color:"var(--gh-text-secondary)",marginBottom:16,fontStyle:"italic"},children:['"',re("communityMotto"),'"']}), ye("div",{className:"about-links-grid",children:[ ye("a",{href:"https://github.com/urzeye/ophel",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",children:[ ye("div",{className:"about-link-header",children:[ be(Ve,{size:20}),re("githubRepository")||"GitHub 仓库"]}), be("div",{className:"about-link-desc",children:re("githubDesc")||"查看源代码、提交问题或参与项目开发"}), be("button",{className:"about-link-btn about-star-btn",children:ye("span",{style:{display:"flex",alignItems:"center",gap:6},children:[ be(Ze,{size:14}),re("giveStar")||"点个 Star"]})})]}), ye("a",{href:"https://github.com/urzeye/ophel",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",children:[ ye("div",{className:"about-link-header",children:[ be(Ge,{size:20}),re("projectWebsite")||"项目官网"]}), be("div",{className:"about-link-desc",children:re("websiteDesc")||"查看详细文档、使用指南和更多信息"}), be("button",{className:"about-link-btn",children:re("visitWebsite")||"访问官网"})]})]}), be("div",{className:"about-section-title",children:re("aboutSupportedPlatforms")||"支持平台"}), ye("div",{className:"about-platforms-card",children:[ ye("div",{className:"about-platforms-header",children:[ be("div",{className:"about-platforms-desc",children:re("aboutSupportedPlatformsDesc",{count:e})||`当前已深度集成 ${e} 个主流 AI 平台,并持续扩充中。这些平台在主界面弹窗中也支持智能状态识别与一键捷径入口。`}), be("span",{className:"about-platforms-count",children:e})]}), be("div",{className:"about-platforms-grid",children:Ur.map(e=>ye("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"about-platform-chip",title:e.url,children:[Qf[e.name]?be("img",{src:Qf[e.name],alt:e.name,className:"about-platform-chip-icon"}):be("span",{className:"about-platform-chip-emoji","aria-hidden":"true",children:e.icon}), be("span",{children:e.name})]},e.id))})]}), be("div",{className:"about-section-title",children:re("techStack")||"技术栈"}), ye("div",{className:"about-tech-grid",children:[ be(tb,{name:"Plasmo",version:"v0.89.0",desc:re("tsPlasmoDesc")||"Browser Extension Framework"}), be(tb,{name:"React",version:"v18.2.0",desc:re("tsReactDesc")||"User Interface Library"}), be(tb,{name:"TypeScript",version:"v5.3.3",desc:re("tsTypescriptDesc")||"Typed JavaScript"}), be(tb,{name:"Zustand",version:"v5.0.3",desc:re("tsZustandDesc")||"State Management"}), be(tb,{name:"Vite",version:"v5.0.0",desc:re("tsViteDesc")||"Frontend Tooling"})]}), be("div",{className:"about-section-title",children:re("credits")||"版权与致谢"}), ye("div",{className:"about-simple-card",children:[ ye("div",{className:"about-simple-header",children:[ be(Qe,{size:18,style:{color:"#ef4444"}}),re("devAndMaintain")||"开发与维护"]}), be("p",{style:{fontSize:"13px",color:"var(--gh-text-secondary)",lineHeight:1.6,marginBottom:16},children:re("creditsDesc")||"感谢所有为开源社区做出贡献的开发者们,本插件的开发得益于这些优秀的开源项目和工具。"}), ye("div",{style:{display:"flex",gap:8},children:[ be(nb,{text:"Made with ❤️"}), be(nb,{text:"Open Source"}), be(nb,{text:"Privacy First"})]}), ye("div",{style:{marginTop:16,fontSize:"12px",color:"var(--gh-text-secondary)"},children:["GNU GPLv3 © ", (new Date).getFullYear()," ",ef]})]}), ye("div",{className:"about-privacy-banner",children:[ be(Ke,{size:24,className:"about-privacy-icon"}), ye("div",{children:[ be("div",{className:"about-privacy-title",children:re("privacyTitle")||"隐私保护"}), be("div",{className:"about-privacy-desc",children:re("privacyText")||"本插件所有数据均存储在本地浏览器中,不会主动上传到任何服务器。您的账号信息和使用数据完全由您自己掌控,确保隐私安全。"})]})]})]})},tb=({name:e,version:t,desc:n})=>ye("div",{className:"about-tech-card",children:[ ye("div",{className:"about-tech-header",children:[ be("div",{className:"about-tech-name",children:e}), be("div",{className:"about-tech-version",children:t})]}), be("div",{className:"about-tech-desc",children:n})]}),nb=({text:e})=>be("span",{style:{display:"inline-flex",alignItems:"center",padding:"2px 8px",background:"var(--gh-bg-secondary)",border:"1px solid var(--gh-border)",borderRadius:"12px",fontSize:"12px",color:"var(--gh-text-secondary)"},children:e});var rb={};const ob=ea(j);var ib;const ab=Xi(function(){if(ib)return rb;ib=1;var e=rb&&rb.__extends||function(){var e=function(t,n){return (e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);})(t,n)};return function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r);}}(),t=rb&&rb.__assign||function(){return t=Object.assign||function(e){for(var t,n=1,r=arguments.length;n-1){e._history.stack=l.slice(0,c+1);var d=e._history.stack.length;if(d>100){var u=d-100;e._history.stack=l.slice(u,d),e._history.offset=Math.max(e._history.offset-u,0);}}var h=Date.now();if(r){var g=e._history.stack[e._history.offset];if(g&&h-g.timestamp<3e3){var p=/[^a-z0-9]([a-z0-9]+)$/i,m=null===(o=e._getLines(g.value,g.selectionStart).pop())||void 0===o?void 0:o.match(p),f=null===(i=e._getLines(n.value,n.selectionStart).pop())||void 0===i?void 0:i.match(p);if((null==m?void 0:m[1])&&(null===(a=null==f?void 0:f[1])||void 0===a?void 0:a.startsWith(m[1])))return void(e._history.stack[e._history.offset]=t(t({},n),{timestamp:h}))}}e._history.stack.push(t(t({},n),{timestamp:h})),e._history.offset++;},e._updateInput=function(t){var n=e._input;n&&(n.value=t.value,n.selectionStart=t.selectionStart,n.selectionEnd=t.selectionEnd,e.props.onValueChange(t.value));},e._applyEdits=function(n){var r=e._input,o=e._history.stack[e._history.offset];o&&r&&(e._history.stack[e._history.offset]=t(t({},o),{selectionStart:r.selectionStart,selectionEnd:r.selectionEnd})),e._recordChange(n),e._updateInput(n);},e._undoEdit=function(){var t=e._history,n=t.stack,r=t.offset,o=n[r-1];o&&(e._updateInput(o),e._history.offset=Math.max(r-1,0));},e._redoEdit=function(){var t=e._history,n=t.stack,r=t.offset,o=n[r+1];o&&(e._updateInput(o),e._history.offset=Math.min(r+1,n.length-1));},e._handleKeyDown=function(t){var n=e.props,r=n.tabSize,o=n.insertSpaces,i=n.ignoreTabKey,a=n.onKeyDown;if(!a||(a(t),!t.defaultPrevented)){27===t.keyCode&&t.currentTarget.blur();var c=t.currentTarget,d=c.value,u=c.selectionStart,h=c.selectionEnd,g=(o?" ":"\t").repeat(r);if(9===t.keyCode&&!i&&e.state.capture)if(t.preventDefault(),t.shiftKey){var p=(y=e._getLines(d,u)).length-1,m=e._getLines(d,h).length-1,f=d.split("\n").map(function(e,t){return t>=p&&t<=m&&e.startsWith(g)?e.substring(g.length):e}).join("\n");if(d!==f){var b=y[p];e._applyEdits({value:f,selectionStart:(null==b?void 0:b.startsWith(g))?u-g.length:u,selectionEnd:h-(d.length-f.length)});}}else if(u!==h){var y,v=(y=e._getLines(d,u)).length-1,w=e._getLines(d,h).length-1;b=y[v];e._applyEdits({value:d.split("\n").map(function(e,t){return t>=v&&t<=w?g+e:e}).join("\n"),selectionStart:b&&/\S/.test(b)?u+g.length:u,selectionEnd:h+g.length*(w-v+1)});}else {var x=u+g.length;e._applyEdits({value:d.substring(0,u)+g+d.substring(h),selectionStart:x,selectionEnd:x});}else if(8===t.keyCode){var k=u!==h;if(d.substring(0,u).endsWith(g)&&!k){t.preventDefault();x=u-g.length;e._applyEdits({value:d.substring(0,u-g.length)+d.substring(h),selectionStart:x,selectionEnd:x});}}else if(13===t.keyCode){if(u===h){var S=e._getLines(d,u).pop(),C=null==S?void 0:S.match(/^\s+/);if(null==C?void 0:C[0]){t.preventDefault();var E="\n"+C[0];x=u+E.length;e._applyEdits({value:d.substring(0,u)+E+d.substring(h),selectionStart:x,selectionEnd:x});}}}else if(57===t.keyCode||219===t.keyCode||222===t.keyCode||192===t.keyCode){var _=void 0;57===t.keyCode&&t.shiftKey?_=["(",")"]:219===t.keyCode?_=t.shiftKey?["{","}"]:["[","]"]:222===t.keyCode?_=t.shiftKey?['"','"']:["'","'"]:192!==t.keyCode||t.shiftKey||(_=["`","`"]),u!==h&&_&&(t.preventDefault(),e._applyEdits({value:d.substring(0,u)+_[0]+d.substring(u,h)+_[1]+d.substring(h),selectionStart:u,selectionEnd:h+2}));}else !(l?t.metaKey&&90===t.keyCode:t.ctrlKey&&90===t.keyCode)||t.shiftKey||t.altKey?(l?t.metaKey&&90===t.keyCode&&t.shiftKey:s?t.ctrlKey&&89===t.keyCode:t.ctrlKey&&90===t.keyCode&&t.shiftKey)&&!t.altKey?(t.preventDefault(),e._redoEdit()):77!==t.keyCode||!t.ctrlKey||l&&!t.shiftKey||(t.preventDefault(),e.setState(function(e){return {capture:!e.capture}})):(t.preventDefault(),e._undoEdit());}},e._handleChange=function(t){var n=t.currentTarget,r=n.value,o=n.selectionStart,i=n.selectionEnd;e._recordChange({value:r,selectionStart:o,selectionEnd:i},true),e.props.onValueChange(r);},e._history={stack:[],offset:-1},e._input=null,e}return e(r,n),r.prototype.componentDidMount=function(){this._recordCurrentState();},Object.defineProperty(r.prototype,"session",{get:function(){return {history:this._history}},set:function(e){this._history=e.history;},enumerable:false,configurable:true}),r.prototype.render=function(){var e=this,n=this.props,r=n.value,o=n.style,s=n.padding,l=n.highlight,u=n.textareaId,g=n.textareaClassName,p=n.autoFocus,m=n.disabled,f=n.form,b=n.maxLength,y=n.minLength,v=n.name,w=n.placeholder,x=n.readOnly,k=n.required,S=n.onClick,C=n.onFocus,E=n.onBlur,_=n.onKeyUp;n.onKeyDown,n.onValueChange,n.tabSize,n.insertSpaces,n.ignoreTabKey;var A=n.preClassName,T=i(n,["value","style","padding","highlight","textareaId","textareaClassName","autoFocus","disabled","form","maxLength","minLength","name","placeholder","readOnly","required","onClick","onFocus","onBlur","onKeyUp","onKeyDown","onValueChange","tabSize","insertSpaces","ignoreTabKey","preClassName"]),M={paddingTop:"object"==typeof s?s.top:s,paddingRight:"object"==typeof s?s.right:s,paddingBottom:"object"==typeof s?s.bottom:s,paddingLeft:"object"==typeof s?s.left:s},I=l(r);return a.createElement("div",t({},T,{style:t(t({},h.container),o)}),a.createElement("pre",t({className:A,"aria-hidden":"true",style:t(t(t({},h.editor),h.highlight),M)},"string"==typeof I?{dangerouslySetInnerHTML:{__html:I+"
"}}:{children:I})),a.createElement("textarea",{ref:function(t){return e._input=t},style:t(t(t({},h.editor),h.textarea),M),className:c+(g?" ".concat(g):""),id:u,value:r,onChange:this._handleChange,onKeyDown:this._handleKeyDown,onClick:S,onKeyUp:_,onFocus:C,onBlur:E,disabled:m,form:f,maxLength:b,minLength:y,name:v,placeholder:w,readOnly:x,required:k,autoFocus:p,autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:false,"data-gramm":false}),a.createElement("style",{dangerouslySetInnerHTML:{__html:d}}))},r.defaultProps={tabSize:2,insertSpaces:true,ignoreTabKey:false,padding:0},r}(a.Component);rb.default=u;var h={container:{position:"relative",textAlign:"left",boxSizing:"border-box",padding:0,overflow:"hidden"},textarea:{position:"absolute",top:0,left:0,height:"100%",width:"100%",resize:"none",color:"inherit",overflow:"hidden",MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",WebkitTextFillColor:"transparent"},highlight:{position:"relative",pointerEvents:"none"},editor:{margin:0,border:0,background:"none",boxSizing:"inherit",display:"inherit",fontFamily:"inherit",fontSize:"inherit",fontStyle:"inherit",fontVariantLigatures:"inherit",fontWeight:"inherit",letterSpacing:"inherit",lineHeight:"inherit",tabSize:"inherit",textIndent:"inherit",textRendering:"inherit",textTransform:"inherit",whiteSpace:"pre-wrap",wordBreak:"keep-all",overflowWrap:"break-word"}};return rb}());class sb extends a{constructor(e){super(e);let t=false;try{document.createElement("div").innerHTML="";}catch{t=true;}this.state={hasError:t};}static getDerivedStateFromError(e){return {hasError:true}}componentDidCatch(e,t){}render(){if(this.state.hasError){const{value:e,onValueChange:t,style:n,placeholder:r,className:o,fallbackPlaceholder:i}=this.props; return be("div",{style:{display:"flex",flexDirection:"column",height:"100%",width:"100%"},children:be("textarea",{className:`settings-textarea ${o||""}`,value:e,onChange:e=>t(e.target.value),placeholder:i||r,style:{...n,fontFamily:'"Menlo", "Monaco", "Consolas", monospace',resize:"none",flex:1,width:"100%",height:"100%",border:"none",outline:"none",padding:"12px"}})})} return be(ab,{...this.props})}}const lb=({preset:e})=>{const t=e.variables,n=t["--gh-bg"]||"#ffffff",r=t["--gh-header-bg"]||t["--gh-primary"]||"#4285f4",o=t["--gh-border"]||"#e5e7eb",i=t["--gh-primary"]||"#4285f4",a=t["--gh-text"]||"#374151",s=t["--gh-text-secondary"]||"#9ca3af",l=t["--gh-bg-secondary"]||"#f3f4f6"; return ye("div",{className:"theme-preview-layout",style:{backgroundColor:n,borderColor:o},children:[ ye("div",{className:"theme-preview-header",style:{backgroundColor:r},children:[ be("div",{className:"theme-preview-dot"}), be("div",{className:"theme-preview-dot delay-1"}), be("div",{className:"theme-preview-dot delay-2"})]}), ye("div",{className:"theme-preview-body",children:[ ye("div",{className:"theme-preview-sidebar",style:{backgroundColor:l,borderColor:o},children:[ be("div",{className:"theme-preview-line short",style:{backgroundColor:s,opacity:.3}}), be("div",{className:"theme-preview-line",style:{backgroundColor:s,opacity:.3}}), be("div",{className:"theme-preview-line",style:{backgroundColor:s,opacity:.3}}), be("div",{className:"theme-preview-active-item",style:{backgroundColor:i,opacity:.15}})]}), ye("div",{className:"theme-preview-content",children:[ be("div",{className:"theme-preview-hero",style:{backgroundColor:i,opacity:.1}}), ye("div",{className:"theme-preview-row",children:[ be("div",{className:"theme-preview-avatar",style:{backgroundColor:s,opacity:.2}}), ye("div",{style:{flex:1},children:[ be("div",{className:"theme-preview-line",style:{backgroundColor:a,opacity:.6,marginBottom:4}}), be("div",{className:"theme-preview-line short",style:{backgroundColor:s,opacity:.4}})]})]}), be("div",{className:"theme-preview-button",style:{backgroundColor:i}})]})]})]})};oa.registerLanguage("css",ua);const cb=({preset:e,isActive:t,onClick:n})=>{const r=`themePreset_${e.id}`,o=re(r),i=o&&o!==r?o:e.name; return ye("div",{className:"settings-theme-card "+(t?"active":""),onClick:n,children:[ be(lb,{preset:e}), be("div",{className:"settings-theme-name",children:i})]})},db=({siteId:e,initialTab:t})=>{const[n,r]=B(t||Yn),{settings:o,setSettings:i}=No();M(()=>{t&&r(t);},[t]);const[a,s]=B(false),[l,c]=B(null),d=o?.theme?.sites?.[e]||o?.theme?.sites?._default;if(!o)return null;const u=[{id:Yn,label:re("themePresetsTab")||"主题预置"},{id:Jn,label:re("customStylesTab")||"自定义样式"}],h=o?.theme?.customStyles||[],g=e=>{const t=(e=>{const t={},n=/(--[\w-]+)\s*:\s*([^;]+);/g;let r;for(;null!==(r=n.exec(e));){const e=r[1],n=r[2].trim();t[e]=n;}return t})(e.css),n={"--gh-bg":"light"===e.mode?"#f3f4f6":"#1f2937","--gh-header-bg":"light"===e.mode?"#e5e7eb":"#374151","--gh-border":"light"===e.mode?"#d1d5db":"#4b5563","--gh-primary":"#4285f4","--gh-text":"light"===e.mode?"#374151":"#f9fafb","--gh-text-secondary":"light"===e.mode?"#6b7280":"#9ca3af","--gh-bg-secondary":"light"===e.mode?"#ffffff":"#1f2937"};return {id:e.id,name:e.name,variables:{...n,...t}}},p=[...km,...h.filter(e=>"light"===e.mode).map(g)],m=[...Sm,...h.filter(e=>"dark"===e.mode).map(g)]; return ye("div",{children:[ be(Xf,{title:re("navAppearance")||"外观主题",Icon:je}), be("p",{className:"settings-page-desc",children:re("appearancePageDesc")||"自定义扩展的视觉样式和主题"}), be(Jf,{tabs:u,activeTab:n,onTabChange:r}),n===Yn&&ye(fe,{children:[ be(Kf,{title:re("lightModePreset")||"浅色模式预置",description:re("lightModePresetDesc")||"仅在浅色模式生效",settingId:"appearance-preset-light",children:be("div",{className:"settings-theme-grid",children:p.map(t=>be(cb,{preset:t,isActive:(d?.lightStyleId||"google-gradient")===t.id,onClick:()=>(async t=>{const n=window.__ophelThemeManager,r="system"===d?.mode;!r&&n?.setMode&&await n.setMode("light");const a=o?.theme?.sites||{},s=a[e]||a._default||{};i({theme:{...o?.theme,sites:{...o?.theme?.sites,[e]:{...s,...r?{}:{mode:"light"},lightStyleId:t}}}});})(t.id)},t.id))})}), be(Kf,{title:re("darkModePreset")||"深色模式预置",description:re("darkModePresetDesc")||"仅在深色模式生效",settingId:"appearance-preset-dark",children:be("div",{className:"settings-theme-grid",children:m.map(t=>be(cb,{preset:t,isActive:(d?.darkStyleId||"classic-dark")===t.id,onClick:()=>(async t=>{const n=window.__ophelThemeManager,r="system"===d?.mode;!r&&n?.setMode&&await n.setMode("dark");const a=o?.theme?.sites||{},s=a[e]||a._default||{};i({theme:{...o?.theme,sites:{...o?.theme?.sites,[e]:{...s,...r?{}:{mode:"dark"},darkStyleId:t}}}});})(t.id)},t.id))})})]}),n===Jn&&be(fe,{children:ye(Kf,{title:re("customCSS")||"自定义样式",description:re("customCSSDesc")||"创建自定义 CSS 样式,可在主题选择器中使用",settingId:"appearance-custom-styles",children:[ ye("button",{className:"settings-btn settings-btn-primary",onClick:()=>{c({id:"",name:"",css:"/* 🎨 Custom CSS Cheat Sheet\n * 以下是本扩展使用的主要 CSS 类名,您可以自由覆盖。\n */\n\n/* === 主题变量 === */\n/*\n:host {\n --gh-bg: #ffffff;\n --gh-text: #1f2937;\n --gh-primary: #4285f4;\n}\n*/\n\n/* === 面板样式 === */\n/*\n.gh-main-panel { }\n.gh-panel-header { }\n.gh-panel-content { }\n*/\n",mode:"light"}),s(true);},style:{marginBottom:"16px"},children:["➕ ",re("addCustomStyle")||"添加样式"]}),0===(o?.theme?.customStyles||[]).length?be("div",{style:{padding:"20px",textAlign:"center",color:"var(--gh-text-secondary, #9ca3af)",fontSize:"13px",border:"1px dashed var(--gh-border, #e5e7eb)",borderRadius:"8px"},children:re("noCustomStyles")||"暂无自定义样式,点击上方「添加」按钮创建"}):be("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:(o?.theme?.customStyles||[]).map(e=>ye("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px",background:"var(--gh-bg-secondary, #f9fafb)",borderRadius:"8px"},children:[ ye("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[ be("span",{style:{fontSize:"11px",padding:"2px 8px",borderRadius:"4px",backgroundColor:"light"===e.mode?"rgba(251, 191, 36, 0.2)":"rgba(99, 102, 241, 0.2)",color:"light"===e.mode?"#b45309":"#4338ca"},children:"light"===e.mode?"☀️":"🌙"}), be("span",{style:{fontSize:"14px",fontWeight:500},children:e.name||re("unnamedStyle")||"未命名样式"})]}), ye("div",{style:{display:"flex",gap:"8px"},children:[ ye("button",{className:"settings-btn settings-btn-secondary",onClick:()=>{c(e),s(true);},style:{padding:"6px 12px",fontSize:"12px"},children:["✏️ ",re("edit")||"编辑"]}), be("button",{className:"settings-btn settings-btn-danger",onClick:()=>((e,t)=>{if(confirm(re("confirmDeleteStyle")||`确认删除样式「${t}」?`)){const t=(o?.theme?.customStyles||[]).filter(t=>t.id!==e);i({theme:{...o?.theme,customStyles:t}});}})(e.id,e.name),style:{padding:"6px 12px",fontSize:"12px"},children:"🗑️"})]})]},e.id))})]})}),a&&l&&be("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e4},children:ye("div",{style:{background:"var(--gh-bg, white)",borderRadius:"12px",width:"800px",maxWidth:"95%",height:"85vh",display:"flex",flexDirection:"column",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},children:[ ye("div",{style:{padding:"16px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ be("h3",{style:{margin:0,fontSize:"16px",fontWeight:600},children:l.id?re("editStyle")||"编辑样式":re("newStyle")||"新建样式"}), be("button",{onClick:()=>s(false),style:{background:"none",border:"none",cursor:"pointer",fontSize:"18px",color:"var(--gh-text-secondary, #9ca3af)"},children:"✕"})]}), ye("div",{style:{padding:"16px",overflowY:"auto",flex:1,display:"flex",flexDirection:"column"},children:[ ye("div",{style:{marginBottom:"16px"},children:[ be("label",{style:{fontSize:"13px",fontWeight:500,marginBottom:"6px",display:"block"},children:re("styleNameLabel")||"样式名称"}), be("input",{type:"text",className:"settings-input",value:l.name,onChange:e=>c({...l,name:e.target.value}),placeholder:re("enterStyleName")||"输入样式名称",style:{width:"100%"}})]}), ye("div",{style:{marginBottom:"16px"},children:[ be("label",{style:{fontSize:"13px",fontWeight:500,marginBottom:"6px",display:"block"},children:re("styleModeLabel")||"适用模式"}), ye("div",{style:{display:"flex",gap:"12px"},children:[ ye("label",{style:{display:"flex",alignItems:"center",gap:"6px",cursor:"pointer"},children:[ be("input",{type:"radio",checked:"light"===l.mode,onChange:()=>c({...l,mode:"light"})}), ye("span",{children:["☀️ ",re("lightMode")||"浅色模式"]})]}), ye("label",{style:{display:"flex",alignItems:"center",gap:"6px",cursor:"pointer"},children:[ be("input",{type:"radio",checked:"dark"===l.mode,onChange:()=>c({...l,mode:"dark"})}), ye("span",{children:["🌙 ",re("darkMode")||"深色模式"]})]})]})]}), ye("div",{style:{flex:1,display:"flex",flexDirection:"column"},children:[ ye("label",{style:{fontSize:"13px",fontWeight:500,marginBottom:"6px",display:"block"},children:["CSS ",re("code")||"代码"]}), be("div",{className:"settings-textarea",style:{flex:1,padding:0,overflow:"hidden",display:"flex",flexDirection:"column"},children:be(sb,{value:l.css,onValueChange:e=>c({...l,css:e}),highlight:e=>Uu(oa.highlight(e,{language:"css"}).value),padding:12,style:{fontFamily:'"Menlo", "Monaco", "Consolas", monospace',fontSize:13,minHeight:"100%"},textareaClassName:"focus-outline-none"})})]})]}), ye("div",{style:{padding:"16px",borderTop:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"flex-end",gap:"8px"},children:[ be("button",{className:"settings-btn settings-btn-secondary",onClick:()=>s(false),children:re("cancel")||"取消"}), be("button",{className:"settings-btn settings-btn-primary",onClick:()=>{if(!l)return;if(!l.name.trim())return void Oo(re("pleaseEnterStyleName")||"请输入样式名称");const e=o?.theme?.customStyles||[];let t;if(l.id)t=e.map(e=>e.id===l.id?l:e);else {const n={...l,id:crypto.randomUUID()};t=[...e,n];}i({theme:{...o?.theme,customStyles:t}}),s(false),Oo(l.id?re("styleUpdated")||"样式已更新":re("styleCreated")||"样式已创建");},children:l.id?re("save")||"保存":re("create")||"创建"})]})]})})]})};function ub(e){const t=[];if(!e||"object"!=typeof e)return {valid:false,errorKeys:["backupValidationInvalidFormat"]};if(e.version||t.push("backupValidationMissingVersion"),!e.data||"object"!=typeof e.data)return t.push("backupValidationMissingData"),{valid:false,errorKeys:t};const n=e.data;return void 0!==n.settings&&("object"!=typeof n.settings||Array.isArray(n.settings))&&t.push("backupValidationSettingsType"),void 0!==n.prompts&&(Array.isArray(n.prompts)||t.push("backupValidationPromptsType")),void 0!==n.folders&&(Array.isArray(n.folders)||t.push("backupValidationFoldersType")),void 0!==n.conversations&&("object"!=typeof n.conversations||Array.isArray(n.conversations))&&t.push("backupValidationConversationsType"),void 0!==n.readingHistory&&("object"!=typeof n.readingHistory||Array.isArray(n.readingHistory))&&t.push("backupValidationHistoryType"),{valid:0===t.length,errorKeys:t}}function hb(e){try{return decodeURIComponent(e)}catch{return e}}const gb={enabled:false,url:"",username:"",password:"",syncMode:"manual",syncInterval:30,remoteDir:Xm};class pb{config=gb;autoSyncTimer=null;constructor(){this.loadConfig();}async loadConfig(){const{getSettingsState:e}=await r(async()=>{const{getSettingsState:e}=await Promise.resolve().then(()=>qo);return {getSettingsState:e}},void 0),t=e();return t?.webdav&&(this.config={...gb,...t.webdav}),this.config} /** * 设置配置 * @param config 配置对象 * @param persist 是否持久化到 storage (默认 true) */async setConfig(e,t=true){if(this.config={...this.config,...e},t){const{useSettingsStore:e}=await r(async()=>{const{useSettingsStore:e}=await Promise.resolve().then(()=>qo);return {useSettingsStore:e}},void 0);e.getState().setSettings({webdav:this.config});}}async saveConfig(e){return this.setConfig(e,true)}getConfig(){return {...this.config}}async testConnection(){if(!this.config.url||!this.config.username||!this.config.password)return {success:false,messageKey:"webdavConfigIncomplete"};try{const e=await this.request("PROPFIND",this.config.remoteDir,null,{Depth:"0"});return e.ok||404===e.status?{success:!0,messageKey:"webdavConnectionSuccess"}:401===e.status?{success:!1,messageKey:"webdavAuthFailed"}:{success:!1,messageKey:"webdavConnectionFailed",messageArgs:{status:e.status}}}catch(e){return {success:false,messageKey:"webdavConnectionFailed",messageArgs:{error:String(e)}}}}async upload(){if(!this.config.url||!this.config.username||!this.config.password)return {success:false,messageKey:"webdavConfigIncomplete"};try{await this.saveConfig({lastSyncStatus:"syncing"});const e=await new Promise(e=>chrome.storage.local.get(null,e)),t=Object.fromEntries(Object.entries(e).map(([e,t])=>{try{let n="string"==typeof t?JSON.parse(t):t;return xr.includes(e)&&n?.state&&(n=kr.includes(e)?n.state:void 0!==n.state[e]?n.state[e]:n.state),[e,n]}catch{return [e,t]}})),n={version:3,timestamp:(new Date).toISOString(),data:t},r=function(){const e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0");return `${Xm}_backup_${t}-${n}-${r}_${o}-${i}-${a}.json`}(),o=this.buildRemotePath(r);if(this.config.remoteDir)try{await this.request("MKCOL",this.config.remoteDir);}catch{}const i=await this.request("PUT",o,JSON.stringify(n,null,2),{"Content-Type":"application/json"});if(i.ok||201===i.status||204===i.status){const e=Date.now();return await this.saveConfig({lastSyncTime:e,lastSyncStatus:"success"}),{success:!0,messageKey:"webdavUploadSuccess",timestamp:e}}return await this.saveConfig({lastSyncStatus:"failed"}),{success:!1,messageKey:"webdavUploadFailed",messageArgs:{status:i.status}}}catch(e){return await this.saveConfig({lastSyncStatus:"failed"}),{success:false,messageKey:"webdavUploadFailed",messageArgs:{error:String(e)}}}}async getBackupList(e=10){if(!this.config.url||!this.config.username||!this.config.password)return [];try{const t='\n\n \n \n \n \n \n',n=await this.request("PROPFIND",this.config.remoteDir,t,{Depth:"1","Content-Type":"application/xml"});if(!n.ok)return [];const r=await n.text(),o="(?:[a-zA-Z0-9_-]+:)?",i=new RegExp(`<${o}response[^>]*>([\\s\\S]*?)<\\/${o}response>`,"gi"),a=Array.from(r.matchAll(i)),s=[];for(const e of a){const t=e[1],n=t.match(new RegExp(`<${o}href[^>]*>([^<]+)<\\/${o}href>`,"i"));if(!n)continue;const r=hb(n[1]);if(!r.endsWith(".json")||!r.includes(`${Xm}_backup_`))continue;const i=t.match(new RegExp(`<${o}getcontentlength[^>]*>([^<]+)<\\/${o}getcontentlength>`,"i")),a=i?parseInt(i[1],10):0,l=t.match(new RegExp(`<${o}getlastmodified[^>]*>([^<]+)<\\/${o}getlastmodified>`,"i")),c=l?new Date(l[1]):new Date(0),d=r.split("/").pop()||r;s.push({name:d,path:r,size:a,lastModified:c});}return s.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime()),s.slice(0,e)}catch(t){return console.error("Failed to get backup list:",t),[]}}async deleteFile(e){if(!this.config.url||!this.config.username||!this.config.password)return {success:false,messageKey:"webdavConfigIncomplete"};try{const t=this.buildRemotePath(e),n=await this.request("DELETE",t);return n.ok||204===n.status||404===n.status?{success:!0,messageKey:"webdavDeleteSuccess"}:{success:!1,messageKey:"webdavDeleteFailed",messageArgs:{status:n.status}}}catch(t){return {success:false,messageKey:"webdavDeleteFailed",messageArgs:{error:String(t)}}}} /** * 从 WebDAV 下载并恢复数据 * @param targetFileName 可选,指定下载的文件名。若不指定则下载最新。 */async download(e){if(!this.config.url||!this.config.username||!this.config.password)return {success:false,messageKey:"webdavConfigIncomplete"};try{await this.saveConfig({lastSyncStatus:"syncing"});let t=e;if(!t){const e=await this.getBackupList(1);if(0===e.length)return await this.saveConfig({lastSyncStatus:"failed"}),{success:!1,messageKey:"webdavFileNotFound"};t=e[0].name;}const n=this.buildRemotePath(t),r=await this.request("GET",n);if(!r.ok)return await this.saveConfig({lastSyncStatus:"failed"}),{success:!1,messageKey:"webdavDownloadFailed",messageArgs:{status:r.status}};const o=await r.text(),i=JSON.parse(o),a=ub(i);if(!a.valid)return console.error("Backup validation failed:",a.errorKeys),await this.saveConfig({lastSyncStatus:"failed"}),{success:!1,messageKey:"webdavInvalidFormat"};const s=this.config,l=Object.fromEntries(Object.entries(i.data).map(([e,t])=>{if(null==t)return [e,t];if(xr.includes(e)){let n;if(kr.includes(e))if("object"!=typeof t||Array.isArray(t))n="readingHistory"===e?{history:t}:{[e]:t};else {const r=t;n="conversations"===e&&void 0!==r.conversations?t:"readingHistory"!==e||void 0===r.history&&void 0===r.lastCleanupRun?"readingHistory"===e?{history:t}:{[e]:t}:t;}else n={[e]:t};return [e,JSON.stringify({state:n,version:0})]}return "object"==typeof t?[e,JSON.stringify(t)]:[e,t]}));await new Promise((e,t)=>chrome.storage.local.set(l,()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e())),await new Promise((e,t)=>{chrome.storage.local.get("settings",n=>{if(chrome.runtime.lastError)return void t(chrome.runtime.lastError);let r=n.settings;if("string"==typeof r)try{r=JSON.parse(r);}catch{return void e()}r?.state?.settings&&(r.state.settings.webdav=s),chrome.storage.local.set({settings:JSON.stringify(r)},()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e());});});const c=Date.now();return await this.saveConfig({lastSyncTime:c,lastSyncStatus:"success"}),{success:!0,messageKey:"webdavDownloadSuccess",timestamp:c}}catch(t){return await this.saveConfig({lastSyncStatus:"failed"}),{success:false,messageKey:"webdavDownloadFailed",messageArgs:{error:String(t)}}}}startAutoSync(){this.stopAutoSync(),this.config.enabled&&"auto"===this.config.syncMode&&this.config.syncInterval>0&&(this.autoSyncTimer=setInterval(()=>{this.upload();},60*this.config.syncInterval*1e3));}stopAutoSync(){this.autoSyncTimer&&(clearInterval(this.autoSyncTimer),this.autoSyncTimer=null);}buildRemotePath(e){let t=this.config.remoteDir.trim();return t=t.replace(/^\/+|\/+$/g,""),t?`${t}/${e}`:e}async request(e,t,n,r){const o=this.buildUrl(t);return this.requestViaGM(e,o,n,r)}requestViaGM(e,t,n,r){return new Promise((o,i)=>{const a={...r};if(this.config.username&&this.config.password){const e=btoa(`${this.config.username}:${this.config.password}`);a.Authorization=`Basic ${e}`;}GM_xmlhttpRequest({method:e,url:t,headers:a,data:n||void 0,onload:e=>{o({ok:e.status>=200&&e.status<300,status:e.status,statusText:e.statusText,text:async()=>e.responseText,headers:{get:t=>{const n=e.responseHeaders?.split("\r\n")||[];for(const e of n){const[n,...r]=e.split(":");if(n?.toLowerCase()===t.toLowerCase())return r.join(":").trim()}return null}}});},onerror:e=>{i(new Error(e.statusText||"GM_xmlhttpRequest failed"));},ontimeout:()=>{i(new Error("Request timeout"));}});})}async requestViaBackground(e,t,n,r){const o=await chrome.runtime.sendMessage({type:"WEBDAV_REQUEST",method:e,url:t,body:n,headers:r,auth:{username:this.config.username,password:this.config.password}});if(!o.success)throw new Error(o.error||"WebDAV request failed");return {ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,text:async()=>o.body,headers:{get:e=>o.headers?.[e.toLowerCase()]||null}}}buildUrl(e){let t=this.config.url.trim();t.endsWith("/")||(t+="/");return t+e.replace(/^\/+/,"")}}let mb=null;function fb(){return mb||(mb=new pb),mb}const bb=io()(lo((e,t)=>({history:{},lastCleanupRun:0,_hasHydrated:false,savePosition:(t,n)=>e(e=>({history:{...e.history,[t]:n}})),getPosition:e=>t().history[e],cleanup:n=>{if(-1===n)return;const r=Date.now(),o=t();if(r-o.lastCleanupRun<864e5)return;const i=24*n*60*60*1e3,a={};let s=false;for(const[e,t]of Object.entries(o.history))r-t.ts<=i?a[e]=t:s=true;e(s?{history:a,lastCleanupRun:r}:{lastCleanupRun:r});},setHasHydrated:t=>e({_hasHydrated:t})}),{name:"readingHistory",storage:ao(()=>Ao),partialize:e=>({history:e.history,lastCleanupRun:e.lastCleanupRun}),onRehydrateStorage:()=>e=>{bb.setState({_hasHydrated:true});}})),yb=()=>bb.getState(),vb=Object.freeze(Object.defineProperty({__proto__:null,getReadingHistoryStore:yb,useReadingHistoryStore:bb},Symbol.toStringTag,{value:"Module"})),wb=e=>{if(0===e)return "0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(2))+" "+["B","KB","MB","GB","TB"][t]},xb=e=>e instanceof Error?e.message:String(e),kb="voyager_",Sb=hr.filter(e=>["📁","📂","🗂️","📋","💼","📝","🔍","🧠"].includes(e)),Cb=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Eb=(e,t)=>`https://gemini.google.com${t}/app/${e}`,_b=(...e)=>{for(const t of e)if("number"==typeof t&&Number.isFinite(t)&&t>0)return t;return Date.now()},Ab=(e,t,n)=>{const r=JSON.parse(e);if(!Cb(r)||"gemini-voyager.folders.v1"!==r.format)throw new Error(re("voyagerImportInvalidFormat")||"不是 Gemini Voyager 文件夹导出格式");const o=r.data;if(!Cb(o))throw new Error(re("voyagerImportInvalidData")||"缺少有效的 data 字段");const i=o.folders,a=o.folderContents;if(!Array.isArray(i)||!Cb(a))throw new Error(re("voyagerImportInvalidData")||"缺少有效的文件夹或内容数据");const s=i.map((e,t)=>{if(!Cb(e)||"string"!=typeof e.id)return null;const n=("string"==typeof e.name?e.name.trim():"")||`${re("untitled")||"未命名"} ${t+1}`,r="string"==typeof e.parentId&&e.parentId.trim()?e.parentId:null,o="number"==typeof e.sortIndex?e.sortIndex:void 0;return {id:e.id,name:n,parentId:r,sortIndex:o,originalIndex:t}}).filter(e=>Boolean(e));if(0===s.length)throw new Error(re("voyagerImportEmpty")||"导入文件中没有可用的文件夹");const l=new Map(s.map(e=>[e.id,e])),c=new Map;s.forEach(e=>{const t=e.parentId&&l.has(e.parentId)?e.parentId:null,n=c.get(t)||[];n.push(e),c.set(t,n);}),c.forEach(e=>{e.sort((e,t)=>{const n="number"==typeof e.sortIndex?e.sortIndex:Number.MAX_SAFE_INTEGER,r="number"==typeof t.sortIndex?t.sortIndex:Number.MAX_SAFE_INTEGER;return n!==r?n-r:e.originalIndex-t.originalIndex});});const d=[],u=new Set,h=c.get(null)||[],g=(e,t)=>{u.has(e.id)||(u.add(e.id),((e,t)=>{const n=[...t,e.name],r=n.join(" / ");var o,i;d.push({sourceId:e.id,folder:{id:(i=e.id,`${kb}${i}`),name:r,icon:(o=r,0===Sb.length?"📁":Sb[(e=>{let t=0;for(let n=0;n>>0;return t})(o)%Sb.length])}}),(c.get(e.id)||[]).forEach(e=>g(e,n));})(e,t));};h.forEach(e=>g(e,[])),s.forEach(e=>g(e,[]));const p=new Set,m=[];return d.forEach(({sourceId:e,folder:r})=>{const o=a[e];if(!Array.isArray(o))return;[...o].sort((e,t)=>{const n=Cb(e)?e:{},r=Cb(t)?t:{},o="number"==typeof n.sortIndex?n.sortIndex:Number.MAX_SAFE_INTEGER,i="number"==typeof r.sortIndex?r.sortIndex:Number.MAX_SAFE_INTEGER;return o!==i?o-i:0}).forEach(e=>{if(!Cb(e)||"string"!=typeof e.conversationId)return;if(p.has(e.conversationId))return;p.add(e.conversationId);const o=_b("number"==typeof e.addedAt?e.addedAt:void 0,"number"==typeof e.updatedAt?e.updatedAt:void 0,"number"==typeof e.lastOpenedAt?e.lastOpenedAt:void 0),i=_b("number"==typeof e.updatedAt?e.updatedAt:void 0,"number"==typeof e.lastOpenedAt?e.lastOpenedAt:void 0,"number"==typeof e.addedAt?e.addedAt:void 0),a="string"==typeof e.title&&e.title.trim()?e.title.trim():e.conversationId;m.push({id:e.conversationId,siteId:Ir,cid:t,title:a,url:Eb(e.conversationId,n),folderId:r.id,importedFolderId:r.id,pinned:Boolean(e.starred),createdAt:o,updatedAt:i});});}),{folders:d,conversations:m,sourceVersion:String(r.version||"-")}},Tb=(e,t,n,r)=>{const o=[...t],i={...n},a=new Set(t.map(e=>e.id));let s=0,l=0,c=0,d=0,u=0,h=0;e.folders.forEach(({folder:e})=>{a.has(e.id)||(o.push(e),a.add(e.id),s++);}),e.conversations.forEach(e=>{const t=i[e.id];if(t&&t.siteId&&t.siteId!==Ir)return void h++;if(!t)return i[e.id]={...e},void l++;const n={...t};let r=false,o=false;var a;n.siteId||(n.siteId=Ir,r=true),n.cid!==e.cid&&(n.cid=e.cid,r=true),n.url&&n.url===e.url||(n.url=e.url,r=true),n.title||(n.title=e.title,r=true),!n.pinned&&e.pinned&&(n.pinned=true,r=true),"inbox"===n.folderId||"string"==typeof(a=n.folderId)&&a.startsWith(kb)||!n.folderId?n.folderId!==e.importedFolderId&&(n.folderId=e.importedFolderId,r=true,o=true):u++,r&&(n.createdAt=n.createdAt||e.createdAt||Date.now(),n.updatedAt=Math.max(n.updatedAt||0,e.updatedAt||0,n.createdAt||0),i[e.id]=n,d++,o&&c++);});const g=r&&a.has(r)?r:"inbox";return {nextFolders:o,nextConversations:i,lastUsedFolderId:g,sourceVersion:e.sourceVersion,stats:{folderCount:e.folders.length,conversationCount:e.conversations.length,foldersAdded:s,conversationsAdded:l,conversationsMoved:c,conversationsUpdated:d,conversationsPreserved:u,conversationsSkipped:h}}},Mb=({onClose:e,onRestore:t})=>{const[n,r]=B([]),[i,a]=B(true),[s,l]=B({show:false,title:"",message:"",onConfirm:()=>{}}),c=async()=>{a(true);try{const e=fb(),t=await e.getBackupList();r(t);}catch(e){Oo("加载失败: "+String(e));}finally{a(false);}};o.useEffect(()=>{c();},[]); return ye("div",{className:"settings-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center"},children:[s.show&&be(sf,{title:s.title,message:s.message,danger:s.danger,onConfirm:s.onConfirm,onCancel:()=>l(e=>({...e,show:false}))}), ye("div",{className:"settings-modal",style:{width:"500px",height:"600px",background:"var(--gh-card-bg, #ffffff)",borderRadius:"12px",display:"flex",flexDirection:"column",overflow:"hidden"},children:[ ye("div",{style:{padding:"16px 20px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ be("div",{style:{fontWeight:600,fontSize:"16px"},children:re("webdavBackupList")||"WebDAV 备份列表"}), ye("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[ be(wu,{content:re("refresh")||"刷新",children:be("button",{onClick:c,className:"settings-btn settings-btn-secondary",style:{padding:"6px"},children:"🔄"})}), be("button",{onClick:e,className:"settings-btn settings-btn-secondary",style:{padding:"6px 12px"},children:"✕"})]})]}), be("div",{style:{overflowY:"auto",padding:"16px",flex:1},children:i?be("div",{style:{textAlign:"center",padding:"20px",color:"var(--gh-text-secondary)"},children:re("loading")||"加载中..."}):0===n.length?be("div",{style:{textAlign:"center",padding:"20px",color:"var(--gh-text-secondary)"},children:re("noBackupsFound")||"未找到备份文件"}):be("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:n.map(e=>ye("div",{style:{padding:"12px",background:"var(--gh-bg-secondary, #f9fafb)",borderRadius:"8px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[ ye("div",{children:[ be("div",{style:{fontSize:"14px",fontWeight:500},children:e.name}), ye("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:[wb(e.size)," • ",e.lastModified.toLocaleString()]})]}), ye("div",{style:{display:"flex",gap:"8px"},children:[ be("button",{onClick:()=>(e=>{l({show:true,title:re("restore")||"恢复",message:`确定要恢复备份 "${e.name}" 吗?当前数据将被覆盖,${re("openAiPagesWillRefresh")||"已打开的 AI 页面将被刷新。"}`,danger:true,onConfirm:async()=>{l(e=>({...e,show:false}));try{a(!0);const n=fb(),r=await n.download(e.name);if(r.success){try{"extension"===xu.type&&"undefined"!=typeof chrome&&(await new Promise((e,t)=>chrome.storage.local.set({[Co]:Date.now()},()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e())),await chrome.runtime.sendMessage({type:Nu}));}catch{}Oo(re("restoreSuccess")||"恢复成功,即将刷新页面..."),setTimeout(()=>{t();},1500);}else Oo(re("restoreError")||"恢复失败: "+r.messageKey),a(!1);}catch(n){Oo("恢复失败: "+String(n)),a(false);}}});})(e),className:"settings-btn settings-btn-primary",style:{padding:"6px 12px",fontSize:"12px"},children:re("restore")||"恢复"}), be("button",{onClick:()=>(e=>{l({show:true,title:re("delete")||"删除",message:`确定要删除云端备份 "${e.name}" 吗?此操作不可逆。`,danger:true,onConfirm:async()=>{l(e=>({...e,show:false}));try{a(!0);const t=fb();(await t.deleteFile(e.name)).success?(Oo(re("deleteSuccess")||"删除成功"),c()):(Oo(re("deleteError")||"删除失败"),a(!1));}catch(t){Oo("删除失败: "+String(t)),a(false);}}});})(e),className:"settings-btn settings-btn-danger",style:{padding:"6px 12px",fontSize:"12px"},children:"🗑️"})]})]},e.name))})})]})]})},Ib=({siteId:e,onNavigate:t})=>{const{settings:n,setSettings:r,resetSettings:o}=No(),i=e===Ir,[a,s]=B(false),l=P(null),[c,d]=B(""),u=P(null),[h,g]=B(""),[p,m]=B({url:"",username:"",password:"",remoteDir:"ophel"});M(()=>{n?.webdav&&m(e=>({...e,...n.webdav}));},[n?.webdav]);const[f,b]=B({show:false,title:"",message:"",onConfirm:()=>{}}),[y,v]=B({show:false,onConfirm:()=>{}});if(!n)return null;const w=async e=>{await new Promise((t,n)=>chrome.storage.local.set(e,()=>chrome.runtime.lastError?n(chrome.runtime.lastError):t()));},x=async()=>{try{"extension"===xu.type&&"undefined"!=typeof chrome&&(await w({[Co]:Date.now()}),await chrome.runtime.sendMessage({type:Nu}));}catch{}},k=async e=>{try{let n={};const r=(new Date).toISOString();let o=`ophel-backup-${r.slice(0,10)}.json`;if("full"===e){const e=await new Promise(e=>chrome.storage.local.get(null,e));n={version:3,timestamp:r,type:"full",data:Object.fromEntries(Object.entries(e).map(([e,t])=>{try{let n="string"==typeof t?JSON.parse(t):t;return xr.includes(e)&&n?.state&&(n=kr.includes(e)?n.state:void 0!==n.state[e]?n.state[e]:n.state),[e,n]}catch{return [e,t]}}))};}else if("prompts"===e){const e=await new Promise(e=>chrome.storage.local.get("prompts",e));let i=[];try{const t="string"==typeof e.prompts?JSON.parse(e.prompts):e.prompts;t?.state?.prompts&&(i=t.state.prompts);}catch(t){console.error(t);}n={version:3,timestamp:r,type:"prompts",data:{prompts:i}},o=`ophel-prompts-${r.slice(0,10)}.json`;}else if("settings"===e){const e=await new Promise(e=>chrome.storage.local.get("settings",e));let i={};try{const t="string"==typeof e.settings?JSON.parse(e.settings):e.settings;t?.state?.settings?i=t.state.settings:t?.state&&(i=t.state);}catch(t){console.error(t);}n={version:3,timestamp:r,type:"settings",data:{settings:i}},o=`ophel-settings-${r.slice(0,10)}.json`;}const i=new Blob([JSON.stringify(n,null,2)],{type:"application/json"}),a=URL.createObjectURL(i),s=document.createElement("a");s.href=a,s.download=o,s.click(),URL.revokeObjectURL(a),Oo(re("exportSuccess")||"导出成功!");}catch(n){Oo(re("exportError")||"导出失败:"+String(n));}},S=async e=>{const t=p.url;if(!t)return Oo(re("webdavConfigIncomplete")||"请填写完整的 WebDAV 配置"),false;if(!xu.hasCapability("permissions"))return await e(),true;try{const n=new URL(t).origin+"/*";return (await chrome.runtime.sendMessage({type:"CHECK_PERMISSION",origin:n})).hasPermission?(await e(),!0):(v({show:!0,onConfirm:async()=>{v(e=>({...e,show:!1})),await chrome.runtime.sendMessage({type:"REQUEST_PERMISSIONS",permType:"allUrls"});}}),!1)}catch(n){return console.warn("Perm check logic skipped:",n),await e(),true}}; return ye("div",{className:"settings-content",children:[ be(Xf,{title:re("navBackup")||"备份与同步",Icon:Ye}),f.show&&be(sf,{title:f.title,message:f.message,danger:f.danger,onConfirm:f.onConfirm,onCancel:()=>b(e=>({...e,show:false}))}),y.show&&be(sf,{title:re("permissionRequired")||"需要权限",message:re("webdavPermissionDesc")||"需要访问该域名的权限才能进行 WebDAV 备份。",onConfirm:y.onConfirm,onCancel:()=>v(e=>({...e,show:false}))}),a&&be(Mb,{onClose:()=>s(false),onRestore:()=>window.location.reload()}), ye("div",{className:"backup-grid",style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(400px, 1fr))",gap:"20px",marginBottom:"24px"},children:[ be(Kf,{title:re("exportData")||"导出数据",description:re("exportDataDesc")||"将数据导出为 JSON 文件进行备份",children:ye("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[ ye("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"12px",background:"var(--gh-bg-secondary)",borderRadius:"8px"},children:[ ye("div",{children:[ be("div",{style:{fontWeight:500,fontSize:"14px"},children:re("fullBackup")||"完整备份"}), be("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:re("fullBackupDesc")||"推荐用于完整迁移"})]}), be("button",{onClick:()=>k("full"),className:"settings-btn settings-btn-success",style:{padding:"6px 16px"},children:re("export")||"导出"})]}), ye("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"12px",background:"var(--gh-bg-secondary)",borderRadius:"8px"},children:[ ye("div",{children:[ be("div",{style:{fontWeight:500,fontSize:"14px"},children:re("promptsBackup")||"仅提示词"}), be("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:re("promptsBackupDesc")||"仅导出提示词数据"})]}), be("button",{onClick:()=>k("prompts"),className:"settings-btn settings-btn-primary",style:{padding:"6px 16px"},children:re("export")||"导出"})]}), ye("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"12px",background:"var(--gh-bg-secondary)",borderRadius:"8px"},children:[ ye("div",{children:[ be("div",{style:{fontWeight:500,fontSize:"14px"},children:re("settingsBackup")||"仅设置"}), be("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:re("settingsBackupDesc")||"仅导出配置项"})]}), be("button",{onClick:()=>k("settings"),className:"settings-btn settings-btn-secondary",style:{padding:"6px 16px"},children:re("export")||"导出"})]})]})}), be(Kf,{title:re("importData")||"导入数据",description:re("importDataDesc")||"从备份文件恢复数据",children:ye("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[ ye("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ be("div",{style:{fontSize:"14px",fontWeight:500},children:re("selectFile")||"选择文件"}), ye("button",{className:"settings-btn settings-btn-secondary",onClick:()=>l.current?.click(),style:{padding:"6px 12px"},children:[re("browse")||"浏览...", be("input",{ref:l,type:"file",accept:".json",style:{display:"none"},onChange:async e=>{const t=e.target.files?.[0];if(!t)return;const n=await t.text();d(n),l.current&&(l.current.value="");}})]})]}), ye("div",{style:{flex:1},children:[ be("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)",marginBottom:"4px"},children:re("dataPreview")||"数据预览 (可直接粘贴)"}), be("textarea",{className:"settings-input",value:c,onChange:e=>d(e.target.value),placeholder:re("pastePlaceholder")||"粘贴 JSON 数据...",style:{width:"100%",height:"120px",fontFamily:"monospace",fontSize:"12px",resize:"vertical"}})]}), be("button",{onClick:()=>{c.trim()?(async e=>{try{const n=JSON.parse(e),r=ub(n);if(!r.valid){const e=r.errorKeys.map(e=>re(e)||e).join(", ");return console.error("Backup validation failed:",r.errorKeys),void Oo(re("invalidBackupFile")||"无效的格式: "+e)}b({show:!0,title:re("importData")||"导入数据",message:ye("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[ be("div",{children:re("importConfirm")||"确定导入?"}), be("div",{style:{border:"1px solid var(--gh-border, #e5e7eb)",background:"var(--gh-hover, #f8fafc)",borderRadius:"8px",padding:"10px 12px"},children:ye("div",{style:{display:"grid",gridTemplateColumns:"72px 1fr",rowGap:"6px",columnGap:"10px",alignItems:"start"},children:[ be("div",{style:{color:"var(--gh-text-secondary, #6b7280)"},children:re("backupTime")||"备份时间"}), be("div",{style:{color:"var(--gh-text, #111827)",fontWeight:500},children:String(n.timestamp||"-")}), be("div",{style:{color:"var(--gh-text-secondary, #6b7280)"},children:re("backupType")||"类型"}), be("div",{style:{color:"var(--gh-text, #111827)",fontWeight:500},children:(t=n.type,"full"===t?re("fullBackup")||"完整备份":"prompts"===t?re("promptsBackup")||"仅提示词":"settings"===t?re("settingsBackup")||"仅设置":String(t||re("unknown")||"未知"))})]})}), be("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:re("openAiPagesWillRefresh")||"已打开的 AI 页面将被刷新。"})]}),danger:!0,onConfirm:async()=>{b(e=>({...e,show:!1}));try{const e={};Object.entries(n.data).forEach(([t,n])=>{if(null!=n)if(xr.includes(t)){let r=n;if(kr.includes(t))if("object"!=typeof n||Array.isArray(n))r="readingHistory"===t?{history:n}:{[t]:n};else {const e=n;r="conversations"===t&&void 0!==e.conversations?n:"readingHistory"!==t||void 0===e.history&&void 0===e.lastCleanupRun?"readingHistory"===t?{history:n}:{[t]:n}:n;}else r="prompts"===t&&Array.isArray(n)?{prompts:n}:"settings"!==t||n.settings?{[t]:n}:{settings:n};e[t]=JSON.stringify({state:r,version:0});}else e[t]="object"==typeof n?JSON.stringify(n):n;}),await w(e),await x(),Oo(re("importSuccess")||"导入成功"),setTimeout(()=>window.location.reload(),1e3);}catch(e){console.error("[Backup] import storage write failed:",e),Oo(`${re("importError")||"导入失败:"}${xb(e)}`);}}});}catch(n){console.error("[Backup] import parse failed:",n),Oo(`${re("importError")||"导入失败:"}${xb(n)}`);}var t;})(c):Oo("请先选择文件或粘贴内容");},className:"settings-btn settings-btn-primary",style:{width:"100%",justifyContent:"center",padding:"8px"},disabled:!c.trim(),children:re("importBtn")||"确认导入"})]})})]}), be(Kf,{title:re("voyagerImportTitle")||"从 Gemini Voyager 导入",description:re("voyagerImportDesc")||"导入文件夹整理结果,并增量合并到当前账号",style:{marginBottom:"24px"},children:ye("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:"20px",alignItems:"start"},children:[ ye("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[ be("div",{style:{fontSize:"12px",lineHeight:1.6,color:"var(--gh-text-secondary)",padding:"10px 12px",borderRadius:"8px",background:"var(--gh-bg-secondary)",border:"1px solid var(--gh-border, #e5e7eb)"},children:i?re("voyagerImportGeminiHint")||"仅支持 Gemini Voyager 的 `gemini-voyager.folders.v1` JSON。导入内容会自动归入当前打开的 Gemini 账号。":re("voyagerImportGeminiOnly")||"请在 Gemini 页面打开数据管理后再执行 Voyager 导入。"}), be("div",{style:{fontSize:"12px",lineHeight:1.6,color:"var(--gh-text-secondary)",padding:"10px 12px",borderRadius:"8px",background:"var(--gh-bg-secondary)",border:"1px solid var(--gh-border, #e5e7eb)"},children:re("voyagerImportMergeNotice")||"为避免覆盖现有整理结果,已在其他 Ophel 文件夹中的会话会保留原位;仅收件箱和已导入的 Voyager 文件夹会被重新归类。"}), be("div",{style:{fontSize:"12px",lineHeight:1.6,color:"var(--gh-text-secondary)",padding:"10px 12px",borderRadius:"8px",background:"var(--gh-bg-secondary)",border:"1px solid var(--gh-border, #e5e7eb)"},children:re("voyagerImportFlattenNotice")||"层级文件夹会压平成路径名称,例如“父级 / 子级”。"})]}), ye("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[ ye("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ be("div",{style:{fontSize:"14px",fontWeight:500},children:re("selectFile")||"选择文件"}), ye("button",{className:"settings-btn settings-btn-secondary",onClick:()=>u.current?.click(),style:{padding:"6px 12px"},disabled:!i,children:[re("browse")||"浏览...", be("input",{ref:u,type:"file",accept:".json",style:{display:"none"},onChange:async e=>{const t=e.target.files?.[0];if(!t)return;const n=await t.text();g(n),u.current&&(u.current.value="");}})]})]}), ye("div",{children:[ be("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)",marginBottom:"4px"},children:re("dataPreview")||"数据预览 (可直接粘贴)"}), be("textarea",{className:"settings-input",value:h,onChange:e=>g(e.target.value),placeholder:re("voyagerImportPlaceholder")||"粘贴 Gemini Voyager 导出的 JSON 内容,例如 gemini-voyager.folders.v1 ...",style:{width:"100%",height:"140px",fontFamily:"monospace",fontSize:"12px",resize:"vertical"},disabled:!i})]}), be("button",{onClick:()=>{if(h.trim())if(i)try{const e=(new ch).getCurrentCid(),t=(()=>{const e=window.location.pathname.match(/^\/u\/(\d+)(?:\/|$)/);return e?`/u/${e[1]}`:""})(),n=Ab(h,e,t),r=Wp.getState(),o=Tb(n,Zp.getState().folders,r.conversations,r.lastUsedFolderId);b({show:!0,title:re("voyagerImportTitle")||"从 Gemini Voyager 导入",message:ye("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[ be("div",{children:re("voyagerImportConfirm")||"确认将 Voyager 文件夹结构增量导入到当前 Gemini 账号?"}), be("div",{style:{border:"1px solid var(--gh-border, #e5e7eb)",background:"var(--gh-hover, #f8fafc)",borderRadius:"8px",padding:"10px 12px"},children:ye("div",{style:{display:"grid",gridTemplateColumns:"120px 1fr",rowGap:"6px",columnGap:"10px",alignItems:"start"},children:[ be("div",{style:{color:"var(--gh-text-secondary, #6b7280)"},children:re("voyagerImportVersion")||"Voyager 版本"}), be("div",{style:{color:"var(--gh-text, #111827)",fontWeight:500},children:o.sourceVersion}), be("div",{style:{color:"var(--gh-text-secondary, #6b7280)"},children:re("voyagerImportFolderCount")||"文件夹"}), be("div",{style:{color:"var(--gh-text, #111827)",fontWeight:500},children:o.stats.folderCount}), be("div",{style:{color:"var(--gh-text-secondary, #6b7280)"},children:re("voyagerImportConversationCount")||"会话"}), be("div",{style:{color:"var(--gh-text, #111827)",fontWeight:500},children:o.stats.conversationCount}), be("div",{style:{color:"var(--gh-text-secondary, #6b7280)"},children:re("voyagerImportNewFolders")||"新增文件夹"}), be("div",{style:{color:"var(--gh-text, #111827)",fontWeight:500},children:o.stats.foldersAdded}), be("div",{style:{color:"var(--gh-text-secondary, #6b7280)"},children:re("voyagerImportNewConversations")||"新增会话"}), be("div",{style:{color:"var(--gh-text, #111827)",fontWeight:500},children:o.stats.conversationsAdded}), be("div",{style:{color:"var(--gh-text-secondary, #6b7280)"},children:re("voyagerImportMovedConversations")||"移动会话"}), be("div",{style:{color:"var(--gh-text, #111827)",fontWeight:500},children:o.stats.conversationsMoved}), be("div",{style:{color:"var(--gh-text-secondary, #6b7280)"},children:re("voyagerImportPreservedConversations")||"保留原文件夹"}), be("div",{style:{color:"var(--gh-text, #111827)",fontWeight:500},children:o.stats.conversationsPreserved})]})}), be("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:re("voyagerImportFlattenNotice")||"层级文件夹会压平成路径名称,例如“父级 / 子级”。"}), be("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:re("voyagerImportMergeNotice")||"为避免覆盖现有整理结果,已在其他 Ophel 文件夹中的会话会保留原位;仅收件箱和已导入的 Voyager 文件夹会被重新归类。"})]}),onConfirm:async()=>{b(e=>({...e,show:!1}));try{await w({folders:JSON.stringify({state:{folders:o.nextFolders},version:0}),conversations:JSON.stringify({state:{conversations:o.nextConversations,lastUsedFolderId:o.lastUsedFolderId},version:0})}),await x(),Oo((re("voyagerImportSuccess")||"Voyager 导入完成:新增 {folders} 个文件夹,新增 {conversations} 个会话,移动 {moved} 个会话。").replace("{folders}",String(o.stats.foldersAdded)).replace("{conversations}",String(o.stats.conversationsAdded)).replace("{moved}",String(o.stats.conversationsMoved))),setTimeout(()=>window.location.reload(),1e3);}catch(e){console.error("[Backup] voyager import write failed:",e),Oo(`${re("importError")||"导入失败:"}${xb(e)}`);}}});}catch(e){console.error("[Backup] voyager import parse failed:",e),Oo(`${re("importError")||"导入失败:"}${xb(e)}`);}else Oo(re("voyagerImportGeminiOnly")||"请在 Gemini 页面打开数据管理后再执行 Voyager 导入");else Oo(re("voyagerImportPasteRequired")||"请先选择 Voyager 文件或粘贴 JSON 内容");},className:"settings-btn settings-btn-primary",style:{width:"100%",justifyContent:"center",padding:"8px"},disabled:!i||!h.trim(),children:re("voyagerImportAction")||"开始导入"})]})]})}), ye(Kf,{title:re("webdavConfig")||"WebDAV 备份与同步",description:re("webdavConfigDesc")||"配置 WebDAV 服务器以启用云端同步",children:[ ye("div",{style:{background:"var(--gh-primary-light-bg, rgba(66, 133, 244, 0.05))",border:"1px solid var(--gh-primary-border, rgba(66, 133, 244, 0.2))",borderRadius:"8px",padding:"12px",marginBottom:"20px",fontSize:"13px",color:"var(--gh-primary, #4285f4)"},children:[ ye("div",{style:{fontWeight:600,marginBottom:"4px"},children:["ℹ️ ",re("restoreTip")||"恢复提示"]}), be("div",{style:{lineHeight:1.5,opacity:.9},children:re("restoreTipContent")})]}), be(Zf,{label:re("webdavAddress")||"服务器地址",children:be("input",{type:"text",className:"settings-input",placeholder:"https://dav.example.com/dav/",value:p.url,onChange:e=>m({...p,url:e.target.value}),style:{width:"280px"}})}), be(Zf,{label:re("username")||"用户名",children:be("input",{type:"text",className:"settings-input",value:p.username,onChange:e=>m({...p,username:e.target.value}),style:{width:"280px"}})}), be(Zf,{label:re("password")||"密码",children:be("input",{type:"password",className:"settings-input",value:p.password,onChange:e=>m({...p,password:e.target.value}),style:{width:"280px"}})}), be(Zf,{label:re("defaultDir")||"默认目录",children:be("input",{type:"text",className:"settings-input",placeholder:"ophel",value:p.remoteDir,onChange:e=>m({...p,remoteDir:e.target.value}),style:{width:"280px"}})}), ye("div",{style:{marginTop:"16px",paddingTop:"16px",borderTop:"1px solid var(--gh-border)",display:"flex",gap:"12px",flexWrap:"wrap",alignItems:"center"},children:[ ye("button",{className:"settings-btn settings-btn-primary",onClick:()=>{const e=n.webdav??bo.webdav;r({webdav:{...e,...p}}),Oo(re("saveSuccess")||"配置已保存");},style:{padding:"6px 20px"},children:["💾 ",re("saveConfig")||"保存配置"]}), be("div",{style:{width:"1px",height:"20px",background:"var(--gh-border)",margin:"0 8px"}}), ye("button",{className:"settings-btn settings-btn-secondary",onClick:async()=>{await S(async()=>{const e=fb();await e.setConfig(p,!1);const t=await e.testConnection();t.success?Oo(re("webdavConnectionSuccess")||"连接成功"):Oo(re("webdavConnectionFailed")||"连接失败: "+t.messageKey);});},children:["🔗 ",re("webdavTestBtn")||"测试连接"]}), ye("button",{className:"settings-btn settings-btn-secondary",onClick:async()=>{await S(async()=>{const e=fb();await e.setConfig(p,!1),s(!0);});},children:["📂 ",re("restore")||"恢复/下载"]}), ye("button",{className:"settings-btn settings-btn-success",onClick:async()=>{await S(async()=>{const e=fb();await e.setConfig(p,!1);const t=await e.upload();t.success?Oo(re("webdavUploadSuccess")||"备份上传成功"):Oo(re("webdavUploadFailed")||"上传失败: "+t.messageKey);});},style:{marginLeft:"auto"},children:["☁️ ",re("backupNow")||"立即上传备份"]})]})]}), be(Kf,{title:re("dangerZone")||"危险区域",description:re("dangerZoneDesc")||"破坏性操作(不可恢复)",className:"danger-zone-card",children:ye("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ ye("div",{children:[ be("div",{style:{fontSize:"14px",fontWeight:500,color:"var(--gh-danger, #ef4444)"},children:re("clearAllData")||"清除全部数据"}), be("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:re("clearAllDataDesc")||"慎重操作:这将清除本地所有设置、提示词和会话数据"})]}), be("button",{className:"settings-btn settings-btn-danger",onClick:()=>{b({show:true,title:re("clearAllData")||"清除全部数据",message:re("clearAllDataConfirm")||"确定要清除所有数据吗?此操作不可逆,所有设置、提示词、会话等数据都将被删除!",danger:true,onConfirm:async()=>{b(e=>({...e,show:false}));try{if("extension"===xu.type&&"undefined"!=typeof chrome)try{await chrome.runtime.sendMessage({type:Iu});}catch{}await Promise.all([new Promise((e,t)=>chrome.storage.local.clear(()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e())),new Promise((e,t)=>chrome.storage.sync.clear(()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e()))]),await new Promise((e,t)=>chrome.storage.local.set({[uo]:Date.now()},()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e())),o(),um.getState().setPrompts(Sr()),Zp.setState({folders:Cr}),Xp.setState({tags:[]}),Wp.setState({conversations:{},lastUsedFolderId:"inbox"}),bb.setState({history:{},lastCleanupRun:0}),Oo(re("clearSuccess")||"数据已清除,即将刷新..."),setTimeout(()=>window.location.reload(),1500);}catch(e){Oo(re("error")+": "+String(e));}}});},style:{padding:"8px 16px",fontSize:"13px"},children:re("clearAllData")||"清除全部数据"})]})})]})},Nb="ophel:usageMonitor",Lb={version:2,records:{},events:[]},Db=(e,t=0)=>Number.isFinite(e)?Math.max(0,Math.floor(e)):t,Rb=e=>{const t=Date.now();return e?{count:Db(e.count),updatedAt:Db(e.updatedAt,t),resetAt:Db(e.resetAt,t)}:{count:0,updatedAt:t,resetAt:t}},qb=e=>{if(!e||"object"!=typeof e)return null;const t=Db(e.ts,Date.now());return {id:"string"==typeof e.id&&e.id?e.id:`${t}-${Math.random().toString(36).slice(2,8)}`,ts:t,siteId:"string"==typeof e.siteId&&e.siteId?e.siteId:"_default",cid:"string"==typeof e.cid&&e.cid?e.cid:"default",sessionId:"string"==typeof e.sessionId?e.sessionId:"",countDelta:Db(e.countDelta,1)||1,requestTokens:Db(e.requestTokens),roundTripTokens:Db(e.roundTripTokens),loadedConversationTokens:Db(e.loadedConversationTokens),loadedOutputTokens:Db(e.loadedOutputTokens)}},Pb=e=>{const t=Date.now();return e.filter(e=>t-e.ts<=3456e7).sort((e,t)=>e.ts-t.ts).slice(-4e3)},Bb=e=>{if(!e||"object"!=typeof e)return {...Lb};const t=Array.isArray(e.events)?e.events:[];return {version:2,records:e.records&&"object"==typeof e.records?e.records:{},events:Pb(t.map(e=>qb(e)).filter(Boolean))}};async function Ob(){const e=await xu.storage.get(Nb);return Bb(e)}async function zb(e){await xu.storage.set(Nb,Bb(e));}const Fb=e=>{const t=new Date(e);return t.setMinutes(0,0,0),t},jb=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t},$b=e=>{const t=new Date(e);return t.setDate(1),t.setHours(0,0,0,0),t},Hb=e=>`${`${e.getHours()}`.padStart(2,"0")}:00`,Ub=e=>`${e.getMonth()+1}/${e.getDate()}`,Wb=e=>`${e.getFullYear()}/${`${e.getMonth()+1}`.padStart(2,"0")}`,Vb=(e,t)=>{switch(t){case "requestTokens":return e.requestTokens;case "roundTripTokens":return e.roundTripTokens;case "loadedConversationTokens":return e.loadedConversationTokens;case "loadedOutputTokens":return e.loadedOutputTokens;default:return e.count}};function Gb(e){return xu.storage.watch(Nb,(t,n)=>{e(Bb(t),Bb(n));})}const Qb=({value:e,onChange:t,placeholder:n,className:r,style:i})=>{const[a,s]=B(e);o.useEffect(()=>{s(e);},[e]);const l=()=>{a!==e&&t(a);}; return be("input",{type:"text",className:r,value:a,onChange:e=>s(e.target.value),onBlur:l,onKeyDown:e=>{"Enter"===e.key&&(l(),e.target.blur());},placeholder:n,style:i})},Kb=({siteId:e})=>{const[t,n]=B("day"),[r,i]=B("requestTokens"),[a,s]=B("_default"===e?"all":e),[l,c]=B([]),[d,u]=B(true),[h,g]=B(null),p=o.useRef(null),m=o.useMemo(()=>[{id:"all",label:re("usageMonitorChartSiteAll")||"全部站点"},{id:Ir,label:"Gemini"},{id:Dr,label:"Gemini Enterprise"},{id:Nr,label:"ChatGPT"},{id:Mr,label:"Claude"},{id:Rr,label:"Grok"},{id:qr,label:"AI Studio"},{id:Or,label:"DeepSeek"},{id:Pr,label:"Doubao"},{id:Br,label:"ima"},{id:Lr,label:"ChatGLM"},{id:zr,label:"Kimi"},{id:Fr,label:"Qianwen"},{id:jr,label:"QwenAI"},{id:Hr,label:"Z.ai"}],[]),f=m.find(e=>e.id===a)?.label||re("usageMonitorChartSiteAll")||"全部站点",b=o.useCallback(async()=>{u(true);try{const e=await async function(e){return (await Ob()).events.filter(t=>!(e?.siteId&&"_default"!==e.siteId&&t.siteId!==e.siteId||e?.cid&&t.cid!==e.cid))}({siteId:"all"===a?void 0:a});c(function(e,t,n=new Date){const r="hour"===t?24:"day"===t?30:12,o=[],i=new Map;for(let a=r-1;a>=0;a--){const e=new Date(n);let r,s,l;"hour"===t?(e.setHours(e.getHours()-a),r=Fb(e),s=`${r.getFullYear()}-${r.getMonth()}-${r.getDate()}-${r.getHours()}`,l=Hb(r)):"day"===t?(e.setDate(e.getDate()-a),r=jb(e),s=`${r.getFullYear()}-${r.getMonth()}-${r.getDate()}`,l=Ub(r)):(e.setMonth(e.getMonth()-a),r=$b(e),s=`${r.getFullYear()}-${r.getMonth()}`,l=Wb(r));const c={key:s,label:l,startAt:r.getTime(),endAt:"hour"===t?r.getTime()+36e5:"day"===t?r.getTime()+864e5:new Date(r.getFullYear(),r.getMonth()+1,1).getTime(),count:0,requestTokens:0,roundTripTokens:0,loadedConversationTokens:0,loadedOutputTokens:0,maxLoadedConversationTokens:0,maxRequestTokens:0,maxRoundTripTokens:0,maxLoadedOutputTokens:0};o.push(c),i.set(s,c);}return e.forEach(e=>{const n=new Date(e.ts),r="hour"===t?`${n.getFullYear()}-${n.getMonth()}-${n.getDate()}-${n.getHours()}`:"day"===t?`${n.getFullYear()}-${n.getMonth()}-${n.getDate()}`:`${n.getFullYear()}-${n.getMonth()}`,o=i.get(r);o&&(o.count+=e.countDelta,o.requestTokens+=e.requestTokens,o.roundTripTokens+=e.roundTripTokens,o.loadedConversationTokens+=e.loadedConversationTokens,o.loadedOutputTokens+=e.loadedOutputTokens,o.maxLoadedConversationTokens=Math.max(o.maxLoadedConversationTokens,e.loadedConversationTokens),o.maxRequestTokens=Math.max(o.maxRequestTokens,e.requestTokens),o.maxRoundTripTokens=Math.max(o.maxRoundTripTokens,e.roundTripTokens),o.maxLoadedOutputTokens=Math.max(o.maxLoadedOutputTokens,e.loadedOutputTokens));}),o}(e,t));}finally{u(false);}},[t,a]);M(()=>{b();},[b]),M(()=>{const e=Gb(()=>{b();});return ()=>e()},[b]),M(()=>{if(!p.current)return;const e=p.current,t=()=>{e.scrollLeft=e.scrollWidth;};t();const n=window.requestAnimationFrame(t);return ()=>window.cancelAnimationFrame(n)},[t,l.length]);const y=l.map(e=>Vb(e,r)),v=Math.max(1,...y),w=y[y.length-1]??0,x="requestTokens"===r?re("usageMonitorChartMetricRequest")||"请求 Tokens":"roundTripTokens"===r?re("usageMonitorChartMetricRoundTrip")||"往返 Tokens":"loadedConversationTokens"===r?re("usageMonitorChartMetricConversation")||"已加载对话 Tokens":"loadedOutputTokens"===r?re("usageMonitorChartMetricOutput")||"输出 Tokens":re("usageMonitorChartMetricCount")||"次数",k="month"===t?72:"hour"===t?48:44,S=l.length>1?Math.max(640,40+(l.length-1)*k+48):640,C=16,E=12,_=18,A=S-_-E,T=220-C-32,I=l.length>1?A/(l.length-1):A,N="month"===t?1:"hour"===t?2:Math.max(2,Math.ceil(l.length/10)),L=l.map((e,t)=>{const n=_+I*t,o=Vb(e,r);return {x:n,y:C+T-o/v*T,value:o,label:e.label}}),D=L.length>0?L.map((e,t)=>`${0===t?"M":"L"} ${e.x.toFixed(2)} ${e.y.toFixed(2)}`).join(" "):"",R=L.length>0?`${D} L ${L[L.length-1].x.toFixed(2)} ${(C+T).toFixed(2)} L ${L[0].x.toFixed(2)} ${(C+T).toFixed(2)} Z`:"",q=null!==h&&h>=0&&h=0&&h0&&h-1$?Math.min(H-$-8,Math.max(8,P.x-U-110)):8,V=P&&P.y>110?Math.max(8,P.y-94):8,G="var(--gh-border, #e5e7eb)",Q="var(--gh-user-query-bg, rgba(66, 133, 244, 0.08))",K="var(--gh-primary, #4285f4)",Z="var(--gh-border-active, #6366f1)",Y="var(--gh-text-secondary, #6b7280)",J="var(--gh-text, #374151)",X="var(--gh-card-bg, #ffffff)",ee="var(--gh-border, #e5e7eb)",te="var(--gh-border-active, #6366f1)",ne="var(--gh-shadow-sm, 0 1px 3px rgba(0,0,0,0.1))"; return ye("div",{style:{marginTop:"14px",padding:"14px",borderRadius:"12px",border:`1px solid ${ee}`,background:"var(--gh-bg-secondary, #f9fafb)"},children:[ ye("div",{style:{display:"flex",justifyContent:"space-between",gap:"12px",flexWrap:"wrap"},children:[ ye("div",{children:[ be("div",{style:{fontSize:"14px",fontWeight:600,color:"var(--gh-text, #374151)"},children:re("usageMonitorChartTitle")||"历史统计曲线"}), be("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)",marginTop:"4px"},children:re("usageMonitorChartDesc")||"基于本地记录的发送事件聚合,可按小时、天、月查看次数或粗估 Tokens。"}), ye("div",{style:{marginTop:"8px",display:"inline-flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[ be("span",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:re("usageMonitorChartSiteLabel")||"统计站点"}), be("select",{className:"settings-select",value:a,onChange:e=>s(e.target.value),style:{minWidth:"170px"},children:m.map(e=>be("option",{value:e.id,children:e.label},e.id))})]})]}), ye("div",{style:{display:"flex",gap:"8px",flexWrap:"wrap",alignItems:"flex-start"},children:[ be("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap"},children:[["hour",re("usageMonitorChartHour")||"小时"],["day",re("usageMonitorChartDay")||"天"],["month",re("usageMonitorChartMonth")||"月"]].map(([e,r])=>be(cf,{size:"sm",variant:t===e?"primary":"secondary",onClick:()=>n(e),children:r},e))}), be("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap"},children:[["count",re("usageMonitorChartMetricCount")||"次数"],["requestTokens",re("usageMonitorChartMetricRequest")||"请求 Tokens"],["roundTripTokens",re("usageMonitorChartMetricRoundTrip")||"往返 Tokens"],["loadedConversationTokens",re("usageMonitorChartMetricConversation")||"已加载对话 Tokens"],["loadedOutputTokens",re("usageMonitorChartMetricOutput")||"输出 Tokens"]].map(([e,t])=>be(cf,{size:"sm",variant:r===e?"primary":"secondary",onClick:()=>i(e),children:t},e))})]})]}), ye("div",{style:{display:"flex",gap:"18px",marginTop:"12px",marginBottom:"8px",flexWrap:"wrap"},children:[ ye("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:[ ye("span",{children:[x,": "]}), be("strong",{style:{color:"var(--gh-text, #374151)"},children:w})]}), ye("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:[ ye("span",{children:[re("usageMonitorChartCurrentSite")||"当前统计站点",": "]}), be("strong",{style:{color:"var(--gh-text, #374151)"},children:f})]}), ye("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:[ be("span",{children:"MAX: "}), be("strong",{style:{color:"var(--gh-text, #374151)"},children:v})]}), be("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:be("span",{children:re("usageMonitorChartScrollHint")||"可左右滚动查看完整时间轴"})})]}), ye("div",{style:{position:"relative",marginTop:"4px"},onMouseLeave:()=>g(null),children:[ ye("div",{ref:p,style:{position:"relative",borderRadius:"10px",overflowX:"auto",overflowY:"hidden",background:X,border:`1px solid ${ee}`,minHeight:"220px"},children:[ be("div",{style:{width:`${S}px`,minWidth:"100%",position:"relative"},children:ye("svg",{viewBox:`0 0 ${S} 220`,style:{width:"100%",height:"220px",display:"block"},children:[[0,.25,.5,.75,1].map(e=>{const t=C+T-T*e; return be("line",{x1:_,x2:S-E,y1:t,y2:t,stroke:G,strokeWidth:"1",opacity:.6},e)}),R&&be("path",{d:R,fill:Q}),D&&be("path",{d:D,fill:"none",stroke:K,strokeWidth:"2.5",strokeLinejoin:"round",strokeLinecap:"round"}),L.map(e=>be("circle",{cx:e.x,cy:e.y,r:"3",fill:K},`${e.label}-${e.x}`)),P&&be("line",{x1:P.x,x2:P.x,y1:C,y2:C+T,stroke:Z,strokeDasharray:"4 4",strokeWidth:"1",opacity:.65}),l.map((e,t)=>{const n=L[t],r=L[t-1],o=L[t+1],i=r?(r.x+n.x)/2:_,a=o?(n.x+o.x)/2:S-E; return be("rect",{x:i,y:C,width:Math.max(12,a-i),height:T,fill:"transparent",pointerEvents:"all",onMouseEnter:()=>g(t),onMouseMove:()=>g(t)},`${e.key}-hover`)}),l.map((e,t)=>{if(!(0===t||t===l.length-1||t%N===0))return null; return be("text",{x:_+I*t,y:210,textAnchor:"middle",fill:Y,fontSize:"11",children:e.label},e.key)})]})}),!d&&l.every(e=>0===Vb(e,r))&&be("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:Y,fontSize:"13px"},children:re("usageMonitorChartEmpty")||"暂无统计数据"})]}),q&&P&&ye("div",{style:{position:"absolute",left:`${W}px`,top:`${V}px`,width:"220px",borderRadius:"10px",padding:"10px 12px",background:X,color:J,border:`1px solid ${te}`,boxShadow:ne,pointerEvents:"none",zIndex:5},children:[ be("div",{style:{fontSize:"12px",fontWeight:700,marginBottom:"8px"},children:(e=>{const n=new Date(e.startAt),r=new Date(e.endAt-1);if("hour"===t){return `${`${n.getFullYear()}/${`${n.getMonth()+1}`.padStart(2,"0")}/${`${n.getDate()}`.padStart(2,"0")}`} ${`${n.getHours()}`.padStart(2,"0")}:00 - ${`${r.getHours()}`.padStart(2,"0")}:59`}return "day"===t?`${n.getFullYear()}/${`${n.getMonth()+1}`.padStart(2,"0")}/${`${n.getDate()}`.padStart(2,"0")}`:`${n.getFullYear()}/${`${n.getMonth()+1}`.padStart(2,"0")}`})(q)}),null!==j&&ye("div",{style:{fontSize:"11px",marginBottom:"8px",color:"var(--gh-text-secondary, #6b7280)"},children:[x,": ",z," · ",j>=0?"+":"",j," ",re("usageMonitorChartDelta")||"较上一桶"]}), ye("div",{style:{display:"grid",gridTemplateColumns:"1fr auto",gap:"6px 10px",fontSize:"12px"},children:[ be("span",{style:{color:Y},children:re("usageMonitorChartMetricCount")||"次数"}), be("strong",{children:q.count}), be("span",{style:{color:Y},children:re("usageMonitorChartMetricRequest")||"请求 Tokens"}), be("strong",{children:q.requestTokens}), be("span",{style:{color:Y},children:re("usageMonitorChartMetricRoundTrip")||"往返 Tokens"}), be("strong",{children:q.roundTripTokens}), be("span",{style:{color:Y},children:re("usageMonitorChartMetricConversation")||"已加载对话 Tokens"}), be("strong",{children:q.loadedConversationTokens}), be("span",{style:{color:Y},children:re("usageMonitorChartMetricOutput")||"输出 Tokens"}), be("strong",{children:q.loadedOutputTokens}), be("span",{style:{color:Y},children:re("usageMonitorChartMaxConversation")||"最大单次已加载对话"}), be("strong",{children:q.maxLoadedConversationTokens}), be("span",{style:{color:Y},children:re("usageMonitorChartMaxRequest")||"最大单次请求"}), be("strong",{children:q.maxRequestTokens}), be("span",{style:{color:Y},children:re("usageMonitorChartMaxRoundTrip")||"最大单次往返"}), be("strong",{children:q.maxRoundTripTokens}), be("span",{style:{color:Y},children:re("usageMonitorChartMaxOutput")||"最大单次输出"}), be("strong",{children:q.maxLoadedOutputTokens})]})]})]})]})},Zb=({siteId:e,initialTab:t})=>{const n=[{id:Hn,label:re("tabOutline")||"大纲"},{id:Un,label:re("tabConversations")||"会话"},{id:Wn,label:re("tabPrompts")||"Prompts"},{id:Vn,label:re("tabSettingsTab")||"标签页"},{id:Gn,label:re("reminderTab")||"提醒"},{id:Qn,label:re("navContent")||"内容交互"},{id:Kn,label:re("readingHistoryTitle")||"阅读历史"}],[r,i]=B(t||n[0].id),[a,s]=B(false),l=o.useRef(null),{settings:c,updateDeepSetting:d,updateNestedSetting:u}=No(),h=E(()=>{l.current&&(l.current.onended=null,l.current.onerror=null);},[]),g=E(()=>{const e=l.current;e?(h(),e.pause(),e.currentTime=0,s(false)):s(false);},[h]);if(M(()=>{t&&i(t);},[t]),M(()=>()=>{g();},[g]),M(()=>{r!==Gn&&g();},[r,g]),M(()=>{c?.tab?.showNotification&&c.tab.notificationSound||g();},[c?.tab?.notificationSound,c?.tab?.showNotification,g]),M(()=>{const e=l.current;if(!e||!a)return;const t=c?.tab?.notificationVolume??.5;e.volume=Math.max(.1,Math.min(1,t));},[a,c?.tab?.notificationVolume]),!c)return null;const p=re("enablePrerequisiteToast")||"请先开启「{setting}」",m=e=>zo(p.replace("{setting}",e),2e3,{},1500,e),f=re("autoRenameTabLabel")||"自动重命名",b=re("showNotificationLabel")||"桌面通知",y=re("privacyModeLabel")||"隐私模式",v=re("readingHistoryPersistenceLabel")||"启用阅读历史",w=re("formulaCopyLabel")||"双击复制公式",x=wr.length>1,k=e=>re("secondsValueLabel",{val:String(e)})||`${e} 秒`,S=e=>`${e}x`,C=re("notificationSoundPreviewButtonLabel")||"试听",_=e=>{const t=e||c.tab?.notificationSoundPreset||wr[0].id,n=xu.getNotificationSoundUrl(t);if(!n)return void Oo(re("notificationSoundPreviewFailed")||"提示音试听失败",2e3);g();let r=l.current;r||(r=new Audio,l.current=r);const o=c.tab?.notificationVolume??.5;r.volume=Math.max(.1,Math.min(1,o)),r.src=n,r.currentTime=0,r.onended=()=>{h(),s(false);},r.onerror=()=>{h(),s(false),Oo(re("notificationSoundPreviewFailed")||"提示音试听失败",2e3);},s(true),r.play().catch(()=>{h(),s(false),Oo(re("notificationSoundPreviewFailed")||"提示音试听失败",2e3);});},A=ye(Kf,{title:re("notificationSettings")||"完成后操作",children:[ be(Yf,{label:re("showNotificationLabel")||"桌面通知",description:re("showNotificationDesc")||"生成完成时发送桌面通知",settingId:"tab-show-notification",checked:c.tab?.showNotification??false,onChange:async()=>{const e=c.tab?.showNotification;if(e)u("tab","showNotification",false);else {if(!xu.hasCapability("permissions"))return void u("tab","showNotification",true);const e=await Lu({type:Tu,permissions:["notifications"]});e.success&&e.hasPermission?u("tab","showNotification",true):(await Lu({type:Mu,permType:"notifications"}),Oo(re("permissionRequestToast")||"请在弹出的窗口中授予权限",3e3));}}}), be(Yf,{label:re("notificationSoundLabel")||"通知声音",description:re("notificationSoundDesc")||"生成完成时播放提示音",settingId:"tab-notification-sound",checked:c.tab?.notificationSound??false,disabled:!c.tab?.showNotification,onDisabledClick:()=>m(b),onChange:()=>u("tab","notificationSound",!c.tab?.notificationSound)}),x&&be(Zf,{label:re("notificationSoundPresetLabel")||"提示音预设",settingId:"tab-notification-sound-preset",disabled:!c.tab?.showNotification||!c.tab?.notificationSound,onDisabledClick:()=>m(b),children:ye("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ be("select",{className:"settings-select",value:c.tab?.notificationSoundPreset||wr[0].id,onChange:e=>{const t=e.target.value;u("tab","notificationSoundPreset",t),_(t);},disabled:!c.tab?.showNotification||!c.tab?.notificationSound,style:{flex:1},children:wr.map(e=>be("option",{value:e.id,children:re(e.labelKey)||e.fallback},e.id))}), be(cf,{type:"button",variant:a?"primary":"secondary",size:"sm",onClick:()=>_(),disabled:!c.tab?.showNotification||!c.tab?.notificationSound,style:{minWidth:"56px",flexShrink:0},children:C})]})}), be(Zf,{label:re("notificationVolumeLabel")||"声音音量",settingId:"tab-notification-volume",disabled:!c.tab?.showNotification||!c.tab?.notificationSound,onDisabledClick:()=>m(b),children:ye("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ be("input",{type:"range",min:"0.1",max:"1.0",step:"0.1",value:c.tab?.notificationVolume||.5,onChange:e=>u("tab","notificationVolume",parseFloat(e.target.value)),disabled:!c.tab?.showNotification||!c.tab?.notificationSound,style:{width:"100px"}}), ye("span",{style:{fontSize:"12px",minWidth:"36px"},children:[Math.round(100*(c.tab?.notificationVolume||.5)),"%"]})]})}), be(Zf,{label:re("notificationRepeatCountLabel")||"播放次数",settingId:"tab-notification-repeat-count",disabled:!c.tab?.showNotification||!c.tab?.notificationSound,onDisabledClick:()=>m(b),children:be("select",{className:"settings-select",value:c.tab?.notificationRepeatCount??1,onChange:e=>u("tab","notificationRepeatCount",parseInt(e.target.value)),disabled:!c.tab?.showNotification||!c.tab?.notificationSound,children:[1,2,3,5].map(e=>be("option",{value:e,children:S(e)},e))})}), be(Zf,{label:re("notificationRepeatIntervalLabel")||"播放间隔",settingId:"tab-notification-repeat-interval",disabled:!c.tab?.showNotification||!c.tab?.notificationSound,onDisabledClick:()=>m(b),children:be("select",{className:"settings-select",value:c.tab?.notificationRepeatInterval??3,onChange:e=>u("tab","notificationRepeatInterval",parseInt(e.target.value)),disabled:!c.tab?.showNotification||!c.tab?.notificationSound,children:[1,2,3,5,10].map(e=>be("option",{value:e,children:k(e)},e))})}), be(Yf,{label:re("notifyWhenFocusedLabel")||"前台时也通知",description:re("notifyWhenFocusedDesc")||"窗口在前台时也发送通知",settingId:"tab-notify-when-focused",checked:c.tab?.notifyWhenFocused??false,disabled:!c.tab?.showNotification,onDisabledClick:()=>m(b),onChange:()=>u("tab","notifyWhenFocused",!c.tab?.notifyWhenFocused)}), be(Yf,{label:re("autoFocusLabel")||"自动置顶窗口",description:re("autoFocusDesc")||"生成完成后自动激活窗口",settingId:"tab-auto-focus",checked:c.tab?.autoFocus??false,onChange:()=>u("tab","autoFocus",!c.tab?.autoFocus)})]}),T=ye(Kf,{title:re("usageMonitorSettingsTitle")||"高级模型本地计数与预估",description:re("usageMonitorSettingsDesc")||"在输入框附近显示本地发送计数、阈值进度和粗略 Token 预估,不影响站点原有发送逻辑",children:[ ye("div",{style:{marginBottom:"12px",padding:"10px 12px",borderRadius:"10px",border:"1px solid var(--gh-border, #e5e7eb)",background:"var(--gh-bg-secondary, #f9fafb)",color:"var(--gh-text-secondary, #6b7280)",fontSize:"12px",lineHeight:1.6},children:[ be("div",{children:re("usageMonitorExplainLocalOnly")||"说明:这是纯本地估算能力。插件不会读取官方剩余额度,也不会知道服务端真实剩余次数。"}), be("div",{children:re("usageMonitorExplainNoBackend")||"行为:仅在本地存储里记录计数,并在页面输入区附近展示面板;不会额外改写站点后端状态。"}), be("div",{children:re("usageMonitorExplainReset")||"归零:平台实际额度重置时间可能不是固定 00:00。自动归零默认关闭,建议在平台真实重置后手动清零校准。"})]}), be(Yf,{label:re("usageMonitorEnabledLabel")||"启用高级模型对话本地计数与预估",description:re("usageMonitorEnabledDesc")||"通过本地计数和输入框附近的轻量面板,辅助估算当日使用情况",settingId:"usage-monitor-enabled",checked:c.usageMonitor?.enabled??false,onChange:()=>u("usageMonitor","enabled",!c.usageMonitor?.enabled)}), be("div",{style:{marginTop:"-2px",marginBottom:"12px",padding:"10px 12px",borderRadius:"10px",border:"1px solid var(--gh-border-active, #6366f1)",background:"var(--gh-user-query-bg, rgba(66, 133, 244, 0.08))",color:"var(--gh-text, #374151)",fontSize:"12px",lineHeight:1.55},children:re("usageMonitorExplainRender")||"面板会显示在当前输入区上方并为正文预留空间;如果开启后出现渲染异常,请刷新页面即可。"}), be(Zf,{label:re("usageMonitorDailyLimitLabel")||"每日对话次数预估上限",description:re("usageMonitorDailyLimitDesc")||"用于计算 80% / 100% 阈值提醒,仅为本地估算值",settingId:"usage-monitor-daily-limit",disabled:!c.usageMonitor?.enabled,onDisabledClick:()=>m(re("usageMonitorEnabledLabel")||"启用高级模型对话本地计数与预估"),children:be(df,{value:c.usageMonitor?.dailyLimit??100,onChange:e=>u("usageMonitor","dailyLimit",e),min:1,max:9999,defaultValue:100,disabled:!c.usageMonitor?.enabled,style:{width:"96px"}})}), be(Yf,{label:re("usageMonitorAutoResetLabel")||"启用自动归零",description:re("usageMonitorAutoResetDesc")||"实验性:按本地日期切换自动归零。由于平台实际重置时间可能变化,默认关闭。",settingId:"usage-monitor-auto-reset",checked:c.usageMonitor?.autoResetEnabled??false,disabled:!c.usageMonitor?.enabled,onDisabledClick:()=>m(re("usageMonitorEnabledLabel")||"启用高级模型对话本地计数与预估"),onChange:()=>u("usageMonitor","autoResetEnabled",!c.usageMonitor?.autoResetEnabled)}), be(Kb,{siteId:e})]}); return ye("div",{children:[ be(Xf,{title:re("navFeatures")||"功能模块",Icon:He}), be("p",{className:"settings-page-desc",children:re("featuresPageDesc")||"配置扩展的各项功能模块"}), be(Jf,{tabs:n,activeTab:r,onTabChange:i}),r===Vn&&ye(fe,{children:[ ye(Kf,{title:re("tabBehaviorTitle")||"标签页行为",children:[ be(Yf,{label:re("openNewTabLabel")||"新标签页打开",description:re("openNewTabDesc")||"在新标签页中打开新对话",settingId:"tab-open-new",checked:c.tab?.openInNewTab??true,onChange:()=>u("tab","openInNewTab",!c.tab?.openInNewTab)}), be(Yf,{label:re("autoRenameTabLabel")||"自动重命名",description:re("autoRenameTabDesc")||"根据对话内容自动更新标签页标题",settingId:"tab-auto-rename",checked:c.tab?.autoRename??false,onChange:()=>u("tab","autoRename",!c.tab?.autoRename)}), be(Zf,{label:re("renameIntervalLabel")||"检测频率",settingId:"tab-rename-interval",disabled:!c.tab?.autoRename,onDisabledClick:()=>m(f),children:be("select",{className:"settings-select",value:c.tab?.renameInterval||3,onChange:e=>u("tab","renameInterval",parseInt(e.target.value)),disabled:!c.tab?.autoRename,children:[1,3,5,10,30,60].map(e=>be("option",{value:e,children:k(e)},e))})}), be(Zf,{label:re("titleFormatLabel")||"标题格式",description:re("titleFormatDesc")||"支持占位符:{status}、{title}、{model}",settingId:"tab-title-format",disabled:!c.tab?.autoRename,onDisabledClick:()=>m(f),children:be("input",{type:"text",className:"settings-input",value:c.tab?.titleFormat||"{status}{title}",onChange:e=>u("tab","titleFormat",e.target.value),placeholder:"{status}{title}",disabled:!c.tab?.autoRename,style:{width:"180px"}})}), be(Yf,{label:re("showStatusLabel")||"显示生成状态",description:re("showStatusDesc")||"在标签页标题中显示生成状态",settingId:"tab-show-status",checked:c.tab?.showStatus??true,onChange:()=>u("tab","showStatus",!c.tab?.showStatus)})]}), ye(Kf,{title:re("privacyModeTitle")||"隐私模式",children:[ be(Yf,{label:re("privacyModeLabel")||"启用隐私模式",description:re("privacyModeDesc")||"使用伪装标题隐藏真实内容",settingId:"tab-privacy-mode",checked:c.tab?.privacyMode??false,onChange:()=>u("tab","privacyMode",!c.tab?.privacyMode)}), be(Zf,{label:re("privacyTitleLabel")||"伪装标题",settingId:"tab-privacy-title",disabled:!c.tab?.privacyMode,onDisabledClick:()=>m(y),children:be("input",{type:"text",className:"settings-input",value:c.tab?.privacyTitle||"Google",onChange:e=>u("tab","privacyTitle",e.target.value),placeholder:"Google",disabled:!c.tab?.privacyMode,style:{width:"180px"}})})]})]}),r===Gn&&ye(fe,{children:[A,T]}),r===Hn&&ye(fe,{children:[ ye(Kf,{title:re("outlineSettings")||"大纲设置",description:re("outlineSettingsDesc")||"配置大纲生成和跟随行为",children:[ be(Yf,{label:re("outlineAutoUpdateLabel")||"自动更新",description:re("outlineAutoUpdateDesc")||"在对话进行时自动刷新大纲",settingId:"outline-auto-update",checked:c.features?.outline?.autoUpdate??true,onChange:()=>d("features","outline","autoUpdate",!c.features?.outline?.autoUpdate)}), be(Zf,{label:re("outlineUpdateIntervalLabel")||"更新检测间隔",description:re("outlineUpdateIntervalDesc")||"大纲自动更新的时间间隔(秒)",settingId:"outline-update-interval",children:be(df,{value:c.features?.outline?.updateInterval??2,onChange:e=>d("features","outline","updateInterval",e),min:1,max:60,defaultValue:2,style:{width:"80px"}})}), be(Zf,{label:re("outlineFollowModeLabel")||"大纲跟随模式",description:"current"===c.features?.outline?.followMode?re("outlineFollowCurrentDesc")||"滚动页面时自动定位高亮大纲项":"latest"===c.features?.outline?.followMode?re("outlineFollowLatestDesc")||"大纲始终自动滚动到底部":re("outlineFollowManualDesc")||"不自动滚动大纲",settingId:"outline-follow-mode",children:ye("select",{className:"settings-select",value:c.features?.outline?.followMode||"current",onChange:e=>d("features","outline","followMode",e.target.value),children:[ be("option",{value:"current",children:re("outlineFollowCurrent")||"跟随当前位置"}), be("option",{value:"latest",children:re("outlineFollowLatest")||"跟随最新消息"}), be("option",{value:"manual",children:re("outlineFollowManual")||"手动控制"})]})}), be(Yf,{label:re("outlineShowWordCountLabel")||"悬浮显示字数",description:re("outlineShowWordCountDesc")||"在大纲悬浮提示中显示该章节的字数",settingId:"outline-show-word-count",checked:c.features?.outline?.showWordCount??false,onChange:()=>d("features","outline","showWordCount",!c.features?.outline?.showWordCount)})]}), ye(Kf,{title:re("bookmarkSettings")||"收藏",description:re("bookmarkSettingsDesc")||"配置页内收藏功能",children:[ be(Zf,{label:re("inlineBookmarkModeLabel")||"页内收藏图标",description:re("inlineBookmarkModeDesc")||"控制页面标题旁的收藏图标显示方式",settingId:"outline-inline-bookmark-mode",children:ye("select",{className:"settings-select",value:c.features?.outline?.inlineBookmarkMode||"always",onChange:e=>d("features","outline","inlineBookmarkMode",e.target.value),children:[ be("option",{value:"always",children:re("inlineBookmarkModeAlways")||"固定显示"}), be("option",{value:"hover",children:re("inlineBookmarkModeHover")||"悬浮显示"}), be("option",{value:"hidden",children:re("inlineBookmarkModeHidden")||"隐藏"})]})}), be(Zf,{label:re("panelBookmarkModeLabel")||"面板收藏图标",description:re("panelBookmarkModeDesc")||"控制大纲面板中的收藏图标显示方式",settingId:"outline-panel-bookmark-mode",children:ye("select",{className:"settings-select",value:c.features?.outline?.panelBookmarkMode||"always",onChange:e=>d("features","outline","panelBookmarkMode",e.target.value),children:[ be("option",{value:"always",children:re("inlineBookmarkModeAlways")||"固定显示"}), be("option",{value:"hover",children:re("inlineBookmarkModeHover")||"悬浮显示"}), be("option",{value:"hidden",children:re("inlineBookmarkModeHidden")||"隐藏"})]})})]}), be(Kf,{title:re("scrollSettings")||"滚动设置",children:be(Yf,{label:re("preventAutoScrollLabel")||"防止自动滚动",description:re("preventAutoScrollDesc")||"阻止页面自动滚动到底部",settingId:"outline-prevent-auto-scroll",checked:c.panel?.preventAutoScroll??false,onChange:()=>u("panel","preventAutoScroll",!c.panel?.preventAutoScroll)})})]}),r===Un&&ye(fe,{children:[ ye(Kf,{title:re("conversationsSettingsTitle")||"会话管理",description:re("conversationsSettingsDesc")||"配置会话同步和显示行为",children:[ be(Yf,{label:re("folderRainbowLabel")||"文件夹彩虹色",description:re("folderRainbowDesc")||"为不同文件夹使用不同颜色",settingId:"conversation-folder-rainbow",checked:c.features?.conversations?.folderRainbow??true,onChange:()=>d("features","conversations","folderRainbow",!c.features?.conversations?.folderRainbow)}), be(Yf,{label:re("conversationsSyncUnpinLabel")||"同步时取消置顶",description:re("conversationsSyncUnpinDesc")||"同步会话时自动取消置顶",settingId:"conversation-sync-unpin",checked:c.features?.conversations?.syncUnpin??false,onChange:()=>d("features","conversations","syncUnpin",!c.features?.conversations?.syncUnpin)}), be(Yf,{label:re("conversationsSyncDeleteLabel")||"Sync Delete Cloud",description:re("conversationsSyncDeleteDesc")||"Delete cloud conversation on supported sites when deleting local record",settingId:"conversation-sync-delete",checked:c.features?.conversations?.syncDelete??true,onChange:()=>d("features","conversations","syncDelete",!(c.features?.conversations?.syncDelete??1))})]}), ye(Kf,{title:re("exportSettings")||"导出设置",children:[ be(Zf,{label:re("exportCustomUserName")||"自定义用户名称",description:re("exportCustomUserNameDesc")||"导出时使用的用户显示名称 (默认: User)",settingId:"export-custom-user-name",children:be(Qb,{className:"settings-input",value:c.export?.customUserName||"",onChange:e=>u("export","customUserName",e),placeholder:"User",style:{width:"180px"}})}), be(Zf,{label:re("exportCustomModelName")||"自定义 AI 名称",description:re("exportCustomModelNameDesc")||"导出时使用的 AI 显示名称 (默认: 站点名称)",settingId:"export-custom-model-name",children:be(Qb,{className:"settings-input",value:c.export?.customModelName||"",onChange:e=>u("export","customModelName",e),placeholder:"Site Name",style:{width:"180px"}})}), be(Yf,{label:re("exportFilenameTimestamp")||"导出文件名包含时间戳",description:re("exportFilenameTimestampDesc")||"在导出文件名末尾添加时间戳",settingId:"export-filename-timestamp",checked:c.export?.exportFilenameTimestamp??false,onChange:()=>u("export","exportFilenameTimestamp",!c.export?.exportFilenameTimestamp)}), be(Yf,{label:re("exportIncludeThoughtsLabel")||"导出包含思维链",description:re("exportIncludeThoughtsDesc")||"导出时包含并自动展开思维链内容",settingId:"export-include-thoughts",checked:c.export?.includeThoughts??true,onChange:()=>u("export","includeThoughts",!(c.export?.includeThoughts??1))}), be(Yf,{label:re("exportImagesToBase64Label")||"导出时图片转 Base64",description:re("exportImagesToBase64Desc")||"导出会话时将图片转为 Base64 嵌入",settingId:"export-images-base64",checked:c.content?.exportImagesToBase64??false,onChange:()=>u("content","exportImagesToBase64",!c.content?.exportImagesToBase64)})]})]}),r===Wn&&ye(Kf,{title:re("promptSettingsTitle")||"Prompts Settings",description:re("promptSettingsDesc")||"Configure interactions in the prompts tab",children:[ be(Yf,{label:re("promptDoubleClickSendLabel")||"Double-click to send prompt",description:re("promptDoubleClickSendDesc")||"When enabled, double-click sends the prompt directly. Prompts with variables are sent after confirmation.",settingId:"prompt-double-click-send",checked:c.features?.prompts?.doubleClickToSend??false,onChange:()=>d("features","prompts","doubleClickToSend",!c.features?.prompts?.doubleClickToSend)}), be(Yf,{label:re("queueSettingLabel")||"Prompt Queue",description:re("queueSettingDesc")||"Show queue overlay above input for queuing prompts while AI generates",settingId:"prompt-queue",checked:c.features?.prompts?.promptQueue??false,onChange:()=>d("features","prompts","promptQueue",!c.features?.prompts?.promptQueue)})]}),r===Kn&&ye(Kf,{title:re("readingHistoryTitle")||"阅读历史",description:re("readingHistoryDesc")||"记录和恢复会话阅读位置",children:[ be(Yf,{label:re("readingHistoryPersistenceLabel")||"启用阅读历史",description:re("readingHistoryPersistenceDesc")||"记录每个会话的阅读位置",settingId:"reading-history-persistence",checked:c.readingHistory?.persistence??true,onChange:()=>u("readingHistory","persistence",!c.readingHistory?.persistence)}), be(Yf,{label:re("readingHistoryAutoRestoreLabel")||"自动恢复位置",description:re("readingHistoryAutoRestoreDesc")||"打开会话时自动跳转到上次阅读位置",settingId:"reading-history-auto-restore",checked:c.readingHistory?.autoRestore??true,disabled:!c.readingHistory?.persistence,onDisabledClick:()=>m(v),onChange:()=>u("readingHistory","autoRestore",!c.readingHistory?.autoRestore)}), be(Zf,{label:re("readingHistoryCleanup")||"历史保留时间",settingId:"reading-history-cleanup-days",disabled:!c.readingHistory?.persistence,onDisabledClick:()=>m(v),children:ye("select",{className:"settings-select",value:c.readingHistory?.cleanupDays||30,onChange:e=>u("readingHistory","cleanupDays",parseInt(e.target.value)),disabled:!c.readingHistory?.persistence,children:[ ye("option",{value:1,children:["1 ",re("day")||"天"]}), ye("option",{value:3,children:["3 ",re("days")||"天"]}), ye("option",{value:7,children:["7 ",re("days")||"天"]}), ye("option",{value:30,children:["30 ",re("days")||"天"]}), ye("option",{value:90,children:["90 ",re("days")||"天"]}), be("option",{value:-1,children:re("forever")||"永久"})]})})]}),r===Qn&&ye(Kf,{title:re("interactionEnhance")||"交互增强",description:re("interactionEnhanceDesc")||"增强 Mermaid、公式和表格的交互功能",children:[ be(Yf,{label:re("assistantMermaidLabel")||"AI 回复 Mermaid 渲染",description:re("assistantMermaidDesc")||"为未原生支持 Mermaid 的站点自动渲染 AI 回复中的 Mermaid 图表",settingId:"content-assistant-mermaid",checked:c.content?.assistantMermaid??true,onChange:()=>u("content","assistantMermaid",!(c.content?.assistantMermaid??1))}), be(Yf,{label:re("userQueryMarkdownLabel")||"用户提问样式优化",description:re("userQueryMarkdownDesc")||"为用户提问启用 Markdown 排版与 LaTeX 数学公式渲染",settingId:"content-user-query-markdown",checked:c.content?.userQueryMarkdown??true,onChange:()=>u("content","userQueryMarkdown",!(c.content?.userQueryMarkdown??1))}), be(Yf,{label:re("formulaCopyLabel")||"双击复制公式",description:re("formulaCopyDesc")||"双击数学公式即可复制其 LaTeX 源码",settingId:"content-formula-copy",checked:c.content?.formulaCopy??true,onChange:()=>u("content","formulaCopy",!c.content?.formulaCopy)}), be(Yf,{label:re("formulaDelimiterLabel")||"公式分隔符转换",description:re("formulaDelimiterDesc")||"复制时将括号分隔符转为美元符号",settingId:"content-formula-delimiter",checked:c.content?.formulaDelimiter??true,disabled:!c.content?.formulaCopy,onDisabledClick:()=>m(w),onChange:()=>u("content","formulaDelimiter",!c.content?.formulaDelimiter)}), be(Yf,{label:re("tableCopyLabel")||"表格复制 Markdown",description:re("tableCopyDesc")||"表格右上角添加复制按钮",settingId:"content-table-copy",checked:c.content?.tableCopy??true,onChange:()=>u("content","tableCopy",!c.content?.tableCopy)})]})]})},Yb=(e,t)=>{const n=re(e);return n===e?t:n},Jb=({siteId:e})=>{const{settings:t,updateNestedSetting:n}=No();if(!t)return null;const r=t.globalSearch?.promptEnterBehavior||"smart",o=t.globalSearch?.doubleShift??bo.globalSearch.doubleShift,i=t.globalSearch?.enableFuzzySearch??false,a=Mn(),s=t.shortcuts?.keybindings?.[cn],l=null===s?null:s||xn[cn],c=l?Tn(l,a):"",d=[];o&&d.push(Yb("globalSearchTriggerDoubleShift","double-press Shift")),c&&d.push(c);const u=((e,t,n)=>{let r=Yb(e,t);return Object.keys(n).forEach(e=>{r=r.replace(new RegExp(`{${e}}`,"g"),n[e]);}),r})("globalSearchTriggerHint","Trigger: {shortcut}",{shortcut:d.join(" / ")||Yb("shortcutNotSet","Not set")}),h=`shortcut-binding-${cn}`; return ye("div",{children:[ be(Xf,{title:Yb("navGlobalSearch","Global Search"),Icon:xt}), be("p",{className:"settings-page-desc",children:`${Yb("globalSearchPageDesc","Configure Search Everywhere behavior and interaction details")} · ${u}`}), ye(Kf,{title:Yb("globalSearchMatchingSettingsTitle","Search Matching"),description:Yb("globalSearchMatchingSettingsDesc","Configure how Search Everywhere matches search results"),children:[ be(Zf,{label:Yb("globalSearchShortcutSettingLabel","全局搜索快捷键"),description:Yb("globalSearchShortcutSettingDesc","跳转到快捷键设置,自定义或禁用全局搜索快捷键。"),settingId:"global-search-shortcut-setting-link",children:be("button",{className:"settings-btn settings-btn-secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:zn,settingId:h}}));},children:Yb("globalSearchShortcutSettingAction","前往设置")})}), be(Yf,{label:Yb("doubleShiftToSearch","Double Shift to open Global Search"),description:Yb("doubleShiftToSearchDesc","Press Shift twice quickly to open Global Search"),checked:o,onChange:()=>n("globalSearch","doubleShift",!o),settingId:"global-search-double-shift"}), be(Yf,{label:Yb("globalSearchEnableFuzzySearchLabel","Enable fuzzy search"),description:Yb("globalSearchEnableFuzzySearchDesc","When enabled, Search Everywhere uses fuzzy matching for title, folder, tag, prompt content, and setting identifiers."),checked:i,onChange:()=>n("globalSearch","enableFuzzySearch",!i),settingId:"global-search-fuzzy-search"})]}), be(Kf,{title:Yb("globalSearchPromptSettingsTitle","Prompt Behavior"),description:Yb("globalSearchPromptSettingsDesc","Choose what happens when pressing Enter on a prompt result in Search Everywhere"),children:be(Zf,{label:Yb("globalSearchPromptEnterBehaviorLabel","Search Everywhere prompt Enter behavior"),description:Yb("globalSearchPromptEnterBehaviorDesc","Smart: insert directly when no variable, open variable dialog when needed; Locate only: switch to Prompts and locate the item."),settingId:"global-search-prompt-enter-behavior",children:ye("select",{className:"settings-select",value:r,onChange:e=>n("globalSearch","promptEnterBehavior",e.target.value),children:[ be("option",{value:"smart",children:Yb("globalSearchPromptEnterBehaviorSmart","Smart (Recommended)")}), be("option",{value:"locate",children:Yb("globalSearchPromptEnterBehaviorLocate","Locate Only")})]})})})]})},Xb=({iconNode:e,label:t,index:n,total:r,enabled:o=true,showToggle:i=false,onToggle:a,onDragStart:s,onDragOver:l,onDragEnd:c,onDrop:d,isDragging:u=false})=>ye("div",{className:"settings-sortable-item "+(u?"dragging":""),draggable:true,onDragStart:e=>s(e,n),onDragOver:e=>l(e,n),onDragEnd:c,onDrop:e=>d(e,n),style:{opacity:u?.4:1,cursor:"grab",border:u?"1px dashed var(--gh-primary)":void 0},children:[ be("div",{className:"settings-sortable-handle",style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"4px 8px 4px 0",cursor:"grab",color:"var(--gh-text-secondary, #9ca3af)"},children:be(Je,{size:16})}),e&&be("span",{className:"settings-sortable-item-icon",children:e}), be("span",{className:"settings-sortable-item-label",children:t}), be("div",{className:"settings-sortable-item-actions",children:i&&be(rf,{checked:o,onChange:()=>a?.(),size:"sm"})})]}),ey=({siteId:e,initialTab:t})=>{const[n,r]=B(t||"panel"),{settings:o,setSettings:i,updateNestedSetting:a,updateDeepSetting:s}=No();M(()=>{t&&r(t);},[t]);const l=re("enablePrerequisiteToast")||"请先开启「{setting}」",c=re("edgeSnapHideLabel")||"边缘自动吸附",[d,u]=B(null),h=(e,t,n)=>{u({type:t,index:n}),e.dataTransfer.effectAllowed="move";},g=e=>{e.preventDefault(),e.dataTransfer.dropEffect="move";},p=(e,t)=>{if(e.preventDefault(),!d||"tab"!==d.type)return;const n=d.index;if(n===t)return;const r=[...o.features?.order||[]],[i]=r.splice(n,1);r.splice(t,0,i),a("features","order",r),u(null);},m=(e,t)=>{if(e.preventDefault(),!d||"button"!==d.type)return;const n=d.index;if(n===t)return;const r=[...o.collapsedButtons||[]],[a]=r.splice(n,1);r.splice(t,0,a),i({collapsedButtons:r}),u(null);},f=()=>{u(null);};if(!o)return null;const b=[{id:"panel",label:re("panelTab")||"面板"},{id:"tabOrder",label:re("tabOrderTab")||"界面排版"},{id:"shortcuts",label:re("shortcutsTab")||"快捷按钮"},{id:"toolsMenu",label:re("toolboxMenu")||"工具箱"}]; return ye("div",{children:[ be(Xf,{title:re("navGeneral")||"基本设置",Icon:Fe}), be("p",{className:"settings-page-desc",children:re("generalPageDesc")||"配置扩展的基本行为和界面"}), be(Jf,{tabs:b,activeTab:n,onTabChange:r}),"panel"===n&&ye(Kf,{title:re("panelSettings")||"面板设置",children:[ be(Yf,{label:re("defaultPanelStateLabel")||"默认显示面板",description:re("defaultPanelStateDesc")||"页面加载后自动展开面板",settingId:"panel-default-open",checked:o.panel?.defaultOpen??false,onChange:()=>a("panel","defaultOpen",!o.panel?.defaultOpen)}), be(Zf,{label:re("defaultPositionLabel")||"默认位置",description:re("defaultPositionDesc")||"页面刷新后面板显示在哪一侧",settingId:"panel-default-position",children:ye("div",{style:{display:"inline-flex",borderRadius:"6px",overflow:"hidden",border:"1px solid var(--gh-border, #e5e7eb)"},children:[ be("button",{onClick:()=>a("panel","defaultPosition","left"),style:{padding:"4px 12px",fontSize:"13px",border:"none",cursor:"pointer",background:"left"===(o.panel?.defaultPosition||"right")?"var(--gh-primary, #4285f4)":"var(--gh-bg, #fff)",color:"left"===(o.panel?.defaultPosition||"right")?"#fff":"var(--gh-text-secondary, #6b7280)",transition:"all 0.2s"},children:re("defaultPositionLeft")||"左侧"}), be("button",{onClick:()=>a("panel","defaultPosition","right"),style:{padding:"4px 12px",fontSize:"13px",border:"none",borderLeft:"1px solid var(--gh-border, #e5e7eb)",cursor:"pointer",background:"right"===(o.panel?.defaultPosition||"right")?"var(--gh-primary, #4285f4)":"var(--gh-bg, #fff)",color:"right"===(o.panel?.defaultPosition||"right")?"#fff":"var(--gh-text-secondary, #6b7280)",transition:"all 0.2s"},children:re("defaultPositionRight")||"右侧"})]})}), be(Zf,{label:re("defaultEdgeDistanceLabel")||"默认边距",description:re("defaultEdgeDistanceDesc")||"面板距离屏幕边缘的初始距离",settingId:"panel-edge-distance",children:ye("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[ be(df,{value:o.panel?.defaultEdgeDistance??25,onChange:e=>{a("panel","defaultEdgeDistance",e);},min:0,max:400,defaultValue:25,style:{width:"85px"}}), be("span",{style:{fontSize:"13px",color:"var(--gh-text-secondary)"},children:"px"})]})}), be(Zf,{label:re("panelWidthLabel")||"面板宽度",description:re("panelWidthDesc")||"面板的宽度 (px)",settingId:"panel-width",children:ye("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[ be(df,{value:o.panel?.width??320,onChange:e=>{a("panel","width",e);},min:200,max:600,defaultValue:320,style:{width:"85px"}}), be("span",{style:{fontSize:"13px",color:"var(--gh-text-secondary)"},children:"px"})]})}), be(Zf,{label:re("panelHeightLabel")||"面板高度",description:re("panelHeightDesc")||"面板占用屏幕高度的百分比",settingId:"panel-height",children:ye("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[ be(df,{value:o.panel?.height??85,onChange:e=>{a("panel","height",e);},min:50,max:100,defaultValue:85,style:{width:"85px"}}), be("span",{style:{fontSize:"13px",color:"var(--gh-text-secondary)"},children:"vh"})]})}), be(Yf,{label:re("edgeSnapHideLabel")||"边缘自动吸附",description:re("edgeSnapHideDesc")||"拖动面板到屏幕边缘时自动吸附,悬停显示",settingId:"panel-edge-snap",checked:o.panel?.edgeSnap??false,onChange:()=>a("panel","edgeSnap",!o.panel?.edgeSnap)}), be(Zf,{label:re("edgeSnapThresholdLabel")||"吸附触发距离",description:re("edgeSnapThresholdDesc")||"拖拽面板到边缘多近时触发吸附",settingId:"panel-edge-snap-threshold",disabled:!o.panel?.edgeSnap,onDisabledClick:()=>{return e=c,zo(l.replace("{setting}",e),2e3,{},1500,e);var e;},children:ye("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[ be(df,{value:o.panel?.edgeSnapThreshold??18,onChange:e=>{a("panel","edgeSnapThreshold",e);},min:0,max:400,defaultValue:18,disabled:!o.panel?.edgeSnap,style:{width:"85px"}}), be("span",{style:{fontSize:"13px",color:"var(--gh-text-secondary)"},children:"px"})]})}), be(Yf,{label:re("autoHidePanelLabel")||"点击外部收起",description:o.panel?.edgeSnap?re("autoHidePanelDescEdgeSnap")||"点击面板外部区域时自动缩回边缘":re("autoHidePanelDesc")||"点击面板外部区域时自动收起为悬浮球",settingId:"panel-auto-hide",checked:o.panel?.autoHide??false,onChange:()=>a("panel","autoHide",!o.panel?.autoHide)})]}),"tabOrder"===n&&be(Kf,{title:re("tabOrderSettings")||"界面排版",description:re("tabOrderDesc")||"调整面板标签页的显示顺序 (拖拽排序)",children:o.features?.order?.filter(e=>dr[e]).map((e,t)=>{const n=dr[e],r="prompts"===e?false!==o.features?.prompts?.enabled:"outline"===e?false!==o.features?.outline?.enabled:"conversations"!==e||false!==o.features?.conversations?.enabled; return be(Xb,{iconNode:n.IconComponent?be(n.IconComponent,{size:18,color:"currentColor"}):n.icon,label:re(n.label)||e,index:t,total:o.features?.order.filter(e=>dr[e]).length,enabled:r,showToggle:true,onToggle:()=>{"prompts"===e?s("features","prompts","enabled",!r):"outline"===e?s("features","outline","enabled",!r):"conversations"===e&&s("features","conversations","enabled",!r);},onDragStart:e=>h(e,"tab",t),onDragOver:g,onDragEnd:f,onDrop:p,isDragging:"tab"===d?.type&&d?.index===t},e)})}),"shortcuts"===n&&ye(Kf,{title:re("collapsedButtonsOrderTitle")||"快捷按钮组",description:re("collapsedButtonsOrderDesc")||"快捷按钮组排序与启用 (拖拽排序)",children:[o.collapsedButtons?.map((e,t)=>{if("manualAnchor"===e.id)return null;const n=ur[e.id];return n?be(Xb,{iconNode:n.IconComponent?be(n.IconComponent,{size:18,color:"currentColor"}):n.icon,label:re(n.labelKey)||e.id,index:t,total:o.collapsedButtons.length,enabled:e.enabled,showToggle:n.canToggle,onToggle:()=>(e=>{const t=[...o.collapsedButtons||[]];t[e]={...t[e],enabled:!t[e].enabled},i({collapsedButtons:t});})(t),onDragStart:e=>h(e,"button",t),onDragOver:g,onDragEnd:f,onDrop:m,isDragging:"button"===d?.type&&d?.index===t},e.id):null}), be(Zf,{label:re("quickButtonsOpacityLabel")||"快捷按钮透明度",description:re("quickButtonsOpacityDesc")||"调整快捷按钮组整体透明度",settingId:"quick-buttons-opacity",children:ye("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ be("input",{type:"range",min:"0.4",max:"1",step:"0.05",value:o.quickButtonsOpacity??1,onChange:e=>i({quickButtonsOpacity:parseFloat(e.target.value)}),style:{width:"120px"}}), ye("span",{style:{fontSize:"12px",minWidth:"36px"},children:[Math.round(100*(o.quickButtonsOpacity??1)),"%"]})]})})]}),"toolsMenu"===n&&be(Kf,{title:re("toolboxMenuTitle")||"工具箱菜单",description:re("toolboxMenuDesc")||"配置工具箱弹出菜单中显示的功能",children:to.filter(e=>e.id!==eo).map(e=>{const t=(o.toolsMenu??to.map(e=>e.id)).includes(e.id); return be(Yf,{label:re(e.labelKey)||e.defaultLabel,settingId:`tools-menu-${e.id}`,checked:t,onChange:()=>{const n=o.toolsMenu??to.map(e=>e.id),r=t?n.filter(t=>t!==e.id):[...n,e.id];i({toolsMenu:r});}},e.id)})})]})},ty=[{id:"storage",name:"存储",nameKey:"permissionStorage",description:"permissionStorageDesc",icon:"💾"}],ny=[{id:"notifications",name:"通知",nameKey:"permissionNotifications",description:"permissionNotificationsDesc",icon:"🔔",permissions:["notifications"]},{id:"cookies",name:"Cookie管理",nameKey:"permissionCookies",description:"permissionCookiesDesc",icon:"🍪",permissions:["cookies"]}],ry=[{id:"webdav",name:"WebDAV 访问权限",nameKey:"permissionWebdavAccess",description:"permissionWebdavAccessDesc",icon:"☁️",origins:[""]}],oy=()=>{const{updateNestedSetting:e}=No(),[t,n]=B({}),[r,o]=B(true),[i,a]=B({open:false,message:"",onConfirm:()=>{}}),s=void 0!==chrome.permissions,l=E(async()=>{o(true);const e={};for(const n of ny)try{let t=!1;if(s)t=await chrome.permissions.contains({permissions:n.permissions||[]});else {const e=await Lu({type:Tu,permissions:n.permissions||[]});e&&e.success&&(t=e.hasPermission);}e[n.id]=t;}catch(t){console.error(`检查权限 ${n.id} 失败:`,t),e[n.id]=false;}for(const n of ry)try{let t=!1;if(s)t=await chrome.permissions.contains({origins:n.origins||[]});else {const e=await Lu({type:Tu,origins:n.origins||[]});e&&e.success&&(t=e.hasPermission);}e[n.id]=t;}catch(t){console.error(`检查权限 ${n.id} 失败:`,t),e[n.id]=false;}n(e),o(false);},[s]),c=E(async e=>{try{if(s){await chrome.permissions.request({origins:e.origins?.length?e.origins:void 0,permissions:e.permissions?.length?e.permissions:void 0})&&n(t=>({...t,[e.id]:!0}));}else await Lu({type:Mu,permType:e.id,origins:e.origins,permissions:e.permissions}),setTimeout(()=>l(),2e3);}catch(t){console.error(`请求权限 ${e.id} 失败:`,t);}},[s,l]);M(()=>{if(l(),s&&"undefined"!=typeof window){"true"===new URLSearchParams(window.location.search).get("auto_request")&&setTimeout(()=>{const e=ry[0];e&&c(e);},500);}},[l,s,c]);const d=t=>{let r=re("revokeConfirmDefault")||"确定要撤销此权限吗?撤销后,依赖该权限的功能将会自动关闭。";"notifications"===t.id?r=re("revokeConfirmNotifications")||"确定要撤销通知权限吗?\n\n撤销后,【桌面通知】功能将自动关闭。如需再次使用,需重新授权。":"webdav"===t.id&&(r=re("revokeConfirmWebdav")||"确定要撤销高级访问权限吗?\n\n撤销后,【水印移除】和【WebDAV 同步】功能将自动关闭。如需再次使用,需重新授权。"),a({open:true,message:be("div",{style:{whiteSpace:"pre-wrap"},children:r}),onConfirm:()=>(async t=>{try{let r=!1;if(s)r=await chrome.permissions.remove({origins:t.origins?.length?t.origins:void 0,permissions:t.permissions?.length?t.permissions:void 0});else {const e=await Lu({type:"REVOKE_PERMISSIONS",origins:t.origins,permissions:t.permissions});e&&e.success&&(r=e.removed);}r&&(n(e=>({...e,[t.id]:!1})),"notifications"===t.id?e("tab","showNotification",!1):"webdav"===t.id&&e("content","watermarkRemoval",!1));}catch(r){console.error(`撤销权限 ${t.id} 失败:`,r);}finally{a(e=>({...e,open:false}));}})(t)});}; return ye("div",{children:[ be(Xf,{title:re("navPermissions")||"权限管理",Icon:Ue}), be("p",{className:"settings-page-desc",children:re("permissionsPageDesc")||"查看和管理扩展的权限。"}), ye(Kf,{title:re("optionalPermissions")||"可选权限",description:re("optionalPermissionsDesc")||"这些权限可以按需授予或撤销",children:[ ye("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px",paddingBottom:"12px",borderBottom:"1px solid var(--gh-border, #e5e7eb)"},children:[ be("span",{style:{fontSize:"13px",color:"var(--gh-text-secondary, #9ca3af)"},children:re("permissionsSyncHint")||"权限状态与浏览器同步,如在此页面外修改请点击刷新。"}), be("button",{className:"settings-btn settings-btn-secondary",onClick:async e=>{e.preventDefault(),e.stopPropagation(),await l(),Oo(re("permissionsRefreshed")||"权限状态已刷新",1500);},disabled:r,style:{fontSize:"12px",padding:"4px 12px",flexShrink:0},children:r?re("refreshing")||"刷新中...":re("refreshStatus")||"刷新状态"})]}),[...ny,...ry].map((e,n,r)=>be(Zf,{label:ye("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ be("span",{style:{fontSize:"18px"},children:e.icon}), be("span",{children:re(e.nameKey)||e.name})]}),description:re(e.description)||e.description,style:n===r.length-1?{borderBottom:"none"}:{},children:be("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:t[e.id]?ye(fe,{children:[ be("span",{style:{padding:"4px 10px",borderRadius:"4px",fontSize:"12px",background:"rgba(16, 185, 129, 0.1)",color:"#10b981"},children:re("granted")||"已授予"}), be("button",{className:"settings-btn settings-btn-secondary",style:{padding:"4px 12px",fontSize:"12px"},onClick:t=>{t.preventDefault(),t.stopPropagation(),d(e);},children:re("revoke")||"撤销"})]}):ye(fe,{children:[ be("span",{style:{padding:"4px 10px",borderRadius:"4px",fontSize:"12px",background:"rgba(239, 68, 68, 0.1)",color:"#ef4444"},children:re("notGranted")||"未授予"}), be("button",{className:"settings-btn settings-btn-primary",style:{padding:"4px 12px",fontSize:"12px"},onClick:t=>{t.preventDefault(),t.stopPropagation(),c(e);},children:re("allowRecommended")||"允许(推荐)"})]})})},e.id))]}), be(Kf,{title:re("requiredPermissions")||"必需权限",description:re("requiredPermissionsDesc")||"这些权限是扩展正常运行所必需的,无法关闭",children:ty.map((e,t)=>be(Zf,{label:ye("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ be("span",{style:{fontSize:"18px"},children:e.icon}), be("span",{children:re(e.nameKey)||e.name})]}),description:re(e.description)||e.description,style:t===ty.length-1?{borderBottom:"none"}:{},children:be("span",{style:{padding:"4px 10px",borderRadius:"4px",fontSize:"12px",background:"rgba(107, 114, 128, 0.1)",color:"var(--gh-text-secondary, #6b7280)"},children:re("required")||"必需"})},e.id))}),i.open&&be(sf,{title:re("warning")||"警告",message:i.message,confirmText:re("confirm")||"确定",cancelText:re("cancel")||"取消",danger:true,onConfirm:i.onConfirm,onCancel:()=>a(e=>({...e,open:false}))})]})},iy=({binding:e,onChange:t,onRemove:n,conflictWarning:r})=>{const[o,i]=B(false),a=Mn(),s=E(e=>{if(!o)return;if(e.preventDefault(),e.stopPropagation(),["Control","Alt","Shift","Meta"].includes(e.key))return;if(!a&&e.getModifierState("AltGraph"))return;const n={key:En(e.key,e.code),alt:e.altKey,ctrl:a?e.metaKey:e.ctrlKey,shift:e.shiftKey};if(!(n.alt||n.ctrl||n.meta||n.shift)){if(!["Escape","F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12"].includes(e.key))return}a&&e.ctrlKey&&!e.metaKey||(t(n),i(false));},[o,t,a]),l=o?re("pressAnyKey")||"请按下快捷键...":e?Tn(e,a):re("shortcutNotSet")||"未设置"; return ye("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ be("button",{className:`shortcut-input ${o?"recording":""} ${e?"":"not-set"}`,onClick:()=>i(true),onKeyDown:s,onBlur:()=>{i(false);},style:{padding:"6px 12px",minWidth:"120px",fontSize:"13px",fontFamily:"monospace",border:o?"2px solid var(--gh-primary)":"1px solid var(--gh-border, #e5e7eb)",borderRadius:"6px",background:o?"var(--gh-bg-hover)":"var(--gh-bg)",color:e?"var(--gh-text)":"var(--gh-text-tertiary)",cursor:"pointer",textAlign:"center",transition:"all 0.2s",fontStyle:e?"normal":"italic"},children:l}),e&&be(wu,{content:re("shortcutRemove")||"移除",children:be("button",{onClick:n,style:{padding:"4px 8px",fontSize:"12px",border:"1px solid var(--gh-border)",borderRadius:"4px",background:"var(--gh-bg)",color:"var(--gh-text-secondary)",cursor:"pointer",transition:"all 0.2s"},children:"✕"})}),r&&be("span",{style:{fontSize:"12px",color:"var(--gh-error, #ef4444)"},children:r})]})},ay=({siteId:e})=>{const{settings:t,setSettings:n}=No(),r=t?.shortcuts,o=E((e,t)=>{if(!t)return;const n=_n(t);if(!n)return;const o=r?.keybindings||{};for(const[r,i]of Object.entries(o)){if(r===e)continue;if(null===i)continue;const t=vn[r];if(!t)continue;const o=_n(i);if(o&&(o.key===n.key&&!!o.alt==!!n.alt&&!!o.ctrl==!!n.ctrl&&!!o.shift==!!n.shift)){return [re("shortcutConflictWith")||"与",`"${re(t.labelKey)||t.label}"`,re("shortcutConflict")].filter(Boolean).join(" ")}}},[r?.keybindings]),i=E((e,t)=>{n({shortcuts:{...r,enabled:r?.enabled??true,globalUrl:r?.globalUrl??"https://gemini.google.com",keybindings:{...r?.keybindings,[e]:t}}});},[r,n]),a=E(e=>{n({shortcuts:{...r,enabled:r?.enabled??true,globalUrl:r?.globalUrl??"https://gemini.google.com",keybindings:{...r?.keybindings,[e]:null}}});},[r,n]),[s,l]=B(false),c=E(()=>{n({shortcuts:{...r,keybindings:{...xn}}}),l(false);},[r,n]),d=Object.entries(wn).map(([e,t])=>{const n=Object.entries(vn).filter(([,t])=>t.category===e);return {categoryId:e,categoryMeta:t,actions:n}});return t?ye("div",{children:[ be(Xf,{title:re("navShortcuts")||"快捷键",Icon:st}), be("p",{className:"settings-page-desc",children:re("shortcutsPageDesc")||"配置键盘快捷键以快速执行操作"}), ye(Kf,{title:re("shortcutsGlobalSettings")||"快捷键设置",children:[ be(Yf,{label:re("enableShortcuts")||"启用自定义快捷键",description:re("enableShortcutsDesc")||"启用或禁用所有自定义键盘快捷键",checked:r?.enabled??true,settingId:"shortcuts-enabled",onChange:()=>n({shortcuts:{...r,enabled:!(r?.enabled??1),globalUrl:r?.globalUrl??"https://gemini.google.com",keybindings:r?.keybindings??xn}})}),xu.hasCapability("commands")&&ye(fe,{children:[ be(Zf,{label:re("globalShortcutUrl")||"全局快捷键打开的 URL",description:re("globalShortcutUrlDesc")||"按下全局快捷键 Alt+G 时打开的网址",settingId:"shortcuts-global-url",children:be("input",{type:"text",className:"settings-input",value:r?.globalUrl||"https://gemini.google.com",onChange:e=>n({shortcuts:{...r,enabled:r?.enabled??true,globalUrl:e.target.value,keybindings:r?.keybindings??xn}}),style:{width:"280px"},placeholder:"https://gemini.google.com"})}), be(Zf,{label:re("globalShortcutsTitle")||"全局快捷键",description:re("globalShortcutsDesc")||"在浏览器任何页面都可使用,需要在浏览器扩展设置页面配置。",settingId:"shortcuts-browser-shortcuts",children:(()=>{const e=navigator.userAgent,t=e.includes("Chrome")&&!e.includes("Edg/"),n=e.includes("Edg/"),r=e.includes("Firefox");if(!(t||n||r)) return be("span",{style:{fontSize:"13px",color:"var(--gh-text-tertiary)"},children:re("browserNotSupported")||"当前浏览器不支持自定义扩展快捷键"});let o="chrome://extensions/shortcuts";return n?o="edge://extensions/shortcuts":r&&(o="about:addons"),be("button",{onClick:()=>Lu({type:"OPEN_URL",url:o}),style:{padding:"6px 12px",fontSize:"13px",border:"none",borderRadius:"6px",background:"var(--gh-primary)",color:"#fff",cursor:"pointer",whiteSpace:"nowrap"},children:re("openBrowserShortcuts")||"打开浏览器快捷键设置"})})()})]}), be("div",{style:{marginTop:"16px",paddingTop:"16px"},children:be("button",{onClick:()=>l(true),style:{padding:"8px 16px",fontSize:"13px",border:"1px solid var(--gh-border)",borderRadius:"6px",background:"var(--gh-bg)",color:"var(--gh-text-secondary)",cursor:"pointer"},children:re("resetShortcuts")||"恢复默认快捷键"})})]}), be(Kf,{title:re("shortcutsInteractionGroup")||"独立设置",description:re("shortcutsInteractionGroupDesc")||"此分组设置始终生效,不受“启用自定义快捷键”开关影响",children:be(Zf,{label:ye("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[ be("span",{children:re("promptSubmitShortcutLabel")||"Send shortcut"}), be("span",{style:{fontSize:"13px",color:"var(--gh-text-secondary)"},children:(re("promptSubmitShortcutDesc")||"Applies to both manual send and prompt auto-send").replace(/[\u3002.]$/,"")})]}),settingId:"shortcuts-prompt-submit-shortcut",children:ye("select",{className:"settings-select",value:t.features?.prompts?.submitShortcut??"enter",onChange:e=>n({features:{...t.features,prompts:{enabled:t.features?.prompts?.enabled??true,doubleClickToSend:t.features?.prompts?.doubleClickToSend??false,submitShortcut:e.target.value,promptQueue:t.features?.prompts?.promptQueue??false}}}),children:[ be("option",{value:"enter",children:re("promptSubmitShortcutEnter")||"Enter"}), be("option",{value:"ctrlEnter",children:re("promptSubmitShortcutCtrlEnter")||"Ctrl + Enter"})]})})}),d.map(({categoryId:e,categoryMeta:t,actions:n})=>be(Kf,{title:re(t.labelKey)||t.label,children:n.map(([e,t])=>{const n=r?.keybindings?.[e],s=null===n?null:n||xn[e],l=o(e,s); return be(Zf,{label:re(t.labelKey)||t.label,disabled:!r?.enabled,settingId:`shortcut-binding-${e}`,children:be(iy,{binding:s,onChange:t=>i(e,t),onRemove:()=>a(e),conflictWarning:l||void 0})},e)})},e)),s&&be(sf,{title:re("resetShortcuts")||"恢复默认快捷键",message:re("resetShortcutsConfirm")||"确定要恢复所有快捷键为默认值吗?",danger:true,onConfirm:c,onCancel:()=>l(false)})]}):null},sy=io()(lo((e,t)=>({keys:[],currentKeyId:"",_hasHydrated:false,addKey:t=>{const n={id:crypto.randomUUID(),...t,createdAt:Date.now()};return e(e=>({keys:[...e.keys,n]})),n},updateKey:(t,n)=>e(e=>({keys:e.keys.map(e=>e.id===t?{...e,...n}:e)})),deleteKey:t=>e(e=>({keys:e.keys.filter(e=>e.id!==t),currentKeyId:e.currentKeyId===t?"":e.currentKeyId})),setCurrentKey:t=>e({currentKeyId:t}),testKey:(t,n)=>e(e=>({keys:e.keys.map(e=>e.id===t?{...e,isValid:n.isValid,accountType:n.accountType,testedAt:Date.now()}:e)})),setKeys:t=>e({keys:t}),setHasHydrated:t=>e({_hasHydrated:t})}),{name:"claudeSessionKeys",storage:ao(()=>Ao),partialize:e=>({keys:e.keys,currentKeyId:e.currentKeyId}),onRehydrateStorage:()=>e=>{sy.setState({_hasHydrated:true});}})),ly=Object.freeze(Object.defineProperty({__proto__:null,useClaudeSessionKeysStore:sy},Symbol.toStringTag,{value:"Module"})),cy=({siteId:e})=>{const{keys:t,currentKeyId:n,addKey:r,deleteKey:o,setCurrentKey:i,testKey:a,setKeys:s}=sy(),[l,c]=B({}),[d,u]=B({type:"none"}),[h,g]=B(null),[p,m]=B(null),[f,b]=B(false),[y,v]=B(""),w=e===Mr,x=t.find(e=>e.id===n),k=()=>u({type:"none"}),S=async(e,t)=>{try{await navigator.clipboard.writeText(t),m(e),Oo(re("claudeKeyCopied"),pr),setTimeout(()=>m(null),pr);}catch{Oo(re("claudeKeyCopyFailed"),pr);}},C=async e=>{if(!e)return void Oo(re("claudePleaseSelectKey"),pr);if(e===n)return void Oo(re("claudeAlreadyUsing"),pr);if(xu.hasCapability("permissions")){if(!(await Lu({type:Tu,permissions:["cookies"]})).hasPermission)return await Lu({type:Mu,permType:"cookies"}),void Oo(re("claudeRequestPermission"),fr)}const r=e?t.find(t=>t.id===e)?.key:"";await xu.setClaudeSessionKey(r||""),i(e),Oo(re("claudeKeySwitched"),mr);},E=async(e,t,n,r=true)=>{if(xu.hasCapability("tabs"))try{if((await Lu({type:"CHECK_CLAUDE_GENERATING"})).isGenerating)return r&&Oo(re("claudeGenerating"),fr),!1}catch{}c(t=>({...t,[e]:true}));try{const o=await xu.testClaudeSessionKey(n);return o.isValid?(a(e,{isValid:!0,accountType:o.accountType}),r&&Oo(`${t}: ${o.accountType}`,mr),!0):(a(e,{isValid:!1}),r&&Oo(`${t}: ${re("claudeKeyInvalid")}`,mr),!1)}catch{return a(e,{isValid:false}),r&&Oo(`${t}: ${re("claudeKeyTest")} ${re("claudeKeyInvalid")}`,mr),false}finally{c(t=>({...t,[e]:false}));}},_=async e=>{const n=t.find(t=>t.id===e);n&&await E(e,n.name,n.key,true);}; return ye("div",{children:[ ye(Kf,{title:re("claudeSessionKeyTitle"),description:re("claudeSessionKeyDesc"),settingId:"claude-session-keys",children:[ ye("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"16px",marginBottom:"20px",backgroundColor:"var(--gh-bg-secondary)",borderRadius:"12px",border:"1px solid var(--gh-border)",flexWrap:"wrap",gap:"12px"},children:[ ye("div",{style:{display:"flex",alignItems:"center",gap:"12px",flex:"1 1 auto"},children:[ be("span",{style:{fontSize:"13px",color:"var(--gh-text-secondary)"},children:re("claudeCurrentUsing")}), be("span",{style:{fontSize:"14px",fontWeight:500,display:"flex",alignItems:"center",gap:"8px"},children:x?ye(fe,{children:[ ye("span",{style:{fontWeight:600},children:["🔑 ",x.name]}),x.accountType&&be("span",{style:{padding:"2px 8px",borderRadius:"12px",fontSize:"11px",fontWeight:500,backgroundColor:"var(--gh-bg)",border:"1px solid var(--gh-border)",color:"var(--gh-text-secondary)"},children:x.accountType})]}):be("span",{style:{color:"var(--gh-text-secondary)"},children:re("claudeNoKeySelected")})})]}), ye("div",{style:{display:"flex",alignItems:"center",gap:"12px",flexWrap:"wrap"},children:[!w&&ye("div",{style:{color:"#ca8a04",backgroundColor:"rgba(234, 179, 8, 0.1)",fontSize:"12px",display:"flex",alignItems:"center",gap:"6px",padding:"6px 10px",borderRadius:"6px",border:"1px solid rgba(234, 179, 8, 0.2)",whiteSpace:"nowrap"},children:[ be("span",{children:"⚠️"}), be("span",{children:re("claudeNotOnSiteHint")})]}), be(wu,{content:w?"":re("claudeNotOnSiteHint")||"请在 Claude 站点使用此功能",children:be("select",{className:"settings-select",value:n,onChange:e=>C(e.target.value),disabled:!w||0===t.length||f,style:{minWidth:"200px",padding:"8px 12px",fontSize:"13px",borderRadius:"8px",opacity:!w||0===t.length||f?.6:1,cursor:!w||f?"not-allowed":"pointer",backgroundColor:"var(--gh-bg)",border:"1px solid var(--gh-border)",color:"var(--gh-text)"},children:0===t.length?be("option",{value:"",children:re("claudePleaseAddKey")}):t.map(e=>ye("option",{value:e.id,children:["🔑 ",e.name," ",e.accountType?`(${e.accountType})`:""]},e.id))})})]})]}), ye("div",{style:{display:"flex",gap:"10px",marginBottom:"20px",flexWrap:"nowrap"},children:[ ye("button",{className:"settings-btn settings-btn-primary",onClick:()=>{u({type:"add"});},disabled:f,style:{justifyContent:"center",padding:"8px 12px",flex:"1 1 auto",opacity:f?.6:1,whiteSpace:"nowrap"},children:["➕ ",re("claudeAddKey")]}), be("button",{className:"settings-btn settings-btn-secondary",onClick:async()=>{if(0===t.length)return;if(f)return;b(true);let e=0,n=0;try{for(let r=0;rsetTimeout(e,Tr));}Oo(re("claudeBatchTestDone").replace("{valid}",String(e)).replace("{invalid}",String(n)),fr);}catch{Oo(re("claudeBatchTestFailed"),mr);}finally{b(false),v("");}},disabled:0===t.length||f,style:{justifyContent:"center",padding:"8px 12px",flex:"1 1 auto",opacity:0===t.length||f?.6:1,backgroundColor:f?"rgba(var(--gh-primary-rgb), 0.1)":void 0,color:f?"var(--gh-primary)":void 0,borderColor:f?"var(--gh-primary)":void 0,whiteSpace:"nowrap"},children:ye(fe,f?{children:[ be("div",{style:{marginRight:"8px",width:"14px",height:"14px",border:"2px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"spin 1s linear infinite"}}),y]}:{children:["⚡ ",re("claudeBatchTest")]})}),xu.hasCapability("cookies")&&be(wu,{content:w?"":re("claudeNotOnSiteHint"),children:ye("button",{className:"settings-btn settings-btn-secondary",onClick:async()=>{try{if(xu.hasCapability("permissions")){if(!(await Lu({type:Tu,permissions:["cookies"]})).hasPermission)return await Lu({type:Mu,permType:"cookies"}),void Oo(re("claudeRequestPermission"),fr)}const e=await xu.getClaudeSessionKey();if(!e.success)return void Oo(e.error||re("claudeNoCookieFound"),mr);const n=t.find(t=>t.key===e.sessionKey);if(n)return void Oo(re("claudeTokenExists").replace("{name}",n.name),mr);u({type:"import-name",sessionKey:e.sessionKey});}catch(e){Oo(re("claudeKeyCopyFailed")+": "+e.message,fr);}},disabled:!w||f,style:{justifyContent:"center",padding:"8px 12px",flex:"1 1 auto",opacity:!w||f?.6:1,backgroundColor:w?"var(--gh-bg)":"var(--gh-bg-secondary)",color:w?"var(--gh-primary)":"var(--gh-text-secondary)",borderColor:w?"var(--gh-primary)":"var(--gh-border)",whiteSpace:"nowrap"},children:["🌐 ",re("claudeImportFromBrowser")]})}), ye("button",{className:"settings-btn settings-btn-secondary",onClick:()=>{const e=document.createElement("input");e.type="file",e.accept="application/json",e.onchange=async e=>{const n=e.target.files?.[0];if(n)try{const e=await n.text(),r=JSON.parse(e);if(!Array.isArray(r))return void Oo(re("claudeInvalidJSON"),mr);const o=new Set(t.map(e=>e.key)),i=r.filter(e=>!o.has(e.key));if(0===i.length)return void Oo(re("claudeNoNewTokens"),pr);s([...t,...i]),Oo(re("claudeImported").replace("{count}",String(i.length)),mr);}catch(r){Oo(re("claudeInvalidJSON")+": "+r.message,fr);}},e.click();},disabled:f,style:{justifyContent:"center",padding:"8px 12px",flex:"1 1 auto",opacity:f?.6:1,whiteSpace:"nowrap"},children:["📥 ",re("claudeImportJSON")]}), ye("button",{className:"settings-btn settings-btn-secondary",onClick:()=>{if(0===t.length)return void Oo(re("claudeNoTokensToExport"),pr);const e=JSON.stringify(t,null,2),n=new Blob([e],{type:"application/json"}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r,o.download=`claude-session-keys-${Date.now()}.json`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r),Oo(re("claudeExported"),pr);},disabled:0===t.length||f,style:{justifyContent:"center",padding:"8px 12px",flex:"1 1 auto",opacity:0===t.length||f?.6:1,whiteSpace:"nowrap"},children:["📤 ",re("claudeExportJSON")]})]}),0===t.length?ye("div",{style:{padding:"48px 24px",textAlign:"center",color:"var(--gh-text-secondary)",backgroundColor:"var(--gh-bg-secondary)",borderRadius:"8px",border:"1px dashed var(--gh-border)"},children:[ be("div",{style:{marginBottom:"8px",fontSize:"24px"},children:"🔑"}), be("div",{children:re("claudeNoKeys")}), be("div",{style:{fontSize:"12px",marginTop:"4px"},children:re("claudeNoKeysHint")})]}):be("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:t.map(e=>{const t=e.id===n,r=h===e.id; return ye("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px",padding:"16px 20px",backgroundColor:t?"var(--gh-bg)":"var(--gh-bg-secondary)",borderRadius:"12px",border:t?"2px solid var(--gh-primary)":"1px solid var(--gh-border)",transition:"all 0.2s ease",boxShadow:t?"var(--gh-shadow-brand)":"none"},onMouseEnter:()=>g(e.id),onMouseLeave:()=>g(null),children:[ ye("div",{style:{display:"flex",flexDirection:"column",gap:"6px",flex:"1 1 auto",minWidth:0},children:[ ye("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[ be("span",{style:{fontWeight:600,fontSize:"15px",color:"var(--gh-text)"},children:e.name}),t&&be("span",{style:{fontSize:"11px",color:"var(--gh-primary)",backgroundColor:"var(--gh-bg-secondary)",padding:"1px 6px",borderRadius:"4px",fontWeight:500,border:"1px solid var(--gh-border)"},children:"当前使用"}),(i=e.accountType,be("span",i?{style:{padding:"2px 8px",borderRadius:"4px",fontSize:"11px",fontWeight:500,backgroundColor:"var(--gh-bg-secondary)"},children:i}:{style:{color:"var(--gh-text-secondary)"},children:re("claudeKeyUntested")}))]}), ye("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ be(wu,{content:re("claudeKeyDoubleTapCopy"),children:ye("code",{onDoubleClick:()=>S(e.id,e.key),style:{fontSize:"12px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",color:"var(--gh-text-secondary)",backgroundColor:"var(--gh-bg-tertiary)",padding:"2px 6px",borderRadius:"4px",cursor:"pointer",maxWidth:"300px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.key.substring(0,32),"..."]})}),(r||p===e.id)&&be(wu,{content:p===e.id?re("claudeCopied"):re("claudeCopyKey"),children:be("button",{onClick:t=>{t.stopPropagation(),S(e.id,e.key);},style:{background:"none",border:"none",cursor:p===e.id?"default":"pointer",fontSize:"12px",padding:"2px",color:p===e.id?"var(--gh-secondary)":"var(--gh-text-tertiary)"},children:p===e.id?"✓":be(lt,{size:14})})})]})]}), ye("div",{style:{display:"flex",alignItems:"center",gap:"16px"},children:[ be("div",{style:{fontSize:"13px",color:"var(--gh-text-secondary)"},children:(o=e.isValid,void 0===o?be("span",{style:{color:vr},children:"-"}):ye("span",o?{style:{color:br,fontWeight:500},children:["✓ ",re("claudeKeyValid")]}:{style:{color:yr,fontWeight:500},children:["✗ ",re("claudeKeyInvalid")]}))}), ye("div",{style:{display:"flex",gap:"8px"},children:[ be(wu,{content:re(t?"claudeAlreadyUsing":w?"claudeKeyUse":"claudeNotOnSiteHint"),children:be("button",{className:"settings-btn settings-btn-secondary",onClick:()=>C(e.id),disabled:!w||t,style:{padding:"6px 12px",fontSize:"13px",opacity:!w||t?.5:1,cursor:!w||t?"not-allowed":"pointer"},children:re(t?"claudeKeyUsing":"claudeKeyUse")})}), be("button",{className:"settings-btn settings-btn-secondary",style:{padding:"6px 12px",fontSize:"13px",minWidth:"60px",justifyContent:"center"},onClick:()=>_(e.id),disabled:l[e.id],children:l[e.id]?be("div",{style:{width:"14px",height:"14px",border:"2px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"spin 1s linear infinite"}}):re("claudeKeyTest")}), be("button",{className:"settings-btn settings-btn-secondary",style:{padding:"6px 12px",fontSize:"13px",color:"var(--gh-danger)",borderColor:"rgba(239, 68, 68, 0.2)",backgroundColor:"rgba(239, 68, 68, 0.05)"},onClick:()=>{return t=e.id,n=e.name,void u({type:"delete",id:t,name:n});var t,n;},children:re("claudeKeyDelete")}), be("style",{children:"\n @keyframes spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n "})]})]})]},e.id);var o,i;})})]}),"add"===d.type&&be(dy,{onConfirm:(e,n)=>{e.trim()?n.trim()?Ar.CLAUDE_KEY.test(n)?t.some(e=>e.key===n)?Oo(re("claudeKeyExists"),mr):(r({name:e.trim(),key:n.trim()}),Oo(re("claudeKeyAdded"),pr),k()):Oo(re("claudeKeyInvalidFormat"),mr):Oo(re("claudeKeyRequired"),pr):Oo(re("claudeNameRequired"),pr);},onCancel:k}),"import-name"===d.type&&be(lf,{title:re("claudeImportNameTitle"),defaultValue:`Import-${(new Date).toLocaleDateString()}`,placeholder:re("claudeImportNamePlaceholder"),onConfirm:e=>{if(!e.trim())return void Oo(re("claudeNameRequired"),pr);const t=d,n=r({name:e.trim(),key:t.sessionKey});i(n.id),Oo(re("claudeKeyImported"),pr),k(),setTimeout(()=>_(n.id),Tr);},onCancel:k}),"delete"===d.type&&be(sf,{title:re("claudeDeleteConfirmTitle"),message:re("claudeDeleteConfirmMsg").replace("{name}",d.name),confirmText:re("claudeKeyDelete"),danger:true,onConfirm:()=>{o(d.id),Oo(re("claudeKeyDeleted"),pr),k();},onCancel:k})]})},dy=({onConfirm:e,onCancel:t})=>{const[n,r]=B(""),[i,a]=B(""),s=o.useRef(null);o.useEffect(()=>{s.current?.focus();},[]);const l=()=>{e(n,i);}; return ye(af,{onClose:t,children:[ be("div",{className:"gh-dialog-title",children:re("claudeAddKey")}), ye("div",{style:{display:"flex",flexDirection:"column",gap:"16px",marginBottom:"24px"},children:[ ye("div",{children:[ be("div",{style:{marginBottom:"6px",fontSize:"14px",fontWeight:500,color:"var(--gh-text)"},children:re("claudeAddKeyNameTitle").split("-")[1].trim().replace("输入","")}), be("input",{ref:s,type:"text",className:"gh-dialog-input",value:n,onChange:e=>r(e.target.value),placeholder:re("claudeAddKeyNamePlaceholder"),style:{marginBottom:0},onKeyDown:e=>"Enter"===e.key&&document.getElementById("claude-key-input")?.focus()})]}), ye("div",{children:[ be("div",{style:{marginBottom:"6px",fontSize:"14px",fontWeight:500,color:"var(--gh-text)"},children:"Session Key"}), be("input",{id:"claude-key-input",type:"text",className:"gh-dialog-input",value:i,onChange:e=>a(e.target.value),placeholder:re("claudeAddKeyValuePlaceholder"),style:{marginBottom:0},onKeyDown:e=>"Enter"===e.key&&l()})]})]}), ye("div",{className:"gh-dialog-buttons",children:[ be("button",{className:"gh-dialog-btn gh-dialog-btn-secondary",onClick:t,children:re("cancel")}), be("button",{className:"gh-dialog-btn gh-dialog-btn-primary",onClick:l,children:re("confirm")})]})]})},uy=({label:e,siteKey:t,settings:n,setSettings:r,placeholder:o,onDisabledClick:i,settingId:a})=>{const s=R(()=>n.modelLock?.[t]||{enabled:false,keyword:""},[n.modelLock,t]),[l,c]=B(s.keyword);M(()=>{c(s.keyword);},[s.keyword]);const d=E(()=>{l!==s.keyword&&r({modelLock:{...n.modelLock,[t]:{...s,keyword:l}}});},[l,s,n.modelLock,t,r]); return ye("div",{style:{display:"flex",alignItems:"center",gap:"12px",marginBottom:"12px",cursor:s.enabled?"default":"not-allowed"},"data-setting-id":a,children:[ be("span",{style:{fontSize:"14px",fontWeight:500,flex:1,color:s.enabled?"var(--gh-text, #374151)":"var(--gh-text-secondary, #9ca3af)"},children:e}), be("div",{onMouseDown:e=>{s.enabled||(e.preventDefault(),i?.());},children:be("input",{type:"text",className:"settings-input",value:l,onChange:e=>c(e.target.value),onBlur:d,onKeyDown:e=>{"Enter"===e.key&&(d(),e.target.blur());},placeholder:o,disabled:!s.enabled,style:{width:"200px",opacity:s.enabled?1:.5,pointerEvents:s.enabled?"auto":"none"}})}), be(rf,{checked:s.enabled,onChange:()=>{r({modelLock:{...n.modelLock,[t]:{...s,enabled:!s.enabled}}});}})]})},hy=({settings:e,setSettings:t,onDisabledClick:n,settingId:r})=>{const o="aistudio",i=e.modelLock?.[o]||{enabled:false,keyword:""},[a,s]=B(e.aistudio?.cachedModels||[]),[l,c]=B(false);M(()=>{e.aistudio?.cachedModels&&s(e.aistudio.cachedModels);},[e.aistudio?.cachedModels]); return ye("div",{style:{display:"flex",alignItems:"center",gap:"12px",marginBottom:"12px",cursor:i.enabled?"default":"not-allowed"},"data-setting-id":r,children:[ be("span",{style:{fontSize:"14px",fontWeight:500,flex:1,color:i.enabled?"var(--gh-text, #374151)":"var(--gh-text-secondary, #9ca3af)"},children:"AI Studio"}), be(wu,{content:re("aistudioRefreshModelListTooltip")||"点击在 AI Studio 页面刷新模型列表",children:be("button",{className:"icon-button",onClick:async()=>{c(true);try{const n=await Lu({type:"GET_AISTUDIO_MODELS"});if(n.success&&n.models)s(n.models),t({aistudio:{...e.aistudio,cachedModels:n.models}}),Oo(re("aistudioModelsFetched")||`获取到 ${n.models.length} 个模型`,2e3);else {Oo("NO_AISTUDIO_TAB"===n.error?re("aistudioNoTabError")||"请先打开 AI Studio 页面":re("aistudioModelsError")||"获取模型失败",3e3);}}catch(n){Oo(re("aistudioModelsError")||"获取模型列表失败",3e3),console.error("Refresh model list failed:",n);}finally{c(false);}},disabled:l,style:{padding:"4px",opacity:l?.5:1,cursor:l?"not-allowed":"pointer",background:"transparent",border:"none",borderRadius:"4px",display:"flex",alignItems:"center",justifyContent:"center"},children:be(Ae,{size:16})})}), be("div",{onMouseDown:e=>{i.enabled||(e.preventDefault(),n?.());},children:ye("select",{className:"settings-select",value:i.keyword||"",onChange:n=>{return r=n.target.value,void t({modelLock:{...e.modelLock,[o]:{...i,keyword:r}}});var r;},disabled:!i.enabled||0===a.length,style:{width:"200px",opacity:i.enabled?1:.5,pointerEvents:i.enabled?"auto":"none"},children:[0===a.length&&be("option",{value:"",children:re("aistudioRefreshModelListFirst")||"请先刷新模型列表"}),a.map(e=>be("option",{value:e.id,children:e.name},e.id))]})}), be(rf,{checked:i.enabled,onChange:()=>{t({modelLock:{...e.modelLock,[o]:{...i,enabled:!i.enabled}}});}})]})},gy=({siteId:e,initialTab:t})=>{const[n,r]=B(t||Xn);M(()=>{t&&r(t);},[t]);const{settings:o,setSettings:i,updateNestedSetting:a}=No(),s=re("enablePrerequisiteToast")||"请先开启「{setting}」",l=e=>zo(s.replace("{setting}",e),2e3,{},1500,e),c=re("enablePageWidth")||"启用页面宽度",d=re("enableUserQueryWidth")||"启用用户问题加宽",u=re("modelLockTitle")||"模型切换锁定",h=o?.layout?.pageWidth?.[e]||o?.layout?.pageWidth?._default,g=o?.layout?.userQueryWidth?.[e]||o?.layout?.userQueryWidth?._default,[p,m]=B(h?.value||Er.DEFAULT_PERCENT),[f,b]=B(g?.value||_r.DEFAULT_PX),[y,v]=B(null),w=P(null),x=P(null),k=P(null),S=P(null);M(()=>{h?.value&&"pageWidth"!==y&&m(h.value);},[h?.value,y]),M(()=>{g?.value&&"userQueryWidth"!==y&&b(g.value);},[g?.value,y]),M(()=>()=>{w.current&&clearTimeout(w.current),x.current&&clearTimeout(x.current);},[]);const C=E(()=>{let t=parseInt(p);const n=h?.unit||"%";isNaN(t)&&(t="%"===n?parseInt(Er.DEFAULT_PERCENT):parseInt(Er.DEFAULT_PX)),"%"===n?(tEr.MAX_PERCENT&&(t=Er.MAX_PERCENT)):t<=0&&(t=Er.MIN_PX);const r=t.toString();if(m(r),r!==h?.value&&o){const t=h||{enabled:true,value:r,unit:"%"};i({layout:{...o.layout,pageWidth:{...o.layout?.pageWidth,[e]:{...t,value:r}}}});}},[p,h,o,e,i]),_=E(()=>{let t=parseInt(f);const n=g?.unit||"px";isNaN(t)&&(t="%"===n?parseInt(_r.DEFAULT_PERCENT):parseInt(_r.DEFAULT_PX)),"%"===n?(t<_r.MIN_PERCENT&&(t=_r.MIN_PERCENT),t>_r.MAX_PERCENT&&(t=_r.MAX_PERCENT)):t<=0&&(t=_r.MIN_PX);const r=t.toString();if(b(r),r!==g?.value&&o){const t=g||{enabled:true,value:r,unit:"px"};i({layout:{...o.layout,userQueryWidth:{...o.layout?.userQueryWidth,[e]:{...t,value:r}}}});}},[f,g,o,e,i]);if(!o)return null;const A=[{id:Xn,label:re("tabLayout")||"页面布局"},{id:er,label:re("tabModelLock")||"模型锁定"},{id:Ir,label:re("tabGemini")||"Gemini"},{id:qr,label:"AI Studio"},{id:Nr,label:"ChatGPT"},{id:Mr,label:"Claude"}]; return ye("div",{children:[ be(Xf,{title:re("navSiteSettings")||"站点设置",Icon:$e}), be("p",{className:"settings-page-desc",children:re("siteSettingsPageDesc")||"配置站点相关的页面布局和内容处理"}), be(Jf,{tabs:A,activeTab:n,onTabChange:r}),n===Xn&&ye(fe,{children:[ ye(Kf,{title:re("layoutSettingsTitle")||"页面宽度控制",children:[ be(Yf,{label:re("enablePageWidth")||"启用页面宽度",description:re("pageWidthDesc")||"调整聊天页面的最大宽度",settingId:"layout-page-width-enabled",checked:h?.enabled??false,onChange:()=>{const t=h||{enabled:false,value:"81",unit:"%"};i({layout:{...o?.layout,pageWidth:{...o?.layout?.pageWidth,[e]:{...t,enabled:!t.enabled}}}});}}), be(Zf,{label:re("pageWidthValueLabel")||"宽度值",settingId:"layout-page-width-value",disabled:!h?.enabled,onDisabledClick:()=>l(c),children:ye("div",{style:{display:"flex",gap:"8px"},children:[ be("input",{ref:k,type:"text",className:"settings-input",value:p,onFocus:()=>{w.current&&(clearTimeout(w.current),w.current=null),v("pageWidth");},onChange:e=>m(e.target.value.replace(/[^0-9]/g,"")),onBlur:()=>{w.current=setTimeout(()=>{document.activeElement!==k.current&&(v(null),C());},100);},onKeyDown:e=>{"Enter"===e.key&&(C(),k.current?.blur());},disabled:!h?.enabled,style:{width:"80px"}}), ye("select",{className:"settings-select",value:h?.unit||"%",onChange:t=>(t=>{const n="px"===t?Er.DEFAULT_PX:Er.DEFAULT_PERCENT;if(m(n),o){const r={...h,unit:t,value:n,enabled:h?.enabled??false};i({layout:{...o.layout,pageWidth:{...o.layout?.pageWidth,[e]:r}}});}})(t.target.value),disabled:!h?.enabled,children:[ be("option",{value:"%",children:"%"}), be("option",{value:"px",children:"px"})]})]})})]}), ye(Kf,{title:re("userQueryWidthSettings")||"用户问题宽度",children:[ be(Yf,{label:re("enableUserQueryWidth")||"启用用户问题加宽",description:re("userQueryWidthDesc")||"调整用户问题气泡的最大宽度",settingId:"layout-user-query-width-enabled",checked:g?.enabled??false,onChange:()=>{const t=g||{enabled:false,value:"600",unit:"px"};i({layout:{...o?.layout,userQueryWidth:{...o?.layout?.userQueryWidth,[e]:{...t,enabled:!t.enabled}}}});}}), be(Zf,{label:re("userQueryWidthValueLabel")||"问题宽度",settingId:"layout-user-query-width-value",disabled:!g?.enabled,onDisabledClick:()=>l(d),children:ye("div",{style:{display:"flex",gap:"8px"},children:[ be("input",{ref:S,type:"text",className:"settings-input",value:f,onFocus:()=>{x.current&&(clearTimeout(x.current),x.current=null),v("userQueryWidth");},onChange:e=>b(e.target.value.replace(/[^0-9]/g,"")),onBlur:()=>{x.current=setTimeout(()=>{document.activeElement!==S.current&&(v(null),_());},100);},onKeyDown:e=>{"Enter"===e.key&&(_(),S.current?.blur());},disabled:!g?.enabled,style:{width:"80px"}}), ye("select",{className:"settings-select",value:g?.unit||"px",onChange:t=>(t=>{const n="px"===t?_r.DEFAULT_PX:_r.DEFAULT_PERCENT;if(b(n),o){const r=g||{enabled:false,value:n,unit:t};i({layout:{...o.layout,userQueryWidth:{...o.layout?.userQueryWidth,[e]:{...r,unit:t,value:n}}}});}})(t.target.value),disabled:!g?.enabled,children:[ be("option",{value:"px",children:"px"}), be("option",{value:"%",children:"%"})]})]})})]}), be(Kf,{title:re("zenModeTitle")||"禅模式 (Zen Mode)",children:be(Yf,{label:re("zenModeLabel")||"启用禅模式",description:re("zenModeDesc")||"隐藏页面中不必要的元素(如底部的模型免责声明等),体验更纯粹的对话界面",settingId:"layout-zen-mode-enabled",checked:o.layout?.zenMode?.[e]?.enabled??false,onChange:()=>{const t=o.layout?.zenMode?.[e]||{enabled:false};i({layout:{...o.layout,zenMode:{...o.layout?.zenMode,[e]:{...t,enabled:!t.enabled}}}});}})})]}),n===er&&ye(Kf,{title:re("modelLockTitle")||"模型切换锁定",description:re("modelLockDesc")||"进入页面后自动切换到指定模型",children:[ be(uy,{label:"Gemini",siteKey:"gemini",settings:o,setSettings:i,placeholder:re("modelKeywordPlaceholder")||"模型关键词",onDisabledClick:()=>l(u),settingId:"model-lock-gemini"}), be(uy,{label:"Gemini Enterprise",siteKey:"gemini-enterprise",settings:o,setSettings:i,placeholder:re("modelKeywordPlaceholder")||"模型关键词",onDisabledClick:()=>l(u),settingId:"model-lock-gemini-enterprise"}), be(hy,{settings:o,setSettings:i,onDisabledClick:()=>l(u),settingId:"model-lock-aistudio"}), be(uy,{label:"ChatGPT",siteKey:"chatgpt",settings:o,setSettings:i,placeholder:re("modelKeywordPlaceholder")||"模型关键词",onDisabledClick:()=>l(u),settingId:"model-lock-chatgpt"}), be(uy,{label:"Claude",siteKey:"claude",settings:o,setSettings:i,placeholder:re("modelKeywordPlaceholder")||"模型关键词",onDisabledClick:()=>l(u),settingId:"model-lock-claude"}), be(uy,{label:"Grok",siteKey:"grok",settings:o,setSettings:i,placeholder:re("modelKeywordPlaceholder")||"模型关键词",onDisabledClick:()=>l(u),settingId:"model-lock-grok"}), be(uy,{label:"Kimi",siteKey:"kimi",settings:o,setSettings:i,placeholder:re("modelKeywordPlaceholder")||"模型关键词",onDisabledClick:()=>l(u),settingId:"model-lock-kimi"}), be(uy,{label:"Qianwen",siteKey:"qianwen",settings:o,setSettings:i,placeholder:re("modelKeywordPlaceholder")||"模型关键词",onDisabledClick:()=>l(u),settingId:"model-lock-qianwen"}), be(uy,{label:"QwenAI",siteKey:"qwenai",settings:o,setSettings:i,placeholder:re("modelKeywordPlaceholder")||"模型关键词",onDisabledClick:()=>l(u),settingId:"model-lock-qwenai"}), be(uy,{label:"Yuanbao",siteKey:"yuanbao",settings:o,setSettings:i,placeholder:re("modelKeywordPlaceholder")||"模型关键词",onDisabledClick:()=>l(u),settingId:"model-lock-yuanbao"}), be(uy,{label:"ima",siteKey:"ima",settings:o,setSettings:i,placeholder:re("modelKeywordPlaceholder")||"模型关键词",onDisabledClick:()=>l(u),settingId:"model-lock-ima"}), be(uy,{label:"Z.ai",siteKey:"zai",settings:o,setSettings:i,placeholder:re("modelKeywordPlaceholder")||"模型关键词",onDisabledClick:()=>l(u),settingId:"model-lock-zai"})]}),"gemini"===n&&ye(Kf,{title:re("geminiSettingsTab")||"Gemini 专属",description:re("contentProcessingDesc")||"配置 AI 回复内容的处理方式",children:[ be(Yf,{label:re("markdownFixLabel")||"Markdown 加粗修复",description:re("markdownFixDesc")||"修复 Gemini 响应中未渲染的加粗文本",settingId:"gemini-markdown-fix",checked:o.content?.markdownFix??true,onChange:()=>a("content","markdownFix",!o.content?.markdownFix)}), be(Yf,{label:re("watermarkRemovalLabel")||"图片水印移除",description:re("watermarkRemovalDesc")||"自动移除 AI 生成图片的水印",settingId:"gemini-watermark-removal",checked:o.content?.watermarkRemoval??false,onChange:async()=>{const e=o.content?.watermarkRemoval;if(e)a("content","watermarkRemoval",false);else {if(!xu.hasCapability("permissions"))return void a("content","watermarkRemoval",true);const e=await Lu({type:Tu,origins:[""]});e.success&&e.hasPermission?a("content","watermarkRemoval",true):(await Lu({type:Mu,permType:"allUrls"}),Oo(re("permissionRequestToast")||"请在弹出的窗口中授予权限",3e3));}}}), ye("div",{className:"setting-subsection",style:{marginTop:"24px",paddingTop:"16px",borderTop:"1px solid var(--gh-border-color)"},children:[ be("h3",{style:{fontSize:"14px",fontWeight:600,marginBottom:"12px"},children:"Gemini Enterprise"}), be(Yf,{label:re("policyRetryLabel"),description:re("policyRetryDesc"),settingId:"gemini-policy-retry",checked:o.geminiEnterprise?.policyRetry?.enabled??false,onChange:()=>{const e=o.geminiEnterprise?.policyRetry||{enabled:false,maxRetries:3};i({geminiEnterprise:{...o.geminiEnterprise,policyRetry:{...e,enabled:!e.enabled}}});}}),o.geminiEnterprise?.policyRetry?.enabled&&be(Zf,{label:re("maxRetriesLabel"),settingId:"gemini-policy-max-retries",children:ye("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ be(df,{value:o.geminiEnterprise?.policyRetry?.maxRetries??3,onChange:e=>i({geminiEnterprise:{...o.geminiEnterprise,policyRetry:{...o.geminiEnterprise?.policyRetry,maxRetries:e}}}),min:1,max:10,defaultValue:3,style:{width:"60px"}}), be("span",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:re("retryCountSuffix")})]})})]})]}),n===qr&&ye(Kf,{title:re("aistudioSettingsTitle")||"AI Studio 设置",description:re("aistudioSettingsDesc")||"配置 AI Studio 页面的默认行为",children:[ be(Yf,{label:re("aistudioCollapseNavbar")||"默认折叠侧边栏",description:re("aistudioCollapseNavbarDesc")||"打开页面时自动折叠左侧导航栏",settingId:"aistudio-collapse-navbar",checked:o.aistudio?.collapseNavbar??false,onChange:()=>i({aistudio:{...o.aistudio,collapseNavbar:!o.aistudio?.collapseNavbar}})}), be(Yf,{label:re("aistudioCollapseRunSettings")||"默认收起运行设置面板",description:re("aistudioCollapseRunSettingsDesc")||"打开页面时自动收起右侧的运行设置面板",settingId:"aistudio-collapse-run-settings",checked:o.aistudio?.collapseRunSettings??false,onChange:()=>i({aistudio:{...o.aistudio,collapseRunSettings:!o.aistudio?.collapseRunSettings}})}), be(Yf,{label:re("aistudioCollapseTools")||"默认收起工具面板",description:re("aistudioCollapseToolsDesc")||"打开页面时自动收起右侧运行设置面板",settingId:"aistudio-collapse-tools",checked:o.aistudio?.collapseTools??false,onChange:()=>i({aistudio:{...o.aistudio,collapseTools:!o.aistudio?.collapseTools}})}), be(Yf,{label:re("aistudioCollapseAdvanced")||"默认收起高级设置",description:re("aistudioCollapseAdvancedDesc")||"打开页面时自动收起运行设置中的高级选项",settingId:"aistudio-collapse-advanced",checked:o.aistudio?.collapseAdvanced??false,onChange:()=>i({aistudio:{...o.aistudio,collapseAdvanced:!o.aistudio?.collapseAdvanced}})}), be(Yf,{label:re("aistudioEnableSearch")||"默认启用搜索工具",description:re("aistudioEnableSearchDesc")||"打开页面时自动启用 Google 实时搜索",settingId:"aistudio-enable-search",checked:o.aistudio?.enableSearch??true,onChange:()=>i({aistudio:{...o.aistudio,enableSearch:!o.aistudio?.enableSearch}})}), be(Yf,{label:re("aistudioRemoveWatermark")||"移除图片水印",description:re("aistudioRemoveWatermarkDesc")||"阻止加载水印图片,让生成图片无水印 (需刷新页面生效)",settingId:"aistudio-remove-watermark",checked:o.aistudio?.removeWatermark??false,onChange:()=>{i({aistudio:{...o.aistudio,removeWatermark:!o.aistudio?.removeWatermark}}),Oo(re("aistudioReloadHint")||"设置已保存,请刷新 AI Studio 页面以生效",3e3);}}), be(Yf,{label:re("aistudioMarkdownFixLabel")||"Markdown 加粗修复",description:re("aistudioMarkdownFixDesc")||"修复 AI Studio 响应中未渲染的 **加粗** 文本",settingId:"aistudio-markdown-fix",checked:o.aistudio?.markdownFix??false,onChange:()=>i({aistudio:{...o.aistudio,markdownFix:!o.aistudio?.markdownFix}})})]}),"claude"===n&&be(cy,{siteId:e}),n===Nr&&be(Kf,{title:re("chatgptSettingsTitle")||"ChatGPT 设置",description:re("chatgptSettingsDesc")||"配置 ChatGPT 页面的默认行为",children:be(Yf,{label:re("chatgptMarkdownFixLabel")||"Markdown 加粗修复",description:re("chatgptMarkdownFixDesc")||"修复 ChatGPT 响应中未渲染的 **加粗** 文本",settingId:"chatgpt-markdown-fix",checked:o.chatgpt?.markdownFix??false,onChange:()=>i({chatgpt:{...o.chatgpt,markdownFix:!o.chatgpt?.markdownFix}})})})]})},py=(e,t)=>{const n=re(e);return n===e?t:n},my=[{id:Rn,Icon:Fe,labelKey:"navGeneral",label:"基本设置"},{id:qn,Icon:je,labelKey:"navAppearance",label:"外观主题"},{id:Pn,Icon:He,labelKey:"navFeatures",label:"功能模块"},{id:Bn,Icon:$e,labelKey:"navSiteSettings",label:"站点配置"},{id:On,Icon:xt,labelKey:"navGlobalSearch",label:"全局搜索"},{id:zn,Icon:st,labelKey:"navShortcuts",label:"快捷键位"},{id:Fn,Icon:({size:e=20,color:t="currentColor",className:n="",style:r})=>be("svg",{viewBox:"0 0 1027 1024",width:e,height:e,className:n,style:{display:"block",...r},children:be("path",{d:"M983.716 651.25l42.5-42.5L847.466 431.25 668.716 608.75l42.5 42.5 106.25-106.25 0 373.75L876.216 918.75 876.216 545 983.716 651.25zM533.716 793.75 533.716 421.25l-60 0 0 373.75-106.25-106.25L326.216 730l177.5 177.5 178.75-178.75L639.966 687.5 533.716 793.75zM297.466 835 238.716 835c-98.75 0-178.75-80-178.75-178.75S139.966 477.5 238.716 477.5c1.25 0 2.5 0 2.5 0l28.75 0c1.25 0 11.25 1.25 21.25-10 10-11.25 6.25-21.25 6.25-33.75 0-148.75 121.25-270 268.75-270 70 0 133.75 26.25 181.25 70 5 5 3.75 5 10 10 6.25 8.75 15 13.75 26.25 13.75 16.25 0 30-13.75 30-30 0-10-5-18.75-12.5-26.25-5-5-3.75-3.75-10-8.75-58.75-56.25-137.5-90-225-90-176.25 0-320 138.75-328.75 312.5-131.25 0-237.5 106.25-237.5 237.5s106.25 237.5 237.5 237.5l57.5 0c16.25 0 30-13.75 30-30C326.216 847.5 313.716 835 297.466 835L297.466 835z",fill:t})}),labelKey:"navBackup",label:"数据管理"},{id:jn,Icon:Ue,labelKey:"navPermissions",label:"权限管理"},{id:$n,Icon:We,labelKey:"navAbout",label:"关于"}],fy=({isOpen:e,onClose:t,siteId:n})=>{const[r,o]=B(Rn),[i,a]=B(void 0),[s,l]=B(null),[c,d]=B(false),{settings:u}=No(),h=Lo(),g=P(null),p=P(null),m=P(void 0),f=P(null);if(M(()=>{h&&u?.language&&te(u.language);},[h,u?.language]),M(()=>{g.current&&(g.current.scrollTop=0);},[r]),M(()=>{if(!e)return;const n=e=>{"Escape"===e.key&&t();};return document.addEventListener("keydown",n),()=>document.removeEventListener("keydown",n)},[e,t]),M(()=>{const e=e=>{const t=(e=>{const t=or(e.settingId),n=ir(t);return {page:e.page??n?.page,subTab:e.subTab??(e.page&&e.page!==n?.page?void 0:n?.subTab),settingId:t}})(e.detail||{});t.page&&my.some(e=>e.id===t.page)&&o(t.page),a(t.subTab),t.settingId?l({settingId:t.settingId,token:Date.now()}):l(null);};return window.addEventListener("ophel:navigateSettingsPage",e),()=>window.removeEventListener("ophel:navigateSettingsPage",e)},[]),M(()=>{if(!e||!s?.settingId)return;let t,n,r=false;const o=`[data-setting-id="${"undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(s.settingId):JSON.stringify(s.settingId).slice(1,-1)}"]`,i=e=>{if(r)return;const n=g.current?.querySelector(o);return n?(void 0!==m.current&&(window.clearTimeout(m.current),m.current=void 0),f.current&&f.current!==n&&f.current.classList.remove("setting-locate-highlight"),n.scrollIntoView({behavior:"smooth",block:"center"}),n.classList.remove("setting-locate-highlight"),n.offsetWidth,n.classList.add("setting-locate-highlight"),f.current=n,m.current=window.setTimeout(()=>{n.classList.remove("setting-locate-highlight"),f.current===n&&(f.current=null),m.current=void 0;},2200),void l(null)):e>=12?(console.warn(`[Ophel] Failed to locate setting: ${s.settingId}`),void l(null)):void(t=window.setTimeout(()=>i(e+1),100))};return n=window.requestAnimationFrame(()=>i(0)),()=>{r=true,void 0!==n&&window.cancelAnimationFrame(n),void 0!==t&&window.clearTimeout(t);}},[e,r,i,s]),M(()=>()=>{ void 0!==m.current&&window.clearTimeout(m.current),f.current&&(f.current.classList.remove("setting-locate-highlight"),f.current=null);},[]),M(()=>{if(e){const e=p.current;if(!e)return;return Zo(e)}},[e,n]),M(()=>e?(document.body.style.overflow="hidden",()=>{document.body.style.overflow="";}):(document.body.style.overflow="",()=>{document.body.style.overflow="";}),[e]),!e)return null; return be("div",{className:"settings-modal-overlay",onClick:t,children:ye("div",{ref:p,className:"settings-modal-container "+(c?"maximized":""),onClick:e=>e.stopPropagation(),children:[ ye("div",{className:"settings-modal-actions",children:[ be(wu,{content:c?re("restore")||"还原":re("maximize")||"最大化",children:be("button",{className:"settings-modal-action-btn",onClick:()=>d(!c),children:be(c?ot:rt,{size:16})})}), be(wu,{content:re("close")||"关闭",children:be("button",{className:"settings-modal-action-btn close",onClick:t,children:be(ke,{size:16})})})]}), ye("aside",{className:"settings-sidebar",children:[ be("div",{className:"settings-sidebar-header",children:ye("div",{className:"settings-sidebar-logo",children:[ be("img",{src:nf,alt:ef}), be("span",{children:ef})]})}), ye("nav",{className:"settings-sidebar-nav",children:[my.filter(e=>!(!xu.hasCapability("permissions")&&e.id===jn)).map(e=>ye("button",{className:"settings-nav-item "+(r===e.id?"active":""),onClick:()=>{o(e.id),a(void 0),l(null);},children:[ be("span",{className:"settings-nav-item-icon",children:be(e.Icon,{size:22})}), be("span",{children:py(e.labelKey,e.label)})]},e.id)), ye("a",{href:"https://github.com/urzeye/ophel",target:"_blank",rel:"noopener noreferrer",className:"sidebar-github-link",children:[ be(Ve,{size:16}), be("span",{children:"Star on GitHub"})]})]}), be(Gf,{siteId:n})]}), be("main",{className:"settings-content",ref:g,children:(()=>{if(!u||!h) return be("div",{style:{padding:40,textAlign:"center"},children:re("loading")||"加载中..."});switch(r){case Rn: return be(ey,{siteId:n,initialTab:i});case Bn: return be(gy,{siteId:n,initialTab:i});case qn: return be(db,{siteId:n,initialTab:i});case Pn: return be(Zb,{siteId:n,initialTab:i});case On: return be(Jb,{siteId:n});case zn: return be(ay,{siteId:n});case jn: return be(oy,{siteId:n});case Fn: return be(Ib,{siteId:n,onNavigate:o});case $n: return be(eb,{});default: return be(ey,{siteId:n,initialTab:i})}})()})]})})},by=e=>{const{isOpen:t,onClose:n,inputRef:r,resultsRef:i,activeOptionId:a,inputValue:s,inputPlaceholder:l,onInputChange:c,hotkeyLabel:d,fuzzySearchToggleLabel:u,fuzzySearchToggleAriaLabel:h,isFuzzySearchEnabled:g,onToggleFuzzySearch:p,syntaxHelpTriggerRef:m,syntaxHelpPopoverRef:f,showSyntaxHelp:b,onToggleSyntaxHelp:y,syntaxHelpTriggerAriaLabel:v,syntaxHelpTitle:w,syntaxHelpDescription:x,syntaxHelpItems:k,onApplySyntaxHelpItem:S,activeFilterChips:C,hasOverflowFilterChips:E,overflowFilterChipText:_,filterChipRemoveTitle:A,clearFiltersLabel:T,onRemoveFilterChip:M,onClearAllFilterChips:I,shouldShowSyntaxSuggestions:N,syntaxSuggestions:L,activeSyntaxSuggestionIndex:D,onHoverSyntaxSuggestion:R,onApplySyntaxSuggestion:q,syntaxDiagnostics:P,resolveSyntaxDiagnosticTitle:B,showShortcutNudge:O,shortcutNudgeMessage:z,closeLabel:F,dismissShortcutNudgeLabel:j,onHideShortcutNudge:$,onDismissShortcutNudgeForever:H,categoriesLabel:U,categories:W,activeCategoryId:V,onSelectCategory:G,activeContext:Q,listboxId:K,listboxLabel:Z,onResultsWheel:Y,visibleResults:J,groupedResults:X,getGroupLabel:ee,allCategoryItemLimit:te,isAllCategory:ne,emptyText:re,emptyGuideTitle:oe,emptyGuideDescription:ie,emptyGuideExamples:ae,renderSearchResultItem:se,resolveVisibleResultIndex:le,collapseLabel:ce,moreLabel:de,onToggleCategoryGroup:ue,footerTips:he,promptPreview:ge}=e,pe=o.useRef(null);return o.useEffect(()=>{if(!t)return;const e=pe.current;return e?Zo(e):void 0},[t]),t?ye("div",{className:"settings-search-overlay gh-interactive",onClick:n,children:[ ye("div",{ref:pe,className:"settings-search-modal",onClick:e=>e.stopPropagation(),children:[ ye("div",{className:"settings-search-input-wrap",children:[ be(xt,{size:16}), be("button",{type:"button",className:"settings-search-fuzzy-toggle "+(g?"active":""),"aria-pressed":g,"aria-label":h,onClick:p,children:u}), be("input",{ref:r,className:"settings-search-input",role:"combobox","aria-autocomplete":"list","aria-expanded":true,"aria-haspopup":"listbox","aria-controls":K,"aria-activedescendant":a,value:s,onChange:e=>{c(e.target.value);},placeholder:l}), ye("span",{className:"settings-search-hotkey",children:["⌨ ",d]}), ye("div",{className:"settings-search-help",children:[ be("button",{ref:m,type:"button",className:"settings-search-help-trigger "+(b?"active":""),"aria-expanded":b,"aria-label":v,onClick:y,children:"?"}),b?ye("div",{ref:f,className:"settings-search-help-popover",role:"dialog","aria-label":w,children:[ be("div",{className:"settings-search-help-title",children:w}), be("div",{className:"settings-search-help-tip",children:x}), be("div",{className:"settings-search-help-items",children:k.map(e=>ye("button",{type:"button",className:"settings-search-help-item",onClick:()=>S(e),children:[ be("span",{className:"settings-search-help-token",children:e.token}), be("span",{className:"settings-search-help-desc",children:e.description})]},e.id))})]}):null]})]}),C.length>0?ye("div",{className:"settings-search-filter-chips","aria-label":"active search filters",children:[C.map(e=>ye("button",{type:"button",className:"settings-search-filter-chip",onClick:()=>M(e.id),title:A,children:[ be("span",{className:"settings-search-filter-chip-label",children:e.label}), be("span",{className:"settings-search-filter-chip-close","aria-hidden":true,children:"×"})]},e.id)),E?be("span",{className:"settings-search-filter-chip-overflow",children:_}):null, be("button",{type:"button",className:"settings-search-filter-chip-clear-all",onClick:I,children:T})]}):null,N?be("div",{className:"settings-search-syntax-suggestions",role:"listbox",children:L.map((e,t)=>ye("button",{type:"button",role:"option","aria-selected":D===t,className:"settings-search-syntax-suggestion "+(D===t?"active":""),onMouseEnter:()=>R(t),onClick:()=>q(e),children:[ be("span",{className:"settings-search-syntax-suggestion-token",children:e.label}), be("span",{className:"settings-search-syntax-suggestion-desc",children:e.description})]},e.id))}):null,P.length>0?be("div",{className:"settings-search-syntax-diagnostics",role:"status","aria-live":"polite",children:P.map(e=>ye("div",{className:"settings-search-syntax-diagnostic",children:[ be("span",{className:"settings-search-syntax-diagnostic-title",children:B(e.code)}), ye("span",{className:"settings-search-syntax-diagnostic-detail",children:[e.operator,e.value?`:${e.value}`:"",e.suggestion?` → ${e.suggestion}:`:""]})]},e.id))}):null,O&&z?ye("div",{className:"settings-search-shortcut-nudge",role:"status","aria-live":"polite",children:[ be("span",{className:"settings-search-shortcut-nudge-text",children:z}), be("button",{type:"button",className:"settings-search-shortcut-nudge-action",onClick:$,children:F}), be("button",{type:"button",className:"settings-search-shortcut-nudge-action",onClick:H,children:j})]}):null, be("div",{className:"settings-search-categories",role:"tablist","aria-label":U,children:W.map(e=>ye("button",{type:"button",role:"tab","aria-selected":V===e.id,className:"settings-search-category "+(V===e.id?"active":""),onClick:()=>G(e.id),children:[ be("span",{children:e.label}), be("span",{className:"settings-search-category-count",children:e.count})]},e.id))}),Q?ye("div",{className:"settings-search-context-bar",children:[ be("span",{className:"settings-search-context-label",children:Q.label}), be("span",{className:"settings-search-context-meta",children:Q.meta})]}):null, be("div",{id:K,className:"settings-search-results",role:"listbox","aria-label":Z,ref:i,onWheel:Y,children:0===J.length?ye("div",{className:"settings-search-empty",children:[ be("div",{children:re}), be("div",{className:"settings-search-empty-guide-title",children:oe}), be("div",{className:"settings-search-empty-guide-desc",children:ie}), be("div",{className:"settings-search-empty-guide-examples",children:ae.map(e=>be("button",{type:"button",className:"settings-search-empty-guide-example",onClick:e.onClick,children:e.token},e.id))})]}):ne?X.map(e=>ye("section",{className:"settings-search-group",children:[ ye("div",{className:"settings-search-group-title",children:[ be("span",{children:ee(e.category)}),e.totalCount>te?ye("span",{className:"settings-search-group-count",children:[e.items.length,"/",e.totalCount]}):null]}),e.items.map((e,t)=>se(e,le(e,t))),e.hasMore||e.isExpanded?be("button",{type:"button",className:"settings-search-group-more",onClick:()=>ue(e.category),children:e.isExpanded?ce:`${de} (+${e.remainingCount})`}):null]},e.category)):J.map((e,t)=>se(e,t))}), be("div",{className:"settings-search-footer",children:he})]}),ge]}):null},yy=(e,t,n)=>{if(!e)return [];const r=((e,t)=>{if(!e||0===t.length)return [];const n=e.toLowerCase(),r=[];if(t.forEach(e=>{if(!e)return;let t=0;for(;te.start!==t.start?e.start-t.start:e.end-t.end);const o=[];return r.forEach(e=>{const t=o[o.length-1];!t||e.start>t.end?o.push({...e}):e.end>t.end&&(t.end=e.end);}),o})(e,t),o=((e,t)=>{if(!e||!t||0===t.length)return [];const n=Array.from(new Set(t.map(e=>Number(e)).filter(t=>Number.isInteger(t)&&t>=0&&te-t);if(0===n.length)return [];const r=[];let o=n[0],i=n[0];for(let a=1;a{for(let t=e.start;t{for(let t=e.start;te.text.length>0)},vy=({item:e,index:t,optionIdPrefix:n,isActive:r,highlightTokens:i,outlineRoleLabels:a,matchReasonLabels:s,onMouseMove:l,onMouseEnter:c,onMouseLeave:d,onClick:u})=>{const h=(e,t="default",n)=>yy(e,i,n).map((e,n)=>{if("none"===e.matchType) return be(o.Fragment,{children:e.text},`plain-${n}-${e.text.length}`);const r=["settings-search-highlight","tag"===t?"settings-search-highlight-tag":"","code"===t?"settings-search-highlight-code":"","fuzzy"===e.matchType?"settings-search-highlight-fuzzy":""].filter(Boolean).join(" "); return be("mark",{className:r,children:e.text},`highlight-${n}-${e.text.length}`)}),g="outline"===e.category&&Boolean(e.outlineTarget),p="conversations"===e.category,m="prompts"===e.category,f=g&&Boolean(e.outlineTarget?.isUserQuery),b=f?a.query:a.reply,y=Boolean(e.code)&&!g,v=e.fuzzyMatch?.field,w="title"===v?e.fuzzyMatch?.indexes:void 0,x="breadcrumb"===v?e.fuzzyMatch?.indexes:void 0,k="snippet"===v?e.fuzzyMatch?.indexes:void 0,S="code"===v?e.fuzzyMatch?.indexes:void 0,C="prompts"===e.category&&e.matchReasons?.includes("content")?`${s.content}: `:"",E=e.matchReasons&&e.matchReasons.length>0?e.matchReasons.map(e=>({reason:e,label:s[e]})):[]; return ye("div",{id:`${n}-${t}`,role:"option","aria-selected":r,tabIndex:-1,"data-global-search-index":t,"data-global-search-item-id":e.id,className:`settings-search-item ${r?"active":""} ${g?f?"outline-item outline-query":"outline-item outline-reply":""} ${p?"conversation-item":""}`.trim(),onMouseMove:l,onMouseEnter:e=>{m&&c(e);},onMouseLeave:()=>{m&&d();},onClick:u,children:[ be("div",{className:"settings-search-item-title",title:e.title,children:g?ye("div",{className:"settings-search-outline-head",children:[ be("span",{className:"settings-search-outline-role "+(f?"query":"reply"),title:b,children:b}),e.code?be("span",{className:"settings-search-outline-code",title:e.code,children:h(e.code,"code",S)}):null, be("span",{className:"settings-search-item-title-text",children:h(e.title,"default",w)})]}):be("span",{className:"settings-search-item-title-text",children:h(e.title,"default",w)})}),e.snippet?ye("div",{className:"settings-search-item-snippet",title:`${C}${e.snippet}`,children:[C?be("span",{className:"settings-search-item-snippet-prefix",children:C}):null,h(e.snippet,"default",k)]}):null, ye("div",{className:("settings-search-item-meta "+(y?"":"no-code")).trim(),children:[ ye("div",{className:"settings-search-item-meta-left",children:[ be("span",{className:"settings-search-item-breadcrumb",title:e.breadcrumb,children:h(e.breadcrumb,"default",x)}),"conversations"===e.category&&e.tagBadges&&e.tagBadges.length>0?be("div",{className:"settings-search-tag-list",children:e.tagBadges.map(e=>be("span",{className:"settings-search-tag",style:{backgroundColor:e.color},title:e.name,children:h(e.name,"tag")},e.id))}):null,E.length>0?be("div",{className:"settings-search-match-reason-list",children:E.map(e=>be("span",{className:"settings-search-match-reason-badge",children:e.label},e.reason))}):null]}),y?be("code",{title:e.code,children:h(e.code,"code",S)}):null]})]})},wy=["type","folder","tag","is","level","date"],xy=["outline","conversations","prompts","settings"],ky=["pinned","unpinned"],Sy=["0","1","2","3","4","5","6"],Cy=["7d","30d"],Ey=e=>e.trim().toLowerCase(),_y=e=>Ey(e).split(" ").map(e=>e.trim()).filter(e=>e.length>0),Ay=e=>e?e.replace(/^"|"$/g,"").replace(/\\([\\"\s:])/g,"$1").trim():"",Ty=e=>{const t=e.trim().toLowerCase().match(/^(\d{1,3})d$/);if(!t)return null;const n=Number(t[1]);return !Number.isFinite(n)||n<=0?null:n},My=(e,t)=>{const n=e.normalizedValue;return "type"===e.key?t.some(e=>"type"===e.key&&e.normalizedValue!==n):"is"===e.key?t.some(e=>"is"===e.key&&e.normalizedValue!==n):"level"===e.key?t.some(e=>"level"===e.key&&e.normalizedValue!==n):"date"===e.key&&t.some(e=>"date"===e.key&&e.normalizedValue!==n)},Iy=(e,t)=>!!t&&("type"===e?xy.includes(t):"is"===e?ky.includes(t):"level"===e?Sy.includes(t):"date"!==e||null!==Ty(t)),Ny=e=>"type"===e?"outline | conversations | prompts | settings":"is"===e?"pinned | unpinned":"level"===e?"0 ~ 6":"date"===e?"Nd (e.g. 7d, 30d)":void 0,Ly=(e,t,n)=>`${e}:${t}:${n}`,Dy=e=>{const t=e.trim().toLowerCase();if(!t)return null;const n=wy.find(e=>e.startsWith(t));if(n)return n;const r=wy.find(e=>t.startsWith(e));return r||null},Ry=e=>{const t=e.match(/(^|\s)([^\s]*)$/);if(!t)return null;const n=t[2]||"",r=e.length;return {token:n,start:r-n.length,end:r}},qy=globalThis.fuzzysort,Py=qy&&"function"==typeof qy.single?qy:{single:()=>null,go:()=>[],prepare:e=>e,cleanup:()=>{}},By=["outline","conversations","prompts","settings"],Oy=Object.entries(rr).reduce((e,[t,n])=>(e[n]||(e[n]=[]),e[n].push(t),e),{}),zy=e=>{if("inbox"===e.id)return (()=>{const e=re("conversationsInbox");return "conversationsInbox"===e?"Inbox":e})();const t=(e.name||"").trim(),n=(e.icon||"").trim();return n&&t.startsWith(n)?t.slice(n.length).trim():t},Fy=({normalizedQuery:e,fields:t})=>{if(!e)return null;let n=null;const r=e.length>=8?2:1;return t.forEach(t=>{if(!t.value)return;const r=Py.single(e,t.value);!r||r.score<.24||(!n||r.score>n.score)&&(n={score:r.score,matchReason:t.matchReason,highlightField:t.highlightField,indexes:Array.from(r.indexes||[]),isTypoFallback:false});}),n||(e.length<4?null:(t.forEach(t=>{if(!t.value)return;var o;((o=t.value)?o.split(/[^a-z0-9\u4e00-\u9fff]+/gi).map(e=>e.trim()).filter(e=>e.length>0):[]).forEach(o=>{if(Math.abs(o.length-e.length)>r)return;const i=((e,t,n)=>{const r=e.length,o=t.length;if(e===t)return 0;if(Math.abs(r-o)>n)return n+1;const i=new Array(o+1).fill(0),a=new Array(o+1),s=new Array(o+1);for(let l=0;l<=o;l+=1)a[l]=l;for(let l=1;l<=r;l+=1){s[0]=l;let r=s[0];for(let n=1;n<=o;n+=1){const o=e[l-1]===t[n-1]?0:1;let c=Math.min(a[n]+1,s[n-1]+1,a[n-1]+o);l>1&&n>1&&e[l-1]===t[n-2]&&e[l-2]===t[n-1]&&(c=Math.min(c,i[n-2]+1)),s[n]=c,cn)return n+1;for(let e=0;e<=o;e+=1)i[e]=a[e],a[e]=s[e];}return a[o]})(e,o,r);if(i>r)return;const a=Math.max(.24,.58-.14*i-.03*Math.abs(o.length-e.length));(!n||a>n.score)&&(n={score:a,matchReason:t.matchReason,highlightField:t.highlightField,indexes:void 0,isTypoFallback:true});});}),n))},jy=({normalizedQuery:e,tokens:t,index:n,fields:r,enableFuzzySearch:o,baseScoreWhenEmpty:i=1e3})=>{const a=r.map(e=>e.value).join(" "),s=t.every(e=>a.includes(e)),l=o&&e?Fy({normalizedQuery:e,fields:r}):null;if(!s&&!l)return null;if(!e)return {score:i-n,matchLevel:0,exactHitCount:0,prefixHitCount:0,includesHitCount:0,matchReasons:[]};let c=0,d=0,u=0,h=0,g=0;const p=new Set;r.forEach(n=>{const r=n.value;if(!r)return;let o=0,i=false,a=false;r===e?(c+=n.exact,o=3,u+=1):r.startsWith(e)?(c+=n.prefix,o=2,h+=1):r.includes(e)&&(c+=n.includes,o=1,g+=1),d=Math.max(d,o),o>0&&n.matchReason&&p.add(n.matchReason),t.forEach(e=>{r.startsWith(e)&&(c+=n.tokenPrefix,i=true),r.includes(e)&&(c+=n.tokenIncludes,a=true);}),0===o?i?(d=Math.max(d,2),h+=1,n.matchReason&&p.add(n.matchReason)):a&&(d=Math.max(d,1),g+=1,n.matchReason&&p.add(n.matchReason)):d=Math.max(d,o);});const m=Boolean(l&&0===d);if(m&&l){const e=Math.round(64*l.score);c+=e+16,p.add("fuzzy"),l.matchReason&&p.add(l.matchReason);}return 0!==d||l?{score:c,matchLevel:d,exactHitCount:u,prefixHitCount:h,includesHitCount:g,matchReasons:Array.from(p),fuzzyMatch:m?{field:l?.highlightField,indexes:l?.indexes,isTypoFallback:l?.isTypoFallback}:void 0}:null},$y=(e,t)=>{if(t.scoreMeta.matchLevel!==e.scoreMeta.matchLevel)return t.scoreMeta.matchLevel-e.scoreMeta.matchLevel;if(t.scoreMeta.exactHitCount!==e.scoreMeta.exactHitCount)return t.scoreMeta.exactHitCount-e.scoreMeta.exactHitCount;if(t.scoreMeta.prefixHitCount!==e.scoreMeta.prefixHitCount)return t.scoreMeta.prefixHitCount-e.scoreMeta.prefixHitCount;if(t.scoreMeta.includesHitCount!==e.scoreMeta.includesHitCount)return t.scoreMeta.includesHitCount-e.scoreMeta.includesHitCount;if(t.scoreMeta.score!==e.scoreMeta.score)return t.scoreMeta.score-e.scoreMeta.score;const n=e.recency||0,r=t.recency||0;return r!==n?r-n:e.index-t.index},Hy=({activeGlobalSearchPlainQuery:e,enableFuzzySearch:t,activeGlobalSearchSyntaxFilters:n,settingsSearchResults:r,resolveSettingSearchTitle:o,getSettingsBreadcrumb:i,conversationManager:a,conversationsSnapshot:s,foldersSnapshot:l,tagsSnapshot:c,promptsSnapshot:d,outlineManager:u,outlineSearchVersion:h,getLocalizedText:g,activeGlobalSearchCategory:p,expandedGlobalSearchCategories:m,allCategoryItemLimit:f})=>{const b=R(()=>{const n=Ey(e),a=_y(e);return r.map((e,r)=>{const s=o(e),l=Ey(s),c=Ey((e.keywords||[]).join(" ")),d=Ey(e.settingId),u=Ey((Oy[e.settingId]||[]).join(" ")),h=jy({normalizedQuery:n,tokens:a,index:r,enableFuzzySearch:t,fields:[{value:l,exact:220,prefix:140,includes:100,tokenPrefix:24,tokenIncludes:12,matchReason:"title",highlightField:"title"},{value:c,exact:0,prefix:0,includes:68,tokenPrefix:0,tokenIncludes:8,matchReason:"keyword"},{value:d,exact:0,prefix:0,includes:48,tokenPrefix:0,tokenIncludes:6,matchReason:"id",highlightField:"code"},{value:u,exact:0,prefix:0,includes:44,tokenPrefix:0,tokenIncludes:6,matchReason:"alias"}]});return null===h?null:{item:{id:`settings:${e.settingId}`,title:s,breadcrumb:i(e.settingId),code:e.settingId,category:"settings",settingId:e.settingId,matchReasons:h.matchReasons,fuzzyMatch:h.fuzzyMatch},scoreMeta:h,index:r}}).filter(e=>Boolean(e)).sort($y).map(({item:e})=>e)},[e,t,i,o,r]),y=R(()=>{if(!a)return [];const n=a.getConversations(),r=a.getFolders(),o=a.getTags(),i=new Map(r.map(e=>[e.id,e])),s=new Map(o.map(e=>[e.id,e])),l=Ey(e),c=_y(e),d=g({key:"untitledConversation",fallback:"Untitled conversation"});return n.map((e,n)=>{const r=e.title?.trim()||d,o=i.get(e.folderId),a=o?`${o.icon?`${o.icon} `:""}${zy(o)}`.trim():e.folderId,u=(e.tagIds||[]).map(e=>{const t=s.get(e);return t?{id:t.id,name:t.name,color:t.color}:null}).filter(e=>Boolean(e)),h=Ey(r),g=Ey(a),p=Ey(u.map(e=>e.name).join(" ")),m=jy({normalizedQuery:l,tokens:c,index:n,enableFuzzySearch:t,fields:[{value:h,exact:220,prefix:140,includes:100,tokenPrefix:24,tokenIncludes:12,matchReason:"title",highlightField:"title"},{value:g,exact:0,prefix:0,includes:72,tokenPrefix:0,tokenIncludes:8,matchReason:"folder",highlightField:"breadcrumb"},{value:p,exact:0,prefix:0,includes:64,tokenPrefix:0,tokenIncludes:8,matchReason:"tag"}]});if(null===m)return null;const f={...m,score:m.score+(e.pinned?6:0)};return {item:{id:`conversations:${e.id}`,title:r,breadcrumb:a,category:"conversations",conversationId:e.id,conversationUrl:e.url,tagBadges:u,folderName:a,tagNames:u.map(e=>e.name),isPinned:Boolean(e.pinned),searchTimestamp:e.updatedAt||0,matchReasons:f.matchReasons,fuzzyMatch:f.fuzzyMatch},scoreMeta:f,index:n,recency:e.updatedAt||0}}).filter(e=>Boolean(e)).sort($y).map(({item:e})=>e)},[a,s,l,c,g,e,t]),v=R(()=>{const n=Ey(e),r=_y(e),o=g({key:"globalSearchCategoryPrompts",fallback:"Prompts"}),i=g({key:"uncategorized",fallback:"Uncategorized"}),a=d.map((e,a)=>{const s=e.title?.trim()||e.content?.trim().split("\n")[0]||`${o} #${a+1}`,l=e.content?.trim()||"",c=e.category?.trim()||i,d=`${o} / ${c}`,u=Ey(s),h=Ey(l),g=Ey(c),p=Ey(e.id),m=jy({normalizedQuery:n,tokens:r,index:a,enableFuzzySearch:t,fields:[{value:u,exact:220,prefix:140,includes:100,tokenPrefix:24,tokenIncludes:12,matchReason:"title",highlightField:"title"},{value:g,exact:0,prefix:0,includes:70,tokenPrefix:0,tokenIncludes:8,matchReason:"category",highlightField:"breadcrumb"},{value:h,exact:0,prefix:0,includes:60,tokenPrefix:0,tokenIncludes:6,matchReason:"content",highlightField:"snippet"},{value:p,exact:0,prefix:0,includes:20,tokenPrefix:0,tokenIncludes:4,matchReason:"id",highlightField:"code"}]});if(null===m)return null;const f={...m,score:m.score+(e.pinned?6:0)},b=f.matchReasons.includes("content")?(({content:e,normalizedQuery:t,tokens:n,maxLength:r=84})=>{const o=e.replace(/\s+/g," ").trim();if(!o)return "";const i=Array.from(new Set([t,...n])).filter(Boolean),a=o.toLowerCase();let s=-1;if(i.forEach(e=>{const t=a.indexOf(e);-1!==t&&(-1===s||tr?`${o.slice(0,r).trim()}…`:o;let l=Math.max(0,s-Math.floor(.25*r));const c=Math.min(o.length,l+r);return c>=o.length&&(l=Math.max(0,o.length-r)),`${l>0?"…":""}${o.slice(l,c).trim()}${cBoolean(e)).sort($y);return a.map(({item:e})=>e)},[e,t,g,d]),w=R(()=>{if(!u)return [];const n=(e=>{const t=[],n=e=>{e.forEach(e=>{t.push(e),e.children&&e.children.length>0&&n(e.children);});};return n(e),t})(u.getTree()),r=Ey(e),o=_y(e),i=g({key:"globalSearchCategoryOutline",fallback:"Outline"}),a=g({key:"outlineOnlyUserQueries",fallback:"Queries"}),s=g({key:"globalSearchOutlineReplies",fallback:"Replies"});return n.map((e,n)=>{const l=e.text?.trim();if(!l)return null;const c=e.isUserQuery?`Q${e.queryIndex??n+1}`:`H${e.level}`,d=e.isUserQuery?a:s,u=e.isUserQuery?`${i} / ${d}`:`${i} / ${d} / H${e.level}`,h=Ey(l),g=Ey(e.isUserQuery?d:`${d} h${e.level}`),p=Ey(c),m=jy({normalizedQuery:r,tokens:o,index:n,enableFuzzySearch:t,fields:[{value:h,exact:200,prefix:120,includes:90,tokenPrefix:16,tokenIncludes:10,matchReason:"title",highlightField:"title"},{value:g,exact:0,prefix:0,includes:48,tokenPrefix:0,tokenIncludes:6,matchReason:"type",highlightField:"breadcrumb"},{value:p,exact:0,prefix:0,includes:36,tokenPrefix:0,tokenIncludes:4,matchReason:"code",highlightField:"code"}]});if(null===m)return null;const f={...m,score:m.score+(e.isBookmarked?4:0)};return {item:{id:`outline:${e.index}`,title:l,breadcrumb:u,code:c,category:"outline",matchReasons:f.matchReasons,fuzzyMatch:f.fuzzyMatch,outlineTarget:{index:e.index,level:e.level,text:l,isUserQuery:Boolean(e.isUserQuery),queryIndex:e.queryIndex,isGhost:Boolean(e.isGhost),scrollTop:e.scrollTop}},scoreMeta:f,index:n}}).filter(e=>Boolean(e)).sort($y).map(({item:e})=>e)},[e,t,u,g,h]),x=R(()=>[...b,...y,...w,...v],[y,w,v,b]),k=R(()=>x.filter(e=>((e,t)=>0===t.length||t.every(t=>{const n=t.normalizedValue;if("type"===t.key)return e.category.toLowerCase().includes(n);if("folder"===t.key)return (e.folderName||e.breadcrumb||"").toLowerCase().includes(n);if("tag"===t.key)return (e.tagNames||e.tagBadges?.map(e=>e.name)||[]).some(e=>e.toLowerCase().includes(n));if("is"===t.key)return "pinned"===n?Boolean(e.isPinned):"unpinned"===n&&!e.isPinned;if("level"===t.key)return "outline"===e.category&&String(e.outlineTarget?.level??"")===n;if("date"===t.key){if("conversations"!==e.category&&"prompts"!==e.category)return false;const t=Ty(n);if(null===t)return false;const r=e.searchTimestamp||0;return !(r<=0)&&Date.now()-r<=864e5*t}return true}))(e,n)),[n,x]),S=R(()=>{const e={all:0,outline:0,conversations:0,prompts:0,settings:0};return k.forEach(t=>{e[t.category]+=1,e.all+=1;}),e},[k]),C=R(()=>"all"!==p?[]:By.map(e=>{const t=k.filter(t=>t.category===e),n=Boolean(m[e]),r=n?t.length:f,o=t.slice(0,r),i=Math.max(0,t.length-o.length);return {category:e,items:o,totalCount:t.length,hasMore:i>0,isExpanded:n,remainingCount:i}}).filter(e=>e.items.length>0),[p,f,m,k]),E=R(()=>"all"!==p?k.filter(e=>e.category===p):C.flatMap(e=>e.items),[p,k,C]);return {filteredGlobalSearchResults:k,globalSearchResultCounts:S,groupedGlobalSearchResults:C,visibleGlobalSearchResults:E}},Uy={[Rn]:{key:"navGeneral",fallback:"General"},[Pn]:{key:"navFeatures",fallback:"Features"},[Bn]:{key:"navSiteSettings",fallback:"Site Config"},[On]:{key:"navGlobalSearch",fallback:"Global Search"},[qn]:{key:"navAppearance",fallback:"Appearance"},[zn]:{key:"navShortcuts",fallback:"Keyboard Shortcuts"},[Fn]:{key:"navBackup",fallback:"Data Management"},[jn]:{key:"navPermissions",fallback:"Permissions"},[$n]:{key:"navAbout",fallback:"About"}},Wy={panel:{key:"panelTab",fallback:"Panel"},tabOrder:{key:"tabOrderTab",fallback:"Tab Order"},shortcuts:{key:"shortcutsTab",fallback:"Quick Buttons"},toolsMenu:{key:"toolboxMenu",fallback:"Toolbox"},[Vn]:{key:"tabSettingsTab",fallback:"Tab Settings"},[Gn]:{key:"reminderTab",fallback:"Alerts"},[Hn]:{key:"outlineSettingsTitle",fallback:"Outline"},[Un]:{key:"conversationsSettingsTitle",fallback:"Conversations"},[Wn]:{key:"promptSettingsTitle",fallback:"Prompts"},[Kn]:{key:"readingHistorySettings",fallback:"Reading History"},[Qn]:{key:"contentProcessing",fallback:"Content"},[Zn]:{key:"toolboxMenu",fallback:"Toolbox"},[Xn]:{key:"layoutTab",fallback:"Layout"},[er]:{key:"tabModelLock",fallback:"Model Lock"},gemini:{key:"geminiSettingsTab",fallback:"Gemini"},aistudio:{key:"aistudioSettingsTitle",fallback:"AI Studio"},chatgpt:{key:"chatgptSettingsTitle",fallback:"ChatGPT"},claude:{key:"claudeSettingsTab",fallback:"Claude"},[Yn]:{key:"themePresetsTab",fallback:"Theme Presets"},[Jn]:{key:"customStylesTab",fallback:"Custom Styles"}},Vy=[{id:"all",label:{key:"globalSearchCategoryAll",fallback:"All"},placeholder:{key:"globalSearchPlaceholderAll",fallback:"Search all"},emptyText:{key:"globalSearchEmptyAll",fallback:"No matching results"}},{id:"outline",label:{key:"globalSearchCategoryOutline",fallback:"Outline"},placeholder:{key:"globalSearchPlaceholderOutline",fallback:"Search outline"},emptyText:{key:"globalSearchEmptyOutline",fallback:"No outline results"}},{id:"conversations",label:{key:"globalSearchCategoryConversations",fallback:"Conversations"},placeholder:{key:"globalSearchPlaceholderConversations",fallback:"Search conversations on current site"},emptyText:{key:"globalSearchEmptyConversations",fallback:"No conversation results"}},{id:"prompts",label:{key:"globalSearchCategoryPrompts",fallback:"Prompts"},placeholder:{key:"globalSearchPlaceholderPrompts",fallback:"Search prompts"},emptyText:{key:"globalSearchEmptyPrompts",fallback:"No prompt results"}},{id:"settings",label:{key:"globalSearchCategorySettings",fallback:"Settings"},placeholder:{key:"globalSearchPlaceholderSettings",fallback:"Search settings"},emptyText:{key:"globalSearchEmptySettings",fallback:"No matching settings"}}],Gy={outline:{key:"globalSearchCategoryOutline",fallback:"Outline"},settings:{key:"globalSearchCategorySettings",fallback:"Settings"},conversations:{key:"globalSearchCategoryConversations",fallback:"Conversations"},prompts:{key:"globalSearchCategoryPrompts",fallback:"Prompts"}},Qy={title:{key:"globalSearchMatchReasonTitle",fallback:"Title match"},folder:{key:"globalSearchMatchReasonFolder",fallback:"Folder match"},tag:{key:"globalSearchMatchReasonTag",fallback:"Tag match"},type:{key:"globalSearchMatchReasonType",fallback:"Type match"},code:{key:"globalSearchMatchReasonCode",fallback:"Code match"},category:{key:"globalSearchMatchReasonCategory",fallback:"Category match"},content:{key:"globalSearchMatchReasonContent",fallback:"Content match"},id:{key:"globalSearchMatchReasonId",fallback:"ID match"},keyword:{key:"globalSearchMatchReasonKeyword",fallback:"Keyword match"},alias:{key:"globalSearchMatchReasonAlias",fallback:"Alias match"},fuzzy:{key:"globalSearchMatchReasonFuzzy",fallback:"Fuzzy match"}},Ky="settings-search-option",Zy="ophel:global-search-shortcut-nudge:v1",Yy={"aistudio-collapse-advanced":"aistudioCollapseAdvanced","aistudio-collapse-navbar":"aistudioCollapseNavbar","aistudio-collapse-run-settings":"aistudioCollapseRunSettings","aistudio-collapse-tools":"aistudioCollapseTools","aistudio-enable-search":"aistudioEnableSearch","aistudio-markdown-fix":"aistudioMarkdownFixLabel","aistudio-remove-watermark":"aistudioRemoveWatermark","appearance-custom-styles":"customCSS","appearance-preset-dark":"darkModePreset","appearance-preset-light":"lightModePreset","chatgpt-markdown-fix":"chatgptMarkdownFixLabel","conversation-sync-delete":"conversationsSyncDeleteLabel","global-search-fuzzy-search":"globalSearchEnableFuzzySearchLabel","global-search-double-shift":"doubleShiftToSearch","global-search-shortcut-setting-link":"globalSearchShortcutSettingLabel","global-search-prompt-enter-behavior":"globalSearchPromptEnterBehaviorLabel","claude-session-keys":"claudeSessionKeyTitle","content-assistant-mermaid":"assistantMermaidLabel","content-formula-copy":"formulaCopyLabel","content-formula-delimiter":"formulaDelimiterLabel","content-table-copy":"tableCopyLabel","content-user-query-markdown":"userQueryMarkdownLabel","conversation-folder-rainbow":"folderRainbowLabel","conversation-sync-unpin":"conversationsSyncUnpinLabel","export-custom-model-name":"exportCustomModelName","export-custom-user-name":"exportCustomUserName","export-filename-timestamp":"exportFilenameTimestamp","export-include-thoughts":"exportIncludeThoughtsLabel","export-images-base64":"exportImagesToBase64Label","gemini-markdown-fix":"markdownFixLabel","gemini-policy-max-retries":"maxRetriesLabel","gemini-policy-retry":"policyRetryLabel","gemini-watermark-removal":"watermarkRemovalLabel","layout-page-width-enabled":"enablePageWidth","layout-page-width-value":"pageWidthValueLabel","layout-user-query-width-enabled":"enableUserQueryWidth","layout-user-query-width-value":"userQueryWidthValueLabel","layout-zen-mode-enabled":"zenModeTitle","outline-auto-update":"outlineAutoUpdateLabel","outline-follow-mode":"outlineFollowModeLabel","outline-inline-bookmark-mode":"inlineBookmarkModeLabel","outline-panel-bookmark-mode":"panelBookmarkModeLabel","outline-prevent-auto-scroll":"preventAutoScrollLabel","outline-show-word-count":"outlineShowWordCountLabel","outline-update-interval":"outlineUpdateIntervalLabel","panel-auto-hide":"autoHidePanelLabel","panel-default-open":"defaultPanelStateLabel","panel-default-position":"defaultPositionLabel","panel-edge-distance":"defaultEdgeDistanceLabel","panel-edge-snap":"edgeSnapHideLabel","panel-edge-snap-threshold":"edgeSnapThresholdLabel","panel-height":"panelHeightLabel","panel-width":"panelWidthLabel","prompt-double-click-send":"promptDoubleClickSendLabel","prompt-queue":"queueSettingLabel","quick-buttons-opacity":"quickButtonsOpacityLabel","reading-history-auto-restore":"readingHistoryAutoRestoreLabel","reading-history-cleanup-days":"readingHistoryCleanup","reading-history-persistence":"readingHistoryPersistenceLabel","shortcuts-enabled":"enableShortcuts","shortcuts-global-url":"globalShortcutUrl","shortcuts-browser-shortcuts":"globalShortcutsTitle","shortcuts-prompt-submit-shortcut":"promptSubmitShortcutLabel","tab-auto-focus":"autoFocusLabel","tab-auto-rename":"autoRenameTabLabel","tab-notification-sound":"notificationSoundLabel","tab-notification-sound-preset":"notificationSoundPresetLabel","tab-notification-volume":"notificationVolumeLabel","tab-notification-repeat-count":"notificationRepeatCountLabel","tab-notification-repeat-interval":"notificationRepeatIntervalLabel","tab-notify-when-focused":"notifyWhenFocusedLabel","tab-open-new":"openNewTabLabel","tab-privacy-mode":"privacyModeLabel","tab-privacy-title":"privacyTitleLabel","tab-rename-interval":"renameIntervalLabel","tab-show-notification":"showNotificationLabel","tab-show-status":"showStatusLabel","tab-title-format":"titleFormatLabel","tools-menu-export":"export","tools-menu-copyMarkdown":"exportToClipboard","tools-menu-move":"conversationsMoveTo","tools-menu-setTag":"conversationsSetTag","tools-menu-scrollLock":"shortcutToggleScrollLock","tools-menu-modelLock":"modelLockTitle","tools-menu-cleanup":"cleanup","tools-menu-settings":"tabSettings","usage-monitor-enabled":"usageMonitorEnabledLabel","usage-monitor-daily-limit":"usageMonitorDailyLimitLabel","usage-monitor-auto-reset":"usageMonitorAutoResetLabel"},Jy={gemini:{key:"globalSearchSiteGemini",fallback:"Gemini"},"gemini-enterprise":{key:"globalSearchSiteGeminiEnterprise",fallback:"Gemini Enterprise"},aistudio:{key:"globalSearchSiteAIStudio",fallback:"AI Studio"},chatgpt:{key:"globalSearchSiteChatGPT",fallback:"ChatGPT"},claude:{key:"globalSearchSiteClaude",fallback:"Claude"},grok:{key:"globalSearchSiteGrok",fallback:"Grok"},qwenai:{key:"globalSearchSiteQwenAi",fallback:"QwenAI"},ima:{key:"globalSearchSiteIma",fallback:"ima"},zai:{key:"globalSearchSiteZai",fallback:"Z.ai"}},Xy=e=>e.replace(/[-_]/g," ").replace(/\s+/g," ").trim().replace(/\b([a-z])/g,(e,t)=>t.toUpperCase()),ev=Object.freeze(Object.defineProperty({__proto__:null,App:()=>{const{settings:e,setSettings:t,updateDeepSetting:n}=No(),r=Lo(),o=e?.features?.prompts?.submitShortcut??"enter";No(e=>e._syncVersion);const[i,a]=B(0),s=E(e=>{const t=re(e.key);return t===e.key?e.fallback:t},[i]),l=E((e,t)=>{let n=s(e);return Object.keys(t).forEach(e=>{n=n.replace(new RegExp(`{${e}}`,"g"),t[e]);}),n},[s]),c=R(()=>(()=>{if("undefined"==typeof navigator)return false;const e=navigator.platform?.toLowerCase?.()||"",t=navigator.userAgent?.toLowerCase?.()||"";return e.includes("mac")||t.includes("mac os")})(),[]),d=R(()=>{const t=e?.shortcuts?.keybindings?.[cn];return null===t?null:t||xn[cn]},[e?.shortcuts?.keybindings]),u=d?Tn(d,c):"",h=e?.globalSearch?.doubleShift??bo.globalSearch.doubleShift,g=R(()=>{const e=[];return u&&e.push(u),h&&e.push("double shift"),e.join(" / ")},[u,h]),p=g||re("shortcutNotSet")||"未设置",m=e?.globalSearch?.enableFuzzySearch??bo.globalSearch.enableFuzzySearch,f=R(()=>g?l({key:"globalSearchShortcutNudge",fallback:"下次可按 {shortcut} 快速打开"},{shortcut:g}):"",[l,g]),b=E(()=>{if("undefined"==typeof window)return {shownCount:0,lastShownAt:0,dismissed:false,shortcutUsedCount:0};try{const e=window.localStorage.getItem(Zy);if(!e)return {shownCount:0,lastShownAt:0,dismissed:!1,shortcutUsedCount:0};const t=JSON.parse(e);return {shownCount:Number.isFinite(t.shownCount)?Math.max(0,Number(t.shownCount)):0,lastShownAt:Number.isFinite(t.lastShownAt)?Math.max(0,Number(t.lastShownAt)):0,dismissed:Boolean(t.dismissed),shortcutUsedCount:Number.isFinite(t.shortcutUsedCount)?Math.max(0,Number(t.shortcutUsedCount)):0}}catch{return {shownCount:0,lastShownAt:0,dismissed:false,shortcutUsedCount:0}}},[]),y=E(e=>{if("undefined"!=typeof window)try{window.localStorage.setItem(Zy,JSON.stringify(e));}catch{}},[]),v=E(()=>{Be.current&&(clearTimeout(Be.current),Be.current=null);},[]),w=E(e=>{e.stopPropagation();const t=e.target.closest(".gh-code-copy-btn");if(!t)return;const n=t.nextElementSibling?.textContent||"";n&&(navigator.clipboard?.writeText?navigator.clipboard.writeText(n).then(()=>{_u(t,{size:14});}).catch(()=>{Oo(s({key:"copyFailed",fallback:"Copy failed"}));}):Oo(s({key:"copyFailed",fallback:"Copy failed"})));},[s]),x=E(()=>{qe.current&&(clearTimeout(qe.current),qe.current=null);},[]),k=E(e=>{x(),oe(e),ae(e);},[x]),S=E(()=>{t({globalSearch:{...bo.globalSearch,...e?.globalSearch||{},enableFuzzySearch:!m}});},[m,t,e?.globalSearch]),C=E(e=>{oe(e),x(),qe.current=setTimeout(()=>{ae(e),qe.current=null;},140);},[x]),_=E(()=>{v(),ve(false),xe("");},[v]),A=E(()=>{const e=b();y({...e,dismissed:true}),_();},[b,_,y]),T=E(()=>{const e=b(),t=e.shortcutUsedCount+1;y({...e,shortcutUsedCount:t,dismissed:e.dismissed||t>=2}),_();},[b,_,y]),I=E(()=>{if(!f)return;const e=b();if(e.dismissed)return;if(e.shortcutUsedCount>=2)return void y({...e,dismissed:true});if(e.shownCount>=3)return;const t=Date.now();e.lastShownAt>0&&t-e.lastShownAt<864e5||(y({...e,shownCount:e.shownCount+1,lastShownAt:t}),xe(f),ve(true),v(),Be.current=setTimeout(()=>{ve(false),xe(""),Be.current=null;},6e3));},[v,b,f,y]),N=E(e=>{const t=Uy[e];return t?s(t):e},[s]),L=E(e=>{const t=Wy[e];return t?s(t):e},[s]),D=E(e=>{const t=Yy[e.settingId];if(t)return s({key:t,fallback:Xy(e.settingId)});if(e.settingId.startsWith("model-lock-")){const t=e.settingId.slice(11),n=Jy[t];if(n){return `${s({key:"tabModelLock",fallback:"Model Lock"})}: ${s(n)}`}}if(e.settingId.startsWith("shortcut-binding-")){const t=e.settingId.slice(17),n=vn[t];if(n){return `${s({key:"navShortcuts",fallback:"Keyboard Shortcuts"})}: ${s({key:n.labelKey,fallback:n.label})}`}}return Xy(e.settingId)},[s]),q=E(e=>{const t=ir(e);if(!t)return s({key:"globalSearchCategorySettings",fallback:"Settings"});const n=N(t.page);if(!t.subTab)return n;return `${n} / ${L(t.subTab)}`},[s,N,L]),z=R(()=>Hp(),[]),F=R(()=>z?new ym(z):null,[z]),j=R(()=>z&&F?new xm(z,F):null,[z,F]);M(()=>{if(!j)return;return e?.features?.prompts?.promptQueue??false?j.start():j.stop(),()=>j.stop()},[j,e?.features?.prompts?.promptQueue]);const $=R(()=>z?new nm(z):null,[z]),H=R(()=>{if(!z)return null;return new dm(z,e?.features?.outline??bo.features.outline,e=>{n("features","outline","expandLevel",e);},e=>{n("features","outline","showUserQueries",e);})},[z,n]),[U,W]=B(false),V=P(e);M(()=>{V.current=e;},[e]),M(()=>{if(r&&e&&!ht.current&&(ht.current=true,e.panel?.defaultOpen)){const{edgeSnap:t,defaultEdgeDistance:n=25,edgeSnapThreshold:r=18,defaultPosition:o="right"}=e.panel;t&&n<=r&&rt(o),W(true);}},[r,e]),M(()=>{if(!r||!e)return;let n=false;const o={},i=e.collapsedButtons||[];let a=i;if(!a.some(e=>"floatingToolbar"===e.id)){a=[...a];const e=a.findIndex(e=>"panel"===e.id),t=e>=0?e+1:a.length;a.splice(t,0,{id:"floatingToolbar",enabled:true}),n=true;}if(!a.some(e=>"globalSearch"===e.id)){a===i&&(a=[...a]);const e=a.findIndex(e=>"floatingToolbar"===e.id),t=e>=0?e+1:a.length;a.splice(t,0,{id:"globalSearch",enabled:true}),n=true;}a!==i&&(o.collapsedButtons=a),e.floatingToolbar||(o.floatingToolbar={open:true},n=true),n&&t(o);},[r,e,t]);const[G,Q]=B(null),[K,Z]=B(false),[Y,J]=B(false),[X,ee]=B("all"),[ne,oe]=B(""),[ie,ae]=B(""),[se,le]=B(0),[ce,de]=B(false),[ue,he]=B("pointer"),[ge,pe]=B({}),[me,ve]=B(false),[we,xe]=B(""),[ke,Se]=B(false),[Ce,Ee]=B(-1),[_e,Ae]=B(()=>"undefined"!=typeof window&&Boolean(window.__OPHEL_EXTENSION_UPDATE_AVAILABLE__)),[Te,Me]=B(()=>"undefined"!=typeof window&&window.__OPHEL_PENDING_UPDATE_VERSION__||null),Ie=P(null),Ne=P(null),Le=P(null),De=P(null),Re=P(null),qe=P(null),Pe=P(0),Be=P(null),Oe=P("ui"),ze=P(0),[Fe,je]=B(0),$e=P(null),{globalSearchPromptPreview:He,globalSearchPromptPreviewPosition:Ue,clearPromptPreviewTimer:We,clearPromptPreviewHideTimer:Ve,hideGlobalSearchPromptPreview:Ge,scheduleHideGlobalSearchPromptPreview:Qe,scheduleGlobalSearchPromptPreview:Ke,scheduleGlobalSearchPointerPreview:Ze,refreshGlobalSearchPromptPreviewAnchorRect:Ye}=(({settingsSearchResultsRef:e,pointerDelayMs:t,hideDelayMs:n})=>{const[r,o]=B(null),i=P(null),a=P(null),s=P(null),l=E(()=>{i.current&&(clearTimeout(i.current),i.current=null);},[]),c=E(()=>{a.current&&(clearTimeout(a.current),a.current=null);},[]),d=E(t=>{const n=e.current;if(!n)return null;const r=n.querySelectorAll("[data-global-search-item-id]");for(const e of r)if(e.dataset.globalSearchItemId===t)return e;return null},[e]),u=E(()=>{l(),c(),s.current=null,o(null);},[c,l]),h=E((e=n)=>{c(),a.current=setTimeout(()=>{u(),a.current=null;},e);},[c,n,u]),g=E(({item:e,anchorElement:t,delay:n,source:r})=>{"prompts"===e.category&&e.promptId&&e.promptContent&&e.promptContent.trim()&&(l(),c(),"keyboard"===r&&(s.current=e.id),i.current=setTimeout(()=>{"keyboard"===r&&s.current!==e.id||(o({itemId:e.id,content:e.promptContent,anchorRect:t.getBoundingClientRect()}),i.current=null);},n));},[c,l]),p=E(({item:e,anchorElement:n})=>{s.current=null,g({item:e,anchorElement:n,delay:t,source:"pointer"});},[t,g]),m=E(()=>{o(e=>{if(!e)return e;const t=d(e.itemId);if(!t)return null;const n=t.getBoundingClientRect();return Math.abs(n.top-e.anchorRect.top)<.5&&Math.abs(n.left-e.anchorRect.left)<.5&&Math.abs(n.right-e.anchorRect.right)<.5&&Math.abs(n.bottom-e.anchorRect.bottom)<.5?e:{...e,anchorRect:n}});},[d]),f=R(()=>{if(!r||"undefined"==typeof window)return null;const e=16,t=Math.max(280,Math.min(420,window.innerWidth-32)),n=Math.max(220,Math.min(420,window.innerHeight-32));let o=r.anchorRect.right+12;return o+t>window.innerWidth-e&&(o=r.anchorRect.left-t-12),o=Math.max(e,Math.min(o,window.innerWidth-t-e)),{top:Math.max(e,Math.min(r.anchorRect.top,window.innerHeight-e-n)),left:o}},[r]);return {globalSearchPromptPreview:r,globalSearchPromptPreviewPosition:f,clearPromptPreviewTimer:l,clearPromptPreviewHideTimer:c,hideGlobalSearchPromptPreview:u,scheduleHideGlobalSearchPromptPreview:h,scheduleGlobalSearchPromptPreview:g,scheduleGlobalSearchPointerPreview:p,refreshGlobalSearchPromptPreviewAnchorRect:m}})({settingsSearchResultsRef:De,pointerDelayMs:450,hideDelayMs:220}),[Je,Xe]=B(null),[et,tt]=B(false),[nt,rt]=B(null),[ot,it]=B(false),at=P(false),st=P(null),lt=P(null),ct=P(false),dt=P(false),ut=P(false),ht=P(false);M(()=>{const e=e=>{Y&&(dt.current=false,$e.current=null,x(),J(false),ee("all"),oe(""),ae(""),Ee(-1),le(0),de(false),he("pointer"),pe({}),Pe.current=0),ct.current||(ct.current=true,nt&&V.current?.panel?.edgeSnap&&it(true),Z(true));};return window.addEventListener("ophel:navigateSettingsPage",e),()=>window.removeEventListener("ophel:navigateSettingsPage",e)},[x,nt,Y]);const gt=Wp(e=>e.conversations),pt=Zp(e=>e.folders),mt=Xp(e=>e.tags),ft=um(e=>e.prompts),bt=R(()=>(e=>{const t=/(^|\s)([a-z]+):((?:"(?:\\.|[^"])+")|(?:\\.|[^\s])+)/gi,n=[],r=[],o=[],i={};let a=t.exec(e);for(;a;){const s=(a[2]||"").toLowerCase(),l=a[3]||"",c=(a.index||0)+(a[1]?.length||0),d=c+`${s}:${l}`.length,u=l.startsWith('"')!==l.endsWith('"'),h=Dy(s),g=Ay(l),p=Ey(g);if(!wy.includes(s)){r.push({id:`unknown:${s}:${a.index||0}`,code:"unknownOperator",operator:s,suggestion:h||void 0}),a=t.exec(e);continue}const m=s;if(u){r.push({id:`invalid:${m}:quote:${a.index||0}`,code:"invalidValue",operator:m,value:l}),o.push({start:c,end:d}),a=t.exec(e);continue}if(!g){r.push({id:`invalid:${m}:empty:${a.index||0}`,code:"invalidValue",operator:m}),o.push({start:c,end:d}),a=t.exec(e);continue}if(!Iy(m,p)){r.push({id:`invalid:${m}:${p}:${a.index||0}`,code:"invalidValue",operator:m,value:g,suggestion:Ny(m)}),o.push({start:c,end:d}),a=t.exec(e);continue}const f=(i[m]||0)+1;i[m]=f;const b={id:Ly(m,p,f),key:m,value:g,normalizedValue:p};My(b,n)?(r.push({id:`conflict:${m}:${p}:${a.index||0}`,code:"conflict",operator:m,value:g}),o.push({start:c,end:d}),a=t.exec(e)):(o.push({start:c,end:d}),n.push(b),a=t.exec(e));}if(0===o.length)return {rawQuery:e,plainQuery:e.trim(),filters:n,diagnostics:r};o.sort((e,t)=>e.start-t.start);let s="",l=0;return o.forEach(t=>{lbt.filters,[bt.filters]),vt=R(()=>bt.diagnostics,[bt.diagnostics]),wt=R(()=>bt.plainQuery,[bt.plainQuery]),xt=R(()=>cr(""),[]);M(()=>{if(!H||!Y)return;const e=()=>{H.refresh(),je(e=>e+1);};e();const t=H.subscribe(()=>{je(e=>e+1);}),n=window.setInterval(()=>{e();},1200);return ()=>{t(),window.clearInterval(n);}},[Y,H]);const kt=R(()=>Array.from(new Set(_y(wt))).sort((e,t)=>t.length-e.length),[wt]),{filteredGlobalSearchResults:St,globalSearchResultCounts:Ct,groupedGlobalSearchResults:Et,visibleGlobalSearchResults:_t}=Hy({activeGlobalSearchPlainQuery:wt,enableFuzzySearch:m,activeGlobalSearchSyntaxFilters:yt,settingsSearchResults:xt,resolveSettingSearchTitle:D,getSettingsBreadcrumb:q,conversationManager:$,conversationsSnapshot:gt,foldersSnapshot:pt,tagsSnapshot:mt,promptsSnapshot:ft,outlineManager:H,outlineSearchVersion:Fe,getLocalizedText:s,activeGlobalSearchCategory:X,expandedGlobalSearchCategories:ge,allCategoryItemLimit:12}),At=R(()=>{const e=new Map;return _t.forEach((t,n)=>{e.set(t.id,n);}),e},[_t]),Tt=R(()=>0===_t.length?-1:Math.min(se,_t.length-1),[se,_t.length]),Mt=Tt>=0?`${Ky}-${Tt}`:void 0,It=R(()=>Vy.find(e=>e.id===X)||Vy[0],[X]),Nt=R(()=>({label:s(It.label),placeholder:s(It.placeholder),emptyText:s(It.emptyText)}),[It,s]),Lt=R(()=>Vy.reduce((e,t)=>(e[t.id]=s(t.label),e),{}),[s]),Dt=R(()=>Object.entries(Gy).reduce((e,[t,n])=>(e[t]=s(n),e),{}),[s]),Rt=R(()=>Object.entries(Qy).reduce((e,[t,n])=>(e[t]=s(n),e),{}),[s]),{activeGlobalSearchFilterChips:qt,hasOverflowGlobalSearchFilterChips:Pt,globalSearchSyntaxDiagnosticMessages:Bt,globalSearchSyntaxHelpTitle:Ot,globalSearchSyntaxHelpDescription:zt,globalSearchSyntaxHelpItems:Ft,globalSearchSyntaxSuggestions:jt,shouldShowGlobalSearchSyntaxSuggestions:$t}=(({getLocalizedText:e,activeGlobalSearchSyntaxFilters:t,filterChipMaxCount:n,isGlobalSettingsSearchOpen:r,settingsSearchInputValue:o,filteredGlobalSearchResults:i,suggestionLimit:a})=>{const s=R(()=>({type:e({key:"globalSearchSyntaxOperatorType",fallback:"Type"}),folder:e({key:"globalSearchSyntaxOperatorFolder",fallback:"Folder"}),tag:e({key:"globalSearchSyntaxOperatorTag",fallback:"Tag"}),is:e({key:"globalSearchSyntaxOperatorIs",fallback:"State"}),level:e({key:"globalSearchSyntaxOperatorLevel",fallback:"Level"}),date:e({key:"globalSearchSyntaxOperatorDate",fallback:"Date"})}),[e]),l=R(()=>({type:e({key:"globalSearchSyntaxOperatorType",fallback:"Type"}),folder:e({key:"globalSearchSyntaxOperatorFolder",fallback:"Folder"}),tag:e({key:"globalSearchSyntaxOperatorTag",fallback:"Tag"}),is:e({key:"globalSearchSyntaxOperatorIs",fallback:"State"}),level:e({key:"globalSearchSyntaxOperatorLevel",fallback:"Level"}),date:e({key:"globalSearchSyntaxOperatorDate",fallback:"Date"})}),[e]),c=R(()=>e({key:"globalSearchSyntaxSuggestionLevelDesc",fallback:"Filter outline level (0 = user query)"}),[e]),d=R(()=>e({key:"globalSearchSyntaxSuggestionDateDesc",fallback:"Filter by recent days (conversations and prompts only)"}),[e]),u=R(()=>({type:e({key:"globalSearchSyntaxSuggestionTypeDesc",fallback:"Filter by result type"}),folder:e({key:"globalSearchSyntaxSuggestionFolderDesc",fallback:"Filter by folder or category"}),tag:e({key:"globalSearchSyntaxSuggestionTagDesc",fallback:"Filter by tag name"}),is:e({key:"globalSearchSyntaxSuggestionIsDesc",fallback:"Filter by status"}),level:e({key:"globalSearchSyntaxSuggestionLevelDesc",fallback:"Filter outline level (0 = user query)"}),date:e({key:"globalSearchSyntaxSuggestionDateDesc",fallback:"Filter by recent days (conversations and prompts only)"})}),[e]),h=R(()=>({outline:e({key:"globalSearchCategoryOutline",fallback:"Outline"}),conversations:e({key:"globalSearchCategoryConversations",fallback:"Conversations"}),prompts:e({key:"globalSearchCategoryPrompts",fallback:"Prompts"}),settings:e({key:"globalSearchCategorySettings",fallback:"Settings"})}),[e]),g=R(()=>({pinned:e({key:"globalSearchSyntaxPinned",fallback:"Pinned"}),unpinned:e({key:"globalSearchSyntaxUnpinned",fallback:"Unpinned"})}),[e]),p=R(()=>({unknownOperator:e({key:"globalSearchSyntaxDiagnosticUnknownOperator",fallback:"Unknown operator"}),invalidValue:e({key:"globalSearchSyntaxDiagnosticInvalidValue",fallback:"Invalid filter value"}),conflict:e({key:"globalSearchSyntaxDiagnosticConflict",fallback:"Conflicting filters removed"})}),[e]),m=R(()=>e({key:"globalSearchSyntaxHelpTitle",fallback:"Search syntax examples"}),[e]),f=R(()=>e({key:"globalSearchSyntaxHelpDesc",fallback:"Click to insert. Keywords are English-only."}),[e]),b=R(()=>[{id:"help:type:outline",token:"type:outline",label:"type:outline",description:h.outline},{id:"help:type:conversations",token:"type:conversations",label:"type:conversations",description:h.conversations},{id:"help:type:prompts",token:"type:prompts",label:"type:prompts",description:h.prompts},{id:"help:type:settings",token:"type:settings",label:"type:settings",description:h.settings},{id:"help:is:pinned",token:"is:pinned",label:"is:pinned",description:g.pinned},{id:"help:is:unpinned",token:"is:unpinned",label:"is:unpinned",description:g.unpinned},{id:"help:level:0",token:"level:0",label:"level:0",description:e({key:"globalSearchSyntaxSuggestionLevelQueryDesc",fallback:"Outline user query"})},{id:"help:date:7d",token:"date:7d",label:"date:7d",description:d},{id:"help:date:30d",token:"date:30d",label:"date:30d",description:d},{id:"help:folder:inbox",token:"folder:inbox",label:"folder:inbox",description:u.folder},{id:"help:tag:work",token:"tag:work",label:"tag:work",description:u.tag}],[e,d,g.pinned,g.unpinned,u.folder,u.tag,h.conversations,h.outline,h.prompts,h.settings]),y=R(()=>t.slice(0,n).map(e=>({id:e.id,key:e.key,value:e.value,label:`${s[e.key]}: ${e.value}`})),[t,n,s]),v=t.length>n,w=R(()=>{if(!r)return [];const t=Ry(o),n=t?.token||"",s=n.length>0,p=n.toLowerCase(),m=n.match(/^([a-z]+):(.*)$/i);if(m){const t=m[1].toLowerCase();if(!wy.includes(t))return [];const n=m[2]||"",r=n.toLowerCase(),o=[],s=e=>{o.some(t=>t.id===e.id)||o.push(e);};if("type"===t)xy.forEach(e=>{n&&!e.toLowerCase().startsWith(r)||s({id:`type:${e}`,token:`type:${e}`,label:`type:${e} · ${h[e]}`,description:u.type});});else if("is"===t)n&&!"pinned".startsWith(r)||s({id:"is:pinned",token:"is:pinned",label:`is:pinned · ${g.pinned}`,description:u.is}),n&&!"unpinned".startsWith(r)||s({id:"is:unpinned",token:"is:unpinned",label:`is:unpinned · ${g.unpinned}`,description:u.is});else if("level"===t)Sy.forEach(t=>{n&&!t.startsWith(r)||s({id:`level:${t}`,token:`level:${t}`,label:`level:${t}`,description:"0"===t?e({key:"globalSearchSyntaxSuggestionLevelQueryDesc",fallback:"Outline user query"}):c});});else if("date"===t){const e=r.match(/^(\d{0,3})d?$/);if(e){const t=e[1];if(t){const e=`${t}d`;Number(t)>0&&s({id:`date:${e}`,token:`date:${e}`,label:`date:${e}`,description:d});}}Cy.forEach(e=>{n&&!e.startsWith(r)||s({id:`date:${e}`,token:`date:${e}`,label:`date:${e}`,description:d});});}if("folder"===t){const e=new Map;i.forEach(t=>{const o=(t.folderName||"").trim();if(!o)return;const i=o.toLowerCase();n&&!i.includes(r)||e.set(i,o);}),Array.from(e.values()).slice(0,a).forEach(e=>{const t=/\s/.test(e)?`folder:"${e}"`:`folder:${e}`;s({id:`folder:${e.toLowerCase()}`,token:t,label:`folder:${e}`,description:u.folder});});}if("tag"===t){const e=new Map;i.forEach(t=>{(t.tagNames||t.tagBadges?.map(e=>e.name)||[]).forEach(t=>{const o=t.trim();if(!o)return;const i=o.toLowerCase();n&&!i.includes(r)||e.set(i,o);});}),Array.from(e.values()).slice(0,a).forEach(e=>{const t=/\s/.test(e)?`tag:"${e}"`:`tag:${e}`;s({id:`tag:${e.toLowerCase()}`,token:t,label:`tag:${e}`,description:u.tag});});}return o.slice(0,a)}return wy.filter(e=>!s||e.startsWith(p)).map(e=>({id:`operator:${e}`,token:`${e}:`,label:`${e}: ${l[e]}`,description:u[e]})).slice(0,a)},[i,e,d,g,c,u,l,h,r,o,a]);return {activeGlobalSearchFilterChips:y,hasOverflowGlobalSearchFilterChips:v,globalSearchSyntaxDiagnosticMessages:p,globalSearchSyntaxHelpTitle:m,globalSearchSyntaxHelpDescription:f,globalSearchSyntaxHelpItems:b,globalSearchSyntaxSuggestions:w,shouldShowGlobalSearchSyntaxSuggestions:w.length>0&&Boolean(Ry(o)?.token)}})({getLocalizedText:s,activeGlobalSearchSyntaxFilters:yt,filterChipMaxCount:4,isGlobalSettingsSearchOpen:Y,settingsSearchInputValue:ne,filteredGlobalSearchResults:St,suggestionLimit:8}),Ht=R(()=>s({key:"globalSearchResultsLabel",fallback:"Global search results"}),[s]),Ut=E(e=>{const t=Ry(ne),n=!e.token.endsWith(":"),r=`${e.token}${n?" ":""}`,o=t?`${ne.slice(0,t.start)}${r}`:`${ne}${ne.endsWith(" ")?"":" "}${r}`;k(o),Ee(-1),le(0),window.requestAnimationFrame(()=>{const e=Ie.current;if(!e)return;const t=o.length;e.focus({preventScroll:true}),e.setSelectionRange(t,t);});},[ne,k]),Wt=E(e=>{Ut(e),Se(false);},[Ut]),Vt=E(e=>{const t=yt.filter(t=>t.id!==e),n=(({plainQuery:e,filters:t})=>`${e} ${t.map(e=>{const t=e.value.replace(/([\\"])/g,"\\$1"),n=/\s/.test(e.value)?`"${t}"`:t;return `${e.key}:${n}`}).join(" ")}`.replace(/\s+/g," ").trim())({plainQuery:wt,filters:t});k(n),Ee(-1),le(0);},[wt,yt,k]),Gt=E(()=>{k(wt),Ee(-1),le(0);},[wt,k]),Qt=R(()=>{if(Tt<0)return null;const e=_t[Tt];if(!e)return null;const t=Dt[e.category],n=l({key:"globalSearchContextCurrentItem",fallback:"第 {current} 项"},{current:String(Tt+1)});if("all"!==X)return {label:t,meta:`${n} · ${l({key:"globalSearchContextTotalItems",fallback:"共 {total} 项"},{total:String(_t.length)})}`};const r=Et.find(t=>t.category===e.category);return r?{label:t,meta:`${n} · ${l({key:"globalSearchContextShownProgress",fallback:"已显示 {shown}/{total}"},{shown:String(r.items.length),total:String(r.totalCount)})}`}:{label:t,meta:`${n} · ${l({key:"globalSearchContextTotalItems",fallback:"共 {total} 项"},{total:String(_t.length)})}`}},[X,Tt,l,Et,Dt,_t]),Kt=E(()=>{ct.current=false,Z(false);const e=V.current;if(!e?.panel?.edgeSnap)return;let t=null;const n=document.querySelector("plasmo-csui, #ophel-userscript-root");if(n?.shadowRoot&&(t=n.shadowRoot.querySelector(".gh-main-panel")),t||(t=document.querySelector(".gh-main-panel")),!t)return;if(t.classList.contains("edge-snapped-left")||t.classList.contains("edge-snapped-right"))return;const r=t.getBoundingClientRect(),o=e?.panel?.edgeSnapThreshold??30;r.left{Oe.current=e,ct.current?(dt.current=true,Kt()):dt.current=false,nt&&V.current?.panel?.edgeSnap&&it(true);const t=document.activeElement;t instanceof HTMLElement&&t!==document.body?$e.current=t:$e.current=null,x(),oe(""),ae(""),Se(false),Ee(-1),ee("all"),le(0),de(false),he("pointer"),pe({}),Pe.current=0,J(true);},[x,Kt,nt]),Yt=E(e=>{const t=e?.restoreFocus??true,n=e?.reopenSettings??false,r=$e.current;if($e.current=null,dt.current=false,x(),J(false),ee("all"),oe(""),ae(""),Se(false),Ee(-1),le(0),de(false),he("pointer"),pe({}),Pe.current=0,n)return ct.current=true,nt&&V.current?.panel?.edgeSnap&&it(true),void Z(true);t&&r&&r.isConnected&&window.requestAnimationFrame(()=>{if(r.isConnected)try{r.focus({preventScroll:!0});}catch{r.focus();}});},[x,nt]),Jt=E(()=>{Y&&Yt({restoreFocus:false}),dt.current=false,ct.current=true,nt&&V.current?.panel?.edgeSnap&&it(true),Z(true);},[Yt,nt,Y]),Xt=E(async t=>{if(Yt({restoreFocus:false}),"settings"===t.category&&t.settingId)window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{settingId:t.settingId}}));else {if("outline"===t.category&&t.outlineTarget&&H){const e=(t,n)=>{for(const r of t){if(r.index===n)return r;if(r.children&&r.children.length>0){const t=e(r.children,n);if(t)return t}}return null},n=e(H.getTree(),t.outlineTarget.index);let r=n?.element||null;if(!r||!r.isConnected){const e=await H.resolveOutlineTarget(t.outlineTarget,t.outlineTarget.queryIndex);e&&(r=e);}if(r&&r.isConnected)return r.scrollIntoView({behavior:"instant",block:"start",__bypassLock:true}),r.classList.add("outline-highlight"),void setTimeout(()=>r?.classList.remove("outline-highlight"),2e3);if(t.outlineTarget.isGhost&&void 0!==t.outlineTarget.scrollTop){const e=H.getScrollContainer();if(e)return e.scrollTo({top:t.outlineTarget.scrollTop,behavior:"smooth"}),void Oo(re("bookmarkContentMissing")||"收藏内容不存在,已跳转到保存位置",3e3)}return void Oo(re("bookmarkContentMissing")||"收藏内容已被删除或折叠",2e3)}if("prompts"===t.category&&t.promptId){const r=ft.find(e=>e.id===t.promptId);if(!r)return;const o=()=>{W(true);const t=(e?.features?.order||bo.features.order).indexOf(In);t>=0&&window.dispatchEvent(new CustomEvent("ophel:switchTab",{detail:{index:t}}));},i=()=>{Q(null),o();const e={promptId:r.id};window.__ophelPendingLocatePrompt=e,window.dispatchEvent(new CustomEvent("ophel:locatePrompt",{detail:e}));};if("locate"===(e?.globalSearch?.promptEnterBehavior??"smart"))return void i();if(!F)return void o();if(n=r.content,/\{\{([^\s{}]+)\}\}/.test(n)){Q(null),o();const e={promptId:r.id,submitAfterInsert:false};return window.__ophelPendingPromptVariableDialog=e,void window.dispatchEvent(new CustomEvent("ophel:openPromptVariableDialog",{detail:e}))}return void(async()=>{if(await F.insertPrompt(r.content))return F.updateLastUsed(r.id),Q(r),void Oo(`${re("inserted")||"已插入"}: ${r.title}`);i(),Oo(re("insertFailed")||"未找到输入框,请点击输入框后重试");})()}var n;"conversations"===t.category&&t.conversationId&&z?.navigateToConversation(t.conversationId,t.conversationUrl);}},[z,Yt,H,F,ft,e]);M(()=>{Y&&(Ie.current?.focus(),Ie.current?.select());},[Y]),M(()=>{Y&&"ui"===Oe.current&&I();},[Y,I]),M(()=>()=>{v();},[v]);const en=P(Y);M(()=>{en.current=Y;},[Y]);const tn=E(()=>{en.current||(ze.current=0,T(),Zt("shortcut"));},[T,Zt]);M(()=>{const e=e=>{if(en.current)return;if("Shift"!==e.key&&(ze.current=0),"Shift"!==e.key||e.repeat||e.ctrlKey||e.metaKey||e.altKey)return;const t=Date.now();if((V.current?.globalSearch?.doubleShift??bo.globalSearch.doubleShift)&&t-ze.current<=360)return e.preventDefault(),e.stopPropagation(),ze.current=0,T(),void Zt("shortcut");ze.current=t;};return window.addEventListener("keydown",e,true),()=>{window.removeEventListener("keydown",e,true);}},[T,Zt]),M(()=>{const e=()=>{Zt("event");};return window.addEventListener("ophel:openSettingsSearch",e),()=>{window.removeEventListener("ophel:openSettingsSearch",e);}},[Zt]),M(()=>()=>{x();},[x]),M(()=>{if(!Y||!ke)return;const e=e=>{const t=e.target;t&&(Ne.current?.contains(t)||Le.current?.contains(t)||Se(false));};return document.addEventListener("mousedown",e,true),()=>{document.removeEventListener("mousedown",e,true);}},[Y,ke]),M(()=>{if(!Y)return void Ge();if("keyboard"!==ue)return;const e=_t[se];if(!e||"prompts"!==e.category)return void Ge();const t=De.current;if(!t)return;const n=t.querySelector(`[data-global-search-index="${se}"]`);n&&Ke({item:e,anchorElement:n,delay:700,source:"keyboard"});},[Ge,Y,Ke,se,ue,_t]),M(()=>{le(0),de(false),he("pointer"),pe({}),Pe.current=0,Ge();},[X,Ge,ie]),M(()=>{Y||Ge();},[Ge,Y]),M(()=>{He&&Re.current&&Au(Re.current,{size:14});},[He]),M(()=>{if(!Y||!He)return;const e=()=>{Ye();},t=De.current;return window.addEventListener("resize",e),window.addEventListener("scroll",e,true),t?.addEventListener("scroll",e),()=>{window.removeEventListener("resize",e),window.removeEventListener("scroll",e,true),t?.removeEventListener("scroll",e);}},[He,Y,Ye]),M(()=>()=>{We(),Ve();},[Ve,We]),(({isGlobalSettingsSearchOpen:e,showGlobalSearchSyntaxHelp:t,setShowGlobalSearchSyntaxHelp:n,activeGlobalSearchCategory:r,categoryIds:o,setActiveGlobalSearchCategory:i,settingsSearchActiveIndex:a,setSettingsSearchActiveIndex:s,settingsSearchNavigationMode:l,setSettingsSearchNavigationMode:c,setSettingsSearchHoverLocked:d,shouldShowGlobalSearchSyntaxSuggestions:u,globalSearchSyntaxSuggestions:h,activeSearchSyntaxSuggestionIndex:g,setActiveSearchSyntaxSuggestionIndex:p,applyGlobalSearchSyntaxSuggestion:m,visibleGlobalSearchResults:f,navigateToSearchResult:b,closeGlobalSettingsSearch:y,getShouldReturnToSettingsOnEscape:v,settingsSearchResultsRef:w,keyboardSafeTop:x,keyboardSafeBottom:k})=>{M(()=>{if(!e)return;const l=e=>{if("Escape"===e.key){if(e.preventDefault(),e.stopPropagation(),t)return void n(false);const r=v();return void y({restoreFocus:!r,reopenSettings:r})}if("Tab"===e.key){e.preventDefault(),e.stopPropagation();const t=o.findIndex(e=>e===r);if(t<0)return i("all"),s(0),d(false),void c("keyboard");const n=o.length,a=e.shiftKey?(t-1+n)%n:(t+1)%n;return i(o[a]),s(0),d(false),void c("keyboard")}if(u){if("ArrowDown"===e.key)return e.preventDefault(),e.stopPropagation(),void p(e=>{if(0===h.length)return -1;const t=e+1;return t>=h.length?0:t});if("ArrowUp"===e.key)return e.preventDefault(),e.stopPropagation(),void p(e=>{if(0===h.length)return -1;const t=e-1;return t<0?h.length-1:t});if("Enter"===e.key&&g>=0){const t=h[g];if(!t)return;return e.preventDefault(),e.stopPropagation(),void m(t)}}if("ArrowDown"===e.key)return e.preventDefault(),e.stopPropagation(),d(true),c("keyboard"),void s(e=>0===f.length?0:(e+1)%f.length);if("ArrowUp"===e.key)return e.preventDefault(),e.stopPropagation(),d(true),c("keyboard"),void s(e=>0===f.length?0:(e-1+f.length)%f.length);if("Enter"===e.key){if(0===f.length)return;const t=f[a]||f[0];if(!t)return;f[a]||s(0),e.preventDefault(),e.stopPropagation(),b(t);}};return window.addEventListener("keydown",l,true),()=>{window.removeEventListener("keydown",l,true);}},[r,g,m,o,y,h,e,b,i,p,s,d,c,n,a,v,u,t,f]),M(()=>{0!==f.length?a>=f.length&&s(0):0!==a&&s(0);},[a,s,f.length]),M(()=>{u?g>=h.length&&p(h.length-1):-1!==g&&p(-1);},[g,h.length,p,u]);const S=E((e,t)=>{const n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),o=n.top+x,i=n.bottom-k;if(r.topi){const t=r.bottom-i,n=Math.max(0,e.scrollHeight-e.clientHeight);e.scrollTop=Math.min(n,e.scrollTop+t);}},[k,x]);M(()=>{if(!e)return;if("keyboard"!==l)return;const t=w.current;if(!t)return;const n=t.querySelector(`[data-global-search-index="${a}"]`);n&&S(t,n);},[S,e,a,l,w,f]);})({isGlobalSettingsSearchOpen:Y,showGlobalSearchSyntaxHelp:ke,setShowGlobalSearchSyntaxHelp:Se,activeGlobalSearchCategory:X,categoryIds:Vy.map(e=>e.id),setActiveGlobalSearchCategory:ee,settingsSearchActiveIndex:se,setSettingsSearchActiveIndex:le,settingsSearchNavigationMode:ue,setSettingsSearchNavigationMode:he,setSettingsSearchHoverLocked:de,shouldShowGlobalSearchSyntaxSuggestions:$t,globalSearchSyntaxSuggestions:jt,activeSearchSyntaxSuggestionIndex:Ce,setActiveSearchSyntaxSuggestionIndex:Ee,applyGlobalSearchSyntaxSuggestion:Ut,visibleGlobalSearchResults:_t,navigateToSearchResult:Xt,closeGlobalSettingsSearch:Yt,getShouldReturnToSettingsOnEscape:()=>dt.current,settingsSearchResultsRef:De,keyboardSafeTop:8,keyboardSafeBottom:12});const nn=E(()=>{lt.current&&(clearTimeout(lt.current),lt.current=null);},[]),rn=E(e=>{at.current=e;},[]);M(()=>{r&&e?.language&&(te(e.language),a(e=>e+1));},[e?.language,r]);const on=E(e=>{Q(e);},[]),an=E(()=>{Q(null),z&&z.clearTextarea();},[z]);M(()=>{H&&e&&H.updateSettings(e.features?.outline);},[H,e]),M(()=>{$&&e&&$.updateSettings({syncUnpin:e.features?.conversations?.syncUnpin??false});},[$,e]);const sn=R(()=>{const t=Hp(),n=t?.getSiteId()||"_default",r=e?.theme?.sites?.[n]||e?.theme?.sites?._default;return Tm({mode:r?.mode||"light",adapter:z,lightPresetId:r?.lightStyleId||"google-gradient",darkPresetId:r?.darkStyleId||"classic-dark"})},[]),ln=O(sn.subscribe,sn.getSnapshot);M(()=>(sn.setOnModeChange((e,n)=>{const r=n||e,o=V.current,i=o?.theme?.sites||{},a=Hp(),s=a?.getSiteId()||"_default",l={lightStyleId:"google-gradient",darkStyleId:"classic-dark",mode:"light",...i[s]||i._default};t({theme:{...o?.theme,sites:{...i,[s]:{...l,mode:r}}}});}),()=>{sn.setOnModeChange(void 0);}),[sn,t]);const dn=e?.theme?.sites,un=e?.features?.conversations?.syncUnpin,hn=e?.features?.conversations?.syncDelete,gn=e?.features?.outline?.inlineBookmarkMode,pn=Boolean(e),mn=e?.collapsedButtons||bo.collapsedButtons,fn=mn.find(e=>"floatingToolbar"===e.id)?.enabled??true,bn=e?.floatingToolbar?.open??true,yn=e?.panel?.preventAutoScroll??false,wn=H?.getGhostBookmarkIds().length??0;M(()=>{fn&&bn||(Xe(null),tt(false));},[fn,bn]),M(()=>{if(!r)return;const e=Hp(),t=e?.getSiteId()||"_default",n=dn?.[t]||dn?._default,o=n?.lightStyleId,i=n?.darkStyleId;o&&i&&sn.setPresets(o,i);},[dn,sn,r]),M(()=>{r&&sn.setCustomStyles(e?.theme?.customStyles||[]);},[e?.theme?.customStyles,sn,r]);const kn=E(async e=>{await sn.toggle(e);},[sn]);M(()=>(sn.monitorTheme(),()=>{sn.stopMonitoring();}),[sn]),M(()=>{if(F&&F.init(),$&&$.init(),H){H.refresh();const e=setInterval(()=>{H.refresh();},2e3);return ()=>{clearInterval(e),$?.destroy();}}},[F,$,H]),M(()=>{if(!$||"undefined"==typeof chrome)return;const e=(e,t,n)=>e?.type===Iu&&($.destroy(),n({success:true}),true);return chrome.runtime.onMessage.addListener(e),()=>{chrome.runtime.onMessage.removeListener(e);}},[$]),M(()=>{const e=e=>{const t=e,n=t.detail?.version||window.__OPHEL_PENDING_UPDATE_VERSION__||null;Me(n),Ae(true);};return window.addEventListener(Ou,e),window.__OPHEL_EXTENSION_UPDATE_AVAILABLE__&&(Ae(true),Me(window.__OPHEL_PENDING_UPDATE_VERSION__||null)),()=>{window.removeEventListener(Ou,e);}},[]),M(()=>(window.__OPHEL_EXTENSION_UPDATE_NOTICE_ACTIVE__=_e,_e&&document.getElementById("ophel-extension-update-fallback")?.remove(),()=>{window.__OPHEL_EXTENSION_UPDATE_NOTICE_ACTIVE__=false;}),[_e]);const Sn=E(()=>{window.__OPHEL_EXTENSION_UPDATE_AVAILABLE__=false,Ae(false);},[]),Cn=E(()=>{window.location.reload();},[]);M(()=>{$&&$.updateSettings({syncUnpin:un??false,syncDelete:hn??true});},[$,un,hn]),M(()=>{if(!H||!z||!pn)return;const e=new cm(H,z,gn||"always");return ()=>{e.cleanup();}},[H,z,gn,pn]);const En=E(()=>{const e=V.current;if(!e)return;const n=!e.panel?.preventAutoScroll;t({panel:{...e.panel,preventAutoScroll:n}}),Oo(re(n?"preventAutoScrollEnabled":"preventAutoScrollDisabled"));},[t]),_n=E(async()=>{if(!$||!z)return;const e=z.getSessionId();if(!e)return void Oo(re("exportNeedOpenFirst")||"请先打开要导出的会话");Oo(re("exportStarted")||"正在导出会话,请勿操作当前页面...",Bo);await $.exportConversation(e,"markdown")||Oo(re("exportFailed")||"导出失败");},[$,z]),An=E(()=>{if(!$||!z)return;const e=z.getSessionId();if(!e)return void Oo(re("noConversationToLocate")||"未找到会话");const t=$.getConversation(e);Xe({convId:e,activeFolderId:t?.folderId});},[$,z]),Mn=E(()=>{if(!H)return;const e=H.clearGhostBookmarks();Oo(0!==e?`${re("cleared")||"已清理"} (${e})`:re("floatingToolbarClearGhostEmpty")||"没有需要清理的无效收藏");},[H]),Nn=E(async()=>{if(!$||!z)return;const e=z.getSessionId();if(!e)return void Oo(re("exportNeedOpenFirst")||"请先打开要导出的会话");Oo(re("exportLoading")||"正在加载...");await $.exportConversation(e,"clipboard")||Oo(re("exportFailed")||"导出失败");},[$,z]),Ln=E(()=>{if(!z)return;const e=z.getSiteId(),n=V.current;if(!n)return;const r=n.modelLock?.[e]||{enabled:false,keyword:""};if(!r.keyword)return void(r.enabled?(t({modelLock:{...n.modelLock,[e]:{...r,enabled:false}}}),Oo(re("modelLockDisabled")||"模型锁定已关闭")):(Oo(re("modelLockNoKeyword")||"请先在设置中配置模型关键词"),t({modelLock:{...n.modelLock,[e]:{...r,enabled:true}}}),Jt(),setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:"siteSettings",subTab:"modelLock"}}));},100)));const o=!r.enabled;t({modelLock:{...n.modelLock,[e]:{...r,enabled:o}}}),Oo(o?re("modelLockEnabled")||"模型锁定已开启":re("modelLockDisabled")||"模型锁定已关闭");},[z,Jt,t]),Dn=R(()=>{if(!z||!e)return false;const t=z.getSiteId();return e.modelLock?.[t]?.enabled||false},[z,e]);Jm({settings:e,adapter:z,outlineManager:H,conversationManager:$,onPanelToggle:()=>W(e=>!e),onThemeToggle:kn,onOpenSettings:Jt,onOpenGlobalSearch:tn,isPanelVisible:U,isSnapped:!!nt&&!ot,onShowSnappedPanel:()=>{it(true),nn(),lt.current=setTimeout(()=>{it(false),lt.current=null;},3e3);},onToggleScrollLock:En}),M(()=>{nt&&!e?.panel?.edgeSnap&&(rt(null),it(false));},[e?.panel?.edgeSnap,nt]);const Rn=P(e?.panel?.defaultPosition);M(()=>{const t=e?.panel?.defaultPosition;void 0===Rn.current&&t?Rn.current=t:t&&Rn.current!==t&&(Rn.current=t,nt&&(rt(t),it(false)));},[e?.panel?.defaultPosition,nt]),M(()=>{if(!nt||!e?.panel?.edgeSnap)return;const t=()=>{const e=document.body.querySelectorAll(".conversations-dialog-overlay, .conversations-folder-menu, .conversations-tag-filter-menu, .prompt-modal, .gh-dialog-overlay, .settings-modal-overlay"),t=document.body.querySelectorAll(".settings-search-overlay");return e.length>0||t.length>0};let n=t();const r=new MutationObserver(()=>{const e=t();e&&!n?(it(true),st.current&&(clearTimeout(st.current),st.current=null)):!e&&n&&(st.current&&clearTimeout(st.current),st.current=setTimeout(()=>{t()||at.current||it(false);},500)),n=e;});return r.observe(document.body,{childList:true,subtree:false}),t()&&it(true),()=>{r.disconnect();}},[nt,e?.panel?.edgeSnap]),M(()=>{if(!nt||!e?.panel?.edgeSnap)return;const t=document.querySelector("plasmo-csui, #ophel-userscript-root"),n=t?.shadowRoot;if(!n)return;const r=e=>{const t=e.target;if("INPUT"===t.tagName||"TEXTAREA"===t.tagName||"true"===t.getAttribute("contenteditable")){if(t.closest(".settings-modal-overlay, .settings-modal"))return;ut.current=true,it(true),st.current&&(clearTimeout(st.current),st.current=null);}},o=e=>{const t=e.target;if("INPUT"===t.tagName||"TEXTAREA"===t.tagName||"true"===t.getAttribute("contenteditable")){if(t.closest(".settings-modal-overlay, .settings-modal"))return;ut.current=false,st.current&&clearTimeout(st.current),st.current=setTimeout(()=>{if(!ut.current&&!ct.current&&!at.current){const e=document.body.querySelectorAll(".conversations-dialog-overlay, .conversations-folder-menu, .conversations-tag-filter-menu, .prompt-modal, .gh-dialog-overlay, .settings-modal-overlay"),t=document.body.querySelectorAll(".settings-search-overlay");0===e.length&&0===t.length&&it(false);}},300);}};return n.addEventListener("focusin",r,true),n.addEventListener("focusout",o,true),()=>{n.removeEventListener("focusin",r,true),n.removeEventListener("focusout",o,true);}},[nt,e?.panel?.edgeSnap]),M(()=>{const t=e?.panel?.autoHide;if(!t||!U)return;const n=t=>{t.composedPath().some(e=>e instanceof Element&&(!!e.closest?.(".gh-main-panel")||(!!e.closest?.(".gh-quick-buttons")||(!!e.closest?.(".conversations-dialog-overlay")||(!!e.closest?.(".conversations-folder-menu")||(!!e.closest?.(".conversations-tag-filter-menu")||(!!e.closest?.(".prompt-modal")||(!!e.closest?.(".gh-dialog-overlay")||(!!e.closest?.(".settings-modal-overlay")||!!e.closest?.(".settings-search-overlay"))))))))))||(e?.panel?.edgeSnap?nt||(rt(e.panel.defaultPosition||"right"),it(false)):W(false));},r=setTimeout(()=>{document.addEventListener("click",n,true);},100);return ()=>{clearTimeout(r),document.removeEventListener("click",n,true);}},[e?.panel?.autoHide,e?.panel?.edgeSnap,U,nt,e?.panel?.defaultPosition]);const qn=E(e=>{if(!z||z.getSiteId()!==qr)return;const t="ophel:aistudio-submit-shortcut-sync-toast",n=`synced:${e}`;let r=true;try{sessionStorage.getItem(t)===n?r=!1:sessionStorage.setItem(t,n);}catch{}if(!r)return;const o="ctrlEnter"===e?"Ctrl + Enter":"Enter";Oo(`AI Studio ${re("promptSubmitShortcutLabel")}: ${o}`);},[z]);M(()=>{if(!z||z.getSiteId()!==qr)return;const e=e=>{const t=e.detail,n=t?.submitShortcut;"enter"!==n&&"ctrlEnter"!==n||qn(n);};return window.addEventListener(bm,e),()=>{window.removeEventListener(bm,e);}},[z,qn]),M(()=>{z&&F&&z.getSiteId()===qr&&F.syncAiStudioSubmitShortcut(o);},[z,F,o]),M(()=>{if(!z||!F)return;const e=e=>{if(!e.isTrusted)return;if("Enter"!==e.key)return;if(e.isComposing||229===e.keyCode)return;const t=e.composedPath();if(t.some(e=>e instanceof HTMLElement&&(e.classList?.contains("gh-queue-panel")||e.classList?.contains("gh-queue-input")||e.classList?.contains("gh-queue-item-edit-input"))))return;const n=t.find(e=>e instanceof HTMLElement&&z.isValidTextarea(e));if(!n)return;const r=e.ctrlKey||e.metaKey,i=r||e.altKey,a="ctrlEnter"===o?r&&!e.altKey&&!e.shiftKey:!i&&!e.shiftKey,s="ctrlEnter"===o&&!i&&!e.shiftKey;if(a)return e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),void(async()=>{F.syncAiStudioSubmitShortcut(o);await F.submitPrompt(o)&&Q(null);})();s&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),(e=>{if(e instanceof HTMLTextAreaElement){const t=e.selectionStart??e.value.length,n=e.selectionEnd??e.value.length;return e.setRangeText("\n",t,n,"end"),void e.dispatchEvent(new Event("input",{bubbles:true}))}if("true"!==e.getAttribute("contenteditable"))return;e.focus();const t={key:"Enter",code:"Enter",keyCode:13,which:13,bubbles:true,cancelable:true,composed:true,shiftKey:true},n=e.innerHTML;e.dispatchEvent(new KeyboardEvent("keydown",t)),e.dispatchEvent(new KeyboardEvent("keypress",t)),e.dispatchEvent(new KeyboardEvent("keyup",t)),e.innerHTML===n&&(document.execCommand("insertLineBreak")||document.execCommand("insertParagraph"),e.dispatchEvent(new Event("input",{bubbles:true})));})(n));};return z.getSiteId()===Mr?(window.addEventListener("keydown",e,true),()=>{window.removeEventListener("keydown",e,true);}):(document.addEventListener("keydown",e,true),()=>{document.removeEventListener("keydown",e,true);})},[z,F,o]),M(()=>{if(!z||!G)return;const e=()=>{Q(null);},t=t=>{const n=z.getSubmitButtonSelectors();if(0===n.length)return;const r=t.composedPath();for(const o of r){if(o===document||o===window)break;for(const t of n)try{if(o.matches?.(t))return void setTimeout(e,100)}catch{}}};return document.addEventListener("click",t,true),()=>{document.removeEventListener("click",t,true);}},[z,G]),M(()=>{if(!G||!z)return;let e=window.location.href;const t=()=>{Q(null),z.clearTextarea();},n=()=>{window.location.href!==e&&t();},r=setInterval(()=>{window.location.href!==e&&(e=window.location.href,t());},500);return window.addEventListener("popstate",n),()=>{clearInterval(r),window.removeEventListener("popstate",n);}},[G,z]);const[Pn,Bn]=B(null),On=E(()=>{if(!$||!z)return;const e=z.getSessionId();e?Bn({convId:e}):Oo(re("noConversationToLocate")||"未找到当前会话");},[$,z]),{tags:zn,addTag:Fn,updateTag:jn,deleteTag:$n}=Xp(),Hn=E(e=>{he("pointer"),pe(t=>({...t,[e]:!t[e]}));},[]),Un=s({key:"extensionUpdateNoticeKicker",fallback:"Extension updated"}),Wn=Te?l({key:"extensionUpdateNoticeWithVersion",fallback:`${ef} has been updated to v{version}. Reload this page to keep using the latest version.`},{version:Te}):s({key:"extensionUpdateNotice",fallback:`${ef} has been updated. Reload this page to keep using the latest version.`}),Vn=s({key:"extensionUpdateNoticeAction",fallback:"Reload page"}),Gn=re("close")||"关闭",Qn=R(()=>({query:s({key:"outlineOnlyUserQueries",fallback:"Query"}),reply:s({key:"globalSearchOutlineReplies",fallback:"Replies"})}),[s]);return z&&F&&$&&H?ye("div",{className:"gh-root",children:[ be(Ff,{isOpen:U,onClose:()=>W(false),promptManager:F,conversationManager:$,outlineManager:H,adapter:z,onThemeToggle:kn,themeMode:ln,selectedPromptId:G?.id,onPromptSelect:on,edgeSnapState:nt,isEdgePeeking:ot,onEdgeSnap:e=>rt(e),onUnsnap:()=>{rt(null),it(false);},onInteractionStateChange:rn,onOpenSettings:()=>{Jt();},onMouseEnter:()=>{st.current&&(clearTimeout(st.current),st.current=null),nn(),nt&&e?.panel?.edgeSnap&&!ot&&it(true);},onMouseLeave:()=>{st.current&&clearTimeout(st.current),st.current=setTimeout(()=>{if(ct.current)return;if(ut.current)return;const t=at.current,n=document.body.querySelectorAll(".conversations-dialog-overlay, .conversations-folder-menu, .conversations-tag-filter-menu, .prompt-modal, .gh-dialog-overlay, .settings-modal-overlay"),r=document.body.querySelectorAll(".settings-search-overlay"),o=n.length>0||r.length>0;t||o||nt&&e?.panel?.edgeSnap&&ot&&it(false);},200);}}), be(Hf,{isPanelOpen:U,onPanelToggle:()=>{U?it(false):nt&&e?.panel?.edgeSnap&&it(true),W(!U);},onThemeToggle:kn,themeMode:ln,onExport:_n,onMove:An,onSetTag:On,onScrollLock:()=>En(),onSettings:()=>{Jt(),setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:"general",subTab:"toolsMenu"}}));},50);},scrollLocked:yn,onCleanup:()=>{0!==wn?tt(true):Oo(re("floatingToolbarClearGhostEmpty")||"没有需要清理的无效收藏");},onGlobalSearch:Zt,onCopyMarkdown:Nn,onModelLockToggle:Ln,isModelLocked:Dn}),G&&be(Uf,{title:G.title,onClear:an,adapter:z}), be(fy,{isOpen:K,onClose:()=>{ct.current=false,Z(false);const e=V.current;if(!e?.panel?.edgeSnap)return;let t=null;const n=document.querySelector("plasmo-csui, #ophel-userscript-root");if(n?.shadowRoot&&(t=n.shadowRoot.querySelector(".gh-main-panel")),t||(t=document.querySelector(".gh-main-panel")),!t)return;if(t.classList.contains("edge-snapped-left")||t.classList.contains("edge-snapped-right"))return;const r=t.getBoundingClientRect(),o=e?.panel?.edgeSnapThreshold??30;r.left{Ge(),Yt();},inputRef:Ie,resultsRef:De,activeOptionId:Mt,inputValue:ne,inputPlaceholder:u?`${Nt.placeholder}(${u})`:Nt.placeholder,onInputChange:e=>{C(e),Ee(-1),le(0);},hotkeyLabel:p,fuzzySearchToggleLabel:s({key:"globalSearchFuzzySearchToggle",fallback:"Fuzzy"}),fuzzySearchToggleAriaLabel:s({key:"globalSearchFuzzySearchToggleAria",fallback:"Toggle fuzzy search"}),isFuzzySearchEnabled:m,onToggleFuzzySearch:S,syntaxHelpTriggerRef:Ne,syntaxHelpPopoverRef:Le,showSyntaxHelp:ke,onToggleSyntaxHelp:()=>Se(e=>!e),syntaxHelpTriggerAriaLabel:s({key:"globalSearchSyntaxHelpTriggerAria",fallback:"Open search syntax help"}),syntaxHelpTitle:Ot,syntaxHelpDescription:zt,syntaxHelpItems:Ft,onApplySyntaxHelpItem:Wt,activeFilterChips:qt,hasOverflowFilterChips:Pt,overflowFilterChipText:l({key:"globalSearchSyntaxChipOverflow",fallback:"+{count} more"},{count:String(yt.length-4)}),filterChipRemoveTitle:s({key:"globalSearchSyntaxChipRemove",fallback:"Click to remove filter"}),clearFiltersLabel:s({key:"clear",fallback:"Clear"}),onRemoveFilterChip:Vt,onClearAllFilterChips:Gt,shouldShowSyntaxSuggestions:$t,syntaxSuggestions:jt,activeSyntaxSuggestionIndex:Ce,onHoverSyntaxSuggestion:Ee,onApplySyntaxSuggestion:Ut,syntaxDiagnostics:vt,resolveSyntaxDiagnosticTitle:e=>Bt[e]||Bt.invalidValue,showShortcutNudge:me,shortcutNudgeMessage:we,closeLabel:s({key:"close",fallback:"Close"}),dismissShortcutNudgeLabel:s({key:"globalSearchShortcutNudgeDismiss",fallback:"Don’t remind me"}),onHideShortcutNudge:_,onDismissShortcutNudgeForever:A,categoriesLabel:s({key:"globalSearchCategoriesLabel",fallback:"Global search categories"}),categories:Vy.map(e=>({id:e.id,label:Lt[e.id],count:Ct[e.id]})),activeCategoryId:X,onSelectCategory:e=>{ee(e),le(0);},activeContext:Qt,listboxId:"settings-search-results-listbox",listboxLabel:Ht,onResultsWheel:()=>{he("pointer"),Pe.current=Date.now()+200,Ge();},visibleResults:_t,groupedResults:Et,getGroupLabel:e=>Dt[e],allCategoryItemLimit:12,isAllCategory:"all"===X,emptyText:Nt.emptyText,emptyGuideTitle:s({key:"globalSearchSyntaxEmptyGuideTitle",fallback:"Try search filters"}),emptyGuideDescription:s({key:"globalSearchSyntaxEmptyGuideDesc",fallback:"Use filter syntax to narrow results quickly"}),emptyGuideExamples:[{id:"example:type-prompts",token:"type:prompts",onClick:()=>k("type:prompts ")},{id:"example:is-pinned",token:"is:pinned",onClick:()=>k("is:pinned ")},{id:"example:folder-inbox",token:"folder:inbox",onClick:()=>k("folder:inbox ")},{id:"example:tag-work",token:"tag:work",onClick:()=>k("tag:work ")},{id:"example:level-0",token:"level:0",onClick:()=>k("level:0 ")},{id:"example:date-7d",token:"date:7d",onClick:()=>k("date:7d ")}],renderSearchResultItem:(e,t)=>be(vy,{item:e,index:t,optionIdPrefix:Ky,isActive:t===se,highlightTokens:kt,outlineRoleLabels:Qn,matchReasonLabels:Rt,onMouseMove:()=>{he("pointer"),Date.now(){he("pointer"),Ze({item:e,anchorElement:t.currentTarget});},onMouseLeave:()=>{Qe();},onClick:()=>Xt(e)},e.id),resolveVisibleResultIndex:(e,t)=>At.get(e.id)??t,collapseLabel:s({key:"collapse",fallback:"Collapse"}),moreLabel:s({key:"floatingToolbarMore",fallback:"More"}),onToggleCategoryGroup:Hn,footerTips:s({key:"globalSearchFooterTips",fallback:"Enter to jump · ↑↓ to select · Tab category · Esc to close"}),promptPreview:He&&Ue?ye(fe,{children:[ be("div",{ref:Re,className:"settings-search-prompt-preview-float gh-markdown-preview",style:{top:Ue.top,left:Ue.left},onMouseEnter:()=>{We(),Ve();},onMouseLeave:()=>{Qe();},onClick:w,dangerouslySetInnerHTML:{__html:Uu(wd(He.content,false))}}), be("style",{children:"\n/* highlight.js GitHub Dark 主题 */\n.hljs {\n background: var(--gh-bg-tertiary, #1e1e1e);\n color: var(--gh-text, #e6edf3);\n padding: 12px;\n border-radius: 6px;\n overflow-x: auto;\n font-family: 'SF Mono', Consolas, 'Liberation Mono', Menlo, monospace;\n font-size: 13px;\n line-height: 1.5;\n /* 代码块自动换行 */\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n.hljs-comment,\n.hljs-quote { color: #8b949e; font-style: italic; }\n.hljs-keyword,\n.hljs-selector-tag { color: #ff7b72; }\n.hljs-string,\n.hljs-doctag { color: #a5d6ff; }\n.hljs-number,\n.hljs-literal { color: #79c0ff; }\n.hljs-title,\n.hljs-section,\n.hljs-selector-id { color: #d2a8ff; font-weight: bold; }\n.hljs-function > .hljs-title { color: #d2a8ff; }\n.hljs-type,\n.hljs-class .hljs-title { color: #7ee787; }\n.hljs-attribute { color: #79c0ff; }\n.hljs-variable,\n.hljs-template-variable { color: #ffa657; }\n.hljs-built_in { color: #ffa657; }\n.hljs-addition { color: #aff5b4; background: rgba(46, 160, 67, 0.15); }\n.hljs-deletion { color: #ffdcd7; background: rgba(248, 81, 73, 0.15); }\n\n/* 变量占位符高亮 */\n.gh-variable-highlight {\n background: rgba(56, 139, 253, 0.2);\n color: #58a6ff;\n padding: 2px 6px;\n border-radius: 4px;\n font-weight: 500;\n}\n\n/* Markdown 渲染样式 */\n.gh-markdown-preview {\n line-height: 1.6;\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview h1,\n.gh-markdown-preview h2,\n.gh-markdown-preview h3 {\n margin: 16px 0 8px;\n font-weight: 600;\n border-bottom: 1px solid var(--gh-border, #30363d);\n padding-bottom: 4px;\n}\n.gh-markdown-preview h1 { font-size: 1.5em; }\n.gh-markdown-preview h2 { font-size: 1.3em; }\n.gh-markdown-preview h3 { font-size: 1.1em; }\n.gh-markdown-preview p { margin: 8px 0; }\n.gh-markdown-preview code:not(.hljs) {\n background: var(--gh-bg-tertiary, #343942);\n padding: 2px 6px;\n border-radius: 4px;\n font-size: 13px;\n}\n.gh-markdown-preview pre {\n margin: 12px 0;\n position: relative;\n max-width: 100%;\n overflow: hidden;\n}\n.gh-markdown-preview pre code {\n display: block;\n max-width: 100%;\n overflow-x: auto;\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n/* 代码块复制按钮 */\n.gh-code-copy-btn {\n position: absolute;\n top: 8px;\n right: 8px;\n padding: 4px 8px;\n background: var(--gh-bg-secondary, #2d333b);\n border: 1px solid var(--gh-border, #444c56);\n border-radius: 4px;\n color: var(--gh-text-secondary, #8b949e);\n font-size: 12px;\n cursor: pointer;\n opacity: 0;\n transition: opacity 0.2s;\n}\n.gh-markdown-preview pre:hover .gh-code-copy-btn {\n opacity: 1;\n}\n.gh-code-copy-btn:hover {\n background: var(--gh-hover, #373e47);\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview blockquote {\n border-left: 3px solid var(--gh-primary, #4285f4);\n margin: 12px 0;\n padding: 8px 16px;\n background: var(--gh-bg-secondary, #161b22);\n color: var(--gh-text-secondary, #8b949e);\n}\n.gh-markdown-preview ul,\n.gh-markdown-preview ol {\n margin: 8px 0;\n padding-left: 24px;\n}\n.gh-markdown-preview li { margin: 4px 0; }\n.gh-markdown-preview a {\n color: var(--gh-primary, #58a6ff);\n text-decoration: none;\n}\n.gh-markdown-preview a:hover { text-decoration: underline; }\n\n/* 任务列表样式 */\n.gh-markdown-preview .task-list-item {\n list-style: none;\n margin-left: -20px;\n}\n.gh-markdown-preview .task-list-item input[type=\"checkbox\"] {\n margin-right: 8px;\n pointer-events: none;\n}\n\n/* 高亮 ==text== */\n.gh-markdown-preview mark {\n background: rgba(255, 235, 59, 0.4);\n color: inherit;\n padding: 2px 4px;\n border-radius: 3px;\n}\n\n/* 容器样式 :::info, :::warning, :::danger */\n.gh-container {\n margin: 12px 0;\n padding: 12px 16px;\n border-radius: 6px;\n border-left: 4px solid;\n}\n.gh-container-info {\n background: rgba(56, 139, 253, 0.1);\n border-color: #388bfd;\n}\n.gh-container-warning {\n background: rgba(255, 166, 87, 0.1);\n border-color: #ffa657;\n}\n.gh-container-danger {\n background: rgba(248, 81, 73, 0.1);\n border-color: #f85149;\n}\n"})]}):void 0}),Je&&be(yf,{folders:$.getFolders(),excludeFolderId:$.getConversation(Je.convId)?.folderId,activeFolderId:Je.activeFolderId,onSelect:async e=>{await $.moveConversation(Je.convId,e),Xe(null);},onCancel:()=>Xe(null)}),Pn&&be(vf,{tags:zn,conv:$.getConversation(Pn.convId),onCancel:()=>Bn(null),onCreateTag:async(e,t)=>Fn(e,t),onUpdateTag:async(e,t,n)=>jn(e,t,n),onDeleteTag:async e=>{$n(e);},onSetConversationTags:async(e,t)=>{await $.updateConversation(e,{tagIds:t});},onRefresh:()=>{}}),et&&be(mf,{title:re("floatingToolbarClearGhost")||"清除无效收藏",message:(re("floatingToolbarClearGhostConfirm")||"是否清除本会话中的 {count} 个无效收藏?").replace("{count}",String(wn)),danger:true,onConfirm:()=>{tt(false),Mn();},onCancel:()=>tt(false)}),z&&j&&(e?.features?.prompts?.promptQueue??false)&&be($f,{adapter:z,dispatcher:j}),_e&&ye("section",{className:"gh-update-notice gh-interactive",role:"status","aria-live":"polite",children:[ be("button",{type:"button",className:"gh-update-notice-close","aria-label":Gn,onClick:Sn,children:ye("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[ be("path",{d:"M18 6 6 18"}), be("path",{d:"m6 6 12 12"})]})}), ye("div",{className:"gh-update-notice-kicker",children:[ be("svg",{className:"gh-update-notice-icon",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:be("path",{d:"m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"})}),Un]}), be("p",{className:"gh-update-notice-message",children:Wn}), be("div",{className:"gh-update-notice-actions",children:be("button",{type:"button",className:"gh-update-notice-button gh-update-notice-button--primary",onClick:Cn,children:Vn})})]}), be(xf,{})]}):null}},Symbol.toStringTag,{value:"Module"})),tv="[GeminiMyStuffBridge]",nv=[1,1,1,0,0,0,1,0],rv=[1,1,1,1,1,0,1,0],ov={"x-same-domain":"1","x-goog-ext-525001261-jspb":"[1,null,null,null,null,null,null,null,[4]]","x-goog-ext-73010989-jspb":"[]"};let iv=false;const av=new Map,sv=new Map;function lv(){return "undefined"!=typeof unsafeWindow&&unsafeWindow!==window?unsafeWindow:window}function cv(e){return "document"===e?rv:nv}function dv(e){let t=av.get(e);return t||(t=new Map,av.set(e,t)),t}function uv(e){return "string"==typeof e&&/^boq_assistant-bard-web-server_/i.test(e)}function hv(e){return "string"==typeof e&&/^\d{10,}$/.test(e)}function gv(e){return "string"==typeof e&&/^[A-Za-z0-9._:-]+:\d{13}$/.test(e)}function pv(e,t){for(const n of Object.values(e))if("string"==typeof n&&t(n))return n;return null}function mv(e,t){const n=e.match(t);return n?.[1]||n?.[0]||null}function fv(){const e=lv(),t=e.WIZ_global_data||{},n=document.querySelector('script[data-id="_gd"]')?.textContent||"",r=(uv(t.cfb2h)?t.cfb2h:null)||pv(t,uv)||mv(n,/"cfb2h":"([^"]+)"/)||mv(n,/boq_assistant-bard-web-server_[^"]+/),o=(hv(t.FdrFJe)?t.FdrFJe:null)||pv(t,hv)||mv(n,/"FdrFJe":"([^"]+)"/)||mv(n,/"\d{10,}"/)?.replace(/"/g,"")||null,i=(gv(t.SNlM0e)?t.SNlM0e:null)||pv(t,gv)||mv(n,/"SNlM0e":"([^"]+)"/)||mv(n,/[A-Za-z0-9._:-]+:\d{13}/)||null;return uv(r)&&hv(o)&&gv(i)?{bl:r,fSid:o,at:i,hl:document.documentElement.lang||navigator.language||"zh-CN"}:(console.warn(`${tv} failed to resolve runtime tokens`,{hasGlobalData:Boolean(e.WIZ_global_data),bl:r,fSid:o,at:i}),null)}function bv(e){const t=new URL("/_/BardChatUi/data/batchexecute",window.location.origin);return t.searchParams.set("rpcids","jGArJ"),t.searchParams.set("source-path","/mystuff"),t.searchParams.set("bl",e.bl),t.searchParams.set("f.sid",e.fSid),t.searchParams.set("hl",e.hl),t.searchParams.set("_reqid",String(Date.now()%1e6)),t.searchParams.set("rt","c"),t.toString()}function yv(e,t,n){const r=new URLSearchParams,o=n?[cv(t),30,n]:[cv(t),30];return r.set("f.req",JSON.stringify([[["jGArJ",JSON.stringify(o),null,"generic"]]])),r.set("at",e.at),r.toString()}function vv(e,t){const n=e.replace(/^\)\]\}'\s*\n\s*\n/,"").split("\n").map(e=>e.trim()).filter(Boolean);if(n.length<2)throw new Error("mystuff-response-lines-missing");const r=JSON.parse(n[1]),o=Array.isArray(r)?r[0]:null,i=Array.isArray(o)&&"string"==typeof o[2]?o[2]:null;if(!i)throw new Error("mystuff-payload-missing");const a=JSON.parse(i);return {items:(Array.isArray(a[0])?a[0]:[]).map(e=>function(e,t){if(!Array.isArray(t)||t.length<3)return null;const n=Array.isArray(t[0])?t[0]:[];if(n.length<2||"string"!=typeof n[0]||"string"!=typeof n[1])return null;const r=Array.isArray(t[1])?t[1]:[],o=Array.isArray(t[4])?t[4]:[];return {kind:e,conversationId:n[0],responseId:n[1],timestamp:"number"==typeof r[0]?r[0]:0,timestampNano:"number"==typeof r[1]?r[1]:0,status:"number"==typeof t[2]?t[2]:0,title:"string"==typeof t[3]&&t[3].trim()?t[3].trim():void 0,thumbnailUrl:"string"==typeof o[1]&&o[1]?o[1]:void 0,resourceId:"string"==typeof t[5]&&t[5]?t[5]:void 0}}(t,e)).filter(e=>null!==e),nextPageToken:"string"==typeof a[1]&&a[1]?a[1]:null}}function wv(e){return e.flatMap(e=>Array.from(dv(e).values()))}function xv(e){window.postMessage({type:Bu,payload:e},"*"),window.dispatchEvent(new CustomEvent(Bu,{detail:e}));}async function kv(e){if(!e?.requestId||!function(e=window.location.pathname){const t=e.replace(/^\/u\/\d+/,"");return "/mystuff"===t||"/mystuff/"===t||t.startsWith("/mystuff/")}())return;const t=function(e){return Array.isArray(e)&&0!==e.length?Array.from(new Set(e.filter(e=>"media"===e||"document"===e))):["media","document"]}(e.kinds),n=e.force||t.some(e=>0===dv(e).size);try{n&&await Promise.all(t.map(t=>async function(e,t){const n=dv(e);if(!t&&n.size>0)return Array.from(n.values());const r=sv.get(e);if(r)return r;const o=(async()=>{const t=new Map;let r;for(let n=0;n<80;n+=1){const o=fv();if(!o)throw new Error("mystuff-runtime-tokens-missing");const i=await lv().fetch(bv(o),{method:"POST",credentials:"include",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",...ov},body:yv(o,e,r)}),a=await i.text();if(!i.ok)throw console.warn(`${tv} fetch failed`,{kind:e,page:n,status:i.status,preview:a.slice(0,240)}),new Error(`mystuff-fetch-failed:${i.status}`);const s=vv(a,e);if(s.items.forEach(e=>{return t.set(`${(n=e).conversationId}:${n.responseId}`,e);var n;}),console.info(`${tv} fetched page`,{kind:e,page:n,itemCount:s.items.length,nextPageToken:s.nextPageToken}),!s.nextPageToken)break;r=s.nextPageToken;}return n.clear(),t.forEach((e,t)=>n.set(t,e)),Array.from(n.values())})();sv.set(e,o);try{return await o}finally{sv.delete(e);}}(t,Boolean(e.force))));const r=wv(t);xv({requestId:e.requestId,items:r,kinds:t,reason:n?"sync":"snapshot",timestamp:Date.now()});}catch(r){console.warn(`${tv} sync request failed`,{requestId:e.requestId,kinds:t,error:r}),xv({requestId:e.requestId,items:wv(t),kinds:t,reason:"snapshot",timestamp:Date.now()});}}function Sv(){iv||"gemini.google.com"!==window.location.hostname||(iv=true,window.addEventListener("message",e=>{e.data?.type===Pu&&kv(e.data.payload);}),window.addEventListener(Pu,e=>{kv(e.detail);}),console.info(`${tv} initialized`));}function Cv(){return "undefined"!=typeof unsafeWindow&&unsafeWindow!==window?unsafeWindow:window}class Ev{urlPatterns;urlPathEndsWith;silenceThreshold;onComplete;onStart;domValidation;_activeCount=0;_silenceTimer=null;_isMonitoring=false;_originalFetch=null;_originalXhrOpen=null;_originalXhrSend=null;_lastUrl="";_hasTriggeredStart=false;_boundHookedFetch;constructor(e={}){this.urlPatterns=e.urlPatterns||[],this.urlPathEndsWith=e.urlPathEndsWith||[],this.silenceThreshold=e.silenceThreshold||3e3,this.onComplete=e.onComplete||(()=>{}),this.onStart=e.onStart||null,this.domValidation=e.domValidation||null,this._boundHookedFetch=this._hookedFetch.bind(this);}start(){if(this._isMonitoring)return;const e=Cv();this._originalFetch=e.fetch,e.fetch=this._boundHookedFetch,this._hookXHR(),this._isMonitoring=true;}stop(){if(!this._isMonitoring)return;const e=Cv();this._originalFetch&&(e.fetch=this._originalFetch,this._originalFetch=null),this._unhookXHR(),this._silenceTimer&&(clearTimeout(this._silenceTimer),this._silenceTimer=null),this._isMonitoring=false,this._activeCount=0,this._hasTriggeredStart=false;}_isTargetUrl(e){if(!e)return false;if(!(0===this.urlPatterns.length||this.urlPatterns.some(t=>e.includes(t))))return false;if(0===this.urlPathEndsWith.length)return true;try{const t=new URL(e,window.location.origin).pathname;return this.urlPathEndsWith.some(e=>t.endsWith(e))}catch{return this.urlPathEndsWith.some(t=>e.endsWith(t))}}_tryTriggerComplete(){if(this._activeCount>0)return;const e={activeCount:this._activeCount,lastUrl:this._lastUrl,timestamp:Date.now()};if(this.domValidation)try{if(!this.domValidation(e))return void(this._silenceTimer=setTimeout(()=>this._tryTriggerComplete(),1e3))}catch(t){console.error(t);}this._hasTriggeredStart=false;try{this.onComplete(e);}catch(t){console.error(t);}}async _hookedFetch(...e){const t=Cv(),n=e[0]?e[0].toString():"";if(!this._isTargetUrl(n))return this._originalFetch.call(t,...e);if(this._activeCount++,this._lastUrl=n,this._silenceTimer&&(clearTimeout(this._silenceTimer),this._silenceTimer=null),!this._hasTriggeredStart&&this.onStart){this._hasTriggeredStart=true;try{this.onStart({url:n,timestamp:Date.now(),type:"fetch"});}catch{}}try{const n=await this._originalFetch.call(t,...e),r=n.clone();return this._readStream(r).catch(()=>{}),n}catch(r){throw this._decrementAndSchedule(),r}}async _readStream(e){try{if(!e.body)return;const t=e.body.getReader();for(;;){const{done:e}=await t.read();if(e)break}}catch{}finally{this._decrementAndSchedule();}}_decrementAndSchedule(){this._activeCount=Math.max(0,this._activeCount-1),this._silenceTimer&&clearTimeout(this._silenceTimer),this._silenceTimer=setTimeout(()=>this._tryTriggerComplete(),this.silenceThreshold);}_hookXHR(){const e=this,t=Cv().XMLHttpRequest;this._originalXhrOpen=t.prototype.open,this._originalXhrSend=t.prototype.send,t.prototype.open=function(t,n,...r){return this._networkMonitorUrl=n?n.toString():"",e._originalXhrOpen.call(this,t,n,...r)},t.prototype.send=function(t){const n=this._networkMonitorUrl||"";if(!e._isTargetUrl(n))return e._originalXhrSend.call(this,t);if(e._activeCount++,e._lastUrl=n,e._silenceTimer&&(clearTimeout(e._silenceTimer),e._silenceTimer=null),!e._hasTriggeredStart&&e.onStart){e._hasTriggeredStart=true;try{e.onStart({url:n,timestamp:Date.now(),type:"xhr"});}catch{}}const r=()=>{e._decrementAndSchedule();};return this.addEventListener("load",r),this.addEventListener("error",r),this.addEventListener("abort",r),this.addEventListener("timeout",r),e._originalXhrSend.call(this,t)};}_unhookXHR(){const e=Cv().XMLHttpRequest;this._originalXhrOpen&&(e.prototype.open=this._originalXhrOpen,this._originalXhrOpen=null),this._originalXhrSend&&(e.prototype.send=this._originalXhrSend,this._originalXhrSend=null);}}let _v=null,Av=false;const Tv=Object.freeze(Object.defineProperty({__proto__:null,initNetworkMonitor:function(){Av||(Av=true,Sv(),window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};e.source!==window&&t!==Du&&t!==qu&&t!==Ru||t===Du&&(_v&&_v.stop(),_v=new Ev({urlPatterns:n?.urlPatterns,urlPathEndsWith:n?.urlPathEndsWith,silenceThreshold:n?.silenceThreshold,onStart:e=>window.postMessage({type:Ru,payload:e},"*"),onComplete:e=>window.postMessage({type:qu,payload:e},"*")}),_v.start());}));}},Symbol.toStringTag,{value:"Module"})),Mv="gh-assistant-mermaid-style",Iv=".gh-assistant-mermaid",Nv="data-ophel-assistant-mermaid-managed",Lv="data-ophel-assistant-mermaid-original-display",Dv="data-ophel-assistant-mermaid-preview-id",Rv="data-ophel-assistant-mermaid-render-token",qv="data-ophel-assistant-mermaid-fullscreen",Pv="data-ophel-assistant-mermaid-restore-zoom",Bv="data-ophel-assistant-mermaid-fullscreen-max-zoom",Ov="OPHEL_ASSISTANT_MERMAID_RENDER_RESPONSE",zv="http://www.w3.org/2000/svg";function Fv(e){{const t=window.__OPHEL_USERSCRIPT_ASSET_URLS__?.[e];return "string"==typeof t&&t.length>0?t:null}}function jv(){return "1"===document.documentElement.getAttribute("data-ophel-assistant-mermaid-runner")}function $v(e,t){const n=e.createElementNS(zv,"svg");return n.setAttribute("viewBox",t),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),n.classList.add("gh-assistant-mermaid-btn-icon"),n}class Hv{adapter;enabled;stopWatch=null;rescanTimer=null;clickHandler=null;messageHandler=null;fullscreenChangeHandler=null;runtimePromise=null;processedBlocks=new WeakMap;blockPanels=new WeakMap;panelBlocks=new WeakMap;injectedRoots=new WeakSet;pendingRequests=new Map;previewIdCounter=0;constructor(e,t){this.adapter=e,this.enabled=t,t&&this.init();}updateSettings(e){this.enabled!==e&&(this.enabled=e,e?this.init():this.stop());}stop(){this.stopWatch&&(this.stopWatch(),this.stopWatch=null),this.rescanTimer&&(window.clearInterval(this.rescanTimer),this.rescanTimer=null),this.clickHandler&&(document.removeEventListener("click",this.clickHandler,true),this.clickHandler=null),this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.fullscreenChangeHandler&&(document.removeEventListener("fullscreenchange",this.fullscreenChangeHandler),document.removeEventListener("webkitfullscreenchange",this.fullscreenChangeHandler),this.fullscreenChangeHandler=null);for(const e of this.pendingRequests.values())window.clearTimeout(e.timeoutId),e.reject(new Error("Assistant Mermaid renderer stopped"));this.pendingRequests.clear(),this.processedBlocks=new WeakMap,this.blockPanels=new WeakMap,this.panelBlocks=new WeakMap,this.cleanupInjectedPanels();}refreshLocalizedTexts(){ei.query(Iv,{all:true,shadow:true}).forEach(e=>{if(!(e instanceof HTMLElement))return;const t=e.querySelector("[data-mermaid-action='preview']"),n=e.querySelector("[data-mermaid-action='code']"),r=e.querySelector("[data-mermaid-action='copy']"),o=e.querySelector("[data-mermaid-action='download']"),i=e.querySelector("[data-mermaid-action='zoom-reset']"),a=e.querySelector("[data-mermaid-action='zoom-out']"),s=e.querySelector("[data-mermaid-action='zoom-in']"),l=e.querySelector("[data-mermaid-action='fullscreen']");t&&(t.textContent=re("assistantMermaidPreviewTab")),n&&(n.textContent=re("assistantMermaidCodeTab")),r&&(r.textContent=re("assistantMermaidCopyCode")),o&&(o.textContent=re("assistantMermaidDownloadPng")),i&&this.configureZoomResetButton(i),a&&this.configureZoomOutButton(a),s&&this.configureZoomInButton(s),l&&this.configureFullscreenButton(l);});}init(){if("fallback"!==this.adapter.getAssistantMermaidSupportMode())return;const e=this.getAssistantSelector();e&&(this.injectStyles(document),this.initClickHandler(),this.initMessageHandler(),this.initFullscreenChangeHandler(),this.stopWatch=ei.each(e,e=>{this.processResponseElement(e);},{shadow:true}),this.startRescanTimer());}getAssistantSelector(){return this.adapter.getExportConfig()?.assistantResponseSelector||null}initClickHandler(){this.clickHandler||(this.clickHandler=e=>{const t=e.composedPath(),n=t.find(e=>e instanceof HTMLElement&&e.hasAttribute("data-mermaid-action"))||e.target?.closest("[data-mermaid-action]");if(!n)return;const r=t.find(e=>e instanceof HTMLElement&&e.matches(Iv))||n.closest(Iv);if(!r)return;const o=this.panelBlocks.get(r);if(!o)return;e.preventDefault(),e.stopPropagation();const i=n.dataset.mermaidAction;"preview"!==i&&"code"!==i?"zoom-in"!==i&&"zoom-out"!==i&&"zoom-reset"!==i?"fullscreen"!==i?"copy"!==i?"download"===i&&this.downloadMermaidPng(r).catch(e=>{console.error("[AssistantMermaidRenderer] PNG download failed:",e),Oo(re("assistantMermaidDownloadFailed")||re("exportFailed"),2e3);}):this.copyMermaidSource(r).catch(e=>{console.error("[AssistantMermaidRenderer] Copy failed:",e);}):this.togglePreviewFullscreen(r).catch(e=>{console.error("[AssistantMermaidRenderer] Fullscreen failed:",e),Oo(re("assistantMermaidFullscreenFailed")||re("exportFailed"),2e3);}):this.adjustPreviewZoom(r,i):this.setView(o,r,i);},document.addEventListener("click",this.clickHandler,true));}initMessageHandler(){this.messageHandler||(this.messageHandler=e=>{const t=e.data;if(e.source!==window&&t?.type!==Ov)return;if(t?.type!==Ov)return;const n="string"==typeof t.requestId?t.requestId:"";if(!n)return;const r=this.pendingRequests.get(n);r&&(window.clearTimeout(r.timeoutId),this.pendingRequests.delete(n),t.success?r.resolve():r.reject(new Error(t.error||"Mermaid render failed")));},window.addEventListener("message",this.messageHandler));}initFullscreenChangeHandler(){this.fullscreenChangeHandler||(this.fullscreenChangeHandler=()=>{const e=ei.query(`${Iv}[${qv}='1']`,{shadow:true});if(!e)return;const t=e.querySelector(".gh-assistant-mermaid-preview");t?document.fullscreenElement!==t?this.restorePreviewZoomAfterFullscreen(e):this.fitPreviewToFullscreen(e,t):this.clearFullscreenState(e);},document.addEventListener("fullscreenchange",this.fullscreenChangeHandler),document.addEventListener("webkitfullscreenchange",this.fullscreenChangeHandler));}startRescanTimer(){this.rescanTimer||(window.setTimeout(()=>{this.enabled&&this.rescan();},1e3),this.rescanTimer=window.setInterval(()=>{this.enabled&&this.rescan();},2e3));}rescan(){if(document.hidden||!document.hasFocus())return;const e=this.getAssistantSelector();if(!e)return;const t=ei.query(e,{all:true,shadow:true});for(const n of t)this.processResponseElement(n);}processResponseElement(e){if(!this.enabled||"fallback"!==this.adapter.getAssistantMermaidSupportMode())return;const t=e.getRootNode();t instanceof ShadowRoot&&this.injectStyles(t);this.adapter.getAssistantMermaidBlocks(e).forEach(({element:e,source:t})=>{this.processMermaidBlock(e,t);});}async processMermaidBlock(e,t){if(!e.isConnected)return;const n=e.getRootNode();n instanceof ShadowRoot&&this.injectStyles(n);const r=ii(t);if(!r)return;const o=this.getMermaidTheme(),i=`${o}::${r}`;if(this.processedBlocks.get(e)===i)return;const a=this.ensurePanel(e),s=a.querySelector(".gh-assistant-mermaid-preview");if(!s)return;const l=a.dataset.view||"preview",c=this.ensurePreviewId(s),d=this.createRequestId();s.setAttribute(Rv,d);try{if(await this.ensureRuntime(),await this.requestRender(d,c,r,o),!e.isConnected)return;if(!a.isConnected||!s.isConnected)return;if(s.getAttribute(Rv)!==d)return;a.hidden=!1,a.dataset.source=r,this.setPreviewEnabled(a,!0),this.setDownloadEnabled(a,!0),this.setZoomEnabled(a,!0),this.applyPreviewZoom(a,1),this.processedBlocks.set(e,i),this.setView(e,a,l);}catch(u){if(!e.isConnected||!a.isConnected||!s.isConnected||s.getAttribute(Rv)!==d)return;console.warn("[AssistantMermaidRenderer] Mermaid render skipped:",u),!function(e){const t=e instanceof Error?e.message:String(e);return ["runtime asset url is unavailable","failed to load script","runner did not initialize","runtime is unavailable","render timed out","preview container not found"].some(e=>t.toLowerCase().includes(e))}(u)?(this.processedBlocks.set(e,i),this.applyRenderFallback(e,a,r)):(this.processedBlocks.delete(e),this.cleanupPanel(e));}}ensurePanel(e){const t=this.blockPanels.get(e)||(e.previousElementSibling?.matches?.(Iv)?e.previousElementSibling:null);if(t?.isConnected)return this.blockPanels.set(e,t),this.panelBlocks.set(t,e),t;const n=document.createElement("div");n.className="gh-assistant-mermaid",n.hidden=true;const r=document.createElement("div");r.className="gh-assistant-mermaid-toolbar";const o=document.createElement("div");o.className="gh-assistant-mermaid-toolbar-group";const i=document.createElement("div");i.className="gh-assistant-mermaid-actions";const a=document.createElement("button");a.type="button",a.className="gh-assistant-mermaid-btn",a.dataset.mermaidAction="preview",a.textContent=re("assistantMermaidPreviewTab");const s=document.createElement("button");s.type="button",s.className="gh-assistant-mermaid-btn",s.dataset.mermaidAction="code",s.textContent=re("assistantMermaidCodeTab");const l=document.createElement("button");l.type="button",l.className="gh-assistant-mermaid-btn",l.dataset.mermaidAction="copy",l.textContent=re("assistantMermaidCopyCode");const c=document.createElement("button");c.type="button",c.className="gh-assistant-mermaid-btn",c.dataset.mermaidAction="download",c.textContent=re("assistantMermaidDownloadPng");const d=document.createElement("div");d.className="gh-assistant-mermaid-toolbar-group";const u=document.createElement("div");u.className="gh-assistant-mermaid-zoom";const h=document.createElement("button");h.type="button",h.className="gh-assistant-mermaid-btn is-icon",h.dataset.mermaidAction="zoom-out",this.configureZoomOutButton(h);const g=document.createElement("button");g.type="button",g.className="gh-assistant-mermaid-btn is-icon",g.dataset.mermaidAction="zoom-reset",this.configureZoomResetButton(g);const p=document.createElement("button");p.type="button",p.className="gh-assistant-mermaid-btn is-icon",p.dataset.mermaidAction="zoom-in",this.configureZoomInButton(p);const m=document.createElement("button");m.type="button",m.className="gh-assistant-mermaid-btn is-icon",m.dataset.mermaidAction="fullscreen",this.configureFullscreenButton(m),u.append(h,g,p,m),o.append(i,u),i.append(a,s),d.append(c,l),r.append(o,d);const f=document.createElement("div");return f.className="gh-assistant-mermaid-preview",this.ensurePreviewId(f),n.append(r,f),e.before(n),e.setAttribute(Nv,"true"),e.hasAttribute(Lv)||e.setAttribute(Lv,e.style.display||""),this.blockPanels.set(e,n),this.panelBlocks.set(n,e),n}configureZoomResetButton(e){const t=re("assistantMermaidFitToPage");e.classList.add("is-icon"),e.setAttribute("aria-label",t),e.title=t,e.replaceChildren(function(e){const t=$v(e,"0 0 24 24"),n=e.createElementNS(zv,"path");return n.setAttribute("fill","currentColor"),n.setAttribute("fill-rule","evenodd"),n.setAttribute("clip-rule","evenodd"),n.setAttribute("d","M9 3a1 1 0 0 0-1-1H4a2 2 0 0 0-2 2v4.5a1 1 0 0 0 2 0V4h4a1 1 0 0 0 1-1m6 0a1 1 0 0 1 1-1h4a2 2 0 0 1 2 2v4.5a1 1 0 1 1-2 0V4h-4a1 1 0 0 1-1-1m1 19a1 1 0 1 1 0-2h4v-4.5a1 1 0 1 1 2 0V20a2 2 0 0 1-2 2zm-7-1a1 1 0 0 1-1 1H4a2 2 0 0 1-2-2v-4.5a1 1 0 1 1 2 0V20h4a1 1 0 0 1 1 1M8 10h8v4H8zm-2 0a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2z"),t.appendChild(n),t}(e.ownerDocument||document));}configureZoomOutButton(e){const t=re("assistantMermaidZoomOut");e.classList.add("is-icon"),e.setAttribute("aria-label",t),e.title=t,e.replaceChildren(function(e){const t=$v(e,"0 0 24 24"),n=e.createElementNS(zv,"path");return n.setAttribute("fill","currentColor"),n.setAttribute("fill-rule","evenodd"),n.setAttribute("clip-rule","evenodd"),n.setAttribute("d","M10.5 17a6.5 6.5 0 1 0 0-13 6.5 6.5 0 0 0 0 13m0 2a8.46 8.46 0 0 0 5.263-1.825l.03.032 5 5a1 1 0 0 0 1.414-1.414l-5-5-.032-.03A8.5 8.5 0 1 0 10.5 19M8 9.5a1 1 0 0 0 0 2h5a1 1 0 1 0 0-2z"),t.appendChild(n),t}(e.ownerDocument||document));}configureZoomInButton(e){const t=re("assistantMermaidZoomIn");e.classList.add("is-icon"),e.setAttribute("aria-label",t),e.title=t,e.replaceChildren(function(e){const t=$v(e,"0 0 24 24"),n=e.createElementNS(zv,"path");return n.setAttribute("fill","currentColor"),n.setAttribute("fill-rule","evenodd"),n.setAttribute("clip-rule","evenodd"),n.setAttribute("d","M17 10.5a6.5 6.5 0 1 1-13 0 6.5 6.5 0 0 1 13 0m-1.237 6.675a8.5 8.5 0 1 1 1.413-1.413l.031.03 5 5a1 1 0 0 1-1.414 1.415l-5-5zM7 10.5a1 1 0 0 1 1-1h1.5V8a1 1 0 0 1 2 0v1.5H13a1 1 0 1 1 0 2h-1.5V13a1 1 0 1 1-2 0v-1.5H8a1 1 0 0 1-1-1"),t.appendChild(n),t}(e.ownerDocument||document));}configureFullscreenButton(e){const t=re("assistantMermaidFullscreen");e.classList.add("is-icon"),e.setAttribute("aria-label",t),e.title=t,e.replaceChildren(function(e){const t=$v(e,"0 0 24 24"),n=e.createElementNS(zv,"path");return n.setAttribute("fill","currentColor"),n.setAttribute("d","M22 3v7a1 1 0 1 1-2 0V4h-6a1 1 0 1 1 0-2h7a1 1 0 0 1 1 1M11.005 21a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1v-7a1 1 0 0 1 2.002 0v6h6.003a1 1 0 0 1 1 1"),t.appendChild(n),t}(e.ownerDocument||document));}ensurePreviewId(e){const t=e.getAttribute(Dv);if(t)return t;this.previewIdCounter+=1;const n=`gh-assistant-mermaid-preview-${Date.now()}-${this.previewIdCounter}`;return e.setAttribute(Dv,n),n}setView(e,t,n){const r=t.querySelector(".gh-assistant-mermaid-preview");if(!r)return;t.dataset.view=n,r.hidden="preview"!==n,e.style.display="preview"===n?"none":e.getAttribute(Lv)||"";t.querySelectorAll("[data-mermaid-action='preview'], [data-mermaid-action='code']").forEach(e=>{e instanceof HTMLElement&&e.classList.toggle("is-active",e.dataset.mermaidAction===n);});}setPreviewEnabled(e,t){const n=e.querySelector("[data-mermaid-action='preview']");n&&(n.disabled=!t);}setZoomEnabled(e,t){e.querySelectorAll("[data-mermaid-action='zoom-out'], [data-mermaid-action='zoom-reset'], [data-mermaid-action='zoom-in'], [data-mermaid-action='fullscreen']").forEach(e=>{e instanceof HTMLButtonElement&&(e.disabled=!t);});}setDownloadEnabled(e,t){const n=e.querySelector("[data-mermaid-action='download']");n&&(n.disabled=!t);}adjustPreviewZoom(e,t){const n=Number.parseFloat(e.dataset.zoom||"1");if("zoom-reset"===t)return void this.applyPreviewZoom(e,1);const r="zoom-in"===t?n+.25:n-.25;this.applyPreviewZoom(e,r);}applyPreviewZoom(e,t){const n=e.querySelector(".gh-assistant-mermaid-preview"),r=n?.querySelector("svg");if(!n||!r)return void this.setZoomEnabled(e,false);const o=Math.min(this.getMaxPreviewZoom(e),Math.max(.5,t));e.dataset.zoom=`${o}`;const i=this.getPreviewBaseWidth(r);r.style.maxWidth="none",r.style.width=`${Math.max(1,Math.round(i*o))}px`,r.style.height="auto",this.updateZoomButtonState(e,o);}getMaxPreviewZoom(e){const t=Number.parseFloat(e.getAttribute(Bv)||"");return Math.max(3,Number.isFinite(t)?t:0)}getPreviewBaseWidth(e){const t=Number.parseFloat(e.dataset.ophelBaseWidth||"");if(Number.isFinite(t)&&t>0)return t;const n=e.getBoundingClientRect().width,r=Number.parseFloat(e.getAttribute("width")||"")||e.viewBox?.baseVal?.width||320,o=n>0?n:r;return e.dataset.ophelBaseWidth=`${o}`,o}getPreviewBaseDimensions(e){const t=this.getPreviewBaseWidth(e),n=e.getBoundingClientRect(),r=Number.parseFloat(e.getAttribute("width")||""),o=Number.parseFloat(e.getAttribute("height")||""),i=e.viewBox?.baseVal?.width||0,a=e.viewBox?.baseVal?.height||0;return {width:t,height:t*(i>0&&a>0&&a/i||n.width>0&&n.height>0&&n.height/n.width||r>0&&o>0&&o/r||.75)}}updateZoomButtonState(e,t){const n=e.querySelector("[data-mermaid-action='zoom-out']"),r=e.querySelector("[data-mermaid-action='zoom-reset']"),o=e.querySelector("[data-mermaid-action='zoom-in']"),i=this.getMaxPreviewZoom(e);n&&(n.disabled=t<=.5),r&&(r.disabled=Math.abs(t-1)<.001),o&&(o.disabled=t>=i);}applyRenderFallback(e,t,n){const r=t.querySelector(".gh-assistant-mermaid-preview");r&&r.replaceChildren(),t.hidden=false,t.dataset.source=n,this.setPreviewEnabled(t,false),this.setDownloadEnabled(t,false),this.setZoomEnabled(t,false),this.setView(e,t,"code");}async togglePreviewFullscreen(e){const t=e.querySelector(".gh-assistant-mermaid-preview");if(!t)throw new Error("Mermaid preview container not found");const n=this.panelBlocks.get(e);if(n&&"preview"!==e.dataset.view&&this.setView(n,e,"preview"),document.fullscreenElement!==t){if("function"!=typeof t.requestFullscreen)throw new Error("Fullscreen API is unavailable");e.setAttribute(qv,"1"),e.setAttribute(Pv,e.dataset.zoom||"1");try{await t.requestFullscreen();}catch(r){throw this.clearFullscreenState(e),r}}else await document.exitFullscreen();}fitPreviewToFullscreen(e,t){const n=t.querySelector("svg");if(!n)return void this.setZoomEnabled(e,false);const{width:r,height:o}=this.getPreviewBaseDimensions(n);if(r<=0||o<=0)return;const i=Math.max(1,t.clientWidth-48),a=Math.max(1,t.clientHeight-48),s=Math.min(i/r,a/o);e.setAttribute(Bv,`${Math.max(3,s)}`),this.applyPreviewZoom(e,s),t.scrollTop=0,t.scrollLeft=0;}restorePreviewZoomAfterFullscreen(e){const t=Number.parseFloat(e.getAttribute(Pv)||"")||1;this.clearFullscreenState(e),this.applyPreviewZoom(e,t);}clearFullscreenState(e){e.removeAttribute(qv),e.removeAttribute(Pv),e.removeAttribute(Bv);}async copyMermaidSource(e){const t=e.dataset.source||"";t&&(await navigator.clipboard.writeText(t),Oo(re("copySuccess"),1500));}async downloadMermaidPng(e){const t=e.querySelector(".gh-assistant-mermaid-preview"),n=t?.querySelector("svg");if(!n)throw new Error("Mermaid preview svg not found");const{width:r,height:o}=this.getSvgExportDimensions(n),i=Math.max(1,Math.round(r)),a=Math.max(1,Math.round(o));let s;try{s=await this.renderSvgToPngBlob(n,i,a);}catch(c){if(!n.querySelector("foreignObject")||!function(e){const t=e instanceof Error?e.message:String(e),n=e instanceof DOMException||e instanceof Error?e.name:"",r=t.toLowerCase();return n.toLowerCase().includes("securityerror")||r.includes("tainted canvas")||r.includes("tainted canvases may not be exported")}(c))throw c;s=await this.renderSvgToPngBlob(n,i,a,{downgradeForeignObjects:true});}const l=URL.createObjectURL(s);try{const e=document.createElement("a");e.href=l,e.download=this.createPngFilename(),e.click();}finally{URL.revokeObjectURL(l);}Oo(re("assistantMermaidDownloadSuccess")||re("exportSuccess"),1500);}getSvgExportDimensions(e){const t=e.getBoundingClientRect(),n=Number.parseFloat(e.style.width||""),r=Number.parseFloat(e.style.height||""),o=Number.parseFloat(e.getAttribute("width")||""),i=Number.parseFloat(e.getAttribute("height")||""),a=e.viewBox?.baseVal?.width||0,s=e.viewBox?.baseVal?.height||0,l=t.width||n||o||this.getPreviewBaseWidth(e)||a||320;return {width:l,height:l*(t.width>0&&t.height>0&&t.height/t.width||n>0&&r>0&&r/n||o>0&&i>0&&i/o||a>0&&s>0&&s/a||.75)}}serializeSvgForPng(e,t,n,r={}){const o=e.cloneNode(true);return o.setAttribute("xmlns",zv),o.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"),o.setAttribute("width",`${t}`),o.setAttribute("height",`${n}`),o.style.width=`${t}px`,o.style.height=`${n}px`,o.style.maxWidth="none",r.downgradeForeignObjects&&this.downgradeForeignObjectsForPng(e,o),(new XMLSerializer).serializeToString(o)}async renderSvgToPngBlob(e,t,n,r={}){const o=this.serializeSvgForPng(e,t,n,r),i=URL.createObjectURL(new Blob([o],{type:"image/svg+xml;charset=utf-8"}));try{const e=await this.loadSvgImage(i),r=document.createElement("canvas");r.width=Math.ceil(2*(t+48)),r.height=Math.ceil(2*(n+48));const o=r.getContext("2d");if(!o)throw new Error("Canvas 2D context is unavailable");return o.scale(2,2),o.fillStyle="dark"===this.getMermaidTheme()?"#0f172a":"#ffffff",o.fillRect(0,0,r.width/2,r.height/2),o.drawImage(e,24,24,t,n),await this.canvasToBlob(r)}finally{URL.revokeObjectURL(i);}}downgradeForeignObjectsForPng(e,t){const n=Array.from(e.querySelectorAll("foreignObject"));Array.from(t.querySelectorAll("foreignObject")).forEach((e,r)=>{const o=this.createForeignObjectTextFallback(n[r],t.ownerDocument);e.replaceWith(o);});}createForeignObjectTextFallback(e,t){const n=t.createElementNS(zv,"g");if(!e)return n;const r=this.getForeignObjectMetric(e,"x"),o=this.getForeignObjectMetric(e,"y"),i=this.getForeignObjectMetric(e,"width"),a=this.getForeignObjectMetric(e,"height"),s=this.getForeignObjectLines(e);if(0===s.length||i<=0||a<=0)return n;const l=e.querySelector("*")||null,c=l?window.getComputedStyle(l):null,d=Math.max(10,Number.parseFloat(c?.fontSize||"")||Math.min(16,Math.max(12,.35*a))),u=Number.parseFloat(c?.lineHeight||"")||Math.max(1.2*d,a/Math.max(s.length,1)),h=r+i/2,g=o+a/2-(s.length-1)*u/2,p=c?.color||("dark"===this.getMermaidTheme()?"#e5e7eb":"#111827"),m=c?.fontFamily||"Arial, sans-serif",f=c?.fontWeight||"400";return s.forEach((e,r)=>{const o=t.createElementNS(zv,"text");o.setAttribute("x",`${h}`),o.setAttribute("y",`${g+r*u}`),o.setAttribute("text-anchor","middle"),o.setAttribute("dominant-baseline","middle"),o.setAttribute("fill",p),o.setAttribute("font-size",`${d}`),o.setAttribute("font-family",m),o.setAttribute("font-weight",f),o.textContent=e,n.appendChild(o);}),n}getForeignObjectMetric(e,t){const n=Number.parseFloat(e.getAttribute(t)||"");if(Number.isFinite(n))return n;const r=e instanceof SVGGraphicsElement?e.getBBox():{x:0,y:0,width:0,height:0};return "x"===t?r.x:"y"===t?r.y:"width"===t?r.width:"height"===t?r.height:0}getForeignObjectLines(e){const t=e.querySelector("*")||null;return (t&&"string"==typeof t.innerText&&t.innerText||t?.textContent||e.textContent||"").replace(/\r\n/g,"\n").split("\n").map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean)}loadSvgImage(e){return new Promise((t,n)=>{const r=new Image;r.decoding="async",r.onload=()=>t(r),r.onerror=()=>n(new Error("Failed to load Mermaid SVG image")),r.src=e;})}canvasToBlob(e){return new Promise((t,n)=>{e.toBlob(e=>{e?t(e):n(new Error("Failed to convert Mermaid canvas to PNG blob"));},"image/png");})}createPngFilename(){return `ophel-mermaid-${(new Date).toISOString().replace(/[:.]/g,"-")}.png`}cleanupInjectedPanels(){ei.query(`[${Nv}]`,{all:true,shadow:true}).forEach(e=>{e instanceof HTMLElement&&(e.style.display=e.getAttribute(Lv)||"",e.removeAttribute(Nv),e.removeAttribute(Lv));});ei.query(Iv,{all:true,shadow:true}).forEach(e=>e.remove());}cleanupPanel(e){const t=this.blockPanels.get(e);t?.isConnected&&t.remove(),e.style.display=e.getAttribute(Lv)||"",e.removeAttribute(Nv),e.removeAttribute(Lv);}injectStyles(e){if(this.injectedRoots.has(e))return;if(e.querySelector?.(`#${Mv}`))return;const t=document.createElement("style");t.id=Mv,t.textContent="\n.gh-assistant-mermaid {\n margin: 12px 0;\n border: 1px solid var(--gh-border, rgba(148, 163, 184, 0.28));\n border-radius: 10px;\n background: var(--gh-bg-secondary, rgba(255, 255, 255, 0.9));\n overflow: hidden;\n}\n\n.gh-assistant-mermaid-toolbar {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 10px;\n padding: 8px 10px;\n border-bottom: 1px solid var(--gh-border, rgba(148, 163, 184, 0.2));\n background: var(--gh-bg-primary, rgba(248, 250, 252, 0.96));\n}\n\n.gh-assistant-mermaid-actions {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n}\n\n.gh-assistant-mermaid-toolbar-group {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n}\n\n.gh-assistant-mermaid-zoom {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n}\n\n.gh-assistant-mermaid-btn {\n appearance: none;\n border: 1px solid var(--gh-border, rgba(148, 163, 184, 0.28));\n background: transparent;\n color: var(--gh-text-secondary, #64748b);\n border-radius: 999px;\n padding: 4px 10px;\n font-size: 12px;\n line-height: 1.4;\n cursor: pointer;\n transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;\n}\n\n.gh-assistant-mermaid-btn.is-icon {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n min-width: 30px;\n padding: 4px 8px;\n}\n\n.gh-assistant-mermaid-btn-icon {\n width: 14px;\n height: 14px;\n display: block;\n flex: 0 0 auto;\n}\n\n.gh-assistant-mermaid-btn:hover {\n background: rgba(59, 130, 246, 0.08);\n color: var(--gh-text, #0f172a);\n border-color: rgba(59, 130, 246, 0.28);\n}\n\n.gh-assistant-mermaid-btn.is-active {\n background: rgba(59, 130, 246, 0.14);\n color: #2563eb;\n border-color: rgba(59, 130, 246, 0.3);\n}\n\n.gh-assistant-mermaid-btn:disabled {\n opacity: 0.56;\n cursor: not-allowed;\n}\n\n.gh-assistant-mermaid-preview {\n padding: 12px;\n overflow-x: auto;\n background: var(--gh-bg-primary, rgba(255, 255, 255, 0.96));\n}\n\n.gh-assistant-mermaid-preview:fullscreen,\n.gh-assistant-mermaid-preview:-webkit-full-screen {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 100%;\n height: 100%;\n padding: 24px;\n box-sizing: border-box;\n overflow: auto;\n background: var(--gh-bg-primary, rgba(255, 255, 255, 0.98));\n}\n\n.gh-assistant-mermaid-preview[hidden] {\n display: none !important;\n}\n\n.gh-assistant-mermaid-preview svg {\n display: block;\n max-width: 100%;\n height: auto;\n margin: 0 auto;\n}\n\n.gh-assistant-mermaid-preview:fullscreen svg,\n.gh-assistant-mermaid-preview:-webkit-full-screen svg {\n margin: auto;\n flex: 0 0 auto;\n}\n\nbody.dark-theme .gh-assistant-mermaid,\nhtml.dark .gh-assistant-mermaid,\nhtml[dark-theme] .gh-assistant-mermaid {\n background: rgba(15, 23, 42, 0.88);\n}\n\nbody.dark-theme .gh-assistant-mermaid-toolbar,\nhtml.dark .gh-assistant-mermaid-toolbar,\nhtml[dark-theme] .gh-assistant-mermaid-toolbar,\nbody.dark-theme .gh-assistant-mermaid-preview,\nhtml.dark .gh-assistant-mermaid-preview,\nhtml[dark-theme] .gh-assistant-mermaid-preview {\n background: rgba(15, 23, 42, 0.92);\n}\n\nbody.dark-theme .gh-assistant-mermaid-btn,\nhtml.dark .gh-assistant-mermaid-btn,\nhtml[dark-theme] .gh-assistant-mermaid-btn {\n color: rgba(226, 232, 240, 0.82);\n border-color: rgba(148, 163, 184, 0.26);\n}\n\nbody.dark-theme .gh-assistant-mermaid-btn:hover,\nhtml.dark .gh-assistant-mermaid-btn:hover,\nhtml[dark-theme] .gh-assistant-mermaid-btn:hover {\n color: #eff6ff;\n background: rgba(59, 130, 246, 0.18);\n}\n\nbody.dark-theme .gh-assistant-mermaid-btn.is-active,\nhtml.dark .gh-assistant-mermaid-btn.is-active,\nhtml[dark-theme] .gh-assistant-mermaid-btn.is-active {\n color: #93c5fd;\n}\n",e instanceof ShadowRoot?e.prepend(t):document.head.appendChild(t),this.injectedRoots.add(e);}getMermaidTheme(){const e=document.documentElement.className,t=document.body.className,n=/\bdark\b/i.test(e),r=/\bdark-theme\b/i.test(t),o=document.documentElement.hasAttribute("dark-theme");return n||r||o?"dark":"default"}createRequestId(){return `gh-assistant-mermaid-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}async ensureRuntime(){if(!jv())return this.runtimePromise||(this.runtimePromise=(async()=>{const e=Fv("assistantMermaidVendor"),t=Fv("assistantMermaidRunner");if(!e||!t)throw new Error("Assistant Mermaid runtime asset URL is unavailable");if(await this.injectScript(e,"ophel-assistant-mermaid-vendor"),await this.injectScript(t,"ophel-assistant-mermaid-runner"),!jv())throw new Error("Assistant Mermaid runner did not initialize")})().catch(e=>{throw this.runtimePromise=null,e})),this.runtimePromise}injectScript(e,t){const n=`script[data-ophel-runtime="${t}"]`,r=document.querySelector(n);return "true"===r?.dataset.loaded?Promise.resolve():new Promise((n,o)=>{const i=r||document.createElement("script"),a=()=>{i.removeEventListener("load",s),i.removeEventListener("error",l);},s=()=>{a(),i.dataset.loaded="true",n();},l=()=>{a(),o(new Error(`Failed to load script: ${e}`));};i.addEventListener("load",s,{once:true}),i.addEventListener("error",l,{once:true});try{i.dataset.ophelRuntime=t,i.dataset.loaded="false",i.async=!1;if((i.getAttribute("src")||i.src)!==e&&!Gu(i,e))throw new Error(`Failed to set trusted script src: ${e}`);r||(document.head||document.documentElement).appendChild(i);}catch(c){a(),o(c instanceof Error?c:new Error(`Failed to load script: ${e}`));}})}requestRender(e,t,n,r){return new Promise((o,i)=>{const a=window.setTimeout(()=>{this.pendingRequests.delete(e),i(new Error("Assistant Mermaid render timed out"));},15e3);this.pendingRequests.set(e,{resolve:o,reject:i,timeoutId:a}),window.postMessage({type:"OPHEL_ASSISTANT_MERMAID_RENDER_REQUEST",requestId:e,previewId:t,source:n,theme:r},"*");})}}class Uv{settings;siteAdapter=null;formulaCopyInitialized=false;tableCopyInitialized=false;formulaDblClickHandler=null;stopTableWatch=null;rescanTimer=null;static FORMULA_HOST_SELECTOR=[".math-block",".math-inline",".katex",".katex-display","math","[data-math]","[data-custom-copy-text]",'annotation[encoding="application/x-tex"]'].join(", ");constructor(e,t){this.settings=e,this.siteAdapter=t||null;}updateSettings(e){e.formulaCopy!==this.settings.formulaCopy&&(e.formulaCopy?(this.settings=e,this.initFormulaCopy()):this.destroyFormulaCopy()),e.tableCopy!==this.settings.tableCopy&&(e.tableCopy?(this.settings=e,this.initTableCopy()):this.destroyTableCopy()),this.settings=e;}initFormulaCopy(){if(this.formulaCopyInitialized)return;this.formulaCopyInitialized=true;const e="gh-formula-copy-style";if(!document.getElementById(e)){const t=document.createElement("style");t.id=e,t.textContent="\n .math-block, .math-inline, .katex {\n user-select: none !important;\n cursor: pointer !important;\n }\n .math-block:hover, .math-inline:hover, .katex:hover {\n outline: 2px solid #4285f4;\n outline-offset: 2px;\n border-radius: 4px;\n }\n ",document.head.appendChild(t);}this.formulaDblClickHandler=e=>{const t=e.target instanceof Element?e.target:e.target instanceof Node?e.target.parentElement:null;if(t)try{const n=t.closest(Uv.FORMULA_HOST_SELECTOR);if(!n)return;const r=n.closest(".math-block, .math-inline, [data-math], [data-custom-copy-text]");if(r){let t=r.getAttribute("data-math")||r.getAttribute("data-custom-copy-text");if(t&&(t=this.unwrapMathDelimiters(t),t))return this.copyLatex(t,r.classList.contains("math-block")||r.matches(".math-block")),e.preventDefault(),void e.stopPropagation()}const o=n.closest(".katex, .katex-display")||t.closest(".katex, .katex-display"),i=n.closest("math")||t.closest("math")||o?.querySelector("math")||null,a=n.matches('annotation[encoding="application/x-tex"]')?n:o?.querySelector('annotation[encoding="application/x-tex"]')||i?.querySelector('annotation[encoding="application/x-tex"]')||null;if(a?.textContent){const t=!!o?.closest(".katex-display");return this.copyLatex(a.textContent,t),e.preventDefault(),void e.stopPropagation()}Oo(re("formulaSourceUnavailable")||re("copyFailed")),e.preventDefault(),e.stopPropagation();}catch(n){console.error("[FormulaCopy] Unexpected error:",n),Oo(re("copyFailed"));}},document.addEventListener("dblclick",this.formulaDblClickHandler,true);}unwrapMathDelimiters(e){const t=e.trim();if(!t)return "";const n=[["$$","$$"],["\\(","\\)"],["\\[","\\]"],["$","$"]];for(const[r,o]of n)if(t.startsWith(r)&&t.endsWith(o)&&t.length>r.length+o.length)return t.slice(r.length,t.length-o.length).trim();return t}copyLatex(e,t){const n=e.replace(/\r\n?/g,"\n").trim();let r=n;if(this.settings.formulaDelimiter){const e=t&&(n.includes("\n")||/(^|[^\\])\\\\($|[^\\])/.test(n));r=t?e?`$$\n${n}\n$$`:`$$${n}$$`:`$${n}$`;}navigator.clipboard?.writeText?navigator.clipboard.writeText(r).then(()=>Oo(re("formulaCopied"))).catch(e=>{console.error("[FormulaCopy] Copy failed:",e),Oo(re("copyFailed"));}):Oo(re("copyFailed"));}destroyFormulaCopy(){this.formulaCopyInitialized=false;const e=document.getElementById("gh-formula-copy-style");e&&e.remove(),this.formulaDblClickHandler&&(document.removeEventListener("dblclick",this.formulaDblClickHandler,true),this.formulaDblClickHandler=null);}initTableCopy(){if(this.tableCopyInitialized)return;this.tableCopyInitialized=true;const e="gh-table-copy-style";if(!document.getElementById(e)){const t=document.createElement("style");t.id=e,t.textContent="\n .gh-table-copy-btn {\n position: absolute;\n top: 4px;\n right: 4px;\n width: 28px;\n height: 28px;\n border: none;\n border-radius: 6px;\n background: rgba(255,255,255,0.9);\n color: #374151;\n cursor: pointer;\n font-size: 14px;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0.7;\n transition: opacity 0.2s, background 0.2s;\n z-index: 10;\n box-shadow: 0 1px 3px rgba(0,0,0,0.1);\n }\n .gh-table-container:hover .gh-table-copy-btn,\n table-block:hover .gh-table-copy-btn,\n ucs-markdown-table:hover .gh-table-copy-btn {\n opacity: 1;\n }\n .gh-table-copy-btn:hover {\n background: #4285f4;\n color: white;\n }\n ",document.head.appendChild(t);}this.siteAdapter?.usesShadowDOM()??false?this.startRescanTimer():this.stopTableWatch=ei.each("table",e=>{this.injectTableButton(e);},{shadow:true});}startRescanTimer(){this.rescanTables(),this.rescanTimer=setInterval(()=>{this.rescanTables();},1e3);}rescanTables(){if(document.hidden)return;const e=ei.query("table",{all:true,shadow:true});for(const t of e)this.injectTableButton(t);}injectTableButton(e){if(e.dataset.ghTableCopy)return;e.dataset.ghTableCopy="true";const t=e.closest(".gh-user-query-markdown")||e.closest(".gh-markdown-preview");try{let n;if(t)n=e,e.style.position="relative";else {if(n=e.closest("table-block, ucs-markdown-table"),!n){if(n=e.parentNode,!n)return;n.classList.add("gh-table-container");}n.style.position="relative";}const r=document.createElement("button");r.className="gh-table-copy-btn",r.appendChild(Eu({size:14,color:"#6b7280"})),r.title=re("tableCopyLabel");const o=n.tagName?.toLowerCase(),i="ucs-markdown-table"===o||n.closest("ucs-markdown-table")||n.classList.contains("gh-table-container")?"80px":"4px";Object.assign(r.style,{position:"absolute",top:"4px",right:i,width:"28px",height:"28px",border:"none",borderRadius:"6px",background:"rgba(255,255,255,0.9)",color:"#374151",cursor:"pointer",fontSize:"14px",display:"flex",alignItems:"center",justifyContent:"center",opacity:"0.6",transition:"opacity 0.2s, background 0.2s, transform 0.2s",zIndex:"10",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",pointerEvents:"auto"}),r.addEventListener("mouseenter",()=>{r.style.opacity="1",r.style.transform="scale(1.1)";}),r.addEventListener("mouseleave",()=>{r.style.opacity="0.6",r.style.transform="scale(1)";}),r.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation();const n=this.tableToMarkdown(e);navigator.clipboard.writeText(n).then(()=>{Oo(re("tableCopied")),_u(r,{size:14});}).catch(e=>{console.error("[TableCopy] Copy failed:",e),Oo(re("copyFailed"));});}),n.appendChild(r);}catch(n){console.error("[TableCopy] Error injecting button:",n);}}tableToMarkdown(e){const t=e.querySelectorAll("tr");if(0===t.length)return "";const n=[];let r=false;const o=e=>{if(this.settings.formulaCopy){const t=e.cloneNode(true);return t.querySelectorAll(".math-block, .math-inline").forEach(e=>{const t=e,n=t.getAttribute("data-math");if(n){const e=t.classList.contains("math-block");let r;r=this.settings.formulaDelimiter?e?`$$${n}$$`:`$${n}$`:n,t.replaceWith(document.createTextNode(r));}}),t.innerText?.trim().replace(/\|/g,"\\|").replace(/\n/g," ")||""}return e.innerText?.trim().replace(/\|/g,"\\|").replace(/\n/g," ")||""};return t.forEach((e,t)=>{const i=e.querySelectorAll("th, td"),a=Array.from(i).map(e=>o(e));if(n.push("| "+a.join(" | ")+" |"),!r&&(e.querySelector("th")||0===t)){const e=Array.from(i).map(e=>e.classList.contains("align-center")?":---:":e.classList.contains("align-right")?"---:":"---");n.push("| "+e.join(" | ")+" |"),r=true;}}),n.join("\n")}destroyTableCopy(){this.tableCopyInitialized=false,this.stopTableWatch&&(this.stopTableWatch(),this.stopTableWatch=null),this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);const e=document.getElementById("gh-table-copy-style");e&&e.remove(),ei.query(".gh-table-copy-btn",{all:true,shadow:true})?.forEach(e=>e.remove()),ei.query("[data-gh-table-copy]",{all:true,shadow:true})?.forEach(e=>{e instanceof HTMLElement&&e.removeAttribute("data-gh-table-copy");}),ei.query(".gh-table-container",{all:true,shadow:true})?.forEach(e=>{e.classList.remove("gh-table-container");});}stop(){this.destroyFormulaCopy(),this.destroyTableCopy();}}const Wv="gh-page-width-styles",Vv="gh-page-width-shadow",Gv="gh-user-query-width-styles",Qv="gh-user-query-width-shadow",Kv="gh-zen-mode-styles",Zv="gh-zen-mode-shadow";class Yv{siteAdapter;pageWidthConfig;userQueryWidthConfig=null;pageWidthStyle=null;userQueryWidthStyle=null;zenModeStyle=null;zenModeLastEnabled=false;zenModeActionTimer=null;zenModeActionAttempts=0;zenModeEnabled=false;processedShadowRoots=new WeakSet;shadowCheckInterval=null;constructor(e,t){this.siteAdapter=e,this.pageWidthConfig=t;}updateConfig(e){this.pageWidthConfig=e,this.apply();}apply(){if(this.removeStyle(this.pageWidthStyle),this.pageWidthStyle=null,!this.pageWidthConfig?.enabled)return void this.refreshShadowInjection();const e=this.generatePageWidthCSS();this.pageWidthStyle=this.injectStyle(Wv,e),this.refreshShadowInjection();}updateUserQueryConfig(e){this.userQueryWidthConfig=e,this.applyUserQueryWidth();}applyUserQueryWidth(){if(this.removeStyle(this.userQueryWidthStyle),this.userQueryWidthStyle=null,!this.userQueryWidthConfig?.enabled)return void this.refreshShadowInjection();const e=this.generateUserQueryWidthCSS();this.userQueryWidthStyle=this.injectStyle(Gv,e),this.refreshShadowInjection();}updateZenMode(e){this.zenModeEnabled=e,this.applyZenMode();}applyZenMode(){if(this.removeStyle(this.zenModeStyle),this.zenModeStyle=null,!this.zenModeEnabled)return this.zenModeLastEnabled=false,void this.refreshShadowInjection();const e=this.generateZenModeCSS();e&&(this.zenModeStyle=this.injectStyle(Kv,e)),this.refreshShadowInjection(),this.zenModeEnabled&&!this.zenModeLastEnabled&&this.runZenModeActions(),this.zenModeLastEnabled=this.zenModeEnabled;}generatePageWidthCSS(){const e=`${this.pageWidthConfig.value}${this.pageWidthConfig.unit}`,t=this.siteAdapter.getWidthSelectors();return this.buildCSSFromSelectors(t,e,true)}generateUserQueryWidthCSS(){if(!this.userQueryWidthConfig)return "";const e=`${this.userQueryWidthConfig.value||"600"}${this.userQueryWidthConfig.unit||"px"}`,t=this.siteAdapter.getUserQueryWidthSelectors();return this.buildCSSFromSelectors(t,e,false)}generateZenModeCSS(){const e=this.siteAdapter.getZenModeSelectors();return 0===e.length?"":e.filter(e=>"hide"===e.action).map(e=>`${e.selector} { display: none !important; }`).join("\n")}runZenModeActions(){const e=this.siteAdapter.getZenModeSelectors().filter(e=>"click"===e.action);if(0===e.length)return;this.zenModeActionTimer&&(window.clearTimeout(this.zenModeActionTimer),this.zenModeActionTimer=null),this.zenModeActionAttempts=0;const t=()=>{this.zenModeActionAttempts+=1;let n=false;e.forEach(e=>{const t=document.querySelector(e.selector);if(!t||null===t.offsetParent)return;const r=t.closest("button, [role='button'], .operation-btn")||t;"function"==typeof r.click&&(r.click(),n=true);}),!n&&this.zenModeActionAttempts<6&&(this.zenModeActionTimer=window.setTimeout(t,400));};t();}buildCSSFromSelectors(e,t,n){return e.map(e=>{const{selector:r,globalSelector:o,property:i,value:a,extraCss:s,noCenter:l}=e;return `${n&&o||r} { ${i}: ${a||t} !important; ${l?"":"margin-left: auto !important; margin-right: auto !important;"} ${s||""} }`}).join("\n")}injectStyle(e,t){const n=document.createElement("style");return n.id=e,n.textContent=t,document.head.appendChild(n),n}removeStyle(e){e&&e.remove();}refreshShadowInjection(){if(!(this.pageWidthConfig?.enabled||this.userQueryWidthConfig?.enabled||this.zenModeEnabled))return this.stopShadowInjection(),void this.clearAllShadowStyles();this.startShadowInjection();}startShadowInjection(){this.injectToAllShadows(),this.shadowCheckInterval||(this.shadowCheckInterval=setInterval(()=>this.injectToAllShadows(),1e3));}stopShadowInjection(){this.shadowCheckInterval&&(clearInterval(this.shadowCheckInterval),this.shadowCheckInterval=null);}injectToAllShadows(){if(!document.body)return;const e=this.siteAdapter;ei.walkShadowRoots((t,n)=>{if(!n||e.shouldInjectIntoShadow(n)){if(this.pageWidthConfig?.enabled){const n=this.buildCSSFromSelectors(e.getWidthSelectors(),`${this.pageWidthConfig.value}${this.pageWidthConfig.unit}`,false);ei.cssToShadow(t,n,Vv);}else this.removeStyleFromShadow(t,Vv);if(this.userQueryWidthConfig?.enabled){const n=this.userQueryWidthConfig.value||"600",r=this.userQueryWidthConfig.unit||"px",o=this.buildCSSFromSelectors(e.getUserQueryWidthSelectors(),`${n}${r}`,false);ei.cssToShadow(t,o,Qv);}else this.removeStyleFromShadow(t,Qv);if(this.zenModeEnabled){const e=this.generateZenModeCSS();e&&ei.cssToShadow(t,e,Zv);}else this.removeStyleFromShadow(t,Zv);this.processedShadowRoots.add(t);}});}removeStyleFromShadow(e,t){const n=e.getElementById(t);n&&n.remove();}clearAllShadowStyles(){document.body&&ei.walkShadowRoots(e=>{this.removeStyleFromShadow(e,Vv),this.removeStyleFromShadow(e,Qv),this.removeStyleFromShadow(e,Zv),this.processedShadowRoots.delete(e);});}}const Jv=/]*>[\s\S]*?<\/code>/gi,Xv=/]*>([\s\S]*?)<\/b>/gi,ew=/]*>([\s\S]*?)<\/strong>/gi,tw=/\*\*([^*]+(?:\*(?!\*)[^*]*)*)\*\*/g,nw=/###OPHEL_CODE_(\d+)###/g;class rw{stopObserver=null;enabled=false;config;constructor(e){this.config=e;}start(){this.enabled||(this.enabled=true,this.fixAllParagraphs(),this.stopObserver=ei.each(this.config.selector,(e,t)=>{t&&setTimeout(()=>this.fixParagraph(e),100);}));}stop(){this.enabled&&(this.enabled=false,this.stopObserver&&(this.stopObserver(),this.stopObserver=null));}fixAllParagraphs(){ei.query(this.config.selector,{all:true}).forEach(e=>this.fixParagraph(e));}fixParagraph(e){if(!e.isConnected)return;if(this.config.shouldSkip?.(e))return void setTimeout(()=>this.fixParagraph(e),500);const t=e.innerHTML;if(e.dataset.mdFixerHash===String(t.length))return;if(!t.includes("(n.push(e),`###OPHEL_CODE_${n.length-1}###`)).replace(ew,"**$1**");r=r.replace(Xv,"**$1**");let o=false;if(r=r.replace(tw,(e,t)=>(o=true,`${t}`)),o){const o=r.replace(nw,(e,t)=>n[parseInt(t,10)]);t!==o&&Wu(e,o);}e.dataset.mdFixerHash=String(e.innerHTML.length);}}class ow{adapter;config;isLocked=false;verifyTimer=null;configDebounceTimer=null;constructor(e,t){this.adapter=e,this.config=t;}updateConfig(e){const t=this.config.enabled,n=this.config.keyword;this.config=e;(!t&&e.enabled||e.enabled&&e.keyword!==n)&&(this.configDebounceTimer&&clearTimeout(this.configDebounceTimer),this.configDebounceTimer=setTimeout(()=>{this.configDebounceTimer=null,this.isLocked=false,this.start(50);},500));}start(e=1500){this.config.enabled&&this.config.keyword&&(this.isLocked||setTimeout(()=>{this.isLocked||this.adapter.lockModel(this.config.keyword,()=>{this.startVerification();});},e));}relock(e=300){this.config.enabled&&this.config.keyword&&(this.stop(),this.isLocked=false,this.start(e));}startVerification(){this.verifyTimer&&clearInterval(this.verifyTimer);let e=0,t=0;this.verifyTimer=setInterval(()=>{e++;const n=this.adapter.getModelSwitcherConfig(this.config.keyword);if(!n)return void this.finishVerification();const r=this.adapter.findElementBySelectors(n.selectorButtonSelectors);if(!r)return void this.finishVerification();const o=this.adapter.getModelLockCheckText(r).toLowerCase().trim(),i=n.targetModelKeyword.toLowerCase().trim();o?o.includes(i)?(t++,(t>=2||e>=3)&&this.finishVerification()):(t=0,e<=2?(this.finishVerification(),this.adapter.lockModel(this.config.keyword,()=>{this.startVerification();})):this.finishVerification()):e>=3&&this.finishVerification();},1500);}finishVerification(){this.isLocked=true,this.verifyTimer&&(clearInterval(this.verifyTimer),this.verifyTimer=null);}stop(){this.configDebounceTimer&&(clearTimeout(this.configDebounceTimer),this.configDebounceTimer=null),this.verifyTimer&&(clearInterval(this.verifyTimer),this.verifyTimer=null),this.isLocked=true;}}class iw{adapter;settings;retryCounts=new Map;lastPromptValues=new WeakMap;monitorInitialized=false;constructor(e,t){this.adapter=e,this.settings=t,window.addEventListener("message",this.handleMessage.bind(this)),this.settings.enabled&&this.initNetworkMonitor();}updateSettings(e){const t=this.settings.enabled;this.settings=e,!t&&e.enabled&&this.initNetworkMonitor();}initNetworkMonitor(){if(this.monitorInitialized)return;const e=this.adapter.getNetworkMonitorConfig?.();e&&(window.postMessage({type:Du,payload:{urlPatterns:e.urlPatterns,urlPathEndsWith:e.urlPathEndsWith,silenceThreshold:e.silenceThreshold}},"*"),this.monitorInitialized=true);}handleMessage(e){if(this.adapter.getSiteId()!==Dr)return;const t=e.data;if(t&&t.type===qu){if(!this.settings.enabled)return;this.checkAndRetry();}}async checkAndRetry(){await new Promise(e=>setTimeout(e,500));const e=ei.query("ucs-conversation",{shadow:true});if(!e||!e.shadowRoot)return;const t=e.shadowRoot,n=t.querySelector(".turn.last")||t.querySelector(".turn:last-child");if(!n)return;const r=n.querySelector("ucs-summary");if(!r)return;if(!this.findBannedAnswer(r))return;const o=n.querySelector(".question-block");if(!o)return void console.warn("[PolicyRetry] User question block not found");const i=this.adapter.extractUserQueryText(o);if(!i)return void console.warn("[PolicyRetry] Empty user question");const a=await this.sha256(i),s=this.retryCounts.get(a)||0;if(ssetTimeout(e,100));if(!this.adapter.insertPrompt(e))return void console.error("[PolicyRetry] Failed to insert prompt");await new Promise(e=>setTimeout(e,300));const t=this.adapter.getSubmitButtonSelectors(),n=ei.query(t,{shadow:true});if(n)n.click();else {const e=this.adapter.findTextarea();e?(e.dispatchEvent(new KeyboardEvent("keydown",{key:"Enter",code:"Enter",keyCode:13,bubbles:true})),e.dispatchEvent(new KeyboardEvent("keypress",{key:"Enter",code:"Enter",keyCode:13,bubbles:true})),e.dispatchEvent(new KeyboardEvent("keyup",{key:"Enter",code:"Enter",keyCode:13,bubbles:true}))):console.error("[PolicyRetry] Submit button and editor not found");}}async sha256(e){const t=(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")}}class aw{static HYDRATION_TIMEOUT_MS=5e3;static SESSION_READY_TIMEOUT_MS=3e3;static SESSION_READY_POLL_MS=100;adapter;settings;isRecording=false;isRestoring=false;currentSessionId=null;listeningContainer=null;scrollHandler=null;userInteractionHandler=null;lastSaveTime=0;ignoreScrollUntil=0;positionKeeperRaF=0;keepPositionEndTime=0;restoredTop;constructor(e,t){this.adapter=e,this.settings=t;}async waitForHydration(e=aw.HYDRATION_TIMEOUT_MS){return !!bb.getState()._hasHydrated||new Promise(t=>{let n=false,r=0;const o=e=>{n||(n=true,window.clearTimeout(r),i(),t(e));},i=bb.subscribe(e=>{e._hasHydrated&&o(true);});r=window.setTimeout(()=>{bb.setState({_hasHydrated:true}),o(false);},e);})}updateSettings(e){this.settings=e,!this.settings.persistence&&this.isRecording?this.stopRecording():this.settings.persistence&&!this.isRecording&&this.startRecording();}startRecording(){if(this.isRecording)return;this.isRecording=true,this.currentSessionId=null,this.scrollHandler=e=>this.handleScroll(e);const e=this.adapter.getScrollContainer();e&&(e.addEventListener("scroll",this.scrollHandler,{passive:true}),this.listeningContainer=e),this.ignoreScrollUntil=Date.now()+2e3,this.userInteractionHandler=e=>{if("keydown"===e.type){const t=e.key;if(!["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "].includes(t))return}this.ignoreScrollUntil>0&&(this.ignoreScrollUntil=0),this.positionKeeperRaF&&this.stopPositionKeeper();},window.addEventListener("wheel",this.userInteractionHandler,{passive:true}),window.addEventListener("touchmove",this.userInteractionHandler,{passive:true}),window.addEventListener("keydown",this.userInteractionHandler,{passive:true}),window.addEventListener("scroll",this.scrollHandler,{capture:true,passive:true}),window.addEventListener("visibilitychange",this.scrollHandler),window.addEventListener("beforeunload",this.scrollHandler);}stopRecording(){this.isRecording&&(this.isRecording=false,this.currentSessionId=null,this.scrollHandler&&(this.listeningContainer&&(this.listeningContainer.removeEventListener("scroll",this.scrollHandler),this.listeningContainer=null),window.removeEventListener("scroll",this.scrollHandler,{capture:true}),window.removeEventListener("visibilitychange",this.scrollHandler),window.removeEventListener("beforeunload",this.scrollHandler),this.scrollHandler=null),this.userInteractionHandler&&(window.removeEventListener("wheel",this.userInteractionHandler),window.removeEventListener("touchmove",this.userInteractionHandler),window.removeEventListener("keydown",this.userInteractionHandler),this.userInteractionHandler=null),this.stopPositionKeeper());}restartRecording(){this.stopRecording(),this.startRecording();}handleScroll(e){if(!this.settings.persistence)return;if("scroll"===e.type){const t=this.adapter.getScrollContainer(),n=e.target;if(t&&n&&n!==document&&n!==window&&n!==t)return}const t=Date.now();("beforeunload"===e.type||"visibilitychange"===e.type||t-this.lastSaveTime>1e3)&&(this.saveProgress(),this.lastSaveTime=t);}getKey(e=this.getSessionId()){const t=e||"unknown";return `${this.adapter.getSiteId()}:${t}`}getSessionId(){return this.adapter.getSessionId()?.trim()||""}lockCurrentSessionId(e){e&&(this.currentSessionId||(this.currentSessionId=e));}async waitForReadySessionId(e=aw.SESSION_READY_TIMEOUT_MS){const t=Date.now()+e;for(;Date.now()<=t;){const e=this.getSessionId();if(e&&!this.adapter.isNewConversation())return e;await new Promise(e=>window.setTimeout(e,aw.SESSION_READY_POLL_MS));}const n=this.getSessionId();return n&&!this.adapter.isNewConversation()?n:""}saveProgress(){if(!this.isRecording)return;if(this.isRestoring)return;const e=this.getSessionId();if(this.currentSessionId&&e&&e!==this.currentSessionId)return;if(Date.now(){e?.(`${re("exportLoading")} ${t}`);}})).success)return !1;const t=r.top;await jm(this.adapter,t),this.restoredTop=t,o=!0;}catch{return !1}}return o}finally{setTimeout(()=>{this.isRestoring=false,void 0!==this.restoredTop&&this.startPositionKeeper(this.restoredTop,3e3);},1e3);}}cleanup(){const e=this.settings.cleanupDays||7;yb().cleanup(e);}startPositionKeeper(e,t){this.stopPositionKeeper(),this.keepPositionEndTime=Date.now()+t;const n=()=>{if(Date.now()>this.keepPositionEndTime)return void this.stopPositionKeeper();const t=this.adapter.getScrollContainer();t&&Math.abs(t.scrollTop-e)>5&&(t.scrollTop=e),this.positionKeeperRaF=requestAnimationFrame(n);};this.positionKeeperRaF=requestAnimationFrame(n);}stopPositionKeeper(){this.positionKeeperRaF&&(cancelAnimationFrame(this.positionKeeperRaF),this.positionKeeperRaF=0,this.keepPositionEndTime=0);}}class sw{adapter;settings;enabled=false;constructor(e,t){this.adapter=e,this.settings=t,this.init();}updateSettings(e){const t=this.settings.panel?.preventAutoScroll;this.settings=e,!t&&e.panel?.preventAutoScroll?this.enable():t&&!e.panel?.preventAutoScroll&&this.disable();}init(){this.settings.panel?.preventAutoScroll&&this.enable();}enable(){this.enabled||(this.enabled=true,this.toggleMainWorldHijack(true));}disable(){this.enabled&&(this.enabled=false,this.toggleMainWorldHijack(false));}stop(){this.disable();}toggleMainWorldHijack(e){window.postMessage({type:"OPHEL_SCROLL_LOCK_TOGGLE",enabled:e},"*");}}class lw{adapter;settings;isRunning=false;intervalId=null;titleObserver=null;expectedTitle=null;isApplyingManagedTitle=false;titleSyncTimer=null;aiState="idle";lastAiState="idle";currentNetworkGenerationPending=false;currentNetworkGenerationConfirmed=false;generationConfirmationIntervalId=null;userSawCompletion=false;lastSessionName=null;notificationAudio=null;notificationRepeatTimer=null;notificationPlaybackId=0;boundHandleMessage;boundVisibilityHandler;boundFocusHandler;boundBlurHandler;constructor(e,t){this.adapter=e,this.settings=t,this.boundHandleMessage=this.handleMessage.bind(this),this.boundVisibilityHandler=this.onVisibilityChange.bind(this),this.boundFocusHandler=this.onWindowFocus.bind(this),this.boundBlurHandler=this.onWindowBlur.bind(this),window.addEventListener("message",this.boundHandleMessage),document.addEventListener("visibilitychange",this.boundVisibilityHandler),window.addEventListener("focus",this.boundFocusHandler),window.addEventListener("blur",this.boundBlurHandler);}updateSettings(e){const t=this.settings.renameInterval,n=this.settings.showNotification,r=this.settings.notificationSound,o=this.settings.notificationSoundPreset,i=this.settings.notificationVolume,a=this.settings.notificationRepeatCount,s=this.settings.notificationRepeatInterval;this.settings=e,n===this.settings.showNotification&&r===this.settings.notificationSound&&o===this.settings.notificationSoundPreset&&i===this.settings.notificationVolume&&a===this.settings.notificationRepeatCount&&s===this.settings.notificationRepeatInterval||this.stopNotificationPlayback(),this.settings.autoRename&&!this.isRunning?this.start():!this.settings.autoRename&&this.isRunning&&this.stop(),this.isRunning&&t!==this.settings.renameInterval&&this.setInterval(this.settings.renameInterval||5),this.isRunning&&this.updateTabName(true);}start(){if(!this.settings.autoRename)return;if(this.isRunning)return;if(this.adapter.supportsTabRename&&!this.adapter.supportsTabRename())return;this.isRunning=true,this.startTitleObserver(),this.updateTabName();const e=1e3*(this.settings.renameInterval||5);this.intervalId=setInterval(()=>this.updateTabName(),e);const t=this.adapter.getNetworkMonitorConfig?this.adapter.getNetworkMonitorConfig():null;t&&window.postMessage({type:Du,payload:{urlPatterns:t.urlPatterns,urlPathEndsWith:t.urlPathEndsWith,silenceThreshold:t.silenceThreshold}},"*");}stop(){this.isRunning&&(this.isRunning=false,this.resetGenerationConfirmationState(),this.stopTitleObserver(),this.expectedTitle=null,this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null));}destroy(){this.stop(),this.stopNotificationPlayback(),this.resetGenerationConfirmationState(),this.stopTitleObserver(),window.removeEventListener("message",this.boundHandleMessage),document.removeEventListener("visibilitychange",this.boundVisibilityHandler),window.removeEventListener("focus",this.boundFocusHandler),window.removeEventListener("blur",this.boundBlurHandler);}setInterval(e){if(!this.isRunning)return;const t=1e3*e;this.intervalId&&clearInterval(this.intervalId),this.intervalId=setInterval(()=>this.updateTabName(),t);}togglePrivacyMode(){return this.settings.privacyMode=!this.settings.privacyMode,this.updateTabName(true),this.settings.privacyMode}resetSessionCache(){this.lastSessionName=null;}updateTabName(e=false){if(!this.isRunning&&!e)return;if(this.adapter.supportsTabRename&&!this.adapter.supportsTabRename())return;if(this.settings.privacyMode){const t=this.settings.privacyTitle||"Google";return void this.applyManagedTitle(t,e)}const t=this.getCleanSessionName(),n=this.isCurrentlyGenerating();"generating"===this.lastAiState&&!n&&this.isUserAway()&&"completed"!==this.aiState&&this.sendCompletionNotification(),this.lastAiState=n?"generating":"idle";const r=false!==this.settings.showStatus?n?"⏳ ":"✅ ":"",o=this.adapter.getName(),i=this.settings.titleFormat||"{status}{title}",a=i.includes("{model}")&&this.adapter.getModelName?.()||"";let s=i.replace("{status}",r).replace("{title}",t||o).replace("{model}",a?`[${a}] `:"").replace("{site}",o).replace(/\s+/g," ").trim();s&&this.applyManagedTitle(s,e);}applyManagedTitle(e,t=false){this.expectedTitle=e,(t||document.title!==e)&&(this.isApplyingManagedTitle=true,document.title=e,queueMicrotask(()=>{this.isApplyingManagedTitle=false;}));}startTitleObserver(){if(this.titleObserver||"undefined"==typeof MutationObserver)return;this.titleObserver=new MutationObserver(()=>{this.isRunning&&this.settings.autoRename&&(this.isApplyingManagedTitle||this.expectedTitle&&document.title!==this.expectedTitle&&(null!==this.titleSyncTimer&&window.clearTimeout(this.titleSyncTimer),this.titleSyncTimer=window.setTimeout(()=>{this.titleSyncTimer=null,this.isRunning&&this.settings.autoRename&&(this.isApplyingManagedTitle||this.expectedTitle&&document.title!==this.expectedTitle&&this.updateTabName(true));},0)));}),(()=>{document.head&&(this.titleObserver?.disconnect(),this.titleObserver?.observe(document.head,{childList:true,subtree:true,characterData:true}));})();}stopTitleObserver(){null!==this.titleSyncTimer&&(window.clearTimeout(this.titleSyncTimer),this.titleSyncTimer=null),this.titleObserver?.disconnect(),this.titleObserver=null,this.isApplyingManagedTitle=false;}getCleanSessionName(){if(this.adapter.isNewConversation?.())return this.lastSessionName=null,null;let e=this.adapter.getConversationTitle?.()||this.adapter.getSessionName?.();return e&&!(e=>!!e&&(!!/^[⏳✅]/.test(e)||(!!/\[[\w\s.]+\]/.test(e)||e===(this.settings.privacyTitle||"Google"))))(e)?(this.lastSessionName=e,e):this.lastSessionName}isCurrentlyGenerating(){return "completed"!==this.aiState&&("generating"===this.aiState||(this.adapter.isGenerating?.()??false))}requiresDomConfirmationForNetworkGeneration(){return this.adapter.requiresDomConfirmationForNetworkGeneration?.()??false}beginNetworkGeneration(){this.stopNotificationPlayback(),this.requiresDomConfirmationForNetworkGeneration()?(this.currentNetworkGenerationPending=true,this.currentNetworkGenerationConfirmed=false,this.startGenerationConfirmationPolling()):this.confirmCurrentNetworkGeneration();}confirmCurrentNetworkGeneration(){this.currentNetworkGenerationPending=false,this.currentNetworkGenerationConfirmed=true,this.clearGenerationConfirmationPolling(),"generating"!==this.aiState&&(this.lastAiState=this.aiState,this.aiState="generating"),this.updateTabName();}startGenerationConfirmationPolling(){this.clearGenerationConfirmationPolling();const e=()=>{this.currentNetworkGenerationPending&&this.adapter.isGenerating?.()&&this.confirmCurrentNetworkGeneration();};e(),this.currentNetworkGenerationConfirmed||(this.generationConfirmationIntervalId=window.setInterval(e,200));}clearGenerationConfirmationPolling(){null!==this.generationConfirmationIntervalId&&(window.clearInterval(this.generationConfirmationIntervalId),this.generationConfirmationIntervalId=null);}resetGenerationConfirmationState(){this.clearGenerationConfirmationPolling(),this.currentNetworkGenerationPending=false,this.currentNetworkGenerationConfirmed=false;}handleMessage(e){if(e.origin!==window.location.origin)return;const{type:t}=e.data||{};if(t===Ru)this.beginNetworkGeneration();else if(t===qu)this.onAiComplete();else if("GH_PRIVACY_TOGGLE"===t){const e=this.togglePrivacyMode();setTimeout(()=>{Oo(e?"隐私模式已开启":"隐私模式已关闭",2e3);},0);}}isUserAway(){const e=document.hidden,t=document.hasFocus(),n="visible"!==document.visibilityState;return e||!t||n}onVisibilityChange(){const e=this.isUserAway();e||this.stopNotificationPlayback({stopCurrentAudio:false}),"generating"!==this.aiState||e||this.adapter.isGenerating&&!this.adapter.isGenerating()&&(this.userSawCompletion=true);}onWindowFocus(){this.stopNotificationPlayback({stopCurrentAudio:false}),"generating"===this.aiState&&this.adapter.isGenerating&&!this.adapter.isGenerating()&&(this.userSawCompletion=true);}onWindowBlur(){}onAiComplete(){const e=this.requiresDomConfirmationForNetworkGeneration(),t=this.currentNetworkGenerationConfirmed;if(e&&!t)return this.resetGenerationConfirmationState(),this.lastAiState=this.aiState,this.aiState="idle",this.userSawCompletion=false,void this.updateTabName(true);const n="generating"===this.aiState;this.lastAiState=this.aiState,this.aiState="completed";const r=this.settings.notifyWhenFocused,o=this.isUserAway();n&&!this.userSawCompletion&&(o||r)&&this.sendCompletionNotification(),this.userSawCompletion=false,this.resetGenerationConfirmationState(),this.updateTabName(true);}sendCompletionNotification(){if(this.stopNotificationPlayback(),this.settings.showNotification)try{const e=this.adapter.getName(),t=re("notificationTitle").replace("{site}",e),n=this.lastSessionName||this.adapter.getConversationTitle?.()||re("notificationBody");xu.notify({title:t,message:n});}catch(e){console.error("[TabManager] 通知发送失败:",e);}this.settings.notificationSound&&this.playNotificationSound(),this.settings.autoFocus&&xu.focusWindow();}playNotificationSound(){const e=this.settings.notificationSoundPreset||wr[0].id,t=wr.find(t=>t.id===e)||wr[0],n=xu.getNotificationSoundUrl(t.id);if(!n)return void console.warn("[TabManager] Notification sound URL not found for preset:",t.id);const r=this.normalizeNotificationRepeatCount(this.settings.notificationRepeatCount),o=1e3*this.normalizeNotificationRepeatInterval(this.settings.notificationRepeatInterval);this.startNotificationPlayback(n,r,o);}startNotificationPlayback(e,t,n){this.stopNotificationPlayback();const r=++this.notificationPlaybackId,o=t=>{if(r===this.notificationPlaybackId)try{this.notificationAudio||(this.notificationAudio=new Audio);const i=this.settings.notificationVolume??.5;this.notificationAudio.volume=Math.max(.1,Math.min(1,i)),this.notificationAudio.src=e,this.notificationAudio.currentTime=0,this.notificationAudio.onended=()=>{if(r===this.notificationPlaybackId)return t<=1?(this.clearNotificationPlaybackHandlers(),void(this.notificationRepeatTimer=null)):void(this.isUserAway()?this.notificationRepeatTimer=window.setTimeout(()=>{this.notificationRepeatTimer=null,o(t-1);},n):this.stopNotificationPlayback())},this.notificationAudio.onerror=()=>{r===this.notificationPlaybackId&&(console.error("[TabManager] Notification audio element error:",{url:e,mediaError:this.notificationAudio?.error}),this.stopNotificationPlayback());},this.notificationAudio.play().catch(t=>{r===this.notificationPlaybackId&&(console.error("[TabManager] Notification audio play rejected:",{url:e,error:t}),this.stopNotificationPlayback());});}catch(i){console.error("[TabManager] 音频初始化失败:",i);}};o(t);}stopNotificationPlayback(e){const t=e?.stopCurrentAudio??true;this.notificationPlaybackId+=1,null!==this.notificationRepeatTimer&&(window.clearTimeout(this.notificationRepeatTimer),this.notificationRepeatTimer=null);try{t&&this.notificationAudio&&(this.clearNotificationPlaybackHandlers(),this.notificationAudio.pause(),this.notificationAudio.currentTime=0);}catch(n){console.error("[TabManager] 音频停止失败:",n);}}clearNotificationPlaybackHandlers(){this.notificationAudio&&(this.notificationAudio.onended=null,this.notificationAudio.onerror=null);}normalizeNotificationRepeatCount(e){return Number.isFinite(e)?Math.max(1,Math.min(10,Math.round(e))):1}normalizeNotificationRepeatInterval(e){return Number.isFinite(e)?Math.max(1,Math.min(60,e)):3}isActive(){return this.isRunning}}const cw="gh-usage-monitor-style",dw="gh-usage-monitor-host",uw={count:0,updatedAt:Date.now(),resetAt:Date.now()},hw=e=>e.replace(/[\u200B\u200C\u200D\uFEFF\u00A0]/g,"").replace(/\s+/g," ").trim(),gw=/[\u3400-\u9FFF\u3040-\u30FF\uAC00-\uD7AF]/g,pw=/[A-Za-z0-9]/g,mw=/[^\sA-Za-z0-9\u3400-\u9FFF\u3040-\u30FF\uAC00-\uD7AF]/g;class fw{adapter;siteId;settings;root=null;slot=null;activeAnchor=null;mounted=false;mountTimer=null;renderTimer=null;renderInFlight=false;rerenderRequested=false;midnightTimer=null;pendingTimer=null;pendingSend=null;unwatchStorage=null;activeRecordKey="";currentRecord={...uw};injectedStyleRoots=new Set;handleViewportChange=()=>{this.settings.enabled&&this.scheduleRender(0);};handleDocumentClick=e=>{if(!this.settings.enabled)return;const t=this.resolveEditor();t&&this.isSubmitButtonClick(e,t)&&this.schedulePendingSend(t);};handleDocumentKeydown=e=>{if(!this.settings.enabled)return;if(!this.isSubmitShortcut(e))return;const t=this.resolveEditorFromTarget(e.target);t&&this.schedulePendingSend(t);};handleDocumentInput=e=>{if(!this.settings.enabled)return;this.resolveEditorFromTarget(e.target)&&(this.ensureMounted(),this.scheduleRender(60));};handleDocumentFocus=()=>{this.settings.enabled&&(this.ensureMounted(),this.scheduleRender(0));};constructor(e,t,n){this.adapter=e,this.settings=this.normalizeSettings(t),this.siteId=n;}start(){if(this.settings.enabled){if(this.mounted)return this.ensureMounted(),void this.scheduleRender(0);this.mounted=true,this.ensureStyles(),document.addEventListener("click",this.handleDocumentClick,true),document.addEventListener("keydown",this.handleDocumentKeydown,true),document.addEventListener("input",this.handleDocumentInput,true),document.addEventListener("focusin",this.handleDocumentFocus,true),window.addEventListener("resize",this.handleViewportChange,true),window.addEventListener("scroll",this.handleViewportChange,true),this.unwatchStorage=Gb(e=>{const t=e.records[this.getRecordKey()];this.currentRecord=t?{count:Math.max(0,Math.floor(t.count||0)),updatedAt:t.updatedAt||Date.now(),resetAt:t.resetAt||Date.now()}:{count:0,updatedAt:Date.now(),resetAt:Date.now()},this.scheduleRender(0);}),this.startMountLoop(),this.scheduleMidnightReset(),this.syncCounterRecord(true),this.ensureMounted(),this.scheduleRender(0);}}stop(){if(!this.mounted)return this.removeRoot(),void this.removeStyles();this.mounted=false,document.removeEventListener("click",this.handleDocumentClick,true),document.removeEventListener("keydown",this.handleDocumentKeydown,true),document.removeEventListener("input",this.handleDocumentInput,true),document.removeEventListener("focusin",this.handleDocumentFocus,true),window.removeEventListener("resize",this.handleViewportChange,true),window.removeEventListener("scroll",this.handleViewportChange,true),null!==this.mountTimer&&(window.clearInterval(this.mountTimer),this.mountTimer=null),null!==this.renderTimer&&(window.clearTimeout(this.renderTimer),this.renderTimer=null),null!==this.midnightTimer&&(window.clearTimeout(this.midnightTimer),this.midnightTimer=null),null!==this.pendingTimer&&(window.clearInterval(this.pendingTimer),this.pendingTimer=null),this.pendingSend=null,this.unwatchStorage?.(),this.unwatchStorage=null,this.removeRoot(),this.removeStyles();}destroy(){this.stop();}updateSettings(e){this.settings=this.normalizeSettings(e),this.settings.enabled?this.mounted?(this.activeRecordKey="",this.scheduleMidnightReset(),this.ensureMounted(),this.syncCounterRecord(true),this.scheduleRender(0)):this.start():this.stop();}handleUrlChange(){this.settings.enabled&&(this.pendingSend=null,null!==this.pendingTimer&&(window.clearInterval(this.pendingTimer),this.pendingTimer=null),this.activeRecordKey="",this.adapter.findTextarea(),this.ensureMounted(true),this.syncCounterRecord(true),[80,220,500,1e3].forEach(e=>window.setTimeout(()=>{this.settings.enabled&&(this.ensureMounted(),this.scheduleRender(0));},e)));}normalizeSettings(e){return {enabled:e?.enabled??false,dailyLimit:Math.max(1,Math.floor(e?.dailyLimit??100)),autoResetEnabled:e?.autoResetEnabled??false}}startMountLoop(){null===this.mountTimer&&(this.mountTimer=window.setInterval(()=>{(this.ensureMounted()||this.root)&&this.scheduleRender(0);},1e3));}ensureMounted(e=false){if(!this.settings.enabled)return false;const t=this.resolveEditor();if(!t)return (e||this.activeAnchor&&!this.activeAnchor.isConnected)&&this.removeRoot(),false;const n=this.resolveMountAnchor(t);if(!n?.parentElement)return false;this.ensureStylesForTarget(n),this.root||(this.root=document.createElement("div"),this.root.className=dw),this.slot||(this.slot=document.createElement("div"),this.slot.className=`${dw}-slot`);const r=e||this.activeAnchor!==n||!this.root.isConnected||!this.slot.isConnected||this.slot.parentElement!==n.parentElement||this.slot.nextSibling!==n;return r&&((n.parentElement&&this.slot.parentElement!==n.parentElement||n.parentElement&&this.slot.nextSibling!==n)&&n.parentElement.insertBefore(this.slot,n),this.root.parentElement!==this.slot&&this.slot.appendChild(this.root),this.activeAnchor=n),this.root.dataset.theme=this.detectThemeMode(),this.applySlotLayout(n),r}removeRoot(){this.activeAnchor=null,this.root?.remove(),this.root=null,this.slot?.remove(),this.slot=null;}bindPanelControls(){if(!this.root)return;const e=this.root.querySelector('[data-action="reset-counter"]');e&&(e.onclick=async e=>{e.preventDefault(),e.stopPropagation(),await this.syncCounterRecord(),this.currentRecord=await async function(e){const t={count:0,updatedAt:Date.now(),resetAt:Date.now()},n=await Ob();return n.records[e]=t,await zb(n),t}(this.getRecordKey()),this.scheduleRender(0);});}ensureStyles(){if(document.getElementById(cw))return;const e=document.createElement("style");e.id=cw,e.textContent=this.getUsageMonitorStyles(),document.head.appendChild(e);}ensureStylesForTarget(e){const t=e.getRootNode();t instanceof ShadowRoot&&(ei.cssToShadow(t,this.getUsageMonitorStyles(),cw),this.injectedStyleRoots.add(t));}getUsageMonitorStyles(){return `\n .${dw} {\n box-sizing: border-box;\n width: 100%;\n max-width: 100%;\n margin: 0;\n pointer-events: auto;\n }\n\n .${dw}-slot {\n width: 100%;\n display: flex;\n align-items: flex-start;\n overflow: visible;\n pointer-events: none;\n margin: 0 0 8px 0;\n }\n\n .${dw} * {\n box-sizing: border-box;\n }\n\n .${dw} .gh-usage-monitor-panel {\n pointer-events: auto;\n border: 1px solid var(--gh-card-border, var(--gh-border, #e5e7eb));\n border-radius: 14px;\n padding: 10px 12px;\n background: var(--gh-card-bg, var(--gh-bg, #ffffff));\n box-shadow: var(--gh-shadow-sm, 0 1px 3px rgba(0, 0, 0, 0.1));\n color: var(--gh-text, #1f2937);\n font-size: 12px;\n line-height: 1.45;\n }\n\n .${dw}[data-theme="dark"] .gh-usage-monitor-panel {\n border-color: var(--gh-card-border, var(--gh-border, #333333));\n background: var(--gh-card-bg, var(--gh-bg, #1e1e1e));\n box-shadow: var(--gh-shadow-sm, 0 1px 3px rgba(0, 0, 0, 0.3));\n color: var(--gh-text, #e3e3e3);\n }\n\n .${dw} .gh-usage-monitor-top {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 10px;\n margin-bottom: 8px;\n }\n\n .${dw} .gh-usage-monitor-title {\n font-weight: 600;\n letter-spacing: 0.01em;\n }\n\n .${dw} .gh-usage-monitor-meta {\n display: flex;\n align-items: center;\n justify-content: flex-end;\n gap: 8px;\n flex-wrap: wrap;\n }\n\n .${dw} .gh-usage-monitor-count {\n font-variant-numeric: tabular-nums;\n font-weight: 600;\n white-space: nowrap;\n }\n\n .${dw} .gh-usage-monitor-badge {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n padding: 2px 8px;\n border-radius: 999px;\n background: var(--gh-user-query-bg, var(--gh-bg-secondary, #f9fafb));\n color: var(--gh-text-secondary, #6b7280);\n font-size: 11px;\n line-height: 1.2;\n white-space: nowrap;\n }\n\n .${dw}[data-theme="dark"] .gh-usage-monitor-badge {\n background: var(--gh-user-query-bg, var(--gh-bg-secondary, #0b0b0b));\n color: var(--gh-text-secondary, #a0a0a0);\n }\n\n .${dw} .gh-usage-monitor-reset {\n appearance: none;\n border: 1px solid var(--gh-input-border, var(--gh-border, #e5e7eb));\n border-radius: 999px;\n background: transparent;\n color: inherit;\n font-size: 11px;\n line-height: 1.2;\n padding: 4px 9px;\n cursor: pointer;\n transition: background-color 160ms ease, border-color 160ms ease, opacity 160ms ease;\n }\n\n .${dw} .gh-usage-monitor-reset:hover {\n background: var(--gh-hover, #f3f4f6);\n border-color: var(--gh-border-active, #6366f1);\n }\n\n .${dw} .gh-usage-monitor-control {\n appearance: none;\n border: 1px solid var(--gh-input-border, var(--gh-border, #e5e7eb));\n border-radius: 999px;\n background: transparent;\n color: inherit;\n font-size: 11px;\n line-height: 1.2;\n padding: 4px 9px;\n cursor: pointer;\n transition: background-color 160ms ease, border-color 160ms ease;\n }\n\n .${dw} .gh-usage-monitor-control:hover {\n background: var(--gh-hover, #f3f4f6);\n border-color: var(--gh-border-active, #6366f1);\n }\n\n .${dw}[data-theme="dark"] .gh-usage-monitor-reset {\n border-color: var(--gh-input-border, var(--gh-border, #333333));\n }\n\n .${dw}[data-theme="dark"] .gh-usage-monitor-reset:hover {\n background: var(--gh-hover, #262626);\n }\n\n .${dw} .gh-usage-monitor-progress {\n position: relative;\n height: 6px;\n border-radius: 999px;\n overflow: hidden;\n background: var(--gh-border, #e5e7eb);\n margin-bottom: 8px;\n }\n\n .${dw} .gh-usage-monitor-progress-bar {\n height: 100%;\n width: 0;\n border-radius: inherit;\n background: var(--gh-primary, #4285f4);\n transition: width 160ms ease, background-color 160ms ease;\n }\n\n .${dw}[data-theme="dark"] .gh-usage-monitor-progress {\n background: var(--gh-border, #333333);\n }\n\n .${dw}[data-level="warning"] .gh-usage-monitor-progress-bar {\n background: var(--gh-secondary, #34a853);\n }\n\n .${dw}[data-level="warning"] .gh-usage-monitor-count {\n color: var(--gh-secondary, #34a853);\n }\n\n .${dw}[data-level="danger"] .gh-usage-monitor-progress-bar {\n background: var(--gh-danger, #ef4444);\n }\n\n .${dw}[data-level="danger"] .gh-usage-monitor-count {\n color: var(--gh-danger, #ef4444);\n }\n\n .${dw}[data-level="normal"] .gh-usage-monitor-count {\n color: var(--gh-primary, #4285f4);\n }\n\n .${dw}[data-theme="dark"][data-level="normal"] .gh-usage-monitor-count {\n color: var(--gh-primary, #4285f4);\n }\n\n .${dw}[data-theme="dark"][data-level="warning"] .gh-usage-monitor-count {\n color: var(--gh-secondary, #34a853);\n }\n\n .${dw}[data-theme="dark"][data-level="danger"] .gh-usage-monitor-count {\n color: var(--gh-danger, #ef4444);\n }\n\n .${dw} .gh-usage-monitor-grid {\n display: grid;\n grid-template-columns: repeat(2, minmax(0, 1fr));\n gap: 6px 12px;\n }\n\n .${dw} .gh-usage-monitor-item {\n display: flex;\n align-items: baseline;\n justify-content: space-between;\n gap: 10px;\n }\n\n .${dw} .gh-usage-monitor-label {\n color: var(--gh-text-secondary, #6b7280);\n }\n\n .${dw}[data-theme="dark"] .gh-usage-monitor-label {\n color: var(--gh-text-secondary, #a0a0a0);\n }\n\n .${dw} .gh-usage-monitor-value {\n font-variant-numeric: tabular-nums;\n font-weight: 600;\n white-space: nowrap;\n }\n\n .${dw} .gh-usage-monitor-footnote {\n margin-top: 8px;\n color: var(--gh-text-secondary, #6b7280);\n font-size: 11px;\n line-height: 1.45;\n }\n\n .${dw}[data-theme="dark"] .gh-usage-monitor-footnote {\n color: var(--gh-text-secondary, #a0a0a0);\n }\n\n @media (max-width: 640px) {\n .${dw} .gh-usage-monitor-grid {\n grid-template-columns: 1fr;\n }\n }\n `}removeStyles(){document.getElementById(cw)?.remove();for(const e of this.injectedStyleRoots)e.getElementById(cw)?.remove();this.injectedStyleRoots.clear();}applySlotLayout(e){if(!this.root||!this.slot||!e?.isConnected)return;const t=e.getBoundingClientRect(),n=this.slot.parentElement?.getBoundingClientRect(),r=Math.max(280,Math.min(t.width,window.innerWidth-16)),o=n?Math.max(0,t.left-n.left):0;this.slot.style.justifyContent="flex-start",this.slot.style.minHeight="0",this.slot.style.marginBottom="8px",this.root.style.width=`${r}px`,this.root.style.maxWidth="100%",this.root.style.marginLeft=`${o}px`,this.root.style.alignSelf="flex-start";const i=this.root.offsetHeight;this.slot.style.height=`${i+8}px`;}scheduleMidnightReset(){if(null!==this.midnightTimer&&(window.clearTimeout(this.midnightTimer),this.midnightTimer=null),!this.settings.autoResetEnabled)return;const e=new Date,t=new Date(e);t.setHours(24,0,0,50);const n=Math.max(1e3,t.getTime()-e.getTime());this.midnightTimer=window.setTimeout(()=>{this.syncCounterRecord(true),this.scheduleRender(0),this.scheduleMidnightReset();},n);}scheduleRender(e=0){this.settings.enabled&&(null!==this.renderTimer&&window.clearTimeout(this.renderTimer),this.renderTimer=window.setTimeout(()=>{this.renderTimer=null,this.render();},e));}async render(){if(this.settings.enabled&&(this.root||(this.ensureMounted(),this.root)))if(this.renderInFlight)this.rerenderRequested=true;else {this.renderInFlight=true;try{await this.syncCounterRecord();const e=this.getEstimateSnapshot(),t=this.currentRecord.count,n=Math.max(1,this.settings.dailyLimit),r=t/n,o=Math.min(100,Math.max(0,100*r)),i=r>=1?"danger":r>=.8?"warning":"normal";this.root.dataset.level=i,this.root.dataset.theme=this.detectThemeMode();const a=re("usageMonitorSettingsTitle")||"高级模型本地计数与预估",s=this.settings.autoResetEnabled?re("usageMonitorTodayUsed")||"今日已用":re("usageMonitorLocallyUsed")||"本地已记",l=re("usageMonitorInputChars")||"输入字符",c=re("usageMonitorLoadedConversationTokens")||"已加载对话",d=re("usageMonitorLoadedOutputTokens")||"已加载输出",u=re("usageMonitorRequestTokens")||"当前请求",h=re("usageMonitorRoundTripTokens")||"单轮往返",g=re("usageMonitorRoundTripDesc")||"单轮往返 = 当前请求 + 一次预计回复的总消耗粗估区间",p=re("usageMonitorResetButton")||"清零",m=this.settings.autoResetEnabled?null:re("usageMonitorManualMode")||"手动模式",f=re("usageMonitorContextChars")||"上下文字符";this.root.replaceChildren(this.buildUsageMonitorPanel({title:a,usageLabel:s,resetButtonLabel:p,roundTripDesc:g,inputCharsLabel:l,loadedConversationLabel:c,loadedOutputLabel:d,requestTokensLabel:u,roundTripLabel:h,contextCharsLabel:f,manualModeLabel:m,count:t,limit:n,percent:o,estimate:e})),this.bindPanelControls(),this.activeAnchor&&this.applySlotLayout(this.activeAnchor);}finally{this.renderInFlight=false,this.rerenderRequested&&(this.rerenderRequested=false,this.scheduleRender(0));}}}async syncCounterRecord(e=false){const t=this.getRecordKey();(e||this.activeRecordKey!==t)&&(this.activeRecordKey=t,this.currentRecord=await async function(e){const t=await Ob(),n=Rb(t.records[e]);return t.records[e]||(t.records[e]=n,await zb(t)),n}(t));}getRecordKey(){const e=this.adapter.getCurrentCid?.()||"default";return this.settings.autoResetEnabled?`${this.siteId}::${e}::day::${((e=new Date)=>`${e.getFullYear()}-${`${e.getMonth()+1}`.padStart(2,"0")}-${`${e.getDate()}`.padStart(2,"0")}`)()}`:`${this.siteId}::${e}::manual`}resolveEditor(){const e=this.collectEditorCandidates();return e.length>0?e.sort((e,t)=>this.scoreEditorCandidate(t)-this.scoreEditorCandidate(e))[0]:this.adapter.findTextarea()||this.adapter.getTextareaElement()}collectEditorCandidates(){const e=new Set,t=[];for(const n of this.adapter.getTextareaSelectors()){let r=[];try{r=ei.query(n,{all:!0,shadow:!0})||[];}catch{continue}for(const n of r)n instanceof HTMLElement&&(e.has(n)||(e.add(n),this.adapter.isValidTextarea(n)&&t.push(n)));}return t}scoreEditorCandidate(e){if(!e.isConnected)return Number.NEGATIVE_INFINITY;const t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return Number.NEGATIVE_INFINITY;let n=0;(e===document.activeElement||e.contains(document.activeElement))&&(n+=1e3);const r=this.adapter.findSubmitButton(e)||this.findSubmitButtonBySelectors(e);r&&r.isConnected&&(n+=400),n+=t.top/Math.max(window.innerHeight,1)*120;const o=(e.getAttribute("aria-label")||"").toLowerCase(),i=(e.getAttribute("placeholder")||e.placeholder||"").toLowerCase();return /prompt|message|chat|发送|输入|ask|query/.test(`${o} ${i}`)&&(n+=120),n}resolveEditorFromTarget(e){if(!(e instanceof Element))return this.resolveEditor();for(const n of this.adapter.getTextareaSelectors())try{if(e.matches(n))return e;const t=ei.closestComposed(e,n);if(t instanceof HTMLElement)return t}catch{continue}const t=this.resolveEditor();return t&&this.containsInComposedTree(t,e)?t:null}resolveMountAnchor(e){const t=this.adapter.findSubmitButton(e)||this.findSubmitButtonBySelectors(e),n=[ei.closestComposed(e,"form"),t?ei.closestComposed(t,"form"):null,this.findClosestCommonAncestor(e,t),ei.closestComposed(e,'[role="form"]')].filter(Boolean),r=this.pickBestMountCandidate(n,e,t);if(r)return r;const o=[ei.closestComposed(e,".chat-input-editor-container"),ei.closestComposed(e,".chat-editor"),ei.closestComposed(e,".input-area-container"),ei.closestComposed(e,".input-area"),ei.closestComposed(e,".composer"),ei.closestComposed(e,".footer-input-wrap"),ei.closestComposed(e,".input-container"),ei.closestComposed(e,".editor-container"),ei.getComposedParentElement(e),e.parentElement].filter(Boolean);return this.pickBestMountCandidate(o,e,t)}pickBestMountCandidate(e,t,n){const r=Array.from(new Set(e)).filter(e=>{if(!e?.parentElement)return false;if(e===document.body||e===document.documentElement)return false;if(e.isContentEditable)return false;const t=e.getBoundingClientRect();return t.width>0&&t.height>0}).map(e=>({candidate:e,score:this.scoreMountCandidate(e,t,n)})).sort((e,t)=>t.score-e.score);return r[0]?.candidate||null}scoreMountCandidate(e,t,n){const r=e.getBoundingClientRect(),o=t.getBoundingClientRect(),i=Math.max(1,r.width*r.height);let a=0;const s=this.containsInComposedTree(e,t),l=!!n&&this.containsInComposedTree(e,n);"form"===e.tagName.toLowerCase()&&(a+=520),"form"===e.getAttribute("role")&&(a+=320),s&&(a+=160),l&&(a+=180),s&&l&&(a+=260),e===t.parentElement&&(a-=260);a-=.2*(Math.abs(r.top-o.top)+Math.abs(r.left-o.left)+Math.abs(r.bottom-o.bottom)),a-=i/5e3,r.height<1.4*o.height&&(a-=140);const c=e.parentElement;if(c){const e=window.getComputedStyle(c);if(e.display.includes("flex")&&!e.flexDirection.startsWith("column")&&this.containsInComposedTree(c,t)&&(!n||this.containsInComposedTree(c,n))){const e=c.getBoundingClientRect(),t=Math.max(1,e.width*e.height);t<2.2*i&&t{this.confirmPendingSend();},120)));}async confirmPendingSend(){if(!this.pendingSend)return void(null!==this.pendingTimer&&(window.clearInterval(this.pendingTimer),this.pendingTimer=null));const e=this.pendingSend,t=this.resolveEditor(),n=this.getEditorText(t),r=this.getUserMessageCount(),o=this.adapter.isGenerating?.()??false,i=Date.now()-e.startedAt,a=r>e.preUserCount,s=o&&!e.preGenerating,l=e.normalizedText.length>0&&0===n.length,c=e.normalizedText.length>0&&n.length>0&&n!==e.normalizedText;if(a||s||l&&o||c&&o){this.pendingSend=null,null!==this.pendingTimer&&(window.clearInterval(this.pendingTimer),this.pendingTimer=null);const e=this.getEstimateSnapshot();return await async function(e){const t=qb(e);if(!t)return;const n=await Ob();n.events=Pb([...n.events,t]),await zb(n);}({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),siteId:this.siteId,cid:this.adapter.getCurrentCid?.()||"default",sessionId:this.adapter.getSessionId?.()||"",countDelta:1,requestTokens:e.requestTokens,roundTripTokens:e.roundTripMid,loadedConversationTokens:e.loadedConversationTokens,loadedOutputTokens:e.loadedOutputTokens}),await this.syncCounterRecord(),this.currentRecord=await async function(e){const t=await Ob(),n=Rb(t.records[e]),r={count:n.count+1,updatedAt:Date.now(),resetAt:n.resetAt};return t.records[e]=r,await zb(t),r}(this.getRecordKey()),void this.scheduleRender(0)}i>4e3&&(this.pendingSend=null,null!==this.pendingTimer&&(window.clearInterval(this.pendingTimer),this.pendingTimer=null));}getUserMessageCount(){const e=this.adapter.getUserQuerySelector();if(!e)return 0;try{return (ei.query(e,{all:!0,shadow:!0})||[]).filter(e=>e instanceof HTMLElement&&e.isConnected).length}catch{return 0}}getEditorText(e){return e?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?hw(e.value||""):hw(e.textContent||""):""}getEstimateSnapshot(){const e=this.resolveEditor(),t=this.getEditorText(e),n=this.getLoadedConversationStats(),r=t.length,o=this.estimateTokens(t),i=this.estimateTokens([n.conversationText,t].filter(Boolean).join("\n")),a=i>0?i+Math.max(32,Math.ceil(.5*i)):0,s=i>0?i+Math.max(128,Math.ceil(2*i)):0,l=a>0||s>0?Math.round((a+s)/2):0;return {inputChars:r,loadedConversationChars:n.conversationChars,loadedConversationTokens:n.conversationTokens,loadedOutputChars:n.outputChars,loadedOutputTokens:n.outputTokens,requestTokens:Math.max(i,o),roundTripMin:a,roundTripMax:s,roundTripMid:l}}getLoadedConversationStats(){const e=this.adapter.getChatContentSelectors();if(!e.length)return {conversationText:"",conversationChars:0,conversationTokens:0,outputChars:0,outputTokens:0};let t=[];try{t=ei.query(e,{all:!0,shadow:!0})||[];}catch{t=[];}if(0===t.length)return {conversationText:"",conversationChars:0,conversationTokens:0,outputChars:0,outputTokens:0};const n=this.adapter.getUserQuerySelector(),r=Array.from(new Set(t)),o=[],i=[];r.forEach(e=>{const t=!!n&&this.matchesSelector(e,n),r=t?this.adapter.extractUserQueryMarkdown(e):this.adapter.extractAssistantResponseText(e),a=hw(r||e.textContent||"");a&&(o.push(a),t||i.push(a));});const a=o.join("\n"),s=i.join("\n");return {conversationText:a,conversationChars:a.length,conversationTokens:this.estimateTokens(a),outputChars:s.length,outputTokens:this.estimateTokens(s)}}matchesSelector(e,t){try{return e.matches(t)}catch{return false}}estimateTokens(e){if(!e)return 0;const t=(e.match(gw)||[]).length,n=(e.match(pw)||[]).length,r=(e.match(mw)||[]).length;return Math.max(0,Math.ceil(1.2*t+n/4+r/2))}detectThemeMode(){const e=document.documentElement.className;if(/\bdark\b/i.test(e))return "dark";if(/\blight\b/i.test(e))return "light";const t=document.body.className;if(/\bdark-theme\b/i.test(t))return "dark";if(/\blight-theme\b/i.test(t))return "light";const n=document.body.dataset.theme||document.documentElement.dataset.theme;return "dark"===n?"dark":"light"===n?"light":window.matchMedia?.("(prefers-color-scheme: dark)")?.matches?"dark":"light"}buildUsageMonitorPanel({title:e,usageLabel:t,resetButtonLabel:n,roundTripDesc:r,inputCharsLabel:o,loadedConversationLabel:i,loadedOutputLabel:a,requestTokensLabel:s,roundTripLabel:l,contextCharsLabel:c,manualModeLabel:d,count:u,limit:h,percent:g,estimate:p}){const m=document.createElement("div");m.className="gh-usage-monitor-panel";const f=document.createElement("div");f.className="gh-usage-monitor-top";const b=document.createElement("div");b.className="gh-usage-monitor-title",b.textContent=e;const y=document.createElement("div");if(y.className="gh-usage-monitor-meta",d){const e=document.createElement("span");e.className="gh-usage-monitor-badge",e.textContent=d,y.appendChild(e);}const v=document.createElement("div");v.className="gh-usage-monitor-count",v.textContent=`${t}: ${u} / ${h}`;const w=document.createElement("button");w.type="button",w.className="gh-usage-monitor-reset",w.dataset.action="reset-counter",w.textContent=n,y.append(v,w),f.append(b,y);const x=document.createElement("div");x.className="gh-usage-monitor-progress";const k=document.createElement("div");k.className="gh-usage-monitor-progress-bar",k.style.width=`${g.toFixed(1)}%`,x.appendChild(k);const S=document.createElement("div");S.className="gh-usage-monitor-grid",S.append(this.createUsageMonitorItem(o,`${p.inputChars} chars`),this.createUsageMonitorItem(i,`${p.loadedConversationTokens} tokens`),this.createUsageMonitorItem(a,`${p.loadedOutputTokens} tokens`),this.createUsageMonitorItem(s,`${p.requestTokens} tokens`),this.createUsageMonitorItem(l,`${p.roundTripMin}-${p.roundTripMax}`),this.createUsageMonitorItem(c,`${p.loadedConversationChars} chars`));const C=document.createElement("div");return C.className="gh-usage-monitor-footnote",C.textContent=r,m.append(f,x,S,C),m}createUsageMonitorItem(e,t){const n=document.createElement("div");n.className="gh-usage-monitor-item";const r=document.createElement("span");r.className="gh-usage-monitor-label",r.textContent=e;const o=document.createElement("span");return o.className="gh-usage-monitor-value",o.textContent=t,n.append(r,o),n}}const bw=[/^\s*#{1,6}\s+\S/m,/^\s*```/m,/^\s*(?:>|>)\s+\S/m,/^\s*[-*]\s+\S/m,/^\s*\d+\.\s+\S/m],yw=[/\*\*[^*]+\*\*/,/`[^`]+`/,/\[.+\]\(.+\)/],vw=[/(^|[^\\])\$\$[\s\S]+?\$\$/m,/\\\[[\s\S]+?\\\]/m],ww=[/(^|[^\\$])\$[^\s$](?:[^$\n]*[^\s$])?\$(?!\$)/,/\\\([^\n]+?\\\)/],xw="gh-user-query-markdown-style",kw="\n/* ============= 用户提问 Markdown 渲染样式 ============= */\n.gh-user-query-markdown {\n font-size: 15px;\n line-height: 1.6;\n}\n/* 图片宽度不大于消息气泡 */\n.gh-user-query-markdown img {\n max-width: 100%;\n}\n\n/* 代码块样式 - 紧凑、自动换行 */\n.gh-user-query-markdown pre {\n margin: 0.5em 0;\n padding: 0.75em;\n padding-right: 0.5em;\n background: rgba(0, 0, 0, 0.05);\n border-radius: 6px;\n font-size: 0.95em;\n max-height: 200px;\n overflow: auto;\n position: relative;\n}\n\n/* 美化滚动条 */\n.gh-user-query-markdown pre::-webkit-scrollbar {\n width: 6px;\n height: 6px;\n}\n.gh-user-query-markdown pre::-webkit-scrollbar-track {\n background: transparent;\n}\n.gh-user-query-markdown pre::-webkit-scrollbar-thumb {\n background: rgba(0, 0, 0, 0.15);\n border-radius: 3px;\n}\n.gh-user-query-markdown pre::-webkit-scrollbar-thumb:hover {\n background: rgba(0, 0, 0, 0.25);\n}\n\n.gh-user-query-markdown pre code {\n background: transparent;\n padding: 0;\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n overflow: visible; /* 覆盖 .hljs 的 overflow-x: auto,让 pre 控制滚动 */\n}\n\n/* 行内代码 */\n.gh-user-query-markdown code {\n background: rgba(0, 0, 0, 0.05);\n padding: 0.2em 0.4em;\n border-radius: 4px;\n font-size: 0.9em;\n}\n\n/* 代码块复制按钮 - sticky 定位,滚动时保持可见 */\n.gh-user-query-markdown .gh-code-copy-btn {\n position: sticky;\n top: 6px;\n float: right;\n margin-top: -1.5em;\n margin-right: -1.0em;\n width: 24px;\n height: 24px;\n padding: 0;\n background: rgba(255, 255, 255, 0.9);\n border: 1px solid rgba(0, 0, 0, 0.1);\n border-radius: 4px;\n color: #666;\n font-size: 12px;\n cursor: pointer;\n opacity: 0.2;\n transition: opacity 0.2s, background 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 1;\n}\n.gh-user-query-markdown pre:hover .gh-code-copy-btn {\n opacity: 1;\n}\n.gh-user-query-markdown .gh-code-copy-btn:hover {\n background: #4285f4;\n color: white;\n border-color: #4285f4;\n}\n\n/* 标题间距优化 */\n.gh-user-query-markdown h1,\n.gh-user-query-markdown h2,\n.gh-user-query-markdown h3,\n.gh-user-query-markdown h4,\n.gh-user-query-markdown h5,\n.gh-user-query-markdown h6 {\n margin: 0.5em 0 0.3em;\n line-height: 1.3;\n}\n\n.gh-user-query-markdown h1 { font-size: 1.3em; }\n.gh-user-query-markdown h2 { font-size: 1.2em; }\n.gh-user-query-markdown h3 { font-size: 1.1em; }\n\n/* 列表样式 */\n.gh-user-query-markdown ul,\n.gh-user-query-markdown ol {\n margin: 0.4em 0;\n padding-left: 1.5em;\n}\n\n.gh-user-query-markdown li {\n margin: 0.2em 0;\n}\n\n/* 引用块 */\n.gh-user-query-markdown blockquote {\n margin: 0.5em 0;\n padding: 0.5em 1em;\n border-left: 3px solid #4285f4;\n background: rgba(0, 0, 0, 0.03);\n border-radius: 0 4px 4px 0;\n}\n\n/* 表格优化 */\n.gh-user-query-markdown table {\n margin: 0.5em 0;\n font-size: 0.9em;\n}\n\n/* 分隔线 */\n.gh-user-query-markdown hr {\n margin: 0.5em 0;\n border: none;\n border-top: 1px solid #e5e7eb;\n}\n\n/* 深色模式适配 - 检测 Gemini 的 dark-theme 类 */\nbody.dark-theme .gh-user-query-markdown pre,\nbody.dark-theme .gh-user-query-markdown code {\n background: rgba(255, 255, 255, 0.08);\n}\nbody.dark-theme .gh-user-query-markdown pre::-webkit-scrollbar-thumb {\n background: rgba(255, 255, 255, 0.15);\n}\nbody.dark-theme .gh-user-query-markdown pre::-webkit-scrollbar-thumb:hover {\n background: rgba(255, 255, 255, 0.25);\n}\nbody.dark-theme .gh-user-query-markdown .gh-code-copy-btn {\n background: rgba(0, 0, 0, 0.5);\n border-color: rgba(255, 255, 255, 0.1);\n color: #aaa;\n}\nbody.dark-theme .gh-user-query-markdown blockquote {\n background: rgba(255, 255, 255, 0.05);\n}\nbody.dark-theme .gh-user-query-markdown hr {\n border-top-color: #4b5563;\n}\n\n/* Gemini Enterprise 深色模式 */\nhtml[dark-theme] .gh-user-query-markdown pre,\nhtml[dark-theme] .gh-user-query-markdown code {\n background: rgba(255, 255, 255, 0.08);\n}\nhtml[dark-theme] .gh-user-query-markdown pre::-webkit-scrollbar-thumb {\n background: rgba(255, 255, 255, 0.15);\n}\nhtml[dark-theme] .gh-user-query-markdown pre::-webkit-scrollbar-thumb:hover {\n background: rgba(255, 255, 255, 0.25);\n}\nhtml[dark-theme] .gh-user-query-markdown .gh-code-copy-btn {\n background: rgba(0, 0, 0, 0.5);\n border-color: rgba(255, 255, 255, 0.1);\n color: #aaa;\n}\nhtml[dark-theme] .gh-user-query-markdown blockquote {\n background: rgba(255, 255, 255, 0.05);\n}\nhtml[dark-theme] .gh-user-query-markdown hr {\n border-top-color: #4b5563;\n}\n\n/* ChatGPT 深色模式(使用 html.dark 类) */\nhtml.dark .gh-user-query-markdown pre,\nhtml.dark .gh-user-query-markdown code {\n background: rgba(255, 255, 255, 0.08);\n}\nhtml.dark .gh-user-query-markdown pre::-webkit-scrollbar-thumb {\n background: rgba(255, 255, 255, 0.15);\n}\nhtml.dark .gh-user-query-markdown pre::-webkit-scrollbar-thumb:hover {\n background: rgba(255, 255, 255, 0.25);\n}\nhtml.dark .gh-user-query-markdown .gh-code-copy-btn {\n background: rgba(0, 0, 0, 0.5);\n border-color: rgba(255, 255, 255, 0.1);\n color: #aaa;\n}\nhtml.dark .gh-user-query-markdown blockquote {\n background: rgba(255, 255, 255, 0.05);\n}\nhtml.dark .gh-user-query-markdown hr {\n border-top-color: #4b5563;\n}\n";function Sw(e){const t=e.trim();return !!t&&(bw.some(e=>e.test(t))||yw.some(e=>e.test(t))||function(e){const t=function(e){return e.replace(/```[\s\S]*?```/g,"").replace(/`[^`\n]*`/g,"")}(e);return vw.some(e=>e.test(t))||ww.some(e=>e.test(t))}(t))}class Cw{adapter;enabled;processedElements=new WeakMap;stopWatch=null;rescanTimer=null;injectedShadowRoots=new WeakSet;codeCopyHandler=null;constructor(e,t){this.adapter=e,this.enabled=t,t&&this.init();}init(){const e=this.adapter.getUserQuerySelector();if(!e)return void console.warn("[UserQueryMarkdownRenderer] No user query selector found for this site");if(this.adapter.usesShadowDOM())this.startRescanTimer();else {this.injectGlobalStyles(),this.initCodeCopyHandler(),this.stopWatch=ei.each(e,e=>{this.processQueryElement(e);},{shadow:true});const t=this.adapter.getSiteId();t!==Pr&&t!==jr||this.startRescanTimer();}}injectGlobalStyles(){if(document.getElementById(xw))return;const e=document.createElement("style");e.id=xw,e.textContent=["\n/* highlight.js GitHub Dark 主题 */\n.hljs {\n background: var(--gh-bg-tertiary, #1e1e1e);\n color: var(--gh-text, #e6edf3);\n padding: 12px;\n border-radius: 6px;\n overflow-x: auto;\n font-family: 'SF Mono', Consolas, 'Liberation Mono', Menlo, monospace;\n font-size: 13px;\n line-height: 1.5;\n /* 代码块自动换行 */\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n.hljs-comment,\n.hljs-quote { color: #8b949e; font-style: italic; }\n.hljs-keyword,\n.hljs-selector-tag { color: #ff7b72; }\n.hljs-string,\n.hljs-doctag { color: #a5d6ff; }\n.hljs-number,\n.hljs-literal { color: #79c0ff; }\n.hljs-title,\n.hljs-section,\n.hljs-selector-id { color: #d2a8ff; font-weight: bold; }\n.hljs-function > .hljs-title { color: #d2a8ff; }\n.hljs-type,\n.hljs-class .hljs-title { color: #7ee787; }\n.hljs-attribute { color: #79c0ff; }\n.hljs-variable,\n.hljs-template-variable { color: #ffa657; }\n.hljs-built_in { color: #ffa657; }\n.hljs-addition { color: #aff5b4; background: rgba(46, 160, 67, 0.15); }\n.hljs-deletion { color: #ffdcd7; background: rgba(248, 81, 73, 0.15); }\n\n/* 变量占位符高亮 */\n.gh-variable-highlight {\n background: rgba(56, 139, 253, 0.2);\n color: #58a6ff;\n padding: 2px 6px;\n border-radius: 4px;\n font-weight: 500;\n}\n\n/* Markdown 渲染样式 */\n.gh-markdown-preview {\n line-height: 1.6;\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview h1,\n.gh-markdown-preview h2,\n.gh-markdown-preview h3 {\n margin: 16px 0 8px;\n font-weight: 600;\n border-bottom: 1px solid var(--gh-border, #30363d);\n padding-bottom: 4px;\n}\n.gh-markdown-preview h1 { font-size: 1.5em; }\n.gh-markdown-preview h2 { font-size: 1.3em; }\n.gh-markdown-preview h3 { font-size: 1.1em; }\n.gh-markdown-preview p { margin: 8px 0; }\n.gh-markdown-preview code:not(.hljs) {\n background: var(--gh-bg-tertiary, #343942);\n padding: 2px 6px;\n border-radius: 4px;\n font-size: 13px;\n}\n.gh-markdown-preview pre {\n margin: 12px 0;\n position: relative;\n max-width: 100%;\n overflow: hidden;\n}\n.gh-markdown-preview pre code {\n display: block;\n max-width: 100%;\n overflow-x: auto;\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n/* 代码块复制按钮 */\n.gh-code-copy-btn {\n position: absolute;\n top: 8px;\n right: 8px;\n padding: 4px 8px;\n background: var(--gh-bg-secondary, #2d333b);\n border: 1px solid var(--gh-border, #444c56);\n border-radius: 4px;\n color: var(--gh-text-secondary, #8b949e);\n font-size: 12px;\n cursor: pointer;\n opacity: 0;\n transition: opacity 0.2s;\n}\n.gh-markdown-preview pre:hover .gh-code-copy-btn {\n opacity: 1;\n}\n.gh-code-copy-btn:hover {\n background: var(--gh-hover, #373e47);\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview blockquote {\n border-left: 3px solid var(--gh-primary, #4285f4);\n margin: 12px 0;\n padding: 8px 16px;\n background: var(--gh-bg-secondary, #161b22);\n color: var(--gh-text-secondary, #8b949e);\n}\n.gh-markdown-preview ul,\n.gh-markdown-preview ol {\n margin: 8px 0;\n padding-left: 24px;\n}\n.gh-markdown-preview li { margin: 4px 0; }\n.gh-markdown-preview a {\n color: var(--gh-primary, #58a6ff);\n text-decoration: none;\n}\n.gh-markdown-preview a:hover { text-decoration: underline; }\n\n/* 任务列表样式 */\n.gh-markdown-preview .task-list-item {\n list-style: none;\n margin-left: -20px;\n}\n.gh-markdown-preview .task-list-item input[type=\"checkbox\"] {\n margin-right: 8px;\n pointer-events: none;\n}\n\n/* 高亮 ==text== */\n.gh-markdown-preview mark {\n background: rgba(255, 235, 59, 0.4);\n color: inherit;\n padding: 2px 4px;\n border-radius: 3px;\n}\n\n/* 容器样式 :::info, :::warning, :::danger */\n.gh-container {\n margin: 12px 0;\n padding: 12px 16px;\n border-radius: 6px;\n border-left: 4px solid;\n}\n.gh-container-info {\n background: rgba(56, 139, 253, 0.1);\n border-color: #388bfd;\n}\n.gh-container-warning {\n background: rgba(255, 166, 87, 0.1);\n border-color: #ffa657;\n}\n.gh-container-danger {\n background: rgba(248, 81, 73, 0.1);\n border-color: #f85149;\n}\n",xd(),kw].filter(Boolean).join("\n"),document.head.appendChild(e);}injectStyleToShadowRoot(e){if(this.injectedShadowRoots.has(e))return;if(e.querySelector(`#${xw}`))return;const t=document.createElement("style");t.id=xw,t.textContent=["\n/* highlight.js GitHub Dark 主题 */\n.hljs {\n background: var(--gh-bg-tertiary, #1e1e1e);\n color: var(--gh-text, #e6edf3);\n padding: 12px;\n border-radius: 6px;\n overflow-x: auto;\n font-family: 'SF Mono', Consolas, 'Liberation Mono', Menlo, monospace;\n font-size: 13px;\n line-height: 1.5;\n /* 代码块自动换行 */\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n.hljs-comment,\n.hljs-quote { color: #8b949e; font-style: italic; }\n.hljs-keyword,\n.hljs-selector-tag { color: #ff7b72; }\n.hljs-string,\n.hljs-doctag { color: #a5d6ff; }\n.hljs-number,\n.hljs-literal { color: #79c0ff; }\n.hljs-title,\n.hljs-section,\n.hljs-selector-id { color: #d2a8ff; font-weight: bold; }\n.hljs-function > .hljs-title { color: #d2a8ff; }\n.hljs-type,\n.hljs-class .hljs-title { color: #7ee787; }\n.hljs-attribute { color: #79c0ff; }\n.hljs-variable,\n.hljs-template-variable { color: #ffa657; }\n.hljs-built_in { color: #ffa657; }\n.hljs-addition { color: #aff5b4; background: rgba(46, 160, 67, 0.15); }\n.hljs-deletion { color: #ffdcd7; background: rgba(248, 81, 73, 0.15); }\n\n/* 变量占位符高亮 */\n.gh-variable-highlight {\n background: rgba(56, 139, 253, 0.2);\n color: #58a6ff;\n padding: 2px 6px;\n border-radius: 4px;\n font-weight: 500;\n}\n\n/* Markdown 渲染样式 */\n.gh-markdown-preview {\n line-height: 1.6;\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview h1,\n.gh-markdown-preview h2,\n.gh-markdown-preview h3 {\n margin: 16px 0 8px;\n font-weight: 600;\n border-bottom: 1px solid var(--gh-border, #30363d);\n padding-bottom: 4px;\n}\n.gh-markdown-preview h1 { font-size: 1.5em; }\n.gh-markdown-preview h2 { font-size: 1.3em; }\n.gh-markdown-preview h3 { font-size: 1.1em; }\n.gh-markdown-preview p { margin: 8px 0; }\n.gh-markdown-preview code:not(.hljs) {\n background: var(--gh-bg-tertiary, #343942);\n padding: 2px 6px;\n border-radius: 4px;\n font-size: 13px;\n}\n.gh-markdown-preview pre {\n margin: 12px 0;\n position: relative;\n max-width: 100%;\n overflow: hidden;\n}\n.gh-markdown-preview pre code {\n display: block;\n max-width: 100%;\n overflow-x: auto;\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n/* 代码块复制按钮 */\n.gh-code-copy-btn {\n position: absolute;\n top: 8px;\n right: 8px;\n padding: 4px 8px;\n background: var(--gh-bg-secondary, #2d333b);\n border: 1px solid var(--gh-border, #444c56);\n border-radius: 4px;\n color: var(--gh-text-secondary, #8b949e);\n font-size: 12px;\n cursor: pointer;\n opacity: 0;\n transition: opacity 0.2s;\n}\n.gh-markdown-preview pre:hover .gh-code-copy-btn {\n opacity: 1;\n}\n.gh-code-copy-btn:hover {\n background: var(--gh-hover, #373e47);\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview blockquote {\n border-left: 3px solid var(--gh-primary, #4285f4);\n margin: 12px 0;\n padding: 8px 16px;\n background: var(--gh-bg-secondary, #161b22);\n color: var(--gh-text-secondary, #8b949e);\n}\n.gh-markdown-preview ul,\n.gh-markdown-preview ol {\n margin: 8px 0;\n padding-left: 24px;\n}\n.gh-markdown-preview li { margin: 4px 0; }\n.gh-markdown-preview a {\n color: var(--gh-primary, #58a6ff);\n text-decoration: none;\n}\n.gh-markdown-preview a:hover { text-decoration: underline; }\n\n/* 任务列表样式 */\n.gh-markdown-preview .task-list-item {\n list-style: none;\n margin-left: -20px;\n}\n.gh-markdown-preview .task-list-item input[type=\"checkbox\"] {\n margin-right: 8px;\n pointer-events: none;\n}\n\n/* 高亮 ==text== */\n.gh-markdown-preview mark {\n background: rgba(255, 235, 59, 0.4);\n color: inherit;\n padding: 2px 4px;\n border-radius: 3px;\n}\n\n/* 容器样式 :::info, :::warning, :::danger */\n.gh-container {\n margin: 12px 0;\n padding: 12px 16px;\n border-radius: 6px;\n border-left: 4px solid;\n}\n.gh-container-info {\n background: rgba(56, 139, 253, 0.1);\n border-color: #388bfd;\n}\n.gh-container-warning {\n background: rgba(255, 166, 87, 0.1);\n border-color: #ffa657;\n}\n.gh-container-danger {\n background: rgba(248, 81, 73, 0.1);\n border-color: #f85149;\n}\n",xd(),kw].filter(Boolean).join("\n"),e.prepend(t),this.injectedShadowRoots.add(e),e.addEventListener("click",e=>this.handleCodeCopy(e));}handleCodeCopy(e){const t=e.target.closest(".gh-code-copy-btn");if(t&&t.closest(".gh-user-query-markdown")){e.preventDefault(),e.stopPropagation();const n=t.nextElementSibling?.textContent||"";navigator.clipboard.writeText(n).then(()=>{_u(t,{size:14});}).catch(e=>{console.error("[UserQueryMarkdownRenderer] Copy failed:",e);});}}initCodeCopyHandler(){this.codeCopyHandler||(this.codeCopyHandler=e=>this.handleCodeCopy(e),document.addEventListener("click",this.codeCopyHandler,true));}startRescanTimer(){this.rescanTimer||(setTimeout(()=>{this.enabled&&this.rescan();},1e3),this.rescanTimer=window.setInterval(()=>{this.enabled&&this.rescan();},2e3));}rescan(){if(document.hidden||!document.hasFocus())return;const e=this.adapter.getUserQuerySelector();if(!e)return;const t=ei.query(e,{all:true,shadow:true});for(const n of t)this.processQueryElement(n);}processQueryElement(e){const t=this.adapter.extractUserQueryMarkdown(e);if(!t)return;if(!Sw(t))return;if(this.processedElements.get(e)===t)return;const n=wd(t,false,{enableMath:true});if(this.adapter.usesShadowDOM()){const t=e.querySelector("ucs-fast-markdown");t?.shadowRoot&&this.injectStyleToShadowRoot(t.shadowRoot);}const r=this.adapter.replaceUserQueryContent(e,n);let o=e.querySelector(".gh-user-query-markdown");if(!o&&this.adapter.usesShadowDOM()){const t=e.querySelector("ucs-fast-markdown");t?.shadowRoot&&(o=t.shadowRoot.querySelector(".gh-user-query-markdown"));}if(o)return Au(o,{size:14,color:"#6b7280"}),void this.processedElements.set(e,t);r&&this.processedElements.set(e,t);}updateSettings(e){this.enabled!==e&&(this.enabled=e,e?this.init():this.stop());}stop(){this.stopWatch&&(this.stopWatch(),this.stopWatch=null),this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);}destroy(){this.stop(),this.processedElements=new WeakMap,this.injectedShadowRoots=new WeakSet;const e=document.getElementById(xw);e&&e.remove(),this.codeCopyHandler&&(document.removeEventListener("click",this.codeCopyHandler,true),this.codeCopyHandler=null);}}const Ew=/^https:\/\/lh3\.googleusercontent\.com\//i;class _w{static WATERMARK_BG_PATHS={48:"assets/userscript/ophel-watermark-bg-48.png",96:"assets/userscript/ophel-watermark-bg-96.png"};static ALPHA_THRESHOLD=.002;static MAX_ALPHA=.99;static LOGO_VALUE=255;alphaMaps={};bgImages={};processingQueue=new Set;processingMap=new Map;processedDataUrlCache=new Map;enabled=false;stopObserver=null;mainWorldMessageListener=null;actionButtonListener=null;userscriptOriginalFetch=null;constructor(){this.alphaMaps={},this.bgImages={},this.processingQueue=new Set,this.processingMap=new Map,this.processedDataUrlCache=new Map;}start(){this.enabled||(this.enabled=true,this.enableUserscriptFetchInterception(),this.processExistingImages(),this.startObserver());}stop(){this.enabled&&(this.enabled=false,this.disableUserscriptFetchInterception(),this.teardownActionButtonInterception(),this.processingMap.clear(),this.processingQueue.clear(),this.stopObserver&&(this.stopObserver(),this.stopObserver=null));}isGeminiStandardSite(){return "gemini.google.com"===window.location.hostname}shouldInterceptGeminiImageUrl(e){return Ew.test(e)}isLikelyGeneratedImage(e){const t=e.currentSrc||e.src||"";if(!t)return false;const n=e.naturalWidth||e.width||0,r=e.naturalHeight||e.height||0;return !(n<192||r<192)&&(this.shouldInterceptGeminiImageUrl(t)||t.startsWith("data:image/")||t.startsWith("blob:"))}isSupportedGeminiImageSource(e){return !!e&&(this.shouldInterceptGeminiImageUrl(e)||e.startsWith("data:image/")||e.startsWith("blob:"))}getImageSourceForAction(e){const t=e.getAttribute("data-ophel-wm-source")||"";if(t)return t;return e.currentSrc||e.src||""}normalizePossibleUrl(e){if(!e)return "";if(e.startsWith("data:image/")||e.startsWith("blob:"))return e;try{return new URL(e,window.location.href).toString()}catch{return e}}extractSupportedUrlFromNode(e){const t=[],n=[],r=[],o=e=>{if(!e)return;const o=this.normalizePossibleUrl(e);this.isSupportedGeminiImageSource(o)&&(this.shouldInterceptGeminiImageUrl(o)?t.push(o):o.startsWith("blob:")?n.push(o):o.startsWith("data:image/")&&r.push(o));const i=e.match(/https?:\/\/[^\s"'<>]*googleusercontent\.com[^\s"'<>]*/gi);if(i&&0!==i.length)for(const n of i){const e=this.normalizePossibleUrl(n);this.shouldInterceptGeminiImageUrl(e)&&t.push(e);}};for(const i of Array.from(e.attributes))o(i?.value||"");return e instanceof HTMLAnchorElement&&e.href&&o(e.href),e instanceof HTMLImageElement&&o(e.currentSrc||e.src||""),t[0]||n[0]||r[0]||""}getRequestUrl(e){if("string"==typeof e)return e;if(e&&"object"==typeof e&&"url"in e){const t=e;if("string"==typeof t.url)return t.url}return ""}toggleMainWorldFetchInterception(e){this.isGeminiStandardSite()&&window.postMessage({type:"OPHEL_WATERMARK_FETCH_TOGGLE",enabled:e},"*");}setupMainWorldBridge(){!this.mainWorldMessageListener&&this.isGeminiStandardSite()&&(this.mainWorldMessageListener=e=>{if(e.source!==window)return;const t=e.data;if(!t||"OPHEL_WATERMARK_PROCESS_REQUEST"!==t.type)return;const n=t.requestId||"",r=t.url||"",o=t.arrayBuffer,i=t.mimeType||"";n&&r&&this.handleMainWorldProcessRequest(n,r,o,i);},window.addEventListener("message",this.mainWorldMessageListener));}teardownMainWorldBridge(){this.mainWorldMessageListener&&(window.removeEventListener("message",this.mainWorldMessageListener),this.mainWorldMessageListener=null);}postMainWorldProcessResponse(e){window.postMessage({type:"OPHEL_WATERMARK_PROCESS_RESPONSE",...e},"*");}async handleMainWorldProcessRequest(e,t,n,r){if(this.enabled&&this.shouldInterceptGeminiImageUrl(t))try{const o=n?new Blob([n],{type:r||"image/png"}):void 0,i=o?await this.processImageBlobToDataUrl(o):await this.getProcessedDataUrl(t);this.postMainWorldProcessResponse({requestId:e,success:!0,dataUrl:i});}catch(o){this.postMainWorldProcessResponse({requestId:e,success:false,error:o instanceof Error?o.message:"Unknown processing error"});}else this.postMainWorldProcessResponse({requestId:e,success:false,error:"Watermark interceptor disabled"});}getUserscriptPageWindow(){return "undefined"!=typeof unsafeWindow&&unsafeWindow&&unsafeWindow!==window?unsafeWindow:window}enableUserscriptFetchInterception(){if(this.userscriptOriginalFetch||!this.isGeminiStandardSite())return;const e=this.getUserscriptPageWindow();this.userscriptOriginalFetch=e.fetch.bind(e),e.fetch=async(...t)=>{const n=this.getRequestUrl(t[0]);if(!this.enabled||!n||!this.shouldInterceptGeminiImageUrl(n))return this.userscriptOriginalFetch.apply(e,t);try{const e=await this.getProcessedDataUrl(n),t=await this.dataUrlToBlob(e);return new Response(t,{status:200,statusText:"OK",headers:new Headers({"Content-Type":t.type||"image/png"})})}catch{return this.userscriptOriginalFetch.apply(e,t)}};}disableUserscriptFetchInterception(){if(!this.userscriptOriginalFetch)return;this.getUserscriptPageWindow().fetch=this.userscriptOriginalFetch,this.userscriptOriginalFetch=null;}setupActionButtonInterception(){}teardownActionButtonInterception(){this.actionButtonListener&&(document.removeEventListener("click",this.actionButtonListener,true),this.actionButtonListener=null);}isActionButtonElement(e,t){const n=[e.getAttribute("aria-label")||"",e.getAttribute("data-tooltip")||"",e.getAttribute("mattooltip")||"",e.getAttribute("title")||"",(e.textContent||"").trim()].join(" ").trim().trim().toLowerCase();return "copy"===t?n.includes("copy")||n.includes("copy image")||n.includes("copy full")||n.includes("复制")||n.includes("複製"):n.includes("download")||n.includes("save image")||n.includes("full size")||n.includes("下载")||n.includes("下載")}findImageAction(e){const t=("function"==typeof e.composedPath?e.composedPath():[]).filter(e=>e instanceof Element),n=e.target instanceof Element?e.target:null,r=[];if(n){const e=n.closest("button,[role='button']");e&&r.push(e);}for(const i of t)i instanceof HTMLElement&&(i.matches("button")||"button"===i.getAttribute("role"))&&r.push(i);const o=Array.from(new Set(r));if(0===o.length)return null;for(const i of o){if(this.isActionButtonElement(i,"copy"))return {action:"copy",button:i};if(this.isActionButtonElement(i,"download"))return {action:"download",button:i};for(const e of Array.from(i.querySelectorAll("[aria-label],[data-tooltip],[mattooltip]"))){if(this.isActionButtonElement(e,"copy"))return {action:"copy",button:i};if(this.isActionButtonElement(e,"download"))return {action:"download",button:i}}}return null}findRelatedGeminiImage(e){let t=e;for(let a=0;a<6&&t;a++){const e=Array.from(t.querySelectorAll("img"));for(const t of e){const e=this.getImageSourceForAction(t);if(this.isValidGeminiImage(t)&&this.isSupportedGeminiImageSource(e))return t}t=t.parentElement;}const n=e.getBoundingClientRect(),r=n.left+n.width/2,o=n.top+n.height/2,i=document.elementFromPoint(r,o)?.closest("generated-image, .generated-image-container");if(i){const e=Array.from(i.querySelectorAll("img"));for(const t of e){const e=this.getImageSourceForAction(t);if(this.isValidGeminiImage(t)&&this.isSupportedGeminiImageSource(e))return t}}return null}findBestVisibleGeminiImage(){const e=Array.from(document.querySelectorAll("img")).filter(e=>!!this.isValidGeminiImage(e)&&this.isSupportedGeminiImageSource(this.getImageSourceForAction(e))).filter(e=>{const t=e.getBoundingClientRect();return t.width>120&&t.height>120&&t.bottom>0&&t.right>0});return 0===e.length?null:(e.sort((e,t)=>{const n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return r.width*r.height-n.width*n.height}),e[0]||null)}findRelatedGeminiImageFromEvent(e){const t="function"==typeof e.composedPath?e.composedPath():[];for(const n of t){if(!(n instanceof Element))continue;if(n instanceof HTMLImageElement){const e=this.getImageSourceForAction(n);if(this.isValidGeminiImage(n)&&this.isSupportedGeminiImageSource(e))return n}const e=Array.from(n.querySelectorAll?.("img")||[]);for(const t of e){const e=this.getImageSourceForAction(t);if(this.isValidGeminiImage(t)&&this.isSupportedGeminiImageSource(e))return t}}return null}findGeminiSourceUrlFromEvent(e){const t="function"==typeof e.composedPath?e.composedPath():[];let n="",r="";for(const o of t){if(!(o instanceof Element))continue;const e=this.extractSupportedUrlFromNode(o);if(e){if(this.shouldInterceptGeminiImageUrl(e))return e;!n&&e.startsWith("blob:")&&(n=e),!r&&e.startsWith("data:image/")&&(r=e);}}return n||r||""}async resolveActionDataUrl(e){return e.startsWith("data:image/")?e:e.startsWith("blob:")?this.processImageSourceToDataUrl(e):this.getProcessedDataUrl(e)}async writeImageToClipboard(e){const t=await this.dataUrlToBlob(e);if("undefined"==typeof ClipboardItem||!navigator.clipboard?.write)throw new Error("Clipboard API unavailable");const n=new ClipboardItem({[t.type||"image/png"]:t});await navigator.clipboard.write([n]);}triggerDownloadFromDataUrl(e){const t=document.createElement("a");t.href=e,t.download=`gemini-image-${Date.now()}.png`,t.rel="noopener",document.body.appendChild(t),t.click(),t.remove();}shouldUseNativeGeminiAction(){return null!==this.userscriptOriginalFetch}async resolveProcessedDataUrlForAction(e,t){if(e.startsWith("data:image/"))return e;if(e.startsWith("blob:"))return this.resolveActionDataUrl(e);try{return await this.getProcessedDataUrl(e,{bypassCache:!0,requireNonPreviewSource:!0})}catch(n){const r=n instanceof Error?n.message:"";if("copy"===t&&"fullsize-source-unavailable"===r)return this.getProcessedDataUrl(e,{bypassCache:true,requireNonPreviewSource:false});throw n}}async handleActionButtonClick(e){if(!this.enabled||!this.isGeminiStandardSite())return;const t=this.findImageAction(e);if(!t)return;if(this.shouldUseNativeGeminiAction())return;const n=this.findRelatedGeminiImageFromEvent(e)||this.findRelatedGeminiImage(t.button)||this.findBestVisibleGeminiImage(),r=this.findGeminiSourceUrlFromEvent(e)||(n?this.getImageSourceForAction(n):"");if(r&&this.isSupportedGeminiImageSource(r)){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();try{const e=await this.resolveProcessedDataUrlForAction(r,t.action);if(!e)return;n&&n.setAttribute("data-ophel-wm-processed","1"),"copy"===t.action?await this.writeImageToClipboard(e):this.triggerDownloadFromDataUrl(e);}catch{return}}}calculateAlphaMap(e){const{width:t,height:n,data:r}=e,o=new Float32Array(t*n);for(let i=0;i1024&&t>1024?{logoSize:96,marginRight:64,marginBottom:64}:{logoSize:48,marginRight:32,marginBottom:32}}calculateWatermarkPosition(e,t,n){const{logoSize:r,marginRight:o,marginBottom:i}=n;return {x:e-o-r,y:t-i-r,width:r,height:r}}getWatermarkBgUrl(e){return 48===e?window.__OPHEL_USERSCRIPT_ASSET_URLS__?.watermarkBg48||"":window.__OPHEL_USERSCRIPT_ASSET_URLS__?.watermarkBg96||""}async loadBgImage(e){return this.bgImages[e]?this.bgImages[e]:new Promise((t,n)=>{const r=this.getWatermarkBgUrl(e);if(!r)return void n(new Error(`Missing watermark background asset for size ${e}`));const o=new Image;o.onload=()=>{this.bgImages[e]=o,t(o);},o.onerror=n,o.src=r;})}async getAlphaMap(e){if(this.alphaMaps[e])return this.alphaMaps[e];const t=await this.loadBgImage(e),n=document.createElement("canvas");n.width=e,n.height=e;const r=n.getContext("2d");if(!r)throw new Error("Could not get canvas context");r.drawImage(t,0,0);const o=r.getImageData(0,0,e,e),i=this.calculateAlphaMap(o);return this.alphaMaps[e]=i,i}loadImageFromSource(e){return new Promise((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=n,r.src=e;})}async dataUrlToBlob(e){const t=e.match(/^data:([^;,]+)?(?:;charset=[^;,]+)?(;base64)?,([\s\S]*)$/i);if(!t)throw new Error("Invalid data URL");const n=t[1]||"application/octet-stream",r=!!t[2],o=t[3]||"";if(!r)return new Blob([decodeURIComponent(o)],{type:n});const i=o.replace(/\s+/g,""),a=atob(i),s=new Uint8Array(a.length);for(let l=0;l{e&&(n.includes(e)||n.push(e));},o=e=>{for(const t of (e=>{const t=e.search(/[?#]/),n=-1===t?e.length:t,r=e.lastIndexOf("/",n),o=e.lastIndexOf("=",n);if(-1===o||o{const t=e.toLowerCase();return !/^s\d+$/.test(t)&&!/^w\d+$/.test(t)&&!/^h\d+$/.test(t)}).filter(e=>"d"!==e.toLowerCase()),s=a.filter(e=>"rj"!==e.toLowerCase()),l=[["s0","d",...s],["s0",...s],["s0","d",...a],["s0",...a]],c=[];for(const d of l){const t=d.join("-"),r=`${e.slice(0,o+1)}${t}${e.slice(n)}`;c.includes(r)||c.push(r);}return c})(e))r(t);};return t.includes("/gg/")?(o(t.replace("/gg/","/rd-gg-dl/")),o(t.replace("/gg/","/rd-gg/")),o(t),n):t.includes("/rd-gg/")?(o(t.replace("/rd-gg/","/rd-gg-dl/")),o(t),o(t.replace("/rd-gg/","/gg/")),n):t.includes("/rd-gg-dl/")?(o(t),o(t.replace("/rd-gg-dl/","/rd-gg/")),o(t.replace("/rd-gg-dl/","/gg/")),n):(o(t),n)}async fetchOriginalBlobSingle(e){return async function(e){return new Promise((t,n)=>{GM_xmlhttpRequest({method:"GET",url:e,headers:{Referer:"https://gemini.google.com/",Origin:"https://gemini.google.com"},responseType:"blob",onload:e=>{e.status>=200&&e.status<300?t(e.response):n(new Error(`HTTP ${e.status}`));},onerror:e=>n(new Error(e?.message||"GM_xmlhttpRequest failed"))});})}(e)}async fetchOriginalBlob(e,t){const n=this.shouldInterceptGeminiImageUrl(e)?this.buildRemoteFetchCandidates(e):[e];let r=null;for(const i of n)try{const e=await this.fetchOriginalBlobSingle(i);if(t?.requireNonPreviewSource&&/\/gg\//.test(i))throw new Error("fullsize-source-unavailable");return e}catch(o){r=o;}throw r instanceof Error?r:new Error("Failed to fetch original image")}async processLoadedImageToDataUrl(e){const t=document.createElement("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");n.drawImage(e,0,0);const r=n.getImageData(0,0,t.width,t.height),o=this.detectWatermarkConfig(t.width,t.height),i=this.calculateWatermarkPosition(t.width,t.height,o),a=await this.getAlphaMap(o.logoSize);return this.removeWatermark(r,a,i),n.putImageData(r,0,0),t.toDataURL("image/png")}async processImageSourceToDataUrl(e){const t=await this.loadImageFromSource(e);return this.processLoadedImageToDataUrl(t)}async processImageBlobToDataUrl(e){const t=URL.createObjectURL(e);try{return await this.processImageSourceToDataUrl(t)}finally{URL.revokeObjectURL(t);}}async getProcessedDataUrl(e,t){const n=this.replaceWithNormalSize(e);if(!t?.bypassCache){const e=this.processedDataUrlCache.get(n);if(e)return e}if(!t?.bypassCache){const e=this.processingMap.get(n);if(e)return e}const r=(async()=>{const e=await this.fetchOriginalBlob(n,{requireNonPreviewSource:t?.requireNonPreviewSource}),r=await this.processImageBlobToDataUrl(e);if(!t?.bypassCache&&(this.processedDataUrlCache.set(n,r),this.processedDataUrlCache.size>100)){const e=this.processedDataUrlCache.keys().next().value;e&&this.processedDataUrlCache.delete(e);}return r})();if(!t?.bypassCache){this.processingMap.set(n,r);try{return await r}finally{this.processingMap.delete(n);}}return r}isValidGeminiImage(e){return !!e.closest("generated-image,.generated-image-container")||this.isLikelyGeneratedImage(e)}findGeminiImages(){return [...document.querySelectorAll("img")].filter(e=>{const t=this.getImageSourceForAction(e);return this.isValidGeminiImage(e)&&this.isSupportedGeminiImageSource(t)&&"true"!==e.dataset.watermarkProcessed&&"processing"!==e.dataset.watermarkProcessed})}async processExistingImages(){const e=this.findGeminiImages();for(const t of e)this.processSingleImage(t);}async processSingleImage(e){const t=e.currentSrc||e.src;if(t&&this.isSupportedGeminiImageSource(t)&&!this.processingQueue.has(t)){this.processingQueue.add(t),e.dataset.watermarkProcessed="processing";try{const n=t.startsWith("data:image/")||t.startsWith("blob:")?t:this.replaceWithNormalSize(t),r=await this.resolveActionDataUrl(n);e.src=r,e.dataset.watermarkProcessed="true",e.setAttribute("data-ophel-wm-source",n),e.setAttribute("data-ophel-wm-processed","1");}catch{e.dataset.watermarkProcessed="error",e.removeAttribute("data-ophel-wm-processed");}finally{this.processingQueue.delete(t);}}}replaceWithNormalSize(e){if(!e)return e;if(e.startsWith("data:image/")||e.startsWith("blob:"))return e;if(!this.shouldInterceptGeminiImageUrl(e))return e;const t=e.search(/[?#]/),n=-1===t?e.length:t,r=e.lastIndexOf("/",n),o=e.lastIndexOf("=",n);if(-1===o||o{const t=e.toLowerCase();return !/^s\d+$/.test(t)&&(!/^w\d+$/.test(t)&&(!/^h\d+$/.test(t)&&"rj"!==t))})].join("-");return `${e.slice(0,o+1)}${a}${e.slice(n)}`}startObserver(){const e=new MutationObserver(e=>{let t=false;for(const n of e)n.addedNodes.length>0&&(t=true);t&&this.processExistingImages();});e.observe(document.body,{childList:true,subtree:true}),this.stopObserver=()=>e.disconnect();}}let Aw={assistantMermaidRenderer:null,themeManager:null,copyManager:null,layoutManager:null,markdownFixer:null,tabManager:null,watermarkRemover:null,readingHistoryManager:null,modelLocker:null,scrollLockManager:null,userQueryMarkdownRenderer:null,policyRetryManager:null,usageCounterManager:null},Tw=null,Mw=null;function Iw(e){return e.content?.assistantMermaid??true}async function Nw(e){const{adapter:t,settings:n}=e;if("fallback"!==t.getAssistantMermaidSupportMode())return Aw.assistantMermaidRenderer?.stop(),void(Aw.assistantMermaidRenderer=null);Iw(n)?Aw.assistantMermaidRenderer?Aw.assistantMermaidRenderer.updateSettings(true):(Mw||(Mw=(async()=>{"fallback"===t.getAssistantMermaidSupportMode()&&Iw(Do())&&(Aw.assistantMermaidRenderer?Aw.assistantMermaidRenderer.updateSettings(true):Aw.assistantMermaidRenderer=new Hv(t,true));})().finally(()=>{Mw=null;})),await Mw):Aw.assistantMermaidRenderer?.updateSettings(false);}function Lw(e){const{adapter:t,settings:n,siteId:r}=e,o=yo(n,r),i=Tm({mode:o.mode,adapter:t,lightPresetId:o.lightStyleId||"google-gradient",darkPresetId:o.darkStyleId||"classic-dark",apply:true});return Aw.themeManager=i,i}async function Dw(e){const{adapter:t,settings:n,siteId:r}=e,o=yo(n,r);if("system"===o.mode&&Aw.themeManager)return void(await Aw.themeManager.setMode("system"));const i="system"===o.mode?window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":"dark"===o.mode?"dark":"light",a=document.documentElement.className,s=/\bdark\b/i.test(a),l=/\blight\b/i.test(a),c=document.body.className,d=/\bdark-theme\b/i.test(c),u=document.body.style.colorScheme;let h="light";s||d||"dark"===u?h="dark":l&&(h="light"),h!==i&&(Aw.themeManager&&Aw.themeManager.apply(i),t&&"function"==typeof t.toggleTheme&&await t.toggleTheme(i));}function Rw(e,t){switch(t){case Ir:return e.content?.markdownFix??false;case qr:return e.aistudio?.markdownFix??false;case Nr:return e.chatgpt?.markdownFix??false;default:return false}}function qw(e){const{adapter:t,settings:n,siteId:r}=e,o=t.getMarkdownFixerConfig(),i=Rw(n,r);o&&i&&(Aw.markdownFixer=new rw(o),Aw.markdownFixer.start(),console.warn(`[Ophel] MarkdownFixer started for ${t.getName()}`));}function Pw(e){const{adapter:t,settings:n,siteId:r}=e,o=vo(n,r),i=xo(n,r),a=ko(n,r).enabled;(o?.enabled||i?.enabled||a)&&(Aw.layoutManager=new Yv(t,o),o?.enabled&&Aw.layoutManager.apply(),i?.enabled&&Aw.layoutManager.updateUserQueryConfig(i),a&&Aw.layoutManager.updateZenMode(true));}function Bw(e){const{adapter:t,settings:n}=e;n.content&&(Aw.copyManager=new Uv(n.content,t),n.content.formulaCopy&&Aw.copyManager.initFormulaCopy(),n.content.tableCopy&&Aw.copyManager.initTableCopy());}function Ow(e){const{adapter:t,settings:n}=e;n.tab&&(Aw.tabManager=new lw(t,n.tab),Aw.tabManager.start());}function zw(e){const{adapter:t,settings:n,siteId:r}=e;Aw.usageCounterManager=new fw(t,n.usageMonitor,r),Aw.usageCounterManager.start();}function Fw(e){const{settings:t,siteId:n}=e;n!==Ir&&n!==Dr||!t.content?.watermarkRemoval||(Aw.watermarkRemover=new _w,Aw.watermarkRemover.start());}async function jw(e){const{adapter:t,settings:n}=e;if(n.readingHistory?.persistence){Tw&&(clearTimeout(Tw),Tw=null);const e=e=>{Aw.readingHistoryManager||(Aw.readingHistoryManager=new aw(t,e.readingHistory),Aw.readingHistoryManager.startRecording(),Aw.readingHistoryManager.cleanup());};if(await(So||(So=new Promise(e=>{"undefined"!=typeof chrome&&chrome.storage?.local?chrome.storage.local.get(uo,t=>{const n=t?.[uo];if(void 0===n)return void e(false);const r="number"==typeof n?n:Number(n);Number.isFinite(r)?Date.now()-r<=5e3?e(true):chrome.storage.local.remove(uo,()=>e(false)):e(true);}):e(false);}),So))||_o())return void(Tw=setTimeout(()=>{Tw=null;const t=Do();t.readingHistory?.persistence&&!Aw.readingHistoryManager&&e(t);},5e3));if(e(n),n.readingHistory.autoRestore){const{showToast:e}=await r(async()=>{const{showToast:e}=await Promise.resolve().then(()=>Fo);return {showToast:e}},void 0);Aw.readingHistoryManager.restoreProgress(t=>e(t,3e3)).then(t=>{t&&e("阅读进度已恢复",2e3);});}Aw.readingHistoryManager.cleanup();}}function $w(e){const{adapter:t,settings:n,siteId:r}=e,o=wo(n,r);Aw.modelLocker=new ow(t,o),o.enabled&&o.keyword&&Aw.modelLocker.start();}function Hw(e){const{adapter:t,settings:n}=e;Aw.scrollLockManager=new sw(t,n);}function Uw(e){const{adapter:t,settings:n}=e;Aw.userQueryMarkdownRenderer=new Cw(t,n.content?.userQueryMarkdown??true);}function Ww(e){const{adapter:t,settings:n,siteId:r}=e;r===Dr&&(Aw.policyRetryManager=new iw(t,n.geminiEnterprise?.policyRetry||{enabled:false,maxRetries:3}));}const Vw=Object.freeze(Object.defineProperty({__proto__:null,initAssistantMermaidRenderer:Nw,initCopyManager:Bw,initCoreModules:async function(e){return Lw(e),setTimeout(()=>Dw(e),1e3),qw(e),Pw(e),Bw(e),Ow(e),Fw(e),zw(e),await jw(e),$w(e),Hw(e),Uw(e),await Nw(e),Ww(e),Aw},initLayoutManager:Pw,initMarkdownFixer:qw,initModelLocker:$w,initPolicyRetryManager:Ww,initReadingHistoryManager:jw,initScrollLockManager:Hw,initTabManager:Ow,initThemeManager:Lw,initUrlChangeObserver:function(e){const{adapter:t}=e;let n=window.location.pathname,o=null;const i=async()=>{const e=window.location.pathname;e!==n&&(n=e,console.warn("[Ophel] URL changed, reinitializing modules..."),o&&(clearTimeout(o),o=null),Aw.readingHistoryManager&&(Aw.readingHistoryManager.stopRecording(),o=setTimeout(async()=>{o=null;const{showToast:e}=await r(async()=>{const{showToast:e}=await Promise.resolve().then(()=>Fo);return {showToast:e}},void 0);if(!_o()){await(Aw.readingHistoryManager?.restoreProgress(t=>e(t,3e3)))&&e("阅读进度已恢复",2e3);}Aw.readingHistoryManager?.startRecording();},1500)),window.dispatchEvent(new Event("gh-url-change")),Aw.tabManager&&(Aw.tabManager.resetSessionCache(),[300,800,1500].forEach(e=>setTimeout(()=>Aw.tabManager?.updateTabName(true),e))),t.findTextarea(),Aw.usageCounterManager?.handleUrlChange(),Aw.modelLocker?.relock(300));};window.addEventListener("popstate",i);const a=history.pushState,s=history.replaceState;history.pushState=function(...e){a.apply(this,e),i();},history.replaceState=function(...e){s.apply(this,e),i();},setInterval(i,1e3);},initUsageCounterManager:zw,initUserQueryMarkdownRenderer:Uw,initWatermarkRemover:Fw,subscribeModuleUpdates:function(e){const{adapter:t,siteId:n}=e;let r=Do().language;Ro(e=>{e.language&&e.language!==r&&(r=e.language,te(e.language),Aw.assistantMermaidRenderer?.refreshLocalizedTexts());const o=yo(e,n);o&&Aw.themeManager&&Aw.themeManager.setPresets(o.lightStyleId||"google-gradient",o.darkStyleId||"classic-dark");const i=wo(e,n);i&&Aw.modelLocker&&Aw.modelLocker.updateConfig(i),e&&Aw.scrollLockManager&&Aw.scrollLockManager.updateSettings(e);const a=t.getMarkdownFixerConfig(),s=Rw(e,n);a&&s?(Aw.markdownFixer||(Aw.markdownFixer=new rw(a)),Aw.markdownFixer.start()):Aw.markdownFixer?.stop();const l=vo(e,n),c=xo(e,n),d=ko(e,n).enabled;Aw.layoutManager?(Aw.layoutManager.updateConfig(l),Aw.layoutManager.updateUserQueryConfig(c),Aw.layoutManager.updateZenMode(d)):(l?.enabled||c?.enabled||d)&&(Aw.layoutManager=new Yv(t,l),l?.enabled&&Aw.layoutManager.apply(),c?.enabled&&Aw.layoutManager.updateUserQueryConfig(c),d&&Aw.layoutManager.updateZenMode(true)),!e||n!==Ir&&n!==Dr||(e.content?.watermarkRemoval?(Aw.watermarkRemover||(Aw.watermarkRemover=new _w),Aw.watermarkRemover.start()):Aw.watermarkRemover?.stop()),e?.tab&&(Aw.tabManager?Aw.tabManager.updateSettings(e.tab):(Aw.tabManager=new lw(t,e.tab),Aw.tabManager.start())),e?.usageMonitor&&(Aw.usageCounterManager?Aw.usageCounterManager.updateSettings(e.usageMonitor):(Aw.usageCounterManager=new fw(t,e.usageMonitor,n),Aw.usageCounterManager.start())),e?.readingHistory&&(Aw.readingHistoryManager?Aw.readingHistoryManager.updateSettings(e.readingHistory):e.readingHistory.persistence&&(Aw.readingHistoryManager=new aw(t,e.readingHistory),Aw.readingHistoryManager.startRecording())),e?.content&&(Aw.copyManager?Aw.copyManager.updateSettings(e.content):(Aw.copyManager=new Uv(e.content),e.content.formulaCopy&&Aw.copyManager.initFormulaCopy(),e.content.tableCopy&&Aw.copyManager.initTableCopy()),e.content.userQueryMarkdown?Aw.userQueryMarkdownRenderer?Aw.userQueryMarkdownRenderer.updateSettings(true):Aw.userQueryMarkdownRenderer=new Cw(t,true):Aw.userQueryMarkdownRenderer?.updateSettings(false)),Nw({adapter:t,settings:e}).catch(e=>{console.error("[Ophel] Assistant Mermaid renderer update failed:",e);}),e?.geminiEnterprise&&n===Dr&&Aw.policyRetryManager&&Aw.policyRetryManager.updateSettings(e.geminiEnterprise?.policyRetry||{enabled:false,maxRetries:3});});},syncPageTheme:Dw},Symbol.toStringTag,{value:"Module"})); })();