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
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/FileEditor-DDl31c6d.js","assets/codemirror-Bp6CUUFk.js","assets/index-Crn1LdzK.css","assets/Inspector-Ba3R1w04.js","assets/virtual-list-6H9b4K51.js","assets/index-C1sQFIC-.css","assets/SettingsProject-DNrKhCcZ.js","assets/AgentFilePicker-CcKLJorU.js","assets/agentNavigation-BiiCpFz5.js","assets/SettingsHiddenContent-BZ2sloH1.js","assets/index-FbCWDPiB.css","assets/SettingsAgents-BNV0MgDB.js","assets/index-Bgg1gnDf.css","assets/SettingsMcp-DOrfbQd1.js","assets/projectQS-D1cSZ7Gr.js","assets/SettingsMcpEdit-BGMQ2CWC.js","assets/SettingsMcpRegistry-BywXee_A.js","assets/SettingsTags-B5kjFdQi.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 qr,me,ta,na,Dt,ki,ra,oa,to,ur,Pn,ia,Fo,yo,vo,Cr={},kr=[],gl=/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 Uo(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function l(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?qr.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 dr(e,s,r,o,null)}function dr(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??++ta,__i:-1,__u:0};return o==null&&me.vnode!=null&&me.vnode(i),i}function Ft(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 _l(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),Vo(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,ua(r,i,o),t.__e=t.__=null,i.__e!=n&&sa(i)}}function sa(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}),sa(e)}function Si(e){(!e.__d&&(e.__d=!0)&&Dt.push(e)&&!Sr.__r++||ki!=me.debounceRendering)&&((ki=me.debounceRendering)||ra)(Sr)}function Sr(){try{for(var e,t=1;Dt.length;)Dt.length>t&&Dt.sort(oa),e=Dt.shift(),t=Dt.length,_l(e)}finally{Dt.length=Sr.__r=0}}function aa(e,t,n,r,o,i,s,c,u,a,d){var p,f,h,g,v,w,k,_=r&&r.__k||kr,y=t.length;for(u=yl(n,t,_,u,y),p=0;p<y;p++)(h=n.__k[p])!=null&&(f=h.__i!=-1&&_[h.__i]||Cr,h.__i=p,w=Vo(e,h,f,o,i,s,c,u,a,d),g=h.__e,h.ref&&f.ref!=h.ref&&(f.ref&&Ho(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?(u=ca(h,u,e,k),k&&f.__e&&(f.__e=null)):typeof h.type=="function"&&w!==void 0?u=w:g&&(u=g.nextSibling),h.__u&=-7);return n.__e=v,u}function yl(e,t,n,r,o){var i,s,c,u,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]=dr(null,s,null,null,null):Gn(s)?s=e.__k[i]=dr(Ft,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[i]=dr(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[i]=s,u=i+f,s.__=e,s.__b=e.__b+1,c=null,(a=s.__i=vl(s,n,u,p))!=-1&&(p--,(c=n[a])&&(c.__u|=2)),c==null||c.__v==null?(a==-1&&(o>d?f--:o<d&&f++),typeof s.type!="function"&&(s.__u|=4)):a!=u&&(a==u-1?f--:a==u+1?f++:(a>u?f--:f++,s.__u|=4))):e.__k[i]=null;if(p)for(i=0;i<d;i++)(c=n[i])!=null&&!(2&c.__u)&&(c.__e==r&&(r=un(c)),pa(c,c));return r}function ca(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=ca(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 Tr(e,t){return t=t||[],e==null||typeof e=="boolean"||(Gn(e)?e.some(function(n){Tr(n,t)}):t.push(e)),t}function vl(e,t,n,r){var o,i,s,c=e.key,u=e.type,a=t[n],d=a!=null&&(2&a.__u)==0;if(a===null&&c==null||d&&c==a.key&&u==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)&&c==a.key&&u==a.type)return s}return-1}function Ti(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||gl.test(t)?n:n+"px"}function nr(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||Ti(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Ti(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(ia,"$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?vo:yo,i)):e.removeEventListener(t,i?vo:yo,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 Ai(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[ur]==null)t[ur]=Fo++;else if(t[ur]<n[Pn])return;return n(me.event?me.event(t):t)}}}function Vo(e,t,n,r,o,i,s,c,u,a){var d,p,f,h,g,v,w,k,_,y,b,D,j,x,X,ne,$=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(u=!!(32&n.__u),i=[c=t.__e=n.__e]),(d=me.__b)&&d(t);e:if(typeof $=="function"){p=s.length;try{if(_=t.props,y=$.prototype&&$.prototype.render,b=(d=$.contextType)&&r[d.__c],D=d?b?b.props.value:d.__:r,n.__c?k=(f=t.__c=n.__c).__=f.__E:(y?t.__c=f=new $(_,D):(t.__c=f=new wt(_,D),f.constructor=$,f.render=wl),b&&b.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&&$.getDerivedStateFromProps!=null&&(f.__s==f.state&&(f.__s=It({},f.__s)),It(f.__s,$.getDerivedStateFromProps(_,f.__s))),g=f.props,v=f.state,f.__v=t,h)y&&$.getDerivedStateFromProps==null&&f.componentWillMount!=null&&f.componentWillMount(),y&&f.componentDidMount!=null&&f.__h.push(f.componentDidMount);else{if(y&&$.getDerivedStateFromProps==null&&_!==g&&f.componentWillReceiveProps!=null&&f.componentWillReceiveProps(_,D),t.__v==n.__v||!f.__e&&f.shouldComponentUpdate!=null&&f.shouldComponentUpdate(_,f.__s,D)===!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)}),kr.push.apply(f.__h,f._sb),f._sb=[],f.__h.length&&s.push(f);break e}f.componentWillUpdate!=null&&f.componentWillUpdate(_,f.__s,D),y&&f.componentDidUpdate!=null&&f.__h.push(function(){f.componentDidUpdate(g,v,w)})}if(f.context=D,f.props=_,f.__P=e,f.__e=!1,j=me.__r,x=0,y)f.state=f.__s,f.__d=!1,j&&j(t),d=f.render(f.props,f.state,f.context),kr.push.apply(f.__h,f._sb),f._sb=[];else do f.__d=!1,j&&j(t),d=f.render(f.props,f.state,f.context),f.state=f.__s;while(f.__d&&++x<25);f.state=f.__s,f.getChildContext!=null&&(r=It(It({},r),f.getChildContext())),y&&!h&&f.getSnapshotBeforeUpdate!=null&&(w=f.getSnapshotBeforeUpdate(g,v)),X=d!=null&&d.type===Ft&&d.key==null?da(d.props.children):d,c=aa(e,Gn(X)?X:[X],t,n,r,o,i,s,c,u,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,u||i!=null){if(I.then){for(t.__u|=u?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;i!=null&&(i[i.indexOf(c)]=null),t.__e=c}else if(i!=null)for(ne=i.length;ne--;)Uo(i[ne])}else t.__e=n.__e;t.__k==null&&(t.__k=n.__k||[]),I.then||la(t),me.__e(I,t,n)}}else i==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=bl(n.__e,t,n,r,o,i,s,u,a);return(d=me.diffed)&&d(t),128&t.__u?void 0:c}function la(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(la))}function ua(e,t,n){for(var r=0;r<n.length;r++)Ho(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 da(e){return typeof e!="object"||e==null||e.__b>0?e:Gn(e)?e.map(da):e.constructor!==void 0?null:It({},e)}function bl(e,t,n,r,o,i,s,c,u){var a,d,p,f,h,g,v,w=n.props||Cr,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),c&&(me.__m&&me.__m(t,i),c=!1),i=null}if(_==null)w===k||c&&e.data==k||(e.data=k);else{if(i=_=="textarea"&&k.defaultValue!=null?null:i&&qr.call(e.childNodes),!c&&i!=null)for(w={},a=0;a<e.attributes.length;a++)w[(h=e.attributes[a]).name]=h.value;for(a in w)h=w[a],a=="dangerouslySetInnerHTML"?p=h:a=="children"||a in k||a=="value"&&"defaultValue"in k||a=="checked"&&"defaultChecked"in k||nr(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:c&&typeof h!="function"||w[a]===h||nr(e,a,h,w[a],o);if(d)c||p&&(d.__html==p.__html||d.__html==e.innerHTML)||(e.innerHTML=d.__html),t.__k=[];else if(p&&(e.innerHTML=""),aa(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),c,u),i!=null)for(a=i.length;a--;)Uo(i[a]);c&&_!="textarea"||(a="value",_=="progress"&&g==null?e.removeAttribute("value"):g!=null&&(g!==e[a]||_=="progress"&&!g||_=="option"&&g!=w[a])&&nr(e,a,g,w[a],o),a="checked",v!=null&&v!=e[a]&&nr(e,a,v,w[a],o))}return e}function Ho(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 pa(e,t,n){var r,o;if(me.unmount&&me.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||Ho(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]&&pa(r[o],t,n||typeof e.type!="function");n||Uo(e.__e),e.__c=e.__=e.__e=void 0}function wl(e,t,n){return this.constructor(e,n)}function Fn(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=[],Vo(t,e=t.__k=l(Ft,null,[e]),o||Cr,Cr,t.namespaceURI,o?null:t.firstChild?qr.call(t.childNodes):null,i,o?o.__e:t.firstChild,r,s),ua(i,e,s),e.props.children=null}qr=kr.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(c){e=c}throw e}},ta=0,na=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),Si(this))},wt.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Si(this))},wt.prototype.render=Ft,Dt=[],ra=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,oa=function(e,t){return e.__v.__b-t.__v.__b},Sr.__r=0,to=Math.random().toString(8),ur="__d"+to,Pn="__a"+to,ia=/(PointerCapture)$|Capture$/i,Fo=0,yo=Ai(!1),vo=Ai(!0);const Cl="modulepreload",kl=function(e){return"/"+e},xi={},Be=function(t,n,r){let o=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),c=s?.nonce||s?.getAttribute("nonce");o=Promise.allSettled(n.map(u=>{if(u=kl(u),u in xi)return;xi[u]=!0;const a=u.endsWith(".css"),d=a?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const p=document.createElement("link");if(p.rel=a?"stylesheet":Cl,a||(p.as="script"),p.crossOrigin="",p.href=u,c&&p.setAttribute("nonce",c),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 ${u}`)))})}))}function i(s){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=s,window.dispatchEvent(c),!c.defaultPrevented)throw s}return o.then(s=>{for(const c of s||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})};var dn,He,no,Ei,Un=0,fa=[],ze=me,Ii=ze.__b,Pi=ze.__r,Ri=ze.diffed,Ni=ze.__c,Li=ze.unmount,Mi=ze.__;function Fr(e,t){ze.__h&&ze.__h(He,e,Un||t),Un=0;var n=He.__H||(He.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function A(e){return Un=1,Sl(ha,e)}function Sl(e,t,n){var r=Fr(dn++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):ha(void 0,t),function(c){var u=r.__N?r.__N[0]:r.__[0],a=r.t(u,c);u!==a&&(r.__N=[a,r.__[1]],r.__c.setState({}))}],r.__c=He,!He.__f)){var o=function(c,u,a){if(!r.__c.__H)return!0;var d=!1,p=r.__c.props!==c;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,c,u,a);return d?f||p:f}return!d||p};He.__f=!0;var i=He.shouldComponentUpdate,s=He.componentWillUpdate;He.componentWillUpdate=function(c,u,a){if(this.__e){var d=i;i=void 0,o(c,u,a),i=d}s&&s.call(this,c,u,a)},He.shouldComponentUpdate=o}return r.__N||r.__}function ue(e,t){var n=Fr(dn++,3);!ze.__s&&Wo(n.__H,t)&&(n.__=e,n.u=t,He.__H.__h.push(n))}function Oi(e,t){var n=Fr(dn++,4);!ze.__s&&Wo(n.__H,t)&&(n.__=e,n.u=t,He.__h.push(n))}function P(e){return Un=5,_t(function(){return{current:e}},[])}function _t(e,t){var n=Fr(dn++,7);return Wo(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 Tl(){for(var e;e=fa.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(pr),t.__h.some(bo),t.__h=[]}catch(n){t.__h=[],ze.__e(n,e.__v)}}}ze.__b=function(e){He=null,Ii&&Ii(e)},ze.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Mi&&Mi(e,t)},ze.__r=function(e){Pi&&Pi(e),dn=0;var t=(He=e.__c).__H;t&&(no===He?(t.__h=[],He.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(pr),t.__h.some(bo),t.__h=[],dn=0)),no=He},ze.diffed=function(e){Ri&&Ri(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(fa.push(t)!==1&&Ei===ze.requestAnimationFrame||((Ei=ze.requestAnimationFrame)||Al)(Tl)),t.__H.__.some(function(n){n.u&&(n.__H=n.u,n.u=void 0)})),no=He=null},ze.__c=function(e,t){t.some(function(n){try{n.__h.some(pr),n.__h=n.__h.filter(function(r){return!r.__||bo(r)})}catch(r){t.some(function(o){o.__h&&(o.__h=[])}),t=[],ze.__e(r,n.__v)}}),Ni&&Ni(e,t)},ze.unmount=function(e){Li&&Li(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{pr(r)}catch(o){t=o}}),n.__H=void 0,t&&ze.__e(t,n.__v))};var ji=typeof requestAnimationFrame=="function";function Al(e){var t,n=function(){clearTimeout(r),ji&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);ji&&(t=requestAnimationFrame(n))}function pr(e){var t=He,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),He=t}function bo(e){var t=He;e.__c=e.__(),He=t}function Wo(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function ha(e,t){return typeof t=="function"?t(e):t}function xl(e,t){for(var n in t)e[n]=t[n];return e}function Di(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 Bi(e,t){this.props=e,this.context=t}(Bi.prototype=new wt).isPureReactComponent=!0,Bi.prototype.shouldComponentUpdate=function(e,t){return Di(this.props,e)||Di(this.state,t)};var qi=me.__b;me.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),qi&&qi(e)};var El=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)}El(e,t,n,r)};var Fi=me.unmount;function ma(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=xl({},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 ma(r,t,n)})),e}function ga(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return ga(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 fr(){this.__u=0,this.o=null,this.__b=null}function _a(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function ya(e){var t,n,r,o=null;function i(s){if(t||(t=e()).then(function(c){c&&(o=c.default||c),r=!0},function(c){n=c,r=!0}),n)throw n;if(!r)throw t;return o?l(o,s):null}return i.displayName="Lazy",i.__f=!0,i}function rr(){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),Fi&&Fi(e)},(fr.prototype=new wt).__c=function(e,t){var n=t.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var o=_a(r.__v),i=!1,s=function(){i||r.__z||(i=!0,n.__R=null,o?o(u):u())};n.__R=s;var c=n.__P;n.__P=null;var u=function(){if(!--r.__u){if(r.state.__a){var a=r.state.__a;r.__v.__k[0]=ga(a,a.__c.__P,a.__c.__O)}var d;for(r.setState({__a:r.__b=null});d=r.o.pop();)d.__P=c,d.forceUpdate()}};r.__u++||32&t.__u||r.setState({__a:r.__b=r.__v.__k[0]}),e.then(s,s)},fr.prototype.componentWillUnmount=function(){this.o=[]},fr.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]=ma(this.__b,n,r.__O=r.__P)}this.__b=null}var o=t.__a&&l(Ft,null,e.fallback);return o&&(o.__u&=-33),[l(Ft,null,t.__a?null:e.children),o]};var Ui=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 Il(e){return this.getChildContext=function(){return e.context},e.children}function Pl(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Fn(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)}}}Fn(l(Il,{context:t.context},e.__v),t.v)}function Rl(e,t){var n=l(Pl,{__v:e,h:t});return n.containerInfo=t,n}(rr.prototype=new wt).__a=function(e){var t=this,n=_a(t.__v),r=t.l.get(e);return r[0]++,function(o){var i=function(){t.props.revealOrder?(r.push(o),Ui(t,e,r)):o()};n?n(i):i()}},rr.prototype.render=function(e){this.i=null,this.l=new Map;var t=Tr(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},rr.prototype.componentDidUpdate=rr.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){Ui(e,n,t)})};var Nl=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Ll=/^(?: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]/,Ml=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Ol=/[A-Z0-9]/g,jl=typeof document<"u",Dl=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 Vi=me.event;me.event=function(e){return Vi&&(e=Vi(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var Bl={configurable:!0,get:function(){return this.class}},Hi=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 c=n[s];if(!(s==="value"&&"defaultValue"in n&&c==null||jl&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var u=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&c===!0?c="":u==="translate"&&c==="no"?c=!1:u[0]==="o"&&u[1]==="n"?u==="ondoubleclick"?s="ondblclick":u!=="onchange"||r!=="input"&&r!=="textarea"||Dl(n.type)?u==="onfocus"?s="onfocusin":u==="onblur"?s="onfocusout":Ml.test(s)&&(s=u):u=s="oninput":i&&Ll.test(s)?s=s.replace(Ol,"-$&").toLowerCase():c===null&&(c=void 0),u==="oninput"&&o[s=u]&&(s="oninputCapture"),o[s]=c}}r=="select"&&(o.multiple&&Array.isArray(o.value)&&(o.value=Tr(n.children).forEach(function(a){a.props.selected=o.value.indexOf(a.props.value)!=-1})),o.defaultValue!=null&&(o.value=Tr(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",Bl)):n.className&&(o.class=o.className=n.className),t.props=o}(e),e.$$typeof=Nl,Hi&&Hi(e)};var Wi=me.__r;me.__r=function(e){Wi&&Wi(e),e.__c};var zi=me.diffed;me.diffed=function(e){zi&&zi(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 ql=Symbol.for("preact-signals");function zo(){if(Jt>1)Jt--;else{var e,t=!1;for(function(){var o=xr;for(xr=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}}();Nn!==void 0;){var n=Nn;for(Nn=void 0,Ar++;n!==void 0;){var r=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&ba(n))try{n.c()}catch(o){t||(e=o,t=!0)}n=r}}if(Ar=0,Jt--,t)throw e}}var Rn,Me=void 0;function Ur(e){var t=Me,n=Rn;Me=void 0,Rn=void 0;try{return e()}finally{Me=t,Rn=n}}var Nn=void 0,Jt=0,Ar=0,$i=0,xr=void 0,Er=0;function va(e){if(Me!==void 0){var t=e.n;if(t===void 0||t.t!==Me)return t={i:0,S:e,p:Me.s,n:void 0,t:Me,e:void 0,x:void 0,r:t},Me.s!==void 0&&(Me.s.n=t),Me.s=t,e.n=t,32&Me.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=Me.s,t.n=void 0,Me.s.n=t,Me.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=ql;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:Ur(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&&Ur(function(){var o;(o=t.Z)==null||o.call(t)}))}};Xe.prototype.subscribe=function(e){var t=this;return Jo(function(){var n=t.value;Ur(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 Ur(function(){return e.value})};Object.defineProperty(Xe.prototype,"value",{get:function(){var e=va(this);return e!==void 0&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(Ar>100)throw new Error("Cycle detected");(function(n){Jt!==0&&Ar===0&&n.l!==$i&&(n.l=$i,xr={S:n,v:n.v,i:n.i,o:xr})})(this),this.v=e,this.i++,Er++,Jt++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{zo()}}}});function Tt(e,t){return new Xe(e,t)}function ba(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 wa(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 Ca(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=Er-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===Er))return!0;if(this.g=Er,this.f|=1,this.i>0&&!ba(this))return this.f&=-2,!0;var e=Me;try{wa(this),Me=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 Me=e,Ca(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=va(this);if(this.h(),e!==void 0&&(e.i=this.i),16&this.f)throw this.v;return this.v}});function Fl(e,t){return new Yt(e,t)}function ka(e){var t=e.m;if(e.m=void 0,typeof t=="function"){Jt++;var n=Me;Me=void 0;try{t()}catch(r){throw e.f&=-2,e.f|=8,$o(e),r}finally{Me=n,zo()}}}function $o(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,ka(e)}function Ul(e){if(Me!==this)throw new Error("Out-of-order effect");Ca(this),Me=e,this.f&=-2,8&this.f&&$o(this),zo()}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,Rn&&Rn.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,ka(this),wa(this),Jt++;var e=Me;return Me=this,Ul.bind(this,e)};mn.prototype.N=function(){2&this.f||(this.f|=2,this.u=Nn,Nn=this)};mn.prototype.d=function(){this.f|=8,1&this.f||$o(this)};mn.prototype.dispose=function(){this.d()};function Jo(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 or;function gn(e,t){me[e]=t.bind(null,me[e]||function(){})}function Ir(e){if(or){var t=or;or=void 0,t()}or=e&&e.S()}function Sa(e){var t=this,n=e.data,r=Hl(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,c=t.__$u.S(),u=o.value;c(),na(u)||((s=t.base)==null?void 0:s.nodeType)!==3?(t.__$f|=1,t.setState({})):t.base.data=u},Fl(function(){var s=r.value.value;return s===0?0:s===!0?"":s||""})},[]);return o.value}Sa.displayName="_st";Object.defineProperties(Xe.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Sa},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),Ir();var n,r=t.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=function(o){var i;return Jo(function(){i=this}),i.c=function(){r.__$f|=1,r.setState({})},i}())),Ir(n)});gn("__e",function(e,t,n,r){Ir(),e(t,n,r)});gn("diffed",function(e,t){Ir();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 c=i[s];c!==void 0&&!(s in r)&&(c.d(),i[s]=void 0)}else n.U=i={};for(var u in r){var a=i[u],d=r[u];a===void 0?(a=Vl(n,u,d,o),i[u]=a):a.o(d,o)}}}e(t)});function Vl(e,t,n,r){var o=t in e&&e.ownerSVGElement===void 0,i=Tt(n);return{o:function(s,c){i.value=s,r=c},d:Jo(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 c=s.__$u;c&&(s.__$u=void 0,c.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 Hl(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,Ji=0;const Wl=4e3;async function Go({force:e=!1}={}){const t=Date.now();if(!e&&tt&&t-Ji<Wl)return tt;const n=await H("/api/settings");if(n.status!==200)throw new Error("HTTP "+n.status);return tt=n.body||{},Ji=t,tt}function zl(){return tt&&Array.isArray(tt.app&&tt.app.providers)?tt.app.providers:[]}async function $l(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 Em(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 ir=null,Gi=0;const Jl=5e3;async function Im({force:e=!1}={}){const t=Date.now();if(!e&&ir&&t-Gi<Jl)return ir;const n=await H("/api/auth/accounts");if(n.status!==200)throw new Error("HTTP "+n.status);return ir=n.body&&n.body.accounts||{},Gi=t,ir}async function Gl(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 Kl(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 Zl=[{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 Pm(e){return Zl.find(t=>t.id===e)||null}function Rm(e){return e==="openai-compatible"?"openai":e}async function Yl(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 Xl(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 wo({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 c=new Error(s.body.error||"Authorization required");throw c.code="EAUTH_REQUIRED",c.callId=s.body.callId||"",c}if(s.status!==200){const c=new Error(s.body&&s.body.error||"HTTP "+s.status);throw c.code=s.body&&s.body.code||"EHTTP",c}return s.body}function ro(e,t,n){!e||!e.current||(e.current.textContent=t||"",n?e.current.dataset.state=n:delete e.current.dataset.state)}function Ta(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 Aa=Tt(0),Kn=Tt({name:"chats"}),rn=Tt({dir:"",name:""});function Ql(e,t){rn.value={dir:e||"",name:""}}const eu=["projects","settings/projects"];function et(e){const t=e.get("from")||"";return eu.includes(t)?t:""}function xa(e){const t=e.indexOf("?");return new URLSearchParams(t>=0?e.slice(t+1):"")}function sr(e){try{return decodeURIComponent(e)}catch{return e}}function nt(e,t){return{match:n=>n===e?{params:new URLSearchParams}:null,build:t}}function ct(e,t){return{match:n=>n===e||n.startsWith(e+"?")?{params:xa(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:xa(n)}},build:t}}const Ea=[nt("projects",()=>({name:"chats"})),nt("auth",()=>({name:"settings"})),nt("settings/copilot",()=>({name:"settingsProviderEdit",id:"github-copilot"})),Ot("settings/project/agents/",e=>({name:"settingsAgentEdit",id:sr(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"})),ct("disable-access",e=>({name:"disableAccess",code:e.params.get("code")||""})),ct("setup",e=>({name:"setup",code:e.params.get("code")||""})),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:sr(e.id)}:null),ct("settings/project/technical",e=>({name:"settingsProjectTechnical",projectDir:e.params.get("projectDir")||"",chatId:e.params.get("chatId")||"",from:et(e.params)})),ct("settings/project/output",e=>({name:"settingsProjectOutput",projectDir:e.params.get("projectDir")||"",from:et(e.params)})),ct("settings/project/preview",e=>({name:"settingsProjectPreview",projectDir:e.params.get("projectDir")||"",from:et(e.params)})),ct("settings/project/hide",e=>({name:"settingsProjectHide",projectDir:e.params.get("projectDir")||"",from:et(e.params),filePath:e.params.get("file")||""})),ct("settings/project",e=>({name:"settingsProject",projectDir:e.params.get("projectDir")||"",chatId:e.params.get("chatId")||"",from:et(e.params)})),ct("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:sr(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"})),ct("settings/actions",e=>({name:"settingsActions",projectDir:e.params.get("projectDir")||"",from:et(e.params)})),Ot("settings/actions/",e=>({name:"settingsActionEdit",id:sr(e.id),projectDir:e.params.get("projectDir")||"",from:et(e.params)})),ct("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)})),ct("settings/mcp/registry",e=>({name:"settingsMcpRegistry",projectDir:e.params.get("projectDir")||"",from:et(e.params)})),ct("settings/mcp",e=>({name:"settingsMcp",projectDir:e.params.get("projectDir")||"",from:et(e.params)})),ct("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)})),ct("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 Ia(e){const t=String(e??"").replace(/^#\/?/,"");if(!t)return{name:"chats"};for(const n of Ea){const r=n.match(t);if(!r)continue;const o=n.build(r);if(o)return o}return{name:"chats"}}Ea.length;Kn.value=Ia(window.location.hash);window.addEventListener("hashchange",()=>{Kn.value=Ia(window.location.hash)});function yt(e){window.location.hash="#/"+e}function Pa(e){return e==="parsed"||e==="installing"||e==="installed"}function tu(e){const t=e||{};return!(!t.hasController||!t.acceptedUpdate||!t.updateApplied)}const nu={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},Ko=Tt(!1);let Pr=null,Co=null,Ki=!1,ko=!1,hr=null;const Zi=new WeakSet,ru=60*1e3;function ou(){try{return!!nu&&!0}catch{return!1}}function So(e,t=e.waiting){Pr=e,Co=t,Ko.value=!0}function oo(e,t){if(!t||Zi.has(t))return;Zi.add(t);const n=()=>{t.state==="installed"&&(navigator.serviceWorker.controller?So(e,t):t.postMessage({type:"SKIP_WAITING"}))};t.addEventListener("statechange",n),n()}function iu(){const e=Pr&&Pr.waiting||Co;if(!(Ki||!e)){if(!Pa(e.state)){Co=null,Ko.value=!1;return}Ki=!0,ko=!0,hr=e,e.postMessage({type:"SKIP_WAITING"})}}function su(){const e=tu({hasController:!!navigator.serviceWorker.controller,acceptedUpdate:ko,updateApplied:!!hr&&!Pa(hr.state)});return ko=!1,hr=null,e}function au(){if(!ou()||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=>{Pr=n,n.waiting&&n.active&&So(n),oo(n,n.installing),n.addEventListener("updatefound",()=>{oo(n,n.installing)}),n.update().then(()=>{n.waiting&&n.active&&So(n),oo(n,n.installing)}).catch(()=>{});const r=()=>n.update().catch(()=>{});document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&r()}),setInterval(()=>{document.visibilityState==="visible"&&r()},ru)}).catch(()=>{})});let t=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{t||su()&&(t=!0,window.location.reload())})}const mr=Tt(typeof navigator>"u"?!1:!navigator.onLine);let Yi=!1;function Xi(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 cu(e){try{return typeof e=="string"?e:e&&typeof e.url=="string"?e.url:String(e||"")}catch{return""}}function lu(){if(Yi||typeof window>"u")return;Yi=!0;const e=()=>{mr.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=cu(r);try{const s=await t(r,o);return Xi(i)&&s&&s.ok&&(mr.value=!1),s}catch(s){throw Xi(i)&&(mr.value=!0),s}}}function uu(){return l("button",{type:"button",class:"pwa-banner__btn tap-target",onClick:()=>{iu()}},"Reload")}function du(){const e=mr.value,t=Ko.value;return!e&&!t?null:l(Ft,null,e?l("div",{class:"pwa-banner pwa-banner--offline",role:"status"},l("span",{class:"pwa-banner__icon","aria-hidden":"true"},l("svg",{viewBox:"0 0 24 24",width:16,height:16},l("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"}))),l("span",{class:"pwa-banner__text"},"You are offline. Showing the last cached view."),l("button",{type:"button",class:"pwa-banner__btn tap-target",onClick:()=>{window.location.reload()}},"Retry")):null,t?l("div",{class:"pwa-banner pwa-banner--update",role:"status"},l("span",{class:"pwa-banner__icon","aria-hidden":"true"},l("svg",{viewBox:"0 0 24 24",width:16,height:16},l("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"}))),l("span",{class:"pwa-banner__text"},"A new version is ready."),uu()):null)}function pu(){const[e,t]=A("API keys & sign-ins"),[n,r]=A("prompt style"),o=rn.value&&rn.value.dir||"",i=rn.value&&rn.value.name||"",s=o?"?projectDir="+encodeURIComponent(o):"";async function c(){try{const a=await Go({force:!0}),d=zl().length;t(d?d===1?"1 connected":d+" connected":"none yet — tap to add"),r(a.app&&a.app.promptSize||"average")}catch{}}ue(()=>{c()},[]);function u(a,d,p={}){const{detail:f=null,sub:h=null}=p;return l("li",null,l("a",{href:"#/"+a,class:"group__row","aria-label":d},l("span",{class:"group__row-label"},d),h&&!f?l("span",{class:"group__row-detail"},h):l("span",{class:"group__row-detail"},f||h||""),l("span",{class:"group__row-chev","aria-hidden":"true"},"›")))}return l("section",{class:"settings-home"},l("div",{class:"group"},l("div",{class:"group__title"},"Providers"),l("ul",{class:"group__list"},u("settings/providers","Providers",{detail:e}),u("settings/projects","Projects",{sub:"registered folders"}))),l("div",{class:"group"},l("div",{class:"group__title"},"App defaults",l("span",{class:"group__title-note"},"Apply to every project")),l("ul",{class:"group__list"},u("settings/defaults","Chat defaults",{detail:n}),u("settings/dictation","Dictation",{sub:"speech-to-text model & transcript"}),u("settings/prompts","Custom prompts",{sub:"app-wide system prompts"}),u("settings/access","Access & passkeys",{sub:"password, WebAuthn, disable QR"}),u("settings/notifications","Notifications",{sub:"questions, approvals & completion"}),u("settings/mcp","MCP servers",{sub:"servers; permissions live in project Tools"}),u("settings/about","About & reset",{sub:"storage · danger zone"}))),l("div",{class:"group"},l("div",{class:"group__title"},"This project",l("span",{class:"group__title-note"},i||o||"none selected")),o?l("ul",{class:"group__list"},u("settings/project"+s,"Project settings",{sub:"prompt style, tools, agents"}),u("settings/mcp"+s,"MCP servers",{sub:"app servers + this project's own"}),u("settings/prompts"+s,"Custom prompts",{sub:"system prompts for this project"})):l("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.")),l("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 Ra(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 fu(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 hu(e){return{...e,challenge:Ln(e.challenge),allowCredentials:(e.allowCredentials||[]).map(t=>({...t,id:Ln(t.id)}))}}async function Na({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:fu(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:Ra(o),name:n})});if(i.status!==200)throw new Error(i.body.error||"Passkey could not be verified");return i.body}async function mu(){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:hu(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:Ra(t)})});if(n.status!==200)throw new Error(n.body.error||"Passkey sign-in failed");return n.body}function Rr({title:e,sub:t,children:n}){return l("main",{class:"access-auth"},l("section",{class:"access-auth__card"},l("div",{class:"access-auth__logo","aria-hidden":"true"},"m"),l("h1",null,e),l("p",{class:"access-auth__sub"},t),n))}function gu({status:e,onAuthenticated:t,onSetup:n}){const[r,o]=A(e.user||""),[i,s]=A(""),[c,u]=A(""),[a,d]=A(!1);async function p(h){h.preventDefault(),d(!0),u("");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():u(g.body.error||"Sign-in failed")}async function f(){d(!0),u("");try{await mu(),t()}catch(h){u(h.message),d(!1)}}return l(Rr,{title:"Sign in",sub:"Access your local mouaif server."},l("form",{onSubmit:p,class:"access-auth__form"},l("label",{class:"label",htmlFor:"access-user"},"User"),l("input",{id:"access-user",class:"input",autocomplete:"username",value:r,onInput:h=>o(h.currentTarget.value),required:!0}),l("label",{class:"label",htmlFor:"access-password"},"Password"),l("input",{id:"access-password",class:"input",type:"password",autocomplete:"current-password",value:i,onInput:h=>s(h.currentTarget.value),required:!0}),l("button",{class:"btn btn--primary",type:"submit",disabled:a},a?"Signing in…":"Sign in")),e.passkeyCount>0&&l("button",{class:"btn access-auth__passkey",type:"button",disabled:a,onClick:f},"Use a passkey"),c&&l("p",{class:"status","data-state":"error",role:"alert"},c),l("button",{class:"access-auth__link",type:"button",onClick:n},"Have a setup code?"))}function _u({initialCode:e="",status:t,onAuthenticated:n,onCancel:r}){const[o,i]=A(e),[s,c]=A(t.user||""),[u,a]=A(""),[d,p]=A(""),[f,h]=A(""),[g,v]=A(!1),[w,k]=A(!1),[_,y]=A(!1);ue(()=>{e&&b(e)},[e]);async function b(x=o){y(!0),h("");const X=await H("/api/access/setup/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:x})});y(!1),v(X.status===200&&X.body.valid),X.status!==200&&h("That setup code is invalid or expired. Generate a new one in the CLI.")}async function D(x){if(x.preventDefault(),u!==d){h("Passwords do not match");return}y(!0),h("");const X=await H("/api/access/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:o,username:s,password:u})});y(!1),X.status===200?(k(!0),h("Password saved. Add a passkey now, or continue.")):h(X.body.error||"Setup failed")}async function j(){y(!0),h("");try{await Na({username:s,name:"Setup device"}),h("Passkey added."),k(!0)}catch(x){h(x.message)}y(!1)}return!g&&!w?l(Rr,{title:"Set up access",sub:"Open the CLI link, scan its QR code, or enter the short code."},l("div",{class:"access-auth__form"},l("label",{class:"label",htmlFor:"setup-code"},"Short code"),l("input",{id:"setup-code",class:"input access-auth__code",autocomplete:"one-time-code",inputMode:"text",placeholder:"ABCD-2345",value:o,onInput:x=>i(x.currentTarget.value.toUpperCase()),maxLength:9}),l("button",{class:"btn btn--primary",type:"button",disabled:_||!o,onClick:()=>b()},_?"Checking…":"Continue")),f&&l("p",{class:"status","data-state":"error",role:"alert"},f),t.configured&&l("button",{class:"access-auth__link",type:"button",onClick:r},"Back to sign in")):l(Rr,{title:w?"Access is ready":"Create your account",sub:w?"Use your password or passkey to sign in.":"This replaces the current access user and signs out other browsers."},!w&&l("form",{onSubmit:D,class:"access-auth__form"},l("label",{class:"label",htmlFor:"setup-user"},"User"),l("input",{id:"setup-user",class:"input",autocomplete:"username",value:s,onInput:x=>c(x.currentTarget.value),required:!0,maxLength:128}),l("label",{class:"label",htmlFor:"setup-password"},"Password"),l("input",{id:"setup-password",class:"input",type:"password",autocomplete:"new-password",value:u,onInput:x=>a(x.currentTarget.value),required:!0,minLength:8}),l("label",{class:"label",htmlFor:"setup-confirm"},"Confirm password"),l("input",{id:"setup-confirm",class:"input",type:"password",autocomplete:"new-password",value:d,onInput:x=>p(x.currentTarget.value),required:!0,minLength:8}),l("button",{class:"btn btn--primary",type:"submit",disabled:_},_?"Saving…":"Save access")),w&&l("div",{class:"access-auth__actions"},l("button",{class:"btn",type:"button",disabled:_,onClick:j},"Add a passkey"),l("button",{class:"btn btn--primary",type:"button",onClick:n},"Open mouaif")),f&&l("p",{class:"status","data-state":f.includes("failed")||f.includes("match")?"error":"success",role:"status"},f))}function yu({children:e}){const[t,n]=A(null),r=Kn.value,o=r.name==="setup",i=r.name==="disableAccess",s=r.code||"";async function c(){const u=await H("/api/access/status");u.status===200&&n(u.body)}return ue(()=>{c()},[]),i?l(vu,{initialCode:s}):t?t.enabled?o||!t.configured?l(_u,{initialCode:s,status:t,onAuthenticated:()=>{window.location.hash="#/projects",c()},onCancel:()=>{window.location.hash="#/login"}}):t.authenticated?e:l(gu,{status:t,onAuthenticated:c,onSetup:()=>{window.location.hash="#/setup"}}):e:null}function vu({initialCode:e=""}){const[t,n]=A(String(e||"").toUpperCase()),[r,o]=A(""),[i,s]=A(""),[c,u]=A(!1);async function a(p){p.preventDefault(),u(!0),o(""),s("");const f=await H("/api/access/disable",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});u(!1),f.status===200?(s("success"),o("Access protection is off. Anyone who can reach this server can open it.")):(s("error"),o(f.body.error||"Could not turn access off"))}const d=i==="success";return l(Rr,{title:d?"Access is off":"Turn off access?",sub:d?"You can turn protection back on from Settings → Access & passkeys.":"This removes the password and passkey wall for this server. It can be turned back on later."},!d&&l("form",{onSubmit:a,class:"access-auth__form"},l("label",{class:"label",htmlFor:"disable-code"},"Confirmation code"),l("input",{id:"disable-code",class:"input access-auth__code",value:t,maxLength:9,inputMode:"text",autocomplete:"one-time-code",placeholder:"ABCD-2345",onInput:p=>n(p.currentTarget.value.toUpperCase())}),l("button",{class:"btn btn--danger",type:"submit",disabled:c||!t},c?"Turning off…":"Disable access")),r&&l("p",{class:"status","data-state":i||void 0,role:"status"},r),d?l("button",{class:"btn btn--primary",type:"button",onClick:()=>{window.location.hash="#/projects"}},"Open mouaif"):l("button",{class:"access-auth__link",type:"button",onClick:()=>{window.location.hash="#/settings/access"}},"Set this up on the signed-in device instead"))}function Qi(){const[e,t]=A(null),[n,r]=A([]),[o,i]=A(""),[s,c]=A(!1),[u,a]=A(""),[d,p]=A(""),[f,h]=A(""),[g,v]=A(""),[w,k]=A(""),[_,y]=A(""),[b,D]=A(0),[j,x]=A(""),[X,ne]=A(!0),[$,I]=A({status:!0,authorization:!0,quickActions:!0});async function N(){const[z,re,W]=await Promise.all([H("/api/access/status"),H("/api/access/passkeys"),Go({force:!0})]);t(z.body),r(re.body.passkeys||[]);const J=W&&W.app&&W.app.notifications||{};ne(J.login===void 0?!0:J.login===!0),I({status:J.status===void 0?!0:J.status===!0,authorization:J.authorization===void 0?!0:J.authorization===!0,quickActions:J.quickActions!==!1})}ue(()=>{N()},[]);async function U(z){ne(z),x("");try{await $l({notifications:{...$,login:z}}),x(z?"Access alerts are on.":"Access alerts are off.")}catch(re){ne(!z),x("Could not save alerts: "+re.message)}}async function Z(z){if(z.preventDefault(),d!==f){v("New passwords do not match");return}v(""),c(!0);const re=await H("/api/access/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:u,newPassword:d})});c(!1),re.status===200?(a(""),p(""),h(""),v("Password changed. Other devices were signed out and passkeys were removed."),N()):v(re.body.error||"Password could not be changed")}async function se(){c(!0),i("");try{await Na(),await N(),i("Passkey added.")}catch(z){i(z.message)}c(!1)}async function ae(z){c(!0),await H("/api/access/passkeys/"+encodeURIComponent(z),{method:"DELETE"}),await N(),c(!1)}async function _e(){await H("/api/access/logout",{method:"POST"}),window.location.hash="#/login",window.location.reload()}async function ye(){c(!0),x("");const z=await H("/api/access/disable/code",{method:"POST"});if(c(!1),z.status!==200){x(z.body.error||"Could not create a disable code");return}k(z.body.code),D(z.body.expiresAt||0),y("/api/access/disable/qr?code="+encodeURIComponent(z.body.code))}function we(){k(""),y(""),D(0),x("")}async function Oe(){c(!0),x("");const z=await H("/api/access/enable",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});c(!1),z.status===200?(x("Access protection is on again."),N()):x(z.body.error||"Could not turn access back on")}const Ce=!!(e&&e.enabled),de=!!(e&&e.armed);return l("section",{class:"view settings-page"},l("header",{class:"view-head"},l("a",{href:"#/settings",class:"view-back","aria-label":"Back"},"‹"),l("h2",{class:"view-title"},"Access & passkeys")),l("div",{class:"settings-section"},l("p",{class:"access-state__badge","data-state":e?Ce?"on":"off":"busy"},e?Ce?"Protection on":"Protection off":"Checking…"),l("p",{class:"hint"},e?Ce?"Signed in as "+e.user+". Changing the password signs out other devices and removes passkeys.":de?"No sign-in is required on this server right now.":"This server was started without an access flag, so no sign-in is required.":"Loading…"),de&&!Ce&&l("div",{class:"access-auth__actions"},l("button",{class:"btn btn--primary",type:"button",disabled:s,onClick:Oe},s?"Working…":"Turn access back on"),l("p",{class:"hint hint--compact"},"Password and passkey sign-in return. This device stays signed in.")),Ce&&!w&&l("div",{class:"access-auth__actions"},l("button",{class:"btn btn--danger",type:"button",disabled:s,onClick:ye},s?"Preparing…":"Create disable QR & code"),l("p",{class:"hint hint--compact"},"Creates a one-time code and QR code. Open the QR on any device, or enter the code on the confirmation page, to remove the sign-in wall.")),Ce&&w&&l("div",{class:"access-auth__quota"},l("p",{class:"hint hint--compact"},"Scan with another device, or open the confirmation page here."),_&&l("img",{class:"access-auth__qr",src:_,width:240,height:240,alt:"Disable access QR code"}),l("p",{class:"access-auth__code"},w),l("p",{class:"hint hint--compact"},"Single use"+(b?" · expires "+new Date(b).toLocaleTimeString():"")),l("div",{class:"row row--actions"},l("a",{class:"btn btn--primary",href:"#/disable-access?code="+encodeURIComponent(w)},"Open confirmation page"),l("button",{class:"btn",type:"button",disabled:s,onClick:we},"Cancel"))),Ce&&l("form",{class:"settings-section__form",onSubmit:Z},l("label",{class:"label",htmlFor:"current-password"},"Current password"),l("input",{id:"current-password",class:"input",type:"password",autocomplete:"current-password",value:u,onInput:z=>a(z.currentTarget.value),required:!0}),l("label",{class:"label",htmlFor:"new-password"},"New password"),l("input",{id:"new-password",class:"input",type:"password",autocomplete:"new-password",minLength:8,value:d,onInput:z=>p(z.currentTarget.value),required:!0}),l("label",{class:"label",htmlFor:"confirm-password"},"Confirm new password"),l("input",{id:"confirm-password",class:"input",type:"password",autocomplete:"new-password",minLength:8,value:f,onInput:z=>h(z.currentTarget.value),required:!0}),l("button",{class:"btn btn--primary",type:"submit",disabled:s},s?"Saving…":"Change password")),g&&l("p",{class:"status","data-state":g.includes("do not match")||g.includes("incorrect")?"error":"success",role:"status"},g),Ce&&l("div",{class:"row row--actions"},l("button",{class:"btn btn--primary",disabled:s,onClick:se},"Add passkey"),l("button",{class:"btn",disabled:s,onClick:_e},"Sign out")),Ce&&l("div",{class:"access-auth__keys"},n.length?n.map(z=>l("div",{class:"access-auth__key",key:z.id},l("div",null,l("strong",null,z.name),l("small",null,"Added "+new Date(z.createdAt).toLocaleDateString())),l("button",{class:"btn btn--danger",disabled:s,onClick:()=>ae(z.id)},"Remove"))):l("p",{class:"hint"},"No passkeys yet. Password sign-in remains available.")),l("label",{class:"group__row settings-notifications__event"},l("span",{class:"group__row-body"},l("span",{class:"group__row-label"},"Access alerts"),l("span",{class:"group__row-detail"},"Sign-in and access on/off notifications to your other devices.")),l("input",{type:"checkbox",class:"checkbox",checked:X,disabled:s||!e,onChange:z=>U(z.currentTarget.checked)})),j&&l("p",{class:"status","data-state":j.includes("again")?"success":"error",role:"status"},j),o&&l("p",{class:"status",role:"status"},o)))}function bu(){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(bu(),{useGrouping:!1,minimumFractionDigits:2,maximumFractionDigits:n}).format(t)}function wu(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 Cu(){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 Zo(e,t,n=!0){ue(()=>{if(!n||!t)return;function r(s){const c=Array.isArray(e)?e:[e],u=s.target;if(!u)return;c.some(d=>{const p=d&&d.current?d.current:d instanceof Element?d:null;return p&&(p===u||p.contains(u))})||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 Lm=[{id:"sparkles",label:"Sparkles"},{id:"code",label:"Code"},{id:"search",label:"Search"},{id:"pencil",label:"Writing"},{id:"bug",label:"Debug"},{id:"book",label:"Research"}],es={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 ts({name:e="sparkles",size:t=20,class:n=""}){const r=es[e]||es.sparkles;return l("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)=>l("path",{d:o,key:i})))}const io=30;function ku(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 Su({project:e,onRename:t,onUnregister:n}){const[r,o]=A(!1),i=P(null);return Zo(i,()=>o(!1),r),l("div",{ref:i,class:"project-card__menu"},l("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)}},"⋯"),l("div",{class:"project-card__menu-pop",hidden:!r,role:"menu",onClick:s=>s.stopPropagation()},l("button",{type:"button",onClick:()=>{o(!1),yt("settings/project?projectDir="+encodeURIComponent(e.path)+"&from=projects")}},"Settings…"),l("button",{type:"button",onClick:()=>{o(!1),t(e)}},"Rename…"),l("button",{type:"button","data-danger":"1",onClick:()=>{o(!1),n(e)}},"Unregister")))}function Tu({project:e}){const[t,n]=A([]),[r,o]=A(0),[i,s]=A(!0),[c,u]=A(0),[a,d]=A(!1),[p,f]=A(!1),[h,g]=A([]);ue(()=>{let _=!1;async function y(){s(!0);try{const[b,D]=await Promise.all([H("/api/chats?projectDir="+encodeURIComponent(e.path)+"&offset=0&limit="+io),H("/api/prompts?projectDir="+encodeURIComponent(e.path)).catch(()=>({status:0,body:{}}))]);if(_)return;if(g(D.status===200?D.body.prompts||[]:[]),b.status===200){const j=b.body.chats||[];n(j),o(b.body.total||j.length),u(j.length)}else n([]),o(0)}catch{_||(n([]),o(0))}_||s(!1)}return y(),()=>{_=!0}},[e.path]);async function v(){if(!(a||i||c>=r)){d(!0);try{const _=await H("/api/chats?projectDir="+encodeURIComponent(e.path)+"&offset="+c+"&limit="+io);if(_.status===200){const y=_.body.chats||[];n(b=>[...b,...y]),o(_.body.total||r||c+y.length),u(b=>b+y.length)}}catch{}d(!1)}}async function w(_=null){f(!0);try{const y={projectDir:e.path};_&&(y.promptId=_);const b=await H("/api/chats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(b.status!==201){alert("create chat failed: HTTP "+b.status),f(!1);return}const D=b.body&&b.body.chat;if(D&&D.id)yt("chat/"+encodeURIComponent(D.id)+"?projectDir="+encodeURIComponent(e.path));else{const j=await H("/api/chats?projectDir="+encodeURIComponent(e.path)+"&offset=0&limit="+io);if(j.status===200){const x=j.body.chats||[];n(x),o(j.body.total||x.length),u(x.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(b=>b.filter(D=>D.id!==_.id)),o(b=>Math.max(0,b-1)),u(b=>Math.max(0,b-1))}return l(Ft,null,l("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?l("li",{class:"project-card__chats-empty"},"loading chats…"):t.length===0?l("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},b=y.known?Ht(y.total):"--",D=ku(_),j=(D.kind==="created"?"new · ":"")+D.text,x=_.trace?" · trace":"",X=_.title&&_.title.trim()?_.title:"New chat",ne=typeof _.messageCount=="number"?_.messageCount:0,$=typeof _.draftSnippet=="string"?_.draftSnippet:"",I=_.hasDraftImage===!0,N=!_.running&&ne===0&&($.trim().length>0||I),U=N?$.replace(/\s+/g," ").trim().slice(0,120)||"Image draft":"",Z=_.promptId?h.find(se=>se.id===_.promptId):null;return l("li",{key:_.id,onClick:()=>yt("chat/"+_.id+"?projectDir="+encodeURIComponent(e.path)),"aria-label":_.running?X+" (running)":N?U+" (draft)":void 0},Z?l("span",{class:"project-card__chat-prompt",title:Z.title,"aria-label":"Prompt: "+Z.title},l(ts,{name:Z.icon,size:17})):null,N?l("span",{class:"project-card__chat-title project-card__chat-title--draft"},U):l("span",{class:"project-card__chat-title"},X),N?l("span",{class:"project-card__chat-draft","aria-hidden":"true"}):_.running?l("span",{class:"project-card__chat-running","aria-hidden":"true"}):null,l("span",{class:"project-card__chat-meta","data-trace":_.trace?"1":void 0,"data-running":_.running?"1":void 0,"data-draft":N?"1":void 0,"data-cost-known":y.known?"1":"0"},b+" · "+j+x),l("button",{class:"project-card__chat-delete",type:"button","aria-label":"Delete chat "+X,onClick:se=>{se.stopPropagation(),k(_)}},"×"))}),a?l("li",{class:"project-card__chats-more"},"Loading more…"):!i&&c<r?l("li",{class:"project-card__chats-more"},"Scroll for more…"):null),l("div",{class:"project-card__new-actions"},l("button",{class:"project-card__new",type:"button",onClick:()=>w(),disabled:p},"+ New chat"),h.filter(_=>_.showOnProjectCard).map(_=>l("button",{class:"project-card__prompt-new",type:"button",key:_.id,onClick:()=>w(_.id),disabled:p,"aria-label":"New chat with "+_.title,title:"New chat with "+_.title},l(ts,{name:_.icon,size:20})))))}function To(){const[e,t]=A([]),[n,r]=A("loading…"),[o,i]=A("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)})},[Aa.value]);async function c(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 u(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 l("section",null,l("div",{class:"page-bar"},l("div",{class:"page-bar__title"},"Chats"),l("span",{class:"status page-bar__status","data-state":o||void 0,"aria-live":"polite"},n),l("button",{class:"page-bar__add",type:"button",onClick:()=>yt("projects/new"),"aria-label":"Add project"},"+")),l("ul",{class:"projects__list","aria-label":"Registered projects"},e.length===0&&o!=="busy"?l("li",{class:"projects__empty"},l("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>'}}),l("p",{class:"projects__empty-title"},"No projects yet"),l("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 l("li",{key:a.id,class:"project-card"},l("div",{class:"project-card__head"},l("div",{class:"project-card__identity"},l("div",{class:"project-card__name"},a.name||a.path),l("div",{class:"project-card__path"},a.path)),l("span",{class:"project-card__cost"},p),l(Su,{project:a,onRename:c,onUnregister:u})),l(Tu,{project:a}))})))}function Au(e){const[t,n]=A(typeof e.dir=="string"?e.dir:""),[r,o]=A([]),[i,s]=A("loading…"),[c,u]=A(""),[a,d]=A(!1),[p,f]=A(!1);async function h(k){const _=k??t;n(_),s("loading…"),o([]);const y=_?"/api/projects?dir="+encodeURIComponent(_):"/api/projects";let b;try{b=await H(y)}catch{s("network error");return}if(b.status!==200){s(b.body&&b.body.error?b.body.error:"HTTP "+b.status);return}const D=b.body.dir||_;n(D);const j=b.body.entries||[];o(j),s(j.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}Aa.value++,yt("projects")}async function v(){const k=c.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?(u(""),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 w(){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]),l("section",null,l("div",{class:"view-head"},l("a",{href:"#/projects",class:"view-back","aria-label":"Back to projects"},"‹"),l("h2",{class:"view-title"},"Pick a folder")),l("p",{class:"picker__path"},t||"user home"),l("div",{class:"page-bar"},l("span",{class:"status page-bar__status","aria-live":"polite"},i),l("button",{class:"btn",type:"button",onClick:()=>{const k=w();k!=null&&yt("projects/new?dir="+encodeURIComponent(k))},"aria-label":"Go to parent folder"},"↑ Up"),l("button",{class:"page-bar__add",type:"button",onClick:()=>g(t),"aria-label":"Select this folder"},"✓")),l("label",{class:"row row--inline picker__db"},l("input",{type:"checkbox",checked:p,onChange:k=>f(!!k.target.checked),"aria-label":"Store settings in app DB"}),l("span",null,"Store settings in app DB — don’t write .mouaif.json")),l("ul",{class:"picker__list","aria-label":"Subfolders"},r.length===0?l("li",{class:"picker__empty"},"no subfolders here"):r.map(k=>l("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)))}},l("span",{class:"picker__name"},k.name),l("span",{class:"picker__meta"},"›")))),l("details",{class:"picker__create"},l("summary",null,"Create new folder"),l("div",{class:"row"},l("input",{class:"input",id:"newFolderName",type:"text",placeholder:"folder name",value:c,onInput:k=>u(k.target.value)})),l("div",{class:"row row--actions"},l("button",{class:"btn btn--primary",type:"button",onClick:v,disabled:a},"Create"))))}function La(e){return"mouaif_models_"+(e||"").replace(/[^a-zA-Z0-9_-]/g,"_")}function Vn(e){try{const t=localStorage.getItem(La(e.props.projectDir)+"_pinned");return new Set(t?JSON.parse(t):[])}catch{return new Set}}function ns(e,t){try{localStorage.setItem(La(e.props.projectDir)+"_pinned",JSON.stringify(Array.from(t)))}catch{}}function Bt(e){return Array.isArray(e.recentModels)?e.recentModels:[]}async function Ma(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 Yl(t)}catch{r=[]}return n!==e._recentLoadRequest||!e.props||e.props.projectDir!==t?!1:(e.recentModels=r,!0)}function Oa(e,t,n){if(!t||!n)return;const r=Array.isArray(e.recentModels)?[...e.recentModels]:[],o=t+"\0"+n,i=r.findIndex(c=>c.provider+"\0"+c.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&&Xl(s,t,n).catch(()=>{})}function ja(e,t,n){const r=Vn(e),o=t+"\0"+n;return r.has(o)?(r.delete(o),ns(e,r),!1):(r.add(o),ns(e,r),!0)}function Yo(e){const t=e.chat;return t&&t.providerId?t.providerId:""}function so(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 Da(e,t,n=!1){const r=await Kl(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 xu(e,t){const n=Yo(e);if(!n)return;(await Da(n,e)).ok&&typeof e._onLiveModels=="function"&&e._onLiveModels(n)}async function rs(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=>Da(a,e,!0).catch(d=>({provider:a,ok:!1,body:{error:String(d),code:"ELIVE"},status:0}))));let o=0,i=0,s=null,c="";for(const a of r)a.ok?o+=a.count:i++;const u=Yo(e);if(s=r.find(a=>a.provider===u),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||"?")+")",c=p+(d&&d!==p?" — "+d:"")}else i&&(c=i+" provider model list(s) could not be refreshed. Try again.");return typeof e._onLiveModels=="function"&&e._onLiveModels("all"),{count:o,error:c}}function sn(e){return String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}const Eu=new Set(["http","https","mailto","ftp","ftps"]);function os(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)&&Eu.has(r.toLowerCase())}function Iu(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())||!os(s)?i:'<img src="'+s+'" alt="'+i+'" loading="lazy" />'),t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(o,i,s)=>/^(https?:\/\/[^/]*)?\/#\//i.test(s.trim())||!os(s)?i:'<a href="'+s+'" target="_blank" rel="noopener noreferrer">'+i+"</a>"),t=Iu(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 ao(e){return e.map(t=>Et(t)).join("<br>")}function Pu(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 c=s.split("|"),u=/^\s*\|/.test(s)?1:0,a=/\|\s*$/.test(s)?c.length-1:c.length;return c.slice(u,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 c=n(e[s]);if(c.length!==0){i+="<tr>";for(let u=0;u<Math.max(c.length,r.length);u++)i+="<td"+(o[u]&&u<o.length?o[u]:"")+">"+Et(c[u]||"")+"</td>";i+="</tr>"}}return i+="</tbody></table>",i}function is(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],c=i[2].trim().split(/\s+/)[0]||"",u=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=u.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:c,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 c of s){const u=c.trim();if(!u)continue;const a=u.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>"+ao(p)+"</blockquote>");continue}if(a.length>=2){const p=Pu(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>"+ao(h.trim().split(`
|
|
8
|
-
`))+"</p>");continue}o.push("<p>"+ao(a)+"</p>")}}return o.join(`
|
|
9
|
-
`)}function Ru(e){return e?e.scrollHeight-e.scrollTop-e.clientHeight<48:!0}function Nu(e){e.transcript.current&&(e.pinnedToBottom.current=!0,e.pendingCount.current=0,Gt(e),Vr(e))}const $t=new WeakMap,Nr=new WeakMap;function Lu(e,t){const n=Nr.get(e.transcript);return Nr.delete(e.transcript),n!=null&&Math.abs(n-t)<1}function Ba(e){Nr.delete(e.transcript);const t=$t.get(e.transcript);t&&(cancelAnimationFrame(t.frame),$t.delete(e.transcript))}function Vr(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}Ba(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,c=t.clientHeight;if(i-s-c<1)r.stableFrames++;else{r.stableFrames=0;const u=Math.max(0,i-c);Nr.set(e.transcript,u),t.scrollTop=u}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?Vr(e):t&&(e.pendingCount.current+=1,Gt(e))))}const qa=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 Ua(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 Va(e,t){const n=Ua(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 Mu({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 Xo(e){const t=String(e||"").trim().match(/^@restart_app(?:\s+([\s\S]*))?$/i);return t?{reason:String(t[1]||"").trim()}:null}function Ou(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 c=t.slice(s,i);if(i>=n||t[i]!=="="||(i++,i>=n))return null;let u;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;u=t.slice(d,i).replace(/\\(.)/g,"$1"),i++}else{const a=i;for(;i<n&&t[i]!==" ";)i++;if(u=t.slice(a,i),!u)return null}o[c]=u}return Object.keys(o).length>0?o:null}function Lr(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 ju(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 Ha(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 Wa(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+" · "+Ha(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 c;(c=s.match(/^# File: (.*)$/))?i.relPath=c[1]:(c=s.match(/^# Lines: (\d+)-(\d+)(?: \/ (\d+))?/))?(i.startLine=Number(c[1]),i.endLine=Number(c[2]),c[3]&&(i.totalLines=Number(c[3]))):(c=s.match(/^# Listing: (.*)$/))?i.pattern=/^<all text/.test(c[1])?"":c[1]:(c=s.match(/^# Kind: image \((.*), (\d+) bytes\)$/))?(i.kind="image",i.mimeType=c[1],i.bytes=Number(c[2])):(c=s.match(/^# Search: (.*)$/))?i.query=c[1]:(c=s.match(/^# Wrote: (.*)$/))?i.relPath=c[1]:(c=s.match(/^# Count: (\d+)(?: \(capped at (\d+)\))?/))?(i.entryCount=Number(c[1]),c[2]!=null&&(i.truncated=!0,i.cap=Number(c[2]))):(c=s.match(/^# Matches: (\d+)(?: \(capped at (\d+) matches \/ (\d+) chars\))?/))?(i.matchCount=Number(c[1]),c[2]!=null&&(i.truncated=!0,i.capMatches=Number(c[2]),i.capBytes=Number(c[3]))):(c=s.match(/^# Skipped: (\d+)/))&&(i.skipped=Number(c[1]))}return i.pattern!=null?(i.entries=Du(i.body),i.entryCount!=null&&i.entries.length>i.entryCount&&(i.entries=i.entries.slice(0,i.entryCount))):i.query!=null&&(i.matches=Bu(i.body),i.matchCount!=null&&i.matches.length>i.matchCount&&(i.matches=i.matches.slice(0,i.matchCount))),i}function Du(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){ss(t,r?r+"/"+i.trim():i.trim());continue}const s=i.match(/^ */)[0].length,c=Math.floor(s/2);let u=i.trim();if(u.endsWith("/")){n.length=c,n[c]=u.slice(0,-1);continue}n.length=c,ss(t,n.filter(Boolean).concat(u).join("/"))}return t}function ss(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 Bu(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 c=s.trim().match(i);if(c){t.push({path:r,line:Number(c[1]),text:c[2]});continue}if(o||!s.trim())continue;const u=s.match(/^ */)[0].length,a=Math.floor(u/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 Ao=new Set;let qt=null;function Wn(e){if(!e||!e.thumbnail)return;const t=Date.parse(qt&&qt.capturedAt||"")||0,n=Date.parse(e.capturedAt||"")||0;qt&&t&&n&&n<t||(qt=e,za())}function as(){return qt}function cs(){qt&&(qt=null,za())}function qu(e){return Ao.add(e),()=>Ao.delete(e)}function za(){for(const e of Ao)try{e(qt)}catch{}}const ls=2e3,co=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 Fu(e,t){if(e==null)return null;const n=ju(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=$a(n,"tool-preview__pre tool-preview__pre--args");return r.appendChild(o),r.appendChild(i),r}function $a(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=$a(t,n);return e.appendChild(r),r}function Uu(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],c=document.createElement("div");let u="ctx";s.startsWith("+")&&!s.startsWith("+++")?u="add":s.startsWith("-")&&!s.startsWith("---")?u="del":s.startsWith("@@")?u="hunk":(s.startsWith("---")||s.startsWith("+++"))&&(u="meta"),c.className="tool-preview__diff-line tool-preview__diff-line--"+u;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||" ",c.appendChild(a),c.appendChild(d),n.appendChild(c)}return e.appendChild(n),n}function xo(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 Vu(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 Ja(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(Ha(t.bytes)),Ut(e,n),Hu(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 Hu(e,t){const n=Array.isArray(t.content)?t.content.find(s=>s&&(s.type==="image"||s.mimeType)):null,r=n?xo(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",()=>Wu(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 gr="mouaif:teardown-lightbox";function Wu(e,t){if(!e)return;if(typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent(gr))}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=c=>{c.key==="Escape"&&s()};function s(){document.removeEventListener("keydown",i),typeof window<"u"&&typeof window.removeEventListener=="function"&&window.removeEventListener(gr,s),n.parentNode&&n.parentNode.removeChild(n)}n.addEventListener("click",c=>{c.target===n&&s()}),o.addEventListener("click",s),document.addEventListener("keydown",i),typeof window<"u"&&typeof window.addEventListener=="function"&&window.addEventListener(gr,s),n.appendChild(r),n.appendChild(o),document.body.appendChild(n)}function zu(){if(!(typeof window>"u"||typeof window.dispatchEvent!="function"))try{window.dispatchEvent(new CustomEvent(gr))}catch{}}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.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 u=String(t.body||"").split(`
|
|
18
|
-
`);return $e(e,u.length&&u[0]?u.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((u,a)=>u.path<a.path?-1:u.path>a.path?1:0);let i=null,s=null,c=null;for(const u of o){const a=String(u.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),c=document.createElement("div"),c.className="tool-preview__group",r.appendChild(c));const h=document.createElement("div");h.className="tool-preview__file",h.textContent=u.image?f+" (image)":f,c.appendChild(h)}e.appendChild(r)}function Ka(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 c=document.createElement("div");c.className="tool-preview__match";const u=document.createElement("span");u.className="tool-preview__match-line",u.textContent=String(s.line);const a=document.createElement("span");a.className="tool-preview__match-text",a.textContent=s.text||"",c.appendChild(u),c.appendChild(a),i.appendChild(c)}e.appendChild(r)}function Za(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),Uu(e,t.diff||"(edit applied)")}function Ya(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,$u(o),"tool-preview__pre tool-preview__pre--content")}function $u(e){const t=String(e),n=t.split(`
|
|
22
|
-
`);if(n.length<=ls&&t.length<=co)return t;let r=n.slice(0,ls).join(`
|
|
23
|
-
`);return r.length>co&&(r=r.slice(0,co)),r+`
|
|
24
|
-
… preview truncated (`+n.length+" lines, "+t.length+" chars written)"}function Xa(e,t,n){e.classList.add("tool-preview","tool-preview--terminal"),typeof t=="string"&&(t=Wt(t,"shell"));const r=Fu(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 Ju(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 Qa(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=xo(r);o?e.appendChild(o):n.push("[image]")}else if(r&&r.type==="resource"){const o=Vu(r),i=o&&xo(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 Gu(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 c=document.createElement("div");c.className="tool-preview__task-list";for(const u of t.tasks){const a=document.createElement("div");a.className="tool-preview__task-item tool-preview__task-item--"+(u.status==="completed"?"done":"progress");const d=document.createElement("span");d.className="tool-preview__task-check",d.textContent=u.status==="completed"?"✓":"○";const p=document.createElement("span");if(p.className="tool-preview__task-label",p.textContent=u.title,a.appendChild(d),a.appendChild(p),u.status!=="completed"&&u.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(u.current/u.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=u.current+" / "+u.total,a.appendChild(v)}if(u.description){const f=document.createElement("div");f.className="tool-preview__task-desc",f.textContent=u.description,a.appendChild(f)}c.appendChild(a)}e.appendChild(c);return}const n=t.task;if(!n)return Qa(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 c=document.createElement("div");c.className="tool-preview__task-bar";const u=document.createElement("div");u.className="tool-preview__task-bar-fill";const a=Math.min(100,Math.max(0,Math.round(n.current/n.total*100)));u.style.width=a+"%",c.appendChild(u),i.appendChild(c);const d=document.createElement("div");d.className="tool-preview__task-stat",d.textContent=n.current+" / "+n.total,i.appendChild(d)}if(n.description){const c=document.createElement("div");c.className="tool-preview__task-desc",c.textContent=n.description,i.appendChild(c)}r.appendChild(o),r.appendChild(i),e.appendChild(r)}function Ku(e,t,n){if(n(t&&t.name)){const c=e.querySelector(".tool-card__subagent-live");c&&c.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 Xa(e,i,s);if(o==="read_file")return Ja(e,i);if(o==="list_files")return Ga(e,i);if(o==="search_files")return Ka(e,i);if(o==="edit_file")return Za(e,i);if(o==="write_file")return Ya(e,i,s);if(o==="task")return Gu(e,i);if(o==="webpreview")return Ju(e,i);n(t&&t.name)||Qa(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 Zu(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 Yu(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 Mm{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(c=>c===""?0:Number(c)),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 c=this._ensureRow(this.row),u=i.length?i[0]:0;if(u===2)for(let a=0;a<c.length;a++)c[a]=" ";else if(u===1)for(let a=0;a<Math.min(this.col-1,c.length);a++)c[a]=" ";else for(let a=this.col-1;a<c.length;a++)c[a]=" ";break}case"J":{const c=i.length?i[0]:0;if(c===2||c===3)this.grid=[];else if(c===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 u=this._ensureRow(this.row);for(let a=0;a<Math.min(this.col-1,u.length);a++)u[a]=" "}else{const u=this._ensureRow(this.row);for(let a=this.col-1;a<u.length;a++)u[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 c=r[o+1];if(c==="["){let u=o+2;for(;u<i&&!(r[u]>="@"&&r[u]<="~");)u++;if(u>=i){this.pending=r.slice(o).join("");break}this._csi(r.slice(o+2,u).join(""),r[u]),o=u+1;continue}if(c==="]"){let u=o+2;for(;u<i&&r[u]!=="\x07"&&!(r[u]==="\x1B"&&r[u+1]==="\\");)u++;if(u>=i){this.pending=r.slice(o).join("");break}o=r[u]==="\x07"?u+1:u+2;continue}if(c==="("||c===")"||c==="#"||c==="%"){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 ec({groups:e=[],onToggleGroup:t,onToggleTool:n,collapsedByDefault:r=!1,initialCollapsed:o,onCollapseChange:i,alwaysExpanded:s=!1,class:c="",onReloadServer:u=null}){const[a,d]=A(()=>o instanceof Set?new Set(o):r?new Set(e.filter(g=>(g.tools||[]).length>1).map(g=>g.id)):new Set),p=P(new Set);ue(()=>{if(o instanceof Set)return;let g=!1;const v=new Set(a);for(const w of e){const k=w.id,_=(w.tools||[]).length>1&&!s&&!w.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=c?"tool-tree "+c:"tool-tree";return e.length?l("ul",{class:h,role:"tree","aria-label":"Tools"},e.map(g=>{const v=g.tools||[],w=v.length>1,k=s||!!g.alwaysExpanded,_=w&&!k,y=_&&a.has(g.id),b=v.length>0&&!y&&(w||k),D=v.filter(x=>x.checked).length,j=v.length>0&&D>0&&D<v.length;return l("li",{key:g.id,class:"tool-tree__group",role:"treeitem","aria-expanded":_?String(!y):void 0},l("div",{class:"tool-tree__row"+(g.disabled?" is-disabled":""),title:g.title||(g.disabled&&g.disabledReason?g.disabledReason:void 0)},_?l("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)},l("svg",{viewBox:"0 0 16 16",width:10,height:10,"aria-hidden":"true"},l("path",{d:"M4 6 L8 10 L12 6",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"}))):l("span",{class:"tool-tree__chew","aria-hidden":"true"}),g.hideCheckbox?null:l("input",{type:"checkbox",class:"checkbox checkbox--sm",checked:!!g.checked,disabled:!!g.disabled,indeterminate:j,"aria-checked":j?"mixed":void 0,onChange:x=>t&&t(g.id,x.target.checked),"aria-label":g.name}),l("span",{class:"tool-tree__name tool-tree__name--group"},g.name),g.description?l("span",{class:"tool-tree__desc"},g.description):null,v.length>1?l("span",{class:"tool-tree__count"},D+"/"+v.length):null,g.control?l("span",{class:"tool-tree__control"},g.control):null,!g.enabled||g.status==="ready"||g.status==="starting"?null:l("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:x=>{x.stopPropagation(),u&&u(g)}},"…")),g.disabled&&g.disabledReason?l("div",{class:"tool-tree__reason"},g.disabledReason):null,b?l("ul",{class:"tool-tree__children",role:"group"},v.map(x=>l("li",{key:x.id,class:"tool-tree__item",role:"treeitem"},l("div",{class:"tool-tree__row tool-tree__row--leaf"+(x.used?" is-used":"")+(x.disabled?" is-disabled":""),title:x.title||(x.disabled&&x.disabledReason?x.disabledReason:void 0)},l("input",{type:"checkbox",class:"checkbox checkbox--sm",checked:!!x.checked,disabled:!!x.disabled||!!g.disabled,onChange:X=>n&&n(g.id,x.id,X.target.checked),"aria-label":x.name}),l("span",{class:"tool-tree__name"},x.name),x.description?l("span",{class:"tool-tree__desc"},x.description):null,x.used?l("span",{class:"tool-tree__used",title:"Used in this chat"},"●"):null,x.disabled&&x.disabledReason?l("span",{class:"tool-tree__leaf-reason"},x.disabledReason):null)))):null,g.extra||null)})):l("div",{class:h+" tool-tree--empty"},"No tools available")}function Om({choices:e,restricted:t,selected:n,mcpServers:r=[],catalog:o=[]}){const i=a=>!t||n(a),s=[],c=e.filter(a=>!a.value.startsWith("mcp__")),u=c.filter(a=>["read_file","list_files","search_files","write_file","edit_file"].includes(a.value));for(const a of c){if(u.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)}]})}u.length&&s.push({id:"files",name:"File tools",description:"read, list, search, write, edit",checked:u.every(a=>i(a.value)),tools:u.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 w=typeof v=="string"?v:v&&v.name;if(!w)return null;const k=w.startsWith(h)?w.slice(h.length):w,_=w.startsWith("mcp__")?w:h+w;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 tc(e,t,n,r=new Set){const o=[],i=Array.isArray(n)?new Set(n):null,s=p=>i==null||i.has(p),c=p=>p.length>0&&p.every(f=>f&&s(f.name)),u=(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:[u(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:[u(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:c(d),tools:d.map(p=>u(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 w=typeof v=="string"?v:v&&v.name;return w?{name:w.startsWith(h)?w:h+w,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:c(g),status:p.status||"stopped",enabled:p.enabled!==!1,serverId:p.id,tools:g.map(v=>{const w=v.name.startsWith(h)?v.name.slice(h.length):v.name;return u(v,{name:w})})})}return o}function nc({tool:e,name:t,mode:n,allowlist:r,modes:o=Hr,namePrefix:i="auth",onPick:s,onClear:c}){const u=oc(n||"ask"),a=Array.isArray(r)?r:[],d=t||e||"tool";return l("div",{class:"seg",role:"radiogroup","aria-label":d+" authorization"},o.map(p=>l("label",{key:p.value,class:"seg__item"+(u===p.value?" seg__item--on":"")},l("input",{type:"radio",name:i+"-"+String(e||d).replace(/\s+/g,"-").toLowerCase(),value:p.value,checked:u===p.value,onChange:()=>{c&&c(),s&&s(p.value,p.value==="allow"?[]:a)}}),l("span",{class:"seg__pill"},p.label))))}const Hr=[{value:"off",label:"Off"},{value:"ask",label:"Ask"},{value:"allow",label:"Allow"}],rc=[{value:"off",label:"Off"},{value:"ask",label:"Ask"}];function oc(e){return e==="allowlist"?"ask":e}async function Xu(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 Qu(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 ed(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 ic({name:e,slug:t,servers:n,shared:r,namePrefix:o="mcp",onSave:i,onClear:s}){const c=t?ed(n,t,r):{mode:r&&r.mode||"ask",allowlist:r&&r.allowlist||[]},u=oc(c.mode);return l("div",{class:"seg",role:"radiogroup","aria-label":e+" authorization"},Hr.map(d=>l("label",{key:d.value,class:"seg__item"+(u===d.value?" seg__item--on":"")},l("input",{type:"radio",name:o+"-"+e.replace(/\s+/g,"-").toLowerCase(),value:d.value,checked:u===d.value,onChange:()=>{if(!i)return;let p=d.value,f=Array.isArray(c.allowlist)?c.allowlist:[];p==="allow"?f=[]:p==="ask"&&f.length&&(p="allowlist"),s&&s(),i(t?{servers:{[t]:{mode:p,allowlist:f}}}:{mode:p,allowlist:f})}}),l("span",{class:"seg__pill"},d.label))))}function td(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 nd(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 rd(e,t){return t?(e.id||"").toLowerCase().indexOf(t)>=0||(e.label||"").toLowerCase().indexOf(t)>=0:!0}function ar(e){return(e.provider||"")+"\0"+e.id}function us({pinned:e}){return l("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},l("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 sc(e){const{models:t,value:n,onChange:r,allowClear:o=!1,clearLabel:i="Inherit chat model",placeholder:s="Pick a model",noProviders:c=!1,label:u,refresh:a,refreshEmpty:d="Refresh models",disabled:p=!1,ariaLabel:f="Pick model",className:h,variant:g="dropdown",open:v,onOpenChange:w,pinned:k,onTogglePin:_,recent:y,recommended:b,extraProviders:D,onOpen:j,children:x}=e,X=_t(()=>td(t),[t]),[ne,$]=A(!1),I=typeof v=="boolean",N=I?v:ne,U=We(T=>{I?w&&w(T):$(T)},[I,w]),[Z,se]=A(""),[ae,_e]=A("all"),[ye,we]=A(!1),[Oe,Ce]=A(""),de=P(!1),[z,re]=A(!1),W=P(null),J=P(null),he=P(null),Re=P(null),q=P(null),R=P(!1),G=P(j);G.current=j;const ce=g==="sheet"||g==="chat",pe=n&&(n.providerId||n.modelId)?{providerId:n.providerId||"",modelId:n.modelId||""}:null,fe=We(()=>{ce&&J.current&&J.current.open&&J.current.close(),U(!1),q.current&&q.current.focus({preventScroll:!0})},[U,ce]);ue(()=>{if(!N||ce)return;const T=oe=>{W.current&&!W.current.contains(oe.target)&&U(!1)},B=oe=>{oe.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)}},[N,ce,U,fe]),ue(()=>{if(!N){re(!1);return}G.current&&G.current()},[N]),Oi(()=>{if(!N||!ce)return;const T=J.current;if(!T)return;const B=window.visualViewport;let oe=0;const Te=q.current&&q.current.getBoundingClientRect(),be=()=>{const Le=B&&B.height?B.height:window.innerHeight,Qe=B?Math.max(0,B.offsetTop):0;if(T.style.setProperty("--model-picker-viewport-height",Le+"px"),T.style.setProperty("--model-picker-viewport-top",Qe+"px"),Te){const at=Math.min(Math.max(Qe,Te.bottom+4),Qe+Le-Math.min(280,Le));T.style.setProperty("--model-picker-anchor-top",at+"px"),T.style.setProperty("--model-picker-anchor-left",Te.left+"px"),T.style.setProperty("--model-picker-available-height",Math.max(0,Qe+Le-at)+"px")}},je=()=>{cancelAnimationFrame(oe),oe=requestAnimationFrame(be)};return B&&(B.addEventListener("resize",be),B.addEventListener("scroll",be)),window.addEventListener("resize",be),window.addEventListener("orientationchange",be),T.addEventListener("focusin",je),T.addEventListener("focusout",je),be(),T.open||T.showModal(),()=>{T.open&&T.close(),cancelAnimationFrame(oe),B&&(B.removeEventListener("resize",be),B.removeEventListener("scroll",be)),window.removeEventListener("resize",be),window.removeEventListener("orientationchange",be),T.removeEventListener("focusin",je),T.removeEventListener("focusout",je),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")}},[N,ce]),Oi(()=>{N&&he.current&&he.current.focus({preventScroll:!0})},[N]);const qe=_t(()=>{const T=[];for(const B of X)B.provider&&T.indexOf(B.provider)<0&&T.push(B.provider);for(const B of D||[])B&&T.indexOf(B)<0&&T.push(B);return T.sort((B,oe)=>B.localeCompare(oe))},[X,D]),Fe=_t(()=>{const T={all:X.length};for(const B of X)T[B.provider]=(T[B.provider]||0)+1;for(const B of D||[])B&&T[B]===void 0&&(T[B]=0);return T},[X,D]),ke=_t(()=>{let T=X;ae!=="all"&&(T=T.filter(oe=>oe.provider===ae));const B=Z.trim().toLowerCase();return B&&(T=T.filter(oe=>rd(oe,B))),T},[X,ae,Z]),dt=_t(()=>nd(ke),[ke]),Ne=pe?pe.providerId+"\0"+pe.modelId:null,it=!!Z.trim(),pt=ae==="all"&&!it;function Je(T){fe(),r&&r({providerId:T.provider,modelId:T.id})}function st(){fe(),r&&r(null)}async function Q(){if(!(!a||de.current)){de.current=!0,we(!0),Ce("");try{const T=await a();T&&T.error&&Ce(T.error)}catch{Ce("Could not refresh models. Try again.")}finally{de.current=!1,we(!1)}}}function te(T){T.button===0&&document.activeElement===he.current&&T.preventDefault()}function C(){se(""),Re.current&&(Re.current.scrollTop=0),he.current&&he.current.focus({preventScroll:!0})}const O=pe?pe.modelId:o?i:s,F=pe?pe.providerId:c?"add a provider in Settings → Providers":"",K=!pe&&!o,E="mp"+(h?" "+h:"")+(g==="chat"?" mp--chat mp--sheet":g==="sheet"?" mp--sheet":"");return l("div",{class:E,ref:W},u?l("label",{class:"mp__label"},u):null,l("button",{ref:q,type:"button",class:"mp__trigger"+(K?" is-empty":"")+(c?" no-providers":"")+(!X.length&&!c?" is-empty":""),disabled:!!p,"aria-label":f,"aria-haspopup":"dialog","aria-expanded":String(N),onClick:()=>U(!N)},l("span",{class:"mp__stack"},l("span",{class:"mp__id"},O),l("span",{class:"mp__provider"},F)),l("span",{class:"mp__caret","aria-hidden":"true"},"▾")),N?l(ce?"dialog":"div",{class:"mp__pop",role:"dialog","aria-modal":ce?"true":void 0,"aria-label":f,ref:J,onCancel:ce?T=>{T.preventDefault(),fe()}:void 0,onKeyDown:ce?T=>{T.key==="Escape"&&(T.preventDefault(),T.stopPropagation(),fe())}:void 0,onPointerDown:ce?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:ce?()=>{R.current=!1}:void 0,onClick:ce?T=>{const B=R.current;if(R.current=!1,!B||T.target!==T.currentTarget)return;const oe=T.currentTarget.getBoundingClientRect();(T.clientX<oe.left||T.clientX>oe.right||T.clientY<oe.top||T.clientY>oe.bottom)&&fe()}:void 0},l("div",{class:"mp__head"},l("input",{ref:he,class:"mp__search",type:"search",placeholder:"Search models","aria-label":"Search models",value:Z,onInput:T=>se(T.currentTarget.value)}),x?l("button",{type:"button",class:"mp__options"+(z?" is-active":""),"aria-label":z?"Hide model options":"Show model options",title:"Model options","aria-expanded":String(z),onClick:()=>re(!z)},l("svg",{viewBox:"0 0 24 24",width:18,height:18,fill:"currentColor","aria-hidden":"true"},l("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?l("button",{type:"button",class:"mp__refresh","aria-label":"Refresh model lists",title:"Refresh model lists",disabled:ye,onPointerDown:te,onClick:Q},l("svg",{viewBox:"0 0 24 24",width:16,height:16,"aria-hidden":"true"},l("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,l("button",{type:"button",class:"mp__close","aria-label":"Close",title:"Close",onClick:fe},"×")),x?l("div",{class:"mp__options-panel",hidden:!z},x):null,qe.length?l("div",{class:"mp__chips",role:"tablist","aria-label":"Filter by provider"},[{id:"all",label:"All"}].concat(qe.map(T=>({id:T,label:T}))).map(T=>l("button",{key:T.id,type:"button",class:"mp__chip"+(ae===T.id?" is-active":""),onClick:()=>_e(T.id)},l("span",{class:"mp__chip-label"},T.label),l("span",{class:"mp__chip-count"},String(Fe[T.id]||0))))):null,Oe?l("p",{class:"mp__refresh-error",role:"alert"},Oe):null,l("div",{class:"mp__list",ref:Re,"aria-busy":ye?"true":void 0},o?l("div",{class:"mp__clear"+(pe?"":" is-active"),role:"button",tabindex:"0",onClick:st},l("span",{class:"mp__clear-id"},i)):null,pt&&b?M("Recommended",ve(X,b,k,y)):null,pt&&k?M("Pinned",X.filter(T=>k.has(ar(T)))):null,pt&&y?xe(y,X,k):null,dt.length?dt.map(T=>l("section",{class:"mp__section",key:T.provider||"other"},l("div",{class:"mp__section-head"},l("span",{class:"mp__section-title"},T.provider||"Other"),l("span",{class:"mp__section-count"},String(T.items.length))),T.items.map(B=>{const oe=ar(B);return l("div",{key:oe,class:"mp__row"+(oe===Ne?" is-active":"")+(B.ghost?" is-ghost":""),role:"button",tabindex:"0",onClick:()=>Je(B)},!B.ghost&&_?l("button",{type:"button",class:"mp__pin","aria-label":"Pin model","aria-pressed":k&&k.has(oe)?"true":"false",onClick:Te=>{Te.stopPropagation(),_(B)}},l(us,{pinned:k&&k.has(oe)})):null,l("span",{class:"mp__row-id"},B.id),B.label&&B.label!==B.id?l("span",{class:"mp__row-label"},B.label):null,l("span",{class:"mp__row-meta"},B.ghost?"unavailable":B.provider||""))}))):l("div",{class:"mp__empty"},l("p",{class:"mp__empty-title"},it?"No matches":X.length?"No models for this provider":"No models yet"),l("p",{class:"mp__empty-text"},it?'No model matches "'+Z+'". Try a shorter query or clear the search.':d),l("div",{class:"mp__empty-actions"},a?l("button",{type:"button",class:"mp__empty-action",disabled:ye,onPointerDown:te,onClick:Q},ye?"Refreshing…":d):null,it?l("button",{type:"button",class:"mp__empty-action mp__empty-action--clear",onPointerDown:te,onClick:C},"Clear search"):null)))):null);function M(T,B){return B.length?l("section",{class:"mp__section",key:T.toLowerCase()},l("div",{class:"mp__section-head"},l("span",{class:"mp__section-title"},T),l("span",{class:"mp__section-count"},String(B.length))),B.map(oe=>{const Te=ar(oe);return l("div",{key:Te,class:"mp__row"+(Te===Ne?" is-active":""),role:"button",tabindex:"0",onClick:()=>Je(oe)},_?l("button",{type:"button",class:"mp__pin","aria-label":"Pin model","aria-pressed":k&&k.has(Te)?"true":"false",onClick:be=>{be.stopPropagation(),_(oe)}},l(us,{pinned:k&&k.has(Te)})):null,l("span",{class:"mp__row-id"},oe.id),oe.label&&oe.label!==oe.id?l("span",{class:"mp__row-label"},oe.label):null,l("span",{class:"mp__row-meta"},oe.provider||""))})):null}function ve(T,B,oe,Te){const be=new Set((Te||[]).map(Le=>(Le.provider||"")+"\0"+Le.id)),je=[];for(const Le of B||[]){const Qe=(Le.provider||"")+"\0"+Le.id;if(be.has(Qe)||oe&&oe.has(Qe))continue;const at=T.find(Nt=>ar(Nt)===Qe);at&&je.push(at)}return je}function xe(T,B,oe){if(!T.length)return null;const Te=new Set,be=[];for(const je of T){const Le=(je.provider||"")+"\0"+je.id;if(Te.has(Le))continue;Te.add(Le);const Qe=B.find(at=>(at.provider||"")===(je.provider||"")&&at.id===je.id);if(Qe&&!(oe&&oe.has(Le))&&be.push(Qe),be.length>=5)break}return be.length?M("Recent",be):null}}const od=["low","medium","high"];function id(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 ac(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 od)t.push({value:n,label:n.charAt(0).toUpperCase()+n.slice(1)});return t.push({value:"__custom__",label:"Custom…"}),t}function sd(e){return ac(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=ac(id(t));n.replaceChildren();for(const c of o){const u=document.createElement("option");u.value=c.value,u.textContent=c.label,c.value==="__custom__"&&(u.style.fontStyle="italic"),n.appendChild(u)}const i=e.thinkingLevelCustom&&e.thinkingLevelCustom.current;o.some(c=>c.value===r)?(n.value=r,i&&(i.hidden=!0)):r&&o.some(u=>u.value==="__custom__")?(n.value="__custom__",i&&(i.value=r,i.hidden=!1)):(n.value="",i&&(i.hidden=!0))}function ad(e){const{value:t,onChange:n,descriptor:r,inheritLabel:o="Inherit",disabled:i=!1,ariaLabel:s="Thinking level"}=e,c=_t(()=>sd(r).filter(p=>p.value!==""),[r]),u=typeof t=="string"?t:"",d=u===""||c.some(p=>p.value===u)?c:c.concat([{value:u,label:u}]);return l("select",{class:"input thinking-select-field",value:u,disabled:!!i,"aria-label":s,onChange:p=>{n&&n(p.currentTarget.value)}},l("option",{value:""},o),d.map(p=>l("option",{key:p.value,value:p.value},p.label)))}function cd({models:e,initialValue:t,projectDir:n,onChange:r}){const[o,i]=A(t||null),[s,c]=A(""),u=_t(()=>({props:{projectDir:n},recentModels:[]}),[n]),[a,d]=A(()=>Bt(u)),[p,f]=A(()=>Vn(u)),h=We(()=>{let y=!0;return Ma(u).then(b=>{y&&b&&d(Bt(u))}),()=>{y=!1}},[u]);function g(y){const b=y;i(b),b&&b.providerId&&b.modelId&&(Oa(u,b.providerId,b.modelId),d(Bt(u))),r&&r({modelOverride:b?{providerId:b.providerId,modelId:b.modelId}:null,thinkingLevel:s,model:b})}function v(y){c(y),r&&r({modelOverride:o?{providerId:o.providerId,modelId:o.modelId}:null,thinkingLevel:y,model:o})}const w=We(y=>{!y||!y.provider||!y.id||(ja(u,y.provider,y.id),f(Vn(u)),d(Bt(u)))},[u]),k=t?"(chat default) "+t.modelId:"(chat default)",_=o&&e.find(y=>y.id===o.modelId&&y.provider===o.providerId);return l("div",{class:"auth-model-picker"},l(sc,{models:e,value:o,variant:"sheet",allowClear:!0,clearLabel:k,ariaLabel:"Model for this subagent run",pinned:p,recent:a,onTogglePin:w,onOpen:h,onChange:g}),l(ad,{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},ld=[".chat-view__setup",'[data-sys-prompt="1"]','[data-tools-card="1"]','[data-agent-files-card="1"]','[data-skills-card="1"]',".chat-view__empty"];function ds(e,t){const n=e&&e.className;return typeof n=="string"&&(" "+n+" ").indexOf(" "+t+" ")>=0}function Qo(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 ds(e,"chat-view__setup")?gt.setup:ds(e,"chat-view__empty")?gt.empty:-1}function cc(e){return Qo(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=Qo(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 ud(e){const t=e&&e.transcript&&e.transcript.current;if(!(!t||typeof t.querySelector!="function"))for(const n of ld){const r=t.querySelector(n);!r||r.parentNode!==t||yn(t,r,Qo(r))}}function dd(){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 ei(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 c=tc(t.catalog,e.mcpServers||[],t.filter,e.usedTools||new Set),u=e._mcpStartBusyServerId;if(u)for(const y of c)y&&y.serverId===u&&(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 c){const b=d[y.id];if(!b)continue;const D=a[b]||{mode:"ask"};y.control=l(nc,{tool:b,name:b,mode:D.mode,allowlist:D.allowlist,modes:b==="ask_user"?rc:Hr,namePrefix:"chat-auth",onClear:()=>{e._saveToolAuth&&e._saveToolAuth(b,null,[])},onPick:(j,x)=>{e._saveToolAuth&&e._saveToolAuth(b,j,x)}})}const p=e.mcpAuth||{mode:"ask",allowlist:[],servers:{},tools:{}};for(const y of c){if(!y.id.startsWith("mcp-"))continue;const b=y.id.slice(4);y.control=l(ic,{name:y.name,slug:b,servers:p.servers,shared:p,namePrefix:"chat-mcp",onClear:()=>{e._saveMcpAuth&&e._saveMcpAuth({servers:{[b]:null}})},onSave:D=>e._saveMcpAuth&&e._saveMcpAuth(D)})}const f=document.createElement("div");f.className="chat-view__tools-tree";const h=e._toolTreeCollapsed||null;function g(y,b){const D=c.find(j=>j.id===y);D&&e._toggleToolGroup&&e._toggleToolGroup(D.tools.map(j=>j.id),b)}function v(y,b,D){e._toggleTool&&e._toggleTool(b,D)}const w=y=>{e._toolTreeCollapsed=y};function k(y,b){if(y)for(const D of c)D&&D.serverId===y&&(D.reloadBusy=b)}async function _(y){const b=y&&y.serverId;if(!(!b||!e._startMcpServer)&&e._mcpStartBusyServerId!==b){k(b,!0),e._updateToolsCard&&e._updateToolsCard();try{await e._startMcpServer(b)}finally{k(b,!1),e._updateToolsCard&&e._updateToolsCard()}}}return Fn(l(ec,{groups:c,onToggleGroup:g,onToggleTool:v,collapsedByDefault:!0,initialCollapsed:h,onCollapseChange:w,onReloadServer:_}),f),n.appendChild(f),n}function pd(e,t){if(!e.transcript.current)return;const n=e.transcript.current.querySelector('[data-tools-card="1"]');n&&n.remove();const r=ei(t);e.toolsCard.current=r,yn(e.transcript.current,r,gt.tools)}function lc(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 c=document.createElement("div");return c.className="chat-view__agent-files-empty",c.textContent="No agent files found at the project root.",n.appendChild(c),n}const s=document.createElement("div");s.className="chat-view__agent-files-list";for(const c of t.files){const u=document.createElement("label");u.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 "+c),a.addEventListener("change",()=>e._toggleAgentFiles&&e._toggleAgentFiles(a.checked));const d=document.createElement("span");d.className="chat-view__agent-files-name",d.textContent=c,u.appendChild(a),u.appendChild(d),s.appendChild(u)}return n.appendChild(s),n}function uc(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 c=document.createElement("div");return c.className="chat-view__skills-empty",c.textContent="No skills found in .agents/skills.",n.appendChild(c),n}const s=document.createElement("div");s.className="chat-view__skills-list";for(const c of t.items){const u=!!c.disabled,a=!!c.chatDisabled,d=!!(t.enabled&&!u&&!a),p=!!t.projectLocked||u,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 "+(c.name||c.id)),h.addEventListener("change",()=>{e._toggleSkill&&e._toggleSkill(c.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=c.name||c.id,g.appendChild(v),c.description){const w=document.createElement("span");w.className="chat-view__skills-desc",w.textContent=c.description,g.appendChild(w)}if(u){const w=document.createElement("span");w.className="chat-view__skills-reason",w.textContent="Disabled in Settings → Project",g.appendChild(w)}f.appendChild(h),f.appendChild(g),s.appendChild(f)}return n.appendChild(s),n}function fd(e,t){if(!e.transcript.current)return;const n=e.transcript.current.querySelector('[data-agent-files-card="1"]');n&&n.remove();const r=lc(t);e.agentFilesCard.current=r,yn(e.transcript.current,r,gt.agentFiles)}function hd(e,t){if(!e.transcript.current)return;const n=e.transcript.current.querySelector('[data-skills-card="1"]');n&&n.remove();const r=uc(t);e.skillsCard.current=r,yn(e.transcript.current,r,gt.skills)}function md(e,t){if(!e.agentFilesCard.current||!e.agentFilesCard.current.parentNode)return;const n=lc(t);e.agentFilesCard.current.parentNode.replaceChild(n,e.agentFilesCard.current),e.agentFilesCard.current=n}function dc(e,t){if(!e.skillsCard.current||!e.skillsCard.current.parentNode)return;const n=uc(t);e.skillsCard.current.parentNode.replaceChild(n,e.skillsCard.current),e.skillsCard.current=n}async function gd(e,t,n,r,o){const i=t.agentFiles||{files:[]};t.agentFiles={files:i.files,enabled:e,explicit:!0,projectLocked:i.projectLocked},md(n,t),await r({agentFiles:e}),typeof o=="function"&&await o()}async function _d(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(u=>Object.assign({},u,{chatDisabled:u.disabled?!!u.chatDisabled:!e}))}),dc(n,t);const c=s.filter(u=>!u.disabled);await r({skills:e,disabledSkills:e||!c.length?null:c.map(u=>u.id)}),typeof o=="function"&&await o()}async function yd(e,t,n,r,o,i){const s=n.skills||{items:[],enabled:!0,projectLocked:!1},c=Array.isArray(s.items)?s.items:[],u=c.filter(h=>!h.disabled),a=s.enabled?new Set(u.filter(h=>!h.chatDisabled).map(h=>h.id)):new Set;t?a.add(e):a.delete(e);const d=u.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:c.map(h=>Object.assign({},h,{chatDisabled:h.disabled?!!h.chatDisabled:!a.has(h.id)}))}),dc(r,n),await o(f),typeof i=="function"&&await i()}function pc(e,t){if(!e.toolsCard.current||!e.toolsCard.current.parentNode)return;const n=ei(t);e.toolsCard.current.parentNode.replaceChild(n,e.toolsCard.current),e.toolsCard.current=n}async function vd(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 c=s.map(a=>a.name);let u;if(i.filter==null)u=c.filter(a=>a!==e),t&&(u=c.slice());else{const a=new Set(i.filter);t?a.add(e):a.delete(e),a.size===s.length?u=null:u=Array.from(a)}n.tools={catalog:s,filter:u},pc(r,n),await o({tools:u??null})}function bd(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 wd(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 c=s.providerId&&s.modelId?{providerId:s.providerId,modelId:s.modelId}:null;const u=document.createElement("div");u.className="tool-card__auth-model";const a=document.createElement("div");return a.className="tool-card__auth-model-field",Fn(l(cd,{models:i,initialValue:c,projectDir:n,onChange:d=>{c=d}}),a),u.appendChild(a),u._selected=()=>c,u}function Rt(e,t,n,r,o,i){return new Promise(s=>{if(!r.transcript.current)return s("deny");const c=document.createElement("div");c.className="tool-card tool-card--authorization",e.callId&&(c.dataset.authCallId=e.callId);const u=document.createElement("div");u.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",u.appendChild(a),u.appendChild(d),u.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=wd(i,e,t),g=document.createElement("div");g.className="tool-card__actions";const v=[];for(const[_,y,b]of[["allow-once","Allow once","1"],["allow-session","Allow session","2"],["allow-always","Always allow","3"],["deny","Deny","4"]]){const D=document.createElement("button");D.type="button",D.className="btn"+(_==="deny"?" btn--danger":""),D.textContent=y+" ["+b+"]",D.setAttribute("aria-label",y+" ("+b+")"),D.dataset.shortcut=b,D.addEventListener("click",async()=>{for(const ne of g.querySelectorAll("button"))ne.disabled=!0;const j={projectDir:t,chatId:n,callId:e.callId,decision:_},x=h&&typeof h._selected=="function"?h._selected():null;if(x&&_!=="deny"){const ne={};x.modelOverride&&x.modelOverride.providerId&&x.modelOverride.modelId&&(ne.modelOverride={providerId:x.modelOverride.providerId,modelId:x.modelOverride.modelId}),typeof x.thinkingLevel=="string"&&x.thinkingLevel&&(ne.thinkingLevel=x.thinkingLevel),Object.keys(ne).length&&(j.payload=ne)}const X=await H("/api/tools/authorization/decision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(j)});if(X.status!==200){for(const ne of g.querySelectorAll("button"))ne.disabled=!1;r.status.current&&(r.status.current.textContent="authorization failed: HTTP "+X.status,r.status.current.dataset.state="error");return}c.remove(),_!=="deny"&&typeof o=="function"&&await o(),s(_)}),g.appendChild(D),v.push(D)}function w(_){if(!_)return!1;const y=String(_.tagName||"").toLowerCase();return y==="input"||y==="textarea"||y==="select"||_.isContentEditable===!0}function k(_){if(w(_.target))return;if(_.key==="Escape"&&v[3]){v[3].click();return}const y=v.find(b=>b.dataset.shortcut===_.key);y&&y.click()}c.addEventListener("keydown",k),v[0]&&setTimeout(()=>v[0].focus(),100),c.appendChild(u),c.appendChild(f),h&&c.appendChild(h),c.appendChild(g),r.transcript.current.appendChild(c),Ye(r,!0);try{c.scrollIntoView({behavior:"smooth",block:"center"})}catch{}})}function Mr(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 c=document.createElement("span");c.className="tool-card__chev",c.setAttribute("aria-hidden","true"),c.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(c);const u=document.createElement("span");u.className="tool-card__role",u.textContent="the model is asking",s.appendChild(u);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 ne=document.createElement("div");ne.className="tool-card__ask-presets";for(const $ of h){const I=document.createElement("button");I.type="button",I.className="tool-card__ask-preset-chip",I.textContent=$,I.addEventListener("click",async()=>{for(const Z of i.querySelectorAll("button"))Z.disabled=!0;const N={choice:$,extra:""},U=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:N})});if(U.status!==200){for(const Z of i.querySelectorAll("button"))Z.disabled=!1;o("ask_user failed: HTTP "+U.status,"error");return}i.remove(),o("answer sent","success")}),ne.appendChild(I)}p.appendChild(ne)}const g=document.createElement("div");g.className="tool-card__ask-options",p.appendChild(g);const v=Array.isArray(e.options)?e.options:[],w=!!e.multiSelect;let k=w?new Set:null,_=null;function y(){for(const ne of g.querySelectorAll(".tool-card__ask-option")){const $=ne.dataset.value||"",I=w?k.has($):$===(_&&_.value);ne.classList.toggle("is-selected",!!I),ne.setAttribute("aria-checked",I?"true":"false")}}for(let ne=0;ne<v.length;ne++){const $=v[ne]||{},I=document.createElement("button");I.type="button",I.className="tool-card__ask-option",I.dataset.value=String($.value||""),I.setAttribute("role",w?"checkbox":"radio"),I.setAttribute("aria-checked","false");const N=document.createElement("span");if(N.className="tool-card__ask-option-label",N.textContent=$.label||$.value||"option "+(ne+1),I.appendChild(N),$.description){const U=document.createElement("span");U.className="tool-card__ask-option-desc",U.textContent=$.description,I.appendChild(U)}I.addEventListener("click",()=>{w?k.has(I.dataset.value)?k.delete(I.dataset.value):k.add(I.dataset.value):_={value:I.dataset.value,label:$.label||I.dataset.value},y()}),I.addEventListener("keydown",U=>{(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),I.click())}),g.appendChild(I)}const b=document.createElement("label");b.className="tool-card__ask-extra-label",b.textContent="Add an extra answer (always optional)",p.appendChild(b);const D=document.createElement("textarea");D.className="input tool-card__ask-extra",D.rows=2,D.spellcheck=!1,D.maxLength=1e3,D.placeholder="Add context, a follow-up, or just a note for the model.",p.appendChild(D);const j=document.createElement("div");j.className="tool-card__actions";const x=document.createElement("button");x.type="button",x.className="btn btn--primary",x.textContent="Send answer",x.addEventListener("click",async()=>{if(!(w?Array.from(k):_?[_.value]:[]).length){for(const U of j.querySelectorAll("button"))U.disabled=!0;const N=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(N.status!==200){for(const U of j.querySelectorAll("button"))U.disabled=!1;o("ask_user failed: HTTP "+N.status,"error");return}i.remove(),o("question dismissed","success");return}for(const N of j.querySelectorAll("button"))N.disabled=!0;const $={choice:w?Array.from(k):_?_.value:"",extra:D.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:$})});if(I.status!==200){for(const N of j.querySelectorAll("button"))N.disabled=!1;o("ask_user failed: HTTP "+I.status,"error");return}i.remove(),o("answer sent","success")}),j.appendChild(x);const X=document.createElement("button");X.type="button",X.className="btn",X.textContent="Dismiss",X.addEventListener("click",async()=>{for(const $ of j.querySelectorAll("button"))$.disabled=!0;const ne=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(ne.status!==200){for(const $ of j.querySelectorAll("button"))$.disabled=!1;o("ask_user failed: HTTP "+ne.status,"error");return}i.remove(),o("question dismissed","success")}),j.appendChild(X),p.appendChild(j),i.appendChild(p),r.transcript.current.appendChild(i),Ye(r,!0);try{i.scrollIntoView({behavior:"smooth",block:"center"})}catch{}}async function Cd(e,t,n,r,o){const i=n.tools||{catalog:[],filter:null},s=i.catalog||[],c=s.map(d=>d&&d.name).filter(Boolean),u=new Set((e||[]).filter(d=>c.includes(d)));if(!u.size)return;let a;if(i.filter==null)a=t?c.slice():c.filter(d=>!u.has(d));else{const d=new Set(i.filter);if(t)for(const p of u)d.add(p);else for(const p of u)d.delete(p);a=d.size===s.length?null:Array.from(d)}n.tools={catalog:s,filter:a},pc(r,n),await o({tools:a??null})}function ti(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 kd(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 Sd(e,t,n,r){let o=null,i=t?t.total:0,s=t?t.known:!1;function c(u){u&&u.known&&Number.isFinite(u.total)&&(i+=u.total,s=!0)}Number.isFinite(r)&&r>0&&(i+=r,s=!0);for(const u of e||[])!u||u.role!=="assistant"||(u.usage&&typeof u.usage.promptTokens=="number"&&(o=u.usage.promptTokens),(!t||!Number.isInteger(u.seq)||u.seq>=t.nextSeq)&&c(u.cost));return n&&(n.usage&&typeof n.usage.promptTokens=="number"&&(o=n.usage.promptTokens),c(n.cost),c(n.liveCost)),{latestContext:o,totalCost:i,hasKnownCost:s}}function ie(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 Td(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}=Sd(e.messages,e.costSnapshot,t,e.attributedCost);r.innerHTML="";const c=(u,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=u;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(c("Context",o==null?"--":nn(o))),r.appendChild(c("Total",s?Ht(i):"--")),e.providerCredit){const u=e.providerCredit,a=u.indexOf(" "),d=a>0?u.slice(0,a):u,p=a>0?u.slice(a+1):"",f=c(d,p,{cls:"chat-view__usage-summary-credit"});r.appendChild(f)}}function _r(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 u="context "+nn(o.promptTokens);const a=Td(n);if(a){const d=Math.round(o.promptTokens/a*100);u+="/"+nn(a)+" ("+d+"%)"}s.push(u)}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 u=[];o.cacheReadTokens>0&&u.push(nn(o.cacheReadTokens)+" read"),o.cacheCreationTokens>0&&u.push(nn(o.cacheCreationTokens)+" written"),s.push("cache "+u.join(" · "))}i&&i.known?s.push("cost "+Ht(i.total)):i&&i.known===!1&&s.push("--");let c=t.liveRate;c==null&&t.streamingMs&&typeof o.completionTokens=="number"&&(c=t.streamingMs>0?o.completionTokens/t.streamingMs*1e3:0),c!=null&&s.push({kind:"rate",label:wu(c)});for(let u=0;u<s.length;u++){if(u>0){const p=document.createElement("span");p.className="chat-msg__meta-sep",p.textContent="·",e.appendChild(p)}const a=s[u],d=document.createElement("span");typeof a=="string"?(d.textContent=a,u===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 Eo(e,t){if(!e.chatMeta.current)return;const n=t.chat;n&&(e.chatMeta.current.textContent=n.trace?"trace on":"")}function ps(e){const t=e.chat;return t&&["very-small","average","extensive"].indexOf(t.promptSize)>=0?t.promptSize:"average"}async function fc(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,Eo(n,t),t._onChatChanged&&t._onChatChanged(),!0)}async function yr(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,gc(t,e.systemPrompt)}async function Ad(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 xd(e,t,n){["very-small","average","extensive"].indexOf(e)<0||(Io(e,n),fc({promptSize:e},t,n).then(()=>{yr(t,n)}))}function Io(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 fs(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 hc(e){return!!e&&e.role==="system"&&/^⚠(?:\s|$)/.test(String(e.content||""))}function Ed(e,t){if(!Array.isArray(e)||!hc(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 Id(e){return String(e??"").trim()||"agent"}function mc(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 c=document.createElement("div");c.className="chat-msg__body";const u=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 · "+u+" line"+(u===1?"":"s");const p=document.createElement("pre");return p.className="chat-msg__system-body",p.textContent=e||"",a.appendChild(d),a.appendChild(p),c.appendChild(a),r.appendChild(o),r.appendChild(c),r}function gc(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=mc(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 Wr(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 Pd(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 Rd(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 c=document.createElement("div");c.className="chat-msg__reasoning-body"+(r?"":" chat-msg__reasoning-body--raw"),r?c.innerHTML=is(n):c.textContent=n,i.appendChild(s),i.appendChild(c),e.appendChild(i)}const o=document.createElement("div");o.className="chat-msg__answer",r?o.innerHTML=is(t||""):o.textContent=t||"",e.appendChild(o)}const hs='<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>',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="M20 6 9 17l-5-5"/></svg>',Ld='<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 Md(e){const t=document.createElement("button");return t.className="chat-msg__copy tap-target",t.type="button",t.innerHTML=hs,t.setAttribute("aria-label","Copy message"),t.title="Copy message",t.addEventListener("click",async()=>{const n=await Zu(Yu(e()));t.innerHTML=n?Nd:Ld,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=hs,t.classList.remove("is-copied","is-failed"),t.setAttribute("aria-label","Copy message"),t.title="Copy message"},1400)}),t}function Zn(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 c=document.createElement("div");c.className="chat-msg__body",e.role==="assistant"?vn(c,e.content||"",e.reasoning||"",!0):(c.textContent=e.content||"",e.role==="user"&&Array.isArray(e.attachments)&&e.attachments.length&&Pd(c,e.attachments));const u=document.createElement("div");u.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,u.appendChild(s),u.appendChild(a),i.appendChild(u),i.appendChild(c),e.role==="user"||e.role==="assistant"){const d=document.createElement("div");d.className="chat-msg__actions",d.appendChild(Md(()=>t?{role:e.role,content:i._content||"",reasoning:i._reasoning||""}:e)),i.appendChild(d)}if(Wr(n,i),e.role==="assistant"&&t&&(i._body=c,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?_r(d,e,r):d.hidden=!0,i.appendChild(d)}Ye(n,!0)}function _c(e){const t=e&&e._body;return t&&(e._streaming||(vn(t,e._content||"",e._reasoning||"",!1),e._streaming=!0),t)}function Od(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 jd(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 Dd(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||"";Zn({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=_c(r);o&&(o._owner=r),r._content=(r._content||"")+e,Od(o,e),Ye(t,!1)}}function Bd(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||"";Zn({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=_c(r);o&&(o._owner=r),r._reasoning=(r._reasoning||"")+e,jd(o,e),Ye(t,!1)}}function vr(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 c=document.createElement("div");c.className="chat-msg__role",c.textContent="error";const u=document.createElement("span");u.className="chat-msg__ts",u.textContent=new Date(r&&r.ts||Date.now()).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),s.appendChild(c),s.appendChild(u);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)}Wr(t,i),n&&(!r||r.persist!==!1)&&(n.messages=n.messages.concat([{role:"system",content:e,ts:new Date().toISOString()}])),Ye(t,!0)}const ms={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 yc(e){const t=Ge(e);if(ms[t])return ms[t];if(t&&t.startsWith("mcp__")){const n=t.split("__").filter(Boolean);return n[n.length-1]||t}return t||"tool"}function vc(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 ni(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=yc(e),o.appendChild(i),n){const c=document.createElement("pre");c.className="tool-card__args",c.textContent=vc(n,qa),c.textContent!==n&&(c.title=n),o.appendChild(c)}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 Po(e,t,n,r,o){if(!e)return null;const i=Ge(t),s=Wt(n,i),c=typeof o=="boolean"?o:!(s&&s.error),u=e.querySelector(".tool-card__pill");u&&(u.className="tool-card__pill "+(c?"tool-card__pill--ok":"tool-card__pill--err"),u.textContent=c?"ok":"error");const a=c||Fa(t,s,c)?Wa(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,u||null)),p.textContent=a}const d=e.querySelector(".tool-card__subagent-preview");return d&&d.remove(),$d(e,t,n,r),s}function ri(e,t,n,r,o,i){const s=document.createElement("div");s.className="tool-card__head",s.setAttribute("role","button");const c=document.createElement("span");c.className="tool-card__chev",c.setAttribute("aria-hidden","true"),c.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 u=document.createElement("span");if(u.className="tool-card__name",u.textContent=yc(e),Lr(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(c),s.appendChild(u),s.appendChild(d),gs(s,e,t,n,r,o)}}return s.appendChild(c),s.appendChild(u),gs(s,e,t,n,r,o)}function gs(e,t,n,r,o,i){const s=n==null?"":typeof n=="string"?n:Hn(n,t),c=document.createElement("span");if(c.className="tool-card__pill "+r,c.textContent=o,s){const u=document.createElement("pre");u.className="tool-card__args",u.textContent=vc(s,qa),u.textContent!==s&&(u.title=s),e.appendChild(u)}if(i){const u=document.createElement("span");u.className="tool-card__result-summary",u.textContent=i,e.appendChild(u)}return e.appendChild(c),e.addEventListener("click",()=>{const u=e.closest(".tool-card");u&&(u.classList.toggle("is-expanded"),u._userCollapsed=!u.classList.contains("is-expanded"),u.classList.contains("is-expanded")&&typeof u._lazyBody=="function"&&u._lazyBody())}),e}function qd(e,t,n,r){Array.isArray(e._anonToolCalls)||(e._anonToolCalls=[]),e._anonToolCalls.push({id:t,name:n,card:r})}function Fd(e,t){const r=(Array.isArray(e._anonToolCalls)?e._anonToolCalls:[]).filter(c=>c&&c.card&&c.card.isConnected);e._anonToolCalls=r;const o=Ge(t);let i=r.findIndex(c=>c.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(si))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(ri(e.name,e.args,"tool-card__pill--busy","running",null,e.args)),Lr(e.name)){i.classList.add("tool-card--subagent"),i.classList.add("is-expanded");const s=document.createElement("div");s.className="tool-card__body";const c=document.createElement("div");c.className="tool-card__subagent-live";const u=document.createElement("div");u.className="tool-card__subagent-live-hint",u.innerHTML='<span class="tool-card__spinner" aria-hidden="true"></span>Subagent is working…',c.appendChild(u),s.appendChild(c),i.appendChild(s)}else if(Ge(e.name)==="shell"){const s=document.createElement("div");s.className="tool-card__body";const c=document.createElement("div");c.className="tool-card__shell-live";const u=document.createElement("div");u.className="tool-card__shell-live-hint",u.textContent=n?"Waiting for results…":"Running…";const a=document.createElement("pre");a.className="tool-card__shell-live-pre",c.appendChild(u),c.appendChild(a),s.appendChild(c),i.appendChild(s),n||i.classList.add("is-expanded")}return Wr(t,i),Ye(t,!0),e.id||qd(t,o,Ge(e.name),i),i}function oi(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 Ud(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 Vd(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 bc(e,t,n){if(!n.transcript.current)return!1;const r=Ud(n,t&&t.parentCallId);if(!r)return!1;const o=Vd(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 c=`
|
|
38
|
-
── stderr ──
|
|
39
|
-
`;s.textContent.includes(c)||(s.textContent+=c),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=ni(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")),Po(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||Fd(t,e.name);let r=n?t.transcript.current.querySelector('[data-tool-id="'+kt(String(n))+'"]'):null;const o=Lr(e&&e.name),i=e.ok?"tool-card__pill--ok":"tool-card__pill--err",s=e.ok?"ok":"error",c=Wt(e&&e.result,Ge(e&&e.name)),u=e.ok||Fa(e&&e.name,c,e.ok)?Wa(e&&e.name,c):null;e.ok&&Ge(e.name)==="webpreview"&&c&&c.thumbnail&&Wn(c);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;Hd(r,e.name,f,i,s,u,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(ri(e.name,f,i,s,u,a));const h=document.createElement("div");h.className="tool-card__body",r.appendChild(h),Wr(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,Ku(d,a?Object.assign({},e,{args:a}):e,Lr),o&&ip(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 Hd(e,t,n,r,o,i,s){const c=e.querySelector(":scope > .tool-card__head"),u=ri(t,n,r,o,i,s);c&&c.parentNode===e?e.replaceChild(u,c):e.insertBefore(u,e.firstChild)}function Wd(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=ni(n.name,t&&t.id,i,o&&typeof o=="object"?o:null);return e.appendChild(s),s}function zd(e,t,n,r){if(r)return r._settled=!0,Po(r,t.name,t.content,n),r;const o=ni(t.name,t.tool_call_id,null,n);return o._settled=!0,e.appendChild(o),Po(o,t.name,t.content,n),o}function $d(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 Jd(s,i,r);if(o==="read_file")return Gd(s,i);if(o==="list_files")return Kd(s,i);if(o==="search_files")return Zd(s,i);if(o==="edit_file")return Yd(s,i);if(o==="write_file")return Xd(s,i,r);if(i&&Array.isArray(i.content)){const c=[];for(const u of i.content)u&&typeof u.text=="string"?c.push(u.text):c.push(String(u&&(u.text||u.type)||u));return _s(s,c.join(`
|
|
40
|
-
`),"tool-preview__pre")}return _s(s,bt(i),"tool-preview__pre")}function Jd(e,t,n){return Qd(e,t,n)}function Gd(e,t){return ep(e,t)}function Kd(e,t){return tp(e,t)}function Zd(e,t){return np(e,t)}function Yd(e,t){return rp(e,t)}function Xd(e,t,n){return op(e,t,n)}function _s(e,t,n){const r=document.createElement("pre");return r.className=n,r.textContent=t||"",e.appendChild(r),r}function Qd(e,t,n){Xa(e,t,n)}function ep(e,t){Ja(e,t)}function tp(e,t){Ga(e,t)}function np(e,t){Ka(e,t)}function rp(e,t){Za(e,t)}function op(e,t,n){Ya(e,t,n)}function ip(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}],c=new Map,u=[],a=(g,v)=>{for(const w of v){const k=Wd(g,w),_=w&&(w.id||w.function&&w.function.id);k&&_&&c.set(_,k),k&&u.push(k)}},d=()=>u.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 w of v){const k=w&&(w.id||w.function&&w.function.id),_=w&&w.function?w.function.arguments:w&&w.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 x=Array.isArray(g.tool_calls)?g.tool_calls:[];x.length?a(i,x):zd(i,g,f.get(g.tool_call_id)||null,c.get(g.tool_call_id)||d());continue}if(v!=="user"&&v!=="assistant"&&v!=="system")continue;const w=Rd(g.content);if(v==="system"){const x=mc(w,"tool-card__subagent-msg",Id(r&&r.agent)),X=Array.isArray(g.tool_calls)?g.tool_calls:[];a(x,X),i.appendChild(x);continue}const k=Array.isArray(g.tool_calls)?g.tool_calls:[];if(v==="assistant"&&!w&&k.length){a(i,k);continue}if(v==="assistant"&&!w)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 b=document.createElement("div");b.className="chat-msg__role",b.textContent=v==="assistant"?p||"assistant":v;const D=document.createElement("span");D.className="chat-msg__ts",D.hidden=!0,y.appendChild(b),y.appendChild(D);const j=document.createElement("div");j.className="chat-msg__body",v==="assistant"?vn(j,w||"","",!0):j.textContent=w||"",_.appendChild(y),_.appendChild(j),i.appendChild(_),a(i,k)}const h=e.querySelector(".tool-card__body");h?h.appendChild(i):e.appendChild(i)}function sp(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 c=document.createElement("span");c.className="tool-card__name",c.textContent=n||"Progress";const u=document.createElement("span");u.className="tool-card__pill tool-card__pill--busy",u.textContent="running",i.appendChild(s),i.appendChild(c),i.appendChild(u),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 wc(e,t){if(!e.transcript.current||!t)return;const n=sp(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),c=n.querySelector(".tool-card__progress-bar");c&&(c.style.width=s+"%");const u=n.querySelector(".tool-card__progress-pct");u&&(u.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 ap(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 Cc=40,cp=120;let ii=0;function zr(e){ii++,e._pendingTranscriptChunk&&(cancelAnimationFrame(e._pendingTranscriptChunk),e._pendingTranscriptChunk=null),e._suspendScrollPin=!1,e._insertAnchor=null}function kc(e){return new Promise(t=>{function n(){if(!e._pendingTranscriptChunk)return t();requestAnimationFrame(n)}n()})}function Or(e){zr(e)}function lp(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 Yn(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||lp(e,n);St({id:n.toolCallId,name:n.name,ok:n.ok,args:r,result:n.content||""},t)}else if(hc(n)){const r=Ed(e.messages,n);vr(n.content,t,e,{persist:!1,ts:n.ts,onRetry:r&&typeof e._retryFailedTurn=="function"?()=>e._retryFailedTurn(r):null})}else Zn(n,!1,t,e);up(t,n)}function up(e,t){const n=e.transcript.current;if(!n)return;const r=e._lastInsertedRow;if(!r||r.parentNode!==n)return;const o=xc(t);o&&(r._rowKey=o)}function Sc(e){return!(e.role==="assistant"&&!String(e.content||"").trim()&&!String(e.reasoning||"").trim())}const si=".tool-card--ask-user[data-auth-call-id], .tool-card--authorization[data-auth-call-id]";function dp(e){if(e)for(const t of Array.from(e.children))t.matches(si)||t.remove()}function pp(e,t,n){const r=t.transcript.current;if(!r)return;zr(t);const o=ii,i=[];for(let a=0;a<e.messages.length;a++)Sc(e.messages[a])&&i.push(a);if(!i.length){jr(n,r),pn(t),On(t),ot(e,null,t);return}t._suspendScrollPin=!0;const s=Math.max(0,i.length-Cc),c=r.children.length;t._insertAnchor=null;try{for(let a=s;a<i.length;a++)Yn(e,t,e.messages[i[a]])}finally{t._suspendScrollPin=!1}if(On(t),s===0){t._insertAnchor=null,jr(n,r),pn(t),On(t),ot(e,null,t);return}const u=r.children[c]||null;t._insertAnchor=u,t._pendingTranscriptChunk=requestAnimationFrame(()=>Tc(e,t,{order:i,index:s-1,token:o,expanded:n}))}function Tc(e,t,n){if(t._pendingTranscriptChunk=null,n.token!==ii){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 c=0;t._suspendScrollPin=!0;try{for(;n.index>=0&&c<Cc;){const u=e.messages[n.order[n.index]];n.index--;const a=r.childElementCount,d=t._insertAnchor?t._insertAnchor.previousElementSibling:r.lastElementChild;if(Yn(e,t,u),r.childElementCount>a){const p=t._insertAnchor?t._insertAnchor.previousElementSibling:r.lastElementChild;p&&p!==d&&(t._insertAnchor=p)}c++}}finally{t._suspendScrollPin=!1}if(o?r.scrollTop=r.scrollHeight:r.scrollTop=i+(r.scrollHeight-s),n.index>=0){t._pendingTranscriptChunk=requestAnimationFrame(()=>Tc(e,t,n));return}t._insertAnchor=null,jr(n.expanded,r),pn(t),t.pinnedToBottom.current&&On(t),ot(e,null,t)}function jr(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(si);if(n.length){for(const r of n)r.parentNode&&r.parentNode.removeChild(r);for(const r of n)t.appendChild(r)}}function fp(e,t,n){const r=t.transcript.current;if(!r)return;const o=e.messages.length;if(o<=n)return;if(n===0){zr(t),Ec(e,t);return}const i=t._insertAnchor;t._insertAnchor=null;for(let s=n;s<o;s++){const c=e.messages[s];c.role==="assistant"&&!String(c.content||"").trim()&&!String(c.reasoning||"").trim()||Yn(e,t,c)}i&&i.parentNode===r&&(t._insertAnchor=i),pn(t),Ye(t,!0),ot(e,null,t)}const ys=new WeakMap;let hp=0;function vs(e,t){const n=e&&e.className;return typeof n=="string"&&(" "+n+" ").indexOf(" "+t+" ")>=0}function Ac(e){return!!(e&&e.dataset&&e.dataset.authCallId)}function xn(e){return!e||e.nodeType!==1||Ac(e)||cc(e)?!1:vs(e,"chat-msg")||vs(e,"tool-card")}function mp(e){const t=e&&e.props||{};return(t.projectDir||"")+"::"+(t.chatId||"")}function xc(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=ys.get(e);return t||(t="obj:"+ ++hp,ys.set(e,t)),t}function gp(e){if(!e)return!1;for(const t of e.children)if(xn(t))return!0;return!1}function _p(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 u of Array.from(r.children)){if(!xn(u))continue;const a=u._rowKey;a&&(i.has(a)?(u.remove(),o.removed++):i.set(a,u))}let s=null;for(const u of r.children){if(xn(u)){s=u;break}if(Ac(u)){s=u;break}}const c=new Set;for(let u=0;u<n.length;u++){const a=e.messages[n[u]],d=xc(a);if(!d)continue;c.add(d);let p=i.get(d)||null;if(p)o.reused++;else{const f=new Set(r.children);Yn(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 u of Array.from(r.children)){if(!xn(u))continue;const a=u._rowKey;a&&c.has(a)||(u.remove(),o.removed++)}return o}function uo(e){try{return JSON.stringify(e??null)}catch{return""}}function yp(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:uo([(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:uo([r.files||[],!!r.enabled,!!r.explicit,!!r.projectLocked]),skills:uo([(o.items||[]).map(i=>[i&&i.id,!!i.disabled,!!i.chatDisabled]),!!o.enabled,!!o.projectLocked])}}function vp(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(Sp())}else r&&r.parentNode===n&&r.remove()}function bp(e,t,n){const r=t.transcript.current;if(!r)return;const o=yp(e,n),i=t._cardSigs||(t._cardSigs={}),s=c=>!!(r.querySelector&&r.querySelector(c));if(o.setup==="hidden"){const c=t.setupCard.current;c&&c.parentNode&&c.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 c=kp(t,e);yn(r,c,gt.setup),t.setupCard.current=c,i.setup=o.setup}(i.sys!==o.sys||!s('[data-sys-prompt="1"]'))&&(gc(t,e.systemPrompt),i.sys=o.sys),(i.tools!==o.tools||!s('[data-tools-card="1"]'))&&(pd(t,e),i.tools=o.tools),(i.agentFiles!==o.agentFiles||!s('[data-agent-files-card="1"]'))&&(fd(t,e),i.agentFiles=o.agentFiles),(i.skills!==o.skills||!s('[data-skills-card="1"]'))&&(hd(t,e),i.skills=o.skills),ud(t),vp(t,n)}function Ec(e,t){if(!t.transcript.current)return;const n=ap(t.transcript.current);zr(t);const r=mp(e);t._transcriptKey!==r&&(t._transcriptKey=r,t._cardSigs={},t._toolTreeCollapsed=null,dp(t.transcript.current),t._anonToolCalls=[],t.setupCard.current=null);const o=!e.messages.length;if(bp(e,t,o),pn(t),e.messages.length>=cp&&!gp(t.transcript.current)){pp(e,t,n);return}const i=[];for(let s=0;s<e.messages.length;s++)Sc(e.messages[s])&&i.push(s);_p(e,t,i),jr(n,t.transcript.current),pn(t),i.length&&On(t),ot(e,null,t)}function wp(e){if(!e)return null;for(let t=0;t<e.children.length;t++){const n=e.children[t];if(!cc(n))return n}return null}function Cp(e,t,n){const r=t.transcript.current;if(!r||!Array.isArray(n)||!n.length)return!1;const o=wp(r);if(!o)return!1;const i=r.scrollHeight,s=r.scrollTop;t._insertAnchor=o,t._suspendScrollPin=!0;const c=r.childElementCount;try{for(const u of n)Yn(e,t,u)}finally{t._suspendScrollPin=!1,t._insertAnchor=null}return r.childElementCount===c?!1:(r.scrollTop=s+(r.scrollHeight-i),ot(e,null,t),!0)}function kp(e,t){const n=dd();return n._onChange=r=>xd(r,t,e),n}function Sp(){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),Vr(e)}function po(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"},Tp={file:"📄",agent:"🧑🔧",action:"⚡",tool:"🛠️",mcp:"🔌",model:"🤖"},Ap=200,xp=4;let Ve=null,rt=null,Ae=null,an=[],zt=[],fn="",cn=null,lt=0,ft=!1,fo=null,bs="",Pt=null;const Ep=[{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,ln=null,zn=[],ho=null,ws="";async function Ip(e){if(!e)return null;if(e===ws&&ho)return ho;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 ho=n.id,ws=e,n.id}}catch{}return null}function Cs(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 mo(e){const t=[],n=[];for(const r of e)(r.category===Ze.FILES?t:n).push(r);return t.concat(n)}async function Ic(e){if(!e)return[];const t=[],n=await Ip(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=Cs(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!==bs&&(bs=r,fo=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)&&(fo=a.body.files)}catch{}const o=fo||[],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=Cs(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,c=Ve&&Ve.tools;if(c&&Array.isArray(c.catalog))for(const a of c.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)){Ve&&typeof Ve._setCustomActions=="function"?Ve._setCustomActions(a.body.actions):Ve&&(Ve.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 u=Ve&&Ve.chat;return u&&u.modelId&&t.push({id:"model:current",label:u.modelId,subtitle:u.providerId||"model",category:Ze.MODEL,icon:"model",insert:u.modelId,searchText:(u.modelId+" "+(u.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 ai(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>=Ap?!1:(o++,!0));return mo(i)}if(Pt)return mo(t);const n={},r=t.filter(o=>{const i=n[o.category]||0;return n[o.category]=i+1,i<xp});return mo(r)}function ks(e){if(fn)return;const t=document.createElement("div");t.className="at-mention__filter";for(const{key:n,label:r}of Ep){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=ai(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="",ks(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="",ks(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=Tp[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 c=document.createElement("div");c.className="at-mention__subtitle",c.textContent=n.item.subtitle,i.appendChild(c)}r.appendChild(i),r.addEventListener("click",()=>Pc(n.index)),r.addEventListener("mousedown",c=>c.preventDefault()),rt.appendChild(r)}}function Pp(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 Pc(e){const t=zt[e];if(!t||!Ae||!cn)return;const n=Ae,r=n.value.slice(0,cn.start),o=n.value.slice(cn.end);if((t.category===Ze.TOOLS||t.category===Ze.MCP)&&t.params&&Object.keys(t.params.properties).length>0){const c=t.params.properties,u=t.params.required,a=u.length>0?u[0]:Object.keys(c)[0];for(const g of Object.keys(c));const d=c[a]&&c[a].description||"",p=!c[a]||c[a].type==="string"||!c[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,ln={properties:c,required:u},zn=[a],Rc(c,u,[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,Np(),ln=null,zn=[],Ct(),n.dispatchEvent(new Event("input",{bubbles:!0})),n.focus()}function Rc(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 c=document.createElement("button");c.type="button",c.className="at-mention__arg-chip"+(t.indexOf(i)>=0?" is-required":""),c.textContent=i;const u=s&&s.description||"";u&&(c.title=u),c.addEventListener("click",a=>{a.preventDefault(),Rp(i,s)}),vt.appendChild(c)}o||(vt.hidden=!0)}function Rp(e,t){if(!Ae)return;const n=!t||t.type==="string"||!t.type,r=n?" "+e+"=`"+(t.description||"")+"`":" "+e+"= ",o=Ae.value.length;Ae.value=Ae.value.slice(0,o)+r+Ae.value.slice(o),n?Ae.selectionStart=Ae.selectionEnd=o+e.length+3:Ae.selectionStart=Ae.selectionEnd=o+r.length,Ae.dispatchEvent(new Event("input",{bubbles:!0})),Ae.focus(),zn.push(e),ln&&Rc(ln.properties,ln.required,zn)}function Np(){vt&&(vt.innerHTML="",vt.hidden=!0),ln=null,zn=[]}function Ct(){ft=!1,zt=[],cn=null,Pt=null,rt&&(rt.hidden=!0)}function Ss(){const e=Ae;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}cn={start:r,end:t},fn=i,lt=0,i||(Pt=null),zt=ai(i),ft=!0,$n()}function Ts(e){if(!ft)return;if(e.key==="Enter"){const n=Xo(Ae&&Ae.value);if(n&&Ve&&typeof Ve._runRestartCommand=="function"){e.preventDefault(),Ct(),Ve._runRestartCommand(n.reason);return}const r=Pp(Ae&&Ae.value,Ve&&Ve.customActions);if(r&&Ve&&typeof Ve._runCustomAction=="function"){e.preventDefault(),Ct(),Ve._runCustomAction(r);return}}const t=zt;t.length&&(e.key==="ArrowDown"?(e.preventDefault(),lt=Math.min(lt+1,t.length-1),$n(),As()):e.key==="ArrowUp"?(e.preventDefault(),lt=Math.max(lt-1,0),$n(),As()):e.key==="Enter"||e.key==="Tab"?(e.preventDefault(),Pc(lt)):e.key==="Escape"&&(e.preventDefault(),Ct(),Ae&&Ae.focus()))}function As(){if(!rt)return;const e=rt.querySelector(".is-selected");e&&e.scrollIntoView({block:"nearest",behavior:"smooth"})}function xs(e){ft&&(!rt||!Ae||rt.contains(e.target)||Ae.contains(e.target)||Ct())}function Lp(e,t,n,r){Ae=e,rt=t,Ve=n,vt=r||null,vt&&(vt.hidden=!0),ft=!1,an=[],zt=[],fn="",cn=null,lt=0,Pt=null;const o=n.props&&n.props.projectDir;return o&&Ic(o).then(i=>{an=i}).catch(()=>{}),Ae.addEventListener("input",Ss),Ae.addEventListener("keydown",Ts),document.addEventListener("click",xs),()=>{Ae.removeEventListener("input",Ss),Ae.removeEventListener("keydown",Ts),document.removeEventListener("click",xs),Ct(),Ve=null}}function Mp(){const e=Ve&&Ve.props&&Ve.props.projectDir;e&&Ic(e).then(t=>{an=t,ft&&(zt=ai(fn),$n())}).catch(()=>{})}function Op(){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 jp(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 Es(e,t,n,r){return jn("",n,r,{draftAttachments:null})}function Dp(e,t,n,r){jp(e.promptInput.current?e.promptInput.current.value:"",t,n,e,r),En(e)}function Bp(e,t,n={}){const r=n.enterForNewline!==!1,o=e.key==="Enter",i=o&&(e.ctrlKey||e.metaKey),s=o&&e.shiftKey,c=o&&!s&&Va(e.currentTarget&&e.currentTarget.value,n.customActions),u=o&&!s&&Xo(e.currentTarget&&e.currentTarget.value);o&&!e.isComposing&&!Op()&&(i||c||u?(e.preventDefault(),t()):r||s||(e.preventDefault(),t()))}function qp(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 Fp(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 Up(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){kc(e).then(()=>{if(!e.transcript||!e.transcript.current||!qp(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 Nc(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 c=Number.isFinite(e.nextLiveSeq)?e.nextLiveSeq:0;return fetch("/api/chats/"+encodeURIComponent(r)+"/live?projectDir="+encodeURIComponent(n)+"&fromLiveSeq="+c,{signal:s.signal}).then(u=>i?!u.ok||!u.body?(on(e,o,{active:!1,connected:!1,ended:!1,failed:!0}),null):(on(e,o,{active:!0,connected:!0,failed:!1}),u.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 w=Ta(v);if(w){if(w.eventName==="run_end"){Wp(w,t,e,o);return}Hp(w,t,e,o)}}}}catch{}}).finally(()=>{if(i){i=!1,Dn.delete(o);const u=e.liveRun;u&&u.key===o&&!u.ended&&!u.failed&&on(e,o,{active:!1,connected:!1})}}),!0}function Vp(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 Lc(e,t){const{projectDir:n,chatId:r}=e.props||{};return!n||!r?!1:!t||t===n+"::"+r}function Hp(e,t,n,r){if(!t.transcript||!t.transcript.current||!Lc(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:c}=n.props;if(e.eventName!=="live_subscribed"){if(e.eventName==="shell_output"){oi(o,t);return}if(e.eventName==="subagent_event"){bc({eventName:o.kind||"message"},Object.assign({parentCallId:o.parentCallId},o.data||{}),t);return}if(e.eventName==="progress_update"){wc(t,o),zp(t,o);return}if(e.eventName==="authorization_resolved"){Fp(t,o.callId);return}if(e.eventName==="authorization_required"){Kt(t,o.callId,()=>Rt(o,s,c,t,null,n)),ie(t,"authorization required","busy");return}e.eventName==="ask_user_required"&&(Kt(t,o.callId,()=>Mr(o,s,c,t,(u,a)=>ie(t,u,a))),ie(t,"answer required","busy"))}}function Wp(e,t,n,r){if(!Lc(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}),Up(t),n.watchingRun=!1,n.watchingStableTicks=0,n.runSettled=!0,typeof n._setRunningVisible=="function"&&n._setRunningVisible(!1),ie(t,"done","success")}function zp(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 $p(e,t){return!(!e||!t||e.role!==t.role||e.content!==t.content||e.role==="assistant"&&(e.reasoning||"")!==(t.reasoning||""))}function Jp(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 Gp(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 c=-1;if(typeof s.seq=="number"){if(n.has(s.seq))continue;for(n.add(s.seq);i<o.length;){const u=o[i],a=r[u];if(i++,a&&typeof a.seq!="number"&&a.role===s.role){c=u;break}}if(c===-1)for(let u=r.length-1;u>=0;u--){const a=r[u];if(a&&typeof a.seq!="number"&&$p(a,s)){c=u;break}}}c>=0?r[c]=s:r.splice(Zp(r,s.seq),0,s)}return r}function Kp(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 Zp(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 Mc=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>Mc)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 Yp(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 Is(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),c=r.slice(i);return s.endsWith(`
|
|
47
|
-
|
|
48
|
-
`)?s=s.slice(0,-2):c.startsWith(`
|
|
49
|
-
|
|
50
|
-
`)&&(c=c.slice(2)),s+c}function Xp(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 Ro(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 Qp(e){const t=Ro(e);return t&&t.attachment?t.attachment.dataUrl:null}function Ps(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 ef(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 c=r.length-s,u=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 c<=d?Object.assign({},a,{__annotationStart:d+u}):i>=f?a:Object.assign({},a,{__annotationStart:-1})})}function tf(e,t={}){if(!e||typeof e.toDataURL!="function")throw new Error("Annotation canvas is unavailable.");const n=Number.isFinite(t.limit)?t.limit:Mc,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 c=Math.min(.9,Math.max(.1,Math.sqrt(n/i.length)*.9)),u=Math.max(1,Math.floor(o.width*c)),a=Math.max(1,Math.floor(o.height*c));if(u===o.width&&a===o.height)break;const d=r();d.width=u,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,u,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 nf=100,rf=48,of=nf;function Rs(){return{offset:0,beforeSeq:null,hasMore:!0,loading:!1,total:null,firstSeq:null}}function sf(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 af(e,t){return!e||e.loading||!e.hasMore||e.beforeSeq===null?!1:t<rf}function br(e,t,n){return e.reconnect&&e.reconnect.active&&ui(e),e.streaming=!1,e.watchingRun=!1,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1),di(e,t,Object.assign({retry:!0,manualRetry:!0},n||{}))}function Ns(e,t,n){return!e.autoRetry||n&&n.manualRetry||n&&n.retry?!1:(ie(t,"auto-retrying…","busy"),di(e,t,Object.assign({},n,{retry:!0,manualRetry:!1})).catch(()=>{}),!0)}function cf(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 Ls(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),ie(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:w}=await p.read();if(w)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"?oi({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 c;try{if(c=await s(),c.status===409&&c.body&&c.body.code==="EAUTH_REQUIRED"){let a=null;await Rt(c.body,r,o,n,async()=>{a=await s()},t)==="deny"?c={status:403,body:{ok:!1,code:"EDENIED",error:"user denied"}}:c=a}}catch(a){St({id:i,name:"shell",args:{cmd:e},ok:!1,result:{error:String(a)}},n),ie(n,"shell error","error"),n.sendBtn.current&&(n.sendBtn.current.disabled=!1);return}const u=c.body||{};St({id:i,name:"shell",ok:!!u.ok,result:u},n),c.status===403?ie(n,"shell tool is disabled for this project","error"):ie(n,u.ok?"shell exit "+(u.exitCode??0):"shell failed: "+(u.error||u.code||""),u.ok?"success":"error"),n.sendBtn.current&&(n.sendBtn.current.disabled=!1)}async function lf(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},c=Xt({id:"pending",name:"subagent",args:s},r);ie(r,"running agent "+e+"…","busy"),r.sendBtn.current&&(r.sendBtn.current.disabled=!0),typeof n._setRunningVisible=="function"&&n._setRunningVisible(!0);let u;try{u=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){c&&c.isConnected&&c.remove(),St({id:null,name:"subagent",args:s,ok:!1,result:{error:String(f)}},r),ie(r,"agent error","error"),r.sendBtn.current&&(r.sendBtn.current.disabled=!1),typeof n._setRunningVisible=="function"&&n._setRunningVisible(!1);return}const a=u.body||{},d=a.id||a.toolCall&&a.toolCall.id||null;c&&c.isConnected&&(d?c.dataset.toolId=String(d):a.ok||c.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]),Zn(f,!1,r,n),ot(n,null,r)}u.status===403?ie(r,"subagent tool is disabled for this project","error"):a.ok?ie(r,"agent "+e+" done","success"):ie(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 uf(e,t,n,r,o,i){const{projectDir:s,chatId:c}=r.props;if(!s||!c||!e)return;const u=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:u},o),ie(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(Mu({projectDir:s,chatId:c,callId:a,serverId:e,toolName:t,args:u}))})}let p;try{if(p=await d(),p.status===409&&p.body&&p.body.code==="EAUTH_REQUIRED"){let h=null;p=await Rt(p.body,s,c,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:u,ok:!1,result:{error:String(h)}},o),ie(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?ie(o,"MCP tool is disabled","error"):!p||p.status!==200?ie(o,"MCP failed: "+(f.error||f.code||"HTTP "+(p&&p.status)),"error"):ie(o,"MCP "+(n||t)+" done","success"),o.sendBtn.current&&(o.sendBtn.current.disabled=!1)}async function Oc(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),c=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:c}},n),ie(n,"restarting app…","busy"),n.sendBtn.current&&(n.sendBtn.current.disabled=!0);let u;try{u=await H("/api/restart",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:c,delayMs:1e3})})}catch(d){u={status:500,body:{ok:!1,error:String(d)}}}const a=u.body||{};St({id:s,name:"restart_app",ok:u.status===200&&a.ok!==!1,result:a},n),u.status===200&&a.ok!==!1?ie(n,"restart requested","success"):(ie(n,"restart failed: "+(a.error||a.code||"HTTP "+u.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),ie(n,"running "+(e.label||e.id)+"…","busy"),n.sendBtn.current&&(n.sendBtn.current.disabled=!0);async function c(){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 u;try{if(u=await c(),u.status===409&&u.body&&u.body.code==="EAUTH_REQUIRED"){let f=null;u=await Rt(u.body,r,o,n,async()=>{f=await c()},t)==="deny"?{status:403,body:{ok:!1,error:"user denied"}}:f}}catch(f){u={status:500,body:{ok:!1,error:String(f)}}}const a=u&&u.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:u.status===200&&a.ok!==!1,result:d},n),u.status===200&&a.ok!==!1?ie(n,(e.label||e.id)+" done","success"):ie(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 ci(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 jc(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 df(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 Dc(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 df(r,o,{limit:of,beforeSeq:n.beforeSeq});if(!i||!Array.isArray(i.messages)||!i.messages.length)return n.hasMore=!1,n.beforeSeq=null,!0;typeof Or=="function"&&Or(t);const s=e.seenSeqs,c=i.messages.filter(a=>typeof a.seq!="number"?!0:s.has(a.seq)?!1:(s.add(a.seq),!0)),u=Cp(e,t,c);if(c.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=c.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=c.length?c[0].seq:n.firstSeq,u}catch{return!1}}async function pf(e,t,n){if(!n||!e||!t||n.loading)return!1;n.loading=!0;try{return await Dc(e,t,n)}finally{n.loading=!1}}async function ff(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 kc(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 Dc(e,t,n),n.beforeSeq===i)return;await new Promise(s=>setTimeout(s,0))}}finally{n.loading=!1}}async function Ms(e,t,n){const{projectDir:r,chatId:o}=e.props,i=await jc(r,o,0);return i?(e.messages=i.messages,e.costSnapshot=ti(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 hf(e,t,n,r){if(!Array.isArray(r))return null;e.transcriptNextSeq=n;const o=e.messages,i=o.length,s=Gp(e,r);if(s===o)return"appended";e.messages=s;const c=Kp(o,s);return c==="render"?e._renderTranscript&&e._renderTranscript():c==="append"&&fp(e,t,i),"appended"}async function li(e,t,n){const{projectDir:r,chatId:o}=e.props,i=Jp(e);if(n<i)return Ms(e,t,n);if(n===i)return e.transcriptNextSeq=n,"stable";const s=await jc(r,o,i);if(!s)return null;if(typeof s.nextSeq=="number"&&s.nextSeq<i)return Ms(e,t,s.nextSeq);const c=hf(e,t,typeof s.nextSeq=="number"?s.nextSeq:n,s.messages),u=ti(s);return u&&(e.costSnapshot=u,e.attributedCost=0),ot(e,null,t),c}function mf(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…"}ie(t,"connection lost — reconnecting…","busy"),typeof e._kickPoll=="function"&&e._kickPoll()}function ui(e){const t=e.reconnect;t.stopped=!0,t.active=!1,t.attempts=0}async function Bc(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 c of i.body.pending)if(!(!c||!c.callId))if(s++,c.tool==="ask_user"&&c.args){const u=Object.assign({},c.args,{callId:c.callId,tool:c.tool});Kt(t,c.callId,()=>{o()&&Mr(u,n,r,t,(a,d)=>ie(t,a,d))})}else Kt(t,c.callId,()=>{o()&&Rt(c,n,r,t,null,e)});return s}async function gf(e,t){const{projectDir:n,chatId:r}=e.props;if(!n||!r)return;ie(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{ie(t,"cancel failed — server unreachable","error");return}if(o.status!==200){ie(t,"cancel failed: HTTP "+o.status,"error");return}bd(t),ui(e),e.streaming=!1,e.watchingRun=!1,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1),t.sendBtn.current&&(t.sendBtn.current.disabled=!1),await Fc(e,t),ie(t,"cancel requested","success")}function qc(e){const t=e&&e.streamAbort;if(!t)return!1;e.streamAbort=null;try{t.abort()}catch{}return!0}async function di(e,t,n){const{content:r,attachments:o,clearComposerDraft:i,setImageAttachments:s,retry:c,manualRetry:u}=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,w=Vt(v);if(!g&&!w.length){t.status.current&&(t.status.current.textContent="type something or add an image");return}if(e.streaming){ie(t,"wait for the current response to finish","busy");return}if(g.startsWith("/shell ")){const q=g.slice(7).trim();if(q)return Ls(q,e,t)}const k=Xo(g);if(k)return Oc(k.reason,e,t,{clearComposerDraft:i,setImageAttachments:s});const _=Ua(g);if(_){const q=_.toolName,R=_.rest,G=Va(g,e.customActions);if(G)return No(G,e,t);if(R&&Array.isArray(e.agents)&&e.agents.some(fe=>fe&&fe.name===q))return lf(q,R,e,t);const pe=((e.tools||{catalog:[]}).catalog||[]).find(fe=>fe&&fe.name===q);if(pe){if(String(q).startsWith("mcp__")){const fe=String(q).split("__");if(fe.length>=3&&pe.serverId){const qe=fe.slice(2).join("__"),Fe=R?Ou(R):null;if(Fe)return uf(pe.serverId,qe,q,e,t,Fe)}}else if(q==="shell"&&R)return Ls(R,e,t)}}if(!f||!h){const q=e.providers.length?"pick a model":"add a provider in Settings → Providers";ie(t,q,"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),ie(t,"preparing message…","busy");try{if(e._persistedModelPair!==h+"|"+f&&await fc({providerId:h,modelId:f},e,t)===!1)throw new Error("model settings could not be saved");if(!c&&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),ie(t,"Could not prepare message — your draft is unchanged. Try sending again.","error");return}ie(t,"streaming…","busy"),c||(t.promptInput.current&&(t.promptInput.current.value=""),s&&s([]),t.imageInput.current&&(t.imageInput.current.value=""),t._autoresize());const y=c?null:{role:"user",content:g,attachments:w,ts:new Date().toISOString()};c||(e.messages=e.messages.concat([y]),Zn(y,!1,t,e),e._updateSetupVisibility&&e._updateSetupVisibility());const b=Cu(),D=(()=>{const q=e.thinkingLevel||"";return q==="__custom__"?t.thinkingLevelCustom&&t.thinkingLevelCustom.current&&t.thinkingLevelCustom.current.value.trim()||"":q})();let j;const x=new AbortController;e.streamAbort=x;try{j=await fetch("/api/chats/"+encodeURIComponent(d)+"/messages/stream",{method:"POST",headers:{"Content-Type":"application/json"},signal:x.signal,body:JSON.stringify({projectDir:a,modelId:f,providerId:h,content:g,attachments:w,thinkingLevel:D,maxOutputTokens:e.maxOutputTokens||""})})}catch(q){if(q&&q.name==="AbortError"){e.streamAbort===x&&(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.",G={content:g,attachments:w,clearComposerDraft:i,setImageAttachments:s,retry:c,manualRetry:u};ie(t,"network error","error"),vr(R+" Try again.",t,e,{onRetry:()=>br(e,t,G)}),e.streaming=!1,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1),t.sendBtn.current&&(t.sendBtn.current.disabled=!1),Ns(e,t,G);return}if(!j.ok){let q="";try{q=await j.text()}catch{}let R="HTTP "+j.status;try{const ce=JSON.parse(q);ce&&ce.error&&(R=ce.error)}catch{}if(j.status===409){if(c){ie(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(ce=>ce!==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:w}).catch(()=>{}),ie(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}ie(t,R,"error");const G={content:g,attachments:w,clearComposerDraft:i,setImageAttachments:s,retry:c,manualRetry:u};vr(R,t,e,{onRetry:()=>br(e,t,G)}),e.streaming=!1,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1),t.sendBtn.current&&(t.sendBtn.current.disabled=!1),Ns(e,t,G);return}const X=j.body.getReader(),ne=new TextDecoder("utf-8");let $="",I="",N="",U=null,Z=null,se=null,ae=0,_e=0,ye=0,we=0,Oe=0,Ce=0;function de(){const q={modelId:f,usage:U,cost:Z,streamingMs:se,liveRate:b.rate(U&&U.completionTokens)};return ae>0&&(q.liveCost={known:!0,total:ae,currency:"USD"}),q}function z(){if(!t.transcript.current)return;const q=t.transcript.current.querySelector('[data-live="1"]');if(!q)return;const R=q.querySelector(".chat-msg__meta");if(!R)return;const G=de();_r(R,G,e),ot(e,G,t)}let re=!1,W=!1;function J(q,R){if(q.eventName==="subagent_event"&&R){bc({eventName:R.kind},Object.assign({parentCallId:R.parentCallId},R.data||{}),t);return}if(q.eventName==="shell_output"&&R){oi(R,t);return}if(R&&R.parentTool==="subagent"&&q.eventName==="authorization_required"){Kt(t,R&&R.callId,()=>Rt(R,a,d,t,null,e));return}if(R&&R.parentTool==="subagent"&&q.eventName==="ask_user_required"){Kt(t,R&&R.callId,()=>Mr(R,a,d,t,(G,ce)=>ie(t,G,ce)));return}if(q.eventName==="message"&&typeof R.delta=="string"){I+=R.delta,b.add(R.delta),Dd(R.delta,t,e);const G=performance.now?performance.now():Date.now();G-Ce>120&&(Ce=G,z())}else if(q.eventName==="reasoning"&&typeof R.delta=="string"){N+=R.delta,b.add(R.delta),Bd(R.delta,t,e);const G=performance.now?performance.now():Date.now();G-Ce>120&&(Ce=G,z())}else if(q.eventName==="done"){if(R.usage){const pe=U||{},fe=Number(R.usage.promptTokens),qe=Number(R.usage.completionTokens),Fe=Number(R.usage.cacheReadTokens),ke=Number(R.usage.cacheCreationTokens);isFinite(fe)&&fe>0&&(pe.promptTokens=fe),isFinite(qe)&&qe>0&&(pe.completionTokens=qe),isFinite(Fe)&&Fe>0&&(pe.cacheReadTokens=Fe),isFinite(ke)&&ke>0&&(pe.cacheCreationTokens=ke),U=pe}Z=R.cost||Z,se=typeof R.streamingMs=="number"?R.streamingMs:se,_e=0,ye=0,ae=0,z();const G=e.chat;(!G||!G.title||G.title==="New chat")&&Ad(e,t)}else if(q.eventName==="usage_input"){const G=Number(R&&R.promptTokens);isFinite(G)&&G>0&&(U=U||{},(!U.promptTokens||G>U.promptTokens)&&(U.promptTokens=G),_e=G,z());const ce=Number(R&&R.cacheReadTokens),pe=Number(R&&R.cacheCreationTokens);isFinite(ce)&&ce>0&&(U=U||{},U.cacheReadTokens=ce),isFinite(pe)&&pe>0&&(U=U||{},U.cacheCreationTokens=pe),isFinite(ce)&&ce>0&&(we=ce),isFinite(pe)&&pe>0&&(Oe=pe)}else if(q.eventName==="usage_output"){const G=Number(R&&R.completionTokens);isFinite(G)&&G>0&&(U=U||{},U.completionTokens=(U.completionTokens||0)+G,ye+=G,z())}else if(q.eventName==="usage_update"){const G=R&&R.cost;G&&G.known&&typeof G.total=="number"&&G.total>0&&(ae+=G.total,ot(e,de(),t))}else if(q.eventName==="assistant_turn_end"){const G=I,ce=N;if(G.trim()||ce.trim()){po({content:G,reasoning:ce},t);const pe=R.usage||(_e||ye||we||Oe?{promptTokens:_e||void 0,completionTokens:ye||void 0,cacheReadTokens:we||void 0,cacheCreationTokens:Oe||void 0}:void 0),fe=R.cost||void 0;if(e.messages=e.messages.concat([{role:"assistant",content:G,reasoning:ce,ts:new Date().toISOString(),modelId:f,usage:pe,cost:fe}]),t.transcript.current){const qe=t.transcript.current.querySelectorAll(".chat-msg--assistant"),Fe=qe.length?qe[qe.length-1]:null;if(Fe){const ke=Fe.querySelector(".chat-msg__meta");ke&&_r(ke,{modelId:f,usage:pe,cost:fe},e)}}_e=0,ye=0,we=0,Oe=0}I="",N=""}else if(q.eventName==="authorization_required"||q.eventName==="ask_user_required")Kt(t,R&&R.callId,()=>{q.eventName==="authorization_required"?Rt(R,a,d,t,null,e):Mr(R,a,d,t,(G,ce)=>ie(t,G,ce))});else if(q.eventName==="tool_call")cf(e,t,R&&R.name),Xt(R,t);else if(q.eventName==="tool_result")St(R,t);else if(q.eventName==="progress_update"){wc(t,R);const G=R.current!=null&&R.total!=null?Math.round(Number(R.current)/Math.max(1,Number(R.total))*100)+"%":R.status||"running";ie(t,R.title+" "+G,"busy")}else if(q.eventName==="error"){re=!0,_e=0,ye=0;const G={content:g,attachments:w,clearComposerDraft:i,setImageAttachments:s,retry:c,manualRetry:u};vr((R.message||"Request failed")+(R.detail?`
|
|
53
|
-
`+String(R.detail).slice(0,500):""),t,e,{onRetry:()=>br(e,t,G)}),ie(t,"error: "+(R.code||"")+" "+(R.message||""),"error")}}try{for(;;){if(e.props.projectDir!==a||e.props.chatId!==d){W=!0,qc(e);break}const{value:q,done:R}=await X.read();if(R)break;$+=ne.decode(q,{stream:!0});let G;for(;(G=$.indexOf(`
|
|
54
|
-
|
|
55
|
-
`))!==-1;){const ce=$.slice(0,G);$=$.slice(G+2);const pe=Ta(ce);if(!pe)continue;let fe;try{fe=JSON.parse(pe.data)}catch{continue}try{J(pe,fe)}catch(qe){console.error("chat SSE event failed",pe.eventName,qe)}}}}catch(q){W=!!(q&&q.name==="AbortError")||x.signal.aborted,W||(re=!0,_e=0,ye=0,console.error("chat SSE reader failed",q),ie(t,"stream interrupted: "+(q&&q.message?q.message:"connection closed"),"error"))}finally{e.streamAbort===x&&(e.streamAbort=null);try{X.releaseLock()}catch{}t.sendBtn.current&&(t.sendBtn.current.disabled=!1)}if(x.signal.aborted&&(W=!0),W){b.reset(),e.streaming=!1,typeof e._setRunningVisible=="function"&&e._setRunningVisible(!1);return}if(re){po({content:I,reasoning:N},t),b.reset(),mf(e,t,I);return}const he=t.transcript.current?t.transcript.current.querySelector('[data-live="1"]'):null;if(!!(I.trim()||N.trim())){po({content:I,reasoning:N},t);const q=b.rate(U&&U.completionTokens),R={role:"assistant",content:I,reasoning:N,ts:new Date().toISOString(),modelId:f,usage:U||void 0,cost:Z||void 0,streamingMs:se||void 0,liveRate:q};if(e.messages=e.messages.concat([R]),ot(e,null,t),he){const G=he.querySelector(".chat-msg__meta");G&&_r(G,R,e)}}else he&&he.parentNode&&(he.remove(),ot(e,null,t));b.reset();try{const q=await ci(a,d);q&&await li(e,t,q.nextSeq)}catch(q){console.error("chat transcript reconciliation failed",q)}if(t.status.current&&t.status.current.textContent==="streaming…"){const q=U&&(U.promptTokens!=null||U.completionTokens!=null);ie(t,q?"done — "+(U.promptTokens||0)+" in, "+(U.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 _f(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 ci(n,r).catch(()=>null);if(!i)return o.attempts<6?!0:Cn(e,t,"could not reconnect — tap to retry",!0);const s=await li(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,ie(t,"reconnected — syncing…","busy"),!0;const c=e.messages[e.messages.length-1],u=c&&c.role==="tool"&&c.phase==="call";return o.stableTicks=(o.stableTicks||0)+1,!i.running&&!u||!u&&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?ie(t,n,r?"error":"success"):ie(t,"reconnected","success"),!1}async function Fc(e,t){const{chatId:n,projectDir:r}=e.props;if(!(!n||!r)){if(e.reconnect&&e.reconnect.active)return _f(e,t);if(!e.streaming)try{const o=await ci(r,n);if(!o)return;const i=!!o.running,s=e.watchingRun,c=await li(e,t,o.nextSeq),u=c&&c!=="stable";if(u&&e.runSettled&&(e.runSettled=!1),i){const a=r+"::"+n;Nc(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=!u&&!h&&e.messages.length>0&&!p;if((!s||u||g||e.pendingAuthCount>0||e.runSettled)&&(e.pendingAuthCount=await Bc(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,ie(t,"waiting for you…","busy")):g?(ie(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),ie(t,"done","success"))):(ie(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),ie(t,"done","success")):typeof e._setRunningVisible=="function"&&(e.pendingAuthCount=0,e._setRunningVisible(!1),e.watchingStableTicks=0)}catch{}}}function yf(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 Os(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(yf))).filter(Boolean).map(Jn).filter(Boolean);if(!s.length){n("image is too large","error");return}t(c=>{const u=c.concat(s).slice(0,8);return r&&r({draftAttachments:Vt(u)}).catch(()=>{}),u}),n(s.length===1?"image attached":s.length+" images attached","success")}catch{n("could not read image","error")}}function vf(e,t,n){t(r=>{const o=r.filter((i,s)=>s!==e);return n&&n({draftAttachments:Vt(o)}).catch(()=>{}),o})}const bf="fileOrbButton",Lo=!1;function wf(e){const t=e&&e.app;if(!t||typeof t!="object")return Lo;const n=t[bf];return typeof n=="boolean"?n:n==="true"?!0:n==="false"?!1:Lo}const go=Object.freeze({2:8,3:8,4:6.5,5:6});function js(e){const t=Number(e);return!Number.isFinite(t)||t<=2?go[2]+"px":t>=5?go[5]+"px":go[Math.floor(t)]+"px"}const Cf="dictationButton",kf="imageButton",Uc=Object.freeze({dictation:!0,image:!0});function Ds(e,t){return typeof e=="boolean"?e:e==="true"?!0:e==="false"?!1:t}function Sf(e){const t=e&&e.app,n=Uc;return!t||typeof t!="object"?{dictation:n.dictation,image:n.image}:{dictation:Ds(t[Cf],n.dictation),image:Ds(t[kf],n.image)}}function Tf(e,t){return"/api/tools/authorization?projectDir="+encodeURIComponent(e)+(t?"&chatId="+encodeURIComponent(t):"")}function Af(e){const{projectDir:t,chatId:n}=e,[r,o]=A([]),[i,s]=A(""),[c,u]=A(!1),[a,d]=A(!1),[p,f]=A(0),[h,g]=A(0),[v,w]=A(null),[k,_]=A(!1),[y,b]=A([]),[D,j]=A(!1),[x,X]=A([]);P(-1);const[ne,$]=A(()=>({models:[],value:null,pinned:new Set,recent:[],open:!1,providers:[]})),I=P(0),N=We(m=>{m||(I.current+=1),$(L=>L.open===m?L:{...L,open:m})},[]),U=P({projectDir:"",offset:0,total:1/0,loading:!1}),Z=P(!1),se=P([]);function ae(m){se.current=typeof m=="function"?m(se.current):m,o(se.current)}const _e=P("");function ye(m){_e.current=typeof m=="string"?m:"",s(_e.current)}const we=P(null),Oe=P(null),Ce=P(null),de=P(null),z=P(null),re=P(null),W=P(null),J=P(null),he=P(null),Re=P(null),q=P(null),R=P(null),G=P(null),ce=P(null),pe=P(null),fe=P(null),qe=P(null),Fe=P(null),ke=P(null),dt=P(null),Ne=P(!0),it=P(0),pt=P(!1),Je=P(0),st=P(0),Q=P(""),te=P([]),C=P([]),O=P({}),F=P([]),K=P({q:"",provider:"all"}),E=P(null),M=P({catalog:[],filter:null}),ve=P({files:[],enabled:!0,explicit:!1}),xe=P({items:[],enabled:!0,projectLocked:!1}),T=P([]),B=P(null),oe=P([]),Te=P({}),be=P({mode:"ask",allowlist:[],servers:{},tools:{}}),je=P(""),Le=P(""),Qe=P(!0),at=P(!0),[Nt,Xn]=A(Lo),[Lt,el]=A(()=>Object.assign({},Uc)),$r=P(new Set),Qt=P(new Set),Jr=P({active:!1,attempts:0,timer:null,stopped:!1,partialText:""}),Gr=P(null),Kr=P(0),Zr=P(!1),Yr=P({key:"",active:!1,connected:!1,ended:!1,failed:!1}),Xr=P(!1),hi=P(null),mi=P([]),gi=P(null),Qr=P(null);Qr.current||(Qr.current={props:{projectDir:t,chatId:n},_setRunningVisible:d,_kickPoll:()=>{Gr.current&&Gr.current()},get chat(){return hi.current},set chat(m){hi.current=m},get providers(){return mi.current},set providers(m){mi.current=Array.isArray(m)?m:[]},get imageAttachments(){return se.current},set imageAttachments(m){se.current=m},get messages(){return te.current},set messages(m){te.current=m},get models(){return C.current},set models(m){C.current=m},get liveByProvider(){return O.current},set liveByProvider(m){O.current=m},get prompts(){return F.current},set prompts(m){F.current=m},get pickerFilter(){return K.current},set pickerFilter(m){K.current=m},get systemPrompt(){return E.current},set systemPrompt(m){E.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 xe.current},set skills(m){xe.current=m},get mcpServers(){return T.current},set mcpServers(m){T.current=m},get agents(){return oe.current},set agents(m){oe.current=Array.isArray(m)?m:[]},get usedTools(){return $r.current},set usedTools(m){$r.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 Q.current},set _persistedModelPair(m){Q.current=m},get streaming(){return pt.current},set streaming(m){pt.current=m},reconnect:Jr.current,get watchingRun(){return Zr.current},set watchingRun(m){Zr.current=m},get watchingStableTicks(){return Kr.current},set watchingStableTicks(m){Kr.current=m},get liveRun(){return Yr.current},set liveRun(m){Yr.current=m&&typeof m=="object"?m:{key:"",active:!1,connected:!1,ended:!1,failed:!1}},get runSettled(){return Xr.current},set runSettled(m){Xr.current=m},get providerCredit(){return gi.current},set providerCredit(m){gi.current=m},get toolAuth(){return Te.current},set toolAuth(m){Te.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 je.current},set thinkingLevel(m){je.current=m},get maxOutputTokens(){return Le.current},set maxOutputTokens(m){Le.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=Qr.current;S.props={projectDir:t,chatId:n},S.customActions=x,S._setCustomActions=m=>{const L=Array.isArray(m)?m:[];JSON.stringify(S.customActions||[])!==JSON.stringify(L)&&(S.customActions=L,X(L))};const tl=P(null),nl=P(null),eo=P(null);eo.current||(eo.current={back:we,chatName:Oe,chatMeta:Ce,usageSummaryRef:de,usageSummary:de,providerCreditRef:z,setupCard:re,transcript:W,thinkingLevel:J,thinkingLevelCustom:he,maxOutputTokens:Re,promptInput:q,imageInput:R,draftSaveTimer:G,sendBtn:ce,stopBtn:pe,status:fe,jumpBtn:qe,toolsCard:Fe,agentFilesCard:ke,skillsCard:dt,pinnedToBottom:Ne,pendingCount:it,chatSwitcherTrigger:tl,chatSwitcherPop:nl,_autoresize:()=>En({promptInput:q})});const Y=eo.current,rl=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,X(m.body.actions))}catch{}},[t]);function Qn(m){if(!m||typeof m!="object")return;const L=m.chat&&typeof m.chat=="object"?m.chat:null,V=m.tools;if(V&&typeof V=="object"){const ge={};for(const le of["shell","file","subagent","task","webpreview","restart_app","report_progress"])V[le]&&(ge[le]={mode:V[le].mode||"ask",allowlist:Array.isArray(V[le].allowlist)?V[le].allowlist:[]});V.ask_user&&(ge.ask_user={mode:V.ask_user.mode==="off"?"off":"ask"}),Te.current=ge}const ee=m.mcp;if(ee&&typeof ee=="object"){const ge=be.current;be.current={mode:ee.mode||ge.mode,allowlist:Array.isArray(ee.allowlist)?ee.allowlist:ge.allowlist,servers:ee.servers&&typeof ee.servers=="object"?ee.servers:ge.servers,tools:ee.tools&&typeof ee.tools=="object"?ee.tools:ge.tools}}S._chatAuthOverrides=L}S._applyChatAuthResponse=Qn;function ol(m,L,V,ee){return H("/api/chats/"+encodeURIComponent(L),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:m,draft:V||"",draftAttachments:Array.isArray(ee)&&ee.length?ee:null})})}const Ue=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 V=await H("/api/chats/"+encodeURIComponent(n),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(Object.assign({projectDir:t},L))});if(V.status!==200)return fe.current&&(fe.current.textContent="HTTP "+V.status),!1;const ee=Object.keys(L);if(ee.length>0&&ee.every(le=>le==="draft"||le==="draftAttachments")){const le={};for(const Ee of ee)le[Ee]=V.body.chat[Ee];return S.chat=Object.assign({},S.chat,le),!0}return S.chat=V.body.chat,S._persistedModelPair=(V.body.chat.providerId||"")+"|"+(V.body.chat.modelId||""),Eo(Y,S),lo(S,Y),en(),!0},[t,n]);function il(){bn(Y,S)}function en(){const m=S.chat;$(L=>({models:so(S),providers:S.providers.map(V=>V&&V.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 _i(){const m=++I.current,L=S.props&&S.props.projectDir,V=S.chat;$({models:so(S),providers:S.providers.map(ee=>ee&&ee.id).filter(Boolean),value:V&&V.providerId&&V.modelId?{providerId:V.providerId,modelId:V.modelId}:null,pinned:Vn(S),recent:Bt(S),open:!0}),Ma(S).then(ee=>{if(!ee||m!==I.current||!S.props||S.props.projectDir!==L)return;const ge=S.chat;$(le=>le.open?{...le,models:so(S),providers:S.providers.map(Ee=>Ee&&Ee.id).filter(Boolean),value:ge&&ge.providerId&&ge.modelId?{providerId:ge.providerId,modelId:ge.modelId}:le.value,recent:Bt(S)}:le)})}S._onChatChanged=()=>il(),S._onLiveModels=()=>{bn(Y,S),en()},S._openModelPicker=()=>{_i()},S._onRefreshAllProviders=()=>rs(S),S._updateToolsCard=()=>{if(Y.toolsCard.current&&Y.toolsCard.current.parentNode){const m=ei(S);Y.toolsCard.current.parentNode.replaceChild(m,Y.toolsCard.current),Y.toolsCard.current=m}},S._runCustomAction=m=>No(m,S,Y),S._runRestartCommand=m=>Oc(m,S,Y,{clearComposerDraft:()=>Es(t,n,Y,Ue),setImageAttachments:ae});const yi=We(async()=>{try{await di(S,Y,{clearComposerDraft:()=>Es(t,n,Y,Ue),setImageAttachments:ae})}finally{ye(Y.promptInput.current?Y.promptInput.current.value:"")}},[t,n,Ue]),sl=We((m,L)=>{vd(m,L,S,Y,Ue),g(V=>V+1)},[Ue]),al=We((m,L)=>{Cd(m,L,S,Y,Ue),g(V=>V+1)},[Ue]),cl=We(m=>{gd(m,S,Y,Ue,()=>yr(S,Y)),g(L=>L+1)},[Ue]),ll=We(m=>{_d(m,S,Y,Ue,()=>yr(S,Y)),g(L=>L+1)},[Ue]),ul=We((m,L)=>{m&&(yd(m,L,S,Y,Ue,()=>yr(S,Y)),g(V=>V+1))},[Ue]),dl=We(()=>gf(S,Y),[t,n]),vi=We((m,L)=>{const V=m&&typeof m=="object"?m.providerId:m,ee=m&&typeof m=="object"?m.modelId:L;if(!V||!ee||(N(!1),S.chat&&S.chat.providerId===V&&S.chat.modelId===ee))return;Oa(S,V,ee);const ge=Object.assign({},S.chat,{providerId:V,modelId:ee});S.chat=ge,$(le=>({...le,value:{providerId:V,modelId:ee},recent:Bt(S),open:!1})),bn(Y,S),lo(S,Y),Ue({providerId:V,modelId:ee})},[Ue]);S._onPickerPick=vi,S._updateChat=Ue;const bi=We(()=>{Ec(S,Y),Io(ps(S),Y)},[]);S._renderTranscript=bi,S._retryFailedTurn=m=>br(S,Y,m),S._updateSetupVisibility=()=>fs(S,Y),S._toggleTool=sl,S._toggleToolGroup=al,S._toggleAgentFiles=cl,S._toggleSkills=ll,S._toggleSkill=ul,S._saveToolAuth=async(m,L,V)=>{const ee=t;if(!ee||!n)return;const ge=L==null?null:{mode:L,allowlist:V||[]},le=await Xu(ee,n,{native:{[m]:ge}});le.status===200&&le.body&&(Qn(le.body),S._updateToolsCard&&S._updateToolsCard(),f(Ee=>Ee+1))},S._saveMcpAuth=async m=>{const L=t;if(!L||!n||!m||typeof m!="object")return;const V=await Qu(L,n,m);V.status===200&&V.body&&(Qn(V.body),S._updateToolsCard&&S._updateToolsCard(),f(ee=>ee+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,V]=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),V.status===200&&Array.isArray(V.body.tools)&&(M.current=Object.assign({},M.current,{catalog:V.body.tools})),g(ee=>ee+1),S._updateToolsCard&&S._updateToolsCard()},S._startMcpServer=async m=>{if(!t||!m||v)return!1;w(m),S._mcpStartBusyServerId=m;try{const V=await S._reloadMcpServer(m);return await S._reloadMcpServerRefresh(),V}finally{S._mcpStartBusyServerId=null,w(null)}},ue(()=>{let m=!1;async function L(){if(!(!t||!n))try{const[V,ee,ge,le,Ee,Ie,Pe,Mt,At,er]=await Promise.all([H("/api/chats/"+encodeURIComponent(n)+"?projectDir="+encodeURIComponent(t)),Gl(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)),Go({force:!0}).catch(()=>null)]);if(m)return;if(V.status!==200){fe.current&&(fe.current.textContent="chat not found"),en();return}const De=V.body.chat;S.chat=De;const tr=er&&er.app||{};S.enterForNewline=typeof tr.enterForNewline=="boolean"?tr.enterForNewline:!0,S.autoRetry=typeof De.autoRetry=="boolean"?De.autoRetry:typeof tr.autoRetry=="boolean"?tr.autoRetry:!0,Xn(wf(er)),el(Sf(er)),Q.current=(De.providerId||"")+"|"+(De.modelId||""),te.current=le.status===200?le.body.messages||[]:[],S.costSnapshot=le.status===200?ti(le.body):null,S.attributedCost=0,B.current=Rs(),sf(B.current,le.status===200?{messages:te.current,total:le.body.total,hasMore:le.body.hasMore,beforeSeq:le.body.beforeSeq}:{messages:[],total:0,hasMore:!1});{const Se=new Set;for(const ht of te.current)typeof ht.seq=="number"&&Se.add(ht.seq);Qt.current=Se}Je.current=le.status===200&&le.body&&typeof le.body.nextSeq=="number"?le.body.nextSeq:Qt.current.size?Math.max(...Qt.current)+1:0,st.current=0,C.current=ee&&Array.isArray(ee.models)?ee.models:[],S.providers=ge.status===200?ge.body.providers||[]:[],O.current={};for(const Se of C.current){if(!Se||!Se.id||!Se.provider)continue;const ht=O.current[Se.provider]||(O.current[Se.provider]=[]),xt={id:Se.id,label:Se.label,contextWindow:Se.contextWindow};Se.thinking&&(xt.thinking=Se.thinking),ht.push(xt)}K.current={q:"",provider:"all"},F.current=Ee.status===200?Ee.body.prompts||[]:[],E.current=Ie.status===200?Ie.body:null,M.current={catalog:[],filter:Array.isArray(De.tools)?De.tools.slice():null};const wi=Ie.status===200?Ie.body.projectAgentFiles:null,fl=Ie.status===200&&typeof Ie.body.agentFilesEnabled=="boolean"?Ie.body.agentFilesEnabled:wi===!1?!1:typeof De.agentFiles=="boolean"?De.agentFiles:!0,hl=Ie.status===200&&Array.isArray(Ie.body.agentFilesAvailable)?Ie.body.agentFilesAvailable:Array.isArray(Ie.body&&Ie.body.agentFiles)?Ie.body.agentFiles:[];ve.current={files:hl.map(Se=>Se.name),enabled:fl,explicit:typeof De.agentFiles=="boolean",projectLocked:wi===!1};const Ci=Ie.status===200?Ie.body.projectSkills:!0,ml=Ie.status===200&&Array.isArray(Ie.body.skills)?Ie.body.skills:[];xe.current={items:ml.map(Se=>({id:Se.id,name:Se.name,description:Se.description,disabled:!!Se.disabled,chatDisabled:!!Se.chatDisabled})),enabled:Ci!==!1&&(typeof Ie.body.skillsEnabled=="boolean"?Ie.body.skillsEnabled:De.skills!==!1),projectLocked:Ci===!1},T.current=Pe.status===200&&Array.isArray(Pe.body.servers)?Pe.body.servers:[],oe.current=Mt.status===200&&Array.isArray(Mt.body.agents)?Mt.body.agents:[],X(At.status===200&&Array.isArray(At.body.actions)?At.body.actions:[]);try{const Se=await H(Tf(t,n));Se.status===200&&Qn(Se.body)}catch{}if(m||(q.current&&!q.current.value&&typeof De.draft=="string"&&De.draft&&(q.current.value=De.draft,En(Y)),q.current&&ye(q.current.value),Array.isArray(De.draftAttachments)&&De.draftAttachments.length&&ae(De.draftAttachments),Oe.current&&(Oe.current.textContent=De.title||n),S.thinkingLevel=De.thinkingLevel||"",S.maxOutputTokens=De.maxOutputTokens||"",bn(Y,S),Eo(Y,S),ot(S,null,Y),lo(S,Y),en(),m))return;if(g(Se=>Se+1),bi(),B.current&&B.current.hasMore&&B.current.beforeSeq!==null&&ff(S,Y,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(De.tools)?De.tools.slice():null},g(xt=>xt+1),S._updateToolsCard&&S._updateToolsCard())}).catch(()=>{})}(),function(){if(Yo(S))xu(S,Y).catch(()=>{});else{const ht=S.providers.map(xt=>xt&&xt.id).filter(Boolean);ht.length&&Promise.all(ht.map(xt=>pl(xt).catch(()=>{}))).catch(()=>{})}}(),De.running){if(d(!0),S.runSettled=!1,S.watchingStableTicks=0,S.pendingAuthCount=await Bc(S,Y),m||S.props.projectDir!==t||S.props.chatId!==n)return;S.pendingAuthCount>0&&(S.watchingRun=!0,ie(Y,"waiting for you…","busy")),Nc(S,Y)}else S.pendingAuthCount=0,d(!1);fs(S,Y),Io(ps(S),Y)}catch{fe.current&&(fe.current.textContent="load failed")}}return L(),()=>{m=!0}},[t,n]);async function pl(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 V=Array.isArray(L.body&&L.body.models)?L.body.models:[];return O.current=Object.assign({},O.current,{[m]:V}),bn(Y,S),en(),{provider:m,ok:!0,count:V.length}}return ue(()=>{function m(V){const ee=Y.chatSwitcherPop&&Y.chatSwitcherPop.current,ge=Y.chatSwitcherTrigger&&Y.chatSwitcherTrigger.current;ee&&!ee.hidden&&ge&&!ee.contains(V.target)&&!ge.contains(V.target)&&_(!1)}function L(V){if(V.key==="Escape"){if(c){u(!1);return}N(!1)}}return document.addEventListener("click",m),document.addEventListener("keydown",L),En(Y),()=>{document.removeEventListener("click",m),document.removeEventListener("keydown",L)}},[c]),ue(()=>{const m=W.current;if(!m)return;function L(){if(Lu(Y,m.scrollTop))return;const Pe=Ru(m);Pe&&!Ne.current?(Ne.current=!0,it.current=0,Gt(Y)):!Pe&&Ne.current&&(Ne.current=!1,Gt(Y)),B.current&&af(B.current,m.scrollTop)&&pf(S,Y,B.current).catch(()=>{})}m.addEventListener("scroll",L,{passive:!0});function V(){Vr(Y)}let ee=null;const ge=new Set;function le(Pe){!ee||Pe.nodeType!==1||Pe.parentNode!==m||ge.has(Pe)||(ge.add(Pe),ee.observe(Pe))}if(typeof ResizeObserver<"u"){ee=new ResizeObserver(V),ee.observe(m);for(const Pe of m.children)le(Pe)}let Ee=null;typeof MutationObserver<"u"&&(Ee=new MutationObserver(Pe=>{for(const Mt of Pe)if(!(Mt.type!=="childList"||Mt.target!==m)){for(const At of Mt.removedNodes)At.parentNode!==m&&ge.delete(At)&&ee&&ee.unobserve(At);for(const At of Mt.addedNodes)le(At)}V()}),Ee.observe(m,{childList:!0,subtree:!0,characterData:!0}));function Ie(Pe){Pe&&Pe.target&&Pe.target.tagName==="IMG"&&V()}return m.addEventListener("load",Ie,!0),()=>{m.removeEventListener("scroll",L),m.removeEventListener("load",Ie,!0),Ee&&Ee.disconnect(),ee&&ee.disconnect(),ge.clear(),Ba(Y)}},[t,n]),ue(()=>{$r.current=new Set},[n]),ue(()=>{Qt.current=new Set},[n]),ue(()=>{Ne.current=!0,it.current=0,Gt(Y)},[n,t]),ue(()=>{Kr.current=0},[n,t]),ue(()=>{Yr.current={key:"",active:!1,connected:!1,ended:!1,failed:!1}},[n,t]),ue(()=>{Xr.current=!1},[n,t]),ue(()=>{B.current=Rs(),Je.current=0,st.current=0},[n,t]),ue(()=>()=>{const m=Y.promptInput.current,L=m?m.value:"",V=Vt(se.current);G.current&&(clearTimeout(G.current),G.current=null),t&&n&&(L||V.length)&&ol(t,n,L,V).catch(()=>{}),m&&(m.value="",En(Y)),ye(""),ae([])},[n,t]),ue(()=>()=>{ui(S),Vp(S,t,n),G.current&&(clearTimeout(G.current),G.current=null),qc(S),typeof Or=="function"&&Or(Y)},[t,n]),ue(()=>{if(!t)return;const m={projectDir:t,chatId:n,offset:0,total:1/0,loading:!1};U.current=m,j(!1),Z.current=!1;let L=!1;return _o(t,m,V=>{!L&&U.current===m&&b(V)}),()=>{L=!0}},[t,n]),ue(()=>{if(!t||!n)return;if(!Z.current){Z.current=!0;return}const m=U.current;if(!m||m.projectDir!==t||m.chatId!==n)return;let L=!1;return _o(t,{projectDir:t,offset:0,total:1/0},V=>{L||U.current!==m||!V.length||b(ee=>{const ge=new Map(V.map(Ee=>[Ee&&Ee.id,Ee])),le=V.slice();for(const Ee of ee)!Ee||ge.has(Ee.id)||le.push(Ee);return le})}),()=>{L=!0}},[a,t,n]),ue(()=>{if(!n||!t)return;let m=!1,L=null;function V(){if(m)return;let Pe;Jr.current.active||Zr.current?Pe=1e3:typeof document<"u"&&document.visibilityState==="hidden"?Pe=6e3:Pe=3e3,L=setTimeout(ee,Pe)}async function ee(){m||((Jr.current.active||!pt.current)&&await Fc(S,Y),V())}Gr.current=()=>{m||(L&&(clearTimeout(L),L=null),ee())};function ge(){m||(L&&clearTimeout(L),L=setTimeout(ee,0))}function le(){m||(L&&(clearTimeout(L),L=null),document.visibilityState==="visible"?ge():V())}function Ee(){ge()}function Ie(){document.visibilityState==="visible"&&ge()}return V(),document.addEventListener("visibilitychange",le),window.addEventListener("pageshow",Ee),window.addEventListener("focus",Ie),()=>{m=!0,L&&clearTimeout(L),document.removeEventListener("visibilitychange",le),window.removeEventListener("pageshow",Ee),window.removeEventListener("focus",Ie)}},[n,t]),{state:S,refs:Y,imageAttachments:r,composerText:i,fileEditorOpen:c,runningVisible:a,authStamp:p,toolDataStamp:h,customActions:x,fileOrb:Nt,composerTools:Lt,mcpStartBusy:v,setImageAttachments:ae,setFileEditorOpen:u,setComposerText:ye,picker:ne,send:yi,runCustomAction:m=>No(m,S,Y),refreshCustomActions:rl,updateChat:Ue,onPickerPick:vi,onPickerTogglePin:m=>{m&&(ja(S,m.provider,m.id),en())},onPickerOpen:()=>{Y.maxOutputTokens&&Y.maxOutputTokens.current&&(Y.maxOutputTokens.current.value=S.chat&&S.chat.maxOutputTokens||S.maxOutputTokens||"")},onRefreshAllProviders:()=>rs(S),onPickerOpenChange:m=>{m?_i():N(!1)},onComposerKey:m=>Bp(m,yi,{enterForNewline:S.enterForNewline,customActions:S.customActions}),onComposerInput:()=>{const m=Y.promptInput.current?Y.promptInput.current.value:"";ae(L=>ef(L,_e.current,m)),ye(m),Dp(Y,t,n,Ue)},onComposerPaste:m=>{const L=m.clipboardData&&m.clipboardData.files;L&&Array.from(L).some(V=>/^image\//i.test(V.type||""))&&(m.preventDefault(),Os(L,{setImageAttachments:ae,setChatStatus:(V,ee)=>ie(Y,V,ee),updateChat:Ue}))},onImagePickerChange:m=>{Os(m.currentTarget.files,{setImageAttachments:ae,setChatStatus:(L,V)=>ie(Y,L,V),updateChat:Ue})},onRemoveImage:m=>vf(m,ae,Ue),onJumpToBottom:()=>Nu(Y),onCancelRunning:dl,onToggleAutoRetry:()=>{S.autoRetry=!S.autoRetry,Ue({autoRetry:S.autoRetry})},onBack:()=>{window.location.hash="#/projects"},chatSwitcherOpen:k,setChatSwitcherOpen:_,chatSwitcherList:y,chatSwitcherLoading:D,onToggleChatSwitcher:We(()=>{_(m=>!m)},[]),onChatSwitcherScroll:We(m=>{if(!t)return;const L=U.current;L.projectDir===t&&(L.loading||L.offset>=L.total||(L.loading=!0,j(!0),_o(t,L,V=>{if(U.current!==L||L.projectDir!==t){j(!1);return}L.loading=!1,j(!1),V.length&&b(ee=>{const ge=new Set(ee.map(le=>le&&le.id));return ee.concat(V.filter(le=>le&&!ge.has(le.id)))})})))},[t]),onSwitchChat:We(m=>{_(!1),m&&m!==n&&yt("chat/"+encodeURIComponent(m)+"?projectDir="+encodeURIComponent(t))},[t,n])}}async function _o(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 c=await H("/api/chats?projectDir="+encodeURIComponent(e)+"&offset="+t.offset+"&limit="+o),u=c.status===200&&c.body?c.body.chats||[]:[];if(c.status===200&&c.body&&typeof c.body.total=="number"&&(t.total=c.body.total),t.offset+=u.length,n(u),u.length<o)break}}catch{n([])}}const Bs=["","k","M","G","T","P"];function xf(e){return e.endsWith(".0")?e.slice(0,-2):e}function cr(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<Bs.length-1;)n/=1e3,t+=1;return(t>0&&n<9.95?xf(n.toFixed(1)):String(Math.round(n)))+Bs[t]}const Ef="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",If="M0.5 5.5 6 1 11.5 5.5 10 6 6 2.5 2 6Z",Pf="M0.5 0.5 6 5 11.5 0.5 10 0 6 3.5 2 0Z",Rf=12,Nf=6,Lf=22,Mf=18;function Of(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 qs(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 c=Of(s.body.stdout);return{additions:i.additions+c.additions,deletions:i.deletions+c.deletions}},{additions:0,deletions:0}):null}function jf(e){const{projectDir:t,onOpenFileEditor:n,onOpenPreview:r,customActions:o,onRunCustomAction:i,onRefreshCustomActions:s,orb:c}=e,[u,a]=A(!1),[d,p]=A(!1),[f,h]=A(!1),[g,v]=A(null),w=P(null),[k,_]=A(null),[y,b]=A(null);ue(()=>{if(!d||k)return;let W=!1;return Be(()=>import("./GitModal-3EC_gpJ5.js"),[]).then(J=>{W||_(()=>J.GitModal)}).catch(()=>{W||_(null)}),()=>{W=!0}},[d,k]),ue(()=>{if(!f||y)return;let W=!1;return Be(()=>import("./CliModal-Hs5phmNZ.js"),[]).then(J=>{W||b(()=>J.CliModal)}).catch(()=>{W||b(null)}),()=>{W=!0}},[f,y]);const D=We(async()=>{try{v(await qs(t))}catch{v(null)}},[t]);ue(()=>{let W=!1;return qs(t).then(J=>{W||v(J)}).catch(()=>{W||v(null)}),()=>{W=!0}},[t]),Zo(w,()=>a(!1),u);function j(){const W=!u;a(W),D(),W&&s&&s()}function x(){a(!1),n&&n()}function X(){a(!1),p(!0)}function ne(){p(!1),D()}function $(){a(!1),h(!0)}function I(){a(!1),r&&r()}function N(W){a(!1),i&&i(W)}const U=g?g.additions:0,Z=g?g.deletions:0,se=g!=null,ae=se&&(U>0||Z===0),_e=se&&(Z>0||U===0),ye=se?U+(U===1?" line added, ":" lines added, ")+Z+(Z===1?" line deleted":" lines deleted"):"";function we(W){const J=W==="up"?If:Pf;return c?l("svg",{class:"file-toolbar__chevron file-toolbar__chevron--"+W,viewBox:"0 0 12 6",width:Rf,height:Nf,"aria-hidden":"true"},l("path",{class:"file-toolbar__chevron-side",d:J}),l("path",{class:"file-toolbar__chevron-face",d:J})):l("svg",{viewBox:"0 0 12 6",width:14,height:7},l("path",{d:J,fill:"currentColor"}))}function Oe(W,J){if(!se)return null;const he=W?" file-toolbar__count--3d":"",Re="+"+cr(U),q="−"+cr(Z),R=W?{"--orb-count":J||js(2)}:null;return l("span",{class:"file-toolbar__git-stats",style:R},ae?l("span",{class:"file-toolbar__git-additions"+he},W?l("span",{class:"file-toolbar__count-echo","aria-hidden":"true"},Re):null,l("span",{class:"file-toolbar__count-face"},Re)):null,_e?l("span",{class:"file-toolbar__git-deletions"+he},W?l("span",{class:"file-toolbar__count-echo","aria-hidden":"true"},q):null,l("span",{class:"file-toolbar__count-face"},q)):null)}const Ce=c&&se?Math.max(ae?("+"+cr(U)).length:0,_e?("−"+cr(Z)).length:0):0,de=Ce?js(Ce):null,z=[["side",l("path",{d:kn})],["body",l("path",{d:kn})],["shade",l("path",{d:kn})],["face",l("path",{d:kn})],["sheen",l("path",{d:kn})],["shine",l("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"})]],re=c?l("span",{class:"file-toolbar__plate"},l("span",{class:"file-toolbar__plate-face"},l("span",{class:"file-toolbar__cast","aria-hidden":"true"}),l("span",{class:"file-toolbar__folder file-toolbar__folder--3d"},l("span",{class:"file-toolbar__folder-ground","aria-hidden":"true"}),...z.map(([W,...J])=>l("svg",{class:"file-toolbar__folder-"+W,viewBox:"0 0 22 18",width:Lf,height:Mf,"aria-hidden":"true"},J)),Oe(!0,de)),l("svg",{class:"file-toolbar__defs",viewBox:"0 0 0 0","aria-hidden":"true"},l("linearGradient",{id:"fileToolbarFolderSide",x1:"0",y1:"0",x2:"0.3",y2:"1"},l("stop",{offset:"0","stop-color":"#dbeaff"}),l("stop",{offset:"0.42","stop-color":"#7895c2"}),l("stop",{offset:"1","stop-color":"#344c72"})),l("linearGradient",{id:"fileToolbarFolderBody",x1:"0.12",y1:"0",x2:"0.7",y2:"1"},l("stop",{offset:"0","stop-color":"#f6fbff"}),l("stop",{offset:"0.48","stop-color":"#d9e8fb"}),l("stop",{offset:"1","stop-color":"#9db6d8"})),l("linearGradient",{id:"fileToolbarFolderFace",x1:"0.1",y1:"0",x2:"0.62",y2:"1"},l("stop",{offset:"0","stop-color":"#ffffff"}),l("stop",{offset:"0.45","stop-color":"#eff8ff"}),l("stop",{offset:"0.72","stop-color":"#dcecff"}),l("stop",{offset:"0.9","stop-color":"#c4d9f3"}),l("stop",{offset:"1","stop-color":"#a9c2e2"})),l("radialGradient",{id:"fileToolbarFolderShade",cx:"0.7",cy:"0.86",r:"0.82"},l("stop",{offset:"0","stop-color":"#464d6b","stop-opacity":"0.40"}),l("stop",{offset:"0.42","stop-color":"#4d5474","stop-opacity":"0.17"}),l("stop",{offset:"0.78","stop-color":"#5b6280","stop-opacity":"0.04"}),l("stop",{offset:"1","stop-color":"#5b6280","stop-opacity":"0"})),l("linearGradient",{id:"fileToolbarFolderSheen",x1:"0",y1:"0",x2:"0.35",y2:"0.85"},l("stop",{offset:"0","stop-color":"#ffffff","stop-opacity":"0.95"}),l("stop",{offset:"0.28","stop-color":"#ffffff","stop-opacity":"0.20"}),l("stop",{offset:"0.55","stop-color":"#ffffff","stop-opacity":"0"}))))):l("span",{class:"file-toolbar__folder"},l("svg",{viewBox:"0 0 20 16",width:28,height:22},l("path",{d:Ef,fill:"currentColor"})),Oe(!1));return l("div",{class:"file-toolbar"+(c?" file-toolbar--orb":"")},l("button",{class:"file-toolbar__trigger",type:"button",onClick:j,"aria-label":"File tools"+(ye?". "+ye:""),"aria-haspopup":"true","aria-expanded":String(u),title:"File, git, and CLI tools"+(ye?" — "+ye:"")},c?l("span",{class:"file-toolbar__sheen","aria-hidden":"true"}):null,l("span",{class:"file-toolbar__stack","aria-hidden":"true"},we("up"),re,we("down"))),u&&l("div",{ref:w,class:"file-toolbar__menu",role:"menu"},o&&o.length?[...o.map(W=>l("button",{key:W.id,class:"file-toolbar__menu-item file-toolbar__menu-item--action",role:"menuitem",type:"button",onClick:()=>N(W)},W.label||W.id)),l("div",{class:"file-toolbar__menu-sep",role:"separator"})]:null,l("button",{class:"file-toolbar__menu-item",role:"menuitem",type:"button",onClick:x},l("span",{class:"file-toolbar__menu-icon"},"📝"),l("span",null,"Files")),l("button",{class:"file-toolbar__menu-item",role:"menuitem",type:"button",onClick:I},l("span",{class:"file-toolbar__menu-icon"},"📱"),l("span",null,"Preview")),l("button",{class:"file-toolbar__menu-item",role:"menuitem",type:"button",onClick:X},l("span",{class:"file-toolbar__menu-icon"},"📁"),l("span",null,"Git")),l("button",{class:"file-toolbar__menu-item",role:"menuitem",type:"button",onClick:$},l("span",{class:"file-toolbar__menu-icon"},"🖥"),l("span",null,"Cli"))),d&&k?l(k,{projectDir:t,onClose:ne}):null,f&&y?l(y,{projectDir:t,onClose:()=>h(!1)}):null)}function Df(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 Bf({toolName:e,current:t,onSave:n}){return!t||!t.mode?null:l(nc,{tool:e,name:e,mode:t.mode,allowlist:Array.isArray(t.allowlist)?t.allowlist:[],modes:e==="ask_user"?rc:Hr,namePrefix:"popup-auth",onClear:()=>{n&&n(e,null,[])},onPick:(r,o)=>{n&&n(e,r,o)}})}function qf(e){const{tools:t,mcpServers:n,usedTools:r,agentFiles:o,skills:i,toolAuth:s,mcpAuth:c,onToggleTool:u,onToggleToolGroup:a,onToggleAgentFiles:d,onToggleSkills:p,onToggleSkill:f,onSaveToolAuth:h,onSaveMcpAuth:g,onReloadMcpServer:v,mcpStartBusy:w,autoRetry:k,onToggleAutoRetry:_}=e,[y,b]=A(!1),D=P(null),j=P(null);Zo([D,j],()=>b(!1),y);const[x,X]=A({}),ne=We(()=>{if(!j.current)return;const re=j.current.getBoundingClientRect(),W=j.current.closest(".chat-view__head"),J=W&&W.getBoundingClientRect(),he=window.visualViewport,Re=he?he.height:window.innerHeight,q=(he?he.offsetTop:0)+Re,R=Math.max(re.bottom,J?J.bottom:0),G=Math.max(0,Math.floor(q-R-10)),ce=Math.min(400,Math.floor(Re*.6),G);X({top:Math.floor(R+4)+"px",right:Math.max(10,Math.floor(window.innerWidth-re.right))+"px",maxHeight:ce+"px"})},[]);Df(ne,y);const $=t&&t.catalog||[],I=t&&t.filter,Z=tc($,n||[],I,r||new Set),se=s||{};function ae(re){return re==="allowlist"?"ask":re}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 re of Z){const W=_e[re.id];if(W){const J=se[W]||{mode:"ask"};re.control=l(Bf,{toolName:W,current:{mode:ae(J.mode),allowlist:Array.isArray(J.allowlist)?J.allowlist:[]},onSave:h})}}const ye=c||{mode:"ask",allowlist:[],servers:{},tools:{}};for(const re of Z){if(!re.id.startsWith("mcp-"))continue;const W=re.id.slice(4);re.control=l(ic,{name:re.name,slug:W,servers:ye.servers,shared:ye,namePrefix:"popup-mcp",onClear:()=>{g&&g({servers:{[W]:null}})},onSave:J=>g&&g(J)}),re.serverId&&re.serverId===w&&(re.reloadBusy=!0)}function we(re){const W=re&&re.serverId;!W||!v||v(W)}function Oe(re,W){if(re==="agent-files"){d&&d(W);return}if(re==="skills"){p&&p(W);return}if(a){const J=Z.find(he=>he.id===re);J&&a(J.tools.map(he=>he.id),W)}}function Ce(re,W,J){if(re==="agent-files"){d&&d(J);return}if(re==="skills"){f&&f(W,J);return}u&&u(W,J)}const de=o||{files:[],enabled:!0,projectLocked:!1};de.files.length&&Z.push({id:"agent-files",name:"Agent files",description:de.enabled?"all selected":"off",checked:de.enabled,disabled:!!de.projectLocked,disabledReason:de.projectLocked?"Locked off by Settings → Project.":"",alwaysExpanded:!0,tools:de.files.map(re=>({id:re,name:re,description:"",checked:de.enabled,disabled:!!de.projectLocked}))});const z=i||{items:[],enabled:!0,projectLocked:!1};if(z.items.length){const re=z.items.filter(J=>!J.disabled),W=re.length>0&&re.every(J=>!J.chatDisabled);Z.push({id:"skills",name:"Skills",description:z.enabled?"available metadata":"off",checked:!!z.enabled&&W,disabled:!!z.projectLocked,disabledReason:z.projectLocked?"Locked off by Settings → Project.":"",alwaysExpanded:!0,tools:z.items.map(J=>({id:J.id,name:J.name,description:J.description||"",checked:z.enabled&&!J.disabled&&!J.chatDisabled,disabled:!!z.projectLocked||!!J.disabled,disabledReason:J.disabled?"Disabled in Settings → Project":""}))})}return l("div",{class:"tool-popup"},l("button",{ref:j,class:"chat-view__toolbar-btn tool-popup__trigger",type:"button",onClick:()=>b(!y),"aria-label":"Toggle available tools","aria-haspopup":"true","aria-expanded":String(y),title:"Tool settings"},l("svg",{viewBox:"0 0 24 24",width:16,height:16,"aria-hidden":"true",fill:"currentColor"},l("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&&l("div",{ref:D,class:"tool-popup__layer","aria-label":"Tool settings"},l("div",{class:"tool-popup__popup",role:"dialog","aria-label":"Tool settings",style:x},l("div",{class:"tool-popup__head"},l("span",{class:"tool-popup__title"},"Tools"),l("button",{class:"tool-popup__close",type:"button",onClick:()=>b(!1),"aria-label":"Close"},"×")),l("div",{class:"tool-popup__body"},l(ec,{groups:Z,onToggleGroup:Oe,onToggleTool:Ce,onReloadServer:we,collapsedByDefault:!0,class:"tool-popup__tree"})),l("div",{class:"tool-popup__foot"},l("label",{class:"switch switch--sm"},l("input",{type:"checkbox",role:"switch","aria-checked":String(!!k),checked:!!k,onChange:()=>_&&_()}),l("span",{class:"switch__track","aria-hidden":"true"},l("span",{class:"switch__thumb"})),l("span",{class:"tool-popup__foot-label"},"Auto-retry failed sends")),l("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 Ff({preview:e,onOpen:t,onDismiss:n}){if(!e||!e.thumbnail)return null;const r=e.title||e.url||"Web preview";return l("aside",{class:"webpreview-dock","aria-label":"Web preview"},l("button",{class:"webpreview-dock__open",type:"button",onClick:t,"aria-label":"Open full preview of "+r},l("img",{class:"webpreview-dock__image",src:e.thumbnail,alt:"Preview of "+r,draggable:"false",loading:"lazy",decoding:"async"})),l("button",{class:"webpreview-dock__dismiss",type:"button",onClick:n,"aria-label":"Dismiss preview",title:"Dismiss preview"},l("svg",{viewBox:"0 0 24 24",width:14,height:14,"aria-hidden":"true"},l("path",{d:"M6 6l12 12 M18 6L6 18",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round"}))))}const Zt=[];function Uf(e){return Vc(e),Zt.push(e),e}function Vc(e){const t=Zt.indexOf(e);return t===-1?!1:(Zt.splice(t,1),t===Zt.length)}function Vf(e){return Zt.length>0&&Zt[Zt.length-1]===e}const Hf=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function Fs(e){if(!e||!e.querySelectorAll)return[];const t=[];for(const n of e.querySelectorAll(Hf)){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 Hc(e){const t=e||{},{onClose:n,active:r=!0,escape:o=!0,trapFocus:i=!0,restoreFocus:s=!0,initialFocus:c="none"}=t,u=P(null),a=P(null),d=P(n);return d.current=n,ue(()=>{if(!r)return;const p={};if(Uf(p),a.current=typeof document>"u"?null:document.activeElement,c==="first"){const[h]=Fs(u.current);h?h.focus():u.current&&(u.current.setAttribute("tabindex","-1"),u.current.focus())}function f(h){if(!Vf(p))return;if(o&&h.key==="Escape"){h.stopPropagation(),d.current&&d.current();return}if(!i||h.key!=="Tab")return;const g=Fs(u.current);if(!g.length)return;const v=g[0],w=g[g.length-1],k=document.activeElement,_=!!(u.current&&u.current.contains(k));h.shiftKey?(!_||k===v)&&(h.preventDefault(),w.focus()):(!_||k===w)&&(h.preventDefault(),v.focus())}return document.addEventListener("keydown",f,!0),()=>{document.removeEventListener("keydown",f,!0),Vc(p);const h=a.current;s&&h&&typeof h.focus=="function"&&typeof document<"u"&&document.contains(h)&&h.focus()}},[r,o,i,s,c]),u}const Dr=[{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}],Mo="custom",Oo=64,jo=2048;function Wf({value:e,onChange:t,busy:n}){const r=Dr.some(o=>o.id===e);return l("select",{class:"wp__size-select",value:r?e:Mo,disabled:n,"aria-label":"Capture size",onChange:o=>t&&t(o.currentTarget.value)},Dr.map(o=>l("option",{key:o.id,value:o.id},o.label+" · "+o.width+"×"+o.height)),l("option",{value:Mo},"Custom"))}function zf({preview:e,onClose:t,onRecapture:n}){const r=$f(e&&e.viewport),o=Jf(r,e),[i,s]=A(r),[c,u]=A(String(o.width)),[a,d]=A(String(o.height)),[p,f]=A(""),h=Hc({onClose:()=>{t&&t()}}),g=e&&e.url||"",v=e&&e.title||g||"Web preview",w=e&&e.thumbnail,k=e&&e.width,_=e&&e.height,y=e&&e.sizeBytes,b=e&&e.capturedAt,D=Gf(g);function j(Z){Z.target===Z.currentTarget&&t&&t()}const[x,X]=A(!1);async function ne(Z){if(x||!n)return;const se=i,ae=Z||i||"phone";s(ae),X(!0);try{const _e=await n(ae);(!_e||!_e.ok)&&s(se)}catch{s(se)}finally{X(!1)}}function $(Z){if(f(""),Z===Mo){s(c+"x"+a);return}ne(Z)}function I(Z){Z.preventDefault();const se=Us(c),ae=Us(a);if(!se||!ae){f("Enter width and height from 64 to 2048 px.");return}f(""),ne(se+"x"+ae)}const N=!Dr.some(Z=>Z.id===i),U=[];return k&&_&&U.push(k+" × "+_),e&&e.viewport&&e.viewport.label&&U.push("viewport "+e.viewport.label),y&&U.push(Kf(y)),b&&U.push("captured "+Zf(b)),l("div",{class:"wp__overlay",role:"dialog","aria-modal":"true","aria-label":v,onClick:j},l("div",{class:"wp__sheet",ref:h},l("div",{class:"wp__head"},l("div",{class:"wp__head-text"},l("div",{class:"wp__title",title:v},v),l("div",{class:"wp__title-sub"},D)),l("div",{class:"wp__head-actions"},l("button",{class:"wp__action wp__action--refresh",type:"button",disabled:x,onClick:()=>ne(i),"aria-label":"Refresh preview",title:"Refresh preview"},l("svg",{viewBox:"0 0 24 24",width:14,height:14,"aria-hidden":"true"},l("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"})),l("span",null,"Refresh")),l(Wf,{value:i,busy:x,onChange:$}),l("button",{class:"wp__close",type:"button","aria-label":"Close preview",title:"Close preview",onClick:()=>t&&t()},l("svg",{viewBox:"0 0 24 24",width:18,height:18,"aria-hidden":"true"},l("path",{d:"M6 6 18 18 M18 6 6 18",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round"}))))),N?l("form",{class:"wp__custom-size",onSubmit:I},l("label",{class:"wp__custom-field"},l("span",null,"Width"),l("input",{class:"wp__custom-input",type:"number",inputMode:"numeric",min:Oo,max:jo,step:1,value:c,disabled:x,onInput:Z=>u(Z.currentTarget.value),"aria-label":"Custom preview width"})),l("span",{class:"wp__custom-times","aria-hidden":"true"},"×"),l("label",{class:"wp__custom-field"},l("span",null,"Height"),l("input",{class:"wp__custom-input",type:"number",inputMode:"numeric",min:Oo,max:jo,step:1,value:a,disabled:x,onInput:Z=>d(Z.currentTarget.value),"aria-label":"Custom preview height"})),l("button",{class:"wp__custom-apply",type:"submit",disabled:x},"Apply"),p?l("div",{class:"wp__custom-error",role:"alert"},p):null):null,l("div",{class:"wp__body"},w?l("img",{class:"wp__img",src:w,alt:v,draggable:"false",decoding:"async"}):l("div",{class:"wp__empty"},l("p",null,"No preview available."),l("p",{class:"wp__empty-hint"},"The webpreview call finished without a captured image."))),l("div",{class:"wp__foot"},l("span",{class:"wp__foot-meta"},U.filter(Boolean).join(" · ")),g?l("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 $f(e){return e?Dr.some(t=>t.id===e.id)?e.id:e.width&&e.height?e.width+"x"+e.height:"phone":"phone"}function Jf(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 Us(e){const t=Number(e);return!Number.isInteger(t)||t<Oo||t>jo?0:t}function Gf(e){if(!e)return"";try{return new URL(e).hostname||""}catch{return""}}function Kf(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 Zf(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 Yf({onSubmit:e,onClose:t}){const[n,r]=A(""),[o,i]=A(""),s=P(null),c=Hc({onClose:()=>{t&&t()}});ue(()=>{s.current&&s.current.focus()},[]);function u(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 l("div",{class:"wp__overlay",role:"dialog","aria-modal":"true","aria-label":"Preview a web page",onClick:u},l("div",{class:"wp__sheet wp__prompt-sheet",ref:c},l("div",{class:"wp__head"},l("div",{class:"wp__head-text"},l("div",{class:"wp__title"},"Preview a web page"),l("div",{class:"wp__title-sub"},"Opens in the web-preview viewer")),l("div",{class:"wp__head-actions"},l("button",{class:"wp__close",type:"button","aria-label":"Close",title:"Close",onClick:()=>t&&t()},l("svg",{viewBox:"0 0 24 24",width:18,height:18,"aria-hidden":"true"},l("path",{d:"M6 6 18 18 M18 6 6 18",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round"}))))),l("form",{class:"wp__prompt-form",onSubmit:a},l("label",{class:"label wp__prompt-label",for:"wp-preview-url"},"URL"),l("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"}),l("button",{class:"btn btn--primary wp__prompt-submit",type:"submit"},"Preview"),o?l("div",{class:"wp__prompt-error",role:"alert"},o):null,l("p",{class:"wp__prompt-hint"},"A screenshot is captured using the Inspector debug Chrome."))))}const Xf=15e3,Qf=6e4;async function wr(e,t,n=Xf){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 eh(e){return(e&&typeof e.title=="string"?e.title.trim():"")||"New chat"}function th(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 nh(e){const t=[];let r=1/0;for(;t.length<r;){const o=await wr("/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 rh({open:e,payload:t,onClose:n,onAdded:r,placement:o="bottom"}){const[i,s]=A([]),[c,u]=A(""),[a,d]=A([]),[p,f]=A(""),[h,g]=A(!1),[v,w]=A(!1),[k,_]=A(!1),[y,b]=A(""),D=h||v;if(ue(()=>{if(!e)return;let I=!1;return s([]),u(""),d([]),f(""),g(!0),b("Loading projects…"),wr("/api/projects/registered").then(N=>{if(I)return;if(N.status!==200||!N.body||!Array.isArray(N.body.projects))throw new Error(N.body&&N.body.error||"Could not load projects.");const U=N.body.projects;s(U);const Z=t&&t.projectDir,se=U.find(ae=>ae.path===Z)||U[0];u(se?se.path:""),b(U.length?"":"Add a project before using Draft Craft.")}).catch(N=>{I||(s([]),u(""),b(N&&N.message?N.message:"Could not load projects."))}).finally(()=>{I||g(!1)}),()=>{I=!0}},[e,t]),ue(()=>{if(!e||!c){d([]),f(""),w(!1);return}let I=!1;return d([]),f(""),w(!0),b("Loading chats…"),nh(c).then(N=>{I||(d(N),b(N.length?"":"This project has no chats yet."))}).catch(N=>{I||(d([]),f(""),b(N&&N.message?N.message:"Could not load chats."))}).finally(()=>{I||w(!1)}),()=>{I=!0}},[e,c]),!e)return null;const j=!!(t&&typeof t.text=="string"&&t.text.trim()),x=!!(t&&t.image&&t.image.dataUrl),X=t&&t.textLabel?t.textLabel:"selected code",ne=t&&t.description?t.description:x&&j?"Add the annotated image and note to any chat draft.":x?"Add the annotated Inspector image to any chat draft.":"Add selected file code to any chat draft.";async function $(){if(!(!c||!p||!j&&!x||k)){_(!0),b("Adding to draft…");try{const I=await wr("/api/chats/"+encodeURIComponent(p)+"?projectDir="+encodeURIComponent(c));if(I.status!==200||!I.body||!I.body.chat)throw new Error(I.body&&I.body.error||"Could not read the chat draft.");const N=I.body.chat,U={projectDir:c};if(j){const se=typeof N.draft=="string"?N.draft.trimEnd():"";U.draft=se?se+`
|
|
57
|
-
|
|
58
|
-
`+t.text.trim():t.text.trim()}if(x){const se=Array.isArray(N.draftAttachments)?N.draftAttachments.slice():[];U.draftAttachments=Vt(se.concat([t.image]).slice(0,8))}const Z=await wr("/api/chats/"+encodeURIComponent(p),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(U)},Qf);if(Z.status!==200)throw new Error(Z.body&&Z.body.error||"Could not update the draft.");b("Added with Draft Craft."),_(!1),r&&r({projectDir:c,chatId:p,chat:Z.body.chat})}catch(I){b(I&&I.message?I.message:"Draft Craft failed."),_(!1)}}}return l("div",{class:"draft-craft__overlay draft-craft__overlay--"+o,role:"presentation",onClick:n},l("section",{class:"draft-craft__sheet",role:"dialog","aria-modal":"true","aria-labelledby":"draftCraftTitle",onClick:I=>I.stopPropagation()},l("div",{class:"draft-craft__handle","aria-hidden":"true"}),l("div",{class:"draft-craft__head"},l("div",null,l("h2",{id:"draftCraftTitle"},"Draft Craft"),l("p",null,ne)),l("button",{class:"draft-craft__close",type:"button",onClick:n,"aria-label":"Close Draft Craft"},"×")),l("div",{class:"draft-craft__content"},l("label",{class:"draft-craft__field"},l("span",null,"Project"),l("select",{class:"input",value:c,onChange:I=>u(I.currentTarget.value),disabled:D||k},i.map(I=>l("option",{key:I.id||I.path,value:I.path},I.name||I.path)))),l("div",{class:"draft-craft__field"},l("span",null,"Chats"),l("ul",{class:"draft-craft__chats","aria-label":"Choose a chat"},D?l("li",{class:"draft-craft__chat-empty"},"Loading chats…"):a.length?a.map(I=>l("li",{key:I.id},l("button",{class:"draft-craft__chat"+(p===I.id?" is-selected":""),type:"button",onClick:()=>f(I.id),disabled:k,"aria-pressed":String(p===I.id)},l("span",{class:"draft-craft__chat-title"},eh(I)),l("span",{class:"draft-craft__chat-meta"},th(I))))):l("li",{class:"draft-craft__chat-empty"},"No chats in this project."))),l("div",{class:"draft-craft__summary"},l("strong",null,"Adding"),l("span",null,[x?"annotated image":"",j?X:""].filter(Boolean).join(" + ")||"nothing")),l("p",{class:"status draft-craft__status",role:"status","aria-live":"polite"},y)),l("div",{class:"draft-craft__actions"},l("button",{class:"btn btn--ghost",type:"button",onClick:n,disabled:k},"Cancel"),l("button",{class:"btn btn--primary",type:"button",onClick:$,disabled:D||k||!p||!j&&!x},k?"Adding…":"Add to draft"))))}const Vs=["#ff5f57","#ffd60a","#32d74b","#0a84ff"],Bn=.1,Wc=4,Sn=26;function Hs(e,t=Bn){return Math.min(Wc,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 Ws(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 zs(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 oh(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:Ws((e.clientX-r.left)/r.width),y:Ws((e.clientY-r.top)/r.height)}}function ih(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 sh(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function $s(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}function ah({image:e,pageTitle:t,pageUrl:n,onClose:r,onAnnotated:o,originalDataUrl:i=null,sourceLabel:s="Inspector image",actionLabel:c="Add to chat draft",onReset:u}){const a=P(null),d=P(null),p=P(null),f=P(!1),h=P(null),g=P(new Map),v=P(null),w=P(null),k=P(null),_=P(null),y=P(null),b=P(1),D=P(null),[j,x]=A(Vs[0]),[X,ne]=A(""),[$,I]=A([]),[N,U]=A("numbers"),[Z,se]=A(null),[ae,_e]=A(null),[ye,we]=A(!1),[Oe,Ce]=A(null),[de,z]=A(!1),[re,W]=A(""),[J,he]=A(1),[Re,q]=A("draw"),[R,G]=A(!0);ue(()=>{if(!e||!e.dataUrl||!a.current)return;let C=!1;const O=new Image;return O.onload=()=>{if(C||!a.current)return;const F=a.current;F.width=O.naturalWidth||1,F.height=O.naturalHeight||1,F.getContext("2d").drawImage(O,0,0),z(!0),requestAnimationFrame(pe)},O.src=e.dataUrl,()=>{C=!0}},[e]),ue(()=>{const C=p.current,O=a.current;if(!C||!O||!de)return;const F=typeof ResizeObserver=="function"?new ResizeObserver(()=>{const K=()=>{if(!p.current||!a.current)return;const E=Tn(p.current,a.current),M=b.current,ve=D.current;M<=(ve??E)+.005&&pe(!1)};K(),requestAnimationFrame(K)}):null;return F&&F.observe(C),()=>{F&&F.disconnect()}},[de]),ue(()=>{const C=_.current,O=y.current;if(!C||!O)return;const F=O.offsetTop,K=F+O.offsetHeight;F<C.scrollTop?C.scrollTop=F:K>C.scrollTop+C.clientHeight&&(C.scrollTop=K-C.clientHeight)},[Z,$.length]);function ce(C,O){const F=p.current,K=a.current,E=K&&K.getBoundingClientRect(),M=Hs(C,Tn(F,K));if(b.current=M,he(M),!F||!E||!O||E.width<=0||E.height<=0)return;const ve=F.getBoundingClientRect(),xe=(O.x-E.left)/E.width,T=(O.y-E.top)/E.height,B=O.x-ve.left,oe=O.y-ve.top;requestAnimationFrame(()=>{const Te=a.current;if(!Te||!F)return;const be=Te.getBoundingClientRect();F.scrollLeft=Math.max(0,xe*be.width-B),F.scrollTop=Math.max(0,T*be.height-oe)})}function pe(C=!0){const O=p.current,F=a.current;if(!O||!F)return;const K=Hs(Tn(O,F),Bn);b.current=K,he(K),D.current=K,C&&(O.scrollLeft=0,O.scrollTop=0)}function fe(C){if(!(!de||!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 O=Array.from(g.current.values());v.current={distance:$s(O[0],O[1]),zoom:b.current},w.current=null,f.current=!1,h.current=null;return}if(Re==="pan"){const O=p.current;w.current=O?{x:C.clientX,y:C.clientY,left:O.scrollLeft,top:O.scrollTop}:null;return}f.current=!0,h.current=zs(C,a.current)}}function qe(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 E=Array.from(g.current.values()).slice(0,2),M=$s(E[0],E[1]);v.current.distance>0&&ce(v.current.zoom*(M/v.current.distance),sh(E[0],E[1]));return}if(Re==="pan"&&w.current&&p.current){p.current.scrollLeft=w.current.left-(C.clientX-w.current.x),p.current.scrollTop=w.current.top-(C.clientY-w.current.y);return}if(!f.current||!h.current)return;const O=a.current,F=zs(C,O),K=O.getContext("2d");K.strokeStyle=j,K.lineWidth=Math.max(5,O.width/180),K.lineCap="round",K.lineJoin="round",K.beginPath(),K.moveTo(h.current.x,h.current.y),K.lineTo(F.x,F.y),K.stroke(),h.current=F}function Fe(C){C&&C.pointerId!==void 0&&g.current.delete(C.pointerId),g.current.size<2&&(v.current=null),w.current=null,f.current=!1,h.current=null}function ke(C,O=null){if(!de||O===null&&$.length>=Sn)return;C.preventDefault(),C.stopPropagation();const F=O===null?null:$.find(K=>K.id===O);k.current={markerId:O,pointerId:C.pointerId},_e({id:O,label:jt(O===null?$.length:$.indexOf(F),N),color:F?F.color:j,clientX:C.clientX,clientY:C.clientY});try{C.currentTarget.setPointerCapture(C.pointerId)}catch{}}function dt(C){!k.current||k.current.pointerId!==C.pointerId||(C.preventDefault(),_e(O=>O&&{...O,clientX:C.clientX,clientY:C.clientY}))}function Ne(C){const O=k.current;if(!O||O.pointerId!==C.pointerId)return;C.preventDefault(),C.stopPropagation();const F=oh(C,d.current,!0);F&&I(K=>{if(O.markerId!==null)return K.map(M=>M.id===O.markerId?{...M,...F}:M);if(K.length>=Sn)return K;const E=[...K,{id:Date.now()+Math.random(),...F,color:j,text:""}];return se(E[E.length-1].id),E}),k.current=null,_e(null)}function it(C,O){I(F=>F.map(K=>K.id===C?{...K,text:O}:K))}function pt(C){I(O=>{const F=O.filter(K=>K.id!==C);return se(K=>K===C?null:K),F})}function Je(){z(!1),I([]),se(null);const C=a.current;if(!C)return;const O=new Image;O.onload=()=>{const F=C.getContext("2d");F.clearRect(0,0,C.width,C.height),F.drawImage(O,0,0,C.width,C.height),z(!0)},O.src=e.dataUrl}function st(){typeof u!="function"||!i||(u(),r())}function Q(){const C=a.current;if(!C||!de)return;W("");let O;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),$.forEach((xe,T)=>ih(ve,xe,jt(T,N),C.width)),O=tf(M)}catch(M){W(M&&M.message?M.message:"Could not export the annotated image.");return}const F=$.map((M,ve)=>{const xe=jt(ve,N);return M.text.trim()?xe+". "+M.text.trim():xe+"."}),E={text:[s,t||"",n||"",X.trim(),F.length?`Annotations:
|
|
59
|
-
`+F.join(`
|
|
60
|
-
`):""].filter(Boolean).join(`
|
|
61
|
-
`),textLabel:$.length?$.length+" matched annotation"+($.length===1?"":"s"):"Inspector context",image:{type:"image",mimeType:"image/png",dataUrl:O,name:"draft-craft-inspector.png"}};if(o){Ce(E),o(E),r();return}Ce(E),we(!0)}const te=l("div",{class:"draft-craft__annotator-overlay",role:"presentation"},l("section",{class:"draft-craft__annotator",role:"dialog","aria-modal":"true","aria-label":"Annotate Inspector image with Draft Craft"},l("header",{class:"draft-craft__annotator-head"},l("div",null,l("strong",null,"Draft Craft"),l("span",null,o?"Draw on the attached image":"Draw on the Inspector image")),l("button",{type:"button",class:"draft-craft__close",onClick:r,"aria-label":"Close image annotator"},"×")),l("div",{ref:p,class:"draft-craft__canvas-wrap"+(Re==="pan"?" is-panning":"")},l("div",{ref:d,class:"draft-craft__canvas-stage",style:{width:J*100+"%"}},l("canvas",{ref:a,class:"draft-craft__canvas",onPointerDown:fe,onPointerMove:qe,onPointerUp:Fe,onPointerCancel:Fe,onPointerLeave:Fe,"aria-label":"Inspector screenshot annotation canvas. Pinch with two fingers to zoom."}),$.map((C,O)=>l("button",{key:C.id,type:"button",class:"draft-craft__image-marker"+(ae&&ae.id===C.id?" is-dragging":""),style:{left:C.x*100+"%",top:C.y*100+"%",background:C.color,color:In(C.color)},onPointerDown:F=>ke(F,C.id),onPointerMove:dt,onPointerUp:Ne,onPointerCancel:Ne,"aria-label":"Move annotation "+jt(O,N)},jt(O,N))))),l("div",{class:"draft-craft__annotator-tools"},l("button",{type:"button",class:"draft-craft__tools-toggle","aria-expanded":String(R),"aria-controls":"draftCraftToolsBody",onClick:()=>G(C=>!C)},l("span",{class:"draft-craft__tools-toggle-label"},"Tools"),l("span",{class:"draft-craft__tools-toggle-hint"},"Annotate & zoom"),l("span",{class:"draft-craft__tools-toggle-chevron","aria-hidden":"true"},R?"⌄":"⌃")),R?l("div",{id:"draftCraftToolsBody",class:"draft-craft__tools-body"},l("div",{class:"draft-craft__zoom",role:"group","aria-label":"Image zoom"},l("button",{class:"btn btn--small",type:"button",onClick:()=>ce(b.current-.25),disabled:J<=Tn(p.current,a.current),"aria-label":"Zoom out"},"−"),l("span",{"aria-live":"polite"},Math.round(J*100)+"%"),l("button",{class:"btn btn--small",type:"button",onClick:()=>ce(b.current+.25),disabled:J>=Wc,"aria-label":"Zoom in"},"+"),l("button",{class:"btn btn--small",type:"button",onClick:()=>pe(),disabled:Math.abs(J-Tn(p.current,a.current))<.005,"aria-label":"Show whole image",title:"Fit image to view"},"Fit"),l("button",{class:"btn btn--small"+(Re==="pan"?" is-active":""),type:"button",onClick:()=>q(C=>C==="pan"?"draw":"pan"),"aria-pressed":String(Re==="pan")},Re==="pan"?"Draw":"Pan")),l("div",{class:"draft-craft__colors",role:"group","aria-label":"Annotation color"},Vs.map(C=>l("button",{key:C,type:"button",class:"draft-craft__color"+(C===j?" is-active":""),style:{background:C},"aria-label":"Use "+C,"aria-pressed":String(C===j),onClick:()=>x(C)}))),l("button",{class:"btn btn--small",type:"button",onClick:Je,disabled:!de},"Clear"),l("section",{class:"draft-craft__markers","aria-label":"Matched image annotations"},l("div",{class:"draft-craft__marker-bar"},l("div",null,l("strong",null,"Marker dots"),l("span",null,"Drag the next dot onto the image")),l("select",{class:"input draft-craft__marker-style",value:N,onChange:C=>U(C.currentTarget.value),"aria-label":"Marker label style"},l("option",{value:"numbers"},"1, 2, 3"),l("option",{value:"letters"},"A, B, C")),l("button",{type:"button",class:"draft-craft__marker-source",style:{background:j,color:In(j)},disabled:!de||$.length>=Sn,onPointerDown:ke,onPointerMove:dt,onPointerUp:Ne,onPointerCancel:Ne,"aria-label":$.length>=Sn?"Maximum markers reached":"Drag marker "+jt($.length,N)+" onto image"},$.length>=Sn?"✓":jt($.length,N))),$.length?l("div",{class:"draft-craft__marker-list",ref:_,role:"list","aria-label":"Marked image annotations"},$.map((C,O)=>{const F=jt(O,N),K=C.id===Z;return l("div",{key:C.id,ref:K?y:null,role:"listitem",class:"draft-craft__marker-row"+(K?" is-active":"")},l("button",{type:"button",class:"draft-craft__marker-label",style:{background:C.color,color:In(C.color)},onClick:()=>se(C.id),"aria-pressed":String(K),"aria-label":"Select annotation "+F+(C.text.trim()?": "+C.text.trim():" (no text)")},F),l("input",{class:"input draft-craft__marker-input",value:C.text,onInput:E=>it(C.id,E.currentTarget.value),placeholder:"Text for "+F,"aria-label":"Text for annotation "+F}),l("button",{type:"button",class:"draft-craft__marker-remove",onClick:()=>pt(C.id),"aria-label":"Remove annotation "+F},"×"))})):l("div",{class:"draft-craft__marker-empty"},"No marker dots on the image yet.")),l("textarea",{class:"input draft-craft__note",rows:2,value:X,onInput:C=>ne(C.currentTarget.value),placeholder:"Optional note about this image","aria-label":"Image note"})):null),l("div",{class:"draft-craft__annotator-foot"},re?l("span",{class:"status",role:"alert"},re):null,i?l("button",{class:"btn btn--ghost",type:"button",onClick:st,disabled:!de},"Reset"):null,l("button",{class:"btn btn--primary",type:"button",onClick:Q,disabled:!de},c))),ae?l("span",{class:"draft-craft__drag-marker",style:{left:ae.clientX+"px",top:ae.clientY+"px",background:ae.color,color:In(ae.color)},"aria-hidden":"true"},ae.label):null,l(rh,{open:ye,payload:Oe,onClose:()=>we(!1),onAdded:()=>{we(!1),r()}}));return typeof document>"u"?te:Rl(te,document.body)}const ch=["audio/webm;codecs=opus","audio/webm","audio/ogg;codecs=opus","audio/ogg","audio/mp4","audio/mpeg"];function lh(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 uh(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 ch)try{if(r.isTypeSupported(o))return o}catch{}return""}function dh(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 Js(e,t){return"dictation-"+new Date(t||0).toISOString().replace(/[:.]/g,"-").slice(0,19)+dh(e)}function ph(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 fh=12e4;function Gs(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 c=0;c<o.length;c+=s)i+=String.fromCharCode.apply(null,o.subarray(c,c+s));t(btoa(i))}).catch(()=>n(new Error("Could not read the recording")))})}async function Ks(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 zc=3e3,Do=400,hh=1;function Zs(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 mh(e,t){const n=Zs(e).map(i=>i.word),r=Zs(t),o=Math.min(n.length,r.length);for(let i=o;i>=hh;i--){let s=!0;for(let c=0;c<i;c++)if(n[n.length-i+c]!==r[c].word){s=!1;break}if(s)return r[i-1].end}return 0}function gh(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=mh(n,o),s=i?o.slice(i).replace(/^[\s\p{P}]+/u,""):o;s&&(n+=" "+s)}return n}function _h(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 yh(e){return(e||{}).live!==!1}function vh(){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 gh(t.map(n=>e.get(n)))},pending(t){return Math.max(0,(Number(t)||0)-e.size)},answered(){return e.size}}}function bh(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):zc;let s=t.mimeType||"",c=null,u=[],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 u=[],_.ondataavailable=y=>{y&&y.data&&y.data.size&&u.push(y.data)},_.onstop=()=>g(_,f(_)),_.onerror=y=>v(_,f(_),y),_}function g(_,y){const b=u;if(u=[],c===_&&(c=null),a&&(o(a),a=null),b.length&&t.onSegment&&t.onSegment(p(b,y),y),d){k();return}t.onEnd&&t.onEnd()}function v(_,y,b){d=!1,g(_,y),t.onError&&t.onError(b||new Error("The recorder stopped unexpectedly."))}function w(){a=null;const _=c;if(!(!_||_.state==="inactive"))try{_.stop()}catch{}}function k(){c=h(),a=r(w,i),c.start()}return{start(){d||!n||(d=!0,k())},stop(){if(!d)return;d=!1,a&&(o(a),a=null);const _=c;if(!_){t.onEnd&&t.onEnd();return}try{_.stop()}catch{g(_,f(_))}},recording(){return d}}}async function wh(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 jm(e,t){const n=(e||[]).find(r=>r&&r.id===t);return n?n.label:t||""}function Ch(e){return e==="gemini"?"Gemini":e==="openai-audio"?"OpenAI chat":e==="openai-compatible"?"OpenAI-shaped":e||"unknown"}const kh=["whisper","transcribe","transcription","voxtral","parakeet"];function $c(e){const t=e&&e.inputModalities;return Array.isArray(t)&&t.some(n=>String(n).toLowerCase()==="audio")}function Jc(e){const t=e&&e.outputModalities;return Array.isArray(t)&&t.some(n=>String(n).toLowerCase()==="transcription")}function Gc(e){if(!e)return 0;const t=String(e.id||"").toLowerCase();return Jc(e)||kh.some(n=>t.includes(n))?3:e.kind==="gemini"||$c(e)?2:e.source==="project"?1:0}function Dm(e,t){const r=(Array.isArray(e)?e:[]).map((s,c)=>({row:s,index:c,rank:Gc(s)})).filter(s=>s.rank>=2).sort((s,c)=>c.rank-s.rank||s.index-c.index),o=r.filter(s=>s.rank>=3);return(o.length?o:r).slice(0,5).map(s=>s.row)}function Sh(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 Th(e,t){const n=Array.isArray(e)?e:[],r=Sh(n,t);if(r)return r;const o=n.filter(i=>Gc(i)>=3);return o.length===1?{modelId:o[0].id,providerId:o[0].provider||""}:null}function Bm(e){return(Array.isArray(e)?e:[]).map(t=>({id:t.id,provider:t.provider||"",label:t.label&&t.label!==t.id?t.label:Ph(t)}))}function qm(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 Ah="Transcribing…";function xh(e){const t=e||{};return t.transcribing||t.finishing?"transcribe":""}const Eh="Preparing dictation…";function Ih(e){const t=e||{};return t.preparing&&Number(t.delayMs)>=Do?Eh:""}function Ph(e){if(!e)return"";const t=$c(e);return e.source==="live"?t&&!Jc(e)?"from provider · audio in":"from provider":""}function Rh(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 Um(e){const t=e||{};return"Last run: "+[t.model&&t.model.id||"unknown model",Ch(t.kind),Math.round((t.bytes||0)/1024)+" kB",Math.round((t.durationMs||0)/100)/10+"s","cost "+(t.costLabel||"--")].join(" · ")}function Vm(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 Ys="No dictation model yet — "+Lh();function Nh(e){const{language:t="",onTranscript:n,onStatus:r,onProgress:o,promptRef:i}=e,[s,c]=A(!1),[u,a]=A(""),[d,p]=A(""),[f,h]=A(!1),[g,v]=A(!1),[w,k]=A(!1),_=f||g,[y,b]=A(0),D=P(""),j=P(null),x=P(null),X=P([]),ne=P(null),$=P(0),I=P(null),N=P(null),U=P(0),Z=P(""),se=P(0),ae=P(!1),_e=P(!1),ye=P([]),we=P(!1),[Oe,Ce]=A(0),de=P(null);function z(Q,te){a(Q||""),p(te||""),r&&r(Q||"",te||"")}function re(Q,te){a(Q||""),p(te)}function W(){const Q=x.current;if(x.current=null,Q&&typeof Q.getTracks=="function")for(const te of Q.getTracks())try{te.stop()}catch{}}function J(){ne.current&&(clearTimeout(ne.current),ne.current=null)}function he(){const Q=Z.current,te=N.current?N.current.text():"",C=te&&Q&&!/\s$/.test(Q)?" ":"";return{draft:Q+C+te,text:te,base:Q+C,caret:(Q+C+te).length}}function Re(){if(!n)return;const Q=he();n(Q.text,{live:!0,model:de.current?{id:de.current.id,provider:de.current.provider||""}:null,cost:null})}function q(Q){const te=N.current,C=te?te.text():"";N.current=null,Z.current="",se.current=0,ae.current=!1,ye.current=[],!(!C||!n)&&n(C,{model:de.current?{id:de.current.id,provider:de.current.provider||""}:null,cost:Q||null})}function R(Q,te){if(!Q||!Q.size)return;const C=se.current++;G(Q,te,C)}async function G(Q,te,C){const O=de.current;if(O)try{const F=await Gs(Q);if(!N.current)return;const K=await Ks({projectDir:e.projectDir||"",chatId:e.chatId||"",modelId:O.id,providerId:O.provider||"",kind:O.kind||"",audioBase64:F,mimeType:te,filename:Js(te,$.current),language:t});if(!N.current)return;ae.current=!1,N.current.set(C,(K.text||"").trim()),K.cost&&ye.current.push(K.cost),we.current&&Re()}catch{if(!N.current)return;ae.current=!0}finally{ce()}}function ce(){const Q=N.current;if(!Q)return;if(we.current){const F=Q.text().split(/\s+/).filter(Boolean).length,K=ae.current?"Recording — part of what you said could not be transcribed; still listening…":F?F+" words so far — tap the mic to stop.":"Recording — tap the mic again to stop.";o?o(K,"busy"):z(K,"busy");return}if(Q.pending(se.current)>0){k(!0);const F=ae.current?"Finishing dictation — part of what you said could not be transcribed…":Ah;o?o(F,"busy"):z(F,"busy");return}k(!1);const te=ae.current,C=Q.text(),O=_h(ye.current);if(q(O),C&&te){z("Added to the composer — part of what you said could not be transcribed.","error");return}if(C){const F=O?Ht(O.total):"--";re(F==="--"?"Added to the composer — review it, then send.":"Added to the composer ("+F+") — review it, then send.","success");return}z(te?"Transcription failed":"Nothing was recognised — try again a little closer to the mic.","error")}ue(()=>()=>{we.current=!1,J();const Q=I.current;I.current=null,Q&&Q.stop();const te=j.current;if(te&&te.state!=="inactive")try{te.stop()}catch{}W()},[]),ue(()=>{if(!s)return;const Q=setInterval(()=>Ce(te=>te+1),1e3);return()=>clearInterval(Q)},[s]),ue(()=>{if(!f)return;const Q=setTimeout(()=>b(Do),Do);return()=>{clearTimeout(Q),b(0)}},[f]);async function pe(Q,te){v(!0),z("Transcribing…","busy");try{const C=de.current||await fe();if(!C){z(Ys,"error"),v(!1);return}const O=await Gs(Q),F=await Ks({projectDir:e.projectDir||"",chatId:e.chatId||"",modelId:C.id,providerId:C.provider||"",kind:C.kind||"",audioBase64:O,mimeType:te,filename:Js(te,$.current),language:t}),K=(F.text||"").trim();if(!K){z("Nothing was recognised — try again a little closer to the mic.","error"),v(!1);return}n&&n(K,{model:F.model,kind:F.kind,usage:F.usage||null,cost:F.cost||null});const E=Rh(F).label;re(E==="--"?"Added to the composer — review it, then send.":"Added to the composer ("+E+") — review it, then send.","success")}catch(C){z(C&&C.message||"Transcription failed","error")}finally{v(!1)}}async function fe(){const Q=await H("/api/settings"),te=Q.status===200&&Q.body&&Q.body.app&&Q.body.app.dictation||{},C=await wh(e.projectDir||""),O=Th(C.models,te);if(!O)return null;const F=C.models.find(K=>K.id===O.modelId&&(K.provider||"")===O.providerId);return F?{row:F,live:yh(te)}:null}async function qe(){const Q=typeof window<"u"?window:null;if(!lh(Q)){z("This browser cannot record audio.","error");return}h(!0);let te=null;try{te=await fe()}catch(E){h(!1),z(E&&E.message||"Could not load the dictation model list.","error");return}if(h(!1),!te){z(Ys,"error");return}de.current=te.row;let C;try{C=await Q.navigator.mediaDevices.getUserMedia({audio:!0})}catch(E){z(E&&E.name==="NotAllowedError"?"Microphone permission was refused.":"Could not open the microphone.","error");return}x.current=C;const O=uh(Q.MediaRecorder,Q),F=e.promptRef&&e.promptRef.current;U.current=F&&typeof F.selectionStart=="number"?F.selectionStart:F?F.value.length:0,Z.current=F?F.value.slice(0,U.current):"",se.current=0,ae.current=!1,ye.current=[],N.current=vh(),_e.current=te.live;let K=null;if(_e.current){const E=bh({recorder:Q.MediaRecorder,stream:C,mimeType:O,segmentMs:zc,onSegment:R,onEnd:()=>{I.current=null,J(),we.current=!1,W(),c(!1),ce()},onError:()=>{I.current=null,J(),we.current=!1,W(),c(!1),z("The recorder stopped unexpectedly.","error")}});I.current=E}else{try{K=O?new Q.MediaRecorder(C,{mimeType:O}):new Q.MediaRecorder(C)}catch{try{K=new Q.MediaRecorder(C)}catch{W(),z("Could not start the recorder.","error");return}}X.current=[],K.ondataavailable=E=>{E&&E.data&&E.data.size&&X.current.push(E.data)},K.onstop=()=>{J();const E=K.mimeType||O||"audio/webm",M=X.current.length?new Blob(X.current,{type:E}):null;X.current=[],j.current=null,we.current=!1,W(),c(!1),N.current=null,M&&M.size?pe(M,E):z("Nothing was captured — check the microphone is not muted.","error")},K.onerror=()=>{J(),j.current=null,we.current=!1,W(),c(!1),N.current=null,z("The recorder stopped unexpectedly.","error")},j.current=K}if($.current=Date.now(),c(!0),we.current=!0,z(_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(),c(!1),N.current=null,z("Could not start the recorder.","error");return}else K.start();ne.current=setTimeout(()=>Fe(),fh)}function Fe(){if(J(),we.current=!1,c(!1),_e.current){const te=I.current;if(te){te.stop();return}_e.current=!1,ce();return}const Q=j.current;if(Q&&Q.state!=="inactive")try{Q.stop()}catch{}N.current=null}function ke(){if(!_){if(s){Fe();return}qe()}}const dt=xh({transcribing:g,finishing:w}),Ne=Ih({preparing:f,delayMs:y});ue(()=>{Ne!==D.current&&(D.current=Ne,Ne&&z(Ne,"busy"))},[Ne]);const it=s?ph(Date.now()-$.current):"",pt=s?"Stop dictation ("+it+")":"Dictate",Je=dt==="transcribe",st=s?l("path",{d:"M7 7h10v10H7Z",fill:"currentColor"}):l("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 l("button",{class:"chat-view__mic-btn"+(s?" is-recording":"")+(Je?" is-busy":""),type:"button",onClick:ke,disabled:_,title:u||"Dictate","aria-label":Je?"Working…":pt,"aria-pressed":s?"true":"false","aria-busy":Je?"true":void 0,"data-state":d||void 0},Je?l("span",{class:"dictation__spinner dictation__spinner--mic","aria-hidden":"true"}):l("svg",{viewBox:"0 0 24 24",width:18,height:18,"aria-hidden":"true"},st))}function Lh(){return"Open Settings → App defaults → Dictation to pick a dictation model."}function Mh(e){const t=Af(e),{refs:n,imageAttachments:r,composerText:o,fileEditorOpen:i,runningVisible:s,authStamp:c,toolDataStamp:u,mcpStartBusy:a,fileOrb:d,composerTools:p,chatSwitcherOpen:f,chatSwitcherList:h,chatSwitcherLoading:g,customActions:v,setFileEditorOpen:w,setImageAttachments:k,setComposerText:_,setChatSwitcherOpen:y,picker:b,send:D,onPickerPick:j,onPickerTogglePin:x,onPickerOpen:X,onRefreshAllProviders:ne,onPickerOpenChange:$,onComposerKey:I,onComposerInput:N,onComposerPaste:U,onImagePickerChange:Z,onRemoveImage:se,onJumpToBottom:ae,onCancelRunning:_e,onBack:ye,onToggleAutoRetry:we,onToggleChatSwitcher:Oe,onChatSwitcherScroll:Ce,onSwitchChat:de,runCustomAction:z,refreshCustomActions:re,updateChat:W}=t,{projectDir:J,chatId:he}=e,Re=P(null),[q,R]=A(null),G=P(null);function ce(E,M){const ve=n.promptInput.current;if(!ve||M&&M.live&&!String(E||"").trim())return;const xe=ve.value,T=G.current,B=T&&T.text?T:null;let oe=null;if(B)if(xe.slice(B.start,B.start+B.text.length)===B.text)oe=B.start;else{const Lt=xe.indexOf(B.text);Lt>=0&&(oe=Lt)}const Te=oe!==null&&B?B.text.length:0;oe===null&&(oe=typeof ve.selectionStart=="number"?ve.selectionStart:xe.length);const be=xe.slice(0,oe),je=xe.slice(oe+Te),Le=be&&!/\s$/.test(be)?" ":"",Qe=je&&!/^\s/.test(je)?" ":"",at=be+Le+E+Qe+je;G.current=M&&M.live?{start:oe,text:Le+E}:null,Ne(at),W&&jn(at,n,W).catch(()=>{});const Nt=M&&!M.live?M.cost:null;if(Nt&&Nt.known&&Number.isFinite(Number(Nt.total))){const Lt=kd(Re.current,t.state.costSnapshot,Nt.total);Lt&&(Re.current=Lt,t.state.attributedCost=Lt.total,ot(t.state,null,n))}const Xn=(be+Le+E).length;try{ve.focus({preventScroll:!0}),ve.setSelectionRange(Xn,Xn)}catch{}(!M||!M.live)&&ro(n.status,"dictation added"+pe(M),"success")}function pe(E){const M=E&&E.cost;return!M||!M.known||!isFinite(Number(M.total))?"":" · "+Ht(M.total)}function fe(E,M){ro(n.status,E,M)}function qe(E,M){ro(n.status,E,M)}function Fe(E){if(!E||E.projectDir!==J||E.chatId!==he||!E.chat)return;const M=E.chat;n.promptInput.current&&(n.promptInput.current.value=M.draft||"",_(M.draft||""),n._autoresize&&n._autoresize()),k(Array.isArray(M.draftAttachments)?M.draftAttachments:[])}const[ke,dt]=A(null);function Ne(E){n.promptInput.current&&(n.promptInput.current.value=E),_(E),n._autoresize&&n._autoresize()}function it(E){if(!ke||!E||!E.image)return;const M=Array.isArray(r)?r.slice():[],ve=M[ke.index];if(ve){const xe=(typeof E.text=="string"?E.text:"").trim(),T=Ro(ve),B=n.promptInput.current?n.promptInput.current.value:o,oe=T?Is(B,T.annotationText,T.annotationStart):B,Te=Yp(oe,xe),be=B.length-oe.length,je=T&&be?Ps(M,T.annotationStart,-be,ke.index):M;je[ke.index]=Xp(ve,E.image,xe,Te.start);const Le=Te.value;k(je),Ne(Le),W&&jn(Le,n,W,{draftAttachments:Vt(je)}).catch(()=>{})}dt(null)}function pt(){if(!ke)return;const E=Array.isArray(r)?r.slice():[],M=Ro(E[ke.index]);if(!M)return;const ve=n.promptInput.current?n.promptInput.current.value:o,xe=Is(ve,M.annotationText,M.annotationStart),T=ve.length-xe.length,B=T?Ps(E,M.annotationStart,-T,ke.index):E;B[ke.index]=M.attachment,k(B),Ne(xe),W&&jn(xe,n,W,{draftAttachments:Vt(B)}).catch(()=>{})}const[Je,st]=A(()=>as()),[Q,te]=A(!1),[C,O]=A(!1);ue(()=>{if(!i||q)return;let E=!1;return Be(()=>import("./FileEditor-DDl31c6d.js"),__vite__mapDeps([0,1,2])).then(M=>{E||R(()=>M.FileEditorView)}).catch(()=>{E||R(null)}),()=>{E=!0}},[i,q]),ue(()=>{const E=qu(M=>{st(M||null),M||te(!1)});return st(as()),()=>{E()}},[]),ue(()=>{cs(),st(null),te(!1),O(!1)},[J,he]),ue(()=>()=>{zu()},[]);const F=P(null),K=P(null);return ue(()=>{if(!n.promptInput.current||!F.current)return;const E=Lp(n.promptInput.current,F.current,t.state,K.current),M=setInterval(()=>Mp(),5e3);return()=>{E(),clearInterval(M)}},[n.promptInput,n.promptInput.current,t.state.props&&t.state.props.projectDir]),l("section",{class:"chat-view"},l("div",{class:"chat-view__head"},l("button",{ref:n.back,class:"chat-view__back",type:"button",onClick:ye,"aria-label":"Back to projects"},"←"),l("div",{class:"chat-view__title-stack","data-switcher":"1"},l("button",{ref:n.chatSwitcherTrigger,class:"chat-view__chat-switcher-trigger",type:"button",onClick:Oe,"aria-label":"Switch chat","aria-haspopup":"true","aria-expanded":String(f)},l("div",{class:"chat-view__chat-switcher-title"},l("div",{ref:n.chatName,class:"chat-view__name"},"…"),l("div",{ref:n.chatMeta,class:"chat-view__meta"},"")),l("span",{class:"chat-view__chat-switcher-caret","aria-hidden":"true"},"▾")),l("div",{ref:n.chatSwitcherPop,class:"chat-view__chat-switcher-pop",hidden:!f,role:"listbox","aria-label":"Switch to a chat",onScroll:Ce},h.map(E=>l("button",{key:E.id,class:"chat-view__chat-switcher-item"+(E.id===he?" is-current":""),type:"button",role:"option","aria-selected":String(E.id===he),onClick:()=>de(E.id)},l("span",{class:"chat-view__chat-switcher-item-title"},E.title&&E.title.trim()?E.title:"New chat"),l("span",{class:"chat-view__chat-switcher-item-model"},E.modelId||""),E.id===he&&s?l("span",{class:"chat-view__chat-switcher-running","aria-hidden":"true"}):null)),h.length?null:l("div",{class:"chat-view__chat-switcher-empty"},"No other chats"),l("div",{class:"chat-view__chat-switcher-more",hidden:!g},"Loading more…")),l("div",{ref:n.usageSummaryRef,class:"chat-view__usage-summary","aria-label":"Chat usage and provider credit"},l("span",null,"Context --"),l("span",null,"Total --"))),l("div",{class:"chat-view__model-row"},l(sc,{models:b.models,value:b.value,variant:"chat",open:b.open,onOpenChange:$,noProviders:!t.state.providers.length,pinned:b.pinned,onTogglePin:x,recent:b.recent,extraProviders:b.providers,refresh:ne,refreshEmpty:"Refresh models",ariaLabel:"Pick model",onOpen:X,onChange:j},l("div",{class:"chat-view__picker-maxout"},l("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:E=>{const M=E.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:E=>{E.key==="Enter"&&E.currentTarget.blur()}}))),l("select",{ref:n.thinkingLevel,class:"input chat-view__thinking-select","aria-label":"Thinking level","data-allow-custom":"1",onChange:E=>{const M=E.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})}}),l("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:E=>{const M=E.currentTarget.value.trim();M&&t.state.chat&&(t.state.thinkingLevel=M,t.updateChat({thinkingLevel:M}))},onKeydown:E=>{E.key==="Enter"&&E.currentTarget.blur()}})),l("div",{class:"chat-view__head-icons"},l("a",{class:"chat-view__iconbtn",href:"#/settings/project?projectDir="+encodeURIComponent(J||"")+"&chatId="+encodeURIComponent(he||""),"aria-label":"Project settings",title:"Settings"},l("svg",{viewBox:"0 0 24 24",width:16,height:16,fill:"currentColor","aria-hidden":"true"},l("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"}))),l(qf,{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:c,toolDataStamp:u}))),l("div",{ref:n.transcript,class:"chat-view__transcript","aria-live":"polite"}),l("button",{ref:n.jumpBtn,class:"chat-view__jump",type:"button",hidden:!0,onClick:ae,"aria-label":"Jump to latest messages"},l("svg",{viewBox:"0 0 24 24",width:16,height:16,"aria-hidden":"true"},l("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"})),l("span",{class:"chat-view__jump-count"},"")),l(Ff,{preview:Je,onOpen:()=>te(!0),onDismiss:()=>cs()}),l("div",{class:"chat-view__composer-row"},l("div",{class:"chat-view__composer-tool"},l(jf,{projectDir:J,orb:d,onOpenFileEditor:()=>w(!0),onOpenPreview:()=>O(!0),customActions:v,onRunCustomAction:z,onRefreshCustomActions:re})),l("div",{class:"chat-view__composer"},l("div",{ref:F,class:"at-mention",role:"listbox","aria-label":"Suggestions",hidden:!0}),l("div",{ref:K,class:"at-mention__arg-bar",hidden:!0}),p.image?l("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"},l("svg",{viewBox:"0 0 24 24",width:18,height:18,"aria-hidden":"true"},l("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,l("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?l(Nh,{projectDir:J,chatId:he,promptRef:n.promptInput,onTranscript:ce,onStatus:fe,onProgress:qe}):null,l("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:U,onInput:N}),s?l("button",{ref:n.stopBtn,class:"btn btn--primary chat-view__send",type:"button",onClick:_e,"aria-label":"Stop"},l("svg",{viewBox:"0 0 24 24",width:18,height:18,"aria-hidden":"true"},l("path",{d:"M6 6h12v12H6Z",fill:"currentColor"}))):l("button",{ref:n.sendBtn,class:"btn btn--primary chat-view__send",type:"button",onClick:D,disabled:!o.trim()&&!r.length,"aria-label":"Send"},l("svg",{viewBox:"0 0 24 24",width:18,height:18,"aria-hidden":"true"},l("path",{d:"M3.4 20.6 21 12 3.4 3.4 3 10l13 2-13 2 .4 6.6Z",fill:"currentColor"}))),r.length?l("div",{class:"chat-view__image-preview"},r.map((E,M)=>l("div",{key:M,class:"chat-view__image-chip"},l("button",{class:"chat-view__image-chipimg",type:"button",onClick:()=>dt({index:M,attachment:E}),"aria-label":"Annotate image "+(E.name||M+1),title:"Annotate image"},l("img",{src:E.dataUrl,alt:E.name||"attached image"})),l("button",{class:"chat-view__image-chipremove",type:"button",onClick:()=>se(M),title:"Remove image","aria-label":"Remove image "+(E.name||M+1)},l("span",null,"×"))))):null)),l("div",{class:"chat-view__status-row"},l("span",{ref:n.status,class:"status chat-view__status","aria-live":"polite"})),i&&q?l(q,{projectDir:J,onClose:()=>w(!1),onDraftCraftAdded:Fe}):null,Q&&Je?l(zf,{preview:Je,onClose:()=>te(!1),onRecapture:E=>Oh(Je,E,{projectDir:J,chatId:he,refs:n,onAuthorizationRequired:()=>te(!1)})}):null,C?l(Yf,{onSubmit:E=>jh(E,{projectDir:J,chatId:he,refs:n,onPromptClose:()=>O(!1)}),onClose:()=>O(!1)}):null,ke?l(ah,{image:ke.attachment,originalDataUrl:Qp(ke.attachment),sourceLabel:"Attached image",actionLabel:"Use annotated image",onReset:pt,onAnnotated:it,onClose:()=>dt(null)}):null)}async function Oh(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 c="ui_"+Date.now().toString(36)+Math.random().toString(36).slice(2,7),u=()=>wo({projectDir:o,chatId:i,url:r,viewport:t||void 0,callId:c});let a=null;try{a=await u()}catch(d){if(d&&d.code==="EAUTH_REQUIRED"){n&&typeof n.onAuthorizationRequired=="function"&&n.onAuthorizationRequired();let p=null;await Rt({callId:d.callId||c,tool:"webpreview",cmd:r,projectDir:o},o,i,s,async()=>{p=await u()})!=="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 jh(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),c=o&&o.status&&o.status.current;c&&(c.textContent="Capturing preview…");let u=null;try{u=await wo({projectDir:n,chatId:r,url:e,callId:s})}catch(a){if(a&&a.code==="EAUTH_REQUIRED")return i&&i(),await Rt({callId:a.callId||s,tool:"webpreview",cmd:e,projectDir:n},n,r,o,async()=>{u=await wo({projectDir:n,chatId:r,url:e,callId:s})})!=="deny"?(u&&u.ok&&u.result&&u.result.thumbnail&&Wn(u.result),u?"captured":"denied"):"denied";const d=a&&a.message||String(a);return c&&(c.textContent="Preview failed: "+d),null}return i&&i(),u&&u.ok&&u.result&&u.result.thumbnail?(Wn(u.result),c&&(c.textContent=""),"captured"):(c&&(c.textContent="Preview failed: "+(u&&u.result&&u.result.error||u&&u.error||"capture failed")),null)}const Ke=(e,t)=>ya(()=>e().then(n=>({default:n[t]}))),Dh=ya(()=>Be(()=>import("./Inspector-Ba3R1w04.js"),__vite__mapDeps([3,4,1,5])).then(e=>({default:e.InspectorView}))),Bh=Ke(()=>Be(()=>import("./SettingsProviders-k0xJN0IK.js"),[]),"SettingsProvidersView"),Xs=Ke(()=>Be(()=>import("./SettingsProviders-k0xJN0IK.js"),[]),"SettingsProviderEditView"),lr=Ke(()=>Be(()=>import("./SettingsProject-DNrKhCcZ.js"),__vite__mapDeps([6,7,8])),"SettingsProjectView"),qh=Ke(()=>Be(()=>import("./SettingsHiddenContent-BZ2sloH1.js"),__vite__mapDeps([9,7,1,10])),"SettingsHiddenContentView"),Fh=Ke(()=>Be(()=>import("./SettingsDefaults-DbMmQbzc.js"),[]),"SettingsDefaultsView"),Uh=Ke(()=>Be(()=>import("./SettingsNotifications-B0LEs11a.js"),[]),"SettingsNotificationsView"),Vh=Ke(()=>Be(()=>import("./SettingsAbout-bvZGDEDw.js"),[]),"SettingsAboutView"),Hh=Ke(()=>Be(()=>import("./SettingsPrompts-BgeiASuk.js"),[]),"SettingsPromptsView"),Wh=Ke(()=>Be(()=>import("./SettingsAgents-BNV0MgDB.js"),__vite__mapDeps([11,8,12])),"SettingsAgentsView"),zh=Ke(()=>Be(()=>import("./SettingsAgents-BNV0MgDB.js"),__vite__mapDeps([11,8,12])),"SettingsAgentEditView"),$h=Ke(()=>Be(()=>import("./SettingsActions-Dk6WX9jv.js"),[]),"SettingsActionsView"),Jh=Ke(()=>Be(()=>import("./SettingsActions-Dk6WX9jv.js"),[]),"SettingsActionEditView"),Gh=Ke(()=>Be(()=>import("./SettingsMcp-DOrfbQd1.js"),__vite__mapDeps([13,14])),"SettingsMcpView"),Kh=Ke(()=>Be(()=>import("./SettingsMcpEdit-BGMQ2CWC.js"),__vite__mapDeps([15,14])),"SettingsMcpEditView"),Zh=Ke(()=>Be(()=>import("./SettingsMcpRegistry-BywXee_A.js"),__vite__mapDeps([16,14])),"SettingsMcpRegistryView"),Yh=Ke(()=>Be(()=>import("./SettingsTags-B5kjFdQi.js"),__vite__mapDeps([17,4])),"SettingsTagsView"),Xh=Ke(()=>Be(()=>import("./SettingsPricing-BAg33iVF.js"),[]),"SettingsPricingView"),Qh=Ke(()=>Be(()=>import("./SettingsProjects-IqkBfDcm.js"),[]),"SettingsProjectsView"),em=Ke(()=>Be(()=>import("./DictationPage-BI23lp42.js"),[]),"DictationView"),Kc={chats:[To],settingsDictation:[em],inspector:[Dh],picker:[Au,({dir:e})=>({dir:e})],chat:[Mh,({chatId:e,projectDir:t})=>({chatId:e,projectDir:t})],settings:[pu],settingsProviders:[Bh],settingsProviderNew:[Xs,()=>({id:""})],settingsProviderEdit:[Xs,({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:[qh,({projectDir:e,from:t,filePath:n})=>({projectDir:e,from:t,filePath:n})],settingsDefaults:[Fh],settingsNotifications:[Uh],settingsPrompts:[Hh,({projectDir:e,id:t="",scope:n="",from:r})=>({projectDir:e,initialId:t,scope:n,from:r})],settingsAgents:[Wh,({projectDir:e,from:t,chatId:n})=>({projectDir:e,from:t,chatId:n})],settingsAgentEdit:[zh,({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:[$h,({projectDir:e,from:t})=>({projectDir:e,from:t})],settingsActionEdit:[Jh,({id:e,projectDir:t,from:n})=>({id:e,projectDir:t,from:n})],settingsMcp:[Gh,({projectDir:e,from:t})=>({projectDir:e,from:t})],settingsMcpEdit:[Kh,({id:e,projectDir:t,scope:n,from:r})=>({id:e,projectDir:t,scope:n,from:r})],settingsMcpRegistry:[Zh,({projectDir:e,from:t})=>({projectDir:e,from:t})],settingsTags:[Yh,({projectId:e,projectDir:t})=>({projectId:e,projectDir:t})],settingsPricing:[Xh],settingsProjects:[Qh],settingsAccess:[Qi],disableAccess:[Qi],setup:[To],settingsAbout:[Vh]},tm=new Set(["chat","picker","disableAccess","setup",...Object.keys(Kc).filter(e=>e.startsWith("settings")&&e!=="settings")]),nm=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 rm(e){const[t=To,n]=Kc[e.name]||[],r=e.name+"|"+(e.projectDir||"")+"|"+(e.id||"")+"|"+(e.scope||"")+"|"+(e.page||"")+"|"+(e.chatId||"")+"|"+(e.isNew?"new":""),o=l(t,{key:r,...n?n(e):null});return nm.has(e.name)?l(fr,{fallback:l("p",{class:"muted",role:"status"},"Loading…")},o):o}const om={chats:l("svg",{viewBox:"0 0 24 24",width:22,height:22,"aria-hidden":"true"},l("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:l("svg",{viewBox:"0 0 24 24",width:22,height:22,"aria-hidden":"true"},l("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:l("svg",{viewBox:"0 0 24 24",width:22,height:22,"aria-hidden":"true"},l("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 im(){const e=Kn.value,t=[{to:"projects",name:"chats",label:"Chats"},{to:"inspector",name:"inspector",label:"Inspector"},{to:"settings",name:"settings",label:"Settings"}];return l("nav",{class:"app__tabbar","aria-label":"Primary"},l("ul",{class:"app__tablist",style:{"--tab-count":t.length}},t.map(n=>l("li",{class:"app__tabitem"},l("a",{href:"#/"+n.to,class:"app__tab"+(e.name===n.name?" is-active":""),"aria-current":e.name===n.name?"page":null},l("span",{class:"app__tab-icon"},om[n.name]),l("span",{class:"app__tab-label"},n.label))))))}const sm=l("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"},l("path",{d:"M0.16 0.98 L0.16 0.14 L0.50 0.62 L0.84 0.14 L0.84 0.98"}));function am(){return l("header",{class:"app__header"},l("div",{class:"app__brand"},l("span",{class:"app__logo","aria-hidden":"true"},sm),l("h1",{class:"app__title"},"mouaif")))}function cm(){const e=Kn.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&&Ql(t)},[t]);const n=!tm.has(e.name),r=rm(e);return l("div",{class:"app__shell"},l(am,null),l(du,null),l("main",{class:"app__main"+(n?"":" app__main--flush")+(e.name==="chat"?" app__main--chat":"")},r),n?l(im,null):null)}const lm="mouaif-push-click",hn="clicks",Bo="latest",um=60*1e3,dm=250,pm=5e3;function Zc(){return new Promise((e,t)=>{if(typeof indexedDB>"u")return t(new Error("IndexedDB unavailable"));const n=indexedDB.open(lm,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 fm(){try{const e=await Zc();await new Promise(t=>{const n=e.transaction(hn,"readwrite");n.objectStore(hn).delete(Bo),n.oncomplete=t,n.onerror=t,n.onabort=t}),e.close()}catch{}}async function hm(){try{const e=await Zc(),t=await new Promise(n=>{const o=e.transaction(hn,"readwrite").objectStore(hn),i=o.get(Bo);i.onsuccess=()=>{const s=i.result;s&&o.delete(Bo),n(s||null)},i.onerror=()=>n(null)});return e.close(),t&&t.url&&Date.now()-(t.at||0)<um?t.url:null}catch{return null}}function Yc(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 mm(){if(typeof document>"u")return;const e=window.location.hash,t=()=>document.visibilityState!=="visible"?Promise.resolve(!1):hm().then(c=>c?(Yc(c),!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(c=>{c&&i()})}},dm),setTimeout(i,pm)}let Qs=!1;function gm(){return{type:"VISIBILITY_STATE",hash:window.location.hash||"",visible:document.visibilityState==="visible",focused:typeof document.hasFocus=="function"?document.hasFocus():!1}}function _m(e,t){const n=gm();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 ym(){Qs||typeof navigator>"u"||!("serviceWorker"in navigator)||(Qs=!0,navigator.serviceWorker.addEventListener("message",e=>{const t=e.data||{};if(t.type==="GET_VISIBILITY_STATE"){_m(e,t);return}t.type==="NAVIGATE"&&t.url&&(Yc(t.url),fm())}))}function vm(){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 bm={},wm=!!bm&&!0,pi=Tt(wm&&typeof window<"u"&&"Notification"in window&&"PushManager"in window&&!!navigator.serviceWorker),qo=Tt(typeof window<"u"&&"Notification"in window?Notification.permission:"denied"),ut=Tt(!1);let qn=null,mt=null;function Br(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 Cm=3e4,fi=1e4,km=32;function Sm(){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 Tm(){try{if(typeof matchMedia=="function"&&matchMedia("(display-mode: fullscreen)").matches)return"expanded"}catch{}return"collapsed"}function Am(){const e={chars:km,viewportWidth:0,os:"",osVersion:0,style:Tm()};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=Sm();e.os=n.os,e.osVersion=n.osVersion}}catch{}return e}async function Xc(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=Am();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 Qc(){if(!pi.value||typeof navigator>"u"||!navigator.serviceWorker)return!1;try{qo.value=Notification.permission;const e=await Br(navigator.serviceWorker.ready,fi,"serviceWorker.ready (sync)");if(!e)return!1;qn=e;const t=await e.pushManager.getSubscription();if(mt=t,ut.value=!!t,t){const n=await H("/api/push/subscriptions"),r=n.status===200&&n.body&&Array.isArray(n.body.subscriptions)?n.body.subscriptions:[];ut.value=r.some(o=>o&&o.endpoint===t.endpoint),ut.value||(ut.value=await Xc(t))}return ut.value}catch{return ut.value=!1,!1}}async function Hm(){if(!pi.value)return!1;try{if(await Br(Notification.requestPermission(),Cm,"Notification.requestPermission")!=="granted")return qo.value=Notification.permission,!1;if(qo.value="granted",ut.value&&await Qc())return!0;const t=await H("/api/push/vapid-public-key");if(t.status!==200)return!1;const n=t.body.publicKey,r=xm(n),o=await Br(navigator.serviceWorker.ready,fi,"serviceWorker.ready (subscribe)");if(!o)return!1;qn=o;const i=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:r});if(mt=i,!await Xc(i)){try{await i.unsubscribe()}catch{}return mt=null,ut.value=!1,!1}return ut.value=!0,!0}catch{return ut.value=!1,!1}}async function Wm(){if(pi.value)try{if(!mt&&qn&&(mt=await qn.pushManager.getSubscription()),!mt&&typeof navigator<"u"&&navigator.serviceWorker){const t=await Br(navigator.serviceWorker.ready,fi,"serviceWorker.ready (unsubscribe)");if(!t){ut.value=!1;return}qn=t,mt=await t.pushManager.getSubscription()}if(!mt){ut.value=!1;return}const e=mt.endpoint;try{await mt.unsubscribe()}catch{}mt=null,ut.value=!1,await H("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoint:e})})}catch{ut.value=!1}}function xm(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 ea=document.getElementById("app");ea&&Fn(l(yu,null,l(cm,null)),ea);lu();ym();vm();mm();au();"serviceWorker"in navigator&&navigator.serviceWorker.ready.then(()=>Qc()).catch(()=>{});export{Rl as $,P as A,Sf as B,pi as C,rh as D,qo as E,ut as F,Qc as G,Wm as H,Hm as I,Em as J,ts as K,Lm as L,ic as M,tc as N,Kl as O,Yf as P,Om as Q,sc as R,Ft as S,_t as T,ad as U,Fn as V,zf as W,lh as X,yh as Y,wh as Z,Oi as _,ah as a,Vn as a0,Bt as a1,Ma as a2,We as a3,Bm as a4,Dm as a5,Vm as a6,Ph as a7,Um as a8,ph as a9,fh as aa,jm as ab,Ch as ac,Th as ad,Fm as ae,uh as af,Gs as ag,Ks as ah,Js as ai,Rh as aj,ja as ak,qm as al,Mm as am,rn as b,Zo as c,A as d,Zl as e,H as f,Im as g,ue as h,zl as i,Rm as j,l as k,Go as l,Hr as m,yt as n,nc as o,Pm as p,ec as q,Ql as r,$l as s,Nm as t,Hc as u,Aa as v,oc as w,Mn as x,wo as y,wf as z};
|