ai-helper-agent 2.7.9 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{a as e,c as t,l as n,r}from"./i18n-DDhHR2eT.js";import{$ as i,b as a}from"./model-profiles-9Pkrdr9U.js";import{b as o,kt as s}from"./session-store-XFFEUHgS.js";import{o as c}from"./agent-store-CuK2pMqc.js";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(审查清理)
1
+ import{a as e,c as t,l as n,r}from"./i18n-DDhHR2eT.js";import{$ as i,b as a}from"./model-profiles-9Pkrdr9U.js";import{b as o,kt as s}from"./session-store-BWuBHdD6.js";import{o as c}from"./agent-store-DDZKtEZX.js";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(审查清理)
2
2
  - store: subAction=add需type+content,update需memoryId+type,**delete仅需memoryId无需type**。**删除前先recall查id**
3
3
  - recall: query用关键词(如"考试"),不用完整句子。可选memoryType和limit
4
4
  - manage: subAction=review审查价值,compact清理低价值
@@ -1,3 +1,3 @@
1
1
  var e=`appTheme`,t=[`light`,`dark`,`system`],n=`light`,r=`light`,i=null,a=null,o=[],s=!1;function c(e){let t=e!==r;r=e,typeof document<`u`&&document.documentElement.setAttribute(`data-theme`,e);try{localStorage.setItem(`appThemeResolved`,e)}catch{}t&&o.slice().forEach(t=>{try{t(e)}catch(e){console.warn(`[theme] subscriber error`,e)}})}function l(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`)&&(r=e,typeof document<`u`&&document.documentElement.setAttribute(`data-theme`,e))}catch{}})();function u(){return n}function d(){return r}function ee(e){o.push(e)}async function te(){typeof matchMedia<`u`&&(i=matchMedia(`(prefers-color-scheme: dark)`),a&&i.removeEventListener(`change`,a),a=()=>{n===`system`&&c(l(`system`))},i.addEventListener(`change`,a)),!s&&typeof chrome<`u`&&chrome.storage&&chrome.storage.onChanged&&(chrome.storage.onChanged.addListener((e,r)=>{r===`local`&&e.appTheme&&t.includes(e.appTheme.newValue)&&(n=e.appTheme.newValue,c(l(n)))}),s=!0);let r=await new Promise(t=>{try{chrome.storage.local.get([e],e=>{if(chrome.runtime&&chrome.runtime.lastError){t(null);return}t(e||{})})}catch{t(null)}});r!==null&&(n=t.includes(r[e])?r[e]:`light`,c(l(n)))}async function ne(e){t.includes(e)&&(n=e,c(l(e)),await new Promise(t=>chrome.storage.local.set({appTheme:e},t)))}function f(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 p(e){if(Array.isArray(e))return e}function re(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 ie(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
2
2
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function m(e,t){return p(e)||re(e,t)||h(e,t)||ie()}function h(e,t){if(e){if(typeof e==`string`)return f(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)?f(e,t):void 0}}var ae=Object.entries,g=Object.setPrototypeOf,_=Object.isFrozen,oe=Object.getPrototypeOf,se=Object.getOwnPropertyDescriptor,v=Object.freeze,y=Object.seal,b=Object.create,x=typeof Reflect<`u`&&Reflect,ce=x.apply,S=x.construct;v||=function(e){return e},y||=function(e){return e},ce||=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)},S||=function(e){return new e(...[...arguments].slice(1))};var le=A(Array.prototype.forEach),ue=A(Array.prototype.lastIndexOf),de=A(Array.prototype.pop),C=A(Array.prototype.push),fe=A(Array.prototype.splice),w=Array.isArray,pe=A(String.prototype.toLowerCase),me=A(String.prototype.toString),he=A(String.prototype.match),ge=A(String.prototype.replace),_e=A(String.prototype.indexOf),ve=A(String.prototype.trim),ye=A(Number.prototype.toString),be=A(Boolean.prototype.toString),T=typeof BigInt>`u`?null:A(BigInt.prototype.toString),xe=typeof Symbol>`u`?null:A(Symbol.prototype.toString),E=A(Object.prototype.hasOwnProperty),D=A(Object.prototype.toString),O=A(RegExp.prototype.test),k=Se(TypeError);function A(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return ce(e,t,n)}}function Se(e){return function(){return S(e,[...arguments])}}function j(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:pe;if(g&&g(e,null),!w(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(_(t)||(t[r]=e),i=e)}e[i]=!0}return e}function Ce(e){for(let t=0;t<e.length;t++)E(e,t)||(e[t]=null);return e}function M(e){let t=b(null);for(let r of ae(e)){var n=m(r,2);let i=n[0],a=n[1];E(e,i)&&(w(a)?t[i]=Ce(a):a&&typeof a==`object`&&a.constructor===Object?t[i]=M(a):t[i]=a)}return t}function we(e){switch(typeof e){case`string`:return e;case`number`:return ye(e);case`boolean`:return be(e);case`bigint`:return T?T(e):`0`;case`symbol`:return xe?xe(e):`Symbol()`;case`undefined`:return D(e);case`function`:case`object`:{if(e===null)return D(e);let t=e,n=N(t,`toString`);if(typeof n==`function`){let e=n(t);return typeof e==`string`?e:D(e)}return D(e)}default:return D(e)}}function N(e,t){for(;e!==null;){let n=se(e,t);if(n){if(n.get)return A(n.get);if(typeof n.value==`function`)return A(n.value)}e=oe(e)}function n(){return null}return n}function Te(e){try{return O(e,``),!0}catch{return!1}}var Ee=v(`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(`.`)),De=v(`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(`.`)),Oe=v([`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`]),ke=v([`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`]),Ae=v(`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(`.`)),je=v([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),Me=v([`#text`]),Ne=v(`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(`.`)),Pe=v(`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(`.`)),Fe=v(`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(`.`)),Ie=v([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),Le=y(/{{[\w\W]*|^[\w\W]*}}/g),Re=y(/<%[\w\W]*|^[\w\W]*%>/g),ze=y(/\${[\w\W]*/g),Be=y(/^data-[\-\w.\u00B7-\uFFFF]+$/),Ve=y(/^aria-[\-\w]+$/),He=y(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Ue=y(/^(?:\w+script|data):/i),We=y(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ge=y(/^html$/i),Ke=y(/^[a-z][.\w]*(-[.\w]+)+$/i),qe=y(/<[/\w!]/g),Je=y(/<[/\w]/g),Ye=y(/<\/no(script|embed|frames)/i),Xe=y(/\/>/i),P={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Ze=function(){return typeof window>`u`?null:window},Qe=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}},$e=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},F=function(e,t,n,r){return E(e,t)&&w(e[t])?j(r.base?M(r.base):{},e[t],r.transform):n};function et(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Ze(),t=e=>et(e);if(t.version=`3.4.12`,t.removed=[],!e||!e.document||e.document.nodeType!==P.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,ee=N(d,`cloneNode`),te=N(d,`remove`),ne=N(d,`nextSibling`),f=N(d,`childNodes`),p=N(d,`parentNode`),re=N(d,`shadowRoot`),ie=N(d,`attributes`),m=o&&o.prototype?N(o.prototype,`nodeType`):null,h=o&&o.prototype?N(o.prototype,`nodeName`):null;if(typeof a==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let g,_=``,oe,se=!1,x=0,ce=function(){if(x>0)throw k(`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.`)},S=function(e){ce(),x++;try{return g.createHTML(e)}finally{x--}},ye=function(e){ce(),x++;try{return g.createScriptURL(e)}finally{x--}},be=function(){return se||=(oe=Qe(u,i),!0),oe},T=n,xe=T.implementation,D=T.createNodeIterator,A=T.createDocumentFragment,Se=T.getElementsByTagName,Ce=r.importNode,I=$e();t.isSupported=typeof ae==`function`&&typeof p==`function`&&xe&&xe.createHTMLDocument!==void 0;let tt=Le,nt=Re,L=ze,rt=Be,it=Ve,at=Ue,ot=We,st=Ke,ct=He,R=null,lt=j({},[...Ee,...De,...Oe,...Ae,...Me]),z=null,ut=j({},[...Ne,...Pe,...Fe,...Ie]),B=Object.seal(b(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}})),dt=null,ft=null,V=Object.seal(b(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),pt=!0,mt=!0,ht=!1,gt=!0,H=!1,U=!0,W=!1,_t=!1,vt=null,yt=null,bt=!1,G=!1,xt=!1,St=!1,Ct=!0,wt=!1,Tt=`user-content-`,Et=!0,Dt=!1,K={},q=null,Ot=j({},`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(`.`)),kt=null,At=j({},[`audio`,`video`,`img`,`source`,`image`,`track`]),jt=null,Mt=j({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),Nt=`http://www.w3.org/1998/Math/MathML`,Pt=`http://www.w3.org/2000/svg`,J=`http://www.w3.org/1999/xhtml`,Y=J,Ft=!1,It=null,Lt=j({},[Nt,Pt,J],me),Rt=v([`mi`,`mo`,`mn`,`ms`,`mtext`]),zt=j({},Rt),Bt=v([`annotation-xml`]),Vt=j({},Bt),Ht=j({},[`title`,`style`,`font`,`a`,`script`]),Ut=null,Wt=[`application/xhtml+xml`,`text/html`],X=null,Gt=null,Kt=n.createElement(`form`),qt=function(e){return e instanceof RegExp||e instanceof Function},Jt=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Gt&&Gt===e)return;(!e||typeof e!=`object`)&&(e={}),e=M(e),Ut=Wt.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,X=Ut===`application/xhtml+xml`?me:pe,R=F(e,`ALLOWED_TAGS`,lt,{transform:X}),z=F(e,`ALLOWED_ATTR`,ut,{transform:X}),It=F(e,`ALLOWED_NAMESPACES`,Lt,{transform:me}),jt=F(e,`ADD_URI_SAFE_ATTR`,Mt,{transform:X,base:Mt}),kt=F(e,`ADD_DATA_URI_TAGS`,At,{transform:X,base:At}),q=F(e,`FORBID_CONTENTS`,Ot,{transform:X}),dt=F(e,`FORBID_TAGS`,M({}),{transform:X}),ft=F(e,`FORBID_ATTR`,M({}),{transform:X}),K=E(e,`USE_PROFILES`)?e.USE_PROFILES&&typeof e.USE_PROFILES==`object`?M(e.USE_PROFILES):e.USE_PROFILES:!1,pt=e.ALLOW_ARIA_ATTR!==!1,mt=e.ALLOW_DATA_ATTR!==!1,ht=e.ALLOW_UNKNOWN_PROTOCOLS||!1,gt=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,H=e.SAFE_FOR_TEMPLATES||!1,U=e.SAFE_FOR_XML!==!1,W=e.WHOLE_DOCUMENT||!1,G=e.RETURN_DOM||!1,xt=e.RETURN_DOM_FRAGMENT||!1,St=e.RETURN_TRUSTED_TYPE||!1,bt=e.FORCE_BODY||!1,Ct=e.SANITIZE_DOM!==!1,wt=e.SANITIZE_NAMED_PROPS||!1,Et=e.KEEP_CONTENT!==!1,Dt=e.IN_PLACE||!1,ct=Te(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:He,Y=typeof e.NAMESPACE==`string`?e.NAMESPACE:J,zt=E(e,`MATHML_TEXT_INTEGRATION_POINTS`)&&e.MATHML_TEXT_INTEGRATION_POINTS&&typeof e.MATHML_TEXT_INTEGRATION_POINTS==`object`?M(e.MATHML_TEXT_INTEGRATION_POINTS):j({},Rt),Vt=E(e,`HTML_INTEGRATION_POINTS`)&&e.HTML_INTEGRATION_POINTS&&typeof e.HTML_INTEGRATION_POINTS==`object`?M(e.HTML_INTEGRATION_POINTS):j({},Bt);let t=E(e,`CUSTOM_ELEMENT_HANDLING`)&&e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING==`object`?M(e.CUSTOM_ELEMENT_HANDLING):b(null);if(B=b(null),E(t,`tagNameCheck`)&&qt(t.tagNameCheck)&&(B.tagNameCheck=t.tagNameCheck),E(t,`attributeNameCheck`)&&qt(t.attributeNameCheck)&&(B.attributeNameCheck=t.attributeNameCheck),E(t,`allowCustomizedBuiltInElements`)&&typeof t.allowCustomizedBuiltInElements==`boolean`&&(B.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),y(B),H&&(mt=!1),xt&&(G=!0),K&&(R=j({},Me),z=b(null),K.html===!0&&(j(R,Ee),j(z,Ne)),K.svg===!0&&(j(R,De),j(z,Pe),j(z,Ie)),K.svgFilters===!0&&(j(R,Oe),j(z,Pe),j(z,Ie)),K.mathMl===!0&&(j(R,Ae),j(z,Fe),j(z,Ie))),V.tagCheck=null,V.attributeCheck=null,E(e,`ADD_TAGS`)&&(typeof e.ADD_TAGS==`function`?V.tagCheck=e.ADD_TAGS:w(e.ADD_TAGS)&&(R===lt&&(R=M(R)),j(R,e.ADD_TAGS,X))),E(e,`ADD_ATTR`)&&(typeof e.ADD_ATTR==`function`?V.attributeCheck=e.ADD_ATTR:w(e.ADD_ATTR)&&(z===ut&&(z=M(z)),j(z,e.ADD_ATTR,X))),E(e,`ADD_URI_SAFE_ATTR`)&&w(e.ADD_URI_SAFE_ATTR)&&j(jt,e.ADD_URI_SAFE_ATTR,X),E(e,`FORBID_CONTENTS`)&&w(e.FORBID_CONTENTS)&&(q===Ot&&(q=M(q)),j(q,e.FORBID_CONTENTS,X)),E(e,`ADD_FORBID_CONTENTS`)&&w(e.ADD_FORBID_CONTENTS)&&(q===Ot&&(q=M(q)),j(q,e.ADD_FORBID_CONTENTS,X)),Et&&(R[`#text`]=!0),W&&j(R,[`html`,`head`,`body`]),R.table&&(j(R,[`tbody`]),delete dt.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw k(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw k(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);let t=g;g=e.TRUSTED_TYPES_POLICY;try{_=S(``)}catch(e){throw g=t,e}}else e.TRUSTED_TYPES_POLICY===null?(g=void 0,_=``):(g===void 0&&(g=be()),g&&typeof _==`string`&&(_=S(``)));v&&v(e),Gt=e},Yt=j({},[...De,...Oe,...ke]),Xt=j({},[...Ae,...je]),Zt=function(e,t,n){return t.namespaceURI===J?e===`svg`:t.namespaceURI===Nt?e===`svg`&&(n===`annotation-xml`||zt[n]):!!Yt[e]},Qt=function(e,t,n){return t.namespaceURI===J?e===`math`:t.namespaceURI===Pt?e===`math`&&Vt[n]:!!Xt[e]},$t=function(e,t,n){return t.namespaceURI===Pt&&!Vt[n]||t.namespaceURI===Nt&&!zt[n]?!1:!Xt[e]&&(Ht[e]||!Yt[e])},en=function(e){let t=p(e);(!t||!t.tagName)&&(t={namespaceURI:Y,tagName:`template`});let n=pe(e.tagName),r=pe(t.tagName);return It[e.namespaceURI]?e.namespaceURI===Pt?Zt(n,t,r):e.namespaceURI===Nt?Qt(n,t,r):e.namespaceURI===J?$t(n,t,r):!!(Ut===`application/xhtml+xml`&&It[e.namespaceURI]):!1},Z=function(e){C(t.removed,{element:e});try{p(e).removeChild(e)}catch{if(te(e),!p(e))throw k(`a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place`)}},tn=function(e){rn(e);let t=f(e);if(t){let e=[];le(t,t=>{C(e,t)}),le(e,e=>{try{te(e)}catch{}})}let n=ie(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{}}},Q=function(e,n){try{C(t.removed,{attribute:n.getAttributeNode(e),from:n})}catch{C(t.removed,{attribute:null,from:n})}if(n.removeAttribute(e),e===`is`)if(G||xt)try{Z(n)}catch{}else try{n.setAttribute(e,``)}catch{}},nn=function(e){let t=ie(e);if(t)for(let n=t.length-1;n>=0;--n){let r=t[n],i=r&&r.name;if(!(typeof i!=`string`||z[X(i)]))try{e.removeAttribute(i)}catch{}}},rn=function(e){let t=[e];for(;t.length>0;){let e=t.pop();(m?m(e):e.nodeType)===P.element&&nn(e);let n=f(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},an=function(e){if(!U)return;let t=[e];for(;t.length>0;){let e=t.pop(),n=m?m(e):e.nodeType;if(n===P.processingInstruction||n===P.comment&&O(Je,e.data)){try{te(e)}catch{}continue}if(n===P.element){let t=e,n=X(h?h(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=f(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}},on=function(e){let t=null,r=null;if(bt)e=`<remove></remove>`+e;else{let t=he(e,/^[\r\n\t ]+/);r=t&&t[0]}Ut===`application/xhtml+xml`&&Y===J&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=g?S(e):e;if(Y===J)try{t=new l().parseFromString(i,Ut)}catch{}if(!t||!t.documentElement){t=xe.createDocument(Y,`template`,null);try{t.documentElement.innerHTML=Ft?_:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),Y===J?Se.call(t,W?`html`:`body`)[0]:W?t.documentElement:a},sn=function(e){return D.call(e.ownerDocument||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},cn=function(e){return e=ge(e,tt,` `),e=ge(e,nt,` `),e=ge(e,L,` `),e},ln=function(e){e.normalize();let t=D.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=cn(n.data),n=t.nextNode();let r=e.querySelectorAll?.call(e,`template`);r&&le(r,e=>{dn(e.content)&&ln(e.content)})},un=function(e){let t=h?h(e):null;return typeof t!=`string`||X(t)!==`form`?!1:typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||e.attributes!==ie(e)||typeof e.removeAttribute!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`||e.nodeType!==m(e)||e.childNodes!==f(e)},dn=function(e){if(!m||typeof e!=`object`||!e)return!1;try{return m(e)===P.documentFragment}catch{return!1}},fn=function(e){if(!m||typeof e!=`object`||!e)return!1;try{return typeof m(e)==`number`}catch{return!1}};function $(e,n,r){e.length!==0&&le(e,e=>{e.call(t,n,r,Gt)})}let pn=function(e,t){return!!(U&&e.hasChildNodes()&&!fn(e.firstElementChild)&&O(qe,e.textContent)&&O(qe,e.innerHTML)||U&&e.namespaceURI===J&&t===`style`&&fn(e.firstElementChild)||e.nodeType===P.processingInstruction||U&&e.nodeType===P.comment&&O(Je,e.data))},mn=function(e,t){if(!dt[t]&&vn(t)&&(B.tagNameCheck instanceof RegExp&&O(B.tagNameCheck,t)||B.tagNameCheck instanceof Function&&B.tagNameCheck(t)))return!1;if(Et&&!q[t]){let t=p(e),n=f(e);if(n&&t){let r=n.length;for(let i=r-1;i>=0;--i){let r=Dt?n[i]:ee(n[i],!0);t.insertBefore(r,ne(e))}}}return Z(e),!0},hn=function(e,n){if($(I.beforeSanitizeElements,e,null),e!==n&&p(e)===null)return!0;if(un(e))return Z(e),!0;let r=X(h?h(e):e.nodeName);if($(I.uponSanitizeElement,e,{tagName:r,allowedTags:R}),e!==n&&p(e)===null)return!0;if(pn(e,r))return Z(e),!0;if(dt[r]||!(V.tagCheck instanceof Function&&V.tagCheck(r))&&!R[r]){let t=mn(e,r);return t===!1&&$(I.afterSanitizeElements,e,null),t}if((m?m(e):e.nodeType)===P.element&&!en(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&O(Ye,e.innerHTML))return Z(e),!0;if(H&&e.nodeType===P.text){let n=cn(e.textContent);e.textContent!==n&&(C(t.removed,{element:e.cloneNode()}),e.textContent=n)}return $(I.afterSanitizeElements,e,null),!1},gn=function(e,t,r){if(ft[t]||U&&t===`patchsrc`||U&&t===`for`&&e!==`label`&&e!==`output`||Ct&&(t===`id`||t===`name`)&&(r in n||r in Kt))return!1;let i=z[t]||V.attributeCheck instanceof Function&&V.attributeCheck(t,e);if(!(mt&&O(rt,t))&&!(pt&&O(it,t))){if(!i){if(!(vn(e)&&(B.tagNameCheck instanceof RegExp&&O(B.tagNameCheck,e)||B.tagNameCheck instanceof Function&&B.tagNameCheck(e))&&(B.attributeNameCheck instanceof RegExp&&O(B.attributeNameCheck,t)||B.attributeNameCheck instanceof Function&&B.attributeNameCheck(t,e))||t===`is`&&B.allowCustomizedBuiltInElements&&(B.tagNameCheck instanceof RegExp&&O(B.tagNameCheck,r)||B.tagNameCheck instanceof Function&&B.tagNameCheck(r))))return!1}else if(!jt[t]&&!O(ct,ge(r,ot,``))&&!((t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&_e(r,`data:`)===0&&kt[e])&&!(ht&&!O(at,ge(r,ot,``)))&&r)return!1}return!0},_n=j({},[`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[pe(e)]&&O(st,e)},yn=function(e,t,n,r){if(g&&typeof u==`object`&&typeof u.getAttributeType==`function`&&!n)switch(u.getAttributeType(e,t)){case`TrustedHTML`:return S(r);case`TrustedScriptURL`:return ye(r)}return r},bn=function(e,n,r,i){try{r?e.setAttributeNS(r,n,i):e.setAttribute(n,i),un(e)?Z(e):de(t.removed)}catch{Q(n,e)}},xn=function(e){$(I.beforeSanitizeAttributes,e,null);let t=e.attributes;if(!t||un(e))return;let n={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:z,forceKeepAttr:void 0},r=t.length,i=X(e.nodeName);for(;r--;){let a=t[r],o=a.name,s=a.namespaceURI,c=a.value,l=X(o),u=c,d=o===`value`?u:ve(u);if(n.attrName=l,n.attrValue=d,n.keepAttr=!0,n.forceKeepAttr=void 0,$(I.uponSanitizeAttribute,e,n),d=n.attrValue,wt&&(l===`id`||l===`name`)&&_e(d,Tt)!==0&&(Q(o,e),d=Tt+d),U&&O(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,d)){Q(o,e);continue}if(l===`attributename`&&he(d,`href`)){Q(o,e);continue}if(!n.forceKeepAttr){if(!n.keepAttr){Q(o,e);continue}if(!gt&&O(Xe,d)){Q(o,e);continue}if(H&&(d=cn(d)),!gn(i,l,d)){Q(o,e);continue}d=yn(i,l,s,d),d!==u&&bn(e,o,s,d)}}$(I.afterSanitizeAttributes,e,null)},Sn=function(e){let t=null,n=sn(e);for($(I.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if($(I.uponSanitizeShadowNode,t,null),hn(t,e),xn(t),dn(t.content)&&Sn(t.content),(m?m(t):t.nodeType)===P.element){let e=re(t);dn(e)&&(Cn(e),Sn(e))}$(I.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=(m?m(n):n.nodeType)===P.element,i=f(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){let e=h?h(n):null;if(typeof e==`string`&&X(e)===`template`){let e=n.content;dn(e)&&t.push({node:e,shadow:null})}}if(r){let e=re(n);dn(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(Ft=!e,Ft&&(e=`<!-->`),typeof e!=`string`&&!fn(e)&&(e=we(e),typeof e!=`string`))throw k(`dirty is not a string, aborting`);if(!t.isSupported)return e;_t?(R=vt,z=yt):Jt(n),(I.uponSanitizeElement.length>0||I.uponSanitizeAttribute.length>0)&&(R=M(R)),I.uponSanitizeAttribute.length>0&&(z=M(z)),t.removed=[];let c=Dt&&typeof e!=`string`&&fn(e);if(c){an(e);let t=h?h(e):e.nodeName;if(typeof t==`string`){let n=X(t);if(!R[n]||dt[n])throw tn(e),k(`root node is forbidden and cannot be sanitized in-place`)}if(un(e))throw tn(e),k(`root node is clobbered and cannot be sanitized in-place`);try{Cn(e)}catch(t){throw tn(e),t}}else if(fn(e))i=on(`<!---->`),a=i.ownerDocument.importNode(e,!0),a.nodeType===P.element&&a.nodeName===`BODY`||a.nodeName===`HTML`?i=a:i.appendChild(a),Cn(a);else{if(!G&&!H&&!W&&e.indexOf(`<`)===-1)return g&&St?S(e):e;if(i=on(e),!i)return G?null:St?_:``}i&&bt&&Z(i.firstChild);let l=c?e:i,u=sn(l);try{for(;o=u.nextNode();)hn(o,l),xn(o),dn(o.content)&&Sn(o.content)}catch(n){throw c&&(tn(e),le(t.removed,e=>{e.element&&rn(e.element)})),n}if(c)return le(t.removed,e=>{e.element&&rn(e.element)}),H&&ln(e),e;if(G){if(H&&ln(i),xt)for(s=A.call(i.ownerDocument);i.firstChild;)s.appendChild(i.firstChild);else s=i;return(z.shadowroot||z.shadowrootmode)&&(s=Ce.call(r,s,!0)),s}let d=W?i.outerHTML:i.innerHTML;return W&&R[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&O(Ge,i.ownerDocument.doctype.name)&&(d=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
3
- `+d),H&&(d=cn(d)),g&&St?S(d):d},t.setConfig=function(){Jt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),_t=!0,vt=R,yt=z},t.clearConfig=function(){Gt=null,_t=!1,vt=null,yt=null,g=oe,_=``},t.isValidAttribute=function(e,t,n){return Gt||Jt({}),gn(X(e),X(t),n)},t.addHook=function(e,t){typeof t==`function`&&E(I,e)&&C(I[e],t)},t.removeHook=function(e,t){if(E(I,e)){if(t!==void 0){let n=ue(I[e],t);return n===-1?void 0:fe(I[e],n,1)[0]}return de(I[e])}},t.removeHooks=function(e){E(I,e)&&(I[e]=[])},t.removeAllHooks=function(){I=$e()},t}var I=et(),tt=`voiceInputDevice`,nt=new Set([`default`,`communications`]);function L(e){return typeof e==`string`?e.trim():``}function rt(e){let t=L(e),n={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};return t?{...n,deviceId:{exact:t}}:n}function it(e){try{return(e.navigator??globalThis.navigator)?.mediaDevices||null}catch{return null}}async function at(e={}){let t=it(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=L(e.deviceId);!t||nt.has(t)||r.has(t)||(r.add(t),i.push({deviceId:t,label:typeof e.label==`string`?e.label.trim():``}))}return i}function ot(e,t){let n=L(t);return n?(Array.isArray(e)?e:[]).some(e=>e?.deviceId===n):!0}var st=2500,ct=Symbol(`device-enum-timeout`);async function R(e={},t=st){let n=it(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(ct),r)});try{let t=await Promise.race([at(e),a]);return t===ct?{devices:[],timedOut:!0,unsupported:!1}:{devices:t,timedOut:!1,unsupported:!1}}finally{i!==null&&clearTimeout(i)}}var lt=1500;async function z(e={},t=lt){let n=it(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 ut(){try{return globalThis.chrome?.storage?.local||null}catch{return null}}async function B(){let e=ut();if(!e?.get)return``;try{return L((await e.get(tt))?.[tt])}catch{return``}}async function dt(e){let t=L(e),n=ut();if(!n?.set)return t;try{await n.set({[tt]:t})}catch{}return t}function ft(e,t={}){let n=it(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 V(e,t={}){let n=it(t);if(!n||typeof n.getUserMedia!=`function`){let e=Error(`unsupported`);throw e.name=`NotSupportedError`,e}let r=L(e);try{return{stream:await n.getUserMedia({audio:rt(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:rt(``)}),fellBack:!0,deviceId:``,error:t}}}var pt={version:`2.7.9`,tag:`v2.7.9`,commitId:`6e8a04b357298b7d5e685ac8a06e4d8c4fee6f1c`,publishedAt:`2026-11-08T03:20:04.183Z`};export{R as a,ft as c,u as d,te as f,B as i,I as l,ee as m,V as n,dt as o,ne as p,ot as r,z as s,pt as t,d as u};
3
+ `+d),H&&(d=cn(d)),g&&St?S(d):d},t.setConfig=function(){Jt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),_t=!0,vt=R,yt=z},t.clearConfig=function(){Gt=null,_t=!1,vt=null,yt=null,g=oe,_=``},t.isValidAttribute=function(e,t,n){return Gt||Jt({}),gn(X(e),X(t),n)},t.addHook=function(e,t){typeof t==`function`&&E(I,e)&&C(I[e],t)},t.removeHook=function(e,t){if(E(I,e)){if(t!==void 0){let n=ue(I[e],t);return n===-1?void 0:fe(I[e],n,1)[0]}return de(I[e])}},t.removeHooks=function(e){E(I,e)&&(I[e]=[])},t.removeAllHooks=function(){I=$e()},t}var I=et(),tt=`voiceInputDevice`,nt=new Set([`default`,`communications`]);function L(e){return typeof e==`string`?e.trim():``}function rt(e){let t=L(e),n={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};return t?{...n,deviceId:{exact:t}}:n}function it(e){try{return(e.navigator??globalThis.navigator)?.mediaDevices||null}catch{return null}}async function at(e={}){let t=it(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=L(e.deviceId);!t||nt.has(t)||r.has(t)||(r.add(t),i.push({deviceId:t,label:typeof e.label==`string`?e.label.trim():``}))}return i}function ot(e,t){let n=L(t);return n?(Array.isArray(e)?e:[]).some(e=>e?.deviceId===n):!0}var st=2500,ct=Symbol(`device-enum-timeout`);async function R(e={},t=st){let n=it(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(ct),r)});try{let t=await Promise.race([at(e),a]);return t===ct?{devices:[],timedOut:!0,unsupported:!1}:{devices:t,timedOut:!1,unsupported:!1}}finally{i!==null&&clearTimeout(i)}}var lt=1500;async function z(e={},t=lt){let n=it(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 ut(){try{return globalThis.chrome?.storage?.local||null}catch{return null}}async function B(){let e=ut();if(!e?.get)return``;try{return L((await e.get(tt))?.[tt])}catch{return``}}async function dt(e){let t=L(e),n=ut();if(!n?.set)return t;try{await n.set({[tt]:t})}catch{}return t}function ft(e,t={}){let n=it(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 V(e,t={}){let n=it(t);if(!n||typeof n.getUserMedia!=`function`){let e=Error(`unsupported`);throw e.name=`NotSupportedError`,e}let r=L(e);try{return{stream:await n.getUserMedia({audio:rt(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:rt(``)}),fellBack:!0,deviceId:``,error:t}}}var pt={version:`2.8.0`,tag:`v2.8.0`,commitId:`1fd004c3eb406745c3d481ba518f9a22cd85b1be`,publishedAt:`2026-11-08T10:56:04.254Z`};export{R as a,ft as c,u as d,te as f,B as i,I as l,ee as m,V as n,dt as o,ne as p,ot as r,z as s,pt as t,d as u};
@@ -0,0 +1 @@
1
+ import{r as e}from"./chunk-CMxvf4Kt.js";import{a as t,c as n,l as r}from"./i18n-DDhHR2eT.js";import{b as i}from"./model-profiles-9Pkrdr9U.js";import{b as a,jt as o}from"./session-store-BWuBHdD6.js";var s=e({BROWSE_DIRS_CLIENT_TIMEOUT_MS:()=>M,PICK_DIRECTORY_CLIENT_TIMEOUT_MS:()=>j,browseDirs:()=>F,buildAgentHeaders:()=>x,cancelPickDirectory:()=>P,createDir:()=>Z,deleteFs:()=>Y,downloadFile:()=>B,downloadFileStream:()=>G,downloadFileStreamWithProgress:()=>K,downloadFiles:()=>V,downloadFilesStream:()=>q,downloadFilesStreamWithProgress:()=>J,formatFileSize:()=>u,formatTime:()=>d,getAgentConfig:()=>w,getAgentStatusDetail:()=>O,getFileIcon:()=>l,getFileInfo:()=>$,getHomeDir:()=>E,getMimeType:()=>h,getPreviewType:()=>p,getWorkspaceRoot:()=>T,isImageFile:()=>m,listDirectory:()=>L,moveFs:()=>Q,pickDirectory:()=>N,readFileContent:()=>R,removeAllowedPath:()=>A,renameFs:()=>X,resetWorkspaceRoot:()=>D,searchFilesRemote:()=>U,supportsPreview:()=>f,switchWorkspace:()=>k,writeFileContent:()=>z});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=(e.split(`.`).pop()||``).toLowerCase();return new Set(`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.pdf.docx.pptx.xlsx.xls.png.jpg.jpeg.gif.webp.bmp.ico.mp4.webm.ogg.m4v.mov.mp3.wav.m4a.aac.flac.opus`.split(`.`)).has(t)}function p(e){let t=(e.split(`.`).pop()||``).toLowerCase();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 m(e){let t=(e.split(`.`).pop()||``).toLowerCase();return new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`bmp`,`ico`,`svg`]).has(t)}function h(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 g=null,_=null,v=null,y=null;function b(){try{return a?.activeSessionId||null}catch{return null}}function x(e,t=b()){let n={Authorization:`Bearer ${e.token}`};return t&&(n[`X-AIH-Session-Id`]=t),n}function S(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 C(e,t){let n=t&&t.message;S(t)?r.debug(`[WorkspaceManager] ${e} skipped (agent unreachable):`,n):r.warn(`[WorkspaceManager] ${e} failed:`,n)}async function w(){if(y&&y.url&&y.token)return y;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?(y={id:r.id,url:r.url,token:i(r.token)},y):null}catch(e){return r.warn(`[WorkspaceManager] getAgentconfiguration failed:`,e.message),null}}async function T(e){let t=e===void 0?b():e,n=await w(),r=`${t||``}::${n?.id||n?.url||``}`;if(g&&_===r)return g;if(!n)return null;try{let e=await fetch(`${n.url}/api/status/detail`,{headers:x(n,t)});if(e.ok){let t=await e.json();if(t.success&&t.workdir)return g=t.workdir,_=r,g}}catch(e){C(`get workingdirectory`,e)}return null}async function E(){if(v)return v;let e=await w();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 v=e.homeDir,v}}catch(e){C(`get homedir`,e)}return null}function D(){g=null,_=null,v=null,y=null,o()}async function O(e){let t=e===void 0?b():e,n=await w();if(!n)return null;try{let e=await fetch(`${n.url}/api/status/detail`,{headers:x(n,t)});if(e.ok){let t=await e.json();if(t.success)return t}}catch(e){C(`get statusdetailcase`,e)}return null}async function k(e,t={}){let n=t.sessionId===void 0?b():t.sessionId,r={workdir:e,scope:n?`session`:`global`};n&&(r.sessionId=n);let i=await I(`/api/config/workdir`,r,n);return i.success&&D(),i}async function A(e){return I(`/api/config/allowed-paths/remove`,{path:e})}var j=200*1e3,M=8*1e3;async function N(){let e=await w();if(!e)return{success:!1,available:!1,error:n(`workspaceMgr.agentNotPairedDetail`)};let t=new AbortController,r=setTimeout(()=>t.abort(),j);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 P(){return I(`/api/config/pick-directory/cancel`,{})}async function F(e){let t=await w();if(!t)return{success:!1,error:n(`workspaceMgr.agentNotPairedDetail`)};let r=new AbortController,i=setTimeout(()=>r.abort(),M);try{let n=await fetch(`${t.url}/api/fs/browse`,{method:`POST`,headers:{"Content-Type":`application/json`,...x(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 I(e,t={},r=void 0){let i=await w();if(!i)return{success:!1,error:n(`workspaceMgr.agentNotPairedDetail`)};let a=r===void 0?b():r;try{return await(await fetch(`${i.url}${e}`,{method:`POST`,headers:{"Content-Type":`application/json`,...x(i,a)},body:JSON.stringify(t)})).json()}catch(e){return{success:!1,error:n(`workspaceMgr.requestFailed`,{message:e.message})}}}async function L(e){return I(`/api/fs/list`,{path:e||`.`})}async function R(e){return I(`/api/fs/read`,{path:e})}async function z(e,t){return I(`/api/fs/write`,{path:e,content:t})}async function B(e){return I(`/api/fs/download`,{path:e})}async function V(e){return I(`/api/fs/download-multi`,{paths:e})}function H(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function ee(e){return e?!!(e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)||/^(\\\\|\/\/)[^\\/]+[\\/]/.test(e)):!1}async function U(e,t,n=200){let r=await I(`/api/fs/search_files`,{path:e,pattern:`*${t}*`,recursive:!0,maxResults:n});return r.success?(r.results||[]).map(t=>{let n=H(ee(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 W(e,t){if(!e)return t;let n=e.match(/filename\*=UTF-8''(.+?)(?:;|$)/)||e.match(/filename="(.+?)"/);return n?decodeURIComponent(n[1]):t}async function G(e){let t=await w();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`,...x(t)},body:JSON.stringify({path:e})});return r.ok?{success:!0,blob:await r.blob(),name:W(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 K(e,t,r){let i=await w();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`,...x(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:W(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 q(e){let t=await w();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`,...x(t)},body:JSON.stringify({paths:e})});return r.ok?{success:!0,blob:await r.blob(),name:W(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 J(e,t,r){let i=await w();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`,...x(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:W(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 Y(e){return I(`/api/fs/delete`,{path:e})}async function X(e,t){return I(`/api/fs/rename`,{path:e,newName:t})}async function Z(e){return I(`/api/fs/mkdir`,{path:e})}async function Q(e,t){return I(`/api/fs/move`,{path:e,destDir:t})}async function $(e){return I(`/api/fs/stat`,{path:e})}export{z as A,A as C,f as D,U as E,k as O,R as S,D as T,p as _,G as a,Q as b,J as c,w as d,O as f,h as g,E as h,Z as i,s as k,u as l,$ as m,x as n,K as o,l as p,P as r,q as s,F as t,d as u,T as v,X as w,N as x,L 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.7.9",
5
+ "version": "2.8.0",
6
6
  "description": "__MSG_extDescription__",
7
7
  "permissions": [
8
8
  "activeTab",
package/dist/options.html CHANGED
@@ -5,7 +5,7 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
6
  <title data-i18n="settings.docTitle">AI Helper - 配置</title>
7
7
  <script type="module" crossorigin src="/assets/theme-Cp7RrL45.js"></script>
8
- <script type="module" crossorigin src="/assets/version-CeLsZH0f.js"></script>
8
+ <script type="module" crossorigin src="/assets/version-Bvlnn3Va.js"></script>
9
9
  <script type="module" crossorigin src="/assets/i18n-DDhHR2eT.js"></script>
10
10
  <script type="module" crossorigin src="/assets/model-profiles-9Pkrdr9U.js"></script>
11
11
  <script type="module" crossorigin src="/assets/network-scope-0d6MoKgI.js"></script>
@@ -8,13 +8,13 @@
8
8
  <script type="module" crossorigin src="/assets/chunk-CMxvf4Kt.js"></script>
9
9
  <script type="module" crossorigin src="/assets/i18n-DDhHR2eT.js"></script>
10
10
  <script type="module" crossorigin src="/assets/model-profiles-9Pkrdr9U.js"></script>
11
- <script type="module" crossorigin src="/assets/session-store-XFFEUHgS.js"></script>
12
- <script type="module" crossorigin src="/assets/version-CeLsZH0f.js"></script>
11
+ <script type="module" crossorigin src="/assets/session-store-BWuBHdD6.js"></script>
12
+ <script type="module" crossorigin src="/assets/version-Bvlnn3Va.js"></script>
13
13
  <script type="module" crossorigin src="/assets/voice-shortcut-Dtt3nhkz.js"></script>
14
- <script type="module" crossorigin src="/assets/agent-store-CuK2pMqc.js"></script>
15
- <script type="module" crossorigin src="/assets/utils-qEM6ytxe.js"></script>
16
- <script type="module" crossorigin src="/assets/markdown-render-BIVttniD.js"></script>
17
- <script type="module" crossorigin src="/assets/workspace-manager-C4IYPHx6.js"></script>
14
+ <script type="module" crossorigin src="/assets/agent-store-DDZKtEZX.js"></script>
15
+ <script type="module" crossorigin src="/assets/utils-BMzWhLj7.js"></script>
16
+ <script type="module" crossorigin src="/assets/markdown-render-ljX8y3-8.js"></script>
17
+ <script type="module" crossorigin src="/assets/workspace-manager-DqpRol8n.js"></script>
18
18
  <script type="module" crossorigin src="/assets/side_panel.js"></script>
19
19
  <link rel="stylesheet" crossorigin href="/assets/theme-ChzggwXz.css">
20
20
  <link rel="stylesheet" crossorigin href="/assets/side_panel.css">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-helper-agent",
3
- "version": "2.7.9",
3
+ "version": "2.8.0",
4
4
  "description": "AI Helper Agent - Local file access and system command execution proxy for Chrome extension / AI Helper 代理服务,为 Chrome 扩展提供本地文件读写和系统命令执行",
5
5
  "type": "module",
6
6
  "main": "./src/server.js",
@@ -0,0 +1,321 @@
1
+ // 目录浏览(工作目录选择用):只读、只列目录,不做路径沙箱校验。
2
+ // 与 /api/fs/list 的职责分开:后者面向文件面板(返回文件与 stat),受 workdir / allowedPaths 约束;
3
+ // 而「切换工作目录」必须能浏览沙箱之外的目录,且只需要目录名。
4
+ // 本模块不 spawn 任何子进程,因此不受 Windows 终端类型 / 桌面会话影响。
5
+
6
+ import fs from 'fs';
7
+ import { readdir, stat } from 'fs/promises';
8
+ import os from 'os';
9
+ import path from 'path';
10
+
11
+ export const MAX_BROWSE_ENTRIES = 5000;
12
+ export const BROWSE_TIMEOUT_MS = 5000;
13
+ export const MAX_BROWSE_PATH_LENGTH = 4096;
14
+ // 符号链接解析并发上限:避免大量链接(pnpm 等)逐个串行等待,
15
+ // 同时避免一次性打开过多文件句柄。
16
+ export const LINK_STAT_CONCURRENCY = 16;
17
+ // 根节点(盘符)探测缓存:Windows 每次 existsSync 都可能命中不可达的映射驱动器,
18
+ // 深层导航不需要重复探测,短 TTL 内复用结果。
19
+ export const ROOTS_CACHE_TTL_MS = 10_000;
20
+
21
+ // 机器码 + 本地化 message key + HTTP 状态码;由 server.js 统一转换成响应
22
+ export class BrowseError extends Error {
23
+ constructor(code, messageKey, httpStatus, detail = '') {
24
+ super(detail || code);
25
+ this.name = 'BrowseError';
26
+ this.code = code;
27
+ this.messageKey = messageKey;
28
+ this.httpStatus = httpStatus;
29
+ }
30
+ }
31
+
32
+ function pathApiFor(platform) {
33
+ return platform === 'win32' ? path.win32 : path.posix;
34
+ }
35
+
36
+ function joinFor(platform, base, name) {
37
+ return pathApiFor(platform).join(base, name);
38
+ }
39
+
40
+ function withTimeout(promise, timeoutMs) {
41
+ if (!timeoutMs || timeoutMs <= 0) return promise;
42
+ return new Promise((resolve, reject) => {
43
+ const timer = setTimeout(() => {
44
+ reject(new BrowseError('timeout', 'error.browseTimeout', 504));
45
+ }, timeoutMs);
46
+ promise.then(
47
+ (value) => { clearTimeout(timer); resolve(value); },
48
+ (err) => { clearTimeout(timer); reject(err); }
49
+ );
50
+ });
51
+ }
52
+
53
+ function mapFsError(err) {
54
+ if (err instanceof BrowseError) return err;
55
+ const code = err && err.code;
56
+ if (code === 'ENOENT') return new BrowseError('path_not_found', 'error.dirNotFound', 404);
57
+ if (code === 'ENOTDIR') return new BrowseError('not_a_directory', 'error.pathNotDir', 400);
58
+ if (code === 'EACCES' || code === 'EPERM') return new BrowseError('permission_denied', 'error.browsePermissionDenied', 403);
59
+ if (code === 'ENAMETOOLONG') return new BrowseError('path_too_long', 'error.browsePathTooLong', 400);
60
+ return new BrowseError('browse_failed', 'error.browseFailed', 500, err && err.message ? err.message : '');
61
+ }
62
+
63
+ /**
64
+ * 规范化浏览路径。
65
+ * - 空值返回 null(表示请求根节点集合)
66
+ * - 支持 ~ 前缀展开(仅前缀,不做 shell 展开)
67
+ * - 必须是绝对路径;统一分隔符;去掉根之外的尾部斜杠
68
+ */
69
+ export function normalizeBrowsePath(rawPath, options = {}) {
70
+ const platform = options.platform || process.platform;
71
+ const homeDir = options.homeDir || os.homedir();
72
+ if (rawPath === undefined || rawPath === null) return null;
73
+
74
+ let raw = String(rawPath);
75
+ if (!raw.trim()) return null;
76
+ raw = raw.trim();
77
+ // 用户从资源管理器复制时可能带引号
78
+ if ((raw.startsWith('"') && raw.endsWith('"')) || (raw.startsWith("'") && raw.endsWith("'"))) {
79
+ raw = raw.slice(1, -1).trim();
80
+ }
81
+ if (!raw) return null;
82
+ if (raw.includes('\0')) throw new BrowseError('bad_path', 'error.browseBadPath', 400);
83
+ if (raw.length > MAX_BROWSE_PATH_LENGTH) throw new BrowseError('path_too_long', 'error.browsePathTooLong', 400);
84
+
85
+ if (raw === '~') {
86
+ raw = homeDir;
87
+ } else if (raw.startsWith('~/') || raw.startsWith('~\\')) {
88
+ raw = pathApiFor(platform).join(homeDir, raw.slice(2));
89
+ }
90
+
91
+ const P = pathApiFor(platform);
92
+
93
+ // Windows 下 /c/Users 这类 MSYS 风格路径会被 resolve 成当前盘下的 \Users,属于静默错误,直接拒绝
94
+ if (platform === 'win32' && /^\/[A-Za-z](\/|$)/.test(raw)) {
95
+ throw new BrowseError('bad_path', 'error.browseBadPath', 400);
96
+ }
97
+
98
+ if (!P.isAbsolute(raw)) {
99
+ throw new BrowseError('bad_path', 'error.browseBadPath', 400);
100
+ }
101
+
102
+ let resolved = P.resolve(raw);
103
+ if (resolved.length > MAX_BROWSE_PATH_LENGTH) {
104
+ throw new BrowseError('path_too_long', 'error.browsePathTooLong', 400);
105
+ }
106
+
107
+ const root = P.parse(resolved).root;
108
+ if (resolved !== root) {
109
+ while (resolved.length > root.length && /[\\/]$/.test(resolved)) {
110
+ resolved = resolved.slice(0, -1);
111
+ }
112
+ }
113
+ return resolved;
114
+ }
115
+
116
+ /**
117
+ * 根节点集合:Windows 为可用盘符 + 主目录,POSIX 为 / + 主目录。
118
+ * existsImpl 可注入,便于在非 Windows 环境测试盘符逻辑。
119
+ */
120
+ export function listRoots(options = {}) {
121
+ const platform = options.platform || process.platform;
122
+ const homeDir = options.homeDir || os.homedir();
123
+ const existsImpl = options.existsImpl || fs.existsSync;
124
+ const roots = [];
125
+
126
+ if (platform === 'win32') {
127
+ for (let i = 0; i < 26; i += 1) {
128
+ const letter = String.fromCharCode(65 + i);
129
+ const rootPath = `${letter}:\\`;
130
+ let ok = false;
131
+ try { ok = Boolean(existsImpl(rootPath)); } catch { ok = false; }
132
+ if (ok) roots.push({ name: `${letter}:`, path: rootPath, kind: 'drive' });
133
+ }
134
+ } else {
135
+ roots.push({ name: '/', path: '/', kind: 'root' });
136
+ }
137
+
138
+ if (homeDir && !roots.some((item) => item.path === homeDir)) {
139
+ roots.push({ name: '~', path: homeDir, kind: 'home' });
140
+ }
141
+ return roots;
142
+ }
143
+
144
+ /**
145
+ * 列出单层子目录(不递归)。只返回目录;符号链接解析后必须是目录才返回。
146
+ */
147
+ export async function listChildDirs(absPath, options = {}) {
148
+ const platform = options.platform || process.platform;
149
+ const timeoutMs = options.timeoutMs === undefined ? BROWSE_TIMEOUT_MS : options.timeoutMs;
150
+ const maxEntries = options.maxEntries === undefined ? MAX_BROWSE_ENTRIES : options.maxEntries;
151
+
152
+ let dirents;
153
+ try {
154
+ dirents = await withTimeout(readdir(absPath, { withFileTypes: true }), timeoutMs);
155
+ } catch (err) {
156
+ throw mapFsError(err);
157
+ }
158
+
159
+ const dirs = [];
160
+ const links = [];
161
+ for (const dirent of dirents) {
162
+ const name = dirent.name;
163
+ if (!name) continue;
164
+ if (dirent.isDirectory()) {
165
+ dirs.push({ name, path: joinFor(platform, absPath, name), kind: 'dir', link: false });
166
+ continue;
167
+ }
168
+ if (dirent.isSymbolicLink()) links.push({ name, fullPath: joinFor(platform, absPath, name) });
169
+ }
170
+
171
+ // 链接/目录联接:解析目标后仍必须是目录;断链或无权访问则跳过。
172
+ // 有界并发 + 整层总预算:单个链接超时按「剩余预算」递减,避免大量链接
173
+ // 把单次列目录拖成 N × timeoutMs(前端 8s 已经超时,服务端却还在跑)。
174
+ if (links.length) {
175
+ const deadline = timeoutMs > 0 ? Date.now() + timeoutMs : 0;
176
+ let cursor = 0;
177
+ const worker = async () => {
178
+ for (;;) {
179
+ const index = cursor;
180
+ cursor += 1;
181
+ if (index >= links.length) return;
182
+ const remaining = deadline ? deadline - Date.now() : 0;
183
+ if (deadline && remaining <= 0) return;
184
+ const item = links[index];
185
+ try {
186
+ const target = await withTimeout(stat(item.fullPath), remaining || timeoutMs);
187
+ if (target.isDirectory()) {
188
+ dirs.push({ name: item.name, path: item.fullPath, kind: 'dir', link: true });
189
+ }
190
+ } catch {
191
+ // 断链 / 目标不可读 / 超时:不返回
192
+ }
193
+ }
194
+ };
195
+ const workers = Array.from(
196
+ { length: Math.min(LINK_STAT_CONCURRENCY, links.length) },
197
+ () => worker(),
198
+ );
199
+ await Promise.all(workers);
200
+ }
201
+
202
+ // 名称升序,大小写不敏感;完全相同时按原名兜底,保证稳定
203
+ dirs.sort((a, b) => {
204
+ const byLower = a.name.toLowerCase().localeCompare(b.name.toLowerCase());
205
+ return byLower !== 0 ? byLower : a.name.localeCompare(b.name);
206
+ });
207
+
208
+ const truncated = dirs.length > maxEntries;
209
+ return {
210
+ entries: truncated ? dirs.slice(0, maxEntries) : dirs,
211
+ truncated,
212
+ };
213
+ }
214
+
215
+ export function parentOf(absPath, platform = process.platform) {
216
+ const P = pathApiFor(platform);
217
+ const parent = P.dirname(absPath);
218
+ return parent === absPath ? null : parent;
219
+ }
220
+
221
+ let rootsCache = null; // { key, at, roots }
222
+
223
+ /** 清空根节点缓存(测试用;盘符变化在 TTL 内自动过期) */
224
+ export function resetRootsCache() {
225
+ rootsCache = null;
226
+ }
227
+
228
+ /**
229
+ * 带 TTL 的根节点探测:每次浏览请求都同步探测 Windows 盘符代价很高,
230
+ * 深层导航复用短时间内的结果;显式注入 existsImpl 时不缓存(测试/特殊场景)。
231
+ */
232
+ function cachedRoots(options = {}) {
233
+ const platform = options.platform || process.platform;
234
+ const homeDir = options.homeDir || os.homedir();
235
+ if (options.existsImpl) {
236
+ return listRoots({ platform, homeDir, existsImpl: options.existsImpl });
237
+ }
238
+ const key = `${platform}|${homeDir}`;
239
+ const now = Date.now();
240
+ if (rootsCache && rootsCache.key === key && now - rootsCache.at < ROOTS_CACHE_TTL_MS) {
241
+ return rootsCache.roots;
242
+ }
243
+ const roots = listRoots({ platform, homeDir });
244
+ rootsCache = { key, at: now, roots };
245
+ return roots;
246
+ }
247
+
248
+ /**
249
+ * 组装 /api/fs/browse 的响应体。
250
+ * rawPath 为空时返回根节点集合(entries 为空)。
251
+ */
252
+ export async function buildBrowsePayload(options = {}) {
253
+ const platform = options.platform || process.platform;
254
+ const homeDir = options.homeDir || os.homedir();
255
+ const roots = cachedRoots({ platform, homeDir, existsImpl: options.existsImpl });
256
+
257
+ const rawPath = options.rawPath;
258
+ const normalized = normalizeBrowsePath(rawPath, { platform, homeDir });
259
+ if (!normalized) {
260
+ return {
261
+ success: true,
262
+ path: null,
263
+ parent: null,
264
+ platform,
265
+ entries: [],
266
+ roots,
267
+ truncated: false,
268
+ };
269
+ }
270
+
271
+ const { entries, truncated } = await listChildDirs(normalized, {
272
+ platform,
273
+ timeoutMs: options.timeoutMs,
274
+ maxEntries: options.maxEntries,
275
+ });
276
+
277
+ return {
278
+ success: true,
279
+ path: normalized,
280
+ parent: parentOf(normalized, platform),
281
+ platform,
282
+ entries,
283
+ roots,
284
+ truncated,
285
+ };
286
+ }
287
+
288
+ /**
289
+ * 简单滑动窗口频控:每 key 在 windowMs 内最多 limit 次。
290
+ * 正常点击速率远低于阈值;这里主要用于防止被刷成目录枚举器。
291
+ */
292
+ export function createBrowseRateLimiter(options = {}) {
293
+ const limit = options.limit === undefined ? 30 : options.limit;
294
+ const windowMs = options.windowMs === undefined ? 10000 : options.windowMs;
295
+ const now = options.now || (() => Date.now());
296
+ const buckets = new Map();
297
+
298
+ return {
299
+ consume(key) {
300
+ const bucketKey = String(key || 'anonymous');
301
+ const ts = now();
302
+ const recent = (buckets.get(bucketKey) || []).filter((t) => ts - t < windowMs);
303
+ if (recent.length >= limit) {
304
+ const retryAfterMs = Math.max(0, windowMs - (ts - recent[0]));
305
+ buckets.set(bucketKey, recent);
306
+ return { allowed: false, retryAfterMs };
307
+ }
308
+ recent.push(ts);
309
+ buckets.set(bucketKey, recent);
310
+ if (buckets.size > 10000) {
311
+ for (const [k, list] of buckets) {
312
+ if (!list.length || ts - list[list.length - 1] >= windowMs) buckets.delete(k);
313
+ }
314
+ }
315
+ return { allowed: true, retryAfterMs: 0 };
316
+ },
317
+ reset() {
318
+ buckets.clear();
319
+ },
320
+ };
321
+ }