ai-helper-agent 2.4.4 → 2.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agent-store-BvS-vIQr.js","assets/chunk-CMxvf4Kt.js","assets/session-store-BrI5n6_W.js","assets/model-profiles-CtoST6-E.js","assets/i18n-8vdDPNQb.js","assets/pdf-DnVqBaAN.js","assets/__vite-browser-external-CM3Eme-n.js","assets/lib-YwkWjNcC.js","assets/jszip.min-DO6SOhXU.js","assets/dist-DuuG_8Br.js","assets/chat-export-CBdPUbRE.js","assets/dist-LQPh1k0y.js","assets/utils-BKYmnE_x.js"])))=>i.map(i=>d[i]);
2
- import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,i,l as a,n as o,r as s,s as c}from"./i18n-8vdDPNQb.js";import{A as l,C as u,E as d,F as f,G as p,I as m,N as h,P as g,R as _,S as v,T as y,W as b,b as x,c as S,d as C,i as w,k as T,r as E,u as D,w as O,y as k,z as A}from"./model-profiles-CtoST6-E.js";import{A as ee,C as te,E as ne,F as re,G as ie,H as j,J as ae,M as oe,N as se,P as ce,S as le,T as ue,V as de,Z as fe,_ as pe,a as M,b as me,c as N,d as he,f as P,g as ge,h as _e,i as ve,it as ye,j as be,k as xe,l as Se,lt as Ce,m as we,n as Te,nt as Ee,o as De,p as F,rt as Oe,s as ke,t as Ae,tt as je,u as Me,v as Ne,w as I,x as Pe,y as Fe}from"./session-store-BrI5n6_W.js";import{a as Ie,i as Le,n as Re,o as ze,r as Be,t as Ve}from"./version-hj8NxYZu.js";import{a as He,c as Ue,i as We,n as Ge,o as Ke,r as qe,s as Je}from"./agent-store-BvS-vIQr.js";import{C as L,S as Ye,T as Xe,_ as Ze,a as Qe,b as $e,c as R,d as et,f as z,g as tt,h as nt,i as rt,l as it,m as at,n as ot,o as st,p as B,r as ct,s as V,t as lt,u as ut,v as dt,w as ft,x as pt,y as mt}from"./utils-BKYmnE_x.js";var ht=ue.map(e=>e.id),gt=[...new Set([...p,`mcp`,`knowledge`])],_t=[{labelKey:`presetMode.preciseLabel`,tipKey:`presetMode.preciseTip`,temp:.2,topP:1},{labelKey:`presetMode.generalLabel`,tipKey:`presetMode.generalTip`,temp:.45,topP:.9},{labelKey:`presetMode.divergentLabel`,tipKey:`presetMode.divergentTip`,temp:.65,topP:.9},{labelKey:`presetMode.creativeLabel`,tipKey:`presetMode.creativeTip`,temp:.9,topP:.9}];n(`zh`,{contextUsage:{compactionInjection:`[上下文摘要|压缩了{count}条历史]`}}),n(`en`,{contextUsage:{compactionInjection:`[Context Summary | {count} messages compacted]`}});var vt=2e3,yt=.7,bt=1e3;function xt(e,{isolateChat:t=!0,maxMemoryMessages:n=null,compaction:r=null,historyBudget:i=1/0,currentMessage:a=null}={}){let o=a||{role:`user`,content:``};if(!t)return{messages:[o],keptHistory:[],compactionApplied:!1,trimmedCount:0,historySummaryText:null};let s=Array.isArray(e)?e:[],c=!1,u=-1;r&&r.summary&&r.upToMessageId&&(u=s.findIndex(e=>e.messageId===r.upToMessageId),c=u>=0);let f=s,p=s.map((e,t)=>t);n&&n>0&&s.length>n&&(f=s.slice(s.length-n),p=p.slice(s.length-n));let m=[];for(let e=0;e<f.length;e++)c&&p[e]<=u||m.push(f[e]);let h=[],g=y([o]);for(let e=m.length-1;e>=0;e--){let t=m[e],n=y([{...t,content:_(t.content)}]);if(g+n<=i)h.unshift(t),g+=n;else break}let v=null,b=m.length-h.length;if(b>0){let e=l(m.slice(0,b));e&&(v=d(e)>bt?e.substring(0,bt*4)+`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agent-store-D-jYf94_.js","assets/chunk-CMxvf4Kt.js","assets/session-store-BBIdbyV_.js","assets/model-profiles-CtoST6-E.js","assets/i18n-8vdDPNQb.js","assets/pdf-DnVqBaAN.js","assets/__vite-browser-external-CM3Eme-n.js","assets/lib-YwkWjNcC.js","assets/jszip.min-DO6SOhXU.js","assets/dist-DuuG_8Br.js","assets/chat-export-B5n-Qevt.js","assets/dist-LQPh1k0y.js","assets/utils-BIworoAB.js"])))=>i.map(i=>d[i]);
2
+ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,i,l as a,n as o,r as s,s as c}from"./i18n-8vdDPNQb.js";import{A as l,C as u,E as d,F as f,G as p,I as m,N as h,P as g,R as _,S as v,T as y,W as b,b as x,c as S,d as C,i as w,k as T,r as E,u as D,w as O,y as k,z as A}from"./model-profiles-CtoST6-E.js";import{A as ee,C as te,E as ne,F as re,H as ie,K as j,M as ae,N as oe,P as se,Q as ce,S as le,T as ue,U as de,Y as fe,_ as pe,a as M,at as me,b as N,c as he,d as P,f as ge,g as _e,h as ve,i as ye,it as be,j as xe,k as Se,l as Ce,m as we,n as Te,nt as Ee,o as De,p as F,rt as Oe,s as ke,t as Ae,u as je,ut as Me,v as Ne,w as I,x as Pe,y as Fe}from"./session-store-BBIdbyV_.js";import{a as Ie,i as Le,n as Re,o as ze,r as Be,t as Ve}from"./version-Djv0o0pB.js";import{a as He,c as Ue,i as We,n as Ge,o as Ke,r as qe,s as Je}from"./agent-store-D-jYf94_.js";import{C as L,S as Ye,T as Xe,_ as Ze,a as Qe,b as $e,c as R,d as et,f as z,g as tt,h as nt,i as rt,l as it,m as at,n as ot,o as st,p as B,r as ct,s as V,t as lt,u as ut,v as dt,w as ft,x as pt,y as mt}from"./utils-BIworoAB.js";var ht=ue.map(e=>e.id),gt=[...new Set([...p,`mcp`,`knowledge`])],_t=[{labelKey:`presetMode.preciseLabel`,tipKey:`presetMode.preciseTip`,temp:.2,topP:1},{labelKey:`presetMode.generalLabel`,tipKey:`presetMode.generalTip`,temp:.45,topP:.9},{labelKey:`presetMode.divergentLabel`,tipKey:`presetMode.divergentTip`,temp:.65,topP:.9},{labelKey:`presetMode.creativeLabel`,tipKey:`presetMode.creativeTip`,temp:.9,topP:.9}];n(`zh`,{contextUsage:{compactionInjection:`[上下文摘要|压缩了{count}条历史]`}}),n(`en`,{contextUsage:{compactionInjection:`[Context Summary | {count} messages compacted]`}});var vt=2e3,yt=.7,bt=1e3;function xt(e,{isolateChat:t=!0,maxMemoryMessages:n=null,compaction:r=null,historyBudget:i=1/0,currentMessage:a=null}={}){let o=a||{role:`user`,content:``};if(!t)return{messages:[o],keptHistory:[],compactionApplied:!1,trimmedCount:0,historySummaryText:null};let s=Array.isArray(e)?e:[],c=!1,u=-1;r&&r.summary&&r.upToMessageId&&(u=s.findIndex(e=>e.messageId===r.upToMessageId),c=u>=0);let f=s,p=s.map((e,t)=>t);n&&n>0&&s.length>n&&(f=s.slice(s.length-n),p=p.slice(s.length-n));let m=[];for(let e=0;e<f.length;e++)c&&p[e]<=u||m.push(f[e]);let h=[],g=y([o]);for(let e=m.length-1;e>=0;e--){let t=m[e],n=y([{...t,content:_(t.content)}]);if(g+n<=i)h.unshift(t),g+=n;else break}let v=null,b=m.length-h.length;if(b>0){let e=l(m.slice(0,b));e&&(v=d(e)>bt?e.substring(0,bt*4)+`
3
3
  ...[历史摘要已截断]`:e)}return{messages:[...h,o],keptHistory:h,compactionApplied:c,trimmedCount:b,historySummaryText:v}}function St(e,t){return!t||!t.summary?e:`${e}\n\n${r(`contextUsage.compactionInjection`,{count:t.compressedCount||0})}\n${t.summary}`}function Ct(e,t,n,r){return t?.compactionApplied&&n?.summary?e[0]={...e[0],content:St(e[0].content,n)}:n?.summary&&r?.warn(`[SidePanel] contextCompaction invalid (upToMessageId not found), ignored this send`),e}function wt({model:e,customModelMap:t=null,systemPromptText:n=``,toolCount:r=0,history:i=[],inputText:a=``,maxMemoryMessages:o=null,compaction:s=null,isolateChat:c=!0,userConfiguredWindow:l=0}={}){let f=h(e,l,t),p=f-d(n)-v-vt,m=Math.floor(Math.max(p,0)*yt),g={role:`user`,content:a},_=c?s:null,b=xt(i,{isolateChat:c,maxMemoryMessages:o,compaction:_,historyBudget:m,currentMessage:g}),x=d(b.compactionApplied?St(n,_):n),S=r*200,C=y(b.keptHistory),w=a&&a.trim()?y([g]):0,T=x+S+C+w,E=u(T,f);return{usedTokens:T,contextWindow:f,ratio:f>0?T/f:0,level:E.level,breakdown:{system:x,tools:S,history:C,input:w,outputReserve:v,safetyMargin:vt,selectedCount:b.keptHistory.length,totalCount:i.length,trimmedCount:b.trimmedCount,compactionApplied:b.compactionApplied,compactionInvalid:!!(_&&_.summary&&!b.compactionApplied),historyBudget:m}}}function Tt(e,{maxMemoryMessages:t=null,compaction:n=null}={}){let r=xt(e,{isolateChat:!0,maxMemoryMessages:t,compaction:n,historyBudget:1/0,currentMessage:null}),i=[],a=!!(r.compactionApplied&&n?.summary);a&&i.push({role:`user`,content:`【已有摘要】\n${n.summary}`});for(let e of r.keptHistory){let t=_(e.content);i.push({role:e.role,content:typeof t==`string`?t:JSON.stringify(t??``)||``})}return{material:i,includedCount:r.keptHistory.length,hasOldSummary:a}}function Et(e){if(!e||!e.trim()||e.trim()==`/`)return;let t=e.trim(),n=F.inputHistory.indexOf(t);n!==-1&&F.inputHistory.splice(n,1),F.inputHistory.push(t),F.inputHistory.length>20&&F.inputHistory.shift(),Dt()}function Dt(){try{chrome.storage.local.set({inputHistory:F.inputHistory}),a.debug(`[SidePanel] input history saved,count:`,F.inputHistory.length)}catch(e){a.error(`[SidePanel] saveinput history failed:`,e)}}var Ot=[`workspace`,`bookmark`,`toc`,`search`,`schedule`],kt=`.workspace-panel.expanded, .bookmark-panel.expanded, .message-toc-panel.expanded, .search-panel.expanded, .schedule-panel.open`,At=null,jt=null;function Mt(){if(At)return At;At=document.createElement(`div`),At.className=`side-rail`,At.id=`sideRail`,At.innerHTML=Ot.map(e=>`<div class="side-rail-slot" data-slot="${e}"></div>`).join(``),document.body.appendChild(At),Pt();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(Pt).observe(e),window.addEventListener(`resize`,Pt),At}function Nt(e){return(At||Mt()).querySelector(`.side-rail-slot[data-slot="${e}"]`)}function Pt(){if(!At)return;let e=document.getElementById(`chatContainer`);if(!e)return;let t=e.getBoundingClientRect(),n=window.innerHeight;At.style.top=`${Math.max(0,Math.round(t.top))}px`,At.style.bottom=`${Math.max(0,Math.round(n-t.bottom))}px`,Ft()}function Ft(){jt&&clearTimeout(jt),jt=setTimeout(()=>{jt=null,document.querySelectorAll(kt).forEach(rt)},120)}n(`zh`,{messageToc:{toggleTitle:`显示目录(H{count}个标题)`,title:`目录`,headingCount:`{count} 个`}}),n(`en`,{messageToc:{toggleTitle:`Show table of contents (H{count} headings)`,title:`Contents`,headingCount:`{count}`}});function It(){document.addEventListener(`mouseover`,Lt,!0),document.addEventListener(`mouseout`,Rt,!0),a.debug(`[SidePanel] messagedirectory featureinitializing`)}function Lt(e){if(!(e.target instanceof Element))return;if(e.target.closest(`.message-toc-container`)){F.isMouseOverToc=!0;return}let t=e.target.closest(`.message.assistant`),n=e.target.closest(`.workspace-preview-markdown`);if(!t&&!n)return;let r=t||n,i=r.querySelectorAll(`.markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4, .markdown-body h5, .markdown-body h6`);if(i.length===0){Bt();return}zt(r,i)}function Rt(e){if(!(e.target instanceof Element))return;if(e.target.closest(`.message-toc-container`)){F.isMouseOverToc=!1,F.tocHideTimer&&=(clearTimeout(F.tocHideTimer),null);return}let t=e.target.closest(`.message.assistant`),n=e.target.closest(`.workspace-preview-markdown`);if(!t&&!n)return;let r=e.relatedTarget;r&&(r.closest(`.message-toc-container`)||r.closest(`.message.assistant`)||r.closest(`.workspace-preview-markdown`))||F.isMouseOverToc||(F.tocHideTimer&&clearTimeout(F.tocHideTimer),F.tocHideTimer=setTimeout(()=>{F.isMouseOverToc||Bt(),F.tocHideTimer=null},800))}function zt(e,t){let n=Array.from(t);F.messageTocContainer&&Bt(),n.forEach((e,t)=>{e.id||=`toc-heading-${Date.now()}-${t}`});let i=document.createElement(`div`);i.className=`message-toc-container`,i.dataset.headingsCount=n.length;let a=0,o=n.map(e=>{let t=parseInt(e.tagName.charAt(1)),n=e.textContent.trim(),r=n.length>30?n.substring(0,30)+`...`:n,i=`H${t}`;return a++,`
4
4
  <li class="message-toc-item level-${t}"
5
5
  data-target="${e.id}"
@@ -24,7 +24,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,i,l as a,n a
24
24
  </ul>
25
25
  </div>
26
26
  </div>
27
- `,Nt(`toc`).appendChild(i),F.messageTocContainer=i;let s=i.querySelector(`.message-toc-toggle`),c=i.querySelector(`.message-toc-panel`);s.addEventListener(`mouseenter`,()=>{c.classList.add(`expanded`),rt(c)}),s.addEventListener(`click`,()=>{c.classList.toggle(`expanded`)?rt(c):$e(c)}),c.addEventListener(`mouseenter`,()=>{c.classList.add(`expanded`)}),i.querySelectorAll(`.message-toc-item`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.target,n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),n.classList.add(`toc-highlight`),setTimeout(()=>{n.classList.remove(`toc-highlight`)},1500))})})}function Bt(){F.tocHideTimer&&=(clearTimeout(F.tocHideTimer),null),F.messageTocContainer&&=(F.messageTocContainer.remove(),null)}var Vt=`completedSessionIds`;async function Ht(){try{let e=(await chrome.storage.local.get([Vt]))[Vt]||[];F.completedSessionIds=new Set(e)}catch(e){a.warn(`[SessionManager] restore completedSessionIds failed:`,e)}}async function Ut(){try{await chrome.storage.local.set({[Vt]:Array.from(F.completedSessionIds)})}catch(e){a.warn(`[SessionManager] persist completedSessionIds failed:`,e)}}async function Wt(e){e&&e!==F.activeSessionId&&(F.completedSessionIds.has(e)||(F.completedSessionIds.add(e),await Ut(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))))}async function Gt(e){e&&F.completedSessionIds.has(e)&&(F.completedSessionIds.delete(e),await Ut(),document.dispatchEvent(new CustomEvent(`generating-state-changed`)))}async function Kt(){return N()}async function qt(){return he()}async function Jt(){return ve()}async function Yt(e){return P(e)}async function Xt(e){let t=await M(e);return F.completedSessionIds.has(e)&&(F.completedSessionIds.delete(e),await Ut()),t}async function Zt(e,t){return Se(e,t)}async function Qt(e){return Me(e)}async function $t(){return Te()}async function en(e){return ke(e)}async function tn(e,t){return Ae(e,t)}async function nn(e,t=null){return De(e,t)}n(`zh`,{toolPanel:{agentRestrictedBanner:`当前 Agent 限制了可用工具,部分工具已禁用`,noMatch:`没有匹配的工具`,enabledCount:`已启用 {enabled}/{total} 个工具`,toolsEnabled:`工具已启用`,allToolsDisabled:`所有工具已禁用`,toggleBtnEnabled:`禁用所有工具`,toggleBtnDisabled:`启用所有工具`,mcpServiceToolCount:`{count} 个工具`,mcpServiceExpand:`展开/收起工具列表`,mcpExcludedByAgent:`已被当前助手排除,可在助手编辑中调整`,categorySelectAllHint:`对该分类下可见项全选/取消全选`,stateOn:`已开启`,stateOff:`已关闭`,stateLine:`{name}:{state}`}}),n(`en`,{toolPanel:{agentRestrictedBanner:`Current agent has restricted available tools, some tools are disabled`,noMatch:`No matching tools`,enabledCount:`{enabled}/{total} tools enabled`,toolsEnabled:`Tools enabled`,allToolsDisabled:`All tools disabled`,toggleBtnEnabled:`Disable all tools`,toggleBtnDisabled:`Enable all tools`,mcpServiceToolCount:`{count} tools`,mcpServiceExpand:`Show/hide tool list`,mcpExcludedByAgent:`Excluded by current assistant; adjust in assistant editor`,categorySelectAllHint:`Select/deselect all visible items in this category`,stateOn:`On`,stateOff:`Off`,stateLine:`{name}: {state}`}});var rn=[],an=[];function on(e){if(!e)return``;let t=`tool.${e.id}`,n=r(t);return n===t?e.description||``:n}function sn(e){if(!e)return``;let t=e.description||``;if(t.startsWith(`[MCP:`)){let e=t.indexOf(`]`);e!==-1&&(t=t.slice(e+1).trim())}return t===(e.name||``)?``:t}async function cn(){try{let e=await chrome.runtime.sendMessage({type:`GET_MCP_TOOLS`});if(e?.success&&e.tools)return rn=e.tools,rn}catch{}try{return rn=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[],rn}catch{return rn=[],[]}}async function ln(){try{an=(await chrome.storage.local.get([`ragTools`])).ragTools||[]}catch{an=[]}return an}async function un(){let e=`agentMcpClosedServers_${F.activeAgentId||`default`}`;try{F.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}catch{F.mcpClosedServers=[]}try{let{getAgent:e}=await I(async()=>{let{getAgent:e}=await import(`./agent-store-BvS-vIQr.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3,4])),t=F.activeAgentId?await e(F.activeAgentId):null;F.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null}catch{}}var dn=!1,fn=!0;chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{dn=e.enableToolPreselect===!0,fn=e.toolConfirmationEnabled!==!1,Rn()}),chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`)return;let n=!1;e.mcpTools&&(rn=e.mcpTools.newValue||[],a.debug(`[SidePanel] MCP toolcache updated:`,rn.length,``),n=!0),e.ragTools&&(an=e.ragTools.newValue||[],a.debug(`[SidePanel] RAG toolcache updated:`,an.length),n=!0),e.mcpEnabled&&(pn=e.mcpEnabled.newValue===!0,a.debug(`[SidePanel] MCP globaltoggle changed:`,pn),n=!0),e.skillsEnabled&&(mn=e.skillsEnabled.newValue!==!1,a.debug(`[SidePanel] Skill global toggle changed:`,mn),n=!0),e.enableImageInput&&(hn=e.enableImageInput.newValue===!0,a.debug(`[SidePanel] 图片识别全局开关变更:`,hn),n=!0);let r=!1;e.enableToolPreselect&&(dn=e.enableToolPreselect.newValue===!0,r=!0),e.toolConfirmationEnabled&&(fn=e.toolConfirmationEnabled.newValue!==!1,r=!0),r&&Rn(),n&&(document.getElementById(`toolsPopupOverlay`)?.classList.contains(`show`)&&(Nn(),Pn(),Tn()),Ln())}),cn().then(()=>Ln()),ln().then(()=>Ln());var pn=!1,mn=!0,hn=!1;chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`enableImageInput`],e=>{pn=e.mcpEnabled===!0,mn=e.skillsEnabled!==!1,hn=e.enableImageInput===!0,Ln()});function gn(){let e=[...b,...an],t=F.activeAgentToolIds,n=e;if(t!=null){let r=new Set(t);n=e.filter(e=>r.has(e.id))}return mn||(n=n.filter(e=>e.id!==`agent_skill`)),F.agentPlatform?.connected!==!0&&(n=n.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),hn||(n=n.filter(e=>e.id!==`read_image`)),n}function _n(){if(!pn||F.agentPlatform?.connected!==!0)return[];let e=new Map;return rn.forEach(t=>{let n=t.serverId||`unknown`;e.has(n)||e.set(n,{serverId:n,serverName:t.serverName||n,tools:[],toolCount:0});let r=e.get(n);r.tools.push(t),r.toolCount++}),Array.from(e.values())}function vn(e){return Array.isArray(F.mcpClosedServers)&&F.mcpClosedServers.includes(e)}function yn(e){return Array.isArray(F.activeAgentMcpExcludedServerIds)&&F.activeAgentMcpExcludedServerIds.includes(e)}function bn(e){return!vn(e)&&!yn(e)}function xn(){if(F.currentCategory!==`all`&&F.currentCategory!==`mcp`)return[];let e=_n();if(F.currentSearch){let t=F.currentSearch;e=e.filter(e=>(e.serverName||``).toLowerCase().includes(t)||(e.serverId||``).toLowerCase().includes(t)||e.tools.some(e=>(e.name||``).toLowerCase().includes(t)||on(e).toLowerCase().includes(t)))}return e}function Sn(e,t){Array.isArray(F.mcpClosedServers)||(F.mcpClosedServers=[]);let n=F.mcpClosedServers.indexOf(e);t?n>-1&&F.mcpClosedServers.splice(n,1):n===-1&&F.mcpClosedServers.push(e)}async function Cn(){let e=document.getElementById(`toolsPopupOverlay`);if(!e)return;F.currentCategory=`all`,F.currentSearch=``;let t=document.getElementById(`toolsSearchInput`);t&&(t.value=``),await cn(),await ln(),await un(),Nn(),Pn(),chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{let t=document.getElementById(`toolsPreselectToggle`);t&&(t.checked=e.enableToolPreselect===void 0?!1:e.enableToolPreselect);let n=document.getElementById(`toolConfirmToggle`);n&&(n.checked=e.toolConfirmationEnabled===void 0?!0:e.toolConfirmationEnabled)}),document.querySelectorAll(`.category-btn`).forEach(e=>{e.classList.remove(`active`),e.classList.contains(`category-all`)?(e.classList.add(`active`),e.style.background=`linear-gradient(135deg, var(--brand-500) 0%, var(--brand-accent) 100%)`,e.style.color=`var(--text-on-brand)`,e.style.borderColor=`transparent`):(e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`,e.style.borderColor=`var(--border-subtle)`)}),Tn(),e.classList.add(`show`),a.debug(`[SidePanel] opentool popup`)}function wn(){let e=document.getElementById(`toolsPopupOverlay`);e&&(document.querySelectorAll(`.category-btn`).forEach(e=>{e.classList.remove(`active`),e.style.background=``,e.style.color=``,e.style.borderColor=``}),e.classList.remove(`show`),a.debug(`[SidePanel] closetool popup`))}function Tn(){let e=document.getElementById(`toolsPopupList`);if(!e)return;e.innerHTML=``;let t=gn();if(F.activeAgentToolIds!==null&&F.activeAgentToolIds!==void 0){let t=document.createElement(`div`);t.className=`popup-tool-agent-banner`,t.innerHTML=`<span>${r(`toolPanel.agentRestrictedBanner`)}</span>`,e.appendChild(t)}let n={};t.forEach(e=>{if(F.currentCategory!==`all`&&e.category!==F.currentCategory)return;if(F.currentSearch){let t=e.name.toLowerCase().includes(F.currentSearch),n=on(e).toLowerCase().includes(F.currentSearch);if(!t&&!n)return}let t=e.category||`other`;n[t]||(n[t]=[]),n[t].push(e)});let i=xn();if(gt.forEach(a=>{let o=a===`mcp`,s=n[a]||[],c=o?i:[];if(o?c.length===0:s.length===0)return;let l;if(o)l=`${c.filter(e=>bn(e.serverId)).length}/${c.length}`;else{let e=t.filter(e=>e.category===a);l=`${e.filter(e=>F.enabledTools.includes(e.id)).length}/${e.length}`}let u=document.createElement(`div`);u.className=`popup-tool-category-group`,u.dataset.category=a;let d=document.createElement(`div`);d.className=`popup-tool-category`,d.dataset.category=a;let f=F.collapsedCategories[a]||!1;d.innerHTML=`
27
+ `,Nt(`toc`).appendChild(i),F.messageTocContainer=i;let s=i.querySelector(`.message-toc-toggle`),c=i.querySelector(`.message-toc-panel`);s.addEventListener(`mouseenter`,()=>{c.classList.add(`expanded`),rt(c)}),s.addEventListener(`click`,()=>{c.classList.toggle(`expanded`)?rt(c):$e(c)}),c.addEventListener(`mouseenter`,()=>{c.classList.add(`expanded`)}),i.querySelectorAll(`.message-toc-item`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.target,n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),n.classList.add(`toc-highlight`),setTimeout(()=>{n.classList.remove(`toc-highlight`)},1500))})})}function Bt(){F.tocHideTimer&&=(clearTimeout(F.tocHideTimer),null),F.messageTocContainer&&=(F.messageTocContainer.remove(),null)}var Vt=`completedSessionIds`;async function Ht(){try{let e=(await chrome.storage.local.get([Vt]))[Vt]||[];F.completedSessionIds=new Set(e)}catch(e){a.warn(`[SessionManager] restore completedSessionIds failed:`,e)}}async function Ut(){try{await chrome.storage.local.set({[Vt]:Array.from(F.completedSessionIds)})}catch(e){a.warn(`[SessionManager] persist completedSessionIds failed:`,e)}}async function Wt(e){e&&e!==F.activeSessionId&&(F.completedSessionIds.has(e)||(F.completedSessionIds.add(e),await Ut(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))))}async function Gt(e){e&&F.completedSessionIds.has(e)&&(F.completedSessionIds.delete(e),await Ut(),document.dispatchEvent(new CustomEvent(`generating-state-changed`)))}async function Kt(){return he()}async function qt(){return P()}async function Jt(){return ye()}async function Yt(e){return ge(e)}async function Xt(e){let t=await M(e);return F.completedSessionIds.has(e)&&(F.completedSessionIds.delete(e),await Ut()),t}async function Zt(e,t){return Ce(e,t)}async function Qt(e){return je(e)}async function $t(){return Te()}async function en(e){return ke(e)}async function tn(e,t){return Ae(e,t)}async function nn(e,t=null){return De(e,t)}n(`zh`,{toolPanel:{agentRestrictedBanner:`当前 Agent 限制了可用工具,部分工具已禁用`,noMatch:`没有匹配的工具`,enabledCount:`已启用 {enabled}/{total} 个工具`,toolsEnabled:`工具已启用`,allToolsDisabled:`所有工具已禁用`,toggleBtnEnabled:`禁用所有工具`,toggleBtnDisabled:`启用所有工具`,mcpServiceToolCount:`{count} 个工具`,mcpServiceExpand:`展开/收起工具列表`,mcpExcludedByAgent:`已被当前助手排除,可在助手编辑中调整`,categorySelectAllHint:`对该分类下可见项全选/取消全选`,stateOn:`已开启`,stateOff:`已关闭`,stateLine:`{name}:{state}`}}),n(`en`,{toolPanel:{agentRestrictedBanner:`Current agent has restricted available tools, some tools are disabled`,noMatch:`No matching tools`,enabledCount:`{enabled}/{total} tools enabled`,toolsEnabled:`Tools enabled`,allToolsDisabled:`All tools disabled`,toggleBtnEnabled:`Disable all tools`,toggleBtnDisabled:`Enable all tools`,mcpServiceToolCount:`{count} tools`,mcpServiceExpand:`Show/hide tool list`,mcpExcludedByAgent:`Excluded by current assistant; adjust in assistant editor`,categorySelectAllHint:`Select/deselect all visible items in this category`,stateOn:`On`,stateOff:`Off`,stateLine:`{name}: {state}`}});var rn=[],an=[];function on(e){if(!e)return``;let t=`tool.${e.id}`,n=r(t);return n===t?e.description||``:n}function sn(e){if(!e)return``;let t=e.description||``;if(t.startsWith(`[MCP:`)){let e=t.indexOf(`]`);e!==-1&&(t=t.slice(e+1).trim())}return t===(e.name||``)?``:t}async function cn(){try{let e=await chrome.runtime.sendMessage({type:`GET_MCP_TOOLS`});if(e?.success&&e.tools)return rn=e.tools,rn}catch{}try{return rn=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[],rn}catch{return rn=[],[]}}async function ln(){try{an=(await chrome.storage.local.get([`ragTools`])).ragTools||[]}catch{an=[]}return an}async function un(){let e=`agentMcpClosedServers_${F.activeAgentId||`default`}`;try{F.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}catch{F.mcpClosedServers=[]}try{let{getAgent:e}=await I(async()=>{let{getAgent:e}=await import(`./agent-store-D-jYf94_.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3,4])),t=F.activeAgentId?await e(F.activeAgentId):null;F.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null}catch{}}var dn=!1,fn=!0;chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{dn=e.enableToolPreselect===!0,fn=e.toolConfirmationEnabled!==!1,Rn()}),chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`)return;let n=!1;e.mcpTools&&(rn=e.mcpTools.newValue||[],a.debug(`[SidePanel] MCP toolcache updated:`,rn.length,``),n=!0),e.ragTools&&(an=e.ragTools.newValue||[],a.debug(`[SidePanel] RAG toolcache updated:`,an.length),n=!0),e.mcpEnabled&&(pn=e.mcpEnabled.newValue===!0,a.debug(`[SidePanel] MCP globaltoggle changed:`,pn),n=!0),e.skillsEnabled&&(mn=e.skillsEnabled.newValue!==!1,a.debug(`[SidePanel] Skill global toggle changed:`,mn),n=!0),e.enableImageInput&&(hn=e.enableImageInput.newValue===!0,a.debug(`[SidePanel] 图片识别全局开关变更:`,hn),n=!0);let r=!1;e.enableToolPreselect&&(dn=e.enableToolPreselect.newValue===!0,r=!0),e.toolConfirmationEnabled&&(fn=e.toolConfirmationEnabled.newValue!==!1,r=!0),r&&Rn(),n&&(document.getElementById(`toolsPopupOverlay`)?.classList.contains(`show`)&&(Nn(),Pn(),Tn()),Ln())}),cn().then(()=>Ln()),ln().then(()=>Ln());var pn=!1,mn=!0,hn=!1;chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`enableImageInput`],e=>{pn=e.mcpEnabled===!0,mn=e.skillsEnabled!==!1,hn=e.enableImageInput===!0,Ln()});function gn(){let e=[...b,...an],t=F.activeAgentToolIds,n=e;if(t!=null){let r=new Set(t);n=e.filter(e=>r.has(e.id))}return mn||(n=n.filter(e=>e.id!==`agent_skill`)),F.agentPlatform?.connected!==!0&&(n=n.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),hn||(n=n.filter(e=>e.id!==`read_image`)),n}function _n(){if(!pn||F.agentPlatform?.connected!==!0)return[];let e=new Map;return rn.forEach(t=>{let n=t.serverId||`unknown`;e.has(n)||e.set(n,{serverId:n,serverName:t.serverName||n,tools:[],toolCount:0});let r=e.get(n);r.tools.push(t),r.toolCount++}),Array.from(e.values())}function vn(e){return Array.isArray(F.mcpClosedServers)&&F.mcpClosedServers.includes(e)}function yn(e){return Array.isArray(F.activeAgentMcpExcludedServerIds)&&F.activeAgentMcpExcludedServerIds.includes(e)}function bn(e){return!vn(e)&&!yn(e)}function xn(){if(F.currentCategory!==`all`&&F.currentCategory!==`mcp`)return[];let e=_n();if(F.currentSearch){let t=F.currentSearch;e=e.filter(e=>(e.serverName||``).toLowerCase().includes(t)||(e.serverId||``).toLowerCase().includes(t)||e.tools.some(e=>(e.name||``).toLowerCase().includes(t)||on(e).toLowerCase().includes(t)))}return e}function Sn(e,t){Array.isArray(F.mcpClosedServers)||(F.mcpClosedServers=[]);let n=F.mcpClosedServers.indexOf(e);t?n>-1&&F.mcpClosedServers.splice(n,1):n===-1&&F.mcpClosedServers.push(e)}async function Cn(){let e=document.getElementById(`toolsPopupOverlay`);if(!e)return;F.currentCategory=`all`,F.currentSearch=``;let t=document.getElementById(`toolsSearchInput`);t&&(t.value=``),await cn(),await ln(),await un(),Nn(),Pn(),chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{let t=document.getElementById(`toolsPreselectToggle`);t&&(t.checked=e.enableToolPreselect===void 0?!1:e.enableToolPreselect);let n=document.getElementById(`toolConfirmToggle`);n&&(n.checked=e.toolConfirmationEnabled===void 0?!0:e.toolConfirmationEnabled)}),document.querySelectorAll(`.category-btn`).forEach(e=>{e.classList.remove(`active`),e.classList.contains(`category-all`)?(e.classList.add(`active`),e.style.background=`linear-gradient(135deg, var(--brand-500) 0%, var(--brand-accent) 100%)`,e.style.color=`var(--text-on-brand)`,e.style.borderColor=`transparent`):(e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`,e.style.borderColor=`var(--border-subtle)`)}),Tn(),e.classList.add(`show`),a.debug(`[SidePanel] opentool popup`)}function wn(){let e=document.getElementById(`toolsPopupOverlay`);e&&(document.querySelectorAll(`.category-btn`).forEach(e=>{e.classList.remove(`active`),e.style.background=``,e.style.color=``,e.style.borderColor=``}),e.classList.remove(`show`),a.debug(`[SidePanel] closetool popup`))}function Tn(){let e=document.getElementById(`toolsPopupList`);if(!e)return;e.innerHTML=``;let t=gn();if(F.activeAgentToolIds!==null&&F.activeAgentToolIds!==void 0){let t=document.createElement(`div`);t.className=`popup-tool-agent-banner`,t.innerHTML=`<span>${r(`toolPanel.agentRestrictedBanner`)}</span>`,e.appendChild(t)}let n={};t.forEach(e=>{if(F.currentCategory!==`all`&&e.category!==F.currentCategory)return;if(F.currentSearch){let t=e.name.toLowerCase().includes(F.currentSearch),n=on(e).toLowerCase().includes(F.currentSearch);if(!t&&!n)return}let t=e.category||`other`;n[t]||(n[t]=[]),n[t].push(e)});let i=xn();if(gt.forEach(a=>{let o=a===`mcp`,s=n[a]||[],c=o?i:[];if(o?c.length===0:s.length===0)return;let l;if(o)l=`${c.filter(e=>bn(e.serverId)).length}/${c.length}`;else{let e=t.filter(e=>e.category===a);l=`${e.filter(e=>F.enabledTools.includes(e.id)).length}/${e.length}`}let u=document.createElement(`div`);u.className=`popup-tool-category-group`,u.dataset.category=a;let d=document.createElement(`div`);d.className=`popup-tool-category`,d.dataset.category=a;let f=F.collapsedCategories[a]||!1;d.innerHTML=`
28
28
  <span class="category-expand-icon">${f?`▶`:`▼`}</span>
29
29
  <span class="category-name">${r(`toolCategory.`+a)}</span>
30
30
  <span class="category-count">${l}</span>
@@ -120,7 +120,7 @@ Ctrl/Cmd+click to copy rich-text table`,downloadExcel:`Download Excel`,exportTab
120
120
  <html>
121
121
  <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
122
122
  <body style="margin:0;padding:0;overflow:auto;">${t}</body>
123
- </html>`}function Cs(e){a.debug(`[SidePanel] show UI prototype preview:`,e),_s=e,Us();let t=document.getElementById(`prototypeTitle`),n=document.getElementById(`prototypeDescription`),i=document.getElementById(`prototypeIframe`),o=document.getElementById(`prototypeLocalOpenBtn`);t&&(t.textContent=e.title||r(`prototype.previewTitle`)),n&&(n.textContent=e.description||``,n.style.display=e.description?`block`:`none`),i&&e.html&&(i.srcdoc=Ss(e.html)),o&&(e.localPath?(o.style.display=``,o.dataset.path=e.localPath):o.style.display=`none`);let s=document.getElementById(`prototypeOverlay`);s&&s.classList.add(`show`),a.debug(`[SidePanel] UI prototype previewpopupshown`)}function ws(){let e=document.getElementById(`prototypeOverlay`);e&&e.classList.remove(`show`);let t=document.getElementById(`prototypeIframe`);t&&(t.srcdoc=``),_s=null,a.debug(`[SidePanel] UI prototype previewpopuphidden`)}function Ts(){if(!_s)return;let e=_s.id,t=_s.title||r(`uiProto.defaultTitle`);ws();let n=document.getElementById(`userInput`);n&&(n.value=r(`uiProto.optimizePrompt`,{id:e,title:t}),n.focus(),n.style.height=`auto`,n.style.height=n.scrollHeight+`px`),a.debug(`[SidePanel] continue optimizeprototype:`,e)}function Es(){if(!_s||!_s.html){a.error(`[SidePanel] no downloadable prototype`);return}let e=Ss(_s.html),t=new Blob([e],{type:`text/html`}),n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=(_s.title||`prototype`).replace(/[^a-zA-Z0-9\u4e00-\u9fa5_-]/g,`_`)+`.html`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n),a.debug(`[SidePanel] prototype down loaded:`,r.download)}function Ds(){if(!_s||!_s.html){a.error(`[SidePanel] no has can open prototype`);return}let e=Ss(_s.html),t=`data:text/html;base64,`+btoa(unescape(encodeURIComponent(e)));chrome.tabs.create({url:t,active:!0}),a.debug(`[SidePanel] prototype in newlabelpageopen`)}async function Os(e){try{let t=await Ee(e);if(!t){a.error(`[SidePanel] not foundprototype:`,e);return}Cs(t)}catch(e){a.error(`[SidePanel] load prototype failed:`,e)}}async function ks(e){try{let t=await Ee(e);if(!t){a.error(`[SidePanel] not foundprototype (autoopen):`,e);return}_s=t,Ds(),a.debug(`[SidePanel] prototype inbrowserlabelpageautoopen:`,t.title)}catch(e){a.error(`[SidePanel] autoopenprototype failed:`,e)}}async function As(){let e=document.getElementById(`prototypeLibraryList`),t=document.getElementById(`prototypeLibraryModal`);if(!(!e||!t)){e.innerHTML=`<div class="prototype-library-empty">${r(`common.loading`)}</div>`;try{let e=await Oe();js(e),Ms(e)}catch(t){a.error(`[SidePanel] loadprototype page library failed:`,t),e.innerHTML=`<div class="prototype-library-empty">${r(`uiProto.loadFailed`)}</div>`}t.classList.add(`show`),a.debug(`[SidePanel] prototype page libraryshown`)}}function js(e){let t=document.getElementById(`prototypeLibraryList`);t&&(e.length===0?t.innerHTML=`<div class="prototype-library-empty">${r(`prototype.empty`)}</div>`:(t.innerHTML=e.map(e=>{let t=e.id.replace(`proto_`,``).slice(-6);return`
123
+ </html>`}function Cs(e){a.debug(`[SidePanel] show UI prototype preview:`,e),_s=e,Us();let t=document.getElementById(`prototypeTitle`),n=document.getElementById(`prototypeDescription`),i=document.getElementById(`prototypeIframe`),o=document.getElementById(`prototypeLocalOpenBtn`);t&&(t.textContent=e.title||r(`prototype.previewTitle`)),n&&(n.textContent=e.description||``,n.style.display=e.description?`block`:`none`),i&&e.html&&(i.srcdoc=Ss(e.html)),o&&(e.localPath?(o.style.display=``,o.dataset.path=e.localPath):o.style.display=`none`);let s=document.getElementById(`prototypeOverlay`);s&&s.classList.add(`show`),a.debug(`[SidePanel] UI prototype previewpopupshown`)}function ws(){let e=document.getElementById(`prototypeOverlay`);e&&e.classList.remove(`show`);let t=document.getElementById(`prototypeIframe`);t&&(t.srcdoc=``),_s=null,a.debug(`[SidePanel] UI prototype previewpopuphidden`)}function Ts(){if(!_s)return;let e=_s.id,t=_s.title||r(`uiProto.defaultTitle`);ws();let n=document.getElementById(`userInput`);n&&(n.value=r(`uiProto.optimizePrompt`,{id:e,title:t}),n.focus(),n.style.height=`auto`,n.style.height=n.scrollHeight+`px`),a.debug(`[SidePanel] continue optimizeprototype:`,e)}function Es(){if(!_s||!_s.html){a.error(`[SidePanel] no downloadable prototype`);return}let e=Ss(_s.html),t=new Blob([e],{type:`text/html`}),n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=(_s.title||`prototype`).replace(/[^a-zA-Z0-9\u4e00-\u9fa5_-]/g,`_`)+`.html`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n),a.debug(`[SidePanel] prototype down loaded:`,r.download)}function Ds(){if(!_s||!_s.html){a.error(`[SidePanel] no has can open prototype`);return}let e=Ss(_s.html),t=`data:text/html;base64,`+btoa(unescape(encodeURIComponent(e)));chrome.tabs.create({url:t,active:!0}),a.debug(`[SidePanel] prototype in newlabelpageopen`)}async function Os(e){try{let t=await Oe(e);if(!t){a.error(`[SidePanel] not foundprototype:`,e);return}Cs(t)}catch(e){a.error(`[SidePanel] load prototype failed:`,e)}}async function ks(e){try{let t=await Oe(e);if(!t){a.error(`[SidePanel] not foundprototype (autoopen):`,e);return}_s=t,Ds(),a.debug(`[SidePanel] prototype inbrowserlabelpageautoopen:`,t.title)}catch(e){a.error(`[SidePanel] autoopenprototype failed:`,e)}}async function As(){let e=document.getElementById(`prototypeLibraryList`),t=document.getElementById(`prototypeLibraryModal`);if(!(!e||!t)){e.innerHTML=`<div class="prototype-library-empty">${r(`common.loading`)}</div>`;try{let e=await be();js(e),Ms(e)}catch(t){a.error(`[SidePanel] loadprototype page library failed:`,t),e.innerHTML=`<div class="prototype-library-empty">${r(`uiProto.loadFailed`)}</div>`}t.classList.add(`show`),a.debug(`[SidePanel] prototype page libraryshown`)}}function js(e){let t=document.getElementById(`prototypeLibraryList`);t&&(e.length===0?t.innerHTML=`<div class="prototype-library-empty">${r(`prototype.empty`)}</div>`:(t.innerHTML=e.map(e=>{let t=e.id.replace(`proto_`,``).slice(-6);return`
124
124
  <div class="prototype-library-item" data-id="${e.id}">
125
125
  <div class="prototype-library-item-info">
126
126
  <div class="prototype-library-item-title" title="${Rs(e.title)}">${Rs(e.title)}</div>
@@ -150,7 +150,7 @@ Ctrl/Cmd+click to copy rich-text table`,downloadExcel:`Download Excel`,exportTab
150
150
  </button>
151
151
  </div>
152
152
  </div>
153
- `}).join(``),t.querySelectorAll(`.prototype-library-item`).forEach(e=>{let t=e.querySelector(`.prototype-library-item-info`),n=e.querySelector(`.prototype-library-item-open`),i=e.querySelector(`.prototype-library-item-local-open`),o=e.querySelector(`.prototype-library-item-optimize`),s=e.querySelector(`.prototype-library-item-delete`),c=e.querySelector(`.prototype-library-item-download`);t&&t.addEventListener(`click`,()=>{let t=e.dataset.id;Os(t)}),n&&n.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.id;Os(n)}),i&&i.addEventListener(`click`,e=>{e.stopPropagation();let t=i.dataset.path;chrome.runtime.sendMessage({type:`OPEN_LOCAL_PROTOTYPE`,path:t},e=>{e?.success||a.error(`[SidePanel] local browseropen failed:`,e?.error)})}),o&&o.addEventListener(`click`,t=>{t.stopPropagation();let n=o.dataset.id;Ps(n,e.querySelector(`.prototype-library-item-title`)?.textContent||r(`uiProto.defaultTitle`)),Ns()}),s&&s.addEventListener(`click`,t=>{t.stopPropagation();let n=s.dataset.id;Is(n,e.querySelector(`.prototype-library-item-title`)?.textContent||r(`uiProto.defaultTitle`))}),c&&c.addEventListener(`click`,e=>{e.stopPropagation();let t=c.dataset.id;Fs(t)})})))}function Ms(e){let t=()=>{let t=document.getElementById(`prototypeLibrarySearch`),n=document.getElementById(`prototypeLibrarySort`),r=(t?.value||``).trim().toLowerCase(),i=n?.value||`createdAt_desc`,a=e;r&&(a=e.filter(e=>(e.title||``).toLowerCase().includes(r)||(e.description||``).toLowerCase().includes(r)));let[o,s]=i.split(`_`);a=[...a].sort((e,t)=>{let n;return n=o===`title`?(e.title||``).localeCompare(t.title||``,`zh-CN`):(e.createdAt||0)-(t.createdAt||0),s===`desc`?-n:n}),js(a)},n=document.getElementById(`prototypeLibrarySearch`),r=document.getElementById(`prototypeLibrarySort`);if(n){let e=n.cloneNode(!0);n.parentNode.replaceChild(e,n),e.addEventListener(`input`,t)}if(r){let e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener(`change`,t)}}function Ns(){let e=document.getElementById(`prototypeLibraryModal`);e&&e.classList.remove(`show`),a.debug(`[SidePanel] prototype page libraryhidden`)}function Ps(e,t){let n=document.getElementById(`userInput`);n&&(n.value=r(`uiProto.optimizePrompt`,{id:e,title:t}),n.focus(),n.style.height=`auto`,n.style.height=n.scrollHeight+`px`),a.debug(`[SidePanel] from prototype page librarycontinue optimizeprototype:`,e)}async function Fs(e){try{let t=await Ee(e);if(!t||!t.html){a.error(`[SidePanel] download prototype failed:not foundprototype`,e);return}let n=Ss(t.html),r=new Blob([n],{type:`text/html`}),i=URL.createObjectURL(r),o=document.createElement(`a`);o.href=i,o.download=(t.title||`prototype`).replace(/[^a-zA-Z0-9\u4e00-\u9fa5_-]/g,`_`)+`.html`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(i),a.debug(`[SidePanel] prototype fromprototypelibrarydownload:`,o.download)}catch(e){a.error(`[SidePanel] download prototype failed:`,e)}}async function Is(e,t){if(await Ls(r(`uiProto.confirmDeleteTitle`),r(`uiProto.confirmDeleteMessage`,{title:t}),r(`common.delete`)))try{let t=await Ee(e);await ie(e),a.debug(`[SidePanel] prototype deleted:`,e),t?.localPath&&chrome.runtime.sendMessage({type:`DELETE_LOCAL_PROTOTYPE`,path:t.localPath},e=>{e?.success?a.debug(`[SidePanel] local prototypefile deleted:`,t.localPath):a.warn(`[SidePanel] local prototypefiledelete failed:`,e?.error)}),As()}catch(e){a.error(`[SidePanel] delete prototype failed:`,e),alert(r(`uiProto.deleteFailed`,{message:e.message}))}}function Ls(e,t,n=r(`common.confirm`)){return new Promise(r=>{let i=document.getElementById(`genericConfirmModal`),a=document.getElementById(`genericConfirmTitle`),o=document.getElementById(`genericConfirmMessage`),s=document.getElementById(`genericConfirmOkBtn`),c=document.getElementById(`genericConfirmCancelBtn`);if(!i){r(confirm(t));return}a.textContent=e,o.textContent=t,s.textContent=n;let l=()=>{i.classList.remove(`show`),s.removeEventListener(`click`,u),c.removeEventListener(`click`,d)},u=()=>{l(),r(!0)},d=()=>{l(),r(!1)};s.addEventListener(`click`,u),c.addEventListener(`click`,d),i.classList.add(`show`)})}function Rs(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}function zs(e){if(!e)return``;let t=new Date(e),n=new Date-t;return n<6e4?r(`uiProto.justNow`):n<36e5?r(`uiProto.minutesAgo`,{count:Math.floor(n/6e4)}):n<864e5?r(`uiProto.hoursAgo`,{count:Math.floor(n/36e5)}):t.toLocaleDateString(`zh-CN`)}function Bs(e){vs=Math.max(ys,Math.min(bs,e)),vs=Math.round(vs*100)/100;let t=document.getElementById(`prototypeIframe`),n=document.getElementById(`prototypeZoomLevel`);t&&(t.style.zoom=vs),n&&(n.textContent=Math.round(vs*100)+`%`,vs===1?n.classList.remove(`zoomed`):n.classList.add(`zoomed`))}function Vs(){Bs(vs+xs),Ws()}function Hs(){Bs(vs-xs),Ws()}function Us(){Bs(1)}function Ws(){let e=document.getElementById(`prototypeZoomLevel`);e&&(e.classList.add(`flash`),setTimeout(()=>e.classList.remove(`flash`),150))}function Gs(e){!e.ctrlKey&&!e.metaKey||(e.preventDefault(),e.deltaY<0?Vs():Hs())}function Ks(e){(e.ctrlKey||e.metaKey)&&e.key===`0`&&(e.preventDefault(),Us())}function qs(){let e=document.getElementById(`prototypeCloseBtn`);e&&e.addEventListener(`click`,ws);let t=document.getElementById(`prototypeDownloadBtn`);t&&t.addEventListener(`click`,Es);let n=document.getElementById(`prototypeOpenTabBtn`);n&&n.addEventListener(`click`,Ds);let r=document.getElementById(`prototypeLocalOpenBtn`);r&&r.addEventListener(`click`,()=>{let e=r.dataset.path;e&&chrome.runtime.sendMessage({type:`OPEN_LOCAL_PROTOTYPE`,path:e},e=>{e?.success||a.error(`[SidePanel] local browseropen failed:`,e?.error)})});let i=document.getElementById(`prototypeContinueBtn`);i&&i.addEventListener(`click`,Ts);let o=document.getElementById(`prototypeZoomInBtn`);o&&o.addEventListener(`click`,Vs);let s=document.getElementById(`prototypeZoomOutBtn`);s&&s.addEventListener(`click`,Hs);let c=document.getElementById(`prototypeZoomLevel`);c&&c.addEventListener(`click`,Us);let l=document.getElementById(`prototypeContent`);l&&l.addEventListener(`wheel`,Gs,{passive:!1}),document.addEventListener(`keydown`,Ks);let u=document.getElementById(`prototypeLibraryCloseBtn`);u&&u.addEventListener(`click`,Ns),chrome.runtime.onMessage.addListener((e,t,n)=>{e.type===`SHOW_UI_PROTOTYPE`&&(a.debug(`[SidePanel] received showprototyperequested :`,e),e.data.localOpened?a.debug(`[SidePanel] prototype inagent-side browseropen,skip popup`):e.data.isRemoteAgent?(a.debug(`[SidePanel] remoteagent,will use browserlabelpageautoopenprototype`),ks(e.data.prototypeId)):Os(e.data.prototypeId),n({success:!0}))}),a.debug(`[SidePanel] UI prototype moduleeventinitializing`)}var Js={enabled:!1,thresholdRatio:.85,minPending:4,maxFailures:2};function Ys(e,t){let n=Number(e);return Number.isFinite(n)&&n>0&&n<=1?n:t}function Xs(e,t){let n=Number(e);return Number.isFinite(n)&&n>=0?Math.floor(n):t}function Zs({enabled:e,ratio:t,thresholdRatio:n,pendingCount:r,minPending:i,isGenerating:a,isolateChat:o}={}){if(!e||a||!o)return!1;let s=Ys(n,Js.thresholdRatio),c=Xs(i,Js.minPending);return!Number.isFinite(t)||t<s?!1:Xs(r,0)>=c}function Qs(e){let t=e?.messageHistory||[],n=e?.activeCompaction?.upToMessageId;if(!n)return t.length;let r=t.findIndex(e=>e.messageId===n);return r===-1?t.length:t.length-r-1}var $s=0;function ec(){$s=0}async function tc({state:e,getRatio:t,compact:n}={}){let r=e?.chatConfig||{},i=r.autoCompaction===!0;if(!i)return{attempted:!1,success:!1,reason:`disabled`};if($s>=Js.maxFailures)return{attempted:!1,success:!1,reason:`backoff`};let o;try{o=Number(t?t():NaN)}catch(e){return a.warn(`[AutoCompaction] usage compute failed, send continues:`,e?.message),{attempted:!1,success:!1,reason:`usage_unavailable`}}let s=Qs(e);if(!Zs({enabled:i,ratio:o,thresholdRatio:r.autoCompactionThreshold,pendingCount:s,isGenerating:!!e?.isGenerating,isolateChat:!!e?.isolateChat}))return{attempted:!1,success:!1,reason:`not_needed`};a.debug(`[AutoCompaction] triggered`,{ratio:o,pendingCount:s});let c=null;try{c=await n({silent:!0})}catch(e){return a.warn(`[AutoCompaction] compact threw, send continues:`,e?.message),$s++,{attempted:!0,success:!1,reason:`exception`}}return c?.success?(ec(),{attempted:!0,success:!0}):($s++,a.debug(`[AutoCompaction] skipped send:`,c?.reason),{attempted:!0,success:!1,reason:c?.reason||`failed`})}var nc=null,rc=`global`,ic=new Map;function ac(){try{chrome.windows?.getCurrent?.().then?.(e=>{e?.id!=null&&(nc=e.id)}).catch?.(e=>{a.debug(`[PanelContext] query current window failed:`,e?.message)})}catch(e){a.debug(`[PanelContext] init window query failed:`,e?.message)}try{chrome.storage?.local?.get?.([`sidePanelScope`],e=>{rc=e?.sidePanelScope===`tab-specific`?`tab-specific`:`global`}),chrome.storage?.onChanged?.addListener?.((e,t)=>{t!==`local`||!e?.sidePanelScope||(rc=e.sidePanelScope.newValue===`tab-specific`?`tab-specific`:`global`)})}catch(e){a.debug(`[PanelContext] init scope mirror failed:`,e?.message)}}function oc(){return nc}function sc(e){e&&typeof F.currentTabId==`number`&&ic.set(e,F.currentTabId)}function cc(e,t){e&&(typeof t==`number`?ic.set(e,t):ic.delete(e))}function lc(e){if(!e)return null;let t=ic.get(e);return typeof t==`number`?t:null}function uc(e){let t=null;try{t=typeof document<`u`?!!document.hidden:null}catch{}return{windowId:nc,hostTabId:lc(e),scope:rc,panelHidden:t}}var dc=0,fc=500,pc=[{frequency:523.25,startTime:0,duration:.12,type:`sine`,gain:.3},{frequency:659.25,startTime:.09,duration:.12,type:`sine`,gain:.3},{frequency:783.99,startTime:.18,duration:.22,type:`sine`,gain:.35}],mc=[{frequency:440,startTime:0,duration:.16,type:`square`,gain:.22},{frequency:349.23,startTime:.14,duration:.3,type:`square`,gain:.22}],hc=[`#FF3B30`,`#FF9500`,`#FFCC00`,`#34C759`,`#00C7BE`,`#007AFF`,`#AF52DE`,`#FF2D55`],gc=120,_c=4e3,vc=600,yc=1e3,bc=.25,xc=.99,Sc=.3,Cc=.6,wc=9999;function Tc(){return new Promise(e=>{try{chrome.storage.local.get([`completionSoundEnabled`,`completionConfettiEnabled`],t=>{e({soundEnabled:t?.completionSoundEnabled!==!1,confettiEnabled:t?.completionConfettiEnabled!==!1})})}catch(t){a.debug(`[CompletionFeedback] read config failed, use defaults:`,t?.message),e({soundEnabled:!0,confettiEnabled:!0})}})}function Ec(e){try{let t=window.AudioContext||window.webkitAudioContext;if(!t){a.debug(`[CompletionFeedback] AudioContext unavailable`);return}let n=new t;n.state===`suspended`&&typeof n.resume==`function`&&n.resume().catch(()=>{});let r=n.currentTime,i=0;for(let t of e){let e=n.createOscillator(),a=n.createGain();e.type=t.type||`sine`,e.frequency.value=t.frequency;let o=r+t.startTime,s=o+t.duration;a.gain.setValueAtTime(1e-4,o),a.gain.exponentialRampToValueAtTime(t.gain,o+.012),a.gain.exponentialRampToValueAtTime(1e-4,s),e.connect(a),a.connect(n.destination),e.start(o),e.stop(s+.02),s>i&&(i=s)}let o=Math.max(0,(i-r)*1e3)+200;setTimeout(()=>{try{n.close()}catch{}},o)}catch(e){a.debug(`[CompletionFeedback] play tone failed:`,e?.message)}}function Dc(){Ec(pc),a.debug(`[CompletionFeedback] success sound played`)}function Oc(){Ec(mc),a.debug(`[CompletionFeedback] failure sound played`)}function kc(){try{return typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}catch{return!1}}function Ac(){try{if(!document.body)return;let e=window.innerWidth,t=window.innerHeight;if(e<=0||t<=0)return;let n=document.createElement(`canvas`);n.style.cssText=`position:fixed;inset:0;pointer-events:none;z-index:${wc};`;let r=window.devicePixelRatio||1;n.width=Math.floor(e*r),n.height=Math.floor(t*r),n.style.width=e+`px`,n.style.height=t+`px`,document.body.appendChild(n);let i=n.getContext(`2d`);if(!i){n.remove();return}i.scale(r,r);let o=[{x:e*.15,y:t+10,baseAngle:-Math.PI/2+Sc},{x:e*.85,y:t+10,baseAngle:-Math.PI/2-Sc}],s=[],c=0,l=0,u=performance.now(),d=e=>{let t=Math.min(gc,Math.floor(Math.min(e,vc)/vc*gc));for(;c<t;){let e=o[c%o.length],t=e.baseAngle+(Math.random()-.5)*Cc,n=12+Math.random()*8,r=4+Math.random()*4;s.push({x:e.x+(Math.random()-.5)*20,y:e.y,vx:Math.cos(t)*n,vy:Math.sin(t)*n,size:r,color:hc[Math.floor(Math.random()*hc.length)],rotation:Math.random()*Math.PI*2,rotationSpeed:(Math.random()-.5)*.3,shape:Math.random()<.5?`rect`:`circle`}),c++}},f=r=>{let a=r-u;if(a>=_c){cancelAnimationFrame(l),n.remove();return}d(a),i.clearRect(0,0,e,t);let o=_c-yc,c=a>o?Math.max(0,1-(a-o)/yc):1;for(let n=s.length-1;n>=0;n--){let r=s[n];if(r.vy+=bc,r.vx*=xc,r.vy*=xc,r.x+=r.vx,r.y+=r.vy,r.rotation+=r.rotationSpeed,r.y-r.size>t||r.x+r.size<0||r.x-r.size>e){s.splice(n,1);continue}i.save(),i.globalAlpha=c,i.translate(r.x,r.y),i.rotate(r.rotation),i.fillStyle=r.color,r.shape===`rect`?i.fillRect(-r.size/2,-r.size/2,r.size,r.size*.6):(i.beginPath(),i.arc(0,0,r.size/2,0,Math.PI*2),i.fill()),i.restore()}l=requestAnimationFrame(f)};l=requestAnimationFrame(f),a.debug(`[CompletionFeedback] confetti launched`)}catch(e){a.debug(`[CompletionFeedback] launch confetti failed:`,e?.message)}}function jc(e,t,n,r){try{chrome.runtime.sendMessage({type:`TASK_FEEDBACK_NOTIFY`,success:e,sessionId:t||null,error:n||``,question:r||``,panel:uc(t)})?.catch?.(()=>{})}catch(e){a.debug(`[CompletionFeedback] desktop notify failed:`,e?.message)}}async function Mc(e=null,t=``){try{let n=Date.now();if(n-dc<fc){a.debug(`[CompletionFeedback] throttled, skip`);return}dc=n;let{soundEnabled:r,confettiEnabled:i}=await Tc();r&&Dc(),i&&!kc()&&Ac(),jc(!0,e,``,t)}catch(e){a.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}async function Nc(e=null,t=``,n=``){try{let r=Date.now();if(r-dc<fc){a.debug(`[CompletionFeedback] throttled, skip`);return}dc=r;let{soundEnabled:i}=await Tc();i&&Oc(),jc(!1,e,t,n)}catch(e){a.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}var Pc=`combo-collapsed`,Fc=`summary-collapsed`,Ic=`summary-wrapped`,Lc=[Pc,Fc,Ic];function Rc(e){if(!e)return;let t=e.querySelector(`.log-summary`);t&&(t.classList.remove(...Lc),!(t.scrollWidth<=t.clientWidth)&&(t.classList.add(Pc),!(t.scrollWidth<=t.clientWidth)&&(t.classList.add(Fc),!(t.scrollWidth<=t.clientWidth)&&t.classList.add(Ic))))}var zc=null,Bc=0,Vc=!1;function Hc(e){e&&(zc=e,Uc(),!Bc&&(Bc=requestAnimationFrame(()=>{Bc=0;let e=zc;zc=null,e&&Rc(e)})))}function Uc(){Vc||typeof window>`u`||(Vc=!0,window.addEventListener(`resize`,()=>{let e=document.querySelector(`.execution-log-panel`);e&&Hc(e)}))}n(`zh`,{execLog:{statusSuccess:`成功`,statusFailed:`失败`,statusProcessing:`处理中`,unknownNode:`未知节点`,sequentialExecution:`顺序执行`,parallelExecution:`并行执行`,subtaskCountStrategy:`{count}个子任务, {strategy}`,messageCountTitle:`本次模型API调用携带的消息数`,toolCountTitle:`本次模型API调用携带的工具定义数`,messageCount:`{count}条`,toolCount:`{count}个`,durationTitle:`耗时`,sectionThought:`💡 思考`,sectionToolCall:`⚡ 工具调用`,labelTool:`工具:`,labelParams:`参数:`,sectionFilterResult:`🔍 筛选结果`,labelSelectedTools:`选中工具:`,labelCount:`数量:`,unitItems:`个`,sectionObservation:`📝 观察结果`,sectionApiRequest:`📡 API 请求`,labelModel:`模型:`,labelTemperature:`温度:`,labelTopP:`top_p:`,labelMessageCount:`消息数:`,labelToolCount:`工具数:`,sectionApiResponse:`📤 API 响应`,labelFinishReason:`完成原因:`,labelFilteredToolCount:`筛选后工具数:`,labelTokenUsage:`Token 使用:`,sectionError:`❌ 错误信息`,sectionSubtaskResult:`✅ 子任务结果`,sectionSubtaskDesc:`📝 任务描述`,subtaskPendingNode:`(待执行)`,sectionReflectionPrompt:`📊 评估提示词`,sectionReflectionRaw:`📤 评估结果(原始响应)`,sectionTokenUsage:`📊 Token 使用`,overallScore:`⭐ 综合评分: {score}/10`,sectionIssues:`📋 发现的问题`,sectionSuggestions:`💡 改进建议`,labelDecision:`🎯 决策: {decision}`,decisionPassed:`✅ 通过`,decisionRevised:`🔧 已修订`,decisionNeedsImprovement:`⚠️ 需改进`,resultUseful:`✅ 结果有用`,resultInvalid:`⚠️ 结果无效`,labelSuggestion:`建议: {suggestion}`,mainTask:`主任务`,stepCount:`({count} 步骤)`,processingDots:`处理中...`,waitingExecution:`等待执行中...`,realtimeLogTitle:`实时执行日志`,executingLabel:`执行中:`,preparing:`准备中...`,totalNodes:`总节点`,labelSuccess:`成功`,labelFailed:`失败`,labelSubtask:`子任务`,expandAll:`展开全部节点`,collapseAll:`收起全部节点`}}),n(`en`,{execLog:{statusSuccess:`Success`,statusFailed:`Failed`,statusProcessing:`Processing`,unknownNode:`Unknown node`,sequentialExecution:`sequential`,parallelExecution:`parallel`,subtaskCountStrategy:`{count} subtasks, {strategy}`,messageCountTitle:`Number of messages carried in this model API call`,toolCountTitle:`Number of tool definitions carried in this model API call`,messageCount:`{count} msgs`,toolCount:`{count} tools`,durationTitle:`Duration`,sectionThought:`💡 Thought`,sectionToolCall:`⚡ Tool Call`,labelTool:`Tool:`,labelParams:`Params:`,sectionFilterResult:`🔍 Filter Result`,labelSelectedTools:`Selected tools:`,labelCount:`Count:`,unitItems:``,sectionObservation:`📝 Observation`,sectionApiRequest:`📡 API Request`,labelModel:`Model:`,labelTemperature:`Temperature:`,labelTopP:`top_p:`,labelMessageCount:`Messages:`,labelToolCount:`Tools:`,sectionApiResponse:`📤 API Response`,labelFinishReason:`Finish reason:`,labelFilteredToolCount:`Filtered tool count:`,labelTokenUsage:`Token Usage:`,sectionError:`❌ Error`,sectionSubtaskResult:`✅ Subtask Result`,sectionSubtaskDesc:`📝 Task Description`,subtaskPendingNode:`(pending)`,sectionReflectionPrompt:`📊 Reflection Prompt`,sectionReflectionRaw:`📤 Reflection Result (raw)`,sectionTokenUsage:`📊 Token Usage`,overallScore:`⭐ Overall Score: {score}/10`,sectionIssues:`📋 Issues Found`,sectionSuggestions:`💡 Suggestions`,labelDecision:`🎯 Decision: {decision}`,decisionPassed:`✅ Passed`,decisionRevised:`🔧 Revised`,decisionNeedsImprovement:`⚠️ Needs Improvement`,resultUseful:`✅ Useful`,resultInvalid:`⚠️ Invalid`,labelSuggestion:`Suggestion: {suggestion}`,mainTask:`Main Task`,stepCount:`({count} steps)`,processingDots:`Processing...`,waitingExecution:`Waiting for execution...`,realtimeLogTitle:`Real-time Execution Log`,executingLabel:`Executing:`,preparing:`Preparing...`,totalNodes:`Total nodes`,labelSuccess:`Success`,labelFailed:`Failed`,labelSubtask:`Subtask`,expandAll:`Expand all nodes`,collapseAll:`Collapse all nodes`}});function Wc(e){if(e?.nodeType!==`tool_exec`||!e?.action)return``;let t=e.action.name||``,n=e.action.params;if(n==null)return``;if(typeof n==`string`&&(n=(()=>{try{return JSON.parse(n)}catch{return{raw:n}}})()),typeof n!=`object`)return String(n).trim();if(t===`execute_command`||t===`agent_exec`)return(n.command||n.cmd||``).toString().trim();if(t===`agent_file`||t===`file_upload`||t===`download_file`){let e=(n.file_path||n.filePath||n.path||n.filename||n.fileName||n.url||``).toString().trim();if(e)return e}if(t===`fetch_url`||t===`interact_element`||t===`fill_form`||t===`manage_tab`||t===`preview_ui`){let e=(n.url||n.href||n.selector||``).toString().trim();if(e)return e}if(t===`search_browser_data`||t===`search_in_page`||t===`exec_log`){let e=(n.query||n.keyword||n.text||``).toString().trim();if(e)return e}if(t===`dispatch_task`){let e=(n.task||``).toString().trim();if(e)return e}if(t===`agent_memory`){let e=(n.action||n.subAction||``).toString().trim();if(e)return e}let r=[`content`,`text`,`prompt`,`description`,`markdown`,`html`,`css`,`js`,`code`,`script`,`data`],i=Object.keys(n).filter(e=>n[e]!=null&&n[e]!==``&&!r.includes(e));if(i.length===0)return``;if(i.length===1){let e=String(n[i[0]]);return`${i[0]}: ${e}`}return i.slice(0,2).map(e=>`${e}=${JSON.stringify(n[e])}`).join(`, `)}function Gc(e){return Wc(e)}function Kc(e){let t=Array.isArray(e)?e:[],n=t.filter(e=>e&&e.nodeType===`subtask_plan`&&Array.isArray(e.items));if(n.length===0)return t;let i=t.filter(e=>e&&e.nodeType!==`subtask_plan`),a=new Set(i.filter(e=>e.nodeType===`subtask`&&typeof e.subtaskIndex==`number`).map(e=>e.subtaskIndex)),o=new Map;n.forEach(e=>{e.items.forEach(t=>{!t||typeof t.index!=`number`||o.set(t.index,{item:t,plan:e})})});let s=[];return Array.from(o.keys()).sort((e,t)=>e-t).forEach(e=>{if(a.has(e))return;let{item:t,plan:n}=o.get(e),i=r(`execLog.subtaskPendingNode`);s.push({id:`plan_pending_${n.id||`x`}_${e}`,nodeType:`subtask`,status:`pending`,iteration:0,timestamp:n.timestamp,subtaskIndex:e,subtaskId:t.id,subtaskName:t.name,description:t.description||``,nodeName:t.name?`${t.name} ${i}`:i,taskGroup:`subtask_group_${e}`,taskGroupIndex:e+1,taskGroupName:t.name,isSubtask:!0})}),i.concat(s)}function qc(e,t){let n=e=>e.status===`pending`?2**53-1:new Date(e.timestamp).getTime();return n(e)-n(t)}function Jc(e){let t=Kc(e).sort(qc),n=t.length,i=``,a=null;return t.forEach((e,t)=>{let o=e.nodeType===`subtask`,s=e.nodeType===`tool_exec`,c=e.nodeType===`api_call`,l=e.nodeType===`preselect`,u=e.nodeType===`reflection`,d=s&&e.action?.name===`plan_task`;o&&(a=e.subtaskIndex);let f=``,p=``;u?p=`🎯`:l?p=`🔍`:d?(f=`plan-task-level`,p=`📋`):o?(f=`subtask-level`,p=`🔀`):s&&a!==null?(f=`tool-level`,p=`🔧`):c&&a!==null?(f=`api-level`,p=`📡`):s?p=`⚡`:c&&(p=`📡`);let m=`○`,h=e.status||`processing`;e.status===`success`?m=`✓`:e.status===`failed`&&(m=`✗`),u&&(h=`reflection ${h}`);let g=R(e.nodeName||r(`execLog.unknownNode`));if(e.subtaskIndex!==null&&e.subtaskIndex>=0&&(g=`<span class="subtask-badge">${e.subtaskIndex+1}</span> ${g}`),e.subtaskCount&&(g+=` <span class="plan-badge">(${r(`execLog.subtaskCountStrategy`,{count:e.subtaskCount,strategy:e.strategy===`sequential`?r(`execLog.sequentialExecution`):r(`execLog.parallelExecution`)})})</span>`),(c||l||u)&&e.apiRequest){let t=[];e.apiRequest.messageCount!==void 0&&e.apiRequest.messageCount!==null&&t.push(`💬<span title="${r(`execLog.messageCountTitle`)}">${r(`execLog.messageCount`,{count:e.apiRequest.messageCount})}</span>`),!l&&e.apiRequest.toolCount!==void 0&&e.apiRequest.toolCount!==null&&t.push(`🔧<span title="${r(`execLog.toolCountTitle`)}">${r(`execLog.toolCount`,{count:e.apiRequest.toolCount})}</span>`),t.length>0&&(g+=` <span class="api-info-badge">(${t.join(` `)})</span>`)}if(s){let t=Gc(e);t&&(g+=` <span class="node-cmd-preview" title="${V(t)}">${R(t)}</span>`)}i+=`
153
+ `}).join(``),t.querySelectorAll(`.prototype-library-item`).forEach(e=>{let t=e.querySelector(`.prototype-library-item-info`),n=e.querySelector(`.prototype-library-item-open`),i=e.querySelector(`.prototype-library-item-local-open`),o=e.querySelector(`.prototype-library-item-optimize`),s=e.querySelector(`.prototype-library-item-delete`),c=e.querySelector(`.prototype-library-item-download`);t&&t.addEventListener(`click`,()=>{let t=e.dataset.id;Os(t)}),n&&n.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.id;Os(n)}),i&&i.addEventListener(`click`,e=>{e.stopPropagation();let t=i.dataset.path;chrome.runtime.sendMessage({type:`OPEN_LOCAL_PROTOTYPE`,path:t},e=>{e?.success||a.error(`[SidePanel] local browseropen failed:`,e?.error)})}),o&&o.addEventListener(`click`,t=>{t.stopPropagation();let n=o.dataset.id;Ps(n,e.querySelector(`.prototype-library-item-title`)?.textContent||r(`uiProto.defaultTitle`)),Ns()}),s&&s.addEventListener(`click`,t=>{t.stopPropagation();let n=s.dataset.id;Is(n,e.querySelector(`.prototype-library-item-title`)?.textContent||r(`uiProto.defaultTitle`))}),c&&c.addEventListener(`click`,e=>{e.stopPropagation();let t=c.dataset.id;Fs(t)})})))}function Ms(e){let t=()=>{let t=document.getElementById(`prototypeLibrarySearch`),n=document.getElementById(`prototypeLibrarySort`),r=(t?.value||``).trim().toLowerCase(),i=n?.value||`createdAt_desc`,a=e;r&&(a=e.filter(e=>(e.title||``).toLowerCase().includes(r)||(e.description||``).toLowerCase().includes(r)));let[o,s]=i.split(`_`);a=[...a].sort((e,t)=>{let n;return n=o===`title`?(e.title||``).localeCompare(t.title||``,`zh-CN`):(e.createdAt||0)-(t.createdAt||0),s===`desc`?-n:n}),js(a)},n=document.getElementById(`prototypeLibrarySearch`),r=document.getElementById(`prototypeLibrarySort`);if(n){let e=n.cloneNode(!0);n.parentNode.replaceChild(e,n),e.addEventListener(`input`,t)}if(r){let e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener(`change`,t)}}function Ns(){let e=document.getElementById(`prototypeLibraryModal`);e&&e.classList.remove(`show`),a.debug(`[SidePanel] prototype page libraryhidden`)}function Ps(e,t){let n=document.getElementById(`userInput`);n&&(n.value=r(`uiProto.optimizePrompt`,{id:e,title:t}),n.focus(),n.style.height=`auto`,n.style.height=n.scrollHeight+`px`),a.debug(`[SidePanel] from prototype page librarycontinue optimizeprototype:`,e)}async function Fs(e){try{let t=await Oe(e);if(!t||!t.html){a.error(`[SidePanel] download prototype failed:not foundprototype`,e);return}let n=Ss(t.html),r=new Blob([n],{type:`text/html`}),i=URL.createObjectURL(r),o=document.createElement(`a`);o.href=i,o.download=(t.title||`prototype`).replace(/[^a-zA-Z0-9\u4e00-\u9fa5_-]/g,`_`)+`.html`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(i),a.debug(`[SidePanel] prototype fromprototypelibrarydownload:`,o.download)}catch(e){a.error(`[SidePanel] download prototype failed:`,e)}}async function Is(e,t){if(await Ls(r(`uiProto.confirmDeleteTitle`),r(`uiProto.confirmDeleteMessage`,{title:t}),r(`common.delete`)))try{let t=await Oe(e);await j(e),a.debug(`[SidePanel] prototype deleted:`,e),t?.localPath&&chrome.runtime.sendMessage({type:`DELETE_LOCAL_PROTOTYPE`,path:t.localPath},e=>{e?.success?a.debug(`[SidePanel] local prototypefile deleted:`,t.localPath):a.warn(`[SidePanel] local prototypefiledelete failed:`,e?.error)}),As()}catch(e){a.error(`[SidePanel] delete prototype failed:`,e),alert(r(`uiProto.deleteFailed`,{message:e.message}))}}function Ls(e,t,n=r(`common.confirm`)){return new Promise(r=>{let i=document.getElementById(`genericConfirmModal`),a=document.getElementById(`genericConfirmTitle`),o=document.getElementById(`genericConfirmMessage`),s=document.getElementById(`genericConfirmOkBtn`),c=document.getElementById(`genericConfirmCancelBtn`);if(!i){r(confirm(t));return}a.textContent=e,o.textContent=t,s.textContent=n;let l=()=>{i.classList.remove(`show`),s.removeEventListener(`click`,u),c.removeEventListener(`click`,d)},u=()=>{l(),r(!0)},d=()=>{l(),r(!1)};s.addEventListener(`click`,u),c.addEventListener(`click`,d),i.classList.add(`show`)})}function Rs(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}function zs(e){if(!e)return``;let t=new Date(e),n=new Date-t;return n<6e4?r(`uiProto.justNow`):n<36e5?r(`uiProto.minutesAgo`,{count:Math.floor(n/6e4)}):n<864e5?r(`uiProto.hoursAgo`,{count:Math.floor(n/36e5)}):t.toLocaleDateString(`zh-CN`)}function Bs(e){vs=Math.max(ys,Math.min(bs,e)),vs=Math.round(vs*100)/100;let t=document.getElementById(`prototypeIframe`),n=document.getElementById(`prototypeZoomLevel`);t&&(t.style.zoom=vs),n&&(n.textContent=Math.round(vs*100)+`%`,vs===1?n.classList.remove(`zoomed`):n.classList.add(`zoomed`))}function Vs(){Bs(vs+xs),Ws()}function Hs(){Bs(vs-xs),Ws()}function Us(){Bs(1)}function Ws(){let e=document.getElementById(`prototypeZoomLevel`);e&&(e.classList.add(`flash`),setTimeout(()=>e.classList.remove(`flash`),150))}function Gs(e){!e.ctrlKey&&!e.metaKey||(e.preventDefault(),e.deltaY<0?Vs():Hs())}function Ks(e){(e.ctrlKey||e.metaKey)&&e.key===`0`&&(e.preventDefault(),Us())}function qs(){let e=document.getElementById(`prototypeCloseBtn`);e&&e.addEventListener(`click`,ws);let t=document.getElementById(`prototypeDownloadBtn`);t&&t.addEventListener(`click`,Es);let n=document.getElementById(`prototypeOpenTabBtn`);n&&n.addEventListener(`click`,Ds);let r=document.getElementById(`prototypeLocalOpenBtn`);r&&r.addEventListener(`click`,()=>{let e=r.dataset.path;e&&chrome.runtime.sendMessage({type:`OPEN_LOCAL_PROTOTYPE`,path:e},e=>{e?.success||a.error(`[SidePanel] local browseropen failed:`,e?.error)})});let i=document.getElementById(`prototypeContinueBtn`);i&&i.addEventListener(`click`,Ts);let o=document.getElementById(`prototypeZoomInBtn`);o&&o.addEventListener(`click`,Vs);let s=document.getElementById(`prototypeZoomOutBtn`);s&&s.addEventListener(`click`,Hs);let c=document.getElementById(`prototypeZoomLevel`);c&&c.addEventListener(`click`,Us);let l=document.getElementById(`prototypeContent`);l&&l.addEventListener(`wheel`,Gs,{passive:!1}),document.addEventListener(`keydown`,Ks);let u=document.getElementById(`prototypeLibraryCloseBtn`);u&&u.addEventListener(`click`,Ns),chrome.runtime.onMessage.addListener((e,t,n)=>{e.type===`SHOW_UI_PROTOTYPE`&&(a.debug(`[SidePanel] received showprototyperequested :`,e),e.data.localOpened?a.debug(`[SidePanel] prototype inagent-side browseropen,skip popup`):e.data.isRemoteAgent?(a.debug(`[SidePanel] remoteagent,will use browserlabelpageautoopenprototype`),ks(e.data.prototypeId)):Os(e.data.prototypeId),n({success:!0}))}),a.debug(`[SidePanel] UI prototype moduleeventinitializing`)}var Js={enabled:!1,thresholdRatio:.85,minPending:4,maxFailures:2};function Ys(e,t){let n=Number(e);return Number.isFinite(n)&&n>0&&n<=1?n:t}function Xs(e,t){let n=Number(e);return Number.isFinite(n)&&n>=0?Math.floor(n):t}function Zs({enabled:e,ratio:t,thresholdRatio:n,pendingCount:r,minPending:i,isGenerating:a,isolateChat:o}={}){if(!e||a||!o)return!1;let s=Ys(n,Js.thresholdRatio),c=Xs(i,Js.minPending);return!Number.isFinite(t)||t<s?!1:Xs(r,0)>=c}function Qs(e){let t=e?.messageHistory||[],n=e?.activeCompaction?.upToMessageId;if(!n)return t.length;let r=t.findIndex(e=>e.messageId===n);return r===-1?t.length:t.length-r-1}var $s=0;function ec(){$s=0}async function tc({state:e,getRatio:t,compact:n}={}){let r=e?.chatConfig||{},i=r.autoCompaction===!0;if(!i)return{attempted:!1,success:!1,reason:`disabled`};if($s>=Js.maxFailures)return{attempted:!1,success:!1,reason:`backoff`};let o;try{o=Number(t?t():NaN)}catch(e){return a.warn(`[AutoCompaction] usage compute failed, send continues:`,e?.message),{attempted:!1,success:!1,reason:`usage_unavailable`}}let s=Qs(e);if(!Zs({enabled:i,ratio:o,thresholdRatio:r.autoCompactionThreshold,pendingCount:s,isGenerating:!!e?.isGenerating,isolateChat:!!e?.isolateChat}))return{attempted:!1,success:!1,reason:`not_needed`};a.debug(`[AutoCompaction] triggered`,{ratio:o,pendingCount:s});let c=null;try{c=await n({silent:!0})}catch(e){return a.warn(`[AutoCompaction] compact threw, send continues:`,e?.message),$s++,{attempted:!0,success:!1,reason:`exception`}}return c?.success?(ec(),{attempted:!0,success:!0}):($s++,a.debug(`[AutoCompaction] skipped send:`,c?.reason),{attempted:!0,success:!1,reason:c?.reason||`failed`})}var nc=null,rc=`global`,ic=new Map;function ac(){try{chrome.windows?.getCurrent?.().then?.(e=>{e?.id!=null&&(nc=e.id)}).catch?.(e=>{a.debug(`[PanelContext] query current window failed:`,e?.message)})}catch(e){a.debug(`[PanelContext] init window query failed:`,e?.message)}try{chrome.storage?.local?.get?.([`sidePanelScope`],e=>{rc=e?.sidePanelScope===`tab-specific`?`tab-specific`:`global`}),chrome.storage?.onChanged?.addListener?.((e,t)=>{t!==`local`||!e?.sidePanelScope||(rc=e.sidePanelScope.newValue===`tab-specific`?`tab-specific`:`global`)})}catch(e){a.debug(`[PanelContext] init scope mirror failed:`,e?.message)}}function oc(){return nc}function sc(e){e&&typeof F.currentTabId==`number`&&ic.set(e,F.currentTabId)}function cc(e,t){e&&(typeof t==`number`?ic.set(e,t):ic.delete(e))}function lc(e){if(!e)return null;let t=ic.get(e);return typeof t==`number`?t:null}function uc(e){let t=null;try{t=typeof document<`u`?!!document.hidden:null}catch{}return{windowId:nc,hostTabId:lc(e),scope:rc,panelHidden:t}}var dc=0,fc=500,pc=[{frequency:523.25,startTime:0,duration:.12,type:`sine`,gain:.3},{frequency:659.25,startTime:.09,duration:.12,type:`sine`,gain:.3},{frequency:783.99,startTime:.18,duration:.22,type:`sine`,gain:.35}],mc=[{frequency:440,startTime:0,duration:.16,type:`square`,gain:.22},{frequency:349.23,startTime:.14,duration:.3,type:`square`,gain:.22}],hc=[`#FF3B30`,`#FF9500`,`#FFCC00`,`#34C759`,`#00C7BE`,`#007AFF`,`#AF52DE`,`#FF2D55`],gc=120,_c=4e3,vc=600,yc=1e3,bc=.25,xc=.99,Sc=.3,Cc=.6,wc=9999;function Tc(){return new Promise(e=>{try{chrome.storage.local.get([`completionSoundEnabled`,`completionConfettiEnabled`],t=>{e({soundEnabled:t?.completionSoundEnabled!==!1,confettiEnabled:t?.completionConfettiEnabled!==!1})})}catch(t){a.debug(`[CompletionFeedback] read config failed, use defaults:`,t?.message),e({soundEnabled:!0,confettiEnabled:!0})}})}function Ec(e){try{let t=window.AudioContext||window.webkitAudioContext;if(!t){a.debug(`[CompletionFeedback] AudioContext unavailable`);return}let n=new t;n.state===`suspended`&&typeof n.resume==`function`&&n.resume().catch(()=>{});let r=n.currentTime,i=0;for(let t of e){let e=n.createOscillator(),a=n.createGain();e.type=t.type||`sine`,e.frequency.value=t.frequency;let o=r+t.startTime,s=o+t.duration;a.gain.setValueAtTime(1e-4,o),a.gain.exponentialRampToValueAtTime(t.gain,o+.012),a.gain.exponentialRampToValueAtTime(1e-4,s),e.connect(a),a.connect(n.destination),e.start(o),e.stop(s+.02),s>i&&(i=s)}let o=Math.max(0,(i-r)*1e3)+200;setTimeout(()=>{try{n.close()}catch{}},o)}catch(e){a.debug(`[CompletionFeedback] play tone failed:`,e?.message)}}function Dc(){Ec(pc),a.debug(`[CompletionFeedback] success sound played`)}function Oc(){Ec(mc),a.debug(`[CompletionFeedback] failure sound played`)}function kc(){try{return typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}catch{return!1}}function Ac(){try{if(!document.body)return;let e=window.innerWidth,t=window.innerHeight;if(e<=0||t<=0)return;let n=document.createElement(`canvas`);n.style.cssText=`position:fixed;inset:0;pointer-events:none;z-index:${wc};`;let r=window.devicePixelRatio||1;n.width=Math.floor(e*r),n.height=Math.floor(t*r),n.style.width=e+`px`,n.style.height=t+`px`,document.body.appendChild(n);let i=n.getContext(`2d`);if(!i){n.remove();return}i.scale(r,r);let o=[{x:e*.15,y:t+10,baseAngle:-Math.PI/2+Sc},{x:e*.85,y:t+10,baseAngle:-Math.PI/2-Sc}],s=[],c=0,l=0,u=performance.now(),d=e=>{let t=Math.min(gc,Math.floor(Math.min(e,vc)/vc*gc));for(;c<t;){let e=o[c%o.length],t=e.baseAngle+(Math.random()-.5)*Cc,n=12+Math.random()*8,r=4+Math.random()*4;s.push({x:e.x+(Math.random()-.5)*20,y:e.y,vx:Math.cos(t)*n,vy:Math.sin(t)*n,size:r,color:hc[Math.floor(Math.random()*hc.length)],rotation:Math.random()*Math.PI*2,rotationSpeed:(Math.random()-.5)*.3,shape:Math.random()<.5?`rect`:`circle`}),c++}},f=r=>{let a=r-u;if(a>=_c){cancelAnimationFrame(l),n.remove();return}d(a),i.clearRect(0,0,e,t);let o=_c-yc,c=a>o?Math.max(0,1-(a-o)/yc):1;for(let n=s.length-1;n>=0;n--){let r=s[n];if(r.vy+=bc,r.vx*=xc,r.vy*=xc,r.x+=r.vx,r.y+=r.vy,r.rotation+=r.rotationSpeed,r.y-r.size>t||r.x+r.size<0||r.x-r.size>e){s.splice(n,1);continue}i.save(),i.globalAlpha=c,i.translate(r.x,r.y),i.rotate(r.rotation),i.fillStyle=r.color,r.shape===`rect`?i.fillRect(-r.size/2,-r.size/2,r.size,r.size*.6):(i.beginPath(),i.arc(0,0,r.size/2,0,Math.PI*2),i.fill()),i.restore()}l=requestAnimationFrame(f)};l=requestAnimationFrame(f),a.debug(`[CompletionFeedback] confetti launched`)}catch(e){a.debug(`[CompletionFeedback] launch confetti failed:`,e?.message)}}function jc(e,t,n,r){try{chrome.runtime.sendMessage({type:`TASK_FEEDBACK_NOTIFY`,success:e,sessionId:t||null,error:n||``,question:r||``,panel:uc(t)})?.catch?.(()=>{})}catch(e){a.debug(`[CompletionFeedback] desktop notify failed:`,e?.message)}}async function Mc(e=null,t=``){try{let n=Date.now();if(n-dc<fc){a.debug(`[CompletionFeedback] throttled, skip`);return}dc=n;let{soundEnabled:r,confettiEnabled:i}=await Tc();r&&Dc(),i&&!kc()&&Ac(),jc(!0,e,``,t)}catch(e){a.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}async function Nc(e=null,t=``,n=``){try{let r=Date.now();if(r-dc<fc){a.debug(`[CompletionFeedback] throttled, skip`);return}dc=r;let{soundEnabled:i}=await Tc();i&&Oc(),jc(!1,e,t,n)}catch(e){a.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}var Pc=`combo-collapsed`,Fc=`summary-collapsed`,Ic=`summary-wrapped`,Lc=[Pc,Fc,Ic];function Rc(e){if(!e)return;let t=e.querySelector(`.log-summary`);t&&(t.classList.remove(...Lc),!(t.scrollWidth<=t.clientWidth)&&(t.classList.add(Pc),!(t.scrollWidth<=t.clientWidth)&&(t.classList.add(Fc),!(t.scrollWidth<=t.clientWidth)&&t.classList.add(Ic))))}var zc=null,Bc=0,Vc=!1;function Hc(e){e&&(zc=e,Uc(),!Bc&&(Bc=requestAnimationFrame(()=>{Bc=0;let e=zc;zc=null,e&&Rc(e)})))}function Uc(){Vc||typeof window>`u`||(Vc=!0,window.addEventListener(`resize`,()=>{let e=document.querySelector(`.execution-log-panel`);e&&Hc(e)}))}n(`zh`,{execLog:{statusSuccess:`成功`,statusFailed:`失败`,statusProcessing:`处理中`,unknownNode:`未知节点`,sequentialExecution:`顺序执行`,parallelExecution:`并行执行`,subtaskCountStrategy:`{count}个子任务, {strategy}`,messageCountTitle:`本次模型API调用携带的消息数`,toolCountTitle:`本次模型API调用携带的工具定义数`,messageCount:`{count}条`,toolCount:`{count}个`,durationTitle:`耗时`,sectionThought:`💡 思考`,sectionToolCall:`⚡ 工具调用`,labelTool:`工具:`,labelParams:`参数:`,sectionFilterResult:`🔍 筛选结果`,labelSelectedTools:`选中工具:`,labelCount:`数量:`,unitItems:`个`,sectionObservation:`📝 观察结果`,sectionApiRequest:`📡 API 请求`,labelModel:`模型:`,labelTemperature:`温度:`,labelTopP:`top_p:`,labelMessageCount:`消息数:`,labelToolCount:`工具数:`,sectionApiResponse:`📤 API 响应`,labelFinishReason:`完成原因:`,labelFilteredToolCount:`筛选后工具数:`,labelTokenUsage:`Token 使用:`,sectionError:`❌ 错误信息`,sectionSubtaskResult:`✅ 子任务结果`,sectionSubtaskDesc:`📝 任务描述`,subtaskPendingNode:`(待执行)`,sectionReflectionPrompt:`📊 评估提示词`,sectionReflectionRaw:`📤 评估结果(原始响应)`,sectionTokenUsage:`📊 Token 使用`,overallScore:`⭐ 综合评分: {score}/10`,sectionIssues:`📋 发现的问题`,sectionSuggestions:`💡 改进建议`,labelDecision:`🎯 决策: {decision}`,decisionPassed:`✅ 通过`,decisionRevised:`🔧 已修订`,decisionNeedsImprovement:`⚠️ 需改进`,resultUseful:`✅ 结果有用`,resultInvalid:`⚠️ 结果无效`,labelSuggestion:`建议: {suggestion}`,mainTask:`主任务`,stepCount:`({count} 步骤)`,processingDots:`处理中...`,waitingExecution:`等待执行中...`,realtimeLogTitle:`实时执行日志`,executingLabel:`执行中:`,preparing:`准备中...`,totalNodes:`总节点`,labelSuccess:`成功`,labelFailed:`失败`,labelSubtask:`子任务`,expandAll:`展开全部节点`,collapseAll:`收起全部节点`}}),n(`en`,{execLog:{statusSuccess:`Success`,statusFailed:`Failed`,statusProcessing:`Processing`,unknownNode:`Unknown node`,sequentialExecution:`sequential`,parallelExecution:`parallel`,subtaskCountStrategy:`{count} subtasks, {strategy}`,messageCountTitle:`Number of messages carried in this model API call`,toolCountTitle:`Number of tool definitions carried in this model API call`,messageCount:`{count} msgs`,toolCount:`{count} tools`,durationTitle:`Duration`,sectionThought:`💡 Thought`,sectionToolCall:`⚡ Tool Call`,labelTool:`Tool:`,labelParams:`Params:`,sectionFilterResult:`🔍 Filter Result`,labelSelectedTools:`Selected tools:`,labelCount:`Count:`,unitItems:``,sectionObservation:`📝 Observation`,sectionApiRequest:`📡 API Request`,labelModel:`Model:`,labelTemperature:`Temperature:`,labelTopP:`top_p:`,labelMessageCount:`Messages:`,labelToolCount:`Tools:`,sectionApiResponse:`📤 API Response`,labelFinishReason:`Finish reason:`,labelFilteredToolCount:`Filtered tool count:`,labelTokenUsage:`Token Usage:`,sectionError:`❌ Error`,sectionSubtaskResult:`✅ Subtask Result`,sectionSubtaskDesc:`📝 Task Description`,subtaskPendingNode:`(pending)`,sectionReflectionPrompt:`📊 Reflection Prompt`,sectionReflectionRaw:`📤 Reflection Result (raw)`,sectionTokenUsage:`📊 Token Usage`,overallScore:`⭐ Overall Score: {score}/10`,sectionIssues:`📋 Issues Found`,sectionSuggestions:`💡 Suggestions`,labelDecision:`🎯 Decision: {decision}`,decisionPassed:`✅ Passed`,decisionRevised:`🔧 Revised`,decisionNeedsImprovement:`⚠️ Needs Improvement`,resultUseful:`✅ Useful`,resultInvalid:`⚠️ Invalid`,labelSuggestion:`Suggestion: {suggestion}`,mainTask:`Main Task`,stepCount:`({count} steps)`,processingDots:`Processing...`,waitingExecution:`Waiting for execution...`,realtimeLogTitle:`Real-time Execution Log`,executingLabel:`Executing:`,preparing:`Preparing...`,totalNodes:`Total nodes`,labelSuccess:`Success`,labelFailed:`Failed`,labelSubtask:`Subtask`,expandAll:`Expand all nodes`,collapseAll:`Collapse all nodes`}});function Wc(e){if(e?.nodeType!==`tool_exec`||!e?.action)return``;let t=e.action.name||``,n=e.action.params;if(n==null)return``;if(typeof n==`string`&&(n=(()=>{try{return JSON.parse(n)}catch{return{raw:n}}})()),typeof n!=`object`)return String(n).trim();if(t===`execute_command`||t===`agent_exec`)return(n.command||n.cmd||``).toString().trim();if(t===`agent_file`||t===`file_upload`||t===`download_file`){let e=(n.file_path||n.filePath||n.path||n.filename||n.fileName||n.url||``).toString().trim();if(e)return e}if(t===`fetch_url`||t===`interact_element`||t===`fill_form`||t===`manage_tab`||t===`preview_ui`){let e=(n.url||n.href||n.selector||``).toString().trim();if(e)return e}if(t===`search_browser_data`||t===`search_in_page`||t===`exec_log`){let e=(n.query||n.keyword||n.text||``).toString().trim();if(e)return e}if(t===`dispatch_task`){let e=(n.task||``).toString().trim();if(e)return e}if(t===`agent_memory`){let e=(n.action||n.subAction||``).toString().trim();if(e)return e}let r=[`content`,`text`,`prompt`,`description`,`markdown`,`html`,`css`,`js`,`code`,`script`,`data`],i=Object.keys(n).filter(e=>n[e]!=null&&n[e]!==``&&!r.includes(e));if(i.length===0)return``;if(i.length===1){let e=String(n[i[0]]);return`${i[0]}: ${e}`}return i.slice(0,2).map(e=>`${e}=${JSON.stringify(n[e])}`).join(`, `)}function Gc(e){return Wc(e)}function Kc(e){let t=Array.isArray(e)?e:[],n=t.filter(e=>e&&e.nodeType===`subtask_plan`&&Array.isArray(e.items));if(n.length===0)return t;let i=t.filter(e=>e&&e.nodeType!==`subtask_plan`),a=new Set(i.filter(e=>e.nodeType===`subtask`&&typeof e.subtaskIndex==`number`).map(e=>e.subtaskIndex)),o=new Map;n.forEach(e=>{e.items.forEach(t=>{!t||typeof t.index!=`number`||o.set(t.index,{item:t,plan:e})})});let s=[];return Array.from(o.keys()).sort((e,t)=>e-t).forEach(e=>{if(a.has(e))return;let{item:t,plan:n}=o.get(e),i=r(`execLog.subtaskPendingNode`);s.push({id:`plan_pending_${n.id||`x`}_${e}`,nodeType:`subtask`,status:`pending`,iteration:0,timestamp:n.timestamp,subtaskIndex:e,subtaskId:t.id,subtaskName:t.name,description:t.description||``,nodeName:t.name?`${t.name} ${i}`:i,taskGroup:`subtask_group_${e}`,taskGroupIndex:e+1,taskGroupName:t.name,isSubtask:!0})}),i.concat(s)}function qc(e,t){let n=e=>e.status===`pending`?2**53-1:new Date(e.timestamp).getTime();return n(e)-n(t)}function Jc(e){let t=Kc(e).sort(qc),n=t.length,i=``,a=null;return t.forEach((e,t)=>{let o=e.nodeType===`subtask`,s=e.nodeType===`tool_exec`,c=e.nodeType===`api_call`,l=e.nodeType===`preselect`,u=e.nodeType===`reflection`,d=s&&e.action?.name===`plan_task`;o&&(a=e.subtaskIndex);let f=``,p=``;u?p=`🎯`:l?p=`🔍`:d?(f=`plan-task-level`,p=`📋`):o?(f=`subtask-level`,p=`🔀`):s&&a!==null?(f=`tool-level`,p=`🔧`):c&&a!==null?(f=`api-level`,p=`📡`):s?p=`⚡`:c&&(p=`📡`);let m=`○`,h=e.status||`processing`;e.status===`success`?m=`✓`:e.status===`failed`&&(m=`✗`),u&&(h=`reflection ${h}`);let g=R(e.nodeName||r(`execLog.unknownNode`));if(e.subtaskIndex!==null&&e.subtaskIndex>=0&&(g=`<span class="subtask-badge">${e.subtaskIndex+1}</span> ${g}`),e.subtaskCount&&(g+=` <span class="plan-badge">(${r(`execLog.subtaskCountStrategy`,{count:e.subtaskCount,strategy:e.strategy===`sequential`?r(`execLog.sequentialExecution`):r(`execLog.parallelExecution`)})})</span>`),(c||l||u)&&e.apiRequest){let t=[];e.apiRequest.messageCount!==void 0&&e.apiRequest.messageCount!==null&&t.push(`💬<span title="${r(`execLog.messageCountTitle`)}">${r(`execLog.messageCount`,{count:e.apiRequest.messageCount})}</span>`),!l&&e.apiRequest.toolCount!==void 0&&e.apiRequest.toolCount!==null&&t.push(`🔧<span title="${r(`execLog.toolCountTitle`)}">${r(`execLog.toolCount`,{count:e.apiRequest.toolCount})}</span>`),t.length>0&&(g+=` <span class="api-info-badge">(${t.join(` `)})</span>`)}if(s){let t=Gc(e);t&&(g+=` <span class="node-cmd-preview" title="${V(t)}">${R(t)}</span>`)}i+=`
154
154
  <div class="timeline-item ${f}" data-status="${e.status||`processing`}" data-node-type="${e.nodeType||``}">
155
155
  <div class="timeline-line"></div>
156
156
  <div class="timeline-dot ${h}">
@@ -718,15 +718,15 @@ Ctrl/Cmd+click to copy rich-text table`,downloadExcel:`Download Excel`,exportTab
718
718
 
719
719
  `)}async function Su(t){let n=(await I(async()=>{let{default:t}=await import(`./lib-YwkWjNcC.js`).then(t=>e(t.default,1));return{default:t}},__vite__mapDeps([7,1,8,6]))).default,r=await t.arrayBuffer();return(await n.extractRawText({arrayBuffer:r})).value}async function Cu(e){let t=await I(()=>import(`./xlsx-DGkz7cnk.js`),[]),n=await e.arrayBuffer(),r=t.read(n,{type:`array`}),i=[];for(let e of r.SheetNames){let n=r.Sheets[e],a=t.utils.sheet_to_csv(n);a.trim()&&i.push(`=== Sheet: ${e} ===\n${a}`)}return i.join(`
720
720
 
721
- `)}async function wu(e){switch(_u(e.name)){case`pdf`:return await xu(e);case`docx`:return await Su(e);case`doc`:throw Error(r(`fileExtract.oldDocNotSupported`));case`xlsx`:return await Cu(e);case`text`:return await bu(e);default:return await bu(e)}}async function Tu(){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=(e.pairedAgents||[]).map(e=>e.token?{...e,token:x(e.token)}:e).find(t=>t.id===e.activeAgentId);return!t?.url||!t?.token?null:{url:t.url,token:t.token}}async function Eu(e){let t=await Tu();if(!t)throw Error(r(`fileExtract.agentNotPaired`));let n=new FormData;n.append(`file`,e);let i=await fetch(`${t.url}/api/files/upload`,{method:`POST`,headers:{Authorization:`Bearer ${t.token}`},body:n});if(!i.ok){let e=await i.text().catch(()=>``);throw Error(r(`fileExtract.agentUploadFailed`,{status:i.status,error:e}))}let a=await i.json();return{path:a.path||``,text:a.text||``}}async function Du(e,t){let n=await Tu();if(!n)throw Error(r(`fileExtract.agentNotPaired`));let i=await fetch(`${n.url}${e}`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n.token}`},body:JSON.stringify(t)});if(!i.ok)throw Error(`HTTP ${i.status}`);return await i.json()}async function Ou(e){let t=await Du(`/api/documents/extract-images`,{path:e.agentPath});if(!t||t.success!==!0)throw Error(t?.error||`extractFailed`);e.images=t.images,e.truncated=t.truncated||0,e.skipped=t.skipped||0,e.imageSource=`agent`;let n=await Tu();if(n)for(let t of(e.images||[]).slice(0,we.DESCRIBE_LIMIT))try{let e=await fetch(`${n.url}/api/fs/download`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n.token}`},body:JSON.stringify({path:t.path})}).then(e=>e.json());if(e.success&&e.content){let n=await Ne(`data:${e.mimeType};base64,${e.content}`);n===null?t.overLimit=!0:t.dataUrl=n}}catch{}}async function ku(e,t,n){let{images:r,truncated:i,skipped:a}=n===`docx`?await me(t):n===`xlsx`?await le(t):await Pe(t);for(let e of r){let t=await Ne(e.dataUrl);t===null?(e.overLimit=!0,delete e.dataUrl):e.dataUrl=t}e.images=r,e.truncated=i,e.skipped=a,e.imageSource=`local`}async function Au(e,t,n,r){if(F.enableImageInput&&!(n!==`docx`&&n!==`pdf`&&n!==`xlsx`))try{if(r&&n===`docx`)try{await Ou(e)}catch(r){a.warn(`[FileExtract] agent image extract failed, downgrade to local:`,r.message),await ku(e,t,n)}else await ku(e,t,n);if(!e.images||e.images.length===0){e.imageStatus=`none`;return}e.imageStatus=`extracted`,e.imageDescriptions={};let i=await Fe(e.images.filter(e=>e.dataUrl),we.DESCRIBE_LIMIT,(t,n)=>{e.imageDescriptions[t]=n});e.imageDescriptions={...e.imageDescriptions,...i},e.imageStatus=`described`}catch(n){a.warn(`[FileExtract] image pipeline failed (degrade):`,t.name,n.message),e.images||(e.imageStatus=`error`)}}async function ju(e,t){let n=F.attachedFiles[t];if(!n)return;n.status=`extracting`,Fu();let i=_u(e.name);try{if(F.agentPlatform?.connected)try{let t=await Eu(e);n.agentPath=t.path,n.text=t.text||``,n.status=`done`,Fu(),await Au(n,e,i,!0),Fu();return}catch(e){a.warn(`[FileExtract] Agent upload failed,downgrade to browserside extraction:`,e.message)}if(i===`unknown`)throw Error(r(`fileExtract.unsupportedFormat`,{name:e.name}));if(i===`doc`)throw Error(r(`fileExtract.oldDocNotSupportedBrowser`));n.text=await wu(e),n.status=`done`,Fu(),await Au(n,e,i,!1)}catch(t){a.error(`[FileExtract] file extract failed:`,e.name,t),n.status=`error`,n.error=t.message}Fu()}function Mu(e){for(let t of e){if(F.attachedFiles.some(e=>e.name===t.name&&e.size===t.size))continue;let e=URL.createObjectURL(t),n={name:t.name,size:t.size,type:t.type,dataUrl:e,text:``,status:`pending`};F.attachedFiles.push(n),ju(t,F.attachedFiles.length-1)}Fu()}function Nu(e){let t=F.attachedFiles[e];t?.dataUrl&&URL.revokeObjectURL(t.dataUrl),F.attachedFiles.splice(e,1),Fu()}function Pu(){for(let e of F.attachedFiles)e.dataUrl&&URL.revokeObjectURL(e.dataUrl);F.attachedFiles=[],Fu()}function Fu(){let e=document.getElementById(`filePreviewBar`);if(e){if(e.innerHTML=``,F.attachedFiles.length===0){e.style.display=`none`;return}e.style.display=``,F.attachedFiles.forEach((t,n)=>{let i=document.createElement(`div`);if(i.className=`file-preview-item`,i.title=`${t.name} (${yu(t.size)})`,t.isImage&&t.dataUrl){let e=document.createElement(`img`);e.className=`file-preview-thumb`,e.src=t.dataUrl,e.alt=t.name,i.appendChild(e);let n=document.createElement(`span`);n.className=`file-preview-thumb-label`,n.textContent=t.name,i.appendChild(n)}else{let e=document.createElement(`span`);e.className=`file-preview-icon`,e.textContent=vu(t.name);let n=document.createElement(`div`);n.className=`file-preview-info`;let r=document.createElement(`span`);r.className=`file-preview-name`,r.textContent=t.name;let a=document.createElement(`span`);a.className=`file-preview-meta`,a.textContent=yu(t.size),n.appendChild(r),n.appendChild(a),i.appendChild(e),i.appendChild(n)}if(t.status===`extracting`){let e=document.createElement(`span`);e.className=`file-preview-status extracting`,e.textContent=r(`fileExtract.extracting`),i.appendChild(e)}else if(t.status===`error`){let e=document.createElement(`span`);e.className=`file-preview-status error`,e.textContent=r(`fileExtract.failed`),e.title=t.error||r(`fileExtract.extractFailed`),i.appendChild(e)}else if(t.status===`done`){let e=document.createElement(`span`);e.className=`file-preview-status done`,e.textContent=`✓`,i.appendChild(e)}if(t.images&&t.images.length>0){let e=document.createElement(`span`);e.className=`file-preview-status images`,e.textContent=ge(t),e.title=pe(t),i.appendChild(e)}else !F.enableImageInput&&[`docx`,`pdf`,`xlsx`].includes(_u(t.name))&&(i.title=`${i.title} — ${r(`docImages.previewOff`)}`);let a=document.createElement(`button`);a.className=`file-preview-remove`,a.innerHTML=`×`,a.title=r(`fileExtract.removeFile`),a.addEventListener(`click`,e=>{e.stopPropagation(),Nu(n)}),i.appendChild(a),e.appendChild(i)})}}function Iu(){let e=F.attachedFiles.filter(e=>e.status===`done`);if(e.length===0)return``;let t=[],n=e.filter(e=>e.agentPath),i=e.filter(e=>!e.agentPath&&e.text);for(let e of n)t.push(r(`fileExtract.workspaceFileMarker`,{path:e.agentPath,name:e.name})+_e(e,e.name));for(let e of i){let n=e.text.length>5e4?e.text.substring(0,5e4)+`
721
+ `)}async function wu(e){switch(_u(e.name)){case`pdf`:return await xu(e);case`docx`:return await Su(e);case`doc`:throw Error(r(`fileExtract.oldDocNotSupported`));case`xlsx`:return await Cu(e);case`text`:return await bu(e);default:return await bu(e)}}async function Tu(){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=(e.pairedAgents||[]).map(e=>e.token?{...e,token:x(e.token)}:e).find(t=>t.id===e.activeAgentId);return!t?.url||!t?.token?null:{url:t.url,token:t.token}}async function Eu(e){let t=await Tu();if(!t)throw Error(r(`fileExtract.agentNotPaired`));let n=new FormData;n.append(`file`,e);let i=await fetch(`${t.url}/api/files/upload`,{method:`POST`,headers:{Authorization:`Bearer ${t.token}`},body:n});if(!i.ok){let e=await i.text().catch(()=>``);throw Error(r(`fileExtract.agentUploadFailed`,{status:i.status,error:e}))}let a=await i.json();return{path:a.path||``,text:a.text||``}}async function Du(e,t){let n=await Tu();if(!n)throw Error(r(`fileExtract.agentNotPaired`));let i=await fetch(`${n.url}${e}`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n.token}`},body:JSON.stringify(t)});if(!i.ok)throw Error(`HTTP ${i.status}`);return await i.json()}async function Ou(e){let t=await Du(`/api/documents/extract-images`,{path:e.agentPath});if(!t||t.success!==!0)throw Error(t?.error||`extractFailed`);e.images=t.images,e.truncated=t.truncated||0,e.skipped=t.skipped||0,e.imageSource=`agent`;let n=await Tu();if(n)for(let t of(e.images||[]).slice(0,we.DESCRIBE_LIMIT))try{let e=await fetch(`${n.url}/api/fs/download`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n.token}`},body:JSON.stringify({path:t.path})}).then(e=>e.json());if(e.success&&e.content){let n=await Ne(`data:${e.mimeType};base64,${e.content}`);n===null?t.overLimit=!0:t.dataUrl=n}}catch{}}async function ku(e,t,n){let{images:r,truncated:i,skipped:a}=n===`docx`?await N(t):n===`xlsx`?await le(t):await Pe(t);for(let e of r){let t=await Ne(e.dataUrl);t===null?(e.overLimit=!0,delete e.dataUrl):e.dataUrl=t}e.images=r,e.truncated=i,e.skipped=a,e.imageSource=`local`}async function Au(e,t,n,r){if(F.enableImageInput&&!(n!==`docx`&&n!==`pdf`&&n!==`xlsx`))try{if(r&&n===`docx`)try{await Ou(e)}catch(r){a.warn(`[FileExtract] agent image extract failed, downgrade to local:`,r.message),await ku(e,t,n)}else await ku(e,t,n);if(!e.images||e.images.length===0){e.imageStatus=`none`;return}e.imageStatus=`extracted`,e.imageDescriptions={};let i=await Fe(e.images.filter(e=>e.dataUrl),we.DESCRIBE_LIMIT,(t,n)=>{e.imageDescriptions[t]=n});e.imageDescriptions={...e.imageDescriptions,...i},e.imageStatus=`described`}catch(n){a.warn(`[FileExtract] image pipeline failed (degrade):`,t.name,n.message),e.images||(e.imageStatus=`error`)}}async function ju(e,t){let n=F.attachedFiles[t];if(!n)return;n.status=`extracting`,Fu();let i=_u(e.name);try{if(F.agentPlatform?.connected)try{let t=await Eu(e);n.agentPath=t.path,n.text=t.text||``,n.status=`done`,Fu(),await Au(n,e,i,!0),Fu();return}catch(e){a.warn(`[FileExtract] Agent upload failed,downgrade to browserside extraction:`,e.message)}if(i===`unknown`)throw Error(r(`fileExtract.unsupportedFormat`,{name:e.name}));if(i===`doc`)throw Error(r(`fileExtract.oldDocNotSupportedBrowser`));n.text=await wu(e),n.status=`done`,Fu(),await Au(n,e,i,!1)}catch(t){a.error(`[FileExtract] file extract failed:`,e.name,t),n.status=`error`,n.error=t.message}Fu()}function Mu(e){for(let t of e){if(F.attachedFiles.some(e=>e.name===t.name&&e.size===t.size))continue;let e=URL.createObjectURL(t),n={name:t.name,size:t.size,type:t.type,dataUrl:e,text:``,status:`pending`};F.attachedFiles.push(n),ju(t,F.attachedFiles.length-1)}Fu()}function Nu(e){let t=F.attachedFiles[e];t?.dataUrl&&URL.revokeObjectURL(t.dataUrl),F.attachedFiles.splice(e,1),Fu()}function Pu(){for(let e of F.attachedFiles)e.dataUrl&&URL.revokeObjectURL(e.dataUrl);F.attachedFiles=[],Fu()}function Fu(){let e=document.getElementById(`filePreviewBar`);if(e){if(e.innerHTML=``,F.attachedFiles.length===0){e.style.display=`none`;return}e.style.display=``,F.attachedFiles.forEach((t,n)=>{let i=document.createElement(`div`);if(i.className=`file-preview-item`,i.title=`${t.name} (${yu(t.size)})`,t.isImage&&t.dataUrl){let e=document.createElement(`img`);e.className=`file-preview-thumb`,e.src=t.dataUrl,e.alt=t.name,i.appendChild(e);let n=document.createElement(`span`);n.className=`file-preview-thumb-label`,n.textContent=t.name,i.appendChild(n)}else{let e=document.createElement(`span`);e.className=`file-preview-icon`,e.textContent=vu(t.name);let n=document.createElement(`div`);n.className=`file-preview-info`;let r=document.createElement(`span`);r.className=`file-preview-name`,r.textContent=t.name;let a=document.createElement(`span`);a.className=`file-preview-meta`,a.textContent=yu(t.size),n.appendChild(r),n.appendChild(a),i.appendChild(e),i.appendChild(n)}if(t.status===`extracting`){let e=document.createElement(`span`);e.className=`file-preview-status extracting`,e.textContent=r(`fileExtract.extracting`),i.appendChild(e)}else if(t.status===`error`){let e=document.createElement(`span`);e.className=`file-preview-status error`,e.textContent=r(`fileExtract.failed`),e.title=t.error||r(`fileExtract.extractFailed`),i.appendChild(e)}else if(t.status===`done`){let e=document.createElement(`span`);e.className=`file-preview-status done`,e.textContent=`✓`,i.appendChild(e)}if(t.images&&t.images.length>0){let e=document.createElement(`span`);e.className=`file-preview-status images`,e.textContent=_e(t),e.title=pe(t),i.appendChild(e)}else !F.enableImageInput&&[`docx`,`pdf`,`xlsx`].includes(_u(t.name))&&(i.title=`${i.title} — ${r(`docImages.previewOff`)}`);let a=document.createElement(`button`);a.className=`file-preview-remove`,a.innerHTML=`×`,a.title=r(`fileExtract.removeFile`),a.addEventListener(`click`,e=>{e.stopPropagation(),Nu(n)}),i.appendChild(a),e.appendChild(i)})}}function Iu(){let e=F.attachedFiles.filter(e=>e.status===`done`);if(e.length===0)return``;let t=[],n=e.filter(e=>e.agentPath),i=e.filter(e=>!e.agentPath&&e.text);for(let e of n)t.push(r(`fileExtract.workspaceFileMarker`,{path:e.agentPath,name:e.name})+ve(e,e.name));for(let e of i){let n=e.text.length>5e4?e.text.substring(0,5e4)+`
722
722
  `+r(`fileExtract.truncated`):e.text;t.push(r(`fileExtract.fileContentMarker`,{name:e.name})+`
723
- `+n+_e(e,e.name))}return`
723
+ `+n+ve(e,e.name))}return`
724
724
 
725
725
  `+t.join(`
726
726
 
727
727
  ---
728
728
 
729
- `)}async function Lu(){try{F.bookmarks=await ae()||[],a.debug(`[Bookmark] loadedbookmark:`,F.bookmarks.length,``)}catch(e){a.error(`[Bookmark] load bookmarks failed:`,e),F.bookmarks=[]}}function Ru(e,t){return F.bookmarks.find(n=>n.sessionId===e&&n.messageId===t)||null}async function zu(e,t,n,r){if(!e||!t)return null;let i=Ru(e,t);if(i)return i;let o={id:`bmk_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,6),sessionId:e,messageId:t,content:n||``,sessionTitle:r||``,createdAt:Date.now(),pinned:!1};try{if(await ye(o))return F.bookmarks.push(o),a.debug(`[Bookmark] bookmark successful:`,o.id),o}catch(e){a.error(`[Bookmark] bookmark failed:`,e)}return null}async function Bu(e,t){let n=Ru(e,t);if(!n)return!1;try{if(await de(n.id))return F.bookmarks=F.bookmarks.filter(e=>e.id!==n.id),a.debug(`[Bookmark] cancelbookmark:`,n.id),!0}catch(e){a.error(`[Bookmark] cancelbookmark failed:`,e)}return!1}async function Vu(e){try{if(await de(e))return F.bookmarks=F.bookmarks.filter(t=>t.id!==e),!0}catch(e){a.error(`[Bookmark] cancelbookmark failed:`,e)}return!1}async function Hu(e,t){try{if(await Ce(e,t)){let n=F.bookmarks.find(t=>t.id===e);return n&&(n.pinned=t),!0}}catch(e){a.error(`[Bookmark] pin operation failed:`,e)}return!1}function Uu(e=null){let t=F.bookmarks;return e&&(t=t.filter(t=>t.sessionId===e)),[...t].sort((e,t)=>e.pinned&&!t.pinned?-1:!e.pinned&&t.pinned?1:t.createdAt-e.createdAt)}var Wu=t({initBookmarkPanel:()=>Gu,refreshBookmarkPanel:()=>Ku,updateBookmarkBadge:()=>Xu,updateBookmarkBtnState:()=>Qu,updateBookmarkButtons:()=>Zu});n(`zh`,{bookmark:{toggleTitle:`收藏列表`,title:`消息收藏`,searchPlaceholder:`搜索收藏内容(支持 & | 组合搜索)...`,clearSearchTitle:`清除搜索`,empty:`暂无收藏`,searchCount:`搜索 {filtered}/{total}`,countResult:`{count} 条`,noMatch:`无匹配结果`,otherSessions:`其他会话`,noTextContent:`(无文本内容)`,unpinTitle:`取消置顶`,pinTitle:`置顶`,removeBookmarkTitle:`取消收藏`,addBookmarkTitle:`收藏消息`,sessionNotExistToast:`会话已不存在,收藏已自动移除`,messageNotExistToast:`消息已不存在,收藏已自动移除`}}),n(`en`,{bookmark:{toggleTitle:`Bookmarks`,title:`Message bookmarks`,searchPlaceholder:`Search bookmarks (supports & | combined search)...`,clearSearchTitle:`Clear search`,empty:`No bookmarks`,searchCount:`Search {filtered}/{total}`,countResult:`{count} items`,noMatch:`No matching results`,otherSessions:`Other sessions`,noTextContent:`(No text content)`,unpinTitle:`Unpin`,pinTitle:`Pin`,removeBookmarkTitle:`Remove bookmark`,addBookmarkTitle:`Bookmark message`,sessionNotExistToast:`Session no longer exists, bookmark automatically removed`,messageNotExistToast:`Message no longer exists, bookmark automatically removed`}});function Gu(){let e=document.createElement(`div`);e.className=`bookmark-panel-container`,e.id=`bookmarkPanelContainer`,e.innerHTML=`
729
+ `)}async function Lu(){try{F.bookmarks=await fe()||[],a.debug(`[Bookmark] loadedbookmark:`,F.bookmarks.length,``)}catch(e){a.error(`[Bookmark] load bookmarks failed:`,e),F.bookmarks=[]}}function Ru(e,t){return F.bookmarks.find(n=>n.sessionId===e&&n.messageId===t)||null}async function zu(e,t,n,r){if(!e||!t)return null;let i=Ru(e,t);if(i)return i;let o={id:`bmk_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,6),sessionId:e,messageId:t,content:n||``,sessionTitle:r||``,createdAt:Date.now(),pinned:!1};try{if(await me(o))return F.bookmarks.push(o),a.debug(`[Bookmark] bookmark successful:`,o.id),o}catch(e){a.error(`[Bookmark] bookmark failed:`,e)}return null}async function Bu(e,t){let n=Ru(e,t);if(!n)return!1;try{if(await ie(n.id))return F.bookmarks=F.bookmarks.filter(e=>e.id!==n.id),a.debug(`[Bookmark] cancelbookmark:`,n.id),!0}catch(e){a.error(`[Bookmark] cancelbookmark failed:`,e)}return!1}async function Vu(e){try{if(await ie(e))return F.bookmarks=F.bookmarks.filter(t=>t.id!==e),!0}catch(e){a.error(`[Bookmark] cancelbookmark failed:`,e)}return!1}async function Hu(e,t){try{if(await Me(e,t)){let n=F.bookmarks.find(t=>t.id===e);return n&&(n.pinned=t),!0}}catch(e){a.error(`[Bookmark] pin operation failed:`,e)}return!1}function Uu(e=null){let t=F.bookmarks;return e&&(t=t.filter(t=>t.sessionId===e)),[...t].sort((e,t)=>e.pinned&&!t.pinned?-1:!e.pinned&&t.pinned?1:t.createdAt-e.createdAt)}var Wu=t({initBookmarkPanel:()=>Gu,refreshBookmarkPanel:()=>Ku,updateBookmarkBadge:()=>Xu,updateBookmarkBtnState:()=>Qu,updateBookmarkButtons:()=>Zu});n(`zh`,{bookmark:{toggleTitle:`收藏列表`,title:`消息收藏`,searchPlaceholder:`搜索收藏内容(支持 & | 组合搜索)...`,clearSearchTitle:`清除搜索`,empty:`暂无收藏`,searchCount:`搜索 {filtered}/{total}`,countResult:`{count} 条`,noMatch:`无匹配结果`,otherSessions:`其他会话`,noTextContent:`(无文本内容)`,unpinTitle:`取消置顶`,pinTitle:`置顶`,removeBookmarkTitle:`取消收藏`,addBookmarkTitle:`收藏消息`,sessionNotExistToast:`会话已不存在,收藏已自动移除`,messageNotExistToast:`消息已不存在,收藏已自动移除`}}),n(`en`,{bookmark:{toggleTitle:`Bookmarks`,title:`Message bookmarks`,searchPlaceholder:`Search bookmarks (supports & | combined search)...`,clearSearchTitle:`Clear search`,empty:`No bookmarks`,searchCount:`Search {filtered}/{total}`,countResult:`{count} items`,noMatch:`No matching results`,otherSessions:`Other sessions`,noTextContent:`(No text content)`,unpinTitle:`Unpin`,pinTitle:`Pin`,removeBookmarkTitle:`Remove bookmark`,addBookmarkTitle:`Bookmark message`,sessionNotExistToast:`Session no longer exists, bookmark automatically removed`,messageNotExistToast:`Message no longer exists, bookmark automatically removed`}});function Gu(){let e=document.createElement(`div`);e.className=`bookmark-panel-container`,e.id=`bookmarkPanelContainer`,e.innerHTML=`
730
730
  <button class="bookmark-panel-toggle" id="bookmarkPanelToggle" title="${r(`bookmark.toggleTitle`)}">
731
731
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
732
732
  <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/>
@@ -1129,7 +1129,7 @@ After removal, the AI will no longer be able to access this directory. You can s
1129
1129
  <source src="${c}" type="${Z(o)}">
1130
1130
  </audio>
1131
1131
  <div id="mediaUnsupportedHint" style="display:none;">${u}</div>
1132
- </div>`;let d=i.querySelector(`video, audio`),f=i.querySelector(`#mediaUnsupportedHint`);if(d){let e=()=>{d.style.display=`none`,f&&(f.style.display=`block`)};d.addEventListener(`error`,e),i.querySelectorAll(`source`).forEach(t=>t.addEventListener(`error`,e))}}var fm=!1;function pm(e,t){let n=e.getBoundingClientRect();t.style.top=n.bottom+4+`px`;let r=n.right-160;t.style.left=Math.max(4,r)+`px`,t.style.right=`auto`}function mm(e,t){pm(e,t),t.classList.add(`show`)}function hm(){let e=document.getElementById(`workspacePreviewExportMenu`),t=document.getElementById(`workspacePreviewExportBtn`),n=document.getElementById(`workspacePreviewExportDropdown`);if(!e||!t||!n)return;document.body.appendChild(n),t.addEventListener(`click`,e=>{e.stopPropagation(),n.classList.contains(`show`)?n.classList.remove(`show`):mm(t,n)});let r=null,i=null;e.addEventListener(`mouseenter`,()=>{i&&=(clearTimeout(i),null),r=setTimeout(()=>{mm(t,n)},200)}),e.addEventListener(`mouseleave`,()=>{r&&=(clearTimeout(r),null),i=setTimeout(()=>{!e.matches(`:hover`)&&!n.matches(`:hover`)&&n.classList.remove(`show`)},300)}),n.addEventListener(`mouseenter`,()=>{i&&=(clearTimeout(i),null)}),n.addEventListener(`mouseleave`,()=>{i=setTimeout(()=>{!e.matches(`:hover`)&&!n.matches(`:hover`)&&n.classList.remove(`show`)},200)}),n.querySelectorAll(`.ws-export-dropdown-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let r=e.dataset.exportType;n.classList.remove(`show`),_m(r)})}),document.addEventListener(`click`,t=>{!e.contains(t.target)&&!n.contains(t.target)&&n.classList.remove(`show`)});let a=()=>{n.classList.contains(`show`)&&pm(t,n)};document.getElementById(`workspacePreviewContent`)?.addEventListener(`scroll`,a),window.addEventListener(`resize`,a)}function gm(){return document.getElementById(`workspacePreviewArea`).dataset.markdownText||``}async function _m(e){if(fm)return;fm=!0;let t=document.getElementById(`workspacePreviewExportBtn`);document.getElementById(`workspacePreviewExportMenu`);let n=document.getElementById(`workspacePreviewExportDropdown`),i=document.getElementById(`workspacePreviewArea`).dataset.previewName||`export`,o=t.innerHTML;t.innerHTML=`<svg viewBox="0 0 24 24" fill="none" style="animation: spin 0.8s linear infinite; width: 14px; height: 14px; flex-shrink: 0;"><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-dasharray="31.4" stroke-dashoffset="10" opacity="0.25"/><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-dasharray="31.4" stroke-dashoffset="10"/></svg>`,t.disabled=!0,t.style.opacity=`0.6`;try{switch(e){case`docx`:await bm(i);break;case`pdf`:await Sm(i);break;case`image`:await Cm(i);break;case`md`:wm(i);break}}catch(e){a.error(`[WorkspacePanel] export failed:`,e),L(r(`chatExport.exportFailed`,{message:e.message}),`error`)}finally{fm=!1,t.innerHTML=o,t.disabled=!1,t.style.opacity=`1`,n.classList.remove(`show`)}}async function vm(e){if(typeof mermaid>`u`)return;let{renderMermaidInContainer:t,convertSvgsToImages:n}=await I(async()=>{let{renderMermaidInContainer:e,convertSvgsToImages:t}=await import(`./chat-export-CBdPUbRE.js`);return{renderMermaidInContainer:e,convertSvgsToImages:t}},__vite__mapDeps([10,11,1,4,12,2,3,0]));await t(e),await n(e)}async function ym(e){if(typeof mermaid>`u`||!/```mermaid/i.test(e))return e;let{renderMermaidInContainer:t,convertSvgsToImages:n}=await I(async()=>{let{renderMermaidInContainer:e,convertSvgsToImages:t}=await import(`./chat-export-CBdPUbRE.js`);return{renderMermaidInContainer:e,convertSvgsToImages:t}},__vite__mapDeps([10,11,1,4,12,2,3,0]));try{let r=Ia(e),i=document.createElement(`div`);i.style.cssText=`position:fixed;left:-9999px;top:-9999px;`,i.innerHTML=r,document.body.appendChild(i),await t(i),await n(i);let a=i.querySelectorAll(`.mermaid`),o=[];for(let e of a){let t=e.querySelector(`img`);t&&t.src&&t.src.startsWith(`data:`)?o.push(t.src):o.push(null)}if(document.body.removeChild(i),o.length===0)return e;let s=0;return e.replace(/```\s*mermaid\s*[\r\n]+([\s\S]*?)```/gi,e=>{let t=o[s];return s++,t?`![mermaid](${t})`:e})}catch(t){return a.warn(`[WorkspacePanel] Mermaid pre-render failed:`,t.message),e}}async function bm(e){let{Document:t,Packer:n,Paragraph:i,TextRun:a,HeadingLevel:o,Table:s,TableRow:c,TableCell:l,AlignmentType:u,WidthType:d,BorderStyle:f,ImageRun:p,ExternalHyperlink:m,convertInchesToTwip:h}=await I(async()=>{let{Document:e,Packer:t,Paragraph:n,TextRun:r,HeadingLevel:i,Table:a,TableRow:o,TableCell:s,AlignmentType:c,WidthType:l,BorderStyle:u,ImageRun:d,ExternalHyperlink:f,convertInchesToTwip:p}=await import(`./dist-LQPh1k0y.js`);return{Document:e,Packer:t,Paragraph:n,TextRun:r,HeadingLevel:i,Table:a,TableRow:o,TableCell:s,AlignmentType:c,WidthType:l,BorderStyle:u,ImageRun:d,ExternalHyperlink:f,convertInchesToTwip:p}},__vite__mapDeps([11,1])),g=gm();if(!g){L(r(`chatExport.noContent`),`error`);return}g=await ym(g);let _=await xm(g),v=new t({styles:{default:{document:{run:{font:`Calibri`,size:22}},heading1:{run:{size:40,bold:!0,color:`333333`},paragraph:{spacing:{before:320,after:160}}},heading2:{run:{size:30,bold:!0,color:`333333`},paragraph:{spacing:{before:280,after:120}}},heading3:{run:{size:26,bold:!0,color:`333333`},paragraph:{spacing:{before:240,after:100}}}}},sections:[{properties:{page:{margin:{top:h(1),right:h(1),bottom:h(1),left:h(1)}}},children:_}]}),y=await n.toBlob(v),b=`word-${new Date().getTime()}.docx`;Tm(y,b),L(r(`workspace.downloaded`,{name:b}),`success`)}async function xm(e){let{Document:t,Packer:n,Paragraph:r,TextRun:i,HeadingLevel:a,Table:o,TableRow:s,TableCell:c,AlignmentType:l,WidthType:u,BorderStyle:d,ImageRun:f,ExternalHyperlink:p,convertInchesToTwip:m}=await I(async()=>{let{Document:e,Packer:t,Paragraph:n,TextRun:r,HeadingLevel:i,Table:a,TableRow:o,TableCell:s,AlignmentType:c,WidthType:l,BorderStyle:u,ImageRun:d,ExternalHyperlink:f,convertInchesToTwip:p}=await import(`./dist-LQPh1k0y.js`);return{Document:e,Packer:t,Paragraph:n,TextRun:r,HeadingLevel:i,Table:a,TableRow:o,TableCell:s,AlignmentType:c,WidthType:l,BorderStyle:u,ImageRun:d,ExternalHyperlink:f,convertInchesToTwip:p}},__vite__mapDeps([11,1])),{createTextRuns:h}=await I(async()=>{let{createTextRuns:e}=await import(`./chat-export-CBdPUbRE.js`);return{createTextRuns:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));if(!e||!e.trim())return[new r({children:[new i({text:``})]})];let g=[],_=e,v=[];_=_.replace(/```(\w*)\n([\s\S]*?)```/g,(e,t,n)=>{let r=v.length;return v.push({lang:t||``,code:n.trimEnd()}),`\n\n%%CODEBLOCK_${r}%%\n\n`});let y=[];_=_.replace(/<table[\s\S]*?<\/table>/gi,e=>{let t=y.length;return y.push(e),`\n\n%%HTMLTABLE_${t}%%\n\n`});let b=[];_=_.replace(/(?:^\|.+\|\s*$\n)+^\|[\s\-:|]+\|\s*$\n(?:^\|.+\|\s*$\n?)+/gm,e=>{let t=b.length;return b.push(e),`\n\n%%MDTABLE_${t}%%\n\n`});let x=_.split(/\n{2,}/).filter(e=>e.trim());function S(e){if(!e)return[];let t=/(\*\*(.+?)\*\*|(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)|__(.+?)__|(?<!_)_(?!_)(.+?)(?<!_)_(?!_)|`([^`]+)`|\[([^\]]+)\]\(([^)]+)\)|!\[([^\]]*)\]\(([^)]+)\))/,n=[],r=e;for(;r.length>0;){let e=r.match(t);if(!e){n.push(...h(r));break}let a=e.index;a>0&&n.push(...h(r.slice(0,a)));let o=e[1];if(e[2]!==void 0)n.push(...h(e[2],{bold:!0}));else if(e[3]!==void 0)n.push(...h(e[3],{italics:!0}));else if(e[4]!==void 0)n.push(...h(e[4],{bold:!0}));else if(e[5]!==void 0)n.push(...h(e[5],{italics:!0}));else if(e[6]!==void 0)n.push(new i({text:e[6],font:`Consolas`,size:20}));else if(e[7]!==void 0)n.push(new p({children:[new i({text:e[7],style:`Hyperlink`})],link:e[8]}));else if(e[9]!==void 0){let t=e[10];if(t.startsWith(`data:`))try{let[e,r]=t.split(`,`),i=e.match(/data:(image\/(\w+))/);if(i&&r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);n.push(new f({data:t,transformation:{width:400,height:300},type:i[2]}))}}catch{n.push(new i({text:`[Image]`,italics:!0,color:`999999`}))}else n.push(new i({text:`[Image: `+(e[9]||t)+`]`,italics:!0,color:`999999`}))}r=r.slice(a+o.length)}return n}function C(e){let t=new DOMParser().parseFromString(e,`text/html`),n=[];return t.querySelectorAll(`tr`).forEach(e=>{let t=[];e.querySelectorAll(`th, td`).forEach(e=>t.push(e.textContent.trim())),t.length>0&&n.push(t)}),n}function w(e){let t=e.trim().split(`
1132
+ </div>`;let d=i.querySelector(`video, audio`),f=i.querySelector(`#mediaUnsupportedHint`);if(d){let e=()=>{d.style.display=`none`,f&&(f.style.display=`block`)};d.addEventListener(`error`,e),i.querySelectorAll(`source`).forEach(t=>t.addEventListener(`error`,e))}}var fm=!1;function pm(e,t){let n=e.getBoundingClientRect();t.style.top=n.bottom+4+`px`;let r=n.right-160;t.style.left=Math.max(4,r)+`px`,t.style.right=`auto`}function mm(e,t){pm(e,t),t.classList.add(`show`)}function hm(){let e=document.getElementById(`workspacePreviewExportMenu`),t=document.getElementById(`workspacePreviewExportBtn`),n=document.getElementById(`workspacePreviewExportDropdown`);if(!e||!t||!n)return;document.body.appendChild(n),t.addEventListener(`click`,e=>{e.stopPropagation(),n.classList.contains(`show`)?n.classList.remove(`show`):mm(t,n)});let r=null,i=null;e.addEventListener(`mouseenter`,()=>{i&&=(clearTimeout(i),null),r=setTimeout(()=>{mm(t,n)},200)}),e.addEventListener(`mouseleave`,()=>{r&&=(clearTimeout(r),null),i=setTimeout(()=>{!e.matches(`:hover`)&&!n.matches(`:hover`)&&n.classList.remove(`show`)},300)}),n.addEventListener(`mouseenter`,()=>{i&&=(clearTimeout(i),null)}),n.addEventListener(`mouseleave`,()=>{i=setTimeout(()=>{!e.matches(`:hover`)&&!n.matches(`:hover`)&&n.classList.remove(`show`)},200)}),n.querySelectorAll(`.ws-export-dropdown-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let r=e.dataset.exportType;n.classList.remove(`show`),_m(r)})}),document.addEventListener(`click`,t=>{!e.contains(t.target)&&!n.contains(t.target)&&n.classList.remove(`show`)});let a=()=>{n.classList.contains(`show`)&&pm(t,n)};document.getElementById(`workspacePreviewContent`)?.addEventListener(`scroll`,a),window.addEventListener(`resize`,a)}function gm(){return document.getElementById(`workspacePreviewArea`).dataset.markdownText||``}async function _m(e){if(fm)return;fm=!0;let t=document.getElementById(`workspacePreviewExportBtn`);document.getElementById(`workspacePreviewExportMenu`);let n=document.getElementById(`workspacePreviewExportDropdown`),i=document.getElementById(`workspacePreviewArea`).dataset.previewName||`export`,o=t.innerHTML;t.innerHTML=`<svg viewBox="0 0 24 24" fill="none" style="animation: spin 0.8s linear infinite; width: 14px; height: 14px; flex-shrink: 0;"><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-dasharray="31.4" stroke-dashoffset="10" opacity="0.25"/><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-dasharray="31.4" stroke-dashoffset="10"/></svg>`,t.disabled=!0,t.style.opacity=`0.6`;try{switch(e){case`docx`:await bm(i);break;case`pdf`:await Sm(i);break;case`image`:await Cm(i);break;case`md`:wm(i);break}}catch(e){a.error(`[WorkspacePanel] export failed:`,e),L(r(`chatExport.exportFailed`,{message:e.message}),`error`)}finally{fm=!1,t.innerHTML=o,t.disabled=!1,t.style.opacity=`1`,n.classList.remove(`show`)}}async function vm(e){if(typeof mermaid>`u`)return;let{renderMermaidInContainer:t,convertSvgsToImages:n}=await I(async()=>{let{renderMermaidInContainer:e,convertSvgsToImages:t}=await import(`./chat-export-B5n-Qevt.js`);return{renderMermaidInContainer:e,convertSvgsToImages:t}},__vite__mapDeps([10,11,1,4,12,2,3,0]));await t(e),await n(e)}async function ym(e){if(typeof mermaid>`u`||!/```mermaid/i.test(e))return e;let{renderMermaidInContainer:t,convertSvgsToImages:n}=await I(async()=>{let{renderMermaidInContainer:e,convertSvgsToImages:t}=await import(`./chat-export-B5n-Qevt.js`);return{renderMermaidInContainer:e,convertSvgsToImages:t}},__vite__mapDeps([10,11,1,4,12,2,3,0]));try{let r=Ia(e),i=document.createElement(`div`);i.style.cssText=`position:fixed;left:-9999px;top:-9999px;`,i.innerHTML=r,document.body.appendChild(i),await t(i),await n(i);let a=i.querySelectorAll(`.mermaid`),o=[];for(let e of a){let t=e.querySelector(`img`);t&&t.src&&t.src.startsWith(`data:`)?o.push(t.src):o.push(null)}if(document.body.removeChild(i),o.length===0)return e;let s=0;return e.replace(/```\s*mermaid\s*[\r\n]+([\s\S]*?)```/gi,e=>{let t=o[s];return s++,t?`![mermaid](${t})`:e})}catch(t){return a.warn(`[WorkspacePanel] Mermaid pre-render failed:`,t.message),e}}async function bm(e){let{Document:t,Packer:n,Paragraph:i,TextRun:a,HeadingLevel:o,Table:s,TableRow:c,TableCell:l,AlignmentType:u,WidthType:d,BorderStyle:f,ImageRun:p,ExternalHyperlink:m,convertInchesToTwip:h}=await I(async()=>{let{Document:e,Packer:t,Paragraph:n,TextRun:r,HeadingLevel:i,Table:a,TableRow:o,TableCell:s,AlignmentType:c,WidthType:l,BorderStyle:u,ImageRun:d,ExternalHyperlink:f,convertInchesToTwip:p}=await import(`./dist-LQPh1k0y.js`);return{Document:e,Packer:t,Paragraph:n,TextRun:r,HeadingLevel:i,Table:a,TableRow:o,TableCell:s,AlignmentType:c,WidthType:l,BorderStyle:u,ImageRun:d,ExternalHyperlink:f,convertInchesToTwip:p}},__vite__mapDeps([11,1])),g=gm();if(!g){L(r(`chatExport.noContent`),`error`);return}g=await ym(g);let _=await xm(g),v=new t({styles:{default:{document:{run:{font:`Calibri`,size:22}},heading1:{run:{size:40,bold:!0,color:`333333`},paragraph:{spacing:{before:320,after:160}}},heading2:{run:{size:30,bold:!0,color:`333333`},paragraph:{spacing:{before:280,after:120}}},heading3:{run:{size:26,bold:!0,color:`333333`},paragraph:{spacing:{before:240,after:100}}}}},sections:[{properties:{page:{margin:{top:h(1),right:h(1),bottom:h(1),left:h(1)}}},children:_}]}),y=await n.toBlob(v),b=`word-${new Date().getTime()}.docx`;Tm(y,b),L(r(`workspace.downloaded`,{name:b}),`success`)}async function xm(e){let{Document:t,Packer:n,Paragraph:r,TextRun:i,HeadingLevel:a,Table:o,TableRow:s,TableCell:c,AlignmentType:l,WidthType:u,BorderStyle:d,ImageRun:f,ExternalHyperlink:p,convertInchesToTwip:m}=await I(async()=>{let{Document:e,Packer:t,Paragraph:n,TextRun:r,HeadingLevel:i,Table:a,TableRow:o,TableCell:s,AlignmentType:c,WidthType:l,BorderStyle:u,ImageRun:d,ExternalHyperlink:f,convertInchesToTwip:p}=await import(`./dist-LQPh1k0y.js`);return{Document:e,Packer:t,Paragraph:n,TextRun:r,HeadingLevel:i,Table:a,TableRow:o,TableCell:s,AlignmentType:c,WidthType:l,BorderStyle:u,ImageRun:d,ExternalHyperlink:f,convertInchesToTwip:p}},__vite__mapDeps([11,1])),{createTextRuns:h}=await I(async()=>{let{createTextRuns:e}=await import(`./chat-export-B5n-Qevt.js`);return{createTextRuns:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));if(!e||!e.trim())return[new r({children:[new i({text:``})]})];let g=[],_=e,v=[];_=_.replace(/```(\w*)\n([\s\S]*?)```/g,(e,t,n)=>{let r=v.length;return v.push({lang:t||``,code:n.trimEnd()}),`\n\n%%CODEBLOCK_${r}%%\n\n`});let y=[];_=_.replace(/<table[\s\S]*?<\/table>/gi,e=>{let t=y.length;return y.push(e),`\n\n%%HTMLTABLE_${t}%%\n\n`});let b=[];_=_.replace(/(?:^\|.+\|\s*$\n)+^\|[\s\-:|]+\|\s*$\n(?:^\|.+\|\s*$\n?)+/gm,e=>{let t=b.length;return b.push(e),`\n\n%%MDTABLE_${t}%%\n\n`});let x=_.split(/\n{2,}/).filter(e=>e.trim());function S(e){if(!e)return[];let t=/(\*\*(.+?)\*\*|(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)|__(.+?)__|(?<!_)_(?!_)(.+?)(?<!_)_(?!_)|`([^`]+)`|\[([^\]]+)\]\(([^)]+)\)|!\[([^\]]*)\]\(([^)]+)\))/,n=[],r=e;for(;r.length>0;){let e=r.match(t);if(!e){n.push(...h(r));break}let a=e.index;a>0&&n.push(...h(r.slice(0,a)));let o=e[1];if(e[2]!==void 0)n.push(...h(e[2],{bold:!0}));else if(e[3]!==void 0)n.push(...h(e[3],{italics:!0}));else if(e[4]!==void 0)n.push(...h(e[4],{bold:!0}));else if(e[5]!==void 0)n.push(...h(e[5],{italics:!0}));else if(e[6]!==void 0)n.push(new i({text:e[6],font:`Consolas`,size:20}));else if(e[7]!==void 0)n.push(new p({children:[new i({text:e[7],style:`Hyperlink`})],link:e[8]}));else if(e[9]!==void 0){let t=e[10];if(t.startsWith(`data:`))try{let[e,r]=t.split(`,`),i=e.match(/data:(image\/(\w+))/);if(i&&r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);n.push(new f({data:t,transformation:{width:400,height:300},type:i[2]}))}}catch{n.push(new i({text:`[Image]`,italics:!0,color:`999999`}))}else n.push(new i({text:`[Image: `+(e[9]||t)+`]`,italics:!0,color:`999999`}))}r=r.slice(a+o.length)}return n}function C(e){let t=new DOMParser().parseFromString(e,`text/html`),n=[];return t.querySelectorAll(`tr`).forEach(e=>{let t=[];e.querySelectorAll(`th, td`).forEach(e=>t.push(e.textContent.trim())),t.length>0&&n.push(t)}),n}function w(e){let t=e.trim().split(`
1133
1133
  `),n=[];for(let e of t){if(/^[\s\|:\-]+$/.test(e.replace(/\|/g,``)))continue;let t=Ra(e).slice(1,-1).map(e=>e.trim());t.length>0&&n.push(t)}return n}function T(e){if(e.length===0)return new r({children:[]});let t=Math.max(...e.map(e=>e.length));return new o({rows:e.map((e,n)=>{let i=[];for(let a=0;a<t;a++){let o=e[a]||``;i.push(new c({children:[new r({children:S(o),spacing:{before:40,after:40}})],shading:n===0?{fill:`F2F2F2`}:void 0,width:{size:100/t,type:u.PERCENTAGE}}))}return new s({children:i})}),width:{size:100,type:u.PERCENTAGE},borders:{top:{style:d.SINGLE,size:1,color:`DDDDDD`},bottom:{style:d.SINGLE,size:1,color:`DDDDDD`},left:{style:d.SINGLE,size:1,color:`DDDDDD`},right:{style:d.SINGLE,size:1,color:`DDDDDD`},insideHorizontal:{style:d.SINGLE,size:1,color:`DDDDDD`},insideVertical:{style:d.SINGLE,size:1,color:`DDDDDD`}}})}for(let e of x){let t=e.trim(),n=t.match(/^%%CODEBLOCK_(\d+)%%$/);if(n){let{lang:e,code:t}=v[parseInt(n[1])],a=e?`${e} code`:`code`;g.push(new r({children:[new i({text:a,bold:!0,font:`Consolas`,size:18})]}));let o=t.split(`
1134
1134
  `);for(let e of o)g.push(new r({children:[new i({text:e||` `,font:`Consolas`,size:18})],spacing:{before:0,after:0,line:240},shading:{fill:`F5F5F5`}}));g.push(new r({children:[new i({text:``})]}));continue}let o=t.match(/^%%HTMLTABLE_(\d+)%%$/);if(o){let e=C(y[parseInt(o[1])]);e.length>0&&(g.push(T(e)),g.push(new r({children:[new i({text:``})]})));continue}let s=t.match(/^%%MDTABLE_(\d+)%%$/);if(s){let e=w(b[parseInt(s[1])]);g.push(T(e)),g.push(new r({children:[new i({text:``})]}));continue}let c=t.match(/^(#{1,6})\s+(.+)/);if(c){let e={1:a.HEADING_1,2:a.HEADING_2,3:a.HEADING_3,4:a.HEADING_4,5:a.HEADING_5,6:a.HEADING_6};g.push(new r({children:S(c[2]),heading:e[c[1].length]||a.HEADING_1,border:{bottom:{style:d.SINGLE,size:6,color:`EAECEF`}}}));let n=t.slice(c[0].length).replace(/^\n+/,``).trim();n&&g.push(new r({children:S(n),spacing:{before:60,after:60}}));continue}if(/^(---|\*\*\*|___)\s*$/.test(t)){g.push(new r({children:[],border:{bottom:{style:d.SINGLE,size:6,color:`CCCCCC`}},spacing:{before:200,after:200}}));continue}if(/^[\-\*\+]\s+/.test(t)){let t=e.split(/\n(?=[\-\*\+]\s+)/);for(let e of t)g.push(new r({children:S(e.replace(/^[\-\*\+]\s+/,``)),bullet:{level:0},spacing:{before:40,after:40}}));continue}if(/^\d+\.\s+/.test(t)){let t=e.split(/\n(?=\d+\.\s+)/);for(let e of t)g.push(new r({children:S(e.replace(/^\d+\.\s+/,``)),numbering:{reference:`default`,level:0},spacing:{before:40,after:40}}));continue}if(t.startsWith(`>`)){let t=e.split(`
1135
1135
  `).map(e=>e.replace(/^>\s?/,``)).join(`
@@ -1575,7 +1575,7 @@ After removal, the AI will no longer be able to access this directory. You can s
1575
1575
  ... (点击展开查看完整输出)`,execResult:`执行结果`,statusFailed:`失败`,statusCompleted:`完成`,preselectFiltered:`从 {total} 个工具中筛选出 <strong>{count}</strong> 个:`,preselectSkippedAll:`跳过筛选({reason}),使用全部工具`,preselectSkippedCount:`跳过筛选({reason}),工具总数 {count}`,preselectDirectAnswer:`模型直接回答:`,toolPreselect:`工具预筛选`,toolsAfterFilter:`筛选后工具数:<strong>{count}</strong>`,listSeparator:`、`,totalNodes:`总节点`,successLabel:`成功`,failedLabel:`失败`,tokenLabel:`Token`,tokenUsageTitle:`Token 消耗: {total} (Prompt: {prompt}, Completion: {completion})`,thinkingProcess:`思考过程`,copyMarkdown:`复制 Markdown 内容 (Ctrl/Cmd + 点击复制富文本)`,copy:`复制`,quoteTitle:`引用该内容问答`,quote:`引用`,export:`导出`,exportWord:`导出 Word`,exportPdf:`导出 PDF`,exportImage:`导出图片`,exportMarkdown:`导出 Markdown`,executionLog:`执行日志`,reflectionRoundsTag:` ({count}轮)`,qualityAssessmentTitle:`AI 质量评估: {score}/10{rounds}
1576
1576
  点击查看评估详情`,reflectionFailedTitle:`反思评估失败(点击查看执行日志)`,reflectionFailedBadge:`⚠️ 反思失败`,prototypeOpenedLocal:`已在本地浏览器打开,点击可在面板内查看`,viewUiPrototype:`查看 UI 原型`,bookmarkMessage:`收藏消息`,removeBookmark:`取消收藏`,forkSession:`从此处分叉会话(仅复制到此条消息)`,deleteMessage:`删除消息`,stopping:`停止中...`,taskStopped:`任务已被用户停止`,cancelled:`已取消`}}),n(`en`,{chatStream:{thinking:`Thinking...`,outputting:`Outputting...`,stopGenerating:`Stop generating`,thinkingResult:`Thinking result`,toolActionOperate:`Operate`,toolActionUpload:`Upload`,toolActionDownload:`Download`,toolActionRequest:`Request`,toolActionInteract:`Interact`,toolActionFill:`Fill`,toolActionDispatch:`Dispatch`,toolActionPreview:`Preview`,toolActionRead:`Read`,toolActionWrite:`Write`,terminateCommand:`Terminate command`,abortWaiting:`Abort waiting (skip current tool wait, does not terminate the actual process)`,executing:`Executing...`,terminating:`Terminating...`,copyCode:`Copy code`,truncatedTitle:`Original result too large, truncated for display`,truncatedNote:`(output too long, truncated)`,noOutput:`(no output)`,execFailed:`Execution failed`,clickToExpand:`
1577
1577
  ... (click to expand and view full output)`,execResult:`Execution result`,statusFailed:`Failed`,statusCompleted:`Completed`,preselectFiltered:`Filtered <strong>{count}</strong> of {total} tools: `,preselectSkippedAll:`Skipped filtering ({reason}), using all tools`,preselectSkippedCount:`Skipped filtering ({reason}), total tools: {count}`,preselectDirectAnswer:`Model direct answer: `,toolPreselect:`Tool Pre-filter`,toolsAfterFilter:`Tools after filtering: <strong>{count}</strong>`,listSeparator:`, `,totalNodes:`Total nodes`,successLabel:`Success`,failedLabel:`Failed`,tokenLabel:`Token`,tokenUsageTitle:`Token usage: {total} (Prompt: {prompt}, Completion: {completion})`,thinkingProcess:`Thinking process`,copyMarkdown:`Copy Markdown content (Ctrl/Cmd + click to copy rich text)`,copy:`Copy`,quoteTitle:`Quote this content for Q&A`,quote:`Quote`,export:`Export`,exportWord:`Export Word`,exportPdf:`Export PDF`,exportImage:`Export Image`,exportMarkdown:`Export Markdown`,executionLog:`Execution log`,reflectionRoundsTag:` ({count} rounds)`,qualityAssessmentTitle:`AI quality assessment: {score}/10{rounds}
1578
- Click to view assessment details`,reflectionFailedTitle:`Reflection assessment failed (click to view execution log)`,reflectionFailedBadge:`⚠️ Reflection failed`,prototypeOpenedLocal:`Already opened in local browser, click to view in panel`,viewUiPrototype:`View UI prototype`,bookmarkMessage:`Bookmark message`,removeBookmark:`Remove bookmark`,forkSession:`Fork session from here (copy up to this message only)`,deleteMessage:`Delete message`,stopping:`Stopping...`,taskStopped:`Task stopped by user`,cancelled:`Cancelled`}});var rv=new Map,iv=!1,av=!1,ov=!1,sv=!1;function cv(){let e=document.getElementById(`scrollToBottomBtn`),t=document.getElementById(`scrollToBottomBadge`);if(!e)return;let n=document.getElementById(`chatContainer`);if(!n)return;let r=n.scrollHeight-n.scrollTop-n.clientHeight<80;r?(e.classList.remove(`visible`),sv=!1):e.classList.add(`visible`),t&&(sv&&!r?(t.classList.add(`active`),F.isGenerating?t.classList.add(`pulsing`):t.classList.remove(`pulsing`)):t.classList.remove(`active`,`pulsing`))}function lv(){if(ov)return;let e=document.getElementById(`chatContainer`);e&&(ov=!0,e.addEventListener(`scroll`,()=>{if(iv)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight<80;av=!t,t?sv=!1:F.isGenerating&&(sv=!0),cv()},{passive:!0}),document.addEventListener(`generating-state-changed`,()=>{F.isGenerating&&(sv=!0),requestAnimationFrame(()=>cv())}))}function uv(e,t={}){if(!e)return;lv();let{force:n=!1,smooth:r=!1}=t;if(!n&&av){sv=!0,cv();return}if(iv=!0,r){e.scrollTo({top:e.scrollHeight,behavior:`smooth`}),requestAnimationFrame(()=>{iv=!1});return}e.scrollTop=e.scrollHeight,requestAnimationFrame(()=>{av||(e.scrollTop=e.scrollHeight),requestAnimationFrame(()=>{iv=!1})})}function dv(e){if(!e||!e.isConnected)return;let t=document.getElementById(`chatContainer`);t&&uv(t)}function fv(){av=!1,sv=!1,F.isGenerating&&(sv=!0),cv()}function pv(){lv();let e=document.getElementById(`scrollToBottomBtn`);if(!e||e.dataset.bound)return;e.dataset.bound=`1`;let t=localStorage.getItem(`scrollBtnPosition`)||`center`;e.classList.add(`pos-${t}`);let n=!1,r=0,i=0,a=!1,o=0,s=!1;function c(){let t=document.getElementById(`chatContainer`);if(!t)return;let n=t.clientWidth,r={left:n/6,center:n/2,right:n*5/6},i=`center`,a=1/0;for(let[e,t]of Object.entries(r)){let n=Math.abs(o-t);n<a&&(a=n,i=e)}e.classList.remove(`pos-left`,`pos-center`,`pos-right`),e.classList.add(`pos-${i}`),e.style.left=``,e.style.marginLeft=``,e.style.right=``,localStorage.setItem(`scrollBtnPosition`,i)}function l(){let t=document.getElementById(`chatContainer`),n=e.getBoundingClientRect(),a=t?t.getBoundingClientRect():null,o=a?n.left-a.left+n.width/2:r;e.classList.remove(`pos-left`,`pos-center`,`pos-right`),e.style.left=`${o}px`,e.style.marginLeft=`0`,e.style.right=`auto`,e.classList.add(`dragging`),i=o,s=!0}function u(e){e.type===`mousedown`&&e.button!==0||(e.preventDefault(),n=!0,a=!1,s=!1,r=e.touches?e.touches[0].clientX:e.clientX)}function d(t){if(!n)return;let c=t.touches?t.touches[0].clientX:t.clientX;if(!s){if(Math.abs(c-r)<=3)return;a=!0,l()}let u=document.getElementById(`chatContainer`);if(!u)return;let d=u.getBoundingClientRect(),f=i+(c-r),p=e.offsetWidth/2;f=Math.max(p,Math.min(d.width-p,f)),o=f,e.style.left=`${f}px`}function f(){if(n){if(n=!1,a)e.classList.remove(`dragging`),c();else{s&&(e.classList.remove(`dragging`),e.style.left=``,e.style.marginLeft=``,e.style.right=``);let t=document.getElementById(`chatContainer`);t&&(av=!1,sv=!1,cv(),uv(t,{force:!0,smooth:!0}))}a=!1,s=!1}}e.addEventListener(`mousedown`,u),e.addEventListener(`touchstart`,u,{passive:!1}),document.addEventListener(`mousemove`,d),document.addEventListener(`touchmove`,d,{passive:!1}),document.addEventListener(`mouseup`,f),document.addEventListener(`touchend`,f),cv()}function mv(){lv();let e=document.getElementById(`chatContainer`);e&&(e.scrollHeight-e.scrollTop-e.clientHeight<80||(sv=!0),cv())}function hv(e,t){let n=e.querySelector(`.thinking-process-content`);if(!n)return;e.dataset.activeFilter=t,e.querySelectorAll(`.thinking-process-stat[data-filter]`).forEach(e=>{e.classList.toggle(`active`,e.dataset.filter===t)});let r=e=>t===`all`||e===t;n.querySelectorAll(`.tool-call-item`).forEach(e=>{e.classList.contains(`preselect-card`)||(e.style.display=r(e.dataset.status)?``:`none`)}),n.querySelectorAll(`.thinking-badge`).forEach(e=>{let t=r(e.dataset.status||`success`);e.style.display=t?``:`none`;let n=e.nextElementSibling;n&&n.classList.contains(`thinking-content`)&&(n.style.display=t?``:`none`)}),n.querySelectorAll(`.thinking-content`).forEach(e=>{let t=e.previousElementSibling;t&&t.classList.contains(`thinking-badge`)||(e.style.display=r(`success`)?``:`none`)})}function gv(e){if(!e||e._filterBound)return;e._filterBound=!0;let t=[``,`success`,`failed`];e.querySelectorAll(`.thinking-process-stat`).forEach((e,n)=>{t[n]&&(e.dataset.filter=t[n],e.classList.add(`filterable`))}),e.querySelectorAll(`.token-stat`).forEach(e=>{e.style.cursor=`pointer`}),e.addEventListener(`click`,t=>{if(t.ctrlKey||t.metaKey)return;let n=t.target.closest(`.thinking-process-stat`),r=e.closest(`.thinking-process`);if(r){if(n&&n.classList.contains(`token-stat`)){let e=r.closest(`.message`);if(e)try{let t=e.dataset.executionLog,r=ot(t?JSON.parse(t):[]);r&&ft(r,n)}catch{}return}n&&n.dataset.filter?hv(r,r.dataset.activeFilter===n.dataset.filter?`all`:n.dataset.filter):r.classList.toggle(`collapsed`)}});let n=e.closest(`.thinking-process`);n&&hv(n,n.dataset.activeFilter||`all`)}async function _v(){try{let{getAllAgents:e}=await I(async()=>{let{getAllAgents:e}=await import(`./agent-store-BvS-vIQr.js`).then(e=>e.t);return{getAllAgents:e}},__vite__mapDeps([0,1,2,3,4])),t=await e();rv.clear();for(let e of t)rv.set(e.id,e.name||e.id)}catch{}}function vv(e){return rv.get(e)||e}var yv=new Map,bv=new Map,xv=null,Sv=0,Cv=0;function wv(e){return t=>t===void 0?yv.get(e)||null:(yv.set(e,t),t)}function Tv(e){yv.delete(e),bv.delete(e)}function Ev(e,t){bv.set(e,t)}function Dv(){return xv}function Ov(e){xv=e}function kv(e){Sv=e}function Av(e){Cv=e}function jv(e){}function Mv(e){let t=document.getElementById(`chatContainer`),n=document.createElement(`div`);n.className=`message-wrapper assistant streaming`;let i=`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8);n.dataset.messageId=i,n.dataset.sessionId=e||``,n.innerHTML=`
1578
+ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment failed (click to view execution log)`,reflectionFailedBadge:`⚠️ Reflection failed`,prototypeOpenedLocal:`Already opened in local browser, click to view in panel`,viewUiPrototype:`View UI prototype`,bookmarkMessage:`Bookmark message`,removeBookmark:`Remove bookmark`,forkSession:`Fork session from here (copy up to this message only)`,deleteMessage:`Delete message`,stopping:`Stopping...`,taskStopped:`Task stopped by user`,cancelled:`Cancelled`}});var rv=new Map,iv=!1,av=!1,ov=!1,sv=!1;function cv(){let e=document.getElementById(`scrollToBottomBtn`),t=document.getElementById(`scrollToBottomBadge`);if(!e)return;let n=document.getElementById(`chatContainer`);if(!n)return;let r=n.scrollHeight-n.scrollTop-n.clientHeight<80;r?(e.classList.remove(`visible`),sv=!1):e.classList.add(`visible`),t&&(sv&&!r?(t.classList.add(`active`),F.isGenerating?t.classList.add(`pulsing`):t.classList.remove(`pulsing`)):t.classList.remove(`active`,`pulsing`))}function lv(){if(ov)return;let e=document.getElementById(`chatContainer`);e&&(ov=!0,e.addEventListener(`scroll`,()=>{if(iv)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight<80;av=!t,t?sv=!1:F.isGenerating&&(sv=!0),cv()},{passive:!0}),document.addEventListener(`generating-state-changed`,()=>{F.isGenerating&&(sv=!0),requestAnimationFrame(()=>cv())}))}function uv(e,t={}){if(!e)return;lv();let{force:n=!1,smooth:r=!1}=t;if(!n&&av){sv=!0,cv();return}if(iv=!0,r){e.scrollTo({top:e.scrollHeight,behavior:`smooth`}),requestAnimationFrame(()=>{iv=!1});return}e.scrollTop=e.scrollHeight,requestAnimationFrame(()=>{av||(e.scrollTop=e.scrollHeight),requestAnimationFrame(()=>{iv=!1})})}function dv(e){if(!e||!e.isConnected)return;let t=document.getElementById(`chatContainer`);t&&uv(t)}function fv(){av=!1,sv=!1,F.isGenerating&&(sv=!0),cv()}function pv(){lv();let e=document.getElementById(`scrollToBottomBtn`);if(!e||e.dataset.bound)return;e.dataset.bound=`1`;let t=localStorage.getItem(`scrollBtnPosition`)||`center`;e.classList.add(`pos-${t}`);let n=!1,r=0,i=0,a=!1,o=0,s=!1;function c(){let t=document.getElementById(`chatContainer`);if(!t)return;let n=t.clientWidth,r={left:n/6,center:n/2,right:n*5/6},i=`center`,a=1/0;for(let[e,t]of Object.entries(r)){let n=Math.abs(o-t);n<a&&(a=n,i=e)}e.classList.remove(`pos-left`,`pos-center`,`pos-right`),e.classList.add(`pos-${i}`),e.style.left=``,e.style.marginLeft=``,e.style.right=``,localStorage.setItem(`scrollBtnPosition`,i)}function l(){let t=document.getElementById(`chatContainer`),n=e.getBoundingClientRect(),a=t?t.getBoundingClientRect():null,o=a?n.left-a.left+n.width/2:r;e.classList.remove(`pos-left`,`pos-center`,`pos-right`),e.style.left=`${o}px`,e.style.marginLeft=`0`,e.style.right=`auto`,e.classList.add(`dragging`),i=o,s=!0}function u(e){e.type===`mousedown`&&e.button!==0||(e.preventDefault(),n=!0,a=!1,s=!1,r=e.touches?e.touches[0].clientX:e.clientX)}function d(t){if(!n)return;let c=t.touches?t.touches[0].clientX:t.clientX;if(!s){if(Math.abs(c-r)<=3)return;a=!0,l()}let u=document.getElementById(`chatContainer`);if(!u)return;let d=u.getBoundingClientRect(),f=i+(c-r),p=e.offsetWidth/2;f=Math.max(p,Math.min(d.width-p,f)),o=f,e.style.left=`${f}px`}function f(){if(n){if(n=!1,a)e.classList.remove(`dragging`),c();else{s&&(e.classList.remove(`dragging`),e.style.left=``,e.style.marginLeft=``,e.style.right=``);let t=document.getElementById(`chatContainer`);t&&(av=!1,sv=!1,cv(),uv(t,{force:!0,smooth:!0}))}a=!1,s=!1}}e.addEventListener(`mousedown`,u),e.addEventListener(`touchstart`,u,{passive:!1}),document.addEventListener(`mousemove`,d),document.addEventListener(`touchmove`,d,{passive:!1}),document.addEventListener(`mouseup`,f),document.addEventListener(`touchend`,f),cv()}function mv(){lv();let e=document.getElementById(`chatContainer`);e&&(e.scrollHeight-e.scrollTop-e.clientHeight<80||(sv=!0),cv())}function hv(e,t){let n=e.querySelector(`.thinking-process-content`);if(!n)return;e.dataset.activeFilter=t,e.querySelectorAll(`.thinking-process-stat[data-filter]`).forEach(e=>{e.classList.toggle(`active`,e.dataset.filter===t)});let r=e=>t===`all`||e===t;n.querySelectorAll(`.tool-call-item`).forEach(e=>{e.classList.contains(`preselect-card`)||(e.style.display=r(e.dataset.status)?``:`none`)}),n.querySelectorAll(`.thinking-badge`).forEach(e=>{let t=r(e.dataset.status||`success`);e.style.display=t?``:`none`;let n=e.nextElementSibling;n&&n.classList.contains(`thinking-content`)&&(n.style.display=t?``:`none`)}),n.querySelectorAll(`.thinking-content`).forEach(e=>{let t=e.previousElementSibling;t&&t.classList.contains(`thinking-badge`)||(e.style.display=r(`success`)?``:`none`)})}function gv(e){if(!e||e._filterBound)return;e._filterBound=!0;let t=[``,`success`,`failed`];e.querySelectorAll(`.thinking-process-stat`).forEach((e,n)=>{t[n]&&(e.dataset.filter=t[n],e.classList.add(`filterable`))}),e.querySelectorAll(`.token-stat`).forEach(e=>{e.style.cursor=`pointer`}),e.addEventListener(`click`,t=>{if(t.ctrlKey||t.metaKey)return;let n=t.target.closest(`.thinking-process-stat`),r=e.closest(`.thinking-process`);if(r){if(n&&n.classList.contains(`token-stat`)){let e=r.closest(`.message`);if(e)try{let t=e.dataset.executionLog,r=ot(t?JSON.parse(t):[]);r&&ft(r,n)}catch{}return}n&&n.dataset.filter?hv(r,r.dataset.activeFilter===n.dataset.filter?`all`:n.dataset.filter):r.classList.toggle(`collapsed`)}});let n=e.closest(`.thinking-process`);n&&hv(n,n.dataset.activeFilter||`all`)}async function _v(){try{let{getAllAgents:e}=await I(async()=>{let{getAllAgents:e}=await import(`./agent-store-D-jYf94_.js`).then(e=>e.t);return{getAllAgents:e}},__vite__mapDeps([0,1,2,3,4])),t=await e();rv.clear();for(let e of t)rv.set(e.id,e.name||e.id)}catch{}}function vv(e){return rv.get(e)||e}var yv=new Map,bv=new Map,xv=null,Sv=0,Cv=0;function wv(e){return t=>t===void 0?yv.get(e)||null:(yv.set(e,t),t)}function Tv(e){yv.delete(e),bv.delete(e)}function Ev(e,t){bv.set(e,t)}function Dv(){return xv}function Ov(e){xv=e}function kv(e){Sv=e}function Av(e){Cv=e}function jv(e){}function Mv(e){let t=document.getElementById(`chatContainer`),n=document.createElement(`div`);n.className=`message-wrapper assistant streaming`;let i=`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8);n.dataset.messageId=i,n.dataset.sessionId=e||``,n.innerHTML=`
1579
1579
  <div class="message-content">
1580
1580
  <div class="stream-content"></div>
1581
1581
  <div class="thinking-indicator">
@@ -1729,7 +1729,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
1729
1729
  <svg class="thinking-process-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1730
1730
  <polyline points="6 9 12 15 18 9"/>
1731
1731
  </svg>
1732
- `,d){let e=p.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),ft(d,e)}))}let g=document.createElement(`div`);g.className=`thinking-process-body`;let _=document.createElement(`div`);for(_.className=`thinking-process-content`,g.appendChild(_);l.firstChild;)_.appendChild(l.firstChild);let v=_.querySelectorAll(`.thinking-content`),y=e.trim();if(v.length>0){let e=v[v.length-1],t=e.textContent.trim();if(!s||s&&t===y){let t=e.previousElementSibling;for(;t;){if(t.classList.contains(`thinking-badge`)){t.remove();break}t=t.previousElementSibling}e.remove()}}if(_.children.length>0&&_.textContent.trim()){f.appendChild(p),f.appendChild(g);let t=document.createElement(`div`);t.className=`final-answer`,e&&e.trim()&&(t.innerHTML=Ka(e));let n=c.querySelector(`.thinking-indicator`);n&&n.remove(),c.appendChild(f),c.appendChild(t),gv(p)}else{let t=c.querySelector(`.thinking-indicator`);t&&t.remove(),e&&e.trim()&&(l.innerHTML=Ka(e))}}else e&&e.trim()&&(l.innerHTML=Ka(e))}e.classList.add(`assistant`,`message`),e.dataset.rawContent=typeof t==`string`?Fa(t):JSON.stringify(t),e.dataset.textContent_=Fa(Gv(t)),e.dataset.executionLog=JSON.stringify(n);let f=document.createElement(`div`);f.className=`message-footer`;let p=document.createElement(`button`);p.className=`copy-btn`,p.title=r(`chatStream.copyMarkdown`),p.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`,`<span>`+r(`chatStream.copy`)+`</span>`].join(``),p.addEventListener(`click`,t=>{t.stopPropagation(),B_(e,p,t)}),f.appendChild(p);let m=document.createElement(`button`);m.className=`quote-btn`,m.title=r(`chatStream.quoteTitle`),m.innerHTML=[`<svg t="1781246498458" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9645" width="14" height="14"><path d="M156.09136 606.57001a457.596822 457.596822 0 0 1 221.680239-392.516385 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z m406.752731 0a457.596822 457.596822 0 0 1 221.680239-392.007944 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z" fill="#8a8a8a" p-id="9646"></path></svg>`,`<span>`+r(`chatStream.quote`)+`</span>`].join(``),m.addEventListener(`click`,t=>{t.stopPropagation(),J_(e)}),f.appendChild(m);let h=document.createElement(`div`);h.className=`export-menu-container`;let g=document.createElement(`button`);g.className=`export-trigger-btn`,g.innerHTML=`<svg t="1781245244396" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5115" width="14" height="14"><path d="M496.213333 739.84c2.133333 2.133333 4.693333 3.84 7.68 5.12 0.853333 0.426667 2.133333 0.426667 2.986667 0.853333 1.706667 0.426667 2.986667 0.853333 4.693333 0.853334 5.546667 0 11.093333-2.133333 14.933334-6.4l256-256c8.533333-8.533333 8.533333-21.76 0-30.293334s-21.76-8.533333-30.293334 0L533.333333 674.133333V128c0-11.946667-9.386667-21.333333-21.333333-21.333333s-21.333333 9.386667-21.333333 21.333333v545.706667l-219.306667-219.306667c-8.533333-8.533333-21.76-8.533333-30.293333 0s-8.533333 21.76 0 30.293333l255.146666 255.146667zM768 874.666667H256c-11.946667 0-21.333333 9.386667-21.333333 21.333333s9.386667 21.333333 21.333333 21.333333h512c11.946667 0 21.333333-9.386667 21.333333-21.333333s-9.386667-21.333333-21.333333-21.333333z" fill="#8a8a8a" p-id="5116"></path></svg><span>`+r(`chatStream.export`)+`</span><svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`;let _=document.createElement(`div`);_.className=`export-dropdown`,_.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">`,`<svg t="1781245550030" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6544" width="32" height="32"><path d="M747.936 901.171H276.819c-72.2 0-130.953-55.224-130.953-123.078V244.721c0-67.854 58.752-123.078 130.953-123.078h383.525c6.597 0 12.937 2.505 17.795 6.954l192.363 178.046c5.317 4.96 8.386 11.914 8.386 19.227v452.223c0 67.854-58.752 123.078-130.952 123.078zM276.819 174.004c-43.31 0-78.592 31.703-78.592 70.717v533.372c0 39.015 35.282 70.718 78.592 70.718h471.117c43.31 0 78.592-31.703 78.592-70.718V337.324l-176.461-163.32H276.819z" fill="#8a8a8a" p-id="6545"></path><path d="M830.567 331.546H669.446c-14.471 0-26.18-11.71-26.18-26.181V156.209c0-14.471 11.709-26.18 26.18-26.18s26.181 11.709 26.181 26.18v122.976h134.94c14.471 0 26.181 11.709 26.181 26.18s-11.711 26.181-26.181 26.181z" fill="#8a8a8a" p-id="6546"></path><path d="M730.214 428.749l-92.04 343.616h-53.179L511.363 498.29l-75.677 274.074h-53.179l-92.04-343.616h49.088l69.542 255.667 69.541-255.667h63.406l69.541 255.667 69.541-255.667h49.088z" fill="#8a8a8a" p-id="6547"></path></svg>`,`<span>`+r(`chatStream.exportWord`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-pdf-item" type="button">`,`<svg t="1781245863206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8152" width="32" height="32"><path d="M582.4 864H170.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V170.666667c0-6.4 4.266667-10.666667 10.666667-10.666667h309.333333V320c0 40.533333 34.133333 74.666667 74.666667 74.666667h160v38.4c0 17.066667 14.933333 32 32 32s32-14.933333 32-32V298.666667c0-8.533333-4.266667-17.066667-8.533334-23.466667l-170.666666-170.666667c-6.4-6.4-14.933333-8.533333-23.466667-8.533333H170.666667C130.133333 96 96 130.133333 96 170.666667v682.666666c0 40.533333 34.133333 74.666667 74.666667 74.666667h411.733333c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32z m132.266667-550.4v17.066667H554.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V160h19.2l151.466667 153.6z" fill="#8a8a8a" p-id="8153"></path><path d="M332.8 533.333333c-12.8 0-19.2 2.133333-25.6 6.4-6.4 4.266667-8.533333 12.8-8.533333 23.466667v206.933333c0 6.4 2.133333 12.8 6.4 19.2 4.266667 4.266667 10.666667 8.533333 21.333333 8.533334s17.066667-4.266667 21.333333-8.533334c4.266667-4.266667 6.4-10.666667 6.4-19.2v-64h32c57.6 0 89.6-29.866667 89.6-87.466666 0-27.733333-8.533333-51.2-23.466666-64-14.933333-14.933333-36.266667-21.333333-66.133334-21.333334h-53.333333z m87.466667 85.333334c0 12.8-2.133333 23.466667-8.533334 27.733333-4.266667 4.266667-14.933333 8.533333-27.733333 8.533333h-32v-70.4H384c12.8 0 21.333333 2.133333 27.733333 8.533334 6.4 4.266667 8.533333 12.8 8.533334 25.6zM667.733333 571.733333c-8.533333-12.8-21.333333-21.333333-34.133333-29.866666-14.933333-4.266667-32-8.533333-51.2-8.533334h-61.866667c-8.533333 0-17.066667 0-23.466666 8.533334-2.133333 4.266667-4.266667 10.666667-4.266667 19.2V768c0 8.533333 2.133333 14.933333 4.266667 19.2 6.4 8.533333 14.933333 8.533333 23.466666 8.533333h64c19.2 0 34.133333-4.266667 49.066667-10.666666 12.8-6.4 25.6-17.066667 34.133333-29.866667 8.533333-12.8 14.933333-25.6 19.2-42.666667 4.266667-14.933333 6.4-32 6.4-49.066666 0-17.066667-2.133333-34.133333-6.4-49.066667-4.266667-14.933333-10.666667-29.866667-19.2-42.666667z m-42.666666 153.6c-8.533333 12.8-21.333333 19.2-38.4 19.2h-38.4v-160H576c21.333333 0 38.4 6.4 46.933333 19.2 10.666667 12.8 14.933333 34.133333 14.933334 59.733334 2.133333 27.733333-4.266667 46.933333-12.8 61.866666zM851.2 533.333333h-106.666667c-8.533333 0-17.066667 2.133333-21.333333 6.4-6.4 4.266667-8.533333 12.8-8.533333 21.333334v209.066666c0 6.4 2.133333 12.8 6.4 17.066667 4.266667 6.4 10.666667 8.533333 21.333333 8.533333 8.533333 0 17.066667-2.133333 21.333333-8.533333 2.133333-4.266667 6.4-8.533333 6.4-19.2v-85.333333h72.533334c12.8 0 23.466667-6.4 25.6-17.066667 2.133333-8.533333 2.133333-14.933333 0-17.066667-2.133333-4.266667-6.4-17.066667-25.6-17.066666H768v-49.066667h81.066667c8.533333 0 14.933333-2.133333 19.2-4.266667 4.266667-2.133333 8.533333-8.533333 8.533333-21.333333 2.133333-12.8-8.533333-23.466667-25.6-23.466667z" fill="#8a8a8a" p-id="8154"></path></svg>`,`<span>`+r(`chatStream.exportPdf`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-image-item" type="button">`,`<svg t="1784207887308" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5993" width="32" height="32"><path d="M400.696 268.795c-17.249 0-31.233 13.986-31.233 31.233v30.471c0 17.249 13.986 31.233 31.233 31.233s31.233-13.986 31.233-31.233v-30.471c0-17.249-13.985-31.233-31.233-31.233z" fill="#8a8a8a" p-id="5994"></path><path d="M623.649 361.734c17.249 0 31.234-13.986 31.234-31.233v-30.471c0-17.249-13.986-31.233-31.234-31.233s-31.233 13.986-31.233 31.233v30.471c-0.001 17.248 13.985 31.233 31.233 31.233z" fill="#8a8a8a" p-id="5995"></path><path d="M438.295 388.804c-14.656 9.104-19.155 28.362-10.050 43.013 11.209 18.047 41.976 48.59 86.157 48.59 43.958 0 75.1-30.313 86.574-48.223 9.303-14.529 5.068-33.847-9.455-43.15-14.539-9.298-33.852-5.068-43.15 9.455-0.122 0.199-13.38 19.45-33.969 19.45-20.009 0-32.444-18.128-33.278-19.373-9.166-14.423-28.28-18.805-42.829-9.761z" fill="#8a8a8a" p-id="5996"></path><path d="M824.508503 116.690676 571.592236 116.690676c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c40.181141 0 72.878844 32.692586 72.878844 72.878844l0 396.966057-189.334159-165.29465c-12.20088-10.655687-30.517037-10.207479-42.173518 0.9967L468.578048 674.16231 309.521472 517.519714c-11.895935-11.70253-30.903847-12.002358-43.154869-0.645706L126.957507 646.163629l0-394.126382c0-40.186258 32.692586-72.878844 72.878844-72.878844l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352S470.000444 116.690676 452.751594 116.690676L199.836351 116.690676c-74.632791 0-135.346571 60.71378-135.346571 135.346571l0 520.56405c0 74.632791 60.71378 135.346571 135.346571 135.346571l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352s-13.985526-31.233352-31.233352-31.233352L199.836351 845.481164c-40.186258 0-72.878844-32.692586-72.878844-72.878844l0-41.23924 160.003134-148.385539 159.428036 157.007917c12.048407 11.865235 31.361265 11.981892 43.546795 0.274246l198.576661-190.68697 208.876238 182.346001 0 40.683585c0 40.186258-32.697703 72.878844-72.878844 72.878844L571.592236 845.481164c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c74.627674 0 135.346571-60.71378 135.346571-135.346571L959.855074 252.037247C959.855074 177.404456 899.136178 116.690676 824.508503 116.690676z" fill="#8a8a8a" p-id="5997"></path></svg>`,`<span>`+r(`chatStream.exportImage`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-md-item" type="button">`,`<svg t="1784038824502" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1666" width="32" height="32"><path d="M601.216 85.333333a42.666667 42.666667 0 0 1 30.485333 12.821334l209.450667 213.973333a42.666667 42.666667 0 0 1 12.181333 29.866667V853.333333a85.333333 85.333333 0 0 1-85.333333 85.333334H256a85.333333 85.333333 0 0 1-85.333333-85.333334V170.666667a85.333333 85.333333 0 0 1 85.333333-85.333334h345.216z m-35.584 64H256a21.333333 21.333333 0 0 0-21.333333 21.333334v682.666666a21.333333 21.333333 0 0 0 21.333333 21.333334h512a21.333333 21.333333 0 0 0 21.333333-21.333334V395.413333h-191.68a32 32 0 0 1-32-32L565.632 149.333333z m64 38.186667v143.893333h140.821333L629.632 187.52z" fill="#8a8a8a" p-id="1667"></path><path d="M384.341333 800l-3.072-0.106667a32 32 0 0 1-29.162666-34.624l21.973333-256c2.752-32.256 46.165333-40.490667 60.544-11.477333l77.290667 156.010667 78.805333-156.224c14.08-27.925333 55.082667-20.906667 60.074667 8.789333l0.384 3.050667 20.714666 256a32 32 0 0 1-63.786666 5.162666l-11.541334-142.549333-56.341333 111.722667c-11.413333 22.613333-42.88 23.381333-55.744 2.517333l-1.493333-2.730667-54.912-110.826666-12.181334 142.016a32 32 0 0 1-31.552 29.269333z" fill="#8a8a8a" p-id="1668"></path></svg>`,`<span>`+r(`chatStream.exportMarkdown`)+`</span>`,`</button>`].join(``);let v=_.querySelector(`.export-docx-item`);v.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToDocx:n}=await I(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-CBdPUbRE.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));n(e,v,_)});let y=_.querySelector(`.export-md-item`);y.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToMarkdown:n}=await I(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-CBdPUbRE.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));n(e,y,_)});let b=_.querySelector(`.export-pdf-item`);b.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToPdf:n}=await I(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-CBdPUbRE.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));n(e,b,_)});let x=_.querySelector(`.export-image-item`);x.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToImage:n}=await I(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-CBdPUbRE.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));n(e,x,_)}),g.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==_&&e.classList.remove(`show`)}),_.classList.toggle(`show`)});let S=null;h.addEventListener(`mouseenter`,()=>{S=setTimeout(()=>{document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==_&&e.classList.remove(`show`)}),_.classList.add(`show`)},300)}),h.addEventListener(`mouseleave`,()=>{S&&=(clearTimeout(S),null),setTimeout(()=>{!h.matches(`:hover`)&&!_.matches(`:hover`)&&_.classList.remove(`show`)},100)}),h.appendChild(g),h.appendChild(_),f.appendChild(h);let C=document.createElement(`div`);C.className=`footer-right-actions`,C.style.marginLeft=`auto`,C.style.display=`flex`,C.style.alignItems=`center`,C.style.gap=`8px`;let w=ot(n);if(w){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:B(w.totalTokens),prompt:B(w.promptTokens),completion:B(w.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${B(w.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),ft(w,e)}),C.appendChild(e)}let T=bg(t),E=Cg(n,t);if(T.length&&(e.dataset.declaredArtifacts=JSON.stringify(T)),Vg(E),E.length>0){let e=document.createElement(`button`);e.className=`artifacts-btn`,e.type=`button`,e.title=r(`artifacts.btnTitle`,{count:E.length}),e.innerHTML=`
1732
+ `,d){let e=p.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),ft(d,e)}))}let g=document.createElement(`div`);g.className=`thinking-process-body`;let _=document.createElement(`div`);for(_.className=`thinking-process-content`,g.appendChild(_);l.firstChild;)_.appendChild(l.firstChild);let v=_.querySelectorAll(`.thinking-content`),y=e.trim();if(v.length>0){let e=v[v.length-1],t=e.textContent.trim();if(!s||s&&t===y){let t=e.previousElementSibling;for(;t;){if(t.classList.contains(`thinking-badge`)){t.remove();break}t=t.previousElementSibling}e.remove()}}if(_.children.length>0&&_.textContent.trim()){f.appendChild(p),f.appendChild(g);let t=document.createElement(`div`);t.className=`final-answer`,e&&e.trim()&&(t.innerHTML=Ka(e));let n=c.querySelector(`.thinking-indicator`);n&&n.remove(),c.appendChild(f),c.appendChild(t),gv(p)}else{let t=c.querySelector(`.thinking-indicator`);t&&t.remove(),e&&e.trim()&&(l.innerHTML=Ka(e))}}else e&&e.trim()&&(l.innerHTML=Ka(e))}e.classList.add(`assistant`,`message`),e.dataset.rawContent=typeof t==`string`?Fa(t):JSON.stringify(t),e.dataset.textContent_=Fa(Gv(t)),e.dataset.executionLog=JSON.stringify(n);let f=document.createElement(`div`);f.className=`message-footer`;let p=document.createElement(`button`);p.className=`copy-btn`,p.title=r(`chatStream.copyMarkdown`),p.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`,`<span>`+r(`chatStream.copy`)+`</span>`].join(``),p.addEventListener(`click`,t=>{t.stopPropagation(),B_(e,p,t)}),f.appendChild(p);let m=document.createElement(`button`);m.className=`quote-btn`,m.title=r(`chatStream.quoteTitle`),m.innerHTML=[`<svg t="1781246498458" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9645" width="14" height="14"><path d="M156.09136 606.57001a457.596822 457.596822 0 0 1 221.680239-392.516385 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z m406.752731 0a457.596822 457.596822 0 0 1 221.680239-392.007944 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z" fill="#8a8a8a" p-id="9646"></path></svg>`,`<span>`+r(`chatStream.quote`)+`</span>`].join(``),m.addEventListener(`click`,t=>{t.stopPropagation(),J_(e)}),f.appendChild(m);let h=document.createElement(`div`);h.className=`export-menu-container`;let g=document.createElement(`button`);g.className=`export-trigger-btn`,g.innerHTML=`<svg t="1781245244396" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5115" width="14" height="14"><path d="M496.213333 739.84c2.133333 2.133333 4.693333 3.84 7.68 5.12 0.853333 0.426667 2.133333 0.426667 2.986667 0.853333 1.706667 0.426667 2.986667 0.853333 4.693333 0.853334 5.546667 0 11.093333-2.133333 14.933334-6.4l256-256c8.533333-8.533333 8.533333-21.76 0-30.293334s-21.76-8.533333-30.293334 0L533.333333 674.133333V128c0-11.946667-9.386667-21.333333-21.333333-21.333333s-21.333333 9.386667-21.333333 21.333333v545.706667l-219.306667-219.306667c-8.533333-8.533333-21.76-8.533333-30.293333 0s-8.533333 21.76 0 30.293333l255.146666 255.146667zM768 874.666667H256c-11.946667 0-21.333333 9.386667-21.333333 21.333333s9.386667 21.333333 21.333333 21.333333h512c11.946667 0 21.333333-9.386667 21.333333-21.333333s-9.386667-21.333333-21.333333-21.333333z" fill="#8a8a8a" p-id="5116"></path></svg><span>`+r(`chatStream.export`)+`</span><svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`;let _=document.createElement(`div`);_.className=`export-dropdown`,_.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">`,`<svg t="1781245550030" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6544" width="32" height="32"><path d="M747.936 901.171H276.819c-72.2 0-130.953-55.224-130.953-123.078V244.721c0-67.854 58.752-123.078 130.953-123.078h383.525c6.597 0 12.937 2.505 17.795 6.954l192.363 178.046c5.317 4.96 8.386 11.914 8.386 19.227v452.223c0 67.854-58.752 123.078-130.952 123.078zM276.819 174.004c-43.31 0-78.592 31.703-78.592 70.717v533.372c0 39.015 35.282 70.718 78.592 70.718h471.117c43.31 0 78.592-31.703 78.592-70.718V337.324l-176.461-163.32H276.819z" fill="#8a8a8a" p-id="6545"></path><path d="M830.567 331.546H669.446c-14.471 0-26.18-11.71-26.18-26.181V156.209c0-14.471 11.709-26.18 26.18-26.18s26.181 11.709 26.181 26.18v122.976h134.94c14.471 0 26.181 11.709 26.181 26.18s-11.711 26.181-26.181 26.181z" fill="#8a8a8a" p-id="6546"></path><path d="M730.214 428.749l-92.04 343.616h-53.179L511.363 498.29l-75.677 274.074h-53.179l-92.04-343.616h49.088l69.542 255.667 69.541-255.667h63.406l69.541 255.667 69.541-255.667h49.088z" fill="#8a8a8a" p-id="6547"></path></svg>`,`<span>`+r(`chatStream.exportWord`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-pdf-item" type="button">`,`<svg t="1781245863206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8152" width="32" height="32"><path d="M582.4 864H170.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V170.666667c0-6.4 4.266667-10.666667 10.666667-10.666667h309.333333V320c0 40.533333 34.133333 74.666667 74.666667 74.666667h160v38.4c0 17.066667 14.933333 32 32 32s32-14.933333 32-32V298.666667c0-8.533333-4.266667-17.066667-8.533334-23.466667l-170.666666-170.666667c-6.4-6.4-14.933333-8.533333-23.466667-8.533333H170.666667C130.133333 96 96 130.133333 96 170.666667v682.666666c0 40.533333 34.133333 74.666667 74.666667 74.666667h411.733333c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32z m132.266667-550.4v17.066667H554.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V160h19.2l151.466667 153.6z" fill="#8a8a8a" p-id="8153"></path><path d="M332.8 533.333333c-12.8 0-19.2 2.133333-25.6 6.4-6.4 4.266667-8.533333 12.8-8.533333 23.466667v206.933333c0 6.4 2.133333 12.8 6.4 19.2 4.266667 4.266667 10.666667 8.533333 21.333333 8.533334s17.066667-4.266667 21.333333-8.533334c4.266667-4.266667 6.4-10.666667 6.4-19.2v-64h32c57.6 0 89.6-29.866667 89.6-87.466666 0-27.733333-8.533333-51.2-23.466666-64-14.933333-14.933333-36.266667-21.333333-66.133334-21.333334h-53.333333z m87.466667 85.333334c0 12.8-2.133333 23.466667-8.533334 27.733333-4.266667 4.266667-14.933333 8.533333-27.733333 8.533333h-32v-70.4H384c12.8 0 21.333333 2.133333 27.733333 8.533334 6.4 4.266667 8.533333 12.8 8.533334 25.6zM667.733333 571.733333c-8.533333-12.8-21.333333-21.333333-34.133333-29.866666-14.933333-4.266667-32-8.533333-51.2-8.533334h-61.866667c-8.533333 0-17.066667 0-23.466666 8.533334-2.133333 4.266667-4.266667 10.666667-4.266667 19.2V768c0 8.533333 2.133333 14.933333 4.266667 19.2 6.4 8.533333 14.933333 8.533333 23.466666 8.533333h64c19.2 0 34.133333-4.266667 49.066667-10.666666 12.8-6.4 25.6-17.066667 34.133333-29.866667 8.533333-12.8 14.933333-25.6 19.2-42.666667 4.266667-14.933333 6.4-32 6.4-49.066666 0-17.066667-2.133333-34.133333-6.4-49.066667-4.266667-14.933333-10.666667-29.866667-19.2-42.666667z m-42.666666 153.6c-8.533333 12.8-21.333333 19.2-38.4 19.2h-38.4v-160H576c21.333333 0 38.4 6.4 46.933333 19.2 10.666667 12.8 14.933333 34.133333 14.933334 59.733334 2.133333 27.733333-4.266667 46.933333-12.8 61.866666zM851.2 533.333333h-106.666667c-8.533333 0-17.066667 2.133333-21.333333 6.4-6.4 4.266667-8.533333 12.8-8.533333 21.333334v209.066666c0 6.4 2.133333 12.8 6.4 17.066667 4.266667 6.4 10.666667 8.533333 21.333333 8.533333 8.533333 0 17.066667-2.133333 21.333333-8.533333 2.133333-4.266667 6.4-8.533333 6.4-19.2v-85.333333h72.533334c12.8 0 23.466667-6.4 25.6-17.066667 2.133333-8.533333 2.133333-14.933333 0-17.066667-2.133333-4.266667-6.4-17.066667-25.6-17.066666H768v-49.066667h81.066667c8.533333 0 14.933333-2.133333 19.2-4.266667 4.266667-2.133333 8.533333-8.533333 8.533333-21.333333 2.133333-12.8-8.533333-23.466667-25.6-23.466667z" fill="#8a8a8a" p-id="8154"></path></svg>`,`<span>`+r(`chatStream.exportPdf`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-image-item" type="button">`,`<svg t="1784207887308" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5993" width="32" height="32"><path d="M400.696 268.795c-17.249 0-31.233 13.986-31.233 31.233v30.471c0 17.249 13.986 31.233 31.233 31.233s31.233-13.986 31.233-31.233v-30.471c0-17.249-13.985-31.233-31.233-31.233z" fill="#8a8a8a" p-id="5994"></path><path d="M623.649 361.734c17.249 0 31.234-13.986 31.234-31.233v-30.471c0-17.249-13.986-31.233-31.234-31.233s-31.233 13.986-31.233 31.233v30.471c-0.001 17.248 13.985 31.233 31.233 31.233z" fill="#8a8a8a" p-id="5995"></path><path d="M438.295 388.804c-14.656 9.104-19.155 28.362-10.050 43.013 11.209 18.047 41.976 48.59 86.157 48.59 43.958 0 75.1-30.313 86.574-48.223 9.303-14.529 5.068-33.847-9.455-43.15-14.539-9.298-33.852-5.068-43.15 9.455-0.122 0.199-13.38 19.45-33.969 19.45-20.009 0-32.444-18.128-33.278-19.373-9.166-14.423-28.28-18.805-42.829-9.761z" fill="#8a8a8a" p-id="5996"></path><path d="M824.508503 116.690676 571.592236 116.690676c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c40.181141 0 72.878844 32.692586 72.878844 72.878844l0 396.966057-189.334159-165.29465c-12.20088-10.655687-30.517037-10.207479-42.173518 0.9967L468.578048 674.16231 309.521472 517.519714c-11.895935-11.70253-30.903847-12.002358-43.154869-0.645706L126.957507 646.163629l0-394.126382c0-40.186258 32.692586-72.878844 72.878844-72.878844l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352S470.000444 116.690676 452.751594 116.690676L199.836351 116.690676c-74.632791 0-135.346571 60.71378-135.346571 135.346571l0 520.56405c0 74.632791 60.71378 135.346571 135.346571 135.346571l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352s-13.985526-31.233352-31.233352-31.233352L199.836351 845.481164c-40.186258 0-72.878844-32.692586-72.878844-72.878844l0-41.23924 160.003134-148.385539 159.428036 157.007917c12.048407 11.865235 31.361265 11.981892 43.546795 0.274246l198.576661-190.68697 208.876238 182.346001 0 40.683585c0 40.186258-32.697703 72.878844-72.878844 72.878844L571.592236 845.481164c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c74.627674 0 135.346571-60.71378 135.346571-135.346571L959.855074 252.037247C959.855074 177.404456 899.136178 116.690676 824.508503 116.690676z" fill="#8a8a8a" p-id="5997"></path></svg>`,`<span>`+r(`chatStream.exportImage`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-md-item" type="button">`,`<svg t="1784038824502" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1666" width="32" height="32"><path d="M601.216 85.333333a42.666667 42.666667 0 0 1 30.485333 12.821334l209.450667 213.973333a42.666667 42.666667 0 0 1 12.181333 29.866667V853.333333a85.333333 85.333333 0 0 1-85.333333 85.333334H256a85.333333 85.333333 0 0 1-85.333333-85.333334V170.666667a85.333333 85.333333 0 0 1 85.333333-85.333334h345.216z m-35.584 64H256a21.333333 21.333333 0 0 0-21.333333 21.333334v682.666666a21.333333 21.333333 0 0 0 21.333333 21.333334h512a21.333333 21.333333 0 0 0 21.333333-21.333334V395.413333h-191.68a32 32 0 0 1-32-32L565.632 149.333333z m64 38.186667v143.893333h140.821333L629.632 187.52z" fill="#8a8a8a" p-id="1667"></path><path d="M384.341333 800l-3.072-0.106667a32 32 0 0 1-29.162666-34.624l21.973333-256c2.752-32.256 46.165333-40.490667 60.544-11.477333l77.290667 156.010667 78.805333-156.224c14.08-27.925333 55.082667-20.906667 60.074667 8.789333l0.384 3.050667 20.714666 256a32 32 0 0 1-63.786666 5.162666l-11.541334-142.549333-56.341333 111.722667c-11.413333 22.613333-42.88 23.381333-55.744 2.517333l-1.493333-2.730667-54.912-110.826666-12.181334 142.016a32 32 0 0 1-31.552 29.269333z" fill="#8a8a8a" p-id="1668"></path></svg>`,`<span>`+r(`chatStream.exportMarkdown`)+`</span>`,`</button>`].join(``);let v=_.querySelector(`.export-docx-item`);v.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToDocx:n}=await I(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-B5n-Qevt.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));n(e,v,_)});let y=_.querySelector(`.export-md-item`);y.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToMarkdown:n}=await I(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-B5n-Qevt.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));n(e,y,_)});let b=_.querySelector(`.export-pdf-item`);b.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToPdf:n}=await I(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-B5n-Qevt.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));n(e,b,_)});let x=_.querySelector(`.export-image-item`);x.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToImage:n}=await I(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-B5n-Qevt.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));n(e,x,_)}),g.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==_&&e.classList.remove(`show`)}),_.classList.toggle(`show`)});let S=null;h.addEventListener(`mouseenter`,()=>{S=setTimeout(()=>{document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==_&&e.classList.remove(`show`)}),_.classList.add(`show`)},300)}),h.addEventListener(`mouseleave`,()=>{S&&=(clearTimeout(S),null),setTimeout(()=>{!h.matches(`:hover`)&&!_.matches(`:hover`)&&_.classList.remove(`show`)},100)}),h.appendChild(g),h.appendChild(_),f.appendChild(h);let C=document.createElement(`div`);C.className=`footer-right-actions`,C.style.marginLeft=`auto`,C.style.display=`flex`,C.style.alignItems=`center`,C.style.gap=`8px`;let w=ot(n);if(w){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:B(w.totalTokens),prompt:B(w.promptTokens),completion:B(w.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${B(w.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),ft(w,e)}),C.appendChild(e)}let T=bg(t),E=Cg(n,t);if(T.length&&(e.dataset.declaredArtifacts=JSON.stringify(T)),Vg(E),E.length>0){let e=document.createElement(`button`);e.className=`artifacts-btn`,e.type=`button`,e.title=r(`artifacts.btnTitle`,{count:E.length}),e.innerHTML=`
1733
1733
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
1734
1734
  <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
1735
1735
  <polyline points="14 2 14 8 20 8"/>
@@ -1755,7 +1755,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
1755
1755
  点击查看评估详情`,reflectionFailedTitle:`反思评估失败(点击查看执行日志)`,reflectionFailedBadge:`⚠️ 反思失败`,prototypeLocalOpened:`已在本地浏览器打开,点击可在面板内查看`,prototypeView:`查看 UI 原型`,bookmarkMessage:`收藏消息`,unbookmarkMessage:`取消收藏`,forkSession:`从此处分叉会话(仅复制到此条消息)`,deleteMessageTitle:`删除消息`,resumeTaskTitle:`从上次中断处继续执行任务`,resumeTaskBtn:`继续执行`,clickToEnlarge:`点击查看大图`,fileExtracting:` 提取中...`,fileFailed:` 失败`,fileExtractFailed:`提取失败`,copyMessageTitle:`复制消息内容`,editAndResend:`编辑后重新发送`,thinking:`思考中...`,stopTask:`停止任务`,viewExecutionLog:`查看执行日志`,preparing:`准备中...`,emptyModelReply:`模型未返回任何内容。若你发送了图片,请确认所选模型支持视觉识别(图片识别需选择支持多模态视觉的模型),或更换模型后重试。`,stopping:`停止中...`,retrying:`连接异常,正在重试 ({attempt}/{max})...`,copyCode:`复制代码`,aborting:`正在终止...`,terminateCommandTitle:`终止命令执行`,terminateCommandPrompt:`请选择终止方式:`,terminateWaitTitle:`终止等待`,terminateWaitDesc:`仅停止等待命令输出,后台进程继续运行。<br/>适用于挂起型服务(如 npm run dev)。`,terminateCommandBtnTitle:`终止命令`,terminateCommandBtnDesc:`直接终止后台命令进程,释放资源。`,confirmDeleteMessage:`确认删除消息`,deleteMessageWarning:`删除后消息将从对话历史中移除,且无法恢复。`,confirmDelete:`确认删除`,quotedContextLabel:`💬 已引用: {text}`,selectedContextLabel:`📌 已选中: {text}`,subtaskDone:`完成`,subtaskFailed:`失败`,subtaskPartial:`部分完成`,subtaskFailReason:`中断原因:{error}`,subtaskExecuting:`执行中...`,subtaskPending:`待执行`,subtaskDescLabel:`任务描述:`,subtaskResultLabel:`产出摘要:`,subtaskAllDone:`✓ 全部完成`,subtaskFilterEmpty:`当前过滤下无匹配节点`,subtaskFilterHint:`点击按此状态过滤节点,再点取消`,subtaskPartialFail:`✗ {success}/{total} 完成,{fail} 个节点失败`,unknownNode:`未知`,stopGeneration:`停止生成`,toolResultTitle:`执行结果`,reflectionInProgress:`质量评估中...`,cannotGetMessageContent:`无法获取消息内容`,editFailed:`编辑失败: {message}`,errTaskStopped:`任务已被用户停止`,errTaskReplaced:`任务已被新请求替代`,errSwRestarted:`后台服务异常重启,API 调用已中断`,errTimeout:`请求超时({seconds}秒)`,cancelBtn:`取消`}}),n(`en`,{chatMsg:{searchPrompt:`Search`,exportWord:`Export Word`,exportPdf:`Export PDF`,exportImage:`Export Image`,exportMarkdown:`Export Markdown`,executionLogTitle:`Execution Log`,revisedTag:`Revised`,roundsTag:` ({count} rounds)`,revisedSuffix:` (Revised)`,scoreBadgeTitle:`AI Quality Assessment: {score}/10{rounds}{revised}
1756
1756
  Click to view assessment details`,reflectionFailedTitle:`Reflection assessment failed (click to view execution log)`,reflectionFailedBadge:`⚠️ Reflection Failed`,prototypeLocalOpened:`Opened in local browser, click to view in panel`,prototypeView:`View UI Prototype`,bookmarkMessage:`Bookmark message`,unbookmarkMessage:`Remove bookmark`,forkSession:`Fork session from here (copy up to this message only)`,deleteMessageTitle:`Delete message`,resumeTaskTitle:`Resume task from last interruption`,resumeTaskBtn:`Resume`,clickToEnlarge:`Click to view full size`,fileExtracting:` extracting...`,fileFailed:` failed`,fileExtractFailed:`Extraction failed`,copyMessageTitle:`Copy message content`,editAndResend:`Edit and resend`,thinking:`Thinking...`,stopTask:`Stop task`,viewExecutionLog:`View execution log`,preparing:`Preparing...`,emptyModelReply:`The model returned no content. If you sent an image, make sure the selected model supports vision (image recognition requires a multimodal vision model), or switch model and retry.`,stopping:`Stopping...`,retrying:`Connection unstable, retrying ({attempt}/{max})...`,copyCode:`Copy code`,aborting:`Aborting...`,terminateCommandTitle:`Terminate Command Execution`,terminateCommandPrompt:`Please select a termination method:`,terminateWaitTitle:`Stop Waiting`,terminateWaitDesc:`Only stop waiting for command output; the background process continues running.<br/>Suitable for hanging services (e.g. npm run dev).`,terminateCommandBtnTitle:`Terminate Command`,terminateCommandBtnDesc:`Directly terminate the background command process and release resources.`,confirmDeleteMessage:`Confirm Delete Message`,deleteMessageWarning:`After deletion, the message will be removed from the conversation history and cannot be recovered.`,confirmDelete:`Confirm Delete`,quotedContextLabel:`💬 Quoted: {text}`,selectedContextLabel:`📌 Selected: {text}`,subtaskDone:`Done`,subtaskFailed:`Failed`,subtaskPartial:`Partial`,subtaskFailReason:`Interrupted: {error}`,subtaskExecuting:`Executing...`,subtaskPending:`Pending`,subtaskDescLabel:`Description: `,subtaskResultLabel:`Output summary: `,subtaskAllDone:`✓ All done`,subtaskFilterEmpty:`No nodes match this filter`,subtaskFilterHint:`Click to filter nodes by this status, click again to clear`,subtaskPartialFail:`✗ {success}/{total} done, {fail} nodes failed`,unknownNode:`Unknown`,stopGeneration:`Stop generation`,toolResultTitle:`Execution Result`,reflectionInProgress:`Assessing quality...`,cannotGetMessageContent:`Cannot get message content`,editFailed:`Edit failed: {message}`,errTaskStopped:`Task stopped by user`,errTaskReplaced:`Task replaced by new request`,errSwRestarted:`Background service restarted unexpectedly, API call interrupted`,errTimeout:`Request timeout ({seconds}s)`,cancelBtn:`Cancel`}});var Hv=`pendingCallApiSessions`;function Uv(){chrome.storage.session.set({[Hv]:[...F.pendingCallApiSessionIds]}).catch(()=>{})}async function Wv(){try{let e=await chrome.storage.session.get([Hv]);e[Hv]&&Array.isArray(e[Hv])&&(F.pendingCallApiSessionIds=new Set(e[Hv]))}catch{}}function Gv(e){if(Array.isArray(e))return e.filter(e=>e.type===`text`).map(e=>e.text).join(``);if(typeof e==`string`&&e.startsWith(`[`))try{let t=JSON.parse(e);if(Array.isArray(t))return t.filter(e=>e.type===`text`).map(e=>e.text).join(``)}catch{}return e}function Kv(e){let t=Gv(e);F.quotedContextText=t;let n=document.getElementById(`selectionIndicator`),i=document.getElementById(`selectionText`),a=document.getElementById(`userInput`);if(n&&i&&a){let e;e=t.length>100?t.substring(0,100)+`...`:t.length>50?t.substring(0,50)+`...`:t,i.textContent=r(`chat.quotedPrefix`,{text:e}),n.classList.add(`show`)}}function qv(){a.debug(`[SidePanel] clear selectedcontenttext `),F.selectedContextText=``,F.quotedContextText=``;let e=document.getElementById(`selectionIndicator`),t=document.getElementById(`userInput`);if(e&&(e.classList.remove(`show`),a.debug(`[SidePanel] hiddenselected contentprompt`)),typeof window.hideFloatingMenu==`function`&&window.hideFloatingMenu(),t&&t.value.startsWith(`[选中内容]`)){let e=t.value.split(`
1757
1757
  `),n=e.findIndex(e=>e.startsWith(`[用户问题]`));n===-1?t.value=``:t.value=e.slice(n+1).join(`
1758
- `).trim()}}var Jv,Yv=new Promise(e=>{Jv=e});async function Xv(){try{await Zv()}finally{Jv()}}async function Zv(){let e=await Kt();if(e.activeSessionId&&e.list.length>0){F.activeSessionId=e.activeSessionId,F.sessions=e.list;let t=e.list.find(t=>t.id===e.activeSessionId);if(t){if(F.messageHistory=t.messageHistory||[],F.activeCompaction=t.contextCompaction||null,F.currentModel=t.model||F.currentModel,F.useTools=t.useTools===void 0?F.useTools:t.useTools,F.temperature=t.temperature===void 0?F.temperature:t.temperature,F.topP=t.topP===void 0?F.topP:t.topP,F.activeAgentId=t.agentId||null,F.activeAgentId&&F.activeAgentId!=="default"){try{let{getAgent:e}=await I(async()=>{let{getAgent:e}=await import(`./agent-store-BvS-vIQr.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3,4])),t=await e(F.activeAgentId);t&&(F.activeAgentMcpExcludedServerIds=t.mcpExcludedServerIds??null,t.model&&(F.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(F.temperature=t.temperature,F.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`)))}catch{}F.activeAgentMcpExcludedServerIds=null}else{F.activeAgentMcpExcludedServerIds=null;try{let e=await chrome.storage.local.get([`modelName`,`temperature`,`topP`]);e.modelName&&(F.currentModel=e.modelName),e.temperature!==void 0&&(F.temperature=e.temperature),e.topP!==void 0&&(F.topP=e.topP)}catch{}document.dispatchEvent(new CustomEvent(`agent-model-changed`))}let e=`agentMcpClosedServers_${F.activeAgentId||`default`}`;F.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}let n=document.getElementById(`chatContainer`);n&&n.querySelectorAll(`.message, .user-context-bubble`).forEach(e=>e.remove()),F.messageHistory.forEach(e=>{let t=e.wasRevised;if(!t&&e.executionLog)try{t=(typeof e.executionLog==`string`?JSON.parse(e.executionLog):e.executionLog).some(e=>e.nodeType===`reflection`&&e.reflectionType===`post`&&e.action?.decision===`revised`)}catch{}if(e.role===`user`&&e.contextBubbles&&Array.isArray(e.contextBubbles)&&e.contextBubbles.forEach(e=>{let t=``;switch(e.type){case`skill`:t=r(`contextBubble.bubbleSkill`,{name:e.name,desc:e.description?`:`+e.description:``});break;case`mcp`:t=r(`contextBubble.bubbleMcp`,{name:e.serverName});break;case`page`:t=r(`contextBubble.bubblePage`,{title:e.title,url:e.url});break;case`file`:t=`${e.name} (${yu(e.size||0)})`;break;case`knowledge`:{let t=Array.isArray(e.refs)?e.refs:[];t.length>0&&ay(t,e.failed===!0);break}}t&&e.type!==`file`&&by(e.type,t,!1)}),e.htmlContent)My(e.htmlContent,e.messageId,e.resumable);else{let n=(e.contextBubbles||[]).filter(e=>e.type===`file`).map(e=>({name:e.name,size:e.size||0,type:e.fileType||``}));Cy(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,t,null,e.messageId,n,e.resumable,e.timestamp??null)}}),Ey(),Oy(),bo();let i=document.querySelector(`.welcome-message`);i&&F.messageHistory.length>0&&i.remove(),Wa(),io(),Qx(),e.activeSessionId===F.activeSessionId?Eo(e):Eo(),await ev();let a=`scrollPosition_`+(F.activeSessionId||`default`);chrome.storage.local.get([a],e=>{e[a]!==void 0&&setTimeout(()=>{let t=document.getElementById(`chatContainer`);t.scrollTop=e[a]},100)})}else{await Jt();let e=await Kt();e.activeSessionId&&(F.activeSessionId=e.activeSessionId,F.sessions=e.list),Eo(e)}}function Qv(){try{qt().catch(e=>{a.error(`[SidePanel] save currentsession failed:`,e)})}catch(e){a.error(`[SidePanel] save conversationhistory exception:`,e)}}async function $v(){try{await qt()}catch(e){a.error(`[SidePanel] save conversationhistory exception:`,e)}}function ey(){F.messageHistory&&F.messageHistory.length>0&&$t().then(()=>{F.messageHistory=[],F.activeCompaction=null;let e=document.getElementById(`chatContainer`);if(e){e.innerHTML=``;let t=document.createElement(`div`);t.className=`welcome-message`,t.innerHTML=`
1758
+ `).trim()}}var Jv,Yv=new Promise(e=>{Jv=e});async function Xv(){try{await Zv()}finally{Jv()}}async function Zv(){let e=await Kt();if(e.activeSessionId&&e.list.length>0){F.activeSessionId=e.activeSessionId,F.sessions=e.list;let t=e.list.find(t=>t.id===e.activeSessionId);if(t){if(F.messageHistory=t.messageHistory||[],F.activeCompaction=t.contextCompaction||null,F.currentModel=t.model||F.currentModel,F.useTools=t.useTools===void 0?F.useTools:t.useTools,F.temperature=t.temperature===void 0?F.temperature:t.temperature,F.topP=t.topP===void 0?F.topP:t.topP,F.activeAgentId=t.agentId||null,F.activeAgentId&&F.activeAgentId!=="default"){try{let{getAgent:e}=await I(async()=>{let{getAgent:e}=await import(`./agent-store-D-jYf94_.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3,4])),t=await e(F.activeAgentId);t&&(F.activeAgentMcpExcludedServerIds=t.mcpExcludedServerIds??null,t.model&&(F.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(F.temperature=t.temperature,F.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`)))}catch{}F.activeAgentMcpExcludedServerIds=null}else{F.activeAgentMcpExcludedServerIds=null;try{let e=await chrome.storage.local.get([`modelName`,`temperature`,`topP`]);e.modelName&&(F.currentModel=e.modelName),e.temperature!==void 0&&(F.temperature=e.temperature),e.topP!==void 0&&(F.topP=e.topP)}catch{}document.dispatchEvent(new CustomEvent(`agent-model-changed`))}let e=`agentMcpClosedServers_${F.activeAgentId||`default`}`;F.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}let n=document.getElementById(`chatContainer`);n&&n.querySelectorAll(`.message, .user-context-bubble`).forEach(e=>e.remove()),F.messageHistory.forEach(e=>{let t=e.wasRevised;if(!t&&e.executionLog)try{t=(typeof e.executionLog==`string`?JSON.parse(e.executionLog):e.executionLog).some(e=>e.nodeType===`reflection`&&e.reflectionType===`post`&&e.action?.decision===`revised`)}catch{}if(e.role===`user`&&e.contextBubbles&&Array.isArray(e.contextBubbles)&&e.contextBubbles.forEach(e=>{let t=``;switch(e.type){case`skill`:t=r(`contextBubble.bubbleSkill`,{name:e.name,desc:e.description?`:`+e.description:``});break;case`mcp`:t=r(`contextBubble.bubbleMcp`,{name:e.serverName});break;case`page`:t=r(`contextBubble.bubblePage`,{title:e.title,url:e.url});break;case`file`:t=`${e.name} (${yu(e.size||0)})`;break;case`knowledge`:{let t=Array.isArray(e.refs)?e.refs:[];t.length>0&&ay(t,e.failed===!0);break}}t&&e.type!==`file`&&by(e.type,t,!1)}),e.htmlContent)My(e.htmlContent,e.messageId,e.resumable);else{let n=(e.contextBubbles||[]).filter(e=>e.type===`file`).map(e=>({name:e.name,size:e.size||0,type:e.fileType||``}));Cy(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,t,null,e.messageId,n,e.resumable,e.timestamp??null)}}),Ey(),Oy(),bo();let i=document.querySelector(`.welcome-message`);i&&F.messageHistory.length>0&&i.remove(),Wa(),io(),Qx(),e.activeSessionId===F.activeSessionId?Eo(e):Eo(),await ev();let a=`scrollPosition_`+(F.activeSessionId||`default`);chrome.storage.local.get([a],e=>{e[a]!==void 0&&setTimeout(()=>{let t=document.getElementById(`chatContainer`);t.scrollTop=e[a]},100)})}else{await Jt();let e=await Kt();e.activeSessionId&&(F.activeSessionId=e.activeSessionId,F.sessions=e.list),Eo(e)}}function Qv(){try{qt().catch(e=>{a.error(`[SidePanel] save currentsession failed:`,e)})}catch(e){a.error(`[SidePanel] save conversationhistory exception:`,e)}}async function $v(){try{await qt()}catch(e){a.error(`[SidePanel] save conversationhistory exception:`,e)}}function ey(){F.messageHistory&&F.messageHistory.length>0&&$t().then(()=>{F.messageHistory=[],F.activeCompaction=null;let e=document.getElementById(`chatContainer`);if(e){e.innerHTML=``;let t=document.createElement(`div`);t.className=`welcome-message`,t.innerHTML=`
1759
1759
  <div class="icon-wrapper">
1760
1760
  <div class="icon">💬</div>
1761
1761
  </div>
@@ -1779,7 +1779,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
1779
1779
  </div>
1780
1780
  <div class="context-bubble-content">${l}</div>
1781
1781
  </div>
1782
- `;let u=o.querySelector(`.context-bubble-header`),d=o.querySelector(`.context-bubble-content`);return u.addEventListener(`click`,e=>{e.stopPropagation(),d.classList.toggle(`expanded`)}),e===`knowledge`&&o.querySelectorAll(`.kb-bubble-hit-text`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),e.classList.toggle(`expanded`)})}),a.appendChild(o),n&&(a.scrollTop=a.scrollHeight),o}function xy(e){let t=e,n;do n=t,t=t.replace(/^\[(?:已选技能|Selected skill): [^\]]+\]\n[\s\S]*?(?:请根据上述技能说明[\s\S]*?处理以下问题[::]|Please use the relevant tools[\s\S]*?handle the following problem[.:])\s*\n/,``).replace(/^\[(?:已选技能|Selected skill): [^\]]+\]\n(?:请|Please)[^\n]*(?:处理以下问题|handle the following problem)[^。\n]*。?\s*\n/,``);while(t!==n);return t}function Sy(e){let t=e,n;do n=t,t=t.replace(/^\[(?:已选MCP服务|Selected MCP service):\s*[^\]]+\]\n(?:请使用「[^」]+」MCP服务来处理以下问题:|Please use the "[^"]+" MCP service to handle the following problem:)\s*\n/,``);while(t!==n);return t}function Cy(e,t,n=!0,i=[],o=null,s=!1,c=null,l=null,u=[],d=!1,f=void 0){let p=document.getElementById(`chatContainer`),m=document.createElement(`div`);m.className=`message ${e}`;let h=f===void 0?new Date().toISOString():f||null;h&&(m.dataset.timestamp=h);let g=l||`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8);m.dataset.messageId=g;let _=Array.isArray(t)?t.filter(e=>e.type===`text`).map(e=>e.text).join(``):t,v=Array.isArray(t)&&t.some(e=>e.type===`image_url`);m.dataset.rawContent=Array.isArray(t)?JSON.stringify(t):Fa(t),m.dataset.textContent_=Fa(c||_);let y=_;if(m.dataset.executionLog=JSON.stringify(i),s&&(m.dataset.wasRevised=`true`),e===`assistant`){m.innerHTML=Ka(t);let e=document.createElement(`div`);e.className=`message-footer`;let n=document.createElement(`button`);n.className=`copy-btn`,n.title=r(`chatStream.copyMarkdown`),n.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`,`<span>${r(`common.copy`)}</span>`].join(``),n.addEventListener(`click`,e=>{e.stopPropagation(),B_(m,n,e)}),e.appendChild(n);let c=document.createElement(`button`);c.className=`quote-btn`,c.title=r(`chat.quoteTitle`),c.innerHTML=[`<svg t="1781246498458" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9645" width="14" height="14"><path d="M156.09136 606.57001a457.596822 457.596822 0 0 1 221.680239-392.516385 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z m406.752731 0a457.596822 457.596822 0 0 1 221.680239-392.007944 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z" fill="#8a8a8a" p-id="9646"></path></svg>`,`<span>${r(`chat.quote`)}</span>`].join(``),c.addEventListener(`click`,e=>{e.stopPropagation(),J_(m)}),e.appendChild(c);let l=document.createElement(`div`);l.className=`export-menu-container`;let u=document.createElement(`button`);u.className=`export-trigger-btn`,u.innerHTML=`<svg t="1781245244396" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5115" width="14" height="14"><path d="M496.213333 739.84c2.133333 2.133333 4.693333 3.84 7.68 5.12 0.853333 0.426667 2.133333 0.426667 2.986667 0.853333 1.706667 0.426667 2.986667 0.853333 4.693333 0.853334 5.546667 0 11.093333-2.133333 14.933334-6.4l256-256c8.533333-8.533333 8.533333-21.76 0-30.293334s-21.76-8.533333-30.293334 0L533.333333 674.133333V128c0-11.946667-9.386667-21.333333-21.333333-21.333333s-21.333333 9.386667-21.333333 21.333333v545.706667l-219.306667-219.306667c-8.533333-8.533333-21.76-8.533333-30.293333 0s-8.533333 21.76 0 30.293333l255.146666 255.146667zM768 874.666667H256c-11.946667 0-21.333333 9.386667-21.333333 21.333333s9.386667 21.333333 21.333333 21.333333h512c11.946667 0 21.333333-9.386667 21.333333-21.333333s-9.386667-21.333333-21.333333-21.333333z" fill="#8a8a8a" p-id="5116"></path></svg><span>${r(`chat.export`)}</span><svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`;let f=document.createElement(`div`);f.className=`export-dropdown`,f.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">`,`<svg t="1781245550030" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6544" width="32" height="32"><path d="M747.936 901.171H276.819c-72.2 0-130.953-55.224-130.953-123.078V244.721c0-67.854 58.752-123.078 130.953-123.078h383.525c6.597 0 12.937 2.505 17.795 6.954l192.363 178.046c5.317 4.96 8.386 11.914 8.386 19.227v452.223c0 67.854-58.752 123.078-130.952 123.078zM276.819 174.004c-43.31 0-78.592 31.703-78.592 70.717v533.372c0 39.015 35.282 70.718 78.592 70.718h471.117c43.31 0 78.592-31.703 78.592-70.718V337.324l-176.461-163.32H276.819z" fill="#8a8a8a" p-id="6545"></path><path d="M830.567 331.546H669.446c-14.471 0-26.18-11.71-26.18-26.181V156.209c0-14.471 11.709-26.18 26.18-26.18s26.181 11.709 26.181 26.18v122.976h134.94c14.471 0 26.181 11.709 26.181 26.18s-11.711 26.181-26.181 26.181z" fill="#8a8a8a" p-id="6546"></path><path d="M730.214 428.749l-92.04 343.616h-53.179L511.363 498.29l-75.677 274.074h-53.179l-92.04-343.616h49.088l69.542 255.667 69.541-255.667h63.406l69.541 255.667 69.541-255.667h49.088z" fill="#8a8a8a" p-id="6547"></path></svg>`,`<span>${r(`chatMsg.exportWord`)}</span>`,`</button>`,`<button class="export-dropdown-item export-pdf-item" type="button">`,`<svg t="1781245863206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8152" width="32" height="32"><path d="M582.4 864H170.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V170.666667c0-6.4 4.266667-10.666667 10.666667-10.666667h309.333333V320c0 40.533333 34.133333 74.666667 74.666667 74.666667h160v38.4c0 17.066667 14.933333 32 32 32s32-14.933333 32-32V298.666667c0-8.533333-4.266667-17.066667-8.533334-23.466667l-170.666666-170.666667c-6.4-6.4-14.933333-8.533333-23.466667-8.533333H170.666667C130.133333 96 96 130.133333 96 170.666667v682.666666c0 40.533333 34.133333 74.666667 74.666667 74.666667h411.733333c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32z m132.266667-550.4v17.066667H554.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V160h19.2l151.466667 153.6z" fill="#8a8a8a" p-id="8153"></path><path d="M332.8 533.333333c-12.8 0-19.2 2.133333-25.6 6.4-6.4 4.266667-8.533333 12.8-8.533333 23.466667v206.933333c0 6.4 2.133333 12.8 6.4 19.2 4.266667 4.266667 10.666667 8.533333 21.333333 8.533334s17.066667-4.266667 21.333333-8.533334c4.266667-4.266667 6.4-10.666667 6.4-19.2v-64h32c57.6 0 89.6-29.866667 89.6-87.466666 0-27.733333-8.533333-51.2-23.466666-64-14.933333-14.933333-36.266667-21.333333-66.133334-21.333334h-53.333333z m87.466667 85.333334c0 12.8-2.133333 23.466667-8.533334 27.733333-4.266667 4.266667-14.933333 8.533333-27.733333 8.533333h-32v-70.4H384c12.8 0 21.333333 2.133333 27.733333 8.533334 6.4 4.266667 8.533333 12.8 8.533334 25.6zM667.733333 571.733333c-8.533333-12.8-21.333333-21.333333-34.133333-29.866666-14.933333-4.266667-32-8.533333-51.2-8.533334h-61.866667c-8.533333 0-17.066667 0-23.466666 8.533334-2.133333 4.266667-4.266667 10.666667-4.266667 19.2V768c0 8.533333 2.133333 14.933333 4.266667 19.2 6.4 8.533333 14.933333 8.533333 23.466666 8.533333h64c19.2 0 34.133333-4.266667 49.066667-10.666666 12.8-6.4 25.6-17.066667 34.133333-29.866667 8.533333-12.8 14.933333-25.6 19.2-42.666667 4.266667-14.933333 6.4-32 6.4-49.066666 0-17.066667-2.133333-34.133333-6.4-49.066667-4.266667-14.933333-10.666667-29.866667-19.2-42.666667z m-42.666666 153.6c-8.533333 12.8-21.333333 19.2-38.4 19.2h-38.4v-160H576c21.333333 0 38.4 6.4 46.933333 19.2 10.666667 12.8 14.933333 34.133333 14.933334 59.733334 2.133333 27.733333-4.266667 46.933333-12.8 61.866666zM851.2 533.333333h-106.666667c-8.533333 0-17.066667 2.133333-21.333333 6.4-6.4 4.266667-8.533333 12.8-8.533333 21.333334v209.066666c0 6.4 2.133333 12.8 6.4 17.066667 4.266667 6.4 10.666667 8.533333 21.333333 8.533333 8.533333 0 17.066667-2.133333 21.333333-8.533333 2.133333-4.266667 6.4-8.533333 6.4-19.2v-85.333333h72.533334c12.8 0 23.466667-6.4 25.6-17.066667 2.133333-8.533333 2.133333-14.933333 0-17.066667-2.133333-4.266667-6.4-17.066667-25.6-17.066666H768v-49.066667h81.066667c8.533333 0 14.933333-2.133333 19.2-4.266667 4.266667-2.133333 8.533333-8.533333 8.533333-21.333333 2.133333-12.8-8.533333-23.466667-25.6-23.466667z" fill="#8a8a8a" p-id="8154"></path></svg>`,`<span>${r(`chatMsg.exportPdf`)}</span>`,`</button>`,`<button class="export-dropdown-item export-image-item" type="button">`,`<svg t="1784207887308" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5993" width="32" height="32"><path d="M400.696 268.795c-17.249 0-31.233 13.986-31.233 31.233v30.471c0 17.249 13.986 31.233 31.233 31.233s31.233-13.986 31.233-31.233v-30.471c0-17.249-13.985-31.233-31.233-31.233z" fill="#8a8a8a" p-id="5994"></path><path d="M623.649 361.734c17.249 0 31.234-13.986 31.234-31.233v-30.471c0-17.249-13.986-31.233-31.234-31.233s-31.233 13.986-31.233 31.233v30.471c-0.001 17.248 13.985 31.233 31.233 31.233z" fill="#8a8a8a" p-id="5995"></path><path d="M438.295 388.804c-14.656 9.104-19.155 28.362-10.050 43.013 11.209 18.047 41.976 48.59 86.157 48.59 43.958 0 75.1-30.313 86.574-48.223 9.303-14.529 5.068-33.847-9.455-43.15-14.539-9.298-33.852-5.068-43.15 9.455-0.122 0.199-13.38 19.45-33.969 19.45-20.009 0-32.444-18.128-33.278-19.373-9.166-14.423-28.28-18.805-42.829-9.761z" fill="#8a8a8a" p-id="5996"></path><path d="M824.508503 116.690676 571.592236 116.690676c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c40.181141 0 72.878844 32.692586 72.878844 72.878844l0 396.966057-189.334159-165.29465c-12.20088-10.655687-30.517037-10.207479-42.173518 0.9967L468.578048 674.16231 309.521472 517.519714c-11.895935-11.70253-30.903847-12.002358-43.154869-0.645706L126.957507 646.163629l0-394.126382c0-40.186258 32.692586-72.878844 72.878844-72.878844l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352S470.000444 116.690676 452.751594 116.690676L199.836351 116.690676c-74.632791 0-135.346571 60.71378-135.346571 135.346571l0 520.56405c0 74.632791 60.71378 135.346571 135.346571 135.346571l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352s-13.985526-31.233352-31.233352-31.233352L199.836351 845.481164c-40.186258 0-72.878844-32.692586-72.878844-72.878844l0-41.23924 160.003134-148.385539 159.428036 157.007917c12.048407 11.865235 31.361265 11.981892 43.546795 0.274246l198.576661-190.68697 208.876238 182.346001 0 40.683585c0 40.186258-32.697703 72.878844-72.878844 72.878844L571.592236 845.481164c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c74.627674 0 135.346571-60.71378 135.346571-135.346571L959.855074 252.037247C959.855074 177.404456 899.136178 116.690676 824.508503 116.690676z" fill="#8a8a8a" p-id="5997"></path></svg>`,`<span>${r(`chatMsg.exportImage`)}</span>`,`</button>`,`<button class="export-dropdown-item export-md-item" type="button">`,`<svg t="1784038824502" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1666" width="32" height="32"><path d="M601.216 85.333333a42.666667 42.666667 0 0 1 30.485333 12.821334l209.450667 213.973333a42.666667 42.666667 0 0 1 12.181333 29.866667V853.333333a85.333333 85.333333 0 0 1-85.333333 85.333334H256a85.333333 85.333333 0 0 1-85.333333-85.333334V170.666667a85.333333 85.333333 0 0 1 85.333333-85.333334h345.216z m-35.584 64H256a21.333333 21.333333 0 0 0-21.333333 21.333334v682.666666a21.333333 21.333333 0 0 0 21.333333 21.333334h512a21.333333 21.333333 0 0 0 21.333333-21.333334V395.413333h-191.68a32 32 0 0 1-32-32L565.632 149.333333z m64 38.186667v143.893333h140.821333L629.632 187.52z" fill="#8a8a8a" p-id="1667"></path><path d="M384.341333 800l-3.072-0.106667a32 32 0 0 1-29.162666-34.624l21.973333-256c2.752-32.256 46.165333-40.490667 60.544-11.477333l77.290667 156.010667 78.805333-156.224c14.08-27.925333 55.082667-20.906667 60.074667 8.789333l0.384 3.050667 20.714666 256a32 32 0 0 1-63.786666 5.162666l-11.541334-142.549333-56.341333 111.722667c-11.413333 22.613333-42.88 23.381333-55.744 2.517333l-1.493333-2.730667-54.912-110.826666-12.181334 142.016a32 32 0 0 1-31.552 29.269333z" fill="#8a8a8a" p-id="1668"></path></svg>`,`<span>${r(`chatMsg.exportMarkdown`)}</span>`,`</button>`].join(``);let p=f.querySelector(`.export-docx-item`);p.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToDocx:t}=await I(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-CBdPUbRE.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));t(m,p,f)});let h=f.querySelector(`.export-md-item`);h.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToMarkdown:t}=await I(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-CBdPUbRE.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));t(m,h,f)});let _=f.querySelector(`.export-pdf-item`);_.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToPdf:t}=await I(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-CBdPUbRE.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));t(m,_,f)});let v=f.querySelector(`.export-image-item`);v.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToImage:t}=await I(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-CBdPUbRE.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));t(m,v,f)}),u.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==f&&e.classList.remove(`show`)}),f.classList.toggle(`show`)});let y=null;l.addEventListener(`mouseenter`,()=>{y=setTimeout(()=>{document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==f&&e.classList.remove(`show`)}),f.classList.add(`show`)},300)}),l.addEventListener(`mouseleave`,()=>{y&&=(clearTimeout(y),null),setTimeout(()=>{!l.matches(`:hover`)&&!f.matches(`:hover`)&&f.classList.remove(`show`)},100)}),l.appendChild(u),l.appendChild(f),e.appendChild(l);let b=document.createElement(`div`);b.className=`footer-right-actions`,b.style.marginLeft=`auto`,b.style.display=`flex`,b.style.alignItems=`center`,b.style.gap=`8px`;let x=ot(i);if(x){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:B(x.totalTokens),prompt:B(x.promptTokens),completion:B(x.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${B(x.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),ft(x,e)}),b.appendChild(e)}let S=i&&i.length>0,C=o!=null,w=i?i.filter(e=>e.nodeType===`reflection`&&e.reflectionType===`post`&&e.status===`success`).length:0;Ey(),Oy(),bo();let T=i?.find(e=>e.nodeType===`reflection`&&e.reflectionType===`post`),E=bg(t),D=Cg(i,t);if(E.length&&(m.dataset.declaredArtifacts=JSON.stringify(E)),Vg(D),console.log(`[addMessage] executionLog entries:`,i?.length,`| agent_file entries:`,i?.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`agent_file`).length,`| artifacts:`,D.length),D.length>0){let e=document.createElement(`button`);e.className=`artifacts-btn`,e.type=`button`,e.title=r(`artifacts.btnTitle`,{count:D.length}),e.innerHTML=`
1782
+ `;let u=o.querySelector(`.context-bubble-header`),d=o.querySelector(`.context-bubble-content`);return u.addEventListener(`click`,e=>{e.stopPropagation(),d.classList.toggle(`expanded`)}),e===`knowledge`&&o.querySelectorAll(`.kb-bubble-hit-text`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),e.classList.toggle(`expanded`)})}),a.appendChild(o),n&&(a.scrollTop=a.scrollHeight),o}function xy(e){let t=e,n;do n=t,t=t.replace(/^\[(?:已选技能|Selected skill): [^\]]+\]\n[\s\S]*?(?:请根据上述技能说明[\s\S]*?处理以下问题[::]|Please use the relevant tools[\s\S]*?handle the following problem[.:])\s*\n/,``).replace(/^\[(?:已选技能|Selected skill): [^\]]+\]\n(?:请|Please)[^\n]*(?:处理以下问题|handle the following problem)[^。\n]*。?\s*\n/,``);while(t!==n);return t}function Sy(e){let t=e,n;do n=t,t=t.replace(/^\[(?:已选MCP服务|Selected MCP service):\s*[^\]]+\]\n(?:请使用「[^」]+」MCP服务来处理以下问题:|Please use the "[^"]+" MCP service to handle the following problem:)\s*\n/,``);while(t!==n);return t}function Cy(e,t,n=!0,i=[],o=null,s=!1,c=null,l=null,u=[],d=!1,f=void 0){let p=document.getElementById(`chatContainer`),m=document.createElement(`div`);m.className=`message ${e}`;let h=f===void 0?new Date().toISOString():f||null;h&&(m.dataset.timestamp=h);let g=l||`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8);m.dataset.messageId=g;let _=Array.isArray(t)?t.filter(e=>e.type===`text`).map(e=>e.text).join(``):t,v=Array.isArray(t)&&t.some(e=>e.type===`image_url`);m.dataset.rawContent=Array.isArray(t)?JSON.stringify(t):Fa(t),m.dataset.textContent_=Fa(c||_);let y=_;if(m.dataset.executionLog=JSON.stringify(i),s&&(m.dataset.wasRevised=`true`),e===`assistant`){m.innerHTML=Ka(t);let e=document.createElement(`div`);e.className=`message-footer`;let n=document.createElement(`button`);n.className=`copy-btn`,n.title=r(`chatStream.copyMarkdown`),n.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`,`<span>${r(`common.copy`)}</span>`].join(``),n.addEventListener(`click`,e=>{e.stopPropagation(),B_(m,n,e)}),e.appendChild(n);let c=document.createElement(`button`);c.className=`quote-btn`,c.title=r(`chat.quoteTitle`),c.innerHTML=[`<svg t="1781246498458" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9645" width="14" height="14"><path d="M156.09136 606.57001a457.596822 457.596822 0 0 1 221.680239-392.516385 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z m406.752731 0a457.596822 457.596822 0 0 1 221.680239-392.007944 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z" fill="#8a8a8a" p-id="9646"></path></svg>`,`<span>${r(`chat.quote`)}</span>`].join(``),c.addEventListener(`click`,e=>{e.stopPropagation(),J_(m)}),e.appendChild(c);let l=document.createElement(`div`);l.className=`export-menu-container`;let u=document.createElement(`button`);u.className=`export-trigger-btn`,u.innerHTML=`<svg t="1781245244396" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5115" width="14" height="14"><path d="M496.213333 739.84c2.133333 2.133333 4.693333 3.84 7.68 5.12 0.853333 0.426667 2.133333 0.426667 2.986667 0.853333 1.706667 0.426667 2.986667 0.853333 4.693333 0.853334 5.546667 0 11.093333-2.133333 14.933334-6.4l256-256c8.533333-8.533333 8.533333-21.76 0-30.293334s-21.76-8.533333-30.293334 0L533.333333 674.133333V128c0-11.946667-9.386667-21.333333-21.333333-21.333333s-21.333333 9.386667-21.333333 21.333333v545.706667l-219.306667-219.306667c-8.533333-8.533333-21.76-8.533333-30.293333 0s-8.533333 21.76 0 30.293333l255.146666 255.146667zM768 874.666667H256c-11.946667 0-21.333333 9.386667-21.333333 21.333333s9.386667 21.333333 21.333333 21.333333h512c11.946667 0 21.333333-9.386667 21.333333-21.333333s-9.386667-21.333333-21.333333-21.333333z" fill="#8a8a8a" p-id="5116"></path></svg><span>${r(`chat.export`)}</span><svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`;let f=document.createElement(`div`);f.className=`export-dropdown`,f.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">`,`<svg t="1781245550030" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6544" width="32" height="32"><path d="M747.936 901.171H276.819c-72.2 0-130.953-55.224-130.953-123.078V244.721c0-67.854 58.752-123.078 130.953-123.078h383.525c6.597 0 12.937 2.505 17.795 6.954l192.363 178.046c5.317 4.96 8.386 11.914 8.386 19.227v452.223c0 67.854-58.752 123.078-130.952 123.078zM276.819 174.004c-43.31 0-78.592 31.703-78.592 70.717v533.372c0 39.015 35.282 70.718 78.592 70.718h471.117c43.31 0 78.592-31.703 78.592-70.718V337.324l-176.461-163.32H276.819z" fill="#8a8a8a" p-id="6545"></path><path d="M830.567 331.546H669.446c-14.471 0-26.18-11.71-26.18-26.181V156.209c0-14.471 11.709-26.18 26.18-26.18s26.181 11.709 26.181 26.18v122.976h134.94c14.471 0 26.181 11.709 26.181 26.18s-11.711 26.181-26.181 26.181z" fill="#8a8a8a" p-id="6546"></path><path d="M730.214 428.749l-92.04 343.616h-53.179L511.363 498.29l-75.677 274.074h-53.179l-92.04-343.616h49.088l69.542 255.667 69.541-255.667h63.406l69.541 255.667 69.541-255.667h49.088z" fill="#8a8a8a" p-id="6547"></path></svg>`,`<span>${r(`chatMsg.exportWord`)}</span>`,`</button>`,`<button class="export-dropdown-item export-pdf-item" type="button">`,`<svg t="1781245863206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8152" width="32" height="32"><path d="M582.4 864H170.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V170.666667c0-6.4 4.266667-10.666667 10.666667-10.666667h309.333333V320c0 40.533333 34.133333 74.666667 74.666667 74.666667h160v38.4c0 17.066667 14.933333 32 32 32s32-14.933333 32-32V298.666667c0-8.533333-4.266667-17.066667-8.533334-23.466667l-170.666666-170.666667c-6.4-6.4-14.933333-8.533333-23.466667-8.533333H170.666667C130.133333 96 96 130.133333 96 170.666667v682.666666c0 40.533333 34.133333 74.666667 74.666667 74.666667h411.733333c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32z m132.266667-550.4v17.066667H554.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V160h19.2l151.466667 153.6z" fill="#8a8a8a" p-id="8153"></path><path d="M332.8 533.333333c-12.8 0-19.2 2.133333-25.6 6.4-6.4 4.266667-8.533333 12.8-8.533333 23.466667v206.933333c0 6.4 2.133333 12.8 6.4 19.2 4.266667 4.266667 10.666667 8.533333 21.333333 8.533334s17.066667-4.266667 21.333333-8.533334c4.266667-4.266667 6.4-10.666667 6.4-19.2v-64h32c57.6 0 89.6-29.866667 89.6-87.466666 0-27.733333-8.533333-51.2-23.466666-64-14.933333-14.933333-36.266667-21.333333-66.133334-21.333334h-53.333333z m87.466667 85.333334c0 12.8-2.133333 23.466667-8.533334 27.733333-4.266667 4.266667-14.933333 8.533333-27.733333 8.533333h-32v-70.4H384c12.8 0 21.333333 2.133333 27.733333 8.533334 6.4 4.266667 8.533333 12.8 8.533334 25.6zM667.733333 571.733333c-8.533333-12.8-21.333333-21.333333-34.133333-29.866666-14.933333-4.266667-32-8.533333-51.2-8.533334h-61.866667c-8.533333 0-17.066667 0-23.466666 8.533334-2.133333 4.266667-4.266667 10.666667-4.266667 19.2V768c0 8.533333 2.133333 14.933333 4.266667 19.2 6.4 8.533333 14.933333 8.533333 23.466666 8.533333h64c19.2 0 34.133333-4.266667 49.066667-10.666666 12.8-6.4 25.6-17.066667 34.133333-29.866667 8.533333-12.8 14.933333-25.6 19.2-42.666667 4.266667-14.933333 6.4-32 6.4-49.066666 0-17.066667-2.133333-34.133333-6.4-49.066667-4.266667-14.933333-10.666667-29.866667-19.2-42.666667z m-42.666666 153.6c-8.533333 12.8-21.333333 19.2-38.4 19.2h-38.4v-160H576c21.333333 0 38.4 6.4 46.933333 19.2 10.666667 12.8 14.933333 34.133333 14.933334 59.733334 2.133333 27.733333-4.266667 46.933333-12.8 61.866666zM851.2 533.333333h-106.666667c-8.533333 0-17.066667 2.133333-21.333333 6.4-6.4 4.266667-8.533333 12.8-8.533333 21.333334v209.066666c0 6.4 2.133333 12.8 6.4 17.066667 4.266667 6.4 10.666667 8.533333 21.333333 8.533333 8.533333 0 17.066667-2.133333 21.333333-8.533333 2.133333-4.266667 6.4-8.533333 6.4-19.2v-85.333333h72.533334c12.8 0 23.466667-6.4 25.6-17.066667 2.133333-8.533333 2.133333-14.933333 0-17.066667-2.133333-4.266667-6.4-17.066667-25.6-17.066666H768v-49.066667h81.066667c8.533333 0 14.933333-2.133333 19.2-4.266667 4.266667-2.133333 8.533333-8.533333 8.533333-21.333333 2.133333-12.8-8.533333-23.466667-25.6-23.466667z" fill="#8a8a8a" p-id="8154"></path></svg>`,`<span>${r(`chatMsg.exportPdf`)}</span>`,`</button>`,`<button class="export-dropdown-item export-image-item" type="button">`,`<svg t="1784207887308" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5993" width="32" height="32"><path d="M400.696 268.795c-17.249 0-31.233 13.986-31.233 31.233v30.471c0 17.249 13.986 31.233 31.233 31.233s31.233-13.986 31.233-31.233v-30.471c0-17.249-13.985-31.233-31.233-31.233z" fill="#8a8a8a" p-id="5994"></path><path d="M623.649 361.734c17.249 0 31.234-13.986 31.234-31.233v-30.471c0-17.249-13.986-31.233-31.234-31.233s-31.233 13.986-31.233 31.233v30.471c-0.001 17.248 13.985 31.233 31.233 31.233z" fill="#8a8a8a" p-id="5995"></path><path d="M438.295 388.804c-14.656 9.104-19.155 28.362-10.050 43.013 11.209 18.047 41.976 48.59 86.157 48.59 43.958 0 75.1-30.313 86.574-48.223 9.303-14.529 5.068-33.847-9.455-43.15-14.539-9.298-33.852-5.068-43.15 9.455-0.122 0.199-13.38 19.45-33.969 19.45-20.009 0-32.444-18.128-33.278-19.373-9.166-14.423-28.28-18.805-42.829-9.761z" fill="#8a8a8a" p-id="5996"></path><path d="M824.508503 116.690676 571.592236 116.690676c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c40.181141 0 72.878844 32.692586 72.878844 72.878844l0 396.966057-189.334159-165.29465c-12.20088-10.655687-30.517037-10.207479-42.173518 0.9967L468.578048 674.16231 309.521472 517.519714c-11.895935-11.70253-30.903847-12.002358-43.154869-0.645706L126.957507 646.163629l0-394.126382c0-40.186258 32.692586-72.878844 72.878844-72.878844l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352S470.000444 116.690676 452.751594 116.690676L199.836351 116.690676c-74.632791 0-135.346571 60.71378-135.346571 135.346571l0 520.56405c0 74.632791 60.71378 135.346571 135.346571 135.346571l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352s-13.985526-31.233352-31.233352-31.233352L199.836351 845.481164c-40.186258 0-72.878844-32.692586-72.878844-72.878844l0-41.23924 160.003134-148.385539 159.428036 157.007917c12.048407 11.865235 31.361265 11.981892 43.546795 0.274246l198.576661-190.68697 208.876238 182.346001 0 40.683585c0 40.186258-32.697703 72.878844-72.878844 72.878844L571.592236 845.481164c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c74.627674 0 135.346571-60.71378 135.346571-135.346571L959.855074 252.037247C959.855074 177.404456 899.136178 116.690676 824.508503 116.690676z" fill="#8a8a8a" p-id="5997"></path></svg>`,`<span>${r(`chatMsg.exportImage`)}</span>`,`</button>`,`<button class="export-dropdown-item export-md-item" type="button">`,`<svg t="1784038824502" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1666" width="32" height="32"><path d="M601.216 85.333333a42.666667 42.666667 0 0 1 30.485333 12.821334l209.450667 213.973333a42.666667 42.666667 0 0 1 12.181333 29.866667V853.333333a85.333333 85.333333 0 0 1-85.333333 85.333334H256a85.333333 85.333333 0 0 1-85.333333-85.333334V170.666667a85.333333 85.333333 0 0 1 85.333333-85.333334h345.216z m-35.584 64H256a21.333333 21.333333 0 0 0-21.333333 21.333334v682.666666a21.333333 21.333333 0 0 0 21.333333 21.333334h512a21.333333 21.333333 0 0 0 21.333333-21.333334V395.413333h-191.68a32 32 0 0 1-32-32L565.632 149.333333z m64 38.186667v143.893333h140.821333L629.632 187.52z" fill="#8a8a8a" p-id="1667"></path><path d="M384.341333 800l-3.072-0.106667a32 32 0 0 1-29.162666-34.624l21.973333-256c2.752-32.256 46.165333-40.490667 60.544-11.477333l77.290667 156.010667 78.805333-156.224c14.08-27.925333 55.082667-20.906667 60.074667 8.789333l0.384 3.050667 20.714666 256a32 32 0 0 1-63.786666 5.162666l-11.541334-142.549333-56.341333 111.722667c-11.413333 22.613333-42.88 23.381333-55.744 2.517333l-1.493333-2.730667-54.912-110.826666-12.181334 142.016a32 32 0 0 1-31.552 29.269333z" fill="#8a8a8a" p-id="1668"></path></svg>`,`<span>${r(`chatMsg.exportMarkdown`)}</span>`,`</button>`].join(``);let p=f.querySelector(`.export-docx-item`);p.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToDocx:t}=await I(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-B5n-Qevt.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));t(m,p,f)});let h=f.querySelector(`.export-md-item`);h.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToMarkdown:t}=await I(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-B5n-Qevt.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));t(m,h,f)});let _=f.querySelector(`.export-pdf-item`);_.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToPdf:t}=await I(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-B5n-Qevt.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));t(m,_,f)});let v=f.querySelector(`.export-image-item`);v.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToImage:t}=await I(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-B5n-Qevt.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));t(m,v,f)}),u.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==f&&e.classList.remove(`show`)}),f.classList.toggle(`show`)});let y=null;l.addEventListener(`mouseenter`,()=>{y=setTimeout(()=>{document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==f&&e.classList.remove(`show`)}),f.classList.add(`show`)},300)}),l.addEventListener(`mouseleave`,()=>{y&&=(clearTimeout(y),null),setTimeout(()=>{!l.matches(`:hover`)&&!f.matches(`:hover`)&&f.classList.remove(`show`)},100)}),l.appendChild(u),l.appendChild(f),e.appendChild(l);let b=document.createElement(`div`);b.className=`footer-right-actions`,b.style.marginLeft=`auto`,b.style.display=`flex`,b.style.alignItems=`center`,b.style.gap=`8px`;let x=ot(i);if(x){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:B(x.totalTokens),prompt:B(x.promptTokens),completion:B(x.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${B(x.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),ft(x,e)}),b.appendChild(e)}let S=i&&i.length>0,C=o!=null,w=i?i.filter(e=>e.nodeType===`reflection`&&e.reflectionType===`post`&&e.status===`success`).length:0;Ey(),Oy(),bo();let T=i?.find(e=>e.nodeType===`reflection`&&e.reflectionType===`post`),E=bg(t),D=Cg(i,t);if(E.length&&(m.dataset.declaredArtifacts=JSON.stringify(E)),Vg(D),console.log(`[addMessage] executionLog entries:`,i?.length,`| agent_file entries:`,i?.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`agent_file`).length,`| artifacts:`,D.length),D.length>0){let e=document.createElement(`button`);e.className=`artifacts-btn`,e.type=`button`,e.title=r(`artifacts.btnTitle`,{count:D.length}),e.innerHTML=`
1783
1783
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
1784
1784
  <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
1785
1785
  <polyline points="14 2 14 8 20 8"/>
@@ -1852,11 +1852,11 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
1852
1852
  <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
1853
1853
  <path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>
1854
1854
  </svg>
1855
- </button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),s.querySelectorAll(`.subtask-progress`).forEach(e=>{py(e)}),s.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),Py(F.activeSessionId)})}),s.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:F.activeSessionId}),e.disabled=!0,e.title=r(`chatMsg.aborting`)})});let l=s.querySelector(`.message-footer`);if(l){let e=l.querySelector(`.copy-btn`);e&&e.addEventListener(`click`,t=>{t.stopPropagation(),B_(s,e,t)});let t=l.querySelector(`.quote-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),J_(s)});let n=l.querySelector(`.export-trigger-btn`),r=l.querySelector(`.export-dropdown`);n&&r&&(n.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==r&&e.classList.remove(`show`)}),r.classList.toggle(`show`)}),r.querySelector(`.export-docx-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToDocx:n}=await I(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-CBdPUbRE.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));n(s,t,r)}),r.querySelector(`.export-md-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToMarkdown:n}=await I(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-CBdPUbRE.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));n(s,t,r)}),r.querySelector(`.export-pdf-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToPdf:n}=await I(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-CBdPUbRE.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));n(s,t,r)}),r.querySelector(`.export-image-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToImage:n}=await I(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-CBdPUbRE.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));n(s,t,r)}));let i=l.querySelector(`.prototype-btn-small`);if(i){let e=(()=>{try{let e=s.dataset.executionLog;return e?JSON.parse(e):[]}catch{return[]}})().find(e=>e.nodeType===`tool_exec`&&e.action?.name===`preview_ui`||e.action?.name===`preview_preview_ui`&&e.status===`success`);e&&i.addEventListener(`click`,()=>{let t=e.prototypeId;if(!t&&e.observation)try{t=(typeof e.observation==`string`?JSON.parse(e.observation):e.observation)?.prototypeId}catch{}t?Os(t):a.error(`[SidePanel] not found prototypeId,entry keys:`,Object.keys(e),`observation:`,e.observation)})}let o=l.querySelector(`.bookmark-btn`);o&&(Qu(o,F.activeSessionId,s.dataset.messageId),o.addEventListener(`click`,async e=>{e.stopPropagation();let t=F.activeSessionId,n=s.dataset.messageId;if(o.classList.contains(`bookmarked`)){await Bu(t,n),Qu(o,t,n);let{refreshBookmarkPanel:e}=await I(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Wu);return{refreshBookmarkPanel:e}},void 0);e()}else{await zu(t,n,s.dataset.textContent_||``,F.sessions.find(e=>e.id===t)?.title||``),Qu(o,t,n);let{refreshBookmarkPanel:e}=await I(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Wu);return{refreshBookmarkPanel:e}},void 0);e()}}));let c=l.querySelector(`.delete-btn`);c&&c.addEventListener(`click`,e=>{e.stopPropagation(),Iy(s)});let u=l.querySelector(`.fork-btn`);u&&u.addEventListener(`click`,async e=>{e.stopPropagation();let t=s.dataset.messageId;t&&await ts(F.activeSessionId,t)});let d=l.querySelector(`.resume-task-btn`);d&&d.addEventListener(`click`,async e=>{if(e.stopPropagation(),d.disabled)return;let t=await Z_();t!==null&&(d.disabled=!0,d.style.opacity=`0.6`,d.style.cursor=`not-allowed`,tv(F.activeSessionId,t).finally(()=>{d.disabled=!1,d.style.opacity=``,d.style.cursor=``}))}),jy(s);let f=l.querySelector(`.token-usage-tag`);f&&!f._clickBound&&(f._clickBound=!0,f.style.cursor=`pointer`,f.addEventListener(`click`,e=>{e.stopPropagation();try{let e=s.dataset.executionLog,t=ot(e?JSON.parse(e):[]);t&&ft(t,f)}catch{}}))}let u=s.querySelector(`.message-toolbar`);if(u){let e=u.querySelector(`.edit-btn`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),zy(s)});let t=u.querySelector(`.copy-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),z_(s,t)});let n=u.querySelector(`.delete-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),Iy(s)})}s.querySelectorAll(`.user-message-image`).forEach(e=>{e.addEventListener(`click`,()=>{Rl(e.src,e)})}),i.appendChild(s),Qx()}function Ny(e){e.querySelectorAll(`.tool-call-body > pre, .tool-result-content > pre, .agent-stream-output > pre`).forEach(e=>{if(e.parentElement.classList.contains(`code-block-container`))return;let t=document.createElement(`div`);t.className=`code-block-container`,t.style.position=`relative`,t.innerHTML=`<button class="code-copy-btn" title="${r(`chatMsg.copyCode`)}">
1855
+ </button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),s.querySelectorAll(`.subtask-progress`).forEach(e=>{py(e)}),s.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),Py(F.activeSessionId)})}),s.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:F.activeSessionId}),e.disabled=!0,e.title=r(`chatMsg.aborting`)})});let l=s.querySelector(`.message-footer`);if(l){let e=l.querySelector(`.copy-btn`);e&&e.addEventListener(`click`,t=>{t.stopPropagation(),B_(s,e,t)});let t=l.querySelector(`.quote-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),J_(s)});let n=l.querySelector(`.export-trigger-btn`),r=l.querySelector(`.export-dropdown`);n&&r&&(n.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==r&&e.classList.remove(`show`)}),r.classList.toggle(`show`)}),r.querySelector(`.export-docx-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToDocx:n}=await I(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-B5n-Qevt.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));n(s,t,r)}),r.querySelector(`.export-md-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToMarkdown:n}=await I(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-B5n-Qevt.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));n(s,t,r)}),r.querySelector(`.export-pdf-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToPdf:n}=await I(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-B5n-Qevt.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));n(s,t,r)}),r.querySelector(`.export-image-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToImage:n}=await I(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-B5n-Qevt.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));n(s,t,r)}));let i=l.querySelector(`.prototype-btn-small`);if(i){let e=(()=>{try{let e=s.dataset.executionLog;return e?JSON.parse(e):[]}catch{return[]}})().find(e=>e.nodeType===`tool_exec`&&e.action?.name===`preview_ui`||e.action?.name===`preview_preview_ui`&&e.status===`success`);e&&i.addEventListener(`click`,()=>{let t=e.prototypeId;if(!t&&e.observation)try{t=(typeof e.observation==`string`?JSON.parse(e.observation):e.observation)?.prototypeId}catch{}t?Os(t):a.error(`[SidePanel] not found prototypeId,entry keys:`,Object.keys(e),`observation:`,e.observation)})}let o=l.querySelector(`.bookmark-btn`);o&&(Qu(o,F.activeSessionId,s.dataset.messageId),o.addEventListener(`click`,async e=>{e.stopPropagation();let t=F.activeSessionId,n=s.dataset.messageId;if(o.classList.contains(`bookmarked`)){await Bu(t,n),Qu(o,t,n);let{refreshBookmarkPanel:e}=await I(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Wu);return{refreshBookmarkPanel:e}},void 0);e()}else{await zu(t,n,s.dataset.textContent_||``,F.sessions.find(e=>e.id===t)?.title||``),Qu(o,t,n);let{refreshBookmarkPanel:e}=await I(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Wu);return{refreshBookmarkPanel:e}},void 0);e()}}));let c=l.querySelector(`.delete-btn`);c&&c.addEventListener(`click`,e=>{e.stopPropagation(),Iy(s)});let u=l.querySelector(`.fork-btn`);u&&u.addEventListener(`click`,async e=>{e.stopPropagation();let t=s.dataset.messageId;t&&await ts(F.activeSessionId,t)});let d=l.querySelector(`.resume-task-btn`);d&&d.addEventListener(`click`,async e=>{if(e.stopPropagation(),d.disabled)return;let t=await Z_();t!==null&&(d.disabled=!0,d.style.opacity=`0.6`,d.style.cursor=`not-allowed`,tv(F.activeSessionId,t).finally(()=>{d.disabled=!1,d.style.opacity=``,d.style.cursor=``}))}),jy(s);let f=l.querySelector(`.token-usage-tag`);f&&!f._clickBound&&(f._clickBound=!0,f.style.cursor=`pointer`,f.addEventListener(`click`,e=>{e.stopPropagation();try{let e=s.dataset.executionLog,t=ot(e?JSON.parse(e):[]);t&&ft(t,f)}catch{}}))}let u=s.querySelector(`.message-toolbar`);if(u){let e=u.querySelector(`.edit-btn`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),zy(s)});let t=u.querySelector(`.copy-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),z_(s,t)});let n=u.querySelector(`.delete-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),Iy(s)})}s.querySelectorAll(`.user-message-image`).forEach(e=>{e.addEventListener(`click`,()=>{Rl(e.src,e)})}),i.appendChild(s),Qx()}function Ny(e){e.querySelectorAll(`.tool-call-body > pre, .tool-result-content > pre, .agent-stream-output > pre`).forEach(e=>{if(e.parentElement.classList.contains(`code-block-container`))return;let t=document.createElement(`div`);t.className=`code-block-container`,t.style.position=`relative`,t.innerHTML=`<button class="code-copy-btn" title="${r(`chatMsg.copyCode`)}">
1856
1856
  <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
1857
1857
  <path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>
1858
1858
  </svg>
1859
- </button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),e.querySelectorAll(`.thinking-process-header`).forEach(e=>{gv(e)}),e.querySelectorAll(`.tool-call-header`).forEach(e=>{e.addEventListener(`click`,t=>{if(t.ctrlKey||t.metaKey)return;let n=e.closest(`.tool-call-item`);n&&n.classList.toggle(`expanded`)})}),e.querySelectorAll(`.tool-call-result`).forEach(e=>{let t=e.querySelector(`code`);if(!t)return;let n=t.dataset.fullContent;if(!n||n.length<=500)return;let r=t.textContent||``,i=!1;e.style.cursor=`pointer`,e.addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||(e.stopPropagation(),i=!i,t.textContent=i?n:r)})}),e.querySelectorAll(`.subtask-progress`).forEach(e=>{py(e)}),e.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),Py(F.activeSessionId)})}),e.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:F.activeSessionId}),e.disabled=!0,e.title=r(`chatMsg.aborting`)})}),e.querySelectorAll(`.message-footer`).forEach(e=>{let t=e.closest(`.message`);if(!t)return;let n=e.querySelector(`.copy-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),B_(t,n,e)});let r=e.querySelector(`.quote-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),J_(t)});let i=e.querySelector(`.export-trigger-btn`),a=e.querySelector(`.export-dropdown`);i&&a&&(i.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==a&&e.classList.remove(`show`)}),a.classList.toggle(`show`)}),a.querySelector(`.export-docx-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToDocx:r}=await I(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-CBdPUbRE.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));r(t,n,a)}),a.querySelector(`.export-md-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToMarkdown:r}=await I(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-CBdPUbRE.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));r(t,n,a)}),a.querySelector(`.export-pdf-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToPdf:r}=await I(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-CBdPUbRE.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));r(t,n,a)}),a.querySelector(`.export-image-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToImage:r}=await I(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-CBdPUbRE.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));r(t,n,a)}));let o=e.querySelector(`.prototype-btn-small`);if(o){let e=(()=>{try{let e=t.dataset.executionLog;return e?JSON.parse(e):[]}catch{return[]}})().find(e=>e.nodeType===`tool_exec`&&e.action?.name===`preview_ui`||e.action?.name===`preview_preview_ui`&&e.status===`success`);e&&o.addEventListener(`click`,()=>{let t=e.prototypeId;if(!t&&e.observation)try{t=(typeof e.observation==`string`?JSON.parse(e.observation):e.observation)?.prototypeId}catch{}t&&Os(t)})}let s=e.querySelector(`.bookmark-btn`);s&&(Qu(s,F.activeSessionId,t.dataset.messageId),s.addEventListener(`click`,async e=>{e.stopPropagation();let n=F.activeSessionId,r=t.dataset.messageId;if(s.classList.contains(`bookmarked`)){await Bu(n,r),Qu(s,n,r);let{refreshBookmarkPanel:e}=await I(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Wu);return{refreshBookmarkPanel:e}},void 0);e()}else{await zu(n,r,t.dataset.textContent_||``,F.sessions.find(e=>e.id===n)?.title||``),Qu(s,n,r);let{refreshBookmarkPanel:e}=await I(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Wu);return{refreshBookmarkPanel:e}},void 0);e()}}));let c=e.querySelector(`.delete-btn`);c&&c.addEventListener(`click`,e=>{e.stopPropagation(),Iy(t)});let l=e.querySelector(`.fork-btn`);l&&l.addEventListener(`click`,async e=>{e.stopPropagation();let n=t.dataset.messageId;n&&await ts(F.activeSessionId,n)});let u=e.querySelector(`.resume-task-btn`);u&&u.addEventListener(`click`,async e=>{if(e.stopPropagation(),u.disabled)return;let t=await Z_();t!==null&&(u.disabled=!0,u.style.opacity=`0.6`,u.style.cursor=`not-allowed`,tv(F.activeSessionId,t).finally(()=>{u.disabled=!1,u.style.opacity=``,u.style.cursor=``}))}),jy(t);let d=e.querySelector(`.token-usage-tag`);d&&!d._clickBound&&(d._clickBound=!0,d.style.cursor=`pointer`,d.addEventListener(`click`,e=>{e.stopPropagation();try{let e=t.dataset.executionLog,n=ot(e?JSON.parse(e):[]);n&&ft(n,d)}catch{}}))}),e.querySelectorAll(`.message-toolbar`).forEach(e=>{let t=e.closest(`.message`);if(!t)return;let n=e.querySelector(`.edit-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),zy(t)});let r=e.querySelector(`.copy-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),z_(t,r)});let i=e.querySelector(`.delete-btn`);i&&i.addEventListener(`click`,e=>{e.stopPropagation(),Iy(t)})}),e.querySelectorAll(`.user-message-image`).forEach(e=>{e.addEventListener(`click`,()=>{Rl(e.src,e)})}),e.querySelectorAll(`.mermaid-controls`).forEach(e=>e.remove()),po(),Ey(),Oy(),Qx()}function Py(e){return new Promise(t=>{let n=document.querySelector(`.command-terminate-overlay`);n&&n.remove();let i=document.createElement(`div`);i.className=`command-terminate-overlay`,i.innerHTML=`
1859
+ </button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),e.querySelectorAll(`.thinking-process-header`).forEach(e=>{gv(e)}),e.querySelectorAll(`.tool-call-header`).forEach(e=>{e.addEventListener(`click`,t=>{if(t.ctrlKey||t.metaKey)return;let n=e.closest(`.tool-call-item`);n&&n.classList.toggle(`expanded`)})}),e.querySelectorAll(`.tool-call-result`).forEach(e=>{let t=e.querySelector(`code`);if(!t)return;let n=t.dataset.fullContent;if(!n||n.length<=500)return;let r=t.textContent||``,i=!1;e.style.cursor=`pointer`,e.addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||(e.stopPropagation(),i=!i,t.textContent=i?n:r)})}),e.querySelectorAll(`.subtask-progress`).forEach(e=>{py(e)}),e.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),Py(F.activeSessionId)})}),e.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:F.activeSessionId}),e.disabled=!0,e.title=r(`chatMsg.aborting`)})}),e.querySelectorAll(`.message-footer`).forEach(e=>{let t=e.closest(`.message`);if(!t)return;let n=e.querySelector(`.copy-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),B_(t,n,e)});let r=e.querySelector(`.quote-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),J_(t)});let i=e.querySelector(`.export-trigger-btn`),a=e.querySelector(`.export-dropdown`);i&&a&&(i.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==a&&e.classList.remove(`show`)}),a.classList.toggle(`show`)}),a.querySelector(`.export-docx-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToDocx:r}=await I(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-B5n-Qevt.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));r(t,n,a)}),a.querySelector(`.export-md-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToMarkdown:r}=await I(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-B5n-Qevt.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));r(t,n,a)}),a.querySelector(`.export-pdf-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToPdf:r}=await I(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-B5n-Qevt.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));r(t,n,a)}),a.querySelector(`.export-image-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToImage:r}=await I(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-B5n-Qevt.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,4,12,2,3,0]));r(t,n,a)}));let o=e.querySelector(`.prototype-btn-small`);if(o){let e=(()=>{try{let e=t.dataset.executionLog;return e?JSON.parse(e):[]}catch{return[]}})().find(e=>e.nodeType===`tool_exec`&&e.action?.name===`preview_ui`||e.action?.name===`preview_preview_ui`&&e.status===`success`);e&&o.addEventListener(`click`,()=>{let t=e.prototypeId;if(!t&&e.observation)try{t=(typeof e.observation==`string`?JSON.parse(e.observation):e.observation)?.prototypeId}catch{}t&&Os(t)})}let s=e.querySelector(`.bookmark-btn`);s&&(Qu(s,F.activeSessionId,t.dataset.messageId),s.addEventListener(`click`,async e=>{e.stopPropagation();let n=F.activeSessionId,r=t.dataset.messageId;if(s.classList.contains(`bookmarked`)){await Bu(n,r),Qu(s,n,r);let{refreshBookmarkPanel:e}=await I(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Wu);return{refreshBookmarkPanel:e}},void 0);e()}else{await zu(n,r,t.dataset.textContent_||``,F.sessions.find(e=>e.id===n)?.title||``),Qu(s,n,r);let{refreshBookmarkPanel:e}=await I(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Wu);return{refreshBookmarkPanel:e}},void 0);e()}}));let c=e.querySelector(`.delete-btn`);c&&c.addEventListener(`click`,e=>{e.stopPropagation(),Iy(t)});let l=e.querySelector(`.fork-btn`);l&&l.addEventListener(`click`,async e=>{e.stopPropagation();let n=t.dataset.messageId;n&&await ts(F.activeSessionId,n)});let u=e.querySelector(`.resume-task-btn`);u&&u.addEventListener(`click`,async e=>{if(e.stopPropagation(),u.disabled)return;let t=await Z_();t!==null&&(u.disabled=!0,u.style.opacity=`0.6`,u.style.cursor=`not-allowed`,tv(F.activeSessionId,t).finally(()=>{u.disabled=!1,u.style.opacity=``,u.style.cursor=``}))}),jy(t);let d=e.querySelector(`.token-usage-tag`);d&&!d._clickBound&&(d._clickBound=!0,d.style.cursor=`pointer`,d.addEventListener(`click`,e=>{e.stopPropagation();try{let e=t.dataset.executionLog,n=ot(e?JSON.parse(e):[]);n&&ft(n,d)}catch{}}))}),e.querySelectorAll(`.message-toolbar`).forEach(e=>{let t=e.closest(`.message`);if(!t)return;let n=e.querySelector(`.edit-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),zy(t)});let r=e.querySelector(`.copy-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),z_(t,r)});let i=e.querySelector(`.delete-btn`);i&&i.addEventListener(`click`,e=>{e.stopPropagation(),Iy(t)})}),e.querySelectorAll(`.user-message-image`).forEach(e=>{e.addEventListener(`click`,()=>{Rl(e.src,e)})}),e.querySelectorAll(`.mermaid-controls`).forEach(e=>e.remove()),po(),Ey(),Oy(),Qx()}function Py(e){return new Promise(t=>{let n=document.querySelector(`.command-terminate-overlay`);n&&n.remove();let i=document.createElement(`div`);i.className=`command-terminate-overlay`,i.innerHTML=`
1860
1860
  <div class="command-terminate-modal">
1861
1861
  <div class="command-terminate-header">
1862
1862
  <div class="command-terminate-icon">⏹</div>
@@ -1908,7 +1908,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
1908
1908
  <h2>${r(`chat.welcomeTitle`)}</h2>
1909
1909
  <p>${r(`chat.welcomeSubtitle`)}</p>
1910
1910
  </div>
1911
- `),await $v(),n&&F.activeSessionId&&j(F.activeSessionId,n).then(e=>{e||a.warn(`[SidePanel] IndexedDB messagecleanup failed, messageId:`,n)}).catch(e=>{a.error(`[SidePanel] IndexedDB messagecleanup exception:`,e)}),a.debug(`[SidePanel] deletedmessage: ${i}, messageId: ${n}`)}async function Ly(e=null){try{let{mcpTools:t}=await chrome.storage.local.get([`mcpTools`]),n=t||[],r=new Set(Array.isArray(F.mcpClosedServers)?F.mcpClosedServers:[]),i=new Set(Array.isArray(F.activeAgentMcpExcludedServerIds)?F.activeAgentMcpExcludedServerIds:[]),a=new Set(Array.isArray(e)?e:[]);return n.filter(e=>{let t=e.serverId||`unknown`;return a.has(t)?!0:!r.has(t)&&!i.has(t)}).length}catch{return 0}}async function Ry(e,t,n=!1,i={},o={}){let{resumeFromCheckpoint:s=!1,userGuidance:c=``,loadingId:l=null,forcedMcpServerIds:u=null}=o,d=(await Ze()).loopTimeout,f=await new Promise(e=>{chrome.storage.local.get(`reflectionConfig`,t=>{e(t.reflectionConfig||{enabled:!1})})}),p=F.activeSessionId,m=s?`resume_${Date.now()}_${Math.random().toString(36).substring(2,8)}`:`call_${Date.now()}_${Math.random().toString(36).substring(2,8)}`;if(a.debug(`[SidePanel] callApi: generating callId: ${m}${s?` (restoremode)`:``}`),s&&l&&(i={...i,_loadingId:l}),F.pendingCancelApiMap&&F.pendingCancelApiMap.has(p)){a.debug(`[SidePanel] callApi: detectedsession has ongoing API call with , first cancelold`);let e=F.pendingCancelApiMap.get(p);e&&e({message:r(`chatMsg.errTaskReplaced`),executionLog:[]})}F.pendingCallApiSessionIds&&F.pendingCallApiSessionIds.has(p)&&(F.pendingCallApiSessionIds.delete(p),Uv());let h=wv(p),g=chrome.runtime.connect({name:`keepalive-`+p});a.debug(`[SidePanel] keepalive portconnected, sessionId:`,p),sc(p);try{let e=oc();g.postMessage({type:`KEEPALIVE_IDENTITY`,identity:e==null?null:{windowId:e}})}catch{}let _={restarted:!1,rejectFn:null,cleanup:null,checkpoint:null};g.onMessage.addListener(e=>{if(e.type===`HOST_TAB_RESOLVED`&&e.sessionId===p){cc(p,e.hostTabId);return}e.type===`SW_RESTARTED`&&e.sessionId===p&&(a.warn(`[SidePanel] ⚠️ recei to SW_RESTARTED notification,background re started,API call lost`),_.restarted=!0,_.checkpoint=e.checkpoint||null,_.rejectFn&&_.cleanup&&(_.cleanup(),_.rejectFn({message:r(`chatMsg.errSwRestarted`),executionLog:[],checkpoint:_.checkpoint,swRestarted:!0}))),e.type===`SHOW_CLARIFY_DIALOG`?wr(e.data):e.type===`CLARIFY_TIMEOUT`?kr(e):e.type===`CLARIFY_EXTENDED`?mr(e):e.type===`SHOW_CONFIRM_DIALOG`?Kr(e.data):e.type===`DISMISS_CONFIRM_DIALOG`&&Yr(e.data)});let v={timeoutId:null,removeListener:()=>{}},y=()=>{try{g.disconnect()}catch{}v.timeoutId&&=(clearTimeout(v.timeoutId),null),v.removeListener(),F.pendingCancelApiMap.delete(p),F.pendingCallApiSessionIds.delete(p),Tv(p),Uv()};return new Promise((o,l)=>{if(_.cleanup=y,_.rejectFn=l,_.restarted){y(),l({message:r(`chatMsg.errSwRestarted`),executionLog:[],checkpoint:_.checkpoint,swRestarted:!0});return}let g=[],b=Math.round(d/1e3);h(null),Ov(null),Av(0);let x=``,S={},C=e=>{h()&&Vv(h()),y(),(!e.executionLog||e.executionLog.length===0||g.length>0)&&(e.executionLog=g),l(e)};F.pendingCancelApi=C,F.pendingCallApiSessionIds.add(p),Uv(),a.debug(`[SidePanel] callApi: add pendingCallApiSessionIds, mySessionId =`,p,`, set:`,[...F.pendingCallApiSessionIds]),v.timeoutId=setTimeout(()=>{C({message:r(`chatMsg.errTimeout`,{seconds:b}),executionLog:g}),chrome.runtime.sendMessage({type:`CANCEL_REACT`,tabId:F.currentTabId,sessionId:F.activeSessionId}).catch(e=>{a.debug(`[SidePanel] sendcancelrequest failed:`,e.message)})},d);let w=Date.now(),T=0,E=null,D=()=>{E===null&&v.timeoutId!==null&&(E=Date.now(),clearTimeout(v.timeoutId),v.timeoutId=null,a.debug(`[SidePanel] before sidetimeoutpaused (waitinguser response:clarification/sensitive toolconfirm)`))},O=()=>{if(E!==null){let e=Date.now()-E;T+=e,E=null;let t=Date.now()-w,n=d+T-t;if(n<=0){C({message:r(`chatMsg.errTimeout`,{seconds:b}),executionLog:g});return}v.timeoutId=setTimeout(()=>{C({message:r(`chatMsg.errTimeout`,{seconds:b}),executionLog:g}),chrome.runtime.sendMessage({type:`CANCEL_REACT`,tabId:F.currentTabId,sessionId:p}).catch(e=>{a.debug(`[SidePanel] sendcancelrequest failed:`,e.message)})},n),a.debug(`[SidePanel] before sidetimeoutrestored,pause duration:`,Math.round(e/1e3),`s,remaining time:`,Math.round(n/1e3),`s`)}},k=e=>{if(e.sessionId&&e.sessionId!==p||e.callId&&e.callId!==m)return!1;if(e.type===`EXECUTION_STATUS_UPDATE`){let t=e.executionLog||[];if(t.length>0&&t.forEach(e=>{let t=g.findIndex(t=>t.id===e.id);t===-1?g.push(e):g[t]={...g[t],...e}}),e.subtaskTotal&&e.subtaskTotal>0){let t=h();if(t){let n=t.querySelector(`.stream-content`);if(n){let t=e.subtaskIndex??0,i=dy(g);i&&[...i.items].sort((e,t)=>e.index-t.index).forEach(r=>{if(r.index===t)return;let a=`.subtask-progress[data-subtask-index="${r.index}"]`;if(n.querySelector(a))return;let o=document.createElement(`div`);o.className=`subtask-progress subtask-progress-pending`,o.dataset.subtaskIndex=r.index,o.innerHTML=fy(r,i.total||e.subtaskTotal),my(n,o),py(o)});let a=`.subtask-progress[data-subtask-index="${t}"]`,o=n.querySelector(a),s=o?o.classList.contains(`subtask-expanded`):!1;o||(o=document.createElement(`div`),o.className=`subtask-progress`,o.dataset.subtaskIndex=t,my(n,o));let c=ly,l=t+1,u=e.subtaskTotal,d=e.subtaskName||``,f=`<span class="subtask-badge">${l}/${u}</span>`,p=uy,m=e.status!==`success`&&e.status!==`failed`,h=g.filter(e=>e.subtaskIndex===t&&e.nodeType!==`subtask`),_=h.length,v=h.filter(e=>e.status===`success`).length,y=h.filter(e=>e.status===`failed`).length,b=h.find(e=>e.status===`processing`),x=oy(e.status,v,_),S=i?i.items.find(e=>e.index===t):null,C=S&&S.description?String(S.description).replace(/\s+/g,` `).trim():``,w=g.find(e=>e.subtaskIndex===t&&e.nodeType===`subtask`);o.classList.remove(`subtask-progress-pending`);let T=``;e.status===`success`?(T=`<span class="subtask-status-done">${r(`chatMsg.subtaskDone`)}</span>`,o.classList.add(`subtask-progress-done`),o.classList.remove(`subtask-progress-active`)):x===`partial`?(T=`<span class="subtask-status-partial">${r(`chatMsg.subtaskPartial`)}</span>`,o.classList.add(`subtask-progress-failed`),o.classList.remove(`subtask-progress-active`)):e.status===`failed`?(T=`<span class="subtask-status-failed">${r(`chatMsg.subtaskFailed`)}</span>`,o.classList.add(`subtask-progress-failed`),o.classList.remove(`subtask-progress-active`)):(T=`<span class="subtask-status-label"><span class="subtask-spinner"></span>${r(`chatMsg.subtaskExecuting`)}</span>`,o.classList.add(`subtask-progress-active`));let E=``;if(m&&_>0){let e=b?b.nodeType===`tool_exec`?`🔧`:b.nodeType===`api_call`?`📡`:b.nodeType===`reflection`?`🎯`:b.nodeType===`preselect`?`🔍`:`○`:`○`,t=b?R(b.nodeName||``):r(`chatMsg.preparing`),n=b?Wc(b):``;E=`<div class="subtask-progress-line">
1911
+ `),await $v(),n&&F.activeSessionId&&de(F.activeSessionId,n).then(e=>{e||a.warn(`[SidePanel] IndexedDB messagecleanup failed, messageId:`,n)}).catch(e=>{a.error(`[SidePanel] IndexedDB messagecleanup exception:`,e)}),a.debug(`[SidePanel] deletedmessage: ${i}, messageId: ${n}`)}async function Ly(e=null){try{let{mcpTools:t}=await chrome.storage.local.get([`mcpTools`]),n=t||[],r=new Set(Array.isArray(F.mcpClosedServers)?F.mcpClosedServers:[]),i=new Set(Array.isArray(F.activeAgentMcpExcludedServerIds)?F.activeAgentMcpExcludedServerIds:[]),a=new Set(Array.isArray(e)?e:[]);return n.filter(e=>{let t=e.serverId||`unknown`;return a.has(t)?!0:!r.has(t)&&!i.has(t)}).length}catch{return 0}}async function Ry(e,t,n=!1,i={},o={}){let{resumeFromCheckpoint:s=!1,userGuidance:c=``,loadingId:l=null,forcedMcpServerIds:u=null}=o,d=(await Ze()).loopTimeout,f=await new Promise(e=>{chrome.storage.local.get(`reflectionConfig`,t=>{e(t.reflectionConfig||{enabled:!1})})}),p=F.activeSessionId,m=s?`resume_${Date.now()}_${Math.random().toString(36).substring(2,8)}`:`call_${Date.now()}_${Math.random().toString(36).substring(2,8)}`;if(a.debug(`[SidePanel] callApi: generating callId: ${m}${s?` (restoremode)`:``}`),s&&l&&(i={...i,_loadingId:l}),F.pendingCancelApiMap&&F.pendingCancelApiMap.has(p)){a.debug(`[SidePanel] callApi: detectedsession has ongoing API call with , first cancelold`);let e=F.pendingCancelApiMap.get(p);e&&e({message:r(`chatMsg.errTaskReplaced`),executionLog:[]})}F.pendingCallApiSessionIds&&F.pendingCallApiSessionIds.has(p)&&(F.pendingCallApiSessionIds.delete(p),Uv());let h=wv(p),g=chrome.runtime.connect({name:`keepalive-`+p});a.debug(`[SidePanel] keepalive portconnected, sessionId:`,p),sc(p);try{let e=oc();g.postMessage({type:`KEEPALIVE_IDENTITY`,identity:e==null?null:{windowId:e}})}catch{}let _={restarted:!1,rejectFn:null,cleanup:null,checkpoint:null};g.onMessage.addListener(e=>{if(e.type===`HOST_TAB_RESOLVED`&&e.sessionId===p){cc(p,e.hostTabId);return}e.type===`SW_RESTARTED`&&e.sessionId===p&&(a.warn(`[SidePanel] ⚠️ recei to SW_RESTARTED notification,background re started,API call lost`),_.restarted=!0,_.checkpoint=e.checkpoint||null,_.rejectFn&&_.cleanup&&(_.cleanup(),_.rejectFn({message:r(`chatMsg.errSwRestarted`),executionLog:[],checkpoint:_.checkpoint,swRestarted:!0}))),e.type===`SHOW_CLARIFY_DIALOG`?wr(e.data):e.type===`CLARIFY_TIMEOUT`?kr(e):e.type===`CLARIFY_EXTENDED`?mr(e):e.type===`SHOW_CONFIRM_DIALOG`?Kr(e.data):e.type===`DISMISS_CONFIRM_DIALOG`&&Yr(e.data)});let v={timeoutId:null,removeListener:()=>{}},y=()=>{try{g.disconnect()}catch{}v.timeoutId&&=(clearTimeout(v.timeoutId),null),v.removeListener(),F.pendingCancelApiMap.delete(p),F.pendingCallApiSessionIds.delete(p),Tv(p),Uv()};return new Promise((o,l)=>{if(_.cleanup=y,_.rejectFn=l,_.restarted){y(),l({message:r(`chatMsg.errSwRestarted`),executionLog:[],checkpoint:_.checkpoint,swRestarted:!0});return}let g=[],b=Math.round(d/1e3);h(null),Ov(null),Av(0);let x=``,S={},C=e=>{h()&&Vv(h()),y(),(!e.executionLog||e.executionLog.length===0||g.length>0)&&(e.executionLog=g),l(e)};F.pendingCancelApi=C,F.pendingCallApiSessionIds.add(p),Uv(),a.debug(`[SidePanel] callApi: add pendingCallApiSessionIds, mySessionId =`,p,`, set:`,[...F.pendingCallApiSessionIds]),v.timeoutId=setTimeout(()=>{C({message:r(`chatMsg.errTimeout`,{seconds:b}),executionLog:g}),chrome.runtime.sendMessage({type:`CANCEL_REACT`,tabId:F.currentTabId,sessionId:F.activeSessionId}).catch(e=>{a.debug(`[SidePanel] sendcancelrequest failed:`,e.message)})},d);let w=Date.now(),T=0,E=null,D=()=>{E===null&&v.timeoutId!==null&&(E=Date.now(),clearTimeout(v.timeoutId),v.timeoutId=null,a.debug(`[SidePanel] before sidetimeoutpaused (waitinguser response:clarification/sensitive toolconfirm)`))},O=()=>{if(E!==null){let e=Date.now()-E;T+=e,E=null;let t=Date.now()-w,n=d+T-t;if(n<=0){C({message:r(`chatMsg.errTimeout`,{seconds:b}),executionLog:g});return}v.timeoutId=setTimeout(()=>{C({message:r(`chatMsg.errTimeout`,{seconds:b}),executionLog:g}),chrome.runtime.sendMessage({type:`CANCEL_REACT`,tabId:F.currentTabId,sessionId:p}).catch(e=>{a.debug(`[SidePanel] sendcancelrequest failed:`,e.message)})},n),a.debug(`[SidePanel] before sidetimeoutrestored,pause duration:`,Math.round(e/1e3),`s,remaining time:`,Math.round(n/1e3),`s`)}},k=e=>{if(e.sessionId&&e.sessionId!==p||e.callId&&e.callId!==m)return!1;if(e.type===`EXECUTION_STATUS_UPDATE`){let t=e.executionLog||[];if(t.length>0&&t.forEach(e=>{let t=g.findIndex(t=>t.id===e.id);t===-1?g.push(e):g[t]={...g[t],...e}}),e.subtaskTotal&&e.subtaskTotal>0){let t=h();if(t){let n=t.querySelector(`.stream-content`);if(n){let t=e.subtaskIndex??0,i=dy(g);i&&[...i.items].sort((e,t)=>e.index-t.index).forEach(r=>{if(r.index===t)return;let a=`.subtask-progress[data-subtask-index="${r.index}"]`;if(n.querySelector(a))return;let o=document.createElement(`div`);o.className=`subtask-progress subtask-progress-pending`,o.dataset.subtaskIndex=r.index,o.innerHTML=fy(r,i.total||e.subtaskTotal),my(n,o),py(o)});let a=`.subtask-progress[data-subtask-index="${t}"]`,o=n.querySelector(a),s=o?o.classList.contains(`subtask-expanded`):!1;o||(o=document.createElement(`div`),o.className=`subtask-progress`,o.dataset.subtaskIndex=t,my(n,o));let c=ly,l=t+1,u=e.subtaskTotal,d=e.subtaskName||``,f=`<span class="subtask-badge">${l}/${u}</span>`,p=uy,m=e.status!==`success`&&e.status!==`failed`,h=g.filter(e=>e.subtaskIndex===t&&e.nodeType!==`subtask`),_=h.length,v=h.filter(e=>e.status===`success`).length,y=h.filter(e=>e.status===`failed`).length,b=h.find(e=>e.status===`processing`),x=oy(e.status,v,_),S=i?i.items.find(e=>e.index===t):null,C=S&&S.description?String(S.description).replace(/\s+/g,` `).trim():``,w=g.find(e=>e.subtaskIndex===t&&e.nodeType===`subtask`);o.classList.remove(`subtask-progress-pending`);let T=``;e.status===`success`?(T=`<span class="subtask-status-done">${r(`chatMsg.subtaskDone`)}</span>`,o.classList.add(`subtask-progress-done`),o.classList.remove(`subtask-progress-active`)):x===`partial`?(T=`<span class="subtask-status-partial">${r(`chatMsg.subtaskPartial`)}</span>`,o.classList.add(`subtask-progress-failed`),o.classList.remove(`subtask-progress-active`)):e.status===`failed`?(T=`<span class="subtask-status-failed">${r(`chatMsg.subtaskFailed`)}</span>`,o.classList.add(`subtask-progress-failed`),o.classList.remove(`subtask-progress-active`)):(T=`<span class="subtask-status-label"><span class="subtask-spinner"></span>${r(`chatMsg.subtaskExecuting`)}</span>`,o.classList.add(`subtask-progress-active`));let E=``;if(m&&_>0){let e=b?b.nodeType===`tool_exec`?`🔧`:b.nodeType===`api_call`?`📡`:b.nodeType===`reflection`?`🎯`:b.nodeType===`preselect`?`🔍`:`○`:`○`,t=b?R(b.nodeName||``):r(`chatMsg.preparing`),n=b?Wc(b):``;E=`<div class="subtask-progress-line">
1912
1912
  <span class="subtask-current-node"><span class="subtask-current-spinner"></span><span class="node-label">${e} ${t}</span>${n?` <span class="subtask-current-cmd" title="${V(n)}">${R(n)}</span>`:``}</span>
1913
1913
  <span class="subtask-node-stats">
1914
1914
  <span class="subtask-stat-total">${_}</span>
@@ -2078,7 +2078,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
2078
2078
  <div class="agent-item" id="agentAddBtn" style="color:var(--brand-500);">
2079
2079
  <span class="agent-item-icon" style="color:var(--brand-500);">+</span>
2080
2080
  <span class="agent-item-name">${r(`agentEditor.createNew`)}</span>
2081
- </div>`),Wb(n,i)}function Wb(e,t){let n=document.getElementById(`agentSelectorBtn`),i=document.getElementById(`agentSelectorText`),a=document.getElementById(`agentSelectorEmoji`);if(!n||!i)return;let o=e.find(e=>e.id===t)||e.find(e=>e.id==="default");if(o){let e=o.id==="default"?r(`agentMgr.defaultAgentName`):o.name;i.textContent=`${o.icon} ${e}`,a&&(a.textContent=o.icon),n.title=`${r(`header.switchAgent`)}: ${o.icon} ${e}`}else i.textContent=r(`header.defaultAssistant`),a&&(a.textContent=`🤖`),n.title=r(`header.switchAgent`)}function Gb(){let e=document.getElementById(`agentSelectorBtn`),t=document.getElementById(`agentSelectorDropdown`),n=document.getElementById(`agentSelectorWrapper`);if(!e||!t||!n)return;let r=n.getBoundingClientRect(),i=document.body.clientWidth;t.style.left=``,t.style.right=`auto`,t.style.maxWidth=Math.min(320,i-16)+`px`;let a=t.getBoundingClientRect().width,o=Math.min(a,i-16),s=e.getBoundingClientRect(),c=s.left+s.width/2,l=i-o-8,u=Math.max(8,Math.min(l,c-o/2));t.style.left=u-r.left+`px`}function Kb(){let e=document.getElementById(`agentSelectorBtn`),t=document.getElementById(`agentSelectorDropdown`);!e||!t||(e.addEventListener(`click`,async e=>{if(e.stopPropagation(),t.style.display===`flex`)t.style.display=`none`;else{t.style.left=``,t.style.right=`auto`,t.style.maxWidth=Math.min(320,document.body.clientWidth-16)+`px`,t.style.display=`flex`,Gb();try{await Ub()}catch{}Gb()}}),document.addEventListener(`click`,()=>{t.style.display=`none`}),t.addEventListener(`click`,async e=>{let n=e.target.closest(`.agent-item`);if(!n)return;let r=e.target.closest(`[data-action]`);if(r&&r.dataset.action===`edit`){e.stopPropagation();let t=r.dataset.agentId;sx(t);return}if(r&&r.dataset.action===`delete`){e.stopPropagation(),await Dx(r.dataset.agentId);return}if(n.id===`agentAddBtn`){sx(null);return}let i=n.dataset.agentId;i&&(await qb(i),t.style.display=`none`)}))}async function qb(e){let t=e?await He(e):null;if(F.activeAgentId=e,F.activeAgentToolIds=t?t.toolIds:null,F.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null,await Je(e),qt().catch(()=>{}),t&&!t.isBuiltin)t.model&&(F.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(F.temperature=t.temperature,F.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`));else if(!t||t.isBuiltin)try{let e=await chrome.storage.local.get([`modelName`,`temperature`,`topP`]);e.modelName&&(F.currentModel=e.modelName),e.temperature!==void 0&&(F.temperature=e.temperature),e.topP!==void 0&&(F.topP=e.topP),document.dispatchEvent(new CustomEvent(`agent-model-changed`))}catch{}await Ub();let n=`agentMcpClosedServers_${e||`default`}`,i=await chrome.storage.local.get([n,`ragTools`,`ragToolsIntroduced`]),o=i.ragTools||[];F.mcpClosedServers=i[n]||[];let s=`agentEnabledTools_${e||`default`}`,c=await chrome.storage.local.get([s,`enabledTools`]),l=!!c[s],u=c[s]||c.enabledTools;if(l||u&&u.length>0){let e=Bn(o),t=u.filter(t=>e.has(t));if(l)F.enabledTools=t;else{let e=b.filter(e=>e.enabled&&!t.includes(e.id)).map(e=>e.id);F.enabledTools=[...t,...e]}let n=zn(F.enabledTools,o,i.ragToolsIntroduced);F.enabledTools=n.tools,F.enabledTools.length!==u.length&&chrome.storage.local.set({[s]:F.enabledTools,...n.migrated?{ragToolsIntroduced:!0}:{}})}else{F.enabledTools=b.filter(e=>e.enabled).map(e=>e.id);let e=zn(F.enabledTools,o,i.ragToolsIntroduced);F.enabledTools=e.tools,e.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[s]:F.enabledTools})}let d=document.getElementById(`toolsPopupOverlay`);d&&d.classList.contains(`show`)&&(Tn(),Nn(),Pn()),Ln();let f=t&&t.id!=="default"?t.name:r(`agentMgr.defaultAgentName`);L(r(`agentMgr.switchedTo`,{name:f}),`info`,2e3),a.debug(`[AgentMgr] switched Agent:`,e,f)}function Jb(){let e=document.getElementById(`agentEditModal`);if(!e)return;e.querySelector(`#agentModalCloseBtn`)?.addEventListener(`click`,cx),e.querySelector(`#agentSaveBtn`)?.addEventListener(`click`,Tx),e.querySelector(`#agentDeleteBtn`)?.addEventListener(`click`,Ex),e.querySelector(`#agentTemplateSelect`)?.addEventListener(`change`,ux),$b();let t=document.getElementById(`agentToolActions`);t&&t.addEventListener(`click`,e=>{let t=e.target.closest(`button`);if(!t)return;let n=t.dataset.action;n===`selectAll`?ex():n===`deselectAll`?tx():n===`toggleSelectedOnly`&&(dx.selectedOnly=!dx.selectedOnly,px())});let n=document.getElementById(`agentToolSearchInput`);if(n){let e=null,t=document.getElementById(`agentToolSearchClear`),r=()=>{t&&(t.style.display=n.value?`block`:`none`)};n.addEventListener(`input`,()=>{r(),clearTimeout(e),e=setTimeout(()=>{dx.searchText=n.value,px()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),n.value=``,r(),dx.searchText=``,px(),n.focus()}),r()}let r=document.getElementById(`agentSkillActions`);r&&r.addEventListener(`click`,e=>{let t=e.target.closest(`button`);if(!t)return;let n=t.dataset.action;n===`selectAllSkills`?nx():n===`deselectAllSkills`?rx():n===`toggleSelectedOnlySkills`&&(_x.selectedOnly=!_x.selectedOnly,yx())});let i=document.getElementById(`agentSkillSearchInput`);if(i){let e=null,t=document.getElementById(`agentSkillSearchClear`),n=()=>{t&&(t.style.display=i.value?`block`:`none`)};i.addEventListener(`input`,()=>{n(),clearTimeout(e),e=setTimeout(()=>{_x.searchText=i.value,yx()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),i.value=``,n(),_x.searchText=``,yx(),i.focus()}),n()}let a=document.getElementById(`agentToolList`);a&&(a.addEventListener(`click`,e=>{let t=e.target.closest(`.agent-mcp-expand-btn`);if(t){e.preventDefault(),mx(t.dataset.serverId,t);return}let n=e.target.closest(`.agent-mcp-service-item`);if(n&&!e.target.closest(`input[type="checkbox"]`)){e.preventDefault(),mx(n.dataset.mcpServerId,n.querySelector(`.agent-mcp-expand-btn`));return}let r=e.target.closest(`.agent-tool-category-clickable`);r&&ix(r.dataset.category)}),a.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=dx,n=e.target.dataset.toolId,r=e.target.dataset.mcpServerId;t.inheritMode=!1,n?e.target.checked?t.selectedSet.add(n):t.selectedSet.delete(n):r&&(e.target.checked?t.excludedSet.delete(r):t.excludedSet.add(r)),t.selectedOnly?px():ax()}));let o=document.getElementById(`agentSkillList`);o&&o.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=_x;t.inheritMode=!1,e.target.checked?t.selectedSet.add(e.target.value):t.selectedSet.delete(e.target.value),t.selectedOnly&&!e.target.checked?yx():ox()}),document.addEventListener(`click`,e=>{let t=document.getElementById(`emojiPicker`),n=document.getElementById(`agentEditIconBtn`);t&&n&&t.style.display===`block`&&!n.contains(e.target)&&!t.contains(e.target)&&(t.style.display=`none`)})}var Yb=[[`smileys`,`emojiCatSmileys`],[`people`,`emojiCatPeople`],[`animals`,`emojiCatAnimals`],[`food`,`emojiCatFood`],[`travel`,`emojiCatTravel`],[`activity`,`emojiCatActivity`],[`objects`,`emojiCatObjects`],[`symbols`,`emojiCatSymbols`],[`flags`,`emojiCatFlags`]];function Xb(e,t){return!!(e[1].includes(t)||e[3]&&e[3].includes(t))}function Zb(e){let t=``;for(let[e,n]of Yb){let i=Bb.filter(t=>t[2]===e);if(i.length){t+=`<div class="emoji-category-label">${r(`agentMgr.`+n)}</div>`,t+=`<div class="emoji-picker-grid">`;for(let e of i)t+=`<button type="button" class="emoji-picker-item" data-emoji="${$(e[0])}" title="${$(e[1])}">${e[0]}</button>`;t+=`</div>`}}e.innerHTML=t}function Qb(e,t){let n=Bb.filter(e=>Xb(e,t));if(!n.length){e.innerHTML=`<div class="emoji-picker-empty">${r(`agentMgr.emojiNoMatch`)}</div>`;return}let i=`<div class="emoji-picker-grid">`;for(let e of n)i+=`<button type="button" class="emoji-picker-item" data-emoji="${$(e[0])}" title="${$(e[1])}">${e[0]}</button>`;i+=`</div>`,e.innerHTML=i}function $b(){let e=document.getElementById(`emojiPicker`),t=document.getElementById(`agentEditIconBtn`),n=document.getElementById(`agentEditIcon`),r=document.getElementById(`emojiSearchInput`),i=document.getElementById(`emojiSearchClear`),a=document.getElementById(`emojiPickerBody`);if(!e||!t)return;let o=()=>{let e=r?r.value.trim().toLowerCase():``;e?Qb(a,e):Zb(a),i&&(i.style.display=e?`flex`:`none`)};t.addEventListener(`click`,n=>{if(n.stopPropagation(),e.style.display===`block`){e.style.display=`none`;return}r&&(r.value=``),o();let i=t.getBoundingClientRect();document.body.clientWidth-i.left>=330?(e.style.left=`0`,e.style.right=`auto`):(e.style.left=`auto`,e.style.right=`0`),e.style.display=`block`}),r&&r.addEventListener(`input`,o),i&&i.addEventListener(`click`,e=>{e.stopPropagation(),r&&(r.value=``),o(),r&&r.focus()}),e.addEventListener(`click`,r=>{let i=r.target.closest(`.emoji-picker-item`);if(!i)return;let a=i.dataset.emoji;t.textContent=a,n&&(n.value=a),e.style.display=`none`})}function ex(){let e=dx;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.add(t.id)),e.mcpServices.forEach(t=>e.excludedSet.delete(t.serverId)),px()}function tx(){let e=dx;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.delete(t.id)),e.mcpServices.forEach(t=>e.excludedSet.add(t.serverId)),px()}function nx(){let e=_x;e.inheritMode=!1,e.skills.forEach(t=>e.selectedSet.add(t.name)),yx()}function rx(){let e=_x;e.inheritMode=!1,e.selectedSet.clear(),yx()}function ix(e){let t=dx;if(e===`mcp`){if(t.mcpServices.length===0)return;let e=t.mcpServices.every(e=>!t.excludedSet.has(e.serverId));t.mcpServices.forEach(n=>{e?t.excludedSet.add(n.serverId):t.excludedSet.delete(n.serverId)}),document.querySelectorAll(`#agentToolList .agent-mcp-service-item input[type="checkbox"]`).forEach(t=>{t.checked=!e})}else{let n=t.allTools.filter(t=>(t.category||`other`)===e);if(n.length===0)return;t.inheritMode=!1;let r=n.every(e=>t.selectedSet.has(e.id));n.forEach(e=>{r?t.selectedSet.delete(e.id):t.selectedSet.add(e.id)}),document.querySelectorAll(`#agentToolList .agent-tool-item[data-category="${e}"] input[type="checkbox"]`).forEach(e=>{e.checked=!r})}t.selectedOnly?px():ax()}function ax(){let e=dx,t=document.getElementById(`agentToolList`);if(!t)return;let n=e.mcpServices.filter(t=>!e.excludedSet.has(t.serverId)).length;t.querySelectorAll(`.agent-tool-category-clickable`).forEach(t=>{let r=t.dataset.category,i=t.querySelector(`.agent-tool-cat-count`);if(i)if(r===`mcp`)i.textContent=`${n}/${e.mcpServices.length}`;else{let t=e.allTools.filter(e=>(e.category||`other`)===r);i.textContent=`${t.filter(t=>e.selectedSet.has(t.id)).length}/${t.length}`}});let i=document.getElementById(`agentToolCount`);if(i){let t=e.allTools.filter(t=>e.selectedSet.has(t.id)).length,a=e.allTools.length+e.mcpServices.length;i.textContent=r(`agentConfig.selectedTotalCount`,{selected:e.inheritMode?a:t+n,total:a})}}function ox(){let e=document.getElementById(`agentSkillCount`);if(!e)return;let t=_x,n=t.skills.length;e.textContent=r(`agentConfig.selectedTotalCount`,{selected:t.inheritMode?n:t.selectedSet.size,total:n})}async function sx(e){let t=document.getElementById(`agentEditModal`);if(!t)return;await xx(),Sx(-1),t.querySelector(`#agentEditId`).value=``,t.querySelector(`#agentEditName`).value=``,t.querySelector(`#agentEditIcon`).value=`🤖`;let n=t.querySelector(`#agentEditIconBtn`);n&&(n.textContent=`🤖`),t.querySelector(`#agentEditDesc`).value=``,t.querySelector(`#agentEditPrompt`).value=``,t.querySelector(`#agentEditAllowSub`).checked=!1,t.querySelector(`#agentTemplateSelect`).value=``,t.querySelector(`#agentEditModel`).value=``;let i=t.querySelector(`#agentDeleteBtn`),a=t.querySelector(`#agentEditTitle`);if(e){let n=await He(e);if(!n||n.isBuiltin)return;a.textContent=r(`agentMgr.editAgent`),t.querySelector(`#agentEditId`).value=n.id,t.querySelector(`#agentEditName`).value=n.name,t.querySelector(`#agentEditIcon`).value=n.icon||`🤖`;let o=t.querySelector(`#agentEditIconBtn`);o&&(o.textContent=n.icon||`🤖`),t.querySelector(`#agentEditDesc`).value=n.description||``,t.querySelector(`#agentEditPrompt`).value=n.systemPrompt||``,t.querySelector(`#agentEditAllowSub`).checked=n.allowSubDispatch||!1,t.querySelector(`#agentEditModel`).value=n.model||``,Sx(wx(n.temperature,n.topP)),i.style.display=`block`,fx(n.toolIds,n.mcpExcludedServerIds??[]),vx(n.skillIds)}else a.textContent=r(`agentEditor.createNew`),i.style.display=`none`,fx(null,[]),vx(null);lx(),t.style.display=`flex`;let o=t.querySelector(`#agentEditModel`);if(o){let e=o.value,t=o.cloneNode(!0);o.parentNode.replaceChild(t,o),t.value=e,t.addEventListener(`mousedown`,()=>{let e=t.value;e&&(t.dataset._saved=e,t.value=``)}),t.addEventListener(`blur`,()=>{setTimeout(()=>{t.value||=t.dataset._saved||``},150)})}}function cx(){let e=document.getElementById(`agentEditModal`);e&&(e.style.display=`none`)}function lx(){let e=document.getElementById(`agentTemplateSelect`);if(!e)return;let t=[r(`agentTemplates.codeReviewName`),r(`agentTemplates.webAutomationName`),r(`agentTemplates.dataAnalystName`),r(`agentTemplates.documentationName`)],n=`<option value="">${r(`agentEditor.selectTemplate`)}</option>`;for(let e=0;e<ne.length;e++){let r=ne[e];n+=`<option value="${e}">${r.icon} ${t[e]}</option>`}e.innerHTML=n}function ux(e){let t=parseInt(e.target.value);if(isNaN(t)||t<0||t>=ne.length)return;let n=ne[t],i=document.getElementById(`agentEditModal`);if(!i)return;let a=[`agentTemplates.codeReviewName`,`agentTemplates.webAutomationName`,`agentTemplates.dataAnalystName`,`agentTemplates.documentationName`],o=[`agentTemplates.codeReviewDesc`,`agentTemplates.webAutomationDesc`,`agentTemplates.dataAnalystDesc`,`agentTemplates.documentationDesc`];i.querySelector(`#agentEditName`).value=r(a[t]),i.querySelector(`#agentEditIcon`).value=n.icon;let c=i.querySelector(`#agentEditIconBtn`);c&&(c.textContent=n.icon),i.querySelector(`#agentEditDesc`).value=r(o[t]),i.querySelector(`#agentEditPrompt`).value=s()===`en`?n.systemPrompt:n.systemPromptZh||n.systemPrompt,i.querySelector(`#agentEditAllowSub`).checked=n.allowSubDispatch||!1,i.querySelector(`#agentEditModel`).value=n.model||``,Sx(wx(n.temperature,n.topP)),fx(n.toolIds,[]),vx(n.skillIds||null),L(r(`agentMgr.templateLoaded`,{name:n.name}),`info`,2e3)}var dx={allTools:[],mcpServices:[],selectedSet:new Set,excludedSet:new Set,searchText:``,selectedOnly:!1,inheritMode:!1};async function fx(e,t){if(!document.getElementById(`agentToolList`))return;let n=[];try{n=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[]}catch{}let{mcpEnabled:r,skillsEnabled:i,ragTools:a}=await chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`ragTools`]),o=F.agentPlatform?.connected===!0,s=[...b,...a||[]];o||(s=s.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),i===!1&&(s=s.filter(e=>e.id!==`agent_skill`));let c=[];if(r===!0&&o){let e=new Map;for(let t of n){let n=t.serverId||`unknown`;e.has(n)||e.set(n,{serverId:n,serverName:t.serverName||n,tools:[]}),e.get(n).tools.push(t)}c=Array.from(e.values())}let l=new Set(Array.isArray(t)?t:[]),u=dx;u.allTools=s,u.mcpServices=c,u.selectedSet=new Set(e||[]),u.excludedSet=l,u.searchText=``,u.selectedOnly=!1,u.inheritMode=!e;let d=document.getElementById(`agentToolSearchInput`);d&&(d.value=``);let f=document.getElementById(`agentToolSearchClear`);f&&(f.style.display=`none`),px()}function px(){let e=document.getElementById(`agentToolList`);if(!e)return;let t=dx,n=Wn({tools:t.allTools,services:t.mcpServices,selectedSet:t.selectedSet,excludedSet:t.excludedSet,query:t.searchText,selectedOnly:t.selectedOnly,getDesc:on}),i=t.mcpServices.filter(e=>!t.excludedSet.has(e.serverId)).length,a={};for(let e of n.tools){let t=e.category||`other`;a[t]||(a[t]=[]),a[t].push(e)}let o=``;for(let[e,n]of Object.entries(a)){let i=r(`toolCategory.${e}`)===`toolCategory.${e}`?e:r(`toolCategory.${e}`),a=t.allTools.filter(t=>(t.category||`other`)===e),s=a.filter(e=>t.selectedSet.has(e.id)).length;o+=`<div class="agent-tool-category agent-tool-category-clickable" data-category="${$(e)}" title="${$(r(`agentConfig.toggleCategoryAll`))}">${i} <span class="agent-tool-cat-count" style="font-weight:400;color:var(--text-tertiary);">${s}/${a.length}</span></div>`;for(let r of n){let n=t.selectedSet.has(r.id)?`checked`:``,i=on(r),a=i.length>40?i.substring(0,40)+`...`:i;o+=`
2081
+ </div>`),Wb(n,i)}function Wb(e,t){let n=document.getElementById(`agentSelectorBtn`),i=document.getElementById(`agentSelectorText`),a=document.getElementById(`agentSelectorEmoji`);if(!n||!i)return;let o=e.find(e=>e.id===t)||e.find(e=>e.id==="default");if(o){let e=o.id==="default"?r(`agentMgr.defaultAgentName`):o.name;i.textContent=`${o.icon} ${e}`,a&&(a.textContent=o.icon),n.title=`${r(`header.switchAgent`)}: ${o.icon} ${e}`}else i.textContent=r(`header.defaultAssistant`),a&&(a.textContent=`🤖`),n.title=r(`header.switchAgent`)}function Gb(){let e=document.getElementById(`agentSelectorBtn`),t=document.getElementById(`agentSelectorDropdown`),n=document.getElementById(`agentSelectorWrapper`);if(!e||!t||!n)return;let r=n.getBoundingClientRect(),i=document.body.clientWidth;t.style.left=``,t.style.right=`auto`,t.style.maxWidth=Math.min(320,i-16)+`px`;let a=t.getBoundingClientRect().width,o=Math.min(a,i-16),s=e.getBoundingClientRect(),c=s.left+s.width/2,l=i-o-8,u=Math.max(8,Math.min(l,c-o/2));t.style.left=u-r.left+`px`}function Kb(){let e=document.getElementById(`agentSelectorBtn`),t=document.getElementById(`agentSelectorDropdown`);!e||!t||(e.addEventListener(`click`,async e=>{if(e.stopPropagation(),t.style.display===`flex`)t.style.display=`none`;else{t.style.left=``,t.style.right=`auto`,t.style.maxWidth=Math.min(320,document.body.clientWidth-16)+`px`,t.style.display=`flex`,Gb();try{await Ub()}catch{}Gb()}}),document.addEventListener(`click`,()=>{t.style.display=`none`}),t.addEventListener(`click`,async e=>{let n=e.target.closest(`.agent-item`);if(!n)return;let r=e.target.closest(`[data-action]`);if(r&&r.dataset.action===`edit`){e.stopPropagation();let t=r.dataset.agentId;sx(t);return}if(r&&r.dataset.action===`delete`){e.stopPropagation(),await Dx(r.dataset.agentId);return}if(n.id===`agentAddBtn`){sx(null);return}let i=n.dataset.agentId;i&&(await qb(i),t.style.display=`none`)}))}async function qb(e){let t=e?await He(e):null;if(F.activeAgentId=e,F.activeAgentToolIds=t?t.toolIds:null,F.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null,await Je(e),qt().catch(()=>{}),t&&!t.isBuiltin)t.model&&(F.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(F.temperature=t.temperature,F.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`));else if(!t||t.isBuiltin)try{let e=await chrome.storage.local.get([`modelName`,`temperature`,`topP`]);e.modelName&&(F.currentModel=e.modelName),e.temperature!==void 0&&(F.temperature=e.temperature),e.topP!==void 0&&(F.topP=e.topP),document.dispatchEvent(new CustomEvent(`agent-model-changed`))}catch{}await Ub();let n=`agentMcpClosedServers_${e||`default`}`,i=await chrome.storage.local.get([n,`ragTools`,`ragToolsIntroduced`]),o=i.ragTools||[];F.mcpClosedServers=i[n]||[];let s=`agentEnabledTools_${e||`default`}`,c=await chrome.storage.local.get([s,`enabledTools`]),l=!!c[s],u=c[s]||c.enabledTools;if(l||u&&u.length>0){let e=Bn(o),t=u.filter(t=>e.has(t));if(l)F.enabledTools=t;else{let e=b.filter(e=>e.enabled&&!t.includes(e.id)).map(e=>e.id);F.enabledTools=[...t,...e]}let n=zn(F.enabledTools,o,i.ragToolsIntroduced);F.enabledTools=n.tools,F.enabledTools.length!==u.length&&chrome.storage.local.set({[s]:F.enabledTools,...n.migrated?{ragToolsIntroduced:!0}:{}})}else{F.enabledTools=b.filter(e=>e.enabled).map(e=>e.id);let e=zn(F.enabledTools,o,i.ragToolsIntroduced);F.enabledTools=e.tools,e.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[s]:F.enabledTools})}let d=document.getElementById(`toolsPopupOverlay`);d&&d.classList.contains(`show`)&&(Tn(),Nn(),Pn()),Ln();let f=t&&t.id!=="default"?t.name:r(`agentMgr.defaultAgentName`);L(r(`agentMgr.switchedTo`,{name:f}),`info`,2e3),a.debug(`[AgentMgr] switched Agent:`,e,f)}function Jb(){let e=document.getElementById(`agentEditModal`);if(!e)return;e.querySelector(`#agentModalCloseBtn`)?.addEventListener(`click`,cx),e.querySelector(`#agentSaveBtn`)?.addEventListener(`click`,Tx),e.querySelector(`#agentDeleteBtn`)?.addEventListener(`click`,Ex),e.querySelector(`#agentTemplateSelect`)?.addEventListener(`change`,ux),$b();let t=document.getElementById(`agentToolActions`);t&&t.addEventListener(`click`,e=>{let t=e.target.closest(`button`);if(!t)return;let n=t.dataset.action;n===`selectAll`?ex():n===`deselectAll`?tx():n===`toggleSelectedOnly`&&(dx.selectedOnly=!dx.selectedOnly,px())});let n=document.getElementById(`agentToolSearchInput`);if(n){let e=null,t=document.getElementById(`agentToolSearchClear`),r=()=>{t&&(t.style.display=n.value?`block`:`none`)};n.addEventListener(`input`,()=>{r(),clearTimeout(e),e=setTimeout(()=>{dx.searchText=n.value,px()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),n.value=``,r(),dx.searchText=``,px(),n.focus()}),r()}let r=document.getElementById(`agentSkillActions`);r&&r.addEventListener(`click`,e=>{let t=e.target.closest(`button`);if(!t)return;let n=t.dataset.action;n===`selectAllSkills`?nx():n===`deselectAllSkills`?rx():n===`toggleSelectedOnlySkills`&&(_x.selectedOnly=!_x.selectedOnly,yx())});let i=document.getElementById(`agentSkillSearchInput`);if(i){let e=null,t=document.getElementById(`agentSkillSearchClear`),n=()=>{t&&(t.style.display=i.value?`block`:`none`)};i.addEventListener(`input`,()=>{n(),clearTimeout(e),e=setTimeout(()=>{_x.searchText=i.value,yx()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),i.value=``,n(),_x.searchText=``,yx(),i.focus()}),n()}let a=document.getElementById(`agentToolList`);a&&(a.addEventListener(`click`,e=>{let t=e.target.closest(`.agent-mcp-expand-btn`);if(t){e.preventDefault(),mx(t.dataset.serverId,t);return}let n=e.target.closest(`.agent-mcp-service-item`);if(n&&!e.target.closest(`input[type="checkbox"]`)){e.preventDefault(),mx(n.dataset.mcpServerId,n.querySelector(`.agent-mcp-expand-btn`));return}let r=e.target.closest(`.agent-tool-category-clickable`);r&&ix(r.dataset.category)}),a.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=dx,n=e.target.dataset.toolId,r=e.target.dataset.mcpServerId;t.inheritMode=!1,n?e.target.checked?t.selectedSet.add(n):t.selectedSet.delete(n):r&&(e.target.checked?t.excludedSet.delete(r):t.excludedSet.add(r)),t.selectedOnly?px():ax()}));let o=document.getElementById(`agentSkillList`);o&&o.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=_x;t.inheritMode=!1,e.target.checked?t.selectedSet.add(e.target.value):t.selectedSet.delete(e.target.value),t.selectedOnly&&!e.target.checked?yx():ox()}),document.addEventListener(`click`,e=>{let t=document.getElementById(`emojiPicker`),n=document.getElementById(`agentEditIconBtn`);t&&n&&t.style.display===`block`&&!n.contains(e.target)&&!t.contains(e.target)&&(t.style.display=`none`)})}var Yb=[[`smileys`,`emojiCatSmileys`],[`people`,`emojiCatPeople`],[`animals`,`emojiCatAnimals`],[`food`,`emojiCatFood`],[`travel`,`emojiCatTravel`],[`activity`,`emojiCatActivity`],[`objects`,`emojiCatObjects`],[`symbols`,`emojiCatSymbols`],[`flags`,`emojiCatFlags`]];function Xb(e,t){return!!(e[1].includes(t)||e[3]&&e[3].includes(t))}function Zb(e){let t=``;for(let[e,n]of Yb){let i=Bb.filter(t=>t[2]===e);if(i.length){t+=`<div class="emoji-category-label">${r(`agentMgr.`+n)}</div>`,t+=`<div class="emoji-picker-grid">`;for(let e of i)t+=`<button type="button" class="emoji-picker-item" data-emoji="${$(e[0])}" title="${$(e[1])}">${e[0]}</button>`;t+=`</div>`}}e.innerHTML=t}function Qb(e,t){let n=Bb.filter(e=>Xb(e,t));if(!n.length){e.innerHTML=`<div class="emoji-picker-empty">${r(`agentMgr.emojiNoMatch`)}</div>`;return}let i=`<div class="emoji-picker-grid">`;for(let e of n)i+=`<button type="button" class="emoji-picker-item" data-emoji="${$(e[0])}" title="${$(e[1])}">${e[0]}</button>`;i+=`</div>`,e.innerHTML=i}function $b(){let e=document.getElementById(`emojiPicker`),t=document.getElementById(`agentEditIconBtn`),n=document.getElementById(`agentEditIcon`),r=document.getElementById(`emojiSearchInput`),i=document.getElementById(`emojiSearchClear`),a=document.getElementById(`emojiPickerBody`);if(!e||!t)return;let o=()=>{let e=r?r.value.trim().toLowerCase():``;e?Qb(a,e):Zb(a),i&&(i.style.display=e?`flex`:`none`)};t.addEventListener(`click`,n=>{if(n.stopPropagation(),e.style.display===`block`){e.style.display=`none`;return}r&&(r.value=``),o();let i=t.getBoundingClientRect();document.body.clientWidth-i.left>=330?(e.style.left=`0`,e.style.right=`auto`):(e.style.left=`auto`,e.style.right=`0`),e.style.display=`block`}),r&&r.addEventListener(`input`,o),i&&i.addEventListener(`click`,e=>{e.stopPropagation(),r&&(r.value=``),o(),r&&r.focus()}),e.addEventListener(`click`,r=>{let i=r.target.closest(`.emoji-picker-item`);if(!i)return;let a=i.dataset.emoji;t.textContent=a,n&&(n.value=a),e.style.display=`none`})}function ex(){let e=dx;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.add(t.id)),e.mcpServices.forEach(t=>e.excludedSet.delete(t.serverId)),px()}function tx(){let e=dx;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.delete(t.id)),e.mcpServices.forEach(t=>e.excludedSet.add(t.serverId)),px()}function nx(){let e=_x;e.inheritMode=!1,e.skills.forEach(t=>e.selectedSet.add(t.name)),yx()}function rx(){let e=_x;e.inheritMode=!1,e.selectedSet.clear(),yx()}function ix(e){let t=dx;if(e===`mcp`){if(t.mcpServices.length===0)return;t.inheritMode=!1;let e=t.mcpServices.every(e=>!t.excludedSet.has(e.serverId));t.mcpServices.forEach(n=>{e?t.excludedSet.add(n.serverId):t.excludedSet.delete(n.serverId)}),document.querySelectorAll(`#agentToolList .agent-mcp-service-item input[type="checkbox"]`).forEach(t=>{t.checked=!e})}else{let n=t.allTools.filter(t=>(t.category||`other`)===e);if(n.length===0)return;t.inheritMode=!1;let r=n.every(e=>t.selectedSet.has(e.id));n.forEach(e=>{r?t.selectedSet.delete(e.id):t.selectedSet.add(e.id)}),document.querySelectorAll(`#agentToolList .agent-tool-item[data-category="${e}"] input[type="checkbox"]`).forEach(e=>{e.checked=!r})}t.selectedOnly?px():ax()}function ax(){let e=dx,t=document.getElementById(`agentToolList`);if(!t)return;let n=e.mcpServices.filter(t=>!e.excludedSet.has(t.serverId)).length;t.querySelectorAll(`.agent-tool-category-clickable`).forEach(t=>{let r=t.dataset.category,i=t.querySelector(`.agent-tool-cat-count`);if(i)if(r===`mcp`)i.textContent=`${n}/${e.mcpServices.length}`;else{let t=e.allTools.filter(e=>(e.category||`other`)===r);i.textContent=`${t.filter(t=>e.selectedSet.has(t.id)).length}/${t.length}`}});let i=document.getElementById(`agentToolCount`);if(i){let t=e.allTools.filter(t=>e.selectedSet.has(t.id)).length,a=e.allTools.length+e.mcpServices.length;i.textContent=r(`agentConfig.selectedTotalCount`,{selected:e.inheritMode?a:t+n,total:a})}}function ox(){let e=document.getElementById(`agentSkillCount`);if(!e)return;let t=_x,n=t.skills.length;e.textContent=r(`agentConfig.selectedTotalCount`,{selected:t.inheritMode?n:t.selectedSet.size,total:n})}async function sx(e){let t=document.getElementById(`agentEditModal`);if(!t)return;await xx(),Sx(-1),t.querySelector(`#agentEditId`).value=``,t.querySelector(`#agentEditName`).value=``,t.querySelector(`#agentEditIcon`).value=`🤖`;let n=t.querySelector(`#agentEditIconBtn`);n&&(n.textContent=`🤖`),t.querySelector(`#agentEditDesc`).value=``,t.querySelector(`#agentEditPrompt`).value=``,t.querySelector(`#agentEditAllowSub`).checked=!1,t.querySelector(`#agentTemplateSelect`).value=``,t.querySelector(`#agentEditModel`).value=``;let i=t.querySelector(`#agentDeleteBtn`),a=t.querySelector(`#agentEditTitle`);if(e){let n=await He(e);if(!n||n.isBuiltin)return;a.textContent=r(`agentMgr.editAgent`),t.querySelector(`#agentEditId`).value=n.id,t.querySelector(`#agentEditName`).value=n.name,t.querySelector(`#agentEditIcon`).value=n.icon||`🤖`;let o=t.querySelector(`#agentEditIconBtn`);o&&(o.textContent=n.icon||`🤖`),t.querySelector(`#agentEditDesc`).value=n.description||``,t.querySelector(`#agentEditPrompt`).value=n.systemPrompt||``,t.querySelector(`#agentEditAllowSub`).checked=n.allowSubDispatch||!1,t.querySelector(`#agentEditModel`).value=n.model||``,Sx(wx(n.temperature,n.topP)),i.style.display=`block`,fx(n.toolIds,n.mcpExcludedServerIds??[]),vx(n.skillIds)}else a.textContent=r(`agentEditor.createNew`),i.style.display=`none`,fx(null,[]),vx(null);lx(),t.style.display=`flex`;let o=t.querySelector(`#agentEditModel`);if(o){let e=o.value,t=o.cloneNode(!0);o.parentNode.replaceChild(t,o),t.value=e,t.addEventListener(`mousedown`,()=>{let e=t.value;e&&(t.dataset._saved=e,t.value=``)}),t.addEventListener(`blur`,()=>{setTimeout(()=>{t.value||=t.dataset._saved||``},150)})}}function cx(){let e=document.getElementById(`agentEditModal`);e&&(e.style.display=`none`)}function lx(){let e=document.getElementById(`agentTemplateSelect`);if(!e)return;let t=[r(`agentTemplates.codeReviewName`),r(`agentTemplates.webAutomationName`),r(`agentTemplates.dataAnalystName`),r(`agentTemplates.documentationName`)],n=`<option value="">${r(`agentEditor.selectTemplate`)}</option>`;for(let e=0;e<ne.length;e++){let r=ne[e];n+=`<option value="${e}">${r.icon} ${t[e]}</option>`}e.innerHTML=n}function ux(e){let t=parseInt(e.target.value);if(isNaN(t)||t<0||t>=ne.length)return;let n=ne[t],i=document.getElementById(`agentEditModal`);if(!i)return;let a=[`agentTemplates.codeReviewName`,`agentTemplates.webAutomationName`,`agentTemplates.dataAnalystName`,`agentTemplates.documentationName`],o=[`agentTemplates.codeReviewDesc`,`agentTemplates.webAutomationDesc`,`agentTemplates.dataAnalystDesc`,`agentTemplates.documentationDesc`];i.querySelector(`#agentEditName`).value=r(a[t]),i.querySelector(`#agentEditIcon`).value=n.icon;let c=i.querySelector(`#agentEditIconBtn`);c&&(c.textContent=n.icon),i.querySelector(`#agentEditDesc`).value=r(o[t]),i.querySelector(`#agentEditPrompt`).value=s()===`en`?n.systemPrompt:n.systemPromptZh||n.systemPrompt,i.querySelector(`#agentEditAllowSub`).checked=n.allowSubDispatch||!1,i.querySelector(`#agentEditModel`).value=n.model||``,Sx(wx(n.temperature,n.topP)),fx(n.toolIds,[]),vx(n.skillIds||null),L(r(`agentMgr.templateLoaded`,{name:n.name}),`info`,2e3)}var dx={allTools:[],mcpServices:[],selectedSet:new Set,excludedSet:new Set,searchText:``,selectedOnly:!1,inheritMode:!1};async function fx(e,t){if(!document.getElementById(`agentToolList`))return;let n=[];try{n=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[]}catch{}let{mcpEnabled:r,skillsEnabled:i,ragTools:a}=await chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`ragTools`]),o=F.agentPlatform?.connected===!0,s=[...b,...a||[]];o||(s=s.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),i===!1&&(s=s.filter(e=>e.id!==`agent_skill`));let c=[];if(r===!0&&o){let e=new Map;for(let t of n){let n=t.serverId||`unknown`;e.has(n)||e.set(n,{serverId:n,serverName:t.serverName||n,tools:[]}),e.get(n).tools.push(t)}c=Array.from(e.values())}let l=new Set(Array.isArray(t)?t:[]),u=dx;u.allTools=s,u.mcpServices=c,u.selectedSet=new Set(e||[]),u.excludedSet=l,u.searchText=``,u.selectedOnly=!1,u.inheritMode=!e;let d=document.getElementById(`agentToolSearchInput`);d&&(d.value=``);let f=document.getElementById(`agentToolSearchClear`);f&&(f.style.display=`none`),px()}function px(){let e=document.getElementById(`agentToolList`);if(!e)return;let t=dx,n=Wn({tools:t.allTools,services:t.mcpServices,selectedSet:t.selectedSet,excludedSet:t.excludedSet,query:t.searchText,selectedOnly:t.selectedOnly,getDesc:on}),i=t.mcpServices.filter(e=>!t.excludedSet.has(e.serverId)).length,a={};for(let e of n.tools){let t=e.category||`other`;a[t]||(a[t]=[]),a[t].push(e)}let o=``;for(let[e,n]of Object.entries(a)){let i=r(`toolCategory.${e}`)===`toolCategory.${e}`?e:r(`toolCategory.${e}`),a=t.allTools.filter(t=>(t.category||`other`)===e),s=a.filter(e=>t.selectedSet.has(e.id)).length;o+=`<div class="agent-tool-category agent-tool-category-clickable" data-category="${$(e)}" title="${$(r(`agentConfig.toggleCategoryAll`))}">${i} <span class="agent-tool-cat-count" style="font-weight:400;color:var(--text-tertiary);">${s}/${a.length}</span></div>`;for(let r of n){let n=t.selectedSet.has(r.id)?`checked`:``,i=on(r),a=i.length>40?i.substring(0,40)+`...`:i;o+=`
2082
2082
  <label class="agent-tool-item" data-category="${$(e)}">
2083
2083
  <input type="checkbox" value="${$(r.id)}" ${n} data-tool-id="${$(r.id)}">
2084
2084
  <span class="agent-tool-name" title="${$(r.name)}">${Ax(r.name)}</span>
@@ -2091,7 +2091,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
2091
2091
  <span class="agent-mcp-service-id" title="ID: ${$(e.serverId)}">ID: ${Ax(e.serverId)}</span>
2092
2092
  <button type="button" class="agent-mcp-expand-btn" data-server-id="${$(e.serverId)}" title="${$(r(`toolPanel.mcpServiceExpand`))}">▶</button>
2093
2093
  </label>
2094
- <div class="agent-mcp-tool-list collapsed" data-server-id="${$(e.serverId)}">${s}</div>`}}o||=`<div class="agent-tool-empty">${Ax(r(`toolPanel.noMatch`))}</div>`,e.innerHTML=o;let s=document.getElementById(`agentToolSelectedOnlyBtn`);if(s){s.classList.toggle(`active`,t.selectedOnly),s.textContent=r(t.selectedOnly?`agentEditor.showAllTools`:`agentEditor.selectedOnlyFilter`);let e=t.allTools.filter(e=>t.selectedSet.has(e.id)).length;s.title=r(`agentToolFilter.selectedCountHint`,{count:e+i})}ax()}function mx(e,t){let n=document.getElementById(`agentToolList`);if(!n||!e)return;let r=Array.from(n.querySelectorAll(`.agent-mcp-tool-list`)).find(t=>t.dataset.serverId===e);if(!r)return;let i=r.classList.toggle(`collapsed`),a=t||r.previousElementSibling?.querySelector(`.agent-mcp-expand-btn`);a&&(a.textContent=i?`▶`:`▼`)}function hx(){let e=dx,t=e.allTools.filter(t=>e.selectedSet.has(t.id)).map(e=>e.id),n=new Set(t),r=[...e.selectedSet].filter(e=>!n.has(e)),i=[...t,...r];return i.length>0?i:null}function gx(){let e=dx;if(e.mcpServices.length!==0)return e.mcpServices.filter(t=>e.excludedSet.has(t.serverId)).map(e=>e.serverId)}var _x={skills:[],selectedSet:new Set,searchText:``,selectedOnly:!1,inheritMode:!1};async function vx(e){if(!document.getElementById(`agentSkillList`))return;let t=[];try{t=await hb()}catch{}let n=_x;n.skills=t,n.selectedSet=new Set(e||[]),n.searchText=``,n.selectedOnly=!1,n.inheritMode=e===null;let r=document.getElementById(`agentSkillSearchInput`);r&&(r.value=``);let i=document.getElementById(`agentSkillSearchClear`);i&&(i.style.display=`none`),yx()}function yx(){let e=document.getElementById(`agentSkillList`);if(!e)return;let t=_x;if(t.skills.length===0)e.innerHTML=`<div style="color:var(--text-tertiary);font-size:12px;padding:8px;text-align:center;">${r(`agentMgr.noSkillsHint`)}</div>`;else{let n=Wn({tools:t.skills.map(e=>({id:e.name,name:e.name,description:e.description||``})),services:[],selectedSet:t.selectedSet,excludedSet:new Set,query:t.searchText,selectedOnly:t.selectedOnly}).tools;n.length===0?e.innerHTML=`<div class="agent-tool-empty">${Ax(r(`toolPanel.noMatch`))}</div>`:e.innerHTML=n.map(e=>{let n=t.selectedSet.has(e.name)?`checked`:``,r=e.description||``;return`
2094
+ <div class="agent-mcp-tool-list collapsed" data-server-id="${$(e.serverId)}">${s}</div>`}}o||=`<div class="agent-tool-empty">${Ax(r(`toolPanel.noMatch`))}</div>`,e.innerHTML=o;let s=document.getElementById(`agentToolSelectedOnlyBtn`);if(s){s.classList.toggle(`active`,t.selectedOnly),s.textContent=r(t.selectedOnly?`agentEditor.showAllTools`:`agentEditor.selectedOnlyFilter`);let e=t.allTools.filter(e=>t.selectedSet.has(e.id)).length;s.title=r(`agentToolFilter.selectedCountHint`,{count:e+i})}ax()}function mx(e,t){let n=document.getElementById(`agentToolList`);if(!n||!e)return;let r=Array.from(n.querySelectorAll(`.agent-mcp-tool-list`)).find(t=>t.dataset.serverId===e);if(!r)return;let i=r.classList.toggle(`collapsed`),a=t||r.previousElementSibling?.querySelector(`.agent-mcp-expand-btn`);a&&(a.textContent=i?`▶`:`▼`)}function hx(){let e=dx,t=e.allTools.filter(t=>e.selectedSet.has(t.id)).map(e=>e.id),n=new Set(t),r=[...e.selectedSet].filter(e=>!n.has(e)),i=[...t,...r];return i.length>0?i:null}function gx(){let e=dx;if(e.mcpServices.length!==0)return e.mcpServices.filter(t=>e.excludedSet.has(t.serverId)).map(e=>e.serverId)}var _x={skills:[],selectedSet:new Set,searchText:``,selectedOnly:!1,inheritMode:!1};async function vx(e){if(!document.getElementById(`agentSkillList`))return;let t=[];try{t=await hb()}catch{}let n=_x;n.skills=t,n.selectedSet=new Set(e||[]),n.searchText=``,n.selectedOnly=!1,n.inheritMode=e==null;let r=document.getElementById(`agentSkillSearchInput`);r&&(r.value=``);let i=document.getElementById(`agentSkillSearchClear`);i&&(i.style.display=`none`),yx()}function yx(){let e=document.getElementById(`agentSkillList`);if(!e)return;let t=_x;if(t.skills.length===0)e.innerHTML=`<div style="color:var(--text-tertiary);font-size:12px;padding:8px;text-align:center;">${r(`agentMgr.noSkillsHint`)}</div>`;else{let n=Wn({tools:t.skills.map(e=>({id:e.name,name:e.name,description:e.description||``})),services:[],selectedSet:t.selectedSet,excludedSet:new Set,query:t.searchText,selectedOnly:t.selectedOnly}).tools;n.length===0?e.innerHTML=`<div class="agent-tool-empty">${Ax(r(`toolPanel.noMatch`))}</div>`:e.innerHTML=n.map(e=>{let n=t.selectedSet.has(e.name)?`checked`:``,r=e.description||``;return`
2095
2095
  <label class="agent-tool-item">
2096
2096
  <input type="checkbox" value="${$(e.name)}" ${n}>
2097
2097
  <span class="agent-tool-name" title="${$(e.name)}">${Ax(e.name)}</span>
@@ -2110,7 +2110,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
2110
2110
  <div class="modal-title"></div>
2111
2111
  <div class="modal-message"></div>
2112
2112
  </div>
2113
- `,e.querySelector(`.modal-title`).textContent=r(`contextUsage.compactingTitle`),e.querySelector(`.modal-message`).textContent=r(`contextUsage.compactingHint`),document.body.appendChild(e),{close:()=>e.remove()}}function Gx(e){let t=String(e||``);return t===`empty_summary`?r(`contextUsage.compactErrEmpty`):t.startsWith(`http_`)?r(`contextUsage.compactErrHttp`,{status:t.slice(5)}):t.includes(`超时`)||/timeout/i.test(t)?r(`contextUsage.compactErrTimeout`):t}async function Kx({silent:e=!1}={}){if(!F.isolateChat)return e||L(r(`contextUsage.memoryOffToast`),`warning`),{success:!1,reason:`memory_off`};if(F.isGenerating)return e||L(r(`contextUsage.generatingToast`),`warning`),{success:!1,reason:`generating`};let t=F.messageHistory;if(!t.length)return e||L(r(`contextUsage.nothingToCompactToast`),`warning`),{success:!1,reason:`nothing_to_compact`};let n=F.activeCompaction,{material:i,includedCount:o,hasOldSummary:s}=Tt(t,{maxMemoryMessages:F.chatConfig?.maxMemoryMessages??null,compaction:n});if(o===0)return e||L(r(`contextUsage.nothingToCompactToast`),`warning`),{success:!1,reason:`nothing_to_compact`};let c=y(i.map(e=>({role:e.role,content:e.content})));if(!e&&!await Ux({title:r(`contextUsage.confirmTitle`),message:r(`contextUsage.confirmMessage`,{count:o,tokens:B(c),summaryHint:s?r(`contextUsage.confirmWithOldSummary`):``}),okText:r(`contextUsage.confirmOk`)}))return{success:!1,reason:`cancelled`};let l=e?null:Wx();try{let a=await chrome.runtime.sendMessage({type:`COMPACT_CONTEXT_SUMMARY`,material:i,model:F.currentModel,sessionId:F.activeSessionId,persistSummaryToMemory:F.chatConfig?.persistSummaryToMemory!==!1,compressedCount:(n?.compressedCount||0)+o,revision:(n?.revision||0)+1,memoryId:n?.memoryId||null});if(!a?.success||!a.summary){if(!e)if(a?.error===`config_missing`)L(r(`contextUsage.compactErrConfig`),`error`);else{let e=Gx(a?.error);L(`${r(`contextUsage.compactErrFailed`)}${e?`(${e})`:``}`,`error`)}return{success:!1,reason:a?.error||`failed`}}let s=t[t.length-1],l=d(a.summary);return F.activeCompaction={summary:a.summary,upToMessageId:s?.messageId,compressedCount:(n?.compressedCount||0)+o,summaryTokens:l,savedTokens:Math.max(c-l,0),model:F.currentModel,createdAt:Date.now(),revision:(n?.revision||0)+1,memoryId:a.memoryId||n?.memoryId||null},await qt(),Qx(),zx(),ec(),e?L(r(`contextUsage.autoCompactedToast`,{saved:B(F.activeCompaction.savedTokens)}),`info`):L(r(`contextUsage.compactDone`,{saved:B(F.activeCompaction.savedTokens)}),`success`),{success:!0,savedTokens:F.activeCompaction.savedTokens}}catch(t){if(a.warn(`[ContextIndicator] compaction failed:`,t?.message),!e){let e=Gx(t?.message);L(`${r(`contextUsage.compactErrFailed`)}${e?`(${e})`:``}`,`error`)}return{success:!1,reason:`exception`}}finally{l?.close()}}async function qx(){await Kx({silent:!1})}function Jx(){let e=F.activeCompaction;if(!e?.upToMessageId)return!1;let t=F.messageHistory||[],n=t.findIndex(t=>t.messageId===e.upToMessageId);return n>=0&&n<t.length-1}async function Yx(e=!1){if(F.activeCompaction){if(Jx()){L(r(`contextUsage.undoExpiredToast`),`warning`);return}!e&&!await Ux({title:r(`contextUsage.undoTitle`),message:r(`contextUsage.undoMessage`),okText:r(`contextUsage.undoOk`)})||(F.activeCompaction=null,await qt(),Xx(),zx(),L(r(`contextUsage.undoDone`),`success`))}}function Xx(){document.querySelectorAll(`.compaction-divider`).forEach(e=>e.remove())}function Zx(){let e=Jx();document.querySelectorAll(`.compaction-divider [data-action="undo"]`).forEach(t=>{t.style.display=e?`none`:``})}function Qx(){Xx();let e=F.activeCompaction;if(!e?.upToMessageId)return;let t=document.getElementById(`chatContainer`);if(!t)return;let n=t.querySelector(`[data-message-id="${CSS.escape(e.upToMessageId)}"]`);if(!n)return;let i=document.createElement(`div`);i.className=`compaction-divider`;let a=!Jx();i.innerHTML=`
2113
+ `,e.querySelector(`.modal-title`).textContent=r(`contextUsage.compactingTitle`),e.querySelector(`.modal-message`).textContent=r(`contextUsage.compactingHint`),document.body.appendChild(e),{close:()=>e.remove()}}function Gx(e){let t=String(e||``);if(t===`empty_summary`)return r(`contextUsage.compactErrEmpty`);if(t.includes(`CHAT_STREAM_IDLE_TIMEOUT`))return r(`contextUsage.compactErrTimeout`);if(t.startsWith(`http_`)){let e=t.slice(5),n=e.indexOf(`:`),i=r(`contextUsage.compactErrHttp`,{status:n<0?e:e.slice(0,n)}),a=n<0?``:e.slice(n+1).trim();if(!a)return i;let o=a;try{let e=JSON.parse(a);o=e?.error?.message||e?.message||a}catch{}return`${i}: ${String(o).slice(0,200)}`}return t.includes(`超时`)||/timeout/i.test(t)?r(`contextUsage.compactErrTimeout`):t}async function Kx({silent:e=!1}={}){if(!F.isolateChat)return e||L(r(`contextUsage.memoryOffToast`),`warning`),{success:!1,reason:`memory_off`};if(F.isGenerating)return e||L(r(`contextUsage.generatingToast`),`warning`),{success:!1,reason:`generating`};let t=F.messageHistory;if(!t.length)return e||L(r(`contextUsage.nothingToCompactToast`),`warning`),{success:!1,reason:`nothing_to_compact`};let n=F.activeCompaction,{material:i,includedCount:o,hasOldSummary:s}=Tt(t,{maxMemoryMessages:F.chatConfig?.maxMemoryMessages??null,compaction:n});if(o===0)return e||L(r(`contextUsage.nothingToCompactToast`),`warning`),{success:!1,reason:`nothing_to_compact`};let c=y(i.map(e=>({role:e.role,content:e.content})));if(!e&&!await Ux({title:r(`contextUsage.confirmTitle`),message:r(`contextUsage.confirmMessage`,{count:o,tokens:B(c),summaryHint:s?r(`contextUsage.confirmWithOldSummary`):``}),okText:r(`contextUsage.confirmOk`)}))return{success:!1,reason:`cancelled`};let l=e?null:Wx();try{let a=await chrome.runtime.sendMessage({type:`COMPACT_CONTEXT_SUMMARY`,material:i,model:F.currentModel,sessionId:F.activeSessionId,persistSummaryToMemory:F.chatConfig?.persistSummaryToMemory!==!1,compressedCount:(n?.compressedCount||0)+o,revision:(n?.revision||0)+1,memoryId:n?.memoryId||null});if(!a?.success||!a.summary){if(!e)if(a?.error===`config_missing`)L(r(`contextUsage.compactErrConfig`),`error`);else{let e=Gx(a?.error);L(`${r(`contextUsage.compactErrFailed`)}${e?`(${e})`:``}`,`error`)}return{success:!1,reason:a?.error||`failed`}}let s=t[t.length-1],l=d(a.summary);return F.activeCompaction={summary:a.summary,upToMessageId:s?.messageId,compressedCount:(n?.compressedCount||0)+o,summaryTokens:l,savedTokens:Math.max(c-l,0),model:F.currentModel,createdAt:Date.now(),revision:(n?.revision||0)+1,memoryId:a.memoryId||n?.memoryId||null},await qt(),Qx(),zx(),ec(),e?L(r(`contextUsage.autoCompactedToast`,{saved:B(F.activeCompaction.savedTokens)}),`info`):L(r(`contextUsage.compactDone`,{saved:B(F.activeCompaction.savedTokens)}),`success`),{success:!0,savedTokens:F.activeCompaction.savedTokens}}catch(t){if(a.warn(`[ContextIndicator] compaction failed:`,t?.message),!e){let e=Gx(t?.message);L(`${r(`contextUsage.compactErrFailed`)}${e?`(${e})`:``}`,`error`)}return{success:!1,reason:`exception`}}finally{l?.close()}}async function qx(){await Kx({silent:!1})}function Jx(){let e=F.activeCompaction;if(!e?.upToMessageId)return!1;let t=F.messageHistory||[],n=t.findIndex(t=>t.messageId===e.upToMessageId);return n>=0&&n<t.length-1}async function Yx(e=!1){if(F.activeCompaction){if(Jx()){L(r(`contextUsage.undoExpiredToast`),`warning`);return}!e&&!await Ux({title:r(`contextUsage.undoTitle`),message:r(`contextUsage.undoMessage`),okText:r(`contextUsage.undoOk`)})||(F.activeCompaction=null,await qt(),Xx(),zx(),L(r(`contextUsage.undoDone`),`success`))}}function Xx(){document.querySelectorAll(`.compaction-divider`).forEach(e=>e.remove())}function Zx(){let e=Jx();document.querySelectorAll(`.compaction-divider [data-action="undo"]`).forEach(t=>{t.style.display=e?`none`:``})}function Qx(){Xx();let e=F.activeCompaction;if(!e?.upToMessageId)return;let t=document.getElementById(`chatContainer`);if(!t)return;let n=t.querySelector(`[data-message-id="${CSS.escape(e.upToMessageId)}"]`);if(!n)return;let i=document.createElement(`div`);i.className=`compaction-divider`;let a=!Jx();i.innerHTML=`
2114
2114
  <span class="compaction-divider-text">${r(`contextUsage.dividerText`,{count:e.compressedCount})}</span>
2115
2115
  <button class="compaction-divider-btn" data-action="view">${r(`contextUsage.dividerView`)}</button>
2116
2116
  ${a?`<button class="compaction-divider-btn" data-action="undo">${r(`contextUsage.dividerUndo`)}</button>`:``}
@@ -2196,7 +2196,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
2196
2196
  <div class="search-panel-empty">${r(`searchPanel.startSearchHint`)}</div>
2197
2197
  </div>
2198
2198
  </div>
2199
- `,Nt(`search`).appendChild(e),lS(),a.debug(`[SearchPanel] search panelinitializing`)}function lS(){document.getElementById(`searchPanelContainer`);let e=document.getElementById(`searchPanel`),t=document.getElementById(`searchPanelToggle`),n=document.getElementById(`searchPanelInput`),r=document.getElementById(`searchPanelClear`),i=document.getElementById(`searchPanelClose`),a=document.getElementById(`searchModeGlobal`),o=document.getElementById(`searchModeCurrent`);t.addEventListener(`click`,()=>{e.classList.contains(`expanded`)?dS():uS()}),i.addEventListener(`click`,()=>{dS()}),r.addEventListener(`click`,()=>{n.value=``,r.style.display=`none`,fS(),n.focus()}),n.addEventListener(`input`,()=>{let e=n.value.trim();r.style.display=e?``:`none`,e||fS()}),n.addEventListener(`keydown`,e=>{if(e.key===`Enter`){e.stopPropagation();let t=n.value.trim();t&&(s(t),pS(t))}else if(e.key===`Escape`)F.searchInputHistoryIndex>=0?(F.searchInputHistoryIndex=-1,n.value=``):(e.stopPropagation(),dS());else if(e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation();let t=F.searchInputHistory;if(t.length===0)return;F.searchInputHistoryIndex===-1?F.searchInputHistoryIndex=t.length-1:F.searchInputHistoryIndex>0&&F.searchInputHistoryIndex--,n.value=t[F.searchInputHistoryIndex]||``,r.style.display=n.value?``:`none`,n.selectionStart=n.selectionEnd=n.value.length}else if(e.key===`ArrowDown`){e.preventDefault(),e.stopPropagation();let t=F.searchInputHistory;F.searchInputHistoryIndex>=0&&F.searchInputHistoryIndex<t.length-1?(F.searchInputHistoryIndex++,n.value=t[F.searchInputHistoryIndex]||``,n.selectionStart=n.selectionEnd=n.value.length):(F.searchInputHistoryIndex=-1,n.value=``),r.style.display=n.value?``:`none`}});function s(e){if(!e||!e.trim())return;let t=e.trim(),n=F.searchInputHistory,r=n.indexOf(t);r!==-1&&n.splice(r,1),n.push(t),n.length>20&&n.shift(),F.searchInputHistoryIndex=-1;try{chrome.storage.local.set({searchInputHistory:n})}catch{}}a.addEventListener(`click`,()=>{a.classList.contains(`active`)||(a.classList.add(`active`),o.classList.remove(`active`));let e=n.value.trim();e&&pS(e)}),o.addEventListener(`click`,()=>{o.classList.contains(`active`)||(o.classList.add(`active`),a.classList.remove(`active`));let e=n.value.trim();e&&pS(e)}),document.getElementById(`searchPanelContent`).addEventListener(`click`,async e=>{let t=e.target.closest(`.search-result-item`);if(!t)return;let n=t.dataset.sessionId,r=t.dataset.messageId;await xS(n,r)})}function uS(){let e=document.getElementById(`searchPanel`),t=document.getElementById(`searchPanelInput`);e.classList.add(`expanded`),rt(e),t.value.trim()&&oS.length===0&&pS(t.value.trim()),setTimeout(()=>t.focus(),100)}function dS(){let e=document.getElementById(`searchPanel`);e.classList.remove(`expanded`),$e(e),aS=!0,iS=!1}function fS(){aS=!0,iS=!1,oS=[],sS=``;let e=document.getElementById(`searchPanelContent`),t=document.getElementById(`searchPanelCount`);e&&(e.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.startSearchHint`)}</div>`),t&&(t.textContent=``)}async function pS(e){if(!e||!e.trim()||(e=e.trim().toLowerCase(),iS&&sS===e))return;aS=!0,await new Promise(e=>setTimeout(e,50)),iS=!0,aS=!1,oS=[],sS=e;let t=document.getElementById(`searchPanelContent`),n=document.getElementById(`searchPanelCount`);t.innerHTML=`<div class="search-panel-loading">${r(`searchPanel.searching`)}</div>`,n.textContent=``;let i=document.getElementById(`searchModeGlobal`).classList.contains(`active`);try{i?await hS(e,t,n):await mS(e,t,n)}catch(e){a.error(`[SearchPanel] search error:`,e),aS||(t.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.searchError`)}</div>`)}aS||(iS=!1)}async function mS(e,t,n){let i=F.activeSessionId;if(!i){t.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noActiveSession`)}</div>`;return}let a=gS(F.messageHistory||[],e,i);if(!aS){if(oS=a,n.textContent=a.length>0?r(`searchPanel.countResult`,{count:a.length}):r(`searchPanel.noResult`),a.length===0){t.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noMatch`)}</div>`;return}vS(a,e,t)}}async function hS(e,t,n){let i=F.activeSessionId,o=await fe();if(aS)return;if(!o||o.length===0){t.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noSessionData`)}</div>`;return}let s=[],c=[];if(i){let a=gS(F.messageHistory||[],e,i);if(aS)return;let c=o.find(e=>e.id===i)?.title||r(`searchPanel.currentSession`);for(let e of a)s.push({...e,sessionTitle:c});oS=[...s],n.textContent=r(`searchPanel.searchingWithCount`,{count:s.length}),vS(oS,e,t,!0)}let l=o.filter(e=>e.id!==i);for(let i of l){if(aS)return;try{let a=await je(i.id);if(!a||!a.messageHistory)continue;let o=gS(a.messageHistory||[],e,i.id);if(o.length>0){for(let e of o)c.push({...e,sessionTitle:i.title||r(`searchPanel.unknownSession`)});oS=[...s,...c];let a=s.length+c.length;n.textContent=a>0?r(`searchPanel.countResult`,{count:a}):r(`searchPanel.noResult`),vS(oS,e,t)}}catch(e){a.warn(`[SearchPanel] searchsession failed:`,i.id,e)}await new Promise(e=>setTimeout(e,10))}if(aS)return;let u=oS.length;if(n.textContent=u>0?r(`searchPanel.countResult`,{count:u}):r(`searchPanel.noResult`),u===0){t.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noMatch`)}</div>`;return}vS(oS,e,t)}function gS(e,t,n){let r=[];if(!e||e.length===0)return r;let i=t.includes(`&`)||t.includes(`|`);for(let a of e){if(a.role!==`assistant`&&a.role!==`user`)continue;let e=a.messageId||a.id;if(!e)continue;let o=_S(a.content);if(!o)continue;let s=o.toLowerCase(),c=-1,l=t;if(i){let e=t.split(`|`).map(e=>e.trim()).filter(Boolean),n=!1;for(let t of e){let e=t.split(`&`).map(e=>e.trim()).filter(Boolean);if(e.length!==0&&e.every(e=>s.includes(e))){n=!0,l=e[0],c=s.indexOf(l);break}}if(!n)continue}else{if(!s.includes(t))continue;c=s.indexOf(t)}let u=l.length,d=Math.max(0,c-30),f=Math.min(o.length,c+u+30),p=o.substring(d,f);d>0&&(p=`...`+p),f<o.length&&(p+=`...`),r.push({messageId:e,content:o.substring(0,200),role:a.role,sessionId:n,matchPreview:p,query:t})}return r}function _S(e){return e?typeof e==`string`?e.replace(/<[^>]*>/g,``):Array.isArray(e)?e.filter(e=>e.type===`text`).map(e=>e.text||``).join(` `):String(e):``}function vS(e,t,n,i){if(n||=document.getElementById(`searchPanelContent`),!n)return;if(e.length===0){n.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noMatch`)}</div>`;return}let a=F.activeSessionId,o=e.filter(e=>e.sessionId===a),s=e.filter(e=>e.sessionId!==a),c=``,l=i?r(`searchPanel.searchingSuffix`):``;o.length>0&&(c+=`<div class="search-section">
2199
+ `,Nt(`search`).appendChild(e),lS(),a.debug(`[SearchPanel] search panelinitializing`)}function lS(){document.getElementById(`searchPanelContainer`);let e=document.getElementById(`searchPanel`),t=document.getElementById(`searchPanelToggle`),n=document.getElementById(`searchPanelInput`),r=document.getElementById(`searchPanelClear`),i=document.getElementById(`searchPanelClose`),a=document.getElementById(`searchModeGlobal`),o=document.getElementById(`searchModeCurrent`);t.addEventListener(`click`,()=>{e.classList.contains(`expanded`)?dS():uS()}),i.addEventListener(`click`,()=>{dS()}),r.addEventListener(`click`,()=>{n.value=``,r.style.display=`none`,fS(),n.focus()}),n.addEventListener(`input`,()=>{let e=n.value.trim();r.style.display=e?``:`none`,e||fS()}),n.addEventListener(`keydown`,e=>{if(e.key===`Enter`){e.stopPropagation();let t=n.value.trim();t&&(s(t),pS(t))}else if(e.key===`Escape`)F.searchInputHistoryIndex>=0?(F.searchInputHistoryIndex=-1,n.value=``):(e.stopPropagation(),dS());else if(e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation();let t=F.searchInputHistory;if(t.length===0)return;F.searchInputHistoryIndex===-1?F.searchInputHistoryIndex=t.length-1:F.searchInputHistoryIndex>0&&F.searchInputHistoryIndex--,n.value=t[F.searchInputHistoryIndex]||``,r.style.display=n.value?``:`none`,n.selectionStart=n.selectionEnd=n.value.length}else if(e.key===`ArrowDown`){e.preventDefault(),e.stopPropagation();let t=F.searchInputHistory;F.searchInputHistoryIndex>=0&&F.searchInputHistoryIndex<t.length-1?(F.searchInputHistoryIndex++,n.value=t[F.searchInputHistoryIndex]||``,n.selectionStart=n.selectionEnd=n.value.length):(F.searchInputHistoryIndex=-1,n.value=``),r.style.display=n.value?``:`none`}});function s(e){if(!e||!e.trim())return;let t=e.trim(),n=F.searchInputHistory,r=n.indexOf(t);r!==-1&&n.splice(r,1),n.push(t),n.length>20&&n.shift(),F.searchInputHistoryIndex=-1;try{chrome.storage.local.set({searchInputHistory:n})}catch{}}a.addEventListener(`click`,()=>{a.classList.contains(`active`)||(a.classList.add(`active`),o.classList.remove(`active`));let e=n.value.trim();e&&pS(e)}),o.addEventListener(`click`,()=>{o.classList.contains(`active`)||(o.classList.add(`active`),a.classList.remove(`active`));let e=n.value.trim();e&&pS(e)}),document.getElementById(`searchPanelContent`).addEventListener(`click`,async e=>{let t=e.target.closest(`.search-result-item`);if(!t)return;let n=t.dataset.sessionId,r=t.dataset.messageId;await xS(n,r)})}function uS(){let e=document.getElementById(`searchPanel`),t=document.getElementById(`searchPanelInput`);e.classList.add(`expanded`),rt(e),t.value.trim()&&oS.length===0&&pS(t.value.trim()),setTimeout(()=>t.focus(),100)}function dS(){let e=document.getElementById(`searchPanel`);e.classList.remove(`expanded`),$e(e),aS=!0,iS=!1}function fS(){aS=!0,iS=!1,oS=[],sS=``;let e=document.getElementById(`searchPanelContent`),t=document.getElementById(`searchPanelCount`);e&&(e.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.startSearchHint`)}</div>`),t&&(t.textContent=``)}async function pS(e){if(!e||!e.trim()||(e=e.trim().toLowerCase(),iS&&sS===e))return;aS=!0,await new Promise(e=>setTimeout(e,50)),iS=!0,aS=!1,oS=[],sS=e;let t=document.getElementById(`searchPanelContent`),n=document.getElementById(`searchPanelCount`);t.innerHTML=`<div class="search-panel-loading">${r(`searchPanel.searching`)}</div>`,n.textContent=``;let i=document.getElementById(`searchModeGlobal`).classList.contains(`active`);try{i?await hS(e,t,n):await mS(e,t,n)}catch(e){a.error(`[SearchPanel] search error:`,e),aS||(t.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.searchError`)}</div>`)}aS||(iS=!1)}async function mS(e,t,n){let i=F.activeSessionId;if(!i){t.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noActiveSession`)}</div>`;return}let a=gS(F.messageHistory||[],e,i);if(!aS){if(oS=a,n.textContent=a.length>0?r(`searchPanel.countResult`,{count:a.length}):r(`searchPanel.noResult`),a.length===0){t.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noMatch`)}</div>`;return}vS(a,e,t)}}async function hS(e,t,n){let i=F.activeSessionId,o=await ce();if(aS)return;if(!o||o.length===0){t.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noSessionData`)}</div>`;return}let s=[],c=[];if(i){let a=gS(F.messageHistory||[],e,i);if(aS)return;let c=o.find(e=>e.id===i)?.title||r(`searchPanel.currentSession`);for(let e of a)s.push({...e,sessionTitle:c});oS=[...s],n.textContent=r(`searchPanel.searchingWithCount`,{count:s.length}),vS(oS,e,t,!0)}let l=o.filter(e=>e.id!==i);for(let i of l){if(aS)return;try{let a=await Ee(i.id);if(!a||!a.messageHistory)continue;let o=gS(a.messageHistory||[],e,i.id);if(o.length>0){for(let e of o)c.push({...e,sessionTitle:i.title||r(`searchPanel.unknownSession`)});oS=[...s,...c];let a=s.length+c.length;n.textContent=a>0?r(`searchPanel.countResult`,{count:a}):r(`searchPanel.noResult`),vS(oS,e,t)}}catch(e){a.warn(`[SearchPanel] searchsession failed:`,i.id,e)}await new Promise(e=>setTimeout(e,10))}if(aS)return;let u=oS.length;if(n.textContent=u>0?r(`searchPanel.countResult`,{count:u}):r(`searchPanel.noResult`),u===0){t.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noMatch`)}</div>`;return}vS(oS,e,t)}function gS(e,t,n){let r=[];if(!e||e.length===0)return r;let i=t.includes(`&`)||t.includes(`|`);for(let a of e){if(a.role!==`assistant`&&a.role!==`user`)continue;let e=a.messageId||a.id;if(!e)continue;let o=_S(a.content);if(!o)continue;let s=o.toLowerCase(),c=-1,l=t;if(i){let e=t.split(`|`).map(e=>e.trim()).filter(Boolean),n=!1;for(let t of e){let e=t.split(`&`).map(e=>e.trim()).filter(Boolean);if(e.length!==0&&e.every(e=>s.includes(e))){n=!0,l=e[0],c=s.indexOf(l);break}}if(!n)continue}else{if(!s.includes(t))continue;c=s.indexOf(t)}let u=l.length,d=Math.max(0,c-30),f=Math.min(o.length,c+u+30),p=o.substring(d,f);d>0&&(p=`...`+p),f<o.length&&(p+=`...`),r.push({messageId:e,content:o.substring(0,200),role:a.role,sessionId:n,matchPreview:p,query:t})}return r}function _S(e){return e?typeof e==`string`?e.replace(/<[^>]*>/g,``):Array.isArray(e)?e.filter(e=>e.type===`text`).map(e=>e.text||``).join(` `):String(e):``}function vS(e,t,n,i){if(n||=document.getElementById(`searchPanelContent`),!n)return;if(e.length===0){n.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noMatch`)}</div>`;return}let a=F.activeSessionId,o=e.filter(e=>e.sessionId===a),s=e.filter(e=>e.sessionId!==a),c=``,l=i?r(`searchPanel.searchingSuffix`):``;o.length>0&&(c+=`<div class="search-section">
2200
2200
  <div class="search-section-title">${r(`searchPanel.currentSessionResults`,{label:l,count:o.length})}</div>
2201
2201
  ${yS(o,t)}
2202
2202
  </div>`),s.length>0&&(c+=`<div class="search-section">
@@ -2210,7 +2210,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
2210
2210
  </div>
2211
2211
  <div class="search-result-preview">${c}</div>
2212
2212
  </div>
2213
- `}).join(``)}function bS(e,t){if(!t)return e;let n=t.split(/[&|]/).map(e=>e.trim()).filter(Boolean);if(n.length===0)return e;let r=n.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)),i=RegExp(`(${r.join(`|`)})`,`gi`);return e.replace(i,`<mark class="search-highlight-match">$1</mark>`)}async function xS(e,t){if(!(!e||!t)){if(F.activeSessionId!==e)try{let t=F.activeSessionId;if(await Yt(e)===!1||F.activeSessionId!==e){L(r(`searchPanel.sessionNotExist`),`warning`);return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:t,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await I(async()=>{let{renderSessionTabs:e}=await Promise.resolve().then(()=>xo);return{renderSessionTabs:e}},void 0);e()}catch(e){a.warn(`[SearchPanel] refreshsessionTab failed:`,e)}}catch(e){a.error(`[SearchPanel] switchsession failed:`,e);return}setTimeout(async()=>{let n=document.getElementById(`chatContainer`);if(!n){a.warn(`[SearchPanel] chatContainer not found`);return}let i=n.querySelector(`.message[data-message-id="${t}"]`);if(i||=n.querySelector(`[data-message-id="${t}"]`),!i){let r=Array.from(n.querySelectorAll(`[data-message-id]`),e=>e.dataset.messageId);a.warn(`[SearchPanel] positionmessage failed`,{targetSessionId:e,activeSessionId:F.activeSessionId,targetMessageId:t,typeOfMessageId:typeof t,messageIdLength:t.length,domMessageIds:r,chatContainerHtmlLen:n.innerHTML.length})}if(i)i.scrollIntoView({behavior:`instant`,block:`nearest`}),i.classList.add(`bookmark-highlight`),setTimeout(()=>{i.classList.remove(`bookmark-highlight`)},2e3);else{L(r(`searchPanel.messageDeleted`),`warning`);try{if(await j(e,t)){oS=oS.filter(n=>!(n.sessionId===e&&n.messageId===t));let n=document.getElementById(`searchPanelContent`),i=document.getElementById(`searchPanelCount`);n&&oS.length>0?(vS(oS,sS,n),i.textContent=r(`searchPanel.countResult`,{count:oS.length})):n&&oS.length===0&&(n.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noMatch`)}</div>`,i&&(i.textContent=r(`searchPanel.noResult`))),a.debug(`[SearchPanel] cleaned IndexedDB dirtydata:`,e,t)}}catch(e){a.warn(`[SearchPanel] cleanupdirtydata failed:`,e)}}},500)}}n(`zh`,{schedPanel:{toggleTitle:`定时任务`,toggleRunning:`执行中`,title:`定时任务`,newTask:`新建任务`,close:`关闭`,empty:`暂无定时任务`,nameLabel:`任务名称`,descLabel:`任务描述(可选)`,promptLabel:`任务指令`,scheduleLabel:`定时规则`,scheduleTypeOnce:`一次性`,scheduleTypeInterval:`间隔`,scheduleTypeCron:`Cron 表达式`,intervalValuePlaceholder:`例如:30m / 2h / 1d`,cronValuePlaceholder:`例如:0 9 * * *`,relativeValuePlaceholder:`例如:30`,onceModeLabel:`执行方式`,onceModeRelative:`多少分钟后`,onceModeAbsolute:`指定时间点`,valueLabelInterval:`间隔时间`,valueLabelCron:`Cron 表达式`,minutesSuffix:` 分钟后`,contextUrlLabel:`上下文网页地址(可选)`,useCurrentPage:`使用当前页面`,sessionLabel:`宿主会话`,sessionAuto:`自动(会话被删时自动新建)`,save:`保存`,cancel:`取消`,edit:`编辑`,editTitle:`编辑任务`,delete:`删除`,runNow:`立即执行`,enable:`启用`,disable:`停用`,statusSuccess:`成功`,statusFailed:`失败`,statusRunning:`运行中`,statusDisabled:`已停用`,nextRun:`下次执行`,deleted:`任务已删除`,saved:`任务已保存`,runNowToast:`已触发执行`,deleteConfirmTitle:`删除定时任务`,deleteConfirmMsg:`确定删除任务「{name}」吗?`,createFailed:`创建任务失败`,nameRequired:`请填写任务名称`,promptRequired:`请填写任务指令`,scheduleRequired:`请填写定时规则`,loading:`加载中...`,contextModeLabel:`网页上下文方式`,contextModeFetch:`抓取网页正文`,contextModeUrlOnly:`仅使用 URL(不抓正文)`,maxRunsLabel:`最多执行次数(可选)`,endAtLabel:`截止时间(可选)`,runHistoryLabel:`运行历史`,runHistoryEmpty:`暂无运行记录`,runCountLabel:`运行历史 ({count})`}}),n(`en`,{schedPanel:{toggleTitle:`Scheduled tasks`,toggleRunning:`Running`,title:`Scheduled tasks`,newTask:`New task`,close:`Close`,empty:`No scheduled tasks`,nameLabel:`Name`,descLabel:`Description (optional)`,promptLabel:`Prompt`,scheduleLabel:`Schedule`,scheduleTypeOnce:`Once`,scheduleTypeInterval:`Interval`,scheduleTypeCron:`Cron expression`,intervalValuePlaceholder:`e.g. 30m / 2h / 1d`,cronValuePlaceholder:`e.g. 0 9 * * *`,relativeValuePlaceholder:`e.g. 30`,onceModeLabel:`Run mode`,onceModeRelative:`After some minutes`,onceModeAbsolute:`At specific time`,valueLabelInterval:`Interval`,valueLabelCron:`Cron expression`,minutesSuffix:` minutes later`,contextUrlLabel:`Context page URL (optional)`,useCurrentPage:`Use current page`,sessionLabel:`Host session`,sessionAuto:`Auto (recreate if deleted)`,save:`Save`,cancel:`Cancel`,edit:`Edit`,editTitle:`Edit task`,delete:`Delete`,runNow:`Run now`,enable:`Enable`,disable:`Disable`,statusSuccess:`Success`,statusFailed:`Failed`,statusRunning:`Running`,statusDisabled:`Disabled`,nextRun:`Next run`,deleted:`Task deleted`,saved:`Task saved`,runNowToast:`Execution triggered`,deleteConfirmTitle:`Delete scheduled task`,deleteConfirmMsg:`Delete task "{name}"?`,createFailed:`Failed to create task`,nameRequired:`Name is required`,promptRequired:`Prompt is required`,scheduleRequired:`Schedule is required`,loading:`Loading...`,contextModeLabel:`Page context mode`,contextModeFetch:`Fetch page content`,contextModeUrlOnly:`URL only`,maxRunsLabel:`Max runs (optional)`,endAtLabel:`End time (optional)`,runHistoryLabel:`Run history`,runHistoryEmpty:`No runs yet`,runCountLabel:`Run history ({count})`}});function SS(e){return chrome.runtime.sendMessage(e)}function CS(e){return e?new Date(e).toLocaleString(void 0,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`}):`—`}function wS(e){return e==null?``:e<1e3?e+`ms`:e<6e4?(e/1e3).toFixed(1).replace(/\.0$/,``)+`s`:(e/6e4).toFixed(1).replace(/\.0$/,``)+`min`}function TS(e){return e===`success`?r(`schedPanel.statusSuccess`):e===`failed`?r(`schedPanel.statusFailed`):e===`running`?r(`schedPanel.statusRunning`):``}function ES(e){if(!e)return``;let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function DS(e){let t=e.schedule||{};return t.type===`once`?t.onceMode===`relative`?r(`schedPanel.scheduleTypeOnce`)+` · `+(t.value||``)+r(`schedPanel.minutesSuffix`):r(`schedPanel.scheduleTypeOnce`)+` · `+CS(new Date(t.value).getTime()):t.type===`interval`?r(`schedPanel.scheduleTypeInterval`)+` · `+(t.value||``):t.type===`cron`?r(`schedPanel.scheduleTypeCron`)+` · `+(t.value||``):``}function OS(e){return e.enabled?e.lastStatus===`running`?`<span class="sched-badge running">${r(`schedPanel.statusRunning`)}</span>`:e.lastStatus===`failed`?`<span class="sched-badge failed">${r(`schedPanel.statusFailed`)}</span>`:e.lastStatus===`success`?`<span class="sched-badge success">${r(`schedPanel.statusSuccess`)}</span>`:``:`<span class="sched-badge muted">${r(`schedPanel.statusDisabled`)}</span>`}function kS(){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=e.scrollHeight)}async function AS(e){if(e){if(F.activeSessionId!==e){let t=F.activeSessionId;try{if(await Yt(e)===!1||F.activeSessionId!==e)return}catch{return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:t,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await I(async()=>{let{renderSessionTabs:e}=await Promise.resolve().then(()=>xo);return{renderSessionTabs:e}},void 0);e()}catch{}}setTimeout(kS,500)}}function jS(){let e=document.createElement(`div`);e.className=`schedule-panel-container`,e.id=`schedulePanelContainer`,e.innerHTML=`
2213
+ `}).join(``)}function bS(e,t){if(!t)return e;let n=t.split(/[&|]/).map(e=>e.trim()).filter(Boolean);if(n.length===0)return e;let r=n.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)),i=RegExp(`(${r.join(`|`)})`,`gi`);return e.replace(i,`<mark class="search-highlight-match">$1</mark>`)}async function xS(e,t){if(!(!e||!t)){if(F.activeSessionId!==e)try{let t=F.activeSessionId;if(await Yt(e)===!1||F.activeSessionId!==e){L(r(`searchPanel.sessionNotExist`),`warning`);return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:t,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await I(async()=>{let{renderSessionTabs:e}=await Promise.resolve().then(()=>xo);return{renderSessionTabs:e}},void 0);e()}catch(e){a.warn(`[SearchPanel] refreshsessionTab failed:`,e)}}catch(e){a.error(`[SearchPanel] switchsession failed:`,e);return}setTimeout(async()=>{let n=document.getElementById(`chatContainer`);if(!n){a.warn(`[SearchPanel] chatContainer not found`);return}let i=n.querySelector(`.message[data-message-id="${t}"]`);if(i||=n.querySelector(`[data-message-id="${t}"]`),!i){let r=Array.from(n.querySelectorAll(`[data-message-id]`),e=>e.dataset.messageId);a.warn(`[SearchPanel] positionmessage failed`,{targetSessionId:e,activeSessionId:F.activeSessionId,targetMessageId:t,typeOfMessageId:typeof t,messageIdLength:t.length,domMessageIds:r,chatContainerHtmlLen:n.innerHTML.length})}if(i)i.scrollIntoView({behavior:`instant`,block:`nearest`}),i.classList.add(`bookmark-highlight`),setTimeout(()=>{i.classList.remove(`bookmark-highlight`)},2e3);else{L(r(`searchPanel.messageDeleted`),`warning`);try{if(await de(e,t)){oS=oS.filter(n=>!(n.sessionId===e&&n.messageId===t));let n=document.getElementById(`searchPanelContent`),i=document.getElementById(`searchPanelCount`);n&&oS.length>0?(vS(oS,sS,n),i.textContent=r(`searchPanel.countResult`,{count:oS.length})):n&&oS.length===0&&(n.innerHTML=`<div class="search-panel-empty">${r(`searchPanel.noMatch`)}</div>`,i&&(i.textContent=r(`searchPanel.noResult`))),a.debug(`[SearchPanel] cleaned IndexedDB dirtydata:`,e,t)}}catch(e){a.warn(`[SearchPanel] cleanupdirtydata failed:`,e)}}},500)}}n(`zh`,{schedPanel:{toggleTitle:`定时任务`,toggleRunning:`执行中`,title:`定时任务`,newTask:`新建任务`,close:`关闭`,empty:`暂无定时任务`,nameLabel:`任务名称`,descLabel:`任务描述(可选)`,promptLabel:`任务指令`,scheduleLabel:`定时规则`,scheduleTypeOnce:`一次性`,scheduleTypeInterval:`间隔`,scheduleTypeCron:`Cron 表达式`,intervalValuePlaceholder:`例如:30m / 2h / 1d`,cronValuePlaceholder:`例如:0 9 * * *`,relativeValuePlaceholder:`例如:30`,onceModeLabel:`执行方式`,onceModeRelative:`多少分钟后`,onceModeAbsolute:`指定时间点`,valueLabelInterval:`间隔时间`,valueLabelCron:`Cron 表达式`,minutesSuffix:` 分钟后`,contextUrlLabel:`上下文网页地址(可选)`,useCurrentPage:`使用当前页面`,sessionLabel:`宿主会话`,sessionAuto:`自动(会话被删时自动新建)`,save:`保存`,cancel:`取消`,edit:`编辑`,editTitle:`编辑任务`,delete:`删除`,runNow:`立即执行`,enable:`启用`,disable:`停用`,statusSuccess:`成功`,statusFailed:`失败`,statusRunning:`运行中`,statusDisabled:`已停用`,nextRun:`下次执行`,deleted:`任务已删除`,saved:`任务已保存`,runNowToast:`已触发执行`,deleteConfirmTitle:`删除定时任务`,deleteConfirmMsg:`确定删除任务「{name}」吗?`,createFailed:`创建任务失败`,nameRequired:`请填写任务名称`,promptRequired:`请填写任务指令`,scheduleRequired:`请填写定时规则`,loading:`加载中...`,contextModeLabel:`网页上下文方式`,contextModeFetch:`抓取网页正文`,contextModeUrlOnly:`仅使用 URL(不抓正文)`,maxRunsLabel:`最多执行次数(可选)`,endAtLabel:`截止时间(可选)`,runHistoryLabel:`运行历史`,runHistoryEmpty:`暂无运行记录`,runCountLabel:`运行历史 ({count})`}}),n(`en`,{schedPanel:{toggleTitle:`Scheduled tasks`,toggleRunning:`Running`,title:`Scheduled tasks`,newTask:`New task`,close:`Close`,empty:`No scheduled tasks`,nameLabel:`Name`,descLabel:`Description (optional)`,promptLabel:`Prompt`,scheduleLabel:`Schedule`,scheduleTypeOnce:`Once`,scheduleTypeInterval:`Interval`,scheduleTypeCron:`Cron expression`,intervalValuePlaceholder:`e.g. 30m / 2h / 1d`,cronValuePlaceholder:`e.g. 0 9 * * *`,relativeValuePlaceholder:`e.g. 30`,onceModeLabel:`Run mode`,onceModeRelative:`After some minutes`,onceModeAbsolute:`At specific time`,valueLabelInterval:`Interval`,valueLabelCron:`Cron expression`,minutesSuffix:` minutes later`,contextUrlLabel:`Context page URL (optional)`,useCurrentPage:`Use current page`,sessionLabel:`Host session`,sessionAuto:`Auto (recreate if deleted)`,save:`Save`,cancel:`Cancel`,edit:`Edit`,editTitle:`Edit task`,delete:`Delete`,runNow:`Run now`,enable:`Enable`,disable:`Disable`,statusSuccess:`Success`,statusFailed:`Failed`,statusRunning:`Running`,statusDisabled:`Disabled`,nextRun:`Next run`,deleted:`Task deleted`,saved:`Task saved`,runNowToast:`Execution triggered`,deleteConfirmTitle:`Delete scheduled task`,deleteConfirmMsg:`Delete task "{name}"?`,createFailed:`Failed to create task`,nameRequired:`Name is required`,promptRequired:`Prompt is required`,scheduleRequired:`Schedule is required`,loading:`Loading...`,contextModeLabel:`Page context mode`,contextModeFetch:`Fetch page content`,contextModeUrlOnly:`URL only`,maxRunsLabel:`Max runs (optional)`,endAtLabel:`End time (optional)`,runHistoryLabel:`Run history`,runHistoryEmpty:`No runs yet`,runCountLabel:`Run history ({count})`}});function SS(e){return chrome.runtime.sendMessage(e)}function CS(e){return e?new Date(e).toLocaleString(void 0,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`}):`—`}function wS(e){return e==null?``:e<1e3?e+`ms`:e<6e4?(e/1e3).toFixed(1).replace(/\.0$/,``)+`s`:(e/6e4).toFixed(1).replace(/\.0$/,``)+`min`}function TS(e){return e===`success`?r(`schedPanel.statusSuccess`):e===`failed`?r(`schedPanel.statusFailed`):e===`running`?r(`schedPanel.statusRunning`):``}function ES(e){if(!e)return``;let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function DS(e){let t=e.schedule||{};return t.type===`once`?t.onceMode===`relative`?r(`schedPanel.scheduleTypeOnce`)+` · `+(t.value||``)+r(`schedPanel.minutesSuffix`):r(`schedPanel.scheduleTypeOnce`)+` · `+CS(new Date(t.value).getTime()):t.type===`interval`?r(`schedPanel.scheduleTypeInterval`)+` · `+(t.value||``):t.type===`cron`?r(`schedPanel.scheduleTypeCron`)+` · `+(t.value||``):``}function OS(e){return e.enabled?e.lastStatus===`running`?`<span class="sched-badge running">${r(`schedPanel.statusRunning`)}</span>`:e.lastStatus===`failed`?`<span class="sched-badge failed">${r(`schedPanel.statusFailed`)}</span>`:e.lastStatus===`success`?`<span class="sched-badge success">${r(`schedPanel.statusSuccess`)}</span>`:``:`<span class="sched-badge muted">${r(`schedPanel.statusDisabled`)}</span>`}function kS(){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=e.scrollHeight)}async function AS(e){if(e){if(F.activeSessionId!==e){let t=F.activeSessionId;try{if(await Yt(e)===!1||F.activeSessionId!==e)return}catch{return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:t,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await I(async()=>{let{renderSessionTabs:e}=await Promise.resolve().then(()=>xo);return{renderSessionTabs:e}},void 0);e()}catch{}}setTimeout(kS,500)}}function jS(){let e=document.createElement(`div`);e.className=`schedule-panel-container`,e.id=`schedulePanelContainer`,e.innerHTML=`
2214
2214
  <style>
2215
2215
  .schedule-panel-container { position: relative; display: flex; justify-content: flex-end; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; width: 100%; background: transparent; }
2216
2216
  .schedule-panel-toggle { background: rgba(var(--success-rgb), 0.14); color: var(--success-strong); border: none; border-radius: 6px 0 0 6px; padding: 8px 4px; cursor: pointer; font-size: 14px; box-shadow: -1px 1px 4px rgba(var(--overlay-rgb), 0.12); transition: all 0.3s ease; display: flex; align-items: center; justify-content: center; }
@@ -2367,7 +2367,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
2367
2367
  <button data-act="delete" class="danger">${r(`schedPanel.delete`)}</button>
2368
2368
  </div>
2369
2369
  </div>
2370
- `}).join(``)}l.addEventListener(`click`,async e=>{let t=e.target.closest(`button[data-act]`);if(!t)return;let n=t.closest(`.sched-item`),i=n?.dataset.id;if(!i)return;let a=t.dataset.act;if(a===`toggle`){let e=(await E())[i];if(!e)return;await SS({type:`SCHEDULED_TASK_TOGGLE`,id:i,enabled:!e.enabled}),C()}else if(a===`run`){let e=await SS({type:`SCHEDULED_TASK_RUN_NOW`,id:i});e?.success?(L(r(`schedPanel.runNowToast`),`success`),AS(e.sessionId),setTimeout(C,1500)):L(e?.error||r(`schedPanel.createFailed`),`error`)}else if(a===`history`){let e=n.querySelector(`[data-history]`);e&&(e.style.display=e.style.display===`none`?``:`none`)}else if(a===`edit`)D((await E())[i]);else if(a===`delete`){let e=(await E())[i];await window.showCustomConfirm(r(`schedPanel.deleteConfirmMsg`,{name:e?.name||``}),r(`schedPanel.deleteConfirmTitle`))&&(await SS({type:`SCHEDULED_TASK_DELETE`,id:i}),L(r(`schedPanel.deleted`),`success`),C())}});async function E(){let e=await SS({type:`SCHEDULED_TASK_LIST`}),t={};return(e?.tasks||[]).forEach(e=>{t[e.id]=e}),t}async function D(e){b=e||null,d.textContent=r(e?`schedPanel.editTitle`:`schedPanel.newTask`),document.getElementById(`schedFormName`).value=e?.name||``,document.getElementById(`schedFormDesc`).value=e?.description||``,document.getElementById(`schedFormPrompt`).value=e?.prompt||``,document.getElementById(`schedFormUrl`).value=e?.contextUrl||``,m.value=e?.schedule?.type||`interval`,g.value=e?.schedule?.onceMode||`relative`,x(),h.value=e?.schedule?.value||``,document.getElementById(`schedFormContextMode`).value=e?.contextMode||`fetch`,document.getElementById(`schedFormMaxRuns`).value=e?.maxRuns??``,document.getElementById(`schedFormEndAt`).value=e?.endAt?ES(e.endAt):``;let t=document.getElementById(`schedFormSession`),n=`<option value="">${r(`schedPanel.sessionAuto`)}</option>`;try{let{list:t}=await N(),r=[...t].sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?new Date(t.createdAt||0)-new Date(e.createdAt||0):r-n});for(let t of r){let r=e?.sessionId===t.id?`selected`:``,i=R(t.title||t.id);n+=`<option value="${R(t.id)}" ${r}>${i}</option>`}}catch{}t.innerHTML=n,u.classList.add(`open`)}function O(){u.classList.remove(`open`),b=null}async function k(){let e=document.getElementById(`schedFormName`).value.trim(),t=document.getElementById(`schedFormPrompt`).value.trim(),n=m.value,i=h.value.trim();if(!e){L(r(`schedPanel.nameRequired`),`warning`);return}if(!t){L(r(`schedPanel.promptRequired`),`warning`);return}if(!i){L(r(`schedPanel.scheduleRequired`),`warning`);return}let a=n===`interval`&&parseInt(document.getElementById(`schedFormMaxRuns`).value,10)||null,o=n===`interval`?document.getElementById(`schedFormEndAt`).value:``,s=o?new Date(o).getTime():null,c={name:e,description:document.getElementById(`schedFormDesc`).value.trim(),prompt:t,schedule:n===`once`?{type:n,value:i,onceMode:g.value}:{type:n,value:i},contextUrl:document.getElementById(`schedFormUrl`).value.trim()||null,contextMode:document.getElementById(`schedFormContextMode`).value||`fetch`,sessionId:document.getElementById(`schedFormSession`).value||null,maxRuns:a,endAt:s,enabled:b?b.enabled:!0};try{let e=await SS({type:b?`SCHEDULED_TASK_UPDATE`:`SCHEDULED_TASK_CREATE`,task:b?{...c,id:b.id}:c});e?.success?(L(r(`schedPanel.saved`),`success`),O(),C()):L(e?.error||r(`schedPanel.createFailed`),`error`)}catch(e){L(e?.message||r(`schedPanel.createFailed`),`error`)}}chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_TASK_RUN_STATE`&&e.taskId&&(e.running?a.add(e.taskId):a.delete(e.taskId),o())}),chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_SESSION_UPDATED`&&(i.classList.contains(`open`)&&C().catch(()=>{}),e.sessionId&&e.sessionId===F.activeSessionId&&setTimeout(kS,600))}),x(),S(!1),C().catch(()=>{})}var MS=`—`,NS=[{labelKey:`versionInfo.website`,url:`https://xiweicheng.github.io/ai-helper/`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/></svg>`},{labelKey:`versionInfo.discussions`,url:`https://github.com/xiweicheng/ai-helper/discussions`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/></svg>`},{labelKey:`versionInfo.reportIssue`,url:`https://github.com/xiweicheng/ai-helper/issues/new`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z"/></svg>`},{labelKey:`versionInfo.githubRepo`,url:`https://github.com/xiweicheng/ai-helper`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 .5C5.73.5.5 5.73.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.7-3.88-1.54-3.88-1.54-.52-1.33-1.28-1.69-1.28-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.19 1.76 1.19 1.03 1.76 2.7 1.25 3.36.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.28-5.24-5.68 0-1.26.45-2.28 1.19-3.09-.12-.29-.52-1.46.11-3.05 0 0 .97-.31 3.18 1.18a11.1 11.1 0 012.9-.39c.98 0 1.97.13 2.9.39 2.2-1.49 3.17-1.18 3.17-1.18.63 1.59.23 2.76.11 3.05.74.81 1.19 1.83 1.19 3.09 0 4.41-2.69 5.38-5.25 5.67.41.35.78 1.05.78 2.12 0 1.53-.01 2.76-.01 3.14 0 .31.21.68.8.56A11.51 11.51 0 0023.5 12C23.5 5.73 18.27.5 12 .5z"/></svg>`},{labelKey:`versionInfo.giteeRepo`,url:`https://gitee.com/xiweicheng/ai-helper`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M11.984 0A12 12 0 000 12a12 12 0 0012 12 12 12 0 0012-12A12 12 0 0012 0zm6.09 5.333c.328 0 .593.266.592.593v1.482a.594.594 0 01-.593.592H9.777c-.982 0-1.778.796-1.778 1.778v5.63c0 .327.266.592.593.592h5.63c.982 0 1.778-.796 1.778-1.778v-.296a.593.593 0 00-.592-.593h-4.15a.592.592 0 01-.592-.592v-1.482a.593.593 0 01.593-.592h6.815c.327 0 .593.265.593.592v3.408a4 4 0 01-4 4H8.444a3.556 3.556 0 01-3.555-3.556V8.89a3.556 3.556 0 013.555-3.556h9.63z"/></svg>`}];function PS(e){let t=e=>typeof e==`string`?e.trim():``,n=e&&typeof e==`object`?e:{};return{version:t(n.version),tag:t(n.tag),commitId:t(n.commitId),publishedAt:t(n.publishedAt)}}function FS(e){if(!e)return MS;let t=Date.parse(e);return Number.isNaN(t)?MS:new Date(t).toLocaleString()}function IS(e){let t=PS(Ve),n=[{label:r(`versionInfo.version`),value:t.version?`v${t.version}`:MS},{label:r(`versionInfo.tag`),value:t.tag||MS},{label:r(`versionInfo.commit`),value:t.commitId?t.commitId.slice(0,8):MS,title:t.commitId,mono:!0},{label:r(`versionInfo.publishedAt`),value:FS(t.publishedAt)}];e.textContent=``;for(let t of n){let n=document.createElement(`div`);n.className=`version-info-row`;let r=document.createElement(`div`);r.className=`version-info-label`,r.textContent=t.label;let i=document.createElement(`div`);i.className=t.mono?`version-info-value mono`:`version-info-value`,i.textContent=t.value,t.title&&(i.title=t.title),n.appendChild(r),n.appendChild(i),e.appendChild(n)}}function LS(e){e.textContent=``;for(let t of NS){let n=document.createElement(`div`);n.className=`version-info-link`,n.title=t.url;let i=document.createElement(`span`);i.className=`version-info-link-icon`,i.innerHTML=t.icon;let a=document.createElement(`span`);a.className=`version-info-link-label`,a.textContent=r(t.labelKey);let o=document.createElement(`span`);o.className=`version-info-link-arrow`,o.textContent=`↗`,n.appendChild(i),n.appendChild(a),n.appendChild(o),n.addEventListener(`click`,()=>{chrome.tabs.create({url:t.url})}),e.appendChild(n)}}function RS(){let e=PS(Ve);return[`AI Helper v${e.version||MS}`,`${r(`versionInfo.tag`)}: ${e.tag||MS}`,`${r(`versionInfo.commit`)}: ${e.commitId||MS}`,`${r(`versionInfo.publishedAt`)}: ${FS(e.publishedAt)}`].join(`
2370
+ `}).join(``)}l.addEventListener(`click`,async e=>{let t=e.target.closest(`button[data-act]`);if(!t)return;let n=t.closest(`.sched-item`),i=n?.dataset.id;if(!i)return;let a=t.dataset.act;if(a===`toggle`){let e=(await E())[i];if(!e)return;await SS({type:`SCHEDULED_TASK_TOGGLE`,id:i,enabled:!e.enabled}),C()}else if(a===`run`){let e=await SS({type:`SCHEDULED_TASK_RUN_NOW`,id:i});e?.success?(L(r(`schedPanel.runNowToast`),`success`),AS(e.sessionId),setTimeout(C,1500)):L(e?.error||r(`schedPanel.createFailed`),`error`)}else if(a===`history`){let e=n.querySelector(`[data-history]`);e&&(e.style.display=e.style.display===`none`?``:`none`)}else if(a===`edit`)D((await E())[i]);else if(a===`delete`){let e=(await E())[i];await window.showCustomConfirm(r(`schedPanel.deleteConfirmMsg`,{name:e?.name||``}),r(`schedPanel.deleteConfirmTitle`))&&(await SS({type:`SCHEDULED_TASK_DELETE`,id:i}),L(r(`schedPanel.deleted`),`success`),C())}});async function E(){let e=await SS({type:`SCHEDULED_TASK_LIST`}),t={};return(e?.tasks||[]).forEach(e=>{t[e.id]=e}),t}async function D(e){b=e||null,d.textContent=r(e?`schedPanel.editTitle`:`schedPanel.newTask`),document.getElementById(`schedFormName`).value=e?.name||``,document.getElementById(`schedFormDesc`).value=e?.description||``,document.getElementById(`schedFormPrompt`).value=e?.prompt||``,document.getElementById(`schedFormUrl`).value=e?.contextUrl||``,m.value=e?.schedule?.type||`interval`,g.value=e?.schedule?.onceMode||`relative`,x(),h.value=e?.schedule?.value||``,document.getElementById(`schedFormContextMode`).value=e?.contextMode||`fetch`,document.getElementById(`schedFormMaxRuns`).value=e?.maxRuns??``,document.getElementById(`schedFormEndAt`).value=e?.endAt?ES(e.endAt):``;let t=document.getElementById(`schedFormSession`),n=`<option value="">${r(`schedPanel.sessionAuto`)}</option>`;try{let{list:t}=await he(),r=[...t].sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?new Date(t.createdAt||0)-new Date(e.createdAt||0):r-n});for(let t of r){let r=e?.sessionId===t.id?`selected`:``,i=R(t.title||t.id);n+=`<option value="${R(t.id)}" ${r}>${i}</option>`}}catch{}t.innerHTML=n,u.classList.add(`open`)}function O(){u.classList.remove(`open`),b=null}async function k(){let e=document.getElementById(`schedFormName`).value.trim(),t=document.getElementById(`schedFormPrompt`).value.trim(),n=m.value,i=h.value.trim();if(!e){L(r(`schedPanel.nameRequired`),`warning`);return}if(!t){L(r(`schedPanel.promptRequired`),`warning`);return}if(!i){L(r(`schedPanel.scheduleRequired`),`warning`);return}let a=n===`interval`&&parseInt(document.getElementById(`schedFormMaxRuns`).value,10)||null,o=n===`interval`?document.getElementById(`schedFormEndAt`).value:``,s=o?new Date(o).getTime():null,c={name:e,description:document.getElementById(`schedFormDesc`).value.trim(),prompt:t,schedule:n===`once`?{type:n,value:i,onceMode:g.value}:{type:n,value:i},contextUrl:document.getElementById(`schedFormUrl`).value.trim()||null,contextMode:document.getElementById(`schedFormContextMode`).value||`fetch`,sessionId:document.getElementById(`schedFormSession`).value||null,maxRuns:a,endAt:s,enabled:b?b.enabled:!0};try{let e=await SS({type:b?`SCHEDULED_TASK_UPDATE`:`SCHEDULED_TASK_CREATE`,task:b?{...c,id:b.id}:c});e?.success?(L(r(`schedPanel.saved`),`success`),O(),C()):L(e?.error||r(`schedPanel.createFailed`),`error`)}catch(e){L(e?.message||r(`schedPanel.createFailed`),`error`)}}chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_TASK_RUN_STATE`&&e.taskId&&(e.running?a.add(e.taskId):a.delete(e.taskId),o())}),chrome.runtime.onMessage.addListener(e=>{e.type===`SCHEDULED_SESSION_UPDATED`&&(i.classList.contains(`open`)&&C().catch(()=>{}),e.sessionId&&e.sessionId===F.activeSessionId&&setTimeout(kS,600))}),x(),S(!1),C().catch(()=>{})}var MS=`—`,NS=[{labelKey:`versionInfo.website`,url:`https://xiweicheng.github.io/ai-helper/`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/></svg>`},{labelKey:`versionInfo.discussions`,url:`https://github.com/xiweicheng/ai-helper/discussions`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/></svg>`},{labelKey:`versionInfo.reportIssue`,url:`https://github.com/xiweicheng/ai-helper/issues/new`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z"/></svg>`},{labelKey:`versionInfo.githubRepo`,url:`https://github.com/xiweicheng/ai-helper`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 .5C5.73.5.5 5.73.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.7-3.88-1.54-3.88-1.54-.52-1.33-1.28-1.69-1.28-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.19 1.76 1.19 1.03 1.76 2.7 1.25 3.36.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.28-5.24-5.68 0-1.26.45-2.28 1.19-3.09-.12-.29-.52-1.46.11-3.05 0 0 .97-.31 3.18 1.18a11.1 11.1 0 012.9-.39c.98 0 1.97.13 2.9.39 2.2-1.49 3.17-1.18 3.17-1.18.63 1.59.23 2.76.11 3.05.74.81 1.19 1.83 1.19 3.09 0 4.41-2.69 5.38-5.25 5.67.41.35.78 1.05.78 2.12 0 1.53-.01 2.76-.01 3.14 0 .31.21.68.8.56A11.51 11.51 0 0023.5 12C23.5 5.73 18.27.5 12 .5z"/></svg>`},{labelKey:`versionInfo.giteeRepo`,url:`https://gitee.com/xiweicheng/ai-helper`,icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M11.984 0A12 12 0 000 12a12 12 0 0012 12 12 12 0 0012-12A12 12 0 0012 0zm6.09 5.333c.328 0 .593.266.592.593v1.482a.594.594 0 01-.593.592H9.777c-.982 0-1.778.796-1.778 1.778v5.63c0 .327.266.592.593.592h5.63c.982 0 1.778-.796 1.778-1.778v-.296a.593.593 0 00-.592-.593h-4.15a.592.592 0 01-.592-.592v-1.482a.593.593 0 01.593-.592h6.815c.327 0 .593.265.593.592v3.408a4 4 0 01-4 4H8.444a3.556 3.556 0 01-3.555-3.556V8.89a3.556 3.556 0 013.555-3.556h9.63z"/></svg>`}];function PS(e){let t=e=>typeof e==`string`?e.trim():``,n=e&&typeof e==`object`?e:{};return{version:t(n.version),tag:t(n.tag),commitId:t(n.commitId),publishedAt:t(n.publishedAt)}}function FS(e){if(!e)return MS;let t=Date.parse(e);return Number.isNaN(t)?MS:new Date(t).toLocaleString()}function IS(e){let t=PS(Ve),n=[{label:r(`versionInfo.version`),value:t.version?`v${t.version}`:MS},{label:r(`versionInfo.tag`),value:t.tag||MS},{label:r(`versionInfo.commit`),value:t.commitId?t.commitId.slice(0,8):MS,title:t.commitId,mono:!0},{label:r(`versionInfo.publishedAt`),value:FS(t.publishedAt)}];e.textContent=``;for(let t of n){let n=document.createElement(`div`);n.className=`version-info-row`;let r=document.createElement(`div`);r.className=`version-info-label`,r.textContent=t.label;let i=document.createElement(`div`);i.className=t.mono?`version-info-value mono`:`version-info-value`,i.textContent=t.value,t.title&&(i.title=t.title),n.appendChild(r),n.appendChild(i),e.appendChild(n)}}function LS(e){e.textContent=``;for(let t of NS){let n=document.createElement(`div`);n.className=`version-info-link`,n.title=t.url;let i=document.createElement(`span`);i.className=`version-info-link-icon`,i.innerHTML=t.icon;let a=document.createElement(`span`);a.className=`version-info-link-label`,a.textContent=r(t.labelKey);let o=document.createElement(`span`);o.className=`version-info-link-arrow`,o.textContent=`↗`,n.appendChild(i),n.appendChild(a),n.appendChild(o),n.addEventListener(`click`,()=>{chrome.tabs.create({url:t.url})}),e.appendChild(n)}}function RS(){let e=PS(Ve);return[`AI Helper v${e.version||MS}`,`${r(`versionInfo.tag`)}: ${e.tag||MS}`,`${r(`versionInfo.commit`)}: ${e.commitId||MS}`,`${r(`versionInfo.publishedAt`)}: ${FS(e.publishedAt)}`].join(`
2371
2371
  `)}function zS(){let e=document.getElementById(`versionInfoBtn`),t=document.getElementById(`versionInfoModal`),n=document.getElementById(`versionInfoCloseBtn`),i=document.getElementById(`versionInfoCopyBtn`),a=document.getElementById(`versionInfoList`),o=document.getElementById(`versionInfoLinks`);if(!e||!t||!a)return;let s=()=>{t.style.display=`none`};e.addEventListener(`click`,e=>{e.stopPropagation();let n=document.getElementById(`headerMoreDropdown`);n&&n.classList.remove(`show`),IS(a),o&&LS(o),t.style.display=`flex`}),n&&n.addEventListener(`click`,s),t.addEventListener(`click`,e=>{e.target===t&&s()}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&t.style.display===`flex`&&s()}),i&&i.addEventListener(`click`,async()=>{try{await navigator.clipboard.writeText(RS()),L(r(`common.copySuccess`),`success`)}catch{L(r(`common.copyFailed`),`error`)}})}var BS=null;function VS(){if(!BS)return;BS.classList.remove(`open`);let e=BS.parentElement?BS.parentElement.querySelector(`.section-select-row`):null;e&&e.classList.remove(`open`),BS=null}function HS(){return`<input type="search" class="section-select-search" placeholder="${r(`sectionSelect.searchPlaceholder`)}" data-i18n-placeholder="sectionSelect.searchPlaceholder" spellcheck="false">`}function US(e,t){if(!e)return;let n=String(t||``).trim().toLowerCase(),i=Array.from(e.children).filter(e=>e.hasAttribute(`data-value`)),a=0;for(let e of i){let t=!n||e.textContent.toLowerCase().includes(n);e.style.display=t?``:`none`,t&&(a+=1)}let o=e.querySelector(`.section-select-empty`);n&&a===0?(o||(o=document.createElement(`div`),o.className=`section-select-empty`,e.appendChild(o)),o.textContent=r(`sectionSelect.noMatch`)):o&&o.remove()}function WS(e,t){VS(),e.classList.add(`open`),t.classList.add(`open`),BS=e;let n=e.querySelector(`.section-select-search`);n&&(n.value=``,US(e,``),n.focus())}document.addEventListener(`click`,e=>{let t=e.target.closest(`.section-select-row`);if(t){let e=t.parentElement.querySelector(`.section-select-list`);if(!e)return;e===BS?VS():WS(e,t);return}BS&&!BS.parentElement.contains(e.target)&&VS()}),document.addEventListener(`input`,e=>{let t=e.target;if(!t||!t.classList||!t.classList.contains(`section-select-search`))return;let n=t.closest(`.section-select-list`);n&&US(n,t.value)});var GS=!1;async function KS(){document.getElementById(`providerList`)&&(GS||(GS=!0,YS(),XS()),await qS())}async function qS(){let e=document.getElementById(`providerList`),t=document.getElementById(`providerSelectValue`),n=document.getElementById(`providerSelectHost`);if(!e)return;let r=await C(),i=r.profiles.find(e=>e.id===r.activeProfileId)||r.profiles[0];t&&(t.textContent=i?i.name:``),n&&(n.textContent=i?D(i.apiBase):``),e.innerHTML=HS();let a=[...r.profiles].sort((e,t)=>w(e.name,t.name));for(let t of a){let n=!!i&&t.id===i.id,r=document.createElement(`div`);r.className=`provider-option`+(n?` selected`:``),r.dataset.value=t.id;let a=document.createElement(`span`);a.className=`provider-option-check`,a.textContent=n?`✓`:``,r.appendChild(a);let o=document.createElement(`span`);o.className=`provider-option-left`,o.textContent=t.name,r.appendChild(o);let s=D(t.apiBase);if(s){let e=document.createElement(`span`);e.className=`provider-option-right`,e.textContent=s,r.appendChild(e)}r.addEventListener(`click`,e=>{e.stopPropagation(),VS(),JS(t.id)}),e.appendChild(r)}}async function JS(e){if(e===(await C()).activeProfileId)return;let t=await E(e);t&&(await qS(),a.debug(`[SidePanel] provider switched:`,t.name))}function YS(){let e=document.getElementById(`providerManageBtn`);e&&e.addEventListener(`click`,async e=>{e.stopPropagation();let t=chrome.runtime.getURL(`options.html#basic`),n=await chrome.tabs.query({url:chrome.runtime.getURL(`options.html`)});n.length>0?await chrome.tabs.update(n[0].id,{active:!0,url:t}):await chrome.tabs.create({url:t})})}function XS(){chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&(e.modelProfiles||e.activeProfileId)&&qS()})}var ZS=0;function QS(e,t){let n=e&&e.nodeType===1?e:e?e.parentElement:null;for(let e=n;e&&e!==t;e=e.parentElement)if(getComputedStyle(e).position===`absolute`)return!0;return!1}function $S(e){let t=[];return e.querySelectorAll(`*`).forEach(e=>{getComputedStyle(e).position===`absolute`&&e.getClientRects().length>0&&t.push(e)}),t}function eC(e){e.forEach(e=>{(e.getAnimations?.()||[]).forEach(e=>{e.playState!==`idle`&&e.finish?.()})})}function tC(){ZS||=requestAnimationFrame(()=>{ZS=0,iC()})}function nC(){let e=document.getElementById(`selectionToggleGroup`),t=document.getElementById(`inputAddMenuSwitches`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function rC(){let e=document.getElementById(`selectionToggleGroup`),t=document.querySelector(`.input-bottom-left`);e&&t&&e.parentElement!==t&&t.appendChild(e)}function iC(){let e=document.querySelector(`.input-bottom-row`),t=e?.closest(`.input-container`)||null;if(!(!e||!t)){t.classList.add(`measuring`);try{aC(e,t)}finally{t.classList.remove(`measuring`)}}}function aC(e,t){t.classList.remove(`temp-collapsed`,`agent-collapsed`,`switches-icon`,`selection-in-menu`),rC();let n=$S(e),r=n.map(e=>e.style.display);n.forEach(e=>{e.style.display=`none`});let i=()=>{n.forEach((e,t)=>{e.style.display=r[t]}),eC(n)};if(e.scrollWidth<=e.clientWidth){i();return}if(t.classList.add(`temp-collapsed`),e.scrollWidth<=e.clientWidth){i();return}if(t.classList.add(`agent-collapsed`),e.scrollWidth<=e.clientWidth){i();return}if(t.classList.add(`switches-icon`),e.scrollWidth<=e.clientWidth){i();return}t.classList.add(`selection-in-menu`),nC(),i()}function oC(){iC(),window.addEventListener(`resize`,tC);let e=document.querySelector(`.input-bottom-row`);e&&typeof MutationObserver<`u`&&new MutationObserver(t=>{let n=document.getElementById(`selectionToggleGroup`),r=e=>!!n&&[...e.addedNodes,...e.removedNodes].includes(n);t.some(t=>!QS(t.target,e)&&!r(t))&&tC()}).observe(e,{subtree:!0,childList:!0,characterData:!0})}n(`zh`,{fileSelector:{workspaceTitle:`工作目录`,switchHint:`方向键切换 · Enter添加到文件问答 · Esc取消`,searching:`搜索中...`,noMatch:`没有匹配的文件或目录`,noWorkspace:`暂无工作目录,请先连接 Agent`,loadFailed:`加载失败: {error}`,truncated:`仅显示前 {count} 条,请继续输入以缩小范围`}}),n(`en`,{fileSelector:{workspaceTitle:`Workspace`,switchHint:`↑↓ navigate · Enter attach · Esc cancel`,searching:`Searching...`,noMatch:`No matching file or directory`,noWorkspace:`No workspace directory. Connect an Agent first.`,loadFailed:`Load failed: {error}`,truncated:`Showing top {count} results. Keep typing to narrow down.`}});var sC=50,cC=200,lC=200,uC=0,dC=null,fC=[];function pC(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function mC(e){let t=document.getElementById(`fileAtTitlePath`);if(!t)return;let n=e?pC(e):``;t.textContent=n,t.title=n}async function hC(e=``){let t=document.getElementById(`fileAtSelector`),n=document.getElementById(`fileAtDropdown`);if(!t||!n)return;n.dataset.focusGuard||(n.dataset.focusGuard=`1`,n.addEventListener(`mousedown`,e=>{e.target.closest(`.prompt-item`)&&e.preventDefault()}));let r=document.getElementById(`fileAtWorkspaceOpenBtn`);r&&!r.dataset.bound&&(r.dataset.bound=`1`,r.addEventListener(`click`,async e=>{e.stopPropagation(),gC(),await Rf()})),Xe(),t.style.display=`block`,n.classList.add(`show`),await _C(e)}function gC(){let e=document.getElementById(`fileAtSelector`),t=document.getElementById(`fileAtDropdown`);e&&(e.style.display=`none`),t&&t.classList.remove(`show`),F.selectedFileAtIndex=-1,dC&&=(clearTimeout(dC),null),uC++}function _C(e=``){let t=document.getElementById(`fileAtList`);if(!t)return;let n=++uC,i=e.trim();dC&&clearTimeout(dC);let o=async()=>{try{let e=await md();if(n!==uC)return;if(mC(e),!e){t.innerHTML=`<div class="prompt-empty">${r(`fileSelector.noWorkspace`)}</div>`,F.selectedFileAtIndex=-1;return}let a;if(a=i?await Od(e,i,cC):((await xd(e)).entries||[]).map(t=>({name:t.name,type:t.type||`file`,size:t.size,mtime:t.mtime,fullPath:pC(`${e}/${t.name}`)})),n!==uC)return;yC(a,i,t,e)}catch(e){if(n!==uC)return;a.warn(`[FileAtSelector] search failed:`,e.message),t.innerHTML=`<div class="prompt-empty">${r(`fileSelector.loadFailed`,{error:e.message})}</div>`,F.selectedFileAtIndex=-1}};i?(t.innerHTML=`<div class="prompt-empty">${r(`fileSelector.searching`)}</div>`,dC=setTimeout(o,lC)):dC=setTimeout(o,0)}function vC(e,t){let n=t.toLowerCase();return[...e].sort((e,t)=>{let r=(e.name||``).toLowerCase(),i=(t.name||``).toLowerCase();if(n){let e=+!!r.startsWith(n),t=+!!i.startsWith(n);if(e!==t)return t-e}let a=e.mtime||0,o=t.mtime||0;if(a!==o)return o-a;let s=e.type===`directory`?0:1,c=t.type===`directory`?0:1;return s===c?r.localeCompare(i):s-c})}function yC(e,t,n,i){let a=vC(e,t),o=a.slice(0,sC),s=a.length>sC,c=pC(i);if(o.length===0){n.innerHTML=`<div class="prompt-empty">${r(`fileSelector.noMatch`)}</div>`,F.selectedFileAtIndex=-1;return}if(F.selectedFileAtIndex=0,fC=o,n.innerHTML=o.map((e,t)=>{let n=td(e.name,e.type),r=pC(e.fullPath),i=r.startsWith(c)?r.substring(c.length).replace(/^\//,``):r;return`
2372
2372
  <div class="prompt-item ${t===0?`selected`:``}" data-index="${t}" data-path="${R(r)}" title="${R(r)}">
2373
2373
  <span class="prompt-item-index">${t+1}</span>
@@ -2407,7 +2407,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
2407
2407
  <span class="input-add-panel-item-title">${e.icon} ${R(r(e.nameKey))}</span>
2408
2408
  <span class="input-add-panel-item-sub">${R(r(e.descKey))}</span>
2409
2409
  <kbd class="input-add-panel-item-kbd">${R(e.kbd)}</kbd>
2410
- </div>`;default:return``}}async function XC(e,t){let n=e.ctrlKey||e.metaKey;switch(OC){case`prompts`:{let e=t.dataset.code;n?Zy(e,{skipTriggerStrip:!0}):Qy(e),jC();break}case`skills`:bb(t.dataset.skillName,kC,{clearTrigger:!1}),n&&jC();break;case`mcp`:Nb(t.dataset.serverId,t.dataset.serverName,kC,{clearTrigger:!1}),n&&jC();break;case`pages`:{let e=kC.find(e=>String(e.id)===t.dataset.tabId);if(e){N_(e);let t=document.getElementById(`userInput`);t&&t.focus(),lt()}jC();break}case`knowledge`:__({id:t.dataset.kbId,name:t.dataset.kbName,enabled:t.dataset.kbDisabled!==`1`},{clearTrigger:!1}),n&&jC();break;case`agents`:await m_(t.dataset.agentId,{clearTrigger:!1}),jC();break;case`proxies`:await E_(t.dataset.proxyId,{clearTrigger:!1}),jC();break;case`workspace`:{let e=kC.find(e=>e.fullPath===t.dataset.path);if(e){let t=document.getElementById(`userInput`);t&&t.focus(),await Jh([e]),lt()}jC();break}case`screenshot`:jC(),await(t.dataset.shotAction===`region`?Wd:Ud)();break;default:break}}var ZC=0,QC=200,$C=150,ew={promptTriggerBtn:`prompts`,addMenuSkillBtn:`skills`,addMenuMcpBtn:`mcp`,addMenuPageBtn:`pages`,addMenuKnowledgeBtn:`knowledge`,addMenuAgentBtn:`agents`,addMenuProxyBtn:`proxies`,addMenuWorkspaceBtn:`workspace`,screenshotBtn:`screenshot`};async function tw(){let e=[{id:`addMenuSkillBtn`,available:()=>mb()},{id:`addMenuMcpBtn`,available:()=>kb()},{id:`addMenuKnowledgeBtn`,available:async()=>(await w_()).ok},{id:`addMenuProxyBtn`,available:async()=>(await Gg()).length>0},{id:`addMenuWorkspaceBtn`,available:async()=>!!await md()}],t=++ZC;await Promise.all(e.map(async({id:e,available:n})=>{let r=document.getElementById(e);if(!r)return;let i=!0;try{i=await n()}catch{i=!0}t===ZC&&(r.style.display=i?``:`none`)}))}function nw(){let e=document.getElementById(`inputAddBtn`),t=document.getElementById(`inputAddMenu`);if(!e||!t)return;let n=e.closest(`.input-add-wrapper`),r=t.querySelector(`.input-add-nav`),i=null,a=null,o=!1,s=()=>{let e=BC()?VC():null;t.querySelectorAll(`.input-add-item`).forEach(t=>{t.classList.toggle(`panel-active`,!!e&&ew[t.id]===e)})},c=e=>{let n=document.getElementById(`inputAddPanel`);if(!n||n.style.display===`none`)return;n.style.left=``;let r=t.getBoundingClientRect(),i=n.getBoundingClientRect(),a=r.right+8;a+i.width>window.innerWidth-8&&(a=window.innerWidth-8-i.width),a<8&&(a=8),n.style.left=`${Math.round(a-r.left)}px`;let o=e||t.querySelector(`.input-add-item.panel-active`),s=(o?o.getBoundingClientRect():r).top;s+i.height>r.bottom&&(s=r.bottom-i.height),s<8&&(s=8),n.style.top=`${Math.round(s-r.top-t.clientTop)}px`},l=n=>{t.style.display=n?``:`none`,e.classList.toggle(`open`,n),e.setAttribute(`aria-expanded`,String(n)),n?(WC(),s(),tw()):(i&&=(clearTimeout(i),null),a&&=(clearTimeout(a),null),WC(),s())},u=()=>t.style.display!==`none`;RC({onRequestClose:()=>l(!1)}),e.addEventListener(`click`,e=>{e.stopPropagation();let t=!u();t&&(Gy(),Yg(),gC()),l(t)}),t.addEventListener(`click`,e=>{e.target.closest&&e.target.closest(`.input-add-item`)&&l(!1)},!0),document.addEventListener(`click`,e=>{u()&&(n&&n.contains(e.target)||l(!1))});let d=()=>{i&&=(clearTimeout(i),null),a&&clearTimeout(a),a=setTimeout(()=>{a=null,!HC()&&(WC(),s())},$C)};r&&r.addEventListener(`mouseover`,e=>{if(!u())return;let t=e.target.closest(`.input-add-item`),n=t?ew[t.id]:null;if(!n){d();return}a&&=(clearTimeout(a),null),!(BC()&&VC()===n)&&(i&&clearTimeout(i),i=setTimeout(async()=>{i=null;let e=UC(n);c(t);try{await e}catch{}c(t),s()},QC))}),t.addEventListener(`mouseenter`,()=>{o=!0,a&&=(clearTimeout(a),null)}),t.addEventListener(`mouseleave`,()=>{o=!1,d()});let f=document.getElementById(`inputAddPanelSearch`);f&&f.addEventListener(`blur`,()=>{o||d()}),window.addEventListener(`resize`,()=>{BC()&&c()}),[{id:`promptTriggerBtn`,open:()=>Wy(``,`prompts`)},{id:`addMenuSkillBtn`,open:()=>Wy(``,`skills`)},{id:`addMenuMcpBtn`,open:()=>Wy(``,`mcp`)},{id:`addMenuPageBtn`,open:()=>qg(``,`pages`)},{id:`addMenuKnowledgeBtn`,open:()=>qg(``,`knowledge`)},{id:`addMenuAgentBtn`,open:()=>qg(``,`agents`)},{id:`addMenuProxyBtn`,open:()=>qg(``,`proxies`)},{id:`addMenuWorkspaceBtn`,open:()=>hC(``)}].forEach(({id:e,open:t})=>{let n=document.getElementById(e);n&&n.addEventListener(`click`,async e=>{e.stopPropagation(),n.blur(),Gy(),Yg(),gC();try{await t()}catch{}let r=document.getElementById(`userInput`);r&&r.focus()})});let p=document.getElementById(`inputAddMenuSwitches`),m=()=>{let t=p?.querySelector(`input[type="checkbox"]`);e.classList.toggle(`has-active-switch`,!!(t&&t.checked))};p&&(typeof MutationObserver<`u`&&new MutationObserver(m).observe(p,{subtree:!0,childList:!0}),p.addEventListener(`change`,m)),m()}function rw(e,t){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>{clearTimeout(n),e(...r)},t)}}n(`zh`,{tokenStats:{clearConfirmMessage:`确定要清空所有 Token 使用统计吗?此操作不可撤销。`,loadFailed:`加载失败`,currentSessionNoData:`当前会话暂无数据`,totalTokenUsage:`总 Token 消耗`,apiCallCount:`API 调用次数`,contextUsageRate:`上下文使用率`,max:`最大`,avg:`平均`,min:`最小`,totalTokens:`总 Token`,totalSessions:`总会话数`,totalApiCalls:`总 API 调用`,callTypeNonStream:`普通`,callTypeStream:`流式`,callTypeReflection:`反思`,callTypeToolReflection:`工具反思`,callTypeSubtaskReflection:`子任务反思`,tabTrend:`趋势`,tabDistribution:`分布`,tabGlobal:`全局`,topCardSessionTokens:`本次 Token`,topCardSessionCalls:`本次调用`,topCardContextPeak:`上下文峰值`,sparklineTitle:`最近 20 次调用趋势`,distPromptVsCompletion:`Prompt / Completion 占比`,distPrompt:`Prompt`,distCompletion:`Completion`,distByModel:`按模型分布`,distByCallType:`按调用类型分布`,distNoData:`暂无分布数据`,globalSparklineTitle:`最近 30 天趋势`,globalNoDailyData:`所选范围内暂无数据`,globalTotalTokens:`总 Token`,globalTotalSessions:`总会话数`,globalTotalApiCalls:`总 API 调用`}}),n(`en`,{tokenStats:{clearConfirmMessage:`Are you sure you want to clear all Token usage statistics? This action cannot be undone.`,loadFailed:`Load failed`,currentSessionNoData:`No data for current session`,totalTokenUsage:`Total Token Usage`,apiCallCount:`API Call Count`,contextUsageRate:`Context Usage Rate`,max:`Max`,avg:`Avg`,min:`Min`,totalTokens:`Total Tokens`,totalSessions:`Total Sessions`,totalApiCalls:`Total API Calls`,callTypeNonStream:`Normal`,callTypeStream:`Stream`,callTypeReflection:`Reflection`,callTypeToolReflection:`Tool Reflection`,callTypeSubtaskReflection:`Subtask Reflection`,tabTrend:`Trend`,tabDistribution:`Distribution`,tabGlobal:`Global`,topCardSessionTokens:`Session Tokens`,topCardSessionCalls:`Session Calls`,topCardContextPeak:`Context Peak`,sparklineTitle:`Last 20 Calls Trend`,distPromptVsCompletion:`Prompt / Completion Ratio`,distPrompt:`Prompt`,distCompletion:`Completion`,distByModel:`By Model`,distByCallType:`By Call Type`,distNoData:`No distribution data`,globalSparklineTitle:`Last 30 Days Trend`,globalNoDailyData:`No data in selected range`,globalTotalTokens:`Total Tokens`,globalTotalSessions:`Total Sessions`,globalTotalApiCalls:`Total API Calls`}});function iw(e,t){let n=document.getElementById(`tokenStatsOverlay`),i=document.getElementById(`tokenStatsClose`),o=document.getElementById(`tokenStatsRefreshBtn`),s=document.getElementById(`tokenStatsClearBtn`),c=document.getElementById(`tokenStatsTabNav`),l=document.getElementById(`tokenStatsTopCards`);if(!n)return;let u=`trend`,d=`month`;function f(){n.style.display=`flex`,h()}function p(){n.style.display=`none`}if(window.openTokenStats=f,i&&i.addEventListener(`click`,p),n&&n.addEventListener(`click`,e=>{e.target===n&&p()}),o&&o.addEventListener(`click`,h),s&&s.addEventListener(`click`,async()=>{await t(r(`tokenStats.clearConfirmMessage`),r(`toolStats.clearTitle`))&&(await xe(),h())}),c){c.addEventListener(`click`,e=>{let t=e.target.closest(`.token-tab-btn`);if(!t)return;let n=t.dataset.tab;if(n===u)return;c.querySelectorAll(`.token-tab-btn`).forEach(e=>{e.classList.remove(`active`),e.style.borderBottomColor=`transparent`,e.style.color=`var(--text-secondary)`}),t.classList.add(`active`),t.style.borderBottomColor=`var(--brand-500)`,t.style.color=`var(--brand-500)`,document.querySelectorAll(`.token-tab-content`).forEach(e=>{e.style.display=`none`});let r=document.getElementById(`tokenTab${n.charAt(0).toUpperCase()+n.slice(1)}`);r&&(r.style.display=n===`global`?`flex`:``),u=n});let e=c.querySelector(`.token-tab-btn.active`);e&&(e.style.borderBottomColor=`var(--brand-500)`,e.style.color=`var(--brand-500)`)}let m=document.querySelectorAll(`.token-time-range-btn`);m.forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.range;t!==d&&(d=t,m.forEach(e=>{e.classList.remove(`active`),e.style.border=`1px solid var(--border-default)`,e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`}),e.classList.add(`active`),e.style.border=`1px solid var(--brand-500)`,e.style.background=`var(--brand-500)`,e.style.color=`var(--text-on-brand)`,w())})});async function h(){let t=e(),n=document.getElementById(`tokenStatsLoading`),i=document.getElementById(`tokenStatsEmpty`),o=document.getElementById(`tokenStatsContent`);n&&(n.style.display=``),i&&(i.style.display=`none`),o&&(o.style.display=`none`),c&&(c.style.display=`none`),l&&(l.style.display=`none`);try{let[e,r]=await Promise.all([se(t),be()]);if(n&&(n.style.display=`none`),!(r&&r.totalApiCalls>0)){i&&(i.style.display=``);return}o&&(o.style.display=``),c&&(c.style.display=`flex`),l&&(l.style.display=``),g(e),_(e),E(e.records||[]),x(r),w()}catch(e){a.error(`[TokenStats] load stats failed:`,e),n&&(n.style.display=`none`),i&&(i.textContent=r(`tokenStats.loadFailed`),i.style.display=``)}}function g(e){if(!l)return;if(!e||e.apiCallCount===0){l.innerHTML=``;return}let t=e.maxContextUsageRate||0,n=O(t);l.innerHTML=`
2410
+ </div>`;default:return``}}async function XC(e,t){let n=e.ctrlKey||e.metaKey;switch(OC){case`prompts`:{let e=t.dataset.code;n?Zy(e,{skipTriggerStrip:!0}):Qy(e),jC();break}case`skills`:bb(t.dataset.skillName,kC,{clearTrigger:!1}),n&&jC();break;case`mcp`:Nb(t.dataset.serverId,t.dataset.serverName,kC,{clearTrigger:!1}),n&&jC();break;case`pages`:{let e=kC.find(e=>String(e.id)===t.dataset.tabId);if(e){N_(e);let t=document.getElementById(`userInput`);t&&t.focus(),lt()}jC();break}case`knowledge`:__({id:t.dataset.kbId,name:t.dataset.kbName,enabled:t.dataset.kbDisabled!==`1`},{clearTrigger:!1}),n&&jC();break;case`agents`:await m_(t.dataset.agentId,{clearTrigger:!1}),jC();break;case`proxies`:await E_(t.dataset.proxyId,{clearTrigger:!1}),jC();break;case`workspace`:{let e=kC.find(e=>e.fullPath===t.dataset.path);if(e){let t=document.getElementById(`userInput`);t&&t.focus(),await Jh([e]),lt()}jC();break}case`screenshot`:jC(),await(t.dataset.shotAction===`region`?Wd:Ud)();break;default:break}}var ZC=0,QC=200,$C=150,ew={promptTriggerBtn:`prompts`,addMenuSkillBtn:`skills`,addMenuMcpBtn:`mcp`,addMenuPageBtn:`pages`,addMenuKnowledgeBtn:`knowledge`,addMenuAgentBtn:`agents`,addMenuProxyBtn:`proxies`,addMenuWorkspaceBtn:`workspace`,screenshotBtn:`screenshot`};async function tw(){let e=[{id:`addMenuSkillBtn`,available:()=>mb()},{id:`addMenuMcpBtn`,available:()=>kb()},{id:`addMenuKnowledgeBtn`,available:async()=>(await w_()).ok},{id:`addMenuProxyBtn`,available:async()=>(await Gg()).length>0},{id:`addMenuWorkspaceBtn`,available:async()=>!!await md()}],t=++ZC;await Promise.all(e.map(async({id:e,available:n})=>{let r=document.getElementById(e);if(!r)return;let i=!0;try{i=await n()}catch{i=!0}t===ZC&&(r.style.display=i?``:`none`)}))}function nw(){let e=document.getElementById(`inputAddBtn`),t=document.getElementById(`inputAddMenu`);if(!e||!t)return;let n=e.closest(`.input-add-wrapper`),r=t.querySelector(`.input-add-nav`),i=null,a=null,o=!1,s=()=>{let e=BC()?VC():null;t.querySelectorAll(`.input-add-item`).forEach(t=>{t.classList.toggle(`panel-active`,!!e&&ew[t.id]===e)})},c=e=>{let n=document.getElementById(`inputAddPanel`);if(!n||n.style.display===`none`)return;n.style.left=``;let r=t.getBoundingClientRect(),i=n.getBoundingClientRect(),a=r.right+8;a+i.width>window.innerWidth-8&&(a=window.innerWidth-8-i.width),a<8&&(a=8),n.style.left=`${Math.round(a-r.left)}px`;let o=e||t.querySelector(`.input-add-item.panel-active`),s=(o?o.getBoundingClientRect():r).top;s+i.height>r.bottom&&(s=r.bottom-i.height),s<8&&(s=8),n.style.top=`${Math.round(s-r.top-t.clientTop)}px`},l=n=>{t.style.display=n?``:`none`,e.classList.toggle(`open`,n),e.setAttribute(`aria-expanded`,String(n)),n?(WC(),s(),tw()):(i&&=(clearTimeout(i),null),a&&=(clearTimeout(a),null),WC(),s())},u=()=>t.style.display!==`none`;RC({onRequestClose:()=>l(!1)}),e.addEventListener(`click`,e=>{e.stopPropagation();let t=!u();t&&(Gy(),Yg(),gC()),l(t)}),t.addEventListener(`click`,e=>{e.target.closest&&e.target.closest(`.input-add-item`)&&l(!1)},!0),document.addEventListener(`click`,e=>{u()&&(n&&n.contains(e.target)||l(!1))});let d=()=>{i&&=(clearTimeout(i),null),a&&clearTimeout(a),a=setTimeout(()=>{a=null,!HC()&&(WC(),s())},$C)};r&&r.addEventListener(`mouseover`,e=>{if(!u())return;let t=e.target.closest(`.input-add-item`),n=t?ew[t.id]:null;if(!n){d();return}a&&=(clearTimeout(a),null),!(BC()&&VC()===n)&&(i&&clearTimeout(i),i=setTimeout(async()=>{i=null;let e=UC(n);c(t);try{await e}catch{}c(t),s()},QC))}),t.addEventListener(`mouseenter`,()=>{o=!0,a&&=(clearTimeout(a),null)}),t.addEventListener(`mouseleave`,()=>{o=!1,d()});let f=document.getElementById(`inputAddPanelSearch`);f&&f.addEventListener(`blur`,()=>{o||d()}),window.addEventListener(`resize`,()=>{BC()&&c()}),[{id:`promptTriggerBtn`,open:()=>Wy(``,`prompts`)},{id:`addMenuSkillBtn`,open:()=>Wy(``,`skills`)},{id:`addMenuMcpBtn`,open:()=>Wy(``,`mcp`)},{id:`addMenuPageBtn`,open:()=>qg(``,`pages`)},{id:`addMenuKnowledgeBtn`,open:()=>qg(``,`knowledge`)},{id:`addMenuAgentBtn`,open:()=>qg(``,`agents`)},{id:`addMenuProxyBtn`,open:()=>qg(``,`proxies`)},{id:`addMenuWorkspaceBtn`,open:()=>hC(``)}].forEach(({id:e,open:t})=>{let n=document.getElementById(e);n&&n.addEventListener(`click`,async e=>{e.stopPropagation(),n.blur(),Gy(),Yg(),gC();try{await t()}catch{}let r=document.getElementById(`userInput`);r&&r.focus()})});let p=document.getElementById(`inputAddMenuSwitches`),m=()=>{let t=p?.querySelector(`input[type="checkbox"]`);e.classList.toggle(`has-active-switch`,!!(t&&t.checked))};p&&(typeof MutationObserver<`u`&&new MutationObserver(m).observe(p,{subtree:!0,childList:!0}),p.addEventListener(`change`,m)),m()}function rw(e,t){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>{clearTimeout(n),e(...r)},t)}}n(`zh`,{tokenStats:{clearConfirmMessage:`确定要清空所有 Token 使用统计吗?此操作不可撤销。`,loadFailed:`加载失败`,currentSessionNoData:`当前会话暂无数据`,totalTokenUsage:`总 Token 消耗`,apiCallCount:`API 调用次数`,contextUsageRate:`上下文使用率`,max:`最大`,avg:`平均`,min:`最小`,totalTokens:`总 Token`,totalSessions:`总会话数`,totalApiCalls:`总 API 调用`,callTypeNonStream:`普通`,callTypeStream:`流式`,callTypeReflection:`反思`,callTypeToolReflection:`工具反思`,callTypeSubtaskReflection:`子任务反思`,tabTrend:`趋势`,tabDistribution:`分布`,tabGlobal:`全局`,topCardSessionTokens:`本次 Token`,topCardSessionCalls:`本次调用`,topCardContextPeak:`上下文峰值`,sparklineTitle:`最近 20 次调用趋势`,distPromptVsCompletion:`Prompt / Completion 占比`,distPrompt:`Prompt`,distCompletion:`Completion`,distByModel:`按模型分布`,distByCallType:`按调用类型分布`,distNoData:`暂无分布数据`,globalSparklineTitle:`最近 30 天趋势`,globalNoDailyData:`所选范围内暂无数据`,globalTotalTokens:`总 Token`,globalTotalSessions:`总会话数`,globalTotalApiCalls:`总 API 调用`}}),n(`en`,{tokenStats:{clearConfirmMessage:`Are you sure you want to clear all Token usage statistics? This action cannot be undone.`,loadFailed:`Load failed`,currentSessionNoData:`No data for current session`,totalTokenUsage:`Total Token Usage`,apiCallCount:`API Call Count`,contextUsageRate:`Context Usage Rate`,max:`Max`,avg:`Avg`,min:`Min`,totalTokens:`Total Tokens`,totalSessions:`Total Sessions`,totalApiCalls:`Total API Calls`,callTypeNonStream:`Normal`,callTypeStream:`Stream`,callTypeReflection:`Reflection`,callTypeToolReflection:`Tool Reflection`,callTypeSubtaskReflection:`Subtask Reflection`,tabTrend:`Trend`,tabDistribution:`Distribution`,tabGlobal:`Global`,topCardSessionTokens:`Session Tokens`,topCardSessionCalls:`Session Calls`,topCardContextPeak:`Context Peak`,sparklineTitle:`Last 20 Calls Trend`,distPromptVsCompletion:`Prompt / Completion Ratio`,distPrompt:`Prompt`,distCompletion:`Completion`,distByModel:`By Model`,distByCallType:`By Call Type`,distNoData:`No distribution data`,globalSparklineTitle:`Last 30 Days Trend`,globalNoDailyData:`No data in selected range`,globalTotalTokens:`Total Tokens`,globalTotalSessions:`Total Sessions`,globalTotalApiCalls:`Total API Calls`}});function iw(e,t){let n=document.getElementById(`tokenStatsOverlay`),i=document.getElementById(`tokenStatsClose`),o=document.getElementById(`tokenStatsRefreshBtn`),s=document.getElementById(`tokenStatsClearBtn`),c=document.getElementById(`tokenStatsTabNav`),l=document.getElementById(`tokenStatsTopCards`);if(!n)return;let u=`trend`,d=`month`;function f(){n.style.display=`flex`,h()}function p(){n.style.display=`none`}if(window.openTokenStats=f,i&&i.addEventListener(`click`,p),n&&n.addEventListener(`click`,e=>{e.target===n&&p()}),o&&o.addEventListener(`click`,h),s&&s.addEventListener(`click`,async()=>{await t(r(`tokenStats.clearConfirmMessage`),r(`toolStats.clearTitle`))&&(await Se(),h())}),c){c.addEventListener(`click`,e=>{let t=e.target.closest(`.token-tab-btn`);if(!t)return;let n=t.dataset.tab;if(n===u)return;c.querySelectorAll(`.token-tab-btn`).forEach(e=>{e.classList.remove(`active`),e.style.borderBottomColor=`transparent`,e.style.color=`var(--text-secondary)`}),t.classList.add(`active`),t.style.borderBottomColor=`var(--brand-500)`,t.style.color=`var(--brand-500)`,document.querySelectorAll(`.token-tab-content`).forEach(e=>{e.style.display=`none`});let r=document.getElementById(`tokenTab${n.charAt(0).toUpperCase()+n.slice(1)}`);r&&(r.style.display=n===`global`?`flex`:``),u=n});let e=c.querySelector(`.token-tab-btn.active`);e&&(e.style.borderBottomColor=`var(--brand-500)`,e.style.color=`var(--brand-500)`)}let m=document.querySelectorAll(`.token-time-range-btn`);m.forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.range;t!==d&&(d=t,m.forEach(e=>{e.classList.remove(`active`),e.style.border=`1px solid var(--border-default)`,e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`}),e.classList.add(`active`),e.style.border=`1px solid var(--brand-500)`,e.style.background=`var(--brand-500)`,e.style.color=`var(--text-on-brand)`,w())})});async function h(){let t=e(),n=document.getElementById(`tokenStatsLoading`),i=document.getElementById(`tokenStatsEmpty`),o=document.getElementById(`tokenStatsContent`);n&&(n.style.display=``),i&&(i.style.display=`none`),o&&(o.style.display=`none`),c&&(c.style.display=`none`),l&&(l.style.display=`none`);try{let[e,r]=await Promise.all([oe(t),xe()]);if(n&&(n.style.display=`none`),!(r&&r.totalApiCalls>0)){i&&(i.style.display=``);return}o&&(o.style.display=``),c&&(c.style.display=`flex`),l&&(l.style.display=``),g(e),_(e),E(e.records||[]),x(r),w()}catch(e){a.error(`[TokenStats] load stats failed:`,e),n&&(n.style.display=`none`),i&&(i.textContent=r(`tokenStats.loadFailed`),i.style.display=``)}}function g(e){if(!l)return;if(!e||e.apiCallCount===0){l.innerHTML=``;return}let t=e.maxContextUsageRate||0,n=O(t);l.innerHTML=`
2411
2411
  <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px;">
2412
2412
  <div style="background: var(--brand-soft-bg); border-radius: 8px; padding: 10px; text-align: center;">
2413
2413
  <div style="font-size: 10px; color: var(--text-tertiary); margin-bottom: 4px;">${r(`tokenStats.topCardSessionTokens`)}</div>
@@ -2456,7 +2456,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
2456
2456
  <span>${r(`tokenStats.min`)}</span>
2457
2457
  <span>${r(`tokenStats.avg`)}</span>
2458
2458
  <span>${r(`tokenStats.max`)}</span>
2459
- </div>`}function b(e){return{react_loop:`ReAct`,non_stream:r(`tokenStats.callTypeNonStream`),stream:r(`tokenStats.callTypeStream`),reflection:r(`tokenStats.callTypeReflection`),tool_reflection:r(`tokenStats.callTypeToolReflection`),subtask_reflection:r(`tokenStats.callTypeSubtaskReflection`),unknown:`-`}[e]||e}async function x(e){let t=document.getElementById(`tokenDistributionStats`);if(t)try{let[n,i]=await Promise.all([re(),ce()]),a=e?.totalPromptTokens||0,o=e?.totalCompletionTokens||0;if(a+o===0&&n.length===0){t.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:20px;">${r(`tokenStats.distNoData`)}</div>`;return}t.innerHTML=`
2459
+ </div>`}function b(e){return{react_loop:`ReAct`,non_stream:r(`tokenStats.callTypeNonStream`),stream:r(`tokenStats.callTypeStream`),reflection:r(`tokenStats.callTypeReflection`),tool_reflection:r(`tokenStats.callTypeToolReflection`),subtask_reflection:r(`tokenStats.callTypeSubtaskReflection`),unknown:`-`}[e]||e}async function x(e){let t=document.getElementById(`tokenDistributionStats`);if(t)try{let[n,i]=await Promise.all([re(),se()]),a=e?.totalPromptTokens||0,o=e?.totalCompletionTokens||0;if(a+o===0&&n.length===0){t.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:20px;">${r(`tokenStats.distNoData`)}</div>`;return}t.innerHTML=`
2460
2460
  <div style="margin-bottom:16px;">
2461
2461
  <div style="font-size:12px;font-weight:600;color:var(--text-secondary);margin-bottom:8px;">${r(`tokenStats.distPromptVsCompletion`)}</div>
2462
2462
  ${S(a,o)}
@@ -2490,7 +2490,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
2490
2490
  <div style="height:8px;background:var(--border-subtle);border-radius:4px;overflow:hidden;">
2491
2491
  <div style="height:100%;width:${r}%;background:${t};border-radius:4px;"></div>
2492
2492
  </div>
2493
- </div>`}).join(``)}async function w(){let e=document.getElementById(`tokenGlobalSparkline`),t=document.getElementById(`tokenOverallStats`);if(!e||!t)return;let n=new Date,i=n.toISOString(),o,s;d===`today`?(o=new Date(n.getFullYear(),n.getMonth(),n.getDate()).toISOString(),s=1):d===`week`?(o=new Date(n.getTime()-10080*60*1e3).toISOString(),s=7):d===`month`?(o=new Date(n.getTime()-720*60*60*1e3).toISOString(),s=30):(o=new Date(0).toISOString(),s=365);try{let[n,a]=await Promise.all([ee(s),oe(o,i)]);if(e.innerHTML=T(n),!a||a.totalApiCalls===0){t.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:16px;font-size:12px;">${r(`tokenStats.globalNoDailyData`)}</div>`;return}t.innerHTML=`
2493
+ </div>`}).join(``)}async function w(){let e=document.getElementById(`tokenGlobalSparkline`),t=document.getElementById(`tokenOverallStats`);if(!e||!t)return;let n=new Date,i=n.toISOString(),o,s;d===`today`?(o=new Date(n.getFullYear(),n.getMonth(),n.getDate()).toISOString(),s=1):d===`week`?(o=new Date(n.getTime()-10080*60*1e3).toISOString(),s=7):d===`month`?(o=new Date(n.getTime()-720*60*60*1e3).toISOString(),s=30):(o=new Date(0).toISOString(),s=365);try{let[n,a]=await Promise.all([ee(s),ae(o,i)]);if(e.innerHTML=T(n),!a||a.totalApiCalls===0){t.innerHTML=`<div style="text-align:center;color:var(--text-tertiary);padding:16px;font-size:12px;">${r(`tokenStats.globalNoDailyData`)}</div>`;return}t.innerHTML=`
2494
2494
  <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;">
2495
2495
  <div style="background:var(--warning-soft-bg);border-radius:8px;padding:10px;text-align:center;">
2496
2496
  <div style="font-size:10px;color:var(--text-tertiary);">${r(`tokenStats.globalTotalTokens`)}</div>
@@ -2536,7 +2536,7 @@ Agent address: {url}
2536
2536
  Are you sure you want to update the agent? It will install the latest version via npm, then restart the service. The service will be unavailable during update.`,updateAgentTitle:`Update Agent`,agentUpdating:`Updating agent (may take a few minutes)...`,agentUpdateRestarting:`Agent is updating and restarting...`,updateFailed:`Update failed: {error}`,updateRequestFailed:`Update request failed: {error}`,stopAgentConfirm:`Agent name: {name}
2537
2537
  Agent address: {url}
2538
2538
 
2539
- Are you sure you want to stop the agent service? You will not be able to connect and will need to manually restart it.`,stopAgentTitle:`Stop Agent`,agentStopped:`Agent service stopped, agent is offline`,stopFailed:`Stop failed: {error}`,stopRequestFailed:`Stop request failed: {error}`,agentStatusRefreshed:`Agent status refreshed`,deleteAgentTitle:`Delete Agent`,deleteAgentConfirm:`Are you sure you want to delete agent "{name}"? This action cannot be undone.`,welcomeTitle:`Start a Conversation`,welcomeSubtitle:`Enter your question and the AI assistant will help you`,sendBtnStop:`Stop generating`,sendBtnSend:`Send`,imageNotEnabled:`Image recognition not enabled, image attached as file`,screenshotFailed:`Screenshot failed, please retry`,auditCategoryAuth:`Auth`,auditCategoryFs:`File`,auditCategoryExec:`Command`,auditCategorySecurity:`Security`,auditCategorySystem:`System`,auditDetailSeparator:`; `,auditQueryFailed:`Query failed: {error}`,auditLoadFailed:`Load failed: {error}`,auditNoMatch:`No matching audit logs`,auditEmpty:`No audit logs`,clearStatsConfirm:`Are you sure you want to clear all tool usage stats? This action cannot be undone.`,clearStatsTitle:`Clear Stats`,toolStatsSummary:`Used {used} tools, unused {unused} tools`,toolStatsLoadFailed:`Load failed`,toolNameDescSeparator:`: `}}),window.showCustomConfirm=function(e,t=r(`sidePanel.confirmAction`)){return new Promise(n=>{let r=document.getElementById(`customConfirmOverlay`),i=document.getElementById(`customConfirmTitle`),a=document.getElementById(`customConfirmMessage`),o=document.getElementById(`customConfirmCancelBtn`),s=document.getElementById(`customConfirmOkBtn`);if(!r||!i||!a||!o||!s){n(confirm(e));return}let c=()=>{r.style.display=`none`,s.removeEventListener(`click`,l),o.removeEventListener(`click`,u),r.removeEventListener(`click`,d),document.removeEventListener(`keydown`,f)},l=()=>{c(),n(!0)},u=()=>{c(),n(!1)},d=e=>{e.target===r&&(c(),n(!1))},f=e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),l()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),u())};i.textContent=t,a.innerHTML=e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`).replace(/\n/g,`<br>`),r.style.display=`flex`,s.addEventListener(`click`,l),o.addEventListener(`click`,u),r.addEventListener(`click`,d),document.addEventListener(`keydown`,f),requestAnimationFrame(()=>s.focus())})},chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&e.chatAutoCompaction&&(F.chatConfig.autoCompaction=e.chatAutoCompaction.newValue===!0,sw(),a.debug(`[SidePanel] auto-compaction config updated:`,F.chatConfig.autoCompaction)),t===`local`&&e.chatPersistSummaryToMemory&&(F.chatConfig.persistSummaryToMemory=e.chatPersistSummaryToMemory.newValue!==!1,cw(),a.debug(`[SidePanel] persist-summary config updated:`,F.chatConfig.persistSummaryToMemory)),t===`local`&&e.chatMaxMemoryMessages&&(F.chatConfig.maxMemoryMessages=e.chatMaxMemoryMessages.newValue,ow(),a.debug(`[SidePanel] memory limitconfiguration updated:`,F.chatConfig.maxMemoryMessages))});function ow(){let e=document.getElementById(`memoryLimitLabel`);e&&(F.chatConfig.maxMemoryMessages!==null&&F.chatConfig.maxMemoryMessages!==void 0&&F.chatConfig.maxMemoryMessages>0?e.textContent=F.chatConfig.maxMemoryMessages:e.textContent=r(`sidePanel.memoryLimitAll`),e.title=r(`sidePanel.memoryLimitTitle`))}function sw(){let e=document.getElementById(`autoCompactBtn`);e&&(e.checked=F.chatConfig.autoCompaction===!0)}function cw(){let e=document.getElementById(`persistSummaryBtn`);e&&(e.checked=F.chatConfig.persistSummaryToMemory!==!1)}function lw(e){e.preventDefault(),e.stopPropagation();let t=document.getElementById(`memoryLimitDropdown`);if(t.classList.toggle(`show`),t.classList.contains(`show`)){let e=F.chatConfig.maxMemoryMessages;t.querySelectorAll(`.memory-limit-option`).forEach(t=>{t.classList.remove(`selected`);let n=parseInt(t.dataset.value);(e===null&&n===0||e!==null&&e>0&&n===e)&&t.classList.add(`selected`)});let n=t.querySelector(`#memoryLimitInput`);e!==null&&e>0?n.value=e:n.value=``}}function uw(){let e=document.getElementById(`memoryLimitDropdown`),t=document.getElementById(`memoryLimitLabel`),n=e?.querySelector(`#memoryLimitInput`);if(!e||!t)return;ow(),t.addEventListener(`click`,lw);let i=document.getElementById(`autoCompactBtn`);i&&(i.checked=F.chatConfig.autoCompaction===!0,i.addEventListener(`change`,()=>{let e=i.checked;chrome.storage.local.set({chatAutoCompaction:e},()=>{F.chatConfig.autoCompaction=e,L(r(`sidePanel.configUpdated`),`success`)})}));let a=document.getElementById(`persistSummaryBtn`);a&&(a.checked=F.chatConfig.persistSummaryToMemory!==!1,a.addEventListener(`change`,()=>{let e=a.checked;chrome.storage.local.set({chatPersistSummaryToMemory:e},()=>{F.chatConfig.persistSummaryToMemory=e,L(r(`sidePanel.configUpdated`),`success`)})}));let o=e.querySelectorAll(`.memory-limit-option`);o.forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let i=parseInt(e.dataset.value),a=i===0?null:i;o.forEach(e=>e.classList.remove(`selected`)),e.classList.add(`selected`),n&&(n.value=i===0?``:i),chrome.storage.local.set({chatMaxMemoryMessages:a},()=>{F.chatConfig.maxMemoryMessages=a,ow(),L(r(`sidePanel.configUpdated`),`success`)})})}),n&&(n.addEventListener(`click`,e=>e.stopPropagation()),n.addEventListener(`mousedown`,e=>e.stopPropagation()),n.addEventListener(`change`,e=>{e.stopPropagation();let t=e.target.value.trim(),n=t&&parseInt(t)>0?parseInt(t):null;o.forEach(e=>e.classList.remove(`selected`)),chrome.storage.local.set({chatMaxMemoryMessages:n},()=>{F.chatConfig.maxMemoryMessages=n,ow(),L(r(`sidePanel.configUpdated`),`success`)})})),document.getElementById(`memoryLimitConfigEntry`)?.addEventListener(`click`,()=>{chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`memory`})}),document.addEventListener(`click`,n=>{!e.contains(n.target)&&n.target!==t&&e.classList.remove(`show`)})}async function dw(e){if(F.activeAgentId&&F.activeAgentId!=="default")try{let{updateAgent:t}=await I(async()=>{let{updateAgent:e}=await import(`./agent-store-BvS-vIQr.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([0,1,2,3,4]));await t(F.activeAgentId,{model:e})}catch{}else chrome.storage.local.set({modelName:e}),k(e)}async function fw(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=aw(e.pairedAgents),n=e.activeAgentId,r=t.find(e=>e.id===n&&!e.disabled);if(!r){F.agentPlatform={connected:!1},xw(F.agentPlatform);return}if(r.token)try{let e=await fetch(`${r.url}/api/status/detail`,{cache:`no-cache`,headers:{Authorization:`Bearer ${r.token}`}});if(e.ok){let t=await e.json();if(t.success){F.agentPlatform={platformName:t.platformName||`Unknown`,platform:t.platform||`unknown`,arch:t.arch||`unknown`,shell:t.shell||`/bin/sh`,homeDir:t.homeDir||``,workdir:t.workdir||``,connected:!0},t.version&&F.agentVersions.set(n,t.version),t.workdir&&F.agentWorkdirs.set(n,t.workdir),t.homeDir&&F.agentHomeDirs.set(n,t.homeDir);let e=Tw(t.platformName||t.platform,t.arch);e&&F.agentSystemInfos.set(n,e)}else F.agentPlatform={connected:!1}}else F.agentPlatform={connected:!1}}catch{F.agentPlatform={connected:!1}}else F.agentPlatform={connected:!1};xw(F.agentPlatform),Vd()}catch{}}async function pw(e,t,n){if(F.activeAgentId&&F.activeAgentId!=="default")try{let{updateAgent:n}=await I(async()=>{let{updateAgent:e}=await import(`./agent-store-BvS-vIQr.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([0,1,2,3,4]));await n(F.activeAgentId,{temperature:e,topP:t})}catch{}else chrome.storage.local.set({temperature:e,topP:t,selectedTempIndex:n})}function mw(){let e=document.getElementById(`currentModelTag`);if(!e)return;let t=F.currentModel||``;e.textContent=t,e.title=t,e.style.display=t?``:`none`}function hw(){let e=document.getElementById(`currentModelTag`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),document.getElementById(`tempDisplay`)?.click()}),mw()}function gw(e){let t=0;document.querySelectorAll(`.model-option`).forEach(n=>{n.dataset.value===e?(n.classList.add(`selected`),n.querySelector(`.model-option-check`).textContent=`✓`,t=parseInt(n.dataset.contextWindow,10)||0):(n.classList.remove(`selected`),n.querySelector(`.model-option-check`).textContent=``)});let n=document.getElementById(`modelSelectValue`);n&&e&&(n.textContent=e);let r=document.getElementById(`modelSelectCtxBadge`);r&&(t>0?(r.textContent=T(t),r.style.display=``):r.style.display=`none`),mw()}function _w(e,t){let n=document.getElementById(`tempDropdown`);if(!n){typeof t==`function`&&t();return}let i=n.querySelector(`.model-section`),a=[];if((Array.isArray(e)?e:[]).forEach(e=>{typeof e==`string`?a.push({name:e,contextWindow:0}):e&&typeof e==`object`&&e.name&&a.push({name:e.name,contextWindow:e.contextWindow||0})}),i){i.innerHTML=`
2539
+ Are you sure you want to stop the agent service? You will not be able to connect and will need to manually restart it.`,stopAgentTitle:`Stop Agent`,agentStopped:`Agent service stopped, agent is offline`,stopFailed:`Stop failed: {error}`,stopRequestFailed:`Stop request failed: {error}`,agentStatusRefreshed:`Agent status refreshed`,deleteAgentTitle:`Delete Agent`,deleteAgentConfirm:`Are you sure you want to delete agent "{name}"? This action cannot be undone.`,welcomeTitle:`Start a Conversation`,welcomeSubtitle:`Enter your question and the AI assistant will help you`,sendBtnStop:`Stop generating`,sendBtnSend:`Send`,imageNotEnabled:`Image recognition not enabled, image attached as file`,screenshotFailed:`Screenshot failed, please retry`,auditCategoryAuth:`Auth`,auditCategoryFs:`File`,auditCategoryExec:`Command`,auditCategorySecurity:`Security`,auditCategorySystem:`System`,auditDetailSeparator:`; `,auditQueryFailed:`Query failed: {error}`,auditLoadFailed:`Load failed: {error}`,auditNoMatch:`No matching audit logs`,auditEmpty:`No audit logs`,clearStatsConfirm:`Are you sure you want to clear all tool usage stats? This action cannot be undone.`,clearStatsTitle:`Clear Stats`,toolStatsSummary:`Used {used} tools, unused {unused} tools`,toolStatsLoadFailed:`Load failed`,toolNameDescSeparator:`: `}}),window.showCustomConfirm=function(e,t=r(`sidePanel.confirmAction`)){return new Promise(n=>{let r=document.getElementById(`customConfirmOverlay`),i=document.getElementById(`customConfirmTitle`),a=document.getElementById(`customConfirmMessage`),o=document.getElementById(`customConfirmCancelBtn`),s=document.getElementById(`customConfirmOkBtn`);if(!r||!i||!a||!o||!s){n(confirm(e));return}let c=()=>{r.style.display=`none`,s.removeEventListener(`click`,l),o.removeEventListener(`click`,u),r.removeEventListener(`click`,d),document.removeEventListener(`keydown`,f)},l=()=>{c(),n(!0)},u=()=>{c(),n(!1)},d=e=>{e.target===r&&(c(),n(!1))},f=e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),l()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),u())};i.textContent=t,a.innerHTML=e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`).replace(/\n/g,`<br>`),r.style.display=`flex`,s.addEventListener(`click`,l),o.addEventListener(`click`,u),r.addEventListener(`click`,d),document.addEventListener(`keydown`,f),requestAnimationFrame(()=>s.focus())})},chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&e.chatAutoCompaction&&(F.chatConfig.autoCompaction=e.chatAutoCompaction.newValue===!0,sw(),a.debug(`[SidePanel] auto-compaction config updated:`,F.chatConfig.autoCompaction)),t===`local`&&e.chatPersistSummaryToMemory&&(F.chatConfig.persistSummaryToMemory=e.chatPersistSummaryToMemory.newValue!==!1,cw(),a.debug(`[SidePanel] persist-summary config updated:`,F.chatConfig.persistSummaryToMemory)),t===`local`&&e.chatMaxMemoryMessages&&(F.chatConfig.maxMemoryMessages=e.chatMaxMemoryMessages.newValue,ow(),a.debug(`[SidePanel] memory limitconfiguration updated:`,F.chatConfig.maxMemoryMessages))});function ow(){let e=document.getElementById(`memoryLimitLabel`);e&&(F.chatConfig.maxMemoryMessages!==null&&F.chatConfig.maxMemoryMessages!==void 0&&F.chatConfig.maxMemoryMessages>0?e.textContent=F.chatConfig.maxMemoryMessages:e.textContent=r(`sidePanel.memoryLimitAll`),e.title=r(`sidePanel.memoryLimitTitle`))}function sw(){let e=document.getElementById(`autoCompactBtn`);e&&(e.checked=F.chatConfig.autoCompaction===!0)}function cw(){let e=document.getElementById(`persistSummaryBtn`);e&&(e.checked=F.chatConfig.persistSummaryToMemory!==!1)}function lw(e){e.preventDefault(),e.stopPropagation();let t=document.getElementById(`memoryLimitDropdown`);if(t.classList.toggle(`show`),t.classList.contains(`show`)){let e=F.chatConfig.maxMemoryMessages;t.querySelectorAll(`.memory-limit-option`).forEach(t=>{t.classList.remove(`selected`);let n=parseInt(t.dataset.value);(e===null&&n===0||e!==null&&e>0&&n===e)&&t.classList.add(`selected`)});let n=t.querySelector(`#memoryLimitInput`);e!==null&&e>0?n.value=e:n.value=``}}function uw(){let e=document.getElementById(`memoryLimitDropdown`),t=document.getElementById(`memoryLimitLabel`),n=e?.querySelector(`#memoryLimitInput`);if(!e||!t)return;ow(),t.addEventListener(`click`,lw);let i=document.getElementById(`autoCompactBtn`);i&&(i.checked=F.chatConfig.autoCompaction===!0,i.addEventListener(`change`,()=>{let e=i.checked;chrome.storage.local.set({chatAutoCompaction:e},()=>{F.chatConfig.autoCompaction=e,L(r(`sidePanel.configUpdated`),`success`)})}));let a=document.getElementById(`persistSummaryBtn`);a&&(a.checked=F.chatConfig.persistSummaryToMemory!==!1,a.addEventListener(`change`,()=>{let e=a.checked;chrome.storage.local.set({chatPersistSummaryToMemory:e},()=>{F.chatConfig.persistSummaryToMemory=e,L(r(`sidePanel.configUpdated`),`success`)})}));let o=e.querySelectorAll(`.memory-limit-option`);o.forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let i=parseInt(e.dataset.value),a=i===0?null:i;o.forEach(e=>e.classList.remove(`selected`)),e.classList.add(`selected`),n&&(n.value=i===0?``:i),chrome.storage.local.set({chatMaxMemoryMessages:a},()=>{F.chatConfig.maxMemoryMessages=a,ow(),L(r(`sidePanel.configUpdated`),`success`)})})}),n&&(n.addEventListener(`click`,e=>e.stopPropagation()),n.addEventListener(`mousedown`,e=>e.stopPropagation()),n.addEventListener(`change`,e=>{e.stopPropagation();let t=e.target.value.trim(),n=t&&parseInt(t)>0?parseInt(t):null;o.forEach(e=>e.classList.remove(`selected`)),chrome.storage.local.set({chatMaxMemoryMessages:n},()=>{F.chatConfig.maxMemoryMessages=n,ow(),L(r(`sidePanel.configUpdated`),`success`)})})),document.getElementById(`memoryLimitConfigEntry`)?.addEventListener(`click`,()=>{chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`memory`})}),document.addEventListener(`click`,n=>{!e.contains(n.target)&&n.target!==t&&e.classList.remove(`show`)})}async function dw(e){if(F.activeAgentId&&F.activeAgentId!=="default")try{let{updateAgent:t}=await I(async()=>{let{updateAgent:e}=await import(`./agent-store-D-jYf94_.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([0,1,2,3,4]));await t(F.activeAgentId,{model:e})}catch{}else chrome.storage.local.set({modelName:e}),k(e)}async function fw(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=aw(e.pairedAgents),n=e.activeAgentId,r=t.find(e=>e.id===n&&!e.disabled);if(!r){F.agentPlatform={connected:!1},xw(F.agentPlatform);return}if(r.token)try{let e=await fetch(`${r.url}/api/status/detail`,{cache:`no-cache`,headers:{Authorization:`Bearer ${r.token}`}});if(e.ok){let t=await e.json();if(t.success){F.agentPlatform={platformName:t.platformName||`Unknown`,platform:t.platform||`unknown`,arch:t.arch||`unknown`,shell:t.shell||`/bin/sh`,homeDir:t.homeDir||``,workdir:t.workdir||``,connected:!0},t.version&&F.agentVersions.set(n,t.version),t.workdir&&F.agentWorkdirs.set(n,t.workdir),t.homeDir&&F.agentHomeDirs.set(n,t.homeDir);let e=Tw(t.platformName||t.platform,t.arch);e&&F.agentSystemInfos.set(n,e)}else F.agentPlatform={connected:!1}}else F.agentPlatform={connected:!1}}catch{F.agentPlatform={connected:!1}}else F.agentPlatform={connected:!1};xw(F.agentPlatform),Vd()}catch{}}async function pw(e,t,n){if(F.activeAgentId&&F.activeAgentId!=="default")try{let{updateAgent:n}=await I(async()=>{let{updateAgent:e}=await import(`./agent-store-D-jYf94_.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([0,1,2,3,4]));await n(F.activeAgentId,{temperature:e,topP:t})}catch{}else chrome.storage.local.set({temperature:e,topP:t,selectedTempIndex:n})}function mw(){let e=document.getElementById(`currentModelTag`);if(!e)return;let t=F.currentModel||``;e.textContent=t,e.title=t,e.style.display=t?``:`none`}function hw(){let e=document.getElementById(`currentModelTag`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),document.getElementById(`tempDisplay`)?.click()}),mw()}function gw(e){let t=0;document.querySelectorAll(`.model-option`).forEach(n=>{n.dataset.value===e?(n.classList.add(`selected`),n.querySelector(`.model-option-check`).textContent=`✓`,t=parseInt(n.dataset.contextWindow,10)||0):(n.classList.remove(`selected`),n.querySelector(`.model-option-check`).textContent=``)});let n=document.getElementById(`modelSelectValue`);n&&e&&(n.textContent=e);let r=document.getElementById(`modelSelectCtxBadge`);r&&(t>0?(r.textContent=T(t),r.style.display=``):r.style.display=`none`),mw()}function _w(e,t){let n=document.getElementById(`tempDropdown`);if(!n){typeof t==`function`&&t();return}let i=n.querySelector(`.model-section`),a=[];if((Array.isArray(e)?e:[]).forEach(e=>{typeof e==`string`?a.push({name:e,contextWindow:0}):e&&typeof e==`object`&&e.name&&a.push({name:e.name,contextWindow:e.contextWindow||0})}),i){i.innerHTML=`
2540
2540
  <div class="model-section-title" data-i18n="model.selectModel">${r(`model.selectModel`)}</div>
2541
2541
  <div class="section-select" id="modelSelect">
2542
2542
  <div class="section-select-row" id="modelSelectRow">
@@ -2585,7 +2585,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
2585
2585
  </div>
2586
2586
  <h2>${r(`sidePanel.welcomeTitle`)}</h2>
2587
2587
  <p>${r(`sidePanel.welcomeSubtitle`)}</p>
2588
- `,i.appendChild(e)}if(a.debug(`[SidePanel] session-switched: pendingTask?`,l,`pendingSessionIds:`,[...F.pendingCallApiSessionIds],`activeSessionId:`,t,`hasCancelApi:`,!!F.pendingCancelApi),l&&(a.debug(`[SidePanel] switch back tobackground task session,rebuildstreamingoutput element`),Nv(t)),!e.detail?.skipScrollRestore){let e=`scrollPosition_`+(t||`default`);chrome.storage.local.get([e],t=>{t[e]!==void 0&&setTimeout(async()=>{let n=document.getElementById(`chatContainer`);n&&(n.scrollTop=t[e]);let{updateScrollButtonState:r}=await I(async()=>{let{updateScrollButtonState:e}=await Promise.resolve().then(()=>nv);return{updateScrollButtonState:e}},void 0);r()},150)})}}),document.addEventListener(`session-cache-invalidate`,e=>{let{sessionId:t}=e.detail||{};t&&Rw(t)}),document.querySelectorAll(`.model-option`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.value;F.currentModel=n,gw(n),dw(n),zx()})}),document.addEventListener(`agent-model-changed`,()=>{gw(F.currentModel);let e=document.getElementById(`tempSlider`),t=document.getElementById(`tempNumberInput`),n=document.getElementById(`tempIconValue`);e&&(e.value=F.temperature),t&&(t.value=F.temperature.toFixed(2)),n&&(n.textContent=F.temperature.toFixed(2)),y()}),document.addEventListener(`click`,e=>{let t=document.getElementById(`promptDropdown`),n=document.getElementById(`promptSelector`),r=document.getElementById(`agentAtSelector`),i=document.getElementById(`selectionFloatingMenu`);n.contains(e.target)||(t.classList.remove(`show`),Gy()),r&&!r.contains(e.target)&&Yg();let a=document.getElementById(`fileAtSelector`);if(a&&!a.contains(e.target)&&gC(),i&&!i.contains(e.target)){let t=window.getSelection(),n=u.contains(e.target),r=t&&!t.isCollapsed&&u.contains(t.anchorNode);(!n||!r)&&window.hideFloatingMenu()}});function ee(){F.isGenerating?(n.classList.add(`stop-mode`),n.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect></svg>`,n.title=r(`sidePanel.sendBtnStop`),n.disabled=!1):(n.classList.remove(`stop-mode`),n.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8-8-8z"/></svg>`,n.title=r(`sidePanel.sendBtnSend`),n.disabled=!1,n.style.opacity=``,n.style.cursor=``)}n.addEventListener(`click`,()=>{F.isGenerating?Bv(n):gy()}),document.addEventListener(`generating-state-changed`,ee);let te=document.getElementById(`shortcutsBtn`),ne=document.getElementById(`shortcutsModal`),re=document.getElementById(`shortcutsCloseBtn`);function ie(){ne&&(ne.style.display=`flex`)}function j(){ne&&(ne.style.display=`none`)}te&&te.addEventListener(`click`,e=>{e.stopPropagation(),ie();let t=document.getElementById(`headerMoreDropdown`);t&&t.classList.remove(`show`)}),re&&re.addEventListener(`click`,j),ne&&ne.addEventListener(`click`,e=>{e.target===ne&&j()});let ae=rS();document.addEventListener(`keydown`,e=>{if((e.ctrlKey||e.metaKey)&&e.key===`t`){e.preventDefault();let t=document.getElementById(`toolsPopup`);t&&t.style.display!==`none`?wn():Cn()}if(!(e.key===`Escape`&&ae.handleEscape())){if(e.key===`Escape`&&ne&&ne.style.display!==`none`){j();return}if(e.altKey&&e.code===`Slash`){e.preventDefault(),ie();return}if(e.altKey&&!e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Ud();return}if(e.altKey&&e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Wd();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyN`){e.preventDefault(),Oo();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyW`){e.preventDefault(),us();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyE`){e.preventDefault();let t=document.querySelectorAll(`#chatContainer .message.user`),n=t[t.length-1];if(n){zy(n);let e=document.getElementById(`userInput`);e&&e.focus()}return}if(e.altKey&&(e.key===`ArrowUp`||e.key===`ArrowDown`)){e.preventDefault();let t=e.key===`ArrowUp`?`prev`:`next`;ae.jumpToMessage(t,e.ctrlKey||e.metaKey),ae.updateActiveQuestion();return}}}),t.addEventListener(`keydown`,e=>{let n=document.getElementById(`promptSelector`),r=document.getElementById(`promptDropdown`),i=document.getElementById(`agentAtSelector`),a=document.getElementById(`agentAtDropdown`);if(i.style.display!==`none`&&a.classList.contains(`show`)){let t=document.getElementById(`agentAtTabs`),n=t&&t.classList.contains(`merged-mode`);if(!n&&e.key===`Tab`){e.preventDefault();let t=Array.from(document.querySelectorAll(`#agentAtTabs .prompt-tab`)).map(e=>e.dataset.tab),n=e=>{let t=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="${e}"]`);return!!t&&t.style.display!==`none`},r=t.indexOf(Wg);for(let e=0;e<t.length;e++)if(r=(r+1)%t.length,n(t[r])){Zg(t[r]);break}return}let r,i;n?(r=document.getElementById(`agentAtList`),i=F.selectedAgentAtIndex):Wg===`pages`?(r=document.getElementById(`agentPageList`),i=F.selectedPageIndex):Wg===`proxies`?(r=document.getElementById(`agentProxyList`),i=F.selectedProxyAtIndex):Wg===`knowledge`?(r=document.getElementById(`agentKnowledgeList`),i=F.selectedKnowledgeAtIndex):(r=document.getElementById(`agentAtList`),i=F.selectedAgentAtIndex);let a=r?r.querySelectorAll(`.prompt-item`):[],o=a.length;if(o!==0){if(e.key===`ArrowDown`){e.preventDefault();let t=i<0?0:(i+1)%o;n?(F.selectedAgentAtIndex=t,d_(a)):Wg===`proxies`?(F.selectedProxyAtIndex=t,d_(a)):Wg===`knowledge`?(F.selectedKnowledgeAtIndex=t,d_(a)):Wg===`pages`?(F.selectedPageIndex=t,M_(a)):(F.selectedAgentAtIndex=t,d_(a));return}else if(e.key===`ArrowUp`){e.preventDefault();let t=i<0||i===0?o-1:i-1;n?(F.selectedAgentAtIndex=t,d_(a)):Wg===`proxies`?(F.selectedProxyAtIndex=t,d_(a)):Wg===`knowledge`?(F.selectedKnowledgeAtIndex=t,d_(a)):Wg===`pages`?(F.selectedPageIndex=t,M_(a)):(F.selectedAgentAtIndex=t,d_(a));return}else if(e.key===`Enter`&&i>=0){e.preventDefault(),a[i].click(),(e.ctrlKey||e.metaKey)&&Yg();return}else if(e.key===`Escape`){Yg();return}}}let o=document.getElementById(`fileAtSelector`),s=document.getElementById(`fileAtDropdown`);if(o&&s&&o.style.display!==`none`&&s.classList.contains(`show`)){let t=document.getElementById(`fileAtList`),n=t?t.querySelectorAll(`.prompt-item`):[],r=n.length;if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),r>0&&(F.selectedFileAtIndex=e.key===`ArrowDown`?F.selectedFileAtIndex<0?0:(F.selectedFileAtIndex+1)%r:F.selectedFileAtIndex<0||F.selectedFileAtIndex===0?r-1:F.selectedFileAtIndex-1,xC(n));return}if(e.key===`Enter`&&r>0&&F.selectedFileAtIndex>=0){e.preventDefault(),n[F.selectedFileAtIndex].click();return}if(e.key===`Escape`){e.preventDefault(),gC();return}}if(n.style.display!==`none`&&r.classList.contains(`show`)){if(F.showMergedList){let t=r.querySelectorAll(`#promptList .prompt-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),F.selectedPromptIndex<0?F.selectedPromptIndex=0:F.selectedPromptIndex=(F.selectedPromptIndex+1)%n,Xy(t);return}if(e.key===`ArrowUp`){e.preventDefault(),F.selectedPromptIndex<0||F.selectedPromptIndex===0?F.selectedPromptIndex=n-1:--F.selectedPromptIndex,Xy(t);return}if(e.key===`Enter`&&F.selectedPromptIndex>=0){e.preventDefault();let n=t[F.selectedPromptIndex];n.dataset.type===`skill`||n.dataset.type===`mcp`?(n.click(),(e.ctrlKey||e.metaKey)&&Gy()):e.ctrlKey||e.metaKey?Zy(n.dataset.code):Qy(n.dataset.code);return}if(e.key===`Escape`){Gy();return}return}if(F.activeDropdownTab===`skills`){let t=r.querySelectorAll(`#skillList .skill-list-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),F.selectedSkillIndex<0?F.selectedSkillIndex=0:F.selectedSkillIndex=(F.selectedSkillIndex+1)%n,vb(t);return}if(e.key===`ArrowUp`){e.preventDefault(),F.selectedSkillIndex<0||F.selectedSkillIndex===0?F.selectedSkillIndex=n-1:--F.selectedSkillIndex,vb(t);return}if(e.key===`Enter`&&F.selectedSkillIndex>=0){e.preventDefault(),t[F.selectedSkillIndex].click(),(e.ctrlKey||e.metaKey)&&Gy();return}if(e.key===`Escape`){Gy();return}if(e.key===`Tab`){e.preventDefault();let t=document.getElementById(`mcpTab`);t&&t.style.display!==`none`?Tb(`mcp`):Tb(`prompts`);return}return}if(F.activeDropdownTab===`mcp`){let t=r.querySelectorAll(`#mcpList .mcp-list-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),F.selectedMcpServiceIndex<0?F.selectedMcpServiceIndex=0:F.selectedMcpServiceIndex=(F.selectedMcpServiceIndex+1)%n,Mb(t);return}if(e.key===`ArrowUp`){e.preventDefault(),F.selectedMcpServiceIndex<0||F.selectedMcpServiceIndex===0?F.selectedMcpServiceIndex=n-1:--F.selectedMcpServiceIndex,Mb(t);return}if(e.key===`Enter`&&F.selectedMcpServiceIndex>=0){e.preventDefault(),t[F.selectedMcpServiceIndex].click(),(e.ctrlKey||e.metaKey)&&Gy();return}if(e.key===`Escape`){Gy();return}if(e.key===`Tab`){e.preventDefault(),Tb(`prompts`);return}return}let t=r.querySelectorAll(`#promptList .prompt-item`),n=t.length;if(e.key===`Tab`){let t=document.getElementById(`skillsTab`),n=document.getElementById(`mcpTab`);if(t&&t.style.display!==`none`){e.preventDefault(),Tb(`skills`);return}if(n&&n.style.display!==`none`){e.preventDefault(),Tb(`mcp`);return}}if(n!==0&&e.key===`ArrowDown`){e.preventDefault(),F.selectedPromptIndex<0?F.selectedPromptIndex=0:F.selectedPromptIndex=(F.selectedPromptIndex+1)%n,Xy(t);return}if(e.key===`ArrowUp`){e.preventDefault(),F.selectedPromptIndex<0||F.selectedPromptIndex===0?F.selectedPromptIndex=n-1:--F.selectedPromptIndex,Xy(t);return}if(e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&F.selectedPromptIndex>=0){e.preventDefault();let n=t[F.selectedPromptIndex].dataset.code;Zy(n);return}if(e.key===`Enter`&&F.selectedPromptIndex>=0){e.preventDefault();let n=t[F.selectedPromptIndex].dataset.code;Qy(n);return}if(e.key===`Escape`){Gy();return}}if(e.key===`Escape`){F.inputHistoryIndex>=0&&(F.inputHistoryIndex=-1),t.value&&(t.value=``,t.style.height=`auto`,t.dispatchEvent(new Event(`input`))),e.preventDefault();return}let c=n.style.display!==`none`&&r.classList.contains(`show`),l=i.style.display!==`none`&&a.classList.contains(`show`),u=o.style.display!==`none`&&s.classList.contains(`show`);if(!c&&!l&&!u&&!F.isGenerating){if(e.key===`ArrowUp`){e.preventDefault(),F.inputHistoryIndex===-1?F.inputHistoryIndex=F.inputHistory.length-1:F.inputHistoryIndex>0&&F.inputHistoryIndex--,F.inputHistoryIndex<0&&(F.inputHistoryIndex=0),F.inputHistoryIndex>=0&&F.inputHistory.length>0&&(t.value=F.inputHistory[F.inputHistoryIndex],t.dispatchEvent(new Event(`input`)));return}if(e.key===`ArrowDown`){e.preventDefault(),F.inputHistoryIndex>=0&&F.inputHistoryIndex<F.inputHistory.length-1?(F.inputHistoryIndex++,t.value=F.inputHistory[F.inputHistoryIndex],t.dispatchEvent(new Event(`input`))):(F.inputHistoryIndex=-1,t.value=``,t.dispatchEvent(new Event(`input`)));return}}if(e.key===`Enter`&&!e.shiftKey){if(F.isComposing)return;e.preventDefault(),gC(),gy()}}),t.addEventListener(`compositionstart`,()=>{F.isComposing=!0}),t.addEventListener(`compositionend`,()=>{F.isComposing=!1}),t.addEventListener(`paste`,e=>{let t=e.clipboardData?.items;if(t)for(let n of t){if(n.type.startsWith(`image/`)&&F.enableImageInput){e.preventDefault();let t=n.getAsFile();t&&Kl(t);break}if(n.kind===`file`&&F.enableFileInput){e.preventDefault();let t=n.getAsFile();t&&Mu([t]);break}}});let oe=document.getElementById(`fileAttachBtn`),se=document.getElementById(`fileInput`);oe&&se&&(oe.addEventListener(`click`,()=>{se.click()}),se.addEventListener(`change`,async()=>{if(se.files.length>0){let e=Array.from(se.files),t=e.filter(e=>e.type.startsWith(`image/`)),n=e.filter(e=>!e.type.startsWith(`image/`));if(t.length>0)if(F.enableImageInput)for(let e of t)await Kl(e);else L(r(`sidePanel.imageNotEnabled`)),Mu(t);n.length>0&&Mu(n),se.value=``}}));let ce=document.querySelector(`.input-wrapper`),le=0;ce&&(ce.addEventListener(`dragenter`,e=>{e.preventDefault(),e.stopPropagation(),le++,ce.classList.add(`drag-over`)}),ce.addEventListener(`dragleave`,e=>{e.preventDefault(),e.stopPropagation(),le--,le<=0&&(le=0,ce.classList.remove(`drag-over`))}),ce.addEventListener(`dragover`,e=>{e.preventDefault(),e.stopPropagation()}),ce.addEventListener(`drop`,async e=>{e.stopPropagation(),le=0,ce.classList.remove(`drag-over`);let n=e.dataTransfer.getData(`application/x-workspace-file`);if(n){e.preventDefault();try{let{path:e}=JSON.parse(n);if(e){Jh([e]);return}}catch(e){a.warn(`[SidePanel] parse workspace dragdata failed:`,e)}}let i=Array.from(e.dataTransfer.files);if(i.length>0){e.preventDefault();let t=i.filter(e=>e.type.startsWith(`image/`)),n=i.filter(e=>!e.type.startsWith(`image/`));if(t.length>0)if(F.enableImageInput)for(let e of t)await Kl(e);else L(r(`sidePanel.imageNotEnabled`)),Mu(t);n.length>0&&Mu(n);return}let o=e.dataTransfer.getData(`text/plain`);if(o&&(e.preventDefault(),t)){t.focus();let e=t.selectionStart??t.value.length,n=t.selectionEnd??t.value.length;t.value=t.value.slice(0,e)+o+t.value.slice(n),t.selectionStart=t.selectionEnd=e+o.length,t.dispatchEvent(new Event(`input`))}}));let ue=document.getElementById(`screenshotBtn`);ue&&ue.addEventListener(`click`,async()=>{if(F.enableImageInput)try{await Ud()}catch(e){a.error(`[SidePanel] screenshot failed:`,e),L(r(`sidePanel.screenshotFailed`))}}),Wl(),t.addEventListener(`wheel`,e=>{F.isScrolling=!0;let n=t.style.height||t.offsetHeight+`px`;t.style.height=n,t.scrollHeight<=t.clientHeight+10&&(e.preventDefault(),e.stopPropagation()),setTimeout(()=>{F.isScrolling=!1},100)},{passive:!1}),t.addEventListener(`input`,e=>{let n=t.value,r=document.getElementById(`promptSelector`),i=document.getElementById(`promptDropdown`);document.getElementById(`agentAtSelector`),document.getElementById(`agentAtDropdown`);let a=n.lastIndexOf(`/`),o=n.lastIndexOf(`@`),s=n.lastIndexOf(`$`),c=e=>{if(e===-1||e!==0&&n[e-1]!==`
2588
+ `,i.appendChild(e)}if(a.debug(`[SidePanel] session-switched: pendingTask?`,l,`pendingSessionIds:`,[...F.pendingCallApiSessionIds],`activeSessionId:`,t,`hasCancelApi:`,!!F.pendingCancelApi),l&&(a.debug(`[SidePanel] switch back tobackground task session,rebuildstreamingoutput element`),Nv(t)),!e.detail?.skipScrollRestore){let e=`scrollPosition_`+(t||`default`);chrome.storage.local.get([e],t=>{t[e]!==void 0&&setTimeout(async()=>{let n=document.getElementById(`chatContainer`);n&&(n.scrollTop=t[e]);let{updateScrollButtonState:r}=await I(async()=>{let{updateScrollButtonState:e}=await Promise.resolve().then(()=>nv);return{updateScrollButtonState:e}},void 0);r()},150)})}}),document.addEventListener(`session-cache-invalidate`,e=>{let{sessionId:t}=e.detail||{};t&&Rw(t)}),document.querySelectorAll(`.model-option`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.value;F.currentModel=n,gw(n),dw(n),zx()})}),document.addEventListener(`agent-model-changed`,()=>{gw(F.currentModel);let e=document.getElementById(`tempSlider`),t=document.getElementById(`tempNumberInput`),n=document.getElementById(`tempIconValue`);e&&(e.value=F.temperature),t&&(t.value=F.temperature.toFixed(2)),n&&(n.textContent=F.temperature.toFixed(2)),y()}),document.addEventListener(`click`,e=>{let t=document.getElementById(`promptDropdown`),n=document.getElementById(`promptSelector`),r=document.getElementById(`agentAtSelector`),i=document.getElementById(`selectionFloatingMenu`);n.contains(e.target)||(t.classList.remove(`show`),Gy()),r&&!r.contains(e.target)&&Yg();let a=document.getElementById(`fileAtSelector`);if(a&&!a.contains(e.target)&&gC(),i&&!i.contains(e.target)){let t=window.getSelection(),n=u.contains(e.target),r=t&&!t.isCollapsed&&u.contains(t.anchorNode);(!n||!r)&&window.hideFloatingMenu()}});function ee(){F.isGenerating?(n.classList.add(`stop-mode`),n.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect></svg>`,n.title=r(`sidePanel.sendBtnStop`),n.disabled=!1):(n.classList.remove(`stop-mode`),n.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8-8-8z"/></svg>`,n.title=r(`sidePanel.sendBtnSend`),n.disabled=!1,n.style.opacity=``,n.style.cursor=``)}n.addEventListener(`click`,()=>{F.isGenerating?Bv(n):gy()}),document.addEventListener(`generating-state-changed`,ee);let te=document.getElementById(`shortcutsBtn`),ne=document.getElementById(`shortcutsModal`),re=document.getElementById(`shortcutsCloseBtn`);function ie(){ne&&(ne.style.display=`flex`)}function j(){ne&&(ne.style.display=`none`)}te&&te.addEventListener(`click`,e=>{e.stopPropagation(),ie();let t=document.getElementById(`headerMoreDropdown`);t&&t.classList.remove(`show`)}),re&&re.addEventListener(`click`,j),ne&&ne.addEventListener(`click`,e=>{e.target===ne&&j()});let ae=rS();document.addEventListener(`keydown`,e=>{if((e.ctrlKey||e.metaKey)&&e.key===`t`){e.preventDefault();let t=document.getElementById(`toolsPopup`);t&&t.style.display!==`none`?wn():Cn()}if(!(e.key===`Escape`&&ae.handleEscape())){if(e.key===`Escape`&&ne&&ne.style.display!==`none`){j();return}if(e.altKey&&e.code===`Slash`){e.preventDefault(),ie();return}if(e.altKey&&!e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Ud();return}if(e.altKey&&e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Wd();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyN`){e.preventDefault(),Oo();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyW`){e.preventDefault(),us();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyE`){e.preventDefault();let t=document.querySelectorAll(`#chatContainer .message.user`),n=t[t.length-1];if(n){zy(n);let e=document.getElementById(`userInput`);e&&e.focus()}return}if(e.altKey&&(e.key===`ArrowUp`||e.key===`ArrowDown`)){e.preventDefault();let t=e.key===`ArrowUp`?`prev`:`next`;ae.jumpToMessage(t,e.ctrlKey||e.metaKey),ae.updateActiveQuestion();return}}}),t.addEventListener(`keydown`,e=>{let n=document.getElementById(`promptSelector`),r=document.getElementById(`promptDropdown`),i=document.getElementById(`agentAtSelector`),a=document.getElementById(`agentAtDropdown`);if(i.style.display!==`none`&&a.classList.contains(`show`)){let t=document.getElementById(`agentAtTabs`),n=t&&t.classList.contains(`merged-mode`);if(!n&&e.key===`Tab`){e.preventDefault();let t=Array.from(document.querySelectorAll(`#agentAtTabs .prompt-tab`)).map(e=>e.dataset.tab),n=e=>{let t=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="${e}"]`);return!!t&&t.style.display!==`none`},r=t.indexOf(Wg);for(let e=0;e<t.length;e++)if(r=(r+1)%t.length,n(t[r])){Zg(t[r]);break}return}let r,i;n?(r=document.getElementById(`agentAtList`),i=F.selectedAgentAtIndex):Wg===`pages`?(r=document.getElementById(`agentPageList`),i=F.selectedPageIndex):Wg===`proxies`?(r=document.getElementById(`agentProxyList`),i=F.selectedProxyAtIndex):Wg===`knowledge`?(r=document.getElementById(`agentKnowledgeList`),i=F.selectedKnowledgeAtIndex):(r=document.getElementById(`agentAtList`),i=F.selectedAgentAtIndex);let a=r?r.querySelectorAll(`.prompt-item`):[],o=a.length;if(o!==0){if(e.key===`ArrowDown`){e.preventDefault();let t=i<0?0:(i+1)%o;n?(F.selectedAgentAtIndex=t,d_(a)):Wg===`proxies`?(F.selectedProxyAtIndex=t,d_(a)):Wg===`knowledge`?(F.selectedKnowledgeAtIndex=t,d_(a)):Wg===`pages`?(F.selectedPageIndex=t,M_(a)):(F.selectedAgentAtIndex=t,d_(a));return}else if(e.key===`ArrowUp`){e.preventDefault();let t=i<0||i===0?o-1:i-1;n?(F.selectedAgentAtIndex=t,d_(a)):Wg===`proxies`?(F.selectedProxyAtIndex=t,d_(a)):Wg===`knowledge`?(F.selectedKnowledgeAtIndex=t,d_(a)):Wg===`pages`?(F.selectedPageIndex=t,M_(a)):(F.selectedAgentAtIndex=t,d_(a));return}else if(e.key===`Enter`&&i>=0){e.preventDefault(),a[i].click(),(e.ctrlKey||e.metaKey)&&Yg();return}else if(e.key===`Escape`){Yg();return}}}let o=document.getElementById(`fileAtSelector`),s=document.getElementById(`fileAtDropdown`);if(o&&s&&o.style.display!==`none`&&s.classList.contains(`show`)){let t=document.getElementById(`fileAtList`),n=t?t.querySelectorAll(`.prompt-item`):[],r=n.length;if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),r>0&&(F.selectedFileAtIndex=e.key===`ArrowDown`?F.selectedFileAtIndex<0?0:(F.selectedFileAtIndex+1)%r:F.selectedFileAtIndex<0||F.selectedFileAtIndex===0?r-1:F.selectedFileAtIndex-1,xC(n));return}if(e.key===`Enter`&&r>0&&F.selectedFileAtIndex>=0){e.preventDefault(),n[F.selectedFileAtIndex].click();return}if(e.key===`Escape`){e.preventDefault(),gC();return}}if(n.style.display!==`none`&&r.classList.contains(`show`)){if(F.showMergedList){let t=r.querySelectorAll(`#promptList .prompt-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),F.selectedPromptIndex<0?F.selectedPromptIndex=0:F.selectedPromptIndex=(F.selectedPromptIndex+1)%n,Xy(t);return}if(e.key===`ArrowUp`){e.preventDefault(),F.selectedPromptIndex<0||F.selectedPromptIndex===0?F.selectedPromptIndex=n-1:--F.selectedPromptIndex,Xy(t);return}if(e.key===`Enter`&&F.selectedPromptIndex>=0){e.preventDefault();let n=t[F.selectedPromptIndex];n.dataset.type===`skill`||n.dataset.type===`mcp`?(n.click(),(e.ctrlKey||e.metaKey)&&Gy()):e.ctrlKey||e.metaKey?Zy(n.dataset.code):Qy(n.dataset.code);return}if(e.key===`Escape`){Gy();return}return}if(F.activeDropdownTab===`skills`){let t=r.querySelectorAll(`#skillList .skill-list-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),F.selectedSkillIndex<0?F.selectedSkillIndex=0:F.selectedSkillIndex=(F.selectedSkillIndex+1)%n,vb(t);return}if(e.key===`ArrowUp`){e.preventDefault(),F.selectedSkillIndex<0||F.selectedSkillIndex===0?F.selectedSkillIndex=n-1:--F.selectedSkillIndex,vb(t);return}if(e.key===`Enter`&&F.selectedSkillIndex>=0){e.preventDefault(),t[F.selectedSkillIndex].click(),(e.ctrlKey||e.metaKey)&&Gy();return}if(e.key===`Escape`){Gy();return}if(e.key===`Tab`){e.preventDefault();let t=document.getElementById(`mcpTab`);t&&t.style.display!==`none`?Tb(`mcp`):Tb(`prompts`);return}return}if(F.activeDropdownTab===`mcp`){let t=r.querySelectorAll(`#mcpList .mcp-list-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),F.selectedMcpServiceIndex<0?F.selectedMcpServiceIndex=0:F.selectedMcpServiceIndex=(F.selectedMcpServiceIndex+1)%n,Mb(t);return}if(e.key===`ArrowUp`){e.preventDefault(),F.selectedMcpServiceIndex<0||F.selectedMcpServiceIndex===0?F.selectedMcpServiceIndex=n-1:--F.selectedMcpServiceIndex,Mb(t);return}if(e.key===`Enter`&&F.selectedMcpServiceIndex>=0){e.preventDefault(),t[F.selectedMcpServiceIndex].click(),(e.ctrlKey||e.metaKey)&&Gy();return}if(e.key===`Escape`){Gy();return}if(e.key===`Tab`){e.preventDefault(),Tb(`prompts`);return}return}let t=r.querySelectorAll(`#promptList .prompt-item`),n=t.length;if(e.key===`Tab`){let t=document.getElementById(`skillsTab`),n=document.getElementById(`mcpTab`);if(t&&t.style.display!==`none`){e.preventDefault(),Tb(`skills`);return}if(n&&n.style.display!==`none`){e.preventDefault(),Tb(`mcp`);return}}if(n!==0&&e.key===`ArrowDown`){e.preventDefault(),F.selectedPromptIndex<0?F.selectedPromptIndex=0:F.selectedPromptIndex=(F.selectedPromptIndex+1)%n,Xy(t);return}if(e.key===`ArrowUp`){e.preventDefault(),F.selectedPromptIndex<0||F.selectedPromptIndex===0?F.selectedPromptIndex=n-1:--F.selectedPromptIndex,Xy(t);return}if(e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&F.selectedPromptIndex>=0){e.preventDefault();let n=t[F.selectedPromptIndex].dataset.code;Zy(n);return}if(e.key===`Enter`&&F.selectedPromptIndex>=0){e.preventDefault();let n=t[F.selectedPromptIndex].dataset.code;Qy(n);return}if(e.key===`Escape`){Gy();return}}if(e.key===`Escape`){F.inputHistoryIndex>=0&&(F.inputHistoryIndex=-1),t.value&&(t.value=``,t.style.height=`auto`,t.dispatchEvent(new Event(`input`))),e.preventDefault();return}let c=n.style.display!==`none`&&r.classList.contains(`show`),l=i.style.display!==`none`&&a.classList.contains(`show`),u=o.style.display!==`none`&&s.classList.contains(`show`);if(!c&&!l&&!u&&!F.isGenerating){if(e.key===`ArrowUp`){e.preventDefault(),F.inputHistoryIndex===-1?F.inputHistoryIndex=F.inputHistory.length-1:F.inputHistoryIndex>0&&F.inputHistoryIndex--,F.inputHistoryIndex<0&&(F.inputHistoryIndex=0),F.inputHistoryIndex>=0&&F.inputHistory.length>0&&(t.value=F.inputHistory[F.inputHistoryIndex],t.dispatchEvent(new Event(`input`)));return}if(e.key===`ArrowDown`){e.preventDefault(),F.inputHistoryIndex>=0&&F.inputHistoryIndex<F.inputHistory.length-1?(F.inputHistoryIndex++,t.value=F.inputHistory[F.inputHistoryIndex],t.dispatchEvent(new Event(`input`))):(F.inputHistoryIndex=-1,t.value=``,t.dispatchEvent(new Event(`input`)));return}}if(e.key===`Enter`&&!e.shiftKey){if(F.isComposing)return;e.preventDefault(),gC(),gy()}}),t.addEventListener(`compositionstart`,()=>{F.isComposing=!0}),t.addEventListener(`compositionend`,()=>{F.isComposing=!1}),t.addEventListener(`paste`,e=>{let t=e.clipboardData?.items;if(t)for(let n of t){if(n.type.startsWith(`image/`)&&F.enableImageInput){e.preventDefault();let t=n.getAsFile();t&&Kl(t);break}if(n.kind===`file`&&F.enableFileInput){e.preventDefault();let t=n.getAsFile();t&&Mu([t]);break}}});let oe=document.getElementById(`fileAttachBtn`),se=document.getElementById(`fileInput`);oe&&se&&(oe.addEventListener(`click`,()=>{se.click()}),se.addEventListener(`change`,async()=>{if(se.files.length>0){let e=Array.from(se.files),t=e.filter(e=>e.type.startsWith(`image/`)),n=e.filter(e=>!e.type.startsWith(`image/`));if(t.length>0)if(F.enableImageInput)for(let e of t)await Kl(e);else L(r(`sidePanel.imageNotEnabled`)),Mu(t);n.length>0&&Mu(n),se.value=``}}));let ce=document.querySelector(`.input-wrapper`),le=0;ce&&(ce.addEventListener(`dragenter`,e=>{e.preventDefault(),e.stopPropagation(),le++,ce.classList.add(`drag-over`)}),ce.addEventListener(`dragleave`,e=>{e.preventDefault(),e.stopPropagation(),le--,le<=0&&(le=0,ce.classList.remove(`drag-over`))}),ce.addEventListener(`dragover`,e=>{e.preventDefault(),e.stopPropagation()}),ce.addEventListener(`drop`,async e=>{e.preventDefault(),e.stopPropagation(),le=0,ce.classList.remove(`drag-over`);let n=e.dataTransfer.getData(`application/x-workspace-file`);if(n){e.preventDefault();try{let{path:e}=JSON.parse(n);if(e){Jh([e]);return}}catch(e){a.warn(`[SidePanel] parse workspace dragdata failed:`,e)}}let i=Array.from(e.dataTransfer.files);if(i.length>0){e.preventDefault();let t=i.filter(e=>e.type.startsWith(`image/`)),n=i.filter(e=>!e.type.startsWith(`image/`));if(t.length>0)if(F.enableImageInput)for(let e of t)await Kl(e);else L(r(`sidePanel.imageNotEnabled`)),Mu(t);n.length>0&&Mu(n);return}let o=e.dataTransfer.getData(`text/plain`);if(o&&(e.preventDefault(),t)){t.focus();let e=t.selectionStart??t.value.length,n=t.selectionEnd??t.value.length;t.value=t.value.slice(0,e)+o+t.value.slice(n),t.selectionStart=t.selectionEnd=e+o.length,t.dispatchEvent(new Event(`input`))}}));let ue=document.getElementById(`screenshotBtn`);ue&&ue.addEventListener(`click`,async()=>{if(F.enableImageInput)try{await Ud()}catch(e){a.error(`[SidePanel] screenshot failed:`,e),L(r(`sidePanel.screenshotFailed`))}}),Wl(),t.addEventListener(`wheel`,e=>{F.isScrolling=!0;let n=t.style.height||t.offsetHeight+`px`;t.style.height=n,t.scrollHeight<=t.clientHeight+10&&(e.preventDefault(),e.stopPropagation()),setTimeout(()=>{F.isScrolling=!1},100)},{passive:!1}),t.addEventListener(`input`,e=>{let n=t.value,r=document.getElementById(`promptSelector`),i=document.getElementById(`promptDropdown`);document.getElementById(`agentAtSelector`),document.getElementById(`agentAtDropdown`);let a=n.lastIndexOf(`/`),o=n.lastIndexOf(`@`),s=n.lastIndexOf(`$`),c=e=>{if(e===-1||e!==0&&n[e-1]!==`
2589
2589
  `&&n[e-1]!==` `)return!1;let t=n.substring(e+1);return!(t.includes(` `)||t.includes(`
2590
2590
  `))},l=c(a),u=c(o),d=c(s),f=null;if(l&&(f={key:`slash`,index:a}),u&&(!f||o>f.index)&&(f={key:`at`,index:o}),d&&(!f||s>f.index)&&(f={key:`dollar`,index:s}),f&&f.key===`dollar`)Gy(),Yg(),hC(n.substring(s+1));else if(f&&f.key===`at`)Gy(),gC(),qg(n.substring(o+1));else if(f&&f.key===`slash`){Yg(),gC();let e=n.substring(a+1);r.style.display!==`none`&&i.classList.contains(`show`)?qy(e):Wy(e)}else Gy(),Yg(),gC();g()});let de=rw((e,t)=>{chrome.storage.local.set({[e]:t})},200);u.addEventListener(`scroll`,()=>{de(`scrollPosition_`+(F.activeSessionId||`default`),u.scrollTop)}),window.addEventListener(`pagehide`,()=>{chrome.storage.local.set({[`scrollPosition_`+(F.activeSessionId||`default`)]:u.scrollTop})});let fe=document.getElementById(`headerMoreBtn`),pe=document.getElementById(`headerMoreDropdown`);fe&&pe&&(fe.addEventListener(`click`,e=>{e.stopPropagation(),pe.classList.toggle(`show`)}),document.addEventListener(`click`,e=>{!pe.contains(e.target)&&e.target!==fe&&ge()}));let M=document.getElementById(`themeToggleBtn`),me=document.getElementById(`themeToggleLabel`),N=document.getElementById(`themeSubmenu`),he=e=>r(e===`dark`?`settings.themeDark`:e===`system`?`settings.themeSystem`:`settings.themeLight`),P=()=>{let e=Be();me&&(me.textContent=r(`header.themeToggle`,{theme:he(e)})),N&&N.querySelectorAll(`.theme-submenu-item`).forEach(t=>{t.classList.toggle(`active`,t.dataset.themeValue===e)}),M&&M.setAttribute(`aria-expanded`,String(!!(N&&N.classList.contains(`show`))))};function ge(){N&&N.classList.remove(`show`),pe&&pe.classList.remove(`show`),M&&M.setAttribute(`aria-expanded`,`false`)}M&&N&&(M.addEventListener(`click`,e=>{e.stopPropagation(),N.classList.toggle(`show`),P()}),N.querySelectorAll(`.theme-submenu-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),Ie(e.dataset.themeValue),ge()})})),P(),ze(P),c(P),s.addEventListener(`click`,e=>{e.stopPropagation(),ge(),ty()}),l&&l.addEventListener(`click`,e=>{e.stopPropagation(),ge(),il()});let _e=document.getElementById(`importChatBtn`);_e&&_e.addEventListener(`click`,e=>{e.stopPropagation(),ge(),ll()});let ve=document.getElementById(`importSessionsFile`);ve&&ve.addEventListener(`change`,e=>{let t=e.target.files[0];t&&ul(t)});let ye=document.getElementById(`settingsBtn`);ye&&ye.addEventListener(`click`,()=>{chrome.runtime.openOptionsPage()});let be=document.getElementById(`headerAgentIndicator`);be&&be.addEventListener(`click`,async()=>{let e=chrome.runtime.getURL(`options.html#agent`),t=await chrome.tabs.query({url:chrome.runtime.getURL(`options.html`)});t.length>0?await chrome.tabs.update(t[0].id,{active:!0,url:e}):await chrome.tabs.create({url:e})});let xe=document.getElementById(`prototypeLibraryBtn`);xe&&xe.addEventListener(`click`,e=>{e.stopPropagation(),ge(),As()});let Se=document.getElementById(`tokenStatsHeaderBtn`);Se&&Se.addEventListener(`click`,e=>{e.stopPropagation(),ge(),window.openTokenStats&&window.openTokenStats()});let Ce=document.getElementById(`auditLogBtn`),we=document.getElementById(`auditLogOverlay`),Te=document.getElementById(`auditLogClose`),Ee=document.getElementById(`auditLogRefreshBtn`),De=document.getElementById(`auditLogCategoryFilter`),Oe=document.getElementById(`auditLogLimit`),ke=document.getElementById(`auditLogSearch`),Ae=document.getElementById(`auditLogSearchClear`),je=document.getElementById(`auditLogLoading`),Me=document.getElementById(`auditLogEmpty`),Ne=document.getElementById(`auditLogList`),Pe=[],Fe={auth:r(`sidePanel.auditCategoryAuth`),fs:r(`sidePanel.auditCategoryFs`),exec:r(`sidePanel.auditCategoryExec`),security:r(`sidePanel.auditCategorySecurity`),system:r(`sidePanel.auditCategorySystem`)},Re={info:`INFO`,warn:`WARN`,error:`ERROR`},Ve={info:`audit-level-info`,warn:`audit-level-warn`,error:`audit-level-error`};function He(e){if(!e)return`-`;let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Ue(e){let t=new Set([`timestamp`,`level`,`category`,`action`]),n=[];for(let[r,i]of Object.entries(e)){if(t.has(r))continue;let e=typeof i==`string`?i:JSON.stringify(i),a=e.length>60?e.slice(0,60)+`...`:e;n.push(`${r}: ${a}`)}return n.join(r(`sidePanel.auditDetailSeparator`))}async function We(){if(!je||!Me||!Ne)return;je.style.display=`block`,Me.style.display=`none`,Ne.style.display=`none`;let e=De?.value||null,t=parseInt(Oe?.value||`200`,10);try{let n=await new Promise((n,r)=>{chrome.runtime.sendMessage({type:`QUERY_AUDIT_LOGS`,category:e,limit:t},e=>{chrome.runtime.lastError?r(Error(chrome.runtime.lastError.message)):n(e)})});if(je.style.display=`none`,!n||!n.success){Me.style.display=`block`,Me.textContent=r(`sidePanel.auditQueryFailed`,{error:n?.error||r(`sidePanel.unknownError`)});return}Pe=n.entries||[],Ge()}catch(e){je.style.display=`none`,Me.style.display=`block`,Me.textContent=r(`sidePanel.auditLoadFailed`,{error:e.message})}}function Ge(){if(!Ne)return;let e=(ke?.value||``).trim().toLowerCase(),t=Pe;if(e&&(t=t.filter(t=>[t.action||``,t.category||``,...Object.entries(t).filter(([e])=>![`timestamp`,`level`,`category`,`action`].includes(e)).map(([,e])=>typeof e==`string`?e:JSON.stringify(e))].join(` `).toLowerCase().includes(e))),Ae&&(Ae.style.display=e?`block`:`none`),je.style.display=`none`,t.length===0){Me.style.display=`block`,Me.textContent=r(e?`sidePanel.auditNoMatch`:`sidePanel.auditEmpty`),Ne.style.display=`none`;return}Me.style.display=`none`,Ne.style.display=`block`,Ne.innerHTML=t.map(e=>{let t=R(Fe[e.category]||e.category||`-`),n=R(Re[e.level]||e.level?.toUpperCase()||`INFO`),r=Ve[e.level]||`audit-level-info`,i=He(e.timestamp),a=R(Ue(e));return`<div class="audit-entry">
2591
2591
  <div class="audit-entry-header">
@@ -2595,7 +2595,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
2595
2595
  <span class="audit-action">${R(e.action||`-`)}</span>
2596
2596
  </div>
2597
2597
  ${a?`<div class="audit-details">${a}</div>`:``}
2598
- </div>`}).join(``)}function Ke(){we&&(we.style.display=`flex`,We())}function qe(){we&&(we.style.display=`none`)}Ce&&Ce.addEventListener(`click`,e=>{e.stopPropagation(),ge(),Ke()}),Te&&Te.addEventListener(`click`,qe),Ee&&Ee.addEventListener(`click`,We),De&&De.addEventListener(`change`,We),Oe&&Oe.addEventListener(`change`,We),ke&&ke.addEventListener(`input`,()=>{Ge()}),Ae&&Ae.addEventListener(`click`,()=>{ke&&(ke.value=``),Ge()}),iw(()=>F.activeSessionId,showCustomConfirm);let Je=document.getElementById(`isolateChatBtn`),Ye=document.getElementById(`enableToolsBtn`),Ze=document.getElementById(`toolsConfigBtn`),Qe=`agentEnabledTools_${F.activeAgentId||`default`}`,$e=`agentMcpClosedServers_${F.activeAgentId||`default`}`;chrome.storage.local.get([Qe,`enabledTools`,`isolateChat`,`enableSelectionQuery`,`enableTools`,$e,`mcpTools`,`mcpEnabled`,`ragTools`,`ragToolsIntroduced`],e=>{e.isolateChat!==void 0&&(F.isolateChat=e.isolateChat),Je.checked=F.isolateChat,e.enableSelectionQuery!==void 0&&(F.enableSelectionQuery=e.enableSelectionQuery);let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=F.enableSelectionQuery),e.enableTools!==void 0&&(F.useTools=e.enableTools),F.activeAgentId&&I(async()=>{let{getAgent:e}=await import(`./agent-store-BvS-vIQr.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3,4])).then(({getAgent:e})=>e(F.activeAgentId)).then(e=>{F.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null,Ln()}).catch(()=>{}),F.mcpClosedServers=e[$e]||[];let n=e.ragTools||[],r=e[Qe],i=e.enabledTools;if(Array.isArray(r)){let t=Bn(n);F.enabledTools=r.filter(e=>t.has(e));let i=zn(F.enabledTools,n,e.ragToolsIntroduced);F.enabledTools=i.tools,i.migrated?chrome.storage.local.set({ragToolsIntroduced:!0,[Qe]:F.enabledTools}):F.enabledTools.length!==r.length&&chrome.storage.local.set({[Qe]:F.enabledTools})}else if(i&&i.length>0){let t=Bn(n),r=i.filter(e=>t.has(e)),a=b.filter(e=>e.enabled&&!r.includes(e.id)).map(e=>e.id);F.enabledTools=[...r,...a];let o=zn(F.enabledTools,n,e.ragToolsIntroduced);F.enabledTools=o.tools,chrome.storage.local.set({[Qe]:F.enabledTools,...o.migrated?{ragToolsIntroduced:!0}:{}})}else{F.enabledTools=b.filter(e=>e.enabled).map(e=>e.id);let t=zn(F.enabledTools,n,e.ragToolsIntroduced);F.enabledTools=t.tools,t.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[Qe]:F.enabledTools})}Ye&&(Ye.checked=F.useTools),Ln(),D()}),Je.addEventListener(`change`,()=>{F.isolateChat=Je.checked,chrome.storage.local.set({isolateChat:F.isolateChat}),a.debug(`[SidePanel] conv memory:`,F.isolateChat?`enabled`:`disabled`)});let et=document.getElementById(`enableSelectionQueryBtn`);et&&et.addEventListener(`change`,()=>{F.enableSelectionQuery=et.checked,chrome.storage.local.set({enableSelectionQuery:F.enableSelectionQuery}),a.debug(`[SidePanel] text Q&A:`,F.enableSelectionQuery?`enabled`:`disabled`),!F.enableSelectionQuery&&F.selectedContextText&&qv()}),Ye&&Ye.addEventListener(`change`,()=>{F.useTools=Ye.checked,chrome.storage.local.set({enableTools:F.useTools}),a.debug(`[SidePanel] tool master switch:`,F.useTools?`enabled`:`disabled`),Ln()}),Ze&&Ze.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),Cn()});let nt=document.getElementById(`toolsPopupOverlay`),rt=document.getElementById(`toolsPopupClose`),it=nt?nt.querySelector(`.modal-container`):null;rt&&rt.addEventListener(`click`,wn),it&&it.addEventListener(`click`,e=>{e.stopPropagation()});let at=document.getElementById(`toolsSearchInput`),ot=document.getElementById(`toolsSearchClear`);at&&at.addEventListener(`input`,e=>{F.currentSearch=e.target.value.toLowerCase(),ot&&(ot.style.display=e.target.value?``:`none`),Tn()}),ot&&ot.addEventListener(`click`,()=>{at&&(at.value=``,ot.style.display=`none`,F.currentSearch=``,Tn())});let st=document.querySelectorAll(`.category-btn`);st.forEach(e=>{e.addEventListener(`click`,()=>{st.forEach(e=>{e.classList.remove(`active`),e.classList.contains(`category-all`)?(e.style.background=`var(--brand-violet-soft-bg)`,e.style.color=`var(--brand-500)`,e.style.borderColor=`var(--brand-violet-soft-border)`):(e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`,e.style.borderColor=`var(--border-subtle)`)}),e.classList.add(`active`),e.style.background=`linear-gradient(135deg, var(--brand-500) 0%, var(--brand-accent) 100%)`,e.style.color=`var(--text-on-brand)`,e.style.borderColor=`transparent`,F.currentCategory=e.dataset.category,Tn()})});let B=document.getElementById(`toolsCategories`);B&&B.addEventListener(`wheel`,e=>{e.preventDefault(),B.scrollLeft+=e.deltaY*2},{passive:!1});let ct=document.getElementById(`toolsSelectAll`),V=document.getElementById(`toolsSelectNone`);ct&&ct.addEventListener(`click`,()=>{jn().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!0),F.enabledTools.includes(e.id)||F.enabledTools.push(e.id)}),In(!0),Mn(),Nn(),Pn()}),V&&V.addEventListener(`click`,()=>{jn().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!1);let n=F.enabledTools.indexOf(e.id);n>-1&&F.enabledTools.splice(n,1)}),In(!1),Mn(),Nn(),Pn()});let lt=document.getElementById(`toolsPopupSave`);lt&&lt.addEventListener(`click`,()=>{Fn(),Pn()});let ut=document.getElementById(`toolsPreselectToggle`);ut&&ut.addEventListener(`change`,()=>{chrome.storage.local.set({enableToolPreselect:ut.checked},()=>{a.debug(`[SidePanel] toolpre-filter toggle updated:`,ut.checked)})});let dt=document.getElementById(`toolConfirmToggle`);dt&&dt.addEventListener(`change`,()=>{chrome.storage.local.set({toolConfirmationEnabled:dt.checked},()=>{a.debug(`[SidePanel] sensitive-operation confirmation toggle updated:`,dt.checked)})});let ft=document.getElementById(`toolsPopupCancel`);ft&&ft.addEventListener(`click`,()=>{wn()});let pt=document.getElementById(`modalCancelBtn`),mt=document.getElementById(`modalConfirmBtn`),ht=document.getElementById(`toolStatsOverlay`),gt=document.getElementById(`toolStatsClose`),vt=document.getElementById(`toolStatsBtn`);function yt(){ht&&(ht.style.display=`flex`,wt())}function bt(){ht&&(ht.style.display=`none`)}vt&&vt.addEventListener(`click`,e=>{e.stopPropagation(),yt()}),gt&&gt.addEventListener(`click`,bt),ht&&ht.addEventListener(`click`,e=>{e.target===ht&&bt()});let xt=document.getElementById(`toolStatsRefreshBtn`);xt&&xt.addEventListener(`click`,wt);let St=document.getElementById(`toolStatsClearBtn`);St&&St.addEventListener(`click`,async()=>{await showCustomConfirm(r(`sidePanel.clearStatsConfirm`),r(`sidePanel.clearStatsTitle`))&&(await chrome.storage.local.remove([`toolUsageStats`]),wt())});let Ct={column:`callCount`,asc:!1};async function wt(){let e=document.getElementById(`toolStatsTable`),t=document.getElementById(`toolStatsTableBody`),n=document.getElementById(`toolStatsLoading`),i=document.getElementById(`toolStatsEmpty`),o=document.getElementById(`toolStatsSummary`),s=document.getElementById(`toolStatsUnusedSection`),c=document.getElementById(`toolStatsUnusedList`);if(!(!e||!t||!n||!i)){e.style.display=`none`,i.style.display=`none`,s&&(s.style.display=`none`),o&&(o.textContent=``),n.style.display=``;try{let t=(await chrome.storage.local.get([`toolUsageStats`])).toolUsageStats||{},a=Object.entries(t);if(a.length===0){n.style.display=`none`,i.style.display=``;return}let l={};b.forEach(e=>{l[e.id]=e.name?`${e.name}${r(`sidePanel.toolNameDescSeparator`)}${e.description||``}`:e.description||e.id}),Tt(a,l);let u=b.map(e=>e.id),d=new Set(a.map(([e])=>e)),f=u.filter(e=>!d.has(e)),p=a.length,m=f.length;o&&(o.textContent=r(`sidePanel.toolStatsSummary`,{used:p,unused:m})),s&&c&&m>0&&(c.innerHTML=f.sort((e,t)=>e.toLowerCase().localeCompare(t.toLowerCase())).map(e=>`<code title="${R(l[e]||e)}" style="padding: 3px 10px; background: var(--bg-subtle); color: var(--text-disabled); border: 1px solid var(--border-subtle); border-radius: 4px; font-size: 11px;">${e}</code>`).join(``),s.style.display=``),n.style.display=`none`,e.style.display=``}catch(e){a.error(`[SidePanel] loadstats failed:`,e),n.style.display=`none`,i.textContent=r(`sidePanel.toolStatsLoadFailed`),i.style.display=``}}}function Tt(e,t){let n=document.getElementById(`toolStatsTableBody`);if(!n)return;let{column:r,asc:i}=Ct;n.innerHTML=[...e].sort((e,t)=>{let[n,a]=e,[o,s]=t,c=a.callCount>0?a.successCount/a.callCount*100:0,l=s.callCount>0?s.successCount/s.callCount*100:0,u=a.callCount>0?a.totalDuration/a.callCount:0,d=s.callCount>0?s.totalDuration/s.callCount:0,f=0;switch(r){case`name`:f=n.toLowerCase().localeCompare(o.toLowerCase());break;case`callCount`:f=a.callCount-s.callCount;break;case`successCount`:f=a.successCount-s.successCount;break;case`successRate`:f=c-l;break;case`duration`:f=u-d;break}return i?f:-f}).map(([e,n])=>{let r=n.callCount>0?n.successCount/n.callCount*100:0,i=n.callCount>0?n.totalDuration/n.callCount:0,a=t[e]||e,o=`#38a169`;r<60?o=`#e53e3e`:r<85&&(o=`#d69e2e`);let s=z(i);return`<tr>
2598
+ </div>`}).join(``)}function Ke(){we&&(we.style.display=`flex`,We())}function qe(){we&&(we.style.display=`none`)}Ce&&Ce.addEventListener(`click`,e=>{e.stopPropagation(),ge(),Ke()}),Te&&Te.addEventListener(`click`,qe),Ee&&Ee.addEventListener(`click`,We),De&&De.addEventListener(`change`,We),Oe&&Oe.addEventListener(`change`,We),ke&&ke.addEventListener(`input`,()=>{Ge()}),Ae&&Ae.addEventListener(`click`,()=>{ke&&(ke.value=``),Ge()}),iw(()=>F.activeSessionId,showCustomConfirm);let Je=document.getElementById(`isolateChatBtn`),Ye=document.getElementById(`enableToolsBtn`),Ze=document.getElementById(`toolsConfigBtn`),Qe=`agentEnabledTools_${F.activeAgentId||`default`}`,$e=`agentMcpClosedServers_${F.activeAgentId||`default`}`;chrome.storage.local.get([Qe,`enabledTools`,`isolateChat`,`enableSelectionQuery`,`enableTools`,$e,`mcpTools`,`mcpEnabled`,`ragTools`,`ragToolsIntroduced`],e=>{e.isolateChat!==void 0&&(F.isolateChat=e.isolateChat),Je.checked=F.isolateChat,e.enableSelectionQuery!==void 0&&(F.enableSelectionQuery=e.enableSelectionQuery);let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=F.enableSelectionQuery),e.enableTools!==void 0&&(F.useTools=e.enableTools),F.activeAgentId&&I(async()=>{let{getAgent:e}=await import(`./agent-store-D-jYf94_.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3,4])).then(({getAgent:e})=>e(F.activeAgentId)).then(e=>{F.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null,Ln()}).catch(()=>{}),F.mcpClosedServers=e[$e]||[];let n=e.ragTools||[],r=e[Qe],i=e.enabledTools;if(Array.isArray(r)){let t=Bn(n);F.enabledTools=r.filter(e=>t.has(e));let i=zn(F.enabledTools,n,e.ragToolsIntroduced);F.enabledTools=i.tools,i.migrated?chrome.storage.local.set({ragToolsIntroduced:!0,[Qe]:F.enabledTools}):F.enabledTools.length!==r.length&&chrome.storage.local.set({[Qe]:F.enabledTools})}else if(i&&i.length>0){let t=Bn(n),r=i.filter(e=>t.has(e)),a=b.filter(e=>e.enabled&&!r.includes(e.id)).map(e=>e.id);F.enabledTools=[...r,...a];let o=zn(F.enabledTools,n,e.ragToolsIntroduced);F.enabledTools=o.tools,chrome.storage.local.set({[Qe]:F.enabledTools,...o.migrated?{ragToolsIntroduced:!0}:{}})}else{F.enabledTools=b.filter(e=>e.enabled).map(e=>e.id);let t=zn(F.enabledTools,n,e.ragToolsIntroduced);F.enabledTools=t.tools,t.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[Qe]:F.enabledTools})}Ye&&(Ye.checked=F.useTools),Ln(),D()}),Je.addEventListener(`change`,()=>{F.isolateChat=Je.checked,chrome.storage.local.set({isolateChat:F.isolateChat}),a.debug(`[SidePanel] conv memory:`,F.isolateChat?`enabled`:`disabled`)});let et=document.getElementById(`enableSelectionQueryBtn`);et&&et.addEventListener(`change`,()=>{F.enableSelectionQuery=et.checked,chrome.storage.local.set({enableSelectionQuery:F.enableSelectionQuery}),a.debug(`[SidePanel] text Q&A:`,F.enableSelectionQuery?`enabled`:`disabled`),!F.enableSelectionQuery&&F.selectedContextText&&qv()}),Ye&&Ye.addEventListener(`change`,()=>{F.useTools=Ye.checked,chrome.storage.local.set({enableTools:F.useTools}),a.debug(`[SidePanel] tool master switch:`,F.useTools?`enabled`:`disabled`),Ln()}),Ze&&Ze.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),Cn()});let nt=document.getElementById(`toolsPopupOverlay`),rt=document.getElementById(`toolsPopupClose`),it=nt?nt.querySelector(`.modal-container`):null;rt&&rt.addEventListener(`click`,wn),it&&it.addEventListener(`click`,e=>{e.stopPropagation()});let at=document.getElementById(`toolsSearchInput`),ot=document.getElementById(`toolsSearchClear`);at&&at.addEventListener(`input`,e=>{F.currentSearch=e.target.value.toLowerCase(),ot&&(ot.style.display=e.target.value?``:`none`),Tn()}),ot&&ot.addEventListener(`click`,()=>{at&&(at.value=``,ot.style.display=`none`,F.currentSearch=``,Tn())});let st=document.querySelectorAll(`.category-btn`);st.forEach(e=>{e.addEventListener(`click`,()=>{st.forEach(e=>{e.classList.remove(`active`),e.classList.contains(`category-all`)?(e.style.background=`var(--brand-violet-soft-bg)`,e.style.color=`var(--brand-500)`,e.style.borderColor=`var(--brand-violet-soft-border)`):(e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`,e.style.borderColor=`var(--border-subtle)`)}),e.classList.add(`active`),e.style.background=`linear-gradient(135deg, var(--brand-500) 0%, var(--brand-accent) 100%)`,e.style.color=`var(--text-on-brand)`,e.style.borderColor=`transparent`,F.currentCategory=e.dataset.category,Tn()})});let B=document.getElementById(`toolsCategories`);B&&B.addEventListener(`wheel`,e=>{e.preventDefault(),B.scrollLeft+=e.deltaY*2},{passive:!1});let ct=document.getElementById(`toolsSelectAll`),V=document.getElementById(`toolsSelectNone`);ct&&ct.addEventListener(`click`,()=>{jn().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!0),F.enabledTools.includes(e.id)||F.enabledTools.push(e.id)}),In(!0),Mn(),Nn(),Pn()}),V&&V.addEventListener(`click`,()=>{jn().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!1);let n=F.enabledTools.indexOf(e.id);n>-1&&F.enabledTools.splice(n,1)}),In(!1),Mn(),Nn(),Pn()});let lt=document.getElementById(`toolsPopupSave`);lt&&lt.addEventListener(`click`,()=>{Fn(),Pn()});let ut=document.getElementById(`toolsPreselectToggle`);ut&&ut.addEventListener(`change`,()=>{chrome.storage.local.set({enableToolPreselect:ut.checked},()=>{a.debug(`[SidePanel] toolpre-filter toggle updated:`,ut.checked)})});let dt=document.getElementById(`toolConfirmToggle`);dt&&dt.addEventListener(`change`,()=>{chrome.storage.local.set({toolConfirmationEnabled:dt.checked},()=>{a.debug(`[SidePanel] sensitive-operation confirmation toggle updated:`,dt.checked)})});let ft=document.getElementById(`toolsPopupCancel`);ft&&ft.addEventListener(`click`,()=>{wn()});let pt=document.getElementById(`modalCancelBtn`),mt=document.getElementById(`modalConfirmBtn`),ht=document.getElementById(`toolStatsOverlay`),gt=document.getElementById(`toolStatsClose`),vt=document.getElementById(`toolStatsBtn`);function yt(){ht&&(ht.style.display=`flex`,wt())}function bt(){ht&&(ht.style.display=`none`)}vt&&vt.addEventListener(`click`,e=>{e.stopPropagation(),yt()}),gt&&gt.addEventListener(`click`,bt),ht&&ht.addEventListener(`click`,e=>{e.target===ht&&bt()});let xt=document.getElementById(`toolStatsRefreshBtn`);xt&&xt.addEventListener(`click`,wt);let St=document.getElementById(`toolStatsClearBtn`);St&&St.addEventListener(`click`,async()=>{await showCustomConfirm(r(`sidePanel.clearStatsConfirm`),r(`sidePanel.clearStatsTitle`))&&(await chrome.storage.local.remove([`toolUsageStats`]),wt())});let Ct={column:`callCount`,asc:!1};async function wt(){let e=document.getElementById(`toolStatsTable`),t=document.getElementById(`toolStatsTableBody`),n=document.getElementById(`toolStatsLoading`),i=document.getElementById(`toolStatsEmpty`),o=document.getElementById(`toolStatsSummary`),s=document.getElementById(`toolStatsUnusedSection`),c=document.getElementById(`toolStatsUnusedList`);if(!(!e||!t||!n||!i)){e.style.display=`none`,i.style.display=`none`,s&&(s.style.display=`none`),o&&(o.textContent=``),n.style.display=``;try{let t=(await chrome.storage.local.get([`toolUsageStats`])).toolUsageStats||{},a=Object.entries(t);if(a.length===0){n.style.display=`none`,i.style.display=``;return}let l={};b.forEach(e=>{l[e.id]=e.name?`${e.name}${r(`sidePanel.toolNameDescSeparator`)}${e.description||``}`:e.description||e.id}),Tt(a,l);let u=b.map(e=>e.id),d=new Set(a.map(([e])=>e)),f=u.filter(e=>!d.has(e)),p=a.length,m=f.length;o&&(o.textContent=r(`sidePanel.toolStatsSummary`,{used:p,unused:m})),s&&c&&m>0&&(c.innerHTML=f.sort((e,t)=>e.toLowerCase().localeCompare(t.toLowerCase())).map(e=>`<code title="${R(l[e]||e)}" style="padding: 3px 10px; background: var(--bg-subtle); color: var(--text-disabled); border: 1px solid var(--border-subtle); border-radius: 4px; font-size: 11px;">${e}</code>`).join(``),s.style.display=``),n.style.display=`none`,e.style.display=``}catch(e){a.error(`[SidePanel] loadstats failed:`,e),n.style.display=`none`,i.textContent=r(`sidePanel.toolStatsLoadFailed`),i.style.display=``}}}function Tt(e,t){let n=document.getElementById(`toolStatsTableBody`);if(!n)return;let{column:r,asc:i}=Ct;n.innerHTML=[...e].sort((e,t)=>{let[n,a]=e,[o,s]=t,c=a.callCount>0?a.successCount/a.callCount*100:0,l=s.callCount>0?s.successCount/s.callCount*100:0,u=a.callCount>0?a.totalDuration/a.callCount:0,d=s.callCount>0?s.totalDuration/s.callCount:0,f=0;switch(r){case`name`:f=n.toLowerCase().localeCompare(o.toLowerCase());break;case`callCount`:f=a.callCount-s.callCount;break;case`successCount`:f=a.successCount-s.successCount;break;case`successRate`:f=c-l;break;case`duration`:f=u-d;break}return i?f:-f}).map(([e,n])=>{let r=n.callCount>0?n.successCount/n.callCount*100:0,i=n.callCount>0?n.totalDuration/n.callCount:0,a=t[e]||e,o=`#38a169`;r<60?o=`#e53e3e`:r<85&&(o=`#d69e2e`);let s=z(i);return`<tr>
2599
2599
  <td style="padding: 6px 10px; border-bottom: 1px solid var(--border-subtle); color: var(--text-primary);"><code title="${R(a)}">${e}</code></td>
2600
2600
  <td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-secondary);">${n.callCount}</td>
2601
2601
  <td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-secondary);">${n.successCount}</td>