mouaif 0.3.0 → 0.3.2
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.
- package/README.md +1 -1
- package/bin/mouaif.js +1 -5
- package/frontend/dist/assets/{AgentFilePicker-CcKLJorU.js → AgentFilePicker-ZW6vm5Hy.js} +1 -1
- package/frontend/dist/assets/{CliModal-Hs5phmNZ.js → CliModal-D2cX4W0a.js} +1 -1
- package/frontend/dist/assets/{DictationPage-BI23lp42.js → DictationPage-Dwb6gGNi.js} +1 -1
- package/frontend/dist/assets/{FileEditor-DDl31c6d.js → FileEditor-BqgbeJHy.js} +1 -1
- package/frontend/dist/assets/{GitModal-3EC_gpJ5.js → GitModal-BPaOnX1a.js} +1 -1
- package/frontend/dist/assets/{Inspector-Ba3R1w04.js → Inspector-C88hoEcC.js} +1 -1
- package/frontend/dist/assets/{SettingsAbout-bvZGDEDw.js → SettingsAbout-D5gHujOy.js} +1 -1
- package/frontend/dist/assets/{SettingsActions-Dk6WX9jv.js → SettingsActions-YrcVF8D3.js} +1 -1
- package/frontend/dist/assets/{SettingsAgents-BNV0MgDB.js → SettingsAgents-BVwBxPbO.js} +1 -1
- package/frontend/dist/assets/{SettingsDefaults-DbMmQbzc.js → SettingsDefaults-CMSIeSt8.js} +1 -1
- package/frontend/dist/assets/{SettingsHiddenContent-BZ2sloH1.js → SettingsHiddenContent-XE1HiHzN.js} +1 -1
- package/frontend/dist/assets/{SettingsMcp-DOrfbQd1.js → SettingsMcp-BAK8U0e4.js} +1 -1
- package/frontend/dist/assets/{SettingsMcpEdit-BGMQ2CWC.js → SettingsMcpEdit-j21BWCAH.js} +1 -1
- package/frontend/dist/assets/{SettingsMcpRegistry-BywXee_A.js → SettingsMcpRegistry-DH5YAigF.js} +1 -1
- package/frontend/dist/assets/{SettingsNotifications-B0LEs11a.js → SettingsNotifications-DJt0f8Jn.js} +1 -1
- package/frontend/dist/assets/{SettingsPricing-BAg33iVF.js → SettingsPricing-Csy5MjG-.js} +1 -1
- package/frontend/dist/assets/{SettingsProject-DNrKhCcZ.js → SettingsProject-Cry5UltF.js} +1 -1
- package/frontend/dist/assets/{SettingsProjects-IqkBfDcm.js → SettingsProjects-d3wgiADv.js} +1 -1
- package/frontend/dist/assets/{SettingsPrompts-BgeiASuk.js → SettingsPrompts-B9ECDKEa.js} +1 -1
- package/frontend/dist/assets/{SettingsProviders-k0xJN0IK.js → SettingsProviders-BalA35c9.js} +1 -1
- package/frontend/dist/assets/{SettingsTags-B5kjFdQi.js → SettingsTags-D_1AgCwY.js} +1 -1
- package/frontend/dist/assets/index-BDkCsON6.js +61 -0
- package/frontend/dist/assets/index-FzhcinOk.css +1 -0
- package/frontend/dist/index.html +2 -2
- package/frontend/dist/sw.js +1 -1
- package/package.json +6 -7
- package/src/access-auth.js +1 -86
- package/src/http-server.js +2 -9
- package/src/pty.js +189 -0
- package/src/server-handlers-access.js +1 -101
- package/src/server-handlers-tools.js +25 -36
- package/src/server-shared.js +1 -14
- package/src/statusBar.js +19 -8
- package/frontend/dist/assets/index-BGvI4n0T.js +0 -61
- package/frontend/dist/assets/index-CANPYzQg.css +0 -1
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/FileEditor-BqgbeJHy.js","assets/codemirror-Bp6CUUFk.js","assets/index-Crn1LdzK.css","assets/Inspector-C88hoEcC.js","assets/virtual-list-6H9b4K51.js","assets/index-C1sQFIC-.css","assets/SettingsProject-Cry5UltF.js","assets/AgentFilePicker-ZW6vm5Hy.js","assets/agentNavigation-BiiCpFz5.js","assets/SettingsHiddenContent-XE1HiHzN.js","assets/index-FbCWDPiB.css","assets/SettingsAgents-BVwBxPbO.js","assets/index-Bgg1gnDf.css","assets/SettingsMcp-BAK8U0e4.js","assets/projectQS-D1cSZ7Gr.js","assets/SettingsMcpEdit-j21BWCAH.js","assets/SettingsMcpRegistry-DH5YAigF.js","assets/SettingsTags-D_1AgCwY.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Dr,me,Xs,Qs,Dt,wi,ea,ta,eo,cr,Pn,na,Fo,_o,yo,wr={},Cr=[],mc=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Gn=Array.isArray;function It(e,t){for(var n in t)e[n]=t[n];return e}function qo(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function u(e,t,n){var r,o,i,s={};for(i in t)i=="key"?r=t[i]:i=="ref"?o=t[i]:s[i]=t[i];if(arguments.length>2&&(s.children=arguments.length>3?Dr.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(i in e.defaultProps)s[i]===void 0&&(s[i]=e.defaultProps[i]);return ur(e,s,r,o,null)}function ur(e,t,n,r,o){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++Xs,__i:-1,__u:0};return o==null&&me.vnode!=null&&me.vnode(i),i}function qt(e){return e.children}function wt(e,t){this.props=e,this.context=t}function un(e,t){if(t==null)return e.__?un(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?un(e):null}function gc(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],o=[],i=It({},t);i.__v=t.__v+1,me.vnode&&me.vnode(i),Uo(e.__P,i,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??un(t),!!(32&t.__u),o),i.__v=t.__v,i.__.__k[i.__i]=i,aa(r,i,o),t.__e=t.__=null,i.__e!=n&&ra(i)}}function ra(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),ra(e)}function Ci(e){(!e.__d&&(e.__d=!0)&&Dt.push(e)&&!kr.__r++||wi!=me.debounceRendering)&&((wi=me.debounceRendering)||ea)(kr)}function kr(){try{for(var e,t=1;Dt.length;)Dt.length>t&&Dt.sort(ta),e=Dt.shift(),t=Dt.length,gc(e)}finally{Dt.length=kr.__r=0}}function oa(e,t,n,r,o,i,s,l,c,a,d){var p,f,h,g,v,b,k,_=r&&r.__k||Cr,y=t.length;for(c=_c(n,t,_,c,y),p=0;p<y;p++)(h=n.__k[p])!=null&&(f=h.__i!=-1&&_[h.__i]||wr,h.__i=p,b=Uo(e,h,f,o,i,s,l,c,a,d),g=h.__e,h.ref&&f.ref!=h.ref&&(f.ref&&Vo(f.ref,null,h),d.push(h.ref,h.__c||g,h)),v==null&&g!=null&&(v=g),(k=!!(4&h.__u))||f.__k===h.__k?(c=ia(h,c,e,k),k&&f.__e&&(f.__e=null)):typeof h.type=="function"&&b!==void 0?c=b:g&&(c=g.nextSibling),h.__u&=-7);return n.__e=v,c}function _c(e,t,n,r,o){var i,s,l,c,a,d=n.length,p=d,f=0;for(e.__k=new Array(o),i=0;i<o;i++)(s=t[i])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[i]=ur(null,s,null,null,null):Gn(s)?s=e.__k[i]=ur(qt,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[i]=ur(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[i]=s,c=i+f,s.__=e,s.__b=e.__b+1,l=null,(a=s.__i=yc(s,n,c,p))!=-1&&(p--,(l=n[a])&&(l.__u|=2)),l==null||l.__v==null?(a==-1&&(o>d?f--:o<d&&f++),typeof s.type!="function"&&(s.__u|=4)):a!=c&&(a==c-1?f--:a==c+1?f++:(a>c?f--:f++,s.__u|=4))):e.__k[i]=null;if(p)for(i=0;i<d;i++)(l=n[i])!=null&&!(2&l.__u)&&(l.__e==r&&(r=un(l)),ca(l,l));return r}function ia(e,t,n,r){var o,i;if(typeof e.type=="function"){for(o=e.__k,i=0;o&&i<o.length;i++)o[i]&&(o[i].__=e,t=ia(o[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=un(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function Sr(e,t){return t=t||[],e==null||typeof e=="boolean"||(Gn(e)?e.some(function(n){Sr(n,t)}):t.push(e)),t}function yc(e,t,n,r){var o,i,s,l=e.key,c=e.type,a=t[n],d=a!=null&&(2&a.__u)==0;if(a===null&&l==null||d&&l==a.key&&c==a.type)return n;if(r>(d?1:0)){for(o=n-1,i=n+1;o>=0||i<t.length;)if((a=t[s=o>=0?o--:i++])!=null&&!(2&a.__u)&&l==a.key&&c==a.type)return s}return-1}function ki(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||mc.test(t)?n:n+"px"}function tr(e,t,n,r,o){var i,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||ki(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||ki(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(na,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r?n[Pn]=r[Pn]:(n[Pn]=Fo,e.addEventListener(t,i?yo:_o,i)):e.removeEventListener(t,i?yo:_o,i);else{if(o=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Si(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[cr]==null)t[cr]=Fo++;else if(t[cr]<n[Pn])return;return n(me.event?me.event(t):t)}}}function Uo(e,t,n,r,o,i,s,l,c,a){var d,p,f,h,g,v,b,k,_,y,w,N,O,P,Y,re,z=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(c=!!(32&n.__u),i=[l=t.__e=n.__e]),(d=me.__b)&&d(t);e:if(typeof z=="function"){p=s.length;try{if(_=t.props,y=z.prototype&&z.prototype.render,w=(d=z.contextType)&&r[d.__c],N=d?w?w.props.value:d.__:r,n.__c?k=(f=t.__c=n.__c).__=f.__E:(y?t.__c=f=new z(_,N):(t.__c=f=new wt(_,N),f.constructor=z,f.render=bc),w&&w.sub(f),f.state||(f.state={}),f.__n=r,h=f.__d=!0,f.__h=[],f._sb=[]),y&&f.__s==null&&(f.__s=f.state),y&&z.getDerivedStateFromProps!=null&&(f.__s==f.state&&(f.__s=It({},f.__s)),It(f.__s,z.getDerivedStateFromProps(_,f.__s))),g=f.props,v=f.state,f.__v=t,h)y&&z.getDerivedStateFromProps==null&&f.componentWillMount!=null&&f.componentWillMount(),y&&f.componentDidMount!=null&&f.__h.push(f.componentDidMount);else{if(y&&z.getDerivedStateFromProps==null&&_!==g&&f.componentWillReceiveProps!=null&&f.componentWillReceiveProps(_,N),t.__v==n.__v||!f.__e&&f.shouldComponentUpdate!=null&&f.shouldComponentUpdate(_,f.__s,N)===!1){t.__v!=n.__v&&(f.props=_,f.state=f.__s,f.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(I){I&&(I.__=t)}),Cr.push.apply(f.__h,f._sb),f._sb=[],f.__h.length&&s.push(f);break e}f.componentWillUpdate!=null&&f.componentWillUpdate(_,f.__s,N),y&&f.componentDidUpdate!=null&&f.__h.push(function(){f.componentDidUpdate(g,v,b)})}if(f.context=N,f.props=_,f.__P=e,f.__e=!1,O=me.__r,P=0,y)f.state=f.__s,f.__d=!1,O&&O(t),d=f.render(f.props,f.state,f.context),Cr.push.apply(f.__h,f._sb),f._sb=[];else do f.__d=!1,O&&O(t),d=f.render(f.props,f.state,f.context),f.state=f.__s;while(f.__d&&++P<25);f.state=f.__s,f.getChildContext!=null&&(r=It(It({},r),f.getChildContext())),y&&!h&&f.getSnapshotBeforeUpdate!=null&&(b=f.getSnapshotBeforeUpdate(g,v)),Y=d!=null&&d.type===qt&&d.key==null?la(d.props.children):d,l=oa(e,Gn(Y)?Y:[Y],t,n,r,o,i,s,l,c,a),f.base=t.__e,t.__u&=-161,f.__h.length&&s.push(f),k&&(f.__E=f.__=null)}catch(I){if(s.length=p,t.__v=null,c||i!=null){if(I.then){for(t.__u|=c?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;i!=null&&(i[i.indexOf(l)]=null),t.__e=l}else if(i!=null)for(re=i.length;re--;)qo(i[re])}else t.__e=n.__e;t.__k==null&&(t.__k=n.__k||[]),I.then||sa(t),me.__e(I,t,n)}}else i==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):l=t.__e=vc(n.__e,t,n,r,o,i,s,c,a);return(d=me.diffed)&&d(t),128&t.__u?void 0:l}function sa(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(sa))}function aa(e,t,n){for(var r=0;r<n.length;r++)Vo(n[r],n[++r],n[++r]);me.__c&&me.__c(t,e),e.some(function(o){try{e=o.__h,o.__h=[],e.some(function(i){i.call(o)})}catch(i){me.__e(i,o.__v)}})}function la(e){return typeof e!="object"||e==null||e.__b>0?e:Gn(e)?e.map(la):e.constructor!==void 0?null:It({},e)}function vc(e,t,n,r,o,i,s,l,c){var a,d,p,f,h,g,v,b=n.props||wr,k=t.props,_=t.type;if(_=="svg"?o="http://www.w3.org/2000/svg":_=="math"?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),i!=null){for(a=0;a<i.length;a++)if((h=i[a])&&"setAttribute"in h==!!_&&(_?h.localName==_:h.nodeType==3)){e=h,i[a]=null;break}}if(e==null){if(_==null)return document.createTextNode(k);e=document.createElementNS(o,_,k.is&&k),l&&(me.__m&&me.__m(t,i),l=!1),i=null}if(_==null)b===k||l&&e.data==k||(e.data=k);else{if(i=_=="textarea"&&k.defaultValue!=null?null:i&&Dr.call(e.childNodes),!l&&i!=null)for(b={},a=0;a<e.attributes.length;a++)b[(h=e.attributes[a]).name]=h.value;for(a in b)h=b[a],a=="dangerouslySetInnerHTML"?p=h:a=="children"||a in k||a=="value"&&"defaultValue"in k||a=="checked"&&"defaultChecked"in k||tr(e,a,null,h,o);for(a in k)h=k[a],a=="children"?f=h:a=="dangerouslySetInnerHTML"?d=h:a=="value"?g=h:a=="checked"?v=h:l&&typeof h!="function"||b[a]===h||tr(e,a,h,b[a],o);if(d)l||p&&(d.__html==p.__html||d.__html==e.innerHTML)||(e.innerHTML=d.__html),t.__k=[];else if(p&&(e.innerHTML=""),oa(t.type=="template"?e.content:e,Gn(f)?f:[f],t,n,r,_=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,s,i?i[0]:n.__k&&un(n,0),l,c),i!=null)for(a=i.length;a--;)qo(i[a]);l&&_!="textarea"||(a="value",_=="progress"&&g==null?e.removeAttribute("value"):g!=null&&(g!==e[a]||_=="progress"&&!g||_=="option"&&g!=b[a])&&tr(e,a,g,b[a],o),a="checked",v!=null&&v!=e[a]&&tr(e,a,v,b[a],o))}return e}function Vo(e,t,n){try{if(typeof e=="function"){var r=typeof e.__u=="function";r&&e.__u(),r&&t==null||(e.__u=e(t))}else e.current=t}catch(o){me.__e(o,n)}}function ca(e,t,n){var r,o;if(me.unmount&&me.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||Vo(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(i){me.__e(i,t)}r.base=r.__P=r.__n=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&ca(r[o],t,n||typeof e.type!="function");n||qo(e.__e),e.__c=e.__=e.__e=void 0}function bc(e,t,n){return this.constructor(e,n)}function qn(e,t,n){var r,o,i,s;t==document&&(t=document.documentElement),me.__&&me.__(e,t),o=(r=!1)?null:t.__k,i=[],s=[],Uo(t,e=t.__k=u(qt,null,[e]),o||wr,wr,t.namespaceURI,o?null:t.firstChild?Dr.call(t.childNodes):null,i,o?o.__e:t.firstChild,r,s),aa(i,e,s),e.props.children=null}Dr=Cr.slice,me={__e:function(e,t,n,r){for(var o,i,s;t=t.__;)if((o=t.__c)&&!o.__)try{if((i=o.constructor)&&i.getDerivedStateFromError!=null&&(o.setState(i.getDerivedStateFromError(e)),s=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(e,r||{}),s=o.__d),s)return o.__E=o}catch(l){e=l}throw e}},Xs=0,Qs=function(e){return e!=null&&e.constructor===void 0},wt.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=It({},this.state),typeof e=="function"&&(e=e(It({},n),this.props)),e&&It(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),Ci(this))},wt.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Ci(this))},wt.prototype.render=qt,Dt=[],ea=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ta=function(e,t){return e.__v.__b-t.__v.__b},kr.__r=0,eo=Math.random().toString(8),cr="__d"+eo,Pn="__a"+eo,na=/(PointerCapture)$|Capture$/i,Fo=0,_o=Si(!1),yo=Si(!0);const wc="modulepreload",Cc=function(e){return"/"+e},Ti={},je=function(t,n,r){let o=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),l=s?.nonce||s?.getAttribute("nonce");o=Promise.allSettled(n.map(c=>{if(c=Cc(c),c in Ti)return;Ti[c]=!0;const a=c.endsWith(".css"),d=a?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${d}`))return;const p=document.createElement("link");if(p.rel=a?"stylesheet":wc,a||(p.as="script"),p.crossOrigin="",p.href=c,l&&p.setAttribute("nonce",l),document.head.appendChild(p),a)return new Promise((f,h)=>{p.addEventListener("load",f),p.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(s){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=s,window.dispatchEvent(l),!l.defaultPrevented)throw s}return o.then(s=>{for(const l of s||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})};var dn,Ve,to,Ai,Un=0,ua=[],ze=me,xi=ze.__b,Ei=ze.__r,Ii=ze.diffed,Pi=ze.__c,Ni=ze.unmount,Ri=ze.__;function Br(e,t){ze.__h&&ze.__h(Ve,e,Un||t),Un=0;var n=Ve.__H||(Ve.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function E(e){return Un=1,kc(da,e)}function kc(e,t,n){var r=Br(dn++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):da(void 0,t),function(l){var c=r.__N?r.__N[0]:r.__[0],a=r.t(c,l);c!==a&&(r.__N=[a,r.__[1]],r.__c.setState({}))}],r.__c=Ve,!Ve.__f)){var o=function(l,c,a){if(!r.__c.__H)return!0;var d=!1,p=r.__c.props!==l;if(r.__c.__H.__.some(function(h){if(h.__N){d=!0;var g=h.__[0];h.__=h.__N,h.__N=void 0,g!==h.__[0]&&(p=!0)}}),i){var f=i.call(this,l,c,a);return d?f||p:f}return!d||p};Ve.__f=!0;var i=Ve.shouldComponentUpdate,s=Ve.componentWillUpdate;Ve.componentWillUpdate=function(l,c,a){if(this.__e){var d=i;i=void 0,o(l,c,a),i=d}s&&s.call(this,l,c,a)},Ve.shouldComponentUpdate=o}return r.__N||r.__}function ue(e,t){var n=Br(dn++,3);!ze.__s&&Ho(n.__H,t)&&(n.__=e,n.u=t,Ve.__H.__h.push(n))}function Li(e,t){var n=Br(dn++,4);!ze.__s&&Ho(n.__H,t)&&(n.__=e,n.u=t,Ve.__h.push(n))}function x(e){return Un=5,_t(function(){return{current:e}},[])}function _t(e,t){var n=Br(dn++,7);return Ho(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function We(e,t){return Un=8,_t(function(){return e},t)}function Sc(){for(var e;e=ua.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(dr),t.__h.some(vo),t.__h=[]}catch(n){t.__h=[],ze.__e(n,e.__v)}}}ze.__b=function(e){Ve=null,xi&&xi(e)},ze.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Ri&&Ri(e,t)},ze.__r=function(e){Ei&&Ei(e),dn=0;var t=(Ve=e.__c).__H;t&&(to===Ve?(t.__h=[],Ve.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(dr),t.__h.some(vo),t.__h=[],dn=0)),to=Ve},ze.diffed=function(e){Ii&&Ii(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(ua.push(t)!==1&&Ai===ze.requestAnimationFrame||((Ai=ze.requestAnimationFrame)||Tc)(Sc)),t.__H.__.some(function(n){n.u&&(n.__H=n.u,n.u=void 0)})),to=Ve=null},ze.__c=function(e,t){t.some(function(n){try{n.__h.some(dr),n.__h=n.__h.filter(function(r){return!r.__||vo(r)})}catch(r){t.some(function(o){o.__h&&(o.__h=[])}),t=[],ze.__e(r,n.__v)}}),Pi&&Pi(e,t)},ze.unmount=function(e){Ni&&Ni(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{dr(r)}catch(o){t=o}}),n.__H=void 0,t&&ze.__e(t,n.__v))};var Mi=typeof requestAnimationFrame=="function";function Tc(e){var t,n=function(){clearTimeout(r),Mi&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Mi&&(t=requestAnimationFrame(n))}function dr(e){var t=Ve,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),Ve=t}function vo(e){var t=Ve;e.__c=e.__(),Ve=t}function Ho(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function da(e,t){return typeof t=="function"?t(e):t}function Ac(e,t){for(var n in t)e[n]=t[n];return e}function Oi(e,t){for(var n in e)if(n!=="__source"&&!(n in t))return!0;for(var r in t)if(r!=="__source"&&e[r]!==t[r])return!0;return!1}function ji(e,t){this.props=e,this.context=t}(ji.prototype=new wt).isPureReactComponent=!0,ji.prototype.shouldComponentUpdate=function(e,t){return Oi(this.props,e)||Oi(this.state,t)};var Di=me.__b;me.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Di&&Di(e)};var xc=me.__e;me.__e=function(e,t,n,r){if(e.then){for(var o,i=t;i=i.__;)if((o=i.__c)&&o.__c)return t.__e==null&&(t.__e=n.__e,t.__k=n.__k||[]),o.__c(e,t)}xc(e,t,n,r)};var Bi=me.unmount;function pa(e,t,n){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),e.__c.__H=null),(e=Ac({},e)).__c!=null&&(e.__c.__P===n&&(e.__c.__P=t),e.__c.__e=!0,e.__c=null),e.__k=e.__k&&e.__k.map(function(r){return pa(r,t,n)})),e}function fa(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return fa(r,t,n)}),e.__c&&e.__c.__P===t&&(e.__e&&n.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=n)),e}function pr(){this.__u=0,this.o=null,this.__b=null}function ha(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function ma(e){var t,n,r,o=null;function i(s){if(t||(t=e()).then(function(l){l&&(o=l.default||l),r=!0},function(l){n=l,r=!0}),n)throw n;if(!r)throw t;return o?u(o,s):null}return i.displayName="Lazy",i.__f=!0,i}function nr(){this.i=null,this.l=null}me.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),Bi&&Bi(e)},(pr.prototype=new wt).__c=function(e,t){var n=t.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var o=ha(r.__v),i=!1,s=function(){i||r.__z||(i=!0,n.__R=null,o?o(c):c())};n.__R=s;var l=n.__P;n.__P=null;var c=function(){if(!--r.__u){if(r.state.__a){var a=r.state.__a;r.__v.__k[0]=fa(a,a.__c.__P,a.__c.__O)}var d;for(r.setState({__a:r.__b=null});d=r.o.pop();)d.__P=l,d.forceUpdate()}};r.__u++||32&t.__u||r.setState({__a:r.__b=r.__v.__k[0]}),e.then(s,s)},pr.prototype.componentWillUnmount=function(){this.o=[]},pr.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=pa(this.__b,n,r.__O=r.__P)}this.__b=null}var o=t.__a&&u(qt,null,e.fallback);return o&&(o.__u&=-33),[u(qt,null,t.__a?null:e.children),o]};var Fi=function(e,t,n){if(++n[1]===n[0]&&e.l.delete(t),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.l.size))for(n=e.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;e.i=n=n[2]}};function Ec(e){return this.getChildContext=function(){return e.context},e.children}function Ic(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){qn(null,t.v),t.v=null,t.h=null},t.h&&t.h!==n&&t.componentWillUnmount(),!t.v){for(var r=t.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;t.h=n,t.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},namespaceURI:n.namespaceURI,insertBefore:function(o,i){this.childNodes.push(o),t.h.insertBefore(o,i)},removeChild:function(o){this.childNodes.splice(this.childNodes.indexOf(o)>>>1,1),t.h.removeChild(o)}}}qn(u(Ec,{context:t.context},e.__v),t.v)}function Pc(e,t){var n=u(Ic,{__v:e,h:t});return n.containerInfo=t,n}(nr.prototype=new wt).__a=function(e){var t=this,n=ha(t.__v),r=t.l.get(e);return r[0]++,function(o){var i=function(){t.props.revealOrder?(r.push(o),Fi(t,e,r)):o()};n?n(i):i()}},nr.prototype.render=function(e){this.i=null,this.l=new Map;var t=Sr(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&t.reverse();for(var n=t.length;n--;)this.l.set(t[n],this.i=[1,0,this.i]);return e.children},nr.prototype.componentDidUpdate=nr.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){Fi(e,n,t)})};var Nc=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Rc=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,Lc=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Mc=/[A-Z0-9]/g,Oc=typeof document<"u",jc=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};wt.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(wt.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var qi=me.event;me.event=function(e){return qi&&(e=qi(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var Dc={configurable:!0,get:function(){return this.class}},Ui=me.vnode;me.vnode=function(e){typeof e.type=="string"&&function(t){var n=t.props,r=t.type,o={},i=r.indexOf("-")==-1;for(var s in n){var l=n[s];if(!(s==="value"&&"defaultValue"in n&&l==null||Oc&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var c=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&l===!0?l="":c==="translate"&&l==="no"?l=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?s="ondblclick":c!=="onchange"||r!=="input"&&r!=="textarea"||jc(n.type)?c==="onfocus"?s="onfocusin":c==="onblur"?s="onfocusout":Lc.test(s)&&(s=c):c=s="oninput":i&&Rc.test(s)?s=s.replace(Mc,"-$&").toLowerCase():l===null&&(l=void 0),c==="oninput"&&o[s=c]&&(s="oninputCapture"),o[s]=l}}r=="select"&&(o.multiple&&Array.isArray(o.value)&&(o.value=Sr(n.children).forEach(function(a){a.props.selected=o.value.indexOf(a.props.value)!=-1})),o.defaultValue!=null&&(o.value=Sr(n.children).forEach(function(a){a.props.selected=o.multiple?o.defaultValue.indexOf(a.props.value)!=-1:o.defaultValue==a.props.value}))),n.class&&!n.className?(o.class=n.class,Object.defineProperty(o,"className",Dc)):n.className&&(o.class=o.className=n.className),t.props=o}(e),e.$$typeof=Nc,Ui&&Ui(e)};var Vi=me.__r;me.__r=function(e){Vi&&Vi(e),e.__c};var Hi=me.diffed;me.diffed=function(e){Hi&&Hi(e);var t=e.props,n=e.__e;n!=null&&e.type==="textarea"&&"value"in t&&t.value!==n.value&&(n.value=t.value==null?"":t.value)};var Bc=Symbol.for("preact-signals");function Wo(){if(Jt>1)Jt--;else{var e,t=!1;for(function(){var o=Ar;for(Ar=void 0;o!==void 0;){var i=o.S;if(i.v===o.v)for(var s=i.t;s!==void 0;s=s.x)s.i===o.i&&(s.i=i.i);o=o.o}}();Rn!==void 0;){var n=Rn;for(Rn=void 0,Tr++;n!==void 0;){var r=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&_a(n))try{n.c()}catch(o){t||(e=o,t=!0)}n=r}}if(Tr=0,Jt--,t)throw e}}var Nn,Le=void 0;function Fr(e){var t=Le,n=Nn;Le=void 0,Nn=void 0;try{return e()}finally{Le=t,Nn=n}}var Rn=void 0,Jt=0,Tr=0,Wi=0,Ar=void 0,xr=0;function ga(e){if(Le!==void 0){var t=e.n;if(t===void 0||t.t!==Le)return t={i:0,S:e,p:Le.s,n:void 0,t:Le,e:void 0,x:void 0,r:t},Le.s!==void 0&&(Le.s.n=t),Le.s=t,e.n=t,32&Le.f&&e.S(t),t;if(t.i===-1)return t.i=0,t.n!==void 0&&(t.n.p=t.p,t.p!==void 0&&(t.p.n=t.n),t.p=Le.s,t.n=void 0,Le.s.n=t,Le.s=t),t}}function Xe(e,t){this.v=e,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=t?.watched,this.Z=t?.unwatched,this.name=t?.name}Xe.prototype.brand=Bc;Xe.prototype.h=function(){return!0};Xe.prototype.S=function(e){var t=this,n=this.t;n!==e&&e.e===void 0&&(e.x=n,this.t=e,n!==void 0?n.e=e:Fr(function(){var r;(r=t.W)==null||r.call(t)}))};Xe.prototype.U=function(e){var t=this;if(this.t!==void 0){var n=e.e,r=e.x;n!==void 0&&(n.x=r,e.e=void 0),r!==void 0&&(r.e=n,e.x=void 0),e===this.t&&(this.t=r,r===void 0&&Fr(function(){var o;(o=t.Z)==null||o.call(t)}))}};Xe.prototype.subscribe=function(e){var t=this;return $o(function(){var n=t.value;Fr(function(){return e(n)})},{name:"sub"})};Xe.prototype.valueOf=function(){return this.value};Xe.prototype.toString=function(){return this.value+""};Xe.prototype.toJSON=function(){return this.value};Xe.prototype.peek=function(){var e=this;return Fr(function(){return e.value})};Object.defineProperty(Xe.prototype,"value",{get:function(){var e=ga(this);return e!==void 0&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(Tr>100)throw new Error("Cycle detected");(function(n){Jt!==0&&Tr===0&&n.l!==Wi&&(n.l=Wi,Ar={S:n,v:n.v,i:n.i,o:Ar})})(this),this.v=e,this.i++,xr++,Jt++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{Wo()}}}});function Tt(e,t){return new Xe(e,t)}function _a(e){for(var t=e.s;t!==void 0;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return!0;return!1}function ya(e){for(var t=e.s;t!==void 0;t=t.n){var n=t.S.n;if(n!==void 0&&(t.r=n),t.S.n=t,t.i=-1,t.n===void 0){e.s=t;break}}}function va(e){for(var t=e.s,n=void 0;t!==void 0;){var r=t.p;t.i===-1?(t.S.U(t),r!==void 0&&(r.n=t.n),t.n!==void 0&&(t.n.p=r)):n=t,t.S.n=t.r,t.r!==void 0&&(t.r=void 0),t=r}e.s=n}function Yt(e,t){Xe.call(this,void 0,t),this.x=e,this.s=void 0,this.g=xr-1,this.f=4}Yt.prototype=new Xe;Yt.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===xr))return!0;if(this.g=xr,this.f|=1,this.i>0&&!_a(this))return this.f&=-2,!0;var e=Le;try{ya(this),Le=this;var t=this.x();(16&this.f||this.v!==t||this.i===0)&&(this.v=t,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return Le=e,va(this),this.f&=-2,!0};Yt.prototype.S=function(e){if(this.t===void 0){this.f|=36;for(var t=this.s;t!==void 0;t=t.n)t.S.S(t)}Xe.prototype.S.call(this,e)};Yt.prototype.U=function(e){if(this.t!==void 0&&(Xe.prototype.U.call(this,e),this.t===void 0)){this.f&=-33;for(var t=this.s;t!==void 0;t=t.n)t.S.U(t)}};Yt.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var e=this.t;e!==void 0;e=e.x)e.t.N()}};Object.defineProperty(Yt.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var e=ga(this);if(this.h(),e!==void 0&&(e.i=this.i),16&this.f)throw this.v;return this.v}});function Fc(e,t){return new Yt(e,t)}function ba(e){var t=e.m;if(e.m=void 0,typeof t=="function"){Jt++;var n=Le;Le=void 0;try{t()}catch(r){throw e.f&=-2,e.f|=8,zo(e),r}finally{Le=n,Wo()}}}function zo(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,ba(e)}function qc(e){if(Le!==this)throw new Error("Out-of-order effect");va(this),Le=e,this.f&=-2,8&this.f&&zo(this),Wo()}function mn(e,t){this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=t?.name,Nn&&Nn.push(this)}mn.prototype.c=function(){var e=this.S();try{if(8&this.f||this.x===void 0)return;var t=this.x();typeof t=="function"&&(this.m=t)}finally{e()}};mn.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,ba(this),ya(this),Jt++;var e=Le;return Le=this,qc.bind(this,e)};mn.prototype.N=function(){2&this.f||(this.f|=2,this.u=Rn,Rn=this)};mn.prototype.d=function(){this.f|=8,1&this.f||zo(this)};mn.prototype.dispose=function(){this.d()};function $o(e,t){var n=new mn(e,t);try{n.c()}catch(o){throw n.d(),o}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var rr;function gn(e,t){me[e]=t.bind(null,me[e]||function(){})}function Er(e){if(rr){var t=rr;rr=void 0,t()}rr=e&&e.S()}function wa(e){var t=this,n=e.data,r=Vc(n);r.value=n;var o=_t(function(){for(var i=t.__v;i=i.__;)if(i.__c){i.__c.__$f|=4;break}return t.__$u.c=function(){var s,l=t.__$u.S(),c=o.value;l(),Qs(c)||((s=t.base)==null?void 0:s.nodeType)!==3?(t.__$f|=1,t.setState({})):t.base.data=c},Fc(function(){var s=r.value.value;return s===0?0:s===!0?"":s||""})},[]);return o.value}wa.displayName="_st";Object.defineProperties(Xe.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:wa},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}});gn("__b",function(e,t){if(typeof t.type=="string"){var n,r=t.props;for(var o in r)if(o!=="children"){var i=r[o];i instanceof Xe&&(n||(t.__np=n={}),n[o]=i,r[o]=i.peek())}}e(t)});gn("__r",function(e,t){e(t),Er();var n,r=t.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=function(o){var i;return $o(function(){i=this}),i.c=function(){r.__$f|=1,r.setState({})},i}())),Er(n)});gn("__e",function(e,t,n,r){Er(),e(t,n,r)});gn("diffed",function(e,t){Er();var n;if(typeof t.type=="string"&&(n=t.__e)){var r=t.__np,o=t.props;if(r){var i=n.U;if(i)for(var s in i){var l=i[s];l!==void 0&&!(s in r)&&(l.d(),i[s]=void 0)}else n.U=i={};for(var c in r){var a=i[c],d=r[c];a===void 0?(a=Uc(n,c,d,o),i[c]=a):a.o(d,o)}}}e(t)});function Uc(e,t,n,r){var o=t in e&&e.ownerSVGElement===void 0,i=Tt(n);return{o:function(s,l){i.value=s,r=l},d:$o(function(){var s=i.value.value;r[t]!==s&&(r[t]=s,o?e[t]=s:s?e.setAttribute(t,s):e.removeAttribute(t))})}}gn("unmount",function(e,t){if(typeof t.type=="string"){var n=t.__e;if(n){var r=n.U;if(r){n.U=void 0;for(var o in r){var i=r[o];i&&i.d()}}}}else{var s=t.__c;if(s){var l=s.__$u;l&&(s.__$u=void 0,l.d())}}e(t)});gn("__h",function(e,t,n,r){(r<3||r===9)&&(t.__$f|=2),e(t,n,r)});wt.prototype.shouldComponentUpdate=function(e,t){if(this.__R)return!0;var n=this.__$u,r=n&&n.s!==void 0;for(var o in t)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){if(!(r||2&this.__$f||4&this.__$f)||1&this.__$f)return!0}else if(!(r||4&this.__$f)||3&this.__$f)return!0;for(var i in e)if(i!=="__source"&&e[i]!==this.props[i])return!0;for(var s in this.props)if(!(s in e))return!0;return!1};function Vc(e){return _t(function(){return Tt(e)},[])}async function H(e,t){const n=await fetch(e,t),r=await n.text();let o;try{o=JSON.parse(r||"{}")}catch{o=r}return{status:n.status,body:o}}let tt=null,zi=0;const Hc=4e3;async function Ca({force:e=!1}={}){const t=Date.now();if(!e&&tt&&t-zi<Hc)return tt;const n=await H("/api/settings");if(n.status!==200)throw new Error("HTTP "+n.status);return tt=n.body||{},zi=t,tt}function Wc(){return tt&&Array.isArray(tt.app&&tt.app.providers)?tt.app.providers:[]}async function Am(e){const t=await H("/api/settings/app",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e||{})});if(t.status!==200)throw new Error("HTTP "+t.status);return tt=Object.assign({},tt,{app:t.body.app||tt&&tt.app||{}}),tt}async function xm(e){const t=await H("/api/settings/app/reset",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({keys:e||[]})});if(t.status!==200)throw new Error("HTTP "+t.status);return tt=Object.assign({},tt,{app:t.body.app||{}}),tt}let or=null,$i=0;const zc=5e3;async function Em({force:e=!1}={}){const t=Date.now();if(!e&&or&&t-$i<zc)return or;const n=await H("/api/auth/accounts");if(n.status!==200)throw new Error("HTTP "+n.status);return or=n.body&&n.body.accounts||{},$i=t,or}async function $c(e,{force:t=!1}={}){const n=await H("/api/ai/models?projectDir="+encodeURIComponent(e));return n.status!==200?{models:[]}:{models:n.body.models||[],projectDir:e}}async function Jc(e,{force:t=!1,purpose:n=""}={}){const r=await H("/api/ai/models/live?provider="+encodeURIComponent(e)+(t?"&_bust=1":"")+(n?"&purpose="+encodeURIComponent(n):""));return r.status!==200?{error:r.body,status:r.status,provider:e}:{models:Array.isArray(r.body&&r.body.models)?r.body.models:[],cached:r.body.cached,provider:e}}const Gc=[{id:"openai-compatible",label:"OpenAI compatible",defaultBaseUrl:"https://api.openai.com/v1",hint:"OpenAI, Together, Groq, LM Studio, Ollama (via /v1), any OpenAI-shaped API."},{id:"anthropic",label:"Anthropic",defaultBaseUrl:"https://api.anthropic.com",hint:"Claude Messages API. Use the OAuth flow below for Claude Pro/Max; otherwise paste an API key.",oauth:!0},{id:"gemini",label:"Google Gemini",defaultBaseUrl:"https://generativelanguage.googleapis.com",hint:"Google AI Studio / Gemini API. API key authentication."},{id:"ollama",label:"Ollama",defaultBaseUrl:"http://127.0.0.1:11434",hint:"Local Ollama server. No API key required."},{id:"openrouter",label:"OpenRouter",defaultBaseUrl:"https://openrouter.ai/api/v1",hint:"OpenRouter: one API key, many models (OpenAI, Anthropic, Google, etc.) via a single OpenAI-shaped endpoint. Paste an API key, or sign in with OpenRouter (PKCE) and the app receives a user-controlled API key.",oauth:!0},{id:"github-copilot",label:"GitHub Copilot",defaultBaseUrl:"https://api.githubcopilot.com",hint:"Requires OAuth. A Copilot subscription on the signed-in account is required to chat.",reserved:!0,oauth:!0},{id:"azure",label:"Azure OpenAI",defaultBaseUrl:"https://<resource>.openai.azure.com/openai/deployments/<deployment>",hint:"Azure OpenAI. Set the resource + deployment in the base URL (or set apiVersion in the project model). API key authentication."},{id:"mistral",label:"Mistral",defaultBaseUrl:"https://api.mistral.ai/v1",hint:"Mistral AI (La Plateforme). API key authentication."},{id:"groq",label:"Groq",defaultBaseUrl:"https://api.groq.com/openai/v1",hint:"Groq — fast inference for open models. API key authentication."},{id:"deepseek",label:"DeepSeek",defaultBaseUrl:"https://api.deepseek.com",hint:"DeepSeek API (OpenAI-compatible). API key authentication."}];function Im(e){return Gc.find(t=>t.id===e)||null}function Pm(e){return e==="openai-compatible"?"openai":e}async function Kc(e){if(!e)return[];const t=await H("/api/settings/models/recent?projectDir="+encodeURIComponent(e));return t.status!==200?[]:Array.isArray(t.body&&t.body.recent)?t.body.recent:[]}async function Zc(e,t,n){!e||!t||!n||await H("/api/settings/models/recent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:e,provider:t,modelId:n})})}async function Nm(e,t){const n=await H("/api/settings/project/storage",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:e,dbBacked:!!t})});if(n.status!==200)throw new Error("HTTP "+n.status);return{dbBacked:!!n.body.dbBacked,project:n.body.project||{},path:n.body.path||null}}async function bo({projectDir:e,chatId:t,url:n,viewport:r,callId:o}){const i={projectDir:e,chatId:t,url:n};r&&(i.viewport=r),o&&(i.callId=o);const s=await H("/api/tools/webpreview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(s.status===409&&s.body&&s.body.code==="EAUTH_REQUIRED"){const l=new Error(s.body.error||"Authorization required");throw l.code="EAUTH_REQUIRED",l.callId=s.body.callId||"",l}if(s.status!==200){const l=new Error(s.body&&s.body.error||"HTTP "+s.status);throw l.code=s.body&&s.body.code||"EHTTP",l}return s.body}function no(e,t,n){!e||!e.current||(e.current.textContent=t||"",n?e.current.dataset.state=n:delete e.current.dataset.state)}function ka(e){let t="message";const n=[];for(const r of e.split(`
|
|
3
|
+
`)){if(!r||r.startsWith(":"))continue;const o=r.indexOf(":");if(o===-1)continue;const i=r.slice(0,o);let s=r.slice(o+1);s.startsWith(" ")&&(s=s.slice(1)),i==="event"?t=s:i==="data"&&n.push(s)}return n.length?{eventName:t,data:n.join(`
|
|
4
|
+
`)}:null}const Sa=Tt(0),qr=Tt({name:"chats"}),rn=Tt({dir:"",name:""});function Yc(e,t){rn.value={dir:e||"",name:""}}const Xc=["projects","settings/projects"];function et(e){const t=e.get("from")||"";return Xc.includes(t)?t:""}function Ta(e){const t=e.indexOf("?");return new URLSearchParams(t>=0?e.slice(t+1):"")}function ir(e){try{return decodeURIComponent(e)}catch{return e}}function nt(e,t){return{match:n=>n===e?{params:new URLSearchParams}:null,build:t}}function pt(e,t){return{match:n=>n===e||n.startsWith(e+"?")?{params:Ta(n)}:null,build:t}}function Ot(e,t){return{match:n=>{if(!n.startsWith(e))return null;const r=n.slice(e.length),o=r.indexOf("?");return{id:o>=0?r.slice(0,o):r,params:Ta(n)}},build:t}}const Aa=[nt("projects",()=>({name:"chats"})),nt("auth",()=>({name:"settings"})),nt("settings/copilot",()=>({name:"settingsProviderEdit",id:"github-copilot"})),Ot("settings/project/agents/",e=>({name:"settingsAgentEdit",id:ir(e.id),projectDir:e.params.get("projectDir")||"",from:et(e.params),chatId:e.params.get("chatId")||"",returnTo:"project",isNew:e.id==="new"&&e.params.get("edit")!=="1"})),nt("settings",()=>({name:"settings"})),nt("settings/access",()=>({name:"settingsAccess"})),nt("inspector",()=>({name:"inspector"})),nt("settings/dictation",()=>({name:"settingsDictation"})),nt("dictation",()=>({name:"settingsDictation"})),nt("settings/projects",()=>({name:"settingsProjects"})),nt("settings/defaults",()=>({name:"settingsDefaults"})),nt("settings/notifications",()=>({name:"settingsNotifications"})),nt("settings/pricing",()=>({name:"settingsPricing"})),nt("settings/about",()=>({name:"settingsAbout"})),nt("settings/providers",()=>({name:"settingsProviders"})),nt("settings/providers/new",()=>({name:"settingsProviderNew"})),Ot("settings/providers/",e=>e.id&&e.id!=="new"?{name:"settingsProviderEdit",id:ir(e.id)}:null),pt("settings/project/technical",e=>({name:"settingsProjectTechnical",projectDir:e.params.get("projectDir")||"",chatId:e.params.get("chatId")||"",from:et(e.params)})),pt("settings/project/output",e=>({name:"settingsProjectOutput",projectDir:e.params.get("projectDir")||"",from:et(e.params)})),pt("settings/project/preview",e=>({name:"settingsProjectPreview",projectDir:e.params.get("projectDir")||"",from:et(e.params)})),pt("settings/project/hide",e=>({name:"settingsProjectHide",projectDir:e.params.get("projectDir")||"",from:et(e.params),filePath:e.params.get("file")||""})),pt("settings/project",e=>({name:"settingsProject",projectDir:e.params.get("projectDir")||"",chatId:e.params.get("chatId")||"",from:et(e.params)})),pt("settings/agents",e=>({name:"settingsAgents",projectDir:e.params.get("projectDir")||"",chatId:e.params.get("chatId")||"",from:et(e.params)})),Ot("settings/agents/",e=>({name:"settingsAgentEdit",id:ir(e.id),projectDir:e.params.get("projectDir")||"",from:et(e.params),chatId:e.params.get("chatId")||"",returnTo:e.params.get("returnTo")==="project"?"project":"",isNew:e.id==="new"&&e.params.get("edit")!=="1"})),pt("settings/actions",e=>({name:"settingsActions",projectDir:e.params.get("projectDir")||"",from:et(e.params)})),Ot("settings/actions/",e=>({name:"settingsActionEdit",id:ir(e.id),projectDir:e.params.get("projectDir")||"",from:et(e.params)})),pt("settings/prompts",e=>({name:"settingsPrompts",id:"",projectDir:e.params.get("projectDir")||"",scope:e.params.get("scope")||"",from:et(e.params)})),Ot("settings/prompts/",e=>({name:"settingsPrompts",id:e.id,projectDir:e.params.get("projectDir")||"",scope:e.params.get("scope")||"",from:et(e.params)})),pt("settings/mcp/registry",e=>({name:"settingsMcpRegistry",projectDir:e.params.get("projectDir")||"",from:et(e.params)})),pt("settings/mcp",e=>({name:"settingsMcp",projectDir:e.params.get("projectDir")||"",from:et(e.params)})),pt("settings/mcp/new",e=>({name:"settingsMcpEdit",id:"",projectDir:e.params.get("projectDir")||"",scope:e.params.get("scope")==="app"?"app":e.params.get("scope")==="project"?"project":"",from:et(e.params)})),Ot("settings/mcp/",e=>({name:"settingsMcpEdit",id:e.id,projectDir:e.params.get("projectDir")||"",scope:e.params.get("scope")==="app"?"app":e.params.get("scope")==="project"?"project":"",from:et(e.params)})),pt("settings/tags",e=>({name:"settingsTags",projectId:e.params.get("projectId")||"",projectDir:e.params.get("projectDir")||""})),Ot("chat/",e=>({name:"chat",chatId:e.id,projectDir:e.params.get("projectDir")||""})),Ot("projects/new",e=>({name:"picker",dir:e.params.get("dir")||""}))];function xa(e){const t=String(e??"").replace(/^#\/?/,"");if(!t)return{name:"chats"};for(const n of Aa){const r=n.match(t);if(!r)continue;const o=n.build(r);if(o)return o}return{name:"chats"}}Aa.length;qr.value=xa(window.location.hash);window.addEventListener("hashchange",()=>{qr.value=xa(window.location.hash)});function yt(e){window.location.hash="#/"+e}function Ea(e){return e==="parsed"||e==="installing"||e==="installed"}function Qc(e){const t=e||{};return!(!t.hasController||!t.acceptedUpdate||!t.updateApplied)}const eu={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},Jo=Tt(!1);let Ir=null,wo=null,Ji=!1,Co=!1,fr=null;const Gi=new WeakSet,tu=60*1e3;function nu(){try{return!!eu&&!0}catch{return!1}}function ko(e,t=e.waiting){Ir=e,wo=t,Jo.value=!0}function ro(e,t){if(!t||Gi.has(t))return;Gi.add(t);const n=()=>{t.state==="installed"&&(navigator.serviceWorker.controller?ko(e,t):t.postMessage({type:"SKIP_WAITING"}))};t.addEventListener("statechange",n),n()}function ru(){const e=Ir&&Ir.waiting||wo;if(!(Ji||!e)){if(!Ea(e.state)){wo=null,Jo.value=!1;return}Ji=!0,Co=!0,fr=e,e.postMessage({type:"SKIP_WAITING"})}}function ou(){const e=Qc({hasController:!!navigator.serviceWorker.controller,acceptedUpdate:Co,updateApplied:!!fr&&!Ea(fr.state)});return Co=!1,fr=null,e}function iu(){if(!nu()||typeof navigator>"u"||!("serviceWorker"in navigator))return;(n=>{typeof requestIdleCallback=="function"?requestIdleCallback(n,{timeout:2500}):setTimeout(n,1500)})(()=>{navigator.serviceWorker.register("/sw.js",{scope:"/"}).then(n=>{Ir=n,n.waiting&&n.active&&ko(n),ro(n,n.installing),n.addEventListener("updatefound",()=>{ro(n,n.installing)}),n.update().then(()=>{n.waiting&&n.active&&ko(n),ro(n,n.installing)}).catch(()=>{});const r=()=>n.update().catch(()=>{});document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&r()}),setInterval(()=>{document.visibilityState==="visible"&&r()},tu)}).catch(()=>{})});let t=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{t||ou()&&(t=!0,window.location.reload())})}const hr=Tt(typeof navigator>"u"?!1:!navigator.onLine);let Ki=!1;function Zi(e){try{const t=new URL(e,window.location.href);if(t.origin!==window.location.origin)return!1;const n=t.pathname;return!(n==="/api"||n.startsWith("/api/")||n==="/events"||n.startsWith("/events/")||n==="/data"||n.startsWith("/data/")||n==="/oauth"||n.startsWith("/oauth/")||n==="/favicon.ico")}catch{return!1}}function su(e){try{return typeof e=="string"?e:e&&typeof e.url=="string"?e.url:String(e||"")}catch{return""}}function au(){if(Ki||typeof window>"u")return;Ki=!0;const e=()=>{hr.value=!navigator.onLine};if(window.addEventListener("online",e),window.addEventListener("offline",e),!window.fetch)return;const t=window.fetch.bind(window);window.fetch=async function(r,o){const i=su(r);try{const s=await t(r,o);return Zi(i)&&s&&s.ok&&(hr.value=!1),s}catch(s){throw Zi(i)&&(hr.value=!0),s}}}function lu(){return u("button",{type:"button",class:"pwa-banner__btn tap-target",onClick:()=>{ru()}},"Reload")}function cu(){const e=hr.value,t=Jo.value;return!e&&!t?null:u(qt,null,e?u("div",{class:"pwa-banner pwa-banner--offline",role:"status"},u("span",{class:"pwa-banner__icon","aria-hidden":"true"},u("svg",{viewBox:"0 0 24 24",width:16,height:16},u("path",{d:"M12 18a2 2 0 1 0 0 4 2 2 0 0 0 0-4Zm0-4c1.66 0 3 1.34 3 3h-2a1 1 0 1 1-2 0H9c0-1.66 1.34-3 3-3Zm0-4c2.76 0 5 2.24 5 5h-2a3 3 0 1 0-6 0H7c0-2.76 2.24-5 5-5Zm0-4c4.42 0 8 3.58 8 8h-2a6 6 0 1 0-12 0H4c0-4.42 3.58-8 8-8Z",fill:"currentColor"}))),u("span",{class:"pwa-banner__text"},"You are offline. Showing the last cached view."),u("button",{type:"button",class:"pwa-banner__btn tap-target",onClick:()=>{window.location.reload()}},"Retry")):null,t?u("div",{class:"pwa-banner pwa-banner--update",role:"status"},u("span",{class:"pwa-banner__icon","aria-hidden":"true"},u("svg",{viewBox:"0 0 24 24",width:16,height:16},u("path",{d:"M12 4V1L7 5l5 4V6c3.31 0 6 2.69 6 6 0 .96-.23 1.87-.63 2.68l1.46 1.46A7.95 7.95 0 0 0 20 12c0-4.42-3.58-8-8-8Zm-6.37 5.32A7.95 7.95 0 0 0 4 12c0 4.42 3.58 8 8 8v3l5-4-5-4v3c-3.31 0-6-2.69-6-6 0-.96.23-1.87.63-2.68L5.63 9.32Z",fill:"currentColor"}))),u("span",{class:"pwa-banner__text"},"A new version is ready."),lu()):null)}function uu(){const[e,t]=E("API keys & sign-ins"),[n,r]=E("prompt style"),o=rn.value&&rn.value.dir||"",i=rn.value&&rn.value.name||"",s=o?"?projectDir="+encodeURIComponent(o):"";async function l(){try{const a=await Ca({force:!0}),d=Wc().length;t(d?d===1?"1 connected":d+" connected":"none yet — tap to add"),r(a.app&&a.app.promptSize||"average")}catch{}}ue(()=>{l()},[]);function c(a,d,p={}){const{detail:f=null,sub:h=null}=p;return u("li",null,u("a",{href:"#/"+a,class:"group__row","aria-label":d},u("span",{class:"group__row-label"},d),h&&!f?u("span",{class:"group__row-detail"},h):u("span",{class:"group__row-detail"},f||h||""),u("span",{class:"group__row-chev","aria-hidden":"true"},"›")))}return u("section",{class:"settings-home"},u("div",{class:"group"},u("div",{class:"group__title"},"Providers"),u("ul",{class:"group__list"},c("settings/providers","Providers",{detail:e}),c("settings/projects","Projects",{sub:"registered folders"}))),u("div",{class:"group"},u("div",{class:"group__title"},"App defaults",u("span",{class:"group__title-note"},"Apply to every project")),u("ul",{class:"group__list"},c("settings/defaults","Chat defaults",{detail:n}),c("settings/dictation","Dictation",{sub:"speech-to-text model & transcript"}),c("settings/prompts","Custom prompts",{sub:"app-wide system prompts"}),c("settings/access","Access & passkeys",{sub:"password, WebAuthn & sign out"}),c("settings/notifications","Notifications",{sub:"questions, approvals & completion"}),c("settings/mcp","MCP servers",{sub:"servers; permissions live in project Tools"}),c("settings/about","About & reset",{sub:"storage · danger zone"}))),u("div",{class:"group"},u("div",{class:"group__title"},"This project",u("span",{class:"group__title-note"},i||o||"none selected")),o?u("ul",{class:"group__list"},c("settings/project"+s,"Project settings",{sub:"prompt style, tools, agents"}),c("settings/mcp"+s,"MCP servers",{sub:"app servers + this project's own"}),c("settings/prompts"+s,"Custom prompts",{sub:"system prompts for this project"})):u("p",{class:"hint hint--compact settings-home__empty"},"Open a chat or pick a project first, then this project's settings (prompt style, tools, MCP servers, custom prompts) show up here.")),u("p",{class:"hint hint--compact settings-home__resolution"},"App defaults apply everywhere. A project can change any of them for its own folder."))}function Ln(e){const t=String(e||"").replace(/-/g,"+").replace(/_/g,"/");return Uint8Array.from(atob(t+"=".repeat((4-t.length%4)%4)),r=>r.charCodeAt(0)).buffer}function tn(e){const t=new Uint8Array(e);let n="";for(const r of t)n+=String.fromCharCode(r);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Ia(e){const t=e.response,n={id:e.id,rawId:tn(e.rawId),type:e.type,response:{clientDataJSON:tn(t.clientDataJSON)}};return t.attestationObject&&(n.response.attestationObject=tn(t.attestationObject)),t.authenticatorData&&(n.response.authenticatorData=tn(t.authenticatorData)),t.signature&&(n.response.signature=tn(t.signature)),t.userHandle&&(n.response.userHandle=tn(t.userHandle)),n}function du(e){return{...e,challenge:Ln(e.challenge),user:{...e.user,id:Ln(e.user.id)},excludeCredentials:(e.excludeCredentials||[]).map(t=>({...t,id:Ln(t.id)}))}}function pu(e){return{...e,challenge:Ln(e.challenge),allowCredentials:(e.allowCredentials||[]).map(t=>({...t,id:Ln(t.id)}))}}async function Pa({code:e="",username:t="",name:n="This device"}={}){if(!window.isSecureContext)throw new Error("Passkeys require HTTPS on remote devices (localhost is allowed for local development)");if(!window.PublicKeyCredential||!navigator.credentials)throw new Error("Passkeys are not supported in this browser");const r=await H("/api/access/passkeys/register/options",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,username:t})});if(r.status!==200)throw new Error(r.body.error||"Could not start passkey setup");const o=await navigator.credentials.create({publicKey:du(r.body.publicKey)});if(!o)throw new Error("Passkey setup was cancelled");const i=await H("/api/access/passkeys/register/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({challengeId:r.body.challengeId,credential:Ia(o),name:n})});if(i.status!==200)throw new Error(i.body.error||"Passkey could not be verified");return i.body}async function fu(){if(!window.isSecureContext)throw new Error("Passkeys require HTTPS on remote devices (localhost is allowed for local development)");if(!window.PublicKeyCredential||!navigator.credentials)throw new Error("Passkeys are not supported in this browser");const e=await H("/api/access/passkeys/login/options",{method:"POST"});if(e.status!==200)throw new Error(e.body.error||"Could not start passkey sign-in");const t=await navigator.credentials.get({publicKey:pu(e.body.publicKey)});if(!t)throw new Error("Passkey sign-in was cancelled");const n=await H("/api/access/passkeys/login/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({challengeId:e.body.challengeId,credential:Ia(t)})});if(n.status!==200)throw new Error(n.body.error||"Passkey sign-in failed");return n.body}function So({title:e,sub:t,children:n}){return u("main",{class:"access-auth"},u("section",{class:"access-auth__card"},u("div",{class:"access-auth__logo","aria-hidden":"true"},"m"),u("h1",null,e),u("p",{class:"access-auth__sub"},t),n))}function hu({status:e,onAuthenticated:t,onSetup:n}){const[r,o]=E(e.user||""),[i,s]=E(""),[l,c]=E(""),[a,d]=E(!1);async function p(h){h.preventDefault(),d(!0),c("");const g=await H("/api/access/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r,password:i})});d(!1),g.status===200?t():c(g.body.error||"Sign-in failed")}async function f(){d(!0),c("");try{await fu(),t()}catch(h){c(h.message),d(!1)}}return u(So,{title:"Sign in",sub:"Access your local mouaif server."},u("form",{onSubmit:p,class:"access-auth__form"},u("label",{class:"label",htmlFor:"access-user"},"User"),u("input",{id:"access-user",class:"input",autocomplete:"username",value:r,onInput:h=>o(h.currentTarget.value),required:!0}),u("label",{class:"label",htmlFor:"access-password"},"Password"),u("input",{id:"access-password",class:"input",type:"password",autocomplete:"current-password",value:i,onInput:h=>s(h.currentTarget.value),required:!0}),u("button",{class:"btn btn--primary",type:"submit",disabled:a},a?"Signing in…":"Sign in")),e.passkeyCount>0&&u("button",{class:"btn access-auth__passkey",type:"button",disabled:a,onClick:f},"Use a passkey"),l&&u("p",{class:"status","data-state":"error",role:"alert"},l),u("button",{class:"access-auth__link",type:"button",onClick:n},"Have a setup code?"))}function mu({initialCode:e="",status:t,onAuthenticated:n,onCancel:r}){const[o,i]=E(e),[s,l]=E(t.user||""),[c,a]=E(""),[d,p]=E(""),[f,h]=E(""),[g,v]=E(!1),[b,k]=E(!1),[_,y]=E(!1);ue(()=>{e&&w(e)},[e]);async function w(P=o){y(!0),h("");const Y=await H("/api/access/setup/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:P})});y(!1),v(Y.status===200&&Y.body.valid),Y.status!==200&&h("That setup code is invalid or expired. Generate a new one in the CLI.")}async function N(P){if(P.preventDefault(),c!==d){h("Passwords do not match");return}y(!0),h("");const Y=await H("/api/access/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:o,username:s,password:c})});y(!1),Y.status===200?(k(!0),h("Password saved. Add a passkey now, or continue.")):h(Y.body.error||"Setup failed")}async function O(){y(!0),h("");try{await Pa({username:s,name:"Setup device"}),h("Passkey added."),k(!0)}catch(P){h(P.message)}y(!1)}return!g&&!b?u(So,{title:"Set up access",sub:"Open the CLI link, scan its QR code, or enter the short code."},u("div",{class:"access-auth__form"},u("label",{class:"label",htmlFor:"setup-code"},"Short code"),u("input",{id:"setup-code",class:"input access-auth__code",autocomplete:"one-time-code",inputMode:"text",placeholder:"ABCD-2345",value:o,onInput:P=>i(P.currentTarget.value.toUpperCase()),maxLength:9}),u("button",{class:"btn btn--primary",type:"button",disabled:_||!o,onClick:()=>w()},_?"Checking…":"Continue")),f&&u("p",{class:"status","data-state":"error",role:"alert"},f),t.configured&&u("button",{class:"access-auth__link",type:"button",onClick:r},"Back to sign in")):u(So,{title:b?"Access is ready":"Create your account",sub:b?"Use your password or passkey to sign in.":"This replaces the current access user and signs out other browsers."},!b&&u("form",{onSubmit:N,class:"access-auth__form"},u("label",{class:"label",htmlFor:"setup-user"},"User"),u("input",{id:"setup-user",class:"input",autocomplete:"username",value:s,onInput:P=>l(P.currentTarget.value),required:!0,maxLength:128}),u("label",{class:"label",htmlFor:"setup-password"},"Password"),u("input",{id:"setup-password",class:"input",type:"password",autocomplete:"new-password",value:c,onInput:P=>a(P.currentTarget.value),required:!0,minLength:8}),u("label",{class:"label",htmlFor:"setup-confirm"},"Confirm password"),u("input",{id:"setup-confirm",class:"input",type:"password",autocomplete:"new-password",value:d,onInput:P=>p(P.currentTarget.value),required:!0,minLength:8}),u("button",{class:"btn btn--primary",type:"submit",disabled:_},_?"Saving…":"Save access")),b&&u("div",{class:"access-auth__actions"},u("button",{class:"btn",type:"button",disabled:_,onClick:O},"Add a passkey"),u("button",{class:"btn btn--primary",type:"button",onClick:n},"Open mouaif")),f&&u("p",{class:"status","data-state":f.includes("failed")||f.includes("match")?"error":"success",role:"status"},f))}function gu({children:e}){const[t,n]=E(null),[r,o]=E(window.location.hash.startsWith("#/setup")),s=new URLSearchParams(window.location.hash.split("?")[1]||"").get("code")||"";async function l(){const c=await H("/api/access/status");c.status===200&&n(c.body)}return ue(()=>{l()},[]),t?t.enabled?r||!t.configured?u(mu,{initialCode:s,status:t,onAuthenticated:()=>{window.location.hash="#/projects",l()},onCancel:()=>o(!1)}):t.authenticated?e:u(hu,{status:t,onAuthenticated:l,onSetup:()=>o(!0)}):e:null}function _u(){const[e,t]=E(null),[n,r]=E([]),[o,i]=E(""),[s,l]=E(!1),[c,a]=E(""),[d,p]=E(""),[f,h]=E(""),[g,v]=E("");async function b(){const[N,O]=await Promise.all([H("/api/access/status"),H("/api/access/passkeys")]);t(N.body),r(O.body.passkeys||[])}ue(()=>{b()},[]);async function k(N){if(N.preventDefault(),d!==f){v("New passwords do not match");return}v(""),l(!0);const O=await H("/api/access/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:c,newPassword:d})});l(!1),O.status===200?(a(""),p(""),h(""),v("Password changed. Other devices were signed out and passkeys were removed."),b()):v(O.body.error||"Password could not be changed")}async function _(){l(!0),i("");try{await Pa(),await b(),i("Passkey added.")}catch(N){i(N.message)}l(!1)}async function y(N){l(!0),await H("/api/access/passkeys/"+encodeURIComponent(N),{method:"DELETE"}),await b(),l(!1)}async function w(){await H("/api/access/logout",{method:"POST"}),window.location.hash="#/login",window.location.reload()}return u("section",{class:"view settings-page"},u("header",{class:"view-head"},u("a",{href:"#/settings",class:"view-back","aria-label":"Back"},"‹"),u("h2",{class:"view-title"},"Access & passkeys")),u("div",{class:"settings-section"},u("p",{class:"hint"},e?"Signed in as "+e.user+". Changing the password signs out other devices and removes passkeys.":"Loading…"),u("form",{class:"settings-section__form",onSubmit:k},u("label",{class:"label",htmlFor:"current-password"},"Current password"),u("input",{id:"current-password",class:"input",type:"password",autocomplete:"current-password",value:c,onInput:N=>a(N.currentTarget.value),required:!0}),u("label",{class:"label",htmlFor:"new-password"},"New password"),u("input",{id:"new-password",class:"input",type:"password",autocomplete:"new-password",minLength:8,value:d,onInput:N=>p(N.currentTarget.value),required:!0}),u("label",{class:"label",htmlFor:"confirm-password"},"Confirm new password"),u("input",{id:"confirm-password",class:"input",type:"password",autocomplete:"new-password",minLength:8,value:f,onInput:N=>h(N.currentTarget.value),required:!0}),u("button",{class:"btn btn--primary",type:"submit",disabled:s},s?"Saving…":"Change password")),g&&u("p",{class:"status","data-state":g.includes("do not match")||g.includes("incorrect")?"error":"success",role:"status"},g),u("div",{class:"row row--actions"},u("button",{class:"btn btn--primary",disabled:s,onClick:_},"Add passkey"),u("button",{class:"btn",disabled:s,onClick:w},"Sign out")),u("div",{class:"access-auth__keys"},n.length?n.map(N=>u("div",{class:"access-auth__key",key:N.id},u("div",null,u("strong",null,N.name),u("small",null,"Added "+new Date(N.createdAt).toLocaleDateString())),u("button",{class:"btn btn--danger",disabled:s,onClick:()=>y(N.id)},"Remove"))):u("p",{class:"hint"},"No passkeys yet. Password sign-in remains available.")),o&&u("p",{class:"status",role:"status"},o)))}function yu(){try{if(typeof Intl<"u"&&Intl.DateTimeFormat)return Intl.DateTimeFormat().resolvedOptions().locale||"en-US"}catch{}return"en-US"}function Ht(e){const t=Number(e);if(!isFinite(t)||t<0)return"--";if(t===0)return"$0.00";const n=t<.01||t<1?5:2;return"$"+new Intl.NumberFormat(yu(),{useGrouping:!1,minimumFractionDigits:2,maximumFractionDigits:n}).format(t)}function vu(e){const t=Number(e);return!isFinite(t)||t<0?"--":t===0?"0 tok/s":t>=100?Math.round(t)+" tok/s":t>=10?t.toFixed(1).replace(/\.0$/,"")+" tok/s":t.toFixed(2).replace(/\.?0+$/,"")+" tok/s"}function nn(e){const t=Number(e);return!isFinite(t)||t<0?"--":t<1e3?String(Math.round(t)):t<1e6?(t/1e3).toFixed(t<1e4?1:0)+"K":(t/1e6).toFixed(t<1e7?2:1)+"M"}function bu(){let e=0,t=0,n=0;return{add(r){const o=Date.now();e||(e=o),t=o;const i=typeof r=="string"?r.length:0;i>0&&(n+=i/4)},rate(r){if(!e)return 0;const o=(t||Date.now())-e;return o<=0?0:(typeof r=="number"&&isFinite(r)?r:n)/o*1e3},reset(){e=0,t=0,n=0}}}function Go(e,t,n=!0){ue(()=>{if(!n||!t)return;function r(s){const l=Array.isArray(e)?e:[e],c=s.target;if(!c)return;l.some(d=>{const p=d&&d.current?d.current:d instanceof Element?d:null;return p&&(p===c||p.contains(c))})||t(s)}function o(s){s.key==="Escape"&&t(s)}const i=setTimeout(()=>{document.addEventListener("mousedown",r),document.addEventListener("touchstart",r),document.addEventListener("keydown",o)},0);return()=>{clearTimeout(i),document.removeEventListener("mousedown",r),document.removeEventListener("touchstart",r),document.removeEventListener("keydown",o)}},[e,t,n])}const Rm=[{id:"sparkles",label:"Sparkles"},{id:"code",label:"Code"},{id:"search",label:"Search"},{id:"pencil",label:"Writing"},{id:"bug",label:"Debug"},{id:"book",label:"Research"}],Yi={sparkles:["M12 3c-.35 3.1-1.85 4.6-4.95 4.95 3.1.35 4.6 1.85 4.95 4.95.35-3.1 1.85-4.6 4.95-4.95C13.85 7.6 12.35 6.1 12 3Z","M5.5 14.5c-.2 1.9-1.1 2.8-3 3 1.9.2 2.8 1.1 3 3 .2-1.9 1.1-2.8 3-3-1.9-.2-2.8-1.1-3-3Z","M18.5 12.5c-.2 1.6-.9 2.3-2.5 2.5 1.6.2 2.3.9 2.5 2.5.2-1.6.9-2.3 2.5-2.5-1.6-.2-2.3-.9-2.5-2.5Z"],code:["M8.5 7 4 12l4.5 5","M15.5 7 20 12l-4.5 5","m14 4-4 16"],search:["M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14Z","m16 16 4 4"],pencil:["m4 20 4.2-1 10.9-10.9a2.1 2.1 0 0 0-3-3L5.2 16 4 20Z","m14.8 6.4 2.8 2.8"],bug:["M9.5 10h5A3.5 3.5 0 0 1 18 13.5v2A6 6 0 0 1 6 15.5v-2A3.5 3.5 0 0 1 9.5 10Z","M9.5 10V8a2.5 2.5 0 0 1 5 0v2","M8.5 10c-.8 0-1.6.3-2.2.8L5 12","M15.5 10c.8 0 1.6.3 2.2.8L19 12","M3.5 14h2.6","M17.9 14h2.6","M4.6 18.4l2.5-1.3","M19.4 18.4l-2.5-1.3"],book:["M4 5.5A2.5 2.5 0 0 1 6.5 3H11a2 2 0 0 1 2 2v16a2 2 0 0 0-2-2H6.5A2.5 2.5 0 0 0 4 21.5v-16Z","M20 5.5A2.5 2.5 0 0 0 17.5 3H13v18a2 2 0 0 1 2-2h2.5a2.5 2.5 0 0 1 2.5 2.5v-16Z"]};function Xi({name:e="sparkles",size:t=20,class:n=""}){const r=Yi[e]||Yi.sparkles;return u("svg",{class:n||void 0,viewBox:"0 0 24 24",width:t,height:t,fill:"none",stroke:"currentColor","stroke-width":"1.8","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",focusable:"false"},r.map((o,i)=>u("path",{d:o,key:i})))}const oo=30;function wu(e){const t=e&&(e.lastOpenedAt||e.createdAt);if(!t)return{kind:"created",text:""};const n=new Date(t);if(isNaN(n.getTime()))return{kind:"created",text:""};const r=new Date,o=n.toDateString()===r.toDateString(),i=n.getFullYear()===r.getFullYear();let s;return o?s=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):i?s=n.toLocaleDateString([],{month:"short",day:"numeric"}):s=n.toLocaleDateString([],{year:"numeric",month:"short",day:"numeric"}),{kind:e.lastOpenedAt?"opened":"created",text:s}}function Cu({project:e,onRename:t,onUnregister:n}){const[r,o]=E(!1),i=x(null);return Go(i,()=>o(!1),r),u("div",{ref:i,class:"project-card__menu"},u("button",{class:"project-card__menu-btn",type:"button","aria-haspopup":"true","aria-expanded":String(r),"aria-label":"Project options",onClick:s=>{s.stopPropagation(),o(!r)}},"⋯"),u("div",{class:"project-card__menu-pop",hidden:!r,role:"menu",onClick:s=>s.stopPropagation()},u("button",{type:"button",onClick:()=>{o(!1),yt("settings/project?projectDir="+encodeURIComponent(e.path)+"&from=projects")}},"Settings…"),u("button",{type:"button",onClick:()=>{o(!1),t(e)}},"Rename…"),u("button",{type:"button","data-danger":"1",onClick:()=>{o(!1),n(e)}},"Unregister")))}function ku({project:e}){const[t,n]=E([]),[r,o]=E(0),[i,s]=E(!0),[l,c]=E(0),[a,d]=E(!1),[p,f]=E(!1),[h,g]=E([]);ue(()=>{let _=!1;async function y(){s(!0);try{const[w,N]=await Promise.all([H("/api/chats?projectDir="+encodeURIComponent(e.path)+"&offset=0&limit="+oo),H("/api/prompts?projectDir="+encodeURIComponent(e.path)).catch(()=>({status:0,body:{}}))]);if(_)return;if(g(N.status===200?N.body.prompts||[]:[]),w.status===200){const O=w.body.chats||[];n(O),o(w.body.total||O.length),c(O.length)}else n([]),o(0)}catch{_||(n([]),o(0))}_||s(!1)}return y(),()=>{_=!0}},[e.path]);async function v(){if(!(a||i||l>=r)){d(!0);try{const _=await H("/api/chats?projectDir="+encodeURIComponent(e.path)+"&offset="+l+"&limit="+oo);if(_.status===200){const y=_.body.chats||[];n(w=>[...w,...y]),o(_.body.total||r||l+y.length),c(w=>w+y.length)}}catch{}d(!1)}}async function b(_=null){f(!0);try{const y={projectDir:e.path};_&&(y.promptId=_);const w=await H("/api/chats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(w.status!==201){alert("create chat failed: HTTP "+w.status),f(!1);return}const N=w.body&&w.body.chat;if(N&&N.id)yt("chat/"+encodeURIComponent(N.id)+"?projectDir="+encodeURIComponent(e.path));else{const O=await H("/api/chats?projectDir="+encodeURIComponent(e.path)+"&offset=0&limit="+oo);if(O.status===200){const P=O.body.chats||[];n(P),o(O.body.total||P.length),c(P.length)}f(!1)}}catch{alert("create chat failed: network error"),f(!1)}}async function k(_){if(!confirm('Delete chat "'+(_.title||_.id)+'"?'))return;const y=await H("/api/chats/"+encodeURIComponent(_.id)+"?projectDir="+encodeURIComponent(e.path),{method:"DELETE"});if(y.status!==200){alert("delete failed: HTTP "+y.status);return}n(w=>w.filter(N=>N.id!==_.id)),o(w=>Math.max(0,w-1)),c(w=>Math.max(0,w-1))}return u(qt,null,u("ul",{class:"project-card__chats","aria-label":"Chats in "+(e.name||e.path),onScroll:_=>{const y=_.currentTarget;y.scrollTop+y.clientHeight>=y.scrollHeight-48&&v()}},i?u("li",{class:"project-card__chats-empty"},"loading chats…"):t.length===0?u("li",{class:"project-card__chats-empty"},'No chats yet. Tap "+ New chat" below to start one.'):t.map(_=>{const y=_.totalCost||{total:0,known:!1},w=y.known?Ht(y.total):"--",N=wu(_),O=(N.kind==="created"?"new · ":"")+N.text,P=_.trace?" · trace":"",Y=_.title&&_.title.trim()?_.title:"New chat",re=typeof _.messageCount=="number"?_.messageCount:0,z=typeof _.draftSnippet=="string"?_.draftSnippet:"",I=_.hasDraftImage===!0,D=!_.running&&re===0&&(z.trim().length>0||I),V=D?z.replace(/\s+/g," ").trim().slice(0,120)||"Image draft":"",Z=_.promptId?h.find(oe=>oe.id===_.promptId):null;return u("li",{key:_.id,onClick:()=>yt("chat/"+_.id+"?projectDir="+encodeURIComponent(e.path)),"aria-label":_.running?Y+" (running)":D?V+" (draft)":void 0},Z?u("span",{class:"project-card__chat-prompt",title:Z.title,"aria-label":"Prompt: "+Z.title},u(Xi,{name:Z.icon,size:17})):null,D?u("span",{class:"project-card__chat-title project-card__chat-title--draft"},V):u("span",{class:"project-card__chat-title"},Y),D?u("span",{class:"project-card__chat-draft","aria-hidden":"true"}):_.running?u("span",{class:"project-card__chat-running","aria-hidden":"true"}):null,u("span",{class:"project-card__chat-meta","data-trace":_.trace?"1":void 0,"data-running":_.running?"1":void 0,"data-draft":D?"1":void 0,"data-cost-known":y.known?"1":"0"},w+" · "+O+P),u("button",{class:"project-card__chat-delete",type:"button","aria-label":"Delete chat "+Y,onClick:oe=>{oe.stopPropagation(),k(_)}},"×"))}),a?u("li",{class:"project-card__chats-more"},"Loading more…"):!i&&l<r?u("li",{class:"project-card__chats-more"},"Scroll for more…"):null),u("div",{class:"project-card__new-actions"},u("button",{class:"project-card__new",type:"button",onClick:()=>b(),disabled:p},"+ New chat"),h.filter(_=>_.showOnProjectCard).map(_=>u("button",{class:"project-card__prompt-new",type:"button",key:_.id,onClick:()=>b(_.id),disabled:p,"aria-label":"New chat with "+_.title,title:"New chat with "+_.title},u(Xi,{name:_.icon,size:20})))))}function Na(){const[e,t]=E([]),[n,r]=E("loading…"),[o,i]=E("busy");async function s(){r("loading…"),i("busy");try{const a=await H("/api/projects/registered");if(a.status!==200){r("HTTP "+a.status),i("error");return}const d=a.body.projects||[];t(d),r(d.length+" projects"),i(d.length?"success":null)}catch{r("network error"),i("error")}}ue(()=>{s().catch(a=>{r("load failed"),i("error"),console.warn("loadProjects rejected:",a)})},[Sa.value]);async function l(a){const d=prompt("Rename project",a.name||a.path);if(d==null)return;const p=d.trim();if(!p||p===a.name)return;const f=await H("/api/projects/registered/"+encodeURIComponent(a.id),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:p})});if(f.status!==200){alert("rename failed: HTTP "+f.status);return}s()}async function c(a){if(!confirm('Unregister project "'+(a.name||a.path)+'"? The folder on disk is not touched.'))return;const d=await H("/api/projects/registered/"+encodeURIComponent(a.id),{method:"DELETE"});if(d.status!==200){alert("unregister failed: HTTP "+d.status);return}s()}return u("section",null,u("div",{class:"page-bar"},u("div",{class:"page-bar__title"},"Chats"),u("span",{class:"status page-bar__status","data-state":o||void 0,"aria-live":"polite"},n),u("button",{class:"page-bar__add",type:"button",onClick:()=>yt("projects/new"),"aria-label":"Add project"},"+")),u("ul",{class:"projects__list","aria-label":"Registered projects"},e.length===0&&o!=="busy"?u("li",{class:"projects__empty"},u("span",{class:"projects__empty-icon",dangerouslySetInnerHTML:{__html:'<svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor" aria-hidden="true"><path d="M3 7.5A1.5 1.5 0 0 1 4.5 6h4.379a1.5 1.5 0 0 1 1.06.44L11.88 8.38a.5.5 0 0 0 .354.146H19.5A1.5 1.5 0 0 1 21 10.027v7.473A1.5 1.5 0 0 1 19.5 19h-15A1.5 1.5 0 0 1 3 17.5v-10Z"/></svg>'}}),u("p",{class:"projects__empty-title"},"No projects yet"),u("p",{class:"projects__empty-text"},'Tap "Add project" to register a folder on disk. Each project keeps its own chats, prompt profile, and trace setting.')):e.map(a=>{const d=a.totalCost||{total:0,known:!1},p=d.known?Ht(d.total):"--";return u("li",{key:a.id,class:"project-card"},u("div",{class:"project-card__head"},u("div",{class:"project-card__identity"},u("div",{class:"project-card__name"},a.name||a.path),u("div",{class:"project-card__path"},a.path)),u("span",{class:"project-card__cost"},p),u(Cu,{project:a,onRename:l,onUnregister:c})),u(ku,{project:a}))})))}function Su(e){const[t,n]=E(typeof e.dir=="string"?e.dir:""),[r,o]=E([]),[i,s]=E("loading…"),[l,c]=E(""),[a,d]=E(!1),[p,f]=E(!1);async function h(k){const _=k??t;n(_),s("loading…"),o([]);const y=_?"/api/projects?dir="+encodeURIComponent(_):"/api/projects";let w;try{w=await H(y)}catch{s("network error");return}if(w.status!==200){s(w.body&&w.body.error?w.body.error:"HTTP "+w.status);return}const N=w.body.dir||_;n(N);const O=w.body.entries||[];o(O),s(O.length+" folders")}async function g(k){s("registering…");let _;try{_=await H("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"register",dir:k,dbBacked:p})})}catch{s("network error");return}if(_.status!==200){s(_.body&&_.body.error?_.body.error:"HTTP "+_.status);return}Sa.value++,yt("projects")}async function v(){const k=l.trim();if(!k){s("name is required");return}const _=t;d(!0),s("creating…");let y;try{y=await H("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"create",parent:_,name:k})})}catch{s("network error"),d(!1);return}y.status===201?(c(""),s("created."),d(!1),yt("projects/new?dir="+encodeURIComponent(y.body.path))):(s(y.body&&y.body.error?y.body.error:"HTTP "+y.status),d(!1))}function b(){const k=t;if(!k)return null;const _=k.replace(/[\\/]+$/,""),y=Math.max(_.lastIndexOf("\\"),_.lastIndexOf("/"));return y>0?_.slice(0,y):""}return ue(()=>{h(e.dir||"")},[e.dir]),u("section",null,u("div",{class:"view-head"},u("a",{href:"#/projects",class:"view-back","aria-label":"Back to projects"},"‹"),u("h2",{class:"view-title"},"Pick a folder")),u("p",{class:"picker__path"},t||"user home"),u("div",{class:"page-bar"},u("span",{class:"status page-bar__status","aria-live":"polite"},i),u("button",{class:"btn",type:"button",onClick:()=>{const k=b();k!=null&&yt("projects/new?dir="+encodeURIComponent(k))},"aria-label":"Go to parent folder"},"↑ Up"),u("button",{class:"page-bar__add",type:"button",onClick:()=>g(t),"aria-label":"Select this folder"},"✓")),u("label",{class:"row row--inline picker__db"},u("input",{type:"checkbox",checked:p,onChange:k=>f(!!k.target.checked),"aria-label":"Store settings in app DB"}),u("span",null,"Store settings in app DB — don’t write .mouaif.json")),u("ul",{class:"picker__list","aria-label":"Subfolders"},r.length===0?u("li",{class:"picker__empty"},"no subfolders here"):r.map(k=>u("li",{key:k.name,class:"picker__row",role:"button",tabIndex:0,onClick:()=>yt("projects/new?dir="+encodeURIComponent(k.path)),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),yt("projects/new?dir="+encodeURIComponent(k.path)))}},u("span",{class:"picker__name"},k.name),u("span",{class:"picker__meta"},"›")))),u("details",{class:"picker__create"},u("summary",null,"Create new folder"),u("div",{class:"row"},u("input",{class:"input",id:"newFolderName",type:"text",placeholder:"folder name",value:l,onInput:k=>c(k.target.value)})),u("div",{class:"row row--actions"},u("button",{class:"btn btn--primary",type:"button",onClick:v,disabled:a},"Create"))))}function Ra(e){return"mouaif_models_"+(e||"").replace(/[^a-zA-Z0-9_-]/g,"_")}function Vn(e){try{const t=localStorage.getItem(Ra(e.props.projectDir)+"_pinned");return new Set(t?JSON.parse(t):[])}catch{return new Set}}function Qi(e,t){try{localStorage.setItem(Ra(e.props.projectDir)+"_pinned",JSON.stringify(Array.from(t)))}catch{}}function Bt(e){return Array.isArray(e.recentModels)?e.recentModels:[]}async function La(e){const t=e.props&&e.props.projectDir,n=(e._recentLoadRequest||0)+1;if(e._recentLoadRequest=n,!t)return e.recentModels=[],!0;let r;try{r=await Kc(t)}catch{r=[]}return n!==e._recentLoadRequest||!e.props||e.props.projectDir!==t?!1:(e.recentModels=r,!0)}function Ma(e,t,n){if(!t||!n)return;const r=Array.isArray(e.recentModels)?[...e.recentModels]:[],o=t+"\0"+n,i=r.findIndex(l=>l.provider+"\0"+l.id===o);i>=0&&r.splice(i,1),r.unshift({provider:t,id:n,ts:Date.now()}),r.length>20&&(r.length=20),e.recentModels=r;const s=e.props&&e.props.projectDir;s&&Zc(s,t,n).catch(()=>{})}function Oa(e,t,n){const r=Vn(e),o=t+"\0"+n;return r.has(o)?(r.delete(o),Qi(e,r),!1):(r.add(o),Qi(e,r),!0)}function Ko(e){const t=e.chat;return t&&t.providerId?t.providerId:""}function io(e){const t=new Map;for(const r of e.models||[])!r||!r.id||!r.provider||t.set(r.provider+"\0"+r.id,{id:r.id,provider:r.provider,label:r.label});const n=e.liveByProvider||{};for(const r of Object.keys(n))for(const o of n[r]||[]){if(!o||!o.id)continue;const i=r+"\0"+o.id;t.has(i)||t.set(i,{id:o.id,provider:r,label:o.label})}return Array.from(t.values())}async function ja(e,t,n=!1){const r=await Jc(e,{force:n});if(r&&r.error)return{provider:e,ok:!1,body:r.error,status:r.status||0};const o=Array.isArray(r&&r.models)?r.models:[];return t.liveByProvider=Object.assign({},t.liveByProvider,{[e]:o}),{provider:e,ok:!0,count:o.length,cached:!!(r&&r.cached)}}async function Tu(e,t){const n=Ko(e);if(!n)return;(await ja(n,e)).ok&&typeof e._onLiveModels=="function"&&e._onLiveModels(n)}async function es(e,t){const n=e.providers.map(a=>a&&a.id).filter(Boolean);if(!n.length)return{error:"Add a provider in Settings → Providers."};const r=await Promise.all(n.map(a=>ja(a,e,!0).catch(d=>({provider:a,ok:!1,body:{error:String(d),code:"ELIVE"},status:0}))));let o=0,i=0,s=null,l="";for(const a of r)a.ok?o+=a.count:i++;const c=Ko(e);if(s=r.find(a=>a.provider===c),s&&!s.ok){const a=s.body&&s.body.code,d=s.body&&s.body.error;let p;a==="ENO_APIKEY"?p="add API key in Settings → Providers":a==="EUNREACHABLE"?p=s.provider==="ollama"?"ollama not running on "+(window.__mouaif_ollama_url||"127.0.0.1:11434"):s.provider+" unreachable":a==="EABORTED"?p="timeout — "+s.provider+" did not respond in 8s":a==="EUPSTREAM"?p=s.provider+" returned "+(s.status||"?"):a==="ENO_LIST"?p=s.provider+" has no model list endpoint":p="model list failed ("+(s.status||"?")+")",l=p+(d&&d!==p?" — "+d:"")}else i&&(l=i+" provider model list(s) could not be refreshed. Try again.");return typeof e._onLiveModels=="function"&&e._onLiveModels("all"),{count:o,error:l}}function sn(e){return String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}const Au=new Set(["http","https","mailto","ftp","ftps"]);function ts(e){const t=String(e??"").replace(/[\u0000-\u0020\u007F]+/g,"");if(!t)return!1;const n=t.indexOf(":");if(n===-1)return!0;const r=t.slice(0,n);return r.includes("&")?!1:/[/?#]/.test(r)?!0:/^[a-z][a-z0-9+.-]*$/i.test(r)&&Au.has(r.toLowerCase())}function xu(e){const t=/(^|[\s([{>])(https?:\/\/[^\s<]+[^\s<.,:;!?)}\]'"\]>]|[a-z0-9.+-]+@[a-z0-9.-]+\.[a-z]{2,}|www\.[a-z0-9.-]+[^\s<.,:;!?)}\]'"\]>]+)/gi;return e.replace(t,(n,r,o)=>{if(/^[a-z0-9.+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i.test(o))return r+'<a href="mailto:'+o+'">'+o+"</a>";const i=o.match(/^www\./i)?"http://"+o:o;return/^https?:\/\/[^/]*\/#\//i.test(i)||/["{}[\]\\]/.test(i)||/\+\S*\+/.test(i)?n:r+'<a href="'+sn(i)+'" target="_blank" rel="noopener noreferrer">'+o+"</a>"})}function Et(e){let t=String(e);const n=[];t=t.replace(/\\([\\`*_~\[\]()#+\-.!|{}<>"])/g,(o,i)=>(n.push(i),""+(n.length-1)+""));const r=[];return t=t.replace(/`([^`]+)`/g,(o,i)=>(r.push("<code>"+sn(i)+"</code>"),""+(r.length-1)+"")),t=sn(t),t=t.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,(o,i,s)=>/^(https?:\/\/[^/]*)?\/#\//i.test(s.trim())||!ts(s)?i:'<img src="'+s+'" alt="'+i+'" loading="lazy" />'),t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(o,i,s)=>/^(https?:\/\/[^/]*)?\/#\//i.test(s.trim())||!ts(s)?i:'<a href="'+s+'" target="_blank" rel="noopener noreferrer">'+i+"</a>"),t=xu(t),t=t.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),t=t.replace(/__([^_]+)__/g,"<strong>$1</strong>"),t=t.replace(/\*([^*]+)\*/g,"<em>$1</em>"),t=t.replace(/_([^_]+)_/g,"<em>$1</em>"),t=t.replace(/~~([^~]+)~~/g,"<del>$1</del>"),t=t.replace(/\uE001(\d+)\uE001/g,(o,i)=>r[Number(i)]||o),t=t.replace(/<a\s+href="([^"]*)"[^>]*>([^<]+)<\/a>/gi,(o,i,s)=>/\+[^=]*\+/.test(i)&&/^https?:\/\//i.test(i)?s:o),t=t.replace(/\uE002(\d+)\uE002/g,(o,i)=>{const s=n[Number(i)];return s===void 0?o:sn(s)}),t}function so(e){return e.map(t=>Et(t)).join("<br>")}function Eu(e){if(e.length<2||!/^\|?[\s:]*-{3,}[\s:]*(\|[\s:]*-{3,}[\s:]*)*\|?$/.test(e[1].replace(/\s+/g,"")))return null;e[0].split("|").filter(s=>s.trim()!=="");const n=s=>{const l=s.split("|"),c=/^\s*\|/.test(s)?1:0,a=/\|\s*$/.test(s)?l.length-1:l.length;return l.slice(c,a).map(d=>d.trim())},r=n(e[0]),o=n(e[1]).map(s=>(s=s.replace(/\s+/g,""),/^:-+$/.test(s)?' style="text-align:left"':/^-+:$/.test(s)?' style="text-align:right"':/^:-+:$/.test(s)?' style="text-align:center"':""));let i="<table><thead><tr>";for(let s=0;s<r.length;s++)i+="<th"+(o[s]||"")+">"+Et(r[s])+"</th>";i+="</tr></thead><tbody>";for(let s=2;s<e.length;s++){const l=n(e[s]);if(l.length!==0){i+="<tr>";for(let c=0;c<Math.max(l.length,r.length);c++)i+="<td"+(o[c]&&c<o.length?o[c]:"")+">"+Et(l[c]||"")+"</td>";i+="</tr>"}}return i+="</tbody></table>",i}function ns(e){if(!e)return"";const t=[];let n=String(e);const r=/^(```|~~~)([^\n]*)$/m;for(;n.length;){const i=r.exec(n);if(!i)break;const s=i[1],l=i[2].trim().split(/\s+/)[0]||"",c=new RegExp("^"+s+"\\s*$","m"),a=n.slice(0,i.index);a.trim()&&t.push({type:"para",text:a}),n=n.slice(i.index+i[0].length);const d=c.exec(n);if(!d){t.push({type:"para",text:s+i[2]+`
|
|
5
|
+
`+n}),n="";break}const p=n.slice(0,d.index);n=n.slice(d.index+d[0].length),t.push({type:"code",lang:l,content:p})}n.trim()&&t.push({type:"para",text:n});const o=[];for(const i of t){if(i.type==="code"){o.push("<pre><code"+(i.lang?' class="language-'+sn(i.lang)+'"':"")+">"+sn(i.content)+"</code></pre>");continue}const s=i.text.split(/\n\n+/);for(const l of s){const c=l.trim();if(!c)continue;const a=c.split(`
|
|
6
|
+
`);if(a.length===1&&/^ {0,3}([-*_]){3,}\s*$/.test(a[0])){o.push("<hr>");continue}if(/^\s*>/.test(a[0])){const p=a.map(f=>f.replace(/^\s*> ?/,""));o.push("<blockquote>"+so(p)+"</blockquote>");continue}if(a.length>=2){const p=Eu(a);if(p){o.push(p);continue}}if(/^\s*[-*+]\s/.test(a[0])||/^\s*[-*+]\s+\[[ x]\]\s/i.test(a[0])){o.push("<ul>");for(const p of a){const f=p.match(/^\s*[-*+]\s+\[([ x])\]\s+(.*)/i);if(f){const g=f[1].toLowerCase()==="x"?" checked":"";o.push('<li class="task-list-item"><label><input type="checkbox" disabled'+g+"> "+Et(f[2])+"</label></li>");continue}const h=p.match(/^\s*[-*+]\s+(.*)/);h?o.push("<li>"+Et(h[1])+"</li>"):o[o.length-1].startsWith("<li")&&(o[o.length-1]=o[o.length-1].replace(/<\/li>$/,"<br>"+Et(p)+"</li>"))}o.push("</ul>");continue}if(/^\s*\d+\.\s/.test(a[0])){o.push("<ol>");for(const p of a){const f=p.match(/^\s*\d+\.\s+(.*)/);f?o.push("<li>"+Et(f[1])+"</li>"):o[o.length-1].startsWith("<li")&&(o[o.length-1]=o[o.length-1].replace(/<\/li>$/,"<br>"+Et(p)+"</li>"))}o.push("</ol>");continue}const d=a[0].match(/^(#{1,6})\s+(.*)/);if(d){const p=d[1].length,f=a.slice(0,1).map(g=>g.replace(/^#+\s*/,"")).join(" "),h=a.slice(1).join(`
|
|
7
|
+
`);o.push("<h"+p+">"+Et(f)+"</h"+p+">"),h.trim()&&o.push("<p>"+so(h.trim().split(`
|
|
8
|
+
`))+"</p>");continue}o.push("<p>"+so(a)+"</p>")}}return o.join(`
|
|
9
|
+
`)}function Iu(e){return e?e.scrollHeight-e.scrollTop-e.clientHeight<48:!0}function Pu(e){e.transcript.current&&(e.pinnedToBottom.current=!0,e.pendingCount.current=0,Gt(e),Ur(e))}const $t=new WeakMap,Pr=new WeakMap;function Nu(e,t){const n=Pr.get(e.transcript);return Pr.delete(e.transcript),n!=null&&Math.abs(n-t)<1}function Da(e){Pr.delete(e.transcript);const t=$t.get(e.transcript);t&&(cancelAnimationFrame(t.frame),$t.delete(e.transcript))}function Ur(e){const t=e.transcript.current;if(!t||!e.pinnedToBottom.current||e._suspendScrollPin||e._insertAnchor)return;const n=$t.get(e.transcript);if(n&&n.el===t){n.stableFrames=0;return}Da(e);const r={el:t,frame:null,stableFrames:0,frames:0};$t.set(e.transcript,r);function o(){if($t.get(e.transcript)!==r)return;if(!e.pinnedToBottom.current||e.transcript.current!==t||e._suspendScrollPin||e._insertAnchor){$t.delete(e.transcript);return}const i=t.scrollHeight,s=t.scrollTop,l=t.clientHeight;if(i-s-l<1)r.stableFrames++;else{r.stableFrames=0;const c=Math.max(0,i-l);Pr.set(e.transcript,c),t.scrollTop=c}if(r.stableFrames>=2||++r.frames>=240){$t.delete(e.transcript);return}r.frame=requestAnimationFrame(o)}r.frame=requestAnimationFrame(o)}function An(e){const t=e&&e.closest&&e.closest(".tool-card__body");t&&(t.scrollTop=t.scrollHeight,requestAnimationFrame(()=>{t.scrollTop=t.scrollHeight}))}function Gt(e){const t=e.jumpBtn.current;if(!t)return;const n=!e.pinnedToBottom.current&&e.pendingCount.current>0;if(t.hidden=!n,n){const r=t.querySelector(".chat-view__jump-count");r&&(r.textContent=e.pendingCount.current>99?"99+":String(e.pendingCount.current))}}function Ye(e,t){e.transcript.current&&(e._suspendScrollPin||(e.pinnedToBottom.current?Ur(e):t&&(e.pendingCount.current+=1,Gt(e))))}const Ba=220;function Ge(e){return String(e||"").replace(/^functions\./,"")}function Fa(e,t,n){return n||Ge(e)!=="ask_user"?!1:!!(t&&typeof t=="object"&&t.cancelled===!0)}function qa(e){const t=String(e||"").match(/^@([^\s:]+)(?::([^\s=]+)=)?\s*([\s\S]*)$/);return t?{toolName:t[1],rest:((t[2]?t[2]+"=":"")+t[3]).trim()}:null}function Ua(e,t){const n=qa(String(e||"").trim());return!n||n.rest||!Array.isArray(t)?null:t.find(r=>r&&r.id&&r.id.toLowerCase()===n.toolName.toLowerCase())||null}function Ru({projectDir:e,chatId:t,callId:n,serverId:r,toolName:o,args:i}){return{projectDir:e,chatId:t,callId:n,serverId:r,toolName:o,args:i||{}}}function Zo(e){const t=String(e||"").trim().match(/^@restart_app(?:\s+([\s\S]*))?$/i);return t?{reason:String(t[1]||"").trim()}:null}function Lu(e){const t=(e||"").trim();if(!t)return null;try{return JSON.parse(t)}catch{}const n=Math.min(t.length,2048),r=s=>s>="a"&&s<="z"||s>="A"&&s<="Z"||s>="0"&&s<="9"||s==="_"||s==="."||s==="-",o={};let i=0;for(;i<n;){for(;i<n&&t[i]===" ";)i++;if(i>=n)break;const s=i;for(;i<n&&r(t[i]);)i++;if(i===s)return null;const l=t.slice(s,i);if(i>=n||t[i]!=="="||(i++,i>=n))return null;let c;if(t[i]==='"'||t[i]==="'"||t[i]==="`"){const a=t[i];i++;const d=i;for(;i<n&&t[i]!==a;)t[i]==="\\"&&i+1<n?i+=2:i++;if(i>=n)return null;c=t.slice(d,i).replace(/\\(.)/g,"$1"),i++}else{const a=i;for(;i<n&&t[i]!==" ";)i++;if(c=t.slice(a,i),!c)return null}o[l]=c}return Object.keys(o).length>0?o:null}function Nr(e){return e==="subagent"||e==="functions.subagent"}function Hn(e,t){if(e==null)return"";if(typeof e=="string")return e;const n=Ge(t);if(n==="shell")return e.cmd||"";if(n==="read_file"){const r=e.startLine!=null||e.endLine!=null?" lines "+(e.startLine||1)+"-"+(e.endLine||"end"):"";return(e.path||e.file||"")+r}if(n==="list_files")return e.pattern||"all text and image files";if(n==="search_files")return[e.path,e.query].filter(Boolean).join(": ");if(n==="write_file"||n==="edit_file")return e.path||e.file||"";if(n==="subagent")return e.task||"";if(n==="ask_user")return e.question||"";if(n==="task")return(e.action||"")+(e.title?": "+e.title:"");if(n==="webpreview")return e.url||"";if(n==="restart_app")return e.reason||"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Mu(e,t){if(e==null)return"";if(typeof e=="string")return e;const n=Ge(t);if(n==="shell")return String(e.cmd||"");if(n==="read_file"){const r=e.startLine!=null||e.endLine!=null?" lines "+(e.startLine||1)+"-"+(e.endLine||"end"):"";return String(e.path||e.file||"")+r}if(n==="list_files")return String(e.pattern||"all text and image files");if(n==="search_files")return[e.path,e.query].filter(Boolean).join(": ");if(n==="write_file"||n==="edit_file")return String(e.path||e.file||"");if(n==="subagent")return String(e.task||"");if(n==="ask_user")return String(e.question||"");if(n==="task")return String(e.action||"")+(e.title?": "+e.title:"");if(n==="webpreview")return String(e.url||"");if(n==="restart_app")return String(e.reason||"");try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Wt(e,t){if(typeof e!="string")return e;const n=e.trim();if(!n)return e;try{const r=JSON.parse(n);return typeof r=="string"?Wt(r,t):r}catch{}return["read_file","list_files","search_files","write_file","edit_file"].includes(t)?_n(e):e}function Va(e){const t=Number(e);return!Number.isFinite(t)||t<0?String(e):t<1024?t+" B":t<1024*1024?Math.round(t/1024)+" KB":Math.round(t/(1024*1024)*10)/10+" MB"}function Ha(e,t){if(!t||t.error)return null;const n=Ge(e);if(n==="shell"){const r=["exit "+(t.exitCode??0)];return t.durationMs!=null&&r.push(t.durationMs+"ms"),r.join(" ")}if(n==="read_file"){if(t.kind==="image"){const r=String(t.mimeType||"image").replace(/^image\//,"").toUpperCase();return t.bytes!=null?r+" · "+Va(t.bytes):r}return t.lines!=null?t.lines+" line"+(t.lines===1?"":"s"):t.chars!=null?t.chars+" chars":t.size!=null&&t.size<1024?t.size+"B":t.size!=null?Math.round(t.size/1024)+"KB":null}if(n==="list_files"){const r=t.entryCount!=null?t.entryCount:Array.isArray(t.entries)?t.entries.length:0,o=t.truncated?" (capped at "+(t.cap!=null?t.cap:r)+")":"";return r+" file"+(r===1?"":"s")+o}if(n==="search_files"){const r=t.matchCount!=null?t.matchCount:Array.isArray(t.matches)?t.matches.length:0,o=t.truncated?" (capped at "+(t.capMatches!=null?t.capMatches:r)+")":"";return r+" match"+(r===1?"":"es")+o}if(n==="edit_file")return t.addedChars!=null?"+"+t.addedChars+" chars":t.bytesWritten!=null?"+"+t.bytesWritten+"B":null;if(n==="write_file")return t.chars!=null?t.chars+" chars":t.bytesWritten!=null?t.bytesWritten+"B":t.size!=null?t.size+"B":null;if(n==="ask_user"){if(t.cancelled)return"dismissed";const r=Array.isArray(t.choice)?t.choice.filter(Boolean):t.choice?[t.choice]:[];return r.length?r.length>1?r.length+" choices":String(r[0]):null}return n==="task"?t.action==="completed"&&t.task?t.task.title+" ✓":t.task&&t.task.status?t.task.status:Array.isArray(t.tasks)?t.tasks.length+" task"+(t.tasks.length===1?"":"s"):null:null}function bt(e){if(e==null)return"";if(typeof e=="string"){const n=e.trim();try{return bt(JSON.parse(n))}catch{return e}}if(e.error)return typeof e.error=="string"?e.error:e.error.message||"error";if(typeof e.output=="string")return e.output;if(typeof e.text=="string")return e.text;if(typeof e.stdout=="string"||typeof e.stderr=="string")return[e.stdout,e.stderr].filter(Boolean).join(`
|
|
10
|
+
`);const t=[];for(const[n,r]of Object.entries(e))r==null||r===""||(typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&t.push(n+": "+r);return t.length?t.join(`
|
|
11
|
+
`):"(no preview)"}function _n(e){const n=(typeof e=="string"?e:"").split(/\n\n/),r=n.shift()||"",i={body:n.join(`
|
|
12
|
+
|
|
13
|
+
`)};for(const s of r.split(`
|
|
14
|
+
`)){let l;(l=s.match(/^# File: (.*)$/))?i.relPath=l[1]:(l=s.match(/^# Lines: (\d+)-(\d+)(?: \/ (\d+))?/))?(i.startLine=Number(l[1]),i.endLine=Number(l[2]),l[3]&&(i.totalLines=Number(l[3]))):(l=s.match(/^# Listing: (.*)$/))?i.pattern=/^<all text/.test(l[1])?"":l[1]:(l=s.match(/^# Kind: image \((.*), (\d+) bytes\)$/))?(i.kind="image",i.mimeType=l[1],i.bytes=Number(l[2])):(l=s.match(/^# Search: (.*)$/))?i.query=l[1]:(l=s.match(/^# Wrote: (.*)$/))?i.relPath=l[1]:(l=s.match(/^# Count: (\d+)(?: \(capped at (\d+)\))?/))?(i.entryCount=Number(l[1]),l[2]!=null&&(i.truncated=!0,i.cap=Number(l[2]))):(l=s.match(/^# Matches: (\d+)(?: \(capped at (\d+) matches \/ (\d+) chars\))?/))?(i.matchCount=Number(l[1]),l[2]!=null&&(i.truncated=!0,i.capMatches=Number(l[2]),i.capBytes=Number(l[3]))):(l=s.match(/^# Skipped: (\d+)/))&&(i.skipped=Number(l[1]))}return i.pattern!=null?(i.entries=Ou(i.body),i.entryCount!=null&&i.entries.length>i.entryCount&&(i.entries=i.entries.slice(0,i.entryCount))):i.query!=null&&(i.matches=ju(i.body),i.matchCount!=null&&i.matches.length>i.matchCount&&(i.matches=i.matches.slice(0,i.matchCount))),i}function Ou(e){const t=[],n=[];let r="",o=!1;for(const i of String(e||"").split(`
|
|
15
|
+
`)){if(!i.trim())continue;if(i.startsWith("# ")){o=!0,r=i.slice(2).replace(/\/+$/,"");continue}if(o){rs(t,r?r+"/"+i.trim():i.trim());continue}const s=i.match(/^ */)[0].length,l=Math.floor(s/2);let c=i.trim();if(c.endsWith("/")){n.length=l,n[l]=c.slice(0,-1);continue}n.length=l,rs(t,n.filter(Boolean).concat(c).join("/"))}return t}function rs(e,t){let n=t,r=!1;n.endsWith(" (image)")&&(r=!0,n=n.slice(0,-8)),e.push(r?{path:n,image:!0}:{path:n})}function ju(e){const t=[],n=[];let r="",o=!1;const i=/^(\d+): ?(.*)$/;for(const s of String(e||"").split(`
|
|
16
|
+
`)){if(s.startsWith("# ")){o=!0,r=s.slice(2);continue}const l=s.trim().match(i);if(l){t.push({path:r,line:Number(l[1]),text:l[2]});continue}if(o||!s.trim())continue;const c=s.match(/^ */)[0].length,a=Math.floor(c/2),d=s.trim();if(d.endsWith("/")){n.length=a,n[a]=d.slice(0,-1);continue}n.length=a,r=n.filter(Boolean).concat(d).join("/")}return t}const To=new Set;let Ft=null;function Wn(e){if(!e||!e.thumbnail)return;const t=Date.parse(Ft&&Ft.capturedAt||"")||0,n=Date.parse(e.capturedAt||"")||0;Ft&&t&&n&&n<t||(Ft=e,Wa())}function os(){return Ft}function is(){Ft&&(Ft=null,Wa())}function Du(e){return To.add(e),()=>To.delete(e)}function Wa(){for(const e of To)try{e(Ft)}catch{}}const ss=2e3,ao=2e5;function Ut(e,t){const n=document.createElement("div");n.className="tool-preview__meta",n.textContent=t.filter(Boolean).join(" · "),e.appendChild(n)}function Bu(e,t){if(e==null)return null;const n=Mu(e,t);if(!n)return null;const r=document.createElement("div");r.className="tool-preview__args";const o=document.createElement("div");o.className="tool-preview__meta",o.textContent="Command";const i=za(n,"tool-preview__pre tool-preview__pre--args");return r.appendChild(o),r.appendChild(i),r}function za(e,t){const n=document.createElement("pre");return n.className=t||"tool-preview__pre",n.textContent=e||"",n}function $e(e,t,n){const r=za(t,n);return e.appendChild(r),r}function Fu(e,t){const n=document.createElement("div");n.className="tool-preview__diff";const r=t==null?"":String(t),o=r?r.split(`
|
|
17
|
+
`):["(edit applied)"];for(let i=0;i<o.length;i++){const s=o[i],l=document.createElement("div");let c="ctx";s.startsWith("+")&&!s.startsWith("+++")?c="add":s.startsWith("-")&&!s.startsWith("---")?c="del":s.startsWith("@@")?c="hunk":(s.startsWith("---")||s.startsWith("+++"))&&(c="meta"),l.className="tool-preview__diff-line tool-preview__diff-line--"+c;const a=document.createElement("span");a.className="tool-preview__diff-gutter",a.textContent=String(i+1);const d=document.createElement("span");d.className="tool-preview__diff-code",d.textContent=s||" ",l.appendChild(a),l.appendChild(d),n.appendChild(l)}return e.appendChild(n),n}function Ao(e){const t=e&&(e.data||e.base64),n=e&&(e.mimeType||e.mime_type||e.mediaType||e.media_type)||"image/png";let r=e&&(e.url||e.uri);if(!r&&typeof t=="string"&&t&&(r=t.startsWith("data:")?t:"data:"+n+";base64,"+t),!r)return null;const o=document.createElement("img");return o.className="tool-card__image",o.src=r,o.alt="MCP image result",o.loading="lazy",o}function qu(e){const t=e&&e.resource;if(!t||typeof t!="object")return null;const n=t.mimeType||t.mime_type||t.mediaType||t.media_type||"";if(!/^image\//i.test(n))return null;const r=t.blob||t.data||t.base64;return typeof r!="string"||!r?null:{type:"image",data:r,mimeType:n}}function $a(e,t){if(e.classList.add("tool-preview","tool-preview--file"),typeof t=="string"&&(t=_n(t)),!t||t.error)return $e(e,bt(t),"tool-preview__pre");const n=[];if(n.push(t.relPath||t.path),t.kind==="image")return n.push(t.mimeType||"image"),t.bytes!=null&&n.push(Va(t.bytes)),Ut(e,n),Uu(e,t);t.startLine!=null&&t.endLine!=null&&n.push("lines "+t.startLine+"-"+t.endLine+(t.totalLines?" / "+t.totalLines:"")),t.truncated&&n.push("truncated"),Ut(e,n),$e(e,t.body||"","tool-preview__pre tool-preview__pre--content")}function Uu(e,t){const n=Array.isArray(t.content)?t.content.find(s=>s&&(s.type==="image"||s.mimeType)):null,r=n?Ao(n):null;if(!r)return $e(e,"Image bytes are not part of this result.","tool-preview__pre");r.alt="Image "+(t.relPath||""),r.className="tool-card__image tool-card__image--zoomable";const o=document.createElement("button");o.type="button",o.className="tool-card__image-button",o.setAttribute("aria-label","Open "+(t.relPath||"image")+" full screen"),o.appendChild(r),o.addEventListener("click",()=>Vu(r.src,r.alt)),e.appendChild(o);const i=document.createElement("div");i.className="tool-preview__image-note",i.textContent="Sent to the model as an image.",e.appendChild(i)}const mr="mouaif:teardown-lightbox";function Vu(e,t){if(!e)return;if(typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent(mr))}catch{}const n=document.createElement("div");n.className="image-lightbox",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.setAttribute("aria-label",t||"Image");const r=document.createElement("img");r.className="image-lightbox__image",r.src=e,r.alt=t||"";const o=document.createElement("button");o.type="button",o.className="image-lightbox__close",o.setAttribute("aria-label","Close image"),o.textContent="✕";const i=l=>{l.key==="Escape"&&s()};function s(){document.removeEventListener("keydown",i),typeof window<"u"&&typeof window.removeEventListener=="function"&&window.removeEventListener(mr,s),n.parentNode&&n.parentNode.removeChild(n)}n.addEventListener("click",l=>{l.target===n&&s()}),o.addEventListener("click",s),document.addEventListener("keydown",i),typeof window<"u"&&typeof window.addEventListener=="function"&&window.addEventListener(mr,s),n.appendChild(r),n.appendChild(o),document.body.appendChild(n)}function Hu(){if(!(typeof window>"u"||typeof window.dispatchEvent!="function"))try{window.dispatchEvent(new CustomEvent(mr))}catch{}}function Ja(e,t){if(e.classList.add("tool-preview","tool-preview--list"),typeof t=="string"&&(t=_n(t)),!t||t.error)return $e(e,bt(t),"tool-preview__pre");const n=[];if(n.push(t.pattern?"pattern "+t.pattern:"all text and image files"),Array.isArray(t.entries)&&(n.push(t.entries.length+" shown"),t.total!=null&&t.total!==t.entries.length&&n.push(t.total+" total")),t.skipped&&n.push(t.skipped+" skipped"),t.truncated&&n.push("capped"),Ut(e,n),!Array.isArray(t.entries)){const c=String(t.body||"").split(`
|
|
18
|
+
`);return $e(e,c.length&&c[0]?c.join(`
|
|
19
|
+
`):"(no matching files)","tool-preview__pre")}if(!t.entries.length)return $e(e,"(no matching files)","tool-preview__pre");const r=document.createElement("div");r.className="tool-preview__grouped";const o=[...t.entries].sort((c,a)=>c.path<a.path?-1:c.path>a.path?1:0);let i=null,s=null,l=null;for(const c of o){const a=String(c.path||""),d=a.lastIndexOf("/"),p=d===-1?".":a.slice(0,d),f=d===-1?a:a.slice(d+1);p!==i&&(i=p,s=document.createElement("div"),s.className="tool-preview__dir",s.textContent=p==="."?"":p+"/",r.appendChild(s),l=document.createElement("div"),l.className="tool-preview__group",r.appendChild(l));const h=document.createElement("div");h.className="tool-preview__file",h.textContent=c.image?f+" (image)":f,l.appendChild(h)}e.appendChild(r)}function Ga(e,t){if(e.classList.add("tool-preview","tool-preview--list"),typeof t=="string"&&(t=_n(t)),!t||t.error)return $e(e,bt(t),"tool-preview__pre");const n=[];if(n.push(t.query?"search "+t.query:"no query"),Array.isArray(t.matches)&&n.push(t.matches.length+" matches"),t.filesScanned!=null&&n.push(t.filesScanned+" files"),t.truncated&&n.push("capped"),Ut(e,n),!Array.isArray(t.matches)){const s=String(t.body||"").split(`
|
|
20
|
+
`);return $e(e,s.length&&s[0]?s.join(`
|
|
21
|
+
`):"(no matches)","tool-preview__pre")}if(!t.matches.length)return $e(e,"(no matches)","tool-preview__pre");const r=document.createElement("div");r.className="tool-preview__grouped";let o=null,i=null;for(const s of t.matches){if(s.path!==o){o=s.path;const d=document.createElement("div");d.className="tool-preview__dir",d.textContent=o||"",r.appendChild(d),i=document.createElement("div"),i.className="tool-preview__group",r.appendChild(i)}const l=document.createElement("div");l.className="tool-preview__match";const c=document.createElement("span");c.className="tool-preview__match-line",c.textContent=String(s.line);const a=document.createElement("span");a.className="tool-preview__match-text",a.textContent=s.text||"",l.appendChild(c),l.appendChild(a),i.appendChild(l)}e.appendChild(r)}function Ka(e,t){if(e.classList.add("tool-preview","tool-preview--diff"),typeof t=="string"&&(t=_n(t)),!t||t.error)return $e(e,bt(t),"tool-preview__pre");const n=[t.relPath||t.path];t.addedChars!=null?n.push("+"+t.addedChars+(t.removedChars!=null?" / -"+t.removedChars:"")+" chars"):t.bytesWritten!=null&&n.push("+"+t.bytesWritten+"B"+(t.replacedBytes!=null?" / -"+t.replacedBytes+"B":"")),Ut(e,n),Fu(e,t.diff||"(edit applied)")}function Za(e,t,n){if(e.classList.add("tool-preview","tool-preview--file"),typeof t=="string"&&(t=_n(t)),!t||t.error)return $e(e,bt(t),"tool-preview__pre");const r=[t.relPath||t.path];t.chars!=null?r.push(t.chars+" chars"+(t.lines!=null?" · "+t.lines+" lines":"")):t.bytesWritten!=null?r.push(t.bytesWritten+"B"):t.size!=null&&r.push(t.size+"B"),Ut(e,r);const o=n&&typeof n.content=="string"?n.content:"";if(!o)return $e(e,"write complete","tool-preview__pre");$e(e,Wu(o),"tool-preview__pre tool-preview__pre--content")}function Wu(e){const t=String(e),n=t.split(`
|
|
22
|
+
`);if(n.length<=ss&&t.length<=ao)return t;let r=n.slice(0,ss).join(`
|
|
23
|
+
`);return r.length>ao&&(r=r.slice(0,ao)),r+`
|
|
24
|
+
… preview truncated (`+n.length+" lines, "+t.length+" chars written)"}function Ya(e,t,n){e.classList.add("tool-preview","tool-preview--terminal"),typeof t=="string"&&(t=Wt(t,"shell"));const r=Bu(n,"shell");if(r&&e.classList.add("tool-preview--with-args"),!t||t.error)return r&&e.appendChild(r),Ut(e,[t&&t.identity,t&&t.code,t&&t.durationMs!=null?t.durationMs+"ms":null]),$e(e,bt(t),"tool-preview__terminal");const o=[];t.identity&&o.push(t.identity),o.push("exit "+(t.exitCode??0)),t.durationMs!=null&&o.push(t.durationMs+"ms"),t.stdout&&o.push(t.stdout.length+" chars out"),t.stderr&&o.push(t.stderr.length+" chars err"),Ut(e,o);const i=[];t.stdout&&i.push(t.stdout),t.stderr&&(t.stdout&&i.push("── stderr ──"),i.push(t.stderr)),r&&e.appendChild(r),$e(e,i.length?i.join(`
|
|
25
|
+
|
|
26
|
+
`):"(exit "+(t.exitCode??0)+", no output)","tool-preview__terminal")}function zu(e,t){if(e.classList.add("tool-preview","tool-preview--webpreview"),typeof t=="string"&&(t=Wt(t,"webpreview")),!t||t.error)return $e(e,bt(t),"tool-preview__pre");Wn(t),$e(e,"Preview ready for the user.","tool-preview__pre")}function Xa(e,t){if(t&&Array.isArray(t.content)){const n=[];for(const r of t.content)if(r&&typeof r.text=="string")n.push(r.text);else if(r&&r.type==="image"){const o=Ao(r);o?e.appendChild(o):n.push("[image]")}else if(r&&r.type==="resource"){const o=qu(r),i=o&&Ao(o);i?e.appendChild(i):n.push("[resource] "+JSON.stringify(r.resource||r))}else n.push(String(r&&(r.text||r.type)||r));n.length&&$e(e,n.join(`
|
|
27
|
+
`),"tool-preview__pre");return}$e(e,bt(t),"tool-preview__pre")}function $u(e,t){if(e.classList.add("tool-preview","tool-preview--task"),typeof t=="string")try{t=JSON.parse(t)}catch{return $e(e,t,"tool-preview__pre")}if(!t||t.error)return $e(e,bt(t),"tool-preview__pre");if(Array.isArray(t.tasks)){if(!t.tasks.length){e.innerHTML='<div class="tool-preview__task-empty">No tasks yet.</div>';return}const l=document.createElement("div");l.className="tool-preview__task-list";for(const c of t.tasks){const a=document.createElement("div");a.className="tool-preview__task-item tool-preview__task-item--"+(c.status==="completed"?"done":"progress");const d=document.createElement("span");d.className="tool-preview__task-check",d.textContent=c.status==="completed"?"✓":"○";const p=document.createElement("span");if(p.className="tool-preview__task-label",p.textContent=c.title,a.appendChild(d),a.appendChild(p),c.status!=="completed"&&c.total>0){const f=document.createElement("div");f.className="tool-preview__task-bar";const h=document.createElement("div");h.className="tool-preview__task-bar-fill";const g=Math.min(100,Math.max(0,Math.round(c.current/c.total*100)));h.style.width=g+"%",f.appendChild(h),a.appendChild(f);const v=document.createElement("div");v.className="tool-preview__task-stat",v.textContent=c.current+" / "+c.total,a.appendChild(v)}if(c.description){const f=document.createElement("div");f.className="tool-preview__task-desc",f.textContent=c.description,a.appendChild(f)}l.appendChild(a)}e.appendChild(l);return}const n=t.task;if(!n)return Xa(e,t);const r=document.createElement("div");r.className="tool-preview__task-item tool-preview__task-item--"+(n.status==="completed"?"done":"progress");const o=document.createElement("span");o.className="tool-preview__task-check",o.textContent=n.status==="completed"?"✓":"○";const i=document.createElement("div");i.className="tool-preview__task-inner";const s=document.createElement("div");if(s.className="tool-preview__task-label",s.textContent=n.title,i.appendChild(s),n.status!=="completed"&&n.total>0){const l=document.createElement("div");l.className="tool-preview__task-bar";const c=document.createElement("div");c.className="tool-preview__task-bar-fill";const a=Math.min(100,Math.max(0,Math.round(n.current/n.total*100)));c.style.width=a+"%",l.appendChild(c),i.appendChild(l);const d=document.createElement("div");d.className="tool-preview__task-stat",d.textContent=n.current+" / "+n.total,i.appendChild(d)}if(n.description){const l=document.createElement("div");l.className="tool-preview__task-desc",l.textContent=n.description,i.appendChild(l)}r.appendChild(o),r.appendChild(i),e.appendChild(r)}function Ju(e,t,n){if(n(t&&t.name)){const l=e.querySelector(".tool-card__subagent-live");l&&l.remove()}e.textContent="",e.className="tool-card__body";const r=e.closest&&e.closest(".tool-card"),o=Ge(t&&t.name||r&&r.dataset.toolName),i=Wt(t&&t.result,o),s=t&&t.args||r&&r._toolArgs||null;if(o==="shell")return Ya(e,i,s);if(o==="read_file")return $a(e,i);if(o==="list_files")return Ja(e,i);if(o==="search_files")return Ga(e,i);if(o==="edit_file")return Ka(e,i);if(o==="write_file")return Za(e,i,s);if(o==="task")return $u(e,i);if(o==="webpreview")return zu(e,i);n(t&&t.name)||Xa(e,i)}function kt(e){return typeof CSS<"u"&&CSS.escape?CSS.escape(e):String(e).replace(/[^A-Za-z0-9_-]/g,t=>"\\"+t)}async function Gu(e){const t=String(e??"");try{if(navigator.clipboard&&navigator.clipboard.writeText)return await navigator.clipboard.writeText(t),!0}catch{}try{const n=document.createElement("textarea");n.value=t,n.setAttribute("readonly",""),n.style.position="fixed",n.style.top="0",n.style.left="0",n.style.opacity="0",document.body.appendChild(n),n.select();const r=document.execCommand("copy");return document.body.removeChild(n),r}catch{return!1}}function Ku(e){if(!e)return"";const t=typeof e.content=="string"?e.content:String(e.content==null?"":e.content);if(e.role!=="assistant"){if(e.role!=="user"||!Array.isArray(e.attachments)||!e.attachments.length)return t;const r=e.attachments.map(o=>o&&o.name||"image").filter(Boolean);return r.length?(t?t+`
|
|
28
|
+
|
|
29
|
+
`:"")+r.map(o=>"[image: "+o+"]").join(`
|
|
30
|
+
`):t}const n=typeof e.reasoning=="string"?e.reasoning:"";return t.trim()?t:n}class Lm{constructor(){this.grid=[],this.row=1,this.col=1,this.pending="",this.fullScreen=!1}get isFullScreen(){return this.fullScreen}_ensureRow(t){for(t<1&&(t=1);this.grid.length<t;)this.grid.push([]);return this.grid[t-1]}_put(t,n,r){n<1&&(n=1),r<1&&(r=1);const o=this._ensureRow(n),i=r-1;for(;o.length<i;)o.push(" ");o[i]=t}_csi(t,n){let r=!1,o=t;o[0]==="?"&&(r=!0,o=o.slice(1)),o=o.replace(/[\x20-\x2f]/g,"");const i=o===""?[]:o.split(";").map(l=>l===""?0:Number(l)),s=i.length?i[0]:n==="K"||n==="J"?0:1;switch(n){case"H":case"f":this.row=i[0]||1,this.col=i[1]||1,this.row<1&&(this.row=1),this.col<1&&(this.col=1),this._ensureRow(this.row);break;case"A":this.row=Math.max(1,this.row-(s||1));break;case"B":this.row+=s||1,this._ensureRow(this.row);break;case"C":this.col+=s||1;break;case"D":this.col=Math.max(1,this.col-(s||1));break;case"E":this.row+=s||1,this.col=1,this._ensureRow(this.row);break;case"F":this.row=Math.max(1,this.row-(s||1)),this.col=1;break;case"G":this.col=s||1,this.col<1&&(this.col=1);break;case"d":this.row=s||1,this._ensureRow(this.row);break;case"K":{const l=this._ensureRow(this.row),c=i.length?i[0]:0;if(c===2)for(let a=0;a<l.length;a++)l[a]=" ";else if(c===1)for(let a=0;a<Math.min(this.col-1,l.length);a++)l[a]=" ";else for(let a=this.col-1;a<l.length;a++)l[a]=" ";break}case"J":{const l=i.length?i[0]:0;if(l===2||l===3)this.grid=[];else if(l===1){for(let a=0;a<this.row-1;a++){const d=this.grid[a];if(d)for(let p=0;p<d.length;p++)d[p]=" "}const c=this._ensureRow(this.row);for(let a=0;a<Math.min(this.col-1,c.length);a++)c[a]=" "}else{const c=this._ensureRow(this.row);for(let a=this.col-1;a<c.length;a++)c[a]=" ";for(let a=this.row;a<this.grid.length;a++){const d=this.grid[a];if(d)for(let p=0;p<d.length;p++)d[p]=" "}}this._ensureRow(this.row);break}case"h":case"l":r&&i.indexOf(1049)!==-1&&(n==="h"?(this.grid=[],this.row=1,this.col=1,this.fullScreen=!0):this.fullScreen=!1);break}}write(t){const n=this.pending+String(t||"");this.pending="";const r=Array.from(n);let o=0;const i=r.length;for(;o<i;){const s=r[o];if(s==="\x1B"){const l=r[o+1];if(l==="["){let c=o+2;for(;c<i&&!(r[c]>="@"&&r[c]<="~");)c++;if(c>=i){this.pending=r.slice(o).join("");break}this._csi(r.slice(o+2,c).join(""),r[c]),o=c+1;continue}if(l==="]"){let c=o+2;for(;c<i&&r[c]!=="\x07"&&!(r[c]==="\x1B"&&r[c+1]==="\\");)c++;if(c>=i){this.pending=r.slice(o).join("");break}o=r[c]==="\x07"?c+1:c+2;continue}if(l==="("||l===")"||l==="#"||l==="%"){if(o+2>=i){this.pending=r.slice(o).join("");break}o+=3;continue}o+=r[o+1]!==void 0?2:1;continue}if(s==="\r"){this.col=1,o+=1;continue}if(s===`
|
|
31
|
+
`){this.row+=1,this.col=1,this._ensureRow(this.row),o+=1;continue}if(s==="\b"){this.col=Math.max(1,this.col-1),o+=1;continue}if(s==="\v"){this.row+=1,this.col=1,this._ensureRow(this.row),o+=1;continue}if(s<" "||s===""){o+=1;continue}this._put(s,this.row,this.col),this.col+=1,o+=1}}render(){const t=[];for(let n=0;n<this.grid.length;n++){const r=this.grid[n];let o="";for(let i=0;i<r.length;i++)o+=r[i]||" ";o=o.replace(/\s+$/,""),o.length&&t.push(o)}return t.join(`
|
|
32
|
+
`)}}function Qa({groups:e=[],onToggleGroup:t,onToggleTool:n,collapsedByDefault:r=!1,initialCollapsed:o,onCollapseChange:i,alwaysExpanded:s=!1,class:l="",onReloadServer:c=null}){const[a,d]=E(()=>o instanceof Set?new Set(o):r?new Set(e.filter(g=>(g.tools||[]).length>1).map(g=>g.id)):new Set),p=x(new Set);ue(()=>{if(o instanceof Set)return;let g=!1;const v=new Set(a);for(const b of e){const k=b.id,_=(b.tools||[]).length>1&&!s&&!b.alwaysExpanded;!r||!_||p.current.has(k)||v.has(k)||(v.add(k),g=!0)}g&&d(v)});function f(g){p.current.add(g);const v=new Set(a);v.has(g)?v.delete(g):v.add(g),d(v),i&&i(v)}const h=l?"tool-tree "+l:"tool-tree";return e.length?u("ul",{class:h,role:"tree","aria-label":"Tools"},e.map(g=>{const v=g.tools||[],b=v.length>1,k=s||!!g.alwaysExpanded,_=b&&!k,y=_&&a.has(g.id),w=v.length>0&&!y&&(b||k),N=v.filter(P=>P.checked).length,O=v.length>0&&N>0&&N<v.length;return u("li",{key:g.id,class:"tool-tree__group",role:"treeitem","aria-expanded":_?String(!y):void 0},u("div",{class:"tool-tree__row"+(g.disabled?" is-disabled":""),title:g.title||(g.disabled&&g.disabledReason?g.disabledReason:void 0)},_?u("button",{type:"button",class:"tool-tree__chev"+(y?" is-collapsed":""),onClick:()=>f(g.id),"aria-label":(y?"Expand ":"Collapse ")+g.name,"aria-expanded":String(!y)},u("svg",{viewBox:"0 0 16 16",width:10,height:10,"aria-hidden":"true"},u("path",{d:"M4 6 L8 10 L12 6",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"}))):u("span",{class:"tool-tree__chew","aria-hidden":"true"}),g.hideCheckbox?null:u("input",{type:"checkbox",class:"checkbox checkbox--sm",checked:!!g.checked,disabled:!!g.disabled,indeterminate:O,"aria-checked":O?"mixed":void 0,onChange:P=>t&&t(g.id,P.target.checked),"aria-label":g.name}),u("span",{class:"tool-tree__name tool-tree__name--group"},g.name),g.description?u("span",{class:"tool-tree__desc"},g.description):null,v.length>1?u("span",{class:"tool-tree__count"},N+"/"+v.length):null,g.control?u("span",{class:"tool-tree__control"},g.control):null,!g.enabled||g.status==="ready"||g.status==="starting"?null:u("button",{type:"button",class:"tool-tree__reload"+(g.reloadBusy?" is-busy":""),title:g.reloadBusy?"Starting MCP server "+g.name+"…":"Start MCP server "+g.name,"aria-label":g.reloadBusy?"Starting MCP server "+g.name:"Start MCP server "+g.name,"aria-busy":g.reloadBusy?"true":void 0,disabled:!!g.reloadBusy,onClick:P=>{P.stopPropagation(),c&&c(g)}},"…")),g.disabled&&g.disabledReason?u("div",{class:"tool-tree__reason"},g.disabledReason):null,w?u("ul",{class:"tool-tree__children",role:"group"},v.map(P=>u("li",{key:P.id,class:"tool-tree__item",role:"treeitem"},u("div",{class:"tool-tree__row tool-tree__row--leaf"+(P.used?" is-used":"")+(P.disabled?" is-disabled":""),title:P.title||(P.disabled&&P.disabledReason?P.disabledReason:void 0)},u("input",{type:"checkbox",class:"checkbox checkbox--sm",checked:!!P.checked,disabled:!!P.disabled||!!g.disabled,onChange:Y=>n&&n(g.id,P.id,Y.target.checked),"aria-label":P.name}),u("span",{class:"tool-tree__name"},P.name),P.description?u("span",{class:"tool-tree__desc"},P.description):null,P.used?u("span",{class:"tool-tree__used",title:"Used in this chat"},"●"):null,P.disabled&&P.disabledReason?u("span",{class:"tool-tree__leaf-reason"},P.disabledReason):null)))):null,g.extra||null)})):u("div",{class:h+" tool-tree--empty"},"No tools available")}function Mm({choices:e,restricted:t,selected:n,mcpServers:r=[],catalog:o=[]}){const i=a=>!t||n(a),s=[],l=e.filter(a=>!a.value.startsWith("mcp__")),c=l.filter(a=>["read_file","list_files","search_files","write_file","edit_file"].includes(a.value));for(const a of l){if(c.includes(a))continue;const d=o.find(p=>p&&p.name===a.value);s.push({id:a.value,name:a.label,description:Mn(d&&d.description),title:d&&d.description||"",checked:i(a.value),tools:[{id:a.value,name:a.label,checked:i(a.value)}]})}c.length&&s.push({id:"files",name:"File tools",description:"read, list, search, write, edit",checked:c.every(a=>i(a.value)),tools:c.map(a=>({id:a.value,name:a.label,checked:i(a.value)}))});for(const a of e){if(!a.value.startsWith("mcp__"))continue;const d=a.value.slice(5),p=r.find(v=>v&&(v.slug||v.id)===d),f=a.label.replace(/^MCP:\s*/,""),h=a.value+"__",g=p&&Array.isArray(p.tools)?p.tools.map(v=>{const b=typeof v=="string"?v:v&&v.name;if(!b)return null;const k=b.startsWith(h)?b.slice(h.length):b,_=b.startsWith("mcp__")?b:h+b;return{id:_,name:k,description:Mn(v&&v.description),title:v&&v.description||"",checked:i(a.value)||i(_)}}).filter(Boolean):[];s.push({id:a.value,name:f,description:(p&&p.status?p.status:"MCP server")+(g.length?"":" · no tools discovered"),checked:i(a.value),tools:g.length?g:[{id:a.value,name:f,checked:i(a.value)}]})}return s}function Mn(e,t=40){const n=String(e||"").replace(/\s+/g," ").trim();if(!n)return"";const r=n.indexOf(". "),o=r>0?n.slice(0,r):n;return o.length<=t?o:o.slice(0,t-1).trimEnd()+"…"}function el(e,t,n,r=new Set){const o=[],i=Array.isArray(n)?new Set(n):null,s=p=>i==null||i.has(p),l=p=>p.length>0&&p.every(f=>f&&s(f.name)),c=(p,f)=>Object.assign({id:p.name,name:p.name,description:Mn(p.description),title:p.description||"",checked:s(p.name),used:r.has(p.name)},f||{});for(const p of["shell","subagent","ask_user","task","webpreview","restart_app"]){const f=e.find(h=>h&&h.name===p);f&&o.push({id:p,name:p,description:Mn(f.description),title:f.description||"",checked:s(p),tools:[c(f)]})}const a=e.find(p=>p&&p.name==="report_progress");a&&o.push({id:"report_progress",name:"Progress updates",description:Mn(a.description),title:a.description||"",checked:s("report_progress"),tools:[c(a)]});const d=e.filter(p=>p&&p.kind==="native"&&p.source==="files");d.length&&o.push({id:"files",name:"File tools",description:"read, list, search, write, edit",checked:l(d),tools:d.map(p=>c(p))});for(const p of t||[]){if(!p||!p.id)continue;const f=p.slug||p.id,h="mcp__"+f+"__";let g=e.filter(v=>v&&v.kind==="mcp"&&v.source===f);!g.length&&Array.isArray(p.tools)&&(g=p.tools.map(v=>{const b=typeof v=="string"?v:v&&v.name;return b?{name:b.startsWith(h)?b:h+b,kind:"mcp",source:f,description:v&&v.description||""}:null}).filter(Boolean)),o.push({id:"mcp-"+f,name:p.name||p.id,description:(p.status||"stopped")+(g.length?"":" · no tools"),checked:l(g),status:p.status||"stopped",enabled:p.enabled!==!1,serverId:p.id,tools:g.map(v=>{const b=v.name.startsWith(h)?v.name.slice(h.length):v.name;return c(v,{name:b})})})}return o}function tl({tool:e,name:t,mode:n,allowlist:r,modes:o=Vr,namePrefix:i="auth",onPick:s,onClear:l}){const c=rl(n||"ask"),a=Array.isArray(r)?r:[],d=t||e||"tool";return u("div",{class:"seg",role:"radiogroup","aria-label":d+" authorization"},o.map(p=>u("label",{key:p.value,class:"seg__item"+(c===p.value?" seg__item--on":"")},u("input",{type:"radio",name:i+"-"+String(e||d).replace(/\s+/g,"-").toLowerCase(),value:p.value,checked:c===p.value,onChange:()=>{l&&l(),s&&s(p.value,p.value==="allow"?[]:a)}}),u("span",{class:"seg__pill"},p.label))))}const Vr=[{value:"off",label:"Off"},{value:"ask",label:"Ask"},{value:"allow",label:"Allow"}],nl=[{value:"off",label:"Off"},{value:"ask",label:"Ask"}];function rl(e){return e==="allowlist"?"ask":e}async function Zu(e,t,n){return await H("/api/tools/authorization",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:"chat",projectDir:e,chatId:t,chat:n})})}async function Yu(e,t,n){return await H("/api/tools/authorization",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:"chat",projectDir:e,chatId:t,chat:{mcp:n}})})}function Xu(e,t,n){const r=e&&typeof e=="object"?e[t]:null,o=!!(r&&typeof r.mode=="string"&&r.mode),i=o?r.mode:n&&n.mode||"ask",s=o?Array.isArray(r.allowlist)?r.allowlist:[]:Array.isArray(n&&n.allowlist)?n.allowlist:[];return{overridden:o,mode:i,allowlist:s}}function ol({name:e,slug:t,servers:n,shared:r,namePrefix:o="mcp",onSave:i,onClear:s}){const l=t?Xu(n,t,r):{mode:r&&r.mode||"ask",allowlist:r&&r.allowlist||[]},c=rl(l.mode);return u("div",{class:"seg",role:"radiogroup","aria-label":e+" authorization"},Vr.map(d=>u("label",{key:d.value,class:"seg__item"+(c===d.value?" seg__item--on":"")},u("input",{type:"radio",name:o+"-"+e.replace(/\s+/g,"-").toLowerCase(),value:d.value,checked:c===d.value,onChange:()=>{if(!i)return;let p=d.value,f=Array.isArray(l.allowlist)?l.allowlist:[];p==="allow"?f=[]:p==="ask"&&f.length&&(p="allowlist"),s&&s(),i(t?{servers:{[t]:{mode:p,allowlist:f}}}:{mode:p,allowlist:f})}}),u("span",{class:"seg__pill"},d.label))))}function Qu(e){const t=new Map;for(const n of e||[]){if(!n||!n.id)continue;const r=n.provider||"",o=r+"\0"+n.id;t.has(o)||t.set(o,{id:n.id,provider:r,label:n.label||"",ghost:!!n.ghost})}return Array.from(t.values())}function ed(e){const t=new Map;for(const r of e){const o=t.get(r.provider)||[];o.push(r),t.set(r.provider,o)}const n=[];for(const[r,o]of t)o.sort((i,s)=>i.id.localeCompare(s.id)),n.push({provider:r,items:o});return n.sort((r,o)=>(r.provider||"Other").localeCompare(o.provider||"Other")),n}function td(e,t){return t?(e.id||"").toLowerCase().indexOf(t)>=0||(e.label||"").toLowerCase().indexOf(t)>=0:!0}function sr(e){return(e.provider||"")+"\0"+e.id}function as({pinned:e}){return u("svg",{viewBox:"0 0 24 24",width:14,height:14,"aria-hidden":"true",fill:e?"currentColor":"none",stroke:e?"none":"currentColor","stroke-width":e?0:2},u("path",{d:"M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"}))}function il(e){const{models:t,value:n,onChange:r,allowClear:o=!1,clearLabel:i="Inherit chat model",placeholder:s="Pick a model",noProviders:l=!1,label:c,refresh:a,refreshEmpty:d="Refresh models",disabled:p=!1,ariaLabel:f="Pick model",className:h,variant:g="dropdown",open:v,onOpenChange:b,pinned:k,onTogglePin:_,recent:y,recommended:w,extraProviders:N,onOpen:O,children:P}=e,Y=_t(()=>Qu(t),[t]),[re,z]=E(!1),I=typeof v=="boolean",D=I?v:re,V=We(T=>{I?b&&b(T):z(T)},[I,b]),[Z,oe]=E(""),[ie,_e]=E("all"),[ye,we]=E(!1),[He,De]=E(""),pe=x(!1),[ae,le]=E(!1),W=x(null),G=x(null),he=x(null),Pe=x(null),F=x(null),R=x(!1),$=x(O);$.current=O;const se=g==="sheet"||g==="chat",de=n&&(n.providerId||n.modelId)?{providerId:n.providerId||"",modelId:n.modelId||""}:null,fe=We(()=>{se&&G.current&&G.current.open&&G.current.close(),V(!1),F.current&&F.current.focus({preventScroll:!0})},[V,se]);ue(()=>{if(!D||se)return;const T=te=>{W.current&&!W.current.contains(te.target)&&V(!1)},B=te=>{te.key==="Escape"&&fe()};return document.addEventListener("mousedown",T),document.addEventListener("touchstart",T),document.addEventListener("keydown",B),()=>{document.removeEventListener("mousedown",T),document.removeEventListener("touchstart",T),document.removeEventListener("keydown",B)}},[D,se,V,fe]),ue(()=>{if(!D){le(!1);return}$.current&&$.current()},[D]),Li(()=>{if(!D||!se)return;const T=G.current;if(!T)return;const B=window.visualViewport;let te=0;const Se=F.current&&F.current.getBoundingClientRect(),be=()=>{const Re=B&&B.height?B.height:window.innerHeight,Qe=B?Math.max(0,B.offsetTop):0;if(T.style.setProperty("--model-picker-viewport-height",Re+"px"),T.style.setProperty("--model-picker-viewport-top",Qe+"px"),Se){const at=Math.min(Math.max(Qe,Se.bottom+4),Qe+Re-Math.min(280,Re));T.style.setProperty("--model-picker-anchor-top",at+"px"),T.style.setProperty("--model-picker-anchor-left",Se.left+"px"),T.style.setProperty("--model-picker-available-height",Math.max(0,Qe+Re-at)+"px")}},Me=()=>{cancelAnimationFrame(te),te=requestAnimationFrame(be)};return B&&(B.addEventListener("resize",be),B.addEventListener("scroll",be)),window.addEventListener("resize",be),window.addEventListener("orientationchange",be),T.addEventListener("focusin",Me),T.addEventListener("focusout",Me),be(),T.open||T.showModal(),()=>{T.open&&T.close(),cancelAnimationFrame(te),B&&(B.removeEventListener("resize",be),B.removeEventListener("scroll",be)),window.removeEventListener("resize",be),window.removeEventListener("orientationchange",be),T.removeEventListener("focusin",Me),T.removeEventListener("focusout",Me),T.style.removeProperty("--model-picker-viewport-height"),T.style.removeProperty("--model-picker-viewport-top"),T.style.removeProperty("--model-picker-anchor-top"),T.style.removeProperty("--model-picker-anchor-left"),T.style.removeProperty("--model-picker-available-height")}},[D,se]),Li(()=>{D&&he.current&&he.current.focus({preventScroll:!0})},[D]);const Be=_t(()=>{const T=[];for(const B of Y)B.provider&&T.indexOf(B.provider)<0&&T.push(B.provider);for(const B of N||[])B&&T.indexOf(B)<0&&T.push(B);return T.sort((B,te)=>B.localeCompare(te))},[Y,N]),Fe=_t(()=>{const T={all:Y.length};for(const B of Y)T[B.provider]=(T[B.provider]||0)+1;for(const B of N||[])B&&T[B]===void 0&&(T[B]=0);return T},[Y,N]),Ce=_t(()=>{let T=Y;ie!=="all"&&(T=T.filter(te=>te.provider===ie));const B=Z.trim().toLowerCase();return B&&(T=T.filter(te=>td(te,B))),T},[Y,ie,Z]),ut=_t(()=>ed(Ce),[Ce]),Ne=de?de.providerId+"\0"+de.modelId:null,it=!!Z.trim(),dt=ie==="all"&&!it;function Je(T){fe(),r&&r({providerId:T.provider,modelId:T.id})}function st(){fe(),r&&r(null)}async function X(){if(!(!a||pe.current)){pe.current=!0,we(!0),De("");try{const T=await a();T&&T.error&&De(T.error)}catch{De("Could not refresh models. Try again.")}finally{pe.current=!1,we(!1)}}}function ee(T){T.button===0&&document.activeElement===he.current&&T.preventDefault()}function C(){oe(""),Pe.current&&(Pe.current.scrollTop=0),he.current&&he.current.focus({preventScroll:!0})}const j=de?de.modelId:o?i:s,q=de?de.providerId:l?"add a provider in Settings → Providers":"",J=!de&&!o,A="mp"+(h?" "+h:"")+(g==="chat"?" mp--chat mp--sheet":g==="sheet"?" mp--sheet":"");return u("div",{class:A,ref:W},c?u("label",{class:"mp__label"},c):null,u("button",{ref:F,type:"button",class:"mp__trigger"+(J?" is-empty":"")+(l?" no-providers":"")+(!Y.length&&!l?" is-empty":""),disabled:!!p,"aria-label":f,"aria-haspopup":"dialog","aria-expanded":String(D),onClick:()=>V(!D)},u("span",{class:"mp__stack"},u("span",{class:"mp__id"},j),u("span",{class:"mp__provider"},q)),u("span",{class:"mp__caret","aria-hidden":"true"},"▾")),D?u(se?"dialog":"div",{class:"mp__pop",role:"dialog","aria-modal":se?"true":void 0,"aria-label":f,ref:G,onCancel:se?T=>{T.preventDefault(),fe()}:void 0,onKeyDown:se?T=>{T.key==="Escape"&&(T.preventDefault(),T.stopPropagation(),fe())}:void 0,onPointerDown:se?T=>{const B=T.currentTarget.getBoundingClientRect();R.current=T.target===T.currentTarget&&(T.clientX<B.left||T.clientX>B.right||T.clientY<B.top||T.clientY>B.bottom)}:void 0,onPointerCancel:se?()=>{R.current=!1}:void 0,onClick:se?T=>{const B=R.current;if(R.current=!1,!B||T.target!==T.currentTarget)return;const te=T.currentTarget.getBoundingClientRect();(T.clientX<te.left||T.clientX>te.right||T.clientY<te.top||T.clientY>te.bottom)&&fe()}:void 0},u("div",{class:"mp__head"},u("input",{ref:he,class:"mp__search",type:"search",placeholder:"Search models","aria-label":"Search models",value:Z,onInput:T=>oe(T.currentTarget.value)}),P?u("button",{type:"button",class:"mp__options"+(ae?" is-active":""),"aria-label":ae?"Hide model options":"Show model options",title:"Model options","aria-expanded":String(ae),onClick:()=>le(!ae)},u("svg",{viewBox:"0 0 24 24",width:18,height:18,fill:"currentColor","aria-hidden":"true"},u("path",{d:"M19.14 12.94a7.07 7.07 0 0 0 0-1.88l2.03-1.58a.5.5 0 0 0 .12-.64l-1.92-3.32a.5.5 0 0 0-.6-.22l-2.39.96a7.03 7.03 0 0 0-1.63-.94l-.36-2.54A.5.5 0 0 0 13.9 2h-3.84a.5.5 0 0 0-.5.42l-.36 2.54a7.03 7.03 0 0 0-1.63.94l-2.39-.96a.5.5 0 0 0-.6.22L2.66 8.48a.5.5 0 0 0 .12.64l2.03 1.58a7.07 7.07 0 0 0 0 1.88L2.78 14.16a.5.5 0 0 0-.12.64l1.92 3.32a.5.5 0 0 0 .6.22l2.39-.96c.5.39 1.05.71 1.63.94l.36 2.54a.5.5 0 0 0 .5.42h3.84a.5.5 0 0 0 .5-.42l.36-2.54c.58-.23 1.13-.55 1.63-.94l2.39.96a.5.5 0 0 0 .6-.22l1.92-3.32a.5.5 0 0 0-.12-.64l-2.04-1.58ZM12 15.5A3.5 3.5 0 1 1 12 8.5a3.5 3.5 0 0 1 0 7Z"}))):null,a?u("button",{type:"button",class:"mp__refresh","aria-label":"Refresh model lists",title:"Refresh model lists",disabled:ye,onPointerDown:ee,onClick:X},u("svg",{viewBox:"0 0 24 24",width:16,height:16,"aria-hidden":"true"},u("path",{d:"M12 4V1L7 6l5 5V7c3.31 0 6 2.69 6 6 0 1-.25 1.97-.7 2.8l1.46 1.46A7.93 7.93 0 0 0 20 13c0-4.42-3.58-8-8-8Zm-5.3 7.7A7.93 7.93 0 0 0 4 13c0 4.42 3.58 8 8 8v3l5-5-5-5v3c-3.31 0-6-2.69-6-6 0-1 .25-1.97.7-2.8L5.24 10.24Z",fill:"currentColor"}))):null,u("button",{type:"button",class:"mp__close","aria-label":"Close",title:"Close",onClick:fe},"×")),P?u("div",{class:"mp__options-panel",hidden:!ae},P):null,Be.length?u("div",{class:"mp__chips",role:"tablist","aria-label":"Filter by provider"},[{id:"all",label:"All"}].concat(Be.map(T=>({id:T,label:T}))).map(T=>u("button",{key:T.id,type:"button",class:"mp__chip"+(ie===T.id?" is-active":""),onClick:()=>_e(T.id)},u("span",{class:"mp__chip-label"},T.label),u("span",{class:"mp__chip-count"},String(Fe[T.id]||0))))):null,He?u("p",{class:"mp__refresh-error",role:"alert"},He):null,u("div",{class:"mp__list",ref:Pe,"aria-busy":ye?"true":void 0},o?u("div",{class:"mp__clear"+(de?"":" is-active"),role:"button",tabindex:"0",onClick:st},u("span",{class:"mp__clear-id"},i)):null,dt&&w?M("Recommended",ve(Y,w,k,y)):null,dt&&k?M("Pinned",Y.filter(T=>k.has(sr(T)))):null,dt&&y?Ae(y,Y,k):null,ut.length?ut.map(T=>u("section",{class:"mp__section",key:T.provider||"other"},u("div",{class:"mp__section-head"},u("span",{class:"mp__section-title"},T.provider||"Other"),u("span",{class:"mp__section-count"},String(T.items.length))),T.items.map(B=>{const te=sr(B);return u("div",{key:te,class:"mp__row"+(te===Ne?" is-active":"")+(B.ghost?" is-ghost":""),role:"button",tabindex:"0",onClick:()=>Je(B)},!B.ghost&&_?u("button",{type:"button",class:"mp__pin","aria-label":"Pin model","aria-pressed":k&&k.has(te)?"true":"false",onClick:Se=>{Se.stopPropagation(),_(B)}},u(as,{pinned:k&&k.has(te)})):null,u("span",{class:"mp__row-id"},B.id),B.label&&B.label!==B.id?u("span",{class:"mp__row-label"},B.label):null,u("span",{class:"mp__row-meta"},B.ghost?"unavailable":B.provider||""))}))):u("div",{class:"mp__empty"},u("p",{class:"mp__empty-title"},it?"No matches":Y.length?"No models for this provider":"No models yet"),u("p",{class:"mp__empty-text"},it?'No model matches "'+Z+'". Try a shorter query or clear the search.':d),u("div",{class:"mp__empty-actions"},a?u("button",{type:"button",class:"mp__empty-action",disabled:ye,onPointerDown:ee,onClick:X},ye?"Refreshing…":d):null,it?u("button",{type:"button",class:"mp__empty-action mp__empty-action--clear",onPointerDown:ee,onClick:C},"Clear search"):null)))):null);function M(T,B){return B.length?u("section",{class:"mp__section",key:T.toLowerCase()},u("div",{class:"mp__section-head"},u("span",{class:"mp__section-title"},T),u("span",{class:"mp__section-count"},String(B.length))),B.map(te=>{const Se=sr(te);return u("div",{key:Se,class:"mp__row"+(Se===Ne?" is-active":""),role:"button",tabindex:"0",onClick:()=>Je(te)},_?u("button",{type:"button",class:"mp__pin","aria-label":"Pin model","aria-pressed":k&&k.has(Se)?"true":"false",onClick:be=>{be.stopPropagation(),_(te)}},u(as,{pinned:k&&k.has(Se)})):null,u("span",{class:"mp__row-id"},te.id),te.label&&te.label!==te.id?u("span",{class:"mp__row-label"},te.label):null,u("span",{class:"mp__row-meta"},te.provider||""))})):null}function ve(T,B,te,Se){const be=new Set((Se||[]).map(Re=>(Re.provider||"")+"\0"+Re.id)),Me=[];for(const Re of B||[]){const Qe=(Re.provider||"")+"\0"+Re.id;if(be.has(Qe)||te&&te.has(Qe))continue;const at=T.find(Rt=>sr(Rt)===Qe);at&&Me.push(at)}return Me}function Ae(T,B,te){if(!T.length)return null;const Se=new Set,be=[];for(const Me of T){const Re=(Me.provider||"")+"\0"+Me.id;if(Se.has(Re))continue;Se.add(Re);const Qe=B.find(at=>(at.provider||"")===(Me.provider||"")&&at.id===Me.id);if(Qe&&!(te&&te.has(Re))&&be.push(Qe),be.length>=5)break}return be.length?M("Recent",be):null}}const nd=["low","medium","high"];function rd(e){const t=e&&e.chat;if(!t||!t.providerId||!t.modelId)return null;const r=(e.liveByProvider&&e.liveByProvider[t.providerId]||[]).find(o=>o&&o.id===t.modelId);return r&&r.thinking||null}function sl(e){const t=[{value:"",label:"No thinking"}];if(e&&e.kind==="toggle")return t.push({value:"on",label:"Thinking"}),t;if(e&&e.kind==="levels"&&Array.isArray(e.levels)&&e.levels.length)for(const n of e.levels)t.push({value:n,label:n.charAt(0).toUpperCase()+n.slice(1)});else for(const n of nd)t.push({value:n,label:n.charAt(0).toUpperCase()+n.slice(1)});return t.push({value:"__custom__",label:"Custom…"}),t}function od(e){return sl(e).filter(t=>t.value!=="__custom__")}function bn(e,t){const n=e.thinkingLevel&&e.thinkingLevel.current;if(!n)return;const r=t.chat&&t.chat.thinkingLevel||"";t.thinkingLevel=r;const o=sl(rd(t));n.replaceChildren();for(const l of o){const c=document.createElement("option");c.value=l.value,c.textContent=l.label,l.value==="__custom__"&&(c.style.fontStyle="italic"),n.appendChild(c)}const i=e.thinkingLevelCustom&&e.thinkingLevelCustom.current;o.some(l=>l.value===r)?(n.value=r,i&&(i.hidden=!0)):r&&o.some(c=>c.value==="__custom__")?(n.value="__custom__",i&&(i.value=r,i.hidden=!1)):(n.value="",i&&(i.hidden=!0))}function id(e){const{value:t,onChange:n,descriptor:r,inheritLabel:o="Inherit",disabled:i=!1,ariaLabel:s="Thinking level"}=e,l=_t(()=>od(r).filter(p=>p.value!==""),[r]),c=typeof t=="string"?t:"",d=c===""||l.some(p=>p.value===c)?l:l.concat([{value:c,label:c}]);return u("select",{class:"input thinking-select-field",value:c,disabled:!!i,"aria-label":s,onChange:p=>{n&&n(p.currentTarget.value)}},u("option",{value:""},o),d.map(p=>u("option",{key:p.value,value:p.value},p.label)))}function sd({models:e,initialValue:t,projectDir:n,onChange:r}){const[o,i]=E(t||null),[s,l]=E(""),c=_t(()=>({props:{projectDir:n},recentModels:[]}),[n]),[a,d]=E(()=>Bt(c)),[p,f]=E(()=>Vn(c)),h=We(()=>{let y=!0;return La(c).then(w=>{y&&w&&d(Bt(c))}),()=>{y=!1}},[c]);function g(y){const w=y;i(w),w&&w.providerId&&w.modelId&&(Ma(c,w.providerId,w.modelId),d(Bt(c))),r&&r({modelOverride:w?{providerId:w.providerId,modelId:w.modelId}:null,thinkingLevel:s,model:w})}function v(y){l(y),r&&r({modelOverride:o?{providerId:o.providerId,modelId:o.modelId}:null,thinkingLevel:y,model:o})}const b=We(y=>{!y||!y.provider||!y.id||(Oa(c,y.provider,y.id),f(Vn(c)),d(Bt(c)))},[c]),k=t?"(chat default) "+t.modelId:"(chat default)",_=o&&e.find(y=>y.id===o.modelId&&y.provider===o.providerId);return u("div",{class:"auth-model-picker"},u(il,{models:e,value:o,variant:"sheet",allowClear:!0,clearLabel:k,ariaLabel:"Model for this subagent run",pinned:p,recent:a,onTogglePin:b,onOpen:h,onChange:g}),u(id,{value:s,descriptor:_&&_.thinking,inheritLabel:"Inherit chat thinking",ariaLabel:"Thinking level for this subagent run",onChange:v}))}const gt={setup:0,sysPrompt:1,tools:2,agentFiles:3,skills:4,empty:5},ad=[".chat-view__setup",'[data-sys-prompt="1"]','[data-tools-card="1"]','[data-agent-files-card="1"]','[data-skills-card="1"]',".chat-view__empty"];function ls(e,t){const n=e&&e.className;return typeof n=="string"&&(" "+n+" ").indexOf(" "+t+" ")>=0}function Yo(e){if(!e||e.nodeType!==1)return-1;const t=e.dataset||null;if(t){if(t.sysPrompt!==void 0)return gt.sysPrompt;if(t.toolsCard!==void 0)return gt.tools;if(t.agentFilesCard!==void 0)return gt.agentFiles;if(t.skillsCard!==void 0)return gt.skills}return ls(e,"chat-view__setup")?gt.setup:ls(e,"chat-view__empty")?gt.empty:-1}function al(e){return Yo(e)!==-1}function yn(e,t,n){if(!e||!t)return;let r=null;for(const i of e.children){if(i===t)continue;const s=Yo(i);if(s===-1||s>n){r=i;break}}const o=t.nextSibling===void 0?null:t.nextSibling;t.parentNode===e&&o===r||e.insertBefore(t,r)}function ld(e){const t=e&&e.transcript&&e.transcript.current;if(!(!t||typeof t.querySelector!="function"))for(const n of ad){const r=t.querySelector(n);!r||r.parentNode!==t||yn(t,r,Yo(r))}}function cd(){const e=document.createElement("select");e.className="input chat-view__setup",e.id="chatPromptSize",e.setAttribute("aria-label","Prompt size");for(const t of[{id:"very-small",label:"Very small — tool names only, no parameter schemas, smallest prompt"},{id:"average",label:"Average — full tools, recommended"},{id:"extensive",label:"Extensive — full tools + best-practice guidance"}]){const n=document.createElement("option");n.value=t.id,n.textContent=t.label,e.appendChild(n)}return e.addEventListener("change",()=>e._onChange&&e._onChange(e.value)),e}function Xo(e){const t=e.tools||{catalog:[],filter:null},n=document.createElement("div");n.className="chat-view__tools-card",n.dataset.toolsCard="1";const r=document.createElement("div");r.className="chat-view__tools-card-head";const o=document.createElement("span");o.className="chat-view__tools-card-title",o.textContent="Tools";const i=document.createElement("span");i.className="chat-view__tools-card-note",i.textContent=t.filter==null?"all on — tap to change":"applies next turn",r.appendChild(o),r.appendChild(i);const s=e._chatAuthOverrides||null;if(s&&(Object.keys(s.native||{}).length||s.mcp)){const y=document.createElement("span");y.className="chat-view__tools-card-scope",y.textContent="Off / Ask / Allow apply to this chat only",r.appendChild(y)}if(n.appendChild(r),!t.catalog.length){const y=document.createElement("div");return y.className="chat-view__tools-empty",y.textContent="No tools available. Add an MCP server in Settings → MCP to expose its tools here.",n.appendChild(y),n}const l=el(t.catalog,e.mcpServers||[],t.filter,e.usedTools||new Set),c=e._mcpStartBusyServerId;if(c)for(const y of l)y&&y.serverId===c&&(y.reloadBusy=!0);const a=e.toolAuth||{},d={shell:"shell",subagent:"subagent",task:"task",ask_user:"ask_user",report_progress:"report_progress",webpreview:"webpreview",restart_app:"restart_app",files:"file"};for(const y of l){const w=d[y.id];if(!w)continue;const N=a[w]||{mode:"ask"};y.control=u(tl,{tool:w,name:w,mode:N.mode,allowlist:N.allowlist,modes:w==="ask_user"?nl:Vr,namePrefix:"chat-auth",onClear:()=>{e._saveToolAuth&&e._saveToolAuth(w,null,[])},onPick:(O,P)=>{e._saveToolAuth&&e._saveToolAuth(w,O,P)}})}const p=e.mcpAuth||{mode:"ask",allowlist:[],servers:{},tools:{}};for(const y of l){if(!y.id.startsWith("mcp-"))continue;const w=y.id.slice(4);y.control=u(ol,{name:y.name,slug:w,servers:p.servers,shared:p,namePrefix:"chat-mcp",onClear:()=>{e._saveMcpAuth&&e._saveMcpAuth({servers:{[w]:null}})},onSave:N=>e._saveMcpAuth&&e._saveMcpAuth(N)})}const f=document.createElement("div");f.className="chat-view__tools-tree";const h=e._toolTreeCollapsed||null;function g(y,w){const N=l.find(O=>O.id===y);N&&e._toggleToolGroup&&e._toggleToolGroup(N.tools.map(O=>O.id),w)}function v(y,w,N){e._toggleTool&&e._toggleTool(w,N)}const b=y=>{e._toolTreeCollapsed=y};function k(y,w){if(y)for(const N of l)N&&N.serverId===y&&(N.reloadBusy=w)}async function _(y){const w=y&&y.serverId;if(!(!w||!e._startMcpServer)&&e._mcpStartBusyServerId!==w){k(w,!0),e._updateToolsCard&&e._updateToolsCard();try{await e._startMcpServer(w)}finally{k(w,!1),e._updateToolsCard&&e._updateToolsCard()}}}return qn(u(Qa,{groups:l,onToggleGroup:g,onToggleTool:v,collapsedByDefault:!0,initialCollapsed:h,onCollapseChange:b,onReloadServer:_}),f),n.appendChild(f),n}function ud(e,t){if(!e.transcript.current)return;const n=e.transcript.current.querySelector('[data-tools-card="1"]');n&&n.remove();const r=Xo(t);e.toolsCard.current=r,yn(e.transcript.current,r,gt.tools)}function ll(e){const t=e.agentFiles||{files:[],enabled:!0,explicit:!1,projectLocked:!1},n=document.createElement("div");n.className="chat-view__agent-files-card",n.dataset.agentFilesCard="1";const r=document.createElement("div");r.className="chat-view__agent-files-head";const o=document.createElement("span");o.className="chat-view__agent-files-title",o.textContent="Agent files";const i=document.createElement("span");if(i.className="chat-view__agent-files-note",t.projectLocked?i.textContent="off (locked by project setting) — enable in Settings → Project":t.explicit?i.textContent=t.enabled?"on — applies next turn":"off — applies next turn":i.textContent=t.enabled?"on (default) — tap to disable":"off (default) — tap to enable",r.appendChild(o),r.appendChild(i),n.appendChild(r),!t.files.length){const l=document.createElement("div");return l.className="chat-view__agent-files-empty",l.textContent="No agent files found at the project root.",n.appendChild(l),n}const s=document.createElement("div");s.className="chat-view__agent-files-list";for(const l of t.files){const c=document.createElement("label");c.className="chat-view__agent-files-row";const a=document.createElement("input");a.type="checkbox",a.className="checkbox checkbox--sm",a.checked=!!t.enabled,a.disabled=!!t.projectLocked,a.setAttribute("aria-label","Use agent file "+l),a.addEventListener("change",()=>e._toggleAgentFiles&&e._toggleAgentFiles(a.checked));const d=document.createElement("span");d.className="chat-view__agent-files-name",d.textContent=l,c.appendChild(a),c.appendChild(d),s.appendChild(c)}return n.appendChild(s),n}function cl(e){const t=e.skills||{items:[],enabled:!0,projectLocked:!1},n=document.createElement("div");n.className="chat-view__skills-card",n.dataset.skillsCard="1";const r=document.createElement("div");r.className="chat-view__skills-head";const o=document.createElement("span");o.className="chat-view__skills-title",o.textContent="Skills";const i=document.createElement("span");if(i.className="chat-view__skills-note",t.projectLocked?i.textContent="off (locked by project setting) — enable in Settings → Project":i.textContent=t.enabled?"on — tap a skill to scope it":"off — tap a skill to enable",r.appendChild(o),r.appendChild(i),n.appendChild(r),!t.items.length){const l=document.createElement("div");return l.className="chat-view__skills-empty",l.textContent="No skills found in .agents/skills.",n.appendChild(l),n}const s=document.createElement("div");s.className="chat-view__skills-list";for(const l of t.items){const c=!!l.disabled,a=!!l.chatDisabled,d=!!(t.enabled&&!c&&!a),p=!!t.projectLocked||c,f=document.createElement("label");f.className="chat-view__skills-row";const h=document.createElement("input");h.type="checkbox",h.className="checkbox checkbox--sm",h.checked=d,h.disabled=p,h.setAttribute("aria-label","Use skill "+(l.name||l.id)),h.addEventListener("change",()=>{e._toggleSkill&&e._toggleSkill(l.id,h.checked)});const g=document.createElement("span");g.className="chat-view__skills-body";const v=document.createElement("span");if(v.className="chat-view__skills-name",v.textContent=l.name||l.id,g.appendChild(v),l.description){const b=document.createElement("span");b.className="chat-view__skills-desc",b.textContent=l.description,g.appendChild(b)}if(c){const b=document.createElement("span");b.className="chat-view__skills-reason",b.textContent="Disabled in Settings → Project",g.appendChild(b)}f.appendChild(h),f.appendChild(g),s.appendChild(f)}return n.appendChild(s),n}function dd(e,t){if(!e.transcript.current)return;const n=e.transcript.current.querySelector('[data-agent-files-card="1"]');n&&n.remove();const r=ll(t);e.agentFilesCard.current=r,yn(e.transcript.current,r,gt.agentFiles)}function pd(e,t){if(!e.transcript.current)return;const n=e.transcript.current.querySelector('[data-skills-card="1"]');n&&n.remove();const r=cl(t);e.skillsCard.current=r,yn(e.transcript.current,r,gt.skills)}function fd(e,t){if(!e.agentFilesCard.current||!e.agentFilesCard.current.parentNode)return;const n=ll(t);e.agentFilesCard.current.parentNode.replaceChild(n,e.agentFilesCard.current),e.agentFilesCard.current=n}function ul(e,t){if(!e.skillsCard.current||!e.skillsCard.current.parentNode)return;const n=cl(t);e.skillsCard.current.parentNode.replaceChild(n,e.skillsCard.current),e.skillsCard.current=n}async function hd(e,t,n,r,o){const i=t.agentFiles||{files:[]};t.agentFiles={files:i.files,enabled:e,explicit:!0,projectLocked:i.projectLocked},fd(n,t),await r({agentFiles:e}),typeof o=="function"&&await o()}async function md(e,t,n,r,o){const i=t.skills||{items:[],enabled:!0,projectLocked:!1},s=Array.isArray(i.items)?i.items:[];t.skills=Object.assign({},i,{enabled:e,items:s.map(c=>Object.assign({},c,{chatDisabled:c.disabled?!!c.chatDisabled:!e}))}),ul(n,t);const l=s.filter(c=>!c.disabled);await r({skills:e,disabledSkills:e||!l.length?null:l.map(c=>c.id)}),typeof o=="function"&&await o()}async function gd(e,t,n,r,o,i){const s=n.skills||{items:[],enabled:!0,projectLocked:!1},l=Array.isArray(s.items)?s.items:[],c=l.filter(h=>!h.disabled),a=s.enabled?new Set(c.filter(h=>!h.chatDisabled).map(h=>h.id)):new Set;t?a.add(e):a.delete(e);const d=c.filter(h=>!a.has(h.id)).map(h=>h.id),p=a.size>0,f={skills:p,disabledSkills:p?d.length?d:null:d};n.skills=Object.assign({},s,{enabled:p,items:l.map(h=>Object.assign({},h,{chatDisabled:h.disabled?!!h.chatDisabled:!a.has(h.id)}))}),ul(r,n),await o(f),typeof i=="function"&&await i()}function dl(e,t){if(!e.toolsCard.current||!e.toolsCard.current.parentNode)return;const n=Xo(t);e.toolsCard.current.parentNode.replaceChild(n,e.toolsCard.current),e.toolsCard.current=n}async function _d(e,t,n,r,o){const i=n.tools||{catalog:[],filter:null},s=i.catalog||[];if(!s.find(a=>a&&a.name===e))return;const l=s.map(a=>a.name);let c;if(i.filter==null)c=l.filter(a=>a!==e),t&&(c=l.slice());else{const a=new Set(i.filter);t?a.add(e):a.delete(e),a.size===s.length?c=null:c=Array.from(a)}n.tools={catalog:s,filter:c},dl(r,n),await o({tools:c??null})}function yd(e){if(!e||!e.transcript||!e.transcript.current)return;const t=".tool-card--authorization[data-auth-call-id], .tool-card--ask-user[data-auth-call-id]";for(const n of e.transcript.current.querySelectorAll(t))n.remove()}function vd(e,t,n){if(!e||t.tool!=="subagent")return null;const r=new Map;for(const d of e.models||[])!d||!d.id||!d.provider||r.set(d.provider+"\0"+d.id,{id:d.id,provider:d.provider,label:d.label||"",thinking:d.thinking||void 0});const o=e.liveByProvider||{};for(const d of Object.keys(o))for(const p of o[d]||[]){if(!p||!p.id)continue;const f=d+"\0"+p.id;r.has(f)||r.set(f,{id:p.id,provider:d,label:p.label||"",thinking:p.thinking||void 0})}const i=Array.from(r.values()).sort((d,p)=>(d.provider+d.id).localeCompare(p.provider+p.id));if(!i.length)return null;const s=e.chat||{};let l=s.providerId&&s.modelId?{providerId:s.providerId,modelId:s.modelId}:null;const c=document.createElement("div");c.className="tool-card__auth-model";const a=document.createElement("div");return a.className="tool-card__auth-model-field",qn(u(sd,{models:i,initialValue:l,projectDir:n,onChange:d=>{l=d}}),a),c.appendChild(a),c._selected=()=>l,c}function Nt(e,t,n,r,o,i){return new Promise(s=>{if(!r.transcript.current)return s("deny");const l=document.createElement("div");l.className="tool-card tool-card--authorization",e.callId&&(l.dataset.authCallId=e.callId);const c=document.createElement("div");c.className="tool-card__head";const a=document.createElement("span");a.className="tool-card__chev",a.setAttribute("aria-hidden","true"),a.innerHTML='<svg viewBox="0 0 24 24" width="12" height="12" fill="currentColor"><path d="M9 5.5 15.5 12 9 18.5l1.4 1.4L18.3 12l-7.9-7.9L9 5.5Z"/></svg>';const d=document.createElement("div");d.className="tool-card__name",d.textContent=e.tool||"tool";const p=document.createElement("div");p.className="tool-card__role",p.textContent="authorization required",c.appendChild(a),c.appendChild(d),c.appendChild(p);const f=document.createElement("pre");f.className="tool-card__body",f.textContent=[e.cmd||"",e.projectDir||"",e.timeoutMs?"timeout: "+e.timeoutMs+" ms":""].filter(Boolean).join(`
|
|
33
|
+
`);const h=vd(i,e,t),g=document.createElement("div");g.className="tool-card__actions";const v=[];for(const[_,y,w]of[["allow-once","Allow once","1"],["allow-session","Allow session","2"],["allow-always","Always allow","3"],["deny","Deny","4"]]){const N=document.createElement("button");N.type="button",N.className="btn"+(_==="deny"?" btn--danger":""),N.textContent=y+" ["+w+"]",N.setAttribute("aria-label",y+" ("+w+")"),N.dataset.shortcut=w,N.addEventListener("click",async()=>{for(const re of g.querySelectorAll("button"))re.disabled=!0;const O={projectDir:t,chatId:n,callId:e.callId,decision:_},P=h&&typeof h._selected=="function"?h._selected():null;if(P&&_!=="deny"){const re={};P.modelOverride&&P.modelOverride.providerId&&P.modelOverride.modelId&&(re.modelOverride={providerId:P.modelOverride.providerId,modelId:P.modelOverride.modelId}),typeof P.thinkingLevel=="string"&&P.thinkingLevel&&(re.thinkingLevel=P.thinkingLevel),Object.keys(re).length&&(O.payload=re)}const Y=await H("/api/tools/authorization/decision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});if(Y.status!==200){for(const re of g.querySelectorAll("button"))re.disabled=!1;r.status.current&&(r.status.current.textContent="authorization failed: HTTP "+Y.status,r.status.current.dataset.state="error");return}l.remove(),_!=="deny"&&typeof o=="function"&&await o(),s(_)}),g.appendChild(N),v.push(N)}function b(_){if(!_)return!1;const y=String(_.tagName||"").toLowerCase();return y==="input"||y==="textarea"||y==="select"||_.isContentEditable===!0}function k(_){if(b(_.target))return;if(_.key==="Escape"&&v[3]){v[3].click();return}const y=v.find(w=>w.dataset.shortcut===_.key);y&&y.click()}l.addEventListener("keydown",k),v[0]&&setTimeout(()=>v[0].focus(),100),l.appendChild(c),l.appendChild(f),h&&l.appendChild(h),l.appendChild(g),r.transcript.current.appendChild(l),Ye(r,!0);try{l.scrollIntoView({behavior:"smooth",block:"center"})}catch{}})}function Rr(e,t,n,r,o){if(!r.transcript.current)return;const i=document.createElement("div");i.className="tool-card tool-card--ask-user",i.dataset.toolId=e.callId||"ask_"+Math.random().toString(36).slice(2,10),e.callId&&(i.dataset.authCallId=e.callId);const s=document.createElement("div");s.className="tool-card__head";const l=document.createElement("span");l.className="tool-card__chev",l.setAttribute("aria-hidden","true"),l.innerHTML='<svg viewBox="0 0 24 24" width="12" height="12" fill="currentColor"><path d="M9 5.5 15.5 12 9 18.5l1.4 1.4L18.3 12l-7.9-7.9L9 5.5Z"/></svg>',s.appendChild(l);const c=document.createElement("span");c.className="tool-card__role",c.textContent="the model is asking",s.appendChild(c);const a=document.createElement("span");a.className="tool-card__name",a.textContent="Question",s.appendChild(a);const d=document.createElement("span");d.className="tool-card__pill tool-card__pill--busy",d.textContent="waiting",s.appendChild(d),i.appendChild(s);const p=document.createElement("div");p.className="tool-card__body tool-card__ask-body";const f=document.createElement("p");f.className="tool-card__ask-question",f.textContent=e.question||"(no question)",p.appendChild(f);const h=Array.isArray(e.presets)?e.presets:[];if(h.length){const re=document.createElement("div");re.className="tool-card__ask-presets";for(const z of h){const I=document.createElement("button");I.type="button",I.className="tool-card__ask-preset-chip",I.textContent=z,I.addEventListener("click",async()=>{for(const Z of i.querySelectorAll("button"))Z.disabled=!0;const D={choice:z,extra:""},V=await H("/api/tools/authorization/decision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:t,chatId:n,callId:e.callId,decision:"allow-once",payload:D})});if(V.status!==200){for(const Z of i.querySelectorAll("button"))Z.disabled=!1;o("ask_user failed: HTTP "+V.status,"error");return}i.remove(),o("answer sent","success")}),re.appendChild(I)}p.appendChild(re)}const g=document.createElement("div");g.className="tool-card__ask-options",p.appendChild(g);const v=Array.isArray(e.options)?e.options:[],b=!!e.multiSelect;let k=b?new Set:null,_=null;function y(){for(const re of g.querySelectorAll(".tool-card__ask-option")){const z=re.dataset.value||"",I=b?k.has(z):z===(_&&_.value);re.classList.toggle("is-selected",!!I),re.setAttribute("aria-checked",I?"true":"false")}}for(let re=0;re<v.length;re++){const z=v[re]||{},I=document.createElement("button");I.type="button",I.className="tool-card__ask-option",I.dataset.value=String(z.value||""),I.setAttribute("role",b?"checkbox":"radio"),I.setAttribute("aria-checked","false");const D=document.createElement("span");if(D.className="tool-card__ask-option-label",D.textContent=z.label||z.value||"option "+(re+1),I.appendChild(D),z.description){const V=document.createElement("span");V.className="tool-card__ask-option-desc",V.textContent=z.description,I.appendChild(V)}I.addEventListener("click",()=>{b?k.has(I.dataset.value)?k.delete(I.dataset.value):k.add(I.dataset.value):_={value:I.dataset.value,label:z.label||I.dataset.value},y()}),I.addEventListener("keydown",V=>{(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),I.click())}),g.appendChild(I)}const w=document.createElement("label");w.className="tool-card__ask-extra-label",w.textContent="Add an extra answer (always optional)",p.appendChild(w);const N=document.createElement("textarea");N.className="input tool-card__ask-extra",N.rows=2,N.spellcheck=!1,N.maxLength=1e3,N.placeholder="Add context, a follow-up, or just a note for the model.",p.appendChild(N);const O=document.createElement("div");O.className="tool-card__actions";const P=document.createElement("button");P.type="button",P.className="btn btn--primary",P.textContent="Send answer",P.addEventListener("click",async()=>{if(!(b?Array.from(k):_?[_.value]:[]).length){for(const V of O.querySelectorAll("button"))V.disabled=!0;const D=await H("/api/tools/authorization/decision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:t,chatId:n,callId:e.callId,decision:"deny"})});if(D.status!==200){for(const V of O.querySelectorAll("button"))V.disabled=!1;o("ask_user failed: HTTP "+D.status,"error");return}i.remove(),o("question dismissed","success");return}for(const D of O.querySelectorAll("button"))D.disabled=!0;const z={choice:b?Array.from(k):_?_.value:"",extra:N.value||""},I=await H("/api/tools/authorization/decision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:t,chatId:n,callId:e.callId,decision:"allow-once",payload:z})});if(I.status!==200){for(const D of O.querySelectorAll("button"))D.disabled=!1;o("ask_user failed: HTTP "+I.status,"error");return}i.remove(),o("answer sent","success")}),O.appendChild(P);const Y=document.createElement("button");Y.type="button",Y.className="btn",Y.textContent="Dismiss",Y.addEventListener("click",async()=>{for(const z of O.querySelectorAll("button"))z.disabled=!0;const re=await H("/api/tools/authorization/decision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:t,chatId:n,callId:e.callId,decision:"deny"})});if(re.status!==200){for(const z of O.querySelectorAll("button"))z.disabled=!1;o("ask_user failed: HTTP "+re.status,"error");return}i.remove(),o("question dismissed","success")}),O.appendChild(Y),p.appendChild(O),i.appendChild(p),r.transcript.current.appendChild(i),Ye(r,!0);try{i.scrollIntoView({behavior:"smooth",block:"center"})}catch{}}async function bd(e,t,n,r,o){const i=n.tools||{catalog:[],filter:null},s=i.catalog||[],l=s.map(d=>d&&d.name).filter(Boolean),c=new Set((e||[]).filter(d=>l.includes(d)));if(!c.size)return;let a;if(i.filter==null)a=t?l.slice():l.filter(d=>!c.has(d));else{const d=new Set(i.filter);if(t)for(const p of c)d.add(p);else for(const p of c)d.delete(p);a=d.size===s.length?null:Array.from(d)}n.tools={catalog:s,filter:a},dl(r,n),await o({tools:a??null})}function Qo(e){const t=e&&e.totalCost;return!t||!Number.isFinite(t.total)||!Number.isInteger(e.nextSeq)||e.nextSeq<0?null:{nextSeq:e.nextSeq,total:t.total,known:!!t.known}}function wd(e,t,n){const r=Number(n);if(!Number.isFinite(r)||r<=0)return null;const o=t||null,i=e&&e.snapshot===o&&Number.isFinite(e.total)?e.total:0;return{snapshot:o,total:i+r}}function Cd(e,t,n,r){let o=null,i=t?t.total:0,s=t?t.known:!1;function l(c){c&&c.known&&Number.isFinite(c.total)&&(i+=c.total,s=!0)}Number.isFinite(r)&&r>0&&(i+=r,s=!0);for(const c of e||[])!c||c.role!=="assistant"||(c.usage&&typeof c.usage.promptTokens=="number"&&(o=c.usage.promptTokens),(!t||!Number.isInteger(c.seq)||c.seq>=t.nextSeq)&&l(c.cost));return n&&(n.usage&&typeof n.usage.promptTokens=="number"&&(o=n.usage.promptTokens),l(n.cost),l(n.liveCost)),{latestContext:o,totalCost:i,hasKnownCost:s}}function ne(e,t,n){e.status.current&&(e.status.current.textContent=t,n?e.status.current.dataset.state=n:delete e.status.current.dataset.state)}function kd(e){const t=e.chat;if(!t||!t.modelId||!t.providerId)return null;const r=(e.liveByProvider||{})[t.providerId]||[];for(const o of r)if(o&&o.id===t.modelId&&typeof o.contextWindow=="number"&&o.contextWindow>0)return o.contextWindow;for(const o of e.models||[])if(o&&o.provider===t.providerId&&o.id===t.modelId&&typeof o.contextWindow=="number"&&o.contextWindow>0)return o.contextWindow;return null}function wn(e,t,n){e.providerCredit=t||null,ot(e,null,n)}async function lo(e,t){const n=e.chat&&e.chat.providerId?e.chat.providerId:"";if(!n)return wn(e,null,t);try{const r=await H("/api/ai/provider-credit?provider="+encodeURIComponent(n));if(r.status!==200||!r.body||!r.body.supported||typeof r.body.remaining!="number")return wn(e,null,t);const o=r.body.label||"Balance";wn(e,o+" "+Ht(r.body.remaining),t)}catch{wn(e,null,t)}}function ot(e,t,n){const r=n.usageSummary.current;if(!r)return;const{latestContext:o,totalCost:i,hasKnownCost:s}=Cd(e.messages,e.costSnapshot,t,e.attributedCost);r.innerHTML="";const l=(c,a,d)=>{const p=document.createElement("span");d&&d.cls&&(p.className=d.cls);const f=document.createElement("span");f.className="chat-view__usage-summary-label",f.textContent=c;const h=document.createElement("span");return h.className="chat-view__usage-summary-value",h.textContent=a,p.appendChild(f),p.appendChild(h),p};if(r.appendChild(l("Context",o==null?"--":nn(o))),r.appendChild(l("Total",s?Ht(i):"--")),e.providerCredit){const c=e.providerCredit,a=c.indexOf(" "),d=a>0?c.slice(0,a):c,p=a>0?c.slice(a+1):"",f=l(d,p,{cls:"chat-view__usage-summary-credit"});r.appendChild(f)}}function gr(e,t,n){e.innerHTML="",e.hidden=!1;const r=t.modelId||"",o=t.usage||{},i=t.cost||null,s=[];if(r&&s.push(r),typeof o.promptTokens=="number"){let c="context "+nn(o.promptTokens);const a=kd(n);if(a){const d=Math.round(o.promptTokens/a*100);c+="/"+nn(a)+" ("+d+"%)"}s.push(c)}if(typeof o.completionTokens=="number"&&s.push("output "+nn(o.completionTokens)),typeof o.cacheReadTokens=="number"&&o.cacheReadTokens>0||typeof o.cacheCreationTokens=="number"&&o.cacheCreationTokens>0){const c=[];o.cacheReadTokens>0&&c.push(nn(o.cacheReadTokens)+" read"),o.cacheCreationTokens>0&&c.push(nn(o.cacheCreationTokens)+" written"),s.push("cache "+c.join(" · "))}i&&i.known?s.push("cost "+Ht(i.total)):i&&i.known===!1&&s.push("--");let l=t.liveRate;l==null&&t.streamingMs&&typeof o.completionTokens=="number"&&(l=t.streamingMs>0?o.completionTokens/t.streamingMs*1e3:0),l!=null&&s.push({kind:"rate",label:vu(l)});for(let c=0;c<s.length;c++){if(c>0){const p=document.createElement("span");p.className="chat-msg__meta-sep",p.textContent="·",e.appendChild(p)}const a=s[c],d=document.createElement("span");typeof a=="string"?(d.textContent=a,c===0?d.dataset.token="model":/^context /.test(a)?d.dataset.token="context":/^output /.test(a)?d.dataset.token="output":/^cost /.test(a)&&(d.dataset.token="cost")):a&&a.kind==="rate"&&(d.textContent=a.label,d.dataset.token="rate"),e.appendChild(d)}}function xo(e,t){if(!e.chatMeta.current)return;const n=t.chat;n&&(e.chatMeta.current.textContent=n.trace?"trace on":"")}function cs(e){const t=e.chat;return t&&["very-small","average","extensive"].indexOf(t.promptSize)>=0?t.promptSize:"average"}async function pl(e,t,n){const{projectDir:r,chatId:o}=t.props;if(!r||!o)return;const i=await H("/api/chats/"+encodeURIComponent(o),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(Object.assign({projectDir:r},e||{}))});return i.status!==200?(n.status.current&&(n.status.current.textContent="HTTP "+i.status),!1):(t.chat=i.body.chat,xo(n,t),t._onChatChanged&&t._onChatChanged(),!0)}async function _r(e,t){const{projectDir:n,chatId:r}=e.props;if(!n||!r)return;const o=await H("/api/chats/"+encodeURIComponent(r)+"/system-prompt?projectDir="+encodeURIComponent(n));e.systemPrompt=o.status===200?o.body:null,ml(t,e.systemPrompt)}async function Sd(e,t){const{projectDir:n,chatId:r}=e.props;if(!(!n||!r))try{const o=await H("/api/chats/"+encodeURIComponent(r)+"?projectDir="+encodeURIComponent(n));o.status===200&&o.body&&o.body.chat&&(e.chat=o.body.chat,t.chatName.current&&(t.chatName.current.textContent=e.chat.title||r))}catch{}}function Td(e,t,n){["very-small","average","extensive"].indexOf(e)<0||(Eo(e,n),pl({promptSize:e},t,n).then(()=>{_r(t,n)}))}function Eo(e,t){const n=t.setupCard.current;if(!n)return;const r=n.querySelectorAll("option");for(const o of r)o.value===e?o.setAttribute("selected",""):o.removeAttribute("selected")}function us(e,t){const n=!e.messages||e.messages.length===0,r=t.setupCard.current;n||(r&&r.parentNode&&r.parentNode.removeChild(r),t.setupCard.current=null)}function fl(e){return!!e&&e.role==="system"&&/^⚠(?:\s|$)/.test(String(e.content||""))}function Ad(e,t){if(!Array.isArray(e)||!fl(t))return null;const n=e.lastIndexOf(t);if(n<0)return null;for(let r=n-1;r>=0;r--){const o=e[r];if(!(!o||o.role!=="user"))return{content:o.content||"",attachments:Array.isArray(o.attachments)?o.attachments:[]}}return null}function xd(e){return String(e??"").trim()||"agent"}function hl(e,t,n){const r=document.createElement("div");r.className="chat-msg chat-msg--system"+(t?" "+t:"");const o=document.createElement("div");o.className="chat-msg__head";const i=document.createElement("div");i.className="chat-msg__role",i.textContent=n||"system";const s=document.createElement("span");s.className="chat-msg__ts",s.hidden=!0,o.appendChild(i),o.appendChild(s);const l=document.createElement("div");l.className="chat-msg__body";const c=String(e||"").split(/\r?\n/).filter(f=>f.length).length,a=document.createElement("details");a.className="chat-msg__system-details";const d=document.createElement("summary");d.textContent="System prompt · "+c+" line"+(c===1?"":"s");const p=document.createElement("pre");return p.className="chat-msg__system-body",p.textContent=e||"",a.appendChild(d),a.appendChild(p),l.appendChild(a),r.appendChild(o),r.appendChild(l),r}function ml(e,t){if(!e.transcript.current)return;const n=e.transcript.current.querySelector('[data-sys-prompt="1"]');if(n&&n.remove(),!t||!t.text)return;const r=hl(t.text);r.dataset.sysPrompt="1",yn(e.transcript.current,r,gt.sysPrompt),e._cardSigs=e._cardSigs||{},e._cardSigs.sys=String(t&&t.text||"")}function Hr(e,t){const n=e.transcript.current;if(!n)return;const r=e._insertAnchor;r&&r.parentNode===n?n.insertBefore(t,r):n.appendChild(t),e._lastInsertedRow=t}function Ed(e,t){const n=document.createElement("div");n.className="chat-msg__attachments";for(const r of t){if(!r||!r.dataUrl)continue;const o=document.createElement("img");o.className="chat-msg__attachment-img",o.src=r.dataUrl,o.alt=r.name||"attached image",n.appendChild(o)}e.appendChild(n)}function Id(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t.text=="string"?t.text:"").filter(t=>t).join(`
|
|
34
|
+
|
|
35
|
+
`):e&&typeof e=="object"?JSON.stringify(e,null,2):""}function vn(e,t,n,r){if(e.innerHTML="",n){const i=document.createElement("details");i.className="chat-msg__reasoning",r||(i.open=!0);const s=document.createElement("summary");s.textContent=r?"Thinking":"Thinking…";const l=document.createElement("div");l.className="chat-msg__reasoning-body"+(r?"":" chat-msg__reasoning-body--raw"),r?l.innerHTML=ns(n):l.textContent=n,i.appendChild(s),i.appendChild(l),e.appendChild(i)}const o=document.createElement("div");o.className="chat-msg__answer",r?o.innerHTML=ns(t||""):o.textContent=t||"",e.appendChild(o)}const ds='<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="11" height="12" rx="2"/><path d="M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"/></svg>',Pd='<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>',Nd='<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg>';function Rd(e){const t=document.createElement("button");return t.className="chat-msg__copy tap-target",t.type="button",t.innerHTML=ds,t.setAttribute("aria-label","Copy message"),t.title="Copy message",t.addEventListener("click",async()=>{const n=await Gu(Ku(e()));t.innerHTML=n?Pd:Nd,t.classList.toggle("is-copied",n),t.classList.toggle("is-failed",!n),t.setAttribute("aria-label",n?"Copied message":"Copy failed"),t.title=n?"Copied message":"Copy failed",t._copyReset&&clearTimeout(t._copyReset),t._copyReset=setTimeout(()=>{t._copyReset=null,t.innerHTML=ds,t.classList.remove("is-copied","is-failed"),t.setAttribute("aria-label","Copy message"),t.title="Copy message"},1400)}),t}function Kn(e,t,n,r){if(!n.transcript.current)return;const o=n.transcript.current.querySelector(".chat-view__empty");o&&o.remove();const i=document.createElement("div");i.className="chat-msg chat-msg--"+e.role,t&&(i.dataset.live="1");const s=document.createElement("div");if(s.className="chat-msg__role",e.role==="assistant"){const d=e.modelId||r.chat&&r.chat.modelId||"assistant";s.textContent=d}else s.textContent=e.role;const l=document.createElement("div");l.className="chat-msg__body",e.role==="assistant"?vn(l,e.content||"",e.reasoning||"",!0):(l.textContent=e.content||"",e.role==="user"&&Array.isArray(e.attachments)&&e.attachments.length&&Ed(l,e.attachments));const c=document.createElement("div");c.className="chat-msg__head";const a=document.createElement("span");if(a.className="chat-msg__ts",e.ts?a.textContent=new Date(e.ts).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):a.hidden=!0,c.appendChild(s),c.appendChild(a),i.appendChild(c),i.appendChild(l),e.role==="user"||e.role==="assistant"){const d=document.createElement("div");d.className="chat-msg__actions",d.appendChild(Rd(()=>t?{role:e.role,content:i._content||"",reasoning:i._reasoning||""}:e)),i.appendChild(d)}if(Hr(n,i),e.role==="assistant"&&t&&(i._body=l,i._content=e.content||"",i._reasoning=e.reasoning||""),e.role==="assistant"){const d=document.createElement("div");d.className="chat-msg__meta",t?d.hidden=!0:e.usage||e.cost||e.modelId?gr(d,e,r):d.hidden=!0,i.appendChild(d)}Ye(n,!0)}function gl(e){const t=e&&e._body;return t&&(e._streaming||(vn(t,e._content||"",e._reasoning||"",!1),e._streaming=!0),t)}function Ld(e,t){if(!e||t==null)return;let n=e.querySelector(".chat-msg__answer");n||(n=document.createElement("div"),n.className="chat-msg__answer",e.appendChild(n)),n.appendChild(document.createTextNode(t))}function Md(e,t){if(!e||t==null)return;let n=e.querySelector(".chat-msg__reasoning-body");if(!n){const r=e._owner||null;return vn(e,r?r._content:"",r?r._reasoning:t,!1)}n.appendChild(document.createTextNode(t))}function Od(e,t,n){if(!t.transcript.current)return;let r=t.transcript.current.querySelector('[data-live="1"]');if(!r){const o=n.chat&&n.chat.modelId||"";Kn({role:"assistant",content:"",reasoning:"",ts:new Date().toISOString(),modelId:o},!0,t,n),r=t.transcript.current.querySelector('[data-live="1"]')}if(r){const o=gl(r);o&&(o._owner=r),r._content=(r._content||"")+e,Ld(o,e),Ye(t,!1)}}function jd(e,t,n){if(!t.transcript.current)return;let r=t.transcript.current.querySelector('[data-live="1"]');if(!r){const o=n.chat&&n.chat.modelId||"";Kn({role:"assistant",content:"",reasoning:"",ts:new Date().toISOString(),modelId:o},!0,t,n),r=t.transcript.current.querySelector('[data-live="1"]')}if(r){const o=gl(r);o&&(o._owner=r),r._reasoning=(r._reasoning||"")+e,Md(o,e),Ye(t,!1)}}function yr(e,t,n,r){if(!t.transcript.current)return;const o=t.transcript.current.querySelector(".chat-view__empty");o&&o.remove();const i=document.createElement("div");i.className="chat-msg chat-msg--system is-error";const s=document.createElement("div");s.className="chat-msg__head";const l=document.createElement("div");l.className="chat-msg__role",l.textContent="error";const c=document.createElement("span");c.className="chat-msg__ts",c.textContent=new Date(r&&r.ts||Date.now()).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),s.appendChild(l),s.appendChild(c);const a=document.createElement("div");if(a.className="chat-msg__body",a.textContent=e,i.appendChild(s),i.appendChild(a),r&&typeof r.onRetry=="function"){const d=document.createElement("div");d.className="chat-msg__actions";const p=document.createElement("button");p.className="btn btn--small chat-msg__retry",p.type="button",p.textContent="Retry",p.addEventListener("click",()=>r.onRetry()),d.appendChild(p),i.appendChild(d)}Hr(t,i),n&&(!r||r.persist!==!1)&&(n.messages=n.messages.concat([{role:"system",content:e,ts:new Date().toISOString()}])),Ye(t,!0)}const ps={read_file:"Read",list_files:"Listed",search_files:"Searched",edit_file:"Edited",write_file:"Wrote",shell:"Ran",subagent:"Subagent",ask_user:"Question",restart_app:"Restarted"};function _l(e){const t=Ge(e);if(ps[t])return ps[t];if(t&&t.startsWith("mcp__")){const n=t.split("__").filter(Boolean);return n[n.length-1]||t}return t||"tool"}function yl(e,t){const n=String(e||"").replace(/\s+/g," ").trim();return!n||n.length<=t?n:n.slice(0,Math.max(0,t-1)).trimEnd()+"…"}function ei(e,t,n,r){const o=document.createElement("div");o.className="tool-card__subagent-tool",t&&(o.dataset.nestedToolId=String(t));const i=document.createElement("span");if(i.className="tool-card__name",i.textContent=_l(e),o.appendChild(i),n){const l=document.createElement("pre");l.className="tool-card__args",l.textContent=yl(n,Ba),l.textContent!==n&&(l.title=n),o.appendChild(l)}const s=document.createElement("span");return s.className="tool-card__pill tool-card__pill--busy",s.textContent="running",o.appendChild(s),r&&typeof r=="object"&&(o._toolArgs=r),o}function Io(e,t,n,r,o){if(!e)return null;const i=Ge(t),s=Wt(n,i),l=typeof o=="boolean"?o:!(s&&s.error),c=e.querySelector(".tool-card__pill");c&&(c.className="tool-card__pill "+(l?"tool-card__pill--ok":"tool-card__pill--err"),c.textContent=l?"ok":"error");const a=l||Fa(t,s,l)?Ha(t,s):null;if(a){let p=e.querySelector(".tool-card__result-summary");p||(p=document.createElement("span"),p.className="tool-card__result-summary",e.insertBefore(p,c||null)),p.textContent=a}const d=e.querySelector(".tool-card__subagent-preview");return d&&d.remove(),Wd(e,t,n,r),s}function ti(e,t,n,r,o,i){const s=document.createElement("div");s.className="tool-card__head",s.setAttribute("role","button");const l=document.createElement("span");l.className="tool-card__chev",l.setAttribute("aria-hidden","true"),l.innerHTML='<svg viewBox="0 0 24 24" width="12" height="12" fill="currentColor"><path d="M9 5.5 15.5 12 9 18.5l1.4 1.4L18.3 12l-7.9-7.9L9 5.5Z"/></svg>';const c=document.createElement("span");if(c.className="tool-card__name",c.textContent=_l(e),Nr(e)){const a=i&&typeof i=="object"?i.agent:null;if(String(a??"").trim()){const d=document.createElement("span");return d.className="tool-card__agent",d.textContent=String(a).trim(),d.title="Agent",s.appendChild(l),s.appendChild(c),s.appendChild(d),fs(s,e,t,n,r,o)}}return s.appendChild(l),s.appendChild(c),fs(s,e,t,n,r,o)}function fs(e,t,n,r,o,i){const s=n==null?"":typeof n=="string"?n:Hn(n,t),l=document.createElement("span");if(l.className="tool-card__pill "+r,l.textContent=o,s){const c=document.createElement("pre");c.className="tool-card__args",c.textContent=yl(s,Ba),c.textContent!==s&&(c.title=s),e.appendChild(c)}if(i){const c=document.createElement("span");c.className="tool-card__result-summary",c.textContent=i,e.appendChild(c)}return e.appendChild(l),e.addEventListener("click",()=>{const c=e.closest(".tool-card");c&&(c.classList.toggle("is-expanded"),c._userCollapsed=!c.classList.contains("is-expanded"),c.classList.contains("is-expanded")&&typeof c._lazyBody=="function"&&c._lazyBody())}),e}function Dd(e,t,n,r){Array.isArray(e._anonToolCalls)||(e._anonToolCalls=[]),e._anonToolCalls.push({id:t,name:n,card:r})}function Bd(e,t){const r=(Array.isArray(e._anonToolCalls)?e._anonToolCalls:[]).filter(l=>l&&l.card&&l.card.isConnected);e._anonToolCalls=r;const o=Ge(t);let i=r.findIndex(l=>l.name===o);i===-1&&(i=0);const s=r[i];return s?(r.splice(i,1),s.id):null}function Xt(e,t,n){if(!t.transcript.current)return;const r=t.transcript.current.querySelector(".chat-view__empty");r&&r.remove();const o=e.id||"call_"+Math.random().toString(36).slice(2,10);if(e.id)for(const s of t.transcript.current.querySelectorAll(oi))s.dataset.authCallId===String(e.id)&&s.remove();const i=document.createElement("div");if(i.className="tool-card tool-card--call",i.dataset.toolId=o,i.dataset.toolName=Ge(e.name),i._toolArgs=e.args&&typeof e.args=="object"?e.args:null,i.appendChild(ti(e.name,e.args,"tool-card__pill--busy","running",null,e.args)),Nr(e.name)){i.classList.add("tool-card--subagent"),i.classList.add("is-expanded");const s=document.createElement("div");s.className="tool-card__body";const l=document.createElement("div");l.className="tool-card__subagent-live";const c=document.createElement("div");c.className="tool-card__subagent-live-hint",c.innerHTML='<span class="tool-card__spinner" aria-hidden="true"></span>Subagent is working…',l.appendChild(c),s.appendChild(l),i.appendChild(s)}else if(Ge(e.name)==="shell"){const s=document.createElement("div");s.className="tool-card__body";const l=document.createElement("div");l.className="tool-card__shell-live";const c=document.createElement("div");c.className="tool-card__shell-live-hint",c.textContent=n?"Waiting for results…":"Running…";const a=document.createElement("pre");a.className="tool-card__shell-live-pre",l.appendChild(c),l.appendChild(a),s.appendChild(l),i.appendChild(s),n||i.classList.add("is-expanded")}return Hr(t,i),Ye(t,!0),e.id||Dd(t,o,Ge(e.name),i),i}function ni(e,t){if(!t.transcript.current||!e)return!1;const n=e.id?t.transcript.current.querySelector('[data-tool-id="'+kt(String(e.id))+'"]'):null;if(!n)return!1;const r=n.querySelector(".tool-card__shell-live-pre");if(!r)return!1;!n.classList.contains("is-expanded")&&!n._userCollapsed&&n.classList.add("is-expanded");const o=n.querySelector(".tool-card__shell-live-hint");if(o&&o.textContent!=="Running…"&&(o.textContent="Running…"),e.stream==="stderr"){r.dataset.hasStderr="1";const i=`
|
|
36
|
+
── stderr ──
|
|
37
|
+
`;r.textContent.includes(i)||(r.textContent+=i),r.textContent+=String(e.delta||"")}else r.textContent+=String(e.delta||"");return An(r),Ye(t,!1),!0}function Fd(e,t){if(!e.transcript.current)return null;if(t){const r=e.transcript.current.querySelector('[data-tool-id="'+kt(t)+'"]');if(r)return r}const n=e.transcript.current.querySelectorAll(".tool-card--subagent");return n.length?n[n.length-1]:null}function qd(e){if(!e)return null;let t=e.querySelector(".tool-card__body");t||(t=document.createElement("div"),t.className="tool-card__body",e.appendChild(t));let n=e.querySelector(".tool-card__subagent-live");return n||(n=document.createElement("div"),n.className="tool-card__subagent-live",t.appendChild(n)),n}function vl(e,t,n){if(!n.transcript.current)return!1;const r=Fd(n,t&&t.parentCallId);if(!r)return!1;const o=qd(r);if(!o)return!1;if(e.eventName==="message"&&typeof t.delta=="string"){o._text=(o._text||"")+t.delta;let i=o.querySelector(".tool-card__subagent-live-msg");if(!i){i=document.createElement("div"),i.className="chat-msg chat-msg--assistant tool-card__subagent-msg tool-card__subagent-live-msg";const s=document.createElement("div");s.className="chat-msg__body",i.appendChild(s),o.appendChild(i)}return vn(i.querySelector(".chat-msg__body"),o._text,"",!1),An(o),Ye(n,!1),!0}if(e.eventName==="shell_output"&&t&&t.id){const i=o.querySelector('[data-nested-tool-id="'+kt(String(t.id))+'"]');if(i){let s=i.querySelector(".tool-card__shell-live-pre");if(s||(s=document.createElement("pre"),s.className="tool-card__shell-live-pre",i.appendChild(s)),t.stream==="stderr"){const l=`
|
|
38
|
+
── stderr ──
|
|
39
|
+
`;s.textContent.includes(l)||(s.textContent+=l),s.textContent+=String(t.delta||"")}else s.textContent+=String(t.delta||"");An(s),Ye(n,!1)}return!0}if(e.eventName==="tool_call"){const i=o.querySelector(".tool-card__subagent-live-hint");i&&i.remove();const s=ei(t.name,t.id,Hn(t.args,t.name),t.args);return o.appendChild(s),An(o),Ye(n,!1),!0}if(e.eventName==="tool_result"){let i=t.id?o.querySelector('[data-nested-tool-id="'+kt(String(t.id))+'"]'):null;return i||(i=o.querySelector(".tool-card__subagent-tool:last-child")),Io(i,t.name,t.result,i&&i._toolArgs,t.ok),An(o),Ye(n,!1),!0}return!1}function St(e,t){if(!t.transcript.current)return;const n=e.id||Bd(t,e.name);let r=n?t.transcript.current.querySelector('[data-tool-id="'+kt(String(n))+'"]'):null;const o=Nr(e&&e.name),i=e.ok?"tool-card__pill--ok":"tool-card__pill--err",s=e.ok?"ok":"error",l=Wt(e&&e.result,Ge(e&&e.name)),c=e.ok||Fa(e&&e.name,l,e.ok)?Ha(e&&e.name,l):null;e.ok&&Ge(e.name)==="webpreview"&&l&&l.thumbnail&&Wn(l);const a=e&&e.args&&typeof e.args=="object"?e.args:r&&r._toolArgs||null;if(a&&r&&(r._toolArgs=a),r){r.classList.add("tool-card--result"),r.classList.remove("tool-card--call"),r.dataset.toolName=Ge(e.name);const p=r.querySelector(".tool-card__args"),f=o?Hn(e.args,e.name):p?p.textContent:null;Ud(r,e.name,f,i,s,c,a);let h=r.querySelector(".tool-card__body");h||(h=document.createElement("div"),h.className="tool-card__body",r.appendChild(h))}else{r=document.createElement("div"),r.className="tool-card tool-card--result",r.dataset.toolId=n||"call_"+Math.random().toString(36).slice(2,10),r.dataset.toolName=Ge(e.name),r._toolArgs=a;const p=Ge(e.name),f=o||p==="shell"||a&&a.cmd?Hn(a,e.name):null;r.appendChild(ti(e.name,f,i,s,c,a));const h=document.createElement("div");h.className="tool-card__body",r.appendChild(h),Hr(t,r)}o&&r.classList.add("tool-card--subagent");const d=r.querySelector(".tool-card__body");if(d){const p=()=>{r._resultBodyBuilt||(r._resultBodyBuilt=!0,Ju(d,a?Object.assign({},e,{args:a}):e,Nr),o&&rp(r,e),Ye(t,!1))};r._lazyBody=p,o||r.classList.contains("is-expanded")||!e.ok?p():d.dataset.lazyResult="1"}e.ok?o?r._userCollapsed||r.classList.add("is-expanded"):r._userCollapsed||r.classList.remove("is-expanded"):r.classList.add("is-expanded"),Ye(t,!0)}function Ud(e,t,n,r,o,i,s){const l=e.querySelector(":scope > .tool-card__head"),c=ti(t,n,r,o,i,s);l&&l.parentNode===e?e.replaceChild(c,l):e.insertBefore(c,e.firstChild)}function Vd(e,t){const n=t&&t.function||t||{},r=n.arguments!=null?n.arguments:t&&t.args;let o=r;if(typeof r=="string")try{o=JSON.parse(r)}catch{}const i=typeof o=="object"&&o!==null?Hn(o,n.name):String(r||""),s=ei(n.name,t&&t.id,i,o&&typeof o=="object"?o:null);return e.appendChild(s),s}function Hd(e,t,n,r){if(r)return r._settled=!0,Io(r,t.name,t.content,n),r;const o=ei(t.name,t.tool_call_id,null,n);return o._settled=!0,e.appendChild(o),Io(o,t.name,t.content,n),o}function Wd(e,t,n,r){const o=Ge(t),i=Wt(n,o),s=document.createElement("div");if(s.className="tool-card__subagent-preview",e.appendChild(s),o==="shell")return zd(s,i,r);if(o==="read_file")return $d(s,i);if(o==="list_files")return Jd(s,i);if(o==="search_files")return Gd(s,i);if(o==="edit_file")return Kd(s,i);if(o==="write_file")return Zd(s,i,r);if(i&&Array.isArray(i.content)){const l=[];for(const c of i.content)c&&typeof c.text=="string"?l.push(c.text):l.push(String(c&&(c.text||c.type)||c));return hs(s,l.join(`
|
|
40
|
+
`),"tool-preview__pre")}return hs(s,bt(i),"tool-preview__pre")}function zd(e,t,n){return Yd(e,t,n)}function $d(e,t){return Xd(e,t)}function Jd(e,t){return Qd(e,t)}function Gd(e,t){return ep(e,t)}function Kd(e,t){return tp(e,t)}function Zd(e,t,n){return np(e,t,n)}function hs(e,t,n){const r=document.createElement("pre");return r.className=n,r.textContent=t||"",e.appendChild(r),r}function Yd(e,t,n){Ya(e,t,n)}function Xd(e,t){$a(e,t)}function Qd(e,t){Ja(e,t)}function ep(e,t){Ga(e,t)}function tp(e,t){Ka(e,t)}function np(e,t,n){Za(e,t,n)}function rp(e,t){if(!e)return;const n=e.querySelector(".tool-card__subagent-chat");n&&n.remove();const r=Wt(t&&t.result,Ge(t&&t.name)),o=r&&Array.isArray(r.chat)?r.chat:null;if((!o||!o.length)&&!(r&&typeof r.text=="string"&&r.text))return;const i=document.createElement("div");i.className="tool-card__subagent-chat",i.addEventListener("click",g=>g.stopPropagation());const s=o&&o.length?o:[{role:"assistant",content:r.text}],l=new Map,c=[],a=(g,v)=>{for(const b of v){const k=Vd(g,b),_=b&&(b.id||b.function&&b.function.id);k&&_&&l.set(_,k),k&&c.push(k)}},d=()=>c.find(g=>!g._settled)||null,p=r&&r.model&&r.model.id?r.model.id:"",f=new Map;for(const g of s){const v=g&&Array.isArray(g.tool_calls)?g.tool_calls:[];for(const b of v){const k=b&&(b.id||b.function&&b.function.id),_=b&&b.function?b.function.arguments:b&&b.args;if(!k||_==null)continue;let y=_;if(typeof _=="string")try{y=JSON.parse(_)}catch{}y&&typeof y=="object"&&f.set(k,y)}}for(const g of s){const v=g&&g.role;if(v==="tool"){const P=Array.isArray(g.tool_calls)?g.tool_calls:[];P.length?a(i,P):Hd(i,g,f.get(g.tool_call_id)||null,l.get(g.tool_call_id)||d());continue}if(v!=="user"&&v!=="assistant"&&v!=="system")continue;const b=Id(g.content);if(v==="system"){const P=hl(b,"tool-card__subagent-msg",xd(r&&r.agent)),Y=Array.isArray(g.tool_calls)?g.tool_calls:[];a(P,Y),i.appendChild(P);continue}const k=Array.isArray(g.tool_calls)?g.tool_calls:[];if(v==="assistant"&&!b&&k.length){a(i,k);continue}if(v==="assistant"&&!b)continue;const _=document.createElement("div");_.className="chat-msg chat-msg--"+v+" tool-card__subagent-msg";const y=document.createElement("div");y.className="chat-msg__head";const w=document.createElement("div");w.className="chat-msg__role",w.textContent=v==="assistant"?p||"assistant":v;const N=document.createElement("span");N.className="chat-msg__ts",N.hidden=!0,y.appendChild(w),y.appendChild(N);const O=document.createElement("div");O.className="chat-msg__body",v==="assistant"?vn(O,b||"","",!0):O.textContent=b||"",_.appendChild(y),_.appendChild(O),i.appendChild(_),a(i,k)}const h=e.querySelector(".tool-card__body");h?h.appendChild(i):e.appendChild(i)}function op(e,t,n){if(!e.transcript.current)return null;const r=e.transcript.current.querySelector('[data-progress-id="'+kt(t||"")+'"]');if(r)return r;const o=document.createElement("div");o.className="tool-card tool-card--progress",t&&(o.dataset.progressId=t);const i=document.createElement("div");i.className="tool-card__head";const s=document.createElement("span");s.className="tool-card__chev",s.setAttribute("aria-hidden","true"),s.innerHTML='<svg viewBox="0 0 24 24" width="12" height="12" fill="currentColor"><path d="M9 5.5 15.5 12 9 18.5l1.4 1.4L18.3 12l-7.9-7.9L9 5.5Z"/></svg>';const l=document.createElement("span");l.className="tool-card__name",l.textContent=n||"Progress";const c=document.createElement("span");c.className="tool-card__pill tool-card__pill--busy",c.textContent="running",i.appendChild(s),i.appendChild(l),i.appendChild(c),o.appendChild(i),i.addEventListener("click",()=>{o.classList.toggle("is-expanded")});const a=document.createElement("div");a.className="tool-card__body";const d=document.createElement("div");d.className="tool-card__progress-row";const p=document.createElement("div");p.className="tool-card__progress-bar-wrap";const f=document.createElement("div");f.className="tool-card__progress-bar",p.appendChild(f),d.appendChild(p);const h=document.createElement("span");h.className="tool-card__progress-pct",h.textContent="0%",d.appendChild(h),a.appendChild(d);const g=document.createElement("div");return g.className="tool-card__progress-msg",a.appendChild(g),o.appendChild(a),e.transcript.current.appendChild(o),Ye(e,!0),o}function bl(e,t){if(!e.transcript.current||!t)return;const n=op(e,t.callId,t.title);if(!n)return;const r=Math.max(0,Math.min(Number(t.current)||0,Number(t.total)||100)),o=Math.max(1,Number(t.total)||100),i=Math.min(1,r/o),s=Math.round(i*100),l=n.querySelector(".tool-card__progress-bar");l&&(l.style.width=s+"%");const c=n.querySelector(".tool-card__progress-pct");c&&(c.textContent=s+"%");const a=n.querySelector(".tool-card__progress-msg");a&&(a.textContent=t.message||"");const d=n.querySelector(".tool-card__pill");d&&(t.status==="completed"?(d.className="tool-card__pill tool-card__pill--ok",d.textContent="completed",n.classList.add("is-expanded")):t.status==="failed"?(d.className="tool-card__pill tool-card__pill--err",d.textContent="failed",n.classList.add("is-expanded")):(d.className="tool-card__pill tool-card__pill--busy",d.textContent="running")),Ye(e,!1)}function ip(e){const t={toolIds:new Set,collapsedToolIds:new Set,builtToolIds:new Set,progressIds:new Set,details:[]};if(!e)return t;for(const n of e.querySelectorAll(".tool-card"))n.dataset&&n.dataset.toolId&&(n.classList.contains("is-expanded")?t.toolIds.add(n.dataset.toolId):n._userCollapsed&&t.collapsedToolIds.add(n.dataset.toolId),n._resultBodyBuilt&&t.builtToolIds.add(n.dataset.toolId));for(const n of e.querySelectorAll(".tool-card--progress.is-expanded"))n.dataset&&n.dataset.progressId&&t.progressIds.add(n.dataset.progressId);return e.querySelectorAll("details[open]").forEach(n=>t.details.push(n.className||"")),t}const wl=40,sp=120;let ri=0;function Wr(e){ri++,e._pendingTranscriptChunk&&(cancelAnimationFrame(e._pendingTranscriptChunk),e._pendingTranscriptChunk=null),e._suspendScrollPin=!1,e._insertAnchor=null}function Cl(e){return new Promise(t=>{function n(){if(!e._pendingTranscriptChunk)return t();requestAnimationFrame(n)}n()})}function Lr(e){Wr(e)}function ap(e,t){if(!e||!Array.isArray(e.messages)||!t.toolCallId)return null;const n=e.messages;for(let r=n.length-1;r>=0;r--){const o=n[r];if(o&&o.role==="tool"&&o.phase==="call"&&o.toolCallId===t.toolCallId&&o.args&&typeof o.args=="object")return o.args}return null}function Zn(e,t,n){if(n.role==="tool"&&n.phase==="call"){if(n.toolCallId&&t.transcript.current&&t.transcript.current.querySelector('[data-tool-id="'+kt(String(n.toolCallId))+'"]'))return;Xt({id:n.toolCallId,name:n.name,args:n.args},t,!0)}else if(n.role==="tool"&&n.phase==="result"){const r=n.args||ap(e,n);St({id:n.toolCallId,name:n.name,ok:n.ok,args:r,result:n.content||""},t)}else if(fl(n)){const r=Ad(e.messages,n);yr(n.content,t,e,{persist:!1,ts:n.ts,onRetry:r&&typeof e._retryFailedTurn=="function"?()=>e._retryFailedTurn(r):null})}else Kn(n,!1,t,e);lp(t,n)}function lp(e,t){const n=e.transcript.current;if(!n)return;const r=e._lastInsertedRow;if(!r||r.parentNode!==n)return;const o=Al(t);o&&(r._rowKey=o)}function kl(e){return!(e.role==="assistant"&&!String(e.content||"").trim()&&!String(e.reasoning||"").trim())}const oi=".tool-card--ask-user[data-auth-call-id], .tool-card--authorization[data-auth-call-id]";function cp(e){if(e)for(const t of Array.from(e.children))t.matches(oi)||t.remove()}function up(e,t,n){const r=t.transcript.current;if(!r)return;Wr(t);const o=ri,i=[];for(let a=0;a<e.messages.length;a++)kl(e.messages[a])&&i.push(a);if(!i.length){Mr(n,r),pn(t),On(t),ot(e,null,t);return}t._suspendScrollPin=!0;const s=Math.max(0,i.length-wl),l=r.children.length;t._insertAnchor=null;try{for(let a=s;a<i.length;a++)Zn(e,t,e.messages[i[a]])}finally{t._suspendScrollPin=!1}if(On(t),s===0){t._insertAnchor=null,Mr(n,r),pn(t),On(t),ot(e,null,t);return}const c=r.children[l]||null;t._insertAnchor=c,t._pendingTranscriptChunk=requestAnimationFrame(()=>Sl(e,t,{order:i,index:s-1,token:o,expanded:n}))}function Sl(e,t,n){if(t._pendingTranscriptChunk=null,n.token!==ri){t._insertAnchor=null;return}const r=t.transcript.current;if(!r){t._insertAnchor=null;return}const o=t.pinnedToBottom.current,i=r.scrollTop,s=r.scrollHeight;let l=0;t._suspendScrollPin=!0;try{for(;n.index>=0&&l<wl;){const c=e.messages[n.order[n.index]];n.index--;const a=r.childElementCount,d=t._insertAnchor?t._insertAnchor.previousElementSibling:r.lastElementChild;if(Zn(e,t,c),r.childElementCount>a){const p=t._insertAnchor?t._insertAnchor.previousElementSibling:r.lastElementChild;p&&p!==d&&(t._insertAnchor=p)}l++}}finally{t._suspendScrollPin=!1}if(o?r.scrollTop=r.scrollHeight:r.scrollTop=i+(r.scrollHeight-s),n.index>=0){t._pendingTranscriptChunk=requestAnimationFrame(()=>Sl(e,t,n));return}t._insertAnchor=null,Mr(n.expanded,r),pn(t),t.pinnedToBottom.current&&On(t),ot(e,null,t)}function Mr(e,t){if(t){for(const n of t.querySelectorAll(".tool-card"))n.dataset&&n.dataset.toolId&&(e.toolIds.has(n.dataset.toolId)?(n.classList.add("is-expanded"),typeof n._lazyBody=="function"&&n._lazyBody()):e.collapsedToolIds&&e.collapsedToolIds.has(n.dataset.toolId)&&(n._userCollapsed=!0,n.classList.remove("is-expanded")),e.builtToolIds&&e.builtToolIds.has(n.dataset.toolId)&&typeof n._lazyBody=="function"&&n._lazyBody());for(const n of t.querySelectorAll(".tool-card--progress"))n.dataset&&n.dataset.progressId&&e.progressIds.has(n.dataset.progressId)&&n.classList.add("is-expanded");t.querySelectorAll("details").forEach(n=>{const r=n.className||"";e.details.includes(r)&&(n.open=!0)})}}function pn(e){const t=e.transcript.current;if(!t)return;const n=t.querySelectorAll(oi);if(n.length){for(const r of n)r.parentNode&&r.parentNode.removeChild(r);for(const r of n)t.appendChild(r)}}function dp(e,t,n){const r=t.transcript.current;if(!r)return;const o=e.messages.length;if(o<=n)return;if(n===0){Wr(t),xl(e,t);return}const i=t._insertAnchor;t._insertAnchor=null;for(let s=n;s<o;s++){const l=e.messages[s];l.role==="assistant"&&!String(l.content||"").trim()&&!String(l.reasoning||"").trim()||Zn(e,t,l)}i&&i.parentNode===r&&(t._insertAnchor=i),pn(t),Ye(t,!0),ot(e,null,t)}const ms=new WeakMap;let pp=0;function gs(e,t){const n=e&&e.className;return typeof n=="string"&&(" "+n+" ").indexOf(" "+t+" ")>=0}function Tl(e){return!!(e&&e.dataset&&e.dataset.authCallId)}function xn(e){return!e||e.nodeType!==1||Tl(e)||al(e)?!1:gs(e,"chat-msg")||gs(e,"tool-card")}function fp(e){const t=e&&e.props||{};return(t.projectDir||"")+"::"+(t.chatId||"")}function Al(e){if(!e||typeof e!="object")return null;if(typeof e.seq=="number"&&Number.isFinite(e.seq))return"seq:"+e.seq;if(e.role==="tool"&&e.toolCallId)return"tool:"+e.toolCallId+":"+(e.phase||"");let t=ms.get(e);return t||(t="obj:"+ ++pp,ms.set(e,t)),t}function hp(e){if(!e)return!1;for(const t of e.children)if(xn(t))return!0;return!1}function mp(e,t,n){const r=t.transcript.current,o={reused:0,created:0,removed:0};if(!r)return o;const i=new Map;for(const c of Array.from(r.children)){if(!xn(c))continue;const a=c._rowKey;a&&(i.has(a)?(c.remove(),o.removed++):i.set(a,c))}let s=null;for(const c of r.children){if(xn(c)){s=c;break}if(Tl(c)){s=c;break}}const l=new Set;for(let c=0;c<n.length;c++){const a=e.messages[n[c]],d=Al(a);if(!d)continue;l.add(d);let p=i.get(d)||null;if(p)o.reused++;else{const f=new Set(r.children);Zn(e,t,a);for(const h of r.children)if(!(f.has(h)||!xn(h)||h._rowKey)){p=h;break}p&&o.created++}if(p){if(p._rowKey=d,p===s){s=p.nextElementSibling;continue}r.insertBefore(p,s),s=p.nextElementSibling}}for(const c of Array.from(r.children)){if(!xn(c))continue;const a=c._rowKey;a&&l.has(a)||(c.remove(),o.removed++)}return o}function co(e){try{return JSON.stringify(e??null)}catch{return""}}function gp(e,t){const n=e.tools||{catalog:[],filter:null},r=e.agentFiles||{},o=e.skills||{};return{setup:t?String(e.chat&&e.chat.promptSize||"average"):"hidden",sys:String(e.systemPrompt&&e.systemPrompt.text||""),tools:co([(n.catalog||[]).map(i=>i&&i.name||""),n.filter==null?null:n.filter,e.toolAuth||null,e.mcpAuth||null,e._mcpStartBusyServerId||null,(e.mcpServers||[]).map(i=>(i&&i.id)+":"+(i&&i.status)),Array.from(e.usedTools||[])]),agentFiles:co([r.files||[],!!r.enabled,!!r.explicit,!!r.projectLocked]),skills:co([(o.items||[]).map(i=>[i&&i.id,!!i.disabled,!!i.chatDisabled]),!!o.enabled,!!o.projectLocked])}}function _p(e,t){const n=e.transcript.current;if(!n)return;const r=n.querySelector?n.querySelector(".chat-view__empty"):null;if(t){if(r&&r.parentNode===n)return;r&&r.remove(),n.appendChild(Cp())}else r&&r.parentNode===n&&r.remove()}function yp(e,t,n){const r=t.transcript.current;if(!r)return;const o=gp(e,n),i=t._cardSigs||(t._cardSigs={}),s=l=>!!(r.querySelector&&r.querySelector(l));if(o.setup==="hidden"){const l=t.setupCard.current;l&&l.parentNode&&l.remove(),t.setupCard.current=null,i.setup=""}else if(i.setup!==o.setup||!t.setupCard.current||!t.setupCard.current.parentNode){t.setupCard.current&&t.setupCard.current.parentNode&&t.setupCard.current.remove();const l=wp(t,e);yn(r,l,gt.setup),t.setupCard.current=l,i.setup=o.setup}(i.sys!==o.sys||!s('[data-sys-prompt="1"]'))&&(ml(t,e.systemPrompt),i.sys=o.sys),(i.tools!==o.tools||!s('[data-tools-card="1"]'))&&(ud(t,e),i.tools=o.tools),(i.agentFiles!==o.agentFiles||!s('[data-agent-files-card="1"]'))&&(dd(t,e),i.agentFiles=o.agentFiles),(i.skills!==o.skills||!s('[data-skills-card="1"]'))&&(pd(t,e),i.skills=o.skills),ld(t),_p(t,n)}function xl(e,t){if(!t.transcript.current)return;const n=ip(t.transcript.current);Wr(t);const r=fp(e);t._transcriptKey!==r&&(t._transcriptKey=r,t._cardSigs={},t._toolTreeCollapsed=null,cp(t.transcript.current),t._anonToolCalls=[],t.setupCard.current=null);const o=!e.messages.length;if(yp(e,t,o),pn(t),e.messages.length>=sp&&!hp(t.transcript.current)){up(e,t,n);return}const i=[];for(let s=0;s<e.messages.length;s++)kl(e.messages[s])&&i.push(s);mp(e,t,i),Mr(n,t.transcript.current),pn(t),i.length&&On(t),ot(e,null,t)}function vp(e){if(!e)return null;for(let t=0;t<e.children.length;t++){const n=e.children[t];if(!al(n))return n}return null}function bp(e,t,n){const r=t.transcript.current;if(!r||!Array.isArray(n)||!n.length)return!1;const o=vp(r);if(!o)return!1;const i=r.scrollHeight,s=r.scrollTop;t._insertAnchor=o,t._suspendScrollPin=!0;const l=r.childElementCount;try{for(const c of n)Zn(e,t,c)}finally{t._suspendScrollPin=!1,t._insertAnchor=null}return r.childElementCount===l?!1:(r.scrollTop=s+(r.scrollHeight-i),ot(e,null,t),!0)}function wp(e,t){const n=cd();return n._onChange=r=>Td(r,t,e),n}function Cp(){const e=document.createElement("div");e.className="chat-view__empty";const t=document.createElement("span");t.className="chat-view__empty-icon",t.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true"><path d="M4 4h16a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1h-9.586a1.5 1.5 0 0 0-1.06.44l-2.122 2.12A.5.5 0 0 1 6.4 20.146V18H4a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1Zm3 5a1 1 0 0 0 0 2h10a1 1 0 1 0 0-2H7Zm0 4a1 1 0 1 0 0 2h7a1 1 0 1 0 0-2H7Z"/></svg>';const n=document.createElement("p");n.className="chat-view__empty-title",n.textContent="Start the conversation";const r=document.createElement("p");return r.className="chat-view__empty-text",r.textContent="Type a message below. The model streams its reply in real time; everything you send is saved to this chat's transcript on disk.",e.appendChild(t),e.appendChild(n),e.appendChild(r),e}function On(e){const t=e.transcript.current;if(!t)return;if(!e.pinnedToBottom.current){e.pendingCount.current=0,Gt(e);return}t.scrollTop=t.scrollHeight,e.pendingCount.current=0,Gt(e),Ur(e)}function uo(e,t){if(!t.transcript.current)return;const n=t.transcript.current.querySelector('[data-live="1"]');n&&(delete n.dataset.live,n._body&&e&&typeof e.content=="string"&&(n.classList.contains("chat-msg--assistant")?vn(n._body,e.content,e.reasoning||n._reasoning||"",!0):n._body.textContent=e.content))}const Ze={FILES:"files",AGENTS:"agents",ACTIONS:"actions",TOOLS:"tools",MCP:"mcp",MODEL:"model"},kp={file:"📄",agent:"🧑🔧",action:"⚡",tool:"🛠️",mcp:"🔌",model:"🤖"},Sp=200,Tp=4;let Ue=null,rt=null,Te=null,an=[],zt=[],fn="",ln=null,lt=0,ft=!1,po=null,_s="",Pt=null;const Ap=[{key:Ze.FILES,label:"Files"},{key:Ze.AGENTS,label:"Agents"},{key:Ze.ACTIONS,label:"Actions"},{key:Ze.TOOLS,label:"Tools"},{key:Ze.MCP,label:"MCP"},{key:Ze.MODEL,label:"Model"}];let vt=null,cn=null,zn=[],fo=null,ys="";async function xp(e){if(!e)return null;if(e===ys&&fo)return fo;try{const t=await H("/api/projects/registered");if(t.status===200&&Array.isArray(t.body&&t.body.projects)){for(const n of t.body.projects)if(n&&n.path===e&&n.id)return fo=n.id,ys=e,n.id}}catch{}return null}function vs(e){const t=String(e||"").replace(/\\/g,"/").replace(/^\/+|\/+$/g,""),n=t.lastIndexOf("/");return{name:n>=0?t.slice(n+1):t,folder:n>=0?t.slice(0,n):"Project root"}}function ho(e){const t=[],n=[];for(const r of e)(r.category===Ze.FILES?t:n).push(r);return t.concat(n)}async function El(e){if(!e)return[];const t=[],n=await xp(e);if(n)try{const a=await H("/api/projects/"+encodeURIComponent(n)+"/tags");if(a.status===200&&a.body&&a.body.tags){const d=a.body.tags;for(const p of Object.keys(d).sort()){const f=d[p],h=vs(p);t.push({id:"file:"+p,label:h.name,subtitle:h.folder,category:Ze.FILES,icon:"file",insert:p,searchText:(h.name+" "+p+" "+(f.tags||[]).join(" ")).toLowerCase()})}}}catch{}const r=e+"|"+(n||"");if(r!==_s&&(_s=r,po=null,n))try{const a=await H("/api/projects/"+encodeURIComponent(n)+"/tags/scan",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});a.status===200&&Array.isArray(a.body&&a.body.files)&&(po=a.body.files)}catch{}const o=po||[],i=new Set(t.filter(a=>a.category===Ze.FILES).map(a=>a.insert));for(const a of o){if(!a.path||i.has(a.path)||a.binary)continue;const d=vs(a.path);t.push({id:"file:"+a.path,label:d.name,subtitle:d.folder,category:Ze.FILES,icon:"file",insert:a.path,searchText:(d.name+" "+a.path).toLowerCase()})}const s=new Set,l=Ue&&Ue.tools;if(l&&Array.isArray(l.catalog))for(const a of l.catalog){if(!a||!a.name||s.has(a.name))continue;s.add(a.name);const d=a.parameters||a.inputSchema||null,p=d&&d.properties||{},f=d&&Array.isArray(d.required)?d.required:[],h=a.kind==="mcp";t.push({id:(h?"mcp:":"tool:")+a.name,label:a.name,subtitle:h?(a.source?a.source+" · ":"")+(a.description||"MCP tool"):a.description||"Native tool",category:h?Ze.MCP:Ze.TOOLS,icon:h?"mcp":"tool",insert:a.name,searchText:(a.name+" "+(a.source||"")+" "+(a.description||"")+(h?" mcp":" native tool")).toLowerCase(),params:{properties:p,required:f}})}try{const a=await H("/api/actions?projectDir="+encodeURIComponent(e));if(a.status===200&&Array.isArray(a.body&&a.body.actions)){Ue&&typeof Ue._setCustomActions=="function"?Ue._setCustomActions(a.body.actions):Ue&&(Ue.customActions=a.body.actions);for(const d of a.body.actions){if(!d||!d.id)continue;const p=d.label||d.id,f=d.description||(p!==d.id?"@"+d.id:"Project action");t.push({id:"custom-action:"+d.id,label:p,subtitle:f,category:Ze.ACTIONS,icon:"action",insert:d.id,searchText:(d.id+" "+p+" "+(d.description||"")).toLowerCase(),params:null})}}}catch{}try{const a=await H("/api/agents?projectDir="+encodeURIComponent(e));if(a.status===200&&Array.isArray(a.body&&a.body.agents))for(const d of a.body.agents)!d||!d.name||t.push({id:"agent:"+d.name,label:d.name,subtitle:(d.modelId?d.modelId+" · ":"")+"agent",category:Ze.AGENTS,icon:"agent",insert:d.name,searchText:(d.name+" agent "+(d.content||"")).toLowerCase().slice(0,200)})}catch{}const c=Ue&&Ue.chat;return c&&c.modelId&&t.push({id:"model:current",label:c.modelId,subtitle:c.providerId||"model",category:Ze.MODEL,icon:"model",insert:c.modelId,searchText:(c.modelId+" "+(c.providerId||"")).toLowerCase()}),t.sort((a,d)=>{const p={files:0,agents:1,actions:2,tools:3,mcp:4,model:5},f=p[a.category]??6,h=p[d.category]??6;return f!==h?f-h:a.label.localeCompare(d.label)}),t}function ii(e){let t=e?an:Pt?an.filter(o=>o.category===Pt):an;if(e&&(t=t.filter(o=>o.searchText.indexOf(e)>=0)),e){let o=0;const i=t.filter(s=>s.category!==Ze.FILES?!0:o>=Sp?!1:(o++,!0));return ho(i)}if(Pt)return ho(t);const n={},r=t.filter(o=>{const i=n[o.category]||0;return n[o.category]=i+1,i<Tp});return ho(r)}function bs(e){if(fn)return;const t=document.createElement("div");t.className="at-mention__filter";for(const{key:n,label:r}of Ap){const o=document.createElement("button");o.type="button",o.className="at-mention__filter-chip"+(Pt===n?" is-active":""),o.textContent=r,o.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),Pt=Pt===n?null:n,lt=0,zt=ii(fn),$n()}),o.addEventListener("mousedown",i=>i.preventDefault()),t.appendChild(o)}e.appendChild(t)}function $n(){if(!rt)return;const e=zt;if(rt.hidden=!1,!ft||!e.length){if(ft&&!fn){rt.innerHTML="",bs(rt);return}rt.hidden=!0;return}lt>=e.length&&(lt=0),lt<0&&(lt=e.length-1);const t=[];for(let n=0;n<e.length;n++)t.push({type:"item",index:n,item:e[n]});rt.innerHTML="",bs(rt);for(const n of t){const r=document.createElement("div");r.className="at-mention__item"+(n.index===lt?" is-selected":""),r.setAttribute("role","option"),r.setAttribute("aria-selected",n.index===lt?"true":"false");const o=document.createElement("span");o.className="at-mention__icon",o.textContent=kp[n.item.icon]||"📄",r.appendChild(o);const i=document.createElement("div");i.className="at-mention__text";const s=document.createElement("div");if(s.className="at-mention__label",s.textContent=n.item.label,i.appendChild(s),n.item.subtitle){const l=document.createElement("div");l.className="at-mention__subtitle",l.textContent=n.item.subtitle,i.appendChild(l)}r.appendChild(i),r.addEventListener("click",()=>Il(n.index)),r.addEventListener("mousedown",l=>l.preventDefault()),rt.appendChild(r)}}function Ep(e,t){const n=String(e||"").trim().match(/^@([^\s:]+)$/);if(!n||!Array.isArray(t))return null;const r=n[1].toLowerCase();return t.find(o=>o&&o.id&&String(o.id).toLowerCase()===r)||null}function Il(e){const t=zt[e];if(!t||!Te||!ln)return;const n=Te,r=n.value.slice(0,ln.start),o=n.value.slice(ln.end);if((t.category===Ze.TOOLS||t.category===Ze.MCP)&&t.params&&Object.keys(t.params.properties).length>0){const l=t.params.properties,c=t.params.required,a=c.length>0?c[0]:Object.keys(l)[0];for(const g of Object.keys(l));const d=l[a]&&l[a].description||"",p=!l[a]||l[a].type==="string"||!l[a].type;let f,h;p?(f="@"+t.insert+":"+a+"=`"+d+"` ",h=r.length+t.insert.length+a.length+4):(f="@"+t.insert+":"+a+"= ",h=r.length+f.length-1),n.value=r+f+o,n.selectionStart=n.selectionEnd=h,cn={properties:l,required:c},zn=[a],Pl(l,c,[a]),Ct(),n.dispatchEvent(new Event("input",{bubbles:!0})),n.focus();return}const i="@"+t.insert+" ";n.value=r+i+o;const s=r.length+i.length;n.selectionStart=n.selectionEnd=s,Pp(),cn=null,zn=[],Ct(),n.dispatchEvent(new Event("input",{bubbles:!0})),n.focus()}function Pl(e,t,n){if(!vt)return;const r=new Set(n||[]);vt.innerHTML="",vt.hidden=!1;let o=!1;for(const[i,s]of Object.entries(e)){if(r.has(i))continue;o=!0;const l=document.createElement("button");l.type="button",l.className="at-mention__arg-chip"+(t.indexOf(i)>=0?" is-required":""),l.textContent=i;const c=s&&s.description||"";c&&(l.title=c),l.addEventListener("click",a=>{a.preventDefault(),Ip(i,s)}),vt.appendChild(l)}o||(vt.hidden=!0)}function Ip(e,t){if(!Te)return;const n=!t||t.type==="string"||!t.type,r=n?" "+e+"=`"+(t.description||"")+"`":" "+e+"= ",o=Te.value.length;Te.value=Te.value.slice(0,o)+r+Te.value.slice(o),n?Te.selectionStart=Te.selectionEnd=o+e.length+3:Te.selectionStart=Te.selectionEnd=o+r.length,Te.dispatchEvent(new Event("input",{bubbles:!0})),Te.focus(),zn.push(e),cn&&Pl(cn.properties,cn.required,zn)}function Pp(){vt&&(vt.innerHTML="",vt.hidden=!0),cn=null,zn=[]}function Ct(){ft=!1,zt=[],ln=null,Pt=null,rt&&(rt.hidden=!0)}function ws(){const e=Te;if(!e)return;const t=e.selectionStart,n=e.value;let r=t-1;for(;r>=0&&n[r]!=="@";)r--;if(r<0||n[r]!=="@"){ft&&Ct();return}if(r>0&&!/\s/.test(n[r-1])&&n[r-1]!=="("){ft&&Ct();return}const i=n.slice(r+1).slice(0,t-r-1).toLowerCase();if(/\s/.test(i)){ft&&Ct();return}ln={start:r,end:t},fn=i,lt=0,i||(Pt=null),zt=ii(i),ft=!0,$n()}function Cs(e){if(!ft)return;if(e.key==="Enter"){const n=Zo(Te&&Te.value);if(n&&Ue&&typeof Ue._runRestartCommand=="function"){e.preventDefault(),Ct(),Ue._runRestartCommand(n.reason);return}const r=Ep(Te&&Te.value,Ue&&Ue.customActions);if(r&&Ue&&typeof Ue._runCustomAction=="function"){e.preventDefault(),Ct(),Ue._runCustomAction(r);return}}const t=zt;t.length&&(e.key==="ArrowDown"?(e.preventDefault(),lt=Math.min(lt+1,t.length-1),$n(),ks()):e.key==="ArrowUp"?(e.preventDefault(),lt=Math.max(lt-1,0),$n(),ks()):e.key==="Enter"||e.key==="Tab"?(e.preventDefault(),Il(lt)):e.key==="Escape"&&(e.preventDefault(),Ct(),Te&&Te.focus()))}function ks(){if(!rt)return;const e=rt.querySelector(".is-selected");e&&e.scrollIntoView({block:"nearest",behavior:"smooth"})}function Ss(e){ft&&(!rt||!Te||rt.contains(e.target)||Te.contains(e.target)||Ct())}function Np(e,t,n,r){Te=e,rt=t,Ue=n,vt=r||null,vt&&(vt.hidden=!0),ft=!1,an=[],zt=[],fn="",ln=null,lt=0,Pt=null;const o=n.props&&n.props.projectDir;return o&&El(o).then(i=>{an=i}).catch(()=>{}),Te.addEventListener("input",ws),Te.addEventListener("keydown",Cs),document.addEventListener("click",Ss),()=>{Te.removeEventListener("input",ws),Te.removeEventListener("keydown",Cs),document.removeEventListener("click",Ss),Ct(),Ue=null}}function Rp(){const e=Ue&&Ue.props&&Ue.props.projectDir;e&&El(e).then(t=>{an=t,ft&&(zt=ii(fn),$n())}).catch(()=>{})}function Lp(){return ft}function En(e){const t=e.promptInput.current;if(!t)return;t.style.height="auto";const n=Math.min(120,Math.max(32,t.scrollHeight));t.style.height=n+"px",t.style.overflowY=t.scrollHeight>120?"auto":""}function Mp(e,t,n,r,o){!t||!n||(r.draftSaveTimer.current&&clearTimeout(r.draftSaveTimer.current),r.draftSaveTimer.current=setTimeout(()=>{r.draftSaveTimer.current=null,o({draft:e||""}).catch(()=>{})},250))}function jn(e,t,n,r={}){return t.draftSaveTimer.current&&(clearTimeout(t.draftSaveTimer.current),t.draftSaveTimer.current=null),n(Object.assign({},r,{draft:e||""}))}function Ts(e,t,n,r){return jn("",n,r,{draftAttachments:null})}function Op(e,t,n,r){Mp(e.promptInput.current?e.promptInput.current.value:"",t,n,e,r),En(e)}function jp(e,t,n={}){const r=n.enterForNewline!==!1,o=e.key==="Enter",i=o&&(e.ctrlKey||e.metaKey),s=o&&e.shiftKey,l=o&&!s&&Ua(e.currentTarget&&e.currentTarget.value,n.customActions),c=o&&!s&&Zo(e.currentTarget&&e.currentTarget.value);o&&!e.isComposing&&!Lp()&&(i||l||c?(e.preventDefault(),t()):r||s||(e.preventDefault(),t()))}function Dp(e,t){if(!t||!e.transcript||!e.transcript.current)return!0;const n=kt(String(t));return!e.transcript.current.querySelector('.tool-card--authorization[data-auth-call-id="'+n+'"],.tool-card--ask-user[data-auth-call-id="'+n+'"],[data-tool-id="'+n+'"]')}function Bp(e,t){if(!t||!e.transcript||!e.transcript.current)return;const n='.tool-card--authorization[data-auth-call-id="'+kt(String(t))+'"],.tool-card--ask-user[data-auth-call-id="'+kt(String(t))+'"]';for(const r of e.transcript.current.querySelectorAll(n))r.remove()}function Fp(e){if(!(!e||!e.transcript||!e.transcript.current))for(const t of e.transcript.current.querySelectorAll(".tool-card--authorization[data-auth-call-id], .tool-card--ask-user[data-auth-call-id]"))t.remove()}function Kt(e,t,n){Cl(e).then(()=>{if(!e.transcript||!e.transcript.current||!Dp(e,t))return;const r=e.transcript.current;r.children.length>0&&!(r.children.length===1&&r.querySelector(":scope > .chat-view__empty"))&&n()})}const Dn=new Map;function on(e,t,n){const r=e.liveRun&&e.liveRun.key===t?e.liveRun:{key:t,active:!1,connected:!1,ended:!1,failed:!1};e.liveRun=Object.assign({},r,n||{},{key:t})}function Nl(e,t){const{projectDir:n,chatId:r}=e.props;if(!n||!r)return!1;const o=n+"::"+r;if(Dn.has(o))return!0;let i=!0;const s=new AbortController;Dn.set(o,{abort:s}),on(e,o,{active:!0,connected:!1,ended:!1,failed:!1});const l=Number.isFinite(e.nextLiveSeq)?e.nextLiveSeq:0;return fetch("/api/chats/"+encodeURIComponent(r)+"/live?projectDir="+encodeURIComponent(n)+"&fromLiveSeq="+l,{signal:s.signal}).then(c=>i?!c.ok||!c.body?(on(e,o,{active:!1,connected:!1,ended:!1,failed:!0}),null):(on(e,o,{active:!0,connected:!0,failed:!1}),c.body.getReader()):null).then(async function(a){if(!a)return;const d=new TextDecoder("utf-8");let p="";try{for(;;){const{value:f,done:h}=await a.read();if(h)break;p+=d.decode(f,{stream:!0});let g;for(;(g=p.indexOf(`
|
|
41
|
+
|
|
42
|
+
`))!==-1;){const v=p.slice(0,g);p=p.slice(g+2);const b=ka(v);if(b){if(b.eventName==="run_end"){Vp(b,t,e,o);return}Up(b,t,e,o)}}}}catch{}}).finally(()=>{if(i){i=!1,Dn.delete(o);const c=e.liveRun;c&&c.key===o&&!c.ended&&!c.failed&&on(e,o,{active:!1,connected:!1})}}),!0}function qp(e,t,n){const r=t||e.props&&e.props.projectDir,o=n||e.props&&e.props.chatId;if(!r||!o)return!1;const i=r+"::"+o,s=Dn.get(i);return s?(Dn.delete(i),on(e,i,{active:!1,connected:!1}),s.abort&&s.abort.abort(),!0):!1}function Rl(e,t){const{projectDir:n,chatId:r}=e.props||{};return!n||!r?!1:!t||t===n+"::"+r}function Up(e,t,n,r){if(!t.transcript||!t.transcript.current||!Rl(n,r))return;let o=null;try{o=JSON.parse(e.data||"null")}catch{return}if(!o||typeof o!="object")return;const i=typeof o.liveSeq=="number"?o.liveSeq:null;if(i!=null){if(i<(n.nextLiveSeq||0))return;n.nextLiveSeq=i+1}const{projectDir:s,chatId:l}=n.props;if(e.eventName!=="live_subscribed"){if(e.eventName==="shell_output"){ni(o,t);return}if(e.eventName==="subagent_event"){vl({eventName:o.kind||"message"},Object.assign({parentCallId:o.parentCallId},o.data||{}),t);return}if(e.eventName==="progress_update"){bl(t,o),Hp(t,o);return}if(e.eventName==="authorization_resolved"){Bp(t,o.callId);return}if(e.eventName==="authorization_required"){Kt(t,o.callId,()=>Nt(o,s,l,t,null,n)),ne(t,"authorization required","busy");return}e.eventName==="ask_user_required"&&(Kt(t,o.callId,()=>Rr(o,s,l,t,(c,a)=>ne(t,c,a))),ne(t,"answer required","busy"))}}function Vp(e,t,n,r){if(!Rl(n,r))return;let o=null;try{o=JSON.parse(e.data||"null")}catch{o=null}o&&typeof o.nextLiveSeq=="number"&&o.nextLiveSeq>(n.nextLiveSeq||0)&&(n.nextLiveSeq=o.nextLiveSeq),on(n,r,{active:!1,connected:!1,ended:!0,failed:!1}),Fp(t),n.watchingRun=!1,n.watchingStableTicks=0,n.runSettled=!0,typeof n._setRunningVisible=="function"&&n._setRunningVisible(!1),ne(t,"done","success"),typeof n._kickPoll=="function"&&n._kickPoll()}function Hp(e,t){if(!e.status||!e.status.current)return;const n=t.current!=null&&t.total!=null?Math.round(Number(t.current)/Math.max(1,Number(t.total))*100)+"%":t.status||"running";e.status.current.textContent=(t.title||"Progress")+" "+n}function Wp(e,t){return!(!e||!t||e.role!==t.role||e.content!==t.content||e.role==="assistant"&&(e.reasoning||"")!==(t.reasoning||""))}function zp(e){let t=-1;const n=e&&Array.isArray(e.messages)?e.messages:[];for(const o of n)o&&typeof o.seq=="number"&&Number.isFinite(o.seq)&&o.seq>t&&(t=o.seq);const r=e&&e.seenSeqs;return r&&typeof r.forEach=="function"&&r.forEach(o=>{typeof o=="number"&&Number.isFinite(o)&&o>t&&(t=o)}),t+1}function $p(e,t){const n=e.seenSeqs,r=e.messages.slice(),o=[];for(let s=r.length-1;s>=0&&!(r[s]&&typeof r[s].seq=="number");s--)o.unshift(s);let i=0;for(const s of t){let l=-1;if(typeof s.seq=="number"){if(n.has(s.seq))continue;for(n.add(s.seq);i<o.length;){const c=o[i],a=r[c];if(i++,a&&typeof a.seq!="number"&&a.role===s.role){l=c;break}}if(l===-1)for(let c=r.length-1;c>=0;c--){const a=r[c];if(a&&typeof a.seq!="number"&&Wp(a,s)){l=c;break}}}l>=0?r[l]=s:r.splice(Gp(r,s.seq),0,s)}return r}function Jp(e,t){if(!Array.isArray(e)||!Array.isArray(t)||t===e)return"noop";const n=e.length;let r=!0;for(let o=0;o<n;o++)if(t[o]!==e[o]){r=!1;break}return r?t.length>n?"append":"noop":"render"}function Gp(e,t){for(let n=0;n<e.length;n++){const r=e[n];if(!r||typeof r.seq!="number"||r.seq>t)return n}return e.length}const Ll=12*1024*1024;function Jn(e){if(!e||typeof e!="object"||e.type!=="image")return null;const t=typeof e.mimeType=="string"?e.mimeType:"",n=typeof e.dataUrl=="string"?e.dataUrl:"";if(!/^image\/(png|jpe?g|webp|gif)$/i.test(t)||!n.startsWith("data:"+t+";base64,")||n.length>Ll)return null;const r={type:"image",mimeType:t,dataUrl:n};return typeof e.name=="string"&&e.name&&(r.name=e.name),r}function Vt(e){return Array.isArray(e)?e.map(Jn).filter(Boolean):[]}function Kp(e,t){const n=typeof e=="string"?e.trimEnd():"",r=typeof t=="string"?t.trim():"";if(!r)return{value:n,start:-1};const o=n?`
|
|
43
|
+
|
|
44
|
+
`:"";return{value:n+o+r,start:n.length+o.length}}function As(e,t,n=-1){const r=typeof e=="string"?e:"",o=typeof t=="string"?t.trim():"";if(!o||!Number.isInteger(n)||n<0||r.slice(n,n+o.length)!==o)return r;const i=n+o.length;if(i<r.length&&r.slice(i,i+2)!==`
|
|
45
|
+
|
|
46
|
+
`)return r;let s=r.slice(0,n),l=r.slice(i);return s.endsWith(`
|
|
47
|
+
|
|
48
|
+
`)?s=s.slice(0,-2):l.startsWith(`
|
|
49
|
+
|
|
50
|
+
`)&&(l=l.slice(2)),s+l}function Zp(e,t,n,r=-1){const o=e&&typeof e=="object"?e:{},i=o.__originalAttachment||Jn(o),s=Object.assign({},o,Jn(t)||{});return s.__originalAttachment=i,s.__annotationText=typeof n=="string"?n.trim():"",s.__annotationStart=Number.isInteger(r)?r:-1,s}function Po(e){return!e||!e.__originalAttachment?null:{attachment:Jn(e.__originalAttachment),annotationText:typeof e.__annotationText=="string"?e.__annotationText:"",annotationStart:Number.isInteger(e.__annotationStart)?e.__annotationStart:-1}}function Yp(e){const t=Po(e);return t&&t.attachment?t.attachment.dataUrl:null}function xs(e,t,n,r=-1){return!Array.isArray(e)||!n?Array.isArray(e)?e.slice():[]:e.map((o,i)=>i===r||!o||!Number.isInteger(o.__annotationStart)||o.__annotationStart<=t?o:Object.assign({},o,{__annotationStart:o.__annotationStart+n}))}function Xp(e,t,n){if(!Array.isArray(e)||t===n)return Array.isArray(e)?e.slice():[];const r=typeof t=="string"?t:"",o=typeof n=="string"?n:"";let i=0;for(;i<r.length&&i<o.length&&r[i]===o[i];)i+=1;let s=0;for(;s<r.length-i&&s<o.length-i&&r[r.length-1-s]===o[o.length-1-s];)s+=1;const l=r.length-s,c=o.length-r.length;return e.map(a=>{if(!a||!Number.isInteger(a.__annotationStart)||a.__annotationStart<0)return a;const d=a.__annotationStart,p=typeof a.__annotationText=="string"?a.__annotationText:"",f=d+p.length;return l<=d?Object.assign({},a,{__annotationStart:d+c}):i>=f?a:Object.assign({},a,{__annotationStart:-1})})}function Qp(e,t={}){if(!e||typeof e.toDataURL!="function")throw new Error("Annotation canvas is unavailable.");const n=Number.isFinite(t.limit)?t.limit:Ll,r=t.makeCanvas||(()=>document.createElement("canvas"));let o=e,i=o.toDataURL("image/png");if(!i.startsWith("data:image/png;base64,"))throw new Error("Could not export the annotated image.");for(let s=0;i.length>n&&s<10;s+=1){const l=Math.min(.9,Math.max(.1,Math.sqrt(n/i.length)*.9)),c=Math.max(1,Math.floor(o.width*l)),a=Math.max(1,Math.floor(o.height*l));if(c===o.width&&a===o.height)break;const d=r();d.width=c,d.height=a;const p=d.getContext("2d");if(!p)throw new Error("Could not resize the annotated image.");if(p.drawImage(o,0,0,c,a),o=d,i=o.toDataURL("image/png"),!i.startsWith("data:image/png;base64,"))throw new Error("Could not export the annotated image.")}if(i.length>n)throw new Error("Annotated image is too large. Try a smaller image.");return i}const ef=100,tf=48,nf=ef;function Es(){return{offset:0,beforeSeq:null,hasMore:!0,loading:!1,total:null,firstSeq:null}}function rf(e,t){!e||!t||(e.offset=Array.isArray(t.messages)?t.messages.length:0,e.total=typeof t.total=="number"?t.total:null,e.beforeSeq=typeof t.beforeSeq=="number"&&t.beforeSeq>=0?t.beforeSeq:Array.isArray(t.messages)&&t.messages.length?t.messages[0].seq:null,e.firstSeq=Array.isArray(t.messages)&&t.messages.length?t.messages[0].seq:null,e.hasMore=typeof t.hasMore=="boolean"?t.hasMore:e.beforeSeq!==null&&e.beforeSeq!==void 0)}function of(e,t){return!e||e.loading||!e.hasMore||e.beforeSeq===null?!1:t<tf}function vr(e,t,n){return e.reconnect&&e.reconnect.active&&li(e),e.streaming=!1,e.watchingRun=!1,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1),ci(e,t,Object.assign({retry:!0,manualRetry:!0},n||{}))}function Is(e,t,n){return!e.autoRetry||n&&n.manualRetry||n&&n.retry?!1:(ne(t,"auto-retrying…","busy"),ci(e,t,Object.assign({},n,{retry:!0,manualRetry:!1})).catch(()=>{}),!0)}function sf(e,t,n){if(!e||!n)return;const r=Ge(n);if(!r)return;const o=e.tools||{catalog:[],filter:null};Array.isArray(o.filter)&&o.filter.indexOf(r)<0&&(o.catalog||[]).some(s=>s&&s.name===r)&&typeof e._toggleTool=="function"&&e._toggleTool(r,!0);const i=e.usedTools||new Set;if(!i.has(r)){const s=new Set(i);s.add(r),e.usedTools=s}e._updateToolsCard&&e._updateToolsCard()}async function Ps(e,t,n){const{projectDir:r,chatId:o}=t.props,i="direct_"+Date.now().toString(36)+Math.random().toString(36).slice(2,7);n.promptInput.current.value="",n._autoresize(),Xt({id:i,name:"shell",args:{cmd:e}},n),ne(n,"running shell…","busy"),n.sendBtn.current&&(n.sendBtn.current.disabled=!0);async function s(){const a=await fetch("/api/tools/shell",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:r,chatId:o,callId:i,cmd:e})});if(a.status===409)return{status:409,body:await a.json()};if(!(a.headers.get("content-type")||"").toLowerCase().includes("ndjson"))return{status:a.status,body:await a.json()};if(!a.body)return{status:500,body:{ok:!1,error:"empty shell response"}};const p=a.body.getReader(),f=new TextDecoder("utf-8");let h="",g=null;try{for(;;){const{value:v,done:b}=await p.read();if(b)break;h+=f.decode(v,{stream:!0});let k;for(;(k=h.indexOf(`
|
|
51
|
+
`))!==-1;){const _=h.slice(0,k).trim();if(h=h.slice(k+1),!_)continue;let y;try{y=JSON.parse(_)}catch{continue}y.type==="output"&&typeof y.delta=="string"?ni({id:i,stream:y.stream,delta:y.delta},n):y.type==="result"&&y.result&&(g=y.result)}}}finally{try{p.releaseLock()}catch{}}return g||(g={ok:!1,error:"empty shell response"}),{status:200,body:g}}let l;try{if(l=await s(),l.status===409&&l.body&&l.body.code==="EAUTH_REQUIRED"){let a=null;await Nt(l.body,r,o,n,async()=>{a=await s()},t)==="deny"?l={status:403,body:{ok:!1,code:"EDENIED",error:"user denied"}}:l=a}}catch(a){St({id:i,name:"shell",args:{cmd:e},ok:!1,result:{error:String(a)}},n),ne(n,"shell error","error"),n.sendBtn.current&&(n.sendBtn.current.disabled=!1);return}const c=l.body||{};St({id:i,name:"shell",ok:!!c.ok,result:c},n),l.status===403?ne(n,"shell tool is disabled for this project","error"):ne(n,c.ok?"shell exit "+(c.exitCode??0):"shell failed: "+(c.error||c.code||""),c.ok?"success":"error"),n.sendBtn.current&&(n.sendBtn.current.disabled=!1)}async function af(e,t,n,r){const{projectDir:o,chatId:i}=n.props;if(!o||!i)return;r.promptInput.current.value="",r._autoresize();const s={task:t,agent:e},l=Xt({id:"pending",name:"subagent",args:s},r);ne(r,"running agent "+e+"…","busy"),r.sendBtn.current&&(r.sendBtn.current.disabled=!0),typeof n._setRunningVisible=="function"&&n._setRunningVisible(!0);let c;try{c=await H("/api/tools/subagent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:o,chatId:i,task:t,agent:e})})}catch(f){l&&l.isConnected&&l.remove(),St({id:null,name:"subagent",args:s,ok:!1,result:{error:String(f)}},r),ne(r,"agent error","error"),r.sendBtn.current&&(r.sendBtn.current.disabled=!1),typeof n._setRunningVisible=="function"&&n._setRunningVisible(!1);return}const a=c.body||{},d=a.id||a.toolCall&&a.toolCall.id||null;l&&l.isConnected&&(d?l.dataset.toolId=String(d):a.ok||l.remove()),St({id:a.id||null,name:"subagent",ok:!!a.ok,result:a.result||a},r);const p=a.result&&typeof a.result.text=="string"?a.result.text:"";if(p){const f={role:"assistant",content:p,ts:new Date().toISOString(),modelId:a.result.model&&a.result.model.id,usage:a.result.usage||void 0,cost:a.result.cost||void 0};n.messages=n.messages.concat([f]),Kn(f,!1,r,n),ot(n,null,r)}c.status===403?ne(r,"subagent tool is disabled for this project","error"):a.ok?ne(r,"agent "+e+" done","success"):ne(r,"agent failed: "+(a.result&&a.result.error&&a.result.error.message||a.error||"unknown"),"error"),r.sendBtn.current&&(r.sendBtn.current.disabled=!1),typeof n._setRunningVisible=="function"&&n._setRunningVisible(!1)}async function lf(e,t,n,r,o,i){const{projectDir:s,chatId:l}=r.props;if(!s||!l||!e)return;const c=i||{},a="mcp_"+Date.now().toString(36)+Math.random().toString(36).slice(2,7);o.promptInput.current.value="",o._autoresize(),Xt({id:a,name:n||t,args:c},o),ne(o,"calling MCP "+(n||t)+"…","busy"),o.sendBtn.current&&(o.sendBtn.current.disabled=!0);async function d(){return H("/api/mcp/call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ru({projectDir:s,chatId:l,callId:a,serverId:e,toolName:t,args:c}))})}let p;try{if(p=await d(),p.status===409&&p.body&&p.body.code==="EAUTH_REQUIRED"){let h=null;p=await Nt(p.body,s,l,o,async()=>{h=await d()},r)==="deny"?{status:403,body:{ok:!1,code:"EDENIED",error:"user denied"}}:h}}catch(h){St({id:null,name:n||t,args:c,ok:!1,result:{error:String(h)}},o),ne(o,"MCP error","error"),o.sendBtn.current&&(o.sendBtn.current.disabled=!1);return}const f=p&&p.body||{};St({id:a,name:n||t,ok:p&&p.status===200&&f.ok!==!1,result:f},o),p&&p.status===403?ne(o,"MCP tool is disabled","error"):!p||p.status!==200?ne(o,"MCP failed: "+(f.error||f.code||"HTTP "+(p&&p.status)),"error"):ne(o,"MCP "+(n||t)+" done","success"),o.sendBtn.current&&(o.sendBtn.current.disabled=!1)}async function Ml(e,t,n,r={}){const{projectDir:o,chatId:i}=t.props;if(!o||!i)return;const s="restart_"+Date.now().toString(36)+Math.random().toString(36).slice(2,7),l=String(e||"").trim()||"User requested restart from chat";n.promptInput.current&&(n.promptInput.current.value=""),typeof r.clearComposerDraft=="function"&&await r.clearComposerDraft(),typeof r.setImageAttachments=="function"&&r.setImageAttachments([]),n._autoresize(),Xt({id:s,name:"restart_app",args:{reason:l}},n),ne(n,"restarting app…","busy"),n.sendBtn.current&&(n.sendBtn.current.disabled=!0);let c;try{c=await H("/api/restart",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:l,delayMs:1e3})})}catch(d){c={status:500,body:{ok:!1,error:String(d)}}}const a=c.body||{};St({id:s,name:"restart_app",ok:c.status===200&&a.ok!==!1,result:a},n),c.status===200&&a.ok!==!1?ne(n,"restart requested","success"):(ne(n,"restart failed: "+(a.error||a.code||"HTTP "+c.status),"error"),n.sendBtn.current&&(n.sendBtn.current.disabled=!1))}async function No(e,t,n){if(!e||!e.id)return;const{projectDir:r,chatId:o}=t.props,i="action_"+Date.now().toString(36)+Math.random().toString(36).slice(2,7),s="action:"+e.id;n.promptInput.current&&(n.promptInput.current.value=""),n._autoresize(),Xt({id:i,name:s,args:{action:e.label||e.id}},n),ne(n,"running "+(e.label||e.id)+"…","busy"),n.sendBtn.current&&(n.sendBtn.current.disabled=!0);async function l(){return H("/api/actions/"+encodeURIComponent(e.id)+"/run",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:r,chatId:o,callId:i})})}let c;try{if(c=await l(),c.status===409&&c.body&&c.body.code==="EAUTH_REQUIRED"){let f=null;c=await Nt(c.body,r,o,n,async()=>{f=await l()},t)==="deny"?{status:403,body:{ok:!1,error:"user denied"}}:f}}catch(f){c={status:500,body:{ok:!1,error:String(f)}}}const a=c&&c.body||{},d=a.result||a,p=d&&Array.isArray(d.content)?d.content.map(f=>f&&f.type==="text"?f.text:"").filter(Boolean).join(`
|
|
52
|
+
`):"";St({id:i,name:s,ok:c.status===200&&a.ok!==!1,result:d},n),c.status===200&&a.ok!==!1?ne(n,(e.label||e.id)+" done","success"):ne(n,(e.label||e.id)+" failed: "+(a.error||d.error||p||a.code||"unknown"),"error"),n.sendBtn.current&&(n.sendBtn.current.disabled=!1)}async function si(e,t){const n=await H("/api/chats/"+encodeURIComponent(t)+"/revision?projectDir="+encodeURIComponent(e));return n.status!==200||!n.body?null:{nextSeq:Number(n.body.nextSeq)||0,running:!!n.body.running}}async function Ol(e,t,n){const r=await H("/api/chats/"+encodeURIComponent(t)+"/messages?projectDir="+encodeURIComponent(e)+"&fromSeq="+n);return r.status!==200||!r.body||!Array.isArray(r.body.messages)?null:r.body}async function cf(e,t,n){const r=Math.max(1,Math.min(200,n&&n.limit||100));let o="/api/chats/"+encodeURIComponent(t)+"/messages?projectDir="+encodeURIComponent(e)+"&limit="+r;n&&typeof n.beforeSeq=="number"&&isFinite(n.beforeSeq)&&n.beforeSeq>=0&&(o+="&beforeSeq="+n.beforeSeq);const i=await H(o);return i.status!==200||!i.body||!Array.isArray(i.body.messages)?null:{messages:i.body.messages,total:typeof i.body.total=="number"?i.body.total:i.body.messages.length,hasMore:!!i.body.hasMore,beforeSeq:typeof i.body.beforeSeq=="number"&&isFinite(i.body.beforeSeq)?i.body.beforeSeq:null}}async function jl(e,t,n){if(!n||!e||!t||!n.hasMore||n.beforeSeq===null)return!1;const{projectDir:r,chatId:o}=e.props;try{const i=await cf(r,o,{limit:nf,beforeSeq:n.beforeSeq});if(!i||!Array.isArray(i.messages)||!i.messages.length)return n.hasMore=!1,n.beforeSeq=null,!0;typeof Lr=="function"&&Lr(t);const s=e.seenSeqs,l=i.messages.filter(a=>typeof a.seq!="number"?!0:s.has(a.seq)?!1:(s.add(a.seq),!0)),c=bp(e,t,l);if(l.length){const a=Array.isArray(e.messages)?e.messages:[],d=new Set;for(const f of a)typeof f.seq=="number"&&d.add(f.seq);const p=l.filter(f=>typeof f.seq!="number"||!d.has(f.seq));p.length&&(e.messages=p.concat(a))}return typeof i.beforeSeq=="number"&&i.beforeSeq>=0?n.beforeSeq=i.beforeSeq:i.messages.length&&typeof i.messages[0].seq=="number"?n.beforeSeq=i.messages[0].seq:n.beforeSeq=null,n.hasMore=!!i.hasMore,n.offset+=i.messages.length,n.firstSeq=l.length?l[0].seq:n.firstSeq,c}catch{return!1}}async function uf(e,t,n){if(!n||!e||!t||n.loading)return!1;n.loading=!0;try{return await jl(e,t,n)}finally{n.loading=!1}}async function df(e,t,n){if(!n||!e||!t||e.streaming||e.watchingRun||n.loading)return;n.loading=!0;const{projectDir:r,chatId:o}=e.props;try{if(await Cl(t),!n.hasMore||n.beforeSeq===null)return;for(;;){if(e.props.projectDir!==r||e.props.chatId!==o||e.streaming||e.watchingRun||typeof t.transcript>"u"||t.transcript&&!t.transcript.current)return;const i=n.beforeSeq;if(await jl(e,t,n),n.beforeSeq===i)return;await new Promise(s=>setTimeout(s,0))}}finally{n.loading=!1}}async function Ns(e,t,n){const{projectDir:r,chatId:o}=e.props,i=await Ol(r,o,0);return i?(e.messages=i.messages,e.costSnapshot=Qo(i),e.attributedCost=0,e.seenSeqs=new Set(i.messages.filter(s=>typeof s.seq=="number").map(s=>s.seq)),e.transcriptNextSeq=typeof i.nextSeq=="number"?i.nextSeq:n,e._renderTranscript&&e._renderTranscript(),"rebuilt"):null}function pf(e,t,n,r){if(!Array.isArray(r))return null;e.transcriptNextSeq=n;const o=e.messages,i=o.length,s=$p(e,r);if(s===o)return"appended";e.messages=s;const l=Jp(o,s);return l==="render"?e._renderTranscript&&e._renderTranscript():l==="append"&&dp(e,t,i),"appended"}async function ai(e,t,n){const{projectDir:r,chatId:o}=e.props,i=zp(e);if(n<i)return Ns(e,t,n);if(n===i)return e.transcriptNextSeq=n,"stable";const s=await Ol(r,o,i);if(!s)return null;if(typeof s.nextSeq=="number"&&s.nextSeq<i)return Ns(e,t,s.nextSeq);const l=pf(e,t,typeof s.nextSeq=="number"?s.nextSeq:n,s.messages),c=Qo(s);return c&&(e.costSnapshot=c,e.attributedCost=0),ot(e,null,t),l}function ff(e,t,n){const r=e.reconnect;if(r.active=!0,r.attempts=0,r.stopped=!1,r.partialText=n||"",e.streaming=!0,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!0),t.transcript&&t.transcript.current){const o=t.transcript.current.querySelectorAll('.tool-card--call[data-tool-name="shell"]:not(.tool-card--result) .tool-card__shell-live-hint');for(const i of o)i.textContent="Reconnecting — waiting for output…"}ne(t,"connection lost — reconnecting…","busy"),typeof e._kickPoll=="function"&&e._kickPoll()}function li(e){const t=e.reconnect;t.stopped=!0,t.active=!1,t.attempts=0}async function Dl(e,t){const{projectDir:n,chatId:r}=e.props;if(!n||!r||!t.transcript.current)return 0;const o=()=>e.props.projectDir===n&&e.props.chatId===r;let i;try{i=await H("/api/tools/authorization/pending?projectDir="+encodeURIComponent(n)+"&chatId="+encodeURIComponent(r))}catch{return 0}if(!o()||!t.transcript.current||i.status!==200||!i.body||!Array.isArray(i.body.pending))return 0;let s=0;for(const l of i.body.pending)if(!(!l||!l.callId))if(s++,l.tool==="ask_user"&&l.args){const c=Object.assign({},l.args,{callId:l.callId,tool:l.tool});Kt(t,l.callId,()=>{o()&&Rr(c,n,r,t,(a,d)=>ne(t,a,d))})}else Kt(t,l.callId,()=>{o()&&Nt(l,n,r,t,null,e)});return s}async function hf(e,t){const{projectDir:n,chatId:r}=e.props;if(!n||!r)return;ne(t,"cancelling…","busy");let o;try{o=await H("/api/tools/authorization/cancel",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:n,chatId:r})})}catch{ne(t,"cancel failed — server unreachable","error");return}if(o.status!==200){ne(t,"cancel failed: HTTP "+o.status,"error");return}yd(t),li(e),e.streaming=!1,e.watchingRun=!1,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1),t.sendBtn.current&&(t.sendBtn.current.disabled=!1),await Fl(e,t),ne(t,"cancel requested","success")}function Bl(e){const t=e&&e.streamAbort;if(!t)return!1;e.streamAbort=null;try{t.abort()}catch{}return!0}async function ci(e,t,n){const{content:r,attachments:o,clearComposerDraft:i,setImageAttachments:s,retry:l,manualRetry:c}=n||{},{projectDir:a,chatId:d}=e.props;if(!a||!d)return;const p=e.chat||{},f=p.modelId||"",h=p.providerId||"",g=(r??(t.promptInput.current.value||"")).trim(),v=o||e.imageAttachments,b=Vt(v);if(!g&&!b.length){t.status.current&&(t.status.current.textContent="type something or add an image");return}if(e.streaming||e.watchingRun){ne(t,"wait for the current response to finish","busy");return}if(g.startsWith("/shell ")){const F=g.slice(7).trim();if(F)return Ps(F,e,t)}const k=Zo(g);if(k)return Ml(k.reason,e,t,{clearComposerDraft:i,setImageAttachments:s});const _=qa(g);if(_){const F=_.toolName,R=_.rest,$=Ua(g,e.customActions);if($)return No($,e,t);if(R&&Array.isArray(e.agents)&&e.agents.some(fe=>fe&&fe.name===F))return af(F,R,e,t);const de=((e.tools||{catalog:[]}).catalog||[]).find(fe=>fe&&fe.name===F);if(de){if(String(F).startsWith("mcp__")){const fe=String(F).split("__");if(fe.length>=3&&de.serverId){const Be=fe.slice(2).join("__"),Fe=R?Lu(R):null;if(Fe)return lf(de.serverId,Be,F,e,t,Fe)}}else if(F==="shell"&&R)return Ps(R,e,t)}}if(!f||!h){const F=e.providers.length?"pick a model":"add a provider in Settings → Providers";ne(t,F,"error"),e._openModelPicker&&e._openModelPicker();return}e.streaming=!0,e.nextLiveSeq=0,t.sendBtn.current&&(t.sendBtn.current.disabled=!0),typeof e._setRunningVisible=="function"&&e._setRunningVisible(!0),ne(t,"preparing message…","busy");try{if(e._persistedModelPair!==h+"|"+f&&await pl({providerId:h,modelId:f},e,t)===!1)throw new Error("model settings could not be saved");if(!l&&i&&await i()===!1)throw new Error("draft could not be saved")}catch{e.streaming=!1,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1),t.sendBtn.current&&(t.sendBtn.current.disabled=!1),ne(t,"Could not prepare message — your draft is unchanged. Try sending again.","error");return}ne(t,"streaming…","busy"),l||(t.promptInput.current&&(t.promptInput.current.value=""),s&&s([]),t.imageInput.current&&(t.imageInput.current.value=""),t._autoresize());const y=l?null:{role:"user",content:g,attachments:b,ts:new Date().toISOString()};l||(e.messages=e.messages.concat([y]),Kn(y,!1,t,e),e._updateSetupVisibility&&e._updateSetupVisibility());const w=bu(),N=(()=>{const F=e.thinkingLevel||"";return F==="__custom__"?t.thinkingLevelCustom&&t.thinkingLevelCustom.current&&t.thinkingLevelCustom.current.value.trim()||"":F})();let O;const P=new AbortController;e.streamAbort=P;try{O=await fetch("/api/chats/"+encodeURIComponent(d)+"/messages/stream",{method:"POST",headers:{"Content-Type":"application/json"},signal:P.signal,body:JSON.stringify({projectDir:a,modelId:f,providerId:h,content:g,attachments:b,thinkingLevel:N,maxOutputTokens:e.maxOutputTokens||""})})}catch(F){if(F&&F.name==="AbortError"){e.streamAbort===P&&(e.streamAbort=null),e.streaming=!1,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1),t.sendBtn.current&&(t.sendBtn.current.disabled=!1);return}const R="Network error — could not reach the server. Your message was sent to the transcript but the response never started.",$={content:g,attachments:b,clearComposerDraft:i,setImageAttachments:s,retry:l,manualRetry:c};ne(t,"network error","error"),yr(R+" Try again.",t,e,{onRetry:()=>vr(e,t,$)}),e.streaming=!1,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1),t.sendBtn.current&&(t.sendBtn.current.disabled=!1),Is(e,t,$);return}if(!O.ok){let F="";try{F=await O.text()}catch{}let R="HTTP "+O.status;try{const se=JSON.parse(F);se&&se.error&&(R=se.error)}catch{}if(O.status===409){if(l){ne(t,"a response is already streaming — retry later","busy"),e.streaming=!1,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1),t.sendBtn.current&&(t.sendBtn.current.disabled=!1);return}e.messages=e.messages.filter(se=>se!==y),e._renderTranscript&&e._renderTranscript(),t.promptInput.current&&(t.promptInput.current.value=g,t._autoresize()),s(v),e._updateChat&&jn(g,t,e._updateChat,{draftAttachments:b}).catch(()=>{}),ne(t,"a response is already streaming — your message is back in the composer","busy"),e.streaming=!1,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1),t.sendBtn.current&&(t.sendBtn.current.disabled=!1);return}ne(t,R,"error");const $={content:g,attachments:b,clearComposerDraft:i,setImageAttachments:s,retry:l,manualRetry:c};yr(R,t,e,{onRetry:()=>vr(e,t,$)}),e.streaming=!1,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1),t.sendBtn.current&&(t.sendBtn.current.disabled=!1),Is(e,t,$);return}const Y=O.body.getReader(),re=new TextDecoder("utf-8");let z="",I="",D="",V=null,Z=null,oe=null,ie=0,_e=0,ye=0,we=0,He=0,De=0;function pe(){const F={modelId:f,usage:V,cost:Z,streamingMs:oe,liveRate:w.rate(V&&V.completionTokens)};return ie>0&&(F.liveCost={known:!0,total:ie,currency:"USD"}),F}function ae(){if(!t.transcript.current)return;const F=t.transcript.current.querySelector('[data-live="1"]');if(!F)return;const R=F.querySelector(".chat-msg__meta");if(!R)return;const $=pe();gr(R,$,e),ot(e,$,t)}let le=!1,W=!1;function G(F,R){if(F.eventName==="subagent_event"&&R){vl({eventName:R.kind},Object.assign({parentCallId:R.parentCallId},R.data||{}),t);return}if(F.eventName==="shell_output"&&R){ni(R,t);return}if(R&&R.parentTool==="subagent"&&F.eventName==="authorization_required"){Kt(t,R&&R.callId,()=>Nt(R,a,d,t,null,e));return}if(R&&R.parentTool==="subagent"&&F.eventName==="ask_user_required"){Kt(t,R&&R.callId,()=>Rr(R,a,d,t,($,se)=>ne(t,$,se)));return}if(F.eventName==="message"&&typeof R.delta=="string"){I+=R.delta,w.add(R.delta),Od(R.delta,t,e);const $=performance.now?performance.now():Date.now();$-De>120&&(De=$,ae())}else if(F.eventName==="reasoning"&&typeof R.delta=="string"){D+=R.delta,w.add(R.delta),jd(R.delta,t,e);const $=performance.now?performance.now():Date.now();$-De>120&&(De=$,ae())}else if(F.eventName==="done"){if(R.usage){const de=V||{},fe=Number(R.usage.promptTokens),Be=Number(R.usage.completionTokens),Fe=Number(R.usage.cacheReadTokens),Ce=Number(R.usage.cacheCreationTokens);isFinite(fe)&&fe>0&&(de.promptTokens=fe),isFinite(Be)&&Be>0&&(de.completionTokens=Be),isFinite(Fe)&&Fe>0&&(de.cacheReadTokens=Fe),isFinite(Ce)&&Ce>0&&(de.cacheCreationTokens=Ce),V=de}Z=R.cost||Z,oe=typeof R.streamingMs=="number"?R.streamingMs:oe,_e=0,ye=0,ie=0,ae();const $=e.chat;(!$||!$.title||$.title==="New chat")&&Sd(e,t)}else if(F.eventName==="usage_input"){const $=Number(R&&R.promptTokens);isFinite($)&&$>0&&(V=V||{},(!V.promptTokens||$>V.promptTokens)&&(V.promptTokens=$),_e=$,ae());const se=Number(R&&R.cacheReadTokens),de=Number(R&&R.cacheCreationTokens);isFinite(se)&&se>0&&(V=V||{},V.cacheReadTokens=se),isFinite(de)&&de>0&&(V=V||{},V.cacheCreationTokens=de),isFinite(se)&&se>0&&(we=se),isFinite(de)&&de>0&&(He=de)}else if(F.eventName==="usage_output"){const $=Number(R&&R.completionTokens);isFinite($)&&$>0&&(V=V||{},V.completionTokens=(V.completionTokens||0)+$,ye+=$,ae())}else if(F.eventName==="usage_update"){const $=R&&R.cost;$&&$.known&&typeof $.total=="number"&&$.total>0&&(ie+=$.total,ot(e,pe(),t))}else if(F.eventName==="assistant_turn_end"){const $=I,se=D;if($.trim()||se.trim()){uo({content:$,reasoning:se},t);const de=R.usage||(_e||ye||we||He?{promptTokens:_e||void 0,completionTokens:ye||void 0,cacheReadTokens:we||void 0,cacheCreationTokens:He||void 0}:void 0),fe=R.cost||void 0;if(e.messages=e.messages.concat([{role:"assistant",content:$,reasoning:se,ts:new Date().toISOString(),modelId:f,usage:de,cost:fe}]),t.transcript.current){const Be=t.transcript.current.querySelectorAll(".chat-msg--assistant"),Fe=Be.length?Be[Be.length-1]:null;if(Fe){const Ce=Fe.querySelector(".chat-msg__meta");Ce&&gr(Ce,{modelId:f,usage:de,cost:fe},e)}}_e=0,ye=0,we=0,He=0}I="",D=""}else if(F.eventName==="authorization_required"||F.eventName==="ask_user_required")Kt(t,R&&R.callId,()=>{F.eventName==="authorization_required"?Nt(R,a,d,t,null,e):Rr(R,a,d,t,($,se)=>ne(t,$,se))});else if(F.eventName==="tool_call")sf(e,t,R&&R.name),Xt(R,t);else if(F.eventName==="tool_result")St(R,t);else if(F.eventName==="progress_update"){bl(t,R);const $=R.current!=null&&R.total!=null?Math.round(Number(R.current)/Math.max(1,Number(R.total))*100)+"%":R.status||"running";ne(t,R.title+" "+$,"busy")}else if(F.eventName==="error"){le=!0,_e=0,ye=0;const $={content:g,attachments:b,clearComposerDraft:i,setImageAttachments:s,retry:l,manualRetry:c};yr((R.message||"Request failed")+(R.detail?`
|
|
53
|
+
`+String(R.detail).slice(0,500):""),t,e,{onRetry:()=>vr(e,t,$)}),ne(t,"error: "+(R.code||"")+" "+(R.message||""),"error")}}try{for(;;){if(e.props.projectDir!==a||e.props.chatId!==d){W=!0,Bl(e);break}const{value:F,done:R}=await Y.read();if(R)break;z+=re.decode(F,{stream:!0});let $;for(;($=z.indexOf(`
|
|
54
|
+
|
|
55
|
+
`))!==-1;){const se=z.slice(0,$);z=z.slice($+2);const de=ka(se);if(!de)continue;let fe;try{fe=JSON.parse(de.data)}catch{continue}try{G(de,fe)}catch(Be){console.error("chat SSE event failed",de.eventName,Be)}}}}catch(F){W=!!(F&&F.name==="AbortError")||P.signal.aborted,W||(le=!0,_e=0,ye=0,console.error("chat SSE reader failed",F),ne(t,"stream interrupted: "+(F&&F.message?F.message:"connection closed"),"error"))}finally{e.streamAbort===P&&(e.streamAbort=null);try{Y.releaseLock()}catch{}t.sendBtn.current&&(t.sendBtn.current.disabled=!1)}if(P.signal.aborted&&(W=!0),W){w.reset(),e.streaming=!1,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1);return}if(le){uo({content:I,reasoning:D},t),w.reset(),ff(e,t,I);return}const he=t.transcript.current?t.transcript.current.querySelector('[data-live="1"]'):null;if(!!(I.trim()||D.trim())){uo({content:I,reasoning:D},t);const F=w.rate(V&&V.completionTokens),R={role:"assistant",content:I,reasoning:D,ts:new Date().toISOString(),modelId:f,usage:V||void 0,cost:Z||void 0,streamingMs:oe||void 0,liveRate:F};if(e.messages=e.messages.concat([R]),ot(e,null,t),he){const $=he.querySelector(".chat-msg__meta");$&&gr($,R,e)}}else he&&he.parentNode&&(he.remove(),ot(e,null,t));w.reset();try{const F=await si(a,d);F&&await ai(e,t,F.nextSeq)}catch(F){console.error("chat transcript reconciliation failed",F)}if(t.status.current&&t.status.current.textContent==="streaming…"){const F=V&&(V.promptTokens!=null||V.completionTokens!=null);ne(t,F?"done — "+(V.promptTokens||0)+" in, "+(V.completionTokens||0)+" out":"done","success")}t.sendBtn.current&&(t.sendBtn.current.disabled=!1),e.streaming=!1,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1)}async function mf(e,t){const{projectDir:n,chatId:r}=e.props,o=e.reconnect;if(!o||!o.active||o.stopped)return o&&(o.active=!1),!1;o.attempts+=1;const i=await si(n,r).catch(()=>null);if(!i)return o.attempts<6?!0:Cn(e,t,"could not reconnect — tap to retry",!0);const s=await ai(e,t,i.nextSeq).catch(()=>null);if(s==null)return o.attempts<6?!0:Cn(e,t,"could not reconnect — tap to retry",!0);if(s!=="stable")return o.stableTicks=0,ne(t,"reconnected — syncing…","busy"),!0;const l=e.messages[e.messages.length-1],c=l&&l.role==="tool"&&l.phase==="call";return o.stableTicks=(o.stableTicks||0)+1,!i.running&&!c||!c&&o.stableTicks>=2?Cn(e,t,null,!1):o.attempts>=8?Cn(e,t,"reconnect timed out — pull to retry",!0):!0}function Cn(e,t,n,r){const o=e.reconnect;return o.active=!1,o.stopped=!1,o.attempts=0,o.stableTicks=0,e.streaming=!1,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1),t.sendBtn.current&&(t.sendBtn.current.disabled=!1),n?ne(t,n,r?"error":"success"):ne(t,"reconnected","success"),!1}async function Fl(e,t){const{chatId:n,projectDir:r}=e.props;if(!(!n||!r)){if(e.reconnect&&e.reconnect.active)return mf(e,t);if(!e.streaming)try{const o=await si(r,n);if(!o)return;const i=!!o.running,s=e.watchingRun,l=await ai(e,t,o.nextSeq),c=l&&l!=="stable";if(c&&e.runSettled&&(e.runSettled=!1),i){const a=r+"::"+n;Nl(e,t);const d=e.liveRun&&e.liveRun.key===a?e.liveRun:null,p=!!(d&&(d.active||d.connected)&&!d.ended&&!d.failed),f=e.messages[e.messages.length-1],h=f&&f.role==="tool"&&f.phase==="call",g=!c&&!h&&e.messages.length>0&&!p;if((!s||c||g||e.pendingAuthCount>0||e.runSettled)&&(e.pendingAuthCount=await Dl(e,t)),e.pendingAuthCount>0&&(e.runSettled=!1),e.runSettled){e.watchingRun=!1,e.watchingStableTicks=0,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1);return}e.watchingRun=!0,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!0),e.pendingAuthCount>0?(e.watchingStableTicks=0,ne(t,"waiting for you…","busy")):g?(ne(t,"streaming…","busy"),e.watchingStableTicks=(e.watchingStableTicks||0)+1,e.watchingStableTicks>=2&&(e.watchingRun=!1,e.watchingStableTicks=0,e.runSettled=!0,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1),ne(t,"done","success"))):(ne(t,"streaming…","busy"),e.watchingStableTicks=0)}else e.watchingRun?(e.pendingAuthCount=0,e.watchingRun=!1,e.watchingStableTicks=0,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1),ne(t,"done","success")):typeof e._setRunningVisible=="function"&&(e.pendingAuthCount=0,e._setRunningVisible(!1),e.watchingStableTicks=0)}catch{}}}function gf(e){return new Promise((t,n)=>{if(!e||!/^image\/(png|jpe?g|webp|gif)$/i.test(e.type||""))return t(null);const r=new FileReader;r.onload=()=>t({type:"image",mimeType:e.type,dataUrl:String(r.result||""),name:e.name||"image"}),r.onerror=()=>n(r.error||new Error("image read failed")),r.readAsDataURL(e)})}async function Rs(e,{setImageAttachments:t,setChatStatus:n,updateChat:r}){const o=Array.from(e||[]).filter(i=>i&&/^image\/(png|jpe?g|webp|gif)$/i.test(i.type||""));if(o.length)try{const s=(await Promise.all(o.map(gf))).filter(Boolean).map(Jn).filter(Boolean);if(!s.length){n("image is too large","error");return}t(l=>{const c=l.concat(s).slice(0,8);return r&&r({draftAttachments:Vt(c)}).catch(()=>{}),c}),n(s.length===1?"image attached":s.length+" images attached","success")}catch{n("could not read image","error")}}function _f(e,t,n){t(r=>{const o=r.filter((i,s)=>s!==e);return n&&n({draftAttachments:Vt(o)}).catch(()=>{}),o})}const yf="fileOrbButton",Ro=!1;function vf(e){const t=e&&e.app;if(!t||typeof t!="object")return Ro;const n=t[yf];return typeof n=="boolean"?n:n==="true"?!0:n==="false"?!1:Ro}const mo=Object.freeze({2:8,3:8,4:6.5,5:6});function Ls(e){const t=Number(e);return!Number.isFinite(t)||t<=2?mo[2]+"px":t>=5?mo[5]+"px":mo[Math.floor(t)]+"px"}const bf="dictationButton",wf="imageButton",ql=Object.freeze({dictation:!0,image:!0});function Ms(e,t){return typeof e=="boolean"?e:e==="true"?!0:e==="false"?!1:t}function Cf(e){const t=e&&e.app,n=ql;return!t||typeof t!="object"?{dictation:n.dictation,image:n.image}:{dictation:Ms(t[bf],n.dictation),image:Ms(t[wf],n.image)}}function kf(e,t){return"/api/tools/authorization?projectDir="+encodeURIComponent(e)+(t?"&chatId="+encodeURIComponent(t):"")}function Sf(e){const{projectDir:t,chatId:n}=e,[r,o]=E([]),[i,s]=E(""),[l,c]=E(!1),[a,d]=E(!1),[p,f]=E(0),[h,g]=E(0),[v,b]=E(null),[k,_]=E(!1),[y,w]=E([]),[N,O]=E(!1),[P,Y]=E([]);x(-1);const[re,z]=E(()=>({models:[],value:null,pinned:new Set,recent:[],open:!1,providers:[]})),I=x(0),D=We(m=>{m||(I.current+=1),z(L=>L.open===m?L:{...L,open:m})},[]),V=x({projectDir:"",offset:0,total:1/0,loading:!1}),Z=x(!1),oe=x([]);function ie(m){oe.current=typeof m=="function"?m(oe.current):m,o(oe.current)}const _e=x("");function ye(m){_e.current=typeof m=="string"?m:"",s(_e.current)}const we=x(null),He=x(null),De=x(null),pe=x(null),ae=x(null),le=x(null),W=x(null),G=x(null),he=x(null),Pe=x(null),F=x(null),R=x(null),$=x(null),se=x(null),de=x(null),fe=x(null),Be=x(null),Fe=x(null),Ce=x(null),ut=x(null),Ne=x(!0),it=x(0),dt=x(!1),Je=x(0),st=x(0),X=x(""),ee=x([]),C=x([]),j=x({}),q=x([]),J=x({q:"",provider:"all"}),A=x(null),M=x({catalog:[],filter:null}),ve=x({files:[],enabled:!0,explicit:!1}),Ae=x({items:[],enabled:!0,projectLocked:!1}),T=x([]),B=x(null),te=x([]),Se=x({}),be=x({mode:"ask",allowlist:[],servers:{},tools:{}}),Me=x(""),Re=x(""),Qe=x(!0),at=x(!0),[Rt,Yn]=E(Ro),[Lt,Ql]=E(()=>Object.assign({},ql)),zr=x(new Set),Qt=x(new Set),$r=x({active:!1,attempts:0,timer:null,stopped:!1,partialText:""}),Jr=x(null),Gr=x(0),Kr=x(!1),Zr=x({key:"",active:!1,connected:!1,ended:!1,failed:!1}),Yr=x(!1),pi=x(null),fi=x([]),hi=x(null),Xr=x(null);Xr.current||(Xr.current={props:{projectDir:t,chatId:n},_setRunningVisible:d,_kickPoll:()=>{Jr.current&&Jr.current()},get chat(){return pi.current},set chat(m){pi.current=m},get providers(){return fi.current},set providers(m){fi.current=Array.isArray(m)?m:[]},get imageAttachments(){return oe.current},set imageAttachments(m){oe.current=m},get messages(){return ee.current},set messages(m){ee.current=m},get models(){return C.current},set models(m){C.current=m},get liveByProvider(){return j.current},set liveByProvider(m){j.current=m},get prompts(){return q.current},set prompts(m){q.current=m},get pickerFilter(){return J.current},set pickerFilter(m){J.current=m},get systemPrompt(){return A.current},set systemPrompt(m){A.current=m},get tools(){return M.current},set tools(m){M.current=m},get agentFiles(){return ve.current},set agentFiles(m){ve.current=m},get skills(){return Ae.current},set skills(m){Ae.current=m},get mcpServers(){return T.current},set mcpServers(m){T.current=m},get agents(){return te.current},set agents(m){te.current=Array.isArray(m)?m:[]},get usedTools(){return zr.current},set usedTools(m){zr.current=m instanceof Set?m:new Set(m||[])},get seenSeqs(){return Qt.current},set seenSeqs(m){Qt.current=m instanceof Set?m:new Set(m||[])},get transcriptNextSeq(){return Je.current},set transcriptNextSeq(m){Je.current=m},get nextLiveSeq(){return st.current},set nextLiveSeq(m){st.current=m},get _persistedModelPair(){return X.current},set _persistedModelPair(m){X.current=m},get streaming(){return dt.current},set streaming(m){dt.current=m},reconnect:$r.current,get watchingRun(){return Kr.current},set watchingRun(m){Kr.current=m},get watchingStableTicks(){return Gr.current},set watchingStableTicks(m){Gr.current=m},get liveRun(){return Zr.current},set liveRun(m){Zr.current=m&&typeof m=="object"?m:{key:"",active:!1,connected:!1,ended:!1,failed:!1}},get runSettled(){return Yr.current},set runSettled(m){Yr.current=m},get providerCredit(){return hi.current},set providerCredit(m){hi.current=m},get toolAuth(){return Se.current},set toolAuth(m){Se.current=m instanceof Object&&!Array.isArray(m)?m:{}},get mcpAuth(){return be.current},set mcpAuth(m){be.current=m instanceof Object&&!Array.isArray(m)?m:{mode:"ask",allowlist:[],servers:{},tools:{}}},get thinkingLevel(){return Me.current},set thinkingLevel(m){Me.current=m},get maxOutputTokens(){return Re.current},set maxOutputTokens(m){Re.current=m},get enterForNewline(){return Qe.current},set enterForNewline(m){Qe.current=!!m},get autoRetry(){return at.current},set autoRetry(m){at.current=!!m}});const S=Xr.current;S.props={projectDir:t,chatId:n},S.customActions=P,S._setCustomActions=m=>{const L=Array.isArray(m)?m:[];JSON.stringify(S.customActions||[])!==JSON.stringify(L)&&(S.customActions=L,Y(L))};const ec=x(null),tc=x(null),Qr=x(null);Qr.current||(Qr.current={back:we,chatName:He,chatMeta:De,usageSummaryRef:pe,usageSummary:pe,providerCreditRef:ae,setupCard:le,transcript:W,thinkingLevel:G,thinkingLevelCustom:he,maxOutputTokens:Pe,promptInput:F,imageInput:R,draftSaveTimer:$,sendBtn:se,stopBtn:de,status:fe,jumpBtn:Be,toolsCard:Fe,agentFilesCard:Ce,skillsCard:ut,pinnedToBottom:Ne,pendingCount:it,chatSwitcherTrigger:ec,chatSwitcherPop:tc,_autoresize:()=>En({promptInput:F})});const K=Qr.current,nc=We(async()=>{if(t)try{const m=await H("/api/actions?projectDir="+encodeURIComponent(t));m.status===200&&Array.isArray(m.body&&m.body.actions)&&(S.customActions=m.body.actions,Y(m.body.actions))}catch{}},[t]);function Xn(m){if(!m||typeof m!="object")return;const L=m.chat&&typeof m.chat=="object"?m.chat:null,U=m.tools;if(U&&typeof U=="object"){const ge={};for(const ce of["shell","file","subagent","task","webpreview","restart_app","report_progress"])U[ce]&&(ge[ce]={mode:U[ce].mode||"ask",allowlist:Array.isArray(U[ce].allowlist)?U[ce].allowlist:[]});U.ask_user&&(ge.ask_user={mode:U.ask_user.mode==="off"?"off":"ask"}),Se.current=ge}const Q=m.mcp;if(Q&&typeof Q=="object"){const ge=be.current;be.current={mode:Q.mode||ge.mode,allowlist:Array.isArray(Q.allowlist)?Q.allowlist:ge.allowlist,servers:Q.servers&&typeof Q.servers=="object"?Q.servers:ge.servers,tools:Q.tools&&typeof Q.tools=="object"?Q.tools:ge.tools}}S._chatAuthOverrides=L}S._applyChatAuthResponse=Xn;function rc(m,L,U,Q){return H("/api/chats/"+encodeURIComponent(L),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:m,draft:U||"",draftAttachments:Array.isArray(Q)&&Q.length?Q:null})})}const qe=We(async m=>{if(!t||!n)return;const L=Object.assign({},m||{});Object.prototype.hasOwnProperty.call(L,"draftAttachments")&&Array.isArray(L.draftAttachments)&&(L.draftAttachments=Vt(L.draftAttachments));const U=await H("/api/chats/"+encodeURIComponent(n),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(Object.assign({projectDir:t},L))});if(U.status!==200)return fe.current&&(fe.current.textContent="HTTP "+U.status),!1;const Q=Object.keys(L);if(Q.length>0&&Q.every(ce=>ce==="draft"||ce==="draftAttachments")){const ce={};for(const xe of Q)ce[xe]=U.body.chat[xe];return S.chat=Object.assign({},S.chat,ce),!0}return S.chat=U.body.chat,S._persistedModelPair=(U.body.chat.providerId||"")+"|"+(U.body.chat.modelId||""),xo(K,S),lo(S,K),en(),!0},[t,n]);function oc(){bn(K,S)}function en(){const m=S.chat;z(L=>({models:io(S),providers:S.providers.map(U=>U&&U.id).filter(Boolean),value:m&&m.providerId&&m.modelId?{providerId:m.providerId,modelId:m.modelId}:null,pinned:Vn(S),recent:Bt(S),open:L.open}))}function mi(){const m=++I.current,L=S.props&&S.props.projectDir,U=S.chat;z({models:io(S),providers:S.providers.map(Q=>Q&&Q.id).filter(Boolean),value:U&&U.providerId&&U.modelId?{providerId:U.providerId,modelId:U.modelId}:null,pinned:Vn(S),recent:Bt(S),open:!0}),La(S).then(Q=>{if(!Q||m!==I.current||!S.props||S.props.projectDir!==L)return;const ge=S.chat;z(ce=>ce.open?{...ce,models:io(S),providers:S.providers.map(xe=>xe&&xe.id).filter(Boolean),value:ge&&ge.providerId&&ge.modelId?{providerId:ge.providerId,modelId:ge.modelId}:ce.value,recent:Bt(S)}:ce)})}S._onChatChanged=()=>oc(),S._onLiveModels=()=>{bn(K,S),en()},S._openModelPicker=()=>{mi()},S._onRefreshAllProviders=()=>es(S),S._updateToolsCard=()=>{if(K.toolsCard.current&&K.toolsCard.current.parentNode){const m=Xo(S);K.toolsCard.current.parentNode.replaceChild(m,K.toolsCard.current),K.toolsCard.current=m}},S._runCustomAction=m=>No(m,S,K),S._runRestartCommand=m=>Ml(m,S,K,{clearComposerDraft:()=>Ts(t,n,K,qe),setImageAttachments:ie});const gi=We(async()=>{try{await ci(S,K,{clearComposerDraft:()=>Ts(t,n,K,qe),setImageAttachments:ie})}finally{ye(K.promptInput.current?K.promptInput.current.value:"")}},[t,n,qe]),ic=We((m,L)=>{_d(m,L,S,K,qe),g(U=>U+1)},[qe]),sc=We((m,L)=>{bd(m,L,S,K,qe),g(U=>U+1)},[qe]),ac=We(m=>{hd(m,S,K,qe,()=>_r(S,K)),g(L=>L+1)},[qe]),lc=We(m=>{md(m,S,K,qe,()=>_r(S,K)),g(L=>L+1)},[qe]),cc=We((m,L)=>{m&&(gd(m,L,S,K,qe,()=>_r(S,K)),g(U=>U+1))},[qe]),uc=We(()=>hf(S,K),[t,n]),_i=We((m,L)=>{const U=m&&typeof m=="object"?m.providerId:m,Q=m&&typeof m=="object"?m.modelId:L;if(!U||!Q||(D(!1),S.chat&&S.chat.providerId===U&&S.chat.modelId===Q))return;Ma(S,U,Q);const ge=Object.assign({},S.chat,{providerId:U,modelId:Q});S.chat=ge,z(ce=>({...ce,value:{providerId:U,modelId:Q},recent:Bt(S),open:!1})),bn(K,S),lo(S,K),qe({providerId:U,modelId:Q})},[qe]);S._onPickerPick=_i,S._updateChat=qe;const yi=We(()=>{xl(S,K),Eo(cs(S),K)},[]);S._renderTranscript=yi,S._retryFailedTurn=m=>vr(S,K,m),S._updateSetupVisibility=()=>us(S,K),S._toggleTool=ic,S._toggleToolGroup=sc,S._toggleAgentFiles=ac,S._toggleSkills=lc,S._toggleSkill=cc,S._saveToolAuth=async(m,L,U)=>{const Q=t;if(!Q||!n)return;const ge=L==null?null:{mode:L,allowlist:U||[]},ce=await Zu(Q,n,{native:{[m]:ge}});ce.status===200&&ce.body&&(Xn(ce.body),S._updateToolsCard&&S._updateToolsCard(),f(xe=>xe+1))},S._saveMcpAuth=async m=>{const L=t;if(!L||!n||!m||typeof m!="object")return;const U=await Yu(L,n,m);U.status===200&&U.body&&(Xn(U.body),S._updateToolsCard&&S._updateToolsCard(),f(Q=>Q+1))},S._reloadMcpServer=async m=>{const L=t;if(!L||!m)return!1;try{return(await H("/api/mcp/servers/"+encodeURIComponent(m)+"/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:L})})).status===200}catch{return!1}},S._reloadMcpServerRefresh=async()=>{const m=t;if(!m)return;const[L,U]=await Promise.all([H("/api/mcp/servers?projectDir="+encodeURIComponent(m)),H("/api/tools/list?projectDir="+encodeURIComponent(m))]);L.status===200&&Array.isArray(L.body.servers)&&(T.current=L.body.servers),U.status===200&&Array.isArray(U.body.tools)&&(M.current=Object.assign({},M.current,{catalog:U.body.tools})),g(Q=>Q+1),S._updateToolsCard&&S._updateToolsCard()},S._startMcpServer=async m=>{if(!t||!m||v)return!1;b(m),S._mcpStartBusyServerId=m;try{const U=await S._reloadMcpServer(m);return await S._reloadMcpServerRefresh(),U}finally{S._mcpStartBusyServerId=null,b(null)}},ue(()=>{let m=!1;async function L(){if(!(!t||!n))try{const[U,Q,ge,ce,xe,Ee,Ie,Mt,At,Qn]=await Promise.all([H("/api/chats/"+encodeURIComponent(n)+"?projectDir="+encodeURIComponent(t)),$c(t),H("/api/ai/models/providers"),H("/api/chats/"+encodeURIComponent(n)+"/messages?projectDir="+encodeURIComponent(t)+"&limit=100"),H("/api/prompts?projectDir="+encodeURIComponent(t)),H("/api/chats/"+encodeURIComponent(n)+"/system-prompt?projectDir="+encodeURIComponent(t)),H("/api/mcp/servers?projectDir="+encodeURIComponent(t)),H("/api/agents?projectDir="+encodeURIComponent(t)),H("/api/actions?projectDir="+encodeURIComponent(t)),Ca({force:!0}).catch(()=>null)]);if(m)return;if(U.status!==200){fe.current&&(fe.current.textContent="chat not found"),en();return}const Oe=U.body.chat;S.chat=Oe;const er=Qn&&Qn.app||{};S.enterForNewline=typeof er.enterForNewline=="boolean"?er.enterForNewline:!0,S.autoRetry=typeof Oe.autoRetry=="boolean"?Oe.autoRetry:typeof er.autoRetry=="boolean"?er.autoRetry:!0,Yn(vf(Qn)),Ql(Cf(Qn)),X.current=(Oe.providerId||"")+"|"+(Oe.modelId||""),ee.current=ce.status===200?ce.body.messages||[]:[],S.costSnapshot=ce.status===200?Qo(ce.body):null,S.attributedCost=0,B.current=Es(),rf(B.current,ce.status===200?{messages:ee.current,total:ce.body.total,hasMore:ce.body.hasMore,beforeSeq:ce.body.beforeSeq}:{messages:[],total:0,hasMore:!1});{const ke=new Set;for(const ht of ee.current)typeof ht.seq=="number"&&ke.add(ht.seq);Qt.current=ke}Je.current=ce.status===200&&ce.body&&typeof ce.body.nextSeq=="number"?ce.body.nextSeq:Qt.current.size?Math.max(...Qt.current)+1:0,st.current=0,C.current=Q&&Array.isArray(Q.models)?Q.models:[],S.providers=ge.status===200?ge.body.providers||[]:[],j.current={};for(const ke of C.current){if(!ke||!ke.id||!ke.provider)continue;const ht=j.current[ke.provider]||(j.current[ke.provider]=[]),xt={id:ke.id,label:ke.label,contextWindow:ke.contextWindow};ke.thinking&&(xt.thinking=ke.thinking),ht.push(xt)}J.current={q:"",provider:"all"},q.current=xe.status===200?xe.body.prompts||[]:[],A.current=Ee.status===200?Ee.body:null,M.current={catalog:[],filter:Array.isArray(Oe.tools)?Oe.tools.slice():null};const vi=Ee.status===200?Ee.body.projectAgentFiles:null,pc=Ee.status===200&&typeof Ee.body.agentFilesEnabled=="boolean"?Ee.body.agentFilesEnabled:vi===!1?!1:typeof Oe.agentFiles=="boolean"?Oe.agentFiles:!0,fc=Ee.status===200&&Array.isArray(Ee.body.agentFilesAvailable)?Ee.body.agentFilesAvailable:Array.isArray(Ee.body&&Ee.body.agentFiles)?Ee.body.agentFiles:[];ve.current={files:fc.map(ke=>ke.name),enabled:pc,explicit:typeof Oe.agentFiles=="boolean",projectLocked:vi===!1};const bi=Ee.status===200?Ee.body.projectSkills:!0,hc=Ee.status===200&&Array.isArray(Ee.body.skills)?Ee.body.skills:[];Ae.current={items:hc.map(ke=>({id:ke.id,name:ke.name,description:ke.description,disabled:!!ke.disabled,chatDisabled:!!ke.chatDisabled})),enabled:bi!==!1&&(typeof Ee.body.skillsEnabled=="boolean"?Ee.body.skillsEnabled:Oe.skills!==!1),projectLocked:bi===!1},T.current=Ie.status===200&&Array.isArray(Ie.body.servers)?Ie.body.servers:[],te.current=Mt.status===200&&Array.isArray(Mt.body.agents)?Mt.body.agents:[],Y(At.status===200&&Array.isArray(At.body.actions)?At.body.actions:[]);try{const ke=await H(kf(t,n));ke.status===200&&Xn(ke.body)}catch{}if(m||(F.current&&!F.current.value&&typeof Oe.draft=="string"&&Oe.draft&&(F.current.value=Oe.draft,En(K)),F.current&&ye(F.current.value),Array.isArray(Oe.draftAttachments)&&Oe.draftAttachments.length&&ie(Oe.draftAttachments),He.current&&(He.current.textContent=Oe.title||n),S.thinkingLevel=Oe.thinkingLevel||"",S.maxOutputTokens=Oe.maxOutputTokens||"",bn(K,S),xo(K,S),ot(S,null,K),lo(S,K),en(),m))return;if(g(ke=>ke+1),yi(),B.current&&B.current.hasMore&&B.current.beforeSeq!==null&&df(S,K,B.current).catch(()=>{}),function(){m||H("/api/tools/list?projectDir="+encodeURIComponent(t)).then(ht=>{m||(M.current={catalog:ht.status===200&&Array.isArray(ht.body.tools)?ht.body.tools:[],filter:Array.isArray(Oe.tools)?Oe.tools.slice():null},g(xt=>xt+1),S._updateToolsCard&&S._updateToolsCard())}).catch(()=>{})}(),function(){if(Ko(S))Tu(S,K).catch(()=>{});else{const ht=S.providers.map(xt=>xt&&xt.id).filter(Boolean);ht.length&&Promise.all(ht.map(xt=>dc(xt).catch(()=>{}))).catch(()=>{})}}(),Oe.running){if(d(!0),S.runSettled=!1,S.watchingStableTicks=0,S.pendingAuthCount=await Dl(S,K),m||S.props.projectDir!==t||S.props.chatId!==n)return;S.pendingAuthCount>0&&(S.watchingRun=!0,ne(K,"waiting for you…","busy")),Nl(S,K)}else S.pendingAuthCount=0,d(!1);us(S,K),Eo(cs(S),K)}catch{fe.current&&(fe.current.textContent="load failed")}}return L(),()=>{m=!0}},[t,n]);async function dc(m){const L=await H("/api/ai/models/live?provider="+encodeURIComponent(m));if(L.status!==200)return{provider:m,ok:!1,body:L.body,status:L.status};const U=Array.isArray(L.body&&L.body.models)?L.body.models:[];return j.current=Object.assign({},j.current,{[m]:U}),bn(K,S),en(),{provider:m,ok:!0,count:U.length}}return ue(()=>{function m(U){const Q=K.chatSwitcherPop&&K.chatSwitcherPop.current,ge=K.chatSwitcherTrigger&&K.chatSwitcherTrigger.current;Q&&!Q.hidden&&ge&&!Q.contains(U.target)&&!ge.contains(U.target)&&_(!1)}function L(U){if(U.key==="Escape"){if(l){c(!1);return}D(!1)}}return document.addEventListener("click",m),document.addEventListener("keydown",L),En(K),()=>{document.removeEventListener("click",m),document.removeEventListener("keydown",L)}},[l]),ue(()=>{const m=W.current;if(!m)return;function L(){if(Nu(K,m.scrollTop))return;const Ie=Iu(m);Ie&&!Ne.current?(Ne.current=!0,it.current=0,Gt(K)):!Ie&&Ne.current&&(Ne.current=!1,Gt(K)),B.current&&of(B.current,m.scrollTop)&&uf(S,K,B.current).catch(()=>{})}m.addEventListener("scroll",L,{passive:!0});function U(){Ur(K)}let Q=null;const ge=new Set;function ce(Ie){!Q||Ie.nodeType!==1||Ie.parentNode!==m||ge.has(Ie)||(ge.add(Ie),Q.observe(Ie))}if(typeof ResizeObserver<"u"){Q=new ResizeObserver(U),Q.observe(m);for(const Ie of m.children)ce(Ie)}let xe=null;typeof MutationObserver<"u"&&(xe=new MutationObserver(Ie=>{for(const Mt of Ie)if(!(Mt.type!=="childList"||Mt.target!==m)){for(const At of Mt.removedNodes)At.parentNode!==m&&ge.delete(At)&&Q&&Q.unobserve(At);for(const At of Mt.addedNodes)ce(At)}U()}),xe.observe(m,{childList:!0,subtree:!0,characterData:!0}));function Ee(Ie){Ie&&Ie.target&&Ie.target.tagName==="IMG"&&U()}return m.addEventListener("load",Ee,!0),()=>{m.removeEventListener("scroll",L),m.removeEventListener("load",Ee,!0),xe&&xe.disconnect(),Q&&Q.disconnect(),ge.clear(),Da(K)}},[t,n]),ue(()=>{zr.current=new Set},[n]),ue(()=>{Qt.current=new Set},[n]),ue(()=>{Ne.current=!0,it.current=0,Gt(K)},[n,t]),ue(()=>{Gr.current=0},[n,t]),ue(()=>{Zr.current={key:"",active:!1,connected:!1,ended:!1,failed:!1}},[n,t]),ue(()=>{Yr.current=!1},[n,t]),ue(()=>{B.current=Es(),Je.current=0,st.current=0},[n,t]),ue(()=>()=>{const m=K.promptInput.current,L=m?m.value:"",U=Vt(oe.current);$.current&&(clearTimeout($.current),$.current=null),t&&n&&(L||U.length)&&rc(t,n,L,U).catch(()=>{}),m&&(m.value="",En(K)),ye(""),ie([])},[n,t]),ue(()=>()=>{li(S),qp(S,t,n),$.current&&(clearTimeout($.current),$.current=null),Bl(S),typeof Lr=="function"&&Lr(K)},[t,n]),ue(()=>{if(!t)return;const m={projectDir:t,chatId:n,offset:0,total:1/0,loading:!1};V.current=m,O(!1),Z.current=!1;let L=!1;return go(t,m,U=>{!L&&V.current===m&&w(U)}),()=>{L=!0}},[t,n]),ue(()=>{if(!t||!n)return;if(!Z.current){Z.current=!0;return}const m=V.current;if(!m||m.projectDir!==t||m.chatId!==n)return;let L=!1;return go(t,{projectDir:t,offset:0,total:1/0},U=>{L||V.current!==m||!U.length||w(Q=>{const ge=new Map(U.map(xe=>[xe&&xe.id,xe])),ce=U.slice();for(const xe of Q)!xe||ge.has(xe.id)||ce.push(xe);return ce})}),()=>{L=!0}},[a,t,n]),ue(()=>{if(!n||!t)return;let m=!1,L=null;function U(){if(m)return;let Ie;$r.current.active||Kr.current?Ie=1e3:typeof document<"u"&&document.visibilityState==="hidden"?Ie=6e3:Ie=3e3,L=setTimeout(Q,Ie)}async function Q(){m||(($r.current.active||!dt.current)&&await Fl(S,K),U())}Jr.current=()=>{m||(L&&(clearTimeout(L),L=null),Q())};function ge(){m||(L&&clearTimeout(L),L=setTimeout(Q,0))}function ce(){m||(L&&(clearTimeout(L),L=null),document.visibilityState==="visible"?ge():U())}function xe(){ge()}function Ee(){document.visibilityState==="visible"&&ge()}return U(),document.addEventListener("visibilitychange",ce),window.addEventListener("pageshow",xe),window.addEventListener("focus",Ee),()=>{m=!0,L&&clearTimeout(L),document.removeEventListener("visibilitychange",ce),window.removeEventListener("pageshow",xe),window.removeEventListener("focus",Ee)}},[n,t]),{state:S,refs:K,imageAttachments:r,composerText:i,fileEditorOpen:l,runningVisible:a,authStamp:p,toolDataStamp:h,customActions:P,fileOrb:Rt,composerTools:Lt,mcpStartBusy:v,setImageAttachments:ie,setFileEditorOpen:c,setComposerText:ye,picker:re,send:gi,runCustomAction:m=>No(m,S,K),refreshCustomActions:nc,updateChat:qe,onPickerPick:_i,onPickerTogglePin:m=>{m&&(Oa(S,m.provider,m.id),en())},onPickerOpen:()=>{K.maxOutputTokens&&K.maxOutputTokens.current&&(K.maxOutputTokens.current.value=S.chat&&S.chat.maxOutputTokens||S.maxOutputTokens||"")},onRefreshAllProviders:()=>es(S),onPickerOpenChange:m=>{m?mi():D(!1)},onComposerKey:m=>jp(m,gi,{enterForNewline:S.enterForNewline,customActions:S.customActions}),onComposerInput:()=>{const m=K.promptInput.current?K.promptInput.current.value:"";ie(L=>Xp(L,_e.current,m)),ye(m),Op(K,t,n,qe)},onComposerPaste:m=>{const L=m.clipboardData&&m.clipboardData.files;L&&Array.from(L).some(U=>/^image\//i.test(U.type||""))&&(m.preventDefault(),Rs(L,{setImageAttachments:ie,setChatStatus:(U,Q)=>ne(K,U,Q),updateChat:qe}))},onImagePickerChange:m=>{Rs(m.currentTarget.files,{setImageAttachments:ie,setChatStatus:(L,U)=>ne(K,L,U),updateChat:qe})},onRemoveImage:m=>_f(m,ie,qe),onJumpToBottom:()=>Pu(K),onCancelRunning:uc,onToggleAutoRetry:()=>{S.autoRetry=!S.autoRetry,qe({autoRetry:S.autoRetry})},onBack:()=>{window.location.hash="#/projects"},chatSwitcherOpen:k,setChatSwitcherOpen:_,chatSwitcherList:y,chatSwitcherLoading:N,onToggleChatSwitcher:We(()=>{_(m=>!m)},[]),onChatSwitcherScroll:We(m=>{if(!t)return;const L=V.current;L.projectDir===t&&(L.loading||L.offset>=L.total||(L.loading=!0,O(!0),go(t,L,U=>{if(V.current!==L||L.projectDir!==t){O(!1);return}L.loading=!1,O(!1),U.length&&w(Q=>{const ge=new Set(Q.map(ce=>ce&&ce.id));return Q.concat(U.filter(ce=>ce&&!ge.has(ce.id)))})})))},[t]),onSwitchChat:We(m=>{_(!1),m&&m!==n&&yt("chat/"+encodeURIComponent(m)+"?projectDir="+encodeURIComponent(t))},[t,n])}}async function go(e,t,n,r={}){if(!e)return;const o=100,i=Math.max(1,Math.min(4,r.pages||1));try{for(let s=0;s<i&&!(t.offset>=t.total);s++){const l=await H("/api/chats?projectDir="+encodeURIComponent(e)+"&offset="+t.offset+"&limit="+o),c=l.status===200&&l.body?l.body.chats||[]:[];if(l.status===200&&l.body&&typeof l.body.total=="number"&&(t.total=l.body.total),t.offset+=c.length,n(c),c.length<o)break}}catch{n([])}}const Os=["","k","M","G","T","P"];function Tf(e){return e.endsWith(".0")?e.slice(0,-2):e}function ar(e){if(!Number.isFinite(e)||e<0)return String(e);if(e<1e3)return String(Math.round(e));let t=0,n=e;for(;n>=999.5&&t<Os.length-1;)n/=1e3,t+=1;return(t>0&&n<9.95?Tf(n.toFixed(1)):String(Math.round(n)))+Os[t]}const Af="M2 3.5a2 2 0 0 1 2-2h4.2l1.9 1.9H16a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-9Z",kn="M1 5.5A3.5 3.5 0 0 1 4.5 2h5l2.5 2.5h6.5A2.5 2.5 0 0 1 21 7v7.5a2.5 2.5 0 0 1-2.5 2.5h-15A2.5 2.5 0 0 1 1 14.5v-9Z",xf="M0.5 5.5 6 1 11.5 5.5 10 6 6 2.5 2 6Z",Ef="M0.5 0.5 6 5 11.5 0.5 10 0 6 3.5 2 0Z",If=12,Pf=6,Nf=22,Rf=18;function Lf(e){let t=0,n=0;for(const r of String(e||"").split(`
|
|
56
|
+
`)){const o=r.split(" ");/^\d+$/.test(o[0])&&(t+=Number(o[0])),/^\d+$/.test(o[1])&&(n+=Number(o[1]))}return{additions:t,deletions:n}}async function js(e){if(!e)return null;const t=i=>H("/api/git",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:e,action:"diff",args:i})}),[n,r]=await Promise.all([t("--numstat --cached"),t("--numstat")]),o=[n,r].filter(i=>i.status===200&&i.body&&i.body.ok);return o.length?o.reduce((i,s)=>{const l=Lf(s.body.stdout);return{additions:i.additions+l.additions,deletions:i.deletions+l.deletions}},{additions:0,deletions:0}):null}function Mf(e){const{projectDir:t,onOpenFileEditor:n,onOpenPreview:r,customActions:o,onRunCustomAction:i,onRefreshCustomActions:s,orb:l}=e,[c,a]=E(!1),[d,p]=E(!1),[f,h]=E(!1),[g,v]=E(null),b=x(null),[k,_]=E(null),[y,w]=E(null);ue(()=>{if(!d||k)return;let W=!1;return je(()=>import("./GitModal-BPaOnX1a.js"),[]).then(G=>{W||_(()=>G.GitModal)}).catch(()=>{W||_(null)}),()=>{W=!0}},[d,k]),ue(()=>{if(!f||y)return;let W=!1;return je(()=>import("./CliModal-D2cX4W0a.js"),[]).then(G=>{W||w(()=>G.CliModal)}).catch(()=>{W||w(null)}),()=>{W=!0}},[f,y]);const N=We(async()=>{try{v(await js(t))}catch{v(null)}},[t]);ue(()=>{let W=!1;return js(t).then(G=>{W||v(G)}).catch(()=>{W||v(null)}),()=>{W=!0}},[t]),Go(b,()=>a(!1),c);function O(){const W=!c;a(W),N(),W&&s&&s()}function P(){a(!1),n&&n()}function Y(){a(!1),p(!0)}function re(){p(!1),N()}function z(){a(!1),h(!0)}function I(){a(!1),r&&r()}function D(W){a(!1),i&&i(W)}const V=g?g.additions:0,Z=g?g.deletions:0,oe=g!=null,ie=oe&&(V>0||Z===0),_e=oe&&(Z>0||V===0),ye=oe?V+(V===1?" line added, ":" lines added, ")+Z+(Z===1?" line deleted":" lines deleted"):"";function we(W){const G=W==="up"?xf:Ef;return l?u("svg",{class:"file-toolbar__chevron file-toolbar__chevron--"+W,viewBox:"0 0 12 6",width:If,height:Pf,"aria-hidden":"true"},u("path",{class:"file-toolbar__chevron-side",d:G}),u("path",{class:"file-toolbar__chevron-face",d:G})):u("svg",{viewBox:"0 0 12 6",width:14,height:7},u("path",{d:G,fill:"currentColor"}))}function He(W,G){if(!oe)return null;const he=W?" file-toolbar__count--3d":"",Pe="+"+ar(V),F="−"+ar(Z),R=W?{"--orb-count":G||Ls(2)}:null;return u("span",{class:"file-toolbar__git-stats",style:R},ie?u("span",{class:"file-toolbar__git-additions"+he},W?u("span",{class:"file-toolbar__count-echo","aria-hidden":"true"},Pe):null,u("span",{class:"file-toolbar__count-face"},Pe)):null,_e?u("span",{class:"file-toolbar__git-deletions"+he},W?u("span",{class:"file-toolbar__count-echo","aria-hidden":"true"},F):null,u("span",{class:"file-toolbar__count-face"},F)):null)}const De=l&&oe?Math.max(ie?("+"+ar(V)).length:0,_e?("−"+ar(Z)).length:0):0,pe=De?Ls(De):null,ae=[["side",u("path",{d:kn})],["body",u("path",{d:kn})],["shade",u("path",{d:kn})],["face",u("path",{d:kn})],["sheen",u("path",{d:kn})],["shine",u("path",{d:"M1.8 5.8A2.9 2.9 0 0 1 4.7 2.9h4.4l2.3 2.3h7A1.7 1.7 0 0 1 20.1 6.9"})]],le=l?u("span",{class:"file-toolbar__plate"},u("span",{class:"file-toolbar__plate-face"},u("span",{class:"file-toolbar__cast","aria-hidden":"true"}),u("span",{class:"file-toolbar__folder file-toolbar__folder--3d"},u("span",{class:"file-toolbar__folder-ground","aria-hidden":"true"}),...ae.map(([W,...G])=>u("svg",{class:"file-toolbar__folder-"+W,viewBox:"0 0 22 18",width:Nf,height:Rf,"aria-hidden":"true"},G)),He(!0,pe)),u("svg",{class:"file-toolbar__defs",viewBox:"0 0 0 0","aria-hidden":"true"},u("linearGradient",{id:"fileToolbarFolderSide",x1:"0",y1:"0",x2:"0.3",y2:"1"},u("stop",{offset:"0","stop-color":"#dbeaff"}),u("stop",{offset:"0.42","stop-color":"#7895c2"}),u("stop",{offset:"1","stop-color":"#344c72"})),u("linearGradient",{id:"fileToolbarFolderBody",x1:"0.12",y1:"0",x2:"0.7",y2:"1"},u("stop",{offset:"0","stop-color":"#f6fbff"}),u("stop",{offset:"0.48","stop-color":"#d9e8fb"}),u("stop",{offset:"1","stop-color":"#9db6d8"})),u("linearGradient",{id:"fileToolbarFolderFace",x1:"0.1",y1:"0",x2:"0.62",y2:"1"},u("stop",{offset:"0","stop-color":"#ffffff"}),u("stop",{offset:"0.45","stop-color":"#eff8ff"}),u("stop",{offset:"0.72","stop-color":"#dcecff"}),u("stop",{offset:"0.9","stop-color":"#c4d9f3"}),u("stop",{offset:"1","stop-color":"#a9c2e2"})),u("radialGradient",{id:"fileToolbarFolderShade",cx:"0.7",cy:"0.86",r:"0.82"},u("stop",{offset:"0","stop-color":"#464d6b","stop-opacity":"0.40"}),u("stop",{offset:"0.42","stop-color":"#4d5474","stop-opacity":"0.17"}),u("stop",{offset:"0.78","stop-color":"#5b6280","stop-opacity":"0.04"}),u("stop",{offset:"1","stop-color":"#5b6280","stop-opacity":"0"})),u("linearGradient",{id:"fileToolbarFolderSheen",x1:"0",y1:"0",x2:"0.35",y2:"0.85"},u("stop",{offset:"0","stop-color":"#ffffff","stop-opacity":"0.95"}),u("stop",{offset:"0.28","stop-color":"#ffffff","stop-opacity":"0.20"}),u("stop",{offset:"0.55","stop-color":"#ffffff","stop-opacity":"0"}))))):u("span",{class:"file-toolbar__folder"},u("svg",{viewBox:"0 0 20 16",width:28,height:22},u("path",{d:Af,fill:"currentColor"})),He(!1));return u("div",{class:"file-toolbar"+(l?" file-toolbar--orb":"")},u("button",{class:"file-toolbar__trigger",type:"button",onClick:O,"aria-label":"File tools"+(ye?". "+ye:""),"aria-haspopup":"true","aria-expanded":String(c),title:"File, git, and CLI tools"+(ye?" — "+ye:"")},l?u("span",{class:"file-toolbar__sheen","aria-hidden":"true"}):null,u("span",{class:"file-toolbar__stack","aria-hidden":"true"},we("up"),le,we("down"))),c&&u("div",{ref:b,class:"file-toolbar__menu",role:"menu"},o&&o.length?[...o.map(W=>u("button",{key:W.id,class:"file-toolbar__menu-item file-toolbar__menu-item--action",role:"menuitem",type:"button",onClick:()=>D(W)},W.label||W.id)),u("div",{class:"file-toolbar__menu-sep",role:"separator"})]:null,u("button",{class:"file-toolbar__menu-item",role:"menuitem",type:"button",onClick:P},u("span",{class:"file-toolbar__menu-icon"},"📝"),u("span",null,"Files")),u("button",{class:"file-toolbar__menu-item",role:"menuitem",type:"button",onClick:I},u("span",{class:"file-toolbar__menu-icon"},"📱"),u("span",null,"Preview")),u("button",{class:"file-toolbar__menu-item",role:"menuitem",type:"button",onClick:Y},u("span",{class:"file-toolbar__menu-icon"},"📁"),u("span",null,"Git")),u("button",{class:"file-toolbar__menu-item",role:"menuitem",type:"button",onClick:z},u("span",{class:"file-toolbar__menu-icon"},"🖥"),u("span",null,"Cli"))),d&&k?u(k,{projectDir:t,onClose:re}):null,f&&y?u(y,{projectDir:t,onClose:()=>h(!1)}):null)}function Of(e,t=!0){ue(()=>{if(!t||typeof e!="function")return;function n(){window.visualViewport&&e(window.visualViewport)}n();const r=window.visualViewport;return r&&(r.addEventListener("resize",n),r.addEventListener("scroll",n)),window.addEventListener("resize",n),window.addEventListener("orientationchange",n),()=>{r&&(r.removeEventListener("resize",n),r.removeEventListener("scroll",n)),window.removeEventListener("resize",n),window.removeEventListener("orientationchange",n)}},[e,t])}function jf({toolName:e,current:t,onSave:n}){return!t||!t.mode?null:u(tl,{tool:e,name:e,mode:t.mode,allowlist:Array.isArray(t.allowlist)?t.allowlist:[],modes:e==="ask_user"?nl:Vr,namePrefix:"popup-auth",onClear:()=>{n&&n(e,null,[])},onPick:(r,o)=>{n&&n(e,r,o)}})}function Df(e){const{tools:t,mcpServers:n,usedTools:r,agentFiles:o,skills:i,toolAuth:s,mcpAuth:l,onToggleTool:c,onToggleToolGroup:a,onToggleAgentFiles:d,onToggleSkills:p,onToggleSkill:f,onSaveToolAuth:h,onSaveMcpAuth:g,onReloadMcpServer:v,mcpStartBusy:b,autoRetry:k,onToggleAutoRetry:_}=e,[y,w]=E(!1),N=x(null),O=x(null);Go([N,O],()=>w(!1),y);const[P,Y]=E({}),re=We(()=>{if(!O.current)return;const le=O.current.getBoundingClientRect(),W=O.current.closest(".chat-view__head"),G=W&&W.getBoundingClientRect(),he=window.visualViewport,Pe=he?he.height:window.innerHeight,F=(he?he.offsetTop:0)+Pe,R=Math.max(le.bottom,G?G.bottom:0),$=Math.max(0,Math.floor(F-R-10)),se=Math.min(400,Math.floor(Pe*.6),$);Y({top:Math.floor(R+4)+"px",right:Math.max(10,Math.floor(window.innerWidth-le.right))+"px",maxHeight:se+"px"})},[]);Of(re,y);const z=t&&t.catalog||[],I=t&&t.filter,Z=el(z,n||[],I,r||new Set),oe=s||{};function ie(le){return le==="allowlist"?"ask":le}const _e={shell:"shell",subagent:"subagent",ask_user:"ask_user",report_progress:"report_progress",task:"task",webpreview:"webpreview",restart_app:"restart_app",files:"file"};for(const le of Z){const W=_e[le.id];if(W){const G=oe[W]||{mode:"ask"};le.control=u(jf,{toolName:W,current:{mode:ie(G.mode),allowlist:Array.isArray(G.allowlist)?G.allowlist:[]},onSave:h})}}const ye=l||{mode:"ask",allowlist:[],servers:{},tools:{}};for(const le of Z){if(!le.id.startsWith("mcp-"))continue;const W=le.id.slice(4);le.control=u(ol,{name:le.name,slug:W,servers:ye.servers,shared:ye,namePrefix:"popup-mcp",onClear:()=>{g&&g({servers:{[W]:null}})},onSave:G=>g&&g(G)}),le.serverId&&le.serverId===b&&(le.reloadBusy=!0)}function we(le){const W=le&&le.serverId;!W||!v||v(W)}function He(le,W){if(le==="agent-files"){d&&d(W);return}if(le==="skills"){p&&p(W);return}if(a){const G=Z.find(he=>he.id===le);G&&a(G.tools.map(he=>he.id),W)}}function De(le,W,G){if(le==="agent-files"){d&&d(G);return}if(le==="skills"){f&&f(W,G);return}c&&c(W,G)}const pe=o||{files:[],enabled:!0,projectLocked:!1};pe.files.length&&Z.push({id:"agent-files",name:"Agent files",description:pe.enabled?"all selected":"off",checked:pe.enabled,disabled:!!pe.projectLocked,disabledReason:pe.projectLocked?"Locked off by Settings → Project.":"",alwaysExpanded:!0,tools:pe.files.map(le=>({id:le,name:le,description:"",checked:pe.enabled,disabled:!!pe.projectLocked}))});const ae=i||{items:[],enabled:!0,projectLocked:!1};if(ae.items.length){const le=ae.items.filter(G=>!G.disabled),W=le.length>0&&le.every(G=>!G.chatDisabled);Z.push({id:"skills",name:"Skills",description:ae.enabled?"available metadata":"off",checked:!!ae.enabled&&W,disabled:!!ae.projectLocked,disabledReason:ae.projectLocked?"Locked off by Settings → Project.":"",alwaysExpanded:!0,tools:ae.items.map(G=>({id:G.id,name:G.name,description:G.description||"",checked:ae.enabled&&!G.disabled&&!G.chatDisabled,disabled:!!ae.projectLocked||!!G.disabled,disabledReason:G.disabled?"Disabled in Settings → Project":""}))})}return u("div",{class:"tool-popup"},u("button",{ref:O,class:"chat-view__toolbar-btn tool-popup__trigger",type:"button",onClick:()=>w(!y),"aria-label":"Toggle available tools","aria-haspopup":"true","aria-expanded":String(y),title:"Tool settings"},u("svg",{viewBox:"0 0 24 24",width:16,height:16,"aria-hidden":"true",fill:"currentColor"},u("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"}))),y&&u("div",{ref:N,class:"tool-popup__layer","aria-label":"Tool settings"},u("div",{class:"tool-popup__popup",role:"dialog","aria-label":"Tool settings",style:P},u("div",{class:"tool-popup__head"},u("span",{class:"tool-popup__title"},"Tools"),u("button",{class:"tool-popup__close",type:"button",onClick:()=>w(!1),"aria-label":"Close"},"×")),u("div",{class:"tool-popup__body"},u(Qa,{groups:Z,onToggleGroup:He,onToggleTool:De,onReloadServer:we,collapsedByDefault:!0,class:"tool-popup__tree"})),u("div",{class:"tool-popup__foot"},u("label",{class:"switch switch--sm"},u("input",{type:"checkbox",role:"switch","aria-checked":String(!!k),checked:!!k,onChange:()=>_&&_()}),u("span",{class:"switch__track","aria-hidden":"true"},u("span",{class:"switch__thumb"})),u("span",{class:"tool-popup__foot-label"},"Auto-retry failed sends")),u("span",{class:"tool-popup__foot-note"},"Actions run immediately. Off / Ask / Allow here applies to this chat only; project-wide modes live in Settings → Project. Tools marked ● have been used in this chat.")))))}function Bf({preview:e,onOpen:t,onDismiss:n}){if(!e||!e.thumbnail)return null;const r=e.title||e.url||"Web preview";return u("aside",{class:"webpreview-dock","aria-label":"Web preview"},u("button",{class:"webpreview-dock__open",type:"button",onClick:t,"aria-label":"Open full preview of "+r},u("img",{class:"webpreview-dock__image",src:e.thumbnail,alt:"Preview of "+r,draggable:"false",loading:"lazy",decoding:"async"})),u("button",{class:"webpreview-dock__dismiss",type:"button",onClick:n,"aria-label":"Dismiss preview",title:"Dismiss preview"},u("svg",{viewBox:"0 0 24 24",width:14,height:14,"aria-hidden":"true"},u("path",{d:"M6 6l12 12 M18 6L6 18",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round"}))))}const Zt=[];function Ff(e){return Ul(e),Zt.push(e),e}function Ul(e){const t=Zt.indexOf(e);return t===-1?!1:(Zt.splice(t,1),t===Zt.length)}function qf(e){return Zt.length>0&&Zt[Zt.length-1]===e}const Uf=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function Ds(e){if(!e||!e.querySelectorAll)return[];const t=[];for(const n of e.querySelectorAll(Uf)){if(n.hasAttribute("hidden")||n.getAttribute("aria-hidden")==="true")continue;const r=typeof getComputedStyle=="function"?getComputedStyle(n):null;r&&(r.display==="none"||r.visibility==="hidden")||t.push(n)}return t}function Vl(e){const t=e||{},{onClose:n,active:r=!0,escape:o=!0,trapFocus:i=!0,restoreFocus:s=!0,initialFocus:l="none"}=t,c=x(null),a=x(null),d=x(n);return d.current=n,ue(()=>{if(!r)return;const p={};if(Ff(p),a.current=typeof document>"u"?null:document.activeElement,l==="first"){const[h]=Ds(c.current);h?h.focus():c.current&&(c.current.setAttribute("tabindex","-1"),c.current.focus())}function f(h){if(!qf(p))return;if(o&&h.key==="Escape"){h.stopPropagation(),d.current&&d.current();return}if(!i||h.key!=="Tab")return;const g=Ds(c.current);if(!g.length)return;const v=g[0],b=g[g.length-1],k=document.activeElement,_=!!(c.current&&c.current.contains(k));h.shiftKey?(!_||k===v)&&(h.preventDefault(),b.focus()):(!_||k===b)&&(h.preventDefault(),v.focus())}return document.addEventListener("keydown",f,!0),()=>{document.removeEventListener("keydown",f,!0),Ul(p);const h=a.current;s&&h&&typeof h.focus=="function"&&typeof document<"u"&&document.contains(h)&&h.focus()}},[r,o,i,s,l]),c}const Or=[{id:"phone",label:"Phone",width:375,height:667},{id:"phone+",label:"Phone+",width:414,height:896},{id:"tablet",label:"Tablet",width:768,height:1024},{id:"laptop",label:"Laptop",width:1280,height:800}],Lo="custom",Mo=64,Oo=2048;function Vf({value:e,onChange:t,busy:n}){const r=Or.some(o=>o.id===e);return u("select",{class:"wp__size-select",value:r?e:Lo,disabled:n,"aria-label":"Capture size",onChange:o=>t&&t(o.currentTarget.value)},Or.map(o=>u("option",{key:o.id,value:o.id},o.label+" · "+o.width+"×"+o.height)),u("option",{value:Lo},"Custom"))}function Hf({preview:e,onClose:t,onRecapture:n}){const r=Wf(e&&e.viewport),o=zf(r,e),[i,s]=E(r),[l,c]=E(String(o.width)),[a,d]=E(String(o.height)),[p,f]=E(""),h=Vl({onClose:()=>{t&&t()}}),g=e&&e.url||"",v=e&&e.title||g||"Web preview",b=e&&e.thumbnail,k=e&&e.width,_=e&&e.height,y=e&&e.sizeBytes,w=e&&e.capturedAt,N=$f(g);function O(Z){Z.target===Z.currentTarget&&t&&t()}const[P,Y]=E(!1);async function re(Z){if(P||!n)return;const oe=i,ie=Z||i||"phone";s(ie),Y(!0);try{const _e=await n(ie);(!_e||!_e.ok)&&s(oe)}catch{s(oe)}finally{Y(!1)}}function z(Z){if(f(""),Z===Lo){s(l+"x"+a);return}re(Z)}function I(Z){Z.preventDefault();const oe=Bs(l),ie=Bs(a);if(!oe||!ie){f("Enter width and height from 64 to 2048 px.");return}f(""),re(oe+"x"+ie)}const D=!Or.some(Z=>Z.id===i),V=[];return k&&_&&V.push(k+" × "+_),e&&e.viewport&&e.viewport.label&&V.push("viewport "+e.viewport.label),y&&V.push(Jf(y)),w&&V.push("captured "+Gf(w)),u("div",{class:"wp__overlay",role:"dialog","aria-modal":"true","aria-label":v,onClick:O},u("div",{class:"wp__sheet",ref:h},u("div",{class:"wp__head"},u("div",{class:"wp__head-text"},u("div",{class:"wp__title",title:v},v),u("div",{class:"wp__title-sub"},N)),u("div",{class:"wp__head-actions"},u("button",{class:"wp__action wp__action--refresh",type:"button",disabled:P,onClick:()=>re(i),"aria-label":"Refresh preview",title:"Refresh preview"},u("svg",{viewBox:"0 0 24 24",width:14,height:14,"aria-hidden":"true"},u("path",{d:"M4 12a8 8 0 0 1 13.66-5.66L20 4 M20 4v5h-5 M20 12a8 8 0 0 1-13.66 5.66L4 20 M4 20v-5h5",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"})),u("span",null,"Refresh")),u(Vf,{value:i,busy:P,onChange:z}),u("button",{class:"wp__close",type:"button","aria-label":"Close preview",title:"Close preview",onClick:()=>t&&t()},u("svg",{viewBox:"0 0 24 24",width:18,height:18,"aria-hidden":"true"},u("path",{d:"M6 6 18 18 M18 6 6 18",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round"}))))),D?u("form",{class:"wp__custom-size",onSubmit:I},u("label",{class:"wp__custom-field"},u("span",null,"Width"),u("input",{class:"wp__custom-input",type:"number",inputMode:"numeric",min:Mo,max:Oo,step:1,value:l,disabled:P,onInput:Z=>c(Z.currentTarget.value),"aria-label":"Custom preview width"})),u("span",{class:"wp__custom-times","aria-hidden":"true"},"×"),u("label",{class:"wp__custom-field"},u("span",null,"Height"),u("input",{class:"wp__custom-input",type:"number",inputMode:"numeric",min:Mo,max:Oo,step:1,value:a,disabled:P,onInput:Z=>d(Z.currentTarget.value),"aria-label":"Custom preview height"})),u("button",{class:"wp__custom-apply",type:"submit",disabled:P},"Apply"),p?u("div",{class:"wp__custom-error",role:"alert"},p):null):null,u("div",{class:"wp__body"},b?u("img",{class:"wp__img",src:b,alt:v,draggable:"false",decoding:"async"}):u("div",{class:"wp__empty"},u("p",null,"No preview available."),u("p",{class:"wp__empty-hint"},"The webpreview call finished without a captured image."))),u("div",{class:"wp__foot"},u("span",{class:"wp__foot-meta"},V.filter(Boolean).join(" · ")),g?u("a",{class:"wp__open-link",href:g,target:"_blank",rel:"noopener noreferrer","aria-label":"Open "+g+" in a new tab"},"Open in new tab"):null)))}function Wf(e){return e?Or.some(t=>t.id===e.id)?e.id:e.width&&e.height?e.width+"x"+e.height:"phone":"phone"}function zf(e,t){const n=typeof e=="string"&&e.match(/^(\d+)x(\d+)$/);return n?{width:Number(n[1]),height:Number(n[2])}:{width:t&&t.width||375,height:t&&t.height||667}}function Bs(e){const t=Number(e);return!Number.isInteger(t)||t<Mo||t>Oo?0:t}function $f(e){if(!e)return"";try{return new URL(e).hostname||""}catch{return""}}function Jf(e){return!e||!isFinite(e)||e<=0?"":e<1024?e+" B":e<1024*1024?Math.round(e/1024)+" KB":(e/1024/1024).toFixed(2)+" MB"}function Gf(e){if(!e)return"";const t=new Date(e);if(isNaN(t.getTime()))return"";try{return t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function Kf({onSubmit:e,onClose:t}){const[n,r]=E(""),[o,i]=E(""),s=x(null),l=Vl({onClose:()=>{t&&t()}});ue(()=>{s.current&&s.current.focus()},[]);function c(d){d.target===d.currentTarget&&t&&t()}function a(d){d.preventDefault();const p=n.trim();if(!p){i("Enter a web URL to preview.");return}let f;try{f=new URL(/^https?:\/\//i.test(p)?p:"https://"+p)}catch{i("That does not look like a valid web URL.");return}if(f.protocol!=="http:"&&f.protocol!=="https:"){i("Only http and https URLs are supported.");return}e&&e(f.href)}return u("div",{class:"wp__overlay",role:"dialog","aria-modal":"true","aria-label":"Preview a web page",onClick:c},u("div",{class:"wp__sheet wp__prompt-sheet",ref:l},u("div",{class:"wp__head"},u("div",{class:"wp__head-text"},u("div",{class:"wp__title"},"Preview a web page"),u("div",{class:"wp__title-sub"},"Opens in the web-preview viewer")),u("div",{class:"wp__head-actions"},u("button",{class:"wp__close",type:"button","aria-label":"Close",title:"Close",onClick:()=>t&&t()},u("svg",{viewBox:"0 0 24 24",width:18,height:18,"aria-hidden":"true"},u("path",{d:"M6 6 18 18 M18 6 6 18",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round"}))))),u("form",{class:"wp__prompt-form",onSubmit:a},u("label",{class:"label wp__prompt-label",for:"wp-preview-url"},"URL"),u("input",{ref:s,id:"wp-preview-url",class:"input mono wp__prompt-input",type:"text",inputMode:"url",autocomplete:"off",autocapitalize:"off",spellcheck:"false",enterkeyhint:"go",placeholder:"https://example.com/landing",value:n,onInput:d=>{r(d.currentTarget.value),o&&i("")},"aria-label":"Web URL to preview"}),u("button",{class:"btn btn--primary wp__prompt-submit",type:"submit"},"Preview"),o?u("div",{class:"wp__prompt-error",role:"alert"},o):null,u("p",{class:"wp__prompt-hint"},"A screenshot is captured using the Inspector debug Chrome."))))}const Zf=15e3,Yf=6e4;async function br(e,t,n=Zf){const r=new AbortController,o=setTimeout(()=>r.abort(),n);try{return await H(e,Object.assign({},t||{},{signal:r.signal}))}catch(i){throw r.signal.aborted?new Error("Request timed out. Try again."):i}finally{clearTimeout(o)}}function Xf(e){return(e&&typeof e.title=="string"?e.title.trim():"")||"New chat"}function Qf(e){const t=e&&(e.lastOpenedAt||e.createdAt);if(!t)return"";const n=new Date(t);return Number.isNaN(n.getTime())?"":n.toLocaleDateString([],{month:"short",day:"numeric"})}async function eh(e){const t=[];let r=1/0;for(;t.length<r;){const o=await br("/api/chats?projectDir="+encodeURIComponent(e)+"&offset="+t.length+"&limit=100");if(o.status!==200||!o.body)throw new Error(o.body&&o.body.error||"Could not load chats.");const i=Array.isArray(o.body.chats)?o.body.chats:[];if(r=typeof o.body.total=="number"?o.body.total:t.length+i.length,t.push(...i),!i.length||i.length<100)break}return t}function th({open:e,payload:t,onClose:n,onAdded:r,placement:o="bottom"}){const[i,s]=E([]),[l,c]=E(""),[a,d]=E([]),[p,f]=E(""),[h,g]=E(!1),[v,b]=E(!1),[k,_]=E(!1),[y,w]=E(""),N=h||v;if(ue(()=>{if(!e)return;let I=!1;return s([]),c(""),d([]),f(""),g(!0),w("Loading projects…"),br("/api/projects/registered").then(D=>{if(I)return;if(D.status!==200||!D.body||!Array.isArray(D.body.projects))throw new Error(D.body&&D.body.error||"Could not load projects.");const V=D.body.projects;s(V);const Z=t&&t.projectDir,oe=V.find(ie=>ie.path===Z)||V[0];c(oe?oe.path:""),w(V.length?"":"Add a project before using Draft Craft.")}).catch(D=>{I||(s([]),c(""),w(D&&D.message?D.message:"Could not load projects."))}).finally(()=>{I||g(!1)}),()=>{I=!0}},[e,t]),ue(()=>{if(!e||!l){d([]),f(""),b(!1);return}let I=!1;return d([]),f(""),b(!0),w("Loading chats…"),eh(l).then(D=>{I||(d(D),w(D.length?"":"This project has no chats yet."))}).catch(D=>{I||(d([]),f(""),w(D&&D.message?D.message:"Could not load chats."))}).finally(()=>{I||b(!1)}),()=>{I=!0}},[e,l]),!e)return null;const O=!!(t&&typeof t.text=="string"&&t.text.trim()),P=!!(t&&t.image&&t.image.dataUrl),Y=t&&t.textLabel?t.textLabel:"selected code",re=t&&t.description?t.description:P&&O?"Add the annotated image and note to any chat draft.":P?"Add the annotated Inspector image to any chat draft.":"Add selected file code to any chat draft.";async function z(){if(!(!l||!p||!O&&!P||k)){_(!0),w("Adding to draft…");try{const I=await br("/api/chats/"+encodeURIComponent(p)+"?projectDir="+encodeURIComponent(l));if(I.status!==200||!I.body||!I.body.chat)throw new Error(I.body&&I.body.error||"Could not read the chat draft.");const D=I.body.chat,V={projectDir:l};if(O){const oe=typeof D.draft=="string"?D.draft.trimEnd():"";V.draft=oe?oe+`
|
|
57
|
+
|
|
58
|
+
`+t.text.trim():t.text.trim()}if(P){const oe=Array.isArray(D.draftAttachments)?D.draftAttachments.slice():[];V.draftAttachments=Vt(oe.concat([t.image]).slice(0,8))}const Z=await br("/api/chats/"+encodeURIComponent(p),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(V)},Yf);if(Z.status!==200)throw new Error(Z.body&&Z.body.error||"Could not update the draft.");w("Added with Draft Craft."),_(!1),r&&r({projectDir:l,chatId:p,chat:Z.body.chat})}catch(I){w(I&&I.message?I.message:"Draft Craft failed."),_(!1)}}}return u("div",{class:"draft-craft__overlay draft-craft__overlay--"+o,role:"presentation",onClick:n},u("section",{class:"draft-craft__sheet",role:"dialog","aria-modal":"true","aria-labelledby":"draftCraftTitle",onClick:I=>I.stopPropagation()},u("div",{class:"draft-craft__handle","aria-hidden":"true"}),u("div",{class:"draft-craft__head"},u("div",null,u("h2",{id:"draftCraftTitle"},"Draft Craft"),u("p",null,re)),u("button",{class:"draft-craft__close",type:"button",onClick:n,"aria-label":"Close Draft Craft"},"×")),u("div",{class:"draft-craft__content"},u("label",{class:"draft-craft__field"},u("span",null,"Project"),u("select",{class:"input",value:l,onChange:I=>c(I.currentTarget.value),disabled:N||k},i.map(I=>u("option",{key:I.id||I.path,value:I.path},I.name||I.path)))),u("div",{class:"draft-craft__field"},u("span",null,"Chats"),u("ul",{class:"draft-craft__chats","aria-label":"Choose a chat"},N?u("li",{class:"draft-craft__chat-empty"},"Loading chats…"):a.length?a.map(I=>u("li",{key:I.id},u("button",{class:"draft-craft__chat"+(p===I.id?" is-selected":""),type:"button",onClick:()=>f(I.id),disabled:k,"aria-pressed":String(p===I.id)},u("span",{class:"draft-craft__chat-title"},Xf(I)),u("span",{class:"draft-craft__chat-meta"},Qf(I))))):u("li",{class:"draft-craft__chat-empty"},"No chats in this project."))),u("div",{class:"draft-craft__summary"},u("strong",null,"Adding"),u("span",null,[P?"annotated image":"",O?Y:""].filter(Boolean).join(" + ")||"nothing")),u("p",{class:"status draft-craft__status",role:"status","aria-live":"polite"},y)),u("div",{class:"draft-craft__actions"},u("button",{class:"btn btn--ghost",type:"button",onClick:n,disabled:k},"Cancel"),u("button",{class:"btn btn--primary",type:"button",onClick:z,disabled:N||k||!p||!O&&!P},k?"Adding…":"Add to draft"))))}const Fs=["#ff5f57","#ffd60a","#32d74b","#0a84ff"],Bn=.1,Hl=4,Sn=26;function qs(e,t=Bn){return Math.min(Hl,Math.max(t,e))}function Tn(e,t){if(!e||!t)return Bn;const n=e.clientWidth||e.offsetWidth,r=e.clientHeight||e.offsetHeight,o=t.width||t.naturalWidth||1,i=t.height||t.naturalHeight||1;if(n<=0||r<=0||o<=0||i<=0)return Bn;const s=n*(i/o);return Math.max(Bn,Math.min(1,r/s))}function Us(e){return Math.min(1,Math.max(0,e))}function jt(e,t){return t==="letters"?String.fromCharCode(65+e):String(e+1)}function In(e){const t=/^#([0-9a-f]{6})$/i.exec(String(e||"").trim());if(!t)return"#ffffff";const n=parseInt(t[1],16),r=n>>16&255,o=n>>8&255,i=n&255;return(.299*r+.587*o+.114*i)/255>.6?"#111111":"#ffffff"}function Vs(e,t){const n=t.getBoundingClientRect();return{x:(e.clientX-n.left)*(t.width/n.width),y:(e.clientY-n.top)*(t.height/n.height)}}function nh(e,t,n=!1){if(!t)return null;const r=t.getBoundingClientRect();return!n&&(e.clientX<r.left||e.clientX>r.right||e.clientY<r.top||e.clientY>r.bottom)?null:{x:Us((e.clientX-r.left)/r.width),y:Us((e.clientY-r.top)/r.height)}}function rh(e,t,n,r){const o=Math.max(14,r/46),i=t.x*e.canvas.width,s=t.y*e.canvas.height;e.save(),e.beginPath(),e.arc(i,s,o,0,Math.PI*2),e.fillStyle=t.color,e.fill(),e.lineWidth=Math.max(3,o/7),e.strokeStyle="#ffffff",e.stroke(),e.fillStyle=In(t.color),e.font="700 "+Math.round(o*1.05)+"px system-ui, sans-serif",e.textAlign="center",e.textBaseline="middle",e.fillText(n,i,s+o*.04),e.restore()}function oh(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function Hs(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}function ih({image:e,pageTitle:t,pageUrl:n,onClose:r,onAnnotated:o,originalDataUrl:i=null,sourceLabel:s="Inspector image",actionLabel:l="Add to chat draft",onReset:c}){const a=x(null),d=x(null),p=x(null),f=x(!1),h=x(null),g=x(new Map),v=x(null),b=x(null),k=x(null),_=x(null),y=x(null),w=x(1),N=x(null),[O,P]=E(Fs[0]),[Y,re]=E(""),[z,I]=E([]),[D,V]=E("numbers"),[Z,oe]=E(null),[ie,_e]=E(null),[ye,we]=E(!1),[He,De]=E(null),[pe,ae]=E(!1),[le,W]=E(""),[G,he]=E(1),[Pe,F]=E("draw"),[R,$]=E(!0);ue(()=>{if(!e||!e.dataUrl||!a.current)return;let C=!1;const j=new Image;return j.onload=()=>{if(C||!a.current)return;const q=a.current;q.width=j.naturalWidth||1,q.height=j.naturalHeight||1,q.getContext("2d").drawImage(j,0,0),ae(!0),requestAnimationFrame(de)},j.src=e.dataUrl,()=>{C=!0}},[e]),ue(()=>{const C=p.current,j=a.current;if(!C||!j||!pe)return;const q=typeof ResizeObserver=="function"?new ResizeObserver(()=>{const J=()=>{if(!p.current||!a.current)return;const A=Tn(p.current,a.current),M=w.current,ve=N.current;M<=(ve??A)+.005&&de(!1)};J(),requestAnimationFrame(J)}):null;return q&&q.observe(C),()=>{q&&q.disconnect()}},[pe]),ue(()=>{const C=_.current,j=y.current;if(!C||!j)return;const q=j.offsetTop,J=q+j.offsetHeight;q<C.scrollTop?C.scrollTop=q:J>C.scrollTop+C.clientHeight&&(C.scrollTop=J-C.clientHeight)},[Z,z.length]);function se(C,j){const q=p.current,J=a.current,A=J&&J.getBoundingClientRect(),M=qs(C,Tn(q,J));if(w.current=M,he(M),!q||!A||!j||A.width<=0||A.height<=0)return;const ve=q.getBoundingClientRect(),Ae=(j.x-A.left)/A.width,T=(j.y-A.top)/A.height,B=j.x-ve.left,te=j.y-ve.top;requestAnimationFrame(()=>{const Se=a.current;if(!Se||!q)return;const be=Se.getBoundingClientRect();q.scrollLeft=Math.max(0,Ae*be.width-B),q.scrollTop=Math.max(0,T*be.height-te)})}function de(C=!0){const j=p.current,q=a.current;if(!j||!q)return;const J=qs(Tn(j,q),Bn);w.current=J,he(J),N.current=J,C&&(j.scrollLeft=0,j.scrollTop=0)}function fe(C){if(!(!pe||!a.current)){g.current.set(C.pointerId,{x:C.clientX,y:C.clientY});try{a.current.setPointerCapture(C.pointerId)}catch{}if(g.current.size===2){const j=Array.from(g.current.values());v.current={distance:Hs(j[0],j[1]),zoom:w.current},b.current=null,f.current=!1,h.current=null;return}if(Pe==="pan"){const j=p.current;b.current=j?{x:C.clientX,y:C.clientY,left:j.scrollLeft,top:j.scrollTop}:null;return}f.current=!0,h.current=Vs(C,a.current)}}function Be(C){if(!g.current.has(C.pointerId)||!a.current)return;if(g.current.set(C.pointerId,{x:C.clientX,y:C.clientY}),g.current.size>=2&&v.current){const A=Array.from(g.current.values()).slice(0,2),M=Hs(A[0],A[1]);v.current.distance>0&&se(v.current.zoom*(M/v.current.distance),oh(A[0],A[1]));return}if(Pe==="pan"&&b.current&&p.current){p.current.scrollLeft=b.current.left-(C.clientX-b.current.x),p.current.scrollTop=b.current.top-(C.clientY-b.current.y);return}if(!f.current||!h.current)return;const j=a.current,q=Vs(C,j),J=j.getContext("2d");J.strokeStyle=O,J.lineWidth=Math.max(5,j.width/180),J.lineCap="round",J.lineJoin="round",J.beginPath(),J.moveTo(h.current.x,h.current.y),J.lineTo(q.x,q.y),J.stroke(),h.current=q}function Fe(C){C&&C.pointerId!==void 0&&g.current.delete(C.pointerId),g.current.size<2&&(v.current=null),b.current=null,f.current=!1,h.current=null}function Ce(C,j=null){if(!pe||j===null&&z.length>=Sn)return;C.preventDefault(),C.stopPropagation();const q=j===null?null:z.find(J=>J.id===j);k.current={markerId:j,pointerId:C.pointerId},_e({id:j,label:jt(j===null?z.length:z.indexOf(q),D),color:q?q.color:O,clientX:C.clientX,clientY:C.clientY});try{C.currentTarget.setPointerCapture(C.pointerId)}catch{}}function ut(C){!k.current||k.current.pointerId!==C.pointerId||(C.preventDefault(),_e(j=>j&&{...j,clientX:C.clientX,clientY:C.clientY}))}function Ne(C){const j=k.current;if(!j||j.pointerId!==C.pointerId)return;C.preventDefault(),C.stopPropagation();const q=nh(C,d.current,!0);q&&I(J=>{if(j.markerId!==null)return J.map(M=>M.id===j.markerId?{...M,...q}:M);if(J.length>=Sn)return J;const A=[...J,{id:Date.now()+Math.random(),...q,color:O,text:""}];return oe(A[A.length-1].id),A}),k.current=null,_e(null)}function it(C,j){I(q=>q.map(J=>J.id===C?{...J,text:j}:J))}function dt(C){I(j=>{const q=j.filter(J=>J.id!==C);return oe(J=>J===C?null:J),q})}function Je(){ae(!1),I([]),oe(null);const C=a.current;if(!C)return;const j=new Image;j.onload=()=>{const q=C.getContext("2d");q.clearRect(0,0,C.width,C.height),q.drawImage(j,0,0,C.width,C.height),ae(!0)},j.src=e.dataUrl}function st(){typeof c!="function"||!i||(c(),r())}function X(){const C=a.current;if(!C||!pe)return;W("");let j;try{const M=document.createElement("canvas");M.width=C.width,M.height=C.height;const ve=M.getContext("2d");if(!ve)throw new Error("Could not export the annotated image.");ve.drawImage(C,0,0),z.forEach((Ae,T)=>rh(ve,Ae,jt(T,D),C.width)),j=Qp(M)}catch(M){W(M&&M.message?M.message:"Could not export the annotated image.");return}const q=z.map((M,ve)=>{const Ae=jt(ve,D);return M.text.trim()?Ae+". "+M.text.trim():Ae+"."}),A={text:[s,t||"",n||"",Y.trim(),q.length?`Annotations:
|
|
59
|
+
`+q.join(`
|
|
60
|
+
`):""].filter(Boolean).join(`
|
|
61
|
+
`),textLabel:z.length?z.length+" matched annotation"+(z.length===1?"":"s"):"Inspector context",image:{type:"image",mimeType:"image/png",dataUrl:j,name:"draft-craft-inspector.png"}};if(o){De(A),o(A),r();return}De(A),we(!0)}const ee=u("div",{class:"draft-craft__annotator-overlay",role:"presentation"},u("section",{class:"draft-craft__annotator",role:"dialog","aria-modal":"true","aria-label":"Annotate Inspector image with Draft Craft"},u("header",{class:"draft-craft__annotator-head"},u("div",null,u("strong",null,"Draft Craft"),u("span",null,o?"Draw on the attached image":"Draw on the Inspector image")),u("button",{type:"button",class:"draft-craft__close",onClick:r,"aria-label":"Close image annotator"},"×")),u("div",{ref:p,class:"draft-craft__canvas-wrap"+(Pe==="pan"?" is-panning":"")},u("div",{ref:d,class:"draft-craft__canvas-stage",style:{width:G*100+"%"}},u("canvas",{ref:a,class:"draft-craft__canvas",onPointerDown:fe,onPointerMove:Be,onPointerUp:Fe,onPointerCancel:Fe,onPointerLeave:Fe,"aria-label":"Inspector screenshot annotation canvas. Pinch with two fingers to zoom."}),z.map((C,j)=>u("button",{key:C.id,type:"button",class:"draft-craft__image-marker"+(ie&&ie.id===C.id?" is-dragging":""),style:{left:C.x*100+"%",top:C.y*100+"%",background:C.color,color:In(C.color)},onPointerDown:q=>Ce(q,C.id),onPointerMove:ut,onPointerUp:Ne,onPointerCancel:Ne,"aria-label":"Move annotation "+jt(j,D)},jt(j,D))))),u("div",{class:"draft-craft__annotator-tools"},u("button",{type:"button",class:"draft-craft__tools-toggle","aria-expanded":String(R),"aria-controls":"draftCraftToolsBody",onClick:()=>$(C=>!C)},u("span",{class:"draft-craft__tools-toggle-label"},"Tools"),u("span",{class:"draft-craft__tools-toggle-hint"},"Annotate & zoom"),u("span",{class:"draft-craft__tools-toggle-chevron","aria-hidden":"true"},R?"⌄":"⌃")),R?u("div",{id:"draftCraftToolsBody",class:"draft-craft__tools-body"},u("div",{class:"draft-craft__zoom",role:"group","aria-label":"Image zoom"},u("button",{class:"btn btn--small",type:"button",onClick:()=>se(w.current-.25),disabled:G<=Tn(p.current,a.current),"aria-label":"Zoom out"},"−"),u("span",{"aria-live":"polite"},Math.round(G*100)+"%"),u("button",{class:"btn btn--small",type:"button",onClick:()=>se(w.current+.25),disabled:G>=Hl,"aria-label":"Zoom in"},"+"),u("button",{class:"btn btn--small",type:"button",onClick:()=>de(),disabled:Math.abs(G-Tn(p.current,a.current))<.005,"aria-label":"Show whole image",title:"Fit image to view"},"Fit"),u("button",{class:"btn btn--small"+(Pe==="pan"?" is-active":""),type:"button",onClick:()=>F(C=>C==="pan"?"draw":"pan"),"aria-pressed":String(Pe==="pan")},Pe==="pan"?"Draw":"Pan")),u("div",{class:"draft-craft__colors",role:"group","aria-label":"Annotation color"},Fs.map(C=>u("button",{key:C,type:"button",class:"draft-craft__color"+(C===O?" is-active":""),style:{background:C},"aria-label":"Use "+C,"aria-pressed":String(C===O),onClick:()=>P(C)}))),u("button",{class:"btn btn--small",type:"button",onClick:Je,disabled:!pe},"Clear"),u("section",{class:"draft-craft__markers","aria-label":"Matched image annotations"},u("div",{class:"draft-craft__marker-bar"},u("div",null,u("strong",null,"Marker dots"),u("span",null,"Drag the next dot onto the image")),u("select",{class:"input draft-craft__marker-style",value:D,onChange:C=>V(C.currentTarget.value),"aria-label":"Marker label style"},u("option",{value:"numbers"},"1, 2, 3"),u("option",{value:"letters"},"A, B, C")),u("button",{type:"button",class:"draft-craft__marker-source",style:{background:O,color:In(O)},disabled:!pe||z.length>=Sn,onPointerDown:Ce,onPointerMove:ut,onPointerUp:Ne,onPointerCancel:Ne,"aria-label":z.length>=Sn?"Maximum markers reached":"Drag marker "+jt(z.length,D)+" onto image"},z.length>=Sn?"✓":jt(z.length,D))),z.length?u("div",{class:"draft-craft__marker-list",ref:_,role:"list","aria-label":"Marked image annotations"},z.map((C,j)=>{const q=jt(j,D),J=C.id===Z;return u("div",{key:C.id,ref:J?y:null,role:"listitem",class:"draft-craft__marker-row"+(J?" is-active":"")},u("button",{type:"button",class:"draft-craft__marker-label",style:{background:C.color,color:In(C.color)},onClick:()=>oe(C.id),"aria-pressed":String(J),"aria-label":"Select annotation "+q+(C.text.trim()?": "+C.text.trim():" (no text)")},q),u("input",{class:"input draft-craft__marker-input",value:C.text,onInput:A=>it(C.id,A.currentTarget.value),placeholder:"Text for "+q,"aria-label":"Text for annotation "+q}),u("button",{type:"button",class:"draft-craft__marker-remove",onClick:()=>dt(C.id),"aria-label":"Remove annotation "+q},"×"))})):u("div",{class:"draft-craft__marker-empty"},"No marker dots on the image yet.")),u("textarea",{class:"input draft-craft__note",rows:2,value:Y,onInput:C=>re(C.currentTarget.value),placeholder:"Optional note about this image","aria-label":"Image note"})):null),u("div",{class:"draft-craft__annotator-foot"},le?u("span",{class:"status",role:"alert"},le):null,i?u("button",{class:"btn btn--ghost",type:"button",onClick:st,disabled:!pe},"Reset"):null,u("button",{class:"btn btn--primary",type:"button",onClick:X,disabled:!pe},l))),ie?u("span",{class:"draft-craft__drag-marker",style:{left:ie.clientX+"px",top:ie.clientY+"px",background:ie.color,color:In(ie.color)},"aria-hidden":"true"},ie.label):null,u(th,{open:ye,payload:He,onClose:()=>we(!1),onAdded:()=>{we(!1),r()}}));return typeof document>"u"?ee:Pc(ee,document.body)}const sh=["audio/webm;codecs=opus","audio/webm","audio/ogg;codecs=opus","audio/ogg","audio/mp4","audio/mpeg"];function ah(e){const t=e||(typeof window<"u"?window:null);return!t||typeof t.MediaRecorder!="function"||!t.navigator||!t.navigator.mediaDevices?!1:typeof t.navigator.mediaDevices.getUserMedia=="function"}function lh(e,t){const n=t||(typeof window<"u"?window:null),r=e||n&&n.MediaRecorder;if(!r||typeof r.isTypeSupported!="function")return"";for(const o of sh)try{if(r.isTypeSupported(o))return o}catch{}return""}function ch(e){const t=String(e||"").toLowerCase();return t.includes("webm")?".webm":t.includes("ogg")?".ogg":t.includes("mp4")||t.includes("m4a")||t.includes("aac")?".m4a":t.includes("mpeg")||t.includes("mp3")?".mp3":t.includes("wav")?".wav":t.includes("flac")?".flac":".webm"}function Ws(e,t){return"dictation-"+new Date(t||0).toISOString().replace(/[:.]/g,"-").slice(0,19)+ch(e)}function uh(e){const t=Math.max(0,Math.floor((Number(e)||0)/1e3)),n=t%60,r=Math.floor(t/60)%60,o=Math.floor(t/3600),i=s=>s<10?"0"+s:String(s);return o?o+":"+i(r)+":"+i(n):r+":"+i(n)}const dh=12e4;function zs(e){return new Promise((t,n)=>{if(!e){n(new Error("Nothing recorded"));return}if(typeof FileReader=="function"){const r=new FileReader;r.onerror=()=>n(new Error("Could not read the recording")),r.onload=()=>{const o=String(r.result||""),i=o.indexOf(",");t(i>=0?o.slice(i+1):o)},r.readAsDataURL(e);return}if(typeof e.arrayBuffer!="function"){n(new Error("This browser cannot read the recording"));return}e.arrayBuffer().then(r=>{const o=new Uint8Array(r);let i="";const s=32768;for(let l=0;l<o.length;l+=s)i+=String.fromCharCode.apply(null,o.subarray(l,l+s));t(btoa(i))}).catch(()=>n(new Error("Could not read the recording")))})}async function $s(e){const t=e||{},n={projectDir:t.projectDir||"",modelId:t.modelId||"",providerId:t.providerId||"",kind:t.kind||"",audioBase64:t.audioBase64||"",mimeType:t.mimeType||"audio/webm",filename:t.filename||"",language:t.language||"",prompt:t.prompt||"",chatId:t.chatId||""},r=await H("/api/ai/transcribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(r.status!==200){const o=new Error(r.body&&r.body.error||"HTTP "+r.status);throw o.code=r.body&&r.body.code||"EHTTP",o.status=r.status,o}return r.body||{}}const Wl=3e3,jo=400,ph=1;function Js(e){const t=/[\p{L}\p{N}]+(?:['’][\p{L}\p{N}]+)*/gu,n=[];let r;for(;(r=t.exec(String(e||"")))!==null;)n.push({word:r[0].toLowerCase(),end:r.index+r[0].length});return n}function fh(e,t){const n=Js(e).map(i=>i.word),r=Js(t),o=Math.min(n.length,r.length);for(let i=o;i>=ph;i--){let s=!0;for(let l=0;l<i;l++)if(n[n.length-i+l]!==r[l].word){s=!1;break}if(s)return r[i-1].end}return 0}function hh(e){const t=Array.isArray(e)?e:[];let n="";for(const r of t){const o=String(r||"").trim();if(!o)continue;if(!n){n=o;continue}const i=fh(n,o),s=i?o.slice(i).replace(/^[\s\p{P}]+/u,""):o;s&&(n+=" "+s)}return n}function mh(e){const t=Array.isArray(e)?e:[];let n=0,r=!1;for(const o of t){if(!o||o.known!==!0)continue;const i=Number(o.total);!isFinite(i)||i<=0||(n+=i,r=!0)}return r?{total:n,currency:"USD",known:!0}:null}function gh(e){return(e||{}).live!==!1}function _h(){const e=new Map;return{set(t,n){e.set(Number(t)||0,String(n||"").trim())},text(){const t=Array.from(e.keys()).sort((n,r)=>n-r);return hh(t.map(n=>e.get(n)))},pending(t){return Math.max(0,(Number(t)||0)-e.size)},answered(){return e.size}}}function yh(e){const t=e||{},n=t.recorder,r=t.setTimeout||((_,y)=>setTimeout(_,y)),o=t.clearTimeout||(_=>clearTimeout(_)),i=Number(t.segmentMs)>0?Number(t.segmentMs):Wl;let s=t.mimeType||"",l=null,c=[],a=null,d=!1;function p(_,y){return t.createBlob?t.createBlob(_,y):new Blob(_,{type:y})}function f(_){return _.mimeType||s||"audio/webm"}function h(){let _;try{_=s?new n(t.stream,{mimeType:s}):new n(t.stream)}catch{s="",_=new n(t.stream)}return c=[],_.ondataavailable=y=>{y&&y.data&&y.data.size&&c.push(y.data)},_.onstop=()=>g(_,f(_)),_.onerror=y=>v(_,f(_),y),_}function g(_,y){const w=c;if(c=[],l===_&&(l=null),a&&(o(a),a=null),w.length&&t.onSegment&&t.onSegment(p(w,y),y),d){k();return}t.onEnd&&t.onEnd()}function v(_,y,w){d=!1,g(_,y),t.onError&&t.onError(w||new Error("The recorder stopped unexpectedly."))}function b(){a=null;const _=l;if(!(!_||_.state==="inactive"))try{_.stop()}catch{}}function k(){l=h(),a=r(b,i),l.start()}return{start(){d||!n||(d=!0,k())},stop(){if(!d)return;d=!1,a&&(o(a),a=null);const _=l;if(!_){t.onEnd&&t.onEnd();return}try{_.stop()}catch{g(_,f(_))}},recording(){return d}}}async function vh(e,t){const n=t||{},r=new URLSearchParams({projectDir:e||""});n.live===!1&&r.set("live","0"),n.refresh&&r.set("refresh","1");const o=await H("/api/ai/transcribe/models?"+r.toString());return o.status!==200?{models:[],kinds:[],total:0,providers:[],liveFailures:[],error:o.body}:{models:Array.isArray(o.body&&o.body.models)?o.body.models:[],kinds:Array.isArray(o.body&&o.body.kinds)?o.body.kinds:[],total:o.body&&o.body.total||0,providers:Array.isArray(o.body&&o.body.providers)?o.body.providers:[],liveFailures:Array.isArray(o.body&&o.body.liveFailures)?o.body.liveFailures:[]}}function Om(e,t){const n=(e||[]).find(r=>r&&r.id===t);return n?n.label:t||""}function bh(e){return e==="gemini"?"Gemini":e==="openai-audio"?"OpenAI chat":e==="openai-compatible"?"OpenAI-shaped":e||"unknown"}const wh=["whisper","transcribe","transcription","voxtral","parakeet"];function zl(e){const t=e&&e.inputModalities;return Array.isArray(t)&&t.some(n=>String(n).toLowerCase()==="audio")}function $l(e){const t=e&&e.outputModalities;return Array.isArray(t)&&t.some(n=>String(n).toLowerCase()==="transcription")}function Jl(e){if(!e)return 0;const t=String(e.id||"").toLowerCase();return $l(e)||wh.some(n=>t.includes(n))?3:e.kind==="gemini"||zl(e)?2:e.source==="project"?1:0}function jm(e,t){const r=(Array.isArray(e)?e:[]).map((s,l)=>({row:s,index:l,rank:Jl(s)})).filter(s=>s.rank>=2).sort((s,l)=>l.rank-s.rank||s.index-l.index),o=r.filter(s=>s.rank>=3);return(o.length?o:r).slice(0,5).map(s=>s.row)}function Ch(e,t){const n=Array.isArray(e)?e:[],r=t||{};if(r.modelId){const i=n.find(s=>s&&s.id===r.modelId&&(s.provider||"")===(r.providerId||""))||n.find(s=>s&&s.id===r.modelId);if(i)return{modelId:i.id,providerId:i.provider||""}}return n.length===1?{modelId:n[0].id,providerId:n[0].provider||""}:null}function kh(e,t){const n=Array.isArray(e)?e:[],r=Ch(n,t);if(r)return r;const o=n.filter(i=>Jl(i)>=3);return o.length===1?{modelId:o[0].id,providerId:o[0].provider||""}:null}function Dm(e){return(Array.isArray(e)?e:[]).map(t=>({id:t.id,provider:t.provider||"",label:t.label&&t.label!==t.id?t.label:Eh(t)}))}function Bm(e){const t=e||{};if(t.catalogBusy)return{text:"Loading models…",loading:!0};if(t.liveBusy)return{text:"Looking for models from your providers…",loading:!0};const n=Number(t.projectCount)||0,r=!!t.hasLive;return n?{text:n+(n===1?" project model":" project models")+(r?", plus models from your provider":""),loading:!1}:{text:r?"Models from your provider connections":"No models",loading:!1}}function Fm(e){const t=e||{};return t.catalogBusy?"catalog":t.liveBusy?"live":t.transcribing?"transcribe":t.handoff?"handoff":""}const Sh="Transcribing…";function Th(e){const t=e||{};return t.transcribing||t.finishing?"transcribe":""}const Ah="Preparing dictation…";function xh(e){const t=e||{};return t.preparing&&Number(t.delayMs)>=jo?Ah:""}function Eh(e){if(!e)return"";const t=zl(e);return e.source==="live"?t&&!$l(e)?"from provider · audio in":"from provider":""}function Ih(e){const t=e&&e.cost,n=t?Number(t.total):NaN,r=!!(t&&t.known)&&isFinite(n)&&n>=0;return{known:r,total:r?n:0,label:r?Ht(n):"--"}}function qm(e){const t=e||{};return"Last run: "+[t.model&&t.model.id||"unknown model",bh(t.kind),Math.round((t.bytes||0)/1024)+" kB",Math.round((t.durationMs||0)/100)/10+"s","cost "+(t.costLabel||"--")].join(" · ")}function Um(e){const t=e||{},n=!!(t.text&&t.text.trim());return[{id:"copy",label:"Copy",disabled:!n},{id:"insert",label:"Insert in chat",disabled:!n||!t.chatId},{id:"send",label:"Send to chat",disabled:!n||!t.chatId},{id:"clear",label:"Clear",disabled:!n&&!t.hasRecording}]}const Gs="No dictation model yet — "+Nh();function Ph(e){const{language:t="",onTranscript:n,onStatus:r,onProgress:o,promptRef:i}=e,[s,l]=E(!1),[c,a]=E(""),[d,p]=E(""),[f,h]=E(!1),[g,v]=E(!1),[b,k]=E(!1),_=f||g,[y,w]=E(0),N=x(""),O=x(null),P=x(null),Y=x([]),re=x(null),z=x(0),I=x(null),D=x(null),V=x(0),Z=x(""),oe=x(0),ie=x(!1),_e=x(!1),ye=x([]),we=x(!1),[He,De]=E(0),pe=x(null);function ae(X,ee){a(X||""),p(ee||""),r&&r(X||"",ee||"")}function le(X,ee){a(X||""),p(ee)}function W(){const X=P.current;if(P.current=null,X&&typeof X.getTracks=="function")for(const ee of X.getTracks())try{ee.stop()}catch{}}function G(){re.current&&(clearTimeout(re.current),re.current=null)}function he(){const X=Z.current,ee=D.current?D.current.text():"",C=ee&&X&&!/\s$/.test(X)?" ":"";return{draft:X+C+ee,text:ee,base:X+C,caret:(X+C+ee).length}}function Pe(){if(!n)return;const X=he();n(X.text,{live:!0,model:pe.current?{id:pe.current.id,provider:pe.current.provider||""}:null,cost:null})}function F(X){const ee=D.current,C=ee?ee.text():"";D.current=null,Z.current="",oe.current=0,ie.current=!1,ye.current=[],!(!C||!n)&&n(C,{model:pe.current?{id:pe.current.id,provider:pe.current.provider||""}:null,cost:X||null})}function R(X,ee){if(!X||!X.size)return;const C=oe.current++;$(X,ee,C)}async function $(X,ee,C){const j=pe.current;if(j)try{const q=await zs(X);if(!D.current)return;const J=await $s({projectDir:e.projectDir||"",chatId:e.chatId||"",modelId:j.id,providerId:j.provider||"",kind:j.kind||"",audioBase64:q,mimeType:ee,filename:Ws(ee,z.current),language:t});if(!D.current)return;ie.current=!1,D.current.set(C,(J.text||"").trim()),J.cost&&ye.current.push(J.cost),we.current&&Pe()}catch{if(!D.current)return;ie.current=!0}finally{se()}}function se(){const X=D.current;if(!X)return;if(we.current){const q=X.text().split(/\s+/).filter(Boolean).length,J=ie.current?"Recording — part of what you said could not be transcribed; still listening…":q?q+" words so far — tap the mic to stop.":"Recording — tap the mic again to stop.";o?o(J,"busy"):ae(J,"busy");return}if(X.pending(oe.current)>0){k(!0);const q=ie.current?"Finishing dictation — part of what you said could not be transcribed…":Sh;o?o(q,"busy"):ae(q,"busy");return}k(!1);const ee=ie.current,C=X.text(),j=mh(ye.current);if(F(j),C&&ee){ae("Added to the composer — part of what you said could not be transcribed.","error");return}if(C){const q=j?Ht(j.total):"--";le(q==="--"?"Added to the composer — review it, then send.":"Added to the composer ("+q+") — review it, then send.","success");return}ae(ee?"Transcription failed":"Nothing was recognised — try again a little closer to the mic.","error")}ue(()=>()=>{we.current=!1,G();const X=I.current;I.current=null,X&&X.stop();const ee=O.current;if(ee&&ee.state!=="inactive")try{ee.stop()}catch{}W()},[]),ue(()=>{if(!s)return;const X=setInterval(()=>De(ee=>ee+1),1e3);return()=>clearInterval(X)},[s]),ue(()=>{if(!f)return;const X=setTimeout(()=>w(jo),jo);return()=>{clearTimeout(X),w(0)}},[f]);async function de(X,ee){v(!0),ae("Transcribing…","busy");try{const C=pe.current||await fe();if(!C){ae(Gs,"error"),v(!1);return}const j=await zs(X),q=await $s({projectDir:e.projectDir||"",chatId:e.chatId||"",modelId:C.id,providerId:C.provider||"",kind:C.kind||"",audioBase64:j,mimeType:ee,filename:Ws(ee,z.current),language:t}),J=(q.text||"").trim();if(!J){ae("Nothing was recognised — try again a little closer to the mic.","error"),v(!1);return}n&&n(J,{model:q.model,kind:q.kind,usage:q.usage||null,cost:q.cost||null});const A=Ih(q).label;le(A==="--"?"Added to the composer — review it, then send.":"Added to the composer ("+A+") — review it, then send.","success")}catch(C){ae(C&&C.message||"Transcription failed","error")}finally{v(!1)}}async function fe(){const X=await H("/api/settings"),ee=X.status===200&&X.body&&X.body.app&&X.body.app.dictation||{},C=await vh(e.projectDir||""),j=kh(C.models,ee);if(!j)return null;const q=C.models.find(J=>J.id===j.modelId&&(J.provider||"")===j.providerId);return q?{row:q,live:gh(ee)}:null}async function Be(){const X=typeof window<"u"?window:null;if(!ah(X)){ae("This browser cannot record audio.","error");return}h(!0);let ee=null;try{ee=await fe()}catch(A){h(!1),ae(A&&A.message||"Could not load the dictation model list.","error");return}if(h(!1),!ee){ae(Gs,"error");return}pe.current=ee.row;let C;try{C=await X.navigator.mediaDevices.getUserMedia({audio:!0})}catch(A){ae(A&&A.name==="NotAllowedError"?"Microphone permission was refused.":"Could not open the microphone.","error");return}P.current=C;const j=lh(X.MediaRecorder,X),q=e.promptRef&&e.promptRef.current;V.current=q&&typeof q.selectionStart=="number"?q.selectionStart:q?q.value.length:0,Z.current=q?q.value.slice(0,V.current):"",oe.current=0,ie.current=!1,ye.current=[],D.current=_h(),_e.current=ee.live;let J=null;if(_e.current){const A=yh({recorder:X.MediaRecorder,stream:C,mimeType:j,segmentMs:Wl,onSegment:R,onEnd:()=>{I.current=null,G(),we.current=!1,W(),l(!1),se()},onError:()=>{I.current=null,G(),we.current=!1,W(),l(!1),ae("The recorder stopped unexpectedly.","error")}});I.current=A}else{try{J=j?new X.MediaRecorder(C,{mimeType:j}):new X.MediaRecorder(C)}catch{try{J=new X.MediaRecorder(C)}catch{W(),ae("Could not start the recorder.","error");return}}Y.current=[],J.ondataavailable=A=>{A&&A.data&&A.data.size&&Y.current.push(A.data)},J.onstop=()=>{G();const A=J.mimeType||j||"audio/webm",M=Y.current.length?new Blob(Y.current,{type:A}):null;Y.current=[],O.current=null,we.current=!1,W(),l(!1),D.current=null,M&&M.size?de(M,A):ae("Nothing was captured — check the microphone is not muted.","error")},J.onerror=()=>{G(),O.current=null,we.current=!1,W(),l(!1),D.current=null,ae("The recorder stopped unexpectedly.","error")},O.current=J}if(z.current=Date.now(),l(!0),we.current=!0,ae(_e.current?"Recording — the words appear in the composer as you speak; tap the mic to stop.":"Recording — tap the mic again to stop.","busy"),_e.current)try{I.current.start()}catch{I.current=null,_e.current=!1,we.current=!1,W(),l(!1),D.current=null,ae("Could not start the recorder.","error");return}else J.start();re.current=setTimeout(()=>Fe(),dh)}function Fe(){if(G(),we.current=!1,l(!1),_e.current){const ee=I.current;if(ee){ee.stop();return}_e.current=!1,se();return}const X=O.current;if(X&&X.state!=="inactive")try{X.stop()}catch{}D.current=null}function Ce(){if(!_){if(s){Fe();return}Be()}}const ut=Th({transcribing:g,finishing:b}),Ne=xh({preparing:f,delayMs:y});ue(()=>{Ne!==N.current&&(N.current=Ne,Ne&&ae(Ne,"busy"))},[Ne]);const it=s?uh(Date.now()-z.current):"",dt=s?"Stop dictation ("+it+")":"Dictate",Je=ut==="transcribe",st=s?u("path",{d:"M7 7h10v10H7Z",fill:"currentColor"}):u("path",{d:"M12 2a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Zm7 9a1 1 0 1 0-2 0 5 5 0 0 1-10 0 1 1 0 1 0-2 0 7 7 0 0 0 6 6.92V21H8a1 1 0 1 0 0 2h8a1 1 0 1 0 0-2h-3v-3.08A7 7 0 0 0 19 11Z",fill:"currentColor"});return u("button",{class:"chat-view__mic-btn"+(s?" is-recording":"")+(Je?" is-busy":""),type:"button",onClick:Ce,disabled:_,title:c||"Dictate","aria-label":Je?"Working…":dt,"aria-pressed":s?"true":"false","aria-busy":Je?"true":void 0,"data-state":d||void 0},Je?u("span",{class:"dictation__spinner dictation__spinner--mic","aria-hidden":"true"}):u("svg",{viewBox:"0 0 24 24",width:18,height:18,"aria-hidden":"true"},st))}function Nh(){return"Open Settings → App defaults → Dictation to pick a dictation model."}function Rh(e){const t=Sf(e),{refs:n,imageAttachments:r,composerText:o,fileEditorOpen:i,runningVisible:s,authStamp:l,toolDataStamp:c,mcpStartBusy:a,fileOrb:d,composerTools:p,chatSwitcherOpen:f,chatSwitcherList:h,chatSwitcherLoading:g,customActions:v,setFileEditorOpen:b,setImageAttachments:k,setComposerText:_,setChatSwitcherOpen:y,picker:w,send:N,onPickerPick:O,onPickerTogglePin:P,onPickerOpen:Y,onRefreshAllProviders:re,onPickerOpenChange:z,onComposerKey:I,onComposerInput:D,onComposerPaste:V,onImagePickerChange:Z,onRemoveImage:oe,onJumpToBottom:ie,onCancelRunning:_e,onBack:ye,onToggleAutoRetry:we,onToggleChatSwitcher:He,onChatSwitcherScroll:De,onSwitchChat:pe,runCustomAction:ae,refreshCustomActions:le,updateChat:W}=t,{projectDir:G,chatId:he}=e,Pe=x(null),[F,R]=E(null),$=x(null);function se(A,M){const ve=n.promptInput.current;if(!ve||M&&M.live&&!String(A||"").trim())return;const Ae=ve.value,T=$.current,B=T&&T.text?T:null;let te=null;if(B)if(Ae.slice(B.start,B.start+B.text.length)===B.text)te=B.start;else{const Lt=Ae.indexOf(B.text);Lt>=0&&(te=Lt)}const Se=te!==null&&B?B.text.length:0;te===null&&(te=typeof ve.selectionStart=="number"?ve.selectionStart:Ae.length);const be=Ae.slice(0,te),Me=Ae.slice(te+Se),Re=be&&!/\s$/.test(be)?" ":"",Qe=Me&&!/^\s/.test(Me)?" ":"",at=be+Re+A+Qe+Me;$.current=M&&M.live?{start:te,text:Re+A}:null,Ne(at),W&&jn(at,n,W).catch(()=>{});const Rt=M&&!M.live?M.cost:null;if(Rt&&Rt.known&&Number.isFinite(Number(Rt.total))){const Lt=wd(Pe.current,t.state.costSnapshot,Rt.total);Lt&&(Pe.current=Lt,t.state.attributedCost=Lt.total,ot(t.state,null,n))}const Yn=(be+Re+A).length;try{ve.focus({preventScroll:!0}),ve.setSelectionRange(Yn,Yn)}catch{}(!M||!M.live)&&no(n.status,"dictation added"+de(M),"success")}function de(A){const M=A&&A.cost;return!M||!M.known||!isFinite(Number(M.total))?"":" · "+Ht(M.total)}function fe(A,M){no(n.status,A,M)}function Be(A,M){no(n.status,A,M)}function Fe(A){if(!A||A.projectDir!==G||A.chatId!==he||!A.chat)return;const M=A.chat;n.promptInput.current&&(n.promptInput.current.value=M.draft||"",_(M.draft||""),n._autoresize&&n._autoresize()),k(Array.isArray(M.draftAttachments)?M.draftAttachments:[])}const[Ce,ut]=E(null);function Ne(A){n.promptInput.current&&(n.promptInput.current.value=A),_(A),n._autoresize&&n._autoresize()}function it(A){if(!Ce||!A||!A.image)return;const M=Array.isArray(r)?r.slice():[],ve=M[Ce.index];if(ve){const Ae=(typeof A.text=="string"?A.text:"").trim(),T=Po(ve),B=n.promptInput.current?n.promptInput.current.value:o,te=T?As(B,T.annotationText,T.annotationStart):B,Se=Kp(te,Ae),be=B.length-te.length,Me=T&&be?xs(M,T.annotationStart,-be,Ce.index):M;Me[Ce.index]=Zp(ve,A.image,Ae,Se.start);const Re=Se.value;k(Me),Ne(Re),W&&jn(Re,n,W,{draftAttachments:Vt(Me)}).catch(()=>{})}ut(null)}function dt(){if(!Ce)return;const A=Array.isArray(r)?r.slice():[],M=Po(A[Ce.index]);if(!M)return;const ve=n.promptInput.current?n.promptInput.current.value:o,Ae=As(ve,M.annotationText,M.annotationStart),T=ve.length-Ae.length,B=T?xs(A,M.annotationStart,-T,Ce.index):A;B[Ce.index]=M.attachment,k(B),Ne(Ae),W&&jn(Ae,n,W,{draftAttachments:Vt(B)}).catch(()=>{})}const[Je,st]=E(()=>os()),[X,ee]=E(!1),[C,j]=E(!1);ue(()=>{if(!i||F)return;let A=!1;return je(()=>import("./FileEditor-BqgbeJHy.js"),__vite__mapDeps([0,1,2])).then(M=>{A||R(()=>M.FileEditorView)}).catch(()=>{A||R(null)}),()=>{A=!0}},[i,F]),ue(()=>{const A=Du(M=>{st(M||null),M||ee(!1)});return st(os()),()=>{A()}},[]),ue(()=>{is(),st(null),ee(!1),j(!1)},[G,he]),ue(()=>()=>{Hu()},[]);const q=x(null),J=x(null);return ue(()=>{if(!n.promptInput.current||!q.current)return;const A=Np(n.promptInput.current,q.current,t.state,J.current),M=setInterval(()=>Rp(),5e3);return()=>{A(),clearInterval(M)}},[n.promptInput,n.promptInput.current,t.state.props&&t.state.props.projectDir]),u("section",{class:"chat-view"},u("div",{class:"chat-view__head"},u("button",{ref:n.back,class:"chat-view__back",type:"button",onClick:ye,"aria-label":"Back to projects"},"←"),u("div",{class:"chat-view__title-stack","data-switcher":"1"},u("button",{ref:n.chatSwitcherTrigger,class:"chat-view__chat-switcher-trigger",type:"button",onClick:He,"aria-label":"Switch chat","aria-haspopup":"true","aria-expanded":String(f)},u("div",{class:"chat-view__chat-switcher-title"},u("div",{ref:n.chatName,class:"chat-view__name"},"…"),u("div",{ref:n.chatMeta,class:"chat-view__meta"},"")),u("span",{class:"chat-view__chat-switcher-caret","aria-hidden":"true"},"▾")),u("div",{ref:n.chatSwitcherPop,class:"chat-view__chat-switcher-pop",hidden:!f,role:"listbox","aria-label":"Switch to a chat",onScroll:De},h.map(A=>u("button",{key:A.id,class:"chat-view__chat-switcher-item"+(A.id===he?" is-current":""),type:"button",role:"option","aria-selected":String(A.id===he),onClick:()=>pe(A.id)},u("span",{class:"chat-view__chat-switcher-item-title"},A.title&&A.title.trim()?A.title:"New chat"),u("span",{class:"chat-view__chat-switcher-item-model"},A.modelId||""),A.id===he&&s?u("span",{class:"chat-view__chat-switcher-running","aria-hidden":"true"}):null)),h.length?null:u("div",{class:"chat-view__chat-switcher-empty"},"No other chats"),u("div",{class:"chat-view__chat-switcher-more",hidden:!g},"Loading more…")),u("div",{ref:n.usageSummaryRef,class:"chat-view__usage-summary","aria-label":"Chat usage and provider credit"},u("span",null,"Context --"),u("span",null,"Total --"))),u("div",{class:"chat-view__model-row"},u(il,{models:w.models,value:w.value,variant:"chat",open:w.open,onOpenChange:z,noProviders:!t.state.providers.length,pinned:w.pinned,onTogglePin:P,recent:w.recent,extraProviders:w.providers,refresh:re,refreshEmpty:"Refresh models",ariaLabel:"Pick model",onOpen:Y,onChange:O},u("div",{class:"chat-view__picker-maxout"},u("input",{ref:n.maxOutputTokens,class:"input chat-view__picker-maxout-input",type:"number",min:1,inputMode:"numeric",placeholder:"Max output tokens (blank = default)","aria-label":"Max output tokens",onBlur:A=>{const M=A.currentTarget.value.trim();M&&t.state.chat?(t.state.maxOutputTokens=M,M!==(t.state.chat.maxOutputTokens||"")&&t.updateChat({maxOutputTokens:M})):!M&&t.state.chat&&t.state.chat.maxOutputTokens&&(t.state.maxOutputTokens="",t.updateChat({maxOutputTokens:""}))},onKeydown:A=>{A.key==="Enter"&&A.currentTarget.blur()}}))),u("select",{ref:n.thinkingLevel,class:"input chat-view__thinking-select","aria-label":"Thinking level","data-allow-custom":"1",onChange:A=>{const M=A.currentTarget.value;t.state.thinkingLevel=M;const ve=t.refs.thinkingLevelCustom&&t.refs.thinkingLevelCustom.current;ve&&(ve.hidden=M!=="__custom__",M==="__custom__"&&ve.focus()),M!=="__custom__"&&t.state.chat&&t.updateChat({thinkingLevel:M})}}),u("input",{ref:n.thinkingLevelCustom,class:"input chat-view__thinking-custom",type:"text",hidden:!0,placeholder:"e.g. 4096, minimal, low, high","aria-label":"Custom thinking level",onBlur:A=>{const M=A.currentTarget.value.trim();M&&t.state.chat&&(t.state.thinkingLevel=M,t.updateChat({thinkingLevel:M}))},onKeydown:A=>{A.key==="Enter"&&A.currentTarget.blur()}})),u("div",{class:"chat-view__head-icons"},u("a",{class:"chat-view__iconbtn",href:"#/settings/project?projectDir="+encodeURIComponent(G||"")+"&chatId="+encodeURIComponent(he||""),"aria-label":"Project settings",title:"Settings"},u("svg",{viewBox:"0 0 24 24",width:16,height:16,fill:"currentColor","aria-hidden":"true"},u("path",{d:"M19.14 12.94a7.07 7.07 0 0 0 0-1.88l2.03-1.58a.5.5 0 0 0 .12-.64l-1.92-3.32a.5.5 0 0 0-.6-.22l-2.39.96a7.03 7.03 0 0 0-1.63-.94l-.36-2.54A.5.5 0 0 0 13.9 2h-3.84a.5.5 0 0 0-.5.42l-.36 2.54a7.03 7.03 0 0 0-1.63.94l-2.39-.96a.5.5 0 0 0-.6.22L2.66 8.48a.5.5 0 0 0 .12.64l2.03 1.58a7.07 7.07 0 0 0 0 1.88L2.78 14.16a.5.5 0 0 0-.12.64l1.92 3.32a.5.5 0 0 0 .6.22l2.39-.96c.5.39 1.05.71 1.63.94l.36 2.54a.5.5 0 0 0 .5.42h3.84a.5.5 0 0 0 .5-.42l.36-2.54c.58-.23 1.13-.55 1.63-.94l2.39.96a.5.5 0 0 0 .6-.22l1.92-3.32a.5.5 0 0 0-.12-.64l-2.04-1.58ZM12 15.5A3.5 3.5 0 1 1 12 8.5a3.5 3.5 0 0 1 0 7Z",fill:"currentColor"}))),u(Df,{tools:t.state.tools,mcpServers:t.state.mcpServers,usedTools:t.state.usedTools,agentFiles:t.state.agentFiles,skills:t.state.skills,autoRetry:t.state.autoRetry,onToggleAutoRetry:we,toolAuth:t.state.toolAuth,mcpAuth:t.state.mcpAuth,onToggleTool:t.state._toggleTool,onToggleToolGroup:t.state._toggleToolGroup,onToggleAgentFiles:t.state._toggleAgentFiles,onToggleSkills:t.state._toggleSkills,onToggleSkill:t.state._toggleSkill,onSaveToolAuth:t.state._saveToolAuth,onSaveMcpAuth:t.state._saveMcpAuth,onReloadMcpServer:t.state._startMcpServer,mcpStartBusy:a,authStamp:l,toolDataStamp:c}))),u("div",{ref:n.transcript,class:"chat-view__transcript","aria-live":"polite"}),u("button",{ref:n.jumpBtn,class:"chat-view__jump",type:"button",hidden:!0,onClick:ie,"aria-label":"Jump to latest messages"},u("svg",{viewBox:"0 0 24 24",width:16,height:16,"aria-hidden":"true"},u("path",{d:"M12 16.5 4.5 9l1.4-1.4 6.1 6.1 6.1-6.1L19.5 9 12 16.5Z",fill:"currentColor"})),u("span",{class:"chat-view__jump-count"},"")),u(Bf,{preview:Je,onOpen:()=>ee(!0),onDismiss:()=>is()}),u("div",{class:"chat-view__composer-row"},u("div",{class:"chat-view__composer-tool"},u(Mf,{projectDir:G,orb:d,onOpenFileEditor:()=>b(!0),onOpenPreview:()=>j(!0),customActions:v,onRunCustomAction:ae,onRefreshCustomActions:le})),u("div",{class:"chat-view__composer"},u("div",{ref:q,class:"at-mention",role:"listbox","aria-label":"Suggestions",hidden:!0}),u("div",{ref:J,class:"at-mention__arg-bar",hidden:!0}),p.image?u("button",{class:"chat-view__iconbtn chat-view__image-btn",type:"button",onClick:()=>n.imageInput.current&&n.imageInput.current.click(),"aria-label":"Add image",title:"Add image"},u("svg",{viewBox:"0 0 24 24",width:18,height:18,"aria-hidden":"true"},u("path",{d:"M5 4h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Zm0 13.5L9.5 13l3 3 2-2.5 4.5 4.5V6H5v11.5ZM8.5 10a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z",fill:"currentColor"}))):null,u("input",{ref:n.imageInput,class:"chat-view__image-input",type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",multiple:!0,onChange:Z}),p.dictation?u(Ph,{projectDir:G,chatId:he,promptRef:n.promptInput,onTranscript:se,onStatus:fe,onProgress:Be}):null,u("textarea",{ref:n.promptInput,class:"input chat-view__textarea",id:"chatComposer",rows:1,placeholder:r.length?"Add a caption or send":"Type a message","aria-label":"Message",onKeydown:I,onPaste:V,onInput:D}),s?u("button",{ref:n.stopBtn,class:"btn btn--primary chat-view__send",type:"button",onClick:_e,"aria-label":"Stop"},u("svg",{viewBox:"0 0 24 24",width:18,height:18,"aria-hidden":"true"},u("path",{d:"M6 6h12v12H6Z",fill:"currentColor"}))):u("button",{ref:n.sendBtn,class:"btn btn--primary chat-view__send",type:"button",onClick:N,disabled:!o.trim()&&!r.length,"aria-label":"Send"},u("svg",{viewBox:"0 0 24 24",width:18,height:18,"aria-hidden":"true"},u("path",{d:"M3.4 20.6 21 12 3.4 3.4 3 10l13 2-13 2 .4 6.6Z",fill:"currentColor"}))),r.length?u("div",{class:"chat-view__image-preview"},r.map((A,M)=>u("div",{key:M,class:"chat-view__image-chip"},u("button",{class:"chat-view__image-chipimg",type:"button",onClick:()=>ut({index:M,attachment:A}),"aria-label":"Annotate image "+(A.name||M+1),title:"Annotate image"},u("img",{src:A.dataUrl,alt:A.name||"attached image"})),u("button",{class:"chat-view__image-chipremove",type:"button",onClick:()=>oe(M),title:"Remove image","aria-label":"Remove image "+(A.name||M+1)},u("span",null,"×"))))):null)),u("div",{class:"chat-view__status-row"},u("span",{ref:n.status,class:"status chat-view__status","aria-live":"polite"})),i&&F?u(F,{projectDir:G,onClose:()=>b(!1),onDraftCraftAdded:Fe}):null,X&&Je?u(Hf,{preview:Je,onClose:()=>ee(!1),onRecapture:A=>Lh(Je,A,{projectDir:G,chatId:he,refs:n,onAuthorizationRequired:()=>ee(!1)})}):null,C?u(Kf,{onSubmit:A=>Mh(A,{projectDir:G,chatId:he,refs:n,onPromptClose:()=>j(!1)}),onClose:()=>j(!1)}):null,Ce?u(ih,{image:Ce.attachment,originalDataUrl:Yp(Ce.attachment),sourceLabel:"Attached image",actionLabel:"Use annotated image",onReset:dt,onAnnotated:it,onClose:()=>ut(null)}):null)}async function Lh(e,t,n){const r=e&&e.url;if(!r)return null;const o=n&&n.projectDir,i=n&&n.chatId,s=n&&n.refs;if(!o||!i)return null;const l="ui_"+Date.now().toString(36)+Math.random().toString(36).slice(2,7),c=()=>bo({projectDir:o,chatId:i,url:r,viewport:t||void 0,callId:l});let a=null;try{a=await c()}catch(d){if(d&&d.code==="EAUTH_REQUIRED"){n&&typeof n.onAuthorizationRequired=="function"&&n.onAuthorizationRequired();let p=null;await Nt({callId:d.callId||l,tool:"webpreview",cmd:r,projectDir:o},o,i,s,async()=>{p=await c()})!=="deny"&&(a=p)}else{const p=d&&d.message||String(d),f=s&&s.status;return f&&f.current&&(f.current.textContent="Preview recapture failed: "+p),null}}return a&&a.ok&&a.result&&a.result.thumbnail?Wn(a.result):a&&!a.ok&&s&&s.status&&s.status.current&&(s.status.current.textContent="Preview recapture failed: "+(a.result&&a.result.error||a.error||"capture failed")),a}async function Mh(e,t){const n=t&&t.projectDir,r=t&&t.chatId,o=t&&t.refs,i=t&&t.onPromptClose;if(!n||!r)return null;const s="ui_"+Date.now().toString(36)+Math.random().toString(36).slice(2,7),l=o&&o.status&&o.status.current;l&&(l.textContent="Capturing preview…");let c=null;try{c=await bo({projectDir:n,chatId:r,url:e,callId:s})}catch(a){if(a&&a.code==="EAUTH_REQUIRED")return i&&i(),await Nt({callId:a.callId||s,tool:"webpreview",cmd:e,projectDir:n},n,r,o,async()=>{c=await bo({projectDir:n,chatId:r,url:e,callId:s})})!=="deny"?(c&&c.ok&&c.result&&c.result.thumbnail&&Wn(c.result),c?"captured":"denied"):"denied";const d=a&&a.message||String(a);return l&&(l.textContent="Preview failed: "+d),null}return i&&i(),c&&c.ok&&c.result&&c.result.thumbnail?(Wn(c.result),l&&(l.textContent=""),"captured"):(l&&(l.textContent="Preview failed: "+(c&&c.result&&c.result.error||c&&c.error||"capture failed")),null)}const Ke=(e,t)=>ma(()=>e().then(n=>({default:n[t]}))),Oh=ma(()=>je(()=>import("./Inspector-C88hoEcC.js"),__vite__mapDeps([3,4,1,5])).then(e=>({default:e.InspectorView}))),jh=Ke(()=>je(()=>import("./SettingsProviders-BalA35c9.js"),[]),"SettingsProvidersView"),Ks=Ke(()=>je(()=>import("./SettingsProviders-BalA35c9.js"),[]),"SettingsProviderEditView"),lr=Ke(()=>je(()=>import("./SettingsProject-Cry5UltF.js"),__vite__mapDeps([6,7,8])),"SettingsProjectView"),Dh=Ke(()=>je(()=>import("./SettingsHiddenContent-XE1HiHzN.js"),__vite__mapDeps([9,7,1,10])),"SettingsHiddenContentView"),Bh=Ke(()=>je(()=>import("./SettingsDefaults-CMSIeSt8.js"),[]),"SettingsDefaultsView"),Fh=Ke(()=>je(()=>import("./SettingsNotifications-DJt0f8Jn.js"),[]),"SettingsNotificationsView"),qh=Ke(()=>je(()=>import("./SettingsAbout-D5gHujOy.js"),[]),"SettingsAboutView"),Uh=Ke(()=>je(()=>import("./SettingsPrompts-B9ECDKEa.js"),[]),"SettingsPromptsView"),Vh=Ke(()=>je(()=>import("./SettingsAgents-BVwBxPbO.js"),__vite__mapDeps([11,8,12])),"SettingsAgentsView"),Hh=Ke(()=>je(()=>import("./SettingsAgents-BVwBxPbO.js"),__vite__mapDeps([11,8,12])),"SettingsAgentEditView"),Wh=Ke(()=>je(()=>import("./SettingsActions-YrcVF8D3.js"),[]),"SettingsActionsView"),zh=Ke(()=>je(()=>import("./SettingsActions-YrcVF8D3.js"),[]),"SettingsActionEditView"),$h=Ke(()=>je(()=>import("./SettingsMcp-BAK8U0e4.js"),__vite__mapDeps([13,14])),"SettingsMcpView"),Jh=Ke(()=>je(()=>import("./SettingsMcpEdit-j21BWCAH.js"),__vite__mapDeps([15,14])),"SettingsMcpEditView"),Gh=Ke(()=>je(()=>import("./SettingsMcpRegistry-DH5YAigF.js"),__vite__mapDeps([16,14])),"SettingsMcpRegistryView"),Kh=Ke(()=>je(()=>import("./SettingsTags-D_1AgCwY.js"),__vite__mapDeps([17,4])),"SettingsTagsView"),Zh=Ke(()=>je(()=>import("./SettingsPricing-Csy5MjG-.js"),[]),"SettingsPricingView"),Yh=Ke(()=>je(()=>import("./SettingsProjects-d3wgiADv.js"),[]),"SettingsProjectsView"),Xh=Ke(()=>je(()=>import("./DictationPage-Dwb6gGNi.js"),[]),"DictationView"),Gl={chats:[Na],settingsDictation:[Xh],inspector:[Oh],picker:[Su,({dir:e})=>({dir:e})],chat:[Rh,({chatId:e,projectDir:t})=>({chatId:e,projectDir:t})],settings:[uu],settingsProviders:[jh],settingsProviderNew:[Ks,()=>({id:""})],settingsProviderEdit:[Ks,({id:e})=>({id:e})],settingsProject:[lr,({projectDir:e,chatId:t,from:n})=>({projectDir:e,chatId:t,from:n})],settingsProjectTechnical:[lr,({projectDir:e,chatId:t,from:n})=>({projectDir:e,chatId:t,from:n,page:"technical"})],settingsProjectOutput:[lr,({projectDir:e,from:t})=>({projectDir:e,from:t,page:"output"})],settingsProjectPreview:[lr,({projectDir:e,from:t})=>({projectDir:e,from:t,page:"preview"})],settingsProjectHide:[Dh,({projectDir:e,from:t,filePath:n})=>({projectDir:e,from:t,filePath:n})],settingsDefaults:[Bh],settingsNotifications:[Fh],settingsPrompts:[Uh,({projectDir:e,id:t="",scope:n="",from:r})=>({projectDir:e,initialId:t,scope:n,from:r})],settingsAgents:[Vh,({projectDir:e,from:t,chatId:n})=>({projectDir:e,from:t,chatId:n})],settingsAgentEdit:[Hh,({id:e,projectDir:t,from:n,chatId:r,returnTo:o,isNew:i})=>({id:e,projectDir:t,from:n,chatId:r,returnTo:o,isNew:i})],settingsActions:[Wh,({projectDir:e,from:t})=>({projectDir:e,from:t})],settingsActionEdit:[zh,({id:e,projectDir:t,from:n})=>({id:e,projectDir:t,from:n})],settingsMcp:[$h,({projectDir:e,from:t})=>({projectDir:e,from:t})],settingsMcpEdit:[Jh,({id:e,projectDir:t,scope:n,from:r})=>({id:e,projectDir:t,scope:n,from:r})],settingsMcpRegistry:[Gh,({projectDir:e,from:t})=>({projectDir:e,from:t})],settingsTags:[Kh,({projectId:e,projectDir:t})=>({projectId:e,projectDir:t})],settingsPricing:[Zh],settingsProjects:[Yh],settingsAccess:[_u],settingsAbout:[qh]},Qh=new Set(["chat","picker",...Object.keys(Gl).filter(e=>e.startsWith("settings")&&e!=="settings")]),em=new Set(["inspector","settingsDictation","settingsProviders","settingsProviderNew","settingsProviderEdit","settingsProject","settingsProjectTechnical","settingsProjectOutput","settingsProjectPreview","settingsProjectHide","settingsDefaults","settingsNotifications","settingsAbout","settingsPrompts","settingsAgents","settingsAgentEdit","settingsActions","settingsActionEdit","settingsMcp","settingsMcpEdit","settingsMcpRegistry","settingsTags","settingsPricing","settingsProjects"]);function tm(e){const[t=Na,n]=Gl[e.name]||[],r=e.name+"|"+(e.projectDir||"")+"|"+(e.id||"")+"|"+(e.scope||"")+"|"+(e.page||"")+"|"+(e.chatId||"")+"|"+(e.isNew?"new":""),o=u(t,{key:r,...n?n(e):null});return em.has(e.name)?u(pr,{fallback:u("p",{class:"muted",role:"status"},"Loading…")},o):o}const nm={chats:u("svg",{viewBox:"0 0 24 24",width:22,height:22,"aria-hidden":"true"},u("path",{d:"M2 5a3 3 0 0 1 3-3h14a3 3 0 0 1 3 3v10a3 3 0 0 1-3 3H9.5l-3.72 3.72A1 1 0 0 1 4 22.56V18H5a3 3 0 0 1-3-3V5Z",fill:"currentColor"})),inspector:u("svg",{viewBox:"0 0 24 24",width:22,height:22,"aria-hidden":"true"},u("path",{d:"M4 4h16a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1Zm0 3v2h16V7H4Zm0 4v2h7v-2H4Zm0 4v2h7v-2H4Zm9 0v2h7v-2h-7Z",fill:"currentColor"})),settings:u("svg",{viewBox:"0 0 24 24",width:22,height:22,"aria-hidden":"true"},u("path",{d:"M19.14 12.94a7.07 7.07 0 0 0 0-1.88l2.03-1.58a.5.5 0 0 0 .12-.64l-1.92-3.32a.5.5 0 0 0-.6-.22l-2.39.96a7.03 7.03 0 0 0-1.63-.94l-.36-2.54A.5.5 0 0 0 13.9 2h-3.84a.5.5 0 0 0-.5.42l-.36 2.54a7.03 7.03 0 0 0-1.63.94l-2.39-.96a.5.5 0 0 0-.6.22L2.66 8.48a.5.5 0 0 0 .12.64l2.03 1.58a7.07 7.07 0 0 0 0 1.88L2.78 14.16a.5.5 0 0 0-.12.64l1.92 3.32a.5.5 0 0 0 .6.22l2.39-.96c.5.39 1.05.71 1.63.94l.36 2.54a.5.5 0 0 0 .5.42h3.84a.5.5 0 0 0 .5-.42l.36-2.54c.58-.23 1.13-.55 1.63-.94l2.39.96a.5.5 0 0 0 .6-.22l1.92-3.32a.5.5 0 0 0-.12-.64l-2.04-1.58ZM12 15.5A3.5 3.5 0 1 1 12 8.5a3.5 3.5 0 0 1 0 7Z",fill:"currentColor"}))};function rm(){const e=qr.value,t=[{to:"projects",name:"chats",label:"Chats"},{to:"inspector",name:"inspector",label:"Inspector"},{to:"settings",name:"settings",label:"Settings"}];return u("nav",{class:"app__tabbar","aria-label":"Primary"},u("ul",{class:"app__tablist",style:{"--tab-count":t.length}},t.map(n=>u("li",{class:"app__tabitem"},u("a",{href:"#/"+n.to,class:"app__tab"+(e.name===n.name?" is-active":""),"aria-current":e.name===n.name?"page":null},u("span",{class:"app__tab-icon"},nm[n.name]),u("span",{class:"app__tab-label"},n.label))))))}const om=u("svg",{viewBox:"-0.05 0.04 1.16 1.04",width:11,height:11,fill:"none",stroke:"currentColor","stroke-width":"0.17","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},u("path",{d:"M0.16 0.98 L0.16 0.14 L0.50 0.62 L0.84 0.14 L0.84 0.98"}));function im(){return u("header",{class:"app__header"},u("div",{class:"app__brand"},u("span",{class:"app__logo","aria-hidden":"true"},om),u("h1",{class:"app__title"},"mouaif")))}function sm(){const e=qr.value;ue(()=>{try{const o=sessionStorage.getItem("oauthPending");if(!o)return;sessionStorage.removeItem("oauthPending");const i=JSON.parse(o);i&&i.provider&&Date.now()-(i.started||0)<10*60*1e3&&(e.name==="chats"||e.name==="settings"||e.name==="settingsProviders")&&yt("settings/providers/"+encodeURIComponent(i.provider))}catch{}},[]);const t=e.name==="chat"&&e.projectDir||"";ue(()=>{t&&t!==rn.value.dir&&Yc(t)},[t]);const n=!Qh.has(e.name),r=tm(e);return u("div",{class:"app__shell"},u(im,null),u(cu,null),u("main",{class:"app__main"+(n?"":" app__main--flush")+(e.name==="chat"?" app__main--chat":"")},r),n?u(rm,null):null)}const am="mouaif-push-click",hn="clicks",Do="latest",lm=60*1e3,cm=250,um=5e3;function Kl(){return new Promise((e,t)=>{if(typeof indexedDB>"u")return t(new Error("IndexedDB unavailable"));const n=indexedDB.open(am,1);n.onupgradeneeded=()=>{const r=n.result;r.objectStoreNames.contains(hn)||r.createObjectStore(hn)},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error||new Error("IndexedDB open failed"))})}async function dm(){try{const e=await Kl();await new Promise(t=>{const n=e.transaction(hn,"readwrite");n.objectStore(hn).delete(Do),n.oncomplete=t,n.onerror=t,n.onabort=t}),e.close()}catch{}}async function pm(){try{const e=await Kl(),t=await new Promise(n=>{const o=e.transaction(hn,"readwrite").objectStore(hn),i=o.get(Do);i.onsuccess=()=>{const s=i.result;s&&o.delete(Do),n(s||null)},i.onerror=()=>n(null)});return e.close(),t&&t.url&&Date.now()-(t.at||0)<lm?t.url:null}catch{return null}}function Zl(e){if(!e||typeof window>"u")return;let t;try{t=new URL(e,window.location.origin)}catch{return}if(t.origin!==window.location.origin||t.pathname!=="/")return;const n=t.hash||"#/projects";window.location.hash===n?window.dispatchEvent(new HashChangeEvent("hashchange")):window.location.hash=n,window.focus()}function fm(){if(typeof document>"u")return;const e=window.location.hash,t=()=>document.visibilityState!=="visible"?Promise.resolve(!1):pm().then(l=>l?(Zl(l),!0):!1),n=()=>{t()};n(),document.addEventListener("visibilitychange",n),window.addEventListener("pageshow",n);let r=null;window.addEventListener("focus",()=>{clearTimeout(r),r=setTimeout(n,0)});let o=null;const i=()=>{o!=null&&(clearInterval(o),o=null)};o=setInterval(()=>{if(document.visibilityState==="visible"){if(window.location.hash!==e){i();return}t().then(l=>{l&&i()})}},cm),setTimeout(i,um)}let Zs=!1;function hm(){return{type:"VISIBILITY_STATE",hash:window.location.hash||"",visible:document.visibilityState==="visible",focused:typeof document.hasFocus=="function"?document.hasFocus():!1}}function mm(e,t){const n=hm();if(e.ports&&e.ports[0])try{e.ports[0].postMessage(n)}catch{}if(t.queryId)try{const r=e.source&&typeof e.source.postMessage=="function"?e.source:navigator.serviceWorker.controller;r&&r.postMessage({type:"VISIBILITY_STATE_RESPONSE",queryId:t.queryId,state:n})}catch{}}function gm(){Zs||typeof navigator>"u"||!("serviceWorker"in navigator)||(Zs=!0,navigator.serviceWorker.addEventListener("message",e=>{const t=e.data||{};if(t.type==="GET_VISIBILITY_STATE"){mm(e,t);return}t.type==="NAVIGATE"&&t.url&&(Zl(t.url),dm())}))}function _m(){typeof document>"u"||document.addEventListener("visibilitychange",()=>{if(document.visibilityState!=="visible")return;const e=window.location.hash||"";e.startsWith("#/chat")||e.startsWith("#/settings")||window.dispatchEvent(new HashChangeEvent("hashchange"))})}const ym={},vm=!!ym&&!0,ui=Tt(vm&&typeof window<"u"&&"Notification"in window&&"PushManager"in window&&!!navigator.serviceWorker),Bo=Tt(typeof window<"u"&&"Notification"in window?Notification.permission:"denied"),ct=Tt(!1);let Fn=null,mt=null;function jr(e,t,n){return new Promise(r=>{let o=!1;const i=setTimeout(()=>{o||(o=!0,console.warn("[mouaif-push] "+n+" timed out after "+t+"ms"),r(null))},t);Promise.resolve(e).then(s=>{o||(o=!0,clearTimeout(i),r(s))},()=>{o||(o=!0,clearTimeout(i),r(null))})})}const bm=3e4,di=1e4,wm=32;function Cm(){if(typeof navigator>"u")return{os:"",osVersion:0};const e=String(navigator.userAgent||""),t=Number(navigator.maxTouchPoints)||0;if(/iPhone|iPod/.test(e)){const r=e.match(/OS (\d+)[._]/);return{os:"ios",osVersion:r?Number(r[1]):0}}if(/iPad/.test(e)){const r=e.match(/OS (\d+)[._]/);return{os:"ios",osVersion:r?Number(r[1]):0}}if(/Macintosh/.test(e)&&t>1)return{os:"ipados",osVersion:0};let n=e.match(/Android (\d+)/);return n?{os:"android",osVersion:Number(n[1])}:(n=e.match(/Mac OS X (\d+)[._]/),n?{os:"macos",osVersion:Number(n[1])}:(n=e.match(/Windows NT (\d+)/),n?{os:"windows",osVersion:Number(n[1])}:(n=e.match(/CrOS \S+ (\d+)/),n?{os:"chromeos",osVersion:Number(n[1])}:/Linux/.test(e)?{os:"linux",osVersion:0}:{os:"",osVersion:0})))}function km(){try{if(typeof matchMedia=="function"&&matchMedia("(display-mode: fullscreen)").matches)return"expanded"}catch{}return"collapsed"}function Sm(){const e={chars:wm,viewportWidth:0,os:"",osVersion:0,style:km()};try{if(typeof window<"u"&&(e.viewportWidth=Math.round(window.visualViewport&&window.visualViewport.width||window.innerWidth||0)),typeof document<"u"&&document.body){const n=document.createElement("span");n.textContent="0".repeat(200),n.setAttribute("aria-hidden","true"),n.style.cssText="position:absolute;left:-9999px;top:0;visibility:hidden;white-space:nowrap;font:12px/1.35 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;",document.body.appendChild(n);const r=n.getBoundingClientRect().width/200;n.remove();const o=e.viewportWidth;if(r>0&&Number.isFinite(r)&&o>0){const i=Math.floor(o*.92/r);i>0&&(e.chars=i)}}const t=typeof navigator<"u"?navigator.userAgentData:null;if(t&&typeof t.platform=="string"&&t.platform){e.os=t.platform;const n=t.platformVersion?Number(String(t.platformVersion).split(".")[0]):0;e.osVersion=Number.isFinite(n)?n:0}else{const n=Cm();e.os=n.os,e.osVersion=n.osVersion}}catch{}return e}async function Yl(e){const t=e&&e.toJSON?e.toJSON():null;if(!t||!t.endpoint||!t.keys||!t.keys.p256dh||!t.keys.auth)return!1;const n=Sm();return(await H("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({subscription:{endpoint:t.endpoint,keys:t.keys,statusBarMaxChars:n.chars,statusBarProfile:n}})})).status===200}async function Xl(){if(!ui.value||typeof navigator>"u"||!navigator.serviceWorker)return!1;try{Bo.value=Notification.permission;const e=await jr(navigator.serviceWorker.ready,di,"serviceWorker.ready (sync)");if(!e)return!1;Fn=e;const t=await e.pushManager.getSubscription();if(mt=t,ct.value=!!t,t){const n=await H("/api/push/subscriptions"),r=n.status===200&&n.body&&Array.isArray(n.body.subscriptions)?n.body.subscriptions:[];ct.value=r.some(o=>o&&o.endpoint===t.endpoint),ct.value||(ct.value=await Yl(t))}return ct.value}catch{return ct.value=!1,!1}}async function Vm(){if(!ui.value)return!1;try{if(await jr(Notification.requestPermission(),bm,"Notification.requestPermission")!=="granted")return Bo.value=Notification.permission,!1;if(Bo.value="granted",ct.value&&await Xl())return!0;const t=await H("/api/push/vapid-public-key");if(t.status!==200)return!1;const n=t.body.publicKey,r=Tm(n),o=await jr(navigator.serviceWorker.ready,di,"serviceWorker.ready (subscribe)");if(!o)return!1;Fn=o;const i=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:r});if(mt=i,!await Yl(i)){try{await i.unsubscribe()}catch{}return mt=null,ct.value=!1,!1}return ct.value=!0,!0}catch{return ct.value=!1,!1}}async function Hm(){if(ui.value)try{if(!mt&&Fn&&(mt=await Fn.pushManager.getSubscription()),!mt&&typeof navigator<"u"&&navigator.serviceWorker){const t=await jr(navigator.serviceWorker.ready,di,"serviceWorker.ready (unsubscribe)");if(!t){ct.value=!1;return}Fn=t,mt=await t.pushManager.getSubscription()}if(!mt){ct.value=!1;return}const e=mt.endpoint;try{await mt.unsubscribe()}catch{}mt=null,ct.value=!1,await H("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoint:e})})}catch{ct.value=!1}}function Tm(e){const t="=".repeat((4-e.length%4)%4),n=(e+t).replace(/\-/g,"+").replace(/_/g,"/"),r=window.atob(n),o=new Uint8Array(r.length);for(let i=0;i<r.length;++i)o[i]=r.charCodeAt(i);return o}const Ys=document.getElementById("app");Ys&&qn(u(gu,null,u(sm,null)),Ys);au();gm();_m();fm();iu();"serviceWorker"in navigator&&navigator.serviceWorker.ready.then(()=>Xl()).catch(()=>{});export{Pc as $,x as A,Cf as B,ui as C,th as D,Bo as E,ct as F,Xl as G,Hm as H,Vm as I,xm as J,Xi as K,Rm as L,ol as M,el as N,Jc as O,Kf as P,Mm as Q,il as R,qt as S,_t as T,id as U,qn as V,Hf as W,ah as X,gh as Y,vh as Z,Li as _,ih as a,Vn as a0,Bt as a1,La as a2,We as a3,Dm as a4,jm as a5,Um as a6,Eh as a7,qm as a8,uh as a9,dh as aa,Om as ab,bh as ac,kh as ad,Fm as ae,lh as af,zs as ag,$s as ah,Ws as ai,Ih as aj,Oa as ak,Bm as al,Lm as am,rn as b,Go as c,E as d,Gc as e,H as f,Em as g,ue as h,Wc as i,Pm as j,u as k,Ca as l,Vr as m,yt as n,tl as o,Im as p,Qa as q,Yc as r,Am as s,Nm as t,Vl as u,Sa as v,rl as w,Mn as x,bo as y,vf as z};
|