ai-helper-agent 2.8.7 → 2.8.9

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.
@@ -0,0 +1,3 @@
1
+ import{a as e,c as t,r as n}from"./i18n-DvmxOw8q.js";import{Ct as r}from"./model-profiles-C3kJEHM6.js";var i=`tokenStats`,a=new Set([`selection_toolbar`]);function o(e){let t={id:`tcr_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,sessionId:e.sessionId,timestamp:new Date().toISOString(),model:e.model||`unknown`,promptTokens:e.promptTokens||0,completionTokens:e.completionTokens||0,totalTokens:e.totalTokens||0,contextWindow:e.contextWindow||256e3,contextUsageRate:e.contextWindow>0?(e.promptTokens||0)/e.contextWindow:0,callType:e.callType||`unknown`};return r(i,`readwrite`,(e,n)=>{let r=e.put(t);r.onsuccess=()=>n(!0),r.onerror=()=>n(!1)})}function s(e){return r(i,`readonly`,(t,n)=>{let r=t.index(`sessionId`),i=e?r.getAll(IDBKeyRange.bound(e,e+`￿`)):t.getAll();i.onsuccess=()=>{let t=(i.result||[]).filter(t=>t.sessionId===e||e&&t.sessionId?.startsWith(e+`_`));if(t.length===0){n({sessionId:e,totalPromptTokens:0,totalCompletionTokens:0,totalTokens:0,apiCallCount:0,avgContextUsageRate:0,maxContextUsageRate:0,minContextUsageRate:0,records:[]});return}let r=t.map(e=>e.contextUsageRate||0).filter(e=>e>0);n({sessionId:e,totalPromptTokens:t.reduce((e,t)=>e+(t.promptTokens||0),0),totalCompletionTokens:t.reduce((e,t)=>e+(t.completionTokens||0),0),totalTokens:t.reduce((e,t)=>e+(t.totalTokens||0),0),apiCallCount:t.length,avgContextUsageRate:r.length>0?r.reduce((e,t)=>e+t,0)/r.length:0,maxContextUsageRate:r.length>0?Math.max(...r):0,minContextUsageRate:r.length>0?Math.min(...r):0,records:t.sort((e,t)=>new Date(t.timestamp)-new Date(e.timestamp)).slice(0,20)})},i.onerror=()=>n(null)})}function c(){return r(i,`readonly`,(e,t)=>{let n=e.getAll();n.onsuccess=()=>{let e=n.result||[];if(e.length===0){t({totalPromptTokens:0,totalCompletionTokens:0,totalTokens:0,totalApiCalls:0,totalSessions:0,lastUpdated:null});return}let r=new Set(e.map(e=>e.sessionId).filter(e=>e&&!a.has(e)));t({totalPromptTokens:e.reduce((e,t)=>e+(t.promptTokens||0),0),totalCompletionTokens:e.reduce((e,t)=>e+(t.completionTokens||0),0),totalTokens:e.reduce((e,t)=>e+(t.totalTokens||0),0),totalApiCalls:e.length,totalSessions:r.size,lastUpdated:e.reduce((e,t)=>t.timestamp>e?t.timestamp:e,``)})},n.onerror=()=>t(null)})}function l(){return r(i,`readwrite`,(e,t)=>{let n=e.clear();n.onsuccess=()=>t(!0),n.onerror=()=>t(!1)})}function u(e=30){return r(i,`readonly`,(t,n)=>{let r=new Date(new Date().getTime()-e*24*60*60*1e3),i=t.index(`timestamp`).getAll(IDBKeyRange.lowerBound(r.toISOString()));i.onsuccess=()=>{let e=i.result||[],t=new Map;e.forEach(e=>{let n=new Date(e.timestamp);if(n<r)return;let i=n.toISOString().split(`T`)[0];t.has(i)||t.set(i,{date:i,totalTokens:0,apiCalls:0});let a=t.get(i);a.totalTokens+=e.totalTokens||0,a.apiCalls+=1}),n(Array.from(t.values()).sort((e,t)=>e.date.localeCompare(t.date)))},i.onerror=()=>n([])})}function d(e,t){return r(i,`readonly`,(n,r)=>{let i=n.index(`timestamp`).getAll(IDBKeyRange.bound(e,t));i.onsuccess=()=>{let n=i.result||[],o=new Date(e),s=new Date(t),c=n.filter(e=>{let t=new Date(e.timestamp);return t>=o&&t<=s});if(c.length===0){r({totalPromptTokens:0,totalCompletionTokens:0,totalTokens:0,totalApiCalls:0,totalSessions:0,lastUpdated:null});return}let l=new Set(c.map(e=>e.sessionId).filter(e=>e&&!a.has(e)));r({totalPromptTokens:c.reduce((e,t)=>e+(t.promptTokens||0),0),totalCompletionTokens:c.reduce((e,t)=>e+(t.completionTokens||0),0),totalTokens:c.reduce((e,t)=>e+(t.totalTokens||0),0),totalApiCalls:c.length,totalSessions:l.size,lastUpdated:c.reduce((e,t)=>t.timestamp>e?t.timestamp:e,``)})},i.onerror=()=>r(null)})}function f(){return r(i,`readonly`,(e,t)=>{let n=e.getAll();n.onsuccess=()=>{let e=n.result||[],r=new Map;e.forEach(e=>{let t=e.model||`unknown`;r.has(t)||r.set(t,0),r.set(t,r.get(t)+(e.totalTokens||0))});let i=Array.from(r.values()).reduce((e,t)=>e+t,0);t(Array.from(r.entries()).map(([e,t])=>({model:e,totalTokens:t,percentage:i>0?t/i*100:0})).sort((e,t)=>t.totalTokens-e.totalTokens))},n.onerror=()=>t([])})}function p(){return r(i,`readonly`,(e,t)=>{let n=e.getAll();n.onsuccess=()=>{let e=n.result||[],r=new Map;e.forEach(e=>{let t=e.callType||`unknown`;r.has(t)||r.set(t,0),r.set(t,r.get(t)+(e.totalTokens||0))});let i=Array.from(r.values()).reduce((e,t)=>e+t,0);t(Array.from(r.entries()).map(([e,t])=>({callType:e,totalTokens:t,percentage:i>0?t/i*100:0})).sort((e,t)=>t.totalTokens-e.totalTokens))},n.onerror=()=>t([])})}e(`zh`,{todoTime:{justNow:`刚刚`,minutesAgo:`{n} 分钟前`,hoursAgo:`{n} 小时前`,daysAgo:`{n} 天前`,today:`今天`,tomorrow:`明天`,yesterday:`昨天`,doneStamp:`{date} 完成`,overdueStamp:`已逾期 {date}`},todoDigest:{active:`待办`,done:`已完成`,note:`备注`,due:`截止`,highPriority:`高优先级`},todoExport:{title:`待办清单`,count:`共 {n} 条`,scopeAll:`全部`,scopeActive:`仅待办`,scopeDone:`仅已完成`}}),e(`en`,{todoTime:{justNow:`just now`,minutesAgo:`{n} min ago`,hoursAgo:`{n} h ago`,daysAgo:`{n} d ago`,today:`Today`,tomorrow:`Tomorrow`,yesterday:`Yesterday`,doneStamp:`done {date}`,overdueStamp:`overdue {date}`},todoDigest:{active:`To do`,done:`Done`,note:`Note`,due:`Due`,highPriority:`high priority`},todoExport:{title:`Todo list`,count:`{n} items`,scopeAll:`All`,scopeActive:`To do only`,scopeDone:`Done only`}});var m={PENDING:`pending`,DOING:`doing`,DONE:`done`},h={HIGH:`high`,MEDIUM:`medium`,LOW:`low`},g=[m.PENDING,m.DOING,m.DONE],_=[h.HIGH,h.MEDIUM,h.LOW],v=[`http:`,`https:`],y=60*1e3,b=60*y,x=24*b,S=[`all`,`active`,`done`],C=[`id`,`title`,`note`,`status`,`prevStatus`,`priority`,`link`,`order`,`dueAt`,`createdAt`,`updatedAt`,`completedAt`];function w(e){return g[(g.indexOf(e)+1)%g.length]}function T(e){return g.includes(e)}function E(e){return _.includes(e)?e:null}function D(e){let t=E(e);if(!t)return _[0];let n=_.indexOf(t);return n===_.length-1?null:_[n+1]}function O(e){let t=String(e??``).trim().replace(/^\/+/,``);if(!t)return{url:``,host:``,valid:!0};let n=/^[a-z][a-z0-9+.-]*:/i.test(t)?t:`https://${t}`,r=null;try{r=new URL(n)}catch{return{url:``,host:``,valid:!1}}return v.includes(r.protocol)?{url:r.href,host:k(r.hostname),valid:!0}:{url:``,host:``,valid:!1}}function k(e,t=22){let n=String(e||``).toLowerCase().replace(/^www\./,``);return n.length>t?`${n.slice(0,t-1)}…`:n}function A(e){let{url:t,host:n}=O(e&&e.link);return t?n:``}function j(e){let{url:t,valid:n}=O(e);return n&&!!t}function ee(e){return(e&&e.prevStatus)===m.DOING?m.DOING:m.PENDING}function M(e){return`todo_`+e.toString(36)+`_`+Math.random().toString(36).substring(2,6)}function N(e,t={},n=Date.now()){return{id:M(n),title:String(e||``).trim(),note:String(t.note||``).trim(),status:m.PENDING,prevStatus:null,priority:E(t.priority),link:O(t.link).url,order:0,dueAt:Number.isFinite(t.dueAt)?t.dueAt:null,createdAt:n,updatedAt:n,completedAt:null}}function P(e){let t=e&&typeof e==`object`?e:{},n=Number.isFinite(t.createdAt)?t.createdAt:Date.now(),r=T(t.status)?t.status:m.PENDING;return{id:String(t.id||``),title:String(t.title||``).trim(),note:String(t.note||``),status:r,prevStatus:r===m.DONE&&T(t.prevStatus)&&t.prevStatus!==m.DONE?t.prevStatus:null,priority:E(t.priority),link:O(t.link).url,order:Number.isFinite(t.order)?t.order:2**53-1,dueAt:Number.isFinite(t.dueAt)?t.dueAt:null,createdAt:n,updatedAt:Number.isFinite(t.updatedAt)?t.updatedAt:n,completedAt:Number.isFinite(t.completedAt)?t.completedAt:null}}function F(e,t){return e.order===t.order?e.createdAt-t.createdAt:e.order-t.order}function I(e,t){return(t.completedAt||t.updatedAt||0)-(e.completedAt||e.updatedAt||0)}function L(e){let t=Array.isArray(e)?e.map(P):[],n=[],r=[];for(let e of t)e.status===m.DONE?r.push(e):n.push(e);return n.sort(F),r.sort(I),{active:n,done:r,stats:{total:t.length,done:r.length,active:n.length,pending:n.filter(e=>e.status===m.PENDING).length,doing:n.filter(e=>e.status===m.DOING).length}}}function R(e,t,n){let r=Array.isArray(e)?e.slice():[];if(t<0||t>=r.length)return r;let[i]=r.splice(t,1),a=Math.max(0,Math.min(n,r.length));return r.splice(a,0,i),r}function z(e,t=Date.now()){return(Array.isArray(e)?e:[]).map((e,n)=>e.order===n?e:{...e,order:n,updatedAt:t})}function B(e){let{active:t}=L(e);return t.reduce((e,t)=>Number.isFinite(t.order)&&t.order<2**53-1?Math.max(e,t.order):e,-1)+1}function V(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function H(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function U(e,t=Date.now()){let r=new Date(e),i=new Date(t);if(isNaN(r.getTime()))return``;if(n()===`en`){let e=r.toLocaleString(`en-US`,{month:`short`});return r.getFullYear()===i.getFullYear()?`${e} ${r.getDate()}`:`${e} ${r.getDate()}, ${r.getFullYear()}`}return r.getFullYear()===i.getFullYear()?`${r.getMonth()+1}月${r.getDate()}日`:`${r.getFullYear()}年${r.getMonth()+1}月${r.getDate()}日`}function W(e,n=Date.now()){if(!Number.isFinite(e))return``;let r=n-e;return r<y?t(`todoTime.justNow`):r<b?t(`todoTime.minutesAgo`,{n:Math.floor(r/y)}):r<x?t(`todoTime.hoursAgo`,{n:Math.floor(r/b)}):r<7*x?t(`todoTime.daysAgo`,{n:Math.floor(r/x)}):U(e,n)}function G(e,n=Date.now()){if(!Number.isFinite(e))return``;let r=new Date(e),i=new Date(n);if(isNaN(r.getTime()))return``;if(V(r,i))return t(`todoTime.today`);let a=Math.round((H(r)-H(i))/x);return a===1?t(`todoTime.tomorrow`):a===-1?t(`todoTime.yesterday`):U(e,n)}function K(e,n=Date.now()){let r=e&&Number.isFinite(e.completedAt)?e.completedAt:e&&e.updatedAt;return Number.isFinite(r)?t(`todoTime.doneStamp`,{date:U(r,n)}):``}function q(e,t=Date.now()){if(!e||!Number.isFinite(e.dueAt)||e.status===m.DONE)return!1;let n=H(new Date(t));return H(new Date(e.dueAt))<n}function J(e){return String(e||``).replace(/\s*\n+\s*/g,` `).trim()}function Y(e,n,r=!0){let i=O(e.link).url,a=i?` [${A(e)}](${i})`:``;if(e.status===m.DONE){let i=Number.isFinite(e.completedAt)?`(${t(`todoTime.doneStamp`,{date:U(e.completedAt,n)})})`:``;return`${r?`- [x] `:``}${J(e.title)}${i}${a}`}let o=e.status===m.DOING?`⏳ `:``,s=Number.isFinite(e.dueAt)?`(${t(`todoDigest.due`)} ${G(e.dueAt,n)})`:``,c=e.priority===h.HIGH?`(${t(`todoDigest.highPriority`)})`:``;return`${r?`- [ ] `:``}${o}${J(e.title)}${c}${s}${a}`}function X(e){return!e.note||!e.note.trim()?``:` - ${t(`todoDigest.note`)}:${J(e.note)}`}function Z(e,t={}){let n=P(e);if(!n.title)return``;let r=[Y(n,t.now||Date.now(),!t.plain)],i=X(n);return i&&r.push(i),r.join(`
2
+ `)}function Q(e){return S.includes(e)?e:`all`}function $(e,t=`all`){let{active:n,done:r}=L(e),i=Q(t);return i===`active`?n:i===`done`?r:[...n,...r]}function te(e){let t=P(e),n={};for(let e of C)n[e]=t[e];return n}function ne(e,t={}){let n=Q(t.scope);return{kind:`todos`,version:1,scope:n,exportedAt:t.now||Date.now(),todos:$(e,n).map(te)}}function re(e,n={}){let r=Q(n.scope),i=n.now||Date.now(),a=$(e,r),o=t(`todoExport.scope${r===`active`?`Active`:r===`done`?`Done`:`All`}`),s=[`# ${t(`todoExport.title`)}(${o} · ${t(`todoExport.count`,{n:a.length})})`,``];for(let e of a){s.push(Y(e,i));let t=X(e);t&&s.push(t)}return s.join(`
3
+ `)}function ie(e){let t=null;return Array.isArray(e)?t=e:e&&typeof e==`object`&&Array.isArray(e.todos)&&(t=e.todos),t?{ok:!0,todos:t.filter(e=>e&&typeof e==`object`&&!Array.isArray(e))}:{ok:!1,reason:`format`}}function ae(e,t,n=Date.now()){let r=(Array.isArray(e)?e:[]).map(P),i=new Set(r.map(e=>e.id).filter(Boolean)),a=r.reduce((e,t)=>Number.isFinite(t.order)&&t.order<2**53-1?Math.max(e,t.order):e,-1)+1,o=[],s=0;for(let e of Array.isArray(t)?t:[]){let t=String(e&&e.title||``).trim();if(!t){s+=1;continue}let r=String(e&&e.id||``).trim();if(r&&i.has(r)){s+=1;continue}r||=M(n),i.add(r),o.push({...P({...e,id:r,title:t}),order:a++})}return{todos:[...r,...o],addedItems:o,added:o.length,skipped:s}}export{d as A,R as C,l as D,z as E,p as M,f as N,u as O,o as P,ie as S,$ as T,D as _,re as a,E as b,G as c,j as d,q as f,B as g,ae as h,ne as i,s as j,c as k,W as l,A as m,m as n,N as o,T as p,Z as r,K as s,h as t,L as u,w as v,ee as w,P as x,O as y};
@@ -0,0 +1,174 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/workspace-manager-DVPkwn2d.js","assets/chunk-CMxvf4Kt.js","assets/model-profiles-C3kJEHM6.js","assets/i18n-DvmxOw8q.js","assets/context-indicator-CWyjBBv3.js","assets/session-store-owqj23pJ.js","assets/voice-shortcut-Dtt3nhkz.js","assets/agent-store-QTeMyM9O.js"])))=>i.map(i=>d[i]);
2
+ import{a as e,c as t,l as n,r}from"./i18n-DvmxOw8q.js";import{N as i,b as a,rn as o,wt as s,x as c}from"./model-profiles-C3kJEHM6.js";import{o as l}from"./agent-store-QTeMyM9O.js";var u=`appTheme`,d=[`light`,`dark`,`system`],f=`light`,p=`light`,m=null,h=null,g=[],_=!1;function v(e){let t=e!==p;p=e,typeof document<`u`&&document.documentElement.setAttribute(`data-theme`,e);try{localStorage.setItem(`appThemeResolved`,e)}catch{}t&&g.slice().forEach(t=>{try{t(e)}catch(e){console.warn(`[theme] subscriber error`,e)}})}function y(e){return e===`system`?typeof matchMedia<`u`&&matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`:e===`dark`?`dark`:`light`}(function(){try{let e=typeof localStorage<`u`&&localStorage.getItem(`appThemeResolved`);(e===`dark`||e===`light`)&&(p=e,typeof document<`u`&&document.documentElement.setAttribute(`data-theme`,e))}catch{}})();function b(){return f}function x(){return p}function S(e){g.push(e)}async function ee(){typeof matchMedia<`u`&&(m=matchMedia(`(prefers-color-scheme: dark)`),h&&m.removeEventListener(`change`,h),h=()=>{f===`system`&&v(y(`system`))},m.addEventListener(`change`,h)),!_&&typeof chrome<`u`&&chrome.storage&&chrome.storage.onChanged&&(chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&e.appTheme&&d.includes(e.appTheme.newValue)&&(f=e.appTheme.newValue,v(y(f)))}),_=!0);let e=await new Promise(e=>{try{chrome.storage.local.get([u],t=>{if(chrome.runtime&&chrome.runtime.lastError){e(null);return}e(t||{})})}catch{e(null)}});e!==null&&(f=d.includes(e[u])?e[u]:`light`,v(y(f)))}async function te(e){d.includes(e)&&(f=e,v(y(e)),await new Promise(t=>chrome.storage.local.set({appTheme:e},t)))}e(`zh`,{util:{cmdHintPowerShell:"(请使用 PowerShell 语法,如 `Get-ChildItem`、`Set-Content`、`Remove-Item` 等)",cmdHintCmd:"(请使用 CMD 语法,如 `dir`、`echo`、`del` 等)",cmdHintGitBash:"(请使用 Unix 命令,如 `ls`、`cat`、`rm` 等,路径使用正斜杠 `/`)",cmdHintPowerShellShort:`(请使用 PowerShell 语法)`,cmdHintUnix:"(请使用 Unix 命令,如 `ls`、`cat`、`rm` 等)",cmdExecEnvTitle:`## 命令执行环境`,cmdExecOsShell:`**操作系统/Shell**`,cmdExecWorkdir:`工作目录`,cmdExecWorkdirUnset:`未设置`,assistantTerm:`- **助手**:用户创建的 AI 智能体,每个助手有独立的系统提示词和工具权限,可独立工作或被其他助手调度执行子任务`,noDesc:`无描述`,subDispatchTitle:`## 子助手调度`,subDispatchDesc:`使用 dispatch_task(subAgentId, task) 分派子任务给其他助手执行,支持并行调用。`,subDispatchAvailable:`可用子助手:`,agentTerm:`- **代理**:远端执行服务,提供文件操作、命令执行等能力。可通过 manage_agent 工具查询或切换代理`,agentHostLabel:`- 代理主机地址:`,agentHostHint:`(访问代理端服务时请优先使用此地址)`,terminologyTitle:`## 术语定义`,taskPlanningTitle:`## 任务拆解`,taskPlanningDesc:`复杂任务(多步骤、有依赖)拆解为子任务,通常 2-6 个、最多不超过 8 个;简单任务(1-2 步即可完成)直接执行,不要为凑数而拆分。使用 plan_task(taskDescription, subtasks) 提交方案。重要:调用 plan_task 时必须单独调用,同一轮响应中不要同时返回其他工具调用;其他想执行的动作请编入子任务描述,由子任务执行。`,artifactDeclTitle:`## 文件产物声明`,artifactDeclDesc:`当本次任务通过脚本或命令在工作目录内创建/修改了文件(尤其是运行时才确定路径的文件,如带日期的报表),请在最终回答末尾各用一行声明每个产物,格式严格为:[[artifact:相对工作目录或绝对路径|可选中文说明]]。示例:[[artifact:报表_2026-10-20.xlsx|书签统计报表]]。只列本次真实产生的文件,不要虚构、不要列未生成的文件;说明可省略。这些标记不会展示给用户。`,memoryTitle:`## 记忆`,memoryRules:`- 统一工具 agent_memory,通过 action 区分:store(增删改)/recall(检索)/manage(审查清理)
3
+ - store: subAction=add需type+content,update需memoryId+type,**delete仅需memoryId无需type**。**删除前先recall查id**
4
+ - recall: query用关键词(如"考试"),不用完整句子。可选memoryType和limit
5
+ - manage: subAction=review审查价值,compact清理低价值
6
+ - 存长期价值信息,加tags和importance(1-10)便于检索
7
+ - importance语义:8-10=跨对话高频相关(环境约束/技术偏好/工作习惯),会常驻系统提示词;5-7=窄场景重要信息(项目详情/配置记录),按需召回;1-4=低价值
8
+ - 不存凭据原文(密码/授权码/密钥),只存位置指针(如"授权码存于 xxx/.env")`,importanceLabel:`重要性`,tagsLabel:`标签`,permanentNotesTitle:`## 永久注意事项`,permanentNotesMore:`> 另有 {count} 条历史记忆(涵盖:{topics} 等主题)。回答涉及本机环境、已装工具/技能、历史项目、个人偏好或过往记录的问题前,先调用 agent_memory 检索(action=recall)再作答;不确定时宁可多召回一次。`,permanentNotesMoreNoTopics:`> 另有 {count} 条历史记忆。回答涉及本机环境、已装工具/技能、历史项目、个人偏好或过往记录的问题前,先调用 agent_memory 检索(action=recall)再作答;不确定时宁可多召回一次。`,currentEnvTitle:`## 当前环境`,currentTimeLabel:`当前时间:`,browserLabel:`浏览器:Chrome 扩展 (Side Panel)`,defaultPromptIntro:`AI Helper:IT技术助手。`,capabilityTitle:`## 能力`,capabilityDesc:`编程开发与调试(Java/Python/JavaScript/Go/C++)、架构优化、性能调优、代码审查、文档编写、浏览器工具调用`,taskPlanningJoin:`、任务规划`,requirementTitle:`## 要求`,requirementDesc:`精准技术术语,代码示例可运行,Markdown格式,方案可落地,不生成安全违规代码`,envTitle:`## 环境`}}),e(`en`,{util:{cmdHintPowerShell:"(Use PowerShell syntax, e.g. `Get-ChildItem`, `Set-Content`, `Remove-Item`, etc.)",cmdHintCmd:"(Use CMD syntax, e.g. `dir`, `echo`, `del`, etc.)",cmdHintGitBash:"(Use Unix commands, e.g. `ls`, `cat`, `rm`, etc. Use forward slashes `/` for paths)",cmdHintPowerShellShort:`(Use PowerShell syntax)`,cmdHintUnix:"(Use Unix commands, e.g. `ls`, `cat`, `rm`, etc.)",cmdExecEnvTitle:`## Command Execution Environment`,cmdExecOsShell:`**OS/Shell**`,cmdExecWorkdir:`Working directory`,cmdExecWorkdirUnset:`not set`,assistantTerm:`- **Assistant**: An AI agent created by the user. Each assistant has its own system prompt and tool permissions, and can work independently or be dispatched by other assistants to perform subtasks`,noDesc:`No description`,subDispatchTitle:`## Sub-assistant Dispatch`,subDispatchDesc:`Use dispatch_task(subAgentId, task) to dispatch subtasks to other assistants. Parallel calls are supported.`,subDispatchAvailable:`Available sub-assistants:`,agentTerm:`- **Agent**: A remote execution service that provides file operations, command execution, and other capabilities. Use the manage_agent tool to query or switch agents`,agentHostLabel:`- Agent host: `,agentHostHint:`(Please use this address first when accessing agent services)`,terminologyTitle:`## Terminology`,taskPlanningTitle:`## Task Decomposition`,taskPlanningDesc:`Break down complex tasks (multi-step, with dependencies) into subtasks — typically 2-6, at most 8; execute simple tasks (doable in 1-2 steps) directly and never split just to hit a count. Use plan_task(taskDescription, subtasks) to submit the plan. Important: when calling plan_task, call it alone — do not return other tool calls in the same turn; put any other intended actions into the subtask descriptions for the subtasks to execute.`,artifactDeclTitle:`## File Artifact Declaration`,artifactDeclDesc:`When this task creates/modifies files in the working directory via scripts or commands (especially paths only determined at runtime, e.g. dated reports), append one line per artifact at the very end of your final answer, strictly formatted as: [[artifact:workspace-relative or absolute path|optional note]]. Example: [[artifact:report_2026-10-20.xlsx|bookmark stats report]]. List only files truly produced this task; never fabricate or declare files that were not generated; the note is optional. These markers are not shown to the user.`,memoryTitle:`## Memory`,memoryRules:`- Unified tool agent_memory, distinguished by action: store (add/update/delete) / recall (retrieve) / manage (review/cleanup)
9
+ - store: subAction=add requires type+content, update requires memoryId+type, **delete only requires memoryId (no type)**. **Always recall first to find the id before deleting**
10
+ - recall: use keywords for query (e.g. "exam"), not full sentences. Optional memoryType and limit
11
+ - manage: subAction=review to assess value, compact to clean up low-value entries
12
+ - Store long-term valuable information; add tags and importance (1-10) for easier retrieval
13
+ - importance semantics: 8-10 = relevant across most conversations (environment constraints / tech preferences / work habits), always injected into the system prompt; 5-7 = important but narrow-scope info (project details / config records), retrieved on demand; 1-4 = low value
14
+ - Never store raw credentials (passwords / auth codes / keys); store only a location pointer (e.g. "auth code lives in xxx/.env")`,importanceLabel:`Importance`,tagsLabel:`Tags`,permanentNotesTitle:`## Permanent Notes`,permanentNotesMore:`> There are {count} more historical memories (covering: {topics}, etc.). Before answering questions about the local environment, installed tools/skills, past projects, personal preferences, or prior records, retrieve them first via agent_memory (action=recall); when unsure, recall once more rather than skip.`,permanentNotesMoreNoTopics:`> There are {count} more historical memories. Before answering questions about the local environment, installed tools/skills, past projects, personal preferences, or prior records, retrieve them first via agent_memory (action=recall); when unsure, recall once more rather than skip.`,currentEnvTitle:`## Current Environment`,currentTimeLabel:`Current time: `,browserLabel:`Browser: Chrome Extension (Side Panel)`,defaultPromptIntro:`AI Helper: IT Technical Assistant.`,capabilityTitle:`## Capabilities`,capabilityDesc:`Programming & debugging (Java/Python/JavaScript/Go/C++), architecture optimization, performance tuning, code review, documentation, browser tool calls`,taskPlanningJoin:`, task planning`,requirementTitle:`## Requirements`,requirementDesc:`Precise technical terminology, runnable code examples, Markdown format, actionable solutions, no security-violating code`,envTitle:`## Environment`}});function C(e,t=`info`,n=3e3){let r=document.getElementById(`toastContainer`);if(!r)return;let i=document.createElement(`div`);i.className=`toast ${t}`,i.textContent=e,r.appendChild(i),requestAnimationFrame(()=>{i.classList.add(`toast-show`)}),setTimeout(()=>{i.classList.remove(`toast-show`),setTimeout(()=>{i.parentNode&&i.parentNode.removeChild(i)},300)},n)}function ne(){let e=document.getElementById(`userInput`);if(!e||a.isScrolling)return;e.style.height=`auto`;let t=e.scrollHeight;t<=40?e.style.height=``:e.style.height=Math.min(t,100)+`px`,w()}function w(){let e=document.querySelector(`.input-wrapper`),t=document.querySelector(`.input-container`);if(!e||!t)return;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect().bottom-n.top+8;t.style.setProperty(`--dropdown-bottom`,r+`px`)}function re(e){if(!e)return``;let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}function T(e){return e?String(e).replace(/&/g,`&amp;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`):``}function ie(e){return!e||e<0?`0ms`:e<1e3?`${Math.round(e)}ms`:e<6e4?`${ae(e/1e3)}s`:e<36e5?`${ae(e/6e4)}min`:`${ae(e/36e5)}h`}function ae(e){let t=Math.round(e*10)/10;return Number.isInteger(t)?String(t):t.toFixed(1)}function E(e){return String(e).padStart(2,`0`)}function oe(e){if(!e)return``;let t=new Date(e);if(isNaN(t.getTime()))return``;let n=`${E(t.getHours())}:${E(t.getMinutes())}`,i=new Date,a=r()!==`en`;return t.getFullYear()===i.getFullYear()&&t.getMonth()===i.getMonth()&&t.getDate()===i.getDate()?n:a?t.getFullYear()===i.getFullYear()?`${t.getMonth()+1}月${t.getDate()}日 ${n}`:`${t.getFullYear()}/${t.getMonth()+1}/${t.getDate()} ${n}`:t.getFullYear()===i.getFullYear()?`${t.toLocaleString(`en-US`,{month:`short`})} ${t.getDate()}, ${n}`:`${t.getFullYear()}/${E(t.getMonth()+1)}/${E(t.getDate())}, ${n}`}function se(e){if(!e)return``;let t=new Date(e);if(isNaN(t.getTime()))return``;let n=`${E(t.getHours())}:${E(t.getMinutes())}:${E(t.getSeconds())}`;return r()===`en`?`${t.getFullYear()}-${E(t.getMonth()+1)}-${E(t.getDate())} ${n}`:`${t.getFullYear()}年${t.getMonth()+1}月${t.getDate()}日 ${n}`}function ce(e){return!e||e<=0?`0`:e<1e3?String(e):e<1e4?Math.round(e/100)/10+`K`:e<1e6?Math.round(e/1e3)+`K`:Math.round(e/1e5)/10+`M`}function D(e){return!e&&e!==0?`0`:Number(e).toLocaleString(`en-US`)}function le(e){if(!e||!Array.isArray(e))return null;let t=0,n=0,r=0,i=!1;for(let a of e){let e=a.apiResponse?.tokenUsage;e&&(t+=e.prompt_tokens||0,n+=e.completion_tokens||0,r+=e.total_tokens||(e.prompt_tokens||0)+(e.completion_tokens||0),i=!0)}return i?{promptTokens:t,completionTokens:n,totalTokens:r}:null}e(`zh`,{tokenPopup:{title:`Token 消耗明细`,total:`总计`,input:`输入`,output:`输出`,inputUnit:`tokens`,outputUnit:`tokens`,percent:`{p}%`,balanceTitle:`账户余额`,balanceTotal:`总余额`,balanceGranted:`赠送余额`,balanceToppedUp:`充值余额`,balanceLoading:`查询中...`}}),e(`en`,{tokenPopup:{title:`Token Usage Details`,total:`Total`,input:`Input`,output:`Output`,inputUnit:`tokens`,outputUnit:`tokens`,percent:`{p}%`,balanceTitle:`Account Balance`,balanceTotal:`Total Balance`,balanceGranted:`Granted`,balanceToppedUp:`Topped Up`,balanceLoading:`Loading...`}});function ue(e,n){if(!e)return;let r=document.querySelector(`.token-detail-popup`);if(r&&(r.remove(),n._tokenPopupOpen)){n._tokenPopupOpen=!1;return}document.querySelectorAll(`[data-token-popup-open]`).forEach(e=>{e._tokenPopupOpen=!1,e.removeAttribute(`data-token-popup-open`)});let{promptTokens:i,completionTokens:a,totalTokens:o}=e,s=o>0?Math.round(i/o*100):0,c=o>0?Math.round(a/o*100):0,l=document.createElement(`div`);l.className=`token-detail-popup`,l.innerHTML=`
15
+ <div class="token-popup-header">
16
+ <span class="token-popup-title">${t(`tokenPopup.title`)}</span>
17
+ <button class="token-popup-close" aria-label="${t(`common.close`)}">×</button>
18
+ </div>
19
+ <div class="token-popup-body">
20
+ <div class="token-popup-row token-popup-total">
21
+ <span class="token-popup-label">${t(`tokenPopup.total`)}</span>
22
+ <span class="token-popup-value">${D(o)}</span>
23
+ </div>
24
+ <div class="token-popup-divider"></div>
25
+ <div class="token-popup-row">
26
+ <span class="token-popup-label">${t(`tokenPopup.input`)}</span>
27
+ <div class="token-popup-right">
28
+ <span class="token-popup-value">${D(i)}</span>
29
+ <span class="token-popup-percent">${s}%</span>
30
+ </div>
31
+ </div>
32
+ <div class="token-popup-row">
33
+ <span class="token-popup-label">${t(`tokenPopup.output`)}</span>
34
+ <div class="token-popup-right">
35
+ <span class="token-popup-value">${D(a)}</span>
36
+ <span class="token-popup-percent">${c}%</span>
37
+ </div>
38
+ </div>
39
+ <div class="token-popup-balance-section" style="display:none;">
40
+ <div class="token-popup-divider"></div>
41
+ <div class="token-popup-balance-header">
42
+ <span class="token-popup-balance-title">${t(`tokenPopup.balanceTitle`)}</span>
43
+ </div>
44
+ <div class="token-popup-balance-content">
45
+ <span class="token-popup-balance-loading">${t(`tokenPopup.balanceLoading`)}</span>
46
+ </div>
47
+ </div>
48
+ </div>
49
+ `,document.body.appendChild(l);let u=n.getBoundingClientRect(),d=l.getBoundingClientRect(),f=window.innerHeight,p,m;p=u.top-d.height-8>0?u.top-d.height-8:u.bottom+8,m=u.left+u.width/2-d.width/2,m=Math.max(8,Math.min(m,window.innerWidth-d.width-8)),p+d.height>f-8&&(p=f-d.height-8),l.style.top=p+`px`,l.style.left=m+`px`,n._tokenPopupOpen=!0,n.setAttribute(`data-token-popup-open`,``),l.querySelector(`.token-popup-close`).addEventListener(`click`,e=>{e.stopPropagation(),l.remove(),n._tokenPopupOpen=!1,n.removeAttribute(`data-token-popup-open`)});let h=e=>{!l.contains(e.target)&&!n.contains(e.target)&&(l.remove(),n._tokenPopupOpen=!1,n.removeAttribute(`data-token-popup-open`),document.removeEventListener(`click`,h,!0))};setTimeout(()=>{document.addEventListener(`click`,h,!0)},0),de(l)}async function de(e){let n=e.querySelector(`.token-popup-balance-section`);if(!n)return;let r=()=>{n.style.display=`none`};try{let e=await chrome.storage.local.get([`apiBase`,`apiKey`,`modelName`]),i=(e.modelName||``).toLowerCase(),a=(e.apiBase||`https://api.deepseek.com`).replace(/\/+$/,``);if(!i.includes(`deepseek`)||!a.includes(`deepseek.com`))return;let o=s(e.apiKey);if(!o)return;n.style.display=``;let c=await fetch(`${a}/user/balance`,{method:`GET`,headers:{Authorization:`Bearer ${o}`}});if(!c.ok)throw Error(`HTTP ${c.status}`);let l=await c.json();if(!l.is_available||!l.balance_infos?.length){r();return}let u=l.balance_infos[0],d=u.currency||`CNY`,f=n.querySelector(`.token-popup-balance-content`);f.innerHTML=`
50
+ <div class="token-popup-row token-popup-total">
51
+ <span class="token-popup-label">${t(`tokenPopup.balanceTotal`)}</span>
52
+ <span class="token-popup-value token-popup-balance-value">${u.total_balance} ${d}</span>
53
+ </div>
54
+ <div class="token-popup-row">
55
+ <span class="token-popup-label">${t(`tokenPopup.balanceToppedUp`)}</span>
56
+ <span class="token-popup-value token-popup-balance-sub">${u.topped_up_balance} ${d}</span>
57
+ </div>
58
+ <div class="token-popup-row">
59
+ <span class="token-popup-label">${t(`tokenPopup.balanceGranted`)}</span>
60
+ <span class="token-popup-value token-popup-balance-sub">${u.granted_balance} ${d}</span>
61
+ </div>
62
+ `}catch(e){console.warn(`[TokenPopup] Failed to fetch DeepSeek balance:`,e),r()}}function fe(e,r){navigator.clipboard.writeText(e).then(()=>{let e=r.innerHTML;r.innerHTML=`<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
63
+ <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"/>
64
+ </svg>`,r.classList.add(`copied`),setTimeout(()=>{r.innerHTML=e,r.classList.remove(`copied`)},2e3)}).catch(i=>{n.error(`[SidePanel] copy failed:`,i);let a=document.createElement(`textarea`);a.value=e,a.style.position=`fixed`,a.style.left=`-999999px`,document.body.appendChild(a),a.select();try{document.execCommand(`copy`);let e=r.innerHTML;r.innerHTML=`<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
65
+ <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"/>
66
+ </svg>`,r.classList.add(`copied`),setTimeout(()=>{r.innerHTML=e,r.classList.remove(`copied`)},2e3)}catch{C(t(`common.copyFailed`),`error`)}document.body.removeChild(a)})}function pe(){if(typeof navigator<`u`&&navigator.userAgent){let e=navigator.userAgent;if(e.includes(`Windows`))return`Windows`;if(e.includes(`Mac OS`)||e.includes(`Macintosh`))return`macOS`;if(e.includes(`Linux`)&&!e.includes(`Android`))return`Linux`}return`Unknown`}function me(e=null,n=``){if(!a.agentPlatform||!a.agentPlatform.connected||!(a.enabledTools&&a.enabledTools.includes(`agent_exec`))||e!=null&&Array.isArray(e)&&!e.includes(`agent_exec`))return null;let r=a.agentPlatform,i=`unknown`,o=r.shell||`/bin/sh`,s=``;return r.platformName&&(r.platformName.toLowerCase().includes(`windows`)?(i=`Windows`,o.toLowerCase().includes(`powershell`)?(o=`PowerShell`,s=t(`util.cmdHintPowerShell`)):o.toLowerCase().includes(`cmd`)||o.toLowerCase().includes(`command`)?(o=`CMD`,s=t(`util.cmdHintCmd`)):o.toLowerCase().includes(`bash`)||r.platformName.toLowerCase().includes(`git`)?(o=`Git Bash`,s=t(`util.cmdHintGitBash`)):(o=`PowerShell`,s=t(`util.cmdHintPowerShellShort`))):r.platformName.toLowerCase().includes(`mac`)||r.platformName.toLowerCase().includes(`darwin`)?(i=`macOS`,o=o.toLowerCase().includes(`zsh`)?`zsh`:o.toLowerCase().includes(`bash`)?`bash`:`zsh`,s=t(`util.cmdHintUnix`)):r.platformName.toLowerCase().includes(`linux`)&&(i=`Linux`,o=o.toLowerCase().includes(`bash`)?`bash`:o.toLowerCase().includes(`zsh`)?`zsh`:o.toLowerCase().includes(`fish`)?`fish`:`bash`,s=t(`util.cmdHintUnix`))),{osType:i,shellType:o,platformName:r.platformName,arch:r.arch,workdir:n||``,commandHint:s}}function he(e,t){return t==null?!0:Array.isArray(t)&&t.includes(e)}async function ge(e=null,o={}){let s=new Date().toLocaleString(`zh-CN`),c=pe(),u=o.sessionId===void 0?a.activeSessionId:o.sessionId,d=o.workdir||``;if(!d&&a.agentPlatform?.connected)try{d=await i(u)||``}catch(e){n.warn(`[SystemPrompt] resolve workdir failed:`,e?.message||e)}let f=me(e?.toolIds,d),p=``;f&&(p=`
67
+
68
+ ${t(`util.cmdExecEnvTitle`)}
69
+ - ${t(`util.cmdExecOsShell`)}: ${f.osType} (${f.arch}) / ${f.shellType}
70
+ - ${t(`util.cmdExecWorkdir`)}: ${f.workdir||t(`util.cmdExecWorkdirUnset`)}
71
+ - ${f.commandHint}`);let m=(await l()).filter(t=>t.allowSubDispatch&&t.id!==(e?.id||``)),h=m.length>0&&he(`dispatch_task`,e?.toolIds),g=!1,_=null;try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=e.pairedAgents||[];if(g=t.length>0,g&&e.activeAgentId){let n=t.find(t=>t.id===e.activeAgentId);if(n?.url)try{_=new URL(n.url).hostname}catch{let e=n.url.replace(/^https?:\/\//,``).replace(/\/.*$/,``).split(`:`)[0];e&&(_=e)}}}catch{}let v=``;_&&(v=`\n${t(`util.agentHostLabel`)}${_}${t(`util.agentHostHint`)}`);let y=``,b=``,x=``;if(h){y=t(`util.assistantTerm`);let e=m.map(e=>`- **${e.id}** (${e.icon} ${e.name}): ${e.description||t(`util.noDesc`)}`).join(`
72
+ `);x=`
73
+
74
+ ${t(`util.subDispatchTitle`)}
75
+ ${t(`util.subDispatchDesc`)}
76
+
77
+ ${t(`util.subDispatchAvailable`)}
78
+ ${e}`}g&&(b=t(`util.agentTerm`));let S=``;if(y||b){let e=[y,b].filter(Boolean).join(`
79
+ `);S=`
80
+
81
+ ${t(`util.terminologyTitle`)}
82
+ ${e}`}let ee=a.useTools&&he(`plan_task`,e?.toolIds)?`
83
+
84
+ ${t(`util.taskPlanningTitle`)}
85
+ ${t(`util.taskPlanningDesc`)}`:``,te=a.useTools&&a.agentPlatform?.connected?`
86
+
87
+ ${t(`util.artifactDeclTitle`)}
88
+ ${t(`util.artifactDeclDesc`)}`:``,C=[`agent_memory`].some(t=>he(t,e?.toolIds)),ne=a.useTools&&C,w=a.useTools&&a.agentPlatform?.connected&&C?`
89
+
90
+ ${t(`util.memoryTitle`)}
91
+ ${t(`util.memoryRules`)}`:``,re=``;if(a.agentPlatform?.connected)try{let e=await O(),n=e.facts||[],i=e.remainingCount||0,a=n.length>0,o=i>0&&ne;if(a||o){let s=`
92
+
93
+ ${t(`util.permanentNotesTitle`)}
94
+ `;if(a&&(s+=n.map((e,n)=>`${n+1}. [${t(`util.importanceLabel`)}: ${e.importance||5}] ${e.content}${e.tags&&e.tags.length?` (${t(`util.tagsLabel`)}: ${e.tags.join(`, `)})`:``}`).join(`
95
+ `)+`
96
+ `),o){let n=e.remainingTags||[],a=n.join(r()===`zh`?`、`:`, `);s+=`
97
+ `+(n.length>0?t(`util.permanentNotesMore`,{count:i,topics:a}):t(`util.permanentNotesMoreNoTopics`,{count:i}))+`
98
+ `}re=s}}catch{}let T;if(T=e&&e.systemPrompt&&e.systemPrompt.trim()?e.systemPrompt:a.systemPrompt&&a.systemPrompt.trim()?a.systemPrompt:null,T){let n=`${T}${S}${re}
99
+
100
+ ${t(`util.currentEnvTitle`)}
101
+ - ${t(`util.currentTimeLabel`)}${s}
102
+ - ${t(`util.browserLabel`)} / ${c}${v}${p}${ee}${x}${w}${te}
103
+ `;try{let t=await _e(e?.toolIds,e?.skillIds);t&&(n+=`\n${t}\n`)}catch{}return n}let ie=`${t(`util.defaultPromptIntro`)}${S}${re}
104
+
105
+ ${t(`util.capabilityTitle`)}
106
+ ${t(`util.capabilityDesc`)}${a.useTools&&he(`plan_task`,e?.toolIds)?t(`util.taskPlanningJoin`):``}
107
+
108
+ ${t(`util.requirementTitle`)}
109
+ ${t(`util.requirementDesc`)}${ee}${x}${w}${te}
110
+
111
+ ${t(`util.envTitle`)}
112
+ ${s} | Chrome Side Panel / ${c}${v}${p}
113
+ `;try{let t=await _e(e?.toolIds,e?.skillIds);t&&(ie+=`\n${t}\n`)}catch{}return ie}async function _e(e,t){return Array.isArray(t)&&t.length===0||!(t!=null&&Array.isArray(t)&&t.length>0)&&e!=null&&Array.isArray(e)&&!e.includes(`agent_skill`)?``:new Promise(e=>{try{chrome.storage.local.get([`skillsEnabled`],n=>{if(n.skillsEnabled===!1){e(``);return}let r={type:`GET_AGENT_SKILL_PROMPTS`};t!=null&&Array.isArray(t)&&t.length>0&&(r.skillNames=t),chrome.runtime.sendMessage(r,t=>{if(chrome.runtime.lastError){e(``);return}e(t?.prompts||``)})})}catch{e(``)}})}async function O(){return new Promise(e=>{let t={facts:[],remainingCount:0,remainingTags:[]};try{chrome.runtime.sendMessage({type:`GET_PERMANENT_NOTES`},n=>{if(chrome.runtime.lastError||!n?.success){e(t);return}e({facts:n.facts||[],remainingCount:n.remainingCount||0,remainingTags:n.remainingTags||[]})})}catch{e(t)}})}function ve(e=null){let t=e&&e.temperature!=null?e.temperature:a.temperature,n=e&&e.topP!=null?e.topP:a.topP;return Promise.resolve({temperature:parseFloat(t.toFixed(2)),top_p:parseFloat(n.toFixed(2))})}function k(){return new Promise(e=>{chrome.runtime.sendMessage({type:`GET_CHAT_CONFIG`},t=>{t&&(a.chatConfig=t,n.debug(`[SidePanel] conversationconfiguration loaded:`,a.chatConfig)),e(t)})})}async function ye(){return new Promise(e=>{chrome.runtime.sendMessage({type:`GET_CHAT_CONFIG`},t=>{t&&(a.chatConfig=t,n.debug(`[SidePanel] sync loadconversationconfiguration:`,a.chatConfig)),e()})})}async function A(){return new Promise(e=>{chrome.tabs.query({active:!0,currentWindow:!0},t=>{t&&t.length>0&&t[0].id?(a.currentTabId=t[0].id,n.debug(`[SidePanel] get current Tab ID:`,a.currentTabId,`URL:`,t[0].url),e(a.currentTabId)):(n.warn(`[SidePanel] did not getvalid Tab ID`),e(null))})})}function be(){return new Promise(e=>{chrome.storage.local.get([`reactLoopTimeout`],t=>{e({apiTimeout:o.apiTimeout,loopTimeout:Math.min(Math.max(t.reactLoopTimeout||o.loopTimeout,6e5),864e5),toolTimeout:o.toolTimeout,clarifyTimeout:o.clarifyTimeout})})})}function xe(e){e&&(e.style.removeProperty(`--clamp-y`),requestAnimationFrame(()=>{let t=e.getBoundingClientRect();if(!t.height)return;let n=0;t.bottom>window.innerHeight-8&&(n=window.innerHeight-8-t.bottom),t.top+n<8&&(n=8-t.top),n&&e.style.setProperty(`--clamp-y`,`${Math.round(n)}px`)}))}function j(e){e&&e.style.removeProperty(`--clamp-y`)}var Se=`.message.user, .message.assistant, .user-context-bubble`;function Ce(e){if(!e)return[];let t=Array.from(e.querySelectorAll(Se));if(t.length===0)return[];let n=[],r=[];for(let e of t)e.classList.contains(`message`)&&e.classList.contains(`user`)?(n.push({start:r.length?r[0]:e,userElement:e,elements:[...r,e]}),r.length=0):n.length===0?r.push(e):n[n.length-1].elements.push(e);return n.length===0&&n.push({start:t[0],userElement:null,elements:t}),n}var we=2e3;function Te(e){if(!e||typeof document>`u`)return!1;let t=document.getElementById(`chatContainer`);if(!t)return!1;let n=null;for(let r of t.querySelectorAll(`[data-message-id]`))if(r.dataset.messageId===String(e)){n=r;break}return n?(n.scrollIntoView({behavior:`instant`,block:`start`}),n.classList.add(`bookmark-highlight`),setTimeout(()=>n.classList.remove(`bookmark-highlight`),we),!0):!1}function M(e,t,n=10){for(let r=0;r<e.length;r++)if(e[r].start.getBoundingClientRect().bottom>t+n)return r;return-1}function N(e,t,n,r=10){if(!Array.isArray(e)||e.length===0)return-1;let i=-1,a=1/0;for(let o=0;o<e.length;o++){let s=(e[o].userElement||e[o].start).getBoundingClientRect();if(s.bottom>t+r&&s.top<n)return o;let c=s.bottom<=t?t-s.bottom:s.top-n;c<a&&(a=c,i=o)}return i}function P(e,t,n){if(e<=0)return null;let r=t;if(r===-1){if(n!==`prev`)return null;r=e}let i=n===`prev`?r-1:r+1;return i>=0&&i<e?i:null}function Ee(e,t=120){let n=String(e||``).replace(/\s+/g,` `).trim();return n?n.length>t?`${n.slice(0,t)}…`:n:``}function De(e){if(!e)return``;let t=new Date(e);if(Number.isNaN(t.getTime()))return``;let n=e=>String(e).padStart(2,`0`),r=`${n(t.getHours())}:${n(t.getMinutes())}`,i=new Date;return t.toDateString()===i.toDateString()?r:`${t.getMonth()+1}-${t.getDate()} ${r}`}function Oe(e){let n=Ee(Array.from(e&&e.childNodes||[]).filter(e=>e.nodeType===Ae).map(e=>e.textContent).join(``));if(n)return n;let r=[];try{r=JSON.parse(e.dataset&&e.dataset.attachedFiles||`[]`)}catch{}let i=(Array.isArray(r)?r:[]).map(e=>e&&e.name).filter(Boolean);if(i.length)return Ee(i.length>1?`${i[0]} +${i.length-1}`:i[0]);let a=e.querySelectorAll?e.querySelectorAll(`.user-message-image`).length:0;return a?t(`chat.navQuestionImageCount`,{count:a}):t(`chat.navQuestionNoText`)}function ke(e,t){let n=String(t||``).trim().toLowerCase(),r=e.map((e,t)=>({group:e,index:t}));return n?r.filter(({group:e})=>Oe(e.userElement||e.start).toLowerCase().includes(n)):r}var Ae=3;function je(e,n,r,i=``){let a=ke(e,i),o=a.map(({group:e,index:t})=>{let r=e.userElement||e.start,i=Oe(r),a=r.dataset&&r.dataset.messageId||``,o=De(r.dataset&&r.dataset.timestamp),s=o?`${i} · ${o}`:i,c=t===n,l=`chat-nav-question-item${c?` current`:``}`,u=`<span class="idx">${t+1}</span>`,d=`<span class="chat-nav-question-text">${T(i)}</span>`,f=o?`<span class="chat-nav-question-time">${T(o)}</span>`:``;return`<button class="${l}" data-message-id="${T(a)}" data-group-index="${t}" aria-current="${c?`true`:`false`}" title="${T(s)}">${u}${d}${f}</button>`}).join(``),s=t(r?`chat.navUnpinLabel`:`chat.navPinLabel`),c=n>=0?n+1:e.length;return`${`<div class="chat-nav-question-header"><span>${t(`chat.navQuestionTitle`)}</span><button type="button" class="chat-nav-pin${r?` on`:``}" title="${T(s)}">${T(s)}</button><span class="count">${t(`chat.navPosition`,{current:c,total:e.length})}</span></div>`}${e.length>=6?`<div class="chat-nav-question-filter"><input type="search" class="chat-nav-question-search" data-role="nav-search" placeholder="${T(t(`chat.navSearchPlaceholder`))}" value="${T(i)}" aria-label="${T(t(`chat.navSearchPlaceholder`))}"></div>`:``}<div class="chat-nav-question-list">${(a.length===0?`<div class="chat-nav-question-empty">${T(t(`chat.navNoMatch`))}</div>`:``)||o}</div>`}function Me(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Ne(e){if(Array.isArray(e))return e}function Pe(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function Fe(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
114
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Ie(e,t){return Ne(e)||Pe(e,t)||Le(e,t)||Fe()}function Le(e,t){if(e){if(typeof e==`string`)return Me(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Me(e,t):void 0}}var Re=Object.entries,F=Object.setPrototypeOf,I=Object.isFrozen,ze=Object.getPrototypeOf,Be=Object.getOwnPropertyDescriptor,L=Object.freeze,R=Object.seal,Ve=Object.create,He=typeof Reflect<`u`&&Reflect,Ue=He.apply,We=He.construct;L||=function(e){return e},R||=function(e){return e},Ue||=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)},We||=function(e){return new e(...[...arguments].slice(1))};var Ge=W(Array.prototype.forEach),Ke=W(Array.prototype.lastIndexOf),qe=W(Array.prototype.pop),Je=W(Array.prototype.push),Ye=W(Array.prototype.splice),Xe=Array.isArray,Ze=W(String.prototype.toLowerCase),Qe=W(String.prototype.toString),$e=W(String.prototype.match),et=W(String.prototype.replace),tt=W(String.prototype.indexOf),nt=W(String.prototype.trim),rt=W(Number.prototype.toString),it=W(Boolean.prototype.toString),z=typeof BigInt>`u`?null:W(BigInt.prototype.toString),B=typeof Symbol>`u`?null:W(Symbol.prototype.toString),V=W(Object.prototype.hasOwnProperty),H=W(Object.prototype.toString),U=W(RegExp.prototype.test),at=ot(TypeError);function W(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return Ue(e,t,n)}}function ot(e){return function(){return We(e,[...arguments])}}function G(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ze;if(F&&F(e,null),!Xe(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(I(t)||(t[r]=e),i=e)}e[i]=!0}return e}function st(e){for(let t=0;t<e.length;t++)V(e,t)||(e[t]=null);return e}function K(e){let t=Ve(null);for(let r of Re(e)){var n=Ie(r,2);let i=n[0],a=n[1];V(e,i)&&(Xe(a)?t[i]=st(a):a&&typeof a==`object`&&a.constructor===Object?t[i]=K(a):t[i]=a)}return t}function ct(e){switch(typeof e){case`string`:return e;case`number`:return rt(e);case`boolean`:return it(e);case`bigint`:return z?z(e):`0`;case`symbol`:return B?B(e):`Symbol()`;case`undefined`:return H(e);case`function`:case`object`:{if(e===null)return H(e);let t=e,n=q(t,`toString`);if(typeof n==`function`){let e=n(t);return typeof e==`string`?e:H(e)}return H(e)}default:return H(e)}}function q(e,t){for(;e!==null;){let n=Be(e,t);if(n){if(n.get)return W(n.get);if(typeof n.value==`function`)return W(n.value)}e=ze(e)}function n(){return null}return n}function lt(e){try{return U(e,``),!0}catch{return!1}}var ut=L(`a.abbr.acronym.address.area.article.aside.audio.b.bdi.bdo.big.blink.blockquote.body.br.button.canvas.caption.center.cite.code.col.colgroup.content.data.datalist.dd.decorator.del.details.dfn.dialog.dir.div.dl.dt.element.em.fieldset.figcaption.figure.font.footer.form.h1.h2.h3.h4.h5.h6.head.header.hgroup.hr.html.i.img.input.ins.kbd.label.legend.li.main.map.mark.marquee.menu.menuitem.meter.nav.nobr.ol.optgroup.option.output.p.picture.pre.progress.q.rp.rt.ruby.s.samp.search.section.select.shadow.slot.small.source.spacer.span.strike.strong.style.sub.summary.sup.table.tbody.td.template.textarea.tfoot.th.thead.time.tr.track.tt.u.ul.var.video.wbr`.split(`.`)),dt=L(`svg.a.altglyph.altglyphdef.altglyphitem.animatecolor.animatemotion.animatetransform.circle.clippath.defs.desc.ellipse.enterkeyhint.exportparts.filter.font.g.glyph.glyphref.hkern.image.inputmode.line.lineargradient.marker.mask.metadata.mpath.part.path.pattern.polygon.polyline.radialgradient.rect.stop.style.switch.symbol.text.textpath.title.tref.tspan.view.vkern`.split(`.`)),ft=L([`feBlend`,`feColorMatrix`,`feComponentTransfer`,`feComposite`,`feConvolveMatrix`,`feDiffuseLighting`,`feDisplacementMap`,`feDistantLight`,`feDropShadow`,`feFlood`,`feFuncA`,`feFuncB`,`feFuncG`,`feFuncR`,`feGaussianBlur`,`feImage`,`feMerge`,`feMergeNode`,`feMorphology`,`feOffset`,`fePointLight`,`feSpecularLighting`,`feSpotLight`,`feTile`,`feTurbulence`]),pt=L([`animate`,`color-profile`,`cursor`,`discard`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`foreignobject`,`hatch`,`hatchpath`,`mesh`,`meshgradient`,`meshpatch`,`meshrow`,`missing-glyph`,`script`,`set`,`solidcolor`,`unknown`,`use`]),mt=L(`math.menclose.merror.mfenced.mfrac.mglyph.mi.mlabeledtr.mmultiscripts.mn.mo.mover.mpadded.mphantom.mroot.mrow.ms.mspace.msqrt.mstyle.msub.msup.msubsup.mtable.mtd.mtext.mtr.munder.munderover.mprescripts`.split(`.`)),ht=L([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),gt=L([`#text`]),_t=L(`accept.action.align.alt.autocapitalize.autocomplete.autopictureinpicture.autoplay.background.bgcolor.border.capture.cellpadding.cellspacing.checked.cite.class.clear.color.cols.colspan.command.commandfor.controls.controlslist.coords.crossorigin.datetime.decoding.default.dir.disabled.disablepictureinpicture.disableremoteplayback.download.draggable.enctype.enterkeyhint.exportparts.face.for.headers.height.hidden.high.href.hreflang.id.inert.inputmode.integrity.ismap.kind.label.lang.list.loading.loop.low.max.maxlength.media.method.min.minlength.multiple.muted.name.nonce.noshade.novalidate.nowrap.open.optimum.part.pattern.placeholder.playsinline.popover.popovertarget.popovertargetaction.poster.preload.pubdate.radiogroup.readonly.rel.required.rev.reversed.role.rows.rowspan.spellcheck.scope.selected.shape.size.sizes.slot.span.srclang.start.src.srcset.step.style.summary.tabindex.title.translate.type.usemap.valign.value.width.wrap.xmlns`.split(`.`)),vt=L(`accent-height.accumulate.additive.alignment-baseline.amplitude.ascent.attributename.attributetype.azimuth.basefrequency.baseline-shift.begin.bias.by.class.clip.clippathunits.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.cx.cy.d.dx.dy.diffuseconstant.direction.display.divisor.dominant-baseline.dur.edgemode.elevation.end.exponent.fill.fill-opacity.fill-rule.filter.filterunits.flood-color.flood-opacity.font-family.font-size.font-size-adjust.font-stretch.font-style.font-variant.font-weight.fx.fy.g1.g2.glyph-name.glyphref.gradientunits.gradienttransform.height.href.id.image-rendering.in.in2.intercept.k.k1.k2.k3.k4.kerning.keypoints.keysplines.keytimes.lang.lengthadjust.letter-spacing.kernelmatrix.kernelunitlength.lighting-color.local.marker-end.marker-mid.marker-start.markerheight.markerunits.markerwidth.maskcontentunits.maskunits.max.mask.mask-type.media.method.mode.min.name.numoctaves.offset.operator.opacity.order.orient.orientation.origin.overflow.paint-order.path.pathlength.patterncontentunits.patterntransform.patternunits.points.preservealpha.preserveaspectratio.primitiveunits.r.rx.ry.radius.refx.refy.repeatcount.repeatdur.restart.result.rotate.scale.seed.shape-rendering.slope.specularconstant.specularexponent.spreadmethod.startoffset.stddeviation.stitchtiles.stop-color.stop-opacity.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke.stroke-width.style.surfacescale.systemlanguage.tabindex.tablevalues.targetx.targety.transform.transform-origin.text-anchor.text-decoration.text-orientation.text-rendering.textlength.type.u1.u2.unicode.values.viewbox.visibility.version.vert-adv-y.vert-origin-x.vert-origin-y.width.word-spacing.wrap.writing-mode.xchannelselector.ychannelselector.x.x1.x2.xmlns.y.y1.y2.z.zoomandpan`.split(`.`)),yt=L(`accent.accentunder.align.bevelled.close.columnalign.columnlines.columnspacing.columnspan.denomalign.depth.dir.display.displaystyle.encoding.fence.frame.height.href.id.largeop.length.linethickness.lquote.lspace.mathbackground.mathcolor.mathsize.mathvariant.maxsize.minsize.movablelimits.notation.numalign.open.rowalign.rowlines.rowspacing.rowspan.rspace.rquote.scriptlevel.scriptminsize.scriptsizemultiplier.selection.separator.separators.stretchy.subscriptshift.supscriptshift.symmetric.voffset.width.xmlns`.split(`.`)),bt=L([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),xt=R(/{{[\w\W]*|^[\w\W]*}}/g),St=R(/<%[\w\W]*|^[\w\W]*%>/g),Ct=R(/\${[\w\W]*/g),wt=R(/^data-[\-\w.\u00B7-\uFFFF]+$/),Tt=R(/^aria-[\-\w]+$/),Et=R(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Dt=R(/^(?:\w+script|data):/i),Ot=R(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),kt=R(/^html$/i),At=R(/^[a-z][.\w]*(-[.\w]+)+$/i),jt=R(/<[/\w!]/g),Mt=R(/<[/\w]/g),Nt=R(/<\/no(script|embed|frames)/i),Pt=R(/\/>/i),J={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Ft=function(){return typeof window>`u`?null:window},It=function(e,t){if(typeof e!=`object`||typeof e.createPolicy!=`function`)return null;let n=null,r=`data-tt-policy-suffix`;t&&t.hasAttribute(r)&&(n=t.getAttribute(r));let i=`dompurify`+(n?`#`+n:``);try{return e.createPolicy(i,{createHTML(e){return e},createScriptURL(e){return e}})}catch{return console.warn(`TrustedTypes policy `+i+` could not be created.`),null}},Lt=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},Rt=function(e,t,n,r){return V(e,t)&&Xe(e[t])?G(r.base?K(r.base):{},e[t],r.transform):n};function zt(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Ft(),t=e=>zt(e);if(t.version=`3.4.12`,t.removed=[],!e||!e.document||e.document.nodeType!==J.document||!e.Element)return t.isSupported=!1,t;let n=e.document,r=n,i=r.currentScript;e.DocumentFragment;let a=e.HTMLTemplateElement,o=e.Node,s=e.Element,c=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let l=e.DOMParser,u=e.trustedTypes,d=s.prototype,f=q(d,`cloneNode`),p=q(d,`remove`),m=q(d,`nextSibling`),h=q(d,`childNodes`),g=q(d,`parentNode`),_=q(d,`shadowRoot`),v=q(d,`attributes`),y=o&&o.prototype?q(o.prototype,`nodeType`):null,b=o&&o.prototype?q(o.prototype,`nodeName`):null;if(typeof a==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let x,S=``,ee,te=!1,C=0,ne=function(){if(C>0)throw at(`A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.`)},w=function(e){ne(),C++;try{return x.createHTML(e)}finally{C--}},re=function(e){ne(),C++;try{return x.createScriptURL(e)}finally{C--}},T=function(){return te||=(ee=It(u,i),!0),ee},ie=n,ae=ie.implementation,E=ie.createNodeIterator,oe=ie.createDocumentFragment,se=ie.getElementsByTagName,ce=r.importNode,D=Lt();t.isSupported=typeof Re==`function`&&typeof g==`function`&&ae&&ae.createHTMLDocument!==void 0;let le=xt,ue=St,de=Ct,fe=wt,pe=Tt,me=Dt,he=Ot,ge=At,_e=Et,O=null,ve=G({},[...ut,...dt,...ft,...mt,...gt]),k=null,ye=G({},[..._t,...vt,...yt,...bt]),A=Object.seal(Ve(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),be=null,xe=null,j=Object.seal(Ve(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Se=!0,Ce=!0,we=!1,Te=!0,M=!1,N=!0,P=!1,Ee=!1,De=null,Oe=null,ke=!1,Ae=!1,je=!1,Me=!1,Ne=!0,Pe=!1,Fe=`user-content-`,Ie=!0,Le=!1,F={},I=null,ze=G({},`annotation-xml.audio.colgroup.desc.foreignobject.head.iframe.math.mi.mn.mo.ms.mtext.noembed.noframes.noscript.plaintext.script.selectedcontent.style.svg.template.thead.title.video.xmp`.split(`.`)),Be=null,He=G({},[`audio`,`video`,`img`,`source`,`image`,`track`]),Ue=null,We=G({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),rt=`http://www.w3.org/1998/Math/MathML`,it=`http://www.w3.org/2000/svg`,z=`http://www.w3.org/1999/xhtml`,B=z,H=!1,W=null,ot=G({},[rt,it,z],Qe),st=L([`mi`,`mo`,`mn`,`ms`,`mtext`]),Bt=G({},st),Vt=L([`annotation-xml`]),Ht=G({},Vt),Ut=G({},[`title`,`style`,`font`,`a`,`script`]),Wt=null,Gt=[`application/xhtml+xml`,`text/html`],Y=null,Kt=null,qt=n.createElement(`form`),Jt=function(e){return e instanceof RegExp||e instanceof Function},Yt=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Kt&&Kt===e)return;(!e||typeof e!=`object`)&&(e={}),e=K(e),Wt=Gt.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,Y=Wt===`application/xhtml+xml`?Qe:Ze,O=Rt(e,`ALLOWED_TAGS`,ve,{transform:Y}),k=Rt(e,`ALLOWED_ATTR`,ye,{transform:Y}),W=Rt(e,`ALLOWED_NAMESPACES`,ot,{transform:Qe}),Ue=Rt(e,`ADD_URI_SAFE_ATTR`,We,{transform:Y,base:We}),Be=Rt(e,`ADD_DATA_URI_TAGS`,He,{transform:Y,base:He}),I=Rt(e,`FORBID_CONTENTS`,ze,{transform:Y}),be=Rt(e,`FORBID_TAGS`,K({}),{transform:Y}),xe=Rt(e,`FORBID_ATTR`,K({}),{transform:Y}),F=V(e,`USE_PROFILES`)?e.USE_PROFILES&&typeof e.USE_PROFILES==`object`?K(e.USE_PROFILES):e.USE_PROFILES:!1,Se=e.ALLOW_ARIA_ATTR!==!1,Ce=e.ALLOW_DATA_ATTR!==!1,we=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Te=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,M=e.SAFE_FOR_TEMPLATES||!1,N=e.SAFE_FOR_XML!==!1,P=e.WHOLE_DOCUMENT||!1,Ae=e.RETURN_DOM||!1,je=e.RETURN_DOM_FRAGMENT||!1,Me=e.RETURN_TRUSTED_TYPE||!1,ke=e.FORCE_BODY||!1,Ne=e.SANITIZE_DOM!==!1,Pe=e.SANITIZE_NAMED_PROPS||!1,Ie=e.KEEP_CONTENT!==!1,Le=e.IN_PLACE||!1,_e=lt(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:Et,B=typeof e.NAMESPACE==`string`?e.NAMESPACE:z,Bt=V(e,`MATHML_TEXT_INTEGRATION_POINTS`)&&e.MATHML_TEXT_INTEGRATION_POINTS&&typeof e.MATHML_TEXT_INTEGRATION_POINTS==`object`?K(e.MATHML_TEXT_INTEGRATION_POINTS):G({},st),Ht=V(e,`HTML_INTEGRATION_POINTS`)&&e.HTML_INTEGRATION_POINTS&&typeof e.HTML_INTEGRATION_POINTS==`object`?K(e.HTML_INTEGRATION_POINTS):G({},Vt);let t=V(e,`CUSTOM_ELEMENT_HANDLING`)&&e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING==`object`?K(e.CUSTOM_ELEMENT_HANDLING):Ve(null);if(A=Ve(null),V(t,`tagNameCheck`)&&Jt(t.tagNameCheck)&&(A.tagNameCheck=t.tagNameCheck),V(t,`attributeNameCheck`)&&Jt(t.attributeNameCheck)&&(A.attributeNameCheck=t.attributeNameCheck),V(t,`allowCustomizedBuiltInElements`)&&typeof t.allowCustomizedBuiltInElements==`boolean`&&(A.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),R(A),M&&(Ce=!1),je&&(Ae=!0),F&&(O=G({},gt),k=Ve(null),F.html===!0&&(G(O,ut),G(k,_t)),F.svg===!0&&(G(O,dt),G(k,vt),G(k,bt)),F.svgFilters===!0&&(G(O,ft),G(k,vt),G(k,bt)),F.mathMl===!0&&(G(O,mt),G(k,yt),G(k,bt))),j.tagCheck=null,j.attributeCheck=null,V(e,`ADD_TAGS`)&&(typeof e.ADD_TAGS==`function`?j.tagCheck=e.ADD_TAGS:Xe(e.ADD_TAGS)&&(O===ve&&(O=K(O)),G(O,e.ADD_TAGS,Y))),V(e,`ADD_ATTR`)&&(typeof e.ADD_ATTR==`function`?j.attributeCheck=e.ADD_ATTR:Xe(e.ADD_ATTR)&&(k===ye&&(k=K(k)),G(k,e.ADD_ATTR,Y))),V(e,`ADD_URI_SAFE_ATTR`)&&Xe(e.ADD_URI_SAFE_ATTR)&&G(Ue,e.ADD_URI_SAFE_ATTR,Y),V(e,`FORBID_CONTENTS`)&&Xe(e.FORBID_CONTENTS)&&(I===ze&&(I=K(I)),G(I,e.FORBID_CONTENTS,Y)),V(e,`ADD_FORBID_CONTENTS`)&&Xe(e.ADD_FORBID_CONTENTS)&&(I===ze&&(I=K(I)),G(I,e.ADD_FORBID_CONTENTS,Y)),Ie&&(O[`#text`]=!0),P&&G(O,[`html`,`head`,`body`]),O.table&&(G(O,[`tbody`]),delete be.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw at(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw at(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);let t=x;x=e.TRUSTED_TYPES_POLICY;try{S=w(``)}catch(e){throw x=t,e}}else e.TRUSTED_TYPES_POLICY===null?(x=void 0,S=``):(x===void 0&&(x=T()),x&&typeof S==`string`&&(S=w(``)));L&&L(e),Kt=e},Xt=G({},[...dt,...ft,...pt]),Zt=G({},[...mt,...ht]),Qt=function(e,t,n){return t.namespaceURI===z?e===`svg`:t.namespaceURI===rt?e===`svg`&&(n===`annotation-xml`||Bt[n]):!!Xt[e]},$t=function(e,t,n){return t.namespaceURI===z?e===`math`:t.namespaceURI===it?e===`math`&&Ht[n]:!!Zt[e]},en=function(e,t,n){return t.namespaceURI===it&&!Ht[n]||t.namespaceURI===rt&&!Bt[n]?!1:!Zt[e]&&(Ut[e]||!Xt[e])},tn=function(e){let t=g(e);(!t||!t.tagName)&&(t={namespaceURI:B,tagName:`template`});let n=Ze(e.tagName),r=Ze(t.tagName);return W[e.namespaceURI]?e.namespaceURI===it?Qt(n,t,r):e.namespaceURI===rt?$t(n,t,r):e.namespaceURI===z?en(n,t,r):!!(Wt===`application/xhtml+xml`&&W[e.namespaceURI]):!1},X=function(e){Je(t.removed,{element:e});try{g(e).removeChild(e)}catch{if(p(e),!g(e))throw at(`a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place`)}},nn=function(e){an(e);let t=h(e);if(t){let e=[];Ge(t,t=>{Je(e,t)}),Ge(e,e=>{try{p(e)}catch{}})}let n=v(e);if(n)for(let t=n.length-1;t>=0;--t){let r=n[t],i=r&&r.name;if(typeof i==`string`)try{e.removeAttribute(i)}catch{}}},Z=function(e,n){try{Je(t.removed,{attribute:n.getAttributeNode(e),from:n})}catch{Je(t.removed,{attribute:null,from:n})}if(n.removeAttribute(e),e===`is`)if(Ae||je)try{X(n)}catch{}else try{n.setAttribute(e,``)}catch{}},rn=function(e){let t=v(e);if(t)for(let n=t.length-1;n>=0;--n){let r=t[n],i=r&&r.name;if(!(typeof i!=`string`||k[Y(i)]))try{e.removeAttribute(i)}catch{}}},an=function(e){let t=[e];for(;t.length>0;){let e=t.pop();(y?y(e):e.nodeType)===J.element&&rn(e);let n=h(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},on=function(e){if(!N)return;let t=[e];for(;t.length>0;){let e=t.pop(),n=y?y(e):e.nodeType;if(n===J.processingInstruction||n===J.comment&&U(Mt,e.data)){try{p(e)}catch{}continue}if(n===J.element){let t=e,n=Y(b?b(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute(`patchsrc`)&&t.removeAttribute(`patchsrc`),t.hasAttribute&&t.hasAttribute(`for`)&&n!==`label`&&n!==`output`&&t.removeAttribute(`for`)}catch{}}let r=h(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}},sn=function(e){let t=null,r=null;if(ke)e=`<remove></remove>`+e;else{let t=$e(e,/^[\r\n\t ]+/);r=t&&t[0]}Wt===`application/xhtml+xml`&&B===z&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=x?w(e):e;if(B===z)try{t=new l().parseFromString(i,Wt)}catch{}if(!t||!t.documentElement){t=ae.createDocument(B,`template`,null);try{t.documentElement.innerHTML=H?S:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),B===z?se.call(t,P?`html`:`body`)[0]:P?t.documentElement:a},cn=function(e){return E.call(e.ownerDocument||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},ln=function(e){return e=et(e,le,` `),e=et(e,ue,` `),e=et(e,de,` `),e},un=function(e){e.normalize();let t=E.call(e.ownerDocument||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null),n=t.nextNode();for(;n;)n.data=ln(n.data),n=t.nextNode();let r=e.querySelectorAll?.call(e,`template`);r&&Ge(r,e=>{fn(e.content)&&un(e.content)})},dn=function(e){let t=b?b(e):null;return typeof t!=`string`||Y(t)!==`form`?!1:typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||e.attributes!==v(e)||typeof e.removeAttribute!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`||e.nodeType!==y(e)||e.childNodes!==h(e)},fn=function(e){if(!y||typeof e!=`object`||!e)return!1;try{return y(e)===J.documentFragment}catch{return!1}},Q=function(e){if(!y||typeof e!=`object`||!e)return!1;try{return typeof y(e)==`number`}catch{return!1}};function $(e,n,r){e.length!==0&&Ge(e,e=>{e.call(t,n,r,Kt)})}let pn=function(e,t){return!!(N&&e.hasChildNodes()&&!Q(e.firstElementChild)&&U(jt,e.textContent)&&U(jt,e.innerHTML)||N&&e.namespaceURI===z&&t===`style`&&Q(e.firstElementChild)||e.nodeType===J.processingInstruction||N&&e.nodeType===J.comment&&U(Mt,e.data))},mn=function(e,t){if(!be[t]&&vn(t)&&(A.tagNameCheck instanceof RegExp&&U(A.tagNameCheck,t)||A.tagNameCheck instanceof Function&&A.tagNameCheck(t)))return!1;if(Ie&&!I[t]){let t=g(e),n=h(e);if(n&&t){let r=n.length;for(let i=r-1;i>=0;--i){let r=Le?n[i]:f(n[i],!0);t.insertBefore(r,m(e))}}}return X(e),!0},hn=function(e,n){if($(D.beforeSanitizeElements,e,null),e!==n&&g(e)===null)return!0;if(dn(e))return X(e),!0;let r=Y(b?b(e):e.nodeName);if($(D.uponSanitizeElement,e,{tagName:r,allowedTags:O}),e!==n&&g(e)===null)return!0;if(pn(e,r))return X(e),!0;if(be[r]||!(j.tagCheck instanceof Function&&j.tagCheck(r))&&!O[r]){let t=mn(e,r);return t===!1&&$(D.afterSanitizeElements,e,null),t}if((y?y(e):e.nodeType)===J.element&&!tn(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&U(Nt,e.innerHTML))return X(e),!0;if(M&&e.nodeType===J.text){let n=ln(e.textContent);e.textContent!==n&&(Je(t.removed,{element:e.cloneNode()}),e.textContent=n)}return $(D.afterSanitizeElements,e,null),!1},gn=function(e,t,r){if(xe[t]||N&&t===`patchsrc`||N&&t===`for`&&e!==`label`&&e!==`output`||Ne&&(t===`id`||t===`name`)&&(r in n||r in qt))return!1;let i=k[t]||j.attributeCheck instanceof Function&&j.attributeCheck(t,e);if(!(Ce&&U(fe,t))&&!(Se&&U(pe,t))){if(!i){if(!(vn(e)&&(A.tagNameCheck instanceof RegExp&&U(A.tagNameCheck,e)||A.tagNameCheck instanceof Function&&A.tagNameCheck(e))&&(A.attributeNameCheck instanceof RegExp&&U(A.attributeNameCheck,t)||A.attributeNameCheck instanceof Function&&A.attributeNameCheck(t,e))||t===`is`&&A.allowCustomizedBuiltInElements&&(A.tagNameCheck instanceof RegExp&&U(A.tagNameCheck,r)||A.tagNameCheck instanceof Function&&A.tagNameCheck(r))))return!1}else if(!Ue[t]&&!U(_e,et(r,he,``))&&!((t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&tt(r,`data:`)===0&&Be[e])&&!(we&&!U(me,et(r,he,``)))&&r)return!1}return!0},_n=G({},[`annotation-xml`,`color-profile`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`missing-glyph`]),vn=function(e){return!_n[Ze(e)]&&U(ge,e)},yn=function(e,t,n,r){if(x&&typeof u==`object`&&typeof u.getAttributeType==`function`&&!n)switch(u.getAttributeType(e,t)){case`TrustedHTML`:return w(r);case`TrustedScriptURL`:return re(r)}return r},bn=function(e,n,r,i){try{r?e.setAttributeNS(r,n,i):e.setAttribute(n,i),dn(e)?X(e):qe(t.removed)}catch{Z(n,e)}},xn=function(e){$(D.beforeSanitizeAttributes,e,null);let t=e.attributes;if(!t||dn(e))return;let n={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:k,forceKeepAttr:void 0},r=t.length,i=Y(e.nodeName);for(;r--;){let a=t[r],o=a.name,s=a.namespaceURI,c=a.value,l=Y(o),u=c,d=o===`value`?u:nt(u);if(n.attrName=l,n.attrValue=d,n.keepAttr=!0,n.forceKeepAttr=void 0,$(D.uponSanitizeAttribute,e,n),d=n.attrValue,Pe&&(l===`id`||l===`name`)&&tt(d,Fe)!==0&&(Z(o,e),d=Fe+d),N&&U(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,d)){Z(o,e);continue}if(l===`attributename`&&$e(d,`href`)){Z(o,e);continue}if(!n.forceKeepAttr){if(!n.keepAttr){Z(o,e);continue}if(!Te&&U(Pt,d)){Z(o,e);continue}if(M&&(d=ln(d)),!gn(i,l,d)){Z(o,e);continue}d=yn(i,l,s,d),d!==u&&bn(e,o,s,d)}}$(D.afterSanitizeAttributes,e,null)},Sn=function(e){let t=null,n=cn(e);for($(D.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if($(D.uponSanitizeShadowNode,t,null),hn(t,e),xn(t),fn(t.content)&&Sn(t.content),(y?y(t):t.nodeType)===J.element){let e=_(t);fn(e)&&(Cn(e),Sn(e))}$(D.afterSanitizeShadowDOM,e,null)},Cn=function(e){let t=[{node:e,shadow:null}];for(;t.length>0;){let e=t.pop();if(e.shadow){Sn(e.shadow);continue}let n=e.node,r=(y?y(n):n.nodeType)===J.element,i=h(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){let e=b?b(n):null;if(typeof e==`string`&&Y(e)===`template`){let e=n.content;fn(e)&&t.push({node:e,shadow:null})}}if(r){let e=_(n);fn(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,a=null,o=null,s=null;if(H=!e,H&&(e=`<!-->`),typeof e!=`string`&&!Q(e)&&(e=ct(e),typeof e!=`string`))throw at(`dirty is not a string, aborting`);if(!t.isSupported)return e;Ee?(O=De,k=Oe):Yt(n),(D.uponSanitizeElement.length>0||D.uponSanitizeAttribute.length>0)&&(O=K(O)),D.uponSanitizeAttribute.length>0&&(k=K(k)),t.removed=[];let c=Le&&typeof e!=`string`&&Q(e);if(c){on(e);let t=b?b(e):e.nodeName;if(typeof t==`string`){let n=Y(t);if(!O[n]||be[n])throw nn(e),at(`root node is forbidden and cannot be sanitized in-place`)}if(dn(e))throw nn(e),at(`root node is clobbered and cannot be sanitized in-place`);try{Cn(e)}catch(t){throw nn(e),t}}else if(Q(e))i=sn(`<!---->`),a=i.ownerDocument.importNode(e,!0),a.nodeType===J.element&&a.nodeName===`BODY`||a.nodeName===`HTML`?i=a:i.appendChild(a),Cn(a);else{if(!Ae&&!M&&!P&&e.indexOf(`<`)===-1)return x&&Me?w(e):e;if(i=sn(e),!i)return Ae?null:Me?S:``}i&&ke&&X(i.firstChild);let l=c?e:i,u=cn(l);try{for(;o=u.nextNode();)hn(o,l),xn(o),fn(o.content)&&Sn(o.content)}catch(n){throw c&&(nn(e),Ge(t.removed,e=>{e.element&&an(e.element)})),n}if(c)return Ge(t.removed,e=>{e.element&&an(e.element)}),M&&un(e),e;if(Ae){if(M&&un(i),je)for(s=oe.call(i.ownerDocument);i.firstChild;)s.appendChild(i.firstChild);else s=i;return(k.shadowroot||k.shadowrootmode)&&(s=ce.call(r,s,!0)),s}let d=P?i.outerHTML:i.innerHTML;return P&&O[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&U(kt,i.ownerDocument.doctype.name)&&(d=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
115
+ `+d),M&&(d=ln(d)),x&&Me?w(d):d},t.setConfig=function(){Yt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),Ee=!0,De=O,Oe=k},t.clearConfig=function(){Kt=null,Ee=!1,De=null,Oe=null,x=ee,S=``},t.isValidAttribute=function(e,t,n){return Kt||Yt({}),gn(Y(e),Y(t),n)},t.addHook=function(e,t){typeof t==`function`&&V(D,e)&&Je(D[e],t)},t.removeHook=function(e,t){if(V(D,e)){if(t!==void 0){let n=Ke(D[e],t);return n===-1?void 0:Ye(D[e],n,1)[0]}return qe(D[e])}},t.removeHooks=function(e){V(D,e)&&(D[e]=[])},t.removeAllHooks=function(){D=Lt()},t}var Bt=zt(),Vt=null,Ht=null,Ut=null;function Wt(e){return{startOnLoad:!1,theme:(e||x())===`dark`?`dark`:`default`,securityLevel:`loose`,fontFamily:`-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`}}function Gt(e){return new Promise((t,n)=>{if(document.querySelector(`script[src="${e}"]`)){t();return}let r=document.createElement(`script`);r.src=e,r.onload=t,r.onerror=()=>n(Error(`Failed to load script: ${e}`)),document.head.appendChild(r)})}function Y(){return window.mermaid===void 0?(Vt||=Gt(`libs/mermaid.min.js`).then(()=>(window.mermaid!==void 0&&window.mermaid.initialize(Wt()),window.mermaid)).catch(e=>{throw Vt=null,e}),Vt):Promise.resolve(window.mermaid)}function Kt(){return window.jspdf&&window.jspdf.jsPDF?Promise.resolve(window.jspdf.jsPDF):(Ht||=Gt(`libs/jspdf.min.js`).then(()=>{let e=window.jspdf&&window.jspdf.jsPDF;if(!e)throw Error(`jsPDF not available after loading`);return e}).catch(e=>{throw Ht=null,e}),Ht)}function qt(){return window.html2canvas?Promise.resolve(window.html2canvas):(Ut||=Gt(`libs/html2canvas.min.js`).then(()=>{if(!window.html2canvas)throw Error(`html2canvas not available after loading`);return window.html2canvas}).catch(e=>{throw Ut=null,e}),Ut)}async function Jt(){let[e,t]=await Promise.all([Kt(),qt()]);return{jsPDF:e,html2canvas:t}}e(`zh`,{chat:{fileLinkTitle:`点击在工作目录中定位该文件`,fileLinkFailed:`定位文件失败`},markdown:{copyCode:`复制代码`,copyMdTableTitle:`复制 Markdown 表格
116
+ 按住 Ctrl/⌘ 点击复制富文本表格`,downloadExcel:`下载 Excel`,exportTableImage:`导出表格为图片`,downloadFailed:`下载失败: {message}`,unknownError:`未知错误`,chartRenderFailed:`图表渲染失败: {detail}`,zoomIn:`放大`,zoomOut:`缩小`,reset:`重置`,copyToClipboard:`复制到剪贴板`,downloadImage:`下载图片`,viewSource:`查看源代码`,mermaidCopied:`Mermaid 图表已复制到剪贴板!`,autoDownloadChart:`已自动转为下载方式保存图表`,copyFailed:`复制失败: {message}`,copySourceTitle:`复制源代码`,backToChart:`返回图表`,codeBlockLabel:`代码块`,codeLabel:`代码`,copiedToClipboard:`{label}已复制到剪贴板`,codeCopied:`代码已复制到剪贴板`,copiedRichTable:`已复制富文本表格`,copyRichTableFailed:`复制富文本表格失败`,copyFailedShort:`复制失败`,copiedMdTable:`已复制 Markdown 表格`,imageExportLibMissing:`图片导出库未加载`,tableImageExported:`表格图片已导出`,exportImageFailed:`导出图片失败`,canvasExportFailed:`Canvas toDataURL 失败,无法导出图片`,svgLoadFailed:`SVG 图片加载失败: {message}`}}),e(`en`,{chat:{fileLinkTitle:`Click to locate this file in the working directory`,fileLinkFailed:`Failed to locate file`},markdown:{copyCode:`Copy code`,copyMdTableTitle:`Copy Markdown table
117
+ Ctrl/Cmd+click to copy rich-text table`,downloadExcel:`Download Excel`,exportTableImage:`Export table as image`,downloadFailed:`Download failed: {message}`,unknownError:`Unknown error`,chartRenderFailed:`Chart rendering failed: {detail}`,zoomIn:`Zoom in`,zoomOut:`Zoom out`,reset:`Reset`,copyToClipboard:`Copy to clipboard`,downloadImage:`Download image`,viewSource:`View source`,mermaidCopied:`Mermaid chart copied to clipboard!`,autoDownloadChart:`Automatically switched to download to save the chart`,copyFailed:`Copy failed: {message}`,copySourceTitle:`Copy source code`,backToChart:`Back to chart`,codeBlockLabel:`Code block`,codeLabel:`Code`,copiedToClipboard:`{label} copied to clipboard`,codeCopied:`Code copied to clipboard`,copiedRichTable:`Rich-text table copied`,copyRichTableFailed:`Failed to copy rich-text table`,copyFailedShort:`Copy failed`,copiedMdTable:`Markdown table copied`,imageExportLibMissing:`Image export library not loaded`,tableImageExported:`Table image exported`,exportImageFailed:`Failed to export image`,canvasExportFailed:`Canvas toDataURL failed, unable to export image`,svgLoadFailed:`SVG image load failed: {message}`}});var Yt=2e3;function Xt(e){let t=e.closest(`.mermaid`);if(!t)return!1;let n=t.getAttribute(`data-raw-code`);if(!n)return!1;try{let e=decodeURIComponent(n);return/^\s*classDiagram/im.test(e)}catch{return!1}}function Zt(e){e.querySelectorAll(`foreignObject`).forEach(e=>{let t=e.querySelector(`div`);if(!t){e.remove();return}let n=t.querySelector(`span`),r=(n||t).textContent.trim();if(!r){e.remove();return}let i=parseFloat(e.getAttribute(`width`))||100,a=parseFloat(e.getAttribute(`height`))||30,o=e.getAttribute(`transform`),s=document.createElementNS(`http://www.w3.org/2000/svg`,`text`);s.setAttribute(`x`,String(i/2)),s.setAttribute(`y`,String(a/2)),s.setAttribute(`text-anchor`,`middle`),s.setAttribute(`dominant-baseline`,`central`),o&&s.setAttribute(`transform`,o);let c=n?n.getAttribute(`class`):``;c&&s.setAttribute(`class`,c),s.textContent=r,e.parentNode.replaceChild(s,e)})}function Qt(e){let t=e.cloneNode(!0),n=document.createElement(`div`);return n.style.cssText=`position:absolute;visibility:hidden;width:0;height:0;overflow:hidden;`,n.appendChild(t),document.body.appendChild(n),Xt(e)?Zt(t):t.querySelectorAll(`foreignObject`).forEach(e=>{let t=e.querySelector(`div`);if(!t){e.remove();return}let n=document.createElementNS(`http://www.w3.org/2000/svg`,`text`),r=parseFloat(e.getAttribute(`x`))||0,i=parseFloat(e.getAttribute(`y`))||0,a=parseFloat(e.getAttribute(`width`))||100,o=parseFloat(e.getAttribute(`height`))||30,s=t.querySelector(`span`)||t,c=window.getComputedStyle(s);n.textContent=s.textContent.trim(),n.setAttribute(`x`,String(r+a/2)),n.setAttribute(`y`,String(i+o/2)),n.setAttribute(`text-anchor`,`middle`),n.setAttribute(`dominant-baseline`,`central`),n.setAttribute(`fill`,c.color||`#333`),n.setAttribute(`font-family`,c.fontFamily||`sans-serif`),n.setAttribute(`font-size`,c.fontSize||`14px`),(c.fontWeight===`bold`||parseInt(c.fontWeight)>=600)&&n.setAttribute(`font-weight`,`bold`),e.parentNode.replaceChild(n,e)}),t.querySelectorAll(`image`).forEach(e=>{let t=e.getAttribute(`href`)||e.getAttributeNS(`http://www.w3.org/1999/xlink`,`href`)||``;/^https?:/i.test(t)&&e.remove()}),t.querySelectorAll(`use`).forEach(e=>{let t=e.getAttribute(`href`)||e.getAttributeNS(`http://www.w3.org/1999/xlink`,`href`)||``;/^https?:/i.test(t)&&e.remove()}),document.body.removeChild(n),t}function $t(e){let t=e.getAttribute(`viewBox`);if(t){let e=t.split(/[\s,]+/).map(parseFloat);if(e.length===4&&!isNaN(e[2])&&!isNaN(e[3])&&e[2]>0&&e[3]>0)return{width:e[2],height:e[3]}}let n=parseFloat(e.getAttribute(`width`)),r=parseFloat(e.getAttribute(`height`));if(!isNaN(n)&&!isNaN(r)&&n>0&&r>0)return{width:n,height:r};try{let t=e.getBoundingClientRect();if(t.width>0&&t.height>0)return{width:t.width,height:t.height}}catch{}return{width:800,height:600}}function en(e){try{let t=e.toDataURL(`image/png`);if(t&&t.length>100)return t}catch(e){n.debug(`[SidePanel] PNG toDataURL failed,downgrade to JPEG:`,e.message)}try{let t=e.toDataURL(`image/jpeg`,.92);if(t&&t.length>100)return t}catch(e){n.debug(`[SidePanel] JPEG toDataURL also failed:`,e.message)}throw Error(t(`markdown.canvasExportFailed`))}function tn(e){return new Promise((r,i)=>{try{let{width:a,height:o}=$t(e);n.debug(`[SidePanel] svgToPngDataUrl size:`,a,`x`,o);let s=2;if(a>Yt||o>Yt){let e=Math.min(Yt/a,Yt/o);a*=e,o*=e,s=1.5}let c=Qt(e),l=new XMLSerializer().serializeToString(c),u=`data:image/svg+xml;charset=utf-8,`+encodeURIComponent(l),d=new Image;d.crossOrigin=`anonymous`,d.onload=function(){try{let e=document.createElement(`canvas`);e.width=Math.ceil((a+20)*s),e.height=Math.ceil((o+20)*s),n.debug(`[SidePanel] Canvas size:`,e.width,`x`,e.height);let t=e.getContext(`2d`);t.fillStyle=`#ffffff`,t.fillRect(0,0,e.width,e.height),t.drawImage(d,10*s,10*s,a*s,o*s),r(en(e))}catch(e){i(e)}},d.onerror=function(e){i(Error(t(`markdown.svgLoadFailed`,{message:String(e?.message||e)})))},d.src=u}catch(e){i(e)}})}function X(e){if(!e)return``;let t=[],n=e.replace(/```[\s\S]*?```/g,e=>(t.push(e),`\u0000F${t.length-1}\u0000`)),r=n.replace(/^[ \t]*\[\[artifact:[^\]]*\]\][ \t]*\n/gm,``).replace(/[ \t]*\[\[artifact:[^\]]*\]\][ \t]*/g,``);return(r===n?n:r.replace(/\n{3,}/g,`
118
+
119
+ `).replace(/^\n+/,``).replace(/\n+$/,``)).replace(/\u0000F(\d+)\u0000/g,(e,n)=>t[Number(n)])}function nn(e){if(!e)return``;e=X(e);let n=[],r=Date.now()+`_`+Math.random().toString(36).slice(2,8);e=e.replace(/```mermaid\n?([\s\S]*?)```/g,(e,t)=>{let r=n.length;return n.push(t.trim()),`%%MERMAID_BLOCK_${r}%%`});let i=[];e=e.replace(/```(\w*)\n?([\s\S]*?)```/g,(e,t,n)=>{let r=i.length;return i.push({language:t||`text`,content:n.trim()}),`%%CODE_BLOCK_${r}%%`});let a=[];e=e.replace(/^(\|.+\|)\n(\|[-| :]+\|)\n((?:\|.+\|\n?)*)/gm,(e,t,n,r)=>{let i=a.length;return a.push({header:t,separator:n,body:r,full:e.trim()}),`\n%%TABLE_BLOCK_${i}%%\n`});let o=``;return typeof marked<`u`?(marked.setOptions({breaks:!0,gfm:!0}),o=marked.parse(e)):o=e.replace(/`([^`]+)`/g,`<code>$1</code>`).replace(/\*\*([^*]+)\*\*/g,`<strong>$1</strong>`).replace(/\*([^*]+)\*/g,`<em>$1</em>`).replace(/\n/g,`<br>`),o=Bt.sanitize(o,{FORBID_TAGS:[`style`,`iframe`,`script`,`object`,`embed`,`svg`],FORBID_ATTR:[`onerror`,`onload`,`onclick`,`onmouseover`,`onfocus`,`onblur`,`onchange`,`oninput`,`onkeydown`,`onkeyup`,`onkeypress`],ADD_ATTR:[`target`]}),n.forEach((e,t)=>{let n=`mermaid-${r}-${t}`;o=o.replace(`%%MERMAID_BLOCK_${t}%%`,`<div class="mermaid" id="${n}" data-raw-code="${encodeURIComponent(e)}">${re(e)}</div>`)}),i.forEach((e,n)=>{let r=e.content.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`);o=o.replace(`%%CODE_BLOCK_${n}%%`,`<div class="code-block-container" style="position: relative;">
120
+ <button class="code-copy-btn" data-code="${n}" title="${t(`markdown.copyCode`)}">
121
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
122
+ <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"/>
123
+ </svg>
124
+ </button>
125
+ <pre><code class="language-${e.language}">${r}</code></pre>
126
+ </div>`)}),a.forEach((e,t)=>{o=o.replace(`%%TABLE_BLOCK_${t}%%`,an(e))}),o}function Z(e){if(!e)return``;let t=e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`);return t=t.replace(/`([^`]+)`/g,`<code>$1</code>`),t=t.replace(/\*\*([^*]+)\*\*/g,`<strong>$1</strong>`),t=t.replace(/\*([^*]+)\*/g,`<em>$1</em>`),t=t.replace(/~~([^~]+)~~/g,`<del>$1</del>`),t}function rn(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`\\`){let i=0;for(;e[r+i]===`\\`;)i++;e[r+i]===`|`?(n+=`\\`.repeat(Math.floor(i/2)),i%2==1?n+=`|`:(t.push(n),n=``),r+=i+1):(n+=`\\`.repeat(i),r+=i);continue}if(i===`|`){t.push(n),n=``,r++;continue}n+=i,r++}return t.push(n),t}function an(e){let{header:n,body:r,full:i}=e,a=window.__tableBlocks?window.__tableBlocks.length:0;window.__tableBlocks&&(window.__tableBlocks[a]={full:i,header:n,body:r});let o=rn(n).slice(1,-1).map(e=>Z(e.trim())),s=r.trim().split(`
127
+ `).filter(e=>e.trim()).map(e=>rn(e).slice(1,-1).map(e=>Z(e.trim()))),c=`<div class="table-container-wrapper"><table>`;return c+=`<thead><tr>`,o.forEach((e,a)=>{a===o.length-1?c+=`<th class="table-header-cell-wrapper">
128
+ ${e}
129
+ <div class="table-toolbar">
130
+ <button class="table-toolbar-btn copy-md-btn" title="${t(`markdown.copyMdTableTitle`)}" data-table-full="${encodeURIComponent(i)}">
131
+ <svg viewBox="0 0 16 16" fill="currentColor">
132
+ <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"/>
133
+ </svg>
134
+ </button>
135
+ <button class="table-toolbar-btn download-excel-btn" title="${t(`markdown.downloadExcel`)}" data-table-header="${encodeURIComponent(n)}" data-table-body="${encodeURIComponent(r)}">
136
+ <svg viewBox="0 0 16 16" fill="currentColor">
137
+ <path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/>
138
+ <path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"/>
139
+ </svg>
140
+ </button>
141
+ <button class="table-toolbar-btn export-table-img-btn" title="${t(`markdown.exportTableImage`)}">
142
+ <svg viewBox="0 0 16 16" fill="currentColor">
143
+ <path d="M6.002 5.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0z"/>
144
+ <path d="M2.002 1a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2h-12zm12 1a1 1 0 0 1 1 1v6.5l-3.777-1.947a.5.5 0 0 0-.577.093l-3.71 3.71-2.66-1.772a.5.5 0 0 0-.63.062L1.002 12V3a1 1 0 0 1 1-1h12z"/>
145
+ </svg>
146
+ </button>
147
+ </div>
148
+ </th>`:c+=`<th>${e}</th>`}),c+=`</tr></thead>`,c+=`<tbody>`,s.forEach(e=>{c+=`<tr>`,e.forEach(e=>{c+=`<td>${e}</td>`}),c+=`</tr>`}),c+=`</tbody>`,c+=`</table></div>`,c}function on(e){try{let{header:t,body:r}=e,i=rn(t).slice(1,-1).map(e=>e.trim()),a=r.trim().split(`
149
+ `).filter(e=>e.trim()).map(e=>rn(e).slice(1,-1).map(e=>e.trim())),o=``;o+=i.map(e=>`"${e.replace(/"/g,`""`)}"`).join(`,`)+`
150
+ `,a.forEach(e=>{o+=e.map(e=>`"${e.replace(/"/g,`""`)}"`).join(`,`)+`
151
+ `});let s=new Blob([o],{type:`text/csv;charset=utf-8;`}),c=document.createElement(`a`),l=URL.createObjectURL(s);c.setAttribute(`href`,l),c.setAttribute(`download`,`table-${Date.now()}.csv`),c.style.visibility=`hidden`,document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(l),n.debug(`[SidePanel] Excel download successful`)}catch(e){n.error(`[SidePanel] download Excel failed:`,e),C(t(`markdown.downloadFailed`,{message:e.message}),`error`)}}function sn(e){if(!e)return t(`markdown.unknownError`);if(typeof e==`string`)return e;let n=e.message||e.str||e.msg||e.text||``;if(n)return n;try{return JSON.stringify(e)}catch{return String(e)}}var cn=2;async function ln(e,t=cn){if(e.querySelector(`svg`))return{success:!0};let r=e.getAttribute(`data-raw-code`),i=r?decodeURIComponent(r):e.textContent||``;for(let r=0;r<=t;r++){r>0&&(e.textContent=i);try{return await mermaid.run({nodes:[e]}),{success:!0}}catch(a){let o=sn(a);if(/(Parse error|syntax error|Lexical error|No diagram type detected)/i.test(o)||r>=t)return n.error(`[SidePanel] Mermaid render failed,original content ( before 300chars):`,i.substring(0,300)),e.textContent=i,{success:!1,detail:o,err:a};await new Promise(e=>setTimeout(e,200))}}}async function un(){let e=document.querySelectorAll(`.mermaid`);if(e.length!==0){try{await Y()}catch(e){n.warn(`[SidePanel] Mermaid lib failed to load:`,e);return}n.debug(`[SidePanel] ===== renderMermaidCharts start =====`),n.debug(`[SidePanel] find to mermaid element count:`,e.length);for(let r=0;r<e.length;r++){let i=e[r],a=await ln(i);a.success?(n.debug(`[SidePanel] `,r+1,` mermaid chart render successful`),Q(i)):(n.error(`[SidePanel] `,r+1,` mermaid chart render failed:`,a.detail,a.err),!i.querySelector(`svg`)&&!i.querySelector(`.mermaid-controls`)&&(i.innerHTML=`<div style="color: #856404; background: #fff3cd; padding: 10px; border-radius: 4px; margin: 10px 0;">${t(`markdown.chartRenderFailed`,{detail:a.detail})}</div>`))}n.debug(`[SidePanel] ===== renderMermaidCharts complete =====`)}}async function dn(){if(typeof window>`u`||window.mermaid===void 0)return;let e=document.querySelectorAll(`.mermaid`);if(e.length!==0){window.mermaid.initialize(Wt());for(let n of e){let e=n.querySelector(`svg`);if(!e)continue;let r=n.getAttribute(`data-raw-code`);if(!r)continue;e.remove();let i=n.querySelector(`.mermaid-controls`);i&&i.remove(),n.removeAttribute(`data-processed`),n.innerHTML=``,n.textContent=decodeURIComponent(r);let a=await ln(n);a.success?Q(n):!n.querySelector(`svg`)&&!n.querySelector(`.mermaid-controls`)&&(n.innerHTML=`<div style="color: #856404; background: #fff3cd; padding: 10px; border-radius: 4px; margin: 10px 0;">${t(`markdown.chartRenderFailed`,{detail:a.detail})}</div>`)}}}function fn(e){return e?`<div class="markdown-body">${nn(e)}</div>`:``}function Q(e){let r=e.querySelector(`.mermaid-controls`);r&&r.remove();let i=e.querySelector(`svg`);if(!i){n.warn(`[SidePanel] SVG elementnot found,current content:`,e.innerHTML.substring(0,100));return}n.debug(`[SidePanel] find to SVG element,start addingtoolbar`),n.debug(`[SidePanel] container class name:`,e.className),n.debug(`[SidePanel] container HTML:`,e.innerHTML.substring(0,200)),e.style.position=`relative`,e.style.cursor=`grab`,e.style.userSelect=`none`,e.style.webkitUserSelect=`none`;let a=e.querySelector(`.mermaid-svg-wrapper`);if(!a){a=document.createElement(`div`),a.className=`mermaid-svg-wrapper`,a.style.transformOrigin=`center center`,a.style.transition=`transform 0.2s ease`,a.style.display=`inline-block`,a.style.width=`100%`,i.style.maxWidth=`100%`,i.style.height=`auto`,i.style.userSelect=`none`,i.style.webkitUserSelect=`none`,a.appendChild(i),e.insertBefore(a,e.firstChild);let t=[];Array.from(e.childNodes).forEach(e=>{e.nodeType===Node.TEXT_NODE&&e.textContent.trim()&&t.push(e)}),t.forEach(e=>e.remove())}let o=document.createElement(`div`);o.className=`mermaid-controls`,o.innerHTML=`
152
+ <button class="zoom-in" title="${t(`markdown.zoomIn`)}">+</button>
153
+ <button class="zoom-out" title="${t(`markdown.zoomOut`)}">−</button>
154
+ <button class="reset-zoom" title="${t(`markdown.reset`)}">↺</button>
155
+ <button class="copy-to-clipboard" title="${t(`markdown.copyToClipboard`)}">
156
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor">
157
+ <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"/>
158
+ </svg>
159
+ </button>
160
+ <button class="download-png" title="${t(`markdown.downloadImage`)}">↓</button>
161
+ <button class="view-source" title="${t(`markdown.viewSource`)}">&lt;/&gt;</button>
162
+ `,e.appendChild(o),n.debug(`[SidePanel] toolbar HTML added`),n.debug(`[SidePanel] container subelement:`,Array.from(e.children).map(e=>e.className).join(`, `)),e._pngDataUrl||tn(i).then(t=>{e._pngDataUrl=t,e._pngBlob=null}).catch(e=>{n.warn(`[SidePanel] Mermaid PNG pre-convert failed:`,e.message)});let s=1,c=.01,l=.15,u=e.dataset.rawCode||``;if(!u){let e=i.querySelector(`title`);e&&e.textContent&&(u=e.textContent.trim())}if(!u){let e=i.querySelector(`script[type="text/plain"]`);e&&(u=e.textContent.trim())}u&&!e.dataset.rawMermaidCode&&(e.dataset.rawMermaidCode=u),o.querySelector(`.view-source`).addEventListener(`click`,t=>{t.stopPropagation();let n=e.getAttribute(`data-raw-code`);vn(e,n?decodeURIComponent(n):e.dataset.rawMermaidCode||``,a,i,s,{MIN_SCALE:c,MAX_SCALE:100,SCALE_STEP:l})}),o.querySelector(`.copy-to-clipboard`).addEventListener(`click`,e=>{e.stopPropagation(),gn(i,a,s)}),o.querySelector(`.download-png`).addEventListener(`click`,e=>{e.stopPropagation(),_n(i,s)}),e.addEventListener(`wheel`,e=>{!e.ctrlKey&&!e.metaKey||(e.preventDefault(),e.stopPropagation(),s=e.deltaY<0?Math.min(100,s+l):Math.max(c,s-l),g())},{passive:!1});let d=!1,f,p,m=0,h=0;function g(){a.style.transform=`translate(${m}px, ${h}px) scale(${s})`}o.querySelector(`.zoom-in`).addEventListener(`click`,e=>{e.stopPropagation(),s=Math.min(100,s+l),g()}),o.querySelector(`.zoom-out`).addEventListener(`click`,e=>{e.stopPropagation(),s=Math.max(c,s-l),g()}),o.querySelector(`.reset-zoom`).addEventListener(`click`,e=>{e.stopPropagation(),s=1,m=0,h=0,g()}),e.addEventListener(`mousedown`,t=>{t.target.tagName!==`BUTTON`&&(d=!0,f=t.clientX-m,p=t.clientY-h,e.style.cursor=`grabbing`)}),document.addEventListener(`mousemove`,e=>{d&&(m=e.clientX-f,h=e.clientY-p,g())}),document.addEventListener(`mouseup`,()=>{d&&(d=!1,e.style.cursor=`grab`)})}function $(e){let t=e.match(/^data:([^;]+)/);return t?t[1]:`image/png`}function pn(e){let t=$(e).split(`/`)[1];return t===`jpeg`?`jpg`:t||`png`}function mn(e){let t=$(e),n=e.split(`,`)[1]||``,r=atob(n),i=r.length,a=new Uint8Array(i);for(let e=0;e<i;e++)a[e]=r.charCodeAt(e);return new Blob([a],{type:t})}function hn(e,t){let n=pn(e),r=t.replace(/\.(png|jpg|jpeg)$/i,``)+`.`+n,i=document.createElement(`a`);i.href=e,i.download=r,document.body.appendChild(i),i.click(),document.body.removeChild(i)}async function gn(e,r,i){try{let r=e.closest(`.mermaid`),i=r&&r._pngDataUrl;i||=await tn(e);let a=mn(i),o=$(i),s=`mermaid-diagram-`+Date.now()+`.png`;if(navigator.clipboard&&typeof ClipboardItem<`u`)try{await navigator.clipboard.write([new ClipboardItem({[o]:a})]),C(t(`markdown.mermaidCopied`),`success`);return}catch(e){n.warn(`[SidePanel] Clipboard API write failed,downgrade to download:`,e.message)}C(t(`markdown.autoDownloadChart`),`warning`),hn(i,s)}catch(e){n.error(`[SidePanel] copyto clipboard failed:`,e),C(t(`markdown.copyFailed`,{message:e.message}),`error`)}}async function _n(e,r){try{let t=e.closest(`.mermaid`),n=t&&t._pngDataUrl,r=`mermaid-diagram-`+Date.now()+`.png`;if(n){hn(n,r);return}hn(await tn(e),r)}catch(e){n.error(`[SidePanel] download PNG failed:`,e),C(t(`markdown.downloadFailed`,{message:e.message}),`error`)}}function vn(e,n,r,i,a,o){let s=e.querySelector(`.mermaid-source-view`),c=e.querySelector(`.mermaid-controls`);if(s)s.parentElement&&s.parentElement.remove(),r&&(r.style.display=`inline-block`),e.style.userSelect=`none`,e.style.webkitUserSelect=`none`,e.style.cursor=`grab`,Q(e);else{r&&(r.style.display=`none`),c&&c.remove(),e.style.userSelect=`text`,e.style.webkitUserSelect=`text`,e.style.cursor=`auto`;let s=document.createElement(`div`);s.className=`mermaid-container-wrapper`,s.style.position=`relative`;let l=document.createElement(`pre`);l.className=`mermaid-source-view`,l.style.position=`relative`,l.textContent=n;let u=document.createElement(`button`);u.className=`source-copy-btn`,u.title=t(`markdown.copySourceTitle`),u.innerHTML=`
163
+ <svg viewBox="0 0 16 16" fill="currentColor">
164
+ <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"/>
165
+ </svg>
166
+ `,u.addEventListener(`click`,e=>{e.stopPropagation(),fe(n,u)});let d=document.createElement(`button`);d.className=`source-copy-btn`,d.style.right=`44px`,d.title=t(`markdown.backToChart`),d.innerHTML=`
167
+ <svg viewBox="0 0 16 16" fill="currentColor">
168
+ <path d="M11.534 7h3.932a.25.25 0 0 1 .192.41l-1.966 2.36a1.25 1.25 0 0 0 0 1.32l1.965 2.36a.25.25 0 0 1-.192.41h-3.932a.25.25 0 0 1-.192-.41l-1.966-2.36a1.25 1.25 0 0 0 0-1.32l1.966-2.36a.25.25 0 0 1 .192-.41zm-6.068 0H1.534a.25.25 0 0 0-.192.41l1.966 2.36a1.25 1.25 0 0 1 0 1.32l-1.966 2.36A.25.25 0 0 0 1.534 14h3.932a.25.25 0 0 0 .192-.41l-1.966-2.36a1.25 1.25 0 0 1 0-1.32l1.966-2.36a.25.25 0 0 0-.192-.41z"/>
169
+ </svg>
170
+ `,d.addEventListener(`click`,t=>{t.stopPropagation(),vn(e,n,r,i,a,o)}),l.appendChild(u),l.appendChild(d),s.appendChild(l),e.appendChild(s)}}async function yn(e){n.debug(`[SidePanel] ===== renderMessageMermaid start =====`);let r=e.querySelectorAll(`.mermaid`);if(r.length===0){n.debug(`[SidePanel] not found mermaid element`);return}try{await Y()}catch(e){n.warn(`[SidePanel] Mermaid lib failed to load:`,e);return}await new Promise(e=>setTimeout(e,300)),n.debug(`[SidePanel] find to mermaid element count:`,r.length);try{for(let i=0;i<r.length;i++){let a=r[i],o=await ln(a),s=e.querySelectorAll(`.mermaid`)[i];o.success&&s?(n.debug(`[SidePanel] `,i+1,` mermaid chart render successful`),Q(s)):s&&!s.querySelector(`svg`)&&!s.querySelector(`.mermaid-controls`)&&(n.error(`[SidePanel] `,i+1,` mermaid chart render failed:`,o.detail,o.err),s.innerHTML=`<div style="color: #856404; background: #fff3cd; padding: 10px; border-radius: 4px;">${t(`markdown.chartRenderFailed`,{detail:o.detail})}</div>`)}n.debug(`[SidePanel] Mermaid rendercomplete`);let i=e.querySelectorAll(`.mermaid-controls`);n.debug(`[SidePanel] toolbar addresult:`,i.length,`successful`)}catch(e){n.error(`[SidePanel] Mermaid overall render failed:`,e)}Sn()}var bn=!1;function xn(){bn||(bn=!0,document.addEventListener(`click`,e=>{if(!e.ctrlKey&&!e.metaKey||e.button!==0||!e.target.closest?.(`#chatContainer, .message-fullscreen-body, .kb-doc-markdown`))return;let r=e.target.closest(`code`);if(!r){let t=e.target.closest(`pre`);if(t&&(r=t.querySelector(`code`)),!r){let t=e.target.closest(`.code-block-container`);t&&(r=t.querySelector(`code`))}}if(!r||e.target.closest(`.code-copy-btn`))return;e.preventDefault();let i=r.textContent;i&&navigator.clipboard.writeText(i).then(()=>{C(t(`markdown.copiedToClipboard`,{label:r.closest(`.code-block-container`)?t(`markdown.codeBlockLabel`):t(`markdown.codeLabel`)}),`success`)}).catch(e=>{n.error(`[SidePanel] Ctrl+clickcopy failed:`,e);let r=document.createElement(`textarea`);r.value=i,r.style.position=`fixed`,r.style.left=`-999999px`,document.body.appendChild(r),r.select(),document.execCommand(`copy`),document.body.removeChild(r),C(t(`markdown.codeCopied`),`success`)})}),n.debug(`[SidePanel] Ctrl+clickcopycodeeventbound (document delegate)`))}function Sn(){kn(),xn()}function Cn(e){let t=e.closest(`.table-container-wrapper`)?.querySelector(`table`);if(!t)return null;let n=[];t.querySelectorAll(`thead th`).forEach(e=>{let t=``;for(let n of e.childNodes)n.nodeType===Node.TEXT_NODE?t+=n.textContent:n.nodeType===Node.ELEMENT_NODE&&!n.classList.contains(`table-toolbar`)&&!n.closest(`.table-toolbar`)&&(t+=n.textContent||``);n.push(t.trim())});let r=[];if(t.querySelectorAll(`tbody tr`).forEach(e=>{let t=[];e.querySelectorAll(`td`).forEach(e=>{t.push(e.textContent.trim())}),r.push(t)}),n.length===0&&r.length===0)return null;let i=e=>e.replace(/\|/g,`\\|`),a=`| `+n.map(i).join(` | `)+` |`,o=`| `+n.map(()=>`---`).join(` | `)+` |`,s=r.map(e=>`| `+e.map(i).join(` | `)+` |`).join(`
171
+ `);return{full:a+`
172
+ `+o+`
173
+ `+s,header:a+`
174
+ `+o,body:s}}function wn(e){let t=e.closest(`.code-block-container`);if(t){let n=t.querySelector(`pre code`);n&&fe(n.textContent,e)}}function Tn(e,n){if(n.ctrlKey||n.metaKey){let n=e.closest(`.table-container-wrapper`)?.querySelector(`table`);if(n)try{let r=jn(n).outerHTML;e.focus();let i=new Blob([r],{type:`text/html`}),a=new ClipboardItem({"text/html":i});navigator.clipboard.write([a]).then(()=>{C(t(`markdown.copiedRichTable`))}).catch(()=>{let n=document.createElement(`div`);n.style.cssText=`position:fixed;left:-999999px;top:-999999px;`,n.innerHTML=r,document.body.appendChild(n);let i=document.createRange();i.selectNodeContents(n);let a=window.getSelection();a.removeAllRanges(),a.addRange(i);try{e.focus(),document.execCommand(`copy`),C(t(`markdown.copiedRichTable`))}catch{C(t(`markdown.copyRichTableFailed`),`error`)}finally{a.removeAllRanges(),document.body.removeChild(n)}})}catch{C(t(`markdown.copyFailedShort`),`error`)}return}let r=e.dataset.tableFull?decodeURIComponent(e.dataset.tableFull):null;if(r){fe(r,e),C(t(`markdown.copiedMdTable`));return}let i=e.dataset.tableIndex,a=window.__tableBlocks?.[parseInt(i)];if(a){fe(a.full,e),C(t(`markdown.copiedMdTable`));return}let o=Cn(e);o&&(fe(o.full,e),C(t(`markdown.copiedMdTable`)))}function En(e){let t=e.dataset.tableHeader?decodeURIComponent(e.dataset.tableHeader):null,n=e.dataset.tableBody?decodeURIComponent(e.dataset.tableBody):null;if(t&&n){on({header:t,body:n});return}let r=e.dataset.tableIndex,i=window.__tableBlocks?.[parseInt(r)];if(i){on(i);return}let a=Cn(e);a&&on(a)}async function Dn(e){let r=e.closest(`.table-container-wrapper`);if(r)try{let e=await qt();if(!e){C(t(`markdown.imageExportLibMissing`),`error`);return}let n=await e(r,{scale:2,useCORS:!0,logging:!1,backgroundColor:`#ffffff`}),i=document.createElement(`a`);i.download=`table-${Date.now()}.jpg`,i.href=n.toDataURL(`image/jpeg`,.95),document.body.appendChild(i),i.click(),document.body.removeChild(i),C(t(`markdown.tableImageExported`))}catch(e){n.error(`[SidePanel] export tableimage failed:`,e),C(t(`markdown.exportImageFailed`),`error`)}}var On=!1;function kn(){On||typeof document>`u`||!document.addEventListener||(On=!0,document.addEventListener(`click`,e=>{let t=e.target;if(!t||typeof t.closest!=`function`)return;let n=t.closest(`.code-copy-btn`);if(n){e.stopPropagation(),wn(n);return}let r=t.closest(`.copy-md-btn`);if(r){e.stopPropagation(),Tn(r,e);return}let i=t.closest(`.download-excel-btn`);if(i){e.stopPropagation(),En(i);return}let a=t.closest(`.export-table-img-btn`);if(a){e.stopPropagation(),Dn(a);return}},!0))}function An(){kn()}function jn(e){let t=e.cloneNode(!0);return t.querySelectorAll(`.table-header-cell-wrapper`).forEach(e=>{let t=e.textContent.trim();e.innerHTML=``,e.textContent=t,e.classList.remove(`table-header-cell-wrapper`)}),t.querySelectorAll(`.table-toolbar`).forEach(e=>e.remove()),t}var Mn=RegExp(`(?:~?/[\\w\\-.\\u4e00-\\u9fa5/]+|\\b[A-Za-z]:\\\\[\\w\\-.\\\\\\u4e00-\\u9fa5]+|\\b[\\w\\-.\\u4e00-\\u9fa5]+/[\\w\\-./\\u4e00-\\u9fa5]*\\.[A-Za-z0-9]{1,6}|\\b[\\w\\-.\\u4e00-\\u9fa5]+\\.[A-Za-z0-9]{1,6})`,`g`);function Nn(e){if(!e)return[];let t=e.replace(/\bhttps?:\/\/\S+/gi,` `),n=[],r;for(Mn.lastIndex=0;(r=Mn.exec(t))!==null;){let e=r[0].replace(/[,。、)()\s]+$/,``);e&&(/\/$/.test(e)&&!RegExp(`\\.[A-Za-z0-9]{1,6}$`).test(e)||/[.\\/~]/.test(e)&&(n.includes(e)||n.push(e)))}return n}function Pn(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}async function Fn(e,n=[]){if(!e)return;let r=e.querySelector(`.markdown-body`)||e,i=new Set((n||[]).map(Pn)),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,{acceptNode(e){if(!e.nodeValue||!e.nodeValue.trim())return NodeFilter.FILTER_REJECT;let t=e.parentNode;return!t||!t.closest||t.closest(`a, pre, code, script, style, .chat-file-link`)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}}),o=[];for(;a.nextNode();)o.push(a.currentNode);let s=new Set;for(let e of o)for(let t of Nn(e.nodeValue))s.add(t);if(s.size===0)return;let l=[...s].filter(e=>!i.has(Pn(e))),u=new Set;if(l.length>0)try{let e=null;try{let t=await(await c(()=>import(`./workspace-manager-DVPkwn2d.js`).then(e=>e.j),__vite__mapDeps([0,1,2,3]))).getAgentStatusDetail();t&&t.workdir&&(e=t.workdir)}catch{}let t=await c(()=>import(`./context-indicator-CWyjBBv3.js`).then(e=>e.cn),__vite__mapDeps([4,1,2,3,5,6,7,0])),n=e?Pn(e):null,r=await Promise.all(l.map(e=>t.resolveWorkspaceAbsolutePath(e).catch(()=>null))),i=[];for(let e=0;e<l.length;e++){let t=r[e];if(!n||!t)continue;let a=Pn(t);a!==n&&!a.startsWith(n.endsWith(`/`)?n:n+`/`)||i.push({token:l[e],path:t})}if(i.length){let e=await chrome.runtime.sendMessage({type:`CHECK_FILES_EXIST`,paths:i.map(e=>e.path)});if(e&&e.success&&e.results)for(let t of i)e.results[t.path]===!0&&u.add(Pn(t.token))}}catch{}let d=e=>i.has(Pn(e))||u.has(Pn(e)),f=t(`chat.fileLinkTitle`);for(let e of o){let t=e.nodeValue,n=Nn(t).filter(d);if(n.length===0)continue;let r=n.slice().sort((e,t)=>t.length-e.length),i=document.createDocumentFragment(),a=t;for(;a.length;){let e=-1,t=null;for(let n of r){let r=a.indexOf(n);r!==-1&&(e===-1||r<e)&&(e=r,t=n)}if(e===-1){i.appendChild(document.createTextNode(a));break}e>0&&i.appendChild(document.createTextNode(a.slice(0,e)));let n=document.createElement(`span`);n.className=`chat-file-link`,n.setAttribute(`data-path`,t),n.setAttribute(`title`,f),n.textContent=t,i.appendChild(n),a=a.slice(e+t.length)}e.parentNode&&e.parentNode.replaceChild(i,e)}}var In=!1;function Ln(){In||(In=!0,document.addEventListener(`click`,async e=>{let n=e.target.closest&&e.target.closest(`.chat-file-link`);if(!n)return;let r=n.getAttribute(`data-path`);if(r)try{await(await c(()=>import(`./context-indicator-CWyjBBv3.js`).then(e=>e.cn),__vite__mapDeps([4,1,2,3,5,6,7,0]))).locateFileInWorkspace(r)}catch{C(t(`chat.fileLinkFailed`),`error`)}},!0))}var Rn=`voiceInputDevice`,zn=new Set([`default`,`communications`]);function Bn(e){return typeof e==`string`?e.trim():``}function Vn(e){let t=Bn(e),n={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};return t?{...n,deviceId:{exact:t}}:n}function Hn(e){try{return(e.navigator??globalThis.navigator)?.mediaDevices||null}catch{return null}}async function Un(e={}){let t=Hn(e);if(!t||typeof t.enumerateDevices!=`function`)return[];let n;try{n=await t.enumerateDevices()}catch{return[]}let r=new Set,i=[];for(let e of Array.isArray(n)?n:[]){if(e?.kind!==`audioinput`)continue;let t=Bn(e.deviceId);!t||zn.has(t)||r.has(t)||(r.add(t),i.push({deviceId:t,label:typeof e.label==`string`?e.label.trim():``}))}return i}function Wn(e,t){let n=Bn(t);return n?(Array.isArray(e)?e:[]).some(e=>e?.deviceId===n):!0}var Gn=2500,Kn=Symbol(`device-enum-timeout`);async function qn(e={},t=Gn){let n=Hn(e);if(!n||typeof n.enumerateDevices!=`function`)return{devices:[],timedOut:!1,unsupported:!0};let r=Math.max(0,Number(t)||2500),i=null,a=new Promise(e=>{i=setTimeout(()=>e(Kn),r)});try{let t=await Promise.race([Un(e),a]);return t===Kn?{devices:[],timedOut:!0,unsupported:!1}:{devices:t,timedOut:!1,unsupported:!1}}finally{i!==null&&clearTimeout(i)}}var Jn=1500;async function Yn(e={},t=Jn){let n=Hn(e);if(!n||typeof n.getUserMedia!=`function`)return!1;let r=Math.max(0,Number(t)||1500),i=e=>{try{e?.getTracks?.().forEach(e=>e.stop())}catch{}},a=!1,o=null,s=null,c=Promise.resolve().then(()=>n.getUserMedia({audio:!0})).then(e=>(a?i(e):o=e,!!e)).catch(()=>!1),l=new Promise(e=>{s=setTimeout(()=>e(!1),r)}),u;try{u=await Promise.race([c,l])}finally{s!==null&&clearTimeout(s),a=!0,i(o),o=null}return u===!0}function Xn(){try{return globalThis.chrome?.storage?.local||null}catch{return null}}async function Zn(){let e=Xn();if(!e?.get)return``;try{return Bn((await e.get(Rn))?.[Rn])}catch{return``}}async function Qn(e){let t=Bn(e),n=Xn();if(!n?.set)return t;try{await n.set({[Rn]:t})}catch{}return t}function $n(e,t={}){let n=Hn(t);if(!n||typeof n.addEventListener!=`function`)return()=>{};let r=()=>{try{e()}catch{}};try{n.addEventListener(`devicechange`,r)}catch{return()=>{}}return()=>{try{n.removeEventListener(`devicechange`,r)}catch{}}}async function er(e,t={}){let n=Hn(t);if(!n||typeof n.getUserMedia!=`function`){let e=Error(`unsupported`);throw e.name=`NotSupportedError`,e}let r=Bn(e);try{return{stream:await n.getUserMedia({audio:Vn(r)}),fellBack:!1,deviceId:r}}catch(e){let t=e?.name||``;if(!r||!(t===`OverconstrainedError`||t===`NotFoundError`||t===`NotReadableError`))throw e;return{stream:await n.getUserMedia({audio:Vn(``)}),fellBack:!0,deviceId:``,error:t}}}var tr={version:`2.8.9`,tag:`v2.8.9`,commitId:`73c2b2579fbebca735430b63da7269d2713a2cfa`,publishedAt:`2026-11-17T23:09:21.837Z`};export{ee as $,ye as A,D as B,Jt as C,Ce as D,le as E,Te as F,k as G,A as H,oe as I,P as J,j as K,se as L,re as M,M as N,xe as O,N as P,b as Q,ie as R,qt as S,ne as T,be as U,ve as V,ge as W,ue as X,C as Y,w as Z,un as _,qn as a,rn as b,$n as c,An as d,te as et,Fn as f,fn as g,nn as h,Zn as i,T as j,fe as k,Sn as l,jn as m,er as n,Qn as o,Ln as p,je as q,Wn as r,Yn as s,tr as t,S as tt,Q as u,yn as v,Bt as w,X as x,dn as y,ce as z};
@@ -0,0 +1 @@
1
+ import{r as e}from"./chunk-CMxvf4Kt.js";import{a as t,c as n,l as r}from"./i18n-DvmxOw8q.js";import{F as i,b as a,wt as o}from"./model-profiles-C3kJEHM6.js";var s=e({BROWSE_DIRS_CLIENT_TIMEOUT_MS:()=>P,PICK_DIRECTORY_CLIENT_TIMEOUT_MS:()=>N,browseDirs:()=>L,buildAgentHeaders:()=>w,cancelPickDirectory:()=>I,createDir:()=>Z,deleteFs:()=>ae,downloadFile:()=>H,downloadFileStream:()=>K,downloadFileStreamWithProgress:()=>q,downloadFiles:()=>U,downloadFilesStream:()=>J,downloadFilesStreamWithProgress:()=>Y,formatFileSize:()=>u,formatTime:()=>d,getAgentConfig:()=>E,getAgentStatusDetail:()=>A,getFileExtension:()=>f,getFileIcon:()=>l,getFileInfo:()=>$,getHomeDir:()=>O,getMimeType:()=>v,getPreviewType:()=>_,getWorkspaceRoot:()=>D,isImageFile:()=>te,isKnownTextFile:()=>h,listDirectory:()=>z,looksLikeBinaryText:()=>g,moveFs:()=>Q,pickDirectory:()=>F,readFileContent:()=>B,removeAllowedPath:()=>M,renameFs:()=>X,resetWorkspaceRoot:()=>k,searchFilesRemote:()=>W,supportsPreview:()=>m,switchWorkspace:()=>j,writeFileContent:()=>V});t(`zh`,{workspaceMgr:{agentNotPairedDetail:`Agent 未配对,请先在设置中完成配对`,agentNotPaired:`Agent 未配对`,requestFailed:`请求失败: {message}`,downloadFailed:`下载失败`,cancelled:`已取消`}}),t(`en`,{workspaceMgr:{agentNotPairedDetail:`Agent not paired. Please complete pairing in Settings first.`,agentNotPaired:`Agent not paired`,requestFailed:`Request failed: {message}`,downloadFailed:`Download failed`,cancelled:`Cancelled`}});var c={txt:`📄`,md:`📝`,json:`📋`,js:`📜`,mjs:`📜`,ts:`📘`,jsx:`⚛️`,tsx:`⚛️`,html:`🌐`,htm:`🌐`,css:`🎨`,scss:`🎨`,less:`🎨`,xml:`📰`,yaml:`📰`,yml:`📰`,py:`🐍`,java:`☕`,c:`⚙️`,cpp:`⚙️`,h:`⚙️`,go:`🔹`,rs:`🦀`,rb:`💎`,php:`🐘`,sql:`🗄️`,sh:`💻`,bash:`💻`,zsh:`💻`,cfg:`⚙️`,ini:`⚙️`,toml:`⚙️`,conf:`⚙️`,log:`📊`,csv:`📊`,tsv:`📊`,env:`🔒`,vue:`💚`,svelte:`🧡`,astro:`🚀`,rtf:`📄`,svg:`🖼️`,png:`🖼️`,jpg:`🖼️`,jpeg:`🖼️`,gif:`🖼️`,webp:`🖼️`,bmp:`🖼️`,ico:`🖼️`,pdf:`📕`,doc:`📘`,docx:`📘`,xls:`📗`,xlsx:`📗`,ppt:`📙`,pptx:`📙`,zip:`📦`,gz:`📦`,tar:`📦`,rar:`📦`,"7z":`📦`,mp3:`🎵`,wav:`🎵`,mp4:`🎬`,webm:`🎬`,avi:`🎬`};function l(e,t){return t===`directory`?`📁`:c[(e.split(`.`).pop()||``).toLowerCase()]||`📄`}function u(e){if(e===0)return`0 B`;if(e==null)return`—`;let t=[`B`,`KB`,`MB`,`GB`,`TB`],n=1024,r=Math.floor(Math.log(e)/Math.log(n));return`${(e/n**r).toFixed(r===0?0:1)} ${t[r]}`}function d(e){return e?new Date(e).toLocaleString(`zh-CN`,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`}):`—`}function f(e){let t=String(e||``).split(/[\\/]/).pop()||``,n=t.lastIndexOf(`.`);return n<=0?``:t.slice(n+1).toLowerCase()}var p=new Set(`txt.md.markdown.json.js.mjs.cjs.ts.jsx.tsx.html.htm.css.scss.less.xml.yaml.yml.py.java.c.cpp.h.hpp.go.rs.rb.php.sql.sh.bash.zsh.cfg.ini.toml.conf.log.csv.tsv.env.vue.svelte.astro.rtf.svg`.split(`.`)),ee=new Set(`zip.rar.7z.gz.tgz.bz2.xz.tar.jar.war.apk.ipa.crx.xpi.exe.dll.so.dylib.bin.dmg.pkg.msi.deb.rpm.class.pyc.o.obj.wasm.doc.ppt.docm.avi.mkv.flv.wmv.mpg.mpeg.rmvb.rm.3gp.wma.amr.aiff.mid.midi.tif.tiff.heic.heif.psd.ai.sketch.fig.xd.ttf.otf.woff.woff2.eot.db.sqlite.sqlite3.mdb`.split(`.`));function m(e){return!ee.has(f(e))}function h(e){return p.has(f(e))}function g(e){if(!e)return!1;let t=e.slice(0,8e3);if(t.includes(`\0`))return!0;let n=0;for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);(r<9||r>13&&r<32)&&n++}return n/t.length>.01}function _(e){let t=f(e);return t===`pdf`?`pdf`:t===`docx`?`docx`:t===`xlsx`||t===`xls`?`xlsx`:t===`pptx`?`pptx`:new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`bmp`,`ico`]).has(t)?`image`:new Set([`mp4`,`webm`,`ogg`,`m4v`,`mov`]).has(t)?`video`:new Set([`mp3`,`wav`,`m4a`,`aac`,`flac`,`opus`]).has(t)?`audio`:`text`}function te(e){let t=(e.split(`.`).pop()||``).toLowerCase();return new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`bmp`,`ico`,`svg`]).has(t)}function v(e){return{txt:`text/plain`,md:`text/markdown`,json:`application/json`,js:`application/javascript`,html:`text/html`,css:`text/css`,xml:`application/xml`,yaml:`text/yaml`,yml:`text/yaml`,csv:`text/csv`,svg:`image/svg+xml`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,bmp:`image/bmp`,pdf:`application/pdf`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,mp4:`video/mp4`,webm:`video/webm`,ogg:`video/ogg`,m4v:`video/x-m4v`,mov:`video/quicktime`,mp3:`audio/mpeg`,wav:`audio/wav`,m4a:`audio/mp4`,aac:`audio/aac`,flac:`audio/flac`,opus:`audio/ogg`}[(e.split(`.`).pop()||``).toLowerCase()]||`text/plain`}var y=null,b=null,x=null,S=null;function C(){try{return a?.activeSessionId||null}catch{return null}}function w(e,t=C()){let n={Authorization:`Bearer ${e.token}`};return t&&(n[`X-AIH-Session-Id`]=t),n}function ne(e){if(e instanceof TypeError)return!0;let t=String(e&&e.message||``).toLowerCase();return t.includes(`failed to fetch`)||t.includes(`load failed`)||t.includes(`networkerror`)}function T(e,t){let n=t&&t.message;ne(t)?r.debug(`[WorkspaceManager] ${e} skipped (agent unreachable):`,n):r.warn(`[WorkspaceManager] ${e} failed:`,n)}async function E(){if(S&&S.url&&S.token)return S;try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=e.pairedAgents||[],n=e.activeAgentId;if(!n||t.length===0)return null;let r=t.find(e=>e.id===n)||t[0];return r?(S={id:r.id,url:r.url,token:o(r.token)},S):null}catch(e){return r.warn(`[WorkspaceManager] getAgentconfiguration failed:`,e.message),null}}async function D(e){let t=e===void 0?C():e,n=await E(),r=`${t||``}::${n?.id||n?.url||``}`;if(y&&b===r)return y;if(!n)return null;try{let e=await fetch(`${n.url}/api/status/detail`,{headers:w(n,t)});if(e.ok){let t=await e.json();if(t.success&&t.workdir)return y=t.workdir,b=r,y}}catch(e){T(`get workingdirectory`,e)}return null}async function O(){if(x)return x;let e=await E();if(!e)return null;try{let t=await fetch(`${e.url}/api/status/detail`,{headers:{Authorization:`Bearer ${e.token}`}});if(t.ok){let e=await t.json();if(e.success&&e.homeDir)return x=e.homeDir,x}}catch(e){T(`get homedir`,e)}return null}function k(){y=null,b=null,x=null,S=null,i()}async function A(e){let t=e===void 0?C():e,n=await E();if(!n)return null;try{let e=await fetch(`${n.url}/api/status/detail`,{headers:w(n,t)});if(e.ok){let t=await e.json();if(t.success)return t}}catch(e){T(`get statusdetailcase`,e)}return null}async function j(e,t={}){let n=t.sessionId===void 0?C():t.sessionId,r={workdir:e,scope:n?`session`:`global`};n&&(r.sessionId=n);let i=await R(`/api/config/workdir`,r,n);return i.success&&k(),i}async function M(e){return R(`/api/config/allowed-paths/remove`,{path:e})}var N=200*1e3,P=8*1e3;async function F(){let e=await E();if(!e)return{success:!1,available:!1,error:n(`workspaceMgr.agentNotPairedDetail`)};let t=new AbortController,r=setTimeout(()=>t.abort(),N);try{let n=await fetch(`${e.url}/api/config/pick-directory`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.token}`},body:JSON.stringify({}),signal:t.signal});if(n.status===404)return{success:!1,path:null,available:!1,outdated:!0};let r=await n.json();return r&&typeof r==`object`?r:{success:!1,path:null,available:!0,error:`bad-response`}}catch(e){return e&&e.name===`AbortError`?{success:!1,path:null,available:!0,error:`client-timeout`}:{success:!1,path:null,error:n(`workspaceMgr.requestFailed`,{message:e.message})}}finally{clearTimeout(r)}}async function I(){return R(`/api/config/pick-directory/cancel`,{})}async function L(e){let t=await E();if(!t)return{success:!1,error:n(`workspaceMgr.agentNotPairedDetail`)};let r=new AbortController,i=setTimeout(()=>r.abort(),P);try{let n=await fetch(`${t.url}/api/fs/browse`,{method:`POST`,headers:{"Content-Type":`application/json`,...w(t)},body:JSON.stringify(typeof e==`string`&&e?{path:e}:{}),signal:r.signal});if(n.status===404)return{success:!1,path:null,outdated:!0,error:`endpoint-missing`};let i=await n.json().catch(()=>null);return!i||typeof i!=`object`?{success:!1,error:`bad-response`}:n.ok?i:{...i,success:!1,status:n.status}}catch(e){return e&&e.name===`AbortError`?{success:!1,error:`client-timeout`}:{success:!1,error:n(`workspaceMgr.requestFailed`,{message:e.message})}}finally{clearTimeout(i)}}async function R(e,t={},r=void 0){let i=await E();if(!i)return{success:!1,error:n(`workspaceMgr.agentNotPairedDetail`)};let a=r===void 0?C():r;try{return await(await fetch(`${i.url}${e}`,{method:`POST`,headers:{"Content-Type":`application/json`,...w(i,a)},body:JSON.stringify(t)})).json()}catch(e){return{success:!1,error:n(`workspaceMgr.requestFailed`,{message:e.message})}}}async function z(e){return R(`/api/fs/list`,{path:e||`.`})}async function B(e){return R(`/api/fs/read`,{path:e})}async function V(e,t){return R(`/api/fs/write`,{path:e,content:t})}async function H(e){return R(`/api/fs/download`,{path:e})}async function U(e){return R(`/api/fs/download-multi`,{paths:e})}function re(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function ie(e){return e?!!(e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)||/^(\\\\|\/\/)[^\\/]+[\\/]/.test(e)):!1}async function W(e,t,n=200){let r=await R(`/api/fs/search_files`,{path:e,pattern:`*${t}*`,recursive:!0,maxResults:n});return r.success?(r.results||[]).map(t=>{let n=re(ie(t.path)?t.path:`${e}/${t.path}`),r=n.substring(0,n.lastIndexOf(`/`));return{name:t.name,type:t.type||`file`,size:t.size,mtime:t.mtime,fullPath:n,matchPath:r}}):[]}function G(e,t){if(!e)return t;let n=e.match(/filename\*=UTF-8''(.+?)(?:;|$)/)||e.match(/filename="(.+?)"/);return n?decodeURIComponent(n[1]):t}async function K(e){let t=await E();if(!t)return{success:!1,error:n(`workspaceMgr.agentNotPairedDetail`)};try{let r=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...w(t)},body:JSON.stringify({path:e})});return r.ok?{success:!0,blob:await r.blob(),name:G(r.headers.get(`Content-Disposition`),e.split(/[\\/]/).pop()),mimeType:r.headers.get(`Content-Type`)}:{success:!1,error:(await r.json().catch(()=>({error:r.statusText}))).error||n(`workspaceMgr.downloadFailed`)}}catch(e){return{success:!1,error:n(`workspaceMgr.requestFailed`,{message:e.message})}}}async function q(e,t,r){let i=await E();if(!i)return{success:!1,error:n(`workspaceMgr.agentNotPaired`)};try{let a=await fetch(`${i.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...w(i)},body:JSON.stringify({path:e}),signal:r});if(!a.ok)return{success:!1,error:(await a.json().catch(()=>({error:a.statusText}))).error||n(`workspaceMgr.downloadFailed`)};let o=parseInt(a.headers.get(`Content-Length`)||`0`,10),s=a.body.getReader();r&&r.addEventListener(`abort`,()=>{try{s.cancel()}catch{}});let c=[],l=0;for(;;){let{done:e,value:n}=await s.read();if(e)break;c.push(n),l+=n.length,t&&o>0&&t({loaded:l,total:o,percent:Math.round(l/o*100)})}return{success:!0,blob:new Blob(c),name:G(a.headers.get(`Content-Disposition`),e.split(/[\\/]/).pop()),mimeType:a.headers.get(`Content-Type`)}}catch(e){return e.name===`AbortError`?{success:!1,error:n(`workspaceMgr.cancelled`),aborted:!0}:{success:!1,error:n(`workspaceMgr.requestFailed`,{message:e.message})}}}async function J(e){let t=await E();if(!t)return{success:!1,error:n(`workspaceMgr.agentNotPairedDetail`)};try{let r=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...w(t)},body:JSON.stringify({paths:e})});return r.ok?{success:!0,blob:await r.blob(),name:G(r.headers.get(`Content-Disposition`),`workspace.zip`),mimeType:r.headers.get(`Content-Type`)}:{success:!1,error:(await r.json().catch(()=>({error:r.statusText}))).error||n(`workspaceMgr.downloadFailed`)}}catch(e){return{success:!1,error:n(`workspaceMgr.requestFailed`,{message:e.message})}}}async function Y(e,t,r){let i=await E();if(!i)return{success:!1,error:n(`workspaceMgr.agentNotPaired`)};try{let a=await fetch(`${i.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...w(i)},body:JSON.stringify({paths:e}),signal:r});if(!a.ok)return{success:!1,error:(await a.json().catch(()=>({error:a.statusText}))).error||n(`workspaceMgr.downloadFailed`)};let o=parseInt(a.headers.get(`Content-Length`)||`0`,10),s=a.body.getReader();r&&r.addEventListener(`abort`,()=>{try{s.cancel()}catch{}});let c=[],l=0;for(;;){let{done:e,value:n}=await s.read();if(e)break;c.push(n),l+=n.length,t&&o>0&&t({loaded:l,total:o,percent:Math.round(l/o*100)})}return{success:!0,blob:new Blob(c),name:G(a.headers.get(`Content-Disposition`),`workspace.zip`),mimeType:a.headers.get(`Content-Type`)}}catch(e){return e.name===`AbortError`?{success:!1,error:n(`workspaceMgr.cancelled`),aborted:!0}:{success:!1,error:n(`workspaceMgr.requestFailed`,{message:e.message})}}}async function ae(e){return R(`/api/fs/delete`,{path:e})}async function X(e,t){return R(`/api/fs/rename`,{path:e,newName:t})}async function Z(e){return R(`/api/fs/mkdir`,{path:e})}async function Q(e,t){return R(`/api/fs/move`,{path:e,destDir:t})}async function $(e){return R(`/api/fs/stat`,{path:e})}export{j as A,F as C,k as D,X as E,V as M,W as O,Q as S,M as T,_,K as a,z as b,Y as c,E as d,A as f,v as g,O as h,Z as i,s as j,m as k,u as l,$ as m,w as n,q as o,l as p,I as r,J as s,L as t,d as u,D as v,B as w,g as x,h as y};
@@ -2,7 +2,7 @@
2
2
  "manifest_version": 3,
3
3
  "default_locale": "zh_CN",
4
4
  "name": "__MSG_extName__",
5
- "version": "2.8.7",
5
+ "version": "2.8.9",
6
6
  "description": "__MSG_extDescription__",
7
7
  "permissions": [
8
8
  "activeTab",