ai-helper-agent 2.7.3 → 2.7.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-CrkBz4jI.js","assets/chunk-CMxvf4Kt.js","assets/session-store-D93MJNgp.js","assets/model-profiles-Czl5eTZY.js","assets/i18n-DU8C0Dir.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-BPasibDS.js","assets/dist-BUuoW_84.js","assets/markdown-render-LHYvFtnH.js","assets/version-D7IEwuLh.js","assets/utils-CbwqBtBF.js","assets/workspace-manager-Dq1z6ENd.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-DU8C0Dir.js";import{A as l,C as u,D as d,E as f,F as p,G as m,I as h,N as g,P as _,R as v,S as y,T as b,W as x,b as S,c as C,d as w,i as T,k as E,r as D,u as O,w as k,y as A,z as j}from"./model-profiles-Czl5eTZY.js";import{A as ee,At as te,C as ne,D as re,E as ie,Et as ae,F as oe,G as se,Ht as ce,Kt as le,Lt as ue,M as de,N as M,Nt as fe,O as pe,Ot as me,P as he,Pt as ge,Rt as _e,S as ve,T as ye,Tt as be,Ut as xe,Vt as Se,Xt as Ce,Yt as we,_ as Te,a as Ee,an as De,b as N,c as Oe,d as ke,dt as Ae,en as je,f as Me,ft as Ne,h as Pe,ht as Fe,j as Ie,k as Le,l as Re,lt as ze,m as Be,mt as Ve,n as He,nn as Ue,o as We,on as Ge,p as Ke,pt as qe,r as Je,rn as Ye,s as Xe,t as Ze,tn as Qe,u as $e,un as et,ut as tt,v as nt,w as rt,x as it,y as at}from"./session-store-D93MJNgp.js";import{a as ot,n as st,r as ct,t as lt}from"./voice-shortcut-Dtt3nhkz.js";import{d as ut,f as dt,i as ft,n as pt,p as mt,t as ht,u as gt}from"./version-D7IEwuLh.js";import{a as _t,c as vt,i as yt,n as bt,o as xt,r as St,s as Ct}from"./agent-store-CrkBz4jI.js";import{C as wt,E as Tt,S as Et,T as Dt,_ as Ot,a as kt,b as At,c as P,d as jt,f as Mt,g as Nt,h as Pt,i as Ft,l as It,m as F,n as Lt,o as Rt,p as zt,r as Bt,s as I,t as Vt,u as Ht,v as Ut,w as L,x as Wt,y as Gt}from"./utils-CbwqBtBF.js";import{a as Kt,c as qt,d as Jt,f as Yt,g as Xt,h as Zt,i as Qt,l as $t,m as en,n as tn,o as nn,p as rn,r as an,s as on,t as sn,u as cn}from"./markdown-render-LHYvFtnH.js";import{C as ln,E as un,O as dn,S as fn,T as pn,_ as mn,a as hn,b as gn,c as _n,d as vn,f as yn,g as bn,h as xn,i as Sn,l as Cn,m as wn,n as Tn,o as En,p as Dn,r as On,s as kn,t as An,u as jn,v as Mn,w as Nn,x as Pn,y as Fn}from"./workspace-manager-Dq1z6ENd.js";var In=he.map(e=>e.id),Ln=[...new Set([...m,`mcp`,`knowledge`])],Rn=[{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 zn=2e3,Bn=.7,Vn=1e3;function Hn(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 d=s,p=s.map((e,t)=>t);n&&n>0&&s.length>n&&(d=s.slice(s.length-n),p=p.slice(s.length-n));let m=[];for(let e=0;e<d.length;e++)c&&p[e]<=u||m.push(d[e]);let h=[],g=b([o]);for(let e=m.length-1;e>=0;e--){let t=m[e],n=b([{...t,content:v(t.content)}]);if(g+n<=i)h.unshift(t),g+=n;else break}let _=null,y=m.length-h.length;if(y>0){let e=l(m.slice(0,y));e&&(_=f(e)>Vn?e.substring(0,Vn*4)+`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agent-store-1fyaAv9T.js","assets/chunk-CMxvf4Kt.js","assets/session-store-xr0nYACs.js","assets/model-profiles-D31rvEiY.js","assets/i18n-DQnIL9xy.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-DeqIrNGG.js","assets/dist-BUuoW_84.js","assets/markdown-render-DHIb_j5C.js","assets/version-vmZC13dl.js","assets/utils-DVhZvlZX.js","assets/workspace-manager-DfSFPqwp.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-DQnIL9xy.js";import{A as l,C as u,D as d,E as f,F as p,G as m,I as h,N as g,P as _,R as v,S as y,T as b,W as x,b as S,c as C,d as w,i as T,k as E,r as D,u as O,w as k,y as A,z as j}from"./model-profiles-D31rvEiY.js";import{A as ee,At as te,C as ne,D as re,E as ie,Et as ae,F as oe,G as se,Ht as ce,Kt as le,Lt as ue,M as de,N as M,Nt as fe,O as pe,Ot as me,P as he,Pt as ge,Rt as _e,S as ve,T as ye,Tt as be,Ut as xe,Vt as Se,Xt as Ce,Yt as we,_ as Te,a as Ee,an as De,b as N,c as Oe,d as ke,dt as Ae,en as je,f as Me,ft as Ne,h as Pe,ht as Fe,j as Ie,k as Le,l as Re,lt as ze,m as Be,mt as Ve,n as He,nn as Ue,o as We,on as Ge,p as Ke,pt as qe,r as Je,rn as Ye,s as Xe,t as Ze,tn as Qe,u as $e,un as et,ut as tt,v as nt,w as rt,x as it,y as at}from"./session-store-xr0nYACs.js";import{a as ot,n as st,r as ct,t as lt}from"./voice-shortcut-Dtt3nhkz.js";import{d as ut,f as dt,i as ft,n as pt,p as mt,t as ht,u as gt}from"./version-vmZC13dl.js";import{a as _t,c as vt,i as yt,n as bt,o as xt,r as St,s as Ct}from"./agent-store-1fyaAv9T.js";import{C as wt,E as Tt,S as Et,T as Dt,_ as Ot,a as kt,b as At,c as P,d as jt,f as Mt,g as Nt,h as Pt,i as Ft,l as It,m as F,n as Lt,o as Rt,p as zt,r as Bt,s as I,t as Vt,u as Ht,v as Ut,w as L,x as Wt,y as Gt}from"./utils-DVhZvlZX.js";import{a as Kt,c as qt,d as Jt,f as Yt,g as Xt,h as Zt,i as Qt,l as $t,m as en,n as tn,o as nn,p as rn,r as an,s as on,t as sn,u as cn}from"./markdown-render-DHIb_j5C.js";import{C as ln,E as un,O as dn,S as fn,T as pn,_ as mn,a as hn,b as gn,c as _n,d as vn,f as yn,g as bn,h as xn,i as Sn,l as Cn,m as wn,n as Tn,o as En,p as Dn,r as On,s as kn,t as An,u as jn,v as Mn,w as Nn,x as Pn,y as Fn}from"./workspace-manager-DfSFPqwp.js";var In=he.map(e=>e.id),Ln=[...new Set([...m,`mcp`,`knowledge`])],Rn=[{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 zn=2e3,Bn=.7,Vn=1e3;function Hn(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 d=s,p=s.map((e,t)=>t);n&&n>0&&s.length>n&&(d=s.slice(s.length-n),p=p.slice(s.length-n));let m=[];for(let e=0;e<d.length;e++)c&&p[e]<=u||m.push(d[e]);let h=[],g=b([o]);for(let e=m.length-1;e>=0;e--){let t=m[e],n=b([{...t,content:v(t.content)}]);if(g+n<=i)h.unshift(t),g+=n;else break}let _=null,y=m.length-h.length;if(y>0){let e=l(m.slice(0,y));e&&(_=f(e)>Vn?e.substring(0,Vn*4)+`
3
3
  ...[历史摘要已截断]`:e)}return{messages:[...h,o],keptHistory:h,compactionApplied:c,trimmedCount:y,historySummaryText:_}}function Un(e,t){return!t||!t.summary?e:`${e}\n\n${r(`contextUsage.compactionInjection`,{count:t.compressedCount||0})}\n${t.summary}`}function Wn(e,t,n,r){return t?.compactionApplied&&n?.summary?e[0]={...e[0],content:Un(e[0].content,n)}:n?.summary&&r?.warn(`[SidePanel] contextCompaction invalid (upToMessageId not found), ignored this send`),e}function Gn({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 d=g(e,l,t),p=d-f(n)-y-zn,m=Math.floor(Math.max(p,0)*Bn),h={role:`user`,content:a},_=c?s:null,v=Hn(i,{isolateChat:c,maxMemoryMessages:o,compaction:_,historyBudget:m,currentMessage:h}),x=f(v.compactionApplied?Un(n,_):n),S=r*200,C=b(v.keptHistory),w=a&&a.trim()?b([h]):0,T=x+S+C+w,E=u(T,d);return{usedTokens:T,contextWindow:d,ratio:d>0?T/d:0,level:E.level,breakdown:{system:x,tools:S,history:C,input:w,outputReserve:y,safetyMargin:zn,selectedCount:v.keptHistory.length,totalCount:i.length,trimmedCount:v.trimmedCount,compactionApplied:v.compactionApplied,compactionInvalid:!!(_&&_.summary&&!v.compactionApplied),historyBudget:m}}}function Kn(e,{maxMemoryMessages:t=null,compaction:n=null}={}){let r=Hn(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=v(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 qn(e){if(!e||!e.trim()||e.trim()==`/`)return;let t=e.trim(),n=N.inputHistory.indexOf(t);n!==-1&&N.inputHistory.splice(n,1),N.inputHistory.push(t),N.inputHistory.length>20&&N.inputHistory.shift(),Jn()}function Jn(){try{chrome.storage.local.set({inputHistory:N.inputHistory}),a.debug(`[SidePanel] input history saved,count:`,N.inputHistory.length)}catch(e){a.error(`[SidePanel] saveinput history failed:`,e)}}var Yn=[`workspace`,`bookmark`,`toc`,`search`,`todo`,`schedule`],Xn=`.workspace-panel.expanded, .bookmark-panel.expanded, .message-toc-panel.expanded, .search-panel.expanded, .schedule-panel.open`,Zn=null,Qn=null;function $n(){if(Zn)return Zn;Zn=document.createElement(`div`),Zn.className=`side-rail`,Zn.id=`sideRail`,Zn.innerHTML=Yn.map(e=>`<div class="side-rail-slot" data-slot="${e}"></div>`).join(``),document.body.appendChild(Zn),tr();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(tr).observe(e),window.addEventListener(`resize`,tr),Zn}function er(e){return(Zn||$n()).querySelector(`.side-rail-slot[data-slot="${e}"]`)}function tr(){if(!Zn)return;let e=document.getElementById(`chatContainer`);if(!e)return;let t=e.getBoundingClientRect(),n=window.innerHeight;Zn.style.top=`${Math.max(0,Math.round(t.top))}px`,Zn.style.bottom=`${Math.max(0,Math.round(n-t.bottom))}px`,nr()}function nr(){Qn&&clearTimeout(Qn),Qn=setTimeout(()=>{Qn=null,document.querySelectorAll(Xn).forEach(Ft)},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 rr(){document.addEventListener(`mouseover`,ir,!0),document.addEventListener(`mouseout`,ar,!0),a.debug(`[SidePanel] messagedirectory featureinitializing`)}function ir(e){if(!(e.target instanceof Element))return;if(e.target.closest(`.message-toc-container`)){N.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){sr();return}or(r,i)}function ar(e){if(!(e.target instanceof Element))return;if(e.target.closest(`.message-toc-container`)){N.isMouseOverToc=!1,N.tocHideTimer&&=(clearTimeout(N.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`))||N.isMouseOverToc||(N.tocHideTimer&&clearTimeout(N.tocHideTimer),N.tocHideTimer=setTimeout(()=>{N.isMouseOverToc||sr(),N.tocHideTimer=null},800))}function or(e,t){let n=Array.from(t);N.messageTocContainer&&sr(),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
- `;let s=e.closest(`.message-fullscreen-overlay`);(s&&s.querySelector(`.message-fullscreen-rail`)||er(`toc`)).appendChild(i),N.messageTocContainer=i;let c=i.querySelector(`.message-toc-toggle`),l=i.querySelector(`.message-toc-panel`);c.addEventListener(`mouseenter`,()=>{l.classList.add(`expanded`),Ft(l)}),c.addEventListener(`click`,()=>{l.classList.toggle(`expanded`)?Ft(l):Wt(l)}),l.addEventListener(`mouseenter`,()=>{l.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 sr(){N.tocHideTimer&&=(clearTimeout(N.tocHideTimer),null),N.messageTocContainer&&=(N.messageTocContainer.remove(),null)}var cr=`promptQueues`,lr=1,ur=30*1e3,dr=15*1e3,fr=20,R={QUEUED:`queued`,DISPATCHING:`dispatching`,INJECTING:`injecting`,INJECTED:`injected`,DONE:`done`,FAILED:`failed`};new Set([R.INJECTED,R.DONE,R.FAILED]);var pr={async get(e){let t=await chrome.storage.local.get(e);return t?t[e]:void 0},async set(e){await chrome.storage.local.set(e)}};function mr(){return{version:lr,sessions:{}}}var z=mr(),hr=!1,gr=null,_r=!1,vr=``,yr=new Set,br=new Set;function xr(){return{items:[],recent:[],paused:!1,pausedReason:null}}function Sr(e){return e?(z.sessions[e]||(z.sessions[e]=xr()),z.sessions[e]):xr()}function Cr(){return JSON.stringify(z)}function wr(e,t){for(let n of br)try{n(e,t)}catch(e){a.error(`[QueueStore] listener failed:`,e?.message)}}function Tr(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`q_`+crypto.randomUUID():`q_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,8)}function Er(e){return e.reduce((e,t)=>Math.max(e,Number(t.order)||0),0)+1}function Dr(e,t){let n=e.indexOf(t);n<0||(e.splice(n,1),e.unshift(t),Or(e))}function Or(e){e.forEach((e,t)=>{e.order=t+1})}function kr(e){return e.slice().sort((e,t)=>(Number(e.order)||0)-(Number(t.order)||0))}async function Ar(e){if(_r)return a.error(`[QueueStore] persist skipped in degraded mode:`,e),!1;let t=Cr();vr=t,jr(t);try{await pr.set({[cr]:z})}catch(e){a.error(`[QueueStore] persist failed:`,e?.message)}wr(e)}function jr(e){if(yr.add(e),yr.size<=fr)return;let t=yr.values().next().value;yr.delete(t)}function Mr(e,{recoverInterrupted:t=!0}={}){let n=mr();if(!e||typeof e!=`object`)return n;let r=e.sessions&&typeof e.sessions==`object`?e.sessions:{};for(let[e,i]of Object.entries(r)){let r=Array.isArray(i?.items)?i.items:[],a=Array.isArray(i?.recent)?i.recent.slice(0,30):[],o=!1;for(let e of r)!e||typeof e!=`object`||t&&(e.status===R.DISPATCHING||e.status===R.INJECTING)&&(e.status=R.QUEUED,e.interrupted=!0,e.previousStatus=e.previousStatus||R.DISPATCHING,e.leaseOwner=null,e.leaseUntil=0,o=!0);let s=kr(r);if(o){let e=s.filter(e=>e.interrupted),t=s.filter(e=>!e.interrupted);s.splice(0,s.length,...e,...t)}Or(s);let c=s.slice(0,20),l=s.slice(20);for(let e of l.reverse())a.unshift(ti({...e,status:R.FAILED,lastError:`over_limit`}));n.sessions[e]={items:c,recent:a.slice(0,30),paused:i?.paused===!0,pausedReason:i?.pausedReason||null}}return n}function Nr(){return _r}async function Pr(){return hr?z:gr||(gr=(async()=>{let e;try{e=await pr.get(cr)}catch(e){return _r=!0,gr=null,a.error(`[QueueStore] load failed, enter degraded mode:`,e?.message),z}return z=Mr(e),hr=!0,_r=!1,vr=Cr(),z})(),gr)}function Fr(){typeof chrome>`u`||!chrome.storage?.onChanged?.addListener||chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`||!e?.[cr])return;let n=e[cr].newValue;if(!n)return;let r=JSON.stringify(n);yr.has(r)||r===vr||(z=Mr(n,{recoverInterrupted:!1}),hr=!0,vr=r,wr(`external`,null))})}function Ir(e){return typeof e==`function`?(br.add(e),()=>br.delete(e)):()=>{}}function Lr(e){let t=z.sessions[e];return t?kr(t.items):[]}function Rr(e,t=30){let n=z.sessions[e];return n?n.recent.slice(0,t):[]}function zr(e){let t=z.sessions[e];return t?{items:kr(t.items),recent:t.recent.slice(),paused:t.paused===!0,pausedReason:t.pausedReason||null}:xr()}function Br(e){return Lr(e).filter(e=>e.status===R.QUEUED).length}function Vr(e){return Lr(e).find(e=>e.status===R.QUEUED)||null}function Hr(e){let t=z.sessions[e];if(!t)return null;for(let e=t.items.length-1;e>=0;--e)if(t.items[e].status===R.QUEUED)return t.items[e];return null}function Ur(e,t){let n=z.sessions[e];return n&&n.items.find(e=>e.id===t)||null}function Wr(){return Object.keys(z.sessions).filter(e=>(z.sessions[e]?.items?.length||0)>0)}function Gr(e){return z.sessions[e]?.paused===!0}async function Kr({sessionId:e,text:t,contextSnapshot:n=null,hasContext:r=!1,attachmentSummary:i=null,source:a=`manual`}){if(!e)return{ok:!1,error:`missing_session`};let o=String(t||``).trim();if(!o)return{ok:!1,error:`empty`};if(await Pr(),_r)return{ok:!1,error:`storage_unavailable`};let s=Sr(e);if(s.items.length>=20)return{ok:!1,error:`queue_full`,limit:20};let c={id:Tr(),sessionId:e,text:o,contextSnapshot:n||null,attachmentSummary:i||null,hasContext:r===!0,status:R.QUEUED,order:Er(s.items),createdAt:Date.now(),updatedAt:Date.now(),attempts:0,lastError:null,source:a,interrupted:!1,leaseOwner:null,leaseUntil:0,injectRequestedAt:0,injectDeadlineAt:0,injectedIntoCallId:null,absorbedIteration:null};return s.items.push(c),await Ar(`enqueue`),{ok:!0,item:c,position:s.items.length}}async function qr(e,t){let n=z.sessions[e];if(!n)return!1;let r=n.items.findIndex(e=>e.id===t);return r<0?!1:(n.items.splice(r,1),Or(n.items),await Ar(`remove`),!0)}async function Jr(e,t){let n=z.sessions[e];if(!n||!Array.isArray(t))return!1;let r=new Map(n.items.map(e=>[e.id,e])),i=[];for(let e of t){let t=r.get(e);t&&!i.includes(t)&&i.push(t)}for(let e of kr(n.items))i.includes(e)||i.push(e);return n.items=i,Or(n.items),await Ar(`reorder`),!0}async function Yr(e,t,n,r={}){let i=Ur(e,t);return i?(i.status=n,Object.assign(i,r,{updatedAt:Date.now()}),await Ar(`status`),!0):!1}async function Xr(e,t,n=dr){let r=Ur(e,t);return r?(r.previousStatus=r.status,r.status=R.INJECTING,r.injectRequestedAt=Date.now(),r.injectDeadlineAt=Date.now()+n,r.updatedAt=Date.now(),await Ar(`inject:request`),!0):!1}async function Zr(e,t,n=`error`,r=null){let i=z.sessions[e];if(!i)return!1;let a=i.items.find(e=>e.id===t);return a?(a.status=R.QUEUED,a.injectDeadlineAt=0,a.updatedAt=Date.now(),a.lastError=r||n,a.rollbackReason=n,Dr(i.items,a),await Ar(`inject:rollback`),!0):!1}async function Qr(e,t,{status:n,note:r=null,callId:i=null,iteration:a=null}={}){let o=z.sessions[e];if(!o)return!1;let s=o.items.findIndex(e=>e.id===t);if(s<0)return!1;let[c]=o.items.splice(s,1);return Or(o.items),c.status=n||R.DONE,c.settledAt=Date.now(),c.settleNote=r,i&&(c.injectedIntoCallId=i),a!=null&&(c.absorbedIteration=a),o.recent.unshift(ti(c)),o.recent=o.recent.slice(0,30),await Ar(`settle`),!0}async function $r(e,t){let n=z.sessions[e];if(!n)return{ok:!1,error:`missing_session`};let r=n.recent.findIndex(e=>e.id===t);if(r<0)return{ok:!1,error:`not_found`};if(n.items.length>=20)return{ok:!1,error:`queue_full`,limit:20};let[i]=n.recent.splice(r,1),a={...i,status:R.QUEUED,order:Er(n.items),attempts:0,lastError:null,interrupted:!1,rollbackReason:null,settledAt:null,leaseOwner:null,leaseUntil:0,injectDeadlineAt:0,updatedAt:Date.now()};return n.items.push(a),await Ar(`requeue`),{ok:!0,item:a}}async function ei(e,t){let n=z.sessions[e];if(!n)return!1;let r=n.recent.findIndex(e=>e.id===t);return r<0?!1:(n.recent.splice(r,1),await Ar(`recent-remove`),!0)}function ti(e){let{leaseOwner:t,leaseUntil:n,injectDeadlineAt:r,contextSnapshot:i,...a}=e;return{...a,hasContext:e.hasContext===!0,contextDropped:!!i}}async function ni(e,t=`user_stopped`){let n=Sr(e);return n.paused?!1:(n.paused=!0,n.pausedReason=t,await Ar(`pause`),!0)}async function ri(e){let t=z.sessions[e];return!t||!t.paused?!1:(t.paused=!1,t.pausedReason=null,await Ar(`resume`),!0)}async function ii(e,t,n){let r=Ur(e,t);if(!r)return!1;let i=Date.now();return r.leaseOwner&&r.leaseOwner!==n&&Number(r.leaseUntil)>i?!1:(r.leaseOwner=n,r.leaseUntil=i+ur,await Ar(`lease`),!0)}async function ai(e){let t=z.sessions[e];if(!t)return 0;let n=t.items.length+t.recent.length;return delete z.sessions[e],n>0&&await Ar(`drop-session`),n}var oi=`ai-helper-queue-attachments`,si=1,ci=`attachments`,li=null,ui=null;function di(){return new Promise((e,t)=>{let n=indexedDB.open(oi,si);n.onupgradeneeded=e=>{let t=e.target.result;t.objectStoreNames.contains(ci)||t.createObjectStore(ci,{keyPath:`id`}).createIndex(`sessionId`,`sessionId`,{unique:!1})},n.onsuccess=t=>{let n=t.target.result;n.onversionchange=()=>{try{n.close()}catch{}li=null},e(n)},n.onerror=()=>t(n.error||Error(`idb_open_failed`)),n.onblocked=()=>{}})}function fi(){return li||=di(),li}function pi(e,t){return fi().then(n=>new Promise((r,i)=>{let a;try{a=n.transaction(ci,e)}catch(e){li=null,i(e);return}let o=a.objectStore(ci),s=null,c=e=>{s=e};try{t(o,c)}catch(e){i(e);return}a.oncomplete=()=>r(s),a.onerror=()=>i(a.error||Error(`idb_tx_failed`)),a.onabort=()=>i(a.error||Error(`idb_tx_aborted`))}))}function mi(){return{async put(e){await pi(`readwrite`,t=>{t.put(e)})},async get(e){return pi(`readonly`,(t,n)=>{let r=t.get(e);r.onsuccess=()=>n(r.result||null)})},async remove(e){await pi(`readwrite`,t=>{t.delete(e)})},async removeBySession(e){await pi(`readwrite`,t=>{let n=t.index(`sessionId`).getAllKeys(e);n.onsuccess=()=>{for(let e of n.result||[])t.delete(e)}})},async allKeys(){return pi(`readonly`,(e,t)=>{let n=e.getAllKeys();n.onsuccess=()=>t(n.result||[])})}}}function hi(){return ui||mi()}function gi(e){return e==null?0:typeof e==`string`?e.length:typeof e==`number`||typeof e==`boolean`?8:Array.isArray(e)?e.reduce((e,t)=>e+gi(t),0):typeof e==`object`?Object.values(e).reduce((e,t)=>e+gi(t),0):0}function _i(e){let t=e&&e.attachedImages||[],n=e&&e.attachedFiles||[];return!t.length&&!n.length?null:{imageCount:t.length,fileCount:n.length,fileNames:n.map(e=>e.name).filter(Boolean).slice(0,5)}}async function vi(e,t,{images:n=[],files:r=[]}={}){if(!e)return{ok:!1,reason:`missing_id`};if(!n.length&&!r.length)return{ok:!0,skipped:!0};let i=gi(n)+gi(r);if(i>26214400)return{ok:!1,reason:`too_large`,size:i};try{return await hi().put({id:e,sessionId:t||null,size:i,images:n,files:r,updatedAt:Date.now()}),{ok:!0,size:i}}catch(e){return{ok:!1,reason:`idb_error`,message:e?.message||String(e)}}}async function yi(e){if(!e)return null;try{let t=await hi().get(e);return t?{images:t.images||[],files:t.files||[]}:null}catch{return null}}async function bi(e){if(!e)return!1;try{return await hi().remove(e),!0}catch{return!1}}async function xi(e){if(!e)return!1;try{return await hi().removeBySession(e),!0}catch{return!1}}async function Si(e){let t=e instanceof Set?e:new Set(e||[]);try{let e=await hi().allKeys(),n=0;for(let r of e||[])t.has(r)||(await hi().remove(r),n+=1);return n}catch{return 0}}var Ci=t({appendMessageToSession:()=>Gi,archiveCurrentSession:()=>Ri,archiveSession:()=>Vi,clearSessionCompleted:()=>Oi,createSession:()=>Ni,deleteArchivedSession:()=>Ui,deleteSession:()=>Fi,duplicateSession:()=>Ki,hydrateSessionWorkdir:()=>ji,importSessions:()=>Wi,isSessionArchivable:()=>Bi,loadArchivedSessions:()=>zi,loadSessions:()=>ki,markSessionCompleted:()=>Di,persistSessionState:()=>Mi,renameSession:()=>Ii,reorderSessions:()=>Li,restoreCompletedSessions:()=>Ti,restoreSession:()=>Hi,saveCurrentSession:()=>Ai,switchToSession:()=>Pi}),wi=`completedSessionIds`;async function Ti(){try{let e=(await chrome.storage.local.get([wi]))[wi]||[];N.completedSessionIds=new Set(e)}catch(e){a.warn(`[SessionManager] restore completedSessionIds failed:`,e)}}async function Ei(){try{await chrome.storage.local.set({[wi]:Array.from(N.completedSessionIds)})}catch(e){a.warn(`[SessionManager] persist completedSessionIds failed:`,e)}}async function Di(e){e&&e!==N.activeSessionId&&(N.completedSessionIds.has(e)||(N.completedSessionIds.add(e),await Ei(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))))}async function Oi(e){e&&N.completedSessionIds.has(e)&&(N.completedSessionIds.delete(e),await Ei(),document.dispatchEvent(new CustomEvent(`generating-state-changed`)))}async function ki(){return ke()}async function Ai(){return Pe()}function ji(e){return Oe(e)}async function Mi(e,t){return Me(e,t)}async function Ni(){return Ee()}async function Pi(e){return nt(e)}async function Fi(e){await ai(e)>0&&xi(e);let t=await We(e);try{chrome.runtime.sendMessage({type:`DROP_GOAL`,sessionId:e},()=>{chrome.runtime.lastError&&a.debug(`[SessionManager] DROP_GOAL skipped:`,chrome.runtime.lastError.message)})}catch(e){a.debug(`[SessionManager] DROP_GOAL send failed:`,e?.message)}return N.completedSessionIds.has(e)&&(N.completedSessionIds.delete(e),await Ei()),t}async function Ii(e,t){return Ke(e,t)}async function Li(e){return Be(e)}async function Ri(){return He()}async function zi(){return $e()}function Bi(e){return e?N.generatingSessionIds.has(e)||N.pendingCallApiSessionIds.has(e)?{ok:!1,reason:`running`}:Br(e)>0?{ok:!1,reason:`queued`}:{ok:!0}:{ok:!1,reason:`missing`}}async function Vi(e){let t=Bi(e);return t.ok?await Je(e)?(N.completedSessionIds.has(e)&&(N.completedSessionIds.delete(e),await Ei(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))),{ok:!0}):{ok:!1,reason:`missing`}:t}async function Hi(e){return at(e)}async function Ui(e){return Fi(e)}async function Wi(e){return Re(e)}async function Gi(e,t){return Ze(e,t)}async function Ki(e,t=null){return Xe(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 qi=[],Ji=[];function Yi(e){if(!e)return``;let t=`tool.${e.id}`,n=r(t);return n===t?e.description||``:n}function Xi(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 Zi(){try{let e=await chrome.runtime.sendMessage({type:`GET_MCP_TOOLS`});if(e?.success&&e.tools)return qi=e.tools,qi}catch{}try{return qi=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[],qi}catch{return qi=[],[]}}async function Qi(){try{Ji=(await chrome.storage.local.get([`ragTools`])).ragTools||[]}catch{Ji=[]}return Ji}async function $i(){let e=`agentMcpClosedServers_${N.activeAgentId||`default`}`;try{N.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}catch{N.mcpClosedServers=[]}try{let{getAgent:e}=await M(async()=>{let{getAgent:e}=await import(`./agent-store-CrkBz4jI.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3,4])),t=N.activeAgentId?await e(N.activeAgentId):null;N.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null}catch{}}var ea=!1,ta=!0;chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{ea=e.enableToolPreselect===!0,ta=e.toolConfirmationEnabled!==!1,Da()}),chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`)return;let n=!1;e.mcpTools&&(qi=e.mcpTools.newValue||[],a.debug(`[SidePanel] MCP toolcache updated:`,qi.length,``),n=!0),e.ragTools&&(Ji=e.ragTools.newValue||[],a.debug(`[SidePanel] RAG toolcache updated:`,Ji.length),n=!0),e.mcpEnabled&&(na=e.mcpEnabled.newValue===!0,a.debug(`[SidePanel] MCP globaltoggle changed:`,na),n=!0),e.skillsEnabled&&(ra=e.skillsEnabled.newValue!==!1,a.debug(`[SidePanel] Skill global toggle changed:`,ra),n=!0),e.enableImageInput&&(ia=e.enableImageInput.newValue===!0,a.debug(`[SidePanel] 图片识别全局开关变更:`,ia),n=!0);let r=!1;e.enableToolPreselect&&(ea=e.enableToolPreselect.newValue===!0,r=!0),e.toolConfirmationEnabled&&(ta=e.toolConfirmationEnabled.newValue!==!1,r=!0),r&&Da(),n&&(document.getElementById(`toolsPopupOverlay`)?.classList.contains(`show`)&&(Sa(),Ca(),ma()),Ea())}),Zi().then(()=>Ea()),Qi().then(()=>Ea());var na=!1,ra=!0,ia=!1;chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`enableImageInput`],e=>{na=e.mcpEnabled===!0,ra=e.skillsEnabled!==!1,ia=e.enableImageInput===!0,Ea()});function aa(){let e=[...x,...Ji],t=N.activeAgentToolIds,n=e;if(t!=null){let r=new Set(t);n=e.filter(e=>r.has(e.id))}return ra||(n=n.filter(e=>e.id!==`agent_skill`)),N.agentPlatform?.connected!==!0&&(n=n.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),ia||(n=n.filter(e=>e.id!==`read_image`)),n}function oa(){if(!na||N.agentPlatform?.connected!==!0)return[];let e=new Map;return qi.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 sa(e){return Array.isArray(N.mcpClosedServers)&&N.mcpClosedServers.includes(e)}function ca(e){return Array.isArray(N.activeAgentMcpExcludedServerIds)&&N.activeAgentMcpExcludedServerIds.includes(e)}function la(e){return!sa(e)&&!ca(e)}function ua(){if(N.currentCategory!==`all`&&N.currentCategory!==`mcp`)return[];let e=oa();if(N.currentSearch){let t=N.currentSearch;e=e.filter(e=>(e.serverName||``).toLowerCase().includes(t)||(e.serverId||``).toLowerCase().includes(t)||e.tools.some(e=>(e.name||``).toLowerCase().includes(t)||Yi(e).toLowerCase().includes(t)))}return e}function da(e,t){Array.isArray(N.mcpClosedServers)||(N.mcpClosedServers=[]);let n=N.mcpClosedServers.indexOf(e);t?n>-1&&N.mcpClosedServers.splice(n,1):n===-1&&N.mcpClosedServers.push(e)}async function fa(){let e=document.getElementById(`toolsPopupOverlay`);if(!e)return;N.currentCategory=`all`,N.currentSearch=``;let t=document.getElementById(`toolsSearchInput`);t&&(t.value=``),await Zi(),await Qi(),await $i(),Sa(),Ca(),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)`)}),ma(),e.classList.add(`show`),a.debug(`[SidePanel] opentool popup`)}function pa(){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 ma(){let e=document.getElementById(`toolsPopupList`);if(!e)return;e.innerHTML=``;let t=aa();if(N.activeAgentToolIds!==null&&N.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(N.currentCategory!==`all`&&e.category!==N.currentCategory)return;if(N.currentSearch){let t=e.name.toLowerCase().includes(N.currentSearch),n=Yi(e).toLowerCase().includes(N.currentSearch);if(!t&&!n)return}let t=e.category||`other`;n[t]||(n[t]=[]),n[t].push(e)});let i=ua();if(Ln.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=>la(e.serverId)).length}/${c.length}`;else{let e=t.filter(e=>e.category===a);l=`${e.filter(e=>N.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=N.collapsedCategories[a]||!1;d.innerHTML=`
27
+ `;let s=e.closest(`.message-fullscreen-overlay`);(s&&s.querySelector(`.message-fullscreen-rail`)||er(`toc`)).appendChild(i),N.messageTocContainer=i;let c=i.querySelector(`.message-toc-toggle`),l=i.querySelector(`.message-toc-panel`);c.addEventListener(`mouseenter`,()=>{l.classList.add(`expanded`),Ft(l)}),c.addEventListener(`click`,()=>{l.classList.toggle(`expanded`)?Ft(l):Wt(l)}),l.addEventListener(`mouseenter`,()=>{l.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 sr(){N.tocHideTimer&&=(clearTimeout(N.tocHideTimer),null),N.messageTocContainer&&=(N.messageTocContainer.remove(),null)}var cr=`promptQueues`,lr=1,ur=30*1e3,dr=15*1e3,fr=20,R={QUEUED:`queued`,DISPATCHING:`dispatching`,INJECTING:`injecting`,INJECTED:`injected`,DONE:`done`,FAILED:`failed`};new Set([R.INJECTED,R.DONE,R.FAILED]);var pr={async get(e){let t=await chrome.storage.local.get(e);return t?t[e]:void 0},async set(e){await chrome.storage.local.set(e)}};function mr(){return{version:lr,sessions:{}}}var z=mr(),hr=!1,gr=null,_r=!1,vr=``,yr=new Set,br=new Set;function xr(){return{items:[],recent:[],paused:!1,pausedReason:null}}function Sr(e){return e?(z.sessions[e]||(z.sessions[e]=xr()),z.sessions[e]):xr()}function Cr(){return JSON.stringify(z)}function wr(e,t){for(let n of br)try{n(e,t)}catch(e){a.error(`[QueueStore] listener failed:`,e?.message)}}function Tr(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`q_`+crypto.randomUUID():`q_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,8)}function Er(e){return e.reduce((e,t)=>Math.max(e,Number(t.order)||0),0)+1}function Dr(e,t){let n=e.indexOf(t);n<0||(e.splice(n,1),e.unshift(t),Or(e))}function Or(e){e.forEach((e,t)=>{e.order=t+1})}function kr(e){return e.slice().sort((e,t)=>(Number(e.order)||0)-(Number(t.order)||0))}async function Ar(e){if(_r)return a.error(`[QueueStore] persist skipped in degraded mode:`,e),!1;let t=Cr();vr=t,jr(t);try{await pr.set({[cr]:z})}catch(e){a.error(`[QueueStore] persist failed:`,e?.message)}wr(e)}function jr(e){if(yr.add(e),yr.size<=fr)return;let t=yr.values().next().value;yr.delete(t)}function Mr(e,{recoverInterrupted:t=!0}={}){let n=mr();if(!e||typeof e!=`object`)return n;let r=e.sessions&&typeof e.sessions==`object`?e.sessions:{};for(let[e,i]of Object.entries(r)){let r=Array.isArray(i?.items)?i.items:[],a=Array.isArray(i?.recent)?i.recent.slice(0,30):[],o=!1;for(let e of r)!e||typeof e!=`object`||t&&(e.status===R.DISPATCHING||e.status===R.INJECTING)&&(e.status=R.QUEUED,e.interrupted=!0,e.previousStatus=e.previousStatus||R.DISPATCHING,e.leaseOwner=null,e.leaseUntil=0,o=!0);let s=kr(r);if(o){let e=s.filter(e=>e.interrupted),t=s.filter(e=>!e.interrupted);s.splice(0,s.length,...e,...t)}Or(s);let c=s.slice(0,20),l=s.slice(20);for(let e of l.reverse())a.unshift(ti({...e,status:R.FAILED,lastError:`over_limit`}));n.sessions[e]={items:c,recent:a.slice(0,30),paused:i?.paused===!0,pausedReason:i?.pausedReason||null}}return n}function Nr(){return _r}async function Pr(){return hr?z:gr||(gr=(async()=>{let e;try{e=await pr.get(cr)}catch(e){return _r=!0,gr=null,a.error(`[QueueStore] load failed, enter degraded mode:`,e?.message),z}return z=Mr(e),hr=!0,_r=!1,vr=Cr(),z})(),gr)}function Fr(){typeof chrome>`u`||!chrome.storage?.onChanged?.addListener||chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`||!e?.[cr])return;let n=e[cr].newValue;if(!n)return;let r=JSON.stringify(n);yr.has(r)||r===vr||(z=Mr(n,{recoverInterrupted:!1}),hr=!0,vr=r,wr(`external`,null))})}function Ir(e){return typeof e==`function`?(br.add(e),()=>br.delete(e)):()=>{}}function Lr(e){let t=z.sessions[e];return t?kr(t.items):[]}function Rr(e,t=30){let n=z.sessions[e];return n?n.recent.slice(0,t):[]}function zr(e){let t=z.sessions[e];return t?{items:kr(t.items),recent:t.recent.slice(),paused:t.paused===!0,pausedReason:t.pausedReason||null}:xr()}function Br(e){return Lr(e).filter(e=>e.status===R.QUEUED).length}function Vr(e){return Lr(e).find(e=>e.status===R.QUEUED)||null}function Hr(e){let t=z.sessions[e];if(!t)return null;for(let e=t.items.length-1;e>=0;--e)if(t.items[e].status===R.QUEUED)return t.items[e];return null}function Ur(e,t){let n=z.sessions[e];return n&&n.items.find(e=>e.id===t)||null}function Wr(){return Object.keys(z.sessions).filter(e=>(z.sessions[e]?.items?.length||0)>0)}function Gr(e){return z.sessions[e]?.paused===!0}async function Kr({sessionId:e,text:t,contextSnapshot:n=null,hasContext:r=!1,attachmentSummary:i=null,source:a=`manual`}){if(!e)return{ok:!1,error:`missing_session`};let o=String(t||``).trim();if(!o)return{ok:!1,error:`empty`};if(await Pr(),_r)return{ok:!1,error:`storage_unavailable`};let s=Sr(e);if(s.items.length>=20)return{ok:!1,error:`queue_full`,limit:20};let c={id:Tr(),sessionId:e,text:o,contextSnapshot:n||null,attachmentSummary:i||null,hasContext:r===!0,status:R.QUEUED,order:Er(s.items),createdAt:Date.now(),updatedAt:Date.now(),attempts:0,lastError:null,source:a,interrupted:!1,leaseOwner:null,leaseUntil:0,injectRequestedAt:0,injectDeadlineAt:0,injectedIntoCallId:null,absorbedIteration:null};return s.items.push(c),await Ar(`enqueue`),{ok:!0,item:c,position:s.items.length}}async function qr(e,t){let n=z.sessions[e];if(!n)return!1;let r=n.items.findIndex(e=>e.id===t);return r<0?!1:(n.items.splice(r,1),Or(n.items),await Ar(`remove`),!0)}async function Jr(e,t){let n=z.sessions[e];if(!n||!Array.isArray(t))return!1;let r=new Map(n.items.map(e=>[e.id,e])),i=[];for(let e of t){let t=r.get(e);t&&!i.includes(t)&&i.push(t)}for(let e of kr(n.items))i.includes(e)||i.push(e);return n.items=i,Or(n.items),await Ar(`reorder`),!0}async function Yr(e,t,n,r={}){let i=Ur(e,t);return i?(i.status=n,Object.assign(i,r,{updatedAt:Date.now()}),await Ar(`status`),!0):!1}async function Xr(e,t,n=dr){let r=Ur(e,t);return r?(r.previousStatus=r.status,r.status=R.INJECTING,r.injectRequestedAt=Date.now(),r.injectDeadlineAt=Date.now()+n,r.updatedAt=Date.now(),await Ar(`inject:request`),!0):!1}async function Zr(e,t,n=`error`,r=null){let i=z.sessions[e];if(!i)return!1;let a=i.items.find(e=>e.id===t);return a?(a.status=R.QUEUED,a.injectDeadlineAt=0,a.updatedAt=Date.now(),a.lastError=r||n,a.rollbackReason=n,Dr(i.items,a),await Ar(`inject:rollback`),!0):!1}async function Qr(e,t,{status:n,note:r=null,callId:i=null,iteration:a=null}={}){let o=z.sessions[e];if(!o)return!1;let s=o.items.findIndex(e=>e.id===t);if(s<0)return!1;let[c]=o.items.splice(s,1);return Or(o.items),c.status=n||R.DONE,c.settledAt=Date.now(),c.settleNote=r,i&&(c.injectedIntoCallId=i),a!=null&&(c.absorbedIteration=a),o.recent.unshift(ti(c)),o.recent=o.recent.slice(0,30),await Ar(`settle`),!0}async function $r(e,t){let n=z.sessions[e];if(!n)return{ok:!1,error:`missing_session`};let r=n.recent.findIndex(e=>e.id===t);if(r<0)return{ok:!1,error:`not_found`};if(n.items.length>=20)return{ok:!1,error:`queue_full`,limit:20};let[i]=n.recent.splice(r,1),a={...i,status:R.QUEUED,order:Er(n.items),attempts:0,lastError:null,interrupted:!1,rollbackReason:null,settledAt:null,leaseOwner:null,leaseUntil:0,injectDeadlineAt:0,updatedAt:Date.now()};return n.items.push(a),await Ar(`requeue`),{ok:!0,item:a}}async function ei(e,t){let n=z.sessions[e];if(!n)return!1;let r=n.recent.findIndex(e=>e.id===t);return r<0?!1:(n.recent.splice(r,1),await Ar(`recent-remove`),!0)}function ti(e){let{leaseOwner:t,leaseUntil:n,injectDeadlineAt:r,contextSnapshot:i,...a}=e;return{...a,hasContext:e.hasContext===!0,contextDropped:!!i}}async function ni(e,t=`user_stopped`){let n=Sr(e);return n.paused?!1:(n.paused=!0,n.pausedReason=t,await Ar(`pause`),!0)}async function ri(e){let t=z.sessions[e];return!t||!t.paused?!1:(t.paused=!1,t.pausedReason=null,await Ar(`resume`),!0)}async function ii(e,t,n){let r=Ur(e,t);if(!r)return!1;let i=Date.now();return r.leaseOwner&&r.leaseOwner!==n&&Number(r.leaseUntil)>i?!1:(r.leaseOwner=n,r.leaseUntil=i+ur,await Ar(`lease`),!0)}async function ai(e){let t=z.sessions[e];if(!t)return 0;let n=t.items.length+t.recent.length;return delete z.sessions[e],n>0&&await Ar(`drop-session`),n}var oi=`ai-helper-queue-attachments`,si=1,ci=`attachments`,li=null,ui=null;function di(){return new Promise((e,t)=>{let n=indexedDB.open(oi,si);n.onupgradeneeded=e=>{let t=e.target.result;t.objectStoreNames.contains(ci)||t.createObjectStore(ci,{keyPath:`id`}).createIndex(`sessionId`,`sessionId`,{unique:!1})},n.onsuccess=t=>{let n=t.target.result;n.onversionchange=()=>{try{n.close()}catch{}li=null},e(n)},n.onerror=()=>t(n.error||Error(`idb_open_failed`)),n.onblocked=()=>{}})}function fi(){return li||=di(),li}function pi(e,t){return fi().then(n=>new Promise((r,i)=>{let a;try{a=n.transaction(ci,e)}catch(e){li=null,i(e);return}let o=a.objectStore(ci),s=null,c=e=>{s=e};try{t(o,c)}catch(e){i(e);return}a.oncomplete=()=>r(s),a.onerror=()=>i(a.error||Error(`idb_tx_failed`)),a.onabort=()=>i(a.error||Error(`idb_tx_aborted`))}))}function mi(){return{async put(e){await pi(`readwrite`,t=>{t.put(e)})},async get(e){return pi(`readonly`,(t,n)=>{let r=t.get(e);r.onsuccess=()=>n(r.result||null)})},async remove(e){await pi(`readwrite`,t=>{t.delete(e)})},async removeBySession(e){await pi(`readwrite`,t=>{let n=t.index(`sessionId`).getAllKeys(e);n.onsuccess=()=>{for(let e of n.result||[])t.delete(e)}})},async allKeys(){return pi(`readonly`,(e,t)=>{let n=e.getAllKeys();n.onsuccess=()=>t(n.result||[])})}}}function hi(){return ui||mi()}function gi(e){return e==null?0:typeof e==`string`?e.length:typeof e==`number`||typeof e==`boolean`?8:Array.isArray(e)?e.reduce((e,t)=>e+gi(t),0):typeof e==`object`?Object.values(e).reduce((e,t)=>e+gi(t),0):0}function _i(e){let t=e&&e.attachedImages||[],n=e&&e.attachedFiles||[];return!t.length&&!n.length?null:{imageCount:t.length,fileCount:n.length,fileNames:n.map(e=>e.name).filter(Boolean).slice(0,5)}}async function vi(e,t,{images:n=[],files:r=[]}={}){if(!e)return{ok:!1,reason:`missing_id`};if(!n.length&&!r.length)return{ok:!0,skipped:!0};let i=gi(n)+gi(r);if(i>26214400)return{ok:!1,reason:`too_large`,size:i};try{return await hi().put({id:e,sessionId:t||null,size:i,images:n,files:r,updatedAt:Date.now()}),{ok:!0,size:i}}catch(e){return{ok:!1,reason:`idb_error`,message:e?.message||String(e)}}}async function yi(e){if(!e)return null;try{let t=await hi().get(e);return t?{images:t.images||[],files:t.files||[]}:null}catch{return null}}async function bi(e){if(!e)return!1;try{return await hi().remove(e),!0}catch{return!1}}async function xi(e){if(!e)return!1;try{return await hi().removeBySession(e),!0}catch{return!1}}async function Si(e){let t=e instanceof Set?e:new Set(e||[]);try{let e=await hi().allKeys(),n=0;for(let r of e||[])t.has(r)||(await hi().remove(r),n+=1);return n}catch{return 0}}var Ci=t({appendMessageToSession:()=>Gi,archiveCurrentSession:()=>Ri,archiveSession:()=>Vi,clearSessionCompleted:()=>Oi,createSession:()=>Ni,deleteArchivedSession:()=>Ui,deleteSession:()=>Fi,duplicateSession:()=>Ki,hydrateSessionWorkdir:()=>ji,importSessions:()=>Wi,isSessionArchivable:()=>Bi,loadArchivedSessions:()=>zi,loadSessions:()=>ki,markSessionCompleted:()=>Di,persistSessionState:()=>Mi,renameSession:()=>Ii,reorderSessions:()=>Li,restoreCompletedSessions:()=>Ti,restoreSession:()=>Hi,saveCurrentSession:()=>Ai,switchToSession:()=>Pi}),wi=`completedSessionIds`;async function Ti(){try{let e=(await chrome.storage.local.get([wi]))[wi]||[];N.completedSessionIds=new Set(e)}catch(e){a.warn(`[SessionManager] restore completedSessionIds failed:`,e)}}async function Ei(){try{await chrome.storage.local.set({[wi]:Array.from(N.completedSessionIds)})}catch(e){a.warn(`[SessionManager] persist completedSessionIds failed:`,e)}}async function Di(e){e&&e!==N.activeSessionId&&(N.completedSessionIds.has(e)||(N.completedSessionIds.add(e),await Ei(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))))}async function Oi(e){e&&N.completedSessionIds.has(e)&&(N.completedSessionIds.delete(e),await Ei(),document.dispatchEvent(new CustomEvent(`generating-state-changed`)))}async function ki(){return ke()}async function Ai(){return Pe()}function ji(e){return Oe(e)}async function Mi(e,t){return Me(e,t)}async function Ni(){return Ee()}async function Pi(e){return nt(e)}async function Fi(e){await ai(e)>0&&xi(e);let t=await We(e);try{chrome.runtime.sendMessage({type:`DROP_GOAL`,sessionId:e},()=>{chrome.runtime.lastError&&a.debug(`[SessionManager] DROP_GOAL skipped:`,chrome.runtime.lastError.message)})}catch(e){a.debug(`[SessionManager] DROP_GOAL send failed:`,e?.message)}return N.completedSessionIds.has(e)&&(N.completedSessionIds.delete(e),await Ei()),t}async function Ii(e,t){return Ke(e,t)}async function Li(e){return Be(e)}async function Ri(){return He()}async function zi(){return $e()}function Bi(e){return e?N.generatingSessionIds.has(e)||N.pendingCallApiSessionIds.has(e)?{ok:!1,reason:`running`}:Br(e)>0?{ok:!1,reason:`queued`}:{ok:!0}:{ok:!1,reason:`missing`}}async function Vi(e){let t=Bi(e);return t.ok?await Je(e)?(N.completedSessionIds.has(e)&&(N.completedSessionIds.delete(e),await Ei(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))),{ok:!0}):{ok:!1,reason:`missing`}:t}async function Hi(e){return at(e)}async function Ui(e){return Fi(e)}async function Wi(e){return Re(e)}async function Gi(e,t){return Ze(e,t)}async function Ki(e,t=null){return Xe(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 qi=[],Ji=[];function Yi(e){if(!e)return``;let t=`tool.${e.id}`,n=r(t);return n===t?e.description||``:n}function Xi(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 Zi(){try{let e=await chrome.runtime.sendMessage({type:`GET_MCP_TOOLS`});if(e?.success&&e.tools)return qi=e.tools,qi}catch{}try{return qi=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[],qi}catch{return qi=[],[]}}async function Qi(){try{Ji=(await chrome.storage.local.get([`ragTools`])).ragTools||[]}catch{Ji=[]}return Ji}async function $i(){let e=`agentMcpClosedServers_${N.activeAgentId||`default`}`;try{N.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}catch{N.mcpClosedServers=[]}try{let{getAgent:e}=await M(async()=>{let{getAgent:e}=await import(`./agent-store-1fyaAv9T.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3,4])),t=N.activeAgentId?await e(N.activeAgentId):null;N.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null}catch{}}var ea=!1,ta=!0;chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{ea=e.enableToolPreselect===!0,ta=e.toolConfirmationEnabled!==!1,Da()}),chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`)return;let n=!1;e.mcpTools&&(qi=e.mcpTools.newValue||[],a.debug(`[SidePanel] MCP toolcache updated:`,qi.length,``),n=!0),e.ragTools&&(Ji=e.ragTools.newValue||[],a.debug(`[SidePanel] RAG toolcache updated:`,Ji.length),n=!0),e.mcpEnabled&&(na=e.mcpEnabled.newValue===!0,a.debug(`[SidePanel] MCP globaltoggle changed:`,na),n=!0),e.skillsEnabled&&(ra=e.skillsEnabled.newValue!==!1,a.debug(`[SidePanel] Skill global toggle changed:`,ra),n=!0),e.enableImageInput&&(ia=e.enableImageInput.newValue===!0,a.debug(`[SidePanel] 图片识别全局开关变更:`,ia),n=!0);let r=!1;e.enableToolPreselect&&(ea=e.enableToolPreselect.newValue===!0,r=!0),e.toolConfirmationEnabled&&(ta=e.toolConfirmationEnabled.newValue!==!1,r=!0),r&&Da(),n&&(document.getElementById(`toolsPopupOverlay`)?.classList.contains(`show`)&&(Sa(),Ca(),ma()),Ea())}),Zi().then(()=>Ea()),Qi().then(()=>Ea());var na=!1,ra=!0,ia=!1;chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`enableImageInput`],e=>{na=e.mcpEnabled===!0,ra=e.skillsEnabled!==!1,ia=e.enableImageInput===!0,Ea()});function aa(){let e=[...x,...Ji],t=N.activeAgentToolIds,n=e;if(t!=null){let r=new Set(t);n=e.filter(e=>r.has(e.id))}return ra||(n=n.filter(e=>e.id!==`agent_skill`)),N.agentPlatform?.connected!==!0&&(n=n.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),ia||(n=n.filter(e=>e.id!==`read_image`)),n}function oa(){if(!na||N.agentPlatform?.connected!==!0)return[];let e=new Map;return qi.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 sa(e){return Array.isArray(N.mcpClosedServers)&&N.mcpClosedServers.includes(e)}function ca(e){return Array.isArray(N.activeAgentMcpExcludedServerIds)&&N.activeAgentMcpExcludedServerIds.includes(e)}function la(e){return!sa(e)&&!ca(e)}function ua(){if(N.currentCategory!==`all`&&N.currentCategory!==`mcp`)return[];let e=oa();if(N.currentSearch){let t=N.currentSearch;e=e.filter(e=>(e.serverName||``).toLowerCase().includes(t)||(e.serverId||``).toLowerCase().includes(t)||e.tools.some(e=>(e.name||``).toLowerCase().includes(t)||Yi(e).toLowerCase().includes(t)))}return e}function da(e,t){Array.isArray(N.mcpClosedServers)||(N.mcpClosedServers=[]);let n=N.mcpClosedServers.indexOf(e);t?n>-1&&N.mcpClosedServers.splice(n,1):n===-1&&N.mcpClosedServers.push(e)}async function fa(){let e=document.getElementById(`toolsPopupOverlay`);if(!e)return;N.currentCategory=`all`,N.currentSearch=``;let t=document.getElementById(`toolsSearchInput`);t&&(t.value=``),await Zi(),await Qi(),await $i(),Sa(),Ca(),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)`)}),ma(),e.classList.add(`show`),a.debug(`[SidePanel] opentool popup`)}function pa(){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 ma(){let e=document.getElementById(`toolsPopupList`);if(!e)return;e.innerHTML=``;let t=aa();if(N.activeAgentToolIds!==null&&N.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(N.currentCategory!==`all`&&e.category!==N.currentCategory)return;if(N.currentSearch){let t=e.name.toLowerCase().includes(N.currentSearch),n=Yi(e).toLowerCase().includes(N.currentSearch);if(!t&&!n)return}let t=e.category||`other`;n[t]||(n[t]=[]),n[t].push(e)});let i=ua();if(Ln.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=>la(e.serverId)).length}/${c.length}`;else{let e=t.filter(e=>e.category===a);l=`${e.filter(e=>N.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=N.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>
@@ -1105,7 +1105,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
1105
1105
  <source src="${c}" type="${J(o)}">
1106
1106
  </audio>
1107
1107
  <div id="mediaUnsupportedHint" style="display:none;">${u}</div>
1108
- </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 f_=!1;function p_(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 m_(e,t){p_(e,t),t.classList.add(`show`)}function h_(){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`):m_(t,n)});let r=null,i=null;e.addEventListener(`mouseenter`,()=>{i&&=(clearTimeout(i),null),r=setTimeout(()=>{m_(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`),__(r)})}),document.addEventListener(`click`,t=>{!e.contains(t.target)&&!n.contains(t.target)&&n.classList.remove(`show`)});let a=()=>{n.classList.contains(`show`)&&p_(t,n)};document.getElementById(`workspacePreviewContent`)?.addEventListener(`scroll`,a),window.addEventListener(`resize`,a)}function g_(){return document.getElementById(`workspacePreviewArea`).dataset.markdownText||``}async function __(e){if(f_)return;f_=!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 b_(i);break;case`pdf`:await S_(i);break;case`image`:await C_(i);break;case`md`:w_(i);break}}catch(e){a.error(`[WorkspacePanel] export failed:`,e),L(r(`chatExport.exportFailed`,{message:e.message}),`error`)}finally{f_=!1,t.innerHTML=o,t.disabled=!1,t.style.opacity=`1`,n.classList.remove(`show`)}}async function v_(e){if(typeof mermaid>`u`)return;let{renderMermaidInContainer:t,convertSvgsToImages:n}=await M(async()=>{let{renderMermaidInContainer:e,convertSvgsToImages:t}=await import(`./chat-export-BPasibDS.js`);return{renderMermaidInContainer:e,convertSvgsToImages:t}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));await t(e),await n(e)}async function y_(e){if(typeof mermaid>`u`||!/```mermaid/i.test(e))return e;let{renderMermaidInContainer:t,convertSvgsToImages:n}=await M(async()=>{let{renderMermaidInContainer:e,convertSvgsToImages:t}=await import(`./chat-export-BPasibDS.js`);return{renderMermaidInContainer:e,convertSvgsToImages:t}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));try{let r=on(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 b_(e){let{Packer:t}=await M(async()=>{let{Packer:e}=await import(`./dist-BUuoW_84.js`);return{Packer:e}},__vite__mapDeps([11,1])),{createDocxDocument:n}=await M(async()=>{let{createDocxDocument:e}=await import(`./chat-export-BPasibDS.js`);return{createDocxDocument:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0])),i=g_();if(!i){L(r(`chatExport.noContent`),`error`);return}i=await y_(i);let a=n(await x_(i)),o=await t.toBlob(a),s=`word-${new Date().getTime()}.docx`;T_(o,s),L(r(`workspace.downloaded`,{name:s}),`success`)}async function x_(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 M(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-BUuoW_84.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,sanitizeDocxText:g,nextDocxImageId:_,isDocxEmbeddableImageType:v}=await M(async()=>{let{createTextRuns:e,sanitizeDocxText:t,nextDocxImageId:n,isDocxEmbeddableImageType:r}=await import(`./chat-export-BPasibDS.js`);return{createTextRuns:e,sanitizeDocxText:t,nextDocxImageId:n,isDocxEmbeddableImageType:r}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));if(!e||!e.trim())return[new r({children:[new i({text:``})]})];let y=[],b=g(e),x=[];b=b.replace(/```(\w*)\n([\s\S]*?)```/g,(e,t,n)=>{let r=x.length;return x.push({lang:t||``,code:n.trimEnd()}),`\n\n%%CODEBLOCK_${r}%%\n\n`});let S=[];b=b.replace(/<table[\s\S]*?<\/table>/gi,e=>{let t=S.length;return S.push(e),`\n\n%%HTMLTABLE_${t}%%\n\n`});let C=[];b=b.replace(/(?:^\|.+\|\s*$\n)+^\|[\s\-:|]+\|\s*$\n(?:^\|.+\|\s*$\n?)+/gm,e=>{let t=C.length;return C.push(e),`\n\n%%MDTABLE_${t}%%\n\n`});let w=b.split(/\n{2,}/).filter(e=>e.trim());function T(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[r,a]=t.split(`,`),o=r.match(/data:(image\/(\w+))/);if(o&&a&&v(o[2])){let t=atob(a),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);n.push(new f({data:r,transformation:{width:400,height:300},type:o[2],altText:{id:_(),name:e[9]||`image`}}))}else n.push(new i({text:`[Image: `+(e[9]||`image`)+`]`,italics:!0,color:`999999`}))}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 E(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 D(e){let t=e.trim().split(`
1108
+ </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 f_=!1;function p_(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 m_(e,t){p_(e,t),t.classList.add(`show`)}function h_(){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`):m_(t,n)});let r=null,i=null;e.addEventListener(`mouseenter`,()=>{i&&=(clearTimeout(i),null),r=setTimeout(()=>{m_(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`),__(r)})}),document.addEventListener(`click`,t=>{!e.contains(t.target)&&!n.contains(t.target)&&n.classList.remove(`show`)});let a=()=>{n.classList.contains(`show`)&&p_(t,n)};document.getElementById(`workspacePreviewContent`)?.addEventListener(`scroll`,a),window.addEventListener(`resize`,a)}function g_(){return document.getElementById(`workspacePreviewArea`).dataset.markdownText||``}async function __(e){if(f_)return;f_=!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 b_(i);break;case`pdf`:await S_(i);break;case`image`:await C_(i);break;case`md`:w_(i);break}}catch(e){a.error(`[WorkspacePanel] export failed:`,e),L(r(`chatExport.exportFailed`,{message:e.message}),`error`)}finally{f_=!1,t.innerHTML=o,t.disabled=!1,t.style.opacity=`1`,n.classList.remove(`show`)}}async function v_(e){if(typeof mermaid>`u`)return;let{renderMermaidInContainer:t,convertSvgsToImages:n}=await M(async()=>{let{renderMermaidInContainer:e,convertSvgsToImages:t}=await import(`./chat-export-DeqIrNGG.js`);return{renderMermaidInContainer:e,convertSvgsToImages:t}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));await t(e),await n(e)}async function y_(e){if(typeof mermaid>`u`||!/```mermaid/i.test(e))return e;let{renderMermaidInContainer:t,convertSvgsToImages:n}=await M(async()=>{let{renderMermaidInContainer:e,convertSvgsToImages:t}=await import(`./chat-export-DeqIrNGG.js`);return{renderMermaidInContainer:e,convertSvgsToImages:t}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));try{let r=on(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 b_(e){let{Packer:t}=await M(async()=>{let{Packer:e}=await import(`./dist-BUuoW_84.js`);return{Packer:e}},__vite__mapDeps([11,1])),{createDocxDocument:n}=await M(async()=>{let{createDocxDocument:e}=await import(`./chat-export-DeqIrNGG.js`);return{createDocxDocument:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0])),i=g_();if(!i){L(r(`chatExport.noContent`),`error`);return}i=await y_(i);let a=n(await x_(i)),o=await t.toBlob(a),s=`word-${new Date().getTime()}.docx`;T_(o,s),L(r(`workspace.downloaded`,{name:s}),`success`)}async function x_(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 M(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-BUuoW_84.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,sanitizeDocxText:g,nextDocxImageId:_,isDocxEmbeddableImageType:v}=await M(async()=>{let{createTextRuns:e,sanitizeDocxText:t,nextDocxImageId:n,isDocxEmbeddableImageType:r}=await import(`./chat-export-DeqIrNGG.js`);return{createTextRuns:e,sanitizeDocxText:t,nextDocxImageId:n,isDocxEmbeddableImageType:r}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));if(!e||!e.trim())return[new r({children:[new i({text:``})]})];let y=[],b=g(e),x=[];b=b.replace(/```(\w*)\n([\s\S]*?)```/g,(e,t,n)=>{let r=x.length;return x.push({lang:t||``,code:n.trimEnd()}),`\n\n%%CODEBLOCK_${r}%%\n\n`});let S=[];b=b.replace(/<table[\s\S]*?<\/table>/gi,e=>{let t=S.length;return S.push(e),`\n\n%%HTMLTABLE_${t}%%\n\n`});let C=[];b=b.replace(/(?:^\|.+\|\s*$\n)+^\|[\s\-:|]+\|\s*$\n(?:^\|.+\|\s*$\n?)+/gm,e=>{let t=C.length;return C.push(e),`\n\n%%MDTABLE_${t}%%\n\n`});let w=b.split(/\n{2,}/).filter(e=>e.trim());function T(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[r,a]=t.split(`,`),o=r.match(/data:(image\/(\w+))/);if(o&&a&&v(o[2])){let t=atob(a),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);n.push(new f({data:r,transformation:{width:400,height:300},type:o[2],altText:{id:_(),name:e[9]||`image`}}))}else n.push(new i({text:`[Image: `+(e[9]||`image`)+`]`,italics:!0,color:`999999`}))}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 E(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 D(e){let t=e.trim().split(`
1109
1109
  `),n=[];for(let e of t){if(/^[\s\|:\-]+$/.test(e.replace(/\|/g,``)))continue;let t=Yt(e).slice(1,-1).map(e=>e.trim());t.length>0&&n.push(t)}return n}function O(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:T(o),spacing:{before:40,after:40}})],shading:n===0?{fill:`F2F2F2`}:void 0,width:{size:Math.round(100/t*100)/100,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 w){let t=e.trim(),n=t.match(/^%%CODEBLOCK_(\d+)%%$/);if(n){let{lang:e,code:t}=x[parseInt(n[1])],a=e?`${e} code`:`code`;y.push(new r({children:[new i({text:a,bold:!0,font:`Consolas`,size:18})]}));let o=t.split(`
1110
1110
  `);for(let e of o)y.push(new r({children:[new i({text:e||` `,font:`Consolas`,size:18})],spacing:{before:0,after:0,line:240},shading:{fill:`F5F5F5`}}));y.push(new r({children:[new i({text:``})]}));continue}let o=t.match(/^%%HTMLTABLE_(\d+)%%$/);if(o){let e=E(S[parseInt(o[1])]);e.length>0&&(y.push(O(e)),y.push(new r({children:[new i({text:``})]})));continue}let s=t.match(/^%%MDTABLE_(\d+)%%$/);if(s){let e=D(C[parseInt(s[1])]);y.push(O(e)),y.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};y.push(new r({children:T(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&&y.push(new r({children:T(n),spacing:{before:60,after:60}}));continue}if(/^(---|\*\*\*|___)\s*$/.test(t)){y.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)y.push(new r({children:T(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)y.push(new r({children:T(e.replace(/^\d+\.\s+/,``)),numbering:{reference:`default`,level:0},spacing:{before:40,after:40}}));continue}if(t.startsWith(`>`)){let t=e.split(`
1111
1111
  `).map(e=>e.replace(/^>\s?/,``)).join(`
@@ -1198,7 +1198,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
1198
1198
  <span style="flex:1;">${J(e)}</span>
1199
1199
  ${t?a:``}${n?o:``}
1200
1200
  ${i?`<button class="switch-workdir-remove" data-remove-path="${J(e)}" title="${r(`workspace.removeFromAllowed`)}" style="flex-shrink:0;background:none;border:none;color:var(--danger-500);cursor:pointer;font-size:16px;line-height:1;padding:2px 6px;border-radius:4px;">×</button>`:``}
1201
- </div>`}).join(``)}C(),b&&b.addEventListener(`change`,()=>{a.querySelectorAll(`.switch-workdir-item.current`).forEach(e=>{e.style.cursor=T(e.dataset.path)?`pointer`:`default`})});async function w(e){let t=d(e,l)||d(e,c);if(!await window.showCustomConfirm(r(t?`workspace.confirmRemoveStillUsable`:`workspace.confirmRemovePath`,{path:e}),r(`workspace.confirmRemovePathTitle`)))return;let n=await Pn(e);n.success?(u=Array.isArray(n.allowedPaths)?n.allowedPaths:u.filter(t=>t!==e),C(),L(r(t?`workspace.removedStillUsable`:`workspace.removedFromAllowed`),`success`)):L(r(`workspace.removeFailedWithError`,{error:n.error||r(`workspace.unknownError`)}),`error`)}let T=e=>{if(!(b&&b.checked))return!1;let t=e=>String(e||``).replace(/\\/g,`/`).toLowerCase();return!l||t(e)!==t(l)};a.addEventListener(`click`,e=>{let t=e.target.closest(`.switch-workdir-remove`);if(t){e.stopPropagation(),w(t.dataset.removePath);return}let n=e.target.closest(`.switch-workdir-item`);n&&(n.classList.contains(`current`)&&!T(n.dataset.path)||E(n.dataset.path))});async function E(n){if(!n){L(r(`workspace.selectOrInputPath`),`error`);return}n=n.trim();let a=e=>e.replace(/\\/g,`/`).toLowerCase(),o=(e,t)=>!!e&&!!t&&a(e)===a(t),s=!!(b&&b.checked);if(o(n,c)){if(s&&!o(n,l)){S(),e(await Yv(n));return}L(r(`workspace.alreadyCurrentWorkdir`),`info`),S(),e(!1);return}let d=i?t:null,f=!d||s;!u.some(e=>{let t=a(n),r=a(e);return t===r||t.startsWith(r+`/`)})&&f&&!await window.showCustomConfirm(r(`workspace.confirmSwitchToNewDefault`,{path:n}),r(`workspace.confirmSwitchToNewTitle`))||(S(),e(await Xv(n,{sessionId:d,setAsDefault:s})))}y&&y.addEventListener(`click`,async()=>{y.disabled=!0,S(),e(await Zv(t,{sessionSupported:i}))}),g.addEventListener(`click`,()=>E(m.value)),h.addEventListener(`click`,()=>{S(),e(!1)}),_.addEventListener(`click`,()=>{S(),e(!1)}),_.addEventListener(`mouseenter`,()=>{_.style.color=`var(--text-primary)`,_.style.background=`var(--border-subtle)`}),_.addEventListener(`mouseleave`,()=>{_.style.color=`var(--text-tertiary)`,_.style.background=`transparent`}),m.addEventListener(`keydown`,t=>{t.key===`Enter`&&(t.preventDefault(),E(m.value)),t.key===`Escape`&&(S(),e(!1))}),n.addEventListener(`click`,e=>{e.target===n&&e.stopPropagation()}),setTimeout(()=>m.focus(),50)})}function Wv(){Jm=null,K=null,Ym=[],q.clear(),Ov=``,kv=[],Av=!1,Vh.clear();let e=document.getElementById(`workspaceSearchInput`);e&&(e.value=``);let t=document.getElementById(`workspaceSearchClear`);t&&(t.style.display=`none`);let n=document.getElementById(`workspaceToolbar`);if(n){n.classList.remove(`search-focused`);let e=n.querySelector(`.workspace-search-box`);e&&e.classList.remove(`search-box-expanded`)}}var Gv=0;async function Kv(){let e=++Gv;if(N.agentPlatform?.connected!==!0){ln(),Wv();return}await sv();let t=Jm;ln();let n=null;try{n=await bn()}catch(e){a.warn(`[WorkspacePanel] resolve root for session failed:`,e?.message||e)}if(e!==Gv||t&&n&&t===n)return;Wv();let r=document.getElementById(`workspacePreviewArea`);if(r&&r.dataset.previewPath&&(ph=!1,await L_(!0)),await Promise.resolve(),e!==Gv)return;let i=document.getElementById(`workspacePanel`);!i||!i.classList.contains(`expanded`)||await zh()}async function qv(e,t){document.dispatchEvent(new CustomEvent(`session-workdir-changed`,{detail:{sessionId:e,workdir:t}}))}async function Jv(e){N.defaultWorkdir=e,N.agentPlatform&&={...N.agentPlatform,workdir:e};try{let{activeAgentId:t}=await chrome.storage.local.get([`activeAgentId`]);t&&(N.agentWorkdirs.set(t,e),typeof window.updateAgentItemWorkdir==`function`&&window.updateAgentItemWorkdir(t,e))}catch(e){a.debug(`[WorkspacePanel] sync dropdown column table workdir failed:`,e)}}async function Yv(e){let t=await un(e,{sessionId:null});return t.success?(await Jv(t.workdir),await qv(null,t.workdir),L(r(`workspace.setAsDefaultDone`,{path:t.workdir}),`success`),!0):(L(r(`workspace.switchFailedWithError`,{error:t.error||r(`workspace.unknownError`)}),`error`),!1)}async function Xv(e,t={}){let n=t.sessionId===void 0?N.activeSessionId||null:t.sessionId,i=t.setAsDefault===!0,o=await un(e,{sessionId:n});if(!o.success)return L(r(`workspace.switchFailedWithError`,{error:o.error||r(`workspace.unknownError`)}),`error`),!1;if(n)try{let{setSessionWorkdirBinding:e}=await M(async()=>{let{setSessionWorkdirBinding:e}=await import(`./session-store-D93MJNgp.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([2,1,3,4])),t=(await Cn())?.id||null;await e(n,o.workdir,t)}catch(e){a.warn(`[WorkspacePanel] persist session workdir failed:`,e)}let s=!1;if(i){let e=await un(o.workdir,{sessionId:null});e.success?s=!0:L(r(`workspace.switchFailedWithError`,{error:e.error||r(`workspace.unknownError`)}),`error`)}return(!n||i)&&await Jv(o.workdir),await qv(n,o.workdir),L(r(s?`workspace.switchedToAndSetDefault`:`workspace.switchedTo`,{path:o.workdir}),`success`),!0}async function Zv(e,t={}){if(!e)return!1;let{unbindSessionWorkdirRemote:n}=await M(async()=>{let{unbindSessionWorkdirRemote:e}=await import(`./session-store-D93MJNgp.js`).then(e=>e.Ft);return{unbindSessionWorkdirRemote:e}},__vite__mapDeps([2,1,3,4]));if(await n(e)===null&&t.sessionSupported)return L(r(`workspace.switchFailedWithError`,{error:r(`workspace.unknownError`)}),`error`),!1;try{let{setSessionWorkdirBinding:t}=await M(async()=>{let{setSessionWorkdirBinding:e}=await import(`./session-store-D93MJNgp.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([2,1,3,4]));await t(e,null,null)}catch(e){a.warn(`[WorkspacePanel] clear session workdir failed:`,e)}return await qv(e,``),L(r(`workdirTag.restoredDefault`),`success`),!0}async function Qv(e,t,n){let i=t,a=``,o=t.lastIndexOf(`.`);n!==`directory`&&o>0&&(i=t.substring(0,o),a=t.substring(o));let s=await Hv(r(n===`directory`?`workspace.renameDir`:`workspace.renameFile`),i,r(`workspace.inputNewName`));if(!s||s===i)return;let c=s+a;try{let t=await fn(e,c);t.success?(L(r(`workspace.renamedTo`,{name:c}),`success`),Jh(K),await uv(),ry(c)):L(r(`workspace.renameFailedWithError`,{error:t.error}),`error`)}catch(e){L(r(`workspace.renameFailedWithError`,{error:e.message}),`error`)}}async function $v(){if(!K)return;let e=await Hv(r(`workspace.newFolderTitle`),``,r(`workspace.inputFolderName`));if(!e)return;let t=qh(`${K}/${e}`);try{let n=await Tn(t);n.success?(L(r(`workspace.folderCreated`,{name:e}),`success`),Jh(K),await uv(),ry(e)):L(r(`workspace.createFailedWithError`,{error:n.error}),`error`)}catch(e){L(r(`workspace.createFailedWithError`,{error:e.message}),`error`)}}async function ey(e){return new Promise((t,n)=>{let i=new Image,a=URL.createObjectURL(e);i.onload=()=>{URL.revokeObjectURL(a);let n=new FileReader;n.onloadend=()=>{let e=n.result,r=i.width,a=i.height,o=Math.max(r,a),s,c;o<=768?(s=o,c=.75):o<=1280?(s=768,c=.7):o<=2560?(s=1024,c=.65):o<=3840?(s=1280,c=.6):(s=1280,c=.55);let l=r,u=a;o>s&&(r>a?(u=Math.round(s/r*a),l=s):(l=Math.round(s/a*r),u=s));let d=document.createElement(`canvas`);d.width=l,d.height=u;let f=d.getContext(`2d`);f.imageSmoothingEnabled=!0,f.imageSmoothingQuality=`high`,f.drawImage(i,0,0,l,u),t({originalUrl:e,compressedUrl:d.toDataURL(`image/jpeg`,c)})},n.readAsDataURL(e)},i.onerror=()=>{URL.revokeObjectURL(a),n(Error(r(`workspace.imageLoadFailed`)))},i.src=a})}async function ty(e){let t=[],n=[];for(let r of e){let e=r&&typeof r==`object`,i=e?r.fullPath||r.path:r,a=i.split(/[\\/]/).pop(),o;e?o=r:(o=vh.find(e=>e.path===i),o||=kv.find(e=>e.fullPath===i));let s=o?o.size:0,c=wn(a);if(c.startsWith(`image/`)&&N.enableImageInput)n.push({name:a,size:s,type:c,path:i});else{let e={name:a,size:s,type:c,text:``,status:`done`,agentPath:i};t.push(e)}}for(let e of n)try{let t=await Cn();if(t){let n=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...An(t)},body:JSON.stringify({path:e.path})});if(n.ok){let{originalUrl:e,compressedUrl:t}=await ey(await n.blob());N.attachedImages.some(e=>e.compressedUrl===t)||N.attachedImages.push({originalUrl:e,compressedUrl:t})}}}catch{}for(let e of t)N.attachedFiles.some(t=>t.name===e.name&&t.agentPath===e.agentPath)||N.attachedFiles.push(e);bm(),Hm();let i=t.length+n.length;i>0&&(!N.enableImageInput&&t.some(e=>e.type?.startsWith(`image/`))?L(r(`workspace.addedFilesToQuestionNoImage`,{count:i}),`success`):L(r(`workspace.addedFilesToQuestion`,{count:i}),`success`))}async function ny(){q.size!==0&&await ty(Array.from(q))}function ry(e,t=0){let n=document.getElementById(`workspacePanelContent`);if(!n)return;if(Qh){let t=Qh.sorted.findIndex(t=>t.name===e);if(t>=0){let r=Qh.itemHeight;n.scrollTop=Math.max(0,t*r-n.clientHeight/2+r/2),tg();let i=Array.from(n.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.name===e);i&&(i.classList.add(`highlight-new`),setTimeout(()=>i.classList.remove(`highlight-new`),2e3));return}}let r=Array.from(n.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.name===e);r?(r.scrollIntoView({behavior:`smooth`,block:`center`}),r.classList.add(`highlight-new`),setTimeout(()=>r.classList.remove(`highlight-new`),2e3)):t<5&&setTimeout(()=>ry(e,t+1),150)}function iy(){let e=document.getElementById(`workspaceAskBtn`);q.size===0?e.style.display=`none`:e.style.display=``}function ay(){let e=document.getElementById(`workspaceDownloadDirBtn`),t=document.getElementById(`workspaceBatchDeleteBtn`),n=document.getElementById(`workspaceSelectedCount`);q.size===0?(e.style.display=`none`,t.style.display=`none`,n.style.display=`none`):(e.style.display=``,t.style.display=``,n.style.display=``,n.textContent=r(`workspace.selectedCount`,{count:q.size}),e.disabled=uh),iy()}n(`zh`,{artifacts:{btnTitle:`文件产物({count})`,modalTitle:`本次任务的文件产物`,emptyHint:`本次任务没有产生文件产物`,fileCol:`文件`,sizeCol:`大小`,typeCol:`类型`,timeCol:`时间`,actionCol:`操作`,locate:`定位到文件`,preview:`预览`,closeBtn:`关闭`,typeWrite:`写入`,typeDelete:`删除`,typeCreate:`创建`,typeEdit:`编辑`,typeOther:`操作`,noWorkspace:`无法获取工作目录,请确认 Agent 已连接`,locateFailed:`定位文件失败`,fileNotFound:`目录已定位,但未找到该文件(可能已被删除)`,previewFailed:`预览文件失败`,previewNotSupported:`此文件类型不支持预览`,totalCount:`共 {count} 个文件`,badgeLabel:`产物`,download:`下载`,downloadFailed:`下载失败`,copyFileName:`复制文件名`,copyFilePath:`复制文件路径`,copiedName:`已复制文件名:{name}`,copiedPath:`已复制文件路径`,dblClickHint:`双击文件名可预览`,sortHint:`点击排序`,serialCol:`序号`}}),n(`en`,{artifacts:{btnTitle:`Artifacts ({count})`,modalTitle:`File Artifacts of This Task`,emptyHint:`No file artifacts produced in this task`,fileCol:`File`,sizeCol:`Size`,typeCol:`Type`,timeCol:`Time`,actionCol:`Actions`,locate:`Locate File`,preview:`Preview`,closeBtn:`Close`,typeWrite:`Write`,typeDelete:`Delete`,typeCreate:`Create`,typeEdit:`Edit`,typeOther:`Op`,noWorkspace:`Unable to access working directory. Please confirm the Agent is connected.`,locateFailed:`Failed to locate file`,fileNotFound:`Directory located, but file not found (may have been deleted)`,previewFailed:`Failed to preview file`,previewNotSupported:`Preview not supported for this file type`,totalCount:`{count} files in total`,badgeLabel:`Artifacts`,download:`Download`,downloadFailed:`Download failed`,copyFileName:`Copy File Name`,copyFilePath:`Copy File Path`,copiedName:`Copied file name: {name}`,copiedPath:`File path copied`,dblClickHint:`Double-click to preview`,sortHint:`Click to sort`,serialCol:`#`}});function oy(e){let t=(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`),n=t.replace(/\/+$/,``);return n?/^[A-Za-z]:$/.test(n)?n+`/`:n:t?`/`:``}function sy(e){if(!e)return``;let t=oy(e).replace(/\/+$/,``).split(`/`);return t[t.length-1]||``}function cy(e){if(!e)return``;let t=sy(e),n=t.lastIndexOf(`.`);return n>0?t.substring(n+1).toLowerCase():``}function ly(e){return String(e??``).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}function uy(e,t){let n=new Set(t),r=[],i=0,a=``;for(let t of e)t===`{`?i++:t===`}`&&(i=Math.max(0,i-1)),i===0&&n.has(t)?(r.push(a),a=``):a+=t;return r.push(a),r}function dy(e){let t=e.indexOf(`{`);if(t===-1)return[e];let n=0,r=-1;for(let i=t;i<e.length;i++)if(e[i]===`{`)n++;else if(e[i]===`}`&&(n--,n===0)){r=i;break}if(r===-1)return[e];let i=e.substring(0,t),a=e.substring(t+1,r),o=e.substring(r+1),s=uy(a,`,`).map(e=>e.trim());if(s.length<=1)return[e];let c=[];for(let e of s)for(let t of dy(e))for(let e of dy(o))c.push(i+t+e);return c}function fy(e,t){let n=[],r=new Set;for(let i of e)if(i)for(let e of dy(i)){if(!e)continue;let i=t(e);!i||r.has(i)||(r.add(i),n.push(i))}return n}function py(e){if(!e)return null;let t=e;if(typeof t==`string`)try{t=JSON.parse(t)}catch{let e=t.match(/["']?path["']?\s*[:=]\s*["']([^"']+)["']/i);return e?e[1]:null}return t&&typeof t==`object`&&(t.path||t.filePath||t.file_path||t.result?.path)||null}function my(e){let t=[],n=0,r=``;for(let i=0;i<e.length;i++){let a=e[i];if(a===`{`?n++:a===`}`&&(n=Math.max(0,n-1)),n===0&&a===`<`&&e[i+1]===`<`){let t=hy(e,i);if(t>i){r+=e.substring(i,t),i=t-1;continue}}n===0&&a===`;`?(t.push(r),r=``):n===0&&a===`&`&&e[i+1]===`&`?(t.push(r),r=``,i++):r+=a}return t.push(r),t}function hy(e,t){let n=e.substring(t).match(/^<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/);if(!n)return-1;let r=n[1],i=t+n[0].length,a=e.substring(i),o=RegExp(`\\n\\s*`+r.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)+`\\s*(?=\\n|$)`),s=a.match(o);return s?i+s.index+s[0].length:-1}function gy(e){let t=oy(e||``).replace(/\/$/,``);if(!t)return``;let n=t.lastIndexOf(`/`);return n>0?t.substring(0,n):``}var _y=new Set([`du`,`df`,`stat`,`wc`,`file`,`cat`,`head`,`tail`,`grep`,`rg`]);function vy(e){if(!e||typeof e!=`string`)return!1;let t=my(e);if(t.length===0)return!1;for(let e of t){let t=e.trim().split(/\s+/).filter(Boolean);for(;t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[0]);)t.shift();if(!t.length)continue;let n=t[0].split(`/`).pop().toLowerCase();if(n===`sudo`&&t.length>1&&(n=t[1].split(`/`).pop().toLowerCase()),!_y.has(n))return!1}return!0}function yy(e,t){let n=t=>e===t||e.startsWith(t.endsWith(`/`)?t:t+`/`);return[...t].some(n)}function by(e,t){if(!e||typeof e!=`string`)return t||``;let n=t||``;for(let t of my(e)){let e=t.trim().match(/^cd\s+(.+?)\s*$/);if(!e)continue;let r=e[1].trim().replace(/^['"]|['"]$/g,``);n=r.startsWith(`/`)||r.startsWith(`~/`)?r:r===`..`?n?oy(n).replace(/\/[^/]+$/,``)||`/`:`..`:oy(n?n.replace(/\/$/,``)+`/`+r:r)}return n}function xy(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=t||``,i=my(e);for(let e of i){let t=e.trim();if(!t)continue;let i=t.replace(/"[^"]*"/g,`""`).replace(/'[^']*'/g,`''`),a=t.match(/^cd\s+(.+?)\s*$/);if(a){let e=a[1].trim().replace(/^['"]|['"]$/g,``);r=e.startsWith(`/`)||e.startsWith(`~/`)?e:e===`..`?r?oy(r).replace(/\/[^/]+$/,``)||`/`:`..`:oy(r?r.replace(/\/$/,``)+`/`+e:e);continue}let o=e=>(e=e.replace(/^['"]|['"]$/g,``),!e.startsWith(`/`)&&!e.startsWith(`~/`)&&r&&(e=oy(r.replace(/\/$/,``)+`/`+e)),oy(e)),s=t.match(/^(\S+)\s+.*<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?\s*\n([\s\S]*?)\n\s*\2\s*$/);if(s){let e=s[1].split(`/`).pop().toLowerCase(),t=s[3],r=null;if(/^python[\d.]*$/.test(e)?r=`py`:/^(ba)?sh$/.test(e)&&(r=`sh`),r){for(let e of Sy(t,r))e&&n.push({path:o(e),isDir:!1});continue}}let c=i.match(/^mkdir\s+(?:-[a-z]+\s+)*(.+?)$/);if(c){let e=fy(uy(c[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)&&e!==`""`&&e!==`''`),o);for(let t of e)n.push({path:t,isDir:!0});continue}let l=i.match(/^touch\s+(.+)$/);if(l){let e=fy(uy(l[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)&&e!==`""`&&e!==`''`),o);for(let t of e)n.push({path:t,isDir:!1});continue}let u=null,d=i.match(/\s[>]{1,2}\s*['"]?([^\s|&;'"]+)['"]?\s*$/);if(d&&(u=d[1]),!u){let e=i.match(/^cat\s+>\s*['"]?([^\s|&;'"]+)['"]?/);e&&(u=e[1])}if(!u){let e=t.match(/^cp\s+(?:-[a-zA-Z]+\s+)*(?:.+?\s+)+?['"]?([^\s|&;'"]+)['"]?\s*$/);e&&(u=e[1])}if(!u){let e=i.match(/tee\s+(?:-[a-zA-Z]+\s+)*['"]?([^\s|&;'"]+)['"]?/);e&&(u=e[1])}if(u){let e=fy([u],o);for(let t of e)n.push({path:t,isDir:!1})}}return n}function Sy(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=e.split(`
1201
+ </div>`}).join(``)}C(),b&&b.addEventListener(`change`,()=>{a.querySelectorAll(`.switch-workdir-item.current`).forEach(e=>{e.style.cursor=T(e.dataset.path)?`pointer`:`default`})});async function w(e){let t=d(e,l)||d(e,c);if(!await window.showCustomConfirm(r(t?`workspace.confirmRemoveStillUsable`:`workspace.confirmRemovePath`,{path:e}),r(`workspace.confirmRemovePathTitle`)))return;let n=await Pn(e);n.success?(u=Array.isArray(n.allowedPaths)?n.allowedPaths:u.filter(t=>t!==e),C(),L(r(t?`workspace.removedStillUsable`:`workspace.removedFromAllowed`),`success`)):L(r(`workspace.removeFailedWithError`,{error:n.error||r(`workspace.unknownError`)}),`error`)}let T=e=>{if(!(b&&b.checked))return!1;let t=e=>String(e||``).replace(/\\/g,`/`).toLowerCase();return!l||t(e)!==t(l)};a.addEventListener(`click`,e=>{let t=e.target.closest(`.switch-workdir-remove`);if(t){e.stopPropagation(),w(t.dataset.removePath);return}let n=e.target.closest(`.switch-workdir-item`);n&&(n.classList.contains(`current`)&&!T(n.dataset.path)||E(n.dataset.path))});async function E(n){if(!n){L(r(`workspace.selectOrInputPath`),`error`);return}n=n.trim();let a=e=>e.replace(/\\/g,`/`).toLowerCase(),o=(e,t)=>!!e&&!!t&&a(e)===a(t),s=!!(b&&b.checked);if(o(n,c)){if(s&&!o(n,l)){S(),e(await Yv(n));return}L(r(`workspace.alreadyCurrentWorkdir`),`info`),S(),e(!1);return}let d=i?t:null,f=!d||s;!u.some(e=>{let t=a(n),r=a(e);return t===r||t.startsWith(r+`/`)})&&f&&!await window.showCustomConfirm(r(`workspace.confirmSwitchToNewDefault`,{path:n}),r(`workspace.confirmSwitchToNewTitle`))||(S(),e(await Xv(n,{sessionId:d,setAsDefault:s})))}y&&y.addEventListener(`click`,async()=>{y.disabled=!0,S(),e(await Zv(t,{sessionSupported:i}))}),g.addEventListener(`click`,()=>E(m.value)),h.addEventListener(`click`,()=>{S(),e(!1)}),_.addEventListener(`click`,()=>{S(),e(!1)}),_.addEventListener(`mouseenter`,()=>{_.style.color=`var(--text-primary)`,_.style.background=`var(--border-subtle)`}),_.addEventListener(`mouseleave`,()=>{_.style.color=`var(--text-tertiary)`,_.style.background=`transparent`}),m.addEventListener(`keydown`,t=>{t.key===`Enter`&&(t.preventDefault(),E(m.value)),t.key===`Escape`&&(S(),e(!1))}),n.addEventListener(`click`,e=>{e.target===n&&e.stopPropagation()}),setTimeout(()=>m.focus(),50)})}function Wv(){Jm=null,K=null,Ym=[],q.clear(),Ov=``,kv=[],Av=!1,Vh.clear();let e=document.getElementById(`workspaceSearchInput`);e&&(e.value=``);let t=document.getElementById(`workspaceSearchClear`);t&&(t.style.display=`none`);let n=document.getElementById(`workspaceToolbar`);if(n){n.classList.remove(`search-focused`);let e=n.querySelector(`.workspace-search-box`);e&&e.classList.remove(`search-box-expanded`)}}var Gv=0;async function Kv(){let e=++Gv;if(N.agentPlatform?.connected!==!0){ln(),Wv();return}await sv();let t=Jm;ln();let n=null;try{n=await bn()}catch(e){a.warn(`[WorkspacePanel] resolve root for session failed:`,e?.message||e)}if(e!==Gv||t&&n&&t===n)return;Wv();let r=document.getElementById(`workspacePreviewArea`);if(r&&r.dataset.previewPath&&(ph=!1,await L_(!0)),await Promise.resolve(),e!==Gv)return;let i=document.getElementById(`workspacePanel`);!i||!i.classList.contains(`expanded`)||await zh()}async function qv(e,t){document.dispatchEvent(new CustomEvent(`session-workdir-changed`,{detail:{sessionId:e,workdir:t}}))}async function Jv(e){N.defaultWorkdir=e,N.agentPlatform&&={...N.agentPlatform,workdir:e};try{let{activeAgentId:t}=await chrome.storage.local.get([`activeAgentId`]);t&&(N.agentWorkdirs.set(t,e),typeof window.updateAgentItemWorkdir==`function`&&window.updateAgentItemWorkdir(t,e))}catch(e){a.debug(`[WorkspacePanel] sync dropdown column table workdir failed:`,e)}}async function Yv(e){let t=await un(e,{sessionId:null});return t.success?(await Jv(t.workdir),await qv(null,t.workdir),L(r(`workspace.setAsDefaultDone`,{path:t.workdir}),`success`),!0):(L(r(`workspace.switchFailedWithError`,{error:t.error||r(`workspace.unknownError`)}),`error`),!1)}async function Xv(e,t={}){let n=t.sessionId===void 0?N.activeSessionId||null:t.sessionId,i=t.setAsDefault===!0,o=await un(e,{sessionId:n});if(!o.success)return L(r(`workspace.switchFailedWithError`,{error:o.error||r(`workspace.unknownError`)}),`error`),!1;if(n)try{let{setSessionWorkdirBinding:e}=await M(async()=>{let{setSessionWorkdirBinding:e}=await import(`./session-store-xr0nYACs.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([2,1,3,4])),t=(await Cn())?.id||null;await e(n,o.workdir,t)}catch(e){a.warn(`[WorkspacePanel] persist session workdir failed:`,e)}let s=!1;if(i){let e=await un(o.workdir,{sessionId:null});e.success?s=!0:L(r(`workspace.switchFailedWithError`,{error:e.error||r(`workspace.unknownError`)}),`error`)}return(!n||i)&&await Jv(o.workdir),await qv(n,o.workdir),L(r(s?`workspace.switchedToAndSetDefault`:`workspace.switchedTo`,{path:o.workdir}),`success`),!0}async function Zv(e,t={}){if(!e)return!1;let{unbindSessionWorkdirRemote:n}=await M(async()=>{let{unbindSessionWorkdirRemote:e}=await import(`./session-store-xr0nYACs.js`).then(e=>e.Ft);return{unbindSessionWorkdirRemote:e}},__vite__mapDeps([2,1,3,4]));if(await n(e)===null&&t.sessionSupported)return L(r(`workspace.switchFailedWithError`,{error:r(`workspace.unknownError`)}),`error`),!1;try{let{setSessionWorkdirBinding:t}=await M(async()=>{let{setSessionWorkdirBinding:e}=await import(`./session-store-xr0nYACs.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([2,1,3,4]));await t(e,null,null)}catch(e){a.warn(`[WorkspacePanel] clear session workdir failed:`,e)}return await qv(e,``),L(r(`workdirTag.restoredDefault`),`success`),!0}async function Qv(e,t,n){let i=t,a=``,o=t.lastIndexOf(`.`);n!==`directory`&&o>0&&(i=t.substring(0,o),a=t.substring(o));let s=await Hv(r(n===`directory`?`workspace.renameDir`:`workspace.renameFile`),i,r(`workspace.inputNewName`));if(!s||s===i)return;let c=s+a;try{let t=await fn(e,c);t.success?(L(r(`workspace.renamedTo`,{name:c}),`success`),Jh(K),await uv(),ry(c)):L(r(`workspace.renameFailedWithError`,{error:t.error}),`error`)}catch(e){L(r(`workspace.renameFailedWithError`,{error:e.message}),`error`)}}async function $v(){if(!K)return;let e=await Hv(r(`workspace.newFolderTitle`),``,r(`workspace.inputFolderName`));if(!e)return;let t=qh(`${K}/${e}`);try{let n=await Tn(t);n.success?(L(r(`workspace.folderCreated`,{name:e}),`success`),Jh(K),await uv(),ry(e)):L(r(`workspace.createFailedWithError`,{error:n.error}),`error`)}catch(e){L(r(`workspace.createFailedWithError`,{error:e.message}),`error`)}}async function ey(e){return new Promise((t,n)=>{let i=new Image,a=URL.createObjectURL(e);i.onload=()=>{URL.revokeObjectURL(a);let n=new FileReader;n.onloadend=()=>{let e=n.result,r=i.width,a=i.height,o=Math.max(r,a),s,c;o<=768?(s=o,c=.75):o<=1280?(s=768,c=.7):o<=2560?(s=1024,c=.65):o<=3840?(s=1280,c=.6):(s=1280,c=.55);let l=r,u=a;o>s&&(r>a?(u=Math.round(s/r*a),l=s):(l=Math.round(s/a*r),u=s));let d=document.createElement(`canvas`);d.width=l,d.height=u;let f=d.getContext(`2d`);f.imageSmoothingEnabled=!0,f.imageSmoothingQuality=`high`,f.drawImage(i,0,0,l,u),t({originalUrl:e,compressedUrl:d.toDataURL(`image/jpeg`,c)})},n.readAsDataURL(e)},i.onerror=()=>{URL.revokeObjectURL(a),n(Error(r(`workspace.imageLoadFailed`)))},i.src=a})}async function ty(e){let t=[],n=[];for(let r of e){let e=r&&typeof r==`object`,i=e?r.fullPath||r.path:r,a=i.split(/[\\/]/).pop(),o;e?o=r:(o=vh.find(e=>e.path===i),o||=kv.find(e=>e.fullPath===i));let s=o?o.size:0,c=wn(a);if(c.startsWith(`image/`)&&N.enableImageInput)n.push({name:a,size:s,type:c,path:i});else{let e={name:a,size:s,type:c,text:``,status:`done`,agentPath:i};t.push(e)}}for(let e of n)try{let t=await Cn();if(t){let n=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...An(t)},body:JSON.stringify({path:e.path})});if(n.ok){let{originalUrl:e,compressedUrl:t}=await ey(await n.blob());N.attachedImages.some(e=>e.compressedUrl===t)||N.attachedImages.push({originalUrl:e,compressedUrl:t})}}}catch{}for(let e of t)N.attachedFiles.some(t=>t.name===e.name&&t.agentPath===e.agentPath)||N.attachedFiles.push(e);bm(),Hm();let i=t.length+n.length;i>0&&(!N.enableImageInput&&t.some(e=>e.type?.startsWith(`image/`))?L(r(`workspace.addedFilesToQuestionNoImage`,{count:i}),`success`):L(r(`workspace.addedFilesToQuestion`,{count:i}),`success`))}async function ny(){q.size!==0&&await ty(Array.from(q))}function ry(e,t=0){let n=document.getElementById(`workspacePanelContent`);if(!n)return;if(Qh){let t=Qh.sorted.findIndex(t=>t.name===e);if(t>=0){let r=Qh.itemHeight;n.scrollTop=Math.max(0,t*r-n.clientHeight/2+r/2),tg();let i=Array.from(n.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.name===e);i&&(i.classList.add(`highlight-new`),setTimeout(()=>i.classList.remove(`highlight-new`),2e3));return}}let r=Array.from(n.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.name===e);r?(r.scrollIntoView({behavior:`smooth`,block:`center`}),r.classList.add(`highlight-new`),setTimeout(()=>r.classList.remove(`highlight-new`),2e3)):t<5&&setTimeout(()=>ry(e,t+1),150)}function iy(){let e=document.getElementById(`workspaceAskBtn`);q.size===0?e.style.display=`none`:e.style.display=``}function ay(){let e=document.getElementById(`workspaceDownloadDirBtn`),t=document.getElementById(`workspaceBatchDeleteBtn`),n=document.getElementById(`workspaceSelectedCount`);q.size===0?(e.style.display=`none`,t.style.display=`none`,n.style.display=`none`):(e.style.display=``,t.style.display=``,n.style.display=``,n.textContent=r(`workspace.selectedCount`,{count:q.size}),e.disabled=uh),iy()}n(`zh`,{artifacts:{btnTitle:`文件产物({count})`,modalTitle:`本次任务的文件产物`,emptyHint:`本次任务没有产生文件产物`,fileCol:`文件`,sizeCol:`大小`,typeCol:`类型`,timeCol:`时间`,actionCol:`操作`,locate:`定位到文件`,preview:`预览`,closeBtn:`关闭`,typeWrite:`写入`,typeDelete:`删除`,typeCreate:`创建`,typeEdit:`编辑`,typeOther:`操作`,noWorkspace:`无法获取工作目录,请确认 Agent 已连接`,locateFailed:`定位文件失败`,fileNotFound:`目录已定位,但未找到该文件(可能已被删除)`,previewFailed:`预览文件失败`,previewNotSupported:`此文件类型不支持预览`,totalCount:`共 {count} 个文件`,badgeLabel:`产物`,download:`下载`,downloadFailed:`下载失败`,copyFileName:`复制文件名`,copyFilePath:`复制文件路径`,copiedName:`已复制文件名:{name}`,copiedPath:`已复制文件路径`,dblClickHint:`双击文件名可预览`,sortHint:`点击排序`,serialCol:`序号`}}),n(`en`,{artifacts:{btnTitle:`Artifacts ({count})`,modalTitle:`File Artifacts of This Task`,emptyHint:`No file artifacts produced in this task`,fileCol:`File`,sizeCol:`Size`,typeCol:`Type`,timeCol:`Time`,actionCol:`Actions`,locate:`Locate File`,preview:`Preview`,closeBtn:`Close`,typeWrite:`Write`,typeDelete:`Delete`,typeCreate:`Create`,typeEdit:`Edit`,typeOther:`Op`,noWorkspace:`Unable to access working directory. Please confirm the Agent is connected.`,locateFailed:`Failed to locate file`,fileNotFound:`Directory located, but file not found (may have been deleted)`,previewFailed:`Failed to preview file`,previewNotSupported:`Preview not supported for this file type`,totalCount:`{count} files in total`,badgeLabel:`Artifacts`,download:`Download`,downloadFailed:`Download failed`,copyFileName:`Copy File Name`,copyFilePath:`Copy File Path`,copiedName:`Copied file name: {name}`,copiedPath:`File path copied`,dblClickHint:`Double-click to preview`,sortHint:`Click to sort`,serialCol:`#`}});function oy(e){let t=(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`),n=t.replace(/\/+$/,``);return n?/^[A-Za-z]:$/.test(n)?n+`/`:n:t?`/`:``}function sy(e){if(!e)return``;let t=oy(e).replace(/\/+$/,``).split(`/`);return t[t.length-1]||``}function cy(e){if(!e)return``;let t=sy(e),n=t.lastIndexOf(`.`);return n>0?t.substring(n+1).toLowerCase():``}function ly(e){return String(e??``).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}function uy(e,t){let n=new Set(t),r=[],i=0,a=``;for(let t of e)t===`{`?i++:t===`}`&&(i=Math.max(0,i-1)),i===0&&n.has(t)?(r.push(a),a=``):a+=t;return r.push(a),r}function dy(e){let t=e.indexOf(`{`);if(t===-1)return[e];let n=0,r=-1;for(let i=t;i<e.length;i++)if(e[i]===`{`)n++;else if(e[i]===`}`&&(n--,n===0)){r=i;break}if(r===-1)return[e];let i=e.substring(0,t),a=e.substring(t+1,r),o=e.substring(r+1),s=uy(a,`,`).map(e=>e.trim());if(s.length<=1)return[e];let c=[];for(let e of s)for(let t of dy(e))for(let e of dy(o))c.push(i+t+e);return c}function fy(e,t){let n=[],r=new Set;for(let i of e)if(i)for(let e of dy(i)){if(!e)continue;let i=t(e);!i||r.has(i)||(r.add(i),n.push(i))}return n}function py(e){if(!e)return null;let t=e;if(typeof t==`string`)try{t=JSON.parse(t)}catch{let e=t.match(/["']?path["']?\s*[:=]\s*["']([^"']+)["']/i);return e?e[1]:null}return t&&typeof t==`object`&&(t.path||t.filePath||t.file_path||t.result?.path)||null}function my(e){let t=[],n=0,r=``;for(let i=0;i<e.length;i++){let a=e[i];if(a===`{`?n++:a===`}`&&(n=Math.max(0,n-1)),n===0&&a===`<`&&e[i+1]===`<`){let t=hy(e,i);if(t>i){r+=e.substring(i,t),i=t-1;continue}}n===0&&a===`;`?(t.push(r),r=``):n===0&&a===`&`&&e[i+1]===`&`?(t.push(r),r=``,i++):r+=a}return t.push(r),t}function hy(e,t){let n=e.substring(t).match(/^<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/);if(!n)return-1;let r=n[1],i=t+n[0].length,a=e.substring(i),o=RegExp(`\\n\\s*`+r.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)+`\\s*(?=\\n|$)`),s=a.match(o);return s?i+s.index+s[0].length:-1}function gy(e){let t=oy(e||``).replace(/\/$/,``);if(!t)return``;let n=t.lastIndexOf(`/`);return n>0?t.substring(0,n):``}var _y=new Set([`du`,`df`,`stat`,`wc`,`file`,`cat`,`head`,`tail`,`grep`,`rg`]);function vy(e){if(!e||typeof e!=`string`)return!1;let t=my(e);if(t.length===0)return!1;for(let e of t){let t=e.trim().split(/\s+/).filter(Boolean);for(;t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[0]);)t.shift();if(!t.length)continue;let n=t[0].split(`/`).pop().toLowerCase();if(n===`sudo`&&t.length>1&&(n=t[1].split(`/`).pop().toLowerCase()),!_y.has(n))return!1}return!0}function yy(e,t){let n=t=>e===t||e.startsWith(t.endsWith(`/`)?t:t+`/`);return[...t].some(n)}function by(e,t){if(!e||typeof e!=`string`)return t||``;let n=t||``;for(let t of my(e)){let e=t.trim().match(/^cd\s+(.+?)\s*$/);if(!e)continue;let r=e[1].trim().replace(/^['"]|['"]$/g,``);n=r.startsWith(`/`)||r.startsWith(`~/`)?r:r===`..`?n?oy(n).replace(/\/[^/]+$/,``)||`/`:`..`:oy(n?n.replace(/\/$/,``)+`/`+r:r)}return n}function xy(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=t||``,i=my(e);for(let e of i){let t=e.trim();if(!t)continue;let i=t.replace(/"[^"]*"/g,`""`).replace(/'[^']*'/g,`''`),a=t.match(/^cd\s+(.+?)\s*$/);if(a){let e=a[1].trim().replace(/^['"]|['"]$/g,``);r=e.startsWith(`/`)||e.startsWith(`~/`)?e:e===`..`?r?oy(r).replace(/\/[^/]+$/,``)||`/`:`..`:oy(r?r.replace(/\/$/,``)+`/`+e:e);continue}let o=e=>(e=e.replace(/^['"]|['"]$/g,``),!e.startsWith(`/`)&&!e.startsWith(`~/`)&&r&&(e=oy(r.replace(/\/$/,``)+`/`+e)),oy(e)),s=t.match(/^(\S+)\s+.*<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?\s*\n([\s\S]*?)\n\s*\2\s*$/);if(s){let e=s[1].split(`/`).pop().toLowerCase(),t=s[3],r=null;if(/^python[\d.]*$/.test(e)?r=`py`:/^(ba)?sh$/.test(e)&&(r=`sh`),r){for(let e of Sy(t,r))e&&n.push({path:o(e),isDir:!1});continue}}let c=i.match(/^mkdir\s+(?:-[a-z]+\s+)*(.+?)$/);if(c){let e=fy(uy(c[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)&&e!==`""`&&e!==`''`),o);for(let t of e)n.push({path:t,isDir:!0});continue}let l=i.match(/^touch\s+(.+)$/);if(l){let e=fy(uy(l[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)&&e!==`""`&&e!==`''`),o);for(let t of e)n.push({path:t,isDir:!1});continue}let u=null,d=i.match(/\s[>]{1,2}\s*['"]?([^\s|&;'"]+)['"]?\s*$/);if(d&&(u=d[1]),!u){let e=i.match(/^cat\s+>\s*['"]?([^\s|&;'"]+)['"]?/);e&&(u=e[1])}if(!u){let e=t.match(/^cp\s+(?:-[a-zA-Z]+\s+)*(?:.+?\s+)+?['"]?([^\s|&;'"]+)['"]?\s*$/);e&&(u=e[1])}if(!u){let e=i.match(/tee\s+(?:-[a-zA-Z]+\s+)*['"]?([^\s|&;'"]+)['"]?/);e&&(u=e[1])}if(u){let e=fy([u],o);for(let t of e)n.push({path:t,isDir:!1})}}return n}function Sy(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=e.split(`
1202
1202
  `);if([`sh`,`bash`,`zsh`].includes(t))for(let e of r){let t=e.trim();if(!t||t.startsWith(`#`))continue;let r=[...t.matchAll(/[>]{1,2}\s*['"]?([^\s|&;>'"]+)['"]?/g)];for(let e of r)e[1]&&!e[1].startsWith(`/dev/`)&&n.push(e[1]);let i=t.match(/^mkdir\s+(?:-[a-z]+\s+)*(.+?)$/);if(i){let e=uy(i[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`));n.push(...e)}let a=t.match(/^touch\s+(.+)$/);if(a){let e=uy(a[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`));n.push(...e)}let o=t.match(/^cp\s+(?:-[a-zA-Z]+\s+)*(?:.+?\s+)+?['"]?([^\s|&;'"]+)['"]?\s*$/);o&&n.push(o[1]);let s=t.match(/tee\s+(?:-[a-zA-Z]+\s+)*['"]?([^\s|&;'"]+)['"]?/);s&&n.push(s[1])}else if(t===`bat`||t===`cmd`)for(let e of r){let t=e.trim().replace(/^@/,``);if(!t||(t.toUpperCase(),/^REM\b/i.test(t)||t.startsWith(`::`))||/^ECHO\b/i.test(t)&&!/[>]{1,2}/.test(t))continue;let r=[...t.matchAll(/[>]{1,2}\s*"?([^\s|&;>"]+)"?/g)];for(let e of r)e[1]&&e[1].toUpperCase()!==`NUL`&&n.push(e[1]);let i=t.match(/^(?:mkdir|md)\s+(?:"([^"]+)"|(\S+))/i);i&&n.push(i[1]||i[2]);let a=t.match(/^copy\s+(?:\/\S+\s+)*(?:.+?\s+)+?"?([^\s|&;"]+)"?\s*$/i);a&&n.push(a[1]);let o=t.match(/^xcopy\s+(?:\/\S+\s+)*(?:"[^"]+"|\S+)\s+(?:"([^"]+)"|(\S+))/i);o&&n.push(o[1]||o[2])}else if(t===`ps1`)for(let e of r){let t=e.trim();if(!t||t.startsWith(`#`))continue;let r=[...t.matchAll(/[>]{1,2}\s*"?([^\s|;>'"]+)"?/g)];for(let e of r)e[1]&&e[1].toUpperCase()!==`NUL`&&n.push(e[1]);let i=t.match(/(?:Set-Content|Out-File|Add-Content)\s+(?:-[\w]+\s+)*"?([^";\s|]+)"?/i);i&&n.push(i[1]);let a=t.match(/New-Item\s+(?:-[\w]+\s+)*-Path\s+"?([^";\s|]+)"?/i);a&&n.push(a[1]);let o=t.match(/New-Item\s+"?([^";\s|]+)"?\s+(?:-[\w]+\s+)*-ItemType/i);o&&n.push(o[1]);let s=t.match(/Copy-Item\s+(?:-[\w]+\s+)*"?([^";\s|]+)"?\s+(?:-[\w]+\s+)*-Destination\s+"?([^";\s|]+)"?/i);s&&n.push(s[2]);let c=t.match(/Move-Item\s+(?:-[\w]+\s+)*"?([^";\s|]+)"?\s+(?:-[\w]+\s+)*-Destination\s+"?([^";\s|]+)"?/i);c&&n.push(c[2])}else if(t===`py`)for(let e of r){let t=e.trim();if(!t||t.startsWith(`#`))continue;let r=t.match(/open\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"][wax][+]?['"]/);r&&n.push(r[1]);let i=t.match(/os\.(?:makedirs|mkdir)\s*\(\s*['"]([^'"]+)['"]/);i&&n.push(i[1]);let a=t.match(/shutil\.(?:copy2?|move)\s*\([^,]+,\s*['"]([^'"]+)['"]/);a&&n.push(a[1]);let o=t.match(/Path\s*\(\s*['"]([^'"]+)['"]\s*\)\s*\.\s*(?:write_text|write_bytes|touch|mkdir)/);o&&n.push(o[1])}let i=new Set;return n.filter(e=>!e||i.has(e)||(i.add(e),/\$[\w({]|%[\w]+%/.test(e))?!1:e.includes(`/`)||e.includes(`\\`)||e.includes(`.`))}function Cy(e,t,n){if(!e||typeof e!=`string`||e.startsWith(`{`)||e.startsWith(`[`))return[];let r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[];let i=new Set([`total`,`.`,`..`,`...`,`.git`,`.DS_Store`,`node_modules`,`__pycache__`,`.learnings`,`dist`,`.trae`]),a=r.some(e=>/^[d-][rwx-]{9}[@+*]?$/.test(e)),o=n?[...n.matchAll(/find\b[\s\S]*?-type\s+([df])/g)].map(e=>e[1]):[],s=o.length===1?o[0]:null,c=/[<>"'`|&;()[\]*?#!]/,l=new Map,u=(e,t)=>{!e||i.has(e)||/^\d+$/.test(e)||c.test(e)||(!l.has(e)||t)&&l.set(e,t)},d=e=>e.startsWith(`/`)?oy(e):oy((t?t.replace(/\/$/,``)+`/`:``)+e),f=e=>!(e.split(`/`).pop()||``).includes(`.`);if(r.some(e=>/^\.\/([^:]+):$/.test(e)&&e.length>3)){let e=new Set;for(let t of r){let n=t.match(/^\.\/([^:]+):$/);n&&n[1]&&e.add(n[1])}let t=null;for(let n of r){let r=n.match(/^\.\/([^:]+):$/);if(r&&r[1]){t=r[1],u(t,!0);continue}if(n.startsWith(`./`)){let t=n.slice(2);t&&!i.has(t)&&u(t,e.has(t)||f(t)&&s!==`f`);continue}if(!(i.has(n)||n.startsWith(`-`)||a||n.endsWith(`...`)))if(t===null)(n.includes(`.`)||e.has(n))&&u(n,e.has(n));else{if(n.includes(`/`)){u(n,e.has(n)||f(n));continue}let r=t+`/`+n;u(r,e.has(r)||f(r))}}}else for(let e of r){if(i.has(e)||e.startsWith(`-`)||e.startsWith(`=`)||e.endsWith(`...`)||e.includes(`:`)||e.includes(`=`)||/^\d+$/.test(e)||/^[\d.]+[KMGTPE]?B?$/i.test(e))continue;let t=null;if(e.startsWith(`./`)){if(e.length<=2)continue;t=e.slice(2)}else if(a)continue;else{if(!e.includes(`/`)&&!/^.+\.[a-zA-Z0-9]+$/.test(e))continue;t=e}!t||i.has(t)||u(t,f(t)&&s!==`f`)}let p=[];for(let[e,t]of l)p.push({path:d(e),isDir:t});return p}function wy(e){if(!e||typeof e!=`string`)return[];let t=[],n=/cat\s+>\s*['"]?(\S+)['"]?\s*<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?\s*\n([\s\S]*?)\n\s*\2\s*(?=\n|$)/g,r;for(;(r=n.exec(e))!==null;){let e=r[1],n=cy(e);[`sh`,`bash`,`zsh`,`bat`,`cmd`,`ps1`,`py`].includes(n)&&t.push({path:oy(e),content:r[3],ext:n})}return t}function Ty(e,t){if(!e||typeof e!=`string`)return null;let n=e.trim();for(let e of t){let t=sy(e).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),r=e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),i=e.replace(/\//g,`\\`).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);if(RegExp(`(?:^|[;\\s&|])(?:ba)?sh\\s+.*${t}|(?:^|[;\\s&|])python[23]?\\s+.*${t}|(?:^|[;\\s&|])node\\s+.*${t}|(?:^|[;\\s&|])\\.?/${t}|(?:^|[;\\s&|])cmd(?:\\.exe)?\\s+(?:/c|/k)\\s+.*${t}|(?:^|[;\\s&|])(?:powershell|pwsh)(?:\\.exe)?\\s+(?:-[\w-]+\\s+)*-File\\s+.*${t}|(?:^|[;\\s&|])${r}|(?:^|[;\\s&|])${i}`).test(n))return e}return null}function Ey(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=t||``,i=e=>(e=e.replace(/^['"]|['"]$/g,``),!e.startsWith(`/`)&&!e.startsWith(`~/`)&&!/^[A-Za-z]:[\\/]/.test(e)&&r&&(e=oy(r.replace(/\/$/,``)+`/`+e)),oy(e)),a=my(e);for(let e of a){let t=e.trim();if(!t)continue;let a=t.match(/^cd\s+(?:\/[dD]\s+)?(.+?)\s*$/);if(a){let e=a[1].trim().replace(/^['"]|['"]$/g,``);r=e.startsWith(`/`)||/^[A-Za-z]:/.test(e)?oy(e):e.startsWith(`~/`)?e:e===`..`?r?oy(r).replace(/\/[^/]+$/,``)||`/`:`..`:oy(r?r.replace(/\/$/,``)+`/`+e:e);continue}let o=t.match(/^rm\s+((?:-[a-zA-Z]+\s+)*)(.+)$/);if(o){let e=o[1],t=o[2],r=/r|R/i.test(e),a=fy(uy(t,` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)),i);for(let e of a)n.push({path:e,isDir:r});continue}let s=t.match(/^(?:del|erase)\s+((?:\/[a-zA-Z]+\s+)*)(.+)$/i);if(s){s[1];let e=s[2],t=fy(uy(e,` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`/`)),i);for(let e of t)n.push({path:e,isDir:!1});continue}let c=t.match(/^(?:rmdir|rd)\s+((?:\/[a-zA-Z]+\s+)*)(.+)$/i);if(c){let e=c[1],t=c[2],r=/s|S/i.test(e),a=fy(uy(t,` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`/`)),i);for(let e of a)n.push({path:e,isDir:r});continue}let l=t.match(/^Remove-Item\s+((?:-[\w-]+\s+)*(?:"[^"]+"|\S+)?(?:\s+(?:-[\w-]+\s+)*(?:"[^"]+"|\S+))*)/i);if(l){let e=l[1],t=/-Recurse/i.test(e),r=fy([...e.matchAll(/(?:"([^"]+)"|(?<![-\/])(\S+))/g)].map(e=>e[1]||e[2]).filter(e=>e&&!e.startsWith(`-`)),i);for(let e of r)n.push({path:e,isDir:t});continue}}return n}function Dy(e){if(!Array.isArray(e)||e.length===0)return[];let t=[],n=new Set,r=[...e].sort((e,t)=>new Date(e.timestamp||0)-new Date(t.timestamp||0)),i=new Map;for(let e of r)if(!(e.nodeType!==`tool_exec`||e.status===`failed`)){if(e.action?.name===`agent_file`){let t=e.action.params;if(typeof t==`string`)try{t=JSON.parse(t)}catch{continue}if(!t||t.action!==`write`||typeof t.content!=`string`)continue;let n=oy(t.path||t.filePath||``),r=cy(n);[`sh`,`bash`,`zsh`,`bat`,`cmd`,`ps1`,`py`].includes(r)&&i.set(n,{content:t.content,ext:r})}else if(e.action?.name===`agent_exec`){let t=e.action.params,n=typeof t==`string`?t:t&&typeof t==`object`?t.command:null;if(typeof n==`string`)for(let e of wy(n))i.has(e.path)||i.set(e.path,{content:e.content,ext:e.ext})}}let a=[...i.keys()],o=new Map,s=(e,t)=>!t||e==null||t.timestamp==null?!0:new Date(t.timestamp||0).getTime()>=new Date(e||0).getTime(),c=new Set,l=!1;for(let e of r){if(e.nodeType!==`tool_exec`||!e.action)continue;let r=e.action.name||``,s=e.action.params;if(s==null)continue;if(typeof s==`string`)try{s=JSON.parse(s)}catch{continue}if(typeof s!=`object`)continue;if(r===`agent_exec`){let u=s.command||``;if(!u)continue;let d=Ty(u,a);if(d&&e.status!==`failed`){let a=i.get(d);if(a){let i=Sy(a.content,a.ext);for(let a of i){if(!a)continue;let i=(a.startsWith(`/`),oy(a));if(n.has(i)){let e=t.findIndex(e=>e.path===i);e>=0&&t.splice(e,1)}n.add(i),t.push({path:i,fileName:sy(i),toolName:r,action:`typeCreate`,size:0,timestamp:e.timestamp||null,status:e.status||`unknown`,type:`file`})}}}if(e.status!==`failed`){let t=Ey(u,s.cwd);for(let n of t)o.set(n.path,{isDir:n.isDir,timestamp:e.timestamp})}let f=xy(u,s.cwd);for(let e of f)if(e&&e.path){let t=e.isDir?e.path:gy(e.path);t&&c.add(t)}for(let i of f){let a=i&&i.path;if(a){if(n.has(a)){let e=t.findIndex(e=>e.path===a);e>=0&&t.splice(e,1)}n.add(a),e.status!==`failed`&&t.push({path:a,fileName:sy(a),toolName:r,action:`typeCreate`,size:0,timestamp:e.timestamp||null,status:e.status||`unknown`,type:i.isDir?`directory`:`file`})}}let p=f.length>0||!!d||/<<-?/.test(u);if(e.status!==`failed`&&typeof e.observation==`string`){let i=by(u,s.cwd);/\bcd\s/.test(u)&&i&&(p||l)&&c.add(oy(i));let a=Cy(e.observation,i,u);a.length>0&&!p&&(a=vy(u)?[]:a.filter(e=>yy(e.path,c)));for(let i of a){if(n.has(i.path)){let e=t.findIndex(e=>e.path===i.path);e>=0&&t.splice(e,1)}n.add(i.path),t.push({path:i.path,fileName:sy(i.path),toolName:r,action:`typeCreate`,size:0,timestamp:e.timestamp||null,status:e.status||`unknown`,type:i.isDir?`directory`:`file`})}}e.status!==`failed`&&p&&(l=!0);continue}let u=null,d=`typeOther`;if(r===`agent_file`){let t=s.action;if(t===`write`)u=s.path||s.filePath,d=`typeWrite`;else if(t===`delete`){let t=oy(s.path||s.filePath||``);t&&e.status!==`failed`&&o.set(t,{isDir:!1,timestamp:e.timestamp});continue}else continue}else if(r===`file_upload`)u=s.path||s.filePath||s.filename,d=`typeCreate`;else if(r===`download_file`)continue;else s.file_path&&(s.content!==void 0||s.action===`write`||s.action===`create`)&&(u=s.file_path,d=s.action===`create`?`typeCreate`:`typeWrite`);if(!u)continue;let f=oy(py(e.observation)||u);if(!f)continue;if(n.has(f)){let e=t.findIndex(e=>e.path===f);e>=0&&t.splice(e,1)}if(n.add(f),e.status===`failed`)continue;let p=gy(f);p&&c.add(p),l=!0;let m=0;if(e.observation){let t=e.observation;if(typeof t==`string`)try{t=JSON.parse(t)}catch{}t&&typeof t==`object`&&(m=t.size||t.fileSize||t.file_size||0)}t.push({path:f,fileName:sy(f),toolName:r,action:d,size:m,timestamp:e.timestamp||null,status:e.status||`unknown`,type:`file`})}if(o.size>0){let e=[...o.keys()],n=(e,t)=>{if(e===t)return!0;let n=e.startsWith(`/`),r=t.startsWith(`/`);return n&&!r?e.endsWith(`/`+t)||e.endsWith(t):r&&!n?t.endsWith(`/`+e)||t.endsWith(e):!1};for(let r of t)r.deleted||(o.has(r.path)&&s(r.timestamp,o.get(r.path))||e.some(e=>{let t=o.get(e);return s(r.timestamp,t)?n(r.path,e)?!0:t&&t.isDir&&(r.path.startsWith(e+`/`)||r.path.startsWith(e+`\\`)):!1}))&&(r.deleted=!0)}return t.filter(e=>e&&e.fileName)}function Oy(e){if(!e||typeof e!=`string`)return[];let t=[],n=new Set,r=/\[\[artifact:([^\]|]+)(?:\|([^\]]*))?\]\]/g,i;for(;(i=r.exec(e))!==null;){let e=(i[1]||``).trim(),r=(i[2]||``).trim();if(!e||/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?|%[A-Za-z0-9_]+%/.test(e))continue;let a=ky(e);!a||n.has(a)||(n.add(a),t.push({path:e,note:r}))}return t}function ky(e){return oy(e).replace(/^\.\//,``)}function Ay(e,t){let n=(e||[]).map(e=>({...e,source:e.source||`static`})),r=n.map(e=>ky(e.path));for(let e of t||[]){let t=ky(e.path);if(!t)continue;let i=sy(e.path);if(!i)continue;let a=r.indexOf(t);if(a===-1&&(a=r.findIndex(e=>e.endsWith(`/`+t))),a!==-1){let t=n[a];t&&e.note&&!t.note&&(t.note=e.note);continue}r.push(t),n.push({path:e.path,fileName:i,toolName:`declared`,action:`typeCreate`,size:0,timestamp:null,status:`unknown`,type:`file`,source:`declared`,note:e.note||``})}return n}function jy(e,t){return Ay(Dy(e),Oy(t))}function My(e){try{return pn(e)}catch{return!1}}var Ny=null,Py=null,Fy=null,Iy=1;function Ly(e){if(!e)return`—`;let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Ry(e){if(!Fy)return e;let t=Iy;return[...e].sort((e,n)=>{let r,i;return Fy===`name`?(r=(e.fileName||e.path||``).toLowerCase(),i=(n.fileName||n.path||``).toLowerCase()):Fy===`type`?(r=e.type||`file`,i=n.type||`file`):(r=new Date(e.timestamp||0).getTime(),i=new Date(n.timestamp||0).getTime()),r<i?-t:r>i?t:0})}function zy(e,t){let n=vn(e.fileName,e.type),i=r(`artifacts.${e.action}`),a=Ly(e.timestamp),o=My(e.fileName),s=`${ly(e.path)} · ${r(`artifacts.dblClickHint`)}`;return`
1203
1203
  <tr class="artifacts-row" data-idx="${t}" data-path="${ly(e.path)}" data-name="${ly(e.fileName)}">
1204
1204
  <td class="col-index">${t+1}</td>
@@ -1360,7 +1360,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
1360
1360
  <span class="page-action-btn" data-action="translate" data-tab-id="${e.id}" title="${r(`pageSelector.translatePage`)}">${r(`pageSelector.translatePage`)}</span>
1361
1361
  </span>
1362
1362
  </div>
1363
- `}).join(``),t.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{let n=t.target.closest(`.page-action-btn`);if(n){t.stopPropagation(),Wb(parseInt(n.dataset.tabId),n.dataset.action);return}Ub(parseInt(e.dataset.tabId))})})}function Bb(e){e.forEach((e,t)=>{t===N.selectedPageIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function Vb(e){N.selectedPage={id:e.id,title:e.title||r(`pageSelector.noTitle`),url:e.url||``,favIconUrl:e.favIconUrl||``};let t=document.getElementById(`pageIndicator`),n=document.getElementById(`pageIndicatorName`);if(t&&n){let e=N.selectedPage.title&&N.selectedPage.title!==r(`pageSelector.noTitle`)?N.selectedPage.title:``,i=N.selectedPage.url||``;e&&i?n.textContent=`${e} · ${i}`:n.textContent=e||i,t.style.display=`flex`}}function Hb(){N.selectedPage=null,N.selectedPageIndex=-1;let e=document.getElementById(`pageIndicator`);e&&(e.style.display=`none`)}function Ub(e){let t=document.getElementById(`userInput`),n=t?t.value:``,r=n.lastIndexOf(`@`);r!==-1&&(t.value=n.substring(0,r)),t&&(t.focus(),t.selectionStart=t.selectionEnd=t.value.length),chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){a.error(`[PageSelector] getlabelpageinfo failed:`,chrome.runtime.lastError);return}Vb(e),rb(),t&&(t.focus(),Vt())})}function Wb(e,t){let n={interpret:r(`pageSelector.interpretMsg`),summarize:r(`pageSelector.summarizeMsg`),translate:r(`pageSelector.translateMsg`)}[t];n&&chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){a.error(`[PageSelector] get tab info failed:`,chrome.runtime.lastError);return}Vb(e),rb();let t=document.getElementById(`userInput`);t&&(t.value=n,Vt()),VC()})}function Gb(){let e=document.getElementById(`pageIndicatorClose`);e&&e.addEventListener(`click`,()=>{Hb()})}n(`zh`,{msgFullscreen:{title:`全屏阅读`,btnTitle:`全屏查看本回答 (Alt+双击 / Alt+F)`,btnLabel:`全屏`,copy:`复制`,copyTitle:`复制回答内容(Ctrl/⌘+点击复制富文本)`,export:`导出`,exportTitle:`导出下载本回答`,exportWord:`导出 Word`,exportPdf:`导出 PDF`,exportImage:`导出图片`,exportMarkdown:`导出 Markdown`,close:`退出全屏`,closeTitle:`退出全屏 (Esc)`}}),n(`en`,{msgFullscreen:{title:`Fullscreen Reading`,btnTitle:`View this answer fullscreen (Alt+Double-click / Alt+F)`,btnLabel:`Fullscreen`,copy:`Copy`,copyTitle:`Copy answer (Ctrl/Cmd+click for rich text)`,export:`Export`,exportTitle:`Export / download this answer`,exportWord:`Export Word`,exportPdf:`Export PDF`,exportImage:`Export Image`,exportMarkdown:`Export Markdown`,close:`Exit fullscreen`,closeTitle:`Exit fullscreen (Esc)`}});var Kb=`messageFullscreenOverlay`,qb=`messageFullscreenBody`,Jb=`messageFullscreenTitle`,Yb=`messageFullscreenCopyBtn`,Xb=`messageFullscreenCloseBtn`,Zb=`messageFullscreenExportBtn`,Qb=`messageFullscreenExportDropdown`,$b=null,ex=null,tx=null,nx=!1,rx=null,ix=!1;function ax(){return $b!==null}function ox(e){return!e||ax()?null:e.innerHTML}function sx(){let e=document.querySelectorAll(`#chatContainer .message.assistant`);return e.length?e[e.length-1]:null}function cx(){let e=document.createElement(`button`);return e.className=`fullscreen-btn`,e.title=r(`msgFullscreen.btnTitle`),e.innerHTML=[`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">`,`<path d="M6 2H2v4M10 2h4v4M6 14H2v-4M10 14h4v-4"/>`,`</svg>`,`<span>${r(`msgFullscreen.btnLabel`)}</span>`].join(``),e}function lx(){let e=document.getElementById(Kb),t=document.getElementById(qb);return!e||!t?(a.warn(`[MsgFullscreen] overlay/body element missing`),null):{overlay:e,body:t,title:document.getElementById(Jb),copyBtn:document.getElementById(Yb),closeBtn:document.getElementById(Xb)}}function ux(e){if(!e)return;let t=lx();if(t&&$b!==e){if(!$b){let e=document.getElementById(`chatContainer`);rx=e?e.scrollTop:null}$b&&(ix=!0,dx(),ix=!1),ex=document.createComment(`msg-fullscreen-anchor`),e.parentNode.insertBefore(ex,e),e.dataset.fullscreen=`1`,t.body.appendChild(e),$b=e,t.overlay.style.display=`flex`,document.body.classList.add(`message-fullscreen-viewing`),t.title&&(t.title.textContent=r(`msgFullscreen.title`)),t.copyBtn&&(t.copyBtn.title=r(`msgFullscreen.copyTitle`)),t.closeBtn&&(t.closeBtn.title=r(`msgFullscreen.closeTitle`)),xx(),px(t.body)}}function dx(){if(!$b)return;let e=lx();if(hx(),Sx(),ex&&ex.parentNode)ex.parentNode.insertBefore($b,ex);else if(e){let e=document.getElementById(`chatContainer`);e&&e.appendChild($b)}if(ex&&ex.parentNode&&ex.parentNode.removeChild(ex),delete $b.dataset.fullscreen,$b=null,ex=null,e){e.overlay.style.display=`none`,e.body.innerHTML=``;let t=e.overlay.querySelector(`.message-fullscreen-rail`);t&&t.querySelectorAll(`.message-toc-container`).forEach(e=>e.remove())}if(document.body.classList.remove(`message-fullscreen-viewing`),!ix&&rx!==null){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=rx),rx=null}}function fx(e){if($b&&$b===e){dx();return}ux(e||sx())}function px(e){hx(),nx=!1,e.scrollTop=e.scrollHeight,e.addEventListener(`scroll`,mx,{passive:!0}),typeof ResizeObserver<`u`&&(tx=new ResizeObserver(()=>{nx||(e.scrollTop=e.scrollHeight)}),tx.observe(e.firstElementChild||e))}function mx(){let e=document.getElementById(qb);e&&(nx=e.scrollHeight-e.scrollTop-e.clientHeight>60)}function hx(){let e=document.getElementById(qb);e&&e.removeEventListener(`scroll`,mx),tx&&=(tx.disconnect(),null)}function gx(e){if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&e.code===`KeyF`){e.preventDefault(),$b?dx():ux(sx());return}e.key===`Escape`&&$b&&(e.preventDefault(),e.stopImmediatePropagation(),dx())}function _x(e){if(!e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let t=e.target.closest?.(`#chatContainer .message.assistant`);t&&(e.preventDefault(),fx(t))}async function vx(e){if(!$b)return;let{copyAssistantMessage:t}=await M(async()=>{let{copyAssistantMessage:e}=await Promise.resolve().then(()=>Tx);return{copyAssistantMessage:e}},void 0);t($b,document.getElementById(Yb),e)}var yx={docx:`<path d="M4 1.5h6L13 4.5v10H4z"/><path d="M10 1.5v3h3"/><path d="M6 8h4M6 10.5h4"/>`,pdf:`<path d="M4 1.5h6L13 4.5v10H4z"/><path d="M10 1.5v3h3"/><path d="M6.5 11.5c2-1 2.5-4 1-4s-1 4 2 4"/>`,image:`<rect x="2.5" y="3" width="11" height="10" rx="1.2"/><circle cx="6" cy="6.5" r="1"/><path d="M13.5 10 10 6.5 4.5 12.5"/>`,markdown:`<path d="M2.5 12V4l3 3 3-3v8"/><path d="M12.5 4v6m0 0 2-2.2m-2 2.2L10.5 7.8"/>`};function bx(){let e=document.createElement(`div`);e.className=`message-fullscreen-export`;let t=document.createElement(`button`);t.className=`message-fullscreen-icon-btn`,t.id=Zb,t.type=`button`,t.title=r(`msgFullscreen.exportTitle`),t.innerHTML=[`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" width="16" height="16">`,`<path d="M8 2v8m0 0 3-3M8 10 5 7M2.5 13.5h11"/>`,`</svg>`,`<span>${r(`msgFullscreen.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>`].join(``);let n=document.createElement(`div`);n.className=`message-fullscreen-export-dropdown`,n.id=Qb;let i=e=>`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">${yx[e]}</svg>`;n.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">${i(`docx`)}<span>${r(`msgFullscreen.exportWord`)}</span></button>`,`<button class="export-dropdown-item export-pdf-item" type="button">${i(`pdf`)}<span>${r(`msgFullscreen.exportPdf`)}</span></button>`,`<button class="export-dropdown-item export-image-item" type="button">${i(`image`)}<span>${r(`msgFullscreen.exportImage`)}</span></button>`,`<button class="export-dropdown-item export-md-item" type="button">${i(`markdown`)}<span>${r(`msgFullscreen.exportMarkdown`)}</span></button>`].join(``),t.addEventListener(`click`,e=>{e.stopPropagation(),n.classList.toggle(`show`)});let a=(e,t)=>{let r=n.querySelector(e);r.addEventListener(`click`,async e=>{e.stopPropagation(),$b&&(n.classList.remove(`show`),(await M(()=>import(`./chat-export-BPasibDS.js`),__vite__mapDeps([10,11,1,12,2,3,4,13,14,0])))[t]($b,r,n))})};return a(`.export-docx-item`,`exportAssistantMessageToDocx`),a(`.export-pdf-item`,`exportAssistantMessageToPdf`),a(`.export-image-item`,`exportAssistantMessageToImage`),a(`.export-md-item`,`exportAssistantMessageToMarkdown`),e.appendChild(t),e.appendChild(n),e}function xx(){if(document.getElementById(Zb))return;let e=document.getElementById(Xb),t=e?e.parentNode:document.querySelector(`.message-fullscreen-actions`);t&&t.insertBefore(bx(),e||null)}function Sx(){let e=document.getElementById(Qb);e&&e.classList.remove(`show`)}var Cx=!1;function wx(){Cx||(Cx=!0,document.addEventListener(`click`,e=>{let t=document.getElementById(Qb);t&&t.classList.contains(`show`)&&!e.target.closest?.(`.message-fullscreen-export`)&&t.classList.remove(`show`);let n=e.target.closest?.(`.fullscreen-btn`);if(n){e.stopPropagation(),fx(n.closest(`.message`));return}if(e.target.closest?.(`#messageFullscreenCloseBtn`)){e.stopPropagation(),dx();return}e.target.closest?.(`#messageFullscreenCopyBtn`)&&(e.stopPropagation(),vx(e))},!0),document.addEventListener(`keydown`,gx,!0),document.addEventListener(`dblclick`,_x,!0))}var Tx=t({copyAssistantMessage:()=>Ox,copyMessage:()=>Dx,copyRichText:()=>jx,fallbackCopyRichText:()=>Nx,fallbackCopyText:()=>Ax,quoteAndAsk:()=>Ix,setQuoteContextInjector:()=>Fx,showCopySuccess:()=>kx,wrapHtmlWithStyles:()=>Mx});n(`zh`,{chatCopy:{copiedMarkdown:`已复制 Markdown`,copiedRich:`已复制富文本`,copyFailedManual:`复制失败,请手动复制`}}),n(`en`,{chatCopy:{copiedMarkdown:`Markdown copied`,copiedRich:`Rich text copied`,copyFailedManual:`Copy failed, please copy manually`}});function Ex(e){let t=e.querySelectorAll(`.mermaid`),n=null;for(let e of t)try{if(!n&&e._pngDataUrl){let t=e._pngDataUrl.split(`,`)[1]||``,r=atob(t),i=r.length,a=new Uint8Array(i);for(let e=0;e<i;e++)a[e]=r.charCodeAt(e);n=new Blob([a],{type:`image/png`})}let t=e.getAttribute(`data-raw-code`),r=t?decodeURIComponent(t):e.dataset.rawMermaidCode||(e.textContent||``).trim();if(r){let t=r.split(`
1363
+ `}).join(``),t.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{let n=t.target.closest(`.page-action-btn`);if(n){t.stopPropagation(),Wb(parseInt(n.dataset.tabId),n.dataset.action);return}Ub(parseInt(e.dataset.tabId))})})}function Bb(e){e.forEach((e,t)=>{t===N.selectedPageIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function Vb(e){N.selectedPage={id:e.id,title:e.title||r(`pageSelector.noTitle`),url:e.url||``,favIconUrl:e.favIconUrl||``};let t=document.getElementById(`pageIndicator`),n=document.getElementById(`pageIndicatorName`);if(t&&n){let e=N.selectedPage.title&&N.selectedPage.title!==r(`pageSelector.noTitle`)?N.selectedPage.title:``,i=N.selectedPage.url||``;e&&i?n.textContent=`${e} · ${i}`:n.textContent=e||i,t.style.display=`flex`}}function Hb(){N.selectedPage=null,N.selectedPageIndex=-1;let e=document.getElementById(`pageIndicator`);e&&(e.style.display=`none`)}function Ub(e){let t=document.getElementById(`userInput`),n=t?t.value:``,r=n.lastIndexOf(`@`);r!==-1&&(t.value=n.substring(0,r)),t&&(t.focus(),t.selectionStart=t.selectionEnd=t.value.length),chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){a.error(`[PageSelector] getlabelpageinfo failed:`,chrome.runtime.lastError);return}Vb(e),rb(),t&&(t.focus(),Vt())})}function Wb(e,t){let n={interpret:r(`pageSelector.interpretMsg`),summarize:r(`pageSelector.summarizeMsg`),translate:r(`pageSelector.translateMsg`)}[t];n&&chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){a.error(`[PageSelector] get tab info failed:`,chrome.runtime.lastError);return}Vb(e),rb();let t=document.getElementById(`userInput`);t&&(t.value=n,Vt()),VC()})}function Gb(){let e=document.getElementById(`pageIndicatorClose`);e&&e.addEventListener(`click`,()=>{Hb()})}n(`zh`,{msgFullscreen:{title:`全屏阅读`,btnTitle:`全屏查看本回答 (Alt+双击 / Alt+F)`,btnLabel:`全屏`,copy:`复制`,copyTitle:`复制回答内容(Ctrl/⌘+点击复制富文本)`,export:`导出`,exportTitle:`导出下载本回答`,exportWord:`导出 Word`,exportPdf:`导出 PDF`,exportImage:`导出图片`,exportMarkdown:`导出 Markdown`,close:`退出全屏`,closeTitle:`退出全屏 (Esc)`}}),n(`en`,{msgFullscreen:{title:`Fullscreen Reading`,btnTitle:`View this answer fullscreen (Alt+Double-click / Alt+F)`,btnLabel:`Fullscreen`,copy:`Copy`,copyTitle:`Copy answer (Ctrl/Cmd+click for rich text)`,export:`Export`,exportTitle:`Export / download this answer`,exportWord:`Export Word`,exportPdf:`Export PDF`,exportImage:`Export Image`,exportMarkdown:`Export Markdown`,close:`Exit fullscreen`,closeTitle:`Exit fullscreen (Esc)`}});var Kb=`messageFullscreenOverlay`,qb=`messageFullscreenBody`,Jb=`messageFullscreenTitle`,Yb=`messageFullscreenCopyBtn`,Xb=`messageFullscreenCloseBtn`,Zb=`messageFullscreenExportBtn`,Qb=`messageFullscreenExportDropdown`,$b=null,ex=null,tx=null,nx=!1,rx=null,ix=!1;function ax(){return $b!==null}function ox(e){return!e||ax()?null:e.innerHTML}function sx(){let e=document.querySelectorAll(`#chatContainer .message.assistant`);return e.length?e[e.length-1]:null}function cx(){let e=document.createElement(`button`);return e.className=`fullscreen-btn`,e.title=r(`msgFullscreen.btnTitle`),e.innerHTML=[`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">`,`<path d="M6 2H2v4M10 2h4v4M6 14H2v-4M10 14h4v-4"/>`,`</svg>`,`<span>${r(`msgFullscreen.btnLabel`)}</span>`].join(``),e}function lx(){let e=document.getElementById(Kb),t=document.getElementById(qb);return!e||!t?(a.warn(`[MsgFullscreen] overlay/body element missing`),null):{overlay:e,body:t,title:document.getElementById(Jb),copyBtn:document.getElementById(Yb),closeBtn:document.getElementById(Xb)}}function ux(e){if(!e)return;let t=lx();if(t&&$b!==e){if(!$b){let e=document.getElementById(`chatContainer`);rx=e?e.scrollTop:null}$b&&(ix=!0,dx(),ix=!1),ex=document.createComment(`msg-fullscreen-anchor`),e.parentNode.insertBefore(ex,e),e.dataset.fullscreen=`1`,t.body.appendChild(e),$b=e,t.overlay.style.display=`flex`,document.body.classList.add(`message-fullscreen-viewing`),t.title&&(t.title.textContent=r(`msgFullscreen.title`)),t.copyBtn&&(t.copyBtn.title=r(`msgFullscreen.copyTitle`)),t.closeBtn&&(t.closeBtn.title=r(`msgFullscreen.closeTitle`)),xx(),px(t.body)}}function dx(){if(!$b)return;let e=lx();if(hx(),Sx(),ex&&ex.parentNode)ex.parentNode.insertBefore($b,ex);else if(e){let e=document.getElementById(`chatContainer`);e&&e.appendChild($b)}if(ex&&ex.parentNode&&ex.parentNode.removeChild(ex),delete $b.dataset.fullscreen,$b=null,ex=null,e){e.overlay.style.display=`none`,e.body.innerHTML=``;let t=e.overlay.querySelector(`.message-fullscreen-rail`);t&&t.querySelectorAll(`.message-toc-container`).forEach(e=>e.remove())}if(document.body.classList.remove(`message-fullscreen-viewing`),!ix&&rx!==null){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=rx),rx=null}}function fx(e){if($b&&$b===e){dx();return}ux(e||sx())}function px(e){hx(),nx=!1,e.scrollTop=e.scrollHeight,e.addEventListener(`scroll`,mx,{passive:!0}),typeof ResizeObserver<`u`&&(tx=new ResizeObserver(()=>{nx||(e.scrollTop=e.scrollHeight)}),tx.observe(e.firstElementChild||e))}function mx(){let e=document.getElementById(qb);e&&(nx=e.scrollHeight-e.scrollTop-e.clientHeight>60)}function hx(){let e=document.getElementById(qb);e&&e.removeEventListener(`scroll`,mx),tx&&=(tx.disconnect(),null)}function gx(e){if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&e.code===`KeyF`){e.preventDefault(),$b?dx():ux(sx());return}e.key===`Escape`&&$b&&(e.preventDefault(),e.stopImmediatePropagation(),dx())}function _x(e){if(!e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let t=e.target.closest?.(`#chatContainer .message.assistant`);t&&(e.preventDefault(),fx(t))}async function vx(e){if(!$b)return;let{copyAssistantMessage:t}=await M(async()=>{let{copyAssistantMessage:e}=await Promise.resolve().then(()=>Tx);return{copyAssistantMessage:e}},void 0);t($b,document.getElementById(Yb),e)}var yx={docx:`<path d="M4 1.5h6L13 4.5v10H4z"/><path d="M10 1.5v3h3"/><path d="M6 8h4M6 10.5h4"/>`,pdf:`<path d="M4 1.5h6L13 4.5v10H4z"/><path d="M10 1.5v3h3"/><path d="M6.5 11.5c2-1 2.5-4 1-4s-1 4 2 4"/>`,image:`<rect x="2.5" y="3" width="11" height="10" rx="1.2"/><circle cx="6" cy="6.5" r="1"/><path d="M13.5 10 10 6.5 4.5 12.5"/>`,markdown:`<path d="M2.5 12V4l3 3 3-3v8"/><path d="M12.5 4v6m0 0 2-2.2m-2 2.2L10.5 7.8"/>`};function bx(){let e=document.createElement(`div`);e.className=`message-fullscreen-export`;let t=document.createElement(`button`);t.className=`message-fullscreen-icon-btn`,t.id=Zb,t.type=`button`,t.title=r(`msgFullscreen.exportTitle`),t.innerHTML=[`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" width="16" height="16">`,`<path d="M8 2v8m0 0 3-3M8 10 5 7M2.5 13.5h11"/>`,`</svg>`,`<span>${r(`msgFullscreen.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>`].join(``);let n=document.createElement(`div`);n.className=`message-fullscreen-export-dropdown`,n.id=Qb;let i=e=>`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">${yx[e]}</svg>`;n.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">${i(`docx`)}<span>${r(`msgFullscreen.exportWord`)}</span></button>`,`<button class="export-dropdown-item export-pdf-item" type="button">${i(`pdf`)}<span>${r(`msgFullscreen.exportPdf`)}</span></button>`,`<button class="export-dropdown-item export-image-item" type="button">${i(`image`)}<span>${r(`msgFullscreen.exportImage`)}</span></button>`,`<button class="export-dropdown-item export-md-item" type="button">${i(`markdown`)}<span>${r(`msgFullscreen.exportMarkdown`)}</span></button>`].join(``),t.addEventListener(`click`,e=>{e.stopPropagation(),n.classList.toggle(`show`)});let a=(e,t)=>{let r=n.querySelector(e);r.addEventListener(`click`,async e=>{e.stopPropagation(),$b&&(n.classList.remove(`show`),(await M(()=>import(`./chat-export-DeqIrNGG.js`),__vite__mapDeps([10,11,1,12,2,3,4,13,14,0])))[t]($b,r,n))})};return a(`.export-docx-item`,`exportAssistantMessageToDocx`),a(`.export-pdf-item`,`exportAssistantMessageToPdf`),a(`.export-image-item`,`exportAssistantMessageToImage`),a(`.export-md-item`,`exportAssistantMessageToMarkdown`),e.appendChild(t),e.appendChild(n),e}function xx(){if(document.getElementById(Zb))return;let e=document.getElementById(Xb),t=e?e.parentNode:document.querySelector(`.message-fullscreen-actions`);t&&t.insertBefore(bx(),e||null)}function Sx(){let e=document.getElementById(Qb);e&&e.classList.remove(`show`)}var Cx=!1;function wx(){Cx||(Cx=!0,document.addEventListener(`click`,e=>{let t=document.getElementById(Qb);t&&t.classList.contains(`show`)&&!e.target.closest?.(`.message-fullscreen-export`)&&t.classList.remove(`show`);let n=e.target.closest?.(`.fullscreen-btn`);if(n){e.stopPropagation(),fx(n.closest(`.message`));return}if(e.target.closest?.(`#messageFullscreenCloseBtn`)){e.stopPropagation(),dx();return}e.target.closest?.(`#messageFullscreenCopyBtn`)&&(e.stopPropagation(),vx(e))},!0),document.addEventListener(`keydown`,gx,!0),document.addEventListener(`dblclick`,_x,!0))}var Tx=t({copyAssistantMessage:()=>Ox,copyMessage:()=>Dx,copyRichText:()=>jx,fallbackCopyRichText:()=>Nx,fallbackCopyText:()=>Ax,quoteAndAsk:()=>Ix,setQuoteContextInjector:()=>Fx,showCopySuccess:()=>kx,wrapHtmlWithStyles:()=>Mx});n(`zh`,{chatCopy:{copiedMarkdown:`已复制 Markdown`,copiedRich:`已复制富文本`,copyFailedManual:`复制失败,请手动复制`}}),n(`en`,{chatCopy:{copiedMarkdown:`Markdown copied`,copiedRich:`Rich text copied`,copyFailedManual:`Copy failed, please copy manually`}});function Ex(e){let t=e.querySelectorAll(`.mermaid`),n=null;for(let e of t)try{if(!n&&e._pngDataUrl){let t=e._pngDataUrl.split(`,`)[1]||``,r=atob(t),i=r.length,a=new Uint8Array(i);for(let e=0;e<i;e++)a[e]=r.charCodeAt(e);n=new Blob([a],{type:`image/png`})}let t=e.getAttribute(`data-raw-code`),r=t?decodeURIComponent(t):e.dataset.rawMermaidCode||(e.textContent||``).trim();if(r){let t=r.split(`
1364
1364
  `),n=document.createElement(`pre`);n.appendChild(document.createTextNode(t[0]||``));for(let e=1;e<t.length;e++)n.appendChild(document.createElement(`br`)),n.appendChild(document.createTextNode(t[e]));e.parentNode.replaceChild(n,e)}else e.remove()}catch(t){a.warn(`[SidePanel] Mermaid chartprocessing failed,remove:`,t.message),e.remove()}return{html:e.innerHTML,firstPngBlob:n}}function Dx(e,t){try{let n=e.dataset.textContent_||e.dataset.rawContent||``;navigator.clipboard.writeText(n).then(()=>{let e=t.innerHTML;t.innerHTML=`
1365
1365
  <svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor">
1366
1366
  <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.75.75 0 0 1 1.06-1.06L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0z"/>
@@ -1564,7 +1564,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
1564
1564
  ... (点击展开查看完整输出)`,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}
1565
1565
  点击查看评估详情`,reflectionFailedTitle:`反思评估失败(点击查看执行日志)`,reflectionFailedBadge:`⚠️ 反思失败`,prototypeOpenedLocal:`已在本地浏览器打开,点击可在面板内查看`,viewUiPrototype:`查看 UI 原型`,bookmarkMessage:`收藏消息`,removeBookmark:`取消收藏`,forkSession:`从此处分叉会话(仅复制到此条消息)`,deleteMessage:`删除消息`,stopping:`停止中...`,taskStopped:`任务已被用户停止`,cancelled:`已取消`}}),n(`en`,{chatStream:{thinking:`Thinking...`,outputting:`Outputting...`,retrying:`Connection unstable, retrying ({attempt}/{max})...`,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:`
1566
1566
  ... (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}
1567
- 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 sS=new Map,cS=!1,lS=!1,uS=!1,dS=!1;function fS(){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`),dS=!1):e.classList.add(`visible`),t&&(dS&&!r?(t.classList.add(`active`),N.isGenerating?t.classList.add(`pulsing`):t.classList.remove(`pulsing`)):t.classList.remove(`active`,`pulsing`))}function pS(){if(uS)return;let e=document.getElementById(`chatContainer`);e&&(uS=!0,e.addEventListener(`scroll`,()=>{if(cS)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight<80;lS=!t,t?dS=!1:N.isGenerating&&(dS=!0),fS()},{passive:!0}),document.addEventListener(`generating-state-changed`,()=>{N.isGenerating&&(dS=!0),requestAnimationFrame(()=>fS())}))}function mS(e,t={}){if(!e)return;pS();let{force:n=!1,smooth:r=!1}=t;if(!n&&lS){dS=!0,fS();return}if(cS=!0,r){e.scrollTo({top:e.scrollHeight,behavior:`smooth`}),requestAnimationFrame(()=>{cS=!1});return}e.scrollTop=e.scrollHeight,requestAnimationFrame(()=>{lS||(e.scrollTop=e.scrollHeight),requestAnimationFrame(()=>{cS=!1})})}function hS(e){if(!e||!e.isConnected)return;let t=document.getElementById(`chatContainer`);t&&mS(t)}function gS(){lS=!1,dS=!1,N.isGenerating&&(dS=!0),fS()}function _S(){pS();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&&(lS=!1,dS=!1,fS(),mS(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),fS()}function vS(){pS();let e=document.getElementById(`chatContainer`);e&&(e.scrollHeight-e.scrollTop-e.clientHeight<80||(dS=!0),fS())}function yS(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 bS(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=Lt(t?JSON.parse(t):[]);r&&Dt(r,n)}catch{}return}n&&n.dataset.filter?yS(r,r.dataset.activeFilter===n.dataset.filter?`all`:n.dataset.filter):r.classList.toggle(`collapsed`)}});let n=e.closest(`.thinking-process`);n&&yS(n,n.dataset.activeFilter||`all`)}async function xS(){try{let{getAllAgents:e}=await M(async()=>{let{getAllAgents:e}=await import(`./agent-store-CrkBz4jI.js`).then(e=>e.t);return{getAllAgents:e}},__vite__mapDeps([0,1,2,3,4])),t=await e();sS.clear();for(let e of t)sS.set(e.id,e.name||e.id)}catch{}}function SS(e){return sS.get(e)||e}var CS=new Map,wS=new Map,TS=null,ES=0,DS=0,OS=``;function kS(e){return t=>t===void 0?CS.get(e)||null:(CS.set(e,t),t)}function AS(e){CS.delete(e),wS.delete(e),aS(e)}function jS(e){return wS.get(e)||``}function MS(e,t){if(wS.set(e,t),!t){nS(e);return}WS(CS.get(e))}function NS(){return TS}function PS(e){TS=e}function FS(){return ES}function IS(e){ES=e}function LS(){return DS}function RS(e){DS=e}function zS(){return OS}function BS(e){OS=e}function VS(){return`
1567
+ 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 sS=new Map,cS=!1,lS=!1,uS=!1,dS=!1;function fS(){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`),dS=!1):e.classList.add(`visible`),t&&(dS&&!r?(t.classList.add(`active`),N.isGenerating?t.classList.add(`pulsing`):t.classList.remove(`pulsing`)):t.classList.remove(`active`,`pulsing`))}function pS(){if(uS)return;let e=document.getElementById(`chatContainer`);e&&(uS=!0,e.addEventListener(`scroll`,()=>{if(cS)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight<80;lS=!t,t?dS=!1:N.isGenerating&&(dS=!0),fS()},{passive:!0}),document.addEventListener(`generating-state-changed`,()=>{N.isGenerating&&(dS=!0),requestAnimationFrame(()=>fS())}))}function mS(e,t={}){if(!e)return;pS();let{force:n=!1,smooth:r=!1}=t;if(!n&&lS){dS=!0,fS();return}if(cS=!0,r){e.scrollTo({top:e.scrollHeight,behavior:`smooth`}),requestAnimationFrame(()=>{cS=!1});return}e.scrollTop=e.scrollHeight,requestAnimationFrame(()=>{lS||(e.scrollTop=e.scrollHeight),requestAnimationFrame(()=>{cS=!1})})}function hS(e){if(!e||!e.isConnected)return;let t=document.getElementById(`chatContainer`);t&&mS(t)}function gS(){lS=!1,dS=!1,N.isGenerating&&(dS=!0),fS()}function _S(){pS();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&&(lS=!1,dS=!1,fS(),mS(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),fS()}function vS(){pS();let e=document.getElementById(`chatContainer`);e&&(e.scrollHeight-e.scrollTop-e.clientHeight<80||(dS=!0),fS())}function yS(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 bS(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=Lt(t?JSON.parse(t):[]);r&&Dt(r,n)}catch{}return}n&&n.dataset.filter?yS(r,r.dataset.activeFilter===n.dataset.filter?`all`:n.dataset.filter):r.classList.toggle(`collapsed`)}});let n=e.closest(`.thinking-process`);n&&yS(n,n.dataset.activeFilter||`all`)}async function xS(){try{let{getAllAgents:e}=await M(async()=>{let{getAllAgents:e}=await import(`./agent-store-1fyaAv9T.js`).then(e=>e.t);return{getAllAgents:e}},__vite__mapDeps([0,1,2,3,4])),t=await e();sS.clear();for(let e of t)sS.set(e.id,e.name||e.id)}catch{}}function SS(e){return sS.get(e)||e}var CS=new Map,wS=new Map,TS=null,ES=0,DS=0,OS=``;function kS(e){return t=>t===void 0?CS.get(e)||null:(CS.set(e,t),t)}function AS(e){CS.delete(e),wS.delete(e),aS(e)}function jS(e){return wS.get(e)||``}function MS(e,t){if(wS.set(e,t),!t){nS(e);return}WS(CS.get(e))}function NS(){return TS}function PS(e){TS=e}function FS(){return ES}function IS(e){ES=e}function LS(){return DS}function RS(e){DS=e}function zS(){return OS}function BS(e){OS=e}function VS(){return`
1568
1568
  <svg class="thinking-icon pulse-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1569
1569
  <path d="M12 2a3 3 0 0 0-3 3v1a3 3 0 0 0 3 3 3 3 0 0 1 3 3v1a3 3 0 0 1-3 3 3 3 0 0 0-3 3v1a3 3 0 0 0 3 3"/>
1570
1570
  <circle cx="8" cy="12" r="1.5"/>
@@ -1721,7 +1721,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
1721
1721
  <svg class="thinking-process-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1722
1722
  <polyline points="6 9 12 15 18 9"/>
1723
1723
  </svg>
1724
- `,d){let e=p.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Dt(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=qt(e));let n=c.querySelector(`.thinking-indicator`);n&&n.remove(),c.appendChild(f),c.appendChild(t),bS(p)}else{let t=c.querySelector(`.thinking-indicator`);t&&t.remove(),e&&e.trim()&&(l.innerHTML=qt(e))}}else e&&e.trim()&&(l.innerHTML=qt(e))}e.classList.add(`assistant`,`message`),e.dataset.rawContent=typeof t==`string`?rn(t):JSON.stringify(t),e.dataset.textContent_=rn(uC(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(),Ox(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(),Ix(e)}),f.appendChild(m),f.appendChild(cx());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 M(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-BPasibDS.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));n(e,v,_)});let y=_.querySelector(`.export-md-item`);y.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToMarkdown:n}=await M(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-BPasibDS.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));n(e,y,_)});let b=_.querySelector(`.export-pdf-item`);b.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToPdf:n}=await M(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-BPasibDS.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));n(e,b,_)});let x=_.querySelector(`.export-image-item`);x.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToImage:n}=await M(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-BPasibDS.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,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=Lt(n);if(w){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:F(w.totalTokens),prompt:F(w.promptTokens),completion:F(w.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${F(w.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Dt(w,e)}),C.appendChild(e)}let T=Oy(t),E=jy(n,t);if(T.length&&(e.dataset.declaredArtifacts=JSON.stringify(T)),Yy(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=`
1724
+ `,d){let e=p.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Dt(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=qt(e));let n=c.querySelector(`.thinking-indicator`);n&&n.remove(),c.appendChild(f),c.appendChild(t),bS(p)}else{let t=c.querySelector(`.thinking-indicator`);t&&t.remove(),e&&e.trim()&&(l.innerHTML=qt(e))}}else e&&e.trim()&&(l.innerHTML=qt(e))}e.classList.add(`assistant`,`message`),e.dataset.rawContent=typeof t==`string`?rn(t):JSON.stringify(t),e.dataset.textContent_=rn(uC(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(),Ox(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(),Ix(e)}),f.appendChild(m),f.appendChild(cx());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 M(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-DeqIrNGG.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));n(e,v,_)});let y=_.querySelector(`.export-md-item`);y.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToMarkdown:n}=await M(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-DeqIrNGG.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));n(e,y,_)});let b=_.querySelector(`.export-pdf-item`);b.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToPdf:n}=await M(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-DeqIrNGG.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));n(e,b,_)});let x=_.querySelector(`.export-image-item`);x.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToImage:n}=await M(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-DeqIrNGG.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,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=Lt(n);if(w){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:F(w.totalTokens),prompt:F(w.promptTokens),completion:F(w.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${F(w.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Dt(w,e)}),C.appendChild(e)}let T=Oy(t),E=jy(n,t);if(T.length&&(e.dataset.declaredArtifacts=JSON.stringify(T)),Yy(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=`
1725
1725
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
1726
1726
  <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
1727
1727
  <polyline points="14 2 14 8 20 8"/>
@@ -1747,7 +1747,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
1747
1747
  点击查看评估详情`,reflectionFailedTitle:`反思评估失败(点击查看执行日志)`,reflectionFailedBadge:`⚠️ 反思失败`,prototypeLocalOpened:`已在本地浏览器打开,点击可在面板内查看`,prototypeView:`查看 UI 原型`,bookmarkMessage:`收藏消息`,unbookmarkMessage:`取消收藏`,forkSession:`从此处分叉会话(仅复制到此条消息)`,deleteMessageTitle:`删除消息`,resumeTaskTitle:`从上次中断处继续执行任务`,resumeTaskTitleBudget:`执行预算已用完(部分完成):点击后可在新的预算下接着未完成的部分继续`,resumeTaskBtn:`继续执行`,clickToEnlarge:`点击查看大图`,fileExtracting:` 提取中...`,fileFailed:` 失败`,fileExtractFailed:`提取失败`,copyMessageTitle:`复制消息内容`,editAndResend:`编辑后重新发送`,thinking:`思考中...`,stopTask:`停止任务`,viewExecutionLog:`查看执行日志`,preparing:`准备中...`,emptyModelReply:`模型未返回任何内容。若你发送了图片,请确认所选模型支持视觉识别(图片识别需选择支持多模态视觉的模型),或更换模型后重试。`,stopping:`停止中...`,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:`✓ 全部完成`,subtaskReplaySkipped:`已跳过重放`,subtaskReplaySkippedHint:`中断前已成功完成,本轮未重复执行,写操作不会二次生效`,subtaskFilterEmpty:`当前过滤下无匹配节点`,subtaskFilterHint:`点击按此状态过滤节点,再点取消`,subtaskStatOtherHint:`已取消 / 未完成节点(用户拒绝确认、任务终止时仍在执行等),点击过滤`,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}
1748
1748
  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`,resumeTaskTitleBudget:`Execution budget exhausted (partially complete): click to continue the unfinished parts with a fresh budget`,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...`,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`,subtaskReplaySkipped:`replay skipped`,subtaskReplaySkippedHint:`Already completed before the interruption; not re-run this round, so side effects do not apply twice`,subtaskFilterEmpty:`No nodes match this filter`,subtaskFilterHint:`Click to filter nodes by this status, click again to clear`,subtaskStatOtherHint:`Cancelled / unfinished nodes (denied confirmations, still running when the task ended). Click to filter`,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 sC=`pendingCallApiSessions`;function cC(){chrome.storage.session.set({[sC]:[...N.pendingCallApiSessionIds]}).catch(()=>{})}async function lC(){try{let e=await chrome.storage.session.get([sC]);e[sC]&&Array.isArray(e[sC])&&(N.pendingCallApiSessionIds=new Set(e[sC]))}catch{}}function uC(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 dC(e){let t=uC(e);N.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 fC(){let e=document.getElementById(`selectionIndicator`),t=document.getElementById(`selectionText`);if(!e||!t)return;let n=(N.quotedContextText||``).trim(),i=(N.selectedContextText||``).trim(),a=n||i;if(!a){e.classList.remove(`show`);return}let o;o=a.length>100?a.substring(0,100)+`...`:a.length>50?a.substring(0,50)+`...`:a,t.textContent=r(n?`chatMsg.quotedContextLabel`:`chatMsg.selectedContextLabel`,{text:o}),e.classList.add(`show`)}function pC(){a.debug(`[SidePanel] clear selectedcontenttext `),N.selectedContextText=``,N.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(`
1749
1749
  `),n=e.findIndex(e=>e.startsWith(`[用户问题]`));n===-1?t.value=``:t.value=e.slice(n+1).join(`
1750
- `).trim()}}var mC,hC=new Promise(e=>{mC=e});function gC(){N.activeSessionId&&document.dispatchEvent(new CustomEvent(`session-hydrated`,{detail:{sessionId:N.activeSessionId,workdir:N.sessionWorkdir||null}}))}async function _C(){try{await vC()}finally{mC(),document.dispatchEvent(new CustomEvent(`chat-history-rendered`,{detail:{sessionId:N.activeSessionId||null}}))}}async function vC(){let e=await ki();if(e.activeSessionId&&e.list.length>0){N.activeSessionId=e.activeSessionId,N.sessions=e.list;let t=e.list.find(t=>t.id===e.activeSessionId);if(t){if(N.messageHistory=t.messageHistory||[],N.activeCompaction=t.contextCompaction||null,ji(t),gC(),N.currentModel=t.model||N.currentModel,N.useTools=t.useTools===void 0?N.useTools:t.useTools,N.temperature=t.temperature===void 0?N.temperature:t.temperature,N.topP=t.topP===void 0?N.topP:t.topP,N.activeAgentId=t.agentId||null,N.activeAgentId&&N.activeAgentId!=="default"){try{let{getAgent:e}=await M(async()=>{let{getAgent:e}=await import(`./agent-store-CrkBz4jI.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3,4])),t=await e(N.activeAgentId);t&&(N.activeAgentMcpExcludedServerIds=t.mcpExcludedServerIds??null,t.model&&(N.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(N.temperature=t.temperature,N.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`)))}catch{}N.activeAgentMcpExcludedServerIds=null}else{N.activeAgentMcpExcludedServerIds=null;try{let e=await chrome.storage.local.get([`modelName`,`temperature`,`topP`]);e.modelName&&(N.currentModel=e.modelName),e.temperature!==void 0&&(N.temperature=e.temperature),e.topP!==void 0&&(N.topP=e.topP)}catch{}document.dispatchEvent(new CustomEvent(`agent-model-changed`))}let e=`agentMcpClosedServers_${N.activeAgentId||`default`}`;N.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}let n=document.getElementById(`chatContainer`);n&&n.querySelectorAll(`.message, .user-context-bubble`).forEach(e=>e.remove()),N.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} (${rm(e.size||0)})`;break;case`knowledge`:{let t=Array.isArray(e.refs)?e.refs:[];t.length>0&&EC(t,e.failed===!0);break}}t&&e.type!==`file`&&GC(e.type,t,!1)}),e.htmlContent)iw(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||``}));YC(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,t,null,e.messageId,n,e.resumable,e.timestamp??null)}}),QC(),ew(),Kt();let i=document.querySelector(`.welcome-message`);i&&N.messageHistory.length>0&&i.remove(),$t(),sn(),wE(),e.activeSessionId===N.activeSessionId?Jo(e):Jo(),await Ux();let a=`scrollPosition_`+(N.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 Ni();let e=await ki();e.activeSessionId&&(N.activeSessionId=e.activeSessionId,N.sessions=e.list,ji(e.list.find(t=>t.id===e.activeSessionId)),gC()),Jo(e)}}function yC(){try{Ai().catch(e=>{a.error(`[SidePanel] save currentsession failed:`,e)})}catch(e){a.error(`[SidePanel] save conversationhistory exception:`,e)}}async function bC(){try{await Ai()}catch(e){a.error(`[SidePanel] save conversationhistory exception:`,e)}}function xC(){N.messageHistory&&N.messageHistory.length>0&&Ri().then(()=>{N.messageHistory=[],N.activeCompaction=null;let e=document.getElementById(`chatContainer`);if(e){e.innerHTML=``;let t=document.createElement(`div`);t.className=`welcome-message`,t.innerHTML=`
1750
+ `).trim()}}var mC,hC=new Promise(e=>{mC=e});function gC(){N.activeSessionId&&document.dispatchEvent(new CustomEvent(`session-hydrated`,{detail:{sessionId:N.activeSessionId,workdir:N.sessionWorkdir||null}}))}async function _C(){try{await vC()}finally{mC(),document.dispatchEvent(new CustomEvent(`chat-history-rendered`,{detail:{sessionId:N.activeSessionId||null}}))}}async function vC(){let e=await ki();if(e.activeSessionId&&e.list.length>0){N.activeSessionId=e.activeSessionId,N.sessions=e.list;let t=e.list.find(t=>t.id===e.activeSessionId);if(t){if(N.messageHistory=t.messageHistory||[],N.activeCompaction=t.contextCompaction||null,ji(t),gC(),N.currentModel=t.model||N.currentModel,N.useTools=t.useTools===void 0?N.useTools:t.useTools,N.temperature=t.temperature===void 0?N.temperature:t.temperature,N.topP=t.topP===void 0?N.topP:t.topP,N.activeAgentId=t.agentId||null,N.activeAgentId&&N.activeAgentId!=="default"){try{let{getAgent:e}=await M(async()=>{let{getAgent:e}=await import(`./agent-store-1fyaAv9T.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3,4])),t=await e(N.activeAgentId);t&&(N.activeAgentMcpExcludedServerIds=t.mcpExcludedServerIds??null,t.model&&(N.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(N.temperature=t.temperature,N.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`)))}catch{}N.activeAgentMcpExcludedServerIds=null}else{N.activeAgentMcpExcludedServerIds=null;try{let e=await chrome.storage.local.get([`modelName`,`temperature`,`topP`]);e.modelName&&(N.currentModel=e.modelName),e.temperature!==void 0&&(N.temperature=e.temperature),e.topP!==void 0&&(N.topP=e.topP)}catch{}document.dispatchEvent(new CustomEvent(`agent-model-changed`))}let e=`agentMcpClosedServers_${N.activeAgentId||`default`}`;N.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}let n=document.getElementById(`chatContainer`);n&&n.querySelectorAll(`.message, .user-context-bubble`).forEach(e=>e.remove()),N.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} (${rm(e.size||0)})`;break;case`knowledge`:{let t=Array.isArray(e.refs)?e.refs:[];t.length>0&&EC(t,e.failed===!0);break}}t&&e.type!==`file`&&GC(e.type,t,!1)}),e.htmlContent)iw(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||``}));YC(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,t,null,e.messageId,n,e.resumable,e.timestamp??null)}}),QC(),ew(),Kt();let i=document.querySelector(`.welcome-message`);i&&N.messageHistory.length>0&&i.remove(),$t(),sn(),wE(),e.activeSessionId===N.activeSessionId?Jo(e):Jo(),await Ux();let a=`scrollPosition_`+(N.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 Ni();let e=await ki();e.activeSessionId&&(N.activeSessionId=e.activeSessionId,N.sessions=e.list,ji(e.list.find(t=>t.id===e.activeSessionId)),gC()),Jo(e)}}function yC(){try{Ai().catch(e=>{a.error(`[SidePanel] save currentsession failed:`,e)})}catch(e){a.error(`[SidePanel] save conversationhistory exception:`,e)}}async function bC(){try{await Ai()}catch(e){a.error(`[SidePanel] save conversationhistory exception:`,e)}}function xC(){N.messageHistory&&N.messageHistory.length>0&&Ri().then(()=>{N.messageHistory=[],N.activeCompaction=null;let e=document.getElementById(`chatContainer`);if(e){e.innerHTML=``;let t=document.createElement(`div`);t.className=`welcome-message`,t.innerHTML=`
1751
1751
  <div class="icon-wrapper">
1752
1752
  <div class="icon">💬</div>
1753
1753
  </div>
@@ -1771,7 +1771,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
1771
1771
  </div>
1772
1772
  <div class="context-bubble-content">${l}</div>
1773
1773
  </div>
1774
- `;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 KC(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 qC(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}var JC=e=>!!e&&e.dataset.resumable===`budget`;function YC(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=e===`user`?de(_):_,y=Array.isArray(t)&&t.some(e=>e.type===`image_url`);m.dataset.rawContent=Array.isArray(t)?JSON.stringify(t):rn(t),m.dataset.textContent_=rn(e===`user`?de(c||v):c||v);let b=v;if(m.dataset.executionLog=JSON.stringify(i),s&&(m.dataset.wasRevised=`true`),e===`assistant`){m.innerHTML=qt(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(),Ox(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(),Ix(m)}),e.appendChild(c),e.appendChild(cx());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 M(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-BPasibDS.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));t(m,p,f)});let h=f.querySelector(`.export-md-item`);h.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToMarkdown:t}=await M(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-BPasibDS.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));t(m,h,f)});let _=f.querySelector(`.export-pdf-item`);_.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToPdf:t}=await M(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-BPasibDS.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));t(m,_,f)});let v=f.querySelector(`.export-image-item`);v.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToImage:t}=await M(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-BPasibDS.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,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=Lt(i);if(x){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:F(x.totalTokens),prompt:F(x.promptTokens),completion:F(x.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${F(x.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Dt(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;QC(),ew(),Kt();let T=i?.find(e=>e.nodeType===`reflection`&&e.reflectionType===`post`),E=Oy(t),D=jy(i,t);if(E.length&&(m.dataset.declaredArtifacts=JSON.stringify(E)),Yy(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=`
1774
+ `;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 KC(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 qC(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}var JC=e=>!!e&&e.dataset.resumable===`budget`;function YC(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=e===`user`?de(_):_,y=Array.isArray(t)&&t.some(e=>e.type===`image_url`);m.dataset.rawContent=Array.isArray(t)?JSON.stringify(t):rn(t),m.dataset.textContent_=rn(e===`user`?de(c||v):c||v);let b=v;if(m.dataset.executionLog=JSON.stringify(i),s&&(m.dataset.wasRevised=`true`),e===`assistant`){m.innerHTML=qt(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(),Ox(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(),Ix(m)}),e.appendChild(c),e.appendChild(cx());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 M(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-DeqIrNGG.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));t(m,p,f)});let h=f.querySelector(`.export-md-item`);h.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToMarkdown:t}=await M(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-DeqIrNGG.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));t(m,h,f)});let _=f.querySelector(`.export-pdf-item`);_.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToPdf:t}=await M(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-DeqIrNGG.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));t(m,_,f)});let v=f.querySelector(`.export-image-item`);v.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToImage:t}=await M(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-DeqIrNGG.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,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=Lt(i);if(x){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:F(x.totalTokens),prompt:F(x.promptTokens),completion:F(x.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${F(x.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Dt(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;QC(),ew(),Kt();let T=i?.find(e=>e.nodeType===`reflection`&&e.reflectionType===`post`),E=Oy(t),D=jy(i,t);if(E.length&&(m.dataset.declaredArtifacts=JSON.stringify(E)),Yy(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=`
1775
1775
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
1776
1776
  <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
1777
1777
  <polyline points="14 2 14 8 20 8"/>
@@ -1834,11 +1834,11 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
1834
1834
  <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
1835
1835
  <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"/>
1836
1836
  </svg>
1837
- </button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),s.querySelectorAll(`.subtask-progress`).forEach(e=>{IC(e)}),s.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),ow(N.activeSessionId)})}),s.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:N.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(),Ox(s,e,t)});let t=l.querySelector(`.quote-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),Ix(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 M(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-BPasibDS.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));n(s,t,r)}),r.querySelector(`.export-md-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToMarkdown:n}=await M(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-BPasibDS.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));n(s,t,r)}),r.querySelector(`.export-pdf-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToPdf:n}=await M(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-BPasibDS.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));n(s,t,r)}),r.querySelector(`.export-image-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToImage:n}=await M(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-BPasibDS.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,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?mc(t):a.error(`[SidePanel] not found prototypeId,entry keys:`,Object.keys(e),`observation:`,e.observation)})}let o=l.querySelector(`.bookmark-btn`);o&&(Lm(o,N.activeSessionId,s.dataset.messageId),o.addEventListener(`click`,async e=>{e.stopPropagation();let t=N.activeSessionId,n=s.dataset.messageId;if(o.classList.contains(`bookmarked`)){await Tm(t,n),Lm(o,t,n);let{refreshBookmarkPanel:e}=await M(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>km);return{refreshBookmarkPanel:e}},void 0);e()}else{await wm(t,n,s.dataset.textContent_||``,N.sessions.find(e=>e.id===t)?.title||``),Lm(o,t,n);let{refreshBookmarkPanel:e}=await M(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>km);return{refreshBookmarkPanel:e}},void 0);e()}}));let c=l.querySelector(`.delete-btn`);c&&c.addEventListener(`click`,e=>{e.stopPropagation(),cw(s)});let u=l.querySelector(`.fork-btn`);u&&u.addEventListener(`click`,async e=>{e.stopPropagation();let t=s.dataset.messageId;t&&await Vs(N.activeSessionId,t)});let d=l.querySelector(`.resume-task-btn`);d&&d.addEventListener(`click`,async e=>{if(e.stopPropagation(),d.disabled)return;let t=await zx({budgetEnded:JC(s)});t!==null&&(d.disabled=!0,d.style.opacity=`0.6`,d.style.cursor=`not-allowed`,Wx(N.activeSessionId,t).finally(()=>{d.disabled=!1,d.style.opacity=``,d.style.cursor=``}))}),rw(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=Lt(e?JSON.parse(e):[]);t&&Dt(t,f)}catch{}}))}let u=s.querySelector(`.message-toolbar`);if(u){let e=u.querySelector(`.edit-btn`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),dw(s)});let t=u.querySelector(`.copy-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),Dx(s,t)});let n=u.querySelector(`.delete-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),cw(s)})}s.querySelectorAll(`.user-message-image`).forEach(e=>{e.addEventListener(`click`,()=>{Sp(e.src,e)})}),i.appendChild(s),wE()}function aw(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`)}">
1837
+ </button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),s.querySelectorAll(`.subtask-progress`).forEach(e=>{IC(e)}),s.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),ow(N.activeSessionId)})}),s.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:N.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(),Ox(s,e,t)});let t=l.querySelector(`.quote-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),Ix(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 M(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-DeqIrNGG.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));n(s,t,r)}),r.querySelector(`.export-md-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToMarkdown:n}=await M(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-DeqIrNGG.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));n(s,t,r)}),r.querySelector(`.export-pdf-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToPdf:n}=await M(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-DeqIrNGG.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));n(s,t,r)}),r.querySelector(`.export-image-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToImage:n}=await M(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-DeqIrNGG.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,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?mc(t):a.error(`[SidePanel] not found prototypeId,entry keys:`,Object.keys(e),`observation:`,e.observation)})}let o=l.querySelector(`.bookmark-btn`);o&&(Lm(o,N.activeSessionId,s.dataset.messageId),o.addEventListener(`click`,async e=>{e.stopPropagation();let t=N.activeSessionId,n=s.dataset.messageId;if(o.classList.contains(`bookmarked`)){await Tm(t,n),Lm(o,t,n);let{refreshBookmarkPanel:e}=await M(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>km);return{refreshBookmarkPanel:e}},void 0);e()}else{await wm(t,n,s.dataset.textContent_||``,N.sessions.find(e=>e.id===t)?.title||``),Lm(o,t,n);let{refreshBookmarkPanel:e}=await M(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>km);return{refreshBookmarkPanel:e}},void 0);e()}}));let c=l.querySelector(`.delete-btn`);c&&c.addEventListener(`click`,e=>{e.stopPropagation(),cw(s)});let u=l.querySelector(`.fork-btn`);u&&u.addEventListener(`click`,async e=>{e.stopPropagation();let t=s.dataset.messageId;t&&await Vs(N.activeSessionId,t)});let d=l.querySelector(`.resume-task-btn`);d&&d.addEventListener(`click`,async e=>{if(e.stopPropagation(),d.disabled)return;let t=await zx({budgetEnded:JC(s)});t!==null&&(d.disabled=!0,d.style.opacity=`0.6`,d.style.cursor=`not-allowed`,Wx(N.activeSessionId,t).finally(()=>{d.disabled=!1,d.style.opacity=``,d.style.cursor=``}))}),rw(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=Lt(e?JSON.parse(e):[]);t&&Dt(t,f)}catch{}}))}let u=s.querySelector(`.message-toolbar`);if(u){let e=u.querySelector(`.edit-btn`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),dw(s)});let t=u.querySelector(`.copy-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),Dx(s,t)});let n=u.querySelector(`.delete-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),cw(s)})}s.querySelectorAll(`.user-message-image`).forEach(e=>{e.addEventListener(`click`,()=>{Sp(e.src,e)})}),i.appendChild(s),wE()}function aw(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`)}">
1838
1838
  <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
1839
1839
  <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"/>
1840
1840
  </svg>
1841
- </button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),e.querySelectorAll(`.thinking-process-header`).forEach(e=>{bS(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=>{IC(e)}),e.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),ow(N.activeSessionId)})}),e.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:N.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(),Ox(t,n,e)});let r=e.querySelector(`.quote-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),Ix(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 M(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-BPasibDS.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));r(t,n,a)}),a.querySelector(`.export-md-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToMarkdown:r}=await M(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-BPasibDS.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));r(t,n,a)}),a.querySelector(`.export-pdf-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToPdf:r}=await M(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-BPasibDS.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));r(t,n,a)}),a.querySelector(`.export-image-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToImage:r}=await M(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-BPasibDS.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,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&&mc(t)})}let s=e.querySelector(`.bookmark-btn`);s&&(Lm(s,N.activeSessionId,t.dataset.messageId),s.addEventListener(`click`,async e=>{e.stopPropagation();let n=N.activeSessionId,r=t.dataset.messageId;if(s.classList.contains(`bookmarked`)){await Tm(n,r),Lm(s,n,r);let{refreshBookmarkPanel:e}=await M(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>km);return{refreshBookmarkPanel:e}},void 0);e()}else{await wm(n,r,t.dataset.textContent_||``,N.sessions.find(e=>e.id===n)?.title||``),Lm(s,n,r);let{refreshBookmarkPanel:e}=await M(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>km);return{refreshBookmarkPanel:e}},void 0);e()}}));let c=e.querySelector(`.delete-btn`);c&&c.addEventListener(`click`,e=>{e.stopPropagation(),cw(t)});let l=e.querySelector(`.fork-btn`);l&&l.addEventListener(`click`,async e=>{e.stopPropagation();let n=t.dataset.messageId;n&&await Vs(N.activeSessionId,n)});let u=e.querySelector(`.resume-task-btn`);u&&u.addEventListener(`click`,async e=>{if(e.stopPropagation(),u.disabled)return;let n=await zx({budgetEnded:JC(t)});n!==null&&(u.disabled=!0,u.style.opacity=`0.6`,u.style.cursor=`not-allowed`,Wx(N.activeSessionId,n).finally(()=>{u.disabled=!1,u.style.opacity=``,u.style.cursor=``}))}),rw(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=Lt(e?JSON.parse(e):[]);n&&Dt(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(),dw(t)});let r=e.querySelector(`.copy-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),Dx(t,r)});let i=e.querySelector(`.delete-btn`);i&&i.addEventListener(`click`,e=>{e.stopPropagation(),cw(t)})}),e.querySelectorAll(`.user-message-image`).forEach(e=>{e.addEventListener(`click`,()=>{Sp(e.src,e)})}),e.querySelectorAll(`.mermaid-controls`).forEach(e=>e.remove()),an(),QC(),ew(),wE()}function ow(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=`
1841
+ </button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),e.querySelectorAll(`.thinking-process-header`).forEach(e=>{bS(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=>{IC(e)}),e.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),ow(N.activeSessionId)})}),e.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:N.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(),Ox(t,n,e)});let r=e.querySelector(`.quote-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),Ix(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 M(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-DeqIrNGG.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));r(t,n,a)}),a.querySelector(`.export-md-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToMarkdown:r}=await M(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-DeqIrNGG.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));r(t,n,a)}),a.querySelector(`.export-pdf-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToPdf:r}=await M(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-DeqIrNGG.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,0]));r(t,n,a)}),a.querySelector(`.export-image-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToImage:r}=await M(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-DeqIrNGG.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([10,11,1,12,2,3,4,13,14,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&&mc(t)})}let s=e.querySelector(`.bookmark-btn`);s&&(Lm(s,N.activeSessionId,t.dataset.messageId),s.addEventListener(`click`,async e=>{e.stopPropagation();let n=N.activeSessionId,r=t.dataset.messageId;if(s.classList.contains(`bookmarked`)){await Tm(n,r),Lm(s,n,r);let{refreshBookmarkPanel:e}=await M(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>km);return{refreshBookmarkPanel:e}},void 0);e()}else{await wm(n,r,t.dataset.textContent_||``,N.sessions.find(e=>e.id===n)?.title||``),Lm(s,n,r);let{refreshBookmarkPanel:e}=await M(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>km);return{refreshBookmarkPanel:e}},void 0);e()}}));let c=e.querySelector(`.delete-btn`);c&&c.addEventListener(`click`,e=>{e.stopPropagation(),cw(t)});let l=e.querySelector(`.fork-btn`);l&&l.addEventListener(`click`,async e=>{e.stopPropagation();let n=t.dataset.messageId;n&&await Vs(N.activeSessionId,n)});let u=e.querySelector(`.resume-task-btn`);u&&u.addEventListener(`click`,async e=>{if(e.stopPropagation(),u.disabled)return;let n=await zx({budgetEnded:JC(t)});n!==null&&(u.disabled=!0,u.style.opacity=`0.6`,u.style.cursor=`not-allowed`,Wx(N.activeSessionId,n).finally(()=>{u.disabled=!1,u.style.opacity=``,u.style.cursor=``}))}),rw(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=Lt(e?JSON.parse(e):[]);n&&Dt(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(),dw(t)});let r=e.querySelector(`.copy-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),Dx(t,r)});let i=e.querySelector(`.delete-btn`);i&&i.addEventListener(`click`,e=>{e.stopPropagation(),cw(t)})}),e.querySelectorAll(`.user-message-image`).forEach(e=>{e.addEventListener(`click`,()=>{Sp(e.src,e)})}),e.querySelectorAll(`.mermaid-controls`).forEach(e=>e.remove()),an(),QC(),ew(),wE()}function ow(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=`
1842
1842
  <div class="command-terminate-modal">
1843
1843
  <div class="command-terminate-header">
1844
1844
  <div class="command-terminate-icon">⏹</div>
@@ -2558,9 +2558,9 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
2558
2558
  <span class="input-add-panel-item-title">${e.icon} ${P(r(e.nameKey))}</span>
2559
2559
  <span class="input-add-panel-item-sub">${P(r(e.descKey))}</span>
2560
2560
  <kbd class="input-add-panel-item-kbd">${P(e.kbd)}</kbd>
2561
- </div>`;default:return``}}async function ZP(e,t){let n=e.ctrlKey||e.metaKey;switch(kP){case`prompts`:{let e=t.dataset.code;n?Cw(e,{skipTriggerStrip:!0}):ww(e),MP();break}case`skills`:Kw(t.dataset.skillName,AP,{clearTrigger:!1}),n&&MP();break;case`mcp`:aT(t.dataset.serverId,t.dataset.serverName,AP,{clearTrigger:!1}),n&&MP();break;case`pages`:{let e=AP.find(e=>String(e.id)===t.dataset.tabId);if(e){Vb(e);let t=document.getElementById(`userInput`);t&&t.focus(),Vt()}MP();break}case`knowledge`:Tb({id:t.dataset.kbId,name:t.dataset.kbName,enabled:t.dataset.kbDisabled!==`1`},{clearTrigger:!1}),n&&MP();break;case`agents`:await Sb(t.dataset.agentId,{clearTrigger:!1}),MP();break;case`proxies`:await Pb(t.dataset.proxyId,{clearTrigger:!1}),MP();break;case`workspace`:{let e=AP.find(e=>e.fullPath===t.dataset.path);if(e){let t=document.getElementById(`userInput`);t&&t.focus(),await ty([e]),Vt()}MP();break}case`screenshot`:MP(),await(t.dataset.shotAction===`region`?Wm:Um)();break;default:break}}var QP=0,$P=200,eF=150,tF={promptTriggerBtn:`prompts`,addMenuSkillBtn:`skills`,addMenuMcpBtn:`mcp`,addMenuPageBtn:`pages`,addMenuKnowledgeBtn:`knowledge`,addMenuAgentBtn:`agents`,addMenuProxyBtn:`proxies`,addMenuWorkspaceBtn:`workspace`,screenshotBtn:`screenshot`};async function nF(){let e=[{id:`addMenuSkillBtn`,available:()=>Bw()},{id:`addMenuMcpBtn`,available:()=>tT()},{id:`addMenuKnowledgeBtn`,available:async()=>(await Mb()).ok},{id:`addMenuProxyBtn`,available:async()=>(await $y()).length>0},{id:`addMenuWorkspaceBtn`,available:async()=>!!await bn()}],t=++QP;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===QP&&(r.style.display=i?``:`none`)}))}function rF(){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=VP()?HP():null;t.querySelectorAll(`.input-add-item`).forEach(t=>{t.classList.toggle(`panel-active`,!!e&&tF[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?(GP(),s(),nF()):(i&&=(clearTimeout(i),null),a&&=(clearTimeout(a),null),GP(),s())},u=()=>t.style.display!==`none`;zP({onRequestClose:()=>l(!1)}),e.addEventListener(`click`,e=>{e.stopPropagation();let t=!u();t&&(_w(),rb(),_P()),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,!UP()&&(GP(),s())},eF)};r&&r.addEventListener(`mouseover`,e=>{if(!u())return;let t=e.target.closest(`.input-add-item`),n=t?tF[t.id]:null;if(!n){d();return}a&&=(clearTimeout(a),null),!(VP()&&HP()===n)&&(i&&clearTimeout(i),i=setTimeout(async()=>{i=null;let e=WP(n);c(t);try{await e}catch{}c(t),s()},$P))}),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`,()=>{VP()&&c()}),[{id:`promptTriggerBtn`,open:()=>gw(``,`prompts`)},{id:`addMenuSkillBtn`,open:()=>gw(``,`skills`)},{id:`addMenuMcpBtn`,open:()=>gw(``,`mcp`)},{id:`addMenuPageBtn`,open:()=>tb(``,`pages`)},{id:`addMenuKnowledgeBtn`,open:()=>tb(``,`knowledge`)},{id:`addMenuAgentBtn`,open:()=>tb(``,`agents`)},{id:`addMenuProxyBtn`,open:()=>tb(``,`proxies`)},{id:`addMenuWorkspaceBtn`,open:()=>gP(``)}].forEach(({id:e,open:t})=>{let n=document.getElementById(e);n&&n.addEventListener(`click`,async e=>{e.stopPropagation(),n.blur(),_w(),rb(),_P();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 iF({key:e,value:t=``,caret:n,history:r=[],index:i=-1}={}){if(e!==`ArrowUp`&&e!==`ArrowDown`||!Array.isArray(r)||r.length===0)return{handled:!1};let a=String(t??``),o=Number.isInteger(n)&&n>=0?n:a.length,s=Number.isInteger(i)&&i>=0;if(e===`ArrowUp`){let e=a.lastIndexOf(`
2561
+ </div>`;default:return``}}async function ZP(e,t){let n=e.ctrlKey||e.metaKey;switch(kP){case`prompts`:{let e=t.dataset.code;n?Cw(e,{skipTriggerStrip:!0}):ww(e),MP();break}case`skills`:Kw(t.dataset.skillName,AP,{clearTrigger:!1}),n&&MP();break;case`mcp`:aT(t.dataset.serverId,t.dataset.serverName,AP,{clearTrigger:!1}),n&&MP();break;case`pages`:{let e=AP.find(e=>String(e.id)===t.dataset.tabId);if(e){Vb(e);let t=document.getElementById(`userInput`);t&&t.focus(),Vt()}MP();break}case`knowledge`:Tb({id:t.dataset.kbId,name:t.dataset.kbName,enabled:t.dataset.kbDisabled!==`1`},{clearTrigger:!1}),n&&MP();break;case`agents`:await Sb(t.dataset.agentId,{clearTrigger:!1}),MP();break;case`proxies`:await Pb(t.dataset.proxyId,{clearTrigger:!1}),MP();break;case`workspace`:{let e=AP.find(e=>e.fullPath===t.dataset.path);if(e){let t=document.getElementById(`userInput`);t&&t.focus(),await ty([e]),Vt()}MP();break}case`screenshot`:MP(),await(t.dataset.shotAction===`region`?Wm:Um)();break;default:break}}var QP=0,$P=200,eF=150,tF={promptTriggerBtn:`prompts`,addMenuSkillBtn:`skills`,addMenuMcpBtn:`mcp`,addMenuPageBtn:`pages`,addMenuKnowledgeBtn:`knowledge`,addMenuAgentBtn:`agents`,addMenuProxyBtn:`proxies`,addMenuWorkspaceBtn:`workspace`,screenshotBtn:`screenshot`};async function nF(){let e=[{id:`addMenuSkillBtn`,available:()=>Bw()},{id:`addMenuMcpBtn`,available:()=>tT()},{id:`addMenuKnowledgeBtn`,available:async()=>(await Mb()).ok},{id:`addMenuProxyBtn`,available:async()=>(await $y()).length>0},{id:`addMenuWorkspaceBtn`,available:async()=>!!await bn()}],t=++QP;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===QP&&(r.style.display=i?``:`none`)}))}function rF(){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=VP()?HP():null;t.querySelectorAll(`.input-add-item`).forEach(t=>{t.classList.toggle(`panel-active`,!!e&&tF[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?(GP(),s(),nF()):(i&&=(clearTimeout(i),null),a&&=(clearTimeout(a),null),GP(),s())},u=()=>t.style.display!==`none`;zP({onRequestClose:()=>l(!1)}),e.addEventListener(`click`,e=>{e.stopPropagation();let t=!u();t&&(_w(),rb(),_P()),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,!UP()&&(GP(),s())},eF)};r&&r.addEventListener(`mouseover`,e=>{if(!u())return;let t=e.target.closest(`.input-add-item`),n=t?tF[t.id]:null;if(!n){d();return}a&&=(clearTimeout(a),null),!(VP()&&HP()===n)&&(i&&clearTimeout(i),i=setTimeout(async()=>{i=null;let e=WP(n);c(t);try{await e}catch{}c(t),s()},$P))}),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`,()=>{VP()&&c()}),[{id:`promptTriggerBtn`,open:()=>gw(``,`prompts`)},{id:`addMenuSkillBtn`,open:()=>gw(``,`skills`)},{id:`addMenuMcpBtn`,open:()=>gw(``,`mcp`)},{id:`addMenuPageBtn`,open:()=>tb(``,`pages`)},{id:`addMenuKnowledgeBtn`,open:()=>tb(``,`knowledge`)},{id:`addMenuAgentBtn`,open:()=>tb(``,`agents`)},{id:`addMenuProxyBtn`,open:()=>tb(``,`proxies`)},{id:`addMenuWorkspaceBtn`,open:()=>gP(``)}].forEach(({id:e,open:t})=>{let n=document.getElementById(e);n&&n.addEventListener(`click`,async e=>{e.stopPropagation(),n.blur(),_w(),rb(),_P();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()}var iF=`usageTipsEnabled`,aF=8e3;n(`zh`,{usageTips:{dismiss:`不再显示`,dismissedHint:`已关闭使用技巧提示。想重新看到:设置 → 基础 → 打开「使用技巧提示」`}}),n(`en`,{usageTips:{dismiss:`Don't show again`,dismissedHint:`Tips hidden. To bring them back: Settings → Basic → enable "Usage tips".`}});var oF=[{id:`slash`,scene:`plugin`,zh:`输入「/」唤起快捷提示,用方向键选择提示词、技能或 MCP,回车直接套用。`,en:`Type "/" to open quick prompts, pick a prompt, skill, or MCP with arrow keys and press Enter.`},{id:`at-page`,scene:`plugin`,zh:`输入「@」可引用当前网页,让 AI 直接基于页面内容回答。`,en:`Type "@" to reference the current page so the AI answers from that content.`},{id:`at-agent`,scene:`plugin`,zh:`「@助手」可以切换不同角色,为不同任务准备不同的身份、提示词与工具。`,en:`"@Assistant" switches roles, giving each task its own persona, prompt, and tool set.`},{id:`history`,scene:`plugin`,zh:`在输入框按「↑ / ↓」翻看历史输入,按 Esc 一键清空当前内容。`,en:`Press ↑ / ↓ in the input box to browse input history, and Esc to clear the current content.`},{id:`goal`,scene:`plugin`,zh:`把目标写成「帮我完成…」,目标模式会自动拆解步骤并持续推进直到达成。`,en:`Write the goal as "Help me finish…" and Goal mode will break it into steps and keep pushing until done.`},{id:`queue`,scene:`plugin`,zh:`任务执行中仍可继续输入,消息会进入队列,不会打断当前任务。`,en:`You can keep typing while a task runs; new messages queue up without interrupting the current task.`},{id:`queue-carry`,scene:`plugin`,zh:`排队时点消息旁的「⚡」,可把队首消息顺带进当前任务,减少来回切换。`,en:`Click "⚡" beside a queued message to fold it into the running task and avoid context switching.`},{id:`prompt-clarify`,scene:`plugin`,zh:`提问时补上背景、目标与限制条件,比只给一句话得到的结果稳定得多。`,en:`Include background, goal, and constraints in your request; results are far more reliable than one-liners.`},{id:`prompt-plan`,scene:`plugin`,zh:`复杂任务先让 AI 列计划:「先给方案,我确认后再动手」,能少走很多弯路。`,en:`For complex work, ask for a plan first: "Propose a plan, then act after I confirm."`},{id:`prompt-split`,scene:`plugin`,zh:`一次只让 AI 做一件事,把大任务拆成小步,成功率更高也更好检查。`,en:`Give the AI one job at a time; splitting big tasks into steps improves success and reviewability.`},{id:`selection`,scene:`plugin`,zh:`在网页上划词后点浮动按钮,可以针对选中的内容单独提问。`,en:`Select text on a page and click the floating button to ask about just that selection.`},{id:`voice`,scene:`plugin`,zh:`点麦克风用语音输入,说完自动转成文字,长问题不必手打。`,en:`Use the mic for voice input: speech is transcribed automatically, so long questions need no typing.`},{id:`image`,scene:`plugin`,zh:`图片可以直接粘贴或拖进输入框,AI 会看图后再回答。`,en:`Paste or drag images into the input box; the AI will look at them before answering.`},{id:`file`,scene:`plugin`,zh:`支持上传 PDF、Word、Excel 等文件,AI 会先提取内容再作答。`,en:`Upload PDF, Word, or Excel files; the AI extracts their content first, then answers.`},{id:`knowledge`,scene:`plugin`,zh:`用「@知识库」引用私有资料,回答会更贴合你的业务与术语。`,en:`Reference private material with "@Knowledge base" to make answers fit your business and terminology.`},{id:`compaction`,scene:`plugin`,zh:`长对话可在基础配置开启自动压缩,上下文接近上限时自动摘要,省 token。`,en:`Enable auto-compaction in Basic settings: near the context limit, long chats are summarized to save tokens.`},{id:`session`,scene:`plugin`,zh:`重要对话可收藏、搜索和导出;也可直接说「搜一下我们以前聊过的 xxx」。`,en:`Bookmark, search, and export important chats; you can also say "Search our past chats for xxx".`},{id:`schedule`,scene:`plugin`,zh:`定时任务可以让 AI 在指定时间自动执行,适合日报、巡检这类重复工作。`,en:`Scheduled tasks let the AI run at set times — handy for daily reports and routine checks.`},{id:`memory`,scene:`plugin`,zh:`说「帮我记一下…」即存入记忆,需要时问「你还记得…吗」,跨会话都有效。`,en:`Say "Remember this…" to save it; ask "Do you remember…?" later — memory persists across sessions.`},{id:`custom-prompt`,scene:`plugin`,zh:`把常用指令存成自定义提示词,下次用「/」一键调用。`,en:`Save frequent instructions as custom prompts and recall them with "/" next time.`},{id:`kb-ingest`,scene:`plugin`,zh:`说「把这份资料存到知识库」,AI 会自动切分并入库,之后可直接检索。`,en:`Say "Save this into the knowledge base" and the AI chunks and ingests it for later retrieval.`},{id:`clipboard`,scene:`plugin`,zh:`说「把结果复制到剪贴板」,AI 会直接写入,省去手动选中复制。`,en:`Say "Copy the result to my clipboard" and the AI writes it for you.`},{id:`page-highlight`,scene:`plugin`,zh:`说「在页面上高亮 xxx」,AI 会把关键内容标出来,方便讲解或核对。`,en:`Say "Highlight xxx on the page" to mark key content for explanation or review.`},{id:`capture`,scene:`plugin`,zh:`说「截图并分析这个页面」,AI 会截图后交给视觉模型解读图表或界面。`,en:`Say "Screenshot and analyze this page" to have the vision model read charts or UI.`},{id:`preview-ui`,scene:`plugin`,zh:`说「做个界面原型给我看看」,AI 会在侧边栏直接渲染可预览的 HTML。`,en:`Say "Show me a UI prototype" and the AI renders previewable HTML in the side panel.`},{id:`form-fill`,scene:`plugin`,zh:`说「帮我填一下这个表单」,AI 能一次批量填入多个字段。`,en:`Say "Fill out this form" and the AI can fill multiple fields in one go.`},{id:`browser-act`,scene:`plugin`,zh:`说「打开这个链接并帮我点…」,AI 能自动开标签页、点击、输入和翻页。`,en:`Say "Open this link and click …" and the AI can open tabs, click, type, and scroll.`},{id:`clarify`,scene:`plugin`,zh:`加上「拿不准就先问我」,AI 会先给出选项确认,避免理解跑偏。`,en:`Add "Ask me first if unsure" and the AI confirms with options before proceeding.`},{id:`dispatch`,scene:`plugin`,zh:`说「这几件事并行处理」,AI 会拆给子代理并发执行,大任务更快。`,en:`Say "Handle these in parallel" and the AI dispatches sub-agents concurrently.`},{id:`qrcode`,scene:`plugin`,zh:`说「把这个链接生成二维码」,AI 会自动生成并展示出来。`,en:`Say "Turn this link into a QR code" and the AI generates and shows it.`},{id:`notify`,scene:`plugin`,zh:`说「做完后提醒我」,AI 会用桌面通知告知结果,不必一直盯着。`,en:`Say "Notify me when done" and the AI sends a desktop notification.`},{id:`fetch`,scene:`plugin`,zh:`说「帮我抓取这个接口的数据」,AI 可发起 HTTP 请求并整理返回结果。`,en:`Say "Fetch the data from this API" and the AI can send an HTTP request and organize the result.`},{id:`agent-hint`,scene:`plugin`,zh:`连接代理端后,可解锁本机文件读写、命令执行等能力(设置 → 代理页配对)。`,en:`Connecting the agent unlocks local file access and command execution (Settings → Agent to pair).`},{id:`agent-file`,scene:`agent`,zh:`已连接代理端:AI 可以读写你电脑上的文件,直接说「帮我改这个文件」即可。`,en:`Agent connected: the AI can read and write files on your computer — just say "update this file".`},{id:`agent-exec`,scene:`agent`,zh:`已连接代理端:AI 可以执行本机命令、运行脚本,适合构建、测试与批处理。`,en:`Agent connected: the AI can run local commands and scripts for builds, tests, and batch jobs.`},{id:`agent-search`,scene:`agent`,zh:`让 AI「在项目里搜索 xxx」,它会用本机搜索定位代码,比网页检索更准。`,en:`Ask the AI to "search the project for xxx"; local search finds code more accurately than the web.`},{id:`agent-workdir`,scene:`agent`,zh:`在工作目录面板切换目录,AI 的文件操作都会被限制在这个范围内。`,en:`Switch directories in the workspace panel; the AI confinement keeps file operations inside that scope.`},{id:`agent-confirm`,scene:`agent`,zh:`敏感操作会先弹确认,可在基础配置里调整确认策略,兼顾安全与效率。`,en:`Sensitive actions ask for confirmation first; adjust the policy in Basic settings to balance safety and speed.`},{id:`agent-log`,scene:`agent`,zh:`命令执行日志可在日志面板查看;也可说「调出执行日志复盘」,让 AI 提取成功路径与失败教训。`,en:`Review commands in the log panel, or say "Review the execution log" to extract successful paths and lessons.`},{id:`agent-stream`,scene:`agent`,zh:`长命令支持流式输出,执行过程实时可见,不用盯着空白等待。`,en:`Long commands stream their output, so progress is visible in real time instead of a blank wait.`},{id:`agent-multi`,scene:`agent`,zh:`配对了多台电脑时,用「@代理」指定目标,也可以说「切换到另一台电脑的代理」。`,en:`With multiple computers, use "@Agent" to pick one, or just say "Switch to the agent on another computer".`},{id:`agent-offline`,scene:`agent`,zh:`代理端离线时,文件与命令类能力会自动隐藏,避免误发无法执行的任务。`,en:`When the agent is offline, file and command abilities are hidden so tasks are not sent in vain.`},{id:`agent-update`,scene:`agent`,zh:`代理端可在设置 → 代理页一键更新或重启,版本不一致时优先升级。`,en:`Update or restart the agent from Settings → Agent; upgrade first when versions differ.`},{id:`agent-skill`,scene:`agent`,zh:`说「跑一下这个工作流技能」,代理端会执行对应的 Skill。`,en:`Say "Run this workflow skill" and the agent executes the matching Skill.`},{id:`agent-skill-create`,scene:`agent`,zh:`说「把刚才的流程沉淀成技能」,AI 会写成 SKILL.md,下次一句话即可复用。`,en:`Say "Turn that process into a skill" and the AI writes a SKILL.md for one-line reuse next time.`},{id:`agent-trash`,scene:`agent`,zh:`说「从回收站恢复刚删的文件」,代理端可以直接恢复。`,en:`Say "Restore the file I just deleted" and the agent can recover it from its trash.`},{id:`agent-download`,scene:`agent`,zh:`说「把这个文件下载到浏览器」,代理端文件会直接下载到本机。`,en:`Say "Download this file to the browser" and the agent transfers it locally.`}],sF=null,cF=null,lF=null,uF=null,dF=null,fF=!1,pF=null,mF=!0;function hF(){return N.agentPlatform?.connected===!0}function gF(){let e=s();return oF.filter(e=>e.scene!==`agent`||hF()).map(t=>({id:t.id,text:e===`en`?t.en:t.zh}))}function _F(e){let t=e.findIndex(e=>e.id===pF);return t>=0?t:0}function vF(){if(!sF||!cF)return;let e=cF.scrollWidth>cF.clientWidth+1;sF.classList.toggle(`is-truncated`,e)}function yF(e,t){if(!cF||!e.length)return;let n=e[t%e.length];pF=n.id,cF.textContent=n.text,lF&&(lF.textContent=n.text),vF(),cF.classList.remove(`fade-in`),cF.offsetWidth,cF.classList.add(`fade-in`)}function bF(){if(!mF||!sF||sF.style.display===`none`)return;let e=gF();e.length&&yF(e,_F(e)+1)}function xF(){dF&&=(clearInterval(dF),null)}function SF(){xF(),!(!mF||fF)&&(dF=setInterval(bF,aF))}function CF(){if(!mF||!sF)return;let e=gF();if(!e.length){TF();return}e.some(e=>e.id===pF)?yF(e,_F(e)):(pF=null,yF(e,0))}function wF(){if(!sF)return;mF=!0,sF.style.display=``;let e=gF();if(!e.length){TF();return}yF(e,_F(e)),SF()}function TF(){sF&&(sF.style.display=`none`,xF())}function EF(){sF.addEventListener(`mouseenter`,()=>{fF=!0,xF()}),sF.addEventListener(`mouseleave`,()=>{fF=!1,SF()}),uF.addEventListener(`click`,e=>{e.stopPropagation(),DF(),L(r(`usageTips.dismissedHint`),`info`,5e3)}),chrome.storage.onChanged.addListener((e,t)=>{t!==`local`||!e[iF]||(e[iF].newValue===!1?(mF=!1,TF()):wF())}),document.addEventListener(`agent-connection-changed`,CF),c(CF),typeof ResizeObserver<`u`&&new ResizeObserver(vF).observe(sF)}function DF(){mF=!1,TF();try{chrome.storage.local.set({[iF]:!1})}catch{}}function OF(){if(sF=document.getElementById(`usageTipsBar`),cF=document.getElementById(`usageTipsText`),lF=document.getElementById(`usageTipsTooltip`),uF=document.getElementById(`usageTipsDismiss`),!(!sF||!cF||!lF||!uF)){EF();try{chrome.storage.local.get([iF],e=>{mF=e?.[iF]!==!1,mF?wF():TF()})}catch{wF()}}}function kF({key:e,value:t=``,caret:n,history:r=[],index:i=-1}={}){if(e!==`ArrowUp`&&e!==`ArrowDown`||!Array.isArray(r)||r.length===0)return{handled:!1};let a=String(t??``),o=Number.isInteger(n)&&n>=0?n:a.length,s=Number.isInteger(i)&&i>=0;if(e===`ArrowUp`){let e=a.lastIndexOf(`
2562
2562
  `,o-1)===-1;if(!s&&!e)return{handled:!1};let t=s?Math.min(i,r.length-1):r.length,n=Math.max(0,t-1);return{handled:!0,index:n,value:r[n]}}if(!s||a.indexOf(`
2563
- `,o)!==-1)return{handled:!1};let c=Math.min(i,r.length-1);if(c<r.length-1){let e=c+1;return{handled:!0,index:e,value:r[e]}}return{handled:!0,index:-1,value:``}}function aF(e,t){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>{clearTimeout(n),e(...r)},t)}}var oF=null,sF=null,cF=null,lF=null,uF=null,dF=null,fF=null,pF=null,mF=null,hF=null,gF=!1,_F=!1,vF=null,yF={[R.DISPATCHING]:`queue.statusDispatching`,[R.INJECTING]:`queue.statusInjecting`,[R.INJECTED]:`queue.statusInjected`,[R.DONE]:`queue.statusDone`,[R.FAILED]:`queue.statusFailed`};function bF(e){if(e.status===R.QUEUED)return e.interrupted?r(`queue.statusRecovered`):``;let t=yF[e.status];return t?r(t):``}function xF(){return N.activeSessionId}function SF(e){let t=e.attachmentSummary||e.contextSnapshot&&e.contextSnapshot.attachmentSummary||null,n=[];t&&(t.imageCount&&n.push(r(`queue.withImages`,{count:t.imageCount})),t.fileCount&&n.push(r(`queue.withFiles`,{count:t.fileCount})));let i=n.length?n.join(` · `):Yu(e.contextSnapshot)?r(`queue.withContext`):``;return i?`<span class="queue-chip-ctx" title="${P(t&&(t.fileNames||[]).length?t.fileNames.join(`、`):i)}">${P(i)}</span>`:``}function CF(e,t){let n=SF(e),i=e.status===R.DISPATCHING,a=bF(e),o=(a?`<span class="queue-chip-status${i?` running`:``}${e.interrupted?` warning`:``}"${i?` title="${P(r(`queue.statusRunningHint`))}"`:``}>${P(a)}</span>`:``)+n,s=N.isGenerating===!0;return`
2563
+ `,o)!==-1)return{handled:!1};let c=Math.min(i,r.length-1);if(c<r.length-1){let e=c+1;return{handled:!0,index:e,value:r[e]}}return{handled:!0,index:-1,value:``}}function AF(e,t){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>{clearTimeout(n),e(...r)},t)}}var jF=null,MF=null,NF=null,PF=null,FF=null,IF=null,LF=null,RF=null,zF=null,BF=null,VF=!1,HF=!1,UF=null,WF={[R.DISPATCHING]:`queue.statusDispatching`,[R.INJECTING]:`queue.statusInjecting`,[R.INJECTED]:`queue.statusInjected`,[R.DONE]:`queue.statusDone`,[R.FAILED]:`queue.statusFailed`};function GF(e){if(e.status===R.QUEUED)return e.interrupted?r(`queue.statusRecovered`):``;let t=WF[e.status];return t?r(t):``}function KF(){return N.activeSessionId}function qF(e){let t=e.attachmentSummary||e.contextSnapshot&&e.contextSnapshot.attachmentSummary||null,n=[];t&&(t.imageCount&&n.push(r(`queue.withImages`,{count:t.imageCount})),t.fileCount&&n.push(r(`queue.withFiles`,{count:t.fileCount})));let i=n.length?n.join(` · `):Yu(e.contextSnapshot)?r(`queue.withContext`):``;return i?`<span class="queue-chip-ctx" title="${P(t&&(t.fileNames||[]).length?t.fileNames.join(`、`):i)}">${P(i)}</span>`:``}function JF(e,t){let n=qF(e),i=e.status===R.DISPATCHING,a=GF(e),o=(a?`<span class="queue-chip-status${i?` running`:``}${e.interrupted?` warning`:``}"${i?` title="${P(r(`queue.statusRunningHint`))}"`:``}>${P(a)}</span>`:``)+n,s=N.isGenerating===!0;return`
2564
2564
  <div class="queue-chip" draggable="true" data-id="${P(e.id)}" data-status="${P(e.status)}">
2565
2565
  <span class="queue-chip-index">${t+1}</span>
2566
2566
  <div class="queue-chip-main">
@@ -2572,16 +2572,16 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
2572
2572
  <button class="queue-chip-btn" type="button" data-act="edit" title="${P(r(`queue.editBack`))}">✎</button>
2573
2573
  <button class="queue-chip-btn danger" type="button" data-act="remove" title="${P(r(`queue.delete`))}">✕</button>
2574
2574
  </div>
2575
- </div>`}function wF(e){return e.length?e.map(e=>`
2575
+ </div>`}function YF(e){return e.length?e.map(e=>`
2576
2576
  <div class="queue-recent-item" data-id="${P(e.id)}">
2577
- <span class="queue-recent-status">${P(bF(e))}</span>
2577
+ <span class="queue-recent-status">${P(GF(e))}</span>
2578
2578
  <span class="queue-recent-text" title="${P(e.text)}">${P(e.text)}</span>
2579
2579
  <button class="queue-chip-btn" type="button" data-act="requeue" title="${P(r(`queue.requeue`))}">↺</button>
2580
2580
  <button class="queue-chip-btn danger" type="button" data-act="forget" title="${P(r(`queue.forgetRecent`))}">✕</button>
2581
- </div>`).join(``):`<div class="queue-recent-empty">${P(r(`queue.recentEmpty`))}</div>`}function TF(e={}){if(!oF||vF)return;let t=xF();if(!t){oF.style.display=`none`;return}let n=zr(t),i=n.items,a=i.length>0,o=n.recent.filter(e=>e.status===R.FAILED).length,s=o>0;if(!a&&!s&&(!_F||n.recent.length===0)){oF.style.display=`none`;return}if(oF.style.display=``,oF.classList.toggle(`empty`,!a),oF.classList.toggle(`expanded`,gF&&a),oF.classList.toggle(`paused`,n.paused),cF&&(a?(cF.textContent=r(`queue.summary`,{count:i.length}),cF.classList.remove(`failed`),cF.removeAttribute(`title`)):s?(cF.textContent=r(`queue.summaryFailed`,{count:o}),cF.classList.add(`failed`),cF.title=r(`queue.summaryFailedHint`)):(cF.textContent=r(`queue.summaryEmpty`),cF.classList.remove(`failed`),cF.removeAttribute(`title`))),lF&&(lF.style.display=n.paused?``:`none`,lF.title=n.pausedReason===`user_stopped`?r(`queue.pausedByStop`):r(`queue.pausedHint`)),uF){let e=n.paused&&i.length>0;uF.style.display=e?``:`none`,uF.textContent=r(`queue.resumeQueue`)}if(dF){let e=N.isGenerating===!0&&a&&!n.paused;dF.style.display=e?``:`none`}fF&&(fF.classList.toggle(`active`,_F),fF.title=r(`queue.recentTitle`)),mF&&(mF.style.display=a?``:`none`,mF.setAttribute(`aria-expanded`,gF?`true`:`false`),mF.textContent=gF?`▲`:`▼`),sF&&(sF.style.display=gF&&a?``:`none`,sF.innerHTML=a?i.map((e,t)=>CF(e,t)).join(``):``),pF&&(pF.style.display=_F?``:`none`,pF.innerHTML=_F?wF(n.recent):``),e.flash&&(oF.classList.remove(`queue-flash`),oF.offsetWidth,oF.classList.add(`queue-flash`))}async function EF(e,t={}){let n=xF();if(!n||!e)return!1;let i=Ur(n,e);if(!i)return!1;let a=document.getElementById(`userInput`);if(a&&a.value.trim()){let e=await ad({autoDrain:!1});if(!e.ok)return L(e.error===`queue_full`?r(`queue.queueFull`,{limit:e.limit}):r(`queue.enqueueFailed`),`warning`),!1}else if(Xu())return L(r(`queue.inputHasUnsavedContext`),`warning`,4e3),!1;let o=await rd(i);return a&&(a.value=i.text,a.style.height=`auto`,a.dispatchEvent(new Event(`input`)),a.focus()),await qr(n,e),await id(e),o.wantsAttachments?L(o.attachments?r(`queue.editBackWithAttachments`):r(`queue.attachmentsMissing`),o.attachments?`success`:`warning`,2500):t.viaShortcut&&L(r(`queue.editTailHint`),`info`,2e3),!0}function DF(){let e=xF();if(!e)return!1;let t=Hr(e);return t?(EF(t.id,{viaShortcut:!0}),!0):!1}async function OF(e,t){let n=xF();if(!(!n||!t)&&!(Lr(n).findIndex(e=>e.id===t)<0))switch(e){case`edit`:await EF(t);break;case`inject`:await Cd(t,n);break;case`remove`:await qr(n,t),await id(t),L(r(`queue.deleted`),`info`,1500);break;default:break}}async function kF(e){let t=xF();t&&await Jr(t,e)}async function AF(e,t){if(e.preventDefault(),!vF)return;let n=t?.dataset?.id;if(!n||n===vF)return;let r=xF();if(!r)return;let i=Lr(r).map(e=>e.id),a=i.indexOf(vF);if(a<0)return;i.splice(a,1);let o=t.getBoundingClientRect(),s=e.clientY-o.top>o.height/2,c=i.indexOf(n);c<0?c=i.length:s&&(c+=1),i.splice(c,0,vF),await kF(i)}function jF(){sF&&(sF.addEventListener(`dragstart`,e=>{let t=e.target.closest?.(`.queue-chip`);if(t){vF=t.dataset.id,t.classList.add(`dragging`);try{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,vF)}catch{}}}),sF.addEventListener(`dragend`,e=>{let t=e.target.closest?.(`.queue-chip`);t&&t.classList.remove(`dragging`),vF=null,sF.querySelectorAll(`.drag-over-top, .drag-over-bottom`).forEach(e=>{e.classList.remove(`drag-over-top`,`drag-over-bottom`)}),TF()}),sF.addEventListener(`dragover`,e=>{let t=e.target.closest?.(`.queue-chip`);if(!t||!vF||t.dataset.id===vF)return;e.preventDefault();let n=t.getBoundingClientRect(),r=e.clientY-n.top>n.height/2;t.classList.toggle(`drag-over-bottom`,r),t.classList.toggle(`drag-over-top`,!r)}),sF.addEventListener(`dragleave`,e=>{let t=e.target.closest?.(`.queue-chip`);t&&t.classList.remove(`drag-over-top`,`drag-over-bottom`)}),sF.addEventListener(`drop`,e=>{let t=e.target.closest?.(`.queue-chip`);AF(e,t)}))}function MF(){sF?.addEventListener(`click`,e=>{let t=e.target.closest?.(`.queue-chip-btn`);if(!t||t.disabled)return;let n=t.closest(`.queue-chip`);n&&OF(t.dataset.act,n.dataset.id)}),pF?.addEventListener(`click`,async e=>{let t=e.target.closest?.(`.queue-chip-btn`),n=t?.closest(`.queue-recent-item`),i=xF();if(!t||!n||!i)return;if(t.dataset.act===`forget`){await ei(i,n.dataset.id)&&L(r(`queue.forgotRecent`),`success`,1500);return}if(t.dataset.act!==`requeue`)return;let a=Rr(i).find(e=>e.id===n.dataset.id),o=!!(a&&a.attachmentSummary),s=await $r(i,n.dataset.id);if(!s.ok){L(s.error===`queue_full`?r(`queue.queueFull`,{limit:s.limit}):r(`queue.enqueueFailed`),`warning`);return}L(r(o?`queue.requeuedNoAttachments`:`queue.requeued`),o?`warning`:`success`,2500)}),mF?.addEventListener(`click`,()=>{gF=!gF,TF()}),hF?.addEventListener(`click`,e=>{e.target.closest?.(`button`)||Lr(xF()||``).length&&(gF=!gF,TF())}),fF?.addEventListener(`click`,()=>{_F=!_F,_F&&(gF=!0),TF()}),uF?.addEventListener(`click`,async()=>{await Bd(),L(r(`queue.resumed`),`success`,1500)}),dF?.addEventListener(`click`,()=>{document.dispatchEvent(new CustomEvent(`queue-stop-and-send`))}),jF(),Ir(()=>TF()),document.addEventListener(`queue-enqueued`,()=>{gF=!0,TF({flash:!0})}),document.addEventListener(`session-switched`,()=>{TF()}),document.addEventListener(`generation-ended`,()=>TF()),document.addEventListener(`generating-state-changed`,()=>TF())}async function NF(){await Pr(),TF()}async function PF(){if(await Pr(),oF=document.getElementById(`queueStrip`),!oF){a.warn(`[QueuePanel] #queueStrip not found, queue UI disabled`);return}sF=document.getElementById(`queueList`),cF=document.getElementById(`queueSummary`),lF=document.getElementById(`queuePausedTag`),uF=document.getElementById(`queueResumeBtn`),dF=document.getElementById(`queueStopSendBtn`),fF=document.getElementById(`queueRecentBtn`),pF=document.getElementById(`queueRecent`),mF=document.getElementById(`queueToggleBtn`),hF=oF.querySelector(`.queue-strip-head`),MF(),TF()}var FF=new Set,IF=new Set,LF=new Map,RF=30*1e3;function zF(e){let t=LF.get(e);return t?Date.now()-t<RF?!0:(LF.delete(e),!1):!1}async function BF(e){let t=me(e)||e;if(!t||FF.has(t)||IF.has(t)||zF(t))return null;IF.add(t);try{let e=await te();if(!e)return null;let n=null;try{let r=await be(`${e.url}/api/status/detail`,{headers:{Authorization:`Bearer ${e.token}`,"X-AIH-Session-Id":t}});if(!r.ok)return LF.set(t,Date.now()),null;n=await r.json()}catch(e){return a.debug(`[WorkdirReconcile] fetch detail failed:`,e?.message||e),LF.set(t,Date.now()),null}if(!n?.success||!n.sessionWorkdirSupported)return LF.set(t,Date.now()),null;let r=n.sessionWorkdir||null,i=n.defaultWorkdir||n.workdir||null;if(!r||r===i)return LF.set(t,Date.now()),null;let o=await fe(t);return o.scope===`session`?(LF.set(t,Date.now()),null):o.boundWorkdir?await ge(t)?(FF.add(t),a.debug(`[WorkdirReconcile] cleared stale agent binding:`,t,r),{cleaned:!0,workdir:r}):null:await Te(t,r,o.agentId||e.id||null)?(FF.add(t),a.debug(`[WorkdirReconcile] restored session workdir:`,t,r),{adopted:!0,workdir:r}):null}finally{IF.delete(t)}}n(`zh`,{sidePanel:{popupTitle:`浮层解答`,popupTooltip:`浮层解答(不进入对话)`,popupLoading:`思考中...`,popupCopy:`复制`,popupCopied:`已复制到剪贴板`,popupTransfer:`转入对话`,popupTransferred:`已转入对话`,popupRegenerate:`重新生成`,popupClose:`关闭`,popupLock:`锁定(不随点击外部关闭)`,popupUnlock:`解锁(可点击外部关闭)`,popupRequestFailed:`请求失败`,popupContextLabel:`上下文`,popupContextTruncated:`(已截断)`,popupSystemPrompt:`用户在阅读 AI 回答时选中了其中的片段,希望理解选中内容。请结合上下文,只针对选中片段回答,简洁清楚,不要展开与选中内容无关的长论述。`}}),n(`en`,{sidePanel:{popupTitle:`Popup Answer`,popupTooltip:`Answer in popup (not in conversation)`,popupLoading:`Thinking...`,popupCopy:`Copy`,popupCopied:`Copied to clipboard`,popupTransfer:`Move to chat`,popupTransferred:`Moved to chat`,popupRegenerate:`Regenerate`,popupClose:`Close`,popupLock:`Lock (keep open on outside click)`,popupUnlock:`Unlock (close on outside click)`,popupRequestFailed:`Request failed`,popupContextLabel:`Context`,popupContextTruncated:`(truncated)`,popupSystemPrompt:`The user selected a fragment while reading an AI answer and wants to understand it. Using the surrounding context, answer only about the selected fragment, concisely and clearly, without expanding into unrelated long discussion.`}});var VF=1500,$=null,HF=null,UF=``,WF=null,GF=``,KF=``,qF=!1,JF=!1,YF=!1;function XF(e){return(e||``).replace(/[ \t\f\v]+/g,` `).replace(/ *\n */g,`
2581
+ </div>`).join(``):`<div class="queue-recent-empty">${P(r(`queue.recentEmpty`))}</div>`}function XF(e={}){if(!jF||UF)return;let t=KF();if(!t){jF.style.display=`none`;return}let n=zr(t),i=n.items,a=i.length>0,o=n.recent.filter(e=>e.status===R.FAILED).length,s=o>0;if(!a&&!s&&(!HF||n.recent.length===0)){jF.style.display=`none`;return}if(jF.style.display=``,jF.classList.toggle(`empty`,!a),jF.classList.toggle(`expanded`,VF&&a),jF.classList.toggle(`paused`,n.paused),NF&&(a?(NF.textContent=r(`queue.summary`,{count:i.length}),NF.classList.remove(`failed`),NF.removeAttribute(`title`)):s?(NF.textContent=r(`queue.summaryFailed`,{count:o}),NF.classList.add(`failed`),NF.title=r(`queue.summaryFailedHint`)):(NF.textContent=r(`queue.summaryEmpty`),NF.classList.remove(`failed`),NF.removeAttribute(`title`))),PF&&(PF.style.display=n.paused?``:`none`,PF.title=n.pausedReason===`user_stopped`?r(`queue.pausedByStop`):r(`queue.pausedHint`)),FF){let e=n.paused&&i.length>0;FF.style.display=e?``:`none`,FF.textContent=r(`queue.resumeQueue`)}if(IF){let e=N.isGenerating===!0&&a&&!n.paused;IF.style.display=e?``:`none`}LF&&(LF.classList.toggle(`active`,HF),LF.title=r(`queue.recentTitle`)),zF&&(zF.style.display=a?``:`none`,zF.setAttribute(`aria-expanded`,VF?`true`:`false`),zF.textContent=VF?`▲`:`▼`),MF&&(MF.style.display=VF&&a?``:`none`,MF.innerHTML=a?i.map((e,t)=>JF(e,t)).join(``):``),RF&&(RF.style.display=HF?``:`none`,RF.innerHTML=HF?YF(n.recent):``),e.flash&&(jF.classList.remove(`queue-flash`),jF.offsetWidth,jF.classList.add(`queue-flash`))}async function ZF(e,t={}){let n=KF();if(!n||!e)return!1;let i=Ur(n,e);if(!i)return!1;let a=document.getElementById(`userInput`);if(a&&a.value.trim()){let e=await ad({autoDrain:!1});if(!e.ok)return L(e.error===`queue_full`?r(`queue.queueFull`,{limit:e.limit}):r(`queue.enqueueFailed`),`warning`),!1}else if(Xu())return L(r(`queue.inputHasUnsavedContext`),`warning`,4e3),!1;let o=await rd(i);return a&&(a.value=i.text,a.style.height=`auto`,a.dispatchEvent(new Event(`input`)),a.focus()),await qr(n,e),await id(e),o.wantsAttachments?L(o.attachments?r(`queue.editBackWithAttachments`):r(`queue.attachmentsMissing`),o.attachments?`success`:`warning`,2500):t.viaShortcut&&L(r(`queue.editTailHint`),`info`,2e3),!0}function QF(){let e=KF();if(!e)return!1;let t=Hr(e);return t?(ZF(t.id,{viaShortcut:!0}),!0):!1}async function $F(e,t){let n=KF();if(!(!n||!t)&&!(Lr(n).findIndex(e=>e.id===t)<0))switch(e){case`edit`:await ZF(t);break;case`inject`:await Cd(t,n);break;case`remove`:await qr(n,t),await id(t),L(r(`queue.deleted`),`info`,1500);break;default:break}}async function eI(e){let t=KF();t&&await Jr(t,e)}async function tI(e,t){if(e.preventDefault(),!UF)return;let n=t?.dataset?.id;if(!n||n===UF)return;let r=KF();if(!r)return;let i=Lr(r).map(e=>e.id),a=i.indexOf(UF);if(a<0)return;i.splice(a,1);let o=t.getBoundingClientRect(),s=e.clientY-o.top>o.height/2,c=i.indexOf(n);c<0?c=i.length:s&&(c+=1),i.splice(c,0,UF),await eI(i)}function nI(){MF&&(MF.addEventListener(`dragstart`,e=>{let t=e.target.closest?.(`.queue-chip`);if(t){UF=t.dataset.id,t.classList.add(`dragging`);try{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,UF)}catch{}}}),MF.addEventListener(`dragend`,e=>{let t=e.target.closest?.(`.queue-chip`);t&&t.classList.remove(`dragging`),UF=null,MF.querySelectorAll(`.drag-over-top, .drag-over-bottom`).forEach(e=>{e.classList.remove(`drag-over-top`,`drag-over-bottom`)}),XF()}),MF.addEventListener(`dragover`,e=>{let t=e.target.closest?.(`.queue-chip`);if(!t||!UF||t.dataset.id===UF)return;e.preventDefault();let n=t.getBoundingClientRect(),r=e.clientY-n.top>n.height/2;t.classList.toggle(`drag-over-bottom`,r),t.classList.toggle(`drag-over-top`,!r)}),MF.addEventListener(`dragleave`,e=>{let t=e.target.closest?.(`.queue-chip`);t&&t.classList.remove(`drag-over-top`,`drag-over-bottom`)}),MF.addEventListener(`drop`,e=>{let t=e.target.closest?.(`.queue-chip`);tI(e,t)}))}function rI(){MF?.addEventListener(`click`,e=>{let t=e.target.closest?.(`.queue-chip-btn`);if(!t||t.disabled)return;let n=t.closest(`.queue-chip`);n&&$F(t.dataset.act,n.dataset.id)}),RF?.addEventListener(`click`,async e=>{let t=e.target.closest?.(`.queue-chip-btn`),n=t?.closest(`.queue-recent-item`),i=KF();if(!t||!n||!i)return;if(t.dataset.act===`forget`){await ei(i,n.dataset.id)&&L(r(`queue.forgotRecent`),`success`,1500);return}if(t.dataset.act!==`requeue`)return;let a=Rr(i).find(e=>e.id===n.dataset.id),o=!!(a&&a.attachmentSummary),s=await $r(i,n.dataset.id);if(!s.ok){L(s.error===`queue_full`?r(`queue.queueFull`,{limit:s.limit}):r(`queue.enqueueFailed`),`warning`);return}L(r(o?`queue.requeuedNoAttachments`:`queue.requeued`),o?`warning`:`success`,2500)}),zF?.addEventListener(`click`,()=>{VF=!VF,XF()}),BF?.addEventListener(`click`,e=>{e.target.closest?.(`button`)||Lr(KF()||``).length&&(VF=!VF,XF())}),LF?.addEventListener(`click`,()=>{HF=!HF,HF&&(VF=!0),XF()}),FF?.addEventListener(`click`,async()=>{await Bd(),L(r(`queue.resumed`),`success`,1500)}),IF?.addEventListener(`click`,()=>{document.dispatchEvent(new CustomEvent(`queue-stop-and-send`))}),nI(),Ir(()=>XF()),document.addEventListener(`queue-enqueued`,()=>{VF=!0,XF({flash:!0})}),document.addEventListener(`session-switched`,()=>{XF()}),document.addEventListener(`generation-ended`,()=>XF()),document.addEventListener(`generating-state-changed`,()=>XF())}async function iI(){await Pr(),XF()}async function aI(){if(await Pr(),jF=document.getElementById(`queueStrip`),!jF){a.warn(`[QueuePanel] #queueStrip not found, queue UI disabled`);return}MF=document.getElementById(`queueList`),NF=document.getElementById(`queueSummary`),PF=document.getElementById(`queuePausedTag`),FF=document.getElementById(`queueResumeBtn`),IF=document.getElementById(`queueStopSendBtn`),LF=document.getElementById(`queueRecentBtn`),RF=document.getElementById(`queueRecent`),zF=document.getElementById(`queueToggleBtn`),BF=jF.querySelector(`.queue-strip-head`),rI(),XF()}var oI=new Set,sI=new Set,cI=new Map,lI=30*1e3;function uI(e){let t=cI.get(e);return t?Date.now()-t<lI?!0:(cI.delete(e),!1):!1}async function dI(e){let t=me(e)||e;if(!t||oI.has(t)||sI.has(t)||uI(t))return null;sI.add(t);try{let e=await te();if(!e)return null;let n=null;try{let r=await be(`${e.url}/api/status/detail`,{headers:{Authorization:`Bearer ${e.token}`,"X-AIH-Session-Id":t}});if(!r.ok)return cI.set(t,Date.now()),null;n=await r.json()}catch(e){return a.debug(`[WorkdirReconcile] fetch detail failed:`,e?.message||e),cI.set(t,Date.now()),null}if(!n?.success||!n.sessionWorkdirSupported)return cI.set(t,Date.now()),null;let r=n.sessionWorkdir||null,i=n.defaultWorkdir||n.workdir||null;if(!r||r===i)return cI.set(t,Date.now()),null;let o=await fe(t);return o.scope===`session`?(cI.set(t,Date.now()),null):o.boundWorkdir?await ge(t)?(oI.add(t),a.debug(`[WorkdirReconcile] cleared stale agent binding:`,t,r),{cleaned:!0,workdir:r}):null:await Te(t,r,o.agentId||e.id||null)?(oI.add(t),a.debug(`[WorkdirReconcile] restored session workdir:`,t,r),{adopted:!0,workdir:r}):null}finally{sI.delete(t)}}n(`zh`,{sidePanel:{popupTitle:`浮层解答`,popupTooltip:`浮层解答(不进入对话)`,popupLoading:`思考中...`,popupCopy:`复制`,popupCopied:`已复制到剪贴板`,popupTransfer:`转入对话`,popupTransferred:`已转入对话`,popupRegenerate:`重新生成`,popupClose:`关闭`,popupLock:`锁定(不随点击外部关闭)`,popupUnlock:`解锁(可点击外部关闭)`,popupRequestFailed:`请求失败`,popupContextLabel:`上下文`,popupContextTruncated:`(已截断)`,popupSystemPrompt:`用户在阅读 AI 回答时选中了其中的片段,希望理解选中内容。请结合上下文,只针对选中片段回答,简洁清楚,不要展开与选中内容无关的长论述。`}}),n(`en`,{sidePanel:{popupTitle:`Popup Answer`,popupTooltip:`Answer in popup (not in conversation)`,popupLoading:`Thinking...`,popupCopy:`Copy`,popupCopied:`Copied to clipboard`,popupTransfer:`Move to chat`,popupTransferred:`Moved to chat`,popupRegenerate:`Regenerate`,popupClose:`Close`,popupLock:`Lock (keep open on outside click)`,popupUnlock:`Unlock (close on outside click)`,popupRequestFailed:`Request failed`,popupContextLabel:`Context`,popupContextTruncated:`(truncated)`,popupSystemPrompt:`The user selected a fragment while reading an AI answer and wants to understand it. Using the surrounding context, answer only about the selected fragment, concisely and clearly, without expanding into unrelated long discussion.`}});var fI=1500,$=null,pI=null,mI=``,hI=null,gI=``,_I=``,vI=!1,yI=!1,bI=!1;function xI(e){return(e||``).replace(/[ \t\f\v]+/g,` `).replace(/ *\n */g,`
2582
2582
  `).replace(/\n{3,}/g,`
2583
2583
 
2584
- `).trim()}function ZF(e,t){if(!e)return{context:``,truncated:!1};let n=e.startContainer?.parentElement?.closest?.(`.message`);if(!n)return{context:``,truncated:!1};let r=XF(n.textContent);if(!r)return{context:``,truncated:!1};let i=f(r);if(i<=VF)return{context:r,truncated:!1};let a=r.indexOf(t),o=a>=0?a+t.length/2:r.length/2,s=Math.floor(r.length*VF/Math.max(i,1)),c=Math.max(0,Math.floor(o-s/2)),l=Math.min(r.length,c+s);if(a>=0){let e=a+t.length;a<c&&(c=Math.max(0,a-50)),e>l&&(l=Math.min(r.length,e+50))}let u=r.slice(c,l).trim();if(f(u)>VF){let e=VF/f(u);u=u.slice(0,Math.floor(u.length*e))}return{context:u,truncated:!0}}function QF(e,t,n,i){let a=r(`sidePanel.popupSystemPrompt`),o=``;return t&&(o+=`[${r(`sidePanel.popupContextLabel`)}${i?r(`sidePanel.popupContextTruncated`):``}]\n${t}\n\n`),o+=`[${r(`sidePanel.selectedContentLabel`)}]\n${e}\n\n`,o+=`[${r(`sidePanel.userQuestionLabel`)}]\n${n}`,[{role:`system`,content:a},{role:`user`,content:o}]}function $F(){return $&&document.body.contains($)?$:($=document.createElement(`div`),$.className=`selection-answer-popup`,$.id=`selectionAnswerPopup`,$.innerHTML=`
2584
+ `).trim()}function SI(e,t){if(!e)return{context:``,truncated:!1};let n=e.startContainer?.parentElement?.closest?.(`.message`);if(!n)return{context:``,truncated:!1};let r=xI(n.textContent);if(!r)return{context:``,truncated:!1};let i=f(r);if(i<=fI)return{context:r,truncated:!1};let a=r.indexOf(t),o=a>=0?a+t.length/2:r.length/2,s=Math.floor(r.length*fI/Math.max(i,1)),c=Math.max(0,Math.floor(o-s/2)),l=Math.min(r.length,c+s);if(a>=0){let e=a+t.length;a<c&&(c=Math.max(0,a-50)),e>l&&(l=Math.min(r.length,e+50))}let u=r.slice(c,l).trim();if(f(u)>fI){let e=fI/f(u);u=u.slice(0,Math.floor(u.length*e))}return{context:u,truncated:!0}}function CI(e,t,n,i){let a=r(`sidePanel.popupSystemPrompt`),o=``;return t&&(o+=`[${r(`sidePanel.popupContextLabel`)}${i?r(`sidePanel.popupContextTruncated`):``}]\n${t}\n\n`),o+=`[${r(`sidePanel.selectedContentLabel`)}]\n${e}\n\n`,o+=`[${r(`sidePanel.userQuestionLabel`)}]\n${n}`,[{role:`system`,content:a},{role:`user`,content:o}]}function wI(){return $&&document.body.contains($)?$:($=document.createElement(`div`),$.className=`selection-answer-popup`,$.id=`selectionAnswerPopup`,$.innerHTML=`
2585
2585
  <div class="sap-header">
2586
2586
  <span class="sap-title"></span>
2587
2587
  <div class="sap-header-actions">
@@ -2595,7 +2595,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
2595
2595
  <button class="sap-btn sap-transfer"></button>
2596
2596
  <button class="sap-btn sap-regen"></button>
2597
2597
  </div>
2598
- `,document.body.appendChild($),$.querySelector(`.sap-close`).addEventListener(`click`,cI),$.querySelector(`.sap-lock`).addEventListener(`click`,nI),$.querySelector(`.sap-copy`).addEventListener(`click`,fI),$.querySelector(`.sap-transfer`).addEventListener(`click`,pI),$.querySelector(`.sap-regen`).addEventListener(`click`,()=>{WF&&GF&&hI()}),dI($.querySelector(`.sap-header`)),$)}function eI(){if(!$)return;$.querySelector(`.sap-close`).title=r(`sidePanel.popupClose`);let e=$.querySelector(`.sap-copy`);e.textContent=r(`sidePanel.popupCopy`),e.title=r(`sidePanel.popupCopy`);let t=$.querySelector(`.sap-transfer`);t.textContent=r(`sidePanel.popupTransfer`),t.title=r(`sidePanel.popupTransfer`);let n=$.querySelector(`.sap-regen`);n.textContent=r(`sidePanel.popupRegenerate`),n.title=r(`sidePanel.popupRegenerate`),tI()}function tI(){if(!$)return;let e=$.querySelector(`.sap-lock`);e&&(e.classList.toggle(`locked`,YF),e.title=r(YF?`sidePanel.popupUnlock`:`sidePanel.popupLock`),e.innerHTML=YF?`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>`:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 9.9-1"/></svg>`)}function nI(){YF=!YF,tI()}function rI(e,t){let n=$F(),r=window.innerWidth,i=window.innerHeight,a=t+12,o=e-320/2;o<8&&(o=8),o+320>r-8&&(o=r-320-8),a+280>i-8&&(a=t-280-12),a<8&&(a=8),n.style.position=`fixed`,n.style.top=a+`px`,n.style.left=o+`px`}function iI(e){let t=$F();eI(),t.querySelector(`.sap-title`).textContent=e||r(`sidePanel.popupTitle`),t.querySelector(`.sap-body`).innerHTML=`<div class="sap-loading">${P(r(`sidePanel.popupLoading`))}</div>`,t.classList.add(`show`),$.style.display=`block`}function aI(){return!!$&&$.classList.contains(`show`)}function oI(e,t=!0){let n=$?.querySelector(`.sap-body`);n&&(n.innerHTML=`<div class="sap-content markdown-body">${e}</div>`,t&&(n.scrollTop=n.scrollHeight))}function sI(e){let t=$?.querySelector(`.sap-body`);t&&(t.innerHTML=`<div class="sap-error">${P(e)}</div>`)}function cI(){JF&&HF&&chrome.runtime.sendMessage({type:`CANCEL_REACT`,sessionId:HF}).catch(()=>{}),$&&($.classList.remove(`show`),$.style.display=`none`),HF=null,UF=``,JF=!1,YF=!1}function lI(e){if(!aI()||YF||$.contains(e.target))return;let t=document.getElementById(`selectionFloatingMenu`);t&&t.contains(e.target)||cI()}function uI(e){e.key===`Escape`&&(!aI()||YF||cI())}function dI(e){let t=!1,n,r,i,a;e.addEventListener(`mousedown`,e=>{if(e.target.closest(`.sap-close, .sap-lock`))return;t=!0,n=e.clientX,r=e.clientY;let o=$.getBoundingClientRect();i=o.top,a=o.left,e.preventDefault()}),document.addEventListener(`mousemove`,e=>{if(!t)return;let o=e.clientX-n,s=e.clientY-r;$.style.position=`fixed`,$.style.top=i+s+`px`,$.style.left=a+o+`px`}),document.addEventListener(`mouseup`,()=>{t=!1})}function fI(){UF&&navigator.clipboard.writeText(UF).then(()=>{L(r(`sidePanel.popupCopied`))}).catch(()=>{let e=document.createElement(`textarea`);e.value=UF,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),L(r(`sidePanel.popupCopied`))})}function pI(){if(!UF||!WF)return;let e=UF,t=WF.content,n=`${KF?`[${r(`sidePanel.popupContextLabel`)}]\n${KF}\n\n`:``}[${r(`sidePanel.selectedContentLabel`)}]\n${GF}\n\n[${r(`sidePanel.userQuestionLabel`)}]\n${WF.content}`;M(async()=>{let{addMessage:e}=await Promise.resolve().then(()=>oC);return{addMessage:e}},void 0).then(({addMessage:i})=>{i(`user`,t,!0,[],null,!1,n),N.messageHistory.push({role:`user`,content:n,timestamp:new Date().toISOString()}),i(`assistant`,e,!0),N.messageHistory.push({role:`assistant`,content:e}),M(async()=>{let{saveCurrentSession:e}=await Promise.resolve().then(()=>Ci);return{saveCurrentSession:e}},void 0).then(({saveCurrentSession:e})=>{e()}),Promise.all([M(()=>Promise.resolve().then(()=>oS),void 0),new Promise(e=>requestAnimationFrame(e))]).then(([{autoScrollToBottom:e}])=>{e(document.getElementById(`chatContainer`),{force:!0,smooth:!0}),L(r(`sidePanel.popupTransferred`))})}),cI()}function mI(e,t,n){let{context:r,truncated:i}=ZF(n,t);WF=e,GF=t,KF=r,qF=i,hI()}function hI(){UF=``,JF=!0,iI(WF?.content);let e=QF(GF,KF,WF.content,qF);HF=`popup_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,chrome.runtime.sendMessage({type:`SIDEPANEL_POPUP_ASK`,sessionId:HF,messages:e}).catch(e=>{a.error(`[SelectionPopup] sendMessage failed:`,e),sI(r(`sidePanel.popupRequestFailed`)),JF=!1})}var gI=!1;function _I(){gI||(gI=!0,chrome.runtime.onMessage.addListener(e=>{if(!(!e||!e.type)&&e.type.startsWith(`SIDEPANEL_POPUP_`)&&e.sessionId===HF){if(e.type===`SIDEPANEL_POPUP_STREAM_CHUNK`)e.delta&&(UF+=e.delta,oI(qt(UF)));else if(e.type===`SIDEPANEL_POPUP_STREAM_DONE`)JF=!1,e.finalContent&&(UF=e.finalContent),oI(qt(UF));else if(e.type===`SIDEPANEL_POPUP_STREAM_ERROR`){if(!JF)return;JF=!1,sI(e.error||r(`sidePanel.popupRequestFailed`))}}}))}function vI(){_I(),document.addEventListener(`mousedown`,lI),document.addEventListener(`keydown`,uI)}function yI(e,t,n,r,i){!t||!e||(_I(),rI(n,r),YF=!1,mI(e,t,i||N.currentSelectionRange))}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 bI(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 ze(),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([qe(t),Ae()]);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=`
2598
+ `,document.body.appendChild($),$.querySelector(`.sap-close`).addEventListener(`click`,NI),$.querySelector(`.sap-lock`).addEventListener(`click`,DI),$.querySelector(`.sap-copy`).addEventListener(`click`,LI),$.querySelector(`.sap-transfer`).addEventListener(`click`,RI),$.querySelector(`.sap-regen`).addEventListener(`click`,()=>{hI&&gI&&BI()}),II($.querySelector(`.sap-header`)),$)}function TI(){if(!$)return;$.querySelector(`.sap-close`).title=r(`sidePanel.popupClose`);let e=$.querySelector(`.sap-copy`);e.textContent=r(`sidePanel.popupCopy`),e.title=r(`sidePanel.popupCopy`);let t=$.querySelector(`.sap-transfer`);t.textContent=r(`sidePanel.popupTransfer`),t.title=r(`sidePanel.popupTransfer`);let n=$.querySelector(`.sap-regen`);n.textContent=r(`sidePanel.popupRegenerate`),n.title=r(`sidePanel.popupRegenerate`),EI()}function EI(){if(!$)return;let e=$.querySelector(`.sap-lock`);e&&(e.classList.toggle(`locked`,bI),e.title=r(bI?`sidePanel.popupUnlock`:`sidePanel.popupLock`),e.innerHTML=bI?`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>`:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 9.9-1"/></svg>`)}function DI(){bI=!bI,EI()}function OI(e,t){let n=wI(),r=window.innerWidth,i=window.innerHeight,a=t+12,o=e-320/2;o<8&&(o=8),o+320>r-8&&(o=r-320-8),a+280>i-8&&(a=t-280-12),a<8&&(a=8),n.style.position=`fixed`,n.style.top=a+`px`,n.style.left=o+`px`}function kI(e){let t=wI();TI(),t.querySelector(`.sap-title`).textContent=e||r(`sidePanel.popupTitle`),t.querySelector(`.sap-body`).innerHTML=`<div class="sap-loading">${P(r(`sidePanel.popupLoading`))}</div>`,t.classList.add(`show`),$.style.display=`block`}function AI(){return!!$&&$.classList.contains(`show`)}function jI(e,t=!0){let n=$?.querySelector(`.sap-body`);n&&(n.innerHTML=`<div class="sap-content markdown-body">${e}</div>`,t&&(n.scrollTop=n.scrollHeight))}function MI(e){let t=$?.querySelector(`.sap-body`);t&&(t.innerHTML=`<div class="sap-error">${P(e)}</div>`)}function NI(){yI&&pI&&chrome.runtime.sendMessage({type:`CANCEL_REACT`,sessionId:pI}).catch(()=>{}),$&&($.classList.remove(`show`),$.style.display=`none`),pI=null,mI=``,yI=!1,bI=!1}function PI(e){if(!AI()||bI||$.contains(e.target))return;let t=document.getElementById(`selectionFloatingMenu`);t&&t.contains(e.target)||NI()}function FI(e){e.key===`Escape`&&(!AI()||bI||NI())}function II(e){let t=!1,n,r,i,a;e.addEventListener(`mousedown`,e=>{if(e.target.closest(`.sap-close, .sap-lock`))return;t=!0,n=e.clientX,r=e.clientY;let o=$.getBoundingClientRect();i=o.top,a=o.left,e.preventDefault()}),document.addEventListener(`mousemove`,e=>{if(!t)return;let o=e.clientX-n,s=e.clientY-r;$.style.position=`fixed`,$.style.top=i+s+`px`,$.style.left=a+o+`px`}),document.addEventListener(`mouseup`,()=>{t=!1})}function LI(){mI&&navigator.clipboard.writeText(mI).then(()=>{L(r(`sidePanel.popupCopied`))}).catch(()=>{let e=document.createElement(`textarea`);e.value=mI,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),L(r(`sidePanel.popupCopied`))})}function RI(){if(!mI||!hI)return;let e=mI,t=hI.content,n=`${_I?`[${r(`sidePanel.popupContextLabel`)}]\n${_I}\n\n`:``}[${r(`sidePanel.selectedContentLabel`)}]\n${gI}\n\n[${r(`sidePanel.userQuestionLabel`)}]\n${hI.content}`;M(async()=>{let{addMessage:e}=await Promise.resolve().then(()=>oC);return{addMessage:e}},void 0).then(({addMessage:i})=>{i(`user`,t,!0,[],null,!1,n),N.messageHistory.push({role:`user`,content:n,timestamp:new Date().toISOString()}),i(`assistant`,e,!0),N.messageHistory.push({role:`assistant`,content:e}),M(async()=>{let{saveCurrentSession:e}=await Promise.resolve().then(()=>Ci);return{saveCurrentSession:e}},void 0).then(({saveCurrentSession:e})=>{e()}),Promise.all([M(()=>Promise.resolve().then(()=>oS),void 0),new Promise(e=>requestAnimationFrame(e))]).then(([{autoScrollToBottom:e}])=>{e(document.getElementById(`chatContainer`),{force:!0,smooth:!0}),L(r(`sidePanel.popupTransferred`))})}),NI()}function zI(e,t,n){let{context:r,truncated:i}=SI(n,t);hI=e,gI=t,_I=r,vI=i,BI()}function BI(){mI=``,yI=!0,kI(hI?.content);let e=CI(gI,_I,hI.content,vI);pI=`popup_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,chrome.runtime.sendMessage({type:`SIDEPANEL_POPUP_ASK`,sessionId:pI,messages:e}).catch(e=>{a.error(`[SelectionPopup] sendMessage failed:`,e),MI(r(`sidePanel.popupRequestFailed`)),yI=!1})}var VI=!1;function HI(){VI||(VI=!0,chrome.runtime.onMessage.addListener(e=>{if(!(!e||!e.type)&&e.type.startsWith(`SIDEPANEL_POPUP_`)&&e.sessionId===pI){if(e.type===`SIDEPANEL_POPUP_STREAM_CHUNK`)e.delta&&(mI+=e.delta,jI(qt(mI)));else if(e.type===`SIDEPANEL_POPUP_STREAM_DONE`)yI=!1,e.finalContent&&(mI=e.finalContent),jI(qt(mI));else if(e.type===`SIDEPANEL_POPUP_STREAM_ERROR`){if(!yI)return;yI=!1,MI(e.error||r(`sidePanel.popupRequestFailed`))}}}))}function UI(){HI(),document.addEventListener(`mousedown`,PI),document.addEventListener(`keydown`,FI)}function WI(e,t,n,r,i){!t||!e||(HI(),OI(n,r),bI=!1,zI(e,t,i||N.currentSelectionRange))}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 GI(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 ze(),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([qe(t),Ae()]);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=`
2599
2599
  <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px;">
2600
2600
  <div style="background: var(--brand-soft-bg); border-radius: 8px; padding: 10px; text-align: center;">
2601
2601
  <div style="font-size: 10px; color: var(--text-tertiary); margin-bottom: 4px;">${r(`tokenStats.topCardSessionTokens`)}</div>
@@ -2706,7 +2706,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
2706
2706
  <span style="background:var(--bg-subtle);padding:1px 5px;border-radius:3px;font-size:9px;color:var(--text-secondary);">${P(i)}</span>
2707
2707
  <span style="font-weight:500;color:var(--text-primary);margin-left:auto;">${D(e.totalTokens)}</span>
2708
2708
  <span style="color:${o};font-size:9px;font-weight:500;width:35px;text-align:right;">${((e.contextUsageRate||0)*100).toFixed(1)}%</span>
2709
- </div>`}).join(``)}function D(e){return e>=1e6?(e/1e6).toFixed(1)+`M`:e>=1e3?(e/1e3).toFixed(1)+`K`:String(e)}function O(e){return e>=.8?`#ef4444`:e>=.5?`#f59e0b`:`#10b981`}}function xI(e){return(e||[]).map(e=>e.token?{...e,token:S(e.token)}:e)}n(`zh`,{sidePanel:{confirmAction:`确认操作`,memoryLimitAll:`全`,memoryLimitTitle:`点击设置记忆历史限制条数`,configUpdated:`✅ 配置已更新`,selectedPrefix:`📌 已选中`,askBasedOnSelection:`基于选中内容提问`,selectedContentLabel:`选中内容`,selectedContentSummary:`摘要`,userQuestionLabel:`用户问题`,requestFailed:`❌ 请求失败:`,unknownError:`未知错误`,notConnected:`未连接`,noPairedAgents:`暂无已配对代理`,agentDisabled:`已停用`,agentConnected:`已连接`,agentChecking:`检测中...`,agentOnline:`在线`,agentOffline:`离线`,enableAgent:`启用`,disableAgent:`停用`,disconnectAgent:`断开`,connectAgent:`连接`,deleteAgentBtn:`删除`,workingDirectory:`工作目录: {path}`,agentAddressCopied:`已复制代理地址`,unknownAgent:`未知`,restartAgentConfirm:`代理名称:{name}
2709
+ </div>`}).join(``)}function D(e){return e>=1e6?(e/1e6).toFixed(1)+`M`:e>=1e3?(e/1e3).toFixed(1)+`K`:String(e)}function O(e){return e>=.8?`#ef4444`:e>=.5?`#f59e0b`:`#10b981`}}function KI(e){return(e||[]).map(e=>e.token?{...e,token:S(e.token)}:e)}n(`zh`,{sidePanel:{confirmAction:`确认操作`,memoryLimitAll:`全`,memoryLimitTitle:`点击设置记忆历史限制条数`,configUpdated:`✅ 配置已更新`,selectedPrefix:`📌 已选中`,askBasedOnSelection:`基于选中内容提问`,selectedContentLabel:`选中内容`,selectedContentSummary:`摘要`,userQuestionLabel:`用户问题`,requestFailed:`❌ 请求失败:`,unknownError:`未知错误`,notConnected:`未连接`,noPairedAgents:`暂无已配对代理`,agentDisabled:`已停用`,agentConnected:`已连接`,agentChecking:`检测中...`,agentOnline:`在线`,agentOffline:`离线`,enableAgent:`启用`,disableAgent:`停用`,disconnectAgent:`断开`,connectAgent:`连接`,deleteAgentBtn:`删除`,workingDirectory:`工作目录: {path}`,agentAddressCopied:`已复制代理地址`,unknownAgent:`未知`,restartAgentConfirm:`代理名称:{name}
2710
2710
  代理地址:{url}
2711
2711
 
2712
2712
  确定要重启代理服务吗?重启期间服务将短暂不可用。`,restartAgentTitle:`重启代理`,agentRestarting:`代理服务正在重启...`,restartFailed:`重启失败: {error}`,restartRequestFailed:`重启请求失败: {error}`,updateAgentConfirm:`代理名称:{name}
@@ -2724,7 +2724,7 @@ Agent address: {url}
2724
2724
  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}
2725
2725
  Agent address: {url}
2726
2726
 
2727
- 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&&(N.chatConfig.autoCompaction=e.chatAutoCompaction.newValue===!0,CI(),a.debug(`[SidePanel] auto-compaction config updated:`,N.chatConfig.autoCompaction)),t===`local`&&e.chatPersistSummaryToMemory&&(N.chatConfig.persistSummaryToMemory=e.chatPersistSummaryToMemory.newValue!==!1,wI(),a.debug(`[SidePanel] persist-summary config updated:`,N.chatConfig.persistSummaryToMemory)),t===`local`&&e.chatMaxMemoryMessages&&(N.chatConfig.maxMemoryMessages=e.chatMaxMemoryMessages.newValue,SI(),a.debug(`[SidePanel] memory limitconfiguration updated:`,N.chatConfig.maxMemoryMessages)),t===`local`&&e.queueAutoCarry&&(N.chatConfig.queueAutoCarry=e.queueAutoCarry.newValue!==!1,a.debug(`[SidePanel] queue auto-carry updated:`,N.chatConfig.queueAutoCarry)),t===`local`&&e.queueAutoCarryEveryNIterations&&(N.chatConfig.queueAutoCarryEveryNIterations=e.queueAutoCarryEveryNIterations.newValue,a.debug(`[SidePanel] queue auto-carry interval updated:`,N.chatConfig.queueAutoCarryEveryNIterations))});function SI(){let e=document.getElementById(`memoryLimitLabel`);e&&(N.chatConfig.maxMemoryMessages!==null&&N.chatConfig.maxMemoryMessages!==void 0&&N.chatConfig.maxMemoryMessages>0?e.textContent=N.chatConfig.maxMemoryMessages:e.textContent=r(`sidePanel.memoryLimitAll`),e.title=r(`sidePanel.memoryLimitTitle`))}function CI(){let e=document.getElementById(`autoCompactBtn`);e&&(e.checked=N.chatConfig.autoCompaction===!0)}function wI(){let e=document.getElementById(`persistSummaryBtn`);e&&(e.checked=N.chatConfig.persistSummaryToMemory!==!1)}function TI(e){e.preventDefault(),e.stopPropagation();let t=document.getElementById(`memoryLimitDropdown`);if(t.classList.toggle(`show`),t.classList.contains(`show`)){let e=N.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 EI(){let e=document.getElementById(`memoryLimitDropdown`),t=document.getElementById(`memoryLimitLabel`),n=e?.querySelector(`#memoryLimitInput`);if(!e||!t)return;SI(),t.addEventListener(`click`,TI);let i=document.getElementById(`autoCompactBtn`);i&&(i.checked=N.chatConfig.autoCompaction===!0,i.addEventListener(`change`,()=>{let e=i.checked;chrome.storage.local.set({chatAutoCompaction:e},()=>{N.chatConfig.autoCompaction=e,L(r(`sidePanel.configUpdated`),`success`)})}));let a=document.getElementById(`persistSummaryBtn`);a&&(a.checked=N.chatConfig.persistSummaryToMemory!==!1,a.addEventListener(`change`,()=>{let e=a.checked;chrome.storage.local.set({chatPersistSummaryToMemory:e},()=>{N.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},()=>{N.chatConfig.maxMemoryMessages=a,SI(),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},()=>{N.chatConfig.maxMemoryMessages=n,SI(),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 DI(e){if(N.activeAgentId&&N.activeAgentId!=="default")try{let{updateAgent:t}=await M(async()=>{let{updateAgent:e}=await import(`./agent-store-CrkBz4jI.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([0,1,2,3,4]));await t(N.activeAgentId,{model:e})}catch{}else chrome.storage.local.set({modelName:e}),A(e)}async function OI(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=xI(e.pairedAgents),n=e.activeAgentId,r=t.find(e=>e.id===n&&!e.disabled);if(!r){N.agentPlatform={connected:!1},HI(N.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){N.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&&N.agentVersions.set(n,t.version),t.workdir&&N.agentWorkdirs.set(n,t.workdir),t.homeDir&&N.agentHomeDirs.set(n,t.homeDir);let e=KI(t.platformName||t.platform,t.arch);e&&N.agentSystemInfos.set(n,e)}else N.agentPlatform={connected:!1}}else N.agentPlatform={connected:!1}}catch{N.agentPlatform={connected:!1}}else N.agentPlatform={connected:!1};HI(N.agentPlatform),Vm()}catch{}}async function kI(e,t,n){if(N.activeAgentId&&N.activeAgentId!=="default")try{let{updateAgent:n}=await M(async()=>{let{updateAgent:e}=await import(`./agent-store-CrkBz4jI.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([0,1,2,3,4]));await n(N.activeAgentId,{temperature:e,topP:t})}catch{}else chrome.storage.local.set({temperature:e,topP:t,selectedTempIndex:n})}function AI(){let e=document.getElementById(`currentModelTag`);if(!e)return;let t=N.currentModel||``;e.textContent=t,e.title=t,e.style.display=t?``:`none`}var jI=new Set,MI=0;function NI(){let e=document.getElementById(`workdirTag`);e&&(e.dataset.locked=Rm(N.activeSessionId)?`true`:`false`)}async function PI(){let e=++MI,t=document.getElementById(`workdirTag`),n=document.getElementById(`workdirTagName`);if(!t||!n)return;let i=N.activeSessionId||null,o=Array.isArray(N.enabledTools)&&N.enabledTools.includes(`agent_exec`);if(N.agentPlatform?.connected!==!0||!o){t.style.display=`none`;return}let s=null;try{s=await fe(i)}catch(e){a.debug(`[WorkdirTag] resolve failed:`,e&&e.message)}if(e!==MI)return;let c=s&&s.workdir||``;if(!c){t.style.display=`none`;return}t.style.display=``,n.textContent=ae(c,{homeDir:N.agentPlatform?.homeDir||``}),NI();try{let{getWorkspaceRoot:e}=await M(async()=>{let{getWorkspaceRoot:e}=await import(`./workspace-manager-Dq1z6ENd.js`).then(e=>e.D);return{getWorkspaceRoot:e}},__vite__mapDeps([15,1,2,3,4])),n=await e(i),r=!!(n&&n!==c);r&&s.scope==="default"?(t.dataset.invalid=`false`,BF(i).then(e=>{e&&PI()}).catch(e=>a.debug(`[WorkdirTag] reconcile failed:`,e&&e.message))):t.dataset.invalid=r?`true`:`false`}catch{t.dataset.invalid=`false`}if(e===MI&&(t.title=`${c}${s.scope===`session`?r(`workdirTag.sessionScope`):r(`workdirTag.defaultScope`)}${t.dataset.invalid===`true`?r(`workdirTag.pathMissing`):``}`,s.boundWorkdir&&s.scope==="default")){let e=`${i||``}::${s.agentId||``}`;jI.has(e)||(jI.add(e),L(r(`workdirTag.agentSwitched`),`warning`))}}function FI(){let e=document.getElementById(`workdirTag`);e&&(e.setAttribute(`aria-label`,r(`workdirTag.tagHint`)),e.addEventListener(`click`,async e=>{if(e.stopPropagation(),Rm(N.activeSessionId)){NI(),L(r(`workdirTag.lockedHint`),`warning`);return}NI();let{showSwitchWorkdirDialog:t}=await M(async()=>{let{showSwitchWorkdirDialog:e}=await Promise.resolve().then(()=>qm);return{showSwitchWorkdirDialog:e}},void 0);await t({sessionId:N.activeSessionId||null})})),PI(),document.addEventListener(`session-switched`,()=>{PI()}),document.addEventListener(`session-workdir-changed`,()=>{PI()}),document.addEventListener(`agent-model-changed`,()=>{PI()}),document.addEventListener(`agent-tools-changed`,()=>{PI()}),document.addEventListener(`generating-state-changed`,()=>{NI()}),document.addEventListener(`generation-ended`,()=>{NI()}),Ir(()=>{NI()})}function II(){let e=document.getElementById(`currentModelTag`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),document.getElementById(`tempDisplay`)?.click()}),AI()}function LI(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=E(t),r.style.display=``):r.style.display=`none`),AI()}function RI(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=`
2727
+ 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&&(N.chatConfig.autoCompaction=e.chatAutoCompaction.newValue===!0,JI(),a.debug(`[SidePanel] auto-compaction config updated:`,N.chatConfig.autoCompaction)),t===`local`&&e.chatPersistSummaryToMemory&&(N.chatConfig.persistSummaryToMemory=e.chatPersistSummaryToMemory.newValue!==!1,YI(),a.debug(`[SidePanel] persist-summary config updated:`,N.chatConfig.persistSummaryToMemory)),t===`local`&&e.chatMaxMemoryMessages&&(N.chatConfig.maxMemoryMessages=e.chatMaxMemoryMessages.newValue,qI(),a.debug(`[SidePanel] memory limitconfiguration updated:`,N.chatConfig.maxMemoryMessages)),t===`local`&&e.queueAutoCarry&&(N.chatConfig.queueAutoCarry=e.queueAutoCarry.newValue!==!1,a.debug(`[SidePanel] queue auto-carry updated:`,N.chatConfig.queueAutoCarry)),t===`local`&&e.queueAutoCarryEveryNIterations&&(N.chatConfig.queueAutoCarryEveryNIterations=e.queueAutoCarryEveryNIterations.newValue,a.debug(`[SidePanel] queue auto-carry interval updated:`,N.chatConfig.queueAutoCarryEveryNIterations))});function qI(){let e=document.getElementById(`memoryLimitLabel`);e&&(N.chatConfig.maxMemoryMessages!==null&&N.chatConfig.maxMemoryMessages!==void 0&&N.chatConfig.maxMemoryMessages>0?e.textContent=N.chatConfig.maxMemoryMessages:e.textContent=r(`sidePanel.memoryLimitAll`),e.title=r(`sidePanel.memoryLimitTitle`))}function JI(){let e=document.getElementById(`autoCompactBtn`);e&&(e.checked=N.chatConfig.autoCompaction===!0)}function YI(){let e=document.getElementById(`persistSummaryBtn`);e&&(e.checked=N.chatConfig.persistSummaryToMemory!==!1)}function XI(e){e.preventDefault(),e.stopPropagation();let t=document.getElementById(`memoryLimitDropdown`);if(t.classList.toggle(`show`),t.classList.contains(`show`)){let e=N.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 ZI(){let e=document.getElementById(`memoryLimitDropdown`),t=document.getElementById(`memoryLimitLabel`),n=e?.querySelector(`#memoryLimitInput`);if(!e||!t)return;qI(),t.addEventListener(`click`,XI);let i=document.getElementById(`autoCompactBtn`);i&&(i.checked=N.chatConfig.autoCompaction===!0,i.addEventListener(`change`,()=>{let e=i.checked;chrome.storage.local.set({chatAutoCompaction:e},()=>{N.chatConfig.autoCompaction=e,L(r(`sidePanel.configUpdated`),`success`)})}));let a=document.getElementById(`persistSummaryBtn`);a&&(a.checked=N.chatConfig.persistSummaryToMemory!==!1,a.addEventListener(`change`,()=>{let e=a.checked;chrome.storage.local.set({chatPersistSummaryToMemory:e},()=>{N.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},()=>{N.chatConfig.maxMemoryMessages=a,qI(),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},()=>{N.chatConfig.maxMemoryMessages=n,qI(),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 QI(e){if(N.activeAgentId&&N.activeAgentId!=="default")try{let{updateAgent:t}=await M(async()=>{let{updateAgent:e}=await import(`./agent-store-1fyaAv9T.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([0,1,2,3,4]));await t(N.activeAgentId,{model:e})}catch{}else chrome.storage.local.set({modelName:e}),A(e)}async function $I(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=KI(e.pairedAgents),n=e.activeAgentId,r=t.find(e=>e.id===n&&!e.disabled);if(!r){N.agentPlatform={connected:!1},mL(N.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){N.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&&N.agentVersions.set(n,t.version),t.workdir&&N.agentWorkdirs.set(n,t.workdir),t.homeDir&&N.agentHomeDirs.set(n,t.homeDir);let e=vL(t.platformName||t.platform,t.arch);e&&N.agentSystemInfos.set(n,e)}else N.agentPlatform={connected:!1}}else N.agentPlatform={connected:!1}}catch{N.agentPlatform={connected:!1}}else N.agentPlatform={connected:!1};mL(N.agentPlatform),Vm()}catch{}}async function eL(e,t,n){if(N.activeAgentId&&N.activeAgentId!=="default")try{let{updateAgent:n}=await M(async()=>{let{updateAgent:e}=await import(`./agent-store-1fyaAv9T.js`).then(e=>e.t);return{updateAgent:e}},__vite__mapDeps([0,1,2,3,4]));await n(N.activeAgentId,{temperature:e,topP:t})}catch{}else chrome.storage.local.set({temperature:e,topP:t,selectedTempIndex:n})}function tL(){let e=document.getElementById(`currentModelTag`);if(!e)return;let t=N.currentModel||``;e.textContent=t,e.title=t,e.style.display=t?``:`none`}var nL=new Set,rL=0;function iL(){let e=document.getElementById(`workdirTag`);e&&(e.dataset.locked=Rm(N.activeSessionId)?`true`:`false`)}async function aL(){let e=++rL,t=document.getElementById(`workdirTag`),n=document.getElementById(`workdirTagName`);if(!t||!n)return;let i=N.activeSessionId||null,o=Array.isArray(N.enabledTools)&&N.enabledTools.includes(`agent_exec`);if(N.agentPlatform?.connected!==!0||!o){t.style.display=`none`;return}let s=null;try{s=await fe(i)}catch(e){a.debug(`[WorkdirTag] resolve failed:`,e&&e.message)}if(e!==rL)return;let c=s&&s.workdir||``;if(!c){t.style.display=`none`;return}t.style.display=``,n.textContent=ae(c,{homeDir:N.agentPlatform?.homeDir||``}),iL();try{let{getWorkspaceRoot:e}=await M(async()=>{let{getWorkspaceRoot:e}=await import(`./workspace-manager-DfSFPqwp.js`).then(e=>e.D);return{getWorkspaceRoot:e}},__vite__mapDeps([15,1,2,3,4])),n=await e(i),r=!!(n&&n!==c);r&&s.scope==="default"?(t.dataset.invalid=`false`,dI(i).then(e=>{e&&aL()}).catch(e=>a.debug(`[WorkdirTag] reconcile failed:`,e&&e.message))):t.dataset.invalid=r?`true`:`false`}catch{t.dataset.invalid=`false`}if(e===rL&&(t.title=`${c}${s.scope===`session`?r(`workdirTag.sessionScope`):r(`workdirTag.defaultScope`)}${t.dataset.invalid===`true`?r(`workdirTag.pathMissing`):``}`,s.boundWorkdir&&s.scope==="default")){let e=`${i||``}::${s.agentId||``}`;nL.has(e)||(nL.add(e),L(r(`workdirTag.agentSwitched`),`warning`))}}function oL(){let e=document.getElementById(`workdirTag`);e&&(e.setAttribute(`aria-label`,r(`workdirTag.tagHint`)),e.addEventListener(`click`,async e=>{if(e.stopPropagation(),Rm(N.activeSessionId)){iL(),L(r(`workdirTag.lockedHint`),`warning`);return}iL();let{showSwitchWorkdirDialog:t}=await M(async()=>{let{showSwitchWorkdirDialog:e}=await Promise.resolve().then(()=>qm);return{showSwitchWorkdirDialog:e}},void 0);await t({sessionId:N.activeSessionId||null})})),aL(),document.addEventListener(`session-switched`,()=>{aL()}),document.addEventListener(`session-workdir-changed`,()=>{aL()}),document.addEventListener(`agent-model-changed`,()=>{aL()}),document.addEventListener(`agent-tools-changed`,()=>{aL()}),document.addEventListener(`generating-state-changed`,()=>{iL()}),document.addEventListener(`generation-ended`,()=>{iL()}),Ir(()=>{iL()})}function sL(){let e=document.getElementById(`currentModelTag`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),document.getElementById(`tempDisplay`)?.click()}),tL()}function cL(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=E(t),r.style.display=``):r.style.display=`none`),tL()}function lL(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=`
2728
2728
  <div class="model-section-title" data-i18n="model.selectModel">${r(`model.selectModel`)}</div>
2729
2729
  <div class="section-select" id="modelSelect">
2730
2730
  <div class="section-select-row" id="modelSelectRow">
@@ -2733,7 +2733,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
2733
2733
  <span class="section-select-caret"></span>
2734
2734
  </div>
2735
2735
  <div class="section-select-list" id="modelSelectList"></div>
2736
- </div>`;let e=i.querySelector(`#modelSelectList`);e.innerHTML=UN();let t=[...a].sort((e,t)=>T(e.name,t.name));for(let n of t){let t=document.createElement(`div`);t.className=`model-option`,t.dataset.value=n.name,n.contextWindow&&n.contextWindow>0&&(t.dataset.contextWindow=n.contextWindow),t.innerHTML=`<span class="model-option-check"></span><span class="model-option-left">${P(n.name)}</span>`;let i=document.createElement(`span`);i.className=`model-option-right`;let a=document.createElement(`span`);a.className=`model-ctx-badge`;let o=n.contextWindow&&n.contextWindow>0;a.textContent=E(o?n.contextWindow:p(n.name)),o||(a.classList.add(`is-auto`),a.title=r(`settings.ctxBadgeAutoTip`)),i.appendChild(a),t.appendChild(i),t.addEventListener(`click`,e=>{e.stopPropagation(),HN(),N.currentModel=n.name,LI(n.name),DI(n.name),dE()}),e.appendChild(t)}}N.customModelMap=h(e),typeof t==`function`&&t()}function zI(e,t=r(`sidePanel.selectedPrefix`)){if(!N.enableSelectionQuery)return;N.quotedContextText=``,N.selectedContextText=e;let n=document.getElementById(`selectionIndicator`),i=document.getElementById(`selectionText`),a=document.getElementById(`userInput`);if(n&&i&&a){let r;r=e.length>100?e.substring(0,100)+`...`:e.length>50?e.substring(0,50)+`...`:e,i.textContent=`${t}: ${r}`,n.classList.add(`show`)}}function BI(e,t,n=0,i=0){if(!N.enableSelectionQuery)return;let o=document.getElementById(`selectionFloatingMenu`),s=document.getElementById(`selectionMenuItems`);if(!o||!s){let e=document.getElementById(`chatContainer`);if(!e)return;o=document.createElement(`div`),o.className=`selection-floating-menu`,o.id=`selectionFloatingMenu`,o.innerHTML=`
2736
+ </div>`;let e=i.querySelector(`#modelSelectList`);e.innerHTML=UN();let t=[...a].sort((e,t)=>T(e.name,t.name));for(let n of t){let t=document.createElement(`div`);t.className=`model-option`,t.dataset.value=n.name,n.contextWindow&&n.contextWindow>0&&(t.dataset.contextWindow=n.contextWindow),t.innerHTML=`<span class="model-option-check"></span><span class="model-option-left">${P(n.name)}</span>`;let i=document.createElement(`span`);i.className=`model-option-right`;let a=document.createElement(`span`);a.className=`model-ctx-badge`;let o=n.contextWindow&&n.contextWindow>0;a.textContent=E(o?n.contextWindow:p(n.name)),o||(a.classList.add(`is-auto`),a.title=r(`settings.ctxBadgeAutoTip`)),i.appendChild(a),t.appendChild(i),t.addEventListener(`click`,e=>{e.stopPropagation(),HN(),N.currentModel=n.name,cL(n.name),QI(n.name),dE()}),e.appendChild(t)}}N.customModelMap=h(e),typeof t==`function`&&t()}function uL(e,t=r(`sidePanel.selectedPrefix`)){if(!N.enableSelectionQuery)return;N.quotedContextText=``,N.selectedContextText=e;let n=document.getElementById(`selectionIndicator`),i=document.getElementById(`selectionText`),a=document.getElementById(`userInput`);if(n&&i&&a){let r;r=e.length>100?e.substring(0,100)+`...`:e.length>50?e.substring(0,50)+`...`:e,i.textContent=`${t}: ${r}`,n.classList.add(`show`)}}function dL(e,t,n=0,i=0){if(!N.enableSelectionQuery)return;let o=document.getElementById(`selectionFloatingMenu`),s=document.getElementById(`selectionMenuItems`);if(!o||!s){let e=document.getElementById(`chatContainer`);if(!e)return;o=document.createElement(`div`),o.className=`selection-floating-menu`,o.id=`selectionFloatingMenu`,o.innerHTML=`
2737
2737
  <div class="menu-header">${r(`sidePanel.askBasedOnSelection`)}</div>
2738
2738
  <div id="selectionMenuItems"></div>
2739
2739
  `,e.appendChild(o),s=document.getElementById(`selectionMenuItems`)}let c=N.customPrompts.filter(e=>e.enabledInMenu===!0);if(c.length===0){a.debug(`[SidePanel] showFloatingMenu skipped: no prompts enabled in menu`);return}s.innerHTML=``,c.forEach(e=>{let a=e.content.length>10?e.content.substring(0,10)+`...`:e.content,o=document.createElement(`div`);o.className=`menu-item`,o.innerHTML=`
@@ -2748,9 +2748,9 @@ Are you sure you want to stop the agent service? You will not be able to connect
2748
2748
  </svg>
2749
2749
  </button>
2750
2750
  </span>
2751
- `,o.addEventListener(`click`,n=>{n.stopPropagation(),VI(e,t)}),o.querySelector(`.menu-item-popup-btn`).addEventListener(`click`,r=>{r.stopPropagation();let a=N.currentSelectionRange?N.currentSelectionRange.cloneRange():null;window.getSelection()?.removeAllRanges(),window.hideFloatingMenu(),yI(e,t,n,i,a)}),s.appendChild(o)});let l=document.body.getBoundingClientRect(),u=40+c.length*36,d=i-l.top-u-30,f=n-l.left-20;d<l.top+10&&(d=i-l.top+30),f<l.left+10&&(f=n-l.left+20),f+180>l.right-10&&(f=n-l.left-180-30,f<l.left+10&&(f=n-l.left+20)),d+u>l.bottom-10&&(d=i-l.top-u-30,d<l.top+10&&(d=i-l.top+30)),o.style.top=d+`px`,o.style.left=f+`px`,o.style.maxHeight=l.bottom-d-20+`px`,o.classList.add(`show`)}window.hideFloatingMenu=function(){let e=document.getElementById(`selectionFloatingMenu`);e&&e.classList.remove(`show`),N.lastSelectedText=``,N.currentSelectionRange=null};async function VI(e,t){if(!N.enableSelectionQuery)return;if(window.hideFloatingMenu(),N.isGenerating){a.debug(`[SidePanel] generating,please wait...`);return}await Vc({state:N,getRatio:()=>lE().usage?.ratio??0,compact:vE}),N.selectedContextText=t,pC();let n=document.getElementById(`chatContainer`).querySelector(`.welcome-message`);n&&n.remove(),GC(`selected`,t,!1);let{compressed:i,wasCompressed:o}=k(t),s=`[${r(`sidePanel.selectedContentLabel`)}${o?r(`sidePanel.selectedContentSummary`):``}]\n${i}\n\n[${r(`sidePanel.userQuestionLabel`)}]\n${e.content}`,{messageId:c,timestamp:l}=YC(`user`,e.content,!0,[],null,!1,s);N.messageHistory.push({role:`user`,content:s,messageId:c,timestamp:l}),yC(),qn(e.content),N.isGenerating=!0;let u=tw(),d=N.activeSessionId,p=N.currentModel;try{await Rt(),a.debug(`[SidePanel] sendmessagedebuginfo:`),a.debug(` - isolateChat:`,N.isolateChat),a.debug(` - chatConfig:`,N.chatConfig),a.debug(` - messageHistory.length:`,N.messageHistory.length);let t=[{role:`system`,content:await Gt(null,{sessionId:d})}];if(N.isolateChat){let e=f(t[0]?.content||``),n=g(p,0,N.customModelMap)-e-4096-2e3,r=Math.floor(n*.7),i=N.messageHistory[N.messageHistory.length-1],o=Hn(N.messageHistory.slice(0,-1),{isolateChat:!0,maxMemoryMessages:N.chatConfig.maxMemoryMessages,compaction:N.activeCompaction,historyBudget:r,currentMessage:i});Wn(t,o,N.activeCompaction,a),o.historySummaryText&&(t[0]={...t[0],content:t[0].content+`
2751
+ `,o.addEventListener(`click`,n=>{n.stopPropagation(),fL(e,t)}),o.querySelector(`.menu-item-popup-btn`).addEventListener(`click`,r=>{r.stopPropagation();let a=N.currentSelectionRange?N.currentSelectionRange.cloneRange():null;window.getSelection()?.removeAllRanges(),window.hideFloatingMenu(),WI(e,t,n,i,a)}),s.appendChild(o)});let l=document.body.getBoundingClientRect(),u=40+c.length*36,d=i-l.top-u-30,f=n-l.left-20;d<l.top+10&&(d=i-l.top+30),f<l.left+10&&(f=n-l.left+20),f+180>l.right-10&&(f=n-l.left-180-30,f<l.left+10&&(f=n-l.left+20)),d+u>l.bottom-10&&(d=i-l.top-u-30,d<l.top+10&&(d=i-l.top+30)),o.style.top=d+`px`,o.style.left=f+`px`,o.style.maxHeight=l.bottom-d-20+`px`,o.classList.add(`show`)}window.hideFloatingMenu=function(){let e=document.getElementById(`selectionFloatingMenu`);e&&e.classList.remove(`show`),N.lastSelectedText=``,N.currentSelectionRange=null};async function fL(e,t){if(!N.enableSelectionQuery)return;if(window.hideFloatingMenu(),N.isGenerating){a.debug(`[SidePanel] generating,please wait...`);return}await Vc({state:N,getRatio:()=>lE().usage?.ratio??0,compact:vE}),N.selectedContextText=t,pC();let n=document.getElementById(`chatContainer`).querySelector(`.welcome-message`);n&&n.remove(),GC(`selected`,t,!1);let{compressed:i,wasCompressed:o}=k(t),s=`[${r(`sidePanel.selectedContentLabel`)}${o?r(`sidePanel.selectedContentSummary`):``}]\n${i}\n\n[${r(`sidePanel.userQuestionLabel`)}]\n${e.content}`,{messageId:c,timestamp:l}=YC(`user`,e.content,!0,[],null,!1,s);N.messageHistory.push({role:`user`,content:s,messageId:c,timestamp:l}),yC(),qn(e.content),N.isGenerating=!0;let u=tw(),d=N.activeSessionId,p=N.currentModel;try{await Rt(),a.debug(`[SidePanel] sendmessagedebuginfo:`),a.debug(` - isolateChat:`,N.isolateChat),a.debug(` - chatConfig:`,N.chatConfig),a.debug(` - messageHistory.length:`,N.messageHistory.length);let t=[{role:`system`,content:await Gt(null,{sessionId:d})}];if(N.isolateChat){let e=f(t[0]?.content||``),n=g(p,0,N.customModelMap)-e-4096-2e3,r=Math.floor(n*.7),i=N.messageHistory[N.messageHistory.length-1],o=Hn(N.messageHistory.slice(0,-1),{isolateChat:!0,maxMemoryMessages:N.chatConfig.maxMemoryMessages,compaction:N.activeCompaction,historyBudget:r,currentMessage:i});Wn(t,o,N.activeCompaction,a),o.historySummaryText&&(t[0]={...t[0],content:t[0].content+`
2752
2752
 
2753
- `+o.historySummaryText}),t=[...t,...o.messages];for(let e=0;e<t.length-1;e++)t[e]={...t[e],content:v(t[e].content)}}else t.push({role:`user`,content:s});let n=await Nt(),i,o;try{let r=await uw(t,p,N.useTools,n);if(i=r.content,o=r.executionLog||[],nw(u),r.wasStreamed)r.streamingMsgId&&(N.messageHistory.push({role:`assistant`,content:i,executionLog:o,messageId:r.streamingMsgId}),yC());else{let{element:e,messageId:t}=YC(`assistant`,i,!0,o);await cn(e),N.messageHistory.push({role:`assistant`,content:i,executionLog:o,messageId:t}),yC()}vl(d,e.content);return}catch(t){nw(u),i=r(`sidePanel.requestFailed`)+(t.message||r(`sidePanel.unknownError`)),o=t.executionLog||[];let{element:n,messageId:a}=YC(`assistant`,i,!0,o);throw N.messageHistory.push({role:`assistant`,content:i,executionLog:o,messageId:a}),yC(),t.message!==r(`chatMsg.errTaskStopped`)&&yl(d,i,e.content),t}}catch{}finally{Sl(d),document.getElementById(`userInput`).focus()}}async function HI(e,t=!1){let n=document.getElementById(`headerAgentDot`),i=document.getElementById(`headerAgentName`),a=document.getElementById(`headerAgentTrigger`);if(!n||!i)return;let o=null,s=[];try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]);s=xI(e.pairedAgents),o=s.find(t=>t.id===e.activeAgentId)}catch{}let c=e?.connected===!0;if(!c||!o?(n.className=`header-agent-dot disconnected`,i.textContent=o?o.name.length>12?o.name.substring(0,12)+`...`:o.name:r(`sidePanel.notConnected`),i.classList.toggle(`truncated`,!!o),a.title=o?o.name:``):(n.className=`header-agent-dot connected`,i.textContent=o.name.length>12?o.name.substring(0,12)+`...`:o.name,i.classList.toggle(`truncated`,o.name.length>12),a.title=o.name),UI(o,s,c),!t){let e=document.getElementById(`headerAgentDropdown`);e&&e.style.display!==`none`&&YI()}_v(c),PI()}function UI(e,t,n){let i=document.getElementById(`agentDdList`),a=document.getElementById(`agentDdCopyRow`);if(!i||!a)return;if(e?.url?(a.style.display=``,a.querySelector(`.agent-dd-copy-label`).textContent=e.url):a.style.display=`none`,t.length===0){i.innerHTML=`<div class="agent-dd-empty">`+r(`sidePanel.noPairedAgents`)+`</div>`;let e=document.getElementById(`agentDdRestartBtn`),t=document.getElementById(`agentDdUpdateBtn`),n=document.getElementById(`agentDdStopBtn`);e&&(e.disabled=!0),t&&(t.disabled=!0),n&&(n.disabled=!0);return}i.innerHTML=t.map(t=>{let i=t.id===e?.id,a=!!t.disabled,o=N.agentVersions.get(t.id),s,c;a?(s=`disabled`,c=r(`sidePanel.agentDisabled`)):i?(s=n?`connected`:`disconnected`,c=r(n?`sidePanel.agentConnected`:`sidePanel.notConnected`)):(s=`checking`,c=r(`sidePanel.agentChecking`));let l=N.agentWorkdirs.get(t.id),u=GI(l,N.agentHomeDirs.get(t.id)),d=N.agentSystemInfos.get(t.id);return`
2753
+ `+o.historySummaryText}),t=[...t,...o.messages];for(let e=0;e<t.length-1;e++)t[e]={...t[e],content:v(t[e].content)}}else t.push({role:`user`,content:s});let n=await Nt(),i,o;try{let r=await uw(t,p,N.useTools,n);if(i=r.content,o=r.executionLog||[],nw(u),r.wasStreamed)r.streamingMsgId&&(N.messageHistory.push({role:`assistant`,content:i,executionLog:o,messageId:r.streamingMsgId}),yC());else{let{element:e,messageId:t}=YC(`assistant`,i,!0,o);await cn(e),N.messageHistory.push({role:`assistant`,content:i,executionLog:o,messageId:t}),yC()}vl(d,e.content);return}catch(t){nw(u),i=r(`sidePanel.requestFailed`)+(t.message||r(`sidePanel.unknownError`)),o=t.executionLog||[];let{element:n,messageId:a}=YC(`assistant`,i,!0,o);throw N.messageHistory.push({role:`assistant`,content:i,executionLog:o,messageId:a}),yC(),t.message!==r(`chatMsg.errTaskStopped`)&&yl(d,i,e.content),t}}catch{}finally{Sl(d),document.getElementById(`userInput`).focus()}}var pL=null;async function mL(e,t=!1){let n=document.getElementById(`headerAgentDot`),i=document.getElementById(`headerAgentName`),a=document.getElementById(`headerAgentTrigger`);if(!n||!i)return;let o=null,s=[];try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]);s=KI(e.pairedAgents),o=s.find(t=>t.id===e.activeAgentId)}catch{}let c=e?.connected===!0;if(c!==pL){pL=c;try{document.dispatchEvent(new CustomEvent(`agent-connection-changed`,{detail:{connected:c}}))}catch{}}if(!c||!o?(n.className=`header-agent-dot disconnected`,i.textContent=o?o.name.length>12?o.name.substring(0,12)+`...`:o.name:r(`sidePanel.notConnected`),i.classList.toggle(`truncated`,!!o),a.title=o?o.name:``):(n.className=`header-agent-dot connected`,i.textContent=o.name.length>12?o.name.substring(0,12)+`...`:o.name,i.classList.toggle(`truncated`,o.name.length>12),a.title=o.name),hL(o,s,c),!t){let e=document.getElementById(`headerAgentDropdown`);e&&e.style.display!==`none`&&xL()}_v(c),aL()}function hL(e,t,n){let i=document.getElementById(`agentDdList`),a=document.getElementById(`agentDdCopyRow`);if(!i||!a)return;if(e?.url?(a.style.display=``,a.querySelector(`.agent-dd-copy-label`).textContent=e.url):a.style.display=`none`,t.length===0){i.innerHTML=`<div class="agent-dd-empty">`+r(`sidePanel.noPairedAgents`)+`</div>`;let e=document.getElementById(`agentDdRestartBtn`),t=document.getElementById(`agentDdUpdateBtn`),n=document.getElementById(`agentDdStopBtn`);e&&(e.disabled=!0),t&&(t.disabled=!0),n&&(n.disabled=!0);return}i.innerHTML=t.map(t=>{let i=t.id===e?.id,a=!!t.disabled,o=N.agentVersions.get(t.id),s,c;a?(s=`disabled`,c=r(`sidePanel.agentDisabled`)):i?(s=n?`connected`:`disconnected`,c=r(n?`sidePanel.agentConnected`:`sidePanel.notConnected`)):(s=`checking`,c=r(`sidePanel.agentChecking`));let l=N.agentWorkdirs.get(t.id),u=_L(l,N.agentHomeDirs.get(t.id)),d=N.agentSystemInfos.get(t.id);return`
2754
2754
  <div class="agent-dd-item${i?` active`:``}${a?` disabled`:``}" data-agent-id="${t.id}">
2755
2755
  <span class="agent-dd-item-dot ${s}"></span>
2756
2756
  <div class="agent-dd-item-info">
@@ -2767,7 +2767,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
2767
2767
  <button class="agent-dd-tool-btn delete" data-action="delete" data-id="${t.id}" title="${r(`sidePanel.deleteAgentBtn`)}">🗑</button>
2768
2768
  </div>
2769
2769
  </div>
2770
- `}).join(``);let o=document.getElementById(`agentDdRestartBtn`),s=document.getElementById(`agentDdUpdateBtn`),c=document.getElementById(`agentDdStopBtn`),l=!!(e&&n);o&&(o.disabled=!l),s&&(s.disabled=!l),c&&(c.disabled=!l)}async function WI(e,t){if(t)try{let n=new AbortController;setTimeout(()=>n.abort(),2e3);let r=await fetch(`${e}/api/status/detail`,{signal:n.signal,headers:{Authorization:`Bearer ${t}`}});if(r.ok){let e=await r.json();if(e.success)return{online:!0,version:e.version||null,workdir:e.workdir||null,homeDir:e.homeDir||null,platformName:e.platformName||e.platform||null,arch:e.arch||null}}}catch{}try{let t=new AbortController;setTimeout(()=>t.abort(),2e3);let n=await fetch(`${e}/api/status`,{signal:t.signal});if(!n.ok)return{online:!1,version:null,workdir:null,homeDir:null,platformName:null,arch:null};let r=await n.json();return{online:!0,version:r.version||null,workdir:null,homeDir:null,platformName:r.platformName||r.platform||null,arch:r.arch||null}}catch{return{online:!1,version:null,workdir:null,homeDir:null,platformName:null,arch:null}}}function GI(e,t){return e?t&&e.startsWith(t)?`~`+e.substring(t.length):e:``}function KI(e,t){return e||``}function qI(e,t){let n=document.querySelector(`.agent-dd-item[data-agent-id="${e}"]`);if(!n)return;let i=n.querySelector(`.agent-dd-item-dot`),a=n.querySelector(`.agent-dd-item-status`),o=n.classList.contains(`active`);i&&(i.classList.remove(`checking`,`connected`,`disconnected`,`online`,`offline`),i.classList.add(o?t?`connected`:`disconnected`:t?`online`:`offline`)),a&&(o?a.textContent=r(t?`sidePanel.agentConnected`:`sidePanel.notConnected`):a.textContent===r(`sidePanel.agentChecking`)&&(a.textContent=r(t?`sidePanel.agentOnline`:`sidePanel.agentOffline`)))}function JI(e,t){if(!t)return;let n=document.querySelector(`.agent-dd-item[data-agent-id="${e}"]`);if(!n)return;let i=n.querySelector(`.agent-dd-item-info`);if(!i)return;let a=GI(t,N.agentHomeDirs.get(e)),o=i.querySelector(`.agent-dd-item-workdir`);o?(o.textContent=a,o.title=r(`sidePanel.workingDirectory`,{path:t})):(o=document.createElement(`span`),o.className=`agent-dd-item-workdir`,o.title=r(`sidePanel.workingDirectory`,{path:t}),o.textContent=a,i.appendChild(o))}window.updateAgentItemWorkdir=JI;async function YI(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=xI(e.pairedAgents),n=e.activeAgentId;await Promise.all(t.filter(e=>!e.disabled).map(async e=>{let t=await WI(e.url,e.token),r=t.online;t.version&&N.agentVersions.set(e.id,t.version),t.workdir&&N.agentWorkdirs.set(e.id,t.workdir),t.homeDir&&N.agentHomeDirs.set(e.id,t.homeDir);let i=KI(t.platformName,t.arch);i&&N.agentSystemInfos.set(e.id,i),t.workdir&&JI(e.id,t.workdir),qI(e.id,r),e.id===n&&r!==(N.agentPlatform?.connected===!0)&&(N.agentPlatform={...N.agentPlatform,connected:r},HI(N.agentPlatform,!0),r&&XI(e))}))}catch{}}async function XI(e){try{let t=e;if(!t){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=xI(e.pairedAgents),r=e.activeAgentId;t=n.find(e=>e.id===r&&!e.disabled)}if(!t||!t.url){N.agentPlatform={...N.agentPlatform,connected:!0},HI(N.agentPlatform),Vm();return}if(t.token)try{let e=new AbortController;setTimeout(()=>e.abort(),3e3);let n=await fetch(`${t.url}/api/status/detail`,{signal:e.signal,headers:{Authorization:`Bearer ${t.token}`}});if(n.ok){let e=await n.json();if(e.success){N.agentPlatform={platformName:e.platformName||`Unknown`,platform:e.platform||`unknown`,arch:e.arch||`unknown`,shell:e.shell||`/bin/sh`,homeDir:e.homeDir||``,workdir:e.workdir||``,connected:!0},e.version&&N.agentVersions.set(t.id,e.version),e.workdir&&(N.agentWorkdirs.set(t.id,e.workdir),JI(t.id,e.workdir)),e.homeDir&&N.agentHomeDirs.set(t.id,e.homeDir);let n=KI(e.platformName||e.platform,e.arch);n&&N.agentSystemInfos.set(t.id,n),HI(N.agentPlatform),Vm();return}}}catch{}try{let e=new AbortController;setTimeout(()=>e.abort(),3e3);let n=await fetch(`${t.url}/api/status`,{signal:e.signal});if(n.ok){let e=await n.json();N.agentPlatform={platformName:e.platformName||e.platform||`Unknown`,platform:e.platform||`unknown`,arch:e.arch||`unknown`,connected:!0},HI(N.agentPlatform),Vm();return}}catch{}N.agentPlatform={...N.agentPlatform,connected:!0},HI(N.agentPlatform),Vm()}catch{N.agentPlatform={...N.agentPlatform,connected:!0},HI(N.agentPlatform),Vm()}}var ZI=null;function QI(e,t=20){ZI&&clearInterval(ZI);let n=0;ZI=setInterval(async()=>{if(n++,n>t||!e){clearInterval(ZI),ZI=null;return}try{let t=xI((await chrome.storage.local.get([`pairedAgents`])).pairedAgents).find(t=>t.id===e);if(!t){clearInterval(ZI),ZI=null;return}let n=await WI(t.url,t.token);if(n.online){clearInterval(ZI),ZI=null,n.version&&N.agentVersions.set(e,n.version),n.workdir&&N.agentWorkdirs.set(e,n.workdir),n.homeDir&&N.agentHomeDirs.set(e,n.homeDir);let r=KI(n.platformName,n.arch);r&&N.agentSystemInfos.set(e,r),n.workdir&&JI(e,n.workdir),await XI(t),qI(e,!0)}}catch{}},3e3)}function $I(){let e=document.getElementById(`headerAgentDropdown`),t=document.getElementById(`headerAgentWrapper`);if(!e||!t)return;let n=document.body.clientWidth,r=t.getBoundingClientRect(),i=e.offsetWidth;n<312?(e.style.minWidth=n-16+`px`,e.style.maxWidth=n-16+`px`):(e.style.minWidth=``,e.style.maxWidth=``);let a=r.right+20-i,o=n-i-8;a=Math.max(8,Math.min(o,a)),e.style.left=a-r.left+`px`}async function eL(){let e=document.getElementById(`headerAgentTrigger`),t=document.getElementById(`headerAgentDropdown`),n=document.getElementById(`agentDdCopyBtn`),i=document.getElementById(`agentDdAddBtn`),a=document.getElementById(`agentDdRestartBtn`),o=document.getElementById(`agentDdUpdateBtn`),s=document.getElementById(`agentDdStopBtn`),c=document.getElementById(`agentDdRefreshBtn`);if(!e||!t)return;e.addEventListener(`click`,e=>{e.stopPropagation();let n=t.style.display!==`none`;t.style.display=n?`none`:``,n||($I(),HI(N.agentPlatform||{}),YI())}),document.addEventListener(`click`,n=>{!t.contains(n.target)&&n.target!==e&&(t.style.display=`none`)}),n.addEventListener(`click`,async e=>{e.stopPropagation(),N.activeAgentId;let t=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=xI(t.pairedAgents).find(e=>e.id===t.activeAgentId);n?.url&&(await navigator.clipboard.writeText(n.url),L(r(`sidePanel.agentAddressCopied`),`success`))}),i.addEventListener(`click`,async()=>{t.style.display=`none`,await chrome.storage.local.set({optionsInitialTab:`agent`});let e=await chrome.tabs.query({}),n=chrome.runtime.getURL(`options/index.html`),r=e.find(e=>e.url&&e.url.startsWith(n));if(r){chrome.tabs.update(r.id,{active:!0});try{chrome.tabs.sendMessage(r.id,{type:`SWITCH_TAB`,tab:`agent`})}catch{}}else chrome.runtime.openOptionsPage()}),a.addEventListener(`click`,async()=>{t.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=xI(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=n?.name||r(`sidePanel.unknownAgent`),a=n?.url||r(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(r(`sidePanel.restartAgentConfirm`,{name:i,url:a}),r(`sidePanel.restartAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_RESTART`},async e=>{e?.success?(L(r(`sidePanel.agentRestarting`),`success`),N.agentPlatform={...N.agentPlatform,connected:!1},await HI(N.agentPlatform,!0),n?.id&&qI(n.id,!1),QI(n?.id)):L(r(`sidePanel.restartFailed`,{error:e?.error||r(`sidePanel.unknownError`)}),`error`)})}catch(e){L(r(`sidePanel.restartRequestFailed`,{error:e.message}),`error`)}}),o.addEventListener(`click`,async()=>{t.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=xI(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=n?.name||r(`sidePanel.unknownAgent`),a=n?.url||r(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(r(`sidePanel.updateAgentConfirm`,{name:i,url:a}),r(`sidePanel.updateAgentTitle`))){L(r(`sidePanel.agentUpdating`),`info`);try{chrome.runtime.sendMessage({type:`AGENT_UPDATE`},async e=>{e?.success?(L(r(`sidePanel.agentUpdateRestarting`),`success`),N.agentPlatform={...N.agentPlatform,connected:!1},await HI(N.agentPlatform,!0),n?.id&&qI(n.id,!1),QI(n?.id)):L(r(`sidePanel.updateFailed`,{error:e?.error||r(`sidePanel.unknownError`)}),`error`)})}catch(e){L(r(`sidePanel.updateRequestFailed`,{error:e.message}),`error`)}}}),s.addEventListener(`click`,async()=>{t.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=xI(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=n?.name||r(`sidePanel.unknownAgent`),a=n?.url||r(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(r(`sidePanel.stopAgentConfirm`,{name:i,url:a}),r(`sidePanel.stopAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_STOP`},async e=>{e?.success?(L(r(`sidePanel.agentStopped`),`success`),N.agentPlatform={...N.agentPlatform,connected:!1},await HI(N.agentPlatform,!0),n?.id&&qI(n.id,!1)):L(r(`sidePanel.stopFailed`,{error:e?.error||r(`sidePanel.unknownError`)}),`error`)})}catch(e){L(r(`sidePanel.stopRequestFailed`,{error:e.message}),`error`)}}),c&&c.addEventListener(`click`,async()=>{document.querySelectorAll(`.agent-dd-item-dot`).forEach(e=>{e.classList.remove(`online`,`offline`),e.classList.add(`checking`)}),document.querySelectorAll(`.agent-dd-item-status`).forEach(e=>{e.textContent=r(`sidePanel.agentChecking`)}),await YI(),L(r(`sidePanel.agentStatusRefreshed`),`success`)}),document.getElementById(`agentDdList`).addEventListener(`click`,async e=>{let t=e.target.closest(`.agent-dd-tool-btn`),n=e.target.closest(`.agent-dd-item`);if(t){e.stopPropagation(),l(t.dataset.action,t.dataset.id);return}n&&!n.classList.contains(`disabled`)&&!n.classList.contains(`active`)&&(e.stopPropagation(),l(`switch`,n.dataset.agentId))});async function l(e,t){let n=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),i=xI(n.pairedAgents);switch(e){case`enable`:i=i.map(e=>e.id===t?{...e,disabled:!1}:e),await chrome.storage.local.set({pairedAgents:i});break;case`disable`:{i=i.map(e=>e.id===t?{...e,disabled:!0}:e);let e=n.activeAgentId;n.activeAgentId===t&&(e=i.find(e=>e.id!==t&&!e.disabled)?.id||null),await chrome.storage.local.set({pairedAgents:i,activeAgentId:e||``}),e?chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:e}):chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break}case`switch`:await chrome.storage.local.set({activeAgentId:t}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:t});break;case`disconnect`:await chrome.storage.local.set({activeAgentId:``}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break;case`delete`:{let e=i.find(e=>e.id===t);if(!await window.showCustomConfirm(r(`sidePanel.deleteAgentTitle`),r(`sidePanel.deleteAgentConfirm`,{name:e?.name||t})))return;i=i.filter(e=>e.id!==t);let a=n.activeAgentId===t?i.find(e=>!e.disabled)?.id||null:n.activeAgentId;await chrome.storage.local.set({pairedAgents:i,activeAgentId:a||``}),a?chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:a}):chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break}}let a=document.getElementById(`headerAgentDropdown`);a&&(a.style.display=`none`)}}var tL=new Map,nL=8;function rL(e,t){for(tL.has(e)&&tL.delete(e),tL.set(e,t);tL.size>nL;)tL.delete(tL.keys().next().value)}function iL(e){let t=tL.get(e);if(t!==void 0)return tL.delete(e),tL.set(e,t),t}function aL(e){tL.delete(e)}document.addEventListener(`DOMContentLoaded`,async()=>{await ut(),mt(()=>{Jt()}),Gc(),await Promise.allSettled([i().then(()=>{o(),Da(),c(()=>{o(),Da()})}),Ot(),lC(),Ti()]),window.__tableBlocks=[],chrome.runtime.onMessage.addListener(e=>{if(e.type===`SCHEDULED_SESSION_UPDATED`){let t=e.sessionId;t===N.activeSessionId?_C().catch(()=>{}):t&&(Di(t).catch(()=>{}),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:t}})));return}if(e.type===`CLOSE_SIDEPANEL`){a.debug(`[SidePanel] recei to CLOSE_SIDEPANEL,closesidebar`);try{window.close()}catch{}return}if(e.type===`SELECTION_AI_SEARCH`&&e.prompt&&(a.debug(`[SidePanel] received selectedtext AI search:`,e.selectedText?.substring(0,50)),e.selectedText&&zI(e.selectedText),HC(e.prompt,e.selectedText),chrome.storage.session.remove(`pendingSelectionSearch`).catch(()=>{})),e.type===`FILL_SIDEPANEL_INPUT`&&e.text&&(a.debug(`[SidePanel] received follow-upfill:`,e.text?.substring(0,50)),UC(e.text),chrome.storage.session.remove(`pendingFillInput`).catch(()=>{})),e.type===`DIRECT_SEND`&&e.text&&(a.debug(`[SidePanel] received directsend:`,e.text?.substring(0,50)),e.selectedText&&zI(e.selectedText),WC(e.text,e.selectedText||``),chrome.storage.session.remove(`pendingDirectSend`).catch(()=>{})),e.type===`AGENT_STATUS_CHANGE`&&(a.debug(`[SidePanel] recei to Agent status change:`,e.connected,e.status),N.agentPlatform={...N.agentPlatform,connected:e.connected},HI(N.agentPlatform),Vm(),Aa(),e.connected&&XI()),e.type===`AGENT_CONNECTION_CHANGED`){if(a.debug(`[SidePanel] recei to Agent connection statuschanged:`,e.connected,e.agentId),!e.connected){N.agentPlatform={connected:!1},HI(N.agentPlatform),Vm(),Aa();return}e.agentId&&(async()=>{try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=xI(e.pairedAgents).find(t=>t.id===e.activeAgentId&&!t.disabled);if(!t){N.agentPlatform={connected:!1},HI(N.agentPlatform),Vm(),Aa(),gv();return}if(t.token)try{let n=await fetch(`${t.url}/api/status/detail`,{cache:`no-cache`,headers:{Authorization:`Bearer ${t.token}`}});if(n.ok){let t=await n.json();if(t.success){N.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&&N.agentVersions.set(e.activeAgentId,t.version),t.workdir&&N.agentWorkdirs.set(e.activeAgentId,t.workdir),t.homeDir&&N.agentHomeDirs.set(e.activeAgentId,t.homeDir);let n=KI(t.platformName||t.platform,t.arch);n&&N.agentSystemInfos.set(e.activeAgentId,n)}else N.agentPlatform={connected:!1}}else N.agentPlatform={connected:!1}}catch{N.agentPlatform={connected:!1}}else try{let n=await fetch(`${t.url}/api/status`,{cache:`no-cache`});if(n.ok){let t=await n.json();N.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&&N.agentVersions.set(e.activeAgentId,t.version);let r=KI(t.platformName||t.platform,t.arch);r&&N.agentSystemInfos.set(e.activeAgentId,r)}else N.agentPlatform={connected:!1}}catch{N.agentPlatform={connected:!1}}}catch{N.agentPlatform={connected:!1}}HI(N.agentPlatform),Vm(),Aa(),gv()})()}e.type===`SCREENSHOT_RESULT`&&e.dataUrl&&(a.debug(`[SidePanel] received pageshortcutscreenshotresult:`,e.mode),Km(e.dataUrl,e.mode,e.rect))});async function e(e){try{let t=await chrome.sidePanel.getOptions({tabId:e});return typeof t?.enabled==`boolean`?t.enabled:(await chrome.sidePanel.getOptions({}))?.enabled!==!1}catch{return!0}}chrome.tabs.onActivated.addListener(async t=>{if(a.debug(`[SidePanel] Tab switch, new Tab ID:`,t.tabId),!await e(t.tabId)){a.debug(`[SidePanel] Tab 无侧边栏,保持 currentTabId:`,N.currentTabId);return}N.currentTabId=t.tabId}),chrome.tabs.onUpdated.addListener(async(e,t)=>{t.status===`complete`&&N.currentTabId===e&&a.debug(`[SidePanel] current Tab page update:`,t)}),typeof marked<`u`&&(marked.setOptions({breaks:!0,gfm:!0}),a.debug(`[SidePanel] Marked library loaded`));let t=document.getElementById(`userInput`),n=document.getElementById(`sendBtn`),s=document.getElementById(`clearChatBtn`),l=document.getElementById(`exportChatBtn`),u=document.getElementById(`chatContainer`),d=document.getElementById(`tempDisplay`),f=document.getElementById(`tempDropdown`),p=document.getElementById(`tempPresetList`),m=document.getElementById(`tempSlider`),h=document.getElementById(`tempNumberInput`);function g(){if(!t||N.isScrolling)return;t.style.height=`auto`;let e=t.scrollHeight;e<=50?t.style.height=``:t.style.height=Math.min(e,100)+`px`,Tt()}chrome.storage.local.get([`temperature`,`topP`,`selectedTempIndex`],e=>{(!N.activeAgentId||N.activeAgentId==="default")&&(e.temperature!==void 0&&(N.temperature=e.temperature),e.topP!==void 0&&(N.topP=e.topP),e.selectedTempIndex!==void 0&&(N.selectedTempIndex=e.selectedTempIndex)),_()});function _(){m&&(m.value=N.temperature),h&&(h.value=N.temperature.toFixed(2));let e=document.getElementById(`tempIconValue`);e&&(e.textContent=N.temperature.toFixed(2)),y()}function v(){let e=0,t=Math.abs(Rn[0].temp-N.temperature);for(let n=1;n<Rn.length;n++){let r=Math.abs(Rn[n].temp-N.temperature);r<t&&(t=r,e=n)}return e}function y(){let e=v();p.innerHTML=Rn.map((t,n)=>`
2770
+ `}).join(``);let o=document.getElementById(`agentDdRestartBtn`),s=document.getElementById(`agentDdUpdateBtn`),c=document.getElementById(`agentDdStopBtn`),l=!!(e&&n);o&&(o.disabled=!l),s&&(s.disabled=!l),c&&(c.disabled=!l)}async function gL(e,t){if(t)try{let n=new AbortController;setTimeout(()=>n.abort(),2e3);let r=await fetch(`${e}/api/status/detail`,{signal:n.signal,headers:{Authorization:`Bearer ${t}`}});if(r.ok){let e=await r.json();if(e.success)return{online:!0,version:e.version||null,workdir:e.workdir||null,homeDir:e.homeDir||null,platformName:e.platformName||e.platform||null,arch:e.arch||null}}}catch{}try{let t=new AbortController;setTimeout(()=>t.abort(),2e3);let n=await fetch(`${e}/api/status`,{signal:t.signal});if(!n.ok)return{online:!1,version:null,workdir:null,homeDir:null,platformName:null,arch:null};let r=await n.json();return{online:!0,version:r.version||null,workdir:null,homeDir:null,platformName:r.platformName||r.platform||null,arch:r.arch||null}}catch{return{online:!1,version:null,workdir:null,homeDir:null,platformName:null,arch:null}}}function _L(e,t){return e?t&&e.startsWith(t)?`~`+e.substring(t.length):e:``}function vL(e,t){return e||``}function yL(e,t){let n=document.querySelector(`.agent-dd-item[data-agent-id="${e}"]`);if(!n)return;let i=n.querySelector(`.agent-dd-item-dot`),a=n.querySelector(`.agent-dd-item-status`),o=n.classList.contains(`active`);i&&(i.classList.remove(`checking`,`connected`,`disconnected`,`online`,`offline`),i.classList.add(o?t?`connected`:`disconnected`:t?`online`:`offline`)),a&&(o?a.textContent=r(t?`sidePanel.agentConnected`:`sidePanel.notConnected`):a.textContent===r(`sidePanel.agentChecking`)&&(a.textContent=r(t?`sidePanel.agentOnline`:`sidePanel.agentOffline`)))}function bL(e,t){if(!t)return;let n=document.querySelector(`.agent-dd-item[data-agent-id="${e}"]`);if(!n)return;let i=n.querySelector(`.agent-dd-item-info`);if(!i)return;let a=_L(t,N.agentHomeDirs.get(e)),o=i.querySelector(`.agent-dd-item-workdir`);o?(o.textContent=a,o.title=r(`sidePanel.workingDirectory`,{path:t})):(o=document.createElement(`span`),o.className=`agent-dd-item-workdir`,o.title=r(`sidePanel.workingDirectory`,{path:t}),o.textContent=a,i.appendChild(o))}window.updateAgentItemWorkdir=bL;async function xL(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=KI(e.pairedAgents),n=e.activeAgentId;await Promise.all(t.filter(e=>!e.disabled).map(async e=>{let t=await gL(e.url,e.token),r=t.online;t.version&&N.agentVersions.set(e.id,t.version),t.workdir&&N.agentWorkdirs.set(e.id,t.workdir),t.homeDir&&N.agentHomeDirs.set(e.id,t.homeDir);let i=vL(t.platformName,t.arch);i&&N.agentSystemInfos.set(e.id,i),t.workdir&&bL(e.id,t.workdir),yL(e.id,r),e.id===n&&r!==(N.agentPlatform?.connected===!0)&&(N.agentPlatform={...N.agentPlatform,connected:r},mL(N.agentPlatform,!0),r&&SL(e))}))}catch{}}async function SL(e){try{let t=e;if(!t){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=KI(e.pairedAgents),r=e.activeAgentId;t=n.find(e=>e.id===r&&!e.disabled)}if(!t||!t.url){N.agentPlatform={...N.agentPlatform,connected:!0},mL(N.agentPlatform),Vm();return}if(t.token)try{let e=new AbortController;setTimeout(()=>e.abort(),3e3);let n=await fetch(`${t.url}/api/status/detail`,{signal:e.signal,headers:{Authorization:`Bearer ${t.token}`}});if(n.ok){let e=await n.json();if(e.success){N.agentPlatform={platformName:e.platformName||`Unknown`,platform:e.platform||`unknown`,arch:e.arch||`unknown`,shell:e.shell||`/bin/sh`,homeDir:e.homeDir||``,workdir:e.workdir||``,connected:!0},e.version&&N.agentVersions.set(t.id,e.version),e.workdir&&(N.agentWorkdirs.set(t.id,e.workdir),bL(t.id,e.workdir)),e.homeDir&&N.agentHomeDirs.set(t.id,e.homeDir);let n=vL(e.platformName||e.platform,e.arch);n&&N.agentSystemInfos.set(t.id,n),mL(N.agentPlatform),Vm();return}}}catch{}try{let e=new AbortController;setTimeout(()=>e.abort(),3e3);let n=await fetch(`${t.url}/api/status`,{signal:e.signal});if(n.ok){let e=await n.json();N.agentPlatform={platformName:e.platformName||e.platform||`Unknown`,platform:e.platform||`unknown`,arch:e.arch||`unknown`,connected:!0},mL(N.agentPlatform),Vm();return}}catch{}N.agentPlatform={...N.agentPlatform,connected:!0},mL(N.agentPlatform),Vm()}catch{N.agentPlatform={...N.agentPlatform,connected:!0},mL(N.agentPlatform),Vm()}}var CL=null;function wL(e,t=20){CL&&clearInterval(CL);let n=0;CL=setInterval(async()=>{if(n++,n>t||!e){clearInterval(CL),CL=null;return}try{let t=KI((await chrome.storage.local.get([`pairedAgents`])).pairedAgents).find(t=>t.id===e);if(!t){clearInterval(CL),CL=null;return}let n=await gL(t.url,t.token);if(n.online){clearInterval(CL),CL=null,n.version&&N.agentVersions.set(e,n.version),n.workdir&&N.agentWorkdirs.set(e,n.workdir),n.homeDir&&N.agentHomeDirs.set(e,n.homeDir);let r=vL(n.platformName,n.arch);r&&N.agentSystemInfos.set(e,r),n.workdir&&bL(e,n.workdir),await SL(t),yL(e,!0)}}catch{}},3e3)}function TL(){let e=document.getElementById(`headerAgentDropdown`),t=document.getElementById(`headerAgentWrapper`);if(!e||!t)return;let n=document.body.clientWidth,r=t.getBoundingClientRect(),i=e.offsetWidth;n<312?(e.style.minWidth=n-16+`px`,e.style.maxWidth=n-16+`px`):(e.style.minWidth=``,e.style.maxWidth=``);let a=r.right+20-i,o=n-i-8;a=Math.max(8,Math.min(o,a)),e.style.left=a-r.left+`px`}async function EL(){let e=document.getElementById(`headerAgentTrigger`),t=document.getElementById(`headerAgentDropdown`),n=document.getElementById(`agentDdCopyBtn`),i=document.getElementById(`agentDdAddBtn`),a=document.getElementById(`agentDdRestartBtn`),o=document.getElementById(`agentDdUpdateBtn`),s=document.getElementById(`agentDdStopBtn`),c=document.getElementById(`agentDdRefreshBtn`);if(!e||!t)return;e.addEventListener(`click`,e=>{e.stopPropagation();let n=t.style.display!==`none`;t.style.display=n?`none`:``,n||(TL(),mL(N.agentPlatform||{}),xL())}),document.addEventListener(`click`,n=>{!t.contains(n.target)&&n.target!==e&&(t.style.display=`none`)}),n.addEventListener(`click`,async e=>{e.stopPropagation(),N.activeAgentId;let t=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=KI(t.pairedAgents).find(e=>e.id===t.activeAgentId);n?.url&&(await navigator.clipboard.writeText(n.url),L(r(`sidePanel.agentAddressCopied`),`success`))}),i.addEventListener(`click`,async()=>{t.style.display=`none`,await chrome.storage.local.set({optionsInitialTab:`agent`});let e=await chrome.tabs.query({}),n=chrome.runtime.getURL(`options/index.html`),r=e.find(e=>e.url&&e.url.startsWith(n));if(r){chrome.tabs.update(r.id,{active:!0});try{chrome.tabs.sendMessage(r.id,{type:`SWITCH_TAB`,tab:`agent`})}catch{}}else chrome.runtime.openOptionsPage()}),a.addEventListener(`click`,async()=>{t.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=KI(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=n?.name||r(`sidePanel.unknownAgent`),a=n?.url||r(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(r(`sidePanel.restartAgentConfirm`,{name:i,url:a}),r(`sidePanel.restartAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_RESTART`},async e=>{e?.success?(L(r(`sidePanel.agentRestarting`),`success`),N.agentPlatform={...N.agentPlatform,connected:!1},await mL(N.agentPlatform,!0),n?.id&&yL(n.id,!1),wL(n?.id)):L(r(`sidePanel.restartFailed`,{error:e?.error||r(`sidePanel.unknownError`)}),`error`)})}catch(e){L(r(`sidePanel.restartRequestFailed`,{error:e.message}),`error`)}}),o.addEventListener(`click`,async()=>{t.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=KI(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=n?.name||r(`sidePanel.unknownAgent`),a=n?.url||r(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(r(`sidePanel.updateAgentConfirm`,{name:i,url:a}),r(`sidePanel.updateAgentTitle`))){L(r(`sidePanel.agentUpdating`),`info`);try{chrome.runtime.sendMessage({type:`AGENT_UPDATE`},async e=>{e?.success?(L(r(`sidePanel.agentUpdateRestarting`),`success`),N.agentPlatform={...N.agentPlatform,connected:!1},await mL(N.agentPlatform,!0),n?.id&&yL(n.id,!1),wL(n?.id)):L(r(`sidePanel.updateFailed`,{error:e?.error||r(`sidePanel.unknownError`)}),`error`)})}catch(e){L(r(`sidePanel.updateRequestFailed`,{error:e.message}),`error`)}}}),s.addEventListener(`click`,async()=>{t.style.display=`none`;let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=KI(e.pairedAgents).find(t=>t.id===e.activeAgentId),i=n?.name||r(`sidePanel.unknownAgent`),a=n?.url||r(`sidePanel.unknownAgent`);if(await window.showCustomConfirm(r(`sidePanel.stopAgentConfirm`,{name:i,url:a}),r(`sidePanel.stopAgentTitle`)))try{chrome.runtime.sendMessage({type:`AGENT_STOP`},async e=>{e?.success?(L(r(`sidePanel.agentStopped`),`success`),N.agentPlatform={...N.agentPlatform,connected:!1},await mL(N.agentPlatform,!0),n?.id&&yL(n.id,!1)):L(r(`sidePanel.stopFailed`,{error:e?.error||r(`sidePanel.unknownError`)}),`error`)})}catch(e){L(r(`sidePanel.stopRequestFailed`,{error:e.message}),`error`)}}),c&&c.addEventListener(`click`,async()=>{document.querySelectorAll(`.agent-dd-item-dot`).forEach(e=>{e.classList.remove(`online`,`offline`),e.classList.add(`checking`)}),document.querySelectorAll(`.agent-dd-item-status`).forEach(e=>{e.textContent=r(`sidePanel.agentChecking`)}),await xL(),L(r(`sidePanel.agentStatusRefreshed`),`success`)}),document.getElementById(`agentDdList`).addEventListener(`click`,async e=>{let t=e.target.closest(`.agent-dd-tool-btn`),n=e.target.closest(`.agent-dd-item`);if(t){e.stopPropagation(),l(t.dataset.action,t.dataset.id);return}n&&!n.classList.contains(`disabled`)&&!n.classList.contains(`active`)&&(e.stopPropagation(),l(`switch`,n.dataset.agentId))});async function l(e,t){let n=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),i=KI(n.pairedAgents);switch(e){case`enable`:i=i.map(e=>e.id===t?{...e,disabled:!1}:e),await chrome.storage.local.set({pairedAgents:i});break;case`disable`:{i=i.map(e=>e.id===t?{...e,disabled:!0}:e);let e=n.activeAgentId;n.activeAgentId===t&&(e=i.find(e=>e.id!==t&&!e.disabled)?.id||null),await chrome.storage.local.set({pairedAgents:i,activeAgentId:e||``}),e?chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:e}):chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break}case`switch`:await chrome.storage.local.set({activeAgentId:t}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:t});break;case`disconnect`:await chrome.storage.local.set({activeAgentId:``}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break;case`delete`:{let e=i.find(e=>e.id===t);if(!await window.showCustomConfirm(r(`sidePanel.deleteAgentTitle`),r(`sidePanel.deleteAgentConfirm`,{name:e?.name||t})))return;i=i.filter(e=>e.id!==t);let a=n.activeAgentId===t?i.find(e=>!e.disabled)?.id||null:n.activeAgentId;await chrome.storage.local.set({pairedAgents:i,activeAgentId:a||``}),a?chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:a}):chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break}}let a=document.getElementById(`headerAgentDropdown`);a&&(a.style.display=`none`)}}var DL=new Map,OL=8;function kL(e,t){for(DL.has(e)&&DL.delete(e),DL.set(e,t);DL.size>OL;)DL.delete(DL.keys().next().value)}function AL(e){let t=DL.get(e);if(t!==void 0)return DL.delete(e),DL.set(e,t),t}function jL(e){DL.delete(e)}document.addEventListener(`DOMContentLoaded`,async()=>{await ut(),mt(()=>{Jt()}),Gc(),await Promise.allSettled([i().then(()=>{o(),Da(),c(()=>{o(),Da()})}),Ot(),lC(),Ti()]),window.__tableBlocks=[],chrome.runtime.onMessage.addListener(e=>{if(e.type===`SCHEDULED_SESSION_UPDATED`){let t=e.sessionId;t===N.activeSessionId?_C().catch(()=>{}):t&&(Di(t).catch(()=>{}),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:t}})));return}if(e.type===`CLOSE_SIDEPANEL`){a.debug(`[SidePanel] recei to CLOSE_SIDEPANEL,closesidebar`);try{window.close()}catch{}return}if(e.type===`SELECTION_AI_SEARCH`&&e.prompt&&(a.debug(`[SidePanel] received selectedtext AI search:`,e.selectedText?.substring(0,50)),e.selectedText&&uL(e.selectedText),HC(e.prompt,e.selectedText),chrome.storage.session.remove(`pendingSelectionSearch`).catch(()=>{})),e.type===`FILL_SIDEPANEL_INPUT`&&e.text&&(a.debug(`[SidePanel] received follow-upfill:`,e.text?.substring(0,50)),UC(e.text),chrome.storage.session.remove(`pendingFillInput`).catch(()=>{})),e.type===`DIRECT_SEND`&&e.text&&(a.debug(`[SidePanel] received directsend:`,e.text?.substring(0,50)),e.selectedText&&uL(e.selectedText),WC(e.text,e.selectedText||``),chrome.storage.session.remove(`pendingDirectSend`).catch(()=>{})),e.type===`AGENT_STATUS_CHANGE`&&(a.debug(`[SidePanel] recei to Agent status change:`,e.connected,e.status),N.agentPlatform={...N.agentPlatform,connected:e.connected},mL(N.agentPlatform),Vm(),Aa(),e.connected&&SL()),e.type===`AGENT_CONNECTION_CHANGED`){if(a.debug(`[SidePanel] recei to Agent connection statuschanged:`,e.connected,e.agentId),!e.connected){N.agentPlatform={connected:!1},mL(N.agentPlatform),Vm(),Aa();return}e.agentId&&(async()=>{try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=KI(e.pairedAgents).find(t=>t.id===e.activeAgentId&&!t.disabled);if(!t){N.agentPlatform={connected:!1},mL(N.agentPlatform),Vm(),Aa(),gv();return}if(t.token)try{let n=await fetch(`${t.url}/api/status/detail`,{cache:`no-cache`,headers:{Authorization:`Bearer ${t.token}`}});if(n.ok){let t=await n.json();if(t.success){N.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&&N.agentVersions.set(e.activeAgentId,t.version),t.workdir&&N.agentWorkdirs.set(e.activeAgentId,t.workdir),t.homeDir&&N.agentHomeDirs.set(e.activeAgentId,t.homeDir);let n=vL(t.platformName||t.platform,t.arch);n&&N.agentSystemInfos.set(e.activeAgentId,n)}else N.agentPlatform={connected:!1}}else N.agentPlatform={connected:!1}}catch{N.agentPlatform={connected:!1}}else try{let n=await fetch(`${t.url}/api/status`,{cache:`no-cache`});if(n.ok){let t=await n.json();N.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&&N.agentVersions.set(e.activeAgentId,t.version);let r=vL(t.platformName||t.platform,t.arch);r&&N.agentSystemInfos.set(e.activeAgentId,r)}else N.agentPlatform={connected:!1}}catch{N.agentPlatform={connected:!1}}}catch{N.agentPlatform={connected:!1}}mL(N.agentPlatform),Vm(),Aa(),gv()})()}e.type===`SCREENSHOT_RESULT`&&e.dataUrl&&(a.debug(`[SidePanel] received pageshortcutscreenshotresult:`,e.mode),Km(e.dataUrl,e.mode,e.rect))});async function e(e){try{let t=await chrome.sidePanel.getOptions({tabId:e});return typeof t?.enabled==`boolean`?t.enabled:(await chrome.sidePanel.getOptions({}))?.enabled!==!1}catch{return!0}}chrome.tabs.onActivated.addListener(async t=>{if(a.debug(`[SidePanel] Tab switch, new Tab ID:`,t.tabId),!await e(t.tabId)){a.debug(`[SidePanel] Tab 无侧边栏,保持 currentTabId:`,N.currentTabId);return}N.currentTabId=t.tabId}),chrome.tabs.onUpdated.addListener(async(e,t)=>{t.status===`complete`&&N.currentTabId===e&&a.debug(`[SidePanel] current Tab page update:`,t)}),typeof marked<`u`&&(marked.setOptions({breaks:!0,gfm:!0}),a.debug(`[SidePanel] Marked library loaded`));let t=document.getElementById(`userInput`),n=document.getElementById(`sendBtn`),s=document.getElementById(`clearChatBtn`),l=document.getElementById(`exportChatBtn`),u=document.getElementById(`chatContainer`),d=document.getElementById(`tempDisplay`),f=document.getElementById(`tempDropdown`),p=document.getElementById(`tempPresetList`),m=document.getElementById(`tempSlider`),h=document.getElementById(`tempNumberInput`);function g(){if(!t||N.isScrolling)return;t.style.height=`auto`;let e=t.scrollHeight;e<=50?t.style.height=``:t.style.height=Math.min(e,100)+`px`,Tt()}chrome.storage.local.get([`temperature`,`topP`,`selectedTempIndex`],e=>{(!N.activeAgentId||N.activeAgentId==="default")&&(e.temperature!==void 0&&(N.temperature=e.temperature),e.topP!==void 0&&(N.topP=e.topP),e.selectedTempIndex!==void 0&&(N.selectedTempIndex=e.selectedTempIndex)),_()});function _(){m&&(m.value=N.temperature),h&&(h.value=N.temperature.toFixed(2));let e=document.getElementById(`tempIconValue`);e&&(e.textContent=N.temperature.toFixed(2)),y()}function v(){let e=0,t=Math.abs(Rn[0].temp-N.temperature);for(let n=1;n<Rn.length;n++){let r=Math.abs(Rn[n].temp-N.temperature);r<t&&(t=r,e=n)}return e}function y(){let e=v();p.innerHTML=Rn.map((t,n)=>`
2771
2771
  <div class="temp-preset-item ${n===e?`selected`:``}" data-index="${n}">
2772
2772
  <div class="temp-preset-radio"></div>
2773
2773
  <div class="temp-preset-info">
@@ -2776,15 +2776,15 @@ Are you sure you want to stop the agent service? You will not be able to connect
2776
2776
  </div>
2777
2777
  <div class="temp-preset-value">${t.temp.toFixed(2)}</div>
2778
2778
  </div>
2779
- `).join(``),p.querySelectorAll(`.temp-preset-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),b(parseInt(e.dataset.index))})})}function b(e){let t=Rn[e];t&&(N.selectedTempIndex=e,N.temperature=t.temp,_(),kI(N.temperature,N.topP,N.selectedTempIndex))}m.addEventListener(`input`,e=>{e.stopPropagation();let t=parseFloat(e.target.value);isNaN(t)&&(t=0),t=Math.max(0,Math.min(1,t)),N.temperature=t,h.value=t.toFixed(2);let n=document.getElementById(`tempIconValue`);n&&(n.textContent=t.toFixed(2)),y(),kI(N.temperature,N.topP,v())}),h.addEventListener(`change`,e=>{e.stopPropagation();let t=parseFloat(e.target.value);isNaN(t)&&(t=0),t=Math.max(0,Math.min(1,t)),N.temperature=t,m.value=t,h.value=t.toFixed(2);let n=document.getElementById(`tempIconValue`);n&&(n.textContent=t.toFixed(2)),y(),kI(N.temperature,N.topP,v())}),d&&f&&(d.addEventListener(`click`,e=>{e.stopPropagation(),f.classList.toggle(`show`)}),document.addEventListener(`click`,e=>{let t=document.querySelector(`.temp-selector`);t&&!t.contains(e.target)&&f.classList.remove(`show`)})),u.addEventListener(`mousedown`,e=>{N.lastMouseX=e.clientX,N.lastMouseY=e.clientY}),u.addEventListener(`mouseup`,e=>{N.lastMouseX=e.clientX,N.lastMouseY=e.clientY,N.enableSelectionQuery&&setTimeout(()=>{let e=window.getSelection();if(e&&!e.isCollapsed&&e.toString().trim()){let t=e.toString().trim();u.contains(e.anchorNode)&&(N.lastSelectedText=t,N.currentSelectionRange=e.getRangeAt(0).cloneRange(),zI(t),BI(e,t,N.lastMouseX,N.lastMouseY))}else u.contains(e.anchorNode)||(N.lastSelectedText=``,N.currentSelectionRange=null,window.hideFloatingMenu())},50)});let w=``,T=null;async function E(){try{let e=await new Promise(e=>{chrome.tabs.query({active:!0,currentWindow:!0},t=>e(t))});if(e&&e.length>0){let t=await new Promise(t=>{chrome.tabs.sendMessage(e[0].id,{action:`getSelectedText`},e=>{chrome.runtime.lastError?(console.debug(`[SidePanel] content script not loaded or unreachable:`,chrome.runtime.lastError.message),t(null)):t(e)})});if(!t)return;let n=t?.text||``;n&&n.trim()?n!==w&&(w=n,zI(n.trim())):w=``}}catch{}}function D(){T&&=(clearInterval(T),null),N.enableSelectionQuery&&(T=setInterval(E,500))}D(),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`&&`enableSelectionQuery`in e){N.enableSelectionQuery=e.enableSelectionQuery.newValue;let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=N.enableSelectionQuery),D()}}),await C(),qN(),chrome.storage.local.get([`modelName`,`customModels`,`customPrompts`,`systemPrompt`,`inputHistory`,`agentPlatform`,`enableImageInput`,`imageModelName`,`imageApiBase`,`imageApiKey`,`enableFileInput`],e=>{let t=e.modelName;t&&(N.currentModel=t),N.customPrompts=e.customPrompts||[],N.systemPrompt=e.systemPrompt||``,N.inputHistory=e.inputHistory||[],e.agentPlatform&&(N.agentPlatform=e.agentPlatform),HI(N.agentPlatform),chrome.runtime.sendMessage({type:`TRIGGER_AGENT_HEALTH_CHECK`}).catch(()=>{}),OI(),N.enableImageInput=e.enableImageInput||!1,N.imageModelName=e.imageModelName||``,N.imageApiBase=e.imageApiBase||``,N.imageApiKey=S(e.imageApiKey)||``,N.enableFileInput=!0,zm(),Vm(),hw(),RI(e.customModels,()=>{t&&LI(t)})}),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`){if(e.customModels&&RI(e.customModels.newValue||[],()=>{LI(N.currentModel)}),e.modelName){let t=e.modelName.newValue;t&&(!N.activeAgentId||N.activeAgentId==="default")&&(N.currentModel=t,LI(t))}if(e.enableImageInput&&(N.enableImageInput=e.enableImageInput.newValue,zm()),e.enableFileInput&&(N.enableFileInput=e.enableFileInput.newValue,Vm()),e.enableExecutionLog&&(N.chatConfig.enableExecutionLog=e.enableExecutionLog.newValue),e.showMessageTimestamp){let t=e.showMessageTimestamp.newValue!==!1;N.chatConfig.showMessageTimestamp=t,XC(t)}e.systemPrompt&&(N.systemPrompt=e.systemPrompt.newValue||``),e.imageModelName&&(N.imageModelName=e.imageModelName.newValue||``),e.imageApiBase&&(N.imageApiBase=e.imageApiBase.newValue||``),e.imageApiKey&&(N.imageApiKey=S(e.imageApiKey.newValue)||``)}}),await _C(),await NF();let O=await chrome.storage.session.get([`pendingSelectionSearch`,`pendingFillInput`,`pendingDirectSend`]),k=[];if(O.pendingSelectionSearch&&O.pendingSelectionSearch.selectedText){let{prompt:e,selectedText:t}=O.pendingSelectionSearch;a.debug(`[SidePanel] pending selected textsearch:`,t?.substring(0,50)),zI(t),setTimeout(()=>{HC(e,t)},500),k.push(`pendingSelectionSearch`)}if(O.pendingFillInput&&O.pendingFillInput.text){let{text:e}=O.pendingFillInput;a.debug(`[SidePanel] pending fill trackasktext:`,e?.substring(0,50)),setTimeout(()=>{UC(e)},500),k.push(`pendingFillInput`)}if(O.pendingDirectSend&&O.pendingDirectSend.text){let{text:e,selectedText:t}=O.pendingDirectSend;a.debug(`[SidePanel] pending directsend text:`,e?.substring(0,50)),t&&zI(t),setTimeout(()=>{WC(e,t||``)},500),k.push(`pendingDirectSend`)}k.length>0&&await chrome.storage.session.remove(k);let A=document.getElementById(`userInput`);A&&A.focus(),document.addEventListener(`session-switched`,e=>{let{sessionId:t,previousSessionId:n}=e.detail||{},i=document.getElementById(`chatContainer`),o=document.getElementById(`userInput`);if(!i)return;let s=n&&N.messageHistory?.some(e=>e.resumable);if(n&&!N.pendingCallApiSessionIds.has(n)&&!s){let e=ox(i);e&&rL(n,e)}let c=document.getElementById(`imagePreviewBar`);N.attachedImages.length>0&&c&&c.style.display===`none`&&(N.attachedImages=[]),N.executionLogListener&&=(chrome.runtime.onMessage.removeListener(N.executionLogListener),null),te(),o&&o.focus();let l=N.pendingCallApiSessionIds.has(t)&&!!N.pendingCancelApi,u=iL(t),d=N.messageHistory&&N.messageHistory.length>0;if(u&&!l&&d){if(i.innerHTML=u,aw(i),$t(),sn(),!e.detail?.skipScrollRestore){let e=`scrollPosition_`+(t||`default`);chrome.storage.local.get([e],t=>{t[e]!==void 0&&setTimeout(()=>{let n=document.getElementById(`chatContainer`);n&&(n.scrollTop=t[e])},150)})}Ux();return}if(i.innerHTML=``,d){if(N.messageHistory.forEach(e=>{e.htmlContent?iw(e.htmlContent,e.messageId,e.resumable):YC(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,e.wasRevised,null,e.messageId,[],e.resumable||!1,e.timestamp??null)}),QC(),ew(),$t(),sn(),!N.pendingCallApiSessionIds.has(t)){let e=ox(i);e&&rL(t,e)}Ux()}else{let e=document.createElement(`div`);e.className=`welcome-message`,e.innerHTML=`
2779
+ `).join(``),p.querySelectorAll(`.temp-preset-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),b(parseInt(e.dataset.index))})})}function b(e){let t=Rn[e];t&&(N.selectedTempIndex=e,N.temperature=t.temp,_(),eL(N.temperature,N.topP,N.selectedTempIndex))}m.addEventListener(`input`,e=>{e.stopPropagation();let t=parseFloat(e.target.value);isNaN(t)&&(t=0),t=Math.max(0,Math.min(1,t)),N.temperature=t,h.value=t.toFixed(2);let n=document.getElementById(`tempIconValue`);n&&(n.textContent=t.toFixed(2)),y(),eL(N.temperature,N.topP,v())}),h.addEventListener(`change`,e=>{e.stopPropagation();let t=parseFloat(e.target.value);isNaN(t)&&(t=0),t=Math.max(0,Math.min(1,t)),N.temperature=t,m.value=t,h.value=t.toFixed(2);let n=document.getElementById(`tempIconValue`);n&&(n.textContent=t.toFixed(2)),y(),eL(N.temperature,N.topP,v())}),d&&f&&(d.addEventListener(`click`,e=>{e.stopPropagation(),f.classList.toggle(`show`)}),document.addEventListener(`click`,e=>{let t=document.querySelector(`.temp-selector`);t&&!t.contains(e.target)&&f.classList.remove(`show`)})),u.addEventListener(`mousedown`,e=>{N.lastMouseX=e.clientX,N.lastMouseY=e.clientY}),u.addEventListener(`mouseup`,e=>{N.lastMouseX=e.clientX,N.lastMouseY=e.clientY,N.enableSelectionQuery&&setTimeout(()=>{let e=window.getSelection();if(e&&!e.isCollapsed&&e.toString().trim()){let t=e.toString().trim();u.contains(e.anchorNode)&&(N.lastSelectedText=t,N.currentSelectionRange=e.getRangeAt(0).cloneRange(),uL(t),dL(e,t,N.lastMouseX,N.lastMouseY))}else u.contains(e.anchorNode)||(N.lastSelectedText=``,N.currentSelectionRange=null,window.hideFloatingMenu())},50)});let w=``,T=null;async function E(){try{let e=await new Promise(e=>{chrome.tabs.query({active:!0,currentWindow:!0},t=>e(t))});if(e&&e.length>0){let t=await new Promise(t=>{chrome.tabs.sendMessage(e[0].id,{action:`getSelectedText`},e=>{chrome.runtime.lastError?(console.debug(`[SidePanel] content script not loaded or unreachable:`,chrome.runtime.lastError.message),t(null)):t(e)})});if(!t)return;let n=t?.text||``;n&&n.trim()?n!==w&&(w=n,uL(n.trim())):w=``}}catch{}}function D(){T&&=(clearInterval(T),null),N.enableSelectionQuery&&(T=setInterval(E,500))}D(),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`&&`enableSelectionQuery`in e){N.enableSelectionQuery=e.enableSelectionQuery.newValue;let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=N.enableSelectionQuery),D()}}),await C(),qN(),chrome.storage.local.get([`modelName`,`customModels`,`customPrompts`,`systemPrompt`,`inputHistory`,`agentPlatform`,`enableImageInput`,`imageModelName`,`imageApiBase`,`imageApiKey`,`enableFileInput`],e=>{let t=e.modelName;t&&(N.currentModel=t),N.customPrompts=e.customPrompts||[],N.systemPrompt=e.systemPrompt||``,N.inputHistory=e.inputHistory||[],e.agentPlatform&&(N.agentPlatform=e.agentPlatform),mL(N.agentPlatform),chrome.runtime.sendMessage({type:`TRIGGER_AGENT_HEALTH_CHECK`}).catch(()=>{}),$I(),N.enableImageInput=e.enableImageInput||!1,N.imageModelName=e.imageModelName||``,N.imageApiBase=e.imageApiBase||``,N.imageApiKey=S(e.imageApiKey)||``,N.enableFileInput=!0,zm(),Vm(),hw(),lL(e.customModels,()=>{t&&cL(t)})}),chrome.storage.onChanged.addListener((e,t)=>{if(t===`local`){if(e.customModels&&lL(e.customModels.newValue||[],()=>{cL(N.currentModel)}),e.modelName){let t=e.modelName.newValue;t&&(!N.activeAgentId||N.activeAgentId==="default")&&(N.currentModel=t,cL(t))}if(e.enableImageInput&&(N.enableImageInput=e.enableImageInput.newValue,zm()),e.enableFileInput&&(N.enableFileInput=e.enableFileInput.newValue,Vm()),e.enableExecutionLog&&(N.chatConfig.enableExecutionLog=e.enableExecutionLog.newValue),e.showMessageTimestamp){let t=e.showMessageTimestamp.newValue!==!1;N.chatConfig.showMessageTimestamp=t,XC(t)}e.systemPrompt&&(N.systemPrompt=e.systemPrompt.newValue||``),e.imageModelName&&(N.imageModelName=e.imageModelName.newValue||``),e.imageApiBase&&(N.imageApiBase=e.imageApiBase.newValue||``),e.imageApiKey&&(N.imageApiKey=S(e.imageApiKey.newValue)||``)}}),await _C(),await iI();let O=await chrome.storage.session.get([`pendingSelectionSearch`,`pendingFillInput`,`pendingDirectSend`]),k=[];if(O.pendingSelectionSearch&&O.pendingSelectionSearch.selectedText){let{prompt:e,selectedText:t}=O.pendingSelectionSearch;a.debug(`[SidePanel] pending selected textsearch:`,t?.substring(0,50)),uL(t),setTimeout(()=>{HC(e,t)},500),k.push(`pendingSelectionSearch`)}if(O.pendingFillInput&&O.pendingFillInput.text){let{text:e}=O.pendingFillInput;a.debug(`[SidePanel] pending fill trackasktext:`,e?.substring(0,50)),setTimeout(()=>{UC(e)},500),k.push(`pendingFillInput`)}if(O.pendingDirectSend&&O.pendingDirectSend.text){let{text:e,selectedText:t}=O.pendingDirectSend;a.debug(`[SidePanel] pending directsend text:`,e?.substring(0,50)),t&&uL(t),setTimeout(()=>{WC(e,t||``)},500),k.push(`pendingDirectSend`)}k.length>0&&await chrome.storage.session.remove(k);let A=document.getElementById(`userInput`);A&&A.focus(),document.addEventListener(`session-switched`,e=>{let{sessionId:t,previousSessionId:n}=e.detail||{},i=document.getElementById(`chatContainer`),o=document.getElementById(`userInput`);if(!i)return;let s=n&&N.messageHistory?.some(e=>e.resumable);if(n&&!N.pendingCallApiSessionIds.has(n)&&!s){let e=ox(i);e&&kL(n,e)}let c=document.getElementById(`imagePreviewBar`);N.attachedImages.length>0&&c&&c.style.display===`none`&&(N.attachedImages=[]),N.executionLogListener&&=(chrome.runtime.onMessage.removeListener(N.executionLogListener),null),te(),o&&o.focus();let l=N.pendingCallApiSessionIds.has(t)&&!!N.pendingCancelApi,u=AL(t),d=N.messageHistory&&N.messageHistory.length>0;if(u&&!l&&d){if(i.innerHTML=u,aw(i),$t(),sn(),!e.detail?.skipScrollRestore){let e=`scrollPosition_`+(t||`default`);chrome.storage.local.get([e],t=>{t[e]!==void 0&&setTimeout(()=>{let n=document.getElementById(`chatContainer`);n&&(n.scrollTop=t[e])},150)})}Ux();return}if(i.innerHTML=``,d){if(N.messageHistory.forEach(e=>{e.htmlContent?iw(e.htmlContent,e.messageId,e.resumable):YC(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,e.wasRevised,null,e.messageId,[],e.resumable||!1,e.timestamp??null)}),QC(),ew(),$t(),sn(),!N.pendingCallApiSessionIds.has(t)){let e=ox(i);e&&kL(t,e)}Ux()}else{let e=document.createElement(`div`);e.className=`welcome-message`,e.innerHTML=`
2780
2780
  <div class="icon-wrapper">
2781
2781
  <div class="icon">💬</div>
2782
2782
  </div>
2783
2783
  <h2>${r(`sidePanel.welcomeTitle`)}</h2>
2784
2784
  <p>${r(`sidePanel.welcomeSubtitle`)}</p>
2785
- `,i.appendChild(e)}if(a.debug(`[SidePanel] session-switched: pendingTask?`,l,`pendingSessionIds:`,[...N.pendingCallApiSessionIds],`activeSessionId:`,t,`hasCancelApi:`,!!N.pendingCancelApi),l&&(a.debug(`[SidePanel] switch back tobackground task session,rebuildstreamingoutput element`),XS(t)),uD(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 M(async()=>{let{updateScrollButtonState:e}=await Promise.resolve().then(()=>oS);return{updateScrollButtonState:e}},void 0);r()},150)})}}),document.addEventListener(`session-cache-invalidate`,e=>{let{sessionId:t}=e.detail||{};t&&aL(t)}),document.querySelectorAll(`.model-option`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.value;N.currentModel=n,LI(n),DI(n),dE()})}),document.addEventListener(`agent-model-changed`,()=>{LI(N.currentModel);let e=document.getElementById(`tempSlider`),t=document.getElementById(`tempNumberInput`),n=document.getElementById(`tempIconValue`);e&&(e.value=N.temperature),t&&(t.value=N.temperature.toFixed(2)),n&&(n.textContent=N.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`),_w()),r&&!r.contains(e.target)&&rb();let a=document.getElementById(`fileAtSelector`);if(a&&!a.contains(e.target)&&_P(),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()}});let j=document.getElementById(`stopCompanionBtn`);function ee(){let e=!!(t&&t.value&&t.value.trim());return N.isGenerating&&e}function te(){t&&t.value&&t.value.trim();let e=N.isGenerating,i=ee();n.classList.toggle(`queue-mode`,i),n.classList.toggle(`stop-mode`,e&&!i),i?(n.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h11"/><path d="M3 12h11"/><path d="M3 18h7"/><path d="M17.5 10v8"/><path d="M14.5 15.5L17.5 18.5l3-3"/></svg>`,n.title=r(`queue.enqueueBtn`)):e?(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.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=``,j&&(j.style.display=i?``:`none`,j.disabled=!1,j.style.opacity=``,j.style.cursor=``)}n.addEventListener(`click`,()=>{if(!N.isGenerating){VC();return}t&&t.value&&t.value.trim()?ad():iC(n)}),j?.addEventListener(`click`,()=>iC(j));function ne(e){if(!N.isGenerating)return!1;let t=N.activeSessionId;return t?dd(t)?(ud(t),iC(j&&j.style.display!==`none`?j:e||n)?(L(r(`queue.stopAndSendStarted`),`success`,2500),!0):(fd(t),!0)):(L(r(`queue.stopAndSendEmpty`),`warning`,3e3),!1):!1}function re(e,{isPrimarySend:t=!1}={}){if(!e)return;let n=()=>t&&ee();e.addEventListener(`contextmenu`,t=>{n()||!N.isGenerating||!dd(N.activeSessionId)||(t.preventDefault(),ne(e))});let r=null,i=()=>{r&&=(clearTimeout(r),null)};e.addEventListener(`pointerdown`,t=>{t.pointerType===`mouse`&&t.button!==0||n()||!N.isGenerating||!dd(N.activeSessionId)||(i(),r=setTimeout(()=>{r=null,ne(e)},600))});for(let t of[`pointerup`,`pointerleave`,`pointercancel`])e.addEventListener(t,i)}re(n,{isPrimarySend:!0}),re(j),document.addEventListener(`queue-stop-and-send`,()=>{ne(j&&j.style.display!==`none`?j:n)}),document.addEventListener(`generating-state-changed`,te),t.addEventListener(`input`,te),document.addEventListener(`voice-draft-written`,te);let ie=document.getElementById(`shortcutsBtn`),ae=document.getElementById(`shortcutsModal`),oe=document.getElementById(`shortcutsCloseBtn`);function se(){ae&&(ae.style.display=`flex`)}function ce(){ae&&(ae.style.display=`none`)}ie&&ie.addEventListener(`click`,e=>{e.stopPropagation(),se();let t=document.getElementById(`headerMoreDropdown`);t&&t.classList.remove(`show`)}),oe&&oe.addEventListener(`click`,ce),ae&&ae.addEventListener(`click`,e=>{e.target===ae&&ce()});let le=jO();wx(),Ru({adjustInputHeight:g}).catch(e=>{a.warn(`[SidePanel] initVoiceInput failed:`,e?.message||e)}),document.addEventListener(`keydown`,e=>{if((e.ctrlKey||e.metaKey)&&e.key===`t`){e.preventDefault();let t=document.getElementById(`toolsPopup`);t&&t.style.display!==`none`?pa():fa()}if(e.key===`Escape`&&Nu()){e.preventDefault();return}if(!(e.key===`Escape`&&le.handleEscape())){if(e.key===`Escape`&&ae&&ae.style.display!==`none`){ce();return}if(e.altKey&&e.code===`Slash`){e.preventDefault(),se();return}if(e.altKey&&!e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Um();return}if(e.altKey&&e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Wm();return}if(Xl(e)){e.preventDefault(),ju();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyN`){e.preventDefault(),Xo();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyW`){e.preventDefault(),Xs();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){dw(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`;le.jumpToMessage(t,e.ctrlKey||e.metaKey),le.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(Qy);for(let e=0;e<t.length;e++)if(r=(r+1)%t.length,n(t[r])){ab(t[r]);break}return}let r,i;n?(r=document.getElementById(`agentAtList`),i=N.selectedAgentAtIndex):Qy===`pages`?(r=document.getElementById(`agentPageList`),i=N.selectedPageIndex):Qy===`proxies`?(r=document.getElementById(`agentProxyList`),i=N.selectedProxyAtIndex):Qy===`knowledge`?(r=document.getElementById(`agentKnowledgeList`),i=N.selectedKnowledgeAtIndex):(r=document.getElementById(`agentAtList`),i=N.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?(N.selectedAgentAtIndex=t,yb(a)):Qy===`proxies`?(N.selectedProxyAtIndex=t,yb(a)):Qy===`knowledge`?(N.selectedKnowledgeAtIndex=t,yb(a)):Qy===`pages`?(N.selectedPageIndex=t,Bb(a)):(N.selectedAgentAtIndex=t,yb(a));return}else if(e.key===`ArrowUp`){e.preventDefault();let t=i<0||i===0?o-1:i-1;n?(N.selectedAgentAtIndex=t,yb(a)):Qy===`proxies`?(N.selectedProxyAtIndex=t,yb(a)):Qy===`knowledge`?(N.selectedKnowledgeAtIndex=t,yb(a)):Qy===`pages`?(N.selectedPageIndex=t,Bb(a)):(N.selectedAgentAtIndex=t,yb(a));return}else if(e.key===`Enter`&&i>=0){e.preventDefault(),a[i].click(),(e.ctrlKey||e.metaKey)&&rb();return}else if(e.key===`Escape`){rb();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&&(N.selectedFileAtIndex=e.key===`ArrowDown`?N.selectedFileAtIndex<0?0:(N.selectedFileAtIndex+1)%r:N.selectedFileAtIndex<0||N.selectedFileAtIndex===0?r-1:N.selectedFileAtIndex-1,SP(n));return}if(e.key===`Enter`&&r>0&&N.selectedFileAtIndex>=0){e.preventDefault(),n[N.selectedFileAtIndex].click();return}if(e.key===`Escape`){e.preventDefault(),_P();return}}if(n.style.display!==`none`&&r.classList.contains(`show`)){if(N.showMergedList){let t=r.querySelectorAll(`#promptList .prompt-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),N.selectedPromptIndex<0?N.selectedPromptIndex=0:N.selectedPromptIndex=(N.selectedPromptIndex+1)%n,Sw(t);return}if(e.key===`ArrowUp`){e.preventDefault(),N.selectedPromptIndex<0||N.selectedPromptIndex===0?N.selectedPromptIndex=n-1:--N.selectedPromptIndex,Sw(t);return}if(e.key===`Enter`&&N.selectedPromptIndex>=0){e.preventDefault();let n=t[N.selectedPromptIndex];n.dataset.type===`skill`||n.dataset.type===`mcp`?(n.click(),(e.ctrlKey||e.metaKey)&&_w()):e.ctrlKey||e.metaKey?Cw(n.dataset.code):ww(n.dataset.code);return}if(e.key===`Escape`){_w();return}return}if(N.activeDropdownTab===`skills`){let t=r.querySelectorAll(`#skillList .skill-list-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),N.selectedSkillIndex<0?N.selectedSkillIndex=0:N.selectedSkillIndex=(N.selectedSkillIndex+1)%n,Ww(t);return}if(e.key===`ArrowUp`){e.preventDefault(),N.selectedSkillIndex<0||N.selectedSkillIndex===0?N.selectedSkillIndex=n-1:--N.selectedSkillIndex,Ww(t);return}if(e.key===`Enter`&&N.selectedSkillIndex>=0){e.preventDefault(),t[N.selectedSkillIndex].click(),(e.ctrlKey||e.metaKey)&&_w();return}if(e.key===`Escape`){_w();return}if(e.key===`Tab`){e.preventDefault();let t=document.getElementById(`mcpTab`);t&&t.style.display!==`none`?Zw(`mcp`):Zw(`prompts`);return}return}if(N.activeDropdownTab===`mcp`){let t=r.querySelectorAll(`#mcpList .mcp-list-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),N.selectedMcpServiceIndex<0?N.selectedMcpServiceIndex=0:N.selectedMcpServiceIndex=(N.selectedMcpServiceIndex+1)%n,iT(t);return}if(e.key===`ArrowUp`){e.preventDefault(),N.selectedMcpServiceIndex<0||N.selectedMcpServiceIndex===0?N.selectedMcpServiceIndex=n-1:--N.selectedMcpServiceIndex,iT(t);return}if(e.key===`Enter`&&N.selectedMcpServiceIndex>=0){e.preventDefault(),t[N.selectedMcpServiceIndex].click(),(e.ctrlKey||e.metaKey)&&_w();return}if(e.key===`Escape`){_w();return}if(e.key===`Tab`){e.preventDefault(),Zw(`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(),Zw(`skills`);return}if(n&&n.style.display!==`none`){e.preventDefault(),Zw(`mcp`);return}}if(n!==0&&e.key===`ArrowDown`){e.preventDefault(),N.selectedPromptIndex<0?N.selectedPromptIndex=0:N.selectedPromptIndex=(N.selectedPromptIndex+1)%n,Sw(t);return}if(e.key===`ArrowUp`){e.preventDefault(),N.selectedPromptIndex<0||N.selectedPromptIndex===0?N.selectedPromptIndex=n-1:--N.selectedPromptIndex,Sw(t);return}if(e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&N.selectedPromptIndex>=0){e.preventDefault();let n=t[N.selectedPromptIndex].dataset.code;Cw(n);return}if(e.key===`Enter`&&N.selectedPromptIndex>=0){e.preventDefault();let n=t[N.selectedPromptIndex].dataset.code;ww(n);return}if(e.key===`Escape`){_w();return}}if(e.key===`Escape`){N.inputHistoryIndex>=0&&(N.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(e.key===`ArrowUp`&&N.inputHistoryIndex===-1&&!t.value.trim()&&!Xu()&&DF()){e.preventDefault();return}if(!c&&!l&&!u){let n=iF({key:e.key,value:t.value,caret:t.selectionStart,history:N.inputHistory,index:N.inputHistoryIndex});if(n.handled){e.preventDefault(),N.inputHistoryIndex=n.index,t.value=n.value,t.dispatchEvent(new Event(`input`)),t.setSelectionRange(n.value.length,n.value.length);return}}if(e.key===`Enter`&&!e.shiftKey){if(N.isComposing)return;if(e.preventDefault(),_P(),N.isGenerating){if(e.altKey){Td(t.value);return}ad();return}VC()}}),t.addEventListener(`compositionstart`,()=>{N.isComposing=!0}),t.addEventListener(`compositionend`,()=>{N.isComposing=!1}),t.addEventListener(`paste`,e=>{let t=e.clipboardData?.items;if(t)for(let n of t){if(n.type.startsWith(`image/`)&&N.enableImageInput){e.preventDefault();let t=n.getAsFile();t&&Ap(t);break}if(n.kind===`file`&&N.enableFileInput){e.preventDefault();let t=n.getAsFile();t&&_m([t]);break}}});let ue=document.getElementById(`fileAttachBtn`),de=document.getElementById(`fileInput`);ue&&de&&(ue.addEventListener(`click`,()=>{de.click()}),de.addEventListener(`change`,async()=>{if(de.files.length>0){let e=Array.from(de.files),t=e.filter(e=>e.type.startsWith(`image/`)),n=e.filter(e=>!e.type.startsWith(`image/`));if(t.length>0)if(N.enableImageInput)for(let e of t)await Ap(e);else L(r(`sidePanel.imageNotEnabled`)),_m(t);n.length>0&&_m(n),de.value=``}}));let fe=document.querySelector(`.input-wrapper`),pe=0;fe&&(fe.addEventListener(`dragenter`,e=>{e.preventDefault(),e.stopPropagation(),pe++,fe.classList.add(`drag-over`)}),fe.addEventListener(`dragleave`,e=>{e.preventDefault(),e.stopPropagation(),pe--,pe<=0&&(pe=0,fe.classList.remove(`drag-over`))}),fe.addEventListener(`dragover`,e=>{e.preventDefault(),e.stopPropagation()}),fe.addEventListener(`drop`,async e=>{e.preventDefault(),e.stopPropagation(),pe=0,fe.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){ty([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(N.enableImageInput)for(let e of t)await Ap(e);else L(r(`sidePanel.imageNotEnabled`)),_m(t);n.length>0&&_m(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 me=document.getElementById(`screenshotBtn`);me&&me.addEventListener(`click`,async()=>{if(N.enableImageInput)try{await Um()}catch(e){a.error(`[SidePanel] screenshot failed:`,e),L(r(`sidePanel.screenshotFailed`))}}),Op(),t.addEventListener(`wheel`,e=>{N.isScrolling=!0;let n=t.style.height||t.offsetHeight+`px`;t.style.height=n,t.scrollHeight<=t.clientHeight+10&&(e.preventDefault(),e.stopPropagation()),setTimeout(()=>{N.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]!==`
2785
+ `,i.appendChild(e)}if(a.debug(`[SidePanel] session-switched: pendingTask?`,l,`pendingSessionIds:`,[...N.pendingCallApiSessionIds],`activeSessionId:`,t,`hasCancelApi:`,!!N.pendingCancelApi),l&&(a.debug(`[SidePanel] switch back tobackground task session,rebuildstreamingoutput element`),XS(t)),uD(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 M(async()=>{let{updateScrollButtonState:e}=await Promise.resolve().then(()=>oS);return{updateScrollButtonState:e}},void 0);r()},150)})}}),document.addEventListener(`session-cache-invalidate`,e=>{let{sessionId:t}=e.detail||{};t&&jL(t)}),document.querySelectorAll(`.model-option`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.value;N.currentModel=n,cL(n),QI(n),dE()})}),document.addEventListener(`agent-model-changed`,()=>{cL(N.currentModel);let e=document.getElementById(`tempSlider`),t=document.getElementById(`tempNumberInput`),n=document.getElementById(`tempIconValue`);e&&(e.value=N.temperature),t&&(t.value=N.temperature.toFixed(2)),n&&(n.textContent=N.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`),_w()),r&&!r.contains(e.target)&&rb();let a=document.getElementById(`fileAtSelector`);if(a&&!a.contains(e.target)&&_P(),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()}});let j=document.getElementById(`stopCompanionBtn`);function ee(){let e=!!(t&&t.value&&t.value.trim());return N.isGenerating&&e}function te(){t&&t.value&&t.value.trim();let e=N.isGenerating,i=ee();n.classList.toggle(`queue-mode`,i),n.classList.toggle(`stop-mode`,e&&!i),i?(n.innerHTML=`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h11"/><path d="M3 12h11"/><path d="M3 18h7"/><path d="M17.5 10v8"/><path d="M14.5 15.5L17.5 18.5l3-3"/></svg>`,n.title=r(`queue.enqueueBtn`)):e?(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.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=``,j&&(j.style.display=i?``:`none`,j.disabled=!1,j.style.opacity=``,j.style.cursor=``)}n.addEventListener(`click`,()=>{if(!N.isGenerating){VC();return}t&&t.value&&t.value.trim()?ad():iC(n)}),j?.addEventListener(`click`,()=>iC(j));function ne(e){if(!N.isGenerating)return!1;let t=N.activeSessionId;return t?dd(t)?(ud(t),iC(j&&j.style.display!==`none`?j:e||n)?(L(r(`queue.stopAndSendStarted`),`success`,2500),!0):(fd(t),!0)):(L(r(`queue.stopAndSendEmpty`),`warning`,3e3),!1):!1}function re(e,{isPrimarySend:t=!1}={}){if(!e)return;let n=()=>t&&ee();e.addEventListener(`contextmenu`,t=>{n()||!N.isGenerating||!dd(N.activeSessionId)||(t.preventDefault(),ne(e))});let r=null,i=()=>{r&&=(clearTimeout(r),null)};e.addEventListener(`pointerdown`,t=>{t.pointerType===`mouse`&&t.button!==0||n()||!N.isGenerating||!dd(N.activeSessionId)||(i(),r=setTimeout(()=>{r=null,ne(e)},600))});for(let t of[`pointerup`,`pointerleave`,`pointercancel`])e.addEventListener(t,i)}re(n,{isPrimarySend:!0}),re(j),document.addEventListener(`queue-stop-and-send`,()=>{ne(j&&j.style.display!==`none`?j:n)}),document.addEventListener(`generating-state-changed`,te),t.addEventListener(`input`,te),document.addEventListener(`voice-draft-written`,te);let ie=document.getElementById(`shortcutsBtn`),ae=document.getElementById(`shortcutsModal`),oe=document.getElementById(`shortcutsCloseBtn`);function se(){ae&&(ae.style.display=`flex`)}function ce(){ae&&(ae.style.display=`none`)}ie&&ie.addEventListener(`click`,e=>{e.stopPropagation(),se();let t=document.getElementById(`headerMoreDropdown`);t&&t.classList.remove(`show`)}),oe&&oe.addEventListener(`click`,ce),ae&&ae.addEventListener(`click`,e=>{e.target===ae&&ce()});let le=jO();wx(),Ru({adjustInputHeight:g}).catch(e=>{a.warn(`[SidePanel] initVoiceInput failed:`,e?.message||e)}),document.addEventListener(`keydown`,e=>{if((e.ctrlKey||e.metaKey)&&e.key===`t`){e.preventDefault();let t=document.getElementById(`toolsPopup`);t&&t.style.display!==`none`?pa():fa()}if(e.key===`Escape`&&Nu()){e.preventDefault();return}if(!(e.key===`Escape`&&le.handleEscape())){if(e.key===`Escape`&&ae&&ae.style.display!==`none`){ce();return}if(e.altKey&&e.code===`Slash`){e.preventDefault(),se();return}if(e.altKey&&!e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Um();return}if(e.altKey&&e.shiftKey&&e.code===`KeyS`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Wm();return}if(Xl(e)){e.preventDefault(),ju();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyN`){e.preventDefault(),Xo();return}if(e.altKey&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyW`){e.preventDefault(),Xs();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){dw(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`;le.jumpToMessage(t,e.ctrlKey||e.metaKey),le.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(Qy);for(let e=0;e<t.length;e++)if(r=(r+1)%t.length,n(t[r])){ab(t[r]);break}return}let r,i;n?(r=document.getElementById(`agentAtList`),i=N.selectedAgentAtIndex):Qy===`pages`?(r=document.getElementById(`agentPageList`),i=N.selectedPageIndex):Qy===`proxies`?(r=document.getElementById(`agentProxyList`),i=N.selectedProxyAtIndex):Qy===`knowledge`?(r=document.getElementById(`agentKnowledgeList`),i=N.selectedKnowledgeAtIndex):(r=document.getElementById(`agentAtList`),i=N.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?(N.selectedAgentAtIndex=t,yb(a)):Qy===`proxies`?(N.selectedProxyAtIndex=t,yb(a)):Qy===`knowledge`?(N.selectedKnowledgeAtIndex=t,yb(a)):Qy===`pages`?(N.selectedPageIndex=t,Bb(a)):(N.selectedAgentAtIndex=t,yb(a));return}else if(e.key===`ArrowUp`){e.preventDefault();let t=i<0||i===0?o-1:i-1;n?(N.selectedAgentAtIndex=t,yb(a)):Qy===`proxies`?(N.selectedProxyAtIndex=t,yb(a)):Qy===`knowledge`?(N.selectedKnowledgeAtIndex=t,yb(a)):Qy===`pages`?(N.selectedPageIndex=t,Bb(a)):(N.selectedAgentAtIndex=t,yb(a));return}else if(e.key===`Enter`&&i>=0){e.preventDefault(),a[i].click(),(e.ctrlKey||e.metaKey)&&rb();return}else if(e.key===`Escape`){rb();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&&(N.selectedFileAtIndex=e.key===`ArrowDown`?N.selectedFileAtIndex<0?0:(N.selectedFileAtIndex+1)%r:N.selectedFileAtIndex<0||N.selectedFileAtIndex===0?r-1:N.selectedFileAtIndex-1,SP(n));return}if(e.key===`Enter`&&r>0&&N.selectedFileAtIndex>=0){e.preventDefault(),n[N.selectedFileAtIndex].click();return}if(e.key===`Escape`){e.preventDefault(),_P();return}}if(n.style.display!==`none`&&r.classList.contains(`show`)){if(N.showMergedList){let t=r.querySelectorAll(`#promptList .prompt-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),N.selectedPromptIndex<0?N.selectedPromptIndex=0:N.selectedPromptIndex=(N.selectedPromptIndex+1)%n,Sw(t);return}if(e.key===`ArrowUp`){e.preventDefault(),N.selectedPromptIndex<0||N.selectedPromptIndex===0?N.selectedPromptIndex=n-1:--N.selectedPromptIndex,Sw(t);return}if(e.key===`Enter`&&N.selectedPromptIndex>=0){e.preventDefault();let n=t[N.selectedPromptIndex];n.dataset.type===`skill`||n.dataset.type===`mcp`?(n.click(),(e.ctrlKey||e.metaKey)&&_w()):e.ctrlKey||e.metaKey?Cw(n.dataset.code):ww(n.dataset.code);return}if(e.key===`Escape`){_w();return}return}if(N.activeDropdownTab===`skills`){let t=r.querySelectorAll(`#skillList .skill-list-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),N.selectedSkillIndex<0?N.selectedSkillIndex=0:N.selectedSkillIndex=(N.selectedSkillIndex+1)%n,Ww(t);return}if(e.key===`ArrowUp`){e.preventDefault(),N.selectedSkillIndex<0||N.selectedSkillIndex===0?N.selectedSkillIndex=n-1:--N.selectedSkillIndex,Ww(t);return}if(e.key===`Enter`&&N.selectedSkillIndex>=0){e.preventDefault(),t[N.selectedSkillIndex].click(),(e.ctrlKey||e.metaKey)&&_w();return}if(e.key===`Escape`){_w();return}if(e.key===`Tab`){e.preventDefault();let t=document.getElementById(`mcpTab`);t&&t.style.display!==`none`?Zw(`mcp`):Zw(`prompts`);return}return}if(N.activeDropdownTab===`mcp`){let t=r.querySelectorAll(`#mcpList .mcp-list-item`),n=t.length;if(e.key===`ArrowDown`){e.preventDefault(),N.selectedMcpServiceIndex<0?N.selectedMcpServiceIndex=0:N.selectedMcpServiceIndex=(N.selectedMcpServiceIndex+1)%n,iT(t);return}if(e.key===`ArrowUp`){e.preventDefault(),N.selectedMcpServiceIndex<0||N.selectedMcpServiceIndex===0?N.selectedMcpServiceIndex=n-1:--N.selectedMcpServiceIndex,iT(t);return}if(e.key===`Enter`&&N.selectedMcpServiceIndex>=0){e.preventDefault(),t[N.selectedMcpServiceIndex].click(),(e.ctrlKey||e.metaKey)&&_w();return}if(e.key===`Escape`){_w();return}if(e.key===`Tab`){e.preventDefault(),Zw(`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(),Zw(`skills`);return}if(n&&n.style.display!==`none`){e.preventDefault(),Zw(`mcp`);return}}if(n!==0&&e.key===`ArrowDown`){e.preventDefault(),N.selectedPromptIndex<0?N.selectedPromptIndex=0:N.selectedPromptIndex=(N.selectedPromptIndex+1)%n,Sw(t);return}if(e.key===`ArrowUp`){e.preventDefault(),N.selectedPromptIndex<0||N.selectedPromptIndex===0?N.selectedPromptIndex=n-1:--N.selectedPromptIndex,Sw(t);return}if(e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&N.selectedPromptIndex>=0){e.preventDefault();let n=t[N.selectedPromptIndex].dataset.code;Cw(n);return}if(e.key===`Enter`&&N.selectedPromptIndex>=0){e.preventDefault();let n=t[N.selectedPromptIndex].dataset.code;ww(n);return}if(e.key===`Escape`){_w();return}}if(e.key===`Escape`){N.inputHistoryIndex>=0&&(N.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(e.key===`ArrowUp`&&N.inputHistoryIndex===-1&&!t.value.trim()&&!Xu()&&QF()){e.preventDefault();return}if(!c&&!l&&!u){let n=kF({key:e.key,value:t.value,caret:t.selectionStart,history:N.inputHistory,index:N.inputHistoryIndex});if(n.handled){e.preventDefault(),N.inputHistoryIndex=n.index,t.value=n.value,t.dispatchEvent(new Event(`input`)),t.setSelectionRange(n.value.length,n.value.length);return}}if(e.key===`Enter`&&!e.shiftKey){if(N.isComposing)return;if(e.preventDefault(),_P(),N.isGenerating){if(e.altKey){Td(t.value);return}ad();return}VC()}}),t.addEventListener(`compositionstart`,()=>{N.isComposing=!0}),t.addEventListener(`compositionend`,()=>{N.isComposing=!1}),t.addEventListener(`paste`,e=>{let t=e.clipboardData?.items;if(t)for(let n of t){if(n.type.startsWith(`image/`)&&N.enableImageInput){e.preventDefault();let t=n.getAsFile();t&&Ap(t);break}if(n.kind===`file`&&N.enableFileInput){e.preventDefault();let t=n.getAsFile();t&&_m([t]);break}}});let ue=document.getElementById(`fileAttachBtn`),de=document.getElementById(`fileInput`);ue&&de&&(ue.addEventListener(`click`,()=>{de.click()}),de.addEventListener(`change`,async()=>{if(de.files.length>0){let e=Array.from(de.files),t=e.filter(e=>e.type.startsWith(`image/`)),n=e.filter(e=>!e.type.startsWith(`image/`));if(t.length>0)if(N.enableImageInput)for(let e of t)await Ap(e);else L(r(`sidePanel.imageNotEnabled`)),_m(t);n.length>0&&_m(n),de.value=``}}));let fe=document.querySelector(`.input-wrapper`),pe=0;fe&&(fe.addEventListener(`dragenter`,e=>{e.preventDefault(),e.stopPropagation(),pe++,fe.classList.add(`drag-over`)}),fe.addEventListener(`dragleave`,e=>{e.preventDefault(),e.stopPropagation(),pe--,pe<=0&&(pe=0,fe.classList.remove(`drag-over`))}),fe.addEventListener(`dragover`,e=>{e.preventDefault(),e.stopPropagation()}),fe.addEventListener(`drop`,async e=>{e.preventDefault(),e.stopPropagation(),pe=0,fe.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){ty([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(N.enableImageInput)for(let e of t)await Ap(e);else L(r(`sidePanel.imageNotEnabled`)),_m(t);n.length>0&&_m(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 me=document.getElementById(`screenshotBtn`);me&&me.addEventListener(`click`,async()=>{if(N.enableImageInput)try{await Um()}catch(e){a.error(`[SidePanel] screenshot failed:`,e),L(r(`sidePanel.screenshotFailed`))}}),Op(),t.addEventListener(`wheel`,e=>{N.isScrolling=!0;let n=t.style.height||t.offsetHeight+`px`;t.style.height=n,t.scrollHeight<=t.clientHeight+10&&(e.preventDefault(),e.stopPropagation()),setTimeout(()=>{N.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]!==`
2786
2786
  `&&n[e-1]!==` `)return!1;let t=n.substring(e+1);return!(t.includes(` `)||t.includes(`
2787
- `))},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`)_w(),rb(),gP(n.substring(s+1));else if(f&&f.key===`at`)_w(),_P(),tb(n.substring(o+1));else if(f&&f.key===`slash`){rb(),_P();let e=n.substring(a+1);r.style.display!==`none`&&i.classList.contains(`show`)?yw(e):gw(e)}else _w(),rb(),_P();g()});let he=aF((e,t)=>{chrome.storage.local.set({[e]:t})},200);u.addEventListener(`scroll`,()=>{he(`scrollPosition_`+(N.activeSessionId||`default`),u.scrollTop)}),window.addEventListener(`pagehide`,()=>{chrome.storage.local.set({[`scrollPosition_`+(N.activeSessionId||`default`)]:u.scrollTop})});let ge=document.getElementById(`headerMoreBtn`),_e=document.getElementById(`headerMoreDropdown`);ge&&_e&&(ge.addEventListener(`click`,e=>{e.stopPropagation(),_e.classList.toggle(`show`)}),document.addEventListener(`click`,e=>{!_e.contains(e.target)&&e.target!==ge&&Ce()}));let ve=document.getElementById(`themeToggleBtn`),ye=document.getElementById(`themeToggleLabel`),be=document.getElementById(`themeSubmenu`),xe=e=>r(e===`dark`?`settings.themeDark`:e===`system`?`settings.themeSystem`:`settings.themeLight`),Se=()=>{let e=gt();ye&&(ye.textContent=r(`header.themeToggle`,{theme:xe(e)})),be&&be.querySelectorAll(`.theme-submenu-item`).forEach(t=>{t.classList.toggle(`active`,t.dataset.themeValue===e)}),ve&&ve.setAttribute(`aria-expanded`,String(!!(be&&be.classList.contains(`show`))))};function Ce(){be&&be.classList.remove(`show`),_e&&_e.classList.remove(`show`),ve&&ve.setAttribute(`aria-expanded`,`false`)}ve&&be&&(ve.addEventListener(`click`,e=>{e.stopPropagation(),be.classList.toggle(`show`),Se()}),be.querySelectorAll(`.theme-submenu-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),dt(e.dataset.themeValue),Ce()})})),Se(),mt(Se),c(Se),s.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),SC()}),l&&l.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),Hf()});let we=document.getElementById(`importChatBtn`);we&&we.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),qf()});let Te=document.getElementById(`importSessionsFile`);Te&&Te.addEventListener(`change`,e=>{let t=e.target.files[0];t&&Jf(t)});let Ee=document.getElementById(`settingsBtn`);Ee&&Ee.addEventListener(`click`,()=>{chrome.runtime.openOptionsPage()});let De=document.getElementById(`headerAgentIndicator`);De&&De.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 Oe=document.getElementById(`prototypeLibraryBtn`);Oe&&Oe.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),gc()});let ke=document.getElementById(`tokenStatsHeaderBtn`);ke&&ke.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),window.openTokenStats&&window.openTokenStats()});let Ae=document.getElementById(`auditLogBtn`),je=document.getElementById(`auditLogOverlay`),Me=document.getElementById(`auditLogClose`),Ne=document.getElementById(`auditLogRefreshBtn`),Pe=document.getElementById(`auditLogCategoryFilter`),Fe=document.getElementById(`auditLogLimit`),Ie=document.getElementById(`auditLogSearch`),Le=document.getElementById(`auditLogSearchClear`),Re=document.getElementById(`auditLogLoading`),ze=document.getElementById(`auditLogEmpty`),Be=document.getElementById(`auditLogList`),Ve=[],He={auth:r(`sidePanel.auditCategoryAuth`),fs:r(`sidePanel.auditCategoryFs`),exec:r(`sidePanel.auditCategoryExec`),security:r(`sidePanel.auditCategorySecurity`),system:r(`sidePanel.auditCategorySystem`)},Ue={info:`INFO`,warn:`WARN`,error:`ERROR`},We={info:`audit-level-info`,warn:`audit-level-warn`,error:`audit-level-error`};function Ge(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 Ke(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 qe(){if(!Re||!ze||!Be)return;Re.style.display=`block`,ze.style.display=`none`,Be.style.display=`none`;let e=Pe?.value||null,t=parseInt(Fe?.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(Re.style.display=`none`,!n||!n.success){ze.style.display=`block`,ze.textContent=r(`sidePanel.auditQueryFailed`,{error:n?.error||r(`sidePanel.unknownError`)});return}Ve=n.entries||[],Je()}catch(e){Re.style.display=`none`,ze.style.display=`block`,ze.textContent=r(`sidePanel.auditLoadFailed`,{error:e.message})}}function Je(){if(!Be)return;let e=(Ie?.value||``).trim().toLowerCase(),t=Ve;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))),Le&&(Le.style.display=e?`block`:`none`),Re.style.display=`none`,t.length===0){ze.style.display=`block`,ze.textContent=r(e?`sidePanel.auditNoMatch`:`sidePanel.auditEmpty`),Be.style.display=`none`;return}ze.style.display=`none`,Be.style.display=`block`,Be.innerHTML=t.map(e=>{let t=P(He[e.category]||e.category||`-`),n=P(Ue[e.level]||e.level?.toUpperCase()||`INFO`),r=We[e.level]||`audit-level-info`,i=Ge(e.timestamp),a=P(Ke(e));return`<div class="audit-entry">
2787
+ `))},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`)_w(),rb(),gP(n.substring(s+1));else if(f&&f.key===`at`)_w(),_P(),tb(n.substring(o+1));else if(f&&f.key===`slash`){rb(),_P();let e=n.substring(a+1);r.style.display!==`none`&&i.classList.contains(`show`)?yw(e):gw(e)}else _w(),rb(),_P();g()});let he=AF((e,t)=>{chrome.storage.local.set({[e]:t})},200);u.addEventListener(`scroll`,()=>{he(`scrollPosition_`+(N.activeSessionId||`default`),u.scrollTop)}),window.addEventListener(`pagehide`,()=>{chrome.storage.local.set({[`scrollPosition_`+(N.activeSessionId||`default`)]:u.scrollTop})});let ge=document.getElementById(`headerMoreBtn`),_e=document.getElementById(`headerMoreDropdown`);ge&&_e&&(ge.addEventListener(`click`,e=>{e.stopPropagation(),_e.classList.toggle(`show`)}),document.addEventListener(`click`,e=>{!_e.contains(e.target)&&e.target!==ge&&Ce()}));let ve=document.getElementById(`themeToggleBtn`),ye=document.getElementById(`themeToggleLabel`),be=document.getElementById(`themeSubmenu`),xe=e=>r(e===`dark`?`settings.themeDark`:e===`system`?`settings.themeSystem`:`settings.themeLight`),Se=()=>{let e=gt();ye&&(ye.textContent=r(`header.themeToggle`,{theme:xe(e)})),be&&be.querySelectorAll(`.theme-submenu-item`).forEach(t=>{t.classList.toggle(`active`,t.dataset.themeValue===e)}),ve&&ve.setAttribute(`aria-expanded`,String(!!(be&&be.classList.contains(`show`))))};function Ce(){be&&be.classList.remove(`show`),_e&&_e.classList.remove(`show`),ve&&ve.setAttribute(`aria-expanded`,`false`)}ve&&be&&(ve.addEventListener(`click`,e=>{e.stopPropagation(),be.classList.toggle(`show`),Se()}),be.querySelectorAll(`.theme-submenu-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),dt(e.dataset.themeValue),Ce()})})),Se(),mt(Se),c(Se),s.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),SC()}),l&&l.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),Hf()});let we=document.getElementById(`importChatBtn`);we&&we.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),qf()});let Te=document.getElementById(`importSessionsFile`);Te&&Te.addEventListener(`change`,e=>{let t=e.target.files[0];t&&Jf(t)});let Ee=document.getElementById(`settingsBtn`);Ee&&Ee.addEventListener(`click`,()=>{chrome.runtime.openOptionsPage()});let De=document.getElementById(`headerAgentIndicator`);De&&De.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 Oe=document.getElementById(`prototypeLibraryBtn`);Oe&&Oe.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),gc()});let ke=document.getElementById(`tokenStatsHeaderBtn`);ke&&ke.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),window.openTokenStats&&window.openTokenStats()});let Ae=document.getElementById(`auditLogBtn`),je=document.getElementById(`auditLogOverlay`),Me=document.getElementById(`auditLogClose`),Ne=document.getElementById(`auditLogRefreshBtn`),Pe=document.getElementById(`auditLogCategoryFilter`),Fe=document.getElementById(`auditLogLimit`),Ie=document.getElementById(`auditLogSearch`),Le=document.getElementById(`auditLogSearchClear`),Re=document.getElementById(`auditLogLoading`),ze=document.getElementById(`auditLogEmpty`),Be=document.getElementById(`auditLogList`),Ve=[],He={auth:r(`sidePanel.auditCategoryAuth`),fs:r(`sidePanel.auditCategoryFs`),exec:r(`sidePanel.auditCategoryExec`),security:r(`sidePanel.auditCategorySecurity`),system:r(`sidePanel.auditCategorySystem`)},Ue={info:`INFO`,warn:`WARN`,error:`ERROR`},We={info:`audit-level-info`,warn:`audit-level-warn`,error:`audit-level-error`};function Ge(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 Ke(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 qe(){if(!Re||!ze||!Be)return;Re.style.display=`block`,ze.style.display=`none`,Be.style.display=`none`;let e=Pe?.value||null,t=parseInt(Fe?.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(Re.style.display=`none`,!n||!n.success){ze.style.display=`block`,ze.textContent=r(`sidePanel.auditQueryFailed`,{error:n?.error||r(`sidePanel.unknownError`)});return}Ve=n.entries||[],Je()}catch(e){Re.style.display=`none`,ze.style.display=`block`,ze.textContent=r(`sidePanel.auditLoadFailed`,{error:e.message})}}function Je(){if(!Be)return;let e=(Ie?.value||``).trim().toLowerCase(),t=Ve;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))),Le&&(Le.style.display=e?`block`:`none`),Re.style.display=`none`,t.length===0){ze.style.display=`block`,ze.textContent=r(e?`sidePanel.auditNoMatch`:`sidePanel.auditEmpty`),Be.style.display=`none`;return}ze.style.display=`none`,Be.style.display=`block`,Be.innerHTML=t.map(e=>{let t=P(He[e.category]||e.category||`-`),n=P(Ue[e.level]||e.level?.toUpperCase()||`INFO`),r=We[e.level]||`audit-level-info`,i=Ge(e.timestamp),a=P(Ke(e));return`<div class="audit-entry">
2788
2788
  <div class="audit-entry-header">
2789
2789
  <span class="audit-time">${i}</span>
2790
2790
  <span class="audit-level ${r}">${n}</span>
@@ -2792,7 +2792,7 @@ Are you sure you want to stop the agent service? You will not be able to connect
2792
2792
  <span class="audit-action">${P(e.action||`-`)}</span>
2793
2793
  </div>
2794
2794
  ${a?`<div class="audit-details">${a}</div>`:``}
2795
- </div>`}).join(``)}function Ye(){je&&(je.style.display=`flex`,qe())}function Xe(){je&&(je.style.display=`none`)}Ae&&Ae.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),Ye()}),Me&&Me.addEventListener(`click`,Xe),Ne&&Ne.addEventListener(`click`,qe),Pe&&Pe.addEventListener(`change`,qe),Fe&&Fe.addEventListener(`change`,qe),Ie&&Ie.addEventListener(`input`,()=>{Je()}),Le&&Le.addEventListener(`click`,()=>{Ie&&(Ie.value=``),Je()}),bI(()=>N.activeSessionId,window.showCustomConfirm);let Ze=document.getElementById(`isolateChatBtn`),Qe=document.getElementById(`enableToolsBtn`),$e=document.getElementById(`toolsConfigBtn`),et=`agentEnabledTools_${N.activeAgentId||`default`}`,tt=`agentMcpClosedServers_${N.activeAgentId||`default`}`;chrome.storage.local.get([et,`enabledTools`,`isolateChat`,`enableSelectionQuery`,`enableTools`,tt,`mcpTools`,`mcpEnabled`,`ragTools`,`ragToolsIntroduced`],e=>{e.isolateChat!==void 0&&(N.isolateChat=e.isolateChat),Ze.checked=N.isolateChat,e.enableSelectionQuery!==void 0&&(N.enableSelectionQuery=e.enableSelectionQuery);let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=N.enableSelectionQuery),e.enableTools!==void 0&&(N.useTools=e.enableTools),N.activeAgentId&&M(async()=>{let{getAgent:e}=await import(`./agent-store-CrkBz4jI.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3,4])).then(({getAgent:e})=>e(N.activeAgentId)).then(e=>{N.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null,Ea()}).catch(()=>{}),N.mcpClosedServers=e[tt]||[];let n=e.ragTools||[],r=e[et],i=e.enabledTools;if(Array.isArray(r)){let t=ka(n);N.enabledTools=r.filter(e=>t.has(e));let i=Oa(N.enabledTools,n,e.ragToolsIntroduced);N.enabledTools=i.tools,i.migrated?chrome.storage.local.set({ragToolsIntroduced:!0,[et]:N.enabledTools}):N.enabledTools.length!==r.length&&chrome.storage.local.set({[et]:N.enabledTools})}else if(i&&i.length>0){let t=ka(n),r=i.filter(e=>t.has(e)),a=x.filter(e=>e.enabled&&!r.includes(e.id)).map(e=>e.id);N.enabledTools=[...r,...a];let o=Oa(N.enabledTools,n,e.ragToolsIntroduced);N.enabledTools=o.tools,chrome.storage.local.set({[et]:N.enabledTools,...o.migrated?{ragToolsIntroduced:!0}:{}})}else{N.enabledTools=x.filter(e=>e.enabled).map(e=>e.id);let t=Oa(N.enabledTools,n,e.ragToolsIntroduced);N.enabledTools=t.tools,t.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[et]:N.enabledTools})}Qe&&(Qe.checked=N.useTools),Ea(),PI(),D()}),Ze.addEventListener(`change`,()=>{N.isolateChat=Ze.checked,chrome.storage.local.set({isolateChat:N.isolateChat}),a.debug(`[SidePanel] conv memory:`,N.isolateChat?`enabled`:`disabled`)});let nt=document.getElementById(`enableSelectionQueryBtn`);nt&&nt.addEventListener(`change`,()=>{N.enableSelectionQuery=nt.checked,chrome.storage.local.set({enableSelectionQuery:N.enableSelectionQuery}),a.debug(`[SidePanel] text Q&A:`,N.enableSelectionQuery?`enabled`:`disabled`),!N.enableSelectionQuery&&N.selectedContextText&&pC()}),Qe&&Qe.addEventListener(`change`,()=>{N.useTools=Qe.checked,chrome.storage.local.set({enableTools:N.useTools}),a.debug(`[SidePanel] tool master switch:`,N.useTools?`enabled`:`disabled`),Ea()}),$e&&$e.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),fa()});let rt=document.getElementById(`toolsPopupOverlay`),it=document.getElementById(`toolsPopupClose`),at=rt?rt.querySelector(`.modal-container`):null;it&&it.addEventListener(`click`,pa),at&&at.addEventListener(`click`,e=>{e.stopPropagation()});let ot=document.getElementById(`toolsSearchInput`),st=document.getElementById(`toolsSearchClear`);ot&&ot.addEventListener(`input`,e=>{N.currentSearch=e.target.value.toLowerCase(),st&&(st.style.display=e.target.value?``:`none`),ma()}),st&&st.addEventListener(`click`,()=>{ot&&(ot.value=``,st.style.display=`none`,N.currentSearch=``,ma())});let ct=document.querySelectorAll(`.category-btn`);ct.forEach(e=>{e.addEventListener(`click`,()=>{ct.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`,N.currentCategory=e.dataset.category,ma()})});let lt=document.getElementById(`toolsCategories`);lt&&lt.addEventListener(`wheel`,e=>{e.preventDefault(),lt.scrollLeft+=e.deltaY*2},{passive:!1});let ft=document.getElementById(`toolsSelectAll`),pt=document.getElementById(`toolsSelectNone`);ft&&ft.addEventListener(`click`,()=>{ba().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!0),N.enabledTools.includes(e.id)||N.enabledTools.push(e.id)}),Ta(!0),xa(),Sa(),Ca()}),pt&&pt.addEventListener(`click`,()=>{ba().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!1);let n=N.enabledTools.indexOf(e.id);n>-1&&N.enabledTools.splice(n,1)}),Ta(!1),xa(),Sa(),Ca()});let ht=document.getElementById(`toolsPopupSave`);ht&&ht.addEventListener(`click`,()=>{wa(),Ca()});let _t=document.getElementById(`toolsPreselectToggle`);_t&&_t.addEventListener(`change`,()=>{chrome.storage.local.set({enableToolPreselect:_t.checked},()=>{a.debug(`[SidePanel] toolpre-filter toggle updated:`,_t.checked)})});let vt=document.getElementById(`toolConfirmToggle`);vt&&vt.addEventListener(`change`,()=>{chrome.storage.local.set({toolConfirmationEnabled:vt.checked},()=>{a.debug(`[SidePanel] sensitive-operation confirmation toggle updated:`,vt.checked)})});let yt=document.getElementById(`toolsPopupCancel`);yt&&yt.addEventListener(`click`,()=>{pa()});let bt=document.getElementById(`modalCancelBtn`),xt=document.getElementById(`modalConfirmBtn`),St=document.getElementById(`toolStatsOverlay`),Ct=document.getElementById(`toolStatsClose`),wt=document.getElementById(`toolStatsBtn`);function Et(){St&&(St.style.display=`flex`,Mt())}function Dt(){St&&(St.style.display=`none`)}wt&&wt.addEventListener(`click`,e=>{e.stopPropagation(),Et()}),Ct&&Ct.addEventListener(`click`,Dt),St&&St.addEventListener(`click`,e=>{e.target===St&&Dt()});let kt=document.getElementById(`toolStatsRefreshBtn`);kt&&kt.addEventListener(`click`,Mt);let At=document.getElementById(`toolStatsClearBtn`);At&&At.addEventListener(`click`,async()=>{await window.showCustomConfirm(r(`sidePanel.clearStatsConfirm`),r(`sidePanel.clearStatsTitle`))&&(await chrome.storage.local.remove([`toolUsageStats`]),Mt())});let jt={column:`callCount`,asc:!1};async function Mt(){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={};x.forEach(e=>{l[e.id]=e.name?`${e.name}${r(`sidePanel.toolNameDescSeparator`)}${e.description||``}`:e.description||e.id}),Nt(a,l);let u=x.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="${P(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 Nt(e,t){let n=document.getElementById(`toolStatsTableBody`);if(!n)return;let{column:r,asc:i}=jt;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=zt(i);return`<tr>
2795
+ </div>`}).join(``)}function Ye(){je&&(je.style.display=`flex`,qe())}function Xe(){je&&(je.style.display=`none`)}Ae&&Ae.addEventListener(`click`,e=>{e.stopPropagation(),Ce(),Ye()}),Me&&Me.addEventListener(`click`,Xe),Ne&&Ne.addEventListener(`click`,qe),Pe&&Pe.addEventListener(`change`,qe),Fe&&Fe.addEventListener(`change`,qe),Ie&&Ie.addEventListener(`input`,()=>{Je()}),Le&&Le.addEventListener(`click`,()=>{Ie&&(Ie.value=``),Je()}),GI(()=>N.activeSessionId,window.showCustomConfirm);let Ze=document.getElementById(`isolateChatBtn`),Qe=document.getElementById(`enableToolsBtn`),$e=document.getElementById(`toolsConfigBtn`),et=`agentEnabledTools_${N.activeAgentId||`default`}`,tt=`agentMcpClosedServers_${N.activeAgentId||`default`}`;chrome.storage.local.get([et,`enabledTools`,`isolateChat`,`enableSelectionQuery`,`enableTools`,tt,`mcpTools`,`mcpEnabled`,`ragTools`,`ragToolsIntroduced`],e=>{e.isolateChat!==void 0&&(N.isolateChat=e.isolateChat),Ze.checked=N.isolateChat,e.enableSelectionQuery!==void 0&&(N.enableSelectionQuery=e.enableSelectionQuery);let t=document.getElementById(`enableSelectionQueryBtn`);t&&(t.checked=N.enableSelectionQuery),e.enableTools!==void 0&&(N.useTools=e.enableTools),N.activeAgentId&&M(async()=>{let{getAgent:e}=await import(`./agent-store-1fyaAv9T.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3,4])).then(({getAgent:e})=>e(N.activeAgentId)).then(e=>{N.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null,Ea()}).catch(()=>{}),N.mcpClosedServers=e[tt]||[];let n=e.ragTools||[],r=e[et],i=e.enabledTools;if(Array.isArray(r)){let t=ka(n);N.enabledTools=r.filter(e=>t.has(e));let i=Oa(N.enabledTools,n,e.ragToolsIntroduced);N.enabledTools=i.tools,i.migrated?chrome.storage.local.set({ragToolsIntroduced:!0,[et]:N.enabledTools}):N.enabledTools.length!==r.length&&chrome.storage.local.set({[et]:N.enabledTools})}else if(i&&i.length>0){let t=ka(n),r=i.filter(e=>t.has(e)),a=x.filter(e=>e.enabled&&!r.includes(e.id)).map(e=>e.id);N.enabledTools=[...r,...a];let o=Oa(N.enabledTools,n,e.ragToolsIntroduced);N.enabledTools=o.tools,chrome.storage.local.set({[et]:N.enabledTools,...o.migrated?{ragToolsIntroduced:!0}:{}})}else{N.enabledTools=x.filter(e=>e.enabled).map(e=>e.id);let t=Oa(N.enabledTools,n,e.ragToolsIntroduced);N.enabledTools=t.tools,t.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[et]:N.enabledTools})}Qe&&(Qe.checked=N.useTools),Ea(),aL(),D()}),Ze.addEventListener(`change`,()=>{N.isolateChat=Ze.checked,chrome.storage.local.set({isolateChat:N.isolateChat}),a.debug(`[SidePanel] conv memory:`,N.isolateChat?`enabled`:`disabled`)});let nt=document.getElementById(`enableSelectionQueryBtn`);nt&&nt.addEventListener(`change`,()=>{N.enableSelectionQuery=nt.checked,chrome.storage.local.set({enableSelectionQuery:N.enableSelectionQuery}),a.debug(`[SidePanel] text Q&A:`,N.enableSelectionQuery?`enabled`:`disabled`),!N.enableSelectionQuery&&N.selectedContextText&&pC()}),Qe&&Qe.addEventListener(`change`,()=>{N.useTools=Qe.checked,chrome.storage.local.set({enableTools:N.useTools}),a.debug(`[SidePanel] tool master switch:`,N.useTools?`enabled`:`disabled`),Ea()}),$e&&$e.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),fa()});let rt=document.getElementById(`toolsPopupOverlay`),it=document.getElementById(`toolsPopupClose`),at=rt?rt.querySelector(`.modal-container`):null;it&&it.addEventListener(`click`,pa),at&&at.addEventListener(`click`,e=>{e.stopPropagation()});let ot=document.getElementById(`toolsSearchInput`),st=document.getElementById(`toolsSearchClear`);ot&&ot.addEventListener(`input`,e=>{N.currentSearch=e.target.value.toLowerCase(),st&&(st.style.display=e.target.value?``:`none`),ma()}),st&&st.addEventListener(`click`,()=>{ot&&(ot.value=``,st.style.display=`none`,N.currentSearch=``,ma())});let ct=document.querySelectorAll(`.category-btn`);ct.forEach(e=>{e.addEventListener(`click`,()=>{ct.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`,N.currentCategory=e.dataset.category,ma()})});let lt=document.getElementById(`toolsCategories`);lt&&lt.addEventListener(`wheel`,e=>{e.preventDefault(),lt.scrollLeft+=e.deltaY*2},{passive:!1});let ft=document.getElementById(`toolsSelectAll`),pt=document.getElementById(`toolsSelectNone`);ft&&ft.addEventListener(`click`,()=>{ba().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!0),N.enabledTools.includes(e.id)||N.enabledTools.push(e.id)}),Ta(!0),xa(),Sa(),Ca()}),pt&&pt.addEventListener(`click`,()=>{ba().forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&(t.checked=!1);let n=N.enabledTools.indexOf(e.id);n>-1&&N.enabledTools.splice(n,1)}),Ta(!1),xa(),Sa(),Ca()});let ht=document.getElementById(`toolsPopupSave`);ht&&ht.addEventListener(`click`,()=>{wa(),Ca()});let _t=document.getElementById(`toolsPreselectToggle`);_t&&_t.addEventListener(`change`,()=>{chrome.storage.local.set({enableToolPreselect:_t.checked},()=>{a.debug(`[SidePanel] toolpre-filter toggle updated:`,_t.checked)})});let vt=document.getElementById(`toolConfirmToggle`);vt&&vt.addEventListener(`change`,()=>{chrome.storage.local.set({toolConfirmationEnabled:vt.checked},()=>{a.debug(`[SidePanel] sensitive-operation confirmation toggle updated:`,vt.checked)})});let yt=document.getElementById(`toolsPopupCancel`);yt&&yt.addEventListener(`click`,()=>{pa()});let bt=document.getElementById(`modalCancelBtn`),xt=document.getElementById(`modalConfirmBtn`),St=document.getElementById(`toolStatsOverlay`),Ct=document.getElementById(`toolStatsClose`),wt=document.getElementById(`toolStatsBtn`);function Et(){St&&(St.style.display=`flex`,Mt())}function Dt(){St&&(St.style.display=`none`)}wt&&wt.addEventListener(`click`,e=>{e.stopPropagation(),Et()}),Ct&&Ct.addEventListener(`click`,Dt),St&&St.addEventListener(`click`,e=>{e.target===St&&Dt()});let kt=document.getElementById(`toolStatsRefreshBtn`);kt&&kt.addEventListener(`click`,Mt);let At=document.getElementById(`toolStatsClearBtn`);At&&At.addEventListener(`click`,async()=>{await window.showCustomConfirm(r(`sidePanel.clearStatsConfirm`),r(`sidePanel.clearStatsTitle`))&&(await chrome.storage.local.remove([`toolUsageStats`]),Mt())});let jt={column:`callCount`,asc:!1};async function Mt(){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={};x.forEach(e=>{l[e.id]=e.name?`${e.name}${r(`sidePanel.toolNameDescSeparator`)}${e.description||``}`:e.description||e.id}),Nt(a,l);let u=x.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="${P(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 Nt(e,t){let n=document.getElementById(`toolStatsTableBody`);if(!n)return;let{column:r,asc:i}=jt;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=zt(i);return`<tr>
2796
2796
  <td style="padding: 6px 10px; border-bottom: 1px solid var(--border-subtle); color: var(--text-primary);"><code title="${P(a)}">${e}</code></td>
2797
2797
  <td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-secondary);">${n.callCount}</td>
2798
2798
  <td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-secondary);">${n.successCount}</td>
@@ -2803,4 +2803,4 @@ Are you sure you want to stop the agent service? You will not be able to connect
2803
2803
  <span style="font-size: 12px; color: ${o}; font-weight: 500;">${r.toFixed(0)}%</span>
2804
2804
  </td>
2805
2805
  <td style="padding: 6px 10px; text-align: right; border-bottom: 1px solid var(--border-subtle); color: var(--text-tertiary); font-size: 12px;">${s}</td>
2806
- </tr>`}).join(``),Pt()}function Pt(){let{column:e,asc:t}=jt,n=[`name`,`callCount`,`successCount`,`successRate`,`duration`],r={name:`sortByName`,callCount:`sortByCallCount`,successCount:`sortBySuccessCount`,successRate:`sortBySuccessRate`,duration:`sortByDuration`};n.forEach(n=>{let i=document.getElementById(r[n]);if(!i)return;let a=i.querySelector(`.sort-indicator`);a&&(n===e?(a.textContent=t?`▲`:`▼`,a.style.color=`var(--brand-500)`):(a.textContent=``,a.style.color=``))})}document.querySelectorAll(`#toolStatsTable th[data-sort]`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.sort;jt.column===t?jt.asc=!jt.asc:(jt.column=t,jt.asc=!1),Mt()})}),bt.addEventListener(`click`,()=>{CC()}),xt.addEventListener(`click`,()=>{CC(),xC()});let Ft=document.getElementById(`confirmModal`);Ft.addEventListener(`click`,e=>{e.target===Ft&&CC()});let It=document.getElementById(`selectionClose`);It&&It.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),a.debug(`[SidePanel] user clickcloseselected content by button`),pC(),window.hideFloatingMenu(),N.lastSelectedText=``,N.currentSelectionRange=null}),t.addEventListener(`input`,()=>{})}),At().then(()=>{SI(),XC(N.chatConfig.showMessageTimestamp!==!1),CI(),wI()}),document.addEventListener(`DOMContentLoaded`,()=>{EI()}),document.addEventListener(`DOMContentLoaded`,rr),document.addEventListener(`DOMContentLoaded`,mE),document.addEventListener(`DOMContentLoaded`,II),document.addEventListener(`DOMContentLoaded`,FI),document.addEventListener(`DOMContentLoaded`,sP),document.addEventListener(`DOMContentLoaded`,rF),document.addEventListener(`DOMContentLoaded`,_f),document.addEventListener(`DOMContentLoaded`,async()=>{$n(),lD(),await Sm(),Am(),await gA(),iM(),IO(),vI(),ak(),eL(),gh(),BN();let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await M(async()=>{let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await Promise.resolve().then(()=>km);return{updateBookmarkButtons:e,updateBookmarkBadge:t}},void 0);e(),t()}),document.addEventListener(`DOMContentLoaded`,()=>{AO()}),document.addEventListener(`DOMContentLoaded`,async()=>{Ku(e=>VC(e)),await zd(),await PF()});function oL(){pC(),qw(),oT(),Db(),Hb(),ym();let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}function sL(e){let t=e||{};t.quotedContextText&&dC(t.quotedContextText),t.selectedPage&&Vb(t.selectedPage),!t.quotedContextText&&N.selectedContextText&&fC(),Jw(),cT(),Ob(),Hm(),bm()}document.addEventListener(`queue-context-cleared`,oL),document.addEventListener(`queue-context-restored`,e=>{sL(e&&e.detail?e.detail.snapshot:null)}),document.addEventListener(`DOMContentLoaded`,Fw),document.addEventListener(`DOMContentLoaded`,Xw),document.addEventListener(`DOMContentLoaded`,$w),document.addEventListener(`DOMContentLoaded`,uT),document.addEventListener(`DOMContentLoaded`,Gb),document.addEventListener(`DOMContentLoaded`,Co),document.addEventListener(`DOMContentLoaded`,Ho),document.addEventListener(`DOMContentLoaded`,Nc),document.addEventListener(`DOMContentLoaded`,Kf),document.addEventListener(`DOMContentLoaded`,()=>pT()),document.addEventListener(`DOMContentLoaded`,async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await M(async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await Promise.resolve().then(()=>oS);return{refreshAgentNames:e,initScrollToBottomBtn:t}},void 0);e(),t()}),document.addEventListener(`DOMContentLoaded`,()=>{let e=new URLSearchParams(window.location.search).has(`popup`),t=document.getElementById(`detachBtn`),n=document.getElementById(`attachBtn`),i=e?n:t;e?n&&(n.style.display=`flex`):t&&(t.style.display=`flex`);let o=()=>{if(!i)return;let t=N.pendingCallApiSessionIds&&N.pendingCallApiSessionIds.size>0;i.disabled=t,i.style.opacity=t?`0.35`:``,i.style.cursor=t?`not-allowed`:`pointer`,i.title=r(t?`detach.taskRunning`:e?`header.attachTitle`:`header.detachTitle`)};o(),document.addEventListener(`generating-state-changed`,o),t&&t.addEventListener(`click`,async()=>{if(N.pendingCallApiSessionIds&&N.pendingCallApiSessionIds.size>0){L(r(`detach.taskRunning`),`warning`);return}try{if((await chrome.runtime.sendMessage({type:`DETACH_SIDEPANEL`,width:window.innerWidth}))?.success)try{window.close()}catch{}}catch(e){a.warn(`[SidePanel] detach failed:`,e?.message)}}),n&&n.addEventListener(`click`,async()=>{if(N.pendingCallApiSessionIds&&N.pendingCallApiSessionIds.size>0){L(r(`detach.taskRunning`),`warning`);return}try{let e=(await chrome.windows.getCurrent()).id;await chrome.runtime.sendMessage({type:`ATTACH_SIDEPANEL`,windowId:e});try{window.close()}catch{}}catch(e){a.warn(`[SidePanel] attach failed:`,e?.message)}})});export{qm as t};
2806
+ </tr>`}).join(``),Pt()}function Pt(){let{column:e,asc:t}=jt,n=[`name`,`callCount`,`successCount`,`successRate`,`duration`],r={name:`sortByName`,callCount:`sortByCallCount`,successCount:`sortBySuccessCount`,successRate:`sortBySuccessRate`,duration:`sortByDuration`};n.forEach(n=>{let i=document.getElementById(r[n]);if(!i)return;let a=i.querySelector(`.sort-indicator`);a&&(n===e?(a.textContent=t?`▲`:`▼`,a.style.color=`var(--brand-500)`):(a.textContent=``,a.style.color=``))})}document.querySelectorAll(`#toolStatsTable th[data-sort]`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.sort;jt.column===t?jt.asc=!jt.asc:(jt.column=t,jt.asc=!1),Mt()})}),bt.addEventListener(`click`,()=>{CC()}),xt.addEventListener(`click`,()=>{CC(),xC()});let Ft=document.getElementById(`confirmModal`);Ft.addEventListener(`click`,e=>{e.target===Ft&&CC()});let It=document.getElementById(`selectionClose`);It&&It.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),a.debug(`[SidePanel] user clickcloseselected content by button`),pC(),window.hideFloatingMenu(),N.lastSelectedText=``,N.currentSelectionRange=null}),t.addEventListener(`input`,()=>{})}),At().then(()=>{qI(),XC(N.chatConfig.showMessageTimestamp!==!1),JI(),YI()}),document.addEventListener(`DOMContentLoaded`,()=>{ZI()}),document.addEventListener(`DOMContentLoaded`,rr),document.addEventListener(`DOMContentLoaded`,mE),document.addEventListener(`DOMContentLoaded`,sL),document.addEventListener(`DOMContentLoaded`,oL),document.addEventListener(`DOMContentLoaded`,sP),document.addEventListener(`DOMContentLoaded`,rF),document.addEventListener(`DOMContentLoaded`,OF),document.addEventListener(`DOMContentLoaded`,_f),document.addEventListener(`DOMContentLoaded`,async()=>{$n(),lD(),await Sm(),Am(),await gA(),iM(),IO(),UI(),ak(),EL(),gh(),BN();let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await M(async()=>{let{updateBookmarkButtons:e,updateBookmarkBadge:t}=await Promise.resolve().then(()=>km);return{updateBookmarkButtons:e,updateBookmarkBadge:t}},void 0);e(),t()}),document.addEventListener(`DOMContentLoaded`,()=>{AO()}),document.addEventListener(`DOMContentLoaded`,async()=>{Ku(e=>VC(e)),await zd(),await aI()});function ML(){pC(),qw(),oT(),Db(),Hb(),ym();let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}function NL(e){let t=e||{};t.quotedContextText&&dC(t.quotedContextText),t.selectedPage&&Vb(t.selectedPage),!t.quotedContextText&&N.selectedContextText&&fC(),Jw(),cT(),Ob(),Hm(),bm()}document.addEventListener(`queue-context-cleared`,ML),document.addEventListener(`queue-context-restored`,e=>{NL(e&&e.detail?e.detail.snapshot:null)}),document.addEventListener(`DOMContentLoaded`,Fw),document.addEventListener(`DOMContentLoaded`,Xw),document.addEventListener(`DOMContentLoaded`,$w),document.addEventListener(`DOMContentLoaded`,uT),document.addEventListener(`DOMContentLoaded`,Gb),document.addEventListener(`DOMContentLoaded`,Co),document.addEventListener(`DOMContentLoaded`,Ho),document.addEventListener(`DOMContentLoaded`,Nc),document.addEventListener(`DOMContentLoaded`,Kf),document.addEventListener(`DOMContentLoaded`,()=>pT()),document.addEventListener(`DOMContentLoaded`,async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await M(async()=>{let{refreshAgentNames:e,initScrollToBottomBtn:t}=await Promise.resolve().then(()=>oS);return{refreshAgentNames:e,initScrollToBottomBtn:t}},void 0);e(),t()}),document.addEventListener(`DOMContentLoaded`,()=>{let e=new URLSearchParams(window.location.search).has(`popup`),t=document.getElementById(`detachBtn`),n=document.getElementById(`attachBtn`),i=e?n:t;e?n&&(n.style.display=`flex`):t&&(t.style.display=`flex`);let o=()=>{if(!i)return;let t=N.pendingCallApiSessionIds&&N.pendingCallApiSessionIds.size>0;i.disabled=t,i.style.opacity=t?`0.35`:``,i.style.cursor=t?`not-allowed`:`pointer`,i.title=r(t?`detach.taskRunning`:e?`header.attachTitle`:`header.detachTitle`)};o(),document.addEventListener(`generating-state-changed`,o),t&&t.addEventListener(`click`,async()=>{if(N.pendingCallApiSessionIds&&N.pendingCallApiSessionIds.size>0){L(r(`detach.taskRunning`),`warning`);return}try{if((await chrome.runtime.sendMessage({type:`DETACH_SIDEPANEL`,width:window.innerWidth}))?.success)try{window.close()}catch{}}catch(e){a.warn(`[SidePanel] detach failed:`,e?.message)}}),n&&n.addEventListener(`click`,async()=>{if(N.pendingCallApiSessionIds&&N.pendingCallApiSessionIds.size>0){L(r(`detach.taskRunning`),`warning`);return}try{let e=(await chrome.windows.getCurrent()).id;await chrome.runtime.sendMessage({type:`ATTACH_SIDEPANEL`,windowId:e});try{window.close()}catch{}}catch(e){a.warn(`[SidePanel] attach failed:`,e?.message)}})});export{qm as t};